-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
loader.ts
236 lines (208 loc) · 7.27 KB
/
loader.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
import generator from '@babel/generator';
import { getOptions } from 'loader-utils';
import logUpdate from 'log-update';
import { relative } from 'path';
import { validate } from 'schema-utils';
import type { Schema as JsonSchema } from 'schema-utils/declarations/validate';
import { loader } from 'webpack';
import { replaceCallExpressions } from './call-expressions/ast';
import {
appendLiteralAndLoadContextForTsSources,
writeTiIndexForContext,
} from './call-expressions/handle-codegen-context';
import { resolveGraphQLDocument } from './call-expressions/type-inject';
import { processCodegenForContext } from './lib/codegen';
import loadConfig from './lib/config';
import { appendDocumentImportContext } from './lib/document-import';
import { processDtsForContext } from './lib/dts';
import { createExecContext } from './lib/exec-context';
import { readFile } from './lib/file';
import memoize from './lib/memoize';
import { PRINT_PREFIX, updateLog, updateLogDone } from './lib/print';
import { isAllSkip, SchemaImportCodegenContext } from './lib/types';
const optionsSchema: JsonSchema = {
type: 'object',
properties: {
configFile: {
type: 'string',
},
},
required: [],
};
export interface GraphQLLetLoaderOptions {
configFile?: string;
}
function parseOptions(ctx: loader.LoaderContext): GraphQLLetLoaderOptions {
const options = getOptions(ctx);
validate(optionsSchema, options);
return (options as unknown) as GraphQLLetLoaderOptions;
}
const processLoaderForSources = memoize(
async (
sourceFullPath: string,
sourceContent: string | Buffer,
addDependency: (path: string) => void,
cwd: string,
options: GraphQLLetLoaderOptions,
): Promise<string | Buffer> => {
const [config, configHash] = await loadConfig(cwd, options.configFile);
const { silent } = config;
const sourceRelPath = relative(cwd, sourceFullPath);
if (!silent) updateLog(`Processing ${sourceRelPath}...`);
const { execContext, codegenContext, schemaHash } = await createExecContext(
cwd,
config,
configHash,
);
const paths = appendLiteralAndLoadContextForTsSources(
execContext,
schemaHash,
codegenContext,
[sourceRelPath],
);
if (!paths.length) throw new Error('Never');
// If we only have 'schema-import' context, the source
// doesn't have any `gql()` or `load()` call. Return.
if (codegenContext.length === 1) return sourceContent;
if (isAllSkip(codegenContext)) {
if (!silent) updateLog(`Nothing to do. Cache was fresh.`);
const [{ tsxFullPath }] = codegenContext as SchemaImportCodegenContext[];
return await readFile(tsxFullPath, 'utf-8');
}
if (!silent) updateLog(`Processing codegen for ${sourceRelPath}...`);
const [[fileNode, programPath, callExpressionPathPairs]] = paths;
// Add dependencies so editing dependent GraphQL emits HMR.
for (const context of codegenContext) {
switch (context.type) {
case 'document-import':
throw new Error('Never');
case 'schema-import':
// Nothing to do
break;
case 'gql-call':
case 'load-call':
for (const d of context.dependantFullPaths) addDependency(d);
break;
}
}
replaceCallExpressions(
programPath,
sourceFullPath,
callExpressionPathPairs,
codegenContext,
);
writeTiIndexForContext(execContext, codegenContext);
await processCodegenForContext(execContext, codegenContext);
if (!silent) updateLog(`Generating d.ts for ${sourceRelPath}...`);
await processDtsForContext(execContext, codegenContext);
const { code } = generator(fileNode);
if (!silent) {
updateLog(`Done processing ${sourceRelPath}.`);
updateLogDone();
}
return code;
},
(gqlFullPath: string) => gqlFullPath,
);
const processLoaderForDocuments = memoize(
async (
gqlFullPath: string,
gqlContent: string | Buffer,
addDependency: (path: string) => void,
cwd: string,
options: GraphQLLetLoaderOptions,
): Promise<string> => {
const [config, configHash] = await loadConfig(cwd, options.configFile);
const { silent } = config;
const graphqlRelPath = relative(cwd, gqlFullPath);
if (!silent) updateLog(`Processing ${graphqlRelPath}...`);
const { execContext, codegenContext, schemaHash } = await createExecContext(
cwd,
config,
configHash,
);
// // Having another array to capture only targets of the loader execution, excluding 'schema-import'
// const documentImportContext: DocumentImportCodegenContext[] = [];
// Add dependencies so editing dependent GraphQL emits HMR.
const { dependantFullPaths } = resolveGraphQLDocument(
gqlFullPath,
String(gqlContent),
cwd,
);
for (const d of dependantFullPaths) addDependency(d);
// const documentImportCodegenContext: DocumentImportCodegenContext[] = [];
await appendDocumentImportContext(execContext, schemaHash, codegenContext, [
graphqlRelPath,
]);
const [, fileContext] = codegenContext;
if (!fileContext) throw new Error('Never');
const { skip, tsxFullPath } = fileContext;
if (skip) {
if (!silent) updateLog(`Nothing to do. Cache was fresh.`);
return await readFile(tsxFullPath, 'utf-8');
}
if (!silent) updateLog(`Processing codegen for ${graphqlRelPath}...`);
const codegenOutputs = await processCodegenForContext(
execContext,
codegenContext,
);
// We need to find what we generate since the array order varies.
const documentImportCodegenResult = codegenOutputs.find(
({ filename }) => filename === tsxFullPath,
);
if (!documentImportCodegenResult)
throw new Error('Output of "document-import" should appear.');
if (!silent) updateLog(`Generating d.ts for ${graphqlRelPath}...`);
await processDtsForContext(execContext, codegenContext);
if (!silent) {
updateLog(`Done processing ${graphqlRelPath}.`);
updateLogDone();
}
return documentImportCodegenResult.content;
},
(gqlFullPath: string) => gqlFullPath,
);
/**
* Webpack loader to handle both *.graphql and *.ts(x).
*/
const graphQLLetLoader: loader.Loader = function (resourceContent) {
const callback = this.async()!;
const { resourcePath: resourceFullPath, rootContext: cwd } = this;
const options = parseOptions(this);
const addDependency = this.addDependency.bind(this);
let promise: Promise<string | Buffer>;
const isTypeScriptSource =
resourceFullPath.endsWith('.ts') || resourceFullPath.endsWith('.tsx');
if (isTypeScriptSource) {
promise = processLoaderForSources(
resourceFullPath,
resourceContent,
addDependency,
cwd,
options,
);
} else {
promise = processLoaderForDocuments(
resourceFullPath,
resourceContent,
addDependency,
cwd,
options,
).then((content) => {
// Pretend .tsx for later loaders.
// babel-loader at least doesn't respond the .graphql extension.
this.resourcePath = `${resourceFullPath}.tsx`;
return content;
});
}
promise
.then((tsxContent) => {
callback(undefined, tsxContent);
})
.catch((e) => {
logUpdate.stderr(PRINT_PREFIX + e.message);
logUpdate.stderr.done();
callback(e);
});
};
export default graphQLLetLoader;