Skip to content

Commit

Permalink
Fix processing to handle typescript imports with no extension (#54)
Browse files Browse the repository at this point in the history
## Summary:
We were assuming that any imports without an extension would be js/flow, not typescript, so I was getting syntax errors running it on the newly-converted mobile repo.

Issue: https://khanacademy.atlassian.net/browse/FEI-5146

## Test plan:
Now running it on `feature/ts` in the mobile repo works!

Author: jaredly

Reviewers: jaredly, jeresig, kevinbarabash

Required Reviewers:

Approved By: jeresig, kevinbarabash

Checks: ✅ Lint & Test (ubuntu-latest, 16.x)

Pull Request URL: #54
  • Loading branch information
jaredly authored May 17, 2023
1 parent 15c843c commit a581359
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 14 deletions.
5 changes: 5 additions & 0 deletions .changeset/bright-pandas-dance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@khanacademy/graphql-flow': patch
---

Fix processing of typescript imports that don't use an extension
2 changes: 2 additions & 0 deletions .flowconfig
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
[ignore]
; The 'resolve' package bundles test files that it really shouldn't
.*/resolve/test/resolver/malformed_package_json/
<PROJECT_ROOT>/dist/

[include]

[libs]
Expand Down
7 changes: 3 additions & 4 deletions src/cli/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,9 @@ export const validateOrThrow = (value: mixed, jsonSchema: mixed) => {
};

export const loadConfigFile = (configFile: string): Config => {
// $FlowIgnore // eslint-disable-next-line flowtype-errors/uncovered
const data: Config = require(configFile);
// eslint-disable-next-line flowtype-errors/uncovered
validateOrThrow(data, configSchema);
// $FlowIgnore
const data: Config = require(configFile); // eslint-disable-line flowtype-errors/uncovered
validateOrThrow(data, configSchema); // eslint-disable-line flowtype-errors/uncovered
return data;
};

Expand Down
17 changes: 14 additions & 3 deletions src/cli/run.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
#!/usr/bin/env node
// @flow
/* eslint-disable no-console */
import type {Schema} from '../types';
import type {GraphQLSchema} from 'graphql/type/schema';

import {generateTypeFiles, processPragmas} from '../generateTypeFiles';
import {processFiles} from '../parser/parse';
import {resolveDocuments} from '../parser/resolve';
Expand All @@ -15,7 +18,6 @@ import {print} from 'graphql/language/printer';
import {validate} from 'graphql/validation';
import path from 'path';
import {dirname} from 'path';
import type {GenerateConfig} from '../types';

/**
* This CLI tool executes the following steps:
Expand Down Expand Up @@ -81,7 +83,16 @@ const files = processFiles(inputFiles, (f) => {
return readFileSync(f, 'utf8');
}
if (existsSync(f + '.js')) {
return readFileSync(f + '.js', 'utf8');
return {text: readFileSync(f + '.js', 'utf8'), resolvedPath: f + '.js'};
}
if (existsSync(f + '.ts')) {
return {text: readFileSync(f + '.ts', 'utf8'), resolvedPath: f + '.ts'};
}
if (existsSync(f + '.tsx')) {
return {
text: readFileSync(f + '.tsx', 'utf8'),
resolvedPath: f + '.tsx',
};
}
throw new Error(`Unable to find ${f}`);
});
Expand Down Expand Up @@ -118,7 +129,7 @@ console.log(Object.keys(resolved).length, 'resolved queries');

/** Step (4) */

const schemaCache = {};
const schemaCache: {[key: string]: [GraphQLSchema, Schema]} = {};
const getCachedSchemas = (schemaFilePath: string) => {
if (!schemaCache[schemaFilePath]) {
schemaCache[schemaFilePath] = getSchemas(
Expand Down
2 changes: 2 additions & 0 deletions src/generateTypeFiles.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {GenerateConfig, CrawlConfig, Schema} from './types';
import fs from 'fs';
import path from 'path';
import {documentToFlowTypes} from '.';
// eslint-disable-next-line flowtype-errors/uncovered
import {convert} from '@khanacademy/flow-to-ts/dist/convert.bundle';

export const indexPrelude = (regenerateCommand?: string): string => `// @flow
Expand Down Expand Up @@ -150,6 +151,7 @@ export const generateTypeFiles = (
Object.keys(files).forEach((key) => {
let fname = key;
if (options.typeScript) {
// eslint-disable-next-line flowtype-errors/uncovered
files[key] = convert(files[key]);
fname = key.replace(/\.js$/, '.ts');
}
Expand Down
4 changes: 3 additions & 1 deletion src/parser/__test__/parse.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import {resolveDocuments} from '../resolve';

import {print} from 'graphql/language/printer';

const fixtureFiles: {[key: string]: string} = {
const fixtureFiles: {
[key: string]: string | {text: string, resolvedPath: string},
} = {
'/firstFile.js': `
// Note that you can import graphql-tag as
// something other than gql.
Expand Down
21 changes: 15 additions & 6 deletions src/parser/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,10 @@ const listExternalReferences = (file: FileResult): Array<string> => {
return Object.keys(paths);
};

export const processFile = (filePath: string, contents: string): FileResult => {
export const processFile = (
filePath: string,
contents: string | {text: string, resolvedPath: string},
): FileResult => {
const dir = path.dirname(filePath);
const result: FileResult = {
path: filePath,
Expand All @@ -130,13 +133,17 @@ export const processFile = (filePath: string, contents: string): FileResult => {
locals: {},
errors: [],
};
const resolved =
typeof contents === 'string' ? filePath : contents.resolvedPath;
const text = typeof contents === 'string' ? contents : contents.text;
const plugins = resolved.match(/\.tsx?$/)
? ['typescript', filePath.endsWith('x') ? 'jsx' : null].filter(Boolean)
: [['flow', {enums: true}], 'jsx'];
/* eslint-disable flowtype-errors/uncovered */
const ast: BabelNodeFile = parse(contents, {
const ast: BabelNodeFile = parse(text, {
sourceType: 'module',
allowImportExportEverywhere: true,
plugins: filePath.match(/\.tsx?$/)
? ['typescript', 'jsx']
: [['flow', {enums: true}], 'jsx'],
plugins: plugins,
});
/* eslint-enable flowtype-errors/uncovered */
const gqlTagNames = [];
Expand Down Expand Up @@ -384,7 +391,9 @@ const getLocals = (

export const processFiles = (
filePaths: Array<string>,
getFileSource: (path: string) => string,
getFileSource: (
path: string,
) => string | {text: string, resolvedPath: string},
): Files => {
const files: Files = {};
const toProcess = filePaths.slice();
Expand Down

0 comments on commit a581359

Please sign in to comment.