forked from aurelia/framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathframework-configuration.js
486 lines (423 loc) · 16.2 KB
/
framework-configuration.js
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
import * as TheLogManager from 'aurelia-logging';
import {ViewEngine, HtmlBehaviorResource} from 'aurelia-templating';
import {join} from 'aurelia-path';
import {Container} from 'aurelia-dependency-injection';
const logger = TheLogManager.getLogger('aurelia');
const extPattern = /\.[^/.]+$/;
function runTasks(config: FrameworkConfiguration, tasks) {
let current;
let next = () => {
current = tasks.shift();
if (current) {
return Promise.resolve(current(config)).then(next);
}
return Promise.resolve();
};
return next();
}
interface FrameworkPluginInfo {
moduleId?: string;
resourcesRelativeTo?: string[];
configure?: (config: FrameworkConfiguration, pluginConfig?: any) => any;
config?: any;
}
function loadPlugin(fwConfig: FrameworkConfiguration, loader: Loader, info: FrameworkPluginInfo) {
logger.debug(`Loading plugin ${info.moduleId}.`);
if (typeof info.moduleId === 'string') {
fwConfig.resourcesRelativeTo = info.resourcesRelativeTo;
let id = info.moduleId; // General plugins installed/configured by the end user.
if (info.resourcesRelativeTo.length > 1 ) { // In case of bootstrapper installed plugins like `aurelia-templating-resources` or `aurelia-history-browser`.
return loader.normalize(info.moduleId, info.resourcesRelativeTo[1])
.then(normalizedId => _loadPlugin(normalizedId));
}
return _loadPlugin(id);
} else if (typeof info.configure === 'function') {
if (fwConfig.configuredPlugins.indexOf(info.configure) !== -1) {
return Promise.resolve();
}
fwConfig.configuredPlugins.push(info.configure);
// use info.config || {} to keep behavior consistent with loading from string
return Promise.resolve(info.configure.call(null, fwConfig, info.config || {}));
}
throw new Error(invalidConfigMsg(info.moduleId || info.configure, 'plugin'));
function _loadPlugin(moduleId) {
return loader.loadModule(moduleId).then(m => { // eslint-disable-line consistent-return
if ('configure' in m) {
if (fwConfig.configuredPlugins.indexOf(m.configure) !== -1) {
return Promise.resolve();
}
return Promise.resolve(m.configure(fwConfig, info.config || {})).then(() => {
fwConfig.configuredPlugins.push(m.configure);
fwConfig.resourcesRelativeTo = null;
logger.debug(`Configured plugin ${info.moduleId}.`);
});
}
fwConfig.resourcesRelativeTo = null;
logger.debug(`Loaded plugin ${info.moduleId}.`);
});
}
}
function loadResources(aurelia, resourcesToLoad, appResources) {
// if devs want to go all in static, and remove loader
// the code after this fucntion shouldn't run
// add a check to make sure it only runs when there is something to do so
if (Object.keys(resourcesToLoad).length === 0) {
return Promise.resolve();
}
let viewEngine = aurelia.container.get(ViewEngine);
return Promise.all(Object.keys(resourcesToLoad).map(n => _normalize(resourcesToLoad[n])))
.then(loads => {
let names = [];
let importIds = [];
loads.forEach(l => {
names.push(undefined);
importIds.push(l.importId);
});
return viewEngine.importViewResources(importIds, names, appResources);
});
function _normalize(load) {
let moduleId = load.moduleId;
let ext = getExt(moduleId);
if (isOtherResource(moduleId)) {
moduleId = removeExt(moduleId);
}
return aurelia.loader.normalize(moduleId, load.relativeTo)
.then(normalized => {
return {
name: load.moduleId,
importId: isOtherResource(load.moduleId) ? addOriginalExt(normalized, ext) : normalized
};
});
}
function isOtherResource(name) {
let ext = getExt(name);
if (!ext) return false;
if (ext === '') return false;
if (ext === '.js' || ext === '.ts') return false;
return true;
}
function removeExt(name) {
return name.replace(extPattern, '');
}
function addOriginalExt(normalized, ext) {
return removeExt(normalized) + '.' + ext;
}
}
function getExt(name: string) { // eslint-disable-line consistent-return
let match = name.match(extPattern);
if (match && match.length > 0) {
return (match[0].split('.'))[1];
}
}
function loadBehaviors(config: FrameworkConfiguration) {
return Promise.all(config.behaviorsToLoad.map(m => m.load(config.container, m.target))).then(() => {
config.behaviorsToLoad = null;
});
}
function assertProcessed(plugins: FrameworkConfiguration) {
if (plugins.processed) {
throw new Error('This config instance has already been applied. To load more plugins or global resources, create a new FrameworkConfiguration instance.');
}
}
function invalidConfigMsg(cfg: any, type: string) {
return `Invalid ${type} [${cfg}], ${type} must be specified as functions or relative module IDs.`;
}
/**
* Manages configuring the aurelia framework instance.
*/
export class FrameworkConfiguration {
/**
* The root DI container used by the application.
*/
container: Container;
/**
* The aurelia instance.
*/
aurelia: Aurelia;
/**
* Creates an instance of FrameworkConfiguration.
* @param aurelia An instance of Aurelia.
*/
constructor(aurelia: Aurelia) {
this.aurelia = aurelia;
this.container = aurelia.container;
/**
* Plugin / feature loading instruction
* @type {FrameworkPluginInfo[]}
*/
this.info = [];
this.processed = false;
this.preTasks = [];
this.postTasks = [];
/**
* Custom element's metadata queue for loading view factory
* @type {HtmlBehaviorResource[]}
*/
this.behaviorsToLoad = [];
/**
* Plugin configure functions temporary cache for avoid duplicate calls
* @type {Function[]}
*/
this.configuredPlugins = [];
this.resourcesToLoad = {};
this.preTask(() => aurelia.loader.normalize('aurelia-bootstrapper').then(name => this.bootstrapperName = name));
this.postTask(() => loadResources(aurelia, this.resourcesToLoad, aurelia.resources));
}
/**
* Adds an existing object to the framework's dependency injection container.
* @param type The object type of the dependency that the framework will inject.
* @param instance The existing instance of the dependency that the framework will inject.
* @return Returns the current FrameworkConfiguration instance.
*/
instance(type: any, instance: any): FrameworkConfiguration {
this.container.registerInstance(type, instance);
return this;
}
/**
* Adds a singleton to the framework's dependency injection container.
* @param type The object type of the dependency that the framework will inject.
* @param implementation The constructor function of the dependency that the framework will inject.
* @return Returns the current FrameworkConfiguration instance.
*/
singleton(type: any, implementation?: Function): FrameworkConfiguration {
this.container.registerSingleton(type, implementation);
return this;
}
/**
* Adds a transient to the framework's dependency injection container.
* @param type The object type of the dependency that the framework will inject.
* @param implementation The constructor function of the dependency that the framework will inject.
* @return Returns the current FrameworkConfiguration instance.
*/
transient(type: any, implementation?: Function): FrameworkConfiguration {
this.container.registerTransient(type, implementation);
return this;
}
/**
* Adds an async function that runs before the plugins are run.
* @param task The function to run before start.
* @return Returns the current FrameworkConfiguration instance.
*/
preTask(task: Function): FrameworkConfiguration {
assertProcessed(this);
this.preTasks.push(task);
return this;
}
/**
* Adds an async function that runs after the plugins are run.
* @param task The function to run after start.
* @return Returns the current FrameworkConfiguration instance.
*/
postTask(task: Function): FrameworkConfiguration {
assertProcessed(this);
this.postTasks.push(task);
return this;
}
/**
* Configures an internal feature plugin before Aurelia starts.
* @param plugin The folder for the internal plugin to configure (expects an index.js in that folder).
* @param config The configuration for the specified plugin.
* @return Returns the current FrameworkConfiguration instance.
*/
feature(plugin: string | ((config: FrameworkConfiguration, pluginConfig?: any) => any), config?: any = {}): FrameworkConfiguration {
switch (typeof plugin) {
case 'string':
let hasIndex = /\/index$/i.test(plugin);
let moduleId = hasIndex || getExt(plugin) ? plugin : plugin + '/index';
let root = hasIndex ? plugin.substr(0, plugin.length - 6) : plugin;
this.info.push({ moduleId, resourcesRelativeTo: [root, ''], config });
break;
// return this.plugin({ moduleId, resourcesRelativeTo: [root, ''], config });
case 'function':
this.info.push({ configure: plugin, config: config || {} });
break;
default:
throw new Error(invalidConfigMsg(plugin, 'feature'));
}
return this;
// return this.plugin(plugin, config);
}
/**
* Adds globally available view resources to be imported into the Aurelia framework.
* @param resources The relative module id to the resource. (Relative to the plugin's installer.)
* @return Returns the current FrameworkConfiguration instance.
*/
globalResources(resources: string | Function | Array<string | Function>): FrameworkConfiguration {
assertProcessed(this);
let toAdd = Array.isArray(resources) ? resources : arguments;
let resource;
let resourcesRelativeTo = this.resourcesRelativeTo || ['', ''];
for (let i = 0, ii = toAdd.length; i < ii; ++i) {
resource = toAdd[i];
switch (typeof resource) {
case 'string':
let parent = resourcesRelativeTo[0];
let grandParent = resourcesRelativeTo[1];
let name = resource;
if ((resource.startsWith('./') || resource.startsWith('../')) && parent !== '') {
name = join(parent, resource);
}
this.resourcesToLoad[name] = { moduleId: name, relativeTo: grandParent };
break;
case 'function':
let meta = this.aurelia.resources.autoRegister(this.container, resource);
if (meta instanceof HtmlBehaviorResource && meta.elementName !== null) {
if (this.behaviorsToLoad.push(meta) === 1) {
this.postTask(() => loadBehaviors(this));
}
}
break;
default:
throw new Error(invalidConfigMsg(resource, 'resource'));
}
}
return this;
}
/**
* Renames a global resource that was imported.
* @param resourcePath The path to the resource.
* @param newName The new name.
* @return Returns the current FrameworkConfiguration instance.
*/
globalName(resourcePath: string, newName: string): FrameworkConfiguration {
assertProcessed(this);
this.resourcesToLoad[resourcePath] = { moduleId: newName, relativeTo: '' };
return this;
}
/**
* Configures an external, 3rd party plugin before Aurelia starts.
* @param plugin The ID of the 3rd party plugin to configure.
* @param pluginConfig The configuration for the specified plugin.
* @return Returns the current FrameworkConfiguration instance.
*/
plugin(
plugin: string | ((frameworkConfig: FrameworkConfiguration) => any) | FrameworkPluginInfo,
pluginConfig?: any
): FrameworkConfiguration {
assertProcessed(this);
let info: FrameworkPluginInfo;
switch (typeof plugin) {
case 'string':
info = { moduleId: plugin, resourcesRelativeTo: [plugin, ''], config: pluginConfig || {} };
break;
case 'function':
info = { configure: plugin, config: pluginConfig || {} };
break;
default:
throw new Error(invalidConfigMsg(plugin, 'plugin'));
}
this.info.push(info);
return this;
}
_addNormalizedPlugin(name, config) {
let plugin = { moduleId: name, resourcesRelativeTo: [name, ''], config: config || {} };
this.info.push(plugin);
this.preTask(() => {
let relativeTo = [name, this.bootstrapperName];
plugin.moduleId = name;
plugin.resourcesRelativeTo = relativeTo;
return Promise.resolve();
});
return this;
}
// Default configuration helpers
// Note: Please do NOT add PLATFORM.moduleName() around those module names.
// Those functions are not guaranteed to be called, they are here to faciliate
// common configurations. If they are not called, we don't want to include a
// static dependency on those modules.
// Including those modules in the bundle or not is a decision that must be
// taken by the bundling tool, at build time.
/**
* Plugs in the default binding language from aurelia-templating-binding.
* @return Returns the current FrameworkConfiguration instance.
*/
defaultBindingLanguage(): FrameworkConfiguration {
return this._addNormalizedPlugin('aurelia-templating-binding');
}
/**
* Plugs in the router from aurelia-templating-router.
* @return Returns the current FrameworkConfiguration instance.
*/
router(): FrameworkConfiguration {
return this._addNormalizedPlugin('aurelia-templating-router');
}
/**
* Plugs in the default history implementation from aurelia-history-browser.
* @return Returns the current FrameworkConfiguration instance.
*/
history(): FrameworkConfiguration {
return this._addNormalizedPlugin('aurelia-history-browser');
}
/**
* Plugs in the default templating resources (if, repeat, show, compose, etc.) from aurelia-templating-resources.
* @return Returns the current FrameworkConfiguration instance.
*/
defaultResources(): FrameworkConfiguration {
return this._addNormalizedPlugin('aurelia-templating-resources');
}
/**
* Plugs in the event aggregator from aurelia-event-aggregator.
* @return Returns the current FrameworkConfiguration instance.
*/
eventAggregator(): FrameworkConfiguration {
return this._addNormalizedPlugin('aurelia-event-aggregator');
}
/**
* Sets up a basic Aurelia configuration. This is equivalent to calling `.defaultBindingLanguage().defaultResources().eventAggregator();`
* @return Returns the current FrameworkConfiguration instance.
*/
basicConfiguration(): FrameworkConfiguration {
return this.defaultBindingLanguage().defaultResources().eventAggregator();
}
/**
* Sets up the standard Aurelia configuration. This is equivalent to calling `.defaultBindingLanguage().defaultResources().eventAggregator().history().router();`
* @return Returns the current FrameworkConfiguration instance.
*/
standardConfiguration(): FrameworkConfiguration {
return this.basicConfiguration().history().router();
}
/**
* Plugs in the ConsoleAppender and sets the log level to debug.
* @param level The log level (none/error/warn/info/debug), default to 'debug'.
* @return {FrameworkConfiguration} Returns the current FrameworkConfiguration instance.
*/
developmentLogging(level?: String): FrameworkConfiguration {
let logLevel = level ? TheLogManager.logLevel[level] : undefined;
if (logLevel === undefined) {
logLevel = TheLogManager.logLevel.debug;
}
this.preTask(() => {
return this.aurelia.loader.normalize('aurelia-logging-console', this.bootstrapperName).then(name => {
return this.aurelia.loader.loadModule(name).then(m => {
TheLogManager.addAppender(new m.ConsoleAppender());
TheLogManager.setLevel(logLevel);
});
});
});
return this;
}
/**
* Loads and configures the plugins registered with this instance.
* @return Returns a promise which resolves when all plugins are loaded and configured.
*/
apply(): Promise<void> {
if (this.processed) {
return Promise.resolve();
}
return runTasks(this, this.preTasks).then(() => {
let loader = this.aurelia.loader;
let info = this.info;
let current;
let next = () => {
current = info.shift();
if (current) {
return loadPlugin(this, loader, current).then(next);
}
this.processed = true;
this.configuredPlugins = null;
return Promise.resolve();
};
return next().then(() => runTasks(this, this.postTasks));
});
}
}