/
esModule.ts
406 lines (373 loc) Β· 13.2 KB
/
esModule.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
import { ImportSpecifier, init, parse } from '@alioth-org/es-module-lexer';
import type { JavaScriptManager } from '@garfish/loader';
import { Lock } from '@garfish/utils';
import {
isAbsolute,
transformUrl,
haveSourcemap,
createSourcemap,
} from '@garfish/utils';
import { interfaces } from '../interface';
import type { App } from './app';
const __GARFISH_ESM_ENV__ = '__GARFISH_ESM_ENV__';
export const getModuleImportProcessor = (code: string) => {
// split code into two segments
// avoid 'pause before potential out of memory crash' in chrome
// for super large string, it can improve performance as well
let finalCode = '';
let resetCode = code;
let prevCodeIndex = 0;
const rawImport = 'import';
const wrapImport = '_import_';
return (importAnalysis: ImportSpecifier, newModuleName = '') => {
const { d: importType, n: moduleName, s, e, ss, se } = importAnalysis;
const isDynamicImport = importType > -1;
if (isDynamicImport) {
// dynamic import
// replace 'import' keyword
const codeStart = ss - prevCodeIndex;
const codeEnd = se - prevCodeIndex;
const dynamicImportStatement = resetCode.slice(codeStart, codeEnd);
// append the code before import statement
finalCode += resetCode.slice(0, codeStart);
// append import statement
finalCode += dynamicImportStatement.replace(rawImport, wrapImport);
resetCode = resetCode.slice(codeEnd);
prevCodeIndex = se;
} else if (moduleName) {
// static import
// replace module name
const codeStart = s - prevCodeIndex;
const codeEnd = e - prevCodeIndex;
// append the code before import name
finalCode += resetCode.slice(0, codeStart);
// append new import name
finalCode += newModuleName;
resetCode = resetCode.slice(codeEnd);
prevCodeIndex = e;
}
return [finalCode, resetCode];
};
};
export const genShellExecutionCode = (
id: string | number,
sourceModuleName: string,
shellUrl: string,
) =>
`;import*as m$$_${id} from'${sourceModuleName}';import{u$$_ as u$$_${id}}from'${shellUrl}';u$$_${id}(m$$_${id})`;
interface ModuleCacheItem {
blobUrl?: string;
shellUrl?: string;
shellExecuted?: boolean;
analysis?: ReturnType<typeof parse>;
source: string;
}
export class ESModuleLoader {
private app: App;
private globalVarKey: string;
private moduleCache: Record<string, ModuleCacheItem> = {};
private lock = new Lock();
constructor(app: App) {
this.app = app;
this.globalVarKey = `${__GARFISH_ESM_ENV__}_${this.app.appId}`;
}
private execModuleCode(blobUrl: string) {
const result = (0, eval)(`import('${blobUrl}')`);
this.lock.release();
return result;
}
private createBlobUrl(code: string) {
return URL.createObjectURL(new Blob([code], { type: 'text/javascript' }));
}
private setBlobUrl(saveId: string, blobUrl: string) {
this.moduleCache[saveId].blobUrl = blobUrl;
}
private async fetchModuleResource(
lockId: number,
envVarStr: string,
noEntryEnvVarStr: string,
saveUrl: string,
requestUrl: string,
) {
const { resourceManager } =
await this.app.context.loader.load<JavaScriptManager>({
scope: this.app.name,
url: requestUrl,
});
// Maybe other resource
if (resourceManager) {
let sourcemap = '';
// eslint-disable-next-line prefer-const
let { url, scriptCode } = resourceManager;
if (!haveSourcemap(scriptCode)) {
sourcemap = await createSourcemap(scriptCode, requestUrl);
}
scriptCode = await this.analysisModule(
lockId,
scriptCode,
envVarStr,
noEntryEnvVarStr,
saveUrl,
url,
);
const blobUrl = this.createBlobUrl(
`import.meta.url='${url}';${this.app.isNoEntryScript(url) ? noEntryEnvVarStr : envVarStr}${scriptCode}\n${sourcemap}`,
);
this.setBlobUrl(saveUrl, blobUrl);
}
}
private getUrl(referUrl, targetUrl) {
return !isAbsolute(targetUrl) && referUrl
? transformUrl(referUrl, targetUrl)
: targetUrl;
}
private preloadStaticModuleAsync(
analysis: ReturnType<typeof parse>,
realUrl?: string | null,
) {
const [imports] = analysis;
for (let i = 0, length = imports.length; i < length; i++) {
const importAnalysis = imports[i];
const { d: importType, n: moduleName } = importAnalysis;
const isDynamicImport = importType > -1;
if (moduleName && !isDynamicImport) {
// async preload all static import module of current file
this.app.context.loader.load<JavaScriptManager>({
scope: this.app.name,
url: this.getUrl(realUrl, moduleName),
});
}
}
}
private async analysisModule(
lockId: number,
code: string,
envVarStr: string,
noEntryEnvVarStr: string,
baseUrl?: string,
realUrl?: string | null,
) {
// wait for the other task
await this.lock.wait(lockId);
// this is necessary for the Web Assembly boot
await init();
const analysis = parse(code, realUrl || '');
const thisModule: ModuleCacheItem = {
analysis,
source: code,
};
if (baseUrl) {
this.moduleCache[baseUrl] = thisModule;
}
let result = ['', code];
let shellExecutionCode = '';
const dynamicImport = `var _import_=(url)=>window.${this.globalVarKey}.import(url,'${baseUrl}','${realUrl}');`;
const processImportModule = getModuleImportProcessor(code);
const [imports] = analysis;
this.preloadStaticModuleAsync(analysis, realUrl);
for (let i = 0, length = imports.length; i < length; i++) {
const importAnalysis = imports[i];
const { d: importType, n: moduleName } = importAnalysis;
const isDynamicImport = importType > -1;
let saveUrl = moduleName || '';
let newModuleName = '';
if (moduleName && !isDynamicImport) {
// static import
const requestUrl = this.getUrl(realUrl, moduleName);
saveUrl = this.getUrl(baseUrl, moduleName);
let currentModule = this.moduleCache[saveUrl];
if (currentModule && !currentModule.blobUrl) {
// circular dependency
if (!currentModule.shellUrl) {
const [currentModuleImports, currentModuleExports] =
currentModule.analysis!;
// case 'export * from "xxx"'
// we can find this in the import statement
const wildcardExports = currentModuleImports.filter(
(importItem) => {
const statement = currentModule.source.substring(
importItem.ss,
importItem.se,
);
return /^export\s*\*\s*from\s*/.test(statement);
},
);
const wildcardExportStatements: string[] = [];
for (let j = 0, l = wildcardExports.length; j < l; j++) {
// find wildcard exports
const wildcardExport = wildcardExports[j];
const wildcardExportUrl = wildcardExport.n || '';
const wildcardExportSaveUrl = this.getUrl(
baseUrl,
wildcardExportUrl,
);
// fetch and analyze wildcard export module
await this.fetchModuleResource(
lockId,
envVarStr,
noEntryEnvVarStr,
wildcardExportSaveUrl,
this.getUrl(realUrl, wildcardExportUrl),
);
const wildcardModule = this.moduleCache[wildcardExportSaveUrl];
if (wildcardModule?.blobUrl) {
wildcardExportStatements.push(
`export * from '${wildcardModule.blobUrl}'`,
);
}
}
// create a shell code for delay assignment
currentModule.shellUrl = this.createBlobUrl(
`export function u$$_(m){${currentModuleExports
.map((exportSpecifier) =>
exportSpecifier.n === 'default' ? 'd$$_=m.default' : `${exportSpecifier.n}=m.${exportSpecifier.n}`,
)
.join(',')}}${currentModuleExports
.map((exportSpecifier) =>
exportSpecifier.n === 'default'
? 'let d$$_;export{d$$_ as default}'
: `export let ${exportSpecifier.n}`,
)
.join(';')}${
wildcardExportStatements.length
? `;${wildcardExportStatements.join(';')}`
: ''
}\n//# sourceURL=${saveUrl}?cycle`,
);
}
newModuleName = currentModule.shellUrl;
} else if (!currentModule) {
await this.fetchModuleResource(lockId, envVarStr, noEntryEnvVarStr, saveUrl, requestUrl);
currentModule = this.moduleCache[saveUrl];
const { blobUrl, shellUrl, shellExecuted } = currentModule;
newModuleName = blobUrl!;
if (shellUrl && !shellExecuted) {
// find circular shell, just execute it
shellExecutionCode += genShellExecutionCode(
i,
newModuleName,
shellUrl,
);
currentModule.shellExecuted = true;
}
} else {
newModuleName = currentModule.blobUrl!;
}
}
result = processImportModule(importAnalysis, newModuleName || moduleName);
}
// clear
thisModule.source = '';
delete thisModule.analysis;
return `${dynamicImport}${shellExecutionCode};${result.join('')}`;
}
destroy() {
for (const key in this.moduleCache) {
const { blobUrl, shellUrl } = this.moduleCache[key];
if (blobUrl) {
URL.revokeObjectURL(blobUrl);
}
if (shellUrl) {
URL.revokeObjectURL(shellUrl);
}
}
this.moduleCache = {};
this.lock.clear();
delete this.app.global[this.globalVarKey];
}
load(
code: string,
env: Record<string, any>,
url?: string,
options?: interfaces.ExecScriptOptions,
) {
return new Promise<void>(async (resolve) => {
if (url && this.moduleCache[url]) {
return resolve();
}
const genShellCodeWrapper = (
blobUrl: string,
shellUrl: string,
sourceUrl: string,
) => {
return `export * from '${blobUrl}'${genShellExecutionCode(
0,
blobUrl,
shellUrl,
)}\n//# sourceURL=${sourceUrl}?cycle`;
};
env = {
...env,
resolve,
import: async (moduleId: string, baseUrl: string, realUrl: string) => {
let saveUrl = moduleId;
let requestUrl = moduleId;
if (!isAbsolute(moduleId)) {
saveUrl = transformUrl(baseUrl, moduleId);
requestUrl = transformUrl(realUrl, moduleId);
}
let targetModule = this.moduleCache[saveUrl];
if (!targetModule?.blobUrl) {
await this.fetchModuleResource(this.lock.genId(), envVarStr, noEntryEnvVarStr, saveUrl, requestUrl);
targetModule = this.moduleCache[saveUrl];
}
if (
targetModule &&
targetModule.shellUrl &&
!targetModule.shellExecuted &&
targetModule.blobUrl
) {
// if the top level load is a shell code, we need to run its update function
return this.execModuleCode(
this.createBlobUrl(
genShellCodeWrapper(
targetModule.blobUrl,
targetModule.shellUrl,
saveUrl,
),
),
);
}
return this.execModuleCode(targetModule.blobUrl!);
},
};
const genEnvVarStr = (targetEnv: Record<string, any>, noEntry?: boolean) => {
const newEnv = { ...targetEnv };
if (noEntry) {
delete newEnv.exports;
delete newEnv.module;
}
return Object.keys(newEnv).reduce((prevCode, name) => {
if (name === 'resolve' || name === 'import') return prevCode;
return `${prevCode} var ${name} = window.${this.globalVarKey}.${name};`;
}, '');
};
const envVarStr = genEnvVarStr(env);
const noEntryEnvVarStr = genEnvVarStr(env, true);
let sourcemap = '';
if (!haveSourcemap(code) && url) {
sourcemap = await createSourcemap(
code,
options && options.isInline
? `index.html(inline.${this.app.scriptCount}.js)`
: url,
);
}
code = await this.analysisModule(this.lock.genId(), code, envVarStr, noEntryEnvVarStr, url, url);
code = `import.meta.url='${url}';${options?.noEntry ? noEntryEnvVarStr : envVarStr}${code}\n;window.${this.globalVarKey}.resolve();\n${sourcemap}`;
this.app.global[this.globalVarKey] = env;
let blobUrl = this.createBlobUrl(code);
if (options && !options.isInline && url) {
this.setBlobUrl(url, blobUrl);
}
const currentModule = this.moduleCache[url || ''];
if (currentModule?.shellUrl && !currentModule.shellExecuted) {
// if the top level load is a shell code, we need to run its update function
blobUrl = this.createBlobUrl(
genShellCodeWrapper(blobUrl, currentModule.shellUrl, url || ''),
);
}
this.execModuleCode(blobUrl);
});
}
}