-
Notifications
You must be signed in to change notification settings - Fork 349
/
ts-artifacts.ts
557 lines (511 loc) · 17.7 KB
/
ts-artifacts.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
import { Logger, Maybe, RawSourceOutput, YamlConfig } from '@graphql-mesh/types';
import * as tsBasePlugin from '@graphql-codegen/typescript';
import * as tsResolversPlugin from '@graphql-codegen/typescript-resolvers';
import { GraphQLSchema, GraphQLObjectType, NamedTypeNode, Kind } from 'graphql';
import { codegen } from '@graphql-codegen/core';
import { pascalCase } from 'pascal-case';
import { printSchemaWithDirectives, Source } from '@graphql-tools/utils';
import * as tsOperationsPlugin from '@graphql-codegen/typescript-operations';
import * as typescriptGenericSdk from '@graphql-codegen/typescript-generic-sdk';
import * as typedDocumentNodePlugin from '@graphql-codegen/typed-document-node';
import { fs, path as pathModule } from '@graphql-mesh/cross-helpers';
import ts from 'typescript';
import { pathExists, writeFile, writeJSON } from '@graphql-mesh/utils';
import { generateOperations } from './generate-operations.js';
import { GraphQLMeshCLIParams } from '..';
import JSON5 from 'json5';
const unifiedContextIdentifier = 'MeshContext';
class CodegenHelpers extends tsBasePlugin.TsVisitor {
public getTypeToUse(namedType: NamedTypeNode): string {
if (this.scalars[namedType.name.value]) {
return this._getScalar(namedType.name.value);
}
return this._getTypeForNode(namedType);
}
}
function buildSignatureBasedOnRootFields(
codegenHelpers: CodegenHelpers,
type: Maybe<GraphQLObjectType>,
): Record<string, string> {
if (!type) {
return {};
}
const fields = type.getFields();
const operationMap: Record<string, string> = {};
for (const fieldName in fields) {
const field = fields[fieldName];
const argsExists = field.args && field.args.length > 0;
const argsName = argsExists ? `${type.name}${field.name}Args` : '{}';
const parentTypeNode: NamedTypeNode = {
kind: Kind.NAMED_TYPE,
name: {
kind: Kind.NAME,
value: type.name,
},
};
operationMap[fieldName] = ` /** ${field.description} **/\n ${
field.name
}: InContextSdkMethod<${codegenHelpers.getTypeToUse(
parentTypeNode,
)}['${fieldName}'], ${argsName}, ${unifiedContextIdentifier}>`;
}
return operationMap;
}
async function generateTypesForApi(options: {
schema: GraphQLSchema;
name: string;
contextVariables: Record<string, string>;
}) {
const config = {
skipTypename: true,
namingConvention: 'keep',
enumsAsTypes: true,
ignoreEnumValuesFromSchema: true,
};
const baseTypes = await codegen({
filename: options.name + '_types.ts',
documents: [],
config,
schemaAst: options.schema,
schema: undefined as any, // This is not necessary on codegen. Will be removed later
skipDocumentsValidation: true,
plugins: [
{
typescript: {},
},
],
pluginMap: {
typescript: tsBasePlugin,
},
});
const codegenHelpers = new CodegenHelpers(options.schema, config, {});
const namespace = pascalCase(`${options.name}Types`);
const queryOperationMap = buildSignatureBasedOnRootFields(
codegenHelpers,
options.schema.getQueryType(),
);
const mutationOperationMap = buildSignatureBasedOnRootFields(
codegenHelpers,
options.schema.getMutationType(),
);
const subscriptionsOperationMap = buildSignatureBasedOnRootFields(
codegenHelpers,
options.schema.getSubscriptionType(),
);
const codeAst = `
import { InContextSdkMethod } from '@graphql-mesh/types';
import { MeshContext } from '@graphql-mesh/runtime';
export namespace ${namespace} {
${baseTypes}
export type QuerySdk = {
${Object.values(queryOperationMap).join(',\n')}
};
export type MutationSdk = {
${Object.values(mutationOperationMap).join(',\n')}
};
export type SubscriptionSdk = {
${Object.values(subscriptionsOperationMap).join(',\n')}
};
export type Context = {
[${JSON.stringify(
options.name,
)}]: { Query: QuerySdk, Mutation: MutationSdk, Subscription: SubscriptionSdk },
${Object.keys(options.contextVariables)
.map(key => `[${JSON.stringify(key)}]: ${options.contextVariables[key]}`)
.join(',\n')}
};
}
`;
return {
identifier: namespace,
codeAst,
};
}
const BASEDIR_ASSIGNMENT_COMMENT = `/* BASEDIR_ASSIGNMENT */`;
export async function generateTsArtifacts(
{
unifiedSchema,
rawSources,
mergerType = 'stitching',
documents,
flattenTypes,
importedModulesSet,
baseDir,
meshConfigImportCodes,
meshConfigCodes,
logger,
sdkConfig,
fileType,
codegenConfig = {},
}: {
unifiedSchema: GraphQLSchema;
rawSources: readonly RawSourceOutput[];
mergerType: string;
documents: Source[];
flattenTypes: boolean;
importedModulesSet: Set<string>;
baseDir: string;
meshConfigImportCodes: Set<string>;
meshConfigCodes: Set<string>;
logger: Logger;
sdkConfig: YamlConfig.SDKConfig;
fileType: 'ts' | 'json' | 'js';
codegenConfig: any;
},
cliParams: GraphQLMeshCLIParams,
) {
const artifactsDir = pathModule.join(baseDir, cliParams.artifactsDir);
logger.info('Generating index file in TypeScript');
for (const rawSource of rawSources) {
const transformedSchema = (unifiedSchema.extensions as any).sourceMap.get(rawSource);
const sdl = printSchemaWithDirectives(transformedSchema);
await writeFile(pathModule.join(artifactsDir, `sources/${rawSource.name}/schema.graphql`), sdl);
}
const documentsInput = sdkConfig?.generateOperations
? generateOperations(unifiedSchema, sdkConfig.generateOperations)
: documents;
const pluginsInput: Record<string, any>[] = [
{
typescript: {},
},
{
resolvers: {},
},
{
contextSdk: {},
},
];
if (documentsInput.length) {
pluginsInput.push(
{
typescriptOperations: {},
},
{
typedDocumentNode: {},
},
{
typescriptGenericSdk: {
documentMode: 'external',
importDocumentNodeExternallyFrom: 'NOWHERE',
},
},
);
}
const codegenOutput =
'// @ts-nocheck\n' +
(
await codegen({
filename: 'types.ts',
documents: documentsInput,
config: {
skipTypename: true,
flattenGeneratedTypes: flattenTypes,
onlyOperationTypes: flattenTypes,
preResolveTypes: flattenTypes,
namingConvention: 'keep',
documentMode: 'graphQLTag',
gqlImport: '@graphql-mesh/utils#gql',
enumsAsTypes: true,
ignoreEnumValuesFromSchema: true,
useIndexSignature: true,
noSchemaStitching: false,
contextType: unifiedContextIdentifier,
federation: mergerType === 'federation',
...codegenConfig,
},
schemaAst: unifiedSchema,
schema: undefined as any, // This is not necessary on codegen.
// skipDocumentsValidation: true,
pluginMap: {
typescript: tsBasePlugin,
typescriptOperations: tsOperationsPlugin,
typedDocumentNode: typedDocumentNodePlugin,
typescriptGenericSdk,
resolvers: tsResolversPlugin,
contextSdk: {
plugin: async () => {
const importCodes = new Set([
...meshConfigImportCodes,
`import { getMesh, ExecuteMeshFn, SubscribeMeshFn, MeshContext as BaseMeshContext, MeshInstance } from '@graphql-mesh/runtime';`,
`import { MeshStore, FsStoreStorageAdapter } from '@graphql-mesh/store';`,
`import { path as pathModule } from '@graphql-mesh/cross-helpers';`,
`import { ImportFn } from '@graphql-mesh/types';`,
]);
const results = await Promise.all(
rawSources.map(async source => {
const sourceMap = unifiedSchema.extensions.sourceMap as Map<
RawSourceOutput,
GraphQLSchema
>;
const sourceSchema = sourceMap.get(source);
const { identifier, codeAst } = await generateTypesForApi({
schema: sourceSchema,
name: source.name,
contextVariables: source.contextVariables,
});
if (codeAst) {
const content = '// @ts-nocheck\n' + codeAst;
await writeFile(
pathModule.join(artifactsDir, `sources/${source.name}/types.ts`),
content,
);
}
if (identifier) {
importCodes.add(
`import type { ${identifier} } from './sources/${source.name}/types';`,
);
}
return {
identifier,
codeAst,
};
}),
);
const contextType = `export type ${unifiedContextIdentifier} = ${results
.map(r => `${r?.identifier}.Context`)
.filter(Boolean)
.join(' & ')} & BaseMeshContext;`;
let meshMethods = `
${BASEDIR_ASSIGNMENT_COMMENT}
const importFn: ImportFn = <T>(moduleId: string) => {
const relativeModuleId = (pathModule.isAbsolute(moduleId) ? pathModule.relative(baseDir, moduleId) : moduleId).split('\\\\').join('/').replace(baseDir + '/', '');
switch(relativeModuleId) {${[...importedModulesSet]
.map(importedModuleName => {
let moduleMapProp = importedModuleName;
let importPath = importedModuleName;
if (importPath.startsWith('.')) {
importPath = pathModule.join(baseDir, importPath);
}
if (pathModule.isAbsolute(importPath)) {
moduleMapProp = pathModule.relative(baseDir, importedModuleName).split('\\').join('/');
importPath = `./${pathModule
.relative(artifactsDir, importedModuleName)
.split('\\')
.join('/')}`;
}
return `
case ${JSON.stringify(moduleMapProp)}:
return import(${JSON.stringify(importPath)}) as T;
`;
})
.join('')}
default:
return Promise.reject(new Error(\`Cannot find module '\${relativeModuleId}'.\`));
}
};
const rootStore = new MeshStore('${cliParams.artifactsDir}', new FsStoreStorageAdapter({
cwd: baseDir,
importFn,
fileType: ${JSON.stringify(fileType)},
}), {
readonly: true,
validate: false
});
${[...meshConfigCodes].join('\n')}
let meshInstance$: Promise<MeshInstance> | undefined;
export function ${cliParams.builtMeshFactoryName}(): Promise<MeshInstance> {
if (meshInstance$ == null) {
meshInstance$ = getMeshOptions().then(meshOptions => getMesh(meshOptions)).then(mesh => {
const id = mesh.pubsub.subscribe('destroy', () => {
meshInstance$ = undefined;
mesh.pubsub.unsubscribe(id);
});
return mesh;
});
}
return meshInstance$;
}
export const execute: ExecuteMeshFn = (...args) => ${
cliParams.builtMeshFactoryName
}().then(({ execute }) => execute(...args));
export const subscribe: SubscribeMeshFn = (...args) => ${
cliParams.builtMeshFactoryName
}().then(({ subscribe }) => subscribe(...args));`;
if (documentsInput.length) {
meshMethods += `
export function ${cliParams.builtMeshSDKFactoryName}<TGlobalContext = any, TOperationContext = any>(globalContext?: TGlobalContext) {
const sdkRequester$ = ${cliParams.builtMeshFactoryName}().then(({ sdkRequesterFactory }) => sdkRequesterFactory(globalContext));
return getSdk<TOperationContext, TGlobalContext>((...args) => sdkRequester$.then(sdkRequester => sdkRequester(...args)));
}`;
}
return {
prepend: [[...importCodes].join('\n'), '\n\n'],
content: [contextType, meshMethods].join('\n\n'),
};
},
},
},
plugins: pluginsInput,
})
)
.replace(`import * as Operations from 'NOWHERE';\n`, '')
.replace(`import { DocumentNode } from 'graphql';`, '');
const endpointAssignmentESM = `import { fileURLToPath } from '@graphql-mesh/utils';
const baseDir = pathModule.join(pathModule.dirname(fileURLToPath(import.meta.url)), '${pathModule.relative(
artifactsDir,
baseDir,
)}');`;
const endpointAssignmentCJS = `const baseDir = pathModule.join(typeof __dirname === 'string' ? __dirname : '/', '${pathModule.relative(
artifactsDir,
baseDir,
)}');`;
const tsFilePath = pathModule.join(artifactsDir, 'index.ts');
const jobs: (() => Promise<void>)[] = [];
const jsFilePath = pathModule.join(artifactsDir, 'index.js');
const dtsFilePath = pathModule.join(artifactsDir, 'index.d.ts');
const esmJob = (ext: 'mjs' | 'js') => async () => {
logger.info('Writing index.ts for ESM to the disk.');
await writeFile(
tsFilePath,
codegenOutput.replace(BASEDIR_ASSIGNMENT_COMMENT, endpointAssignmentESM),
);
const esmJsFilePath = pathModule.join(artifactsDir, `index.${ext}`);
if (await pathExists(esmJsFilePath)) {
await fs.promises.unlink(esmJsFilePath);
}
if (fileType !== 'ts') {
logger.info(`Compiling TS file as ES Module to "index.${ext}"`);
compileTS(tsFilePath, ts.ModuleKind.ESNext, [jsFilePath, dtsFilePath]);
if (ext === 'mjs') {
const mjsFilePath = pathModule.join(artifactsDir, 'index.mjs');
await fs.promises.rename(jsFilePath, mjsFilePath);
}
logger.info('Deleting index.ts');
await fs.promises.unlink(tsFilePath);
}
};
const cjsJob = async () => {
logger.info('Writing index.ts for CJS to the disk.');
await writeFile(
tsFilePath,
codegenOutput.replace(BASEDIR_ASSIGNMENT_COMMENT, endpointAssignmentCJS),
);
if (await pathExists(jsFilePath)) {
await fs.promises.unlink(jsFilePath);
}
if (fileType !== 'ts') {
logger.info('Compiling TS file as CommonJS Module to `index.js`');
compileTS(tsFilePath, ts.ModuleKind.CommonJS, [jsFilePath, dtsFilePath]);
logger.info('Deleting index.ts');
await fs.promises.unlink(tsFilePath);
}
};
const packageJsonJob = (module: string) => () =>
writeJSON(pathModule.join(artifactsDir, 'package.json'), {
name: 'mesh-artifacts',
private: true,
type: module,
main: 'index.js',
module: 'index.mjs',
sideEffects: false,
typings: 'index.d.ts',
typescript: {
definition: 'index.d.ts',
},
exports: {
'.': {
require: './index.js',
import: './index.mjs',
},
'./*': {
require: './*.js',
import: './*.mjs',
},
},
});
function setTsConfigDefault() {
jobs.push(cjsJob);
if (fileType !== 'ts') {
jobs.push(packageJsonJob('commonjs'));
}
}
const rootDir = pathModule.resolve('./');
const tsConfigPath = pathModule.join(rootDir, 'tsconfig.json');
const packageJsonPath = pathModule.join(rootDir, 'package.json');
if (await pathExists(tsConfigPath)) {
// case tsconfig exists
const tsConfigStr = await fs.promises.readFile(tsConfigPath, 'utf-8');
const tsConfig = JSON5.parse(tsConfigStr);
if (tsConfig?.compilerOptions?.module?.toLowerCase()?.startsWith('es')) {
// case tsconfig set to esm
jobs.push(esmJob('js'));
if (fileType !== 'ts') {
jobs.push(packageJsonJob('module'));
}
} else if (
tsConfig?.compilerOptions?.module?.toLowerCase()?.startsWith('node') &&
(await pathExists(packageJsonPath))
) {
// case tsconfig set to node* and package.json exists
const packageJsonStr = await fs.promises.readFile(packageJsonPath, 'utf-8');
const packageJson = JSON5.parse(packageJsonStr);
if (packageJson?.type === 'module') {
// case package.json set to esm
jobs.push(esmJob('js'));
if (fileType !== 'ts') {
jobs.push(packageJsonJob('module'));
}
} else {
// case package.json set to cjs or not set
setTsConfigDefault();
}
} else {
// case tsconfig set to cjs or set to node* with no package.json
setTsConfigDefault();
}
} else if (await pathExists(packageJsonPath)) {
// case package.json exists
const packageJsonStr = await fs.promises.readFile(packageJsonPath, 'utf-8');
const packageJson = JSON5.parse(packageJsonStr);
if (packageJson?.type === 'module') {
// case package.json set to esm
jobs.push(esmJob('js'));
if (fileType !== 'ts') {
jobs.push(packageJsonJob('module'));
}
} else {
// case package.json set to cjs or not set
jobs.push(esmJob('mjs'));
if (fileType === 'js') {
jobs.push(packageJsonJob('module'));
} else {
jobs.push(cjsJob);
jobs.push(packageJsonJob('commonjs'));
}
}
} else {
// case no tsconfig and no package.json
jobs.push(esmJob('mjs'));
if (fileType === 'js') {
jobs.push(packageJsonJob('module'));
} else {
jobs.push(cjsJob);
jobs.push(packageJsonJob('commonjs'));
}
}
for (const job of jobs) {
await job();
}
}
export function compileTS(tsFilePath: string, module: ts.ModuleKind, outputFilePaths: string[]) {
const options: ts.CompilerOptions = {
target: ts.ScriptTarget.ESNext,
module,
sourceMap: false,
inlineSourceMap: false,
importHelpers: true,
allowSyntheticDefaultImports: true,
esModuleInterop: true,
declaration: true,
};
const host = ts.createCompilerHost(options);
const hostWriteFile = host.writeFile.bind(host);
host.writeFile = (fileName, ...rest) => {
if (outputFilePaths.some(f => pathModule.normalize(f) === pathModule.normalize(fileName))) {
return hostWriteFile(fileName, ...rest);
}
};
// Prepare and emit the d.ts files
const program = ts.createProgram([tsFilePath], options, host);
program.emit();
}