@khanacademy/graphql-flow 1.1.2 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/cli/schema.json +3 -0
- package/dist/generateTypeFiles.js +4 -12
- package/dist/generateTypeFiles.js.flow +4 -10
- package/dist/generateTypeFiles.js.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.flow +1 -0
- package/dist/index.js.map +1 -1
- package/dist/parser/parse.js +4 -1
- package/dist/parser/parse.js.flow +4 -1
- package/dist/parser/parse.js.map +1 -1
- package/dist/parser/resolve.js +10 -6
- package/dist/parser/resolve.js.flow +10 -8
- package/dist/parser/resolve.js.map +1 -1
- package/dist/parser/utils.js +37 -0
- package/dist/parser/utils.js.flow +25 -0
- package/dist/parser/utils.js.map +1 -0
- package/dist/types.js.flow +1 -0
- package/package.json +1 -1
- package/src/cli/schema.json +3 -0
- package/src/generateTypeFiles.js +4 -10
- package/src/index.js +1 -0
- package/src/parser/parse.js +4 -1
- package/src/parser/resolve.js +10 -8
- package/src/parser/utils.js +25 -0
- package/src/types.js +1 -0
package/CHANGELOG.md
CHANGED
package/dist/cli/schema.json
CHANGED
|
@@ -32,24 +32,16 @@ const generateTypeFileContents = (fileName, schema, document, options, generated
|
|
|
32
32
|
const files = {}; /// Write export for __generated__/index.js if it doesn't exist
|
|
33
33
|
|
|
34
34
|
const addToIndex = (filePath, typeName) => {
|
|
35
|
-
if (options.typeScript) {
|
|
35
|
+
if (options.typeScript || options.omitFileExtensions) {
|
|
36
36
|
// Typescript doesn't like file extensions
|
|
37
37
|
filePath = filePath.replace(/\.js$/, '');
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
const newLine = `export type {${typeName}} from './${_path.default.basename(filePath)}';`;
|
|
40
|
+
const newLine = `export type {${typeName}} from './${_path.default.basename(filePath)}';`; // We match the entire new line to avoid issues that can arise from
|
|
41
|
+
// prefix matches.
|
|
41
42
|
|
|
42
|
-
if (indexContents.indexOf(
|
|
43
|
+
if (indexContents.indexOf(newLine) === -1) {
|
|
43
44
|
indexContents += newLine + '\n';
|
|
44
|
-
} else {
|
|
45
|
-
const lines = indexContents.split('\n').map(line => {
|
|
46
|
-
if (line.includes('./' + _path.default.basename(filePath))) {
|
|
47
|
-
return newLine;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
return line;
|
|
51
|
-
});
|
|
52
|
-
indexContents = lines.join('\n');
|
|
53
45
|
}
|
|
54
46
|
};
|
|
55
47
|
|
|
@@ -29,23 +29,17 @@ export const generateTypeFileContents = (
|
|
|
29
29
|
|
|
30
30
|
/// Write export for __generated__/index.js if it doesn't exist
|
|
31
31
|
const addToIndex = (filePath, typeName) => {
|
|
32
|
-
if (options.typeScript) {
|
|
32
|
+
if (options.typeScript || options.omitFileExtensions) {
|
|
33
33
|
// Typescript doesn't like file extensions
|
|
34
34
|
filePath = filePath.replace(/\.js$/, '');
|
|
35
35
|
}
|
|
36
36
|
const newLine = `export type {${typeName}} from './${path.basename(
|
|
37
37
|
filePath,
|
|
38
38
|
)}';`;
|
|
39
|
-
|
|
39
|
+
// We match the entire new line to avoid issues that can arise from
|
|
40
|
+
// prefix matches.
|
|
41
|
+
if (indexContents.indexOf(newLine) === -1) {
|
|
40
42
|
indexContents += newLine + '\n';
|
|
41
|
-
} else {
|
|
42
|
-
const lines = indexContents.split('\n').map((line) => {
|
|
43
|
-
if (line.includes('./' + path.basename(filePath))) {
|
|
44
|
-
return newLine;
|
|
45
|
-
}
|
|
46
|
-
return line;
|
|
47
|
-
});
|
|
48
|
-
indexContents = lines.join('\n');
|
|
49
43
|
}
|
|
50
44
|
};
|
|
51
45
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/generateTypeFiles.js"],"names":["indexPrelude","regenerateCommand","generateTypeFileContents","fileName","schema","document","options","generatedDir","indexContents","files","addToIndex","filePath","typeName","typeScript","replace","newLine","path","basename","indexOf","lines","split","map","line","includes","join","generated","forEach","name","code","isFragment","extraTypes","experimentalEnums","targetFileName","typeFileName","targetPath","fileContents","splitTypes","Object","keys","enumNames","length","getGeneratedDir","generatedDirectory","isAbsolute","relative","process","cwd","dirname","generateTypeFiles","indexFile","fs","existsSync","mkdirSync","recursive","writeFileSync","readFileSync","key","fname","processPragmas","generateConfig","crawlConfig","rawSource","ignorePragma","generate","autogen","loosePragma","autogenStrict","pragma","noPragmas","strict","strictNullability"],"mappings":";;;;;;;AAGA;;AACA;;AACA;;AAEA;;;;AADA;AAGO,MAAMA,YAAY,GAAIC,iBAAD,IAAyC;AACrE;AACA;AACA;AACA;AACA,IAAIA,iBAAiB,GAAG,8BAA8BA,iBAAjC,GAAqD,EAAG;AAC7E;AACA;AACA,CARO;;;;AAUA,MAAMC,wBAAwB,GAAG,CACpCC,QADoC,EAEpCC,MAFoC,EAGpCC,QAHoC,EAIpCC,OAJoC,EAKpCC,YALoC,EAMpCC,aANoC,KAOsB;AAC1D,QAAMC,KAAK,GAAG,EAAd,CAD0D,CAG1D;;AACA,QAAMC,UAAU,GAAG,CAACC,QAAD,EAAWC,QAAX,KAAwB;AACvC,QAAIN,OAAO,CAACO,UAAZ,EAAwB;AACpB;AACAF,MAAAA,QAAQ,GAAGA,QAAQ,CAACG,OAAT,CAAiB,OAAjB,EAA0B,EAA1B,CAAX;AACH;;AACD,UAAMC,OAAO,GAAI,gBAAeH,QAAS,aAAYI,cAAKC,QAAL,CACjDN,QADiD,CAEnD,IAFF;;AAGA,QAAIH,aAAa,CAACU,OAAd,CAAsB,OAAOF,cAAKC,QAAL,CAAcN,QAAd,CAA7B,MAA0D,CAAC,CAA/D,EAAkE;AAC9DH,MAAAA,aAAa,IAAIO,OAAO,GAAG,IAA3B;AACH,KAFD,MAEO;AACH,YAAMI,KAAK,GAAGX,aAAa,CAACY,KAAd,CAAoB,IAApB,EAA0BC,GAA1B,CAA+BC,IAAD,IAAU;AAClD,YAAIA,IAAI,CAACC,QAAL,CAAc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XD;;AAaAN,cAAGI,aAAH,CAAiBL,SAAjB,EAA4BzC,aAA5B;AACH,CA3CM;;;;AA6CA,MAAMkD,cAAc,GAAG,CAC1BC,cAD0B,EAE1BC,WAF0B,EAG1BC,SAH0B,KAIc;AACxC,MACID,WAAW,CAACE,YAAZ,IACAD,SAAS,CAACtC,QAAV,CAAmBqC,WAAW,CAACE,YAA/B,CAFJ,EAGE;AACE,WAAO;AAACC,MAAAA,QAAQ,EAAE;AAAX,KAAP;AACH;;AAED,QAAMC,OAAO,GAAGJ,WAAW,CAACK,WAAZ,GACVJ,SAAS,CAACtC,QAAV,CAAmBqC,WAAW,CAACK,WAA/B,CADU,GAEV,KAFN;AAGA,QAAMC,aAAa,GAAGN,WAAW,CAACO,MAAZ,GAChBN,SAAS,CAACtC,QAAV,CAAmBqC,WAAW,CAACO,MAA/B,CADgB,GAEhB,KAFN;AAGA,QAAMC,SAAS,GAAG,CAACR,WAAW,CAACK,WAAb,IAA4B,CAACL,WAAW,CAACO,MAA3D;;AAEA,MAAIH,OAAO,IAAIE,aAAX,IAA4BE,SAAhC,EAA2C;AACvC,WAAO;AACHL,MAAAA,QAAQ,EAAE,IADP;AAEHM,MAAAA,MAAM,EAAED,SAAS,GACXT,cAAc,CAACW,iBADJ,GAEXJ,aAAa,IAAI,CAACF;AAJrB,KAAP;AAMH,GAPD,MAOO;AACH,WAAO;AAACD,MAAAA,QAAQ,EAAE;AAAX,KAAP;AACH;AACJ,CA9BM","sourcesContent":["// @flow\nimport type {DocumentNode} from 'graphql';\nimport type {GenerateConfig, CrawlConfig, Schema} from './types';\nimport fs from 'fs';\nimport path from 'path';\nimport {documentToFlowTypes} from '.';\n// eslint-disable-next-line flowtype-errors/uncovered\nimport {convert} from '@khanacademy/flow-to-ts/dist/convert.bundle';\n\nexport const indexPrelude = (regenerateCommand?: string): string => `// @flow\n//\n// AUTOGENERATED\n// NOTE: New response types are added to this file automatically.\n// Outdated response types can be removed manually as they are deprecated.\n//${regenerateCommand ? ' To regenerate, run ' + regenerateCommand : ''}\n//\n\n`;\n\nexport const generateTypeFileContents = (\n fileName: string,\n schema: Schema,\n document: DocumentNode,\n options: GenerateConfig,\n generatedDir: string,\n indexContents: string,\n): {indexContents: string, files: {[key: string]: string}} => {\n const files = {};\n\n /// Write export for __generated__/index.js if it doesn't exist\n const addToIndex = (filePath, typeName) => {\n if (options.typeScript) {\n // Typescript doesn't like file extensions\n filePath = filePath.replace(/\\.js$/, '');\n }\n const newLine = `export type {${typeName}} from './${path.basename(\n filePath,\n )}';`;\n if (indexContents.indexOf('./' + path.basename(filePath)) === -1) {\n indexContents += newLine + '\\n';\n } else {\n const lines = indexContents.split('\\n').map((line) => {\n if (line.includes('./' + path.basename(filePath))) {\n return newLine;\n }\n return line;\n });\n indexContents = lines.join('\\n');\n }\n };\n\n const generated = documentToFlowTypes(document, schema, options);\n generated.forEach(\n ({name, typeName, code, isFragment, extraTypes, experimentalEnums}) => {\n // We write all generated files to a `__generated__` subdir to keep\n // things tidy.\n const targetFileName = options.typeFileName\n ? options.typeFileName.replace('[operationName]', name)\n : `${name}.js`;\n const targetPath = path.join(generatedDir, targetFileName);\n\n let fileContents =\n '// @' +\n `flow\\n// AUTOGENERATED -- DO NOT EDIT\\n` +\n `// Generated for operation '${name}' in file '../${path.basename(\n fileName,\n )}'\\n` +\n (options.regenerateCommand\n ? `// To regenerate, run '${options.regenerateCommand}'.\\n`\n : '') +\n code;\n if (options.splitTypes && !isFragment) {\n fileContents +=\n `\\nexport type ${name} = ${typeName}['response'];\\n` +\n `export type ${name}Variables = ${typeName}['variables'];\\n`;\n }\n Object.keys(extraTypes).forEach(\n (name) =>\n (fileContents += `\\n\\nexport type ${name} = ${extraTypes[name]};`),\n );\n const enumNames = Object.keys(experimentalEnums);\n if (options.experimentalEnums && enumNames.length) {\n // TODO(somewhatabstract, FEI-4172): Update to fixed eslint-plugin-flowtype\n // and remove this disable.\n fileContents += `\\n\\n/* eslint-disable no-undef */`;\n enumNames.forEach(\n (name) =>\n (fileContents += `\\nexport ${experimentalEnums[name]};\\n`),\n );\n fileContents += `/* eslint-enable no-undef */`;\n }\n\n addToIndex(targetPath, typeName);\n files[targetPath] =\n fileContents\n // Remove whitespace from the ends of lines; babel's generate sometimes\n // leaves them hanging around.\n .replace(/\\s+$/gm, '') + '\\n';\n },\n );\n\n return {files, indexContents};\n};\n\nconst getGeneratedDir = (fileName: string, options: GenerateConfig) => {\n const generatedDirectory = options.generatedDirectory ?? '__generated__';\n if (path.isAbsolute(generatedDirectory)) {\n // fileName is absolute here, so we make it relative to cwd\n // for more reasonable filenames. We convert leading ..'s\n // to `__` so this doesn't escape the output directory.\n return path.join(\n generatedDirectory,\n path\n .relative(process.cwd(), path.dirname(fileName))\n .replace(/\\.\\.\\//g, '__/'),\n );\n } else {\n return path.join(path.dirname(fileName), generatedDirectory);\n }\n};\n\nexport const generateTypeFiles = (\n fileName: string,\n schema: Schema,\n document: DocumentNode,\n options: GenerateConfig,\n) => {\n const generatedDir = getGeneratedDir(fileName, options);\n const indexFile = path.join(\n generatedDir,\n 'index' + (options.typeScript ? '.ts' : '.js'),\n );\n\n if (!fs.existsSync(generatedDir)) {\n fs.mkdirSync(generatedDir, {recursive: true});\n }\n if (!fs.existsSync(indexFile)) {\n fs.writeFileSync(indexFile, indexPrelude(options.regenerateCommand));\n }\n\n const {indexContents, files} = generateTypeFileContents(\n fileName,\n schema,\n document,\n options,\n generatedDir,\n fs.readFileSync(indexFile, 'utf8'),\n );\n\n fs.writeFileSync(indexFile, indexContents);\n Object.keys(files).forEach((key) => {\n let fname = key;\n if (options.typeScript) {\n // eslint-disable-next-line flowtype-errors/uncovered\n files[key] = convert(files[key]).replace(\n `variables: {}`,\n `variables: Record<never, never>`,\n );\n fname = key.replace(/\\.js$/, '.ts');\n }\n fs.writeFileSync(fname, files[key]);\n });\n\n fs.writeFileSync(indexFile, indexContents);\n};\n\nexport const processPragmas = (\n generateConfig: GenerateConfig,\n crawlConfig: CrawlConfig,\n rawSource: string,\n): {generate: boolean, strict?: boolean} => {\n if (\n crawlConfig.ignorePragma &&\n rawSource.includes(crawlConfig.ignorePragma)\n ) {\n return {generate: false};\n }\n\n const autogen = crawlConfig.loosePragma\n ? rawSource.includes(crawlConfig.loosePragma)\n : false;\n const autogenStrict = crawlConfig.pragma\n ? rawSource.includes(crawlConfig.pragma)\n : false;\n const noPragmas = !crawlConfig.loosePragma && !crawlConfig.pragma;\n\n if (autogen || autogenStrict || noPragmas) {\n return {\n generate: true,\n strict: noPragmas\n ? generateConfig.strictNullability\n : autogenStrict || !autogen,\n };\n } else {\n return {generate: false};\n }\n};\n"],"file":"generateTypeFiles.js"}
|
|
1
|
+
{"version":3,"sources":["../src/generateTypeFiles.js"],"names":["indexPrelude","regenerateCommand","generateTypeFileContents","fileName","schema","document","options","generatedDir","indexContents","files","addToIndex","filePath","typeName","typeScript","omitFileExtensions","replace","newLine","path","basename","indexOf","generated","forEach","name","code","isFragment","extraTypes","experimentalEnums","targetFileName","typeFileName","targetPath","join","fileContents","splitTypes","Object","keys","enumNames","length","getGeneratedDir","generatedDirectory","isAbsolute","relative","process","cwd","dirname","generateTypeFiles","indexFile","fs","existsSync","mkdirSync","recursive","writeFileSync","readFileSync","key","fname","processPragmas","generateConfig","crawlConfig","rawSource","ignorePragma","includes","generate","autogen","loosePragma","autogenStrict","pragma","noPragmas","strict","strictNullability"],"mappings":";;;;;;;AAGA;;AACA;;AACA;;AAEA;;;;AADA;AAGO,MAAMA,YAAY,GAAIC,iBAAD,IAAyC;AACrE;AACA;AACA;AACA;AACA,IAAIA,iBAAiB,GAAG,8BAA8BA,iBAAjC,GAAqD,EAAG;AAC7E;AACA;AACA,CARO;;;;AAUA,MAAMC,wBAAwB,GAAG,CACpCC,QADoC,EAEpCC,MAFoC,EAGpCC,QAHoC,EAIpCC,OAJoC,EAKpCC,YALoC,EAMpCC,aANoC,KAOsB;AAC1D,QAAMC,KAAK,GAAG,EAAd,CAD0D,CAG1D;;AACA,QAAMC,UAAU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AAD,CAAb,EAAoBrC,OAApB,CACR,eADQ,EAER,iCAFQ,CAAb;AAIAsC,MAAAA,KAAK,GAAGD,GAAG,CAACrC,OAAJ,CAAY,OAAZ,EAAqB,KAArB,CAAR;AACH;;AACD+B,gBAAGI,aAAH,CAAiBG,KAAjB,EAAwB5C,KAAK,CAAC2C,GAAD,CAA7B;AACH,GAXD;;AAaAN,cAAGI,aAAH,CAAiBL,SAAjB,EAA4BrC,aAA5B;AACH,CA3CM;;;;AA6CA,MAAM8C,cAAc,GAAG,CAC1BC,cAD0B,EAE1BC,WAF0B,EAG1BC,SAH0B,KAIc;AACxC,MACID,WAAW,CAACE,YAAZ,IACAD,SAAS,CAACE,QAAV,CAAmBH,WAAW,CAACE,YAA/B,CAFJ,EAGE;AACE,WAAO;AAACE,MAAAA,QAAQ,EAAE;AAAX,KAAP;AACH;;AAED,QAAMC,OAAO,GAAGL,WAAW,CAACM,WAAZ,GACVL,SAAS,CAACE,QAAV,CAAmBH,WAAW,CAACM,WAA/B,CADU,GAEV,KAFN;AAGA,QAAMC,aAAa,GAAGP,WAAW,CAACQ,MAAZ,GAChBP,SAAS,CAACE,QAAV,CAAmBH,WAAW,CAACQ,MAA/B,CADgB,GAEhB,KAFN;AAGA,QAAMC,SAAS,GAAG,CAACT,WAAW,CAACM,WAAb,IAA4B,CAACN,WAAW,CAACQ,MAA3D;;AAEA,MAAIH,OAAO,IAAIE,aAAX,IAA4BE,SAAhC,EAA2C;AACvC,WAAO;AACHL,MAAAA,QAAQ,EAAE,IADP;AAEHM,MAAAA,MAAM,EAAED,SAAS,GACXV,cAAc,CAACY,iBADJ,GAEXJ,aAAa,IAAI,CAACF;AAJrB,KAAP;AAMH,GAPD,MAOO;AACH,WAAO;AAACD,MAAAA,QAAQ,EAAE;AAAX,KAAP;AACH;AACJ,CA9BM","sourcesContent":["// @flow\nimport type {DocumentNode} from 'graphql';\nimport type {GenerateConfig, CrawlConfig, Schema} from './types';\nimport fs from 'fs';\nimport path from 'path';\nimport {documentToFlowTypes} from '.';\n// eslint-disable-next-line flowtype-errors/uncovered\nimport {convert} from '@khanacademy/flow-to-ts/dist/convert.bundle';\n\nexport const indexPrelude = (regenerateCommand?: string): string => `// @flow\n//\n// AUTOGENERATED\n// NOTE: New response types are added to this file automatically.\n// Outdated response types can be removed manually as they are deprecated.\n//${regenerateCommand ? ' To regenerate, run ' + regenerateCommand : ''}\n//\n\n`;\n\nexport const generateTypeFileContents = (\n fileName: string,\n schema: Schema,\n document: DocumentNode,\n options: GenerateConfig,\n generatedDir: string,\n indexContents: string,\n): {indexContents: string, files: {[key: string]: string}} => {\n const files = {};\n\n /// Write export for __generated__/index.js if it doesn't exist\n const addToIndex = (filePath, typeName) => {\n if (options.typeScript || options.omitFileExtensions) {\n // Typescript doesn't like file extensions\n filePath = filePath.replace(/\\.js$/, '');\n }\n const newLine = `export type {${typeName}} from './${path.basename(\n filePath,\n )}';`;\n // We match the entire new line to avoid issues that can arise from\n // prefix matches.\n if (indexContents.indexOf(newLine) === -1) {\n indexContents += newLine + '\\n';\n }\n };\n\n const generated = documentToFlowTypes(document, schema, options);\n generated.forEach(\n ({name, typeName, code, isFragment, extraTypes, experimentalEnums}) => {\n // We write all generated files to a `__generated__` subdir to keep\n // things tidy.\n const targetFileName = options.typeFileName\n ? options.typeFileName.replace('[operationName]', name)\n : `${name}.js`;\n const targetPath = path.join(generatedDir, targetFileName);\n\n let fileContents =\n '// @' +\n `flow\\n// AUTOGENERATED -- DO NOT EDIT\\n` +\n `// Generated for operation '${name}' in file '../${path.basename(\n fileName,\n )}'\\n` +\n (options.regenerateCommand\n ? `// To regenerate, run '${options.regenerateCommand}'.\\n`\n : '') +\n code;\n if (options.splitTypes && !isFragment) {\n fileContents +=\n `\\nexport type ${name} = ${typeName}['response'];\\n` +\n `export type ${name}Variables = ${typeName}['variables'];\\n`;\n }\n Object.keys(extraTypes).forEach(\n (name) =>\n (fileContents += `\\n\\nexport type ${name} = ${extraTypes[name]};`),\n );\n const enumNames = Object.keys(experimentalEnums);\n if (options.experimentalEnums && enumNames.length) {\n // TODO(somewhatabstract, FEI-4172): Update to fixed eslint-plugin-flowtype\n // and remove this disable.\n fileContents += `\\n\\n/* eslint-disable no-undef */`;\n enumNames.forEach(\n (name) =>\n (fileContents += `\\nexport ${experimentalEnums[name]};\\n`),\n );\n fileContents += `/* eslint-enable no-undef */`;\n }\n\n addToIndex(targetPath, typeName);\n files[targetPath] =\n fileContents\n // Remove whitespace from the ends of lines; babel's generate sometimes\n // leaves them hanging around.\n .replace(/\\s+$/gm, '') + '\\n';\n },\n );\n\n return {files, indexContents};\n};\n\nconst getGeneratedDir = (fileName: string, options: GenerateConfig) => {\n const generatedDirectory = options.generatedDirectory ?? '__generated__';\n if (path.isAbsolute(generatedDirectory)) {\n // fileName is absolute here, so we make it relative to cwd\n // for more reasonable filenames. We convert leading ..'s\n // to `__` so this doesn't escape the output directory.\n return path.join(\n generatedDirectory,\n path\n .relative(process.cwd(), path.dirname(fileName))\n .replace(/\\.\\.\\//g, '__/'),\n );\n } else {\n return path.join(path.dirname(fileName), generatedDirectory);\n }\n};\n\nexport const generateTypeFiles = (\n fileName: string,\n schema: Schema,\n document: DocumentNode,\n options: GenerateConfig,\n) => {\n const generatedDir = getGeneratedDir(fileName, options);\n const indexFile = path.join(\n generatedDir,\n 'index' + (options.typeScript ? '.ts' : '.js'),\n );\n\n if (!fs.existsSync(generatedDir)) {\n fs.mkdirSync(generatedDir, {recursive: true});\n }\n if (!fs.existsSync(indexFile)) {\n fs.writeFileSync(indexFile, indexPrelude(options.regenerateCommand));\n }\n\n const {indexContents, files} = generateTypeFileContents(\n fileName,\n schema,\n document,\n options,\n generatedDir,\n fs.readFileSync(indexFile, 'utf8'),\n );\n\n fs.writeFileSync(indexFile, indexContents);\n Object.keys(files).forEach((key) => {\n let fname = key;\n if (options.typeScript) {\n // eslint-disable-next-line flowtype-errors/uncovered\n files[key] = convert(files[key]).replace(\n `variables: {}`,\n `variables: Record<never, never>`,\n );\n fname = key.replace(/\\.js$/, '.ts');\n }\n fs.writeFileSync(fname, files[key]);\n });\n\n fs.writeFileSync(indexFile, indexContents);\n};\n\nexport const processPragmas = (\n generateConfig: GenerateConfig,\n crawlConfig: CrawlConfig,\n rawSource: string,\n): {generate: boolean, strict?: boolean} => {\n if (\n crawlConfig.ignorePragma &&\n rawSource.includes(crawlConfig.ignorePragma)\n ) {\n return {generate: false};\n }\n\n const autogen = crawlConfig.loosePragma\n ? rawSource.includes(crawlConfig.loosePragma)\n : false;\n const autogenStrict = crawlConfig.pragma\n ? rawSource.includes(crawlConfig.pragma)\n : false;\n const noPragmas = !crawlConfig.loosePragma && !crawlConfig.pragma;\n\n if (autogen || autogenStrict || noPragmas) {\n return {\n generate: true,\n strict: noPragmas\n ? generateConfig.strictNullability\n : autogenStrict || !autogen,\n };\n } else {\n return {generate: false};\n }\n};\n"],"file":"generateTypeFiles.js"}
|
package/dist/index.js
CHANGED
|
@@ -25,13 +25,14 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
|
|
|
25
25
|
*/
|
|
26
26
|
// eslint-disable-line flowtype-errors/uncovered
|
|
27
27
|
const optionsToConfig = (schema, definitions, options, errors = []) => {
|
|
28
|
-
var _options$strictNullab, _options$readOnlyArra, _options$scalars, _options$typeScript;
|
|
28
|
+
var _options$strictNullab, _options$readOnlyArra, _options$scalars, _options$typeScript, _options$omitFileExte;
|
|
29
29
|
|
|
30
30
|
const internalOptions = {
|
|
31
31
|
strictNullability: (_options$strictNullab = options === null || options === void 0 ? void 0 : options.strictNullability) !== null && _options$strictNullab !== void 0 ? _options$strictNullab : true,
|
|
32
32
|
readOnlyArray: (_options$readOnlyArra = options === null || options === void 0 ? void 0 : options.readOnlyArray) !== null && _options$readOnlyArra !== void 0 ? _options$readOnlyArra : true,
|
|
33
33
|
scalars: (_options$scalars = options === null || options === void 0 ? void 0 : options.scalars) !== null && _options$scalars !== void 0 ? _options$scalars : {},
|
|
34
|
-
typeScript: (_options$typeScript = options === null || options === void 0 ? void 0 : options.typeScript) !== null && _options$typeScript !== void 0 ? _options$typeScript : false
|
|
34
|
+
typeScript: (_options$typeScript = options === null || options === void 0 ? void 0 : options.typeScript) !== null && _options$typeScript !== void 0 ? _options$typeScript : false,
|
|
35
|
+
omitFileExtensions: (_options$omitFileExte = options === null || options === void 0 ? void 0 : options.omitFileExtensions) !== null && _options$omitFileExte !== void 0 ? _options$omitFileExte : false
|
|
35
36
|
};
|
|
36
37
|
const fragments = {};
|
|
37
38
|
definitions.forEach(def => {
|
package/dist/index.js.flow
CHANGED
|
@@ -30,6 +30,7 @@ const optionsToConfig = (
|
|
|
30
30
|
readOnlyArray: options?.readOnlyArray ?? true,
|
|
31
31
|
scalars: options?.scalars ?? {},
|
|
32
32
|
typeScript: options?.typeScript ?? false,
|
|
33
|
+
omitFileExtensions: options?.omitFileExtensions ?? false,
|
|
33
34
|
};
|
|
34
35
|
const fragments = {};
|
|
35
36
|
definitions.forEach((def) => {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.js"],"names":["optionsToConfig","schema","definitions","options","errors","internalOptions","strictNullability","readOnlyArray","scalars","typeScript","fragments","forEach","def","kind","name","value","config","allObjectTypes","path","experimentalEnumsMap","experimentalEnums","undefined","FlowGenerationError","Error","constructor","join","messages","documentToFlowTypes","document","result","map","item","types","code","exportAllObjectTypes","extraTypes","codegenExtraTypes","typeName","isFragment","operation","response","variables","filter","Boolean","length","Object","keys","k"],"mappings":";;;;;;;AAWA;;AACA;;AAIA;;;;AAhBA;;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AAGyC;AAUzC,MAAMA,eAAe,GAAG,CACpBC,MADoB,EAEpBC,WAFoB,EAGpBC,OAHoB,EAIpBC,MAAqB,GAAG,EAJJ,KAKV;AAAA;;AACV,QAAMC,eAAe,GAAG;AACpBC,IAAAA,iBAAiB,2BAAEH,OAAF,aAAEA,OAAF,uBAAEA,OAAO,CAAEG,iBAAX,yEAAgC,IAD7B;AAEpBC,IAAAA,aAAa,2BAAEJ,OAAF,aAAEA,OAAF,uBAAEA,OAAO,CAAEI,aAAX,yEAA4B,IAFrB;AAGpBC,IAAAA,OAAO,sBAAEL,OAAF,aAAEA,OAAF,uBAAEA,OAAO,CAAEK,OAAX,+DAAsB,EAHT;AAIpBC,IAAAA,UAAU,yBAAEN,OAAF,aAAEA,OAAF,uBAAEA,OAAO,CAAEM,UAAX,qEAAyB;
|
|
1
|
+
{"version":3,"sources":["../src/index.js"],"names":["optionsToConfig","schema","definitions","options","errors","internalOptions","strictNullability","readOnlyArray","scalars","typeScript","omitFileExtensions","fragments","forEach","def","kind","name","value","config","allObjectTypes","path","experimentalEnumsMap","experimentalEnums","undefined","FlowGenerationError","Error","constructor","join","messages","documentToFlowTypes","document","result","map","item","types","code","exportAllObjectTypes","extraTypes","codegenExtraTypes","typeName","isFragment","operation","response","variables","filter","Boolean","length","Object","keys","k"],"mappings":";;;;;;;AAWA;;AACA;;AAIA;;;;AAhBA;;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AAGyC;AAUzC,MAAMA,eAAe,GAAG,CACpBC,MADoB,EAEpBC,WAFoB,EAGpBC,OAHoB,EAIpBC,MAAqB,GAAG,EAJJ,KAKV;AAAA;;AACV,QAAMC,eAAe,GAAG;AACpBC,IAAAA,iBAAiB,2BAAEH,OAAF,aAAEA,OAAF,uBAAEA,OAAO,CAAEG,iBAAX,yEAAgC,IAD7B;AAEpBC,IAAAA,aAAa,2BAAEJ,OAAF,aAAEA,OAAF,uBAAEA,OAAO,CAAEI,aAAX,yEAA4B,IAFrB;AAGpBC,IAAAA,OAAO,sBAAEL,OAAF,aAAEA,OAAF,uBAAEA,OAAO,CAAEK,OAAX,+DAAsB,EAHT;AAIpBC,IAAAA,UAAU,yBAAEN,OAAF,aAAEA,OAAF,uBAAEA,OAAO,CAAEM,UAAX,qEAAyB,KAJf;AAKpBC,IAAAA,kBAAkB,2BAAEP,OA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9B,EAAoC,EAClD,GAAGf,MAD+C;AAElDE,QAAAA,IAAI,EAAE,CAACJ,IAAD;AAF4C,OAApC,CAAlB;AAKA,YAAMuB,QAAQ,GAAI,GAAEvB,IAAK,MAAzB,CAfF,CAgBE;AACA;;AACA,YAAMmB,IAAI,GAAI,eAAcI,QAAS,yBAAwBI,SAAU,oBAAmBD,QAAS,OAAnG;AAEA,YAAML,UAAU,GAAGC,iBAAiB,CAACJ,KAAD,CAApC;AACA,YAAMZ,iBAAiB,GAAGgB,iBAAiB,CACvCpB,MAAM,CAACG,oBAAP,IAA+B,EADQ,CAA3C;AAIA,aAAO;AAACL,QAAAA,IAAD;AAAOuB,QAAAA,QAAP;AAAiBJ,QAAAA,IAAjB;AAAuBE,QAAAA,UAAvB;AAAmCf,QAAAA;AAAnC,OAAP;AACH;AACJ,GA9DU,EA+DVsB,MA/DU,CA+DHC,OA/DG,CAAf;;AAgEA,MAAIxC,MAAM,CAACyC,MAAX,EAAmB;AACf,UAAM,IAAItB,mBAAJ,CAAwBnB,MAAxB,CAAN;AACH;;AACD,SAAO0B,MAAP;AACH,CAvFM;;;;AAyFP,SAASO,iBAAT,CAA2BJ,KAA3B,EAEE;AACE,QAAMG,UAAmC,GAAG,EAA5C;AACAU,EAAAA,MAAM,CAACC,IAAP,CAAYd,KAAZ,EAAmBrB,OAAnB,CAA4BoC,CAAD,IAAe;AACtC;AACAZ,IAAAA,UAAU,CAACY,CAAD,CAAV,GAAgB,wBAASf,KAAK,CAACe,CAAD,CAAd,EAAmBd,IAAnC;AACH,GAHD;AAIA,SAAOE,UAAP;AACH","sourcesContent":["/* eslint-disable no-console */\n/* flow-uncovered-file */\n// @flow\n/**\n * This tool generates flowtype definitions from graphql queries.\n *\n * It relies on `introspection-query.json` existing in this directory,\n * which is produced by running `./tools/graphql-flow/sendIntrospection.js`.\n */\nimport type {DefinitionNode, DocumentNode} from 'graphql';\n\nimport generate from '@babel/generator'; // eslint-disable-line flowtype-errors/uncovered\nimport {\n generateFragmentType,\n generateResponseType,\n} from './generateResponseType';\nimport {generateVariablesType} from './generateVariablesType';\nimport type {BabelNode} from '@babel/types';\n\nimport type {Context, Schema, GenerateConfig} from './types';\n\nconst optionsToConfig = (\n schema: Schema,\n definitions: $ReadOnlyArray<DefinitionNode>,\n options?: GenerateConfig,\n errors: Array<string> = [],\n): Context => {\n const internalOptions = {\n strictNullability: options?.strictNullability ?? true,\n readOnlyArray: options?.readOnlyArray ?? true,\n scalars: options?.scalars ?? {},\n typeScript: options?.typeScript ?? false,\n omitFileExtensions: options?.omitFileExtensions ?? false,\n };\n const fragments = {};\n definitions.forEach((def) => {\n if (def.kind === 'FragmentDefinition') {\n fragments[def.name.value] = def;\n }\n });\n const config = {\n fragments,\n schema,\n errors,\n allObjectTypes: null,\n path: [],\n experimentalEnumsMap: options?.experimentalEnums ? {} : undefined,\n ...internalOptions,\n };\n\n return config;\n};\n\nexport class FlowGenerationError extends Error {\n messages: Array<string>;\n constructor(errors: Array<string>) {\n super(`Graphql-flow type generation failed! ${errors.join('; ')}`);\n this.messages = errors;\n }\n}\n\nexport const documentToFlowTypes = (\n document: DocumentNode,\n schema: Schema,\n options?: GenerateConfig,\n): $ReadOnlyArray<{\n name: string,\n typeName: string,\n code: string,\n isFragment?: boolean,\n extraTypes: {[key: string]: string},\n experimentalEnums: {[key: string]: string},\n}> => {\n const errors: Array<string> = [];\n const config = optionsToConfig(\n schema,\n document.definitions,\n options,\n errors,\n );\n const result = document.definitions\n .map((item) => {\n if (item.kind === 'FragmentDefinition') {\n const name = item.name.value;\n const types = {};\n const code = `export type ${name} = ${generateFragmentType(\n schema,\n item,\n {\n ...config,\n path: [name],\n allObjectTypes: options?.exportAllObjectTypes\n ? types\n : null,\n },\n )};`;\n\n const extraTypes = codegenExtraTypes(types);\n const experimentalEnums = codegenExtraTypes(\n config.experimentalEnumsMap || {},\n );\n\n return {\n name,\n typeName: name,\n code,\n isFragment: true,\n extraTypes,\n experimentalEnums,\n };\n }\n if (\n item.kind === 'OperationDefinition' &&\n (item.operation === 'query' || item.operation === 'mutation') &&\n item.name\n ) {\n const types = {};\n const name = item.name.value;\n const response = generateResponseType(schema, item, {\n ...config,\n path: [name],\n allObjectTypes: options?.exportAllObjectTypes\n ? types\n : null,\n });\n const variables = generateVariablesType(schema, item, {\n ...config,\n path: [name],\n });\n\n const typeName = `${name}Type`;\n // TODO(jared): Maybe make this template configurable?\n // We'll see what's required to get webapp on board.\n const code = `export type ${typeName} = {|\\n variables: ${variables},\\n response: ${response}\\n|};`;\n\n const extraTypes = codegenExtraTypes(types);\n const experimentalEnums = codegenExtraTypes(\n config.experimentalEnumsMap || {},\n );\n\n return {name, typeName, code, extraTypes, experimentalEnums};\n }\n })\n .filter(Boolean);\n if (errors.length) {\n throw new FlowGenerationError(errors);\n }\n return result;\n};\n\nfunction codegenExtraTypes(types: {[key: string]: BabelNode}): {\n [key: string]: string,\n} {\n const extraTypes: {[key: string]: string} = {};\n Object.keys(types).forEach((k: string) => {\n // eslint-disable-next-line flowtype-errors/uncovered\n extraTypes[k] = generate(types[k]).code;\n });\n return extraTypes;\n}\n"],"file":"index.js"}
|
package/dist/parser/parse.js
CHANGED
|
@@ -11,6 +11,8 @@ var _traverse = _interopRequireDefault(require("@babel/traverse"));
|
|
|
11
11
|
|
|
12
12
|
var _path = _interopRequireDefault(require("path"));
|
|
13
13
|
|
|
14
|
+
var _utils = require("./utils");
|
|
15
|
+
|
|
14
16
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
15
17
|
|
|
16
18
|
// eslint-disable-line flowtype-errors/uncovered
|
|
@@ -30,7 +32,8 @@ const listExternalReferences = file => {
|
|
|
30
32
|
const add = (v, followImports) => {
|
|
31
33
|
if (v.type === 'import') {
|
|
32
34
|
if (followImports) {
|
|
33
|
-
|
|
35
|
+
const absPath = (0, _utils.getPathWithExtension)(v.path);
|
|
36
|
+
paths[absPath] = true;
|
|
34
37
|
}
|
|
35
38
|
} else {
|
|
36
39
|
v.source.expressions.forEach(expr => add(expr, true));
|
|
@@ -11,6 +11,8 @@ import traverse from '@babel/traverse'; // eslint-disable-line flowtype-errors/u
|
|
|
11
11
|
|
|
12
12
|
import path from 'path';
|
|
13
13
|
|
|
14
|
+
import {getPathWithExtension} from './utils';
|
|
15
|
+
|
|
14
16
|
/**
|
|
15
17
|
* This file is responsible for finding all gql`-annotated
|
|
16
18
|
* template strings in a set of provided files, and for resolving
|
|
@@ -88,7 +90,8 @@ const listExternalReferences = (file: FileResult): Array<string> => {
|
|
|
88
90
|
const add = (v: Document | Import, followImports: boolean) => {
|
|
89
91
|
if (v.type === 'import') {
|
|
90
92
|
if (followImports) {
|
|
91
|
-
|
|
93
|
+
const absPath = getPathWithExtension(v.path);
|
|
94
|
+
paths[absPath] = true;
|
|
92
95
|
}
|
|
93
96
|
} else {
|
|
94
97
|
v.source.expressions.forEach((expr) => add(expr, true));
|
package/dist/parser/parse.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/parser/parse.js"],"names":["listExternalReferences","file","paths","add","v","followImports","type","path","source","expressions","forEach","expr","Object","keys","exports","k","locals","operations","op","processFile","filePath","contents","dir","dirname","result","errors","resolved","resolvedPath","text","plugins","match","endsWith","filter","Boolean","enums","ast","sourceType","allowImportExportEverywhere","gqlTagNames","seenTemplates","program","body","toplevel","newLocals","getLocals","local","startsWith","name","push","importPath","value","resolve","join","specifiers","spec","exported","loc","start","end","line","processDeclarator","decl","isExported","id","init","tag","includes","tpl","processTemplate","document","declarations","declaration","visitTpl","node","getBinding","TaggedTemplateExpression","binding","scope","getTemplate","literals","quasi","quasis","map","q","cooked","message","found","myPath","importKind","imported","processFiles","filePaths","getFileSource","files","toProcess","slice","length","next","shift"],"mappings":";;;;;;;AAQA;;AACA;;AAEA;;;;AAHqC;AACG;;AAoExC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMA,sBAAsB,GAAIC,IAAD,IAAqC;AAChE,QAA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C,KAAY,GAAG,EAArB;AACA,QAAMC,SAAS,GAAGH,SAAS,CAACI,KAAV,EAAlB;;AACA,SAAOD,SAAS,CAACE,MAAjB,EAAyB;AACrB,UAAMC,IAAI,GAAGH,SAAS,CAACI,KAAV,EAAb;;AACA,QAAIL,KAAK,CAACI,IAAD,CAAT,EAAiB;AACb;AACH;;AACD,UAAMzE,MAAM,GAAGL,WAAW,CAAC8E,IAAD,EAAOL,aAAa,CAACK,IAAD,CAApB,CAA1B;AACAJ,IAAAA,KAAK,CAACI,IAAD,CAAL,GAAczE,MAAd;AACAxB,IAAAA,sBAAsB,CAACwB,MAAD,CAAtB,CAA+Bd,OAA/B,CAAwCH,IAAD,IAAU;AAC7C,UAAI,CAACsF,KAAK,CAACtF,IAAD,CAAN,IAAgB,CAACuF,SAAS,CAAC5B,QAAV,CAAmB3D,IAAnB,CAArB,EAA+C;AAC3CuF,QAAAA,SAAS,CAAC9C,IAAV,CAAezC,IAAf;AACH;AACJ,KAJD;AAKH;;AACD,SAAOsF,KAAP;AACH,CAtBM","sourcesContent":["// @flow\nimport type {\n BabelNodeImportDeclaration,\n BabelNodeVariableDeclarator,\n BabelNodeTaggedTemplateExpression,\n BabelNodeFile,\n} from '@babel/types';\n\nimport {parse} from '@babel/parser'; // eslint-disable-line flowtype-errors/uncovered\nimport traverse from '@babel/traverse'; // eslint-disable-line flowtype-errors/uncovered\n\nimport path from 'path';\n\n/**\n * This file is responsible for finding all gql`-annotated\n * template strings in a set of provided files, and for resolving\n * all fragment references to their eventual sources.\n *\n * Things that are supported:\n * - importing fragments from other files\n * - re-exporting fragments that were imported\n * - using locally-defined fragments, even if they're\n * not at the top level (scope is honored correctly)\n * - importing the gql tag as some other name\n * \t (e.g. 'import blah from \"graphql-tag\"')\n * - renaming fragments at the top level\n *\n * Things that are *not* supported:\n * - doing anything other than 'const x = gql`my template`'\n * \t e.g. const x = someCond ? one fragment literal : another fragment literal\n * or const x = someFragmentPreprocessor(fragment literal)\n * - importing the graphql tag fn from anywhere other than \"graphql-tag\"\n * - anything else fancy with the graphql tag fn, e.g. 'const blah = gql; blah`xyz`'\n * - including a fragment in an operation by anything other than a bare identifier,\n * e.g. 'const myQuery = gql`query xyz {...} ${cond ? someFrag : otherFrag}`.\n * - getting fragments from e.g. function arguments, or renaming non-toplevel fragments\n *\n * Things that could be supported, but are not yet:\n * - tracking whether a given graphql operation has already been wrapped\n * in `gqlOp<Type>()` or not (to inform an auto-wrapper of the future)\n */\n\nexport type Template = {|\n literals: Array<string>,\n expressions: Array<Document | Import>,\n loc: Loc,\n|};\nexport type Loc = {start: number, end: number, path: string, line: number};\n\nexport type Document = {|\n type: 'document',\n source: Template,\n|};\nexport type Import = {|\n type: 'import',\n name: string,\n path: string,\n loc: Loc,\n|};\n\nexport type Operation = {|\n source: Template,\n // TODO: Determine if an operation is already wrapped\n // in `gqlOp` so we can automatically wrap if needed.\n // needsWrapping: boolean,\n|};\n\nexport type FileResult = {|\n path: string,\n operations: Array<Operation>,\n exports: {[key: string]: Document | Import},\n locals: {[key: string]: Document | Import},\n errors: Array<{loc: Loc, message: string}>,\n|};\n\nexport type Files = {[path: string]: FileResult};\n\n/**\n * Finds all referenced imports that might possibly be relevant\n * graphql fragments.\n *\n * Importantly, any values that are re-exported are treated as\n * potentially relevant, and of course any values referenced\n * from a graphql template are treated as relevant.\n */\nconst listExternalReferences = (file: FileResult): Array<string> => {\n const paths = {};\n const add = (v: Document | Import, followImports: boolean) => {\n if (v.type === 'import') {\n if (followImports) {\n paths[v.path] = true;\n }\n } else {\n v.source.expressions.forEach((expr) => add(expr, true));\n }\n };\n Object.keys(file.exports).forEach((k) =>\n add(\n file.exports[k],\n // If we're re-exporting something, we need to follow that import.\n true,\n ),\n );\n Object.keys(file.locals).forEach((k) =>\n add(\n file.locals[k],\n // If we've imported something but haven't used it or exported it,\n // we don't need to follow the import.\n false,\n ),\n );\n file.operations.forEach((op) =>\n op.source.expressions.forEach((expr) =>\n add(\n expr,\n // Imports that are used in graphql expressions definitely need to be followed.\n true,\n ),\n ),\n );\n return Object.keys(paths);\n};\n\nexport const processFile = (\n filePath: string,\n contents: string | {text: string, resolvedPath: string},\n): FileResult => {\n const dir = path.dirname(filePath);\n const result: FileResult = {\n path: filePath,\n operations: [],\n exports: {},\n locals: {},\n errors: [],\n };\n const resolved =\n typeof contents === 'string' ? filePath : contents.resolvedPath;\n const text = typeof contents === 'string' ? contents : contents.text;\n const plugins = resolved.match(/\\.tsx?$/)\n ? ['typescript', filePath.endsWith('x') ? 'jsx' : null].filter(Boolean)\n : [['flow', {enums: true}], 'jsx'];\n /* eslint-disable flowtype-errors/uncovered */\n const ast: BabelNodeFile = parse(text, {\n sourceType: 'module',\n allowImportExportEverywhere: true,\n plugins: plugins,\n });\n /* eslint-enable flowtype-errors/uncovered */\n const gqlTagNames = [];\n const seenTemplates: {[key: number]: Document | false} = {};\n\n ast.program.body.forEach((toplevel) => {\n if (toplevel.type === 'ImportDeclaration') {\n const newLocals = getLocals(dir, toplevel, filePath);\n if (newLocals) {\n Object.keys(newLocals).forEach((k) => {\n const local = newLocals[k];\n if (local.path.startsWith('/')) {\n result.locals[k] = local;\n }\n if (\n local.path === 'graphql-tag' &&\n local.name === 'default'\n ) {\n gqlTagNames.push(k);\n }\n });\n }\n }\n if (toplevel.type === 'ExportNamedDeclaration') {\n if (toplevel.source) {\n const source = toplevel.source;\n const importPath = source.value.startsWith('.')\n ? path.resolve(path.join(dir, source.value))\n : source.value;\n toplevel.specifiers?.forEach((spec) => {\n if (\n spec.type === 'ExportSpecifier' &&\n spec.exported.type === 'Identifier'\n ) {\n result.exports[spec.exported.name] = {\n type: 'import',\n name: spec.local.name,\n path: importPath,\n loc: {\n start: spec.start ?? -1,\n end: spec.end ?? -1,\n line: spec.loc?.start.line ?? -1,\n path: filePath,\n },\n };\n }\n });\n } else {\n toplevel.specifiers?.forEach((spec) => {\n if (spec.type === 'ExportSpecifier') {\n const local = result.locals[spec.local.name];\n if (local && spec.exported.type === 'Identifier') {\n result.exports[spec.exported.name] = local;\n }\n }\n });\n }\n }\n\n const processDeclarator = (\n decl: BabelNodeVariableDeclarator,\n isExported: boolean,\n ) => {\n if (decl.id.type !== 'Identifier' || !decl.init) {\n return;\n }\n const {init} = decl;\n const id = decl.id.name;\n if (\n init.type === 'TaggedTemplateExpression' &&\n init.tag.type === 'Identifier'\n ) {\n if (gqlTagNames.includes(init.tag.name)) {\n const tpl = processTemplate(init, result);\n if (tpl) {\n const document = (result.locals[id] = {\n type: 'document',\n source: tpl,\n });\n seenTemplates[init.start ?? -1] = document;\n if (isExported) {\n result.exports[id] = document;\n }\n } else {\n seenTemplates[init.start ?? -1] = false;\n }\n }\n }\n if (init.type === 'Identifier' && result.locals[init.name]) {\n result.locals[id] = result.locals[init.name];\n if (isExported) {\n result.exports[id] = result.locals[init.name];\n }\n }\n };\n\n if (toplevel.type === 'VariableDeclaration') {\n toplevel.declarations.forEach((decl) => {\n processDeclarator(decl, false);\n });\n }\n\n if (\n toplevel.type === 'ExportNamedDeclaration' &&\n toplevel.declaration?.type === 'VariableDeclaration'\n ) {\n toplevel.declaration.declarations.forEach((decl) => {\n processDeclarator(decl, true);\n });\n }\n });\n\n const visitTpl = (\n node: BabelNodeTaggedTemplateExpression,\n getBinding: (name: string) => Document | null,\n ) => {\n if (seenTemplates[node.start ?? -1] != null) {\n return;\n }\n if (\n node.tag.type !== 'Identifier' ||\n !gqlTagNames.includes(node.tag.name)\n ) {\n return;\n }\n const tpl = processTemplate(node, result, getBinding);\n if (tpl) {\n seenTemplates[node.start ?? -1] = {type: 'document', source: tpl};\n result.operations.push({\n source: tpl,\n });\n } else {\n seenTemplates[node.start ?? -1] = false;\n }\n };\n\n /* eslint-disable flowtype-errors/uncovered */\n traverse(ast, {\n TaggedTemplateExpression(path) {\n visitTpl(path.node, (name) => {\n const binding = path.scope.getBinding(name);\n const start = binding.path.node.init\n ? binding.path.node.init.start\n : null;\n if (start && seenTemplates[start]) {\n return seenTemplates[start];\n }\n return null;\n });\n },\n });\n /* eslint-enable flowtype-errors/uncovered */\n\n return result;\n};\n\nconst processTemplate = (\n tpl: BabelNodeTaggedTemplateExpression,\n result: FileResult,\n getTemplate?: (name: string) => Document | null,\n // getBinding?: (name: string) => Binding,\n // seenTemplates,\n): ?Template => {\n // 'cooked' is the string as runtime javascript will see it.\n const literals = tpl.quasi.quasis.map((q) => q.value.cooked || '');\n const expressions = tpl.quasi.expressions.map(\n (expr): null | Document | Import => {\n const loc: Loc = {\n start: expr.start ?? -1,\n end: expr.end ?? -1,\n line: expr.loc?.start.line ?? -1,\n path: result.path,\n };\n if (expr.type !== 'Identifier') {\n result.errors.push({\n loc,\n message: `Template literal interpolation must be an identifier`,\n });\n return null;\n }\n if (!result.locals[expr.name]) {\n if (getTemplate) {\n const found = getTemplate(expr.name);\n return found;\n }\n result.errors.push({\n loc,\n message: `Unable to resolve ${expr.name}`,\n });\n return null;\n }\n return result.locals[expr.name];\n },\n );\n if (expressions.includes(null)) {\n // bail, stop processing.\n return;\n }\n return {\n literals,\n expressions: expressions.filter(Boolean),\n loc: {\n line: tpl.loc?.start.line ?? -1,\n start: tpl.start ?? -1,\n end: tpl.end ?? -1,\n path: result.path,\n },\n };\n};\n\nconst getLocals = (\n dir,\n toplevel: BabelNodeImportDeclaration,\n myPath: string,\n): ?{[key: string]: Import} => {\n if (toplevel.importKind === 'type') {\n return null;\n }\n const importPath = toplevel.source.value.startsWith('.')\n ? path.resolve(path.join(dir, toplevel.source.value))\n : toplevel.source.value;\n const locals = {};\n toplevel.specifiers.forEach((spec) => {\n if (spec.type === 'ImportDefaultSpecifier') {\n locals[spec.local.name] = {\n type: 'import',\n name: 'default',\n path: importPath,\n loc: {start: spec.start, end: spec.end, path: myPath},\n };\n } else if (spec.type === 'ImportSpecifier') {\n locals[spec.local.name] = {\n type: 'import',\n name:\n spec.imported.type === 'Identifier'\n ? spec.imported.name\n : spec.imported.value,\n path: importPath,\n loc: {start: spec.start, end: spec.end, path: myPath},\n };\n }\n });\n return locals;\n};\n\nexport const processFiles = (\n filePaths: Array<string>,\n getFileSource: (\n path: string,\n ) => string | {text: string, resolvedPath: string},\n): Files => {\n const files: Files = {};\n const toProcess = filePaths.slice();\n while (toProcess.length) {\n const next = toProcess.shift();\n if (files[next]) {\n continue;\n }\n const result = processFile(next, getFileSource(next));\n files[next] = result;\n listExternalReferences(result).forEach((path) => {\n if (!files[path] && !toProcess.includes(path)) {\n toProcess.push(path);\n }\n });\n }\n return files;\n};\n"],"file":"parse.js"}
|
|
1
|
+
{"version":3,"sources":["../../src/parser/parse.js"],"names":["listExternalReferences","file","paths","add","v","followImports","type","absPath","path","source","expressions","forEach","expr","Object","keys","exports","k","locals","operations","op","processFile","filePath","contents","dir","dirname","result","errors","resolved","resolvedPath","text","plugins","match","endsWith","filter","Boolean","enums","ast","sourceType","allowImportExportEverywhere","gqlTagNames","seenTemplates","program","body","toplevel","newLocals","getLocals","local","startsWith","name","push","importPath","value","resolve","join","specifiers","spec","exported","loc","start","end","line","processDeclarator","decl","isExported","id","init","tag","includes","tpl","processTemplate","document","declarations","declaration","visitTpl","node","getBinding","TaggedTemplateExpression","binding","scope","getTemplate","literals","quasi","quasis","map","q","cooked","message","found","myPath","importKind","imported","processFiles","filePaths","getFileSource","files","toProcess","slice","length","next","shift"],"mappings":";;;;;;;AAQA;;AACA;;AAEA;;AAEA;;;;AALqC;AACG;;AAsExC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMA,sBAAsB,GAAIC,IAAD,IAAqC;AAChE,QAAMC,KAAK,GAAG,EAAd;;AACA,QAAMC,GAAG,GAAG,CAACC,CAAD,EAAuBC,aAAvB,KAAkD;AAC1D,QAAID,CAAC,CAACE,IAAF,KAAW,QAAf,EAAyB;AACrB,UAAID,aAAJ,EAAmB;AACf,cAAME,OAAO,GAAG,iCAAqBH,CAAC,CAACI,IAAvB,CAAhB;AACAN,QAAAA,KAAK,CAACK,OAAD,CAAL,GAAiB,IAAjB;AACH;AACJ,KALD,MA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L,WAAW,CAAC8E,IAAD,EAAOL,aAAa,CAACK,IAAD,CAApB,CAA1B;AACAJ,IAAAA,KAAK,CAACI,IAAD,CAAL,GAAczE,MAAd;AACAzB,IAAAA,sBAAsB,CAACyB,MAAD,CAAtB,CAA+Bd,OAA/B,CAAwCH,IAAD,IAAU;AAC7C,UAAI,CAACsF,KAAK,CAACtF,IAAD,CAAN,IAAgB,CAACuF,SAAS,CAAC5B,QAAV,CAAmB3D,IAAnB,CAArB,EAA+C;AAC3CuF,QAAAA,SAAS,CAAC9C,IAAV,CAAezC,IAAf;AACH;AACJ,KAJD;AAKH;;AACD,SAAOsF,KAAP;AACH,CAtBM","sourcesContent":["// @flow\nimport type {\n BabelNodeImportDeclaration,\n BabelNodeVariableDeclarator,\n BabelNodeTaggedTemplateExpression,\n BabelNodeFile,\n} from '@babel/types';\n\nimport {parse} from '@babel/parser'; // eslint-disable-line flowtype-errors/uncovered\nimport traverse from '@babel/traverse'; // eslint-disable-line flowtype-errors/uncovered\n\nimport path from 'path';\n\nimport {getPathWithExtension} from './utils';\n\n/**\n * This file is responsible for finding all gql`-annotated\n * template strings in a set of provided files, and for resolving\n * all fragment references to their eventual sources.\n *\n * Things that are supported:\n * - importing fragments from other files\n * - re-exporting fragments that were imported\n * - using locally-defined fragments, even if they're\n * not at the top level (scope is honored correctly)\n * - importing the gql tag as some other name\n * \t (e.g. 'import blah from \"graphql-tag\"')\n * - renaming fragments at the top level\n *\n * Things that are *not* supported:\n * - doing anything other than 'const x = gql`my template`'\n * \t e.g. const x = someCond ? one fragment literal : another fragment literal\n * or const x = someFragmentPreprocessor(fragment literal)\n * - importing the graphql tag fn from anywhere other than \"graphql-tag\"\n * - anything else fancy with the graphql tag fn, e.g. 'const blah = gql; blah`xyz`'\n * - including a fragment in an operation by anything other than a bare identifier,\n * e.g. 'const myQuery = gql`query xyz {...} ${cond ? someFrag : otherFrag}`.\n * - getting fragments from e.g. function arguments, or renaming non-toplevel fragments\n *\n * Things that could be supported, but are not yet:\n * - tracking whether a given graphql operation has already been wrapped\n * in `gqlOp<Type>()` or not (to inform an auto-wrapper of the future)\n */\n\nexport type Template = {|\n literals: Array<string>,\n expressions: Array<Document | Import>,\n loc: Loc,\n|};\nexport type Loc = {start: number, end: number, path: string, line: number};\n\nexport type Document = {|\n type: 'document',\n source: Template,\n|};\nexport type Import = {|\n type: 'import',\n name: string,\n path: string,\n loc: Loc,\n|};\n\nexport type Operation = {|\n source: Template,\n // TODO: Determine if an operation is already wrapped\n // in `gqlOp` so we can automatically wrap if needed.\n // needsWrapping: boolean,\n|};\n\nexport type FileResult = {|\n path: string,\n operations: Array<Operation>,\n exports: {[key: string]: Document | Import},\n locals: {[key: string]: Document | Import},\n errors: Array<{loc: Loc, message: string}>,\n|};\n\nexport type Files = {[path: string]: FileResult};\n\n/**\n * Finds all referenced imports that might possibly be relevant\n * graphql fragments.\n *\n * Importantly, any values that are re-exported are treated as\n * potentially relevant, and of course any values referenced\n * from a graphql template are treated as relevant.\n */\nconst listExternalReferences = (file: FileResult): Array<string> => {\n const paths = {};\n const add = (v: Document | Import, followImports: boolean) => {\n if (v.type === 'import') {\n if (followImports) {\n const absPath = getPathWithExtension(v.path);\n paths[absPath] = true;\n }\n } else {\n v.source.expressions.forEach((expr) => add(expr, true));\n }\n };\n Object.keys(file.exports).forEach((k) =>\n add(\n file.exports[k],\n // If we're re-exporting something, we need to follow that import.\n true,\n ),\n );\n Object.keys(file.locals).forEach((k) =>\n add(\n file.locals[k],\n // If we've imported something but haven't used it or exported it,\n // we don't need to follow the import.\n false,\n ),\n );\n file.operations.forEach((op) =>\n op.source.expressions.forEach((expr) =>\n add(\n expr,\n // Imports that are used in graphql expressions definitely need to be followed.\n true,\n ),\n ),\n );\n return Object.keys(paths);\n};\n\nexport const processFile = (\n filePath: string,\n contents: string | {text: string, resolvedPath: string},\n): FileResult => {\n const dir = path.dirname(filePath);\n const result: FileResult = {\n path: filePath,\n operations: [],\n exports: {},\n locals: {},\n errors: [],\n };\n const resolved =\n typeof contents === 'string' ? filePath : contents.resolvedPath;\n const text = typeof contents === 'string' ? contents : contents.text;\n const plugins = resolved.match(/\\.tsx?$/)\n ? ['typescript', filePath.endsWith('x') ? 'jsx' : null].filter(Boolean)\n : [['flow', {enums: true}], 'jsx'];\n /* eslint-disable flowtype-errors/uncovered */\n const ast: BabelNodeFile = parse(text, {\n sourceType: 'module',\n allowImportExportEverywhere: true,\n plugins: plugins,\n });\n /* eslint-enable flowtype-errors/uncovered */\n const gqlTagNames = [];\n const seenTemplates: {[key: number]: Document | false} = {};\n\n ast.program.body.forEach((toplevel) => {\n if (toplevel.type === 'ImportDeclaration') {\n const newLocals = getLocals(dir, toplevel, filePath);\n if (newLocals) {\n Object.keys(newLocals).forEach((k) => {\n const local = newLocals[k];\n if (local.path.startsWith('/')) {\n result.locals[k] = local;\n }\n if (\n local.path === 'graphql-tag' &&\n local.name === 'default'\n ) {\n gqlTagNames.push(k);\n }\n });\n }\n }\n if (toplevel.type === 'ExportNamedDeclaration') {\n if (toplevel.source) {\n const source = toplevel.source;\n const importPath = source.value.startsWith('.')\n ? path.resolve(path.join(dir, source.value))\n : source.value;\n toplevel.specifiers?.forEach((spec) => {\n if (\n spec.type === 'ExportSpecifier' &&\n spec.exported.type === 'Identifier'\n ) {\n result.exports[spec.exported.name] = {\n type: 'import',\n name: spec.local.name,\n path: importPath,\n loc: {\n start: spec.start ?? -1,\n end: spec.end ?? -1,\n line: spec.loc?.start.line ?? -1,\n path: filePath,\n },\n };\n }\n });\n } else {\n toplevel.specifiers?.forEach((spec) => {\n if (spec.type === 'ExportSpecifier') {\n const local = result.locals[spec.local.name];\n if (local && spec.exported.type === 'Identifier') {\n result.exports[spec.exported.name] = local;\n }\n }\n });\n }\n }\n\n const processDeclarator = (\n decl: BabelNodeVariableDeclarator,\n isExported: boolean,\n ) => {\n if (decl.id.type !== 'Identifier' || !decl.init) {\n return;\n }\n const {init} = decl;\n const id = decl.id.name;\n if (\n init.type === 'TaggedTemplateExpression' &&\n init.tag.type === 'Identifier'\n ) {\n if (gqlTagNames.includes(init.tag.name)) {\n const tpl = processTemplate(init, result);\n if (tpl) {\n const document = (result.locals[id] = {\n type: 'document',\n source: tpl,\n });\n seenTemplates[init.start ?? -1] = document;\n if (isExported) {\n result.exports[id] = document;\n }\n } else {\n seenTemplates[init.start ?? -1] = false;\n }\n }\n }\n if (init.type === 'Identifier' && result.locals[init.name]) {\n result.locals[id] = result.locals[init.name];\n if (isExported) {\n result.exports[id] = result.locals[init.name];\n }\n }\n };\n\n if (toplevel.type === 'VariableDeclaration') {\n toplevel.declarations.forEach((decl) => {\n processDeclarator(decl, false);\n });\n }\n\n if (\n toplevel.type === 'ExportNamedDeclaration' &&\n toplevel.declaration?.type === 'VariableDeclaration'\n ) {\n toplevel.declaration.declarations.forEach((decl) => {\n processDeclarator(decl, true);\n });\n }\n });\n\n const visitTpl = (\n node: BabelNodeTaggedTemplateExpression,\n getBinding: (name: string) => Document | null,\n ) => {\n if (seenTemplates[node.start ?? -1] != null) {\n return;\n }\n if (\n node.tag.type !== 'Identifier' ||\n !gqlTagNames.includes(node.tag.name)\n ) {\n return;\n }\n const tpl = processTemplate(node, result, getBinding);\n if (tpl) {\n seenTemplates[node.start ?? -1] = {type: 'document', source: tpl};\n result.operations.push({\n source: tpl,\n });\n } else {\n seenTemplates[node.start ?? -1] = false;\n }\n };\n\n /* eslint-disable flowtype-errors/uncovered */\n traverse(ast, {\n TaggedTemplateExpression(path) {\n visitTpl(path.node, (name) => {\n const binding = path.scope.getBinding(name);\n const start = binding.path.node.init\n ? binding.path.node.init.start\n : null;\n if (start && seenTemplates[start]) {\n return seenTemplates[start];\n }\n return null;\n });\n },\n });\n /* eslint-enable flowtype-errors/uncovered */\n\n return result;\n};\n\nconst processTemplate = (\n tpl: BabelNodeTaggedTemplateExpression,\n result: FileResult,\n getTemplate?: (name: string) => Document | null,\n // getBinding?: (name: string) => Binding,\n // seenTemplates,\n): ?Template => {\n // 'cooked' is the string as runtime javascript will see it.\n const literals = tpl.quasi.quasis.map((q) => q.value.cooked || '');\n const expressions = tpl.quasi.expressions.map(\n (expr): null | Document | Import => {\n const loc: Loc = {\n start: expr.start ?? -1,\n end: expr.end ?? -1,\n line: expr.loc?.start.line ?? -1,\n path: result.path,\n };\n if (expr.type !== 'Identifier') {\n result.errors.push({\n loc,\n message: `Template literal interpolation must be an identifier`,\n });\n return null;\n }\n if (!result.locals[expr.name]) {\n if (getTemplate) {\n const found = getTemplate(expr.name);\n return found;\n }\n result.errors.push({\n loc,\n message: `Unable to resolve ${expr.name}`,\n });\n return null;\n }\n return result.locals[expr.name];\n },\n );\n if (expressions.includes(null)) {\n // bail, stop processing.\n return;\n }\n return {\n literals,\n expressions: expressions.filter(Boolean),\n loc: {\n line: tpl.loc?.start.line ?? -1,\n start: tpl.start ?? -1,\n end: tpl.end ?? -1,\n path: result.path,\n },\n };\n};\n\nconst getLocals = (\n dir,\n toplevel: BabelNodeImportDeclaration,\n myPath: string,\n): ?{[key: string]: Import} => {\n if (toplevel.importKind === 'type') {\n return null;\n }\n const importPath = toplevel.source.value.startsWith('.')\n ? path.resolve(path.join(dir, toplevel.source.value))\n : toplevel.source.value;\n const locals = {};\n toplevel.specifiers.forEach((spec) => {\n if (spec.type === 'ImportDefaultSpecifier') {\n locals[spec.local.name] = {\n type: 'import',\n name: 'default',\n path: importPath,\n loc: {start: spec.start, end: spec.end, path: myPath},\n };\n } else if (spec.type === 'ImportSpecifier') {\n locals[spec.local.name] = {\n type: 'import',\n name:\n spec.imported.type === 'Identifier'\n ? spec.imported.name\n : spec.imported.value,\n path: importPath,\n loc: {start: spec.start, end: spec.end, path: myPath},\n };\n }\n });\n return locals;\n};\n\nexport const processFiles = (\n filePaths: Array<string>,\n getFileSource: (\n path: string,\n ) => string | {text: string, resolvedPath: string},\n): Files => {\n const files: Files = {};\n const toProcess = filePaths.slice();\n while (toProcess.length) {\n const next = toProcess.shift();\n if (files[next]) {\n continue;\n }\n const result = processFile(next, getFileSource(next));\n files[next] = result;\n listExternalReferences(result).forEach((path) => {\n if (!files[path] && !toProcess.includes(path)) {\n toProcess.push(path);\n }\n });\n }\n return files;\n};\n"],"file":"parse.js"}
|
package/dist/parser/resolve.js
CHANGED
|
@@ -7,6 +7,8 @@ exports.resolveDocuments = void 0;
|
|
|
7
7
|
|
|
8
8
|
var _graphqlTag = _interopRequireDefault(require("graphql-tag"));
|
|
9
9
|
|
|
10
|
+
var _utils = require("./utils");
|
|
11
|
+
|
|
10
12
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
11
13
|
|
|
12
14
|
const resolveDocuments = files => {
|
|
@@ -34,21 +36,23 @@ const resolveDocuments = files => {
|
|
|
34
36
|
exports.resolveDocuments = resolveDocuments;
|
|
35
37
|
|
|
36
38
|
const resolveImport = (expr, files, errors, seen) => {
|
|
37
|
-
|
|
39
|
+
const absPath = (0, _utils.getPathWithExtension)(expr.path);
|
|
40
|
+
|
|
41
|
+
if (seen[absPath]) {
|
|
38
42
|
errors.push({
|
|
39
43
|
loc: expr.loc,
|
|
40
|
-
message: `Circular import ${Object.keys(seen).join(' -> ')} -> ${
|
|
44
|
+
message: `Circular import ${Object.keys(seen).join(' -> ')} -> ${absPath}`
|
|
41
45
|
});
|
|
42
46
|
return null;
|
|
43
47
|
}
|
|
44
48
|
|
|
45
|
-
seen[
|
|
46
|
-
const res = files[
|
|
49
|
+
seen[absPath] = true;
|
|
50
|
+
const res = files[absPath];
|
|
47
51
|
|
|
48
52
|
if (!res) {
|
|
49
53
|
errors.push({
|
|
50
54
|
loc: expr.loc,
|
|
51
|
-
message: `No file ${
|
|
55
|
+
message: `No file ${absPath}`
|
|
52
56
|
});
|
|
53
57
|
return null;
|
|
54
58
|
}
|
|
@@ -56,7 +60,7 @@ const resolveImport = (expr, files, errors, seen) => {
|
|
|
56
60
|
if (!res.exports[expr.name]) {
|
|
57
61
|
errors.push({
|
|
58
62
|
loc: expr.loc,
|
|
59
|
-
message: `${
|
|
63
|
+
message: `${absPath} has no valid gql export ${expr.name}`
|
|
60
64
|
});
|
|
61
65
|
return null;
|
|
62
66
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// @flow
|
|
2
2
|
import gql from 'graphql-tag';
|
|
3
|
+
import {getPathWithExtension} from './utils';
|
|
3
4
|
import type {DocumentNode} from 'graphql/language/ast';
|
|
4
5
|
import type {FileResult, Files, Import, Template, Document} from './parse';
|
|
5
6
|
|
|
@@ -36,25 +37,26 @@ const resolveImport = (
|
|
|
36
37
|
errors: FileResult['errors'],
|
|
37
38
|
seen: {[key: string]: true},
|
|
38
39
|
): ?Document => {
|
|
39
|
-
|
|
40
|
+
const absPath: string = getPathWithExtension(expr.path);
|
|
41
|
+
if (seen[absPath]) {
|
|
40
42
|
errors.push({
|
|
41
43
|
loc: expr.loc,
|
|
42
|
-
message: `Circular import ${Object.keys(seen).join(
|
|
43
|
-
|
|
44
|
-
}`,
|
|
44
|
+
message: `Circular import ${Object.keys(seen).join(
|
|
45
|
+
' -> ',
|
|
46
|
+
)} -> ${absPath}`,
|
|
45
47
|
});
|
|
46
48
|
return null;
|
|
47
49
|
}
|
|
48
|
-
seen[
|
|
49
|
-
const res = files[
|
|
50
|
+
seen[absPath] = true;
|
|
51
|
+
const res = files[absPath];
|
|
50
52
|
if (!res) {
|
|
51
|
-
errors.push({loc: expr.loc, message: `No file ${
|
|
53
|
+
errors.push({loc: expr.loc, message: `No file ${absPath}`});
|
|
52
54
|
return null;
|
|
53
55
|
}
|
|
54
56
|
if (!res.exports[expr.name]) {
|
|
55
57
|
errors.push({
|
|
56
58
|
loc: expr.loc,
|
|
57
|
-
message: `${
|
|
59
|
+
message: `${absPath} has no valid gql export ${expr.name}`,
|
|
58
60
|
});
|
|
59
61
|
return null;
|
|
60
62
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/parser/resolve.js"],"names":["resolveDocuments","files","resolved","errors","Object","keys","forEach","path","file","operations","op","resolveGqlTemplate","source","locals","k","local","type","resolveImport","expr","seen","push","loc","message","join","res","exports","name","value","template","key","line","map","expressions","length","literals","document","includes","raw"],"mappings":";;;;;;;AACA;;;;AAWO,MAAMA,gBAAgB,GACzBC,KAD4B,IAEyB;AACrD,QAAMC,QAAkB,GAAG,EAA3B;AACA,QAAMC,MAA4B,GAAG,EAArC;AACAC,EAAAA,MAAM,CAACC,IAAP,CAAYJ,KAAZ,EAAmBK,OAAnB,CAA4BC,IAAD,IAAU;AACjC,UAAMC,IAAI,GAAGP,KAAK,CAACM,IAAD,CAAlB;AACAC,IAAAA,IAAI,CAACC,UAAL,CAAgBH,OAAhB,CAAyBI,EAAD,IAAQ;AAC5BC,MAAAA,kBAAkB,CAACD,EAAE,CAACE,MAAJ,EAAYX,KAAZ,EAAmBE,MAAnB,EAA2BD,QAA3B,EAAqC,EAArC,CAAlB;AACH,KAFD;AAGAE,IAAAA,MAAM,CAACC,IAAP,CAAYG,IAAI,CAACK,MAAjB,EAAyBP,OAAzB,CAAkCQ,CAAD,IAAO;AACpC,YAAMC,KAAK,GAAGP,IAAI,CAACK,MAAL,CAAYC,CAAZ,CAAd;;AACA,UAAIC,KAAK,CAACC,IAAN,KAAe,UAAnB,EAA+B;AAC3BL,QAAAA,kBAAkB,CAACI,KAAK,CAACH,MAAP,EAAeX,KAAf,EAAsBE,MAAtB,EAA8BD,QAA9B,EAAwC,EAAxC,CAAlB;AACH;AACJ,KALD;AAMH,GAXD;AAYA,SAAO;AAACA,IAAAA,QAAD;AAAWC,IAAAA;AAAX,GAAP;AACH,CAlBM;;;;AAoBP,MAAMc,aAAa,GAAG,CAClBC,IADkB,EAElBjB,KAFkB,EAGlBE,MAHkB,EAIlBgB,IAJkB,KAKN;AACZ,
|
|
1
|
+
{"version":3,"sources":["../../src/parser/resolve.js"],"names":["resolveDocuments","files","resolved","errors","Object","keys","forEach","path","file","operations","op","resolveGqlTemplate","source","locals","k","local","type","resolveImport","expr","seen","absPath","push","loc","message","join","res","exports","name","value","template","key","line","map","expressions","length","literals","document","includes","raw"],"mappings":";;;;;;;AACA;;AACA;;;;AAWO,MAAMA,gBAAgB,GACzBC,KAD4B,IAEyB;AACrD,QAAMC,QAAkB,GAAG,EAA3B;AACA,QAAMC,MAA4B,GAAG,EAArC;AACAC,EAAAA,MAAM,CAACC,IAAP,CAAYJ,KAAZ,EAAmBK,OAAnB,CAA4BC,IAAD,IAAU;AACjC,UAAMC,IAAI,GAAGP,KAAK,CAACM,IAAD,CAAlB;AACAC,IAAAA,IAAI,CAACC,UAAL,CAAgBH,OAAhB,CAAyBI,EAAD,IAAQ;AAC5BC,MAAAA,kBAAkB,CAACD,EAAE,CAACE,MAAJ,EAAYX,KAAZ,EAAmBE,MAAnB,EAA2BD,QAA3B,EAAqC,EAArC,CAAlB;AACH,KAFD;AAGAE,IAAAA,MAAM,CAACC,IAAP,CAAYG,IAAI,CAACK,MAAjB,EAAyBP,OAAzB,CAAkCQ,CAAD,IAAO;AACpC,YAAMC,KAAK,GAAGP,IAAI,CAACK,MAAL,CAAYC,CAAZ,CAAd;;AACA,UAAIC,KAAK,CAACC,IAAN,KAAe,UAAnB,EAA+B;AAC3BL,QAAAA,kBAAkB,CAACI,KAAK,CAACH,MAAP,EAAeX,KAAf,EAAsBE,MAAtB,EAA8BD,QAA9B,EAAwC,EAAxC,CAAlB;AACH;AACJ,KALD;AAMH,GAXD;AAYA,SAAO;AAACA,IAAAA,QAAD;AAAWC,IAAAA;AAAX,GAAP;AACH,CAlBM;;;;AAoBP,MAAMc,aAAa,GAAG,CAClBC,IADkB,EAElBjB,KAFkB,EAGlBE,MAHkB,EAIlBgB,IAJkB,KAKN;AACZ,QAAMC,OAAe,GAAG,iCAAqBF,IAAI,CAACX,IAA1B,CAAxB;;AACA,MAAIY,IAAI,CAACC,OAAD,CAAR,EAAmB;AACfjB,IAAAA,MAAM,CAACkB,IAAP,CAAY;AACRC,MAAAA,GAAG,EAAEJ,IAAI,CAACI,GADF;AAERC,MAAA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C,EAAAA,QAAQ,CAAC4B,GAAD,CAAR,GAAgB;AACZM,IAAAA,QAAQ,EAAE,yBAAIP,QAAQ,CAACM,QAAb,EAAuB,GAAGF,WAA1B,CADE;AAEZK,IAAAA,GAAG,EAAET;AAFO,GAAhB;AAIA,SAAO3B,QAAQ,CAAC4B,GAAD,CAAR,CAAcM,QAArB;AACH,CAjDD","sourcesContent":["// @flow\nimport gql from 'graphql-tag';\nimport {getPathWithExtension} from './utils';\nimport type {DocumentNode} from 'graphql/language/ast';\nimport type {FileResult, Files, Import, Template, Document} from './parse';\n\nexport type Resolved = {\n [key: string]: {\n document: DocumentNode,\n raw: Template,\n },\n};\n\nexport const resolveDocuments = (\n files: Files,\n): {resolved: Resolved, errors: FileResult['errors']} => {\n const resolved: Resolved = {};\n const errors: FileResult['errors'] = [];\n Object.keys(files).forEach((path) => {\n const file = files[path];\n file.operations.forEach((op) => {\n resolveGqlTemplate(op.source, files, errors, resolved, {});\n });\n Object.keys(file.locals).forEach((k) => {\n const local = file.locals[k];\n if (local.type === 'document') {\n resolveGqlTemplate(local.source, files, errors, resolved, {});\n }\n });\n });\n return {resolved, errors};\n};\n\nconst resolveImport = (\n expr: Import,\n files: Files,\n errors: FileResult['errors'],\n seen: {[key: string]: true},\n): ?Document => {\n const absPath: string = getPathWithExtension(expr.path);\n if (seen[absPath]) {\n errors.push({\n loc: expr.loc,\n message: `Circular import ${Object.keys(seen).join(\n ' -> ',\n )} -> ${absPath}`,\n });\n return null;\n }\n seen[absPath] = true;\n const res = files[absPath];\n if (!res) {\n errors.push({loc: expr.loc, message: `No file ${absPath}`});\n return null;\n }\n if (!res.exports[expr.name]) {\n errors.push({\n loc: expr.loc,\n message: `${absPath} has no valid gql export ${expr.name}`,\n });\n return null;\n }\n const value = res.exports[expr.name];\n if (value.type === 'import') {\n return resolveImport(value, files, errors, seen);\n }\n return value;\n};\n\nconst resolveGqlTemplate = (\n template: Template,\n files: Files,\n errors: FileResult['errors'],\n resolved: Resolved,\n seen: {[key: string]: Template},\n): ?DocumentNode => {\n const key = template.loc.path + ':' + template.loc.line;\n if (seen[key]) {\n errors.push({\n loc: template.loc,\n message: `Recursive template dependency! ${Object.keys(seen)\n .map(\n (k) =>\n k +\n ' ~ ' +\n seen[k].expressions.length +\n ',' +\n seen[k].literals.length,\n )\n .join(' -> ')} -> ${key}`,\n });\n return null;\n }\n seen[key] = template;\n if (resolved[key]) {\n return resolved[key].document;\n }\n const expressions = template.expressions.map((expr) => {\n if (expr.type === 'import') {\n const document = resolveImport(expr, files, errors, {});\n return document\n ? resolveGqlTemplate(document.source, files, errors, resolved, {\n ...seen,\n })\n : null;\n }\n return resolveGqlTemplate(expr.source, files, errors, resolved, {\n ...seen,\n });\n });\n if (expressions.includes(null)) {\n return null;\n }\n resolved[key] = {\n document: gql(template.literals, ...expressions),\n raw: template,\n };\n return resolved[key].document;\n};\n"],"file":"resolve.js"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.getPathWithExtension = void 0;
|
|
7
|
+
|
|
8
|
+
var _fs = _interopRequireDefault(require("fs"));
|
|
9
|
+
|
|
10
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
11
|
+
|
|
12
|
+
const getPathWithExtension = pathWithoutExtension => {
|
|
13
|
+
if (/\.(less|css|png|gif|jpg|jpeg|js|jsx|ts|tsx|mjs)$/.test(pathWithoutExtension)) {
|
|
14
|
+
return pathWithoutExtension;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
if (_fs.default.existsSync(pathWithoutExtension + '.js')) {
|
|
18
|
+
return pathWithoutExtension + '.js';
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
if (_fs.default.existsSync(pathWithoutExtension + '.jsx')) {
|
|
22
|
+
return pathWithoutExtension + '.jsx';
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (_fs.default.existsSync(pathWithoutExtension + '.tsx')) {
|
|
26
|
+
return pathWithoutExtension + '.tsx';
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
if (_fs.default.existsSync(pathWithoutExtension + '.ts')) {
|
|
30
|
+
return pathWithoutExtension + '.ts';
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
throw new Error("Can't find file at " + pathWithoutExtension);
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
exports.getPathWithExtension = getPathWithExtension;
|
|
37
|
+
//# sourceMappingURL=utils.js.map
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// @flow
|
|
2
|
+
import fs from 'fs';
|
|
3
|
+
|
|
4
|
+
export const getPathWithExtension = (pathWithoutExtension: string): string => {
|
|
5
|
+
if (
|
|
6
|
+
/\.(less|css|png|gif|jpg|jpeg|js|jsx|ts|tsx|mjs)$/.test(
|
|
7
|
+
pathWithoutExtension,
|
|
8
|
+
)
|
|
9
|
+
) {
|
|
10
|
+
return pathWithoutExtension;
|
|
11
|
+
}
|
|
12
|
+
if (fs.existsSync(pathWithoutExtension + '.js')) {
|
|
13
|
+
return pathWithoutExtension + '.js';
|
|
14
|
+
}
|
|
15
|
+
if (fs.existsSync(pathWithoutExtension + '.jsx')) {
|
|
16
|
+
return pathWithoutExtension + '.jsx';
|
|
17
|
+
}
|
|
18
|
+
if (fs.existsSync(pathWithoutExtension + '.tsx')) {
|
|
19
|
+
return pathWithoutExtension + '.tsx';
|
|
20
|
+
}
|
|
21
|
+
if (fs.existsSync(pathWithoutExtension + '.ts')) {
|
|
22
|
+
return pathWithoutExtension + '.ts';
|
|
23
|
+
}
|
|
24
|
+
throw new Error("Can't find file at " + pathWithoutExtension);
|
|
25
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/parser/utils.js"],"names":["getPathWithExtension","pathWithoutExtension","test","fs","existsSync","Error"],"mappings":";;;;;;;AACA;;;;AAEO,MAAMA,oBAAoB,GAAIC,oBAAD,IAA0C;AAC1E,MACI,mDAAmDC,IAAnD,CACID,oBADJ,CADJ,EAIE;AACE,WAAOA,oBAAP;AACH;;AACD,MAAIE,YAAGC,UAAH,CAAcH,oBAAoB,GAAG,KAArC,CAAJ,EAAiD;AAC7C,WAAOA,oBAAoB,GAAG,KAA9B;AACH;;AACD,MAAIE,YAAGC,UAAH,CAAcH,oBAAoB,GAAG,MAArC,CAAJ,EAAkD;AAC9C,WAAOA,oBAAoB,GAAG,MAA9B;AACH;;AACD,MAAIE,YAAGC,UAAH,CAAcH,oBAAoB,GAAG,MAArC,CAAJ,EAAkD;AAC9C,WAAOA,oBAAoB,GAAG,MAA9B;AACH;;AACD,MAAIE,YAAGC,UAAH,CAAcH,oBAAoB,GAAG,KAArC,CAAJ,EAAiD;AAC7C,WAAOA,oBAAoB,GAAG,KAA9B;AACH;;AACD,QAAM,IAAII,KAAJ,CAAU,wBAAwBJ,oBAAlC,CAAN;AACH,CArBM","sourcesContent":["// @flow\nimport fs from 'fs';\n\nexport const getPathWithExtension = (pathWithoutExtension: string): string => {\n if (\n /\\.(less|css|png|gif|jpg|jpeg|js|jsx|ts|tsx|mjs)$/.test(\n pathWithoutExtension,\n )\n ) {\n return pathWithoutExtension;\n }\n if (fs.existsSync(pathWithoutExtension + '.js')) {\n return pathWithoutExtension + '.js';\n }\n if (fs.existsSync(pathWithoutExtension + '.jsx')) {\n return pathWithoutExtension + '.jsx';\n }\n if (fs.existsSync(pathWithoutExtension + '.tsx')) {\n return pathWithoutExtension + '.tsx';\n }\n if (fs.existsSync(pathWithoutExtension + '.ts')) {\n return pathWithoutExtension + '.ts';\n }\n throw new Error(\"Can't find file at \" + pathWithoutExtension);\n};\n"],"file":"utils.js"}
|
package/dist/types.js.flow
CHANGED
package/package.json
CHANGED
package/src/cli/schema.json
CHANGED
package/src/generateTypeFiles.js
CHANGED
|
@@ -29,23 +29,17 @@ export const generateTypeFileContents = (
|
|
|
29
29
|
|
|
30
30
|
/// Write export for __generated__/index.js if it doesn't exist
|
|
31
31
|
const addToIndex = (filePath, typeName) => {
|
|
32
|
-
if (options.typeScript) {
|
|
32
|
+
if (options.typeScript || options.omitFileExtensions) {
|
|
33
33
|
// Typescript doesn't like file extensions
|
|
34
34
|
filePath = filePath.replace(/\.js$/, '');
|
|
35
35
|
}
|
|
36
36
|
const newLine = `export type {${typeName}} from './${path.basename(
|
|
37
37
|
filePath,
|
|
38
38
|
)}';`;
|
|
39
|
-
|
|
39
|
+
// We match the entire new line to avoid issues that can arise from
|
|
40
|
+
// prefix matches.
|
|
41
|
+
if (indexContents.indexOf(newLine) === -1) {
|
|
40
42
|
indexContents += newLine + '\n';
|
|
41
|
-
} else {
|
|
42
|
-
const lines = indexContents.split('\n').map((line) => {
|
|
43
|
-
if (line.includes('./' + path.basename(filePath))) {
|
|
44
|
-
return newLine;
|
|
45
|
-
}
|
|
46
|
-
return line;
|
|
47
|
-
});
|
|
48
|
-
indexContents = lines.join('\n');
|
|
49
43
|
}
|
|
50
44
|
};
|
|
51
45
|
|
package/src/index.js
CHANGED
|
@@ -30,6 +30,7 @@ const optionsToConfig = (
|
|
|
30
30
|
readOnlyArray: options?.readOnlyArray ?? true,
|
|
31
31
|
scalars: options?.scalars ?? {},
|
|
32
32
|
typeScript: options?.typeScript ?? false,
|
|
33
|
+
omitFileExtensions: options?.omitFileExtensions ?? false,
|
|
33
34
|
};
|
|
34
35
|
const fragments = {};
|
|
35
36
|
definitions.forEach((def) => {
|
package/src/parser/parse.js
CHANGED
|
@@ -11,6 +11,8 @@ import traverse from '@babel/traverse'; // eslint-disable-line flowtype-errors/u
|
|
|
11
11
|
|
|
12
12
|
import path from 'path';
|
|
13
13
|
|
|
14
|
+
import {getPathWithExtension} from './utils';
|
|
15
|
+
|
|
14
16
|
/**
|
|
15
17
|
* This file is responsible for finding all gql`-annotated
|
|
16
18
|
* template strings in a set of provided files, and for resolving
|
|
@@ -88,7 +90,8 @@ const listExternalReferences = (file: FileResult): Array<string> => {
|
|
|
88
90
|
const add = (v: Document | Import, followImports: boolean) => {
|
|
89
91
|
if (v.type === 'import') {
|
|
90
92
|
if (followImports) {
|
|
91
|
-
|
|
93
|
+
const absPath = getPathWithExtension(v.path);
|
|
94
|
+
paths[absPath] = true;
|
|
92
95
|
}
|
|
93
96
|
} else {
|
|
94
97
|
v.source.expressions.forEach((expr) => add(expr, true));
|
package/src/parser/resolve.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// @flow
|
|
2
2
|
import gql from 'graphql-tag';
|
|
3
|
+
import {getPathWithExtension} from './utils';
|
|
3
4
|
import type {DocumentNode} from 'graphql/language/ast';
|
|
4
5
|
import type {FileResult, Files, Import, Template, Document} from './parse';
|
|
5
6
|
|
|
@@ -36,25 +37,26 @@ const resolveImport = (
|
|
|
36
37
|
errors: FileResult['errors'],
|
|
37
38
|
seen: {[key: string]: true},
|
|
38
39
|
): ?Document => {
|
|
39
|
-
|
|
40
|
+
const absPath: string = getPathWithExtension(expr.path);
|
|
41
|
+
if (seen[absPath]) {
|
|
40
42
|
errors.push({
|
|
41
43
|
loc: expr.loc,
|
|
42
|
-
message: `Circular import ${Object.keys(seen).join(
|
|
43
|
-
|
|
44
|
-
}`,
|
|
44
|
+
message: `Circular import ${Object.keys(seen).join(
|
|
45
|
+
' -> ',
|
|
46
|
+
)} -> ${absPath}`,
|
|
45
47
|
});
|
|
46
48
|
return null;
|
|
47
49
|
}
|
|
48
|
-
seen[
|
|
49
|
-
const res = files[
|
|
50
|
+
seen[absPath] = true;
|
|
51
|
+
const res = files[absPath];
|
|
50
52
|
if (!res) {
|
|
51
|
-
errors.push({loc: expr.loc, message: `No file ${
|
|
53
|
+
errors.push({loc: expr.loc, message: `No file ${absPath}`});
|
|
52
54
|
return null;
|
|
53
55
|
}
|
|
54
56
|
if (!res.exports[expr.name]) {
|
|
55
57
|
errors.push({
|
|
56
58
|
loc: expr.loc,
|
|
57
|
-
message: `${
|
|
59
|
+
message: `${absPath} has no valid gql export ${expr.name}`,
|
|
58
60
|
});
|
|
59
61
|
return null;
|
|
60
62
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// @flow
|
|
2
|
+
import fs from 'fs';
|
|
3
|
+
|
|
4
|
+
export const getPathWithExtension = (pathWithoutExtension: string): string => {
|
|
5
|
+
if (
|
|
6
|
+
/\.(less|css|png|gif|jpg|jpeg|js|jsx|ts|tsx|mjs)$/.test(
|
|
7
|
+
pathWithoutExtension,
|
|
8
|
+
)
|
|
9
|
+
) {
|
|
10
|
+
return pathWithoutExtension;
|
|
11
|
+
}
|
|
12
|
+
if (fs.existsSync(pathWithoutExtension + '.js')) {
|
|
13
|
+
return pathWithoutExtension + '.js';
|
|
14
|
+
}
|
|
15
|
+
if (fs.existsSync(pathWithoutExtension + '.jsx')) {
|
|
16
|
+
return pathWithoutExtension + '.jsx';
|
|
17
|
+
}
|
|
18
|
+
if (fs.existsSync(pathWithoutExtension + '.tsx')) {
|
|
19
|
+
return pathWithoutExtension + '.tsx';
|
|
20
|
+
}
|
|
21
|
+
if (fs.existsSync(pathWithoutExtension + '.ts')) {
|
|
22
|
+
return pathWithoutExtension + '.ts';
|
|
23
|
+
}
|
|
24
|
+
throw new Error("Can't find file at " + pathWithoutExtension);
|
|
25
|
+
};
|