-
Notifications
You must be signed in to change notification settings - Fork 23
/
PluginLoader.ts
454 lines (380 loc) · 14.3 KB
/
PluginLoader.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
import { v4 as uuidv4 } from 'uuid';
import type { AnyObject } from '@monorepo/common';
import { consoleLogger, ErrorWithCause } from '@monorepo/common';
import { identity, noop } from 'lodash';
import * as semver from 'semver';
import { DEFAULT_REMOTE_ENTRY_CALLBACK } from '../constants';
import type { ResourceFetch } from '../types/fetch';
import type { PluginLoadResult, PluginLoaderInterface } from '../types/loader';
import type { PluginManifest } from '../types/plugin';
import type { PluginEntryModule, PluginEntryCallback } from '../types/runtime';
import { basicFetch } from '../utils/basic-fetch';
import { settleAllPromises } from '../utils/promise';
import { injectScriptElement, getScriptElement } from '../utils/scripts';
import { resolveURL } from '../utils/url';
import { pluginManifestSchema } from '../yup-schemas';
declare global {
interface Window {
[name: string]: PluginEntryCallback;
}
}
type PluginLoadData = {
status: 'pending' | 'loaded' | 'failed';
manifest: PluginManifest;
entryCallbackFired?: boolean;
entryCallbackModule?: PluginEntryModule;
};
type DependencyResolution =
| {
success: true;
version: string;
}
| {
success: false;
};
export type PluginLoaderOptions = Partial<{
/**
* Control which plugins can be loaded.
*
* The `reload` argument indicates whether an already loaded plugin is to be reloaded.
*
* By default, all plugins are allowed to be loaded.
*/
canLoadPlugin: (manifest: PluginManifest, reload: boolean) => boolean;
/**
* Control whether the given plugin script can be reloaded when attempting to reload
* the associated plugin.
*
* By default, all plugin scripts are allowed to be reloaded.
*/
canReloadScript: (manifest: PluginManifest, scriptName: string) => boolean;
/**
* Customize the global callback function used by plugin entry scripts.
*
* This option applies only to plugins using the `callback` registration method.
*/
entryCallbackSettings: Partial<{
/**
* Control whether to register the callback function.
*
* Default value: `true`.
*/
registerCallback: boolean;
/**
* Name of the callback function.
*
* Default value: `__load_plugin_entry__`.
*/
name: string;
}>;
/**
* Custom resource fetch implementation.
*
* The custom implementation may specify any host application or environment specific
* request headers that are necessary to fetch plugin resources over the network.
*
* By default, a basic {@link fetch} API based implementation is used.
*/
fetchImpl: ResourceFetch;
/**
* Fixed resolutions used when processing plugin dependencies.
*
* There are two kinds of dependencies:
* - Regular dependencies, which refer to actual plugins that must be loaded with
* the right version prior to loading the plugin that depends on them.
* - Environment dependencies, which refer to any environment specific constants
* such as the host application's version, runtime platform version, etc.
*
* This option should be used to satisfy any environment specific dependencies
* supported by the host application.
*
* Default value: empty object.
*/
fixedPluginDependencyResolutions: Record<string, string>;
/**
* webpack share scope object for initializing `PluginEntryModule` containers.
*
* Host applications built with webpack should use dedicated webpack specific APIs
* such as `__webpack_init_sharing__` and `__webpack_share_scopes__` to initialize
* and access this object.
*
* Default value: empty object.
*
* @see https://webpack.js.org/concepts/module-federation/#dynamic-remote-containers
*/
sharedScope: AnyObject;
/**
* Transform the plugin manifest before loading the associated plugin.
*
* By default, no transformation is performed on the manifest.
*/
transformPluginManifest: (manifest: PluginManifest) => PluginManifest;
/**
* Provide access to the plugin's entry module.
*
* This option applies only to plugins using the `custom` registration method.
*
* For example, if a plugin was built with `var` library type (i.e. its entry module
* is assigned to a variable), you can access the entry module via `window[pluginName]`.
*
* By default, this function does nothing.
*/
getPluginEntryModule: (manifest: PluginManifest) => PluginEntryModule | void;
}>;
/**
* Loads plugin assets from remote sources.
*/
export class PluginLoader implements PluginLoaderInterface {
private readonly options: Required<PluginLoaderOptions>;
/** Plugins processed by this loader. */
private readonly plugins = new Map<string, PluginLoadData>();
private readonly loadListeners = new Set<VoidFunction>();
constructor(options: PluginLoaderOptions = {}) {
this.options = {
canLoadPlugin: options.canLoadPlugin ?? (() => true),
canReloadScript: options.canReloadScript ?? (() => true),
entryCallbackSettings: options.entryCallbackSettings ?? {},
fetchImpl: options.fetchImpl ?? basicFetch,
fixedPluginDependencyResolutions: options.fixedPluginDependencyResolutions ?? {},
sharedScope: options.sharedScope ?? {},
transformPluginManifest: options.transformPluginManifest ?? identity,
getPluginEntryModule: options.getPluginEntryModule ?? noop,
};
this.registerPluginEntryCallback();
}
private invokeLoadListeners() {
this.loadListeners.forEach((listener) => {
listener();
});
}
async loadPluginManifest(manifestURL: string) {
const response = await this.options.fetchImpl(manifestURL, { cache: 'no-cache' });
const manifest = JSON.parse(await response.text());
pluginManifestSchema.validateSync(manifest, { strict: true, abortEarly: false });
return manifest;
}
transformPluginManifest(manifest: PluginManifest) {
return this.options.transformPluginManifest(manifest);
}
/**
* @inheritDoc
*
* Plugins using the `callback` registration method are expected to call the global entry
* callback function created via {@link registerPluginEntryCallback} method, passing two
* arguments: plugin name and the entry module.
*
* For plugins using the `custom` registration method, the `getPluginEntryModule` function
* is expected to return the entry module of the given plugin. If not implemented properly,
* plugins using the `custom` registration method will fail to load.
*/
async loadPlugin(manifest: PluginManifest): Promise<PluginLoadResult> {
const pluginName = manifest.name;
const reload = this.plugins.has(pluginName);
const data: PluginLoadData = { status: 'pending', manifest };
let entryModule: PluginEntryModule;
if (manifest.registrationMethod === 'callback') {
data.entryCallbackFired = false;
}
this.plugins.set(pluginName, data);
if (!this.options.canLoadPlugin(manifest, reload)) {
data.status = 'failed';
this.invokeLoadListeners();
return {
success: false,
errorMessage: `Plugin ${pluginName} is not allowed to be ${reload ? 'reloaded' : 'loaded'}`,
};
}
try {
await this.resolvePluginDependencies(manifest);
} catch (e) {
data.status = 'failed';
this.invokeLoadListeners();
return {
success: false,
errorMessage: `Failed to resolve dependencies of plugin ${pluginName}`,
errorCause: e,
};
}
try {
await this.loadPluginScripts(manifest, data);
} catch (e) {
data.status = 'failed';
this.invokeLoadListeners();
return {
success: false,
errorMessage: `Failed to load scripts of plugin ${pluginName}`,
errorCause: e,
};
}
try {
entryModule = await this.initSharedModules(manifest, data);
} catch (e) {
data.status = 'failed';
this.invokeLoadListeners();
return {
success: false,
errorMessage: `Failed to initialize shared modules of plugin ${pluginName}`,
errorCause: e,
};
}
data.status = 'loaded';
this.invokeLoadListeners();
return { success: true, entryModule };
}
/**
* Load all scripts of the given plugin.
*/
private async loadPluginScripts(manifest: PluginManifest, data: PluginLoadData) {
const pluginName = manifest.name;
const [, rejectedReasons] = await settleAllPromises(
manifest.loadScripts.map((scriptName) => {
const scriptID = `${pluginName}/${scriptName}`;
const scriptElement = getScriptElement(scriptID);
if (scriptElement && !this.options.canReloadScript(manifest, scriptName)) {
return Promise.resolve();
}
if (scriptElement) {
scriptElement.remove();
}
const scriptURL = resolveURL(manifest.baseURL, scriptName, (url) => {
url.searchParams.set('cacheBuster', uuidv4());
return url;
});
return injectScriptElement(scriptURL, scriptID);
}),
);
if (rejectedReasons.length > 0) {
throw new ErrorWithCause('Detected errors while loading scripts', rejectedReasons);
}
if (manifest.registrationMethod === 'callback' && !data.entryCallbackFired) {
throw new Error('Scripts loaded without a plugin entry callback');
}
if (manifest.registrationMethod === 'callback' && !data.entryCallbackModule) {
throw new Error('Plugin entry callback called without an entry module');
}
}
/**
* Initialize the plugin with provided shared modules.
*/
private async initSharedModules(manifest: PluginManifest, data: PluginLoadData) {
const pluginName = manifest.name;
const entryModule =
manifest.registrationMethod === 'callback'
? data.entryCallbackModule
: this.options.getPluginEntryModule(manifest);
if (!entryModule) {
throw new Error(`Failed to retrieve entry module of plugin ${pluginName}`);
}
if (typeof entryModule.init !== 'function' || typeof entryModule.get !== 'function') {
throw new Error(`Entry module of plugin ${pluginName} does not meet expected contract`);
}
await Promise.resolve(entryModule.init(this.options.sharedScope));
return entryModule;
}
private getCurrentDependencyResolutions() {
const resolutions = new Map<string, DependencyResolution>();
Array.from(this.plugins.entries()).forEach(([pluginName, data]) => {
if (data.status === 'loaded') {
resolutions.set(pluginName, { success: true, version: data.manifest.version });
} else if (data.status === 'failed') {
resolutions.set(pluginName, { success: false });
}
});
Object.entries(this.options.fixedPluginDependencyResolutions).forEach(([depName, version]) => {
if (semver.valid(version)) {
resolutions.set(depName, { success: true, version });
}
});
return resolutions;
}
/**
* Resolve all dependencies of the given plugin.
*
* Fail early if there are any unsuccessful or unmet dependency resolutions.
*/
private resolvePluginDependencies(manifest: PluginManifest) {
return new Promise<void>((resolve, reject) => {
const pluginName = manifest.name;
const dependencies = manifest.dependencies ?? {};
const semverRangeOptions: semver.RangeOptions = { includePrerelease: true };
let isResolutionComplete = false;
let listener: VoidFunction;
const setResolutionComplete = () => {
isResolutionComplete = true;
this.loadListeners.delete(listener);
};
const tryResolveDependencies = () => {
const resolutions = this.getCurrentDependencyResolutions();
const resolutionErrors: string[] = [];
Object.entries(dependencies).forEach(([depName, versionRange]) => {
if (resolutions.has(depName)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const res = resolutions.get(depName)!;
if (res.success && !semver.satisfies(res.version, versionRange, semverRangeOptions)) {
resolutionErrors.push(
`Dependency ${depName} not met: required range ${versionRange}, resolved version ${res.version}`,
);
} else if (!res.success) {
resolutionErrors.push(`Dependency ${depName} could not be resolved successfully`);
}
}
});
if (resolutionErrors.length > 0) {
setResolutionComplete();
reject(new ErrorWithCause('Detected dependency resolution errors', resolutionErrors));
return;
}
const pendingDepNames = Object.keys(dependencies).filter(
(depName) => !resolutions.has(depName),
);
if (pendingDepNames.length === 0) {
setResolutionComplete();
resolve();
} else {
consoleLogger.info(
`Plugin ${pluginName} has ${pendingDepNames.length} pending dependency resolutions`,
);
}
};
tryResolveDependencies();
if (!isResolutionComplete) {
listener = tryResolveDependencies;
this.loadListeners.add(listener);
}
});
}
private createPluginEntryCallback(): PluginEntryCallback {
return (pluginName, entryModule) => {
if (!this.plugins.has(pluginName)) {
consoleLogger.warn(`Received entry callback for unknown plugin ${pluginName}`);
return;
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const data = this.plugins.get(pluginName)!;
if (data.entryCallbackFired) {
consoleLogger.warn(`Entry callback for plugin ${pluginName} called more than once`);
return;
}
data.entryCallbackFired = true;
data.entryCallbackModule = entryModule;
};
}
/**
* Register the global callback function used by plugin entry scripts.
*
* This must be called in order to load plugins using the `callback` registration method.
*/
registerPluginEntryCallback() {
const registerCallback = this.options.entryCallbackSettings.registerCallback ?? true;
const callbackName = this.options.entryCallbackSettings.name ?? DEFAULT_REMOTE_ENTRY_CALLBACK;
if (!registerCallback) {
consoleLogger.info(`Plugin entry callback ${callbackName} will not be registered`);
return;
}
if (typeof window[callbackName] === 'function') {
consoleLogger.warn(`Plugin entry callback ${callbackName} is already registered`);
return;
}
window[callbackName] = this.createPluginEntryCallback();
}
}