-
Notifications
You must be signed in to change notification settings - Fork 31.7k
/
Copy pathamdX.ts
237 lines (205 loc) · 8.31 KB
/
amdX.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { AppResourcePath, FileAccess, nodeModulesAsarPath, nodeModulesPath, Schemas, VSCODE_AUTHORITY } from './base/common/network.js';
import * as platform from './base/common/platform.js';
import { IProductConfiguration } from './base/common/product.js';
import { URI } from './base/common/uri.js';
import { generateUuid } from './base/common/uuid.js';
export const canASAR = false; // TODO@esm: ASAR disabled in ESM
class DefineCall {
constructor(
public readonly id: string | null | undefined,
public readonly dependencies: string[] | null | undefined,
public readonly callback: any
) { }
}
enum AMDModuleImporterState {
Uninitialized = 1,
InitializedInternal,
InitializedExternal
}
class AMDModuleImporter {
public static INSTANCE = new AMDModuleImporter();
private readonly _isWebWorker = (typeof self === 'object' && self.constructor && self.constructor.name === 'DedicatedWorkerGlobalScope');
private readonly _isRenderer = typeof document === 'object';
private readonly _defineCalls: DefineCall[] = [];
private _state = AMDModuleImporterState.Uninitialized;
private _amdPolicy: Pick<TrustedTypePolicy<{
createScriptURL(value: string): string;
}>, 'name' | 'createScriptURL'> | undefined;
constructor() { }
private _initialize(): void {
if (this._state === AMDModuleImporterState.Uninitialized) {
if ((globalThis as any).define) {
this._state = AMDModuleImporterState.InitializedExternal;
return;
}
} else {
return;
}
this._state = AMDModuleImporterState.InitializedInternal;
(globalThis as any).define = (id: any, dependencies: any, callback: any) => {
if (typeof id !== 'string') {
callback = dependencies;
dependencies = id;
id = null;
}
if (typeof dependencies !== 'object' || !Array.isArray(dependencies)) {
callback = dependencies;
dependencies = null;
}
// if (!dependencies) {
// dependencies = ['require', 'exports', 'module'];
// }
this._defineCalls.push(new DefineCall(id, dependencies, callback));
};
(globalThis as any).define.amd = true;
if (this._isRenderer) {
this._amdPolicy = (globalThis as any)._VSCODE_WEB_PACKAGE_TTP ?? window.trustedTypes?.createPolicy('amdLoader', {
createScriptURL(value) {
if (value.startsWith(window.location.origin)) {
return value;
}
if (value.startsWith(`${Schemas.vscodeFileResource}://${VSCODE_AUTHORITY}`)) {
return value;
}
throw new Error(`[trusted_script_src] Invalid script url: ${value}`);
}
});
} else if (this._isWebWorker) {
this._amdPolicy = (globalThis as any)._VSCODE_WEB_PACKAGE_TTP ?? (globalThis as any).trustedTypes?.createPolicy('amdLoader', {
createScriptURL(value: string) {
return value;
}
});
}
}
public async load<T>(scriptSrc: string): Promise<T> {
this._initialize();
if (this._state === AMDModuleImporterState.InitializedExternal) {
return new Promise<T>(resolve => {
const tmpModuleId = generateUuid();
(globalThis as any).define(tmpModuleId, [scriptSrc], function (moduleResult: T) {
resolve(moduleResult);
});
});
}
const defineCall = await (this._isWebWorker ? this._workerLoadScript(scriptSrc) : this._isRenderer ? this._rendererLoadScript(scriptSrc) : this._nodeJSLoadScript(scriptSrc));
if (!defineCall) {
console.warn(`Did not receive a define call from script ${scriptSrc}`);
return <T>undefined;
}
// TODO@esm require, module
const exports = {};
const dependencyObjs: any[] = [];
const dependencyModules: string[] = [];
if (Array.isArray(defineCall.dependencies)) {
for (const mod of defineCall.dependencies) {
if (mod === 'exports') {
dependencyObjs.push(exports);
} else {
dependencyModules.push(mod);
}
}
}
if (dependencyModules.length > 0) {
throw new Error(`Cannot resolve dependencies for script ${scriptSrc}. The dependencies are: ${dependencyModules.join(', ')}`);
}
if (typeof defineCall.callback === 'function') {
return defineCall.callback(...dependencyObjs) ?? exports;
} else {
return defineCall.callback;
}
}
private _rendererLoadScript(scriptSrc: string): Promise<DefineCall | undefined> {
return new Promise<DefineCall | undefined>((resolve, reject) => {
const scriptElement = document.createElement('script');
scriptElement.setAttribute('async', 'async');
scriptElement.setAttribute('type', 'text/javascript');
const unbind = () => {
scriptElement.removeEventListener('load', loadEventListener);
scriptElement.removeEventListener('error', errorEventListener);
};
const loadEventListener = (e: any) => {
unbind();
resolve(this._defineCalls.pop());
};
const errorEventListener = (e: any) => {
unbind();
reject(e);
};
scriptElement.addEventListener('load', loadEventListener);
scriptElement.addEventListener('error', errorEventListener);
if (this._amdPolicy) {
scriptSrc = this._amdPolicy.createScriptURL(scriptSrc) as any as string;
}
scriptElement.setAttribute('src', scriptSrc);
window.document.getElementsByTagName('head')[0].appendChild(scriptElement);
});
}
private async _workerLoadScript(scriptSrc: string): Promise<DefineCall | undefined> {
if (this._amdPolicy) {
scriptSrc = this._amdPolicy.createScriptURL(scriptSrc) as any as string;
}
await import(scriptSrc);
return this._defineCalls.pop();
}
private async _nodeJSLoadScript(scriptSrc: string): Promise<DefineCall | undefined> {
try {
const fs = (await import(`${'fs'}`)).default;
const vm = (await import(`${'vm'}`)).default;
const module = (await import(`${'module'}`)).default;
const filePath = URI.parse(scriptSrc).fsPath;
const content = fs.readFileSync(filePath).toString();
const scriptSource = module.wrap(content.replace(/^#!.*/, ''));
const script = new vm.Script(scriptSource);
const compileWrapper = script.runInThisContext();
compileWrapper.apply();
return this._defineCalls.pop();
} catch (error) {
throw error;
}
}
}
const cache = new Map<string, Promise<any>>();
/**
* Utility for importing an AMD node module. This util supports AMD and ESM contexts and should be used while the ESM adoption
* is on its way.
*
* e.g. pass in `vscode-textmate/release/main.js`
*/
export async function importAMDNodeModule<T>(nodeModuleName: string, pathInsideNodeModule: string, isBuilt?: boolean): Promise<T> {
if (isBuilt === undefined) {
const product = globalThis._VSCODE_PRODUCT_JSON as unknown as IProductConfiguration;
isBuilt = Boolean((product ?? (globalThis as any).vscode?.context?.configuration()?.product)?.commit);
}
const nodeModulePath = pathInsideNodeModule ? `${nodeModuleName}/${pathInsideNodeModule}` : nodeModuleName;
if (cache.has(nodeModulePath)) {
return cache.get(nodeModulePath)!;
}
let scriptSrc: string;
if (/^\w[\w\d+.-]*:\/\//.test(nodeModulePath)) {
// looks like a URL
// bit of a special case for: src/vs/workbench/services/languageDetection/browser/languageDetectionWebWorker.ts
scriptSrc = nodeModulePath;
} else {
const useASAR = (canASAR && isBuilt && !platform.isWeb);
const actualNodeModulesPath = (useASAR ? nodeModulesAsarPath : nodeModulesPath);
const resourcePath: AppResourcePath = `${actualNodeModulesPath}/${nodeModulePath}`;
scriptSrc = FileAccess.asBrowserUri(resourcePath).toString(true);
}
const result = AMDModuleImporter.INSTANCE.load<T>(scriptSrc);
cache.set(nodeModulePath, result);
return result;
}
export function resolveAmdNodeModulePath(nodeModuleName: string, pathInsideNodeModule: string): string {
const product = globalThis._VSCODE_PRODUCT_JSON as unknown as IProductConfiguration;
const isBuilt = Boolean((product ?? (globalThis as any).vscode?.context?.configuration()?.product)?.commit);
const useASAR = (canASAR && isBuilt && !platform.isWeb);
const nodeModulePath = `${nodeModuleName}/${pathInsideNodeModule}`;
const actualNodeModulesPath = (useASAR ? nodeModulesAsarPath : nodeModulesPath);
const resourcePath: AppResourcePath = `${actualNodeModulesPath}/${nodeModulePath}`;
return FileAccess.asBrowserUri(resourcePath).toString(true);
}