-
Notifications
You must be signed in to change notification settings - Fork 202
/
index.ts
617 lines (564 loc) Β· 17.5 KB
/
index.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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
import { ancestor } from 'acorn-walk';
import { generate } from 'escodegen';
import { Parser, Node as AcornNode } from 'acorn';
import { transformUrl, haveSourcemap } from '@garfish/utils';
import type {
Node,
Program,
Identifier,
Expression,
MetaProperty,
CallExpression,
MemberExpression,
VariableDeclaration,
ExportDefaultDeclaration,
ImportSpecifier,
ImportExpression,
ImportDeclaration,
ExportAllDeclaration,
ExportNamedDeclaration,
} from 'estree';
import {
isIdentifier,
isVariableDeclaration,
isExportSpecifier,
isExportAllDeclaration,
isExportDefaultDeclaration,
isImportDefaultSpecifier,
isImportNamespaceSpecifier,
} from './types';
import {
literal,
identifier,
callExpression,
objectProperty,
objectExpression,
memberExpression,
arrowFunctionExpression,
variableDeclarator,
variableDeclaration,
} from './generated';
import type { Scope } from './scope';
import { mergeSourcemap } from './mergeMap';
import { State, createState } from './state';
import { Runtime, ModuleResource } from '../runtime';
type ImportInfoData = (
| ReturnType<Compiler['getImportInformation']>
| ReturnType<Compiler['getImportInformationBySource']>
) & {
moduleName: string;
};
type ImportTransformNode = ReturnType<Compiler['generateImportTransformNode']>;
interface CompilerOptions {
code: string;
storeId: string;
filename: string;
runtime: Runtime;
}
export interface Output {
map: string;
code: string;
}
export class Compiler {
static keys = {
__GARFISH_IMPORT__: '__GARFISH_IMPORT__',
__GARFISH_EXPORT__: '__GARFISH_EXPORT__',
__GARFISH_DEFAULT__: '__GARFISH_DEFAULT__',
__GARFISH_WRAPPER__: '__GARFISH_WRAPPER__',
__GARFISH_NAMESPACE__: '__GARFISH_NAMESPACE__',
__GARFISH_IMPORT_META__: '__GARFISH_IMPORT_META__',
__GARFISH_DYNAMIC_IMPORT__: '__GARFISH_DYNAMIC_IMPORT__',
};
private ast: Program;
private state: ReturnType<typeof createState>;
private moduleCount = 0;
private consumed = false;
private importInfos: Array<{
data: ImportInfoData;
transformNode: ImportTransformNode;
}> = [];
private exportInfos: Array<{
name: string;
refNode: Identifier | CallExpression | MemberExpression;
}> = [];
private deferQueue = {
removes: new Set<() => void>(),
replaces: new Set<() => void>(),
importChecks: new Set<() => void>(),
identifierRefs: new Set<() => void>(),
exportNamespaces: new Set<{
moduleId: string;
namespace: string | undefined;
fn: (names: Array<string>) => void;
}>(),
};
public options: CompilerOptions;
public sourcemapComment: string;
constructor(options: CompilerOptions) {
this.options = options;
this.ast = this.parse();
this.state = createState(this.ast);
}
private parse() {
const parser = new Parser(
{
locations: true,
sourceType: 'module',
ecmaVersion: 'latest',
sourceFile: this.options.filename,
onComment: (isBlock, text) => this.onParseComment(isBlock, text),
},
this.options.code,
);
try {
return parser.parse() as unknown as Program;
} catch (e) {
e.message += `(${this.options.filename})`;
throw e;
}
}
private onParseComment(isBlock: boolean, text: string) {
if (haveSourcemap(text)) {
this.sourcemapComment = text;
}
}
private checkImportNames(
imports: ImportInfoData['imports'],
moduleId: string,
) {
const exports = this.getChildModuleExports(moduleId);
if (exports) {
imports.forEach((item) => {
if (item.isNamespace) return;
const checkName = item.isDefault ? 'default' : item.name;
if (!exports.includes(checkName)) {
throw SyntaxError(
`(${this.options.filename}): The module '${moduleId}' does not provide an export named '${checkName}'`,
);
}
});
}
}
private getChildModuleExports(moduleId: string) {
const storeId = transformUrl(this.options.storeId, moduleId);
const output = this.options.runtime.resources[storeId] as ModuleResource;
return output ? output.exports : null;
}
private getImportInformation(node: ImportDeclaration) {
const imports = node.specifiers.map((n) => {
const isDefault = isImportDefaultSpecifier(n);
const isNamespace = isImportNamespaceSpecifier(n);
const isSpecial = isDefault || isNamespace;
const alias = isSpecial ? null : n.local.name;
const name = isSpecial
? n.local.name
: (n as ImportSpecifier).imported.name;
return {
name,
isDefault,
isNamespace,
alias: alias === name ? null : alias,
};
});
return {
imports,
isExport: false,
moduleId: node.source.value as string,
};
}
private getImportInformationBySource(
node: ExportNamedDeclaration | ExportAllDeclaration,
) {
const imports = ((node as ExportNamedDeclaration).specifiers || []).map(
(n) => {
const alias = n.exported.name;
const name = n.local.name;
return {
name,
alias: alias === name ? null : alias,
};
},
);
return {
imports,
isExport: true,
moduleId: node.source?.value as string,
};
}
private generateImportTransformNode(moduleName: string, moduleId: string) {
const varName = identifier(moduleName);
const varExpr = callExpression(
identifier(Compiler.keys.__GARFISH_IMPORT__),
[literal(moduleId)],
);
const varNode = variableDeclarator(varName, varExpr);
return variableDeclaration('const', [varNode]);
}
private generateIdentifierTransformNode(
nameOrInfo: string | ReturnType<Compiler['findIndexInData']>,
) {
let info;
if (typeof nameOrInfo === 'string') {
for (const { data } of this.importInfos) {
if (!data.isExport) {
const result = this.findIndexInData(nameOrInfo, data);
if (result) {
info = result;
break;
}
}
}
} else {
info = nameOrInfo;
}
if (info && info.data) {
const { i, data } = info;
const item = data.imports[i];
if (item.isNamespace) {
return callExpression(identifier(Compiler.keys.__GARFISH_NAMESPACE__), [
identifier(data.moduleName),
]);
} else {
const propName = item.isDefault ? 'default' : item.name;
return memberExpression(
identifier(data.moduleName),
identifier(propName),
);
}
}
}
private generateVirtualModuleSystem() {
const exportNodes = this.exportInfos.map(({ name, refNode }) => {
return objectProperty(
identifier(name),
arrowFunctionExpression([], refNode),
);
});
const exportCallExpression = callExpression(
identifier(Compiler.keys.__GARFISH_EXPORT__),
[objectExpression(exportNodes)],
);
this.ast.body.unshift(
exportCallExpression as any,
...new Set(this.importInfos.map((val) => val.transformNode)),
);
}
private findIndexInData(refName: string, data: ImportInfoData) {
for (let i = 0; i < data.imports.length; i++) {
const { name, alias } = data.imports[i];
if (refName === alias || refName === name) {
return { i, data };
}
}
}
private findImportInfo(moduleId: string): [string?, VariableDeclaration?] {
for (const { data, transformNode } of this.importInfos) {
if (data.moduleId === moduleId) {
return [data.moduleName, transformNode];
}
}
return [];
}
private isReferencedModuleVariable(scope: Scope, node: Identifier) {
const u = () =>
Object.keys(scope.bindings).some((key) => {
const { kind, references, constantViolations } = scope.bindings[key];
if (kind === 'module') {
return references.has(node) || constantViolations.has(node);
}
});
while (scope) {
if (u()) return true;
if (scope.parent) {
scope = scope.parent;
} else {
break;
}
}
return false;
}
// 1. export { a as default };
// 2. export { default as x } from 'module';
private processExportSpecifiers(
node: ExportNamedDeclaration,
state: State,
ancestors: Array<Node>,
) {
if (node.source) {
const moduleId = node.source.value as string;
const data = this.getImportInformationBySource(node);
let [moduleName, transformNode] = this.findImportInfo(moduleId);
if (!moduleName) {
moduleName = `__m${this.moduleCount++}__`;
transformNode = this.generateImportTransformNode(moduleName, moduleId);
}
(data as ImportInfoData).moduleName = moduleName;
transformNode &&
this.importInfos.push({ data: data as ImportInfoData, transformNode });
this.deferQueue.importChecks.add(() =>
this.checkImportNames(data.imports, moduleId),
);
node.specifiers.forEach((n) => {
const useInfo = this.findIndexInData(
n.local.name,
data as ImportInfoData,
);
const refNode = this.generateIdentifierTransformNode(useInfo);
refNode && this.exportInfos.push({ refNode, name: n.exported.name });
});
} else {
const scope = state.getScopeByAncestors(ancestors);
node.specifiers.forEach((n) => {
const refNode =
scope && this.isReferencedModuleVariable(scope, n.local)
? this.generateIdentifierTransformNode(n.local.name)
: identifier(n.local.name);
refNode && this.exportInfos.push({ refNode, name: n.exported.name });
});
}
this.deferQueue.removes.add(() => state.remove(ancestors));
}
// 1. export default 1;
// 2. export const a = 1;
private processExportNamedDeclaration(
node: ExportNamedDeclaration | ExportDefaultDeclaration,
state: State,
ancestors: Array<Node>,
) {
const isDefault = isExportDefaultDeclaration(node);
if (node.declaration) {
const nodes = isVariableDeclaration(node.declaration)
? node.declaration.declarations
: [node.declaration];
nodes.forEach((node) => {
if (isDefault) {
const name = 'default';
const refNode = identifier(Compiler.keys.__GARFISH_DEFAULT__);
this.exportInfos.push({ name, refNode });
} else {
const names = state.getBindingIdentifiers(node.id);
names.forEach(({ name }) => {
this.exportInfos.push({ name, refNode: identifier(name) });
});
}
});
if (isDefault) {
this.deferQueue.replaces.add(() => {
// ζ€ζΆ declaration ε―θ½ε·²η»θ’«ζΏζ’θΏδΊ
const varName = identifier(Compiler.keys.__GARFISH_DEFAULT__);
const varNode = variableDeclarator(
varName,
node.declaration as Expression,
);
state.replaceWith(variableDeclaration('const', [varNode]), ancestors);
});
} else if (node.declaration && isIdentifier(node.declaration)) {
this.deferQueue.removes.add(() => state.remove(ancestors));
} else {
node.declaration &&
this.deferQueue.replaces.add(() => {
node.declaration && state.replaceWith(node.declaration, ancestors);
});
}
}
}
// 1. export * from 'module';
// 2. export * as x from 'module';
private processExportAllDeclaration(
node: ExportAllDeclaration,
state: State,
ancestors: Array<Node>,
) {
const namespace = node.exported?.name;
const moduleId = node.source.value as string;
const data = this.getImportInformationBySource(node);
let [moduleName, transformNode] = this.findImportInfo(moduleId);
if (!moduleName) {
moduleName = `__m${this.moduleCount++}__`;
transformNode = this.generateImportTransformNode(moduleName, moduleId);
}
(data as ImportInfoData).moduleName = moduleName;
transformNode &&
this.importInfos.push({ data: data as ImportInfoData, transformNode });
this.deferQueue.removes.add(() => state.remove(ancestors));
this.deferQueue.exportNamespaces.add({
moduleId,
namespace,
fn: (names) => {
names.forEach((name) => {
let refNode;
if (moduleName) {
if (name === namespace) {
refNode = callExpression(
identifier(Compiler.keys.__GARFISH_NAMESPACE__),
[identifier(moduleName)],
);
} else {
refNode = memberExpression(
identifier(moduleName),
identifier(name),
);
}
}
this.exportInfos.push({ refNode, name });
});
},
});
}
// ε€ηζζη export
private exportDeclarationVisitor(
node: any,
state: State,
ancestors: Array<Node>,
) {
if (node.declaration) {
this.processExportNamedDeclaration(node, state, [...ancestors]);
} else if (node.specifiers) {
this.processExportSpecifiers(node, state, [...ancestors]);
} else if (isExportAllDeclaration(node)) {
this.processExportAllDeclaration(node, state, [...ancestors]);
}
}
// ε€ηζζη¨ε° esm ηεΌη¨
private identifierVisitor(
node: Identifier,
state: State,
ancestors: Array<Node>,
) {
const parent = ancestors[ancestors.length - 2];
if (isExportSpecifier(parent)) return;
const scope = state.getScopeByAncestors(ancestors);
if (scope && this.isReferencedModuleVariable(scope, node)) {
ancestors = [...ancestors];
this.deferQueue.identifierRefs.add(() => {
const replacement = this.generateIdentifierTransformNode(node.name);
if (replacement) {
state.replaceWith(replacement, ancestors);
}
});
}
}
// Static import expression
private importDeclarationVisitor(
node: ImportDeclaration,
state: State,
ancestors: Array<Node>,
) {
ancestors = [...ancestors];
const moduleId = node.source.value as string;
const data = this.getImportInformation(node);
let [moduleName, transformNode] = this.findImportInfo(moduleId);
if (!moduleName) {
moduleName = `__m${this.moduleCount++}__`;
transformNode = this.generateImportTransformNode(moduleName, moduleId);
}
(data as ImportInfoData).moduleName = moduleName;
transformNode &&
this.importInfos.push({ data: data as ImportInfoData, transformNode });
this.deferQueue.removes.add(() => state.remove(ancestors));
this.deferQueue.importChecks.add(() =>
this.checkImportNames(data.imports, moduleId),
);
}
// Dynamic import expression
private importExpressionVisitor(
node: ImportExpression,
state: State,
ancestors: Array<Node>,
) {
const replacement = callExpression(
identifier(Compiler.keys.__GARFISH_DYNAMIC_IMPORT__),
[node.source],
);
state.replaceWith(replacement, ancestors);
}
// `import.meta`
private importMetaVisitor(
node: MetaProperty,
state: State,
ancestors: Array<Node>,
) {
if (node.meta.name === 'import') {
const replacement = memberExpression(
identifier(Compiler.keys.__GARFISH_IMPORT_META__),
node.property,
);
state.replaceWith(replacement, ancestors);
}
}
private async generateCode() {
const nameCounts = {};
const getExports = ({ namespace, moduleId }) => {
return namespace
? [namespace as string]
: this.getChildModuleExports(moduleId) || [];
};
this.deferQueue.exportNamespaces.forEach((val) => {
getExports(val).forEach((name) => {
if (!nameCounts[name]) {
nameCounts[name] = 1;
} else {
nameCounts[name]++;
}
});
});
this.deferQueue.exportNamespaces.forEach((val) => {
// `export namespace` ειηε»ι
const exports = getExports(val).filter((name) => {
if (name === 'default') return false;
if (nameCounts[name] > 1) return false;
return this.exportInfos.every((val) => val.name !== name);
});
val.fn(exports);
});
this.deferQueue.importChecks.forEach((fn) => fn());
this.deferQueue.identifierRefs.forEach((fn) => fn());
this.deferQueue.replaces.forEach((fn) => fn());
this.deferQueue.removes.forEach((fn) => fn());
this.generateVirtualModuleSystem();
const output = generate(this.ast, {
sourceMapWithCode: true,
sourceMap: this.options.filename,
sourceContent: this.options.code,
}) as unknown as Output;
await mergeSourcemap(this, output);
return output;
}
transform() {
if (this.consumed) {
throw new Error('Already consumed');
}
this.consumed = true;
const that = this;
const c = (fn) => {
return function () {
fn.apply(that, arguments);
};
};
ancestor(
this.ast as unknown as AcornNode,
{
Identifier: c(this.identifierVisitor),
VariablePattern: c(this.identifierVisitor),
MetaProperty: c(this.importMetaVisitor),
ImportExpression: c(this.importExpressionVisitor),
ImportDeclaration: c(this.importDeclarationVisitor),
ExportAllDeclaration: c(this.exportDeclarationVisitor),
ExportNamedDeclaration: c(this.exportDeclarationVisitor),
ExportDefaultDeclaration: c(this.exportDeclarationVisitor),
},
undefined,
this.state,
);
return {
imports: this.importInfos.map((v) => v.data),
generateCode: async () => {
const output = await this.generateCode();
(output as ModuleResource).exports = this.exportInfos.map(
(v) => v.name,
);
return output;
},
};
}
}