forked from rancher/dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugins.js
More file actions
442 lines (352 loc) · 13.2 KB
/
Copy pathplugins.js
File metadata and controls
442 lines (352 loc) · 13.2 KB
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
import { productsLoaded } from '@shell/store/type-map';
import { clearModelCache } from '@shell/plugins/dashboard-store/model-loader';
import { Plugin } from './plugin';
import { PluginRoutes } from './plugin-routes';
import { UI_PLUGIN_BASE_URL } from '@shell/config/uiplugins';
import { ExtensionPoint, RegistrationType } from './types';
import { createBrand } from './plugin-brand';
const MODEL_TYPE = 'models';
export default function(context, inject, vueApp) {
const {
app, store, $axios, redirect
} = context;
const dynamic = {};
const validators = {};
let _lastLoaded = 0;
// Track which plugin loaded what, so we can unload stuff
const plugins = {};
const pluginRoutes = new PluginRoutes(app.router);
const uiConfig = {};
for (const ep in ExtensionPoint) {
uiConfig[ExtensionPoint[ep]] = {};
}
inject(
'plugin',
{
// Plugins should not use these - but we will pass them in for now as a 2nd argument
// in case there are use cases not covered that require direct access - we may remove access later
internal() {
const internal = {
app,
store,
$axios,
redirect,
plugins: this
};
return internal;
},
// Load a plugin from a UI package
loadPluginAsync(plugin) {
const { name, version } = plugin;
const id = `${ name }-${ version }`;
let url;
if (plugin?.metadata?.direct === 'true') {
url = plugin.endpoint;
} else {
// See if the plugin has a main metadata property set
const main = plugin?.metadata?.main || `${ id }.umd.min.js`;
url = `${ UI_PLUGIN_BASE_URL }/${ name }/${ version }/plugin/${ main }`;
}
return this.loadAsync(id, url);
},
// Load a plugin from a UI package
loadAsync(id, mainFile) {
return new Promise((resolve, reject) => {
// The plugin is already loaded so we should avoid loading it again.
// This will primarily affect plugins that load prior to authentication and we attempt to load again after authentication.
if (document.getElementById(id)) {
return resolve();
}
const moduleUrl = mainFile;
const element = document.createElement('script');
element.src = moduleUrl;
element.type = 'text/javascript';
element.async = true;
element.id = id;
element.dataset.purpose = 'extension';
// id is `<product>-<version>`.
const oldPlugin = Object.values(plugins).find((p) => id.startsWith(p.name));
let removed = Promise.resolve();
if (oldPlugin) {
// Uninstall existing plugin if there is one. This ensures that last loaded plugin is not always used
// (nav harv1-->harv2-->harv1 and harv2 would be shown)
removed = this.removePlugin(oldPlugin.name).then(() => {
delete window[oldPlugin.id];
delete plugins[oldPlugin.id];
const oldElement = document.getElementById(oldPlugin.id);
oldElement.parentElement.removeChild(oldElement);
});
}
removed.then(() => {
element.onload = () => {
if (!window[id]) {
return reject(new Error('Could not load plugin code'));
}
// Update the timestamp that new plugins were loaded - may be needed
// to update caches when new plugins are loaded
_lastLoaded = new Date().getTime();
// name is the name of the plugin, including the version number
const plugin = new Plugin(id);
plugins[id] = plugin;
// Initialize the plugin
window[id].default(plugin, this.internal());
// Uninstall existing plugin if there is one
this.removePlugin(plugin.name); // Removing this causes the plugin to not load on refresh
// Load all of the types etc from the plugin
this.applyPlugin(plugin);
// Add the plugin to the store
store.dispatch('uiplugins/addPlugin', plugin);
resolve();
};
element.onerror = (e) => {
element.parentElement.removeChild(element);
// Massage the error into something useful
const errorMessage = `Failed to load script from '${ e.target.src }'`;
console.error(errorMessage, e); // eslint-disable-line no-console
reject(new Error(errorMessage)); // This is more useful where it's used
};
document.head.appendChild(element);
}).catch((e) => {
const errorMessage = `Failed to unload old plugin${ oldPlugin?.id }`;
console.error(errorMessage, e); // eslint-disable-line no-console
reject(new Error(errorMessage)); // This is more useful where it's used
});
});
},
// Used by the dynamic loader when a plugin is included in the build
initPlugin(id, module) {
const plugin = new Plugin(id);
// Mark the plugin as being built-in
plugin.builtin = true;
plugins[id] = plugin;
// Initialize the plugin
const p = module;
try {
p.default(plugin, this.internal());
// Uninstall existing product if there is one
this.removePlugin(plugin.name);
// Load all of the types etc from the plugin
this.applyPlugin(plugin);
// Add the plugin to the store
store.dispatch('uiplugins/addPlugin', plugin);
} catch (e) {
console.error(`Error loading plugin ${ plugin.name }`); // eslint-disable-line no-console
console.error(e); // eslint-disable-line no-console
}
},
async logout() {
const all = Object.values(plugins);
for (let i = 0; i < all.length; i++) {
const plugin = all[i];
if (plugin.builtin) {
continue;
}
try {
await this.removePlugin(plugin.name);
} catch (e) {
console.error('Error removing plugin', e); // eslint-disable-line no-console
}
delete plugins[plugin.id];
}
},
// Remove the plugin
async removePlugin(name) {
const plugin = Object.values(plugins).find((p) => p.name === name);
if (!plugin) {
return;
}
const promises = [];
plugin.productNames.forEach((product) => {
promises.push(store.dispatch('type-map/removeProduct', { product, plugin }));
});
// Remove all of the types
Object.keys(plugin.types).forEach((typ) => {
Object.keys(plugin.types[typ]).forEach((name) => {
this.unregister(typ, name);
if (typ === MODEL_TYPE) {
clearModelCache(name);
}
});
});
// Remove locales
plugin.locales.forEach((localeObj) => {
promises.push(store.dispatch('i18n/removeLocale', localeObj));
});
if (plugin.types.models) {
// Ask the Steve stores to forget any data it has for models that we are removing
promises.push(...this.removeTypeFromStore(store, 'rancher', Object.keys(plugin.types.models)));
promises.push(...this.removeTypeFromStore(store, 'management', Object.keys(plugin.types.models)));
}
// Call plugin uninstall hooks
plugin.uninstallHooks.forEach((fn) => fn(plugin, this.internal()));
// Remove the plugin itself
promises.push( store.dispatch('uiplugins/removePlugin', name));
// Unregister vuex stores
plugin.stores.forEach((pStore) => pStore.unregister(store));
// Remove validators
Object.keys(plugin.validators).forEach((key) => {
delete validators[key];
});
await Promise.all(promises);
// Update last load since we removed a plugin
_lastLoaded = new Date().getTime();
},
removeTypeFromStore(store, storeName, types) {
return (types || []).map((type) => store.commit(`${ storeName }/forgetType`, type));
},
// Apply the plugin based on its metadata
applyPlugin(plugin) {
// Types
Object.keys(plugin.types).forEach((typ) => {
Object.keys(plugin.types[typ]).forEach((name) => {
this.register(typ, name, plugin.types[typ][name]);
});
});
// UI Configuration - copy UI config from a plugin into the global uiConfig object
Object.keys(plugin.uiConfig).forEach((actionType) => {
Object.keys(plugin.uiConfig[actionType]).forEach((actionLocation) => {
plugin.uiConfig[actionType][actionLocation].forEach((action) => {
if (!uiConfig[actionType][actionLocation]) {
uiConfig[actionType][actionLocation] = [];
}
uiConfig[actionType][actionLocation].push(action);
});
});
});
// l10n
Object.keys(plugin.l10n).forEach((name) => {
plugin.l10n[name].forEach((fn) => {
this.register('l10n', name, fn);
});
});
// Initialize the product if the store is ready
if (productsLoaded()) {
this.loadProducts([plugin]);
}
// Register vuex stores
plugin.stores.forEach((pStore) => pStore.register()(store));
// Locales
plugin.locales.forEach((localeObj) => {
store.dispatch('i18n/addLocale', localeObj);
});
// Brand
if (plugin.brands.length) {
plugin.brands.forEach((brand) => {
createBrand(brand, (name, fn) => this.register('image', name, fn));
});
}
// Brand
if (plugin.settings.length) {
plugin.settings.forEach((setting) => {
// Check if the setting has already been set by another extension
if (this.getDynamic(RegistrationType.SETTING, setting.name)) {
console.warning(`Setting ${ setting.name } has already been set by another extension - ignoring`); // eslint-disable-line no-console
} else {
this.register(RegistrationType.SETTING, setting.name, {
value: setting.value,
extension: plugin.name,
override: setting.override
});
}
});
}
// Routes
pluginRoutes.addRoutes(plugin, plugin.routes);
// Validators
Object.keys(plugin.validators).forEach((key) => {
validators[key] = plugin.validators[key];
});
},
/**
* Register 'something' that can be dynamically loaded - e.g. model, edit, create, list, i18n
* @param {String} type type of thing to register, e.g. 'edit'
* @param {String} name unique name of 'something'
* @param {Function} fn function that dynamically loads the module for the thing being registered
*/
register(type, name, fn) {
if (!dynamic[type]) {
dynamic[type] = {};
}
// Accumulate l10n resources rather than replace
if (type === 'l10n') {
if (!dynamic[type][name]) {
dynamic[type][name] = [];
}
dynamic[type][name].push(fn);
} else {
dynamic[type][name] = fn;
}
},
unregister(type, name, fn) {
if (type === 'l10n') {
if (dynamic[type]?.[name]) {
const index = dynamic[type][name].find((func) => func === fn);
if (index !== -1) {
dynamic[type][name].splice(index, 1);
}
}
} else if (dynamic[type]?.[name]) {
delete dynamic[type][name];
}
},
// For debugging
getAll() {
return dynamic;
},
getPlugins() {
return plugins;
},
getDynamic(typeName, name) {
return dynamic[typeName]?.[name];
},
getValidator(name) {
return validators[name];
},
/**
* Return the UI configuration for the given type and location
*/
getUIConfig(type, uiArea) {
return uiConfig[type][uiArea] || [];
},
/**
* Returns all UI Configuration (useful for debugging)
*/
getAllUIConfig() {
return uiConfig;
},
// Timestamp that a UI package was last loaded
// Typically used to invalidate caches (e.g. i18n) when new plugins are loaded
get lastLoad() {
return _lastLoaded;
},
listDynamic(typeName) {
if (!dynamic[typeName]) {
return [];
}
return Object.keys(dynamic[typeName]);
},
// Get the products provided by plugins
get products() {
return dynamic.products || [];
},
// Load all of the products provided by plugins
loadProducts(loadPlugins) {
if (!loadPlugins) {
loadPlugins = Object.values(plugins);
}
loadPlugins.forEach((plugin) => {
if (plugin.products) {
plugin.products.forEach(async(p) => {
const impl = await p;
if (impl.init) {
impl.init(plugin, store);
}
});
}
});
},
},
context,
vueApp
);
}