-
Notifications
You must be signed in to change notification settings - Fork 593
/
plugin-loader.ts
234 lines (193 loc) · 6.47 KB
/
plugin-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
/* eslint-disable no-console */
import * as _ from 'lodash';
import * as semver from 'semver';
import { PluginStore } from '@console/plugin-sdk/src/store';
import { getRandomChars } from '@console/shared/src/utils/utils';
import {
AnyConsolePluginManifest,
StandardConsolePluginManifest,
isStandardPluginManifest,
} from '../build-types';
import { resolveEncodedCodeRefs } from '../coderefs/coderef-resolver';
import { initSharedPluginModules } from '../shared-modules-init';
import { RemoteEntryModule } from '../types';
import { ErrorWithCause } from '../utils/error/custom-error';
import { settleAllPromises } from '../utils/promise';
import { resolveURL } from '../utils/url';
import { resolvePluginDependencies } from './plugin-dependencies';
import { fetchPluginManifest } from './plugin-manifest';
import { getPluginID } from './plugin-utils';
type ConsolePluginData = {
/** The manifest containing plugin metadata and extension declarations. */
manifest: StandardConsolePluginManifest;
/** Indicates if `window.loadPluginEntry` callback has been fired for this plugin. */
entryCallbackFired: boolean;
};
const pluginMap = new Map<string, ConsolePluginData>();
export const getScriptElementID = (pluginName: string, scriptName: string) =>
`${pluginName}/${scriptName}`;
const injectScriptElement = (url: string, id: string) =>
new Promise<void>((resolve, reject) => {
const script = document.createElement('script');
script.async = true;
script.src = url;
script.id = id;
script.onload = () => {
resolve();
};
script.onerror = (event) => {
reject(event);
};
document.head.appendChild(script);
});
export const loadDynamicPlugin = (manifest: StandardConsolePluginManifest) =>
new Promise<string>((resolve, reject) => {
const pluginID = getPluginID(manifest);
const existingPluginData = Array.from(pluginMap.values()).find(
(p) => p.manifest.name === manifest.name,
);
if (existingPluginData) {
const existingPluginID = getPluginID(existingPluginData.manifest);
reject(new Error(`Attempt to reload plugin ${existingPluginID} with ${pluginID}`));
return;
}
if (manifest.registrationMethod !== 'callback') {
reject(new Error(`Plugin ${pluginID} does not use callback registration method`));
return;
}
pluginMap.set(pluginID, {
manifest,
entryCallbackFired: false,
});
console.info(`Loading scripts of plugin ${pluginID}`);
// eslint-disable-next-line promise/catch-or-return
settleAllPromises(
manifest.loadScripts.map((scriptName) => {
const scriptID = getScriptElementID(manifest.name, scriptName);
const scriptURL = resolveURL(manifest.baseURL, scriptName, (url) => {
url.search = `?cacheBuster=${getRandomChars()}`;
return url;
});
console.info(`Loading plugin script from ${scriptURL}`);
return injectScriptElement(scriptURL, scriptID);
}),
).then(([, rejectedReasons]) => {
if (rejectedReasons.length > 0) {
reject(
new ErrorWithCause(`Detected errors while loading plugin entry scripts`, rejectedReasons),
);
return;
}
if (!pluginMap.get(pluginID).entryCallbackFired) {
reject(new Error(`Scripts of plugin ${pluginID} loaded without entry callback`));
return;
}
resolve(pluginID);
});
});
export const getPluginEntryCallback = (
pluginStore: PluginStore,
initSharedPluginModulesCallback: typeof initSharedPluginModules,
resolveEncodedCodeRefsCallback: typeof resolveEncodedCodeRefs,
) => (pluginID: string, entryModule: RemoteEntryModule) => {
if (!pluginMap.has(pluginID)) {
console.error(`Received callback for unknown plugin ${pluginID}`);
return;
}
const pluginData = pluginMap.get(pluginID);
if (pluginData.entryCallbackFired) {
console.error(`Received callback for already loaded plugin ${pluginID}`);
return;
}
pluginData.entryCallbackFired = true;
try {
initSharedPluginModulesCallback(entryModule);
} catch (error) {
console.error(`Failed to initialize shared modules for plugin ${pluginID}`, error);
return;
}
const resolvedExtensions = resolveEncodedCodeRefsCallback(
pluginData.manifest.extensions,
entryModule,
pluginID,
() => {
console.error(`Code reference resolution failed for plugin ${pluginID}`);
},
);
pluginStore.addDynamicPlugin(pluginID, pluginData.manifest, resolvedExtensions);
};
export const registerPluginEntryCallback = (pluginStore: PluginStore) => {
window.loadPluginEntry = getPluginEntryCallback(
pluginStore,
initSharedPluginModules,
resolveEncodedCodeRefs,
);
};
export const adaptPluginManifest = (
manifest: AnyConsolePluginManifest,
baseURL: string,
): StandardConsolePluginManifest => {
if (isStandardPluginManifest(manifest)) {
return manifest;
}
const {
name,
version,
extensions,
dependencies,
displayName,
description,
disableStaticPlugins,
} = manifest;
return {
name,
version,
extensions,
dependencies,
customProperties: { console: { displayName, description, disableStaticPlugins } },
baseURL,
loadScripts: ['plugin-entry.js'],
registrationMethod: 'callback',
};
};
export const loadAndEnablePlugin = async (
pluginName: string,
pluginStore: PluginStore,
onError: (errorMessage: string, errorCause?: unknown) => void = _.noop,
) => {
const baseURL = `${window.SERVER_FLAGS.basePath}api/plugins/${pluginName}/`;
let manifest: StandardConsolePluginManifest;
try {
manifest = adaptPluginManifest(await fetchPluginManifest(baseURL), baseURL);
} catch (e) {
onError(`Failed to get a valid plugin manifest from ${baseURL}`, e);
return;
}
try {
await resolvePluginDependencies(
manifest,
semver.valid(window.SERVER_FLAGS.releaseVersion),
pluginStore.getAllowedDynamicPluginNames(),
);
} catch (e) {
onError(`Failed to resolve dependencies of plugin ${pluginName}`, e);
return;
}
try {
await loadDynamicPlugin(manifest);
} catch (e) {
onError(`Failed to load scripts of plugin ${pluginName}`, e);
return;
}
pluginStore.setDynamicPluginEnabled(getPluginID(manifest), true);
};
export const getStateForTestPurposes = () => ({
pluginMap,
});
export const resetStateAndEnvForTestPurposes = () => {
pluginMap.clear();
Array.from(document.scripts).forEach((element) => {
element.remove();
});
window.loadPluginEntry = undefined;
};