forked from ember-cli/ember-resolver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
450 lines (359 loc) · 13.4 KB
/
index.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
/* globals requirejs, require */
import Ember from 'ember';
import { assert, deprecate, warn } from '@ember/debug';
import EmberObject, { get, computed } from '@ember/object';
import { dasherize, classify, underscore } from '@ember/string';
import { DEBUG } from '@glimmer/env';
import classFactory from '../../utils/class-factory';
import makeDictionary from '../../utils/make-dictionary';
if (typeof requirejs.entries === 'undefined') {
requirejs.entries = requirejs._eak_seen;
}
export class ModuleRegistry {
constructor(entries) {
this._entries = entries || requirejs.entries;
}
moduleNames() {
return Object.keys(this._entries);
}
has(moduleName) {
return moduleName in this._entries;
}
get(moduleName) {
return require(moduleName);
}
}
/**
* This module defines a subclass of Ember.DefaultResolver that adds two
* important features:
*
* 1) The resolver makes the container aware of es6 modules via the AMD
* output. The loader's _moduleEntries is consulted so that classes can be
* resolved directly via the module loader, without needing a manual
* `import`.
* 2) is able to provide injections to classes that implement `extend`
* (as is typical with Ember).
*/
function parseName(fullName) {
if (fullName.parsedName === true) { return fullName; }
let prefix, type, name;
let fullNameParts = fullName.split('@');
if (fullNameParts.length === 2) {
let prefixParts = fullNameParts[0].split(':');
if (prefixParts.length === 2) {
if (prefixParts[1].length === 0) {
type = prefixParts[0];
name = `@${fullNameParts[1]}`;
} else {
prefix = prefixParts[1];
type = prefixParts[0];
name = fullNameParts[1];
}
} else {
let nameParts = fullNameParts[1].split(':');
prefix = fullNameParts[0];
type = nameParts[0];
name = nameParts[1];
}
if (type === 'template' && prefix.lastIndexOf('components/', 0) === 0) {
name = `components/${name}`;
prefix = prefix.slice(11);
}
} else {
fullNameParts = fullName.split(':');
type = fullNameParts[0];
name = fullNameParts[1];
}
let fullNameWithoutType = name;
let namespace = get(this, 'namespace');
let root = namespace;
return {
parsedName: true,
fullName: fullName,
prefix: prefix || this.prefix({type: type}),
type: type,
fullNameWithoutType: fullNameWithoutType,
name: name,
root: root,
resolveMethodName: "resolve" + classify(type)
};
}
function resolveOther(parsedName) {
assert('`modulePrefix` must be defined', this.namespace.modulePrefix);
let normalizedModuleName = this.findModuleName(parsedName);
if (normalizedModuleName) {
let defaultExport = this._extractDefaultExport(normalizedModuleName, parsedName);
if (defaultExport === undefined) {
throw new Error(` Expected to find: '${parsedName.fullName}' within '${normalizedModuleName}' but got 'undefined'. Did you forget to 'export default' within '${normalizedModuleName}'?`);
}
if (this.shouldWrapInClassFactory(defaultExport, parsedName)) {
defaultExport = classFactory(defaultExport);
}
return defaultExport;
}
}
const Resolver = EmberObject.extend({
resolveOther,
parseName,
pluralizedTypes: null,
moduleRegistry: null,
makeToString(factory, fullName) {
return '' + this.namespace.modulePrefix + '@' + fullName + ':';
},
shouldWrapInClassFactory(/* module, parsedName */){
return false;
},
init() {
this._super();
this.moduleBasedResolver = true;
if (!this._moduleRegistry) {
this._moduleRegistry = new ModuleRegistry();
}
this._normalizeCache = makeDictionary();
this.pluralizedTypes = this.pluralizedTypes || makeDictionary();
if (!this.pluralizedTypes.config) {
this.pluralizedTypes.config = 'config';
}
this._deprecatedPodModulePrefix = false;
},
normalize(fullName) {
return this._normalizeCache[fullName] || (this._normalizeCache[fullName] = this._normalize(fullName));
},
resolve(fullName) {
let parsedName = this.parseName(fullName);
let resolveMethodName = parsedName.resolveMethodName;
let resolved;
if (typeof this[resolveMethodName] === 'function') {
resolved = this[resolveMethodName](parsedName);
}
if (resolved == null) {
resolved = this.resolveOther(parsedName);
}
return resolved;
},
_normalize(fullName) {
// A) Convert underscores to dashes
// B) Convert camelCase to dash-case, except for helpers where we want to avoid shadowing camelCase expressions
// C) replace `.` with `/` in order to make nested controllers work in the following cases
// 1. `needs: ['posts/post']`
// 2. `{{render "posts/post"}}`
// 3. `this.render('posts/post')` from Route
let split = fullName.split(':');
if (split.length > 1) {
if (split[0] === 'helper') {
return split[0] + ':' + split[1].replace(/_/g, '-');
} else {
return split[0] + ':' + dasherize(split[1].replace(/\./g, '/'));
}
} else {
return fullName;
}
},
pluralize(type) {
return this.pluralizedTypes[type] || (this.pluralizedTypes[type] = type + 's');
},
podBasedLookupWithPrefix(podPrefix, parsedName) {
let fullNameWithoutType = parsedName.fullNameWithoutType;
if (parsedName.type === 'template') {
fullNameWithoutType = fullNameWithoutType.replace(/^components\//, '');
}
return podPrefix + '/' + fullNameWithoutType + '/' + parsedName.type;
},
podBasedModuleName(parsedName) {
let podPrefix = this.namespace.podModulePrefix || this.namespace.modulePrefix;
return this.podBasedLookupWithPrefix(podPrefix, parsedName);
},
podBasedComponentsInSubdir(parsedName) {
let podPrefix = this.namespace.podModulePrefix || this.namespace.modulePrefix;
podPrefix = podPrefix + '/components';
if (parsedName.type === 'component' || /^components/.test(parsedName.fullNameWithoutType)) {
return this.podBasedLookupWithPrefix(podPrefix, parsedName);
}
},
resolveEngine(parsedName) {
let engineName = parsedName.fullNameWithoutType;
let engineModule = engineName + '/engine';
if (this._moduleRegistry.has(engineModule)) {
return this._extractDefaultExport(engineModule);
}
},
resolveRouteMap(parsedName) {
let engineName = parsedName.fullNameWithoutType;
let engineRoutesModule = engineName + '/routes';
if (this._moduleRegistry.has(engineRoutesModule)) {
let routeMap = this._extractDefaultExport(engineRoutesModule);
assert(`The route map for ${engineName} should be wrapped by 'buildRoutes' before exporting.` , routeMap.isRouteMap);
return routeMap;
}
},
resolveTemplate(parsedName) {
let resolved = this.resolveOther(parsedName);
if (resolved == null) {
resolved = Ember.TEMPLATES[parsedName.fullNameWithoutType];
}
return resolved;
},
mainModuleName(parsedName) {
if (parsedName.fullNameWithoutType === 'main') {
// if router:main or adapter:main look for a module with just the type first
return parsedName.prefix + '/' + parsedName.type;
}
},
defaultModuleName(parsedName) {
return parsedName.prefix + '/' + this.pluralize(parsedName.type) + '/' + parsedName.fullNameWithoutType;
},
prefix(parsedName) {
let tmpPrefix = this.namespace.modulePrefix;
if (this.namespace[parsedName.type + 'Prefix']) {
tmpPrefix = this.namespace[parsedName.type + 'Prefix'];
}
return tmpPrefix;
},
/**
A listing of functions to test for moduleName's based on the provided
`parsedName`. This allows easy customization of additional module based
lookup patterns.
@property moduleNameLookupPatterns
@returns {Ember.Array}
*/
moduleNameLookupPatterns: computed(function(){
return [
this.podBasedModuleName,
this.podBasedComponentsInSubdir,
this.mainModuleName,
this.defaultModuleName
];
}).readOnly(),
findModuleName(parsedName, loggingDisabled){
let moduleNameLookupPatterns = this.get('moduleNameLookupPatterns');
let moduleName;
for (let index = 0, length = moduleNameLookupPatterns.length; index < length; index++) {
let item = moduleNameLookupPatterns[index];
let tmpModuleName = item.call(this, parsedName);
// allow treat all dashed and all underscored as the same thing
// supports components with dashes and other stuff with underscores.
if (tmpModuleName) {
tmpModuleName = this.chooseModuleName(tmpModuleName, parsedName);
}
if (tmpModuleName && this._moduleRegistry.has(tmpModuleName)) {
moduleName = tmpModuleName;
}
if (!loggingDisabled) {
this._logLookup(moduleName, parsedName, tmpModuleName);
}
if (moduleName) {
return moduleName;
}
}
},
chooseModuleName(moduleName, parsedName) {
let underscoredModuleName = underscore(moduleName);
if (moduleName !== underscoredModuleName && this._moduleRegistry.has(moduleName) && this._moduleRegistry.has(underscoredModuleName)) {
throw new TypeError(`Ambiguous module names: '${ moduleName}' and '${underscoredModuleName }'`);
}
if (this._moduleRegistry.has(moduleName)) {
return moduleName;
} else if (this._moduleRegistry.has(underscoredModuleName)) {
return underscoredModuleName;
}
// workaround for dasherized partials:
// something/something/-something => something/something/_something
let partializedModuleName = moduleName.replace(/\/-([^/]*)$/, '/_$1');
if (this._moduleRegistry.has(partializedModuleName)) {
deprecate('Modules should not contain underscores. ' +
'Attempted to lookup "'+moduleName+'" which ' +
'was not found. Please rename "'+partializedModuleName+'" '+
'to "'+moduleName+'" instead.', false,
{ id: 'ember-resolver.underscored-modules', until: '3.0.0' });
return partializedModuleName;
}
if (DEBUG) {
let isCamelCaseHelper = parsedName.type === 'helper' && /[a-z]+[A-Z]+/.test(moduleName);
if (isCamelCaseHelper) {
this._camelCaseHelperWarnedNames = this._camelCaseHelperWarnedNames || [];
let alreadyWarned = this._camelCaseHelperWarnedNames.indexOf(parsedName.fullName) > -1;
if (!alreadyWarned && this._moduleRegistry.has(dasherize(moduleName))) {
this._camelCaseHelperWarnedNames.push(parsedName.fullName);
warn('Attempted to lookup "' + parsedName.fullName + '" which ' +
'was not found. In previous versions of ember-resolver, a bug would have ' +
'caused the module at "' + dasherize(moduleName) + '" to be ' +
'returned for this camel case helper name. This has been fixed. ' +
'Use the dasherized name to resolve the module that would have been ' +
'returned in previous versions.',
false,
{ id: 'ember-resolver.camelcase-helper-names', until: '3.0.0' });
}
}
}
},
// used by Ember.DefaultResolver.prototype._logLookup
lookupDescription(fullName) {
let parsedName = this.parseName(fullName);
let moduleName = this.findModuleName(parsedName, true);
return moduleName;
},
// only needed until 1.6.0-beta.2 can be required
_logLookup(found, parsedName, description) {
if (!Ember.ENV.LOG_MODULE_RESOLVER && !parsedName.root.LOG_RESOLVER) {
return;
}
let padding;
let symbol = found ? '[✓]' : '[ ]';
if (parsedName.fullName.length > 60) {
padding = '.';
} else {
padding = new Array(60 - parsedName.fullName.length).join('.');
}
if (!description) {
description = this.lookupDescription(parsedName);
}
/* eslint-disable no-console */
if (console && console.info) {
console.info(symbol, parsedName.fullName, padding, description);
}
},
knownForType(type) {
let moduleKeys = this._moduleRegistry.moduleNames();
let items = makeDictionary();
for (let index = 0, length = moduleKeys.length; index < length; index++) {
let moduleName = moduleKeys[index];
let fullname = this.translateToContainerFullname(type, moduleName);
if (fullname) {
items[fullname] = true;
}
}
return items;
},
translateToContainerFullname(type, moduleName) {
let prefix = this.prefix({ type });
// Note: using string manipulation here rather than regexes for better performance.
// pod modules
// '^' + prefix + '/(.+)/' + type + '$'
let podPrefix = prefix + '/';
let podSuffix = '/' + type;
let start = moduleName.indexOf(podPrefix);
let end = moduleName.indexOf(podSuffix);
if (start === 0 && end === (moduleName.length - podSuffix.length) &&
moduleName.length > (podPrefix.length + podSuffix.length)) {
return type + ':' + moduleName.slice(start + podPrefix.length, end);
}
// non-pod modules
// '^' + prefix + '/' + pluralizedType + '/(.+)$'
let pluralizedType = this.pluralize(type);
let nonPodPrefix = prefix + '/' + pluralizedType + '/';
if (moduleName.indexOf(nonPodPrefix) === 0 && moduleName.length > nonPodPrefix.length) {
return type + ':' + moduleName.slice(nonPodPrefix.length);
}
},
_extractDefaultExport(normalizedModuleName) {
let module = require(normalizedModuleName, null, null, true /* force sync */);
if (module && module['default']) {
module = module['default'];
}
return module;
}
});
Resolver.reopenClass({
moduleBasedResolver: true
});
export default Resolver;