-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
596 lines (509 loc) · 22.9 KB
/
Copy pathindex.js
File metadata and controls
596 lines (509 loc) · 22.9 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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
// import events from "events";
// const { isBrowser } = require("@bmatusiak/rectify");
const isBrowserEnv = (typeof window != "undefined" && typeof window.document != "undefined") ? 1 : 0;
const events = require("events");
const EventEmitter = events.EventEmitter;
function objHas(obj, name) { return Object.prototype.hasOwnProperty.call(obj, name); }
// Something to call a plugin by in an error message. The fork dropped
// architect's packagePath, so the setup function's name is the next best thing
// -- except that the usual way to write a plugin leaves every one of them
// called "setup", "plugin" or "main", which names nothing. In that case say
// what it provides instead, which is how the rest of the config refers to it
// anyway.
var GENERIC = ["setup", "plugin", "main", "default", ""];
function describe(plugin, setup, provides, consumes, index) {
if (plugin && plugin.packagePath) { return plugin.packagePath; }
var name = (setup && setup.name) || (typeof plugin == "function" && plugin.name) || "";
if (GENERIC.indexOf(name) === -1) { return name; }
if (provides && provides.length) {
return "the plugin providing [" + provides.join(", ") + "]";
}
// Nothing provided means nothing to name it by, so say what it wanted.
if (consumes && consumes.length) {
return "the plugin at config index " + index + " consuming [" + consumes.join(", ") + "]";
}
return "the plugin at config index " + index;
}
// Read setup/provides/consumes off each config entry into our own record.
// Nothing is written back to the entry: an ES module namespace object is
// frozen, and assigning to one silently no-ops in sloppy mode, which used to
// leave `import * as plugin` reported as a plugin with no setup function.
function checkConfig(config) {
var normalized = config.map(function (plugin, index) {
var setup = null;
if (plugin && objHas(plugin, "setup")) { setup = plugin.setup; }
else if (typeof plugin == "function") { setup = plugin; }
else if (plugin && typeof plugin.default == "function") { setup = plugin.default; }
var provides = (plugin && objHas(plugin, "provides")) ? plugin.provides
: (setup && setup.provides);
var consumes = (plugin && objHas(plugin, "consumes")) ? plugin.consumes
: (setup && setup.consumes);
var name = describe(plugin, setup, provides, consumes, index);
if (typeof setup != "function") {
throw new Error("Plugin is missing the setup function: " + name);
}
if (!Array.isArray(provides)) {
throw new Error("Plugin is missing the provides array: " + name);
}
if (!Array.isArray(consumes)) {
throw new Error("Plugin is missing the consumes array: " + name);
}
var allowed = (plugin && objHas(plugin, "allowed")) ? plugin.allowed
: (objHas(setup, "allowed") ? setup.allowed : null);
return {
name: name,
plugin: plugin, // what the caller passed, emitted as "plugin"
setup: setup,
provides: provides,
consumes: consumes,
allowed: allowed,
config: (plugin && plugin.config) || setup.config || null
};
});
var providers = {};
normalized.forEach(function (entry) {
entry.provides.forEach(function (name) {
// Taking this name would replace on/emit/services and the
// environment flags for every plugin loaded after it.
if (name === "app") {
throw new Error("Plugin cannot provide \"app\", that service is Rectify's own: " + entry.name);
}
// Otherwise whichever registers last wins, and any plugin that
// consumed the name earlier is left holding the other one.
if (objHas(providers, name)) {
throw new Error("Service " + name + " is provided by two plugins: " + providers[name] + " and " + entry.name);
}
providers[name] = entry.name;
});
});
checkAllowed(normalized);
return checkCycles(normalized);
}
// Names as one comparable string, so order and repeats do not matter.
function asSet(names) {
return names.filter(function (name, i) {
return names.indexOf(name) === i;
}).sort().join(",");
}
// One group per plugin allowed in, each holding everything that plugin
// provides. A flat list of names is the one-plugin shorthand:
//
// allowed: ["ssh"] <- same as [["ssh"]]
// allowed: ["ssh", "terminal"] <- ONE plugin providing both
// allowed: [["ssh"], ["terminal"]] <- TWO plugins, one name each
//
// Mixing the two would make ["ssh", ["terminal"]] mean either, so it is an
// error rather than a guess.
function allowedGroups(allowed, name) {
if (!Array.isArray(allowed)) {
throw new Error("Plugin allowed must be an array of service names: " + name);
}
if (!allowed.length) { return []; }
var grouped = allowed.filter(Array.isArray).length;
if (grouped && grouped !== allowed.length) {
throw new Error("Plugin allowed must be either names or groups of names, not both: " + name);
}
var groups = grouped ? allowed : [allowed];
groups.forEach(function (group) {
if (!group.length) {
throw new Error("Plugin allowed has an empty group, which nothing can match: " + name);
}
group.forEach(function (service) {
if (typeof service != "string") {
throw new Error("Plugin allowed must contain service names: " + name);
}
});
});
return groups;
}
// `setup.allowed` limits who may consume what a plugin provides. Each group is
// one permitted plugin, described by everything it provides, and the match is
// exact: a plugin providing ["ssh", "sftp"] does not match the group ["ssh"],
// because a plugin may not widen its own surface and keep its access. A plugin
// that provides nothing is therefore never allowed, and allowed: [] means
// nobody. Leaving `allowed` off means anything may consume the service.
//
// This is a check on the config, not a wall around the service: a plugin that
// consumes "app" can still reach app.services. It says who is meant to depend
// on what, and fails the build when something else does.
function checkAllowed(normalized) {
normalized.forEach(function (entry) {
if (entry.allowed === null || entry.allowed === undefined) { return; }
var groups = allowedGroups(entry.allowed, entry.name);
if (!entry.provides.length) {
throw new Error("Plugin declares allowed but provides nothing to restrict: " + entry.name);
}
var permitted = groups.map(asSet);
var shapes = groups.map(function (group) {
return "[" + group.join(", ") + "]";
}).join(" or ");
normalized.forEach(function (consumer) {
if (consumer === entry) { return; }
entry.provides.forEach(function (service) {
if (consumer.consumes.indexOf(service) === -1) { return; }
if (consumer.provides.length && permitted.indexOf(asSet(consumer.provides)) !== -1) {
return;
}
throw new Error("Plugin " + entry.name + " allows " +
(groups.length ? "only " + shapes : "nothing") +
" to consume \"" + service + "\", but " + consumer.name +
" consumes it and provides " +
(consumer.provides.length ? "[" + consumer.provides.join(", ") + "]" : "nothing"));
});
});
});
}
function checkCycles(normalized) {
var plugins = normalized.map(function (entry, index) {
return {
name: entry.name,
provides: entry.provides.concat(),
consumes: entry.consumes.concat(),
i: index
};
});
var resolved = {
app: true
};
var changed = true;
var sorted = [];
while (plugins.length && changed) {
changed = false;
plugins.concat().forEach(function (plugin) {
var consumes = plugin.consumes.concat();
var resolvedAll = true;
for (var i = 0; i < consumes.length; i++) {
var service = consumes[i];
if (!resolved[service]) {
resolvedAll = false;
} else {
plugin.consumes.splice(plugin.consumes.indexOf(service), 1);
}
}
if (!resolvedAll)
return;
plugins.splice(plugins.indexOf(plugin), 1);
plugin.provides.forEach(function (service) {
resolved[service] = true;
});
sorted.push(normalized[plugin.i]);
changed = true;
});
}
if (plugins.length) {
var unresolved = {};
plugins.forEach(function (plugin) {
plugin.consumes.forEach(function (name) {
if (unresolved[name] === false)
return;
if (!unresolved[name])
unresolved[name] = [];
unresolved[name].push(plugin.name);
});
plugin.provides.forEach(function (name) {
unresolved[name] = false;
});
});
Object.keys(unresolved).forEach(function (name) {
if (unresolved[name] === false)
delete unresolved[name];
});
// A cycle leaves nothing in `unresolved` -- every plugin in it provides
// what the next one wants -- so name the stuck plugins either way.
var stuck = plugins.map(function (plugin) { return plugin.name; });
console.error("Could not resolve dependencies of these plugins:", stuck);
console.error("Resolved services:", Object.keys(resolved));
console.error("Missing services:", unresolved);
// Name what is missing in the error too, not only on the console: a
// caller that catches this gets the whole story, and a cycle -- where
// nothing is missing -- still names the plugins caught in it.
var wanted = Object.keys(unresolved).map(function (name) {
return name + " (wanted by " + unresolved[name].join(", ") + ")";
});
throw new Error(wanted.length
? "Could not resolve dependencies, nothing provides: " + wanted.join("; ")
: "Could not resolve dependencies of: " + stuck.join(", "));
}
return sorted;
}
class Rectify extends EventEmitter {
constructor(config, appArg) {
super();//setup emitter
var app = this;
app.config = config;
// Every plugin consuming "app" is expected to subscribe to the hub, so
// the default limit of 10 only produces a leak warning for a normal app.
app.setMaxListeners(0);
// The plugin whose setup() has not called register() yet, for when a
// load stops moving.
app.loading = null;
var services = app.services = {
app: {
EventEmitter: EventEmitter,
isBrowser: Rectify.isBrowser,
isElectron: Rectify.isElectron,
isNode: Rectify.isNode,
isFork: Rectify.isFork,
isNWJS: Rectify.isNWJS,
isWorker: Rectify.isWorker,
window: typeof window == "undefined" ? global : window,
on: function (name, callback) {
if (typeof (callback) == "function") callback = callback.bind(app);
app.on.apply(app, [name, callback]);
},
once: function (name, callback) {
if (typeof (callback) == "function") callback = callback.bind(app);
app.once.apply(app, [name, callback]);
},
emit: function () {
app.emit.apply(app, arguments);
},
get services() {
return app.services;
},
get plugins() {
return app.plugins;
}
}
};
if (appArg && typeof appArg == "object")
for (var i in appArg) {
services.app[i] = appArg[i];
}
else
services.app.arg = appArg;
// Check the config
var sortedPlugins = checkConfig(config);
// What the graph looks like, for anything that wants to ask -- which
// plugin wanted what, and who else is relying on it. Rectify works this
// out to sort the load and used to throw it away; only the container
// can answer it, so it belongs on the app service. Copies and frozen:
// it is a description, not a handle on anything.
app.plugins = Object.freeze(sortedPlugins.map(function (entry) {
return Object.freeze({
name: entry.name,
provides: Object.freeze(entry.provides.concat()),
consumes: Object.freeze(entry.consumes.concat())
});
}));
// Services whose plugin declared `allowed`. These are handed to the
// plugins that declared them in consumes -- which build() has already
// checked -- and kept out of `services`, so that a plugin consuming
// "app" cannot reach around the declaration and take one anyway.
var restricted = {};
function lookup(name) {
return objHas(restricted, name) ? restricted[name] : services[name];
}
var destructors = [];
// The load runs once and settles once, either on "ready" or on the
// first failure. `startPromise` is what every app.start() hands back.
var startPromise = null;
var settled = false;
var stopStallHint = null;
var destroying = null;
// Run what the plugins handed back to register() as `onDestroy`, in
// reverse order, so a consumer is undone before what it consumed.
// One that throws must not strand the rest.
app.destroy = function () {
if (!destroying) {
destroying = (async function () {
while (destructors.length) {
try {
await destructors.pop()();
} catch (err) {
report(err);
}
}
app.emit("destroy");
})();
}
return destroying;
};
app.start = function (event, callback) {
if (typeof event == "function") {
callback = event;
event = null;
}
if (event) app.$ = event;
if (callback) app.on("ready", callback);
// Loading is one-shot. A second call used to walk the already
// emptied plugin list and emit a second "ready" over an app that
// was already running; hand back the same promise instead.
if (!startPromise) {
// A caller listening for "error" has already said where
// failures go, so a start() they never awaited must not also
// crash the process as an unhandled rejection. Asked before
// loading, because a wholly synchronous load can report and
// remove that listener before we get to look.
var reported = app.listenerCount("error") > 0;
stopStallHint = watchForStall();
startPromise = new Promise(function (resolve, reject) {
loadNext(resolve, reject);
});
// Not a swallow: whoever awaits startPromise still gets it.
if (reported) {
startPromise.catch(function () { });
}
}
return startPromise;
};
// A plugin that forgets register() stalls the load with nothing said.
// If that leaves the event loop empty, node is about to exit having
// done nothing -- the one moment where naming the plugin is free.
function watchForStall() {
if (typeof process == "undefined" || typeof process.on != "function") {
return function () { };
}
function hint() {
if (settled) return;
console.error("Rectify: start() never finished" + (app.loading
? " -- plugin " + app.loading + " has not called register()"
: ""));
}
process.on("beforeExit", hint);
return function () { process.removeListener("beforeExit", hint); };
}
// Everything that ends the load goes through here, once.
function settle() {
settled = true;
app.loading = null;
if (stopStallHint) stopStallHint();
}
// An "error" with no listener throws, and that must not stop us
// rejecting with the real error.
function report(err) {
try {
app.emit("error", err);
} catch {
// nowhere to put it beyond the rejection
}
}
// Stop the load and unwind whatever did start, so a failure does not
// leave the app holding open what its plugins already opened. The
// error is reported once that is done, and only the first one is:
// what a stopped load does next is not worth a second error.
function fail(err, reject) {
if (settled) return;
settle();
Promise.resolve(app.destroy()).catch(function () { }).then(function () {
report(err);
reject(err);
});
}
// Sets up one plugin, then stops. What moves the load forward is that
// plugin calling register(), which comes back in here for the next one.
async function loadNext(resolve, reject) {
var entry = sortedPlugins.shift();
if (!entry) {
if (settled) return;
settle();
if (app.$) services.app.emit(app.$, app);
app.emit("ready", app);
return resolve(app);
}
app.loading = entry.name;
var imports = {};
entry.consumes.forEach(function (name) {
imports[name] = lookup(name);
});
var $config = {};
entry.provides.forEach(function (name) {
// Copied rather than merged in place -- this used to write the
// app-wide config into the plugin's own config object.
$config[name] = Object.assign(
{},
entry.config && entry.config[name],
config.config && config.config[name]
);
});
var registered = false;
try {
await entry.setup(imports, register, $config);
} catch (e) {
return fail(e, reject);
}
function register(err, provided) {
// Calling register() twice used to run the whole remaining
// chain a second time, ending in two "ready" events. Worth
// saying even once the app is up: it is a bug in the plugin.
if (registered) {
var again = new Error("Plugin called register() more than once: " + entry.name);
if (settled) return report(again);
return fail(again, reject);
}
registered = true;
if (err) { return fail(err, reject); }
provided = provided || {};
var isRestricted = entry.allowed !== null && entry.allowed !== undefined;
for (var i = 0; i < entry.provides.length; i++) {
var name = entry.provides[i];
if (!objHas(provided, name)) {
// Carrying on from here only hands the next plugin an
// undefined service and fails somewhere less obvious.
return fail(new Error("Plugin failed to provide " + name + " service: " + entry.name), reject);
}
if (isRestricted) {
// Not in `services`, and not announced either -- the
// "service" event would hand it to any listener.
restricted[name] = provided[name];
} else {
services[name] = provided[name];
app.emit("service", name, services[name]);
}
}
if (objHas(provided, "onDestroy"))
destructors.push(provided.onDestroy);
app.emit("plugin", entry.plugin);
// Returned so a plugin can `await register(...)` and know the
// rest of the app came up.
return loadNext(resolve, reject);
}
}
}
}
if (typeof process !== "undefined") {
const browserLike = (process && process.__nwjs) || (process && process.versions && process.versions.electron);
Rectify.isBrowser = (typeof window != "undefined" && typeof window.document != "undefined") ? 1 : 0;
Rectify.isNode = (typeof process != "undefined" && !browserLike ? 1 : 0);
Rectify.isFork = (typeof process != "undefined" && process.send ? 1 : 0);
Rectify.isNWJS = (typeof process != "undefined" && process.__nwjs ? 1 : 0);
Rectify.isElectron = (typeof process != "undefined" && process.versions && process.versions.electron ? 1 : 0);
Rectify.isWorker = (typeof WorkerGlobalScope != "undefined" && globalThis instanceof WorkerGlobalScope) ? 1 : 0;
} else {
Rectify.isBrowser = isBrowserEnv;
Rectify.isNode = 0;
Rectify.isFork = 0;
Rectify.isNWJS = 0;
Rectify.isElectron = 0;
Rectify.isWorker = (typeof WorkerGlobalScope != "undefined" && globalThis instanceof WorkerGlobalScope) ? 1 : 0;
}
Rectify.build = function (config, callback) {
var app;
var isCallback = typeof callback == "function";
try {
app = new Rectify(config, !isCallback && callback && typeof callback == "object" ? callback : null);
} catch (err) {
if (!isCallback) throw err;
return callback(err, app);
}
// Listening for "error" here is also what tells start() that this caller
// has an error channel and need not crash on an unawaited rejection.
if (isCallback) {
app.on("error", done);
app.on("ready", onReady);
}
return app;
function onReady() {
done();
}
function done(err) {
app.removeListener("error", done);
app.removeListener("ready", onReady);
// A failed load has already unwound itself by the time it is reported.
if (err) console.error(err);
callback(err, app);
}
};
// Shipped with Rectify, but loaded like any other plugin -- see plugin-base.js.
Rectify.PluginBase = require("./plugin-base.js");
module.exports = Rectify;