@embroider/core 3.4.9-unstable.ccbf41f → 3.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,59 +15,63 @@ const path_1 = require("path");
15
15
  const shared_internals_2 = require("@embroider/shared-internals");
16
16
  const debug_1 = __importDefault(require("debug"));
17
17
  const assert_never_1 = __importDefault(require("assert-never"));
18
- const reverse_exports_1 = __importDefault(require("@embroider/reverse-exports"));
19
- const resolve_exports_1 = require("resolve.exports");
18
+ const resolve_1 = __importDefault(require("resolve"));
20
19
  const virtual_content_1 = require("./virtual-content");
21
20
  const typescript_memoize_1 = require("typescript-memoize");
22
21
  const describe_exports_1 = require("./describe-exports");
23
22
  const fs_1 = require("fs");
24
- const node_resolve_1 = require("./node-resolve");
25
23
  const debug = (0, debug_1.default)('embroider:resolver');
26
- // Using a formatter makes this work lazy so nothing happens when we aren't
27
- // logging. It is unfortunate that formatters are a globally mutable config and
28
- // you can only use single character names, but oh well.
29
- debug_1.default.formatters.p = (s) => {
30
- let cwd = process.cwd();
31
- if (s.startsWith(cwd)) {
32
- return s.slice(cwd.length + 1);
33
- }
34
- return s;
35
- };
36
24
  function logTransition(reason, before, after = before) {
37
25
  if (after.isVirtual) {
38
- debug(`[%s:virtualized] %s because %s\n in %p`, before.debugType, before.specifier, reason, before.fromFile);
39
- }
40
- else if (after.resolvedTo) {
41
- debug(`[%s:resolvedTo] %s because %s\n in %p`, before.debugType, before.specifier, reason, before.fromFile);
26
+ debug(`virtualized %s in %s because %s`, before.specifier, before.fromFile, reason);
42
27
  }
43
28
  else if (before.specifier !== after.specifier) {
44
29
  if (before.fromFile !== after.fromFile) {
45
- debug(`[%s:aliased and rehomed] %s to %s\n because %s\n from %p\n to %p`, before.debugType, before.specifier, after.specifier, reason, before.fromFile, after.fromFile);
30
+ debug(`aliased and rehomed: %s to %s, from %s to %s because %s`, before.specifier, after.specifier, before.fromFile, after.fromFile, reason);
46
31
  }
47
32
  else {
48
- debug(`[%s:aliased] %s to %s\n because %s`, before.debugType, before.specifier, after.specifier, reason);
33
+ debug(`aliased: %s to %s in %s because`, before.specifier, after.specifier, before.fromFile, reason);
49
34
  }
50
35
  }
51
36
  else if (before.fromFile !== after.fromFile) {
52
- debug(`[%s:rehomed] %s, because %s\n from %p\n to %p`, before.debugType, before.specifier, reason, before.fromFile, after.fromFile);
53
- }
54
- else if (after.isNotFound) {
55
- debug(`[%s:not-found] %s because %s\n in %p`, before.debugType, before.specifier, reason, before.fromFile);
37
+ debug(`rehomed: %s from %s to %s because`, before.specifier, before.fromFile, after.fromFile, reason);
56
38
  }
57
39
  else {
58
- debug(`[%s:unchanged] %s because %s\n in %p`, before.debugType, before.specifier, reason, before.fromFile);
40
+ debug(`unchanged: %s in %s because %s`, before.specifier, before.fromFile, reason);
59
41
  }
60
42
  return after;
61
43
  }
62
- function isTerminal(request) {
63
- return request.isVirtual || request.isNotFound || Boolean(request.resolvedTo);
64
- }
65
44
  const compatPattern = /#embroider_compat\/(?<type>[^\/]+)\/(?<rest>.*)/;
45
+ class NodeModuleRequest {
46
+ constructor(specifier, fromFile, isVirtual, meta) {
47
+ this.specifier = specifier;
48
+ this.fromFile = fromFile;
49
+ this.isVirtual = isVirtual;
50
+ this.meta = meta;
51
+ }
52
+ alias(specifier) {
53
+ return new NodeModuleRequest(specifier, this.fromFile, false, this.meta);
54
+ }
55
+ rehome(fromFile) {
56
+ if (this.fromFile === fromFile) {
57
+ return this;
58
+ }
59
+ else {
60
+ return new NodeModuleRequest(this.specifier, fromFile, false, this.meta);
61
+ }
62
+ }
63
+ virtualize(filename) {
64
+ return new NodeModuleRequest(filename, this.fromFile, true, this.meta);
65
+ }
66
+ withMeta(meta) {
67
+ return new NodeModuleRequest(this.specifier, this.fromFile, this.isVirtual, meta);
68
+ }
69
+ }
66
70
  class Resolver {
67
71
  constructor(options) {
68
72
  this.options = options;
69
73
  }
70
- async beforeResolve(request) {
74
+ beforeResolve(request) {
71
75
  if (request.specifier === '@embroider/macros') {
72
76
  // the macros package is always handled directly within babel (not
73
77
  // necessarily as a real resolvable package), so we should not mess with it.
@@ -75,17 +79,10 @@ class Resolver {
75
79
  // why we need to know about it.
76
80
  return logTransition('early exit', request);
77
81
  }
78
- if (request.specifier === 'require') {
79
- return this.external('early require', request, request.specifier);
80
- }
81
82
  request = this.handleFastbootSwitch(request);
82
- request = await this.handleGlobalsCompat(request);
83
+ request = this.handleGlobalsCompat(request);
83
84
  request = this.handleImplicitModules(request);
84
- request = this.handleImplicitTestScripts(request);
85
- request = this.handleVendorStyles(request);
86
- request = this.handleTestSupportStyles(request);
87
85
  request = this.handleRenaming(request);
88
- request = this.handleVendor(request);
89
86
  // we expect the specifier to be app relative at this point - must be after handleRenaming
90
87
  request = this.generateFastbootSwitch(request);
91
88
  request = this.preHandleExternal(request);
@@ -99,45 +96,95 @@ class Resolver {
99
96
  // that calls your build system's normal module resolver, this does both pre-
100
97
  // and post-resolution adjustments as needed to implement our compatibility
101
98
  // rules.
102
- async resolve(request) {
103
- request = await this.beforeResolve(request);
104
- if (request.resolvedTo) {
105
- return request.resolvedTo;
106
- }
107
- let resolution = await request.defaultResolve();
99
+ //
100
+ // Depending on the plugin architecture you're working in, it may be easier to
101
+ // call beforeResolve and fallbackResolve directly, in which case matching the
102
+ // details of the recursion to what this method does are your responsibility.
103
+ async resolve(request, defaultResolve) {
104
+ let gen = this.internalResolve(request, defaultResolve);
105
+ let out = gen.next();
106
+ while (!out.done) {
107
+ out = gen.next(await out.value);
108
+ }
109
+ return out.value;
110
+ }
111
+ // synchronous alternative to resolve() above. Because our own internals are
112
+ // all synchronous, you can use this if your defaultResolve function is
113
+ // synchronous.
114
+ resolveSync(request, defaultResolve) {
115
+ let gen = this.internalResolve(request, defaultResolve);
116
+ let out = gen.next();
117
+ while (!out.done) {
118
+ out = gen.next(out.value);
119
+ }
120
+ return out.value;
121
+ }
122
+ // Our core implementation is a generator so it can power both resolve() and
123
+ // resolveSync()
124
+ *internalResolve(request, defaultResolve) {
125
+ request = this.beforeResolve(request);
126
+ let resolution = yield defaultResolve(request);
108
127
  switch (resolution.type) {
109
128
  case 'found':
110
- case 'ignored':
111
129
  return resolution;
112
130
  case 'not_found':
113
131
  break;
114
132
  default:
115
133
  throw (0, assert_never_1.default)(resolution);
116
134
  }
117
- let nextRequest = await this.fallbackResolve(request);
135
+ let nextRequest = this.fallbackResolve(request);
118
136
  if (nextRequest === request) {
119
137
  // no additional fallback is available.
120
138
  return resolution;
121
139
  }
122
- if (nextRequest.resolvedTo) {
123
- return nextRequest.resolvedTo;
124
- }
125
140
  if (nextRequest.fromFile === request.fromFile && nextRequest.specifier === request.specifier) {
126
141
  throw new Error('Bug Discovered! New request is not === original request but has the same fromFile and specifier. This will likely create a loop.');
127
142
  }
128
- if (nextRequest.isVirtual || nextRequest.isNotFound) {
129
- // virtual and NotFound requests are terminal, there is no more
130
- // beforeResolve or fallbackResolve around them. The defaultResolve is
131
- // expected to know how to implement them.
132
- return nextRequest.defaultResolve();
143
+ if (nextRequest.isVirtual) {
144
+ // virtual requests are terminal, there is no more beforeResolve or
145
+ // fallbackResolve around them. The defaultResolve is expected to know how
146
+ // to implement them.
147
+ return yield defaultResolve(nextRequest);
133
148
  }
134
- return this.resolve(nextRequest);
149
+ return yield* this.internalResolve(nextRequest, defaultResolve);
135
150
  }
136
151
  // Use standard NodeJS resolving, with our required compatibility rules on
137
152
  // top. This is a convenience method for calling resolveSync with the
138
153
  // defaultResolve already configured to be "do the normal node thing".
139
- async nodeResolve(specifier, fromFile) {
140
- return (0, node_resolve_1.nodeResolve)(this, specifier, fromFile);
154
+ nodeResolve(specifier, fromFile) {
155
+ let resolution = this.resolveSync(new NodeModuleRequest(specifier, fromFile, false, undefined), request => {
156
+ if (request.isVirtual) {
157
+ return {
158
+ type: 'found',
159
+ result: {
160
+ type: 'virtual',
161
+ content: (0, virtual_content_1.virtualContent)(request.specifier, this),
162
+ filename: request.specifier,
163
+ },
164
+ };
165
+ }
166
+ try {
167
+ let filename = resolve_1.default.sync(request.specifier, {
168
+ basedir: (0, path_1.dirname)(request.fromFile),
169
+ extensions: this.options.resolvableExtensions,
170
+ });
171
+ return { type: 'found', result: { type: 'real', filename } };
172
+ }
173
+ catch (err) {
174
+ if (err.code !== 'MODULE_NOT_FOUND') {
175
+ throw err;
176
+ }
177
+ return { type: 'not_found', err };
178
+ }
179
+ });
180
+ switch (resolution.type) {
181
+ case 'not_found':
182
+ return resolution;
183
+ case 'found':
184
+ return resolution.result;
185
+ default:
186
+ throw (0, assert_never_1.default)(resolution);
187
+ }
141
188
  }
142
189
  get packageCache() {
143
190
  return shared_internals_2.RewrittenPackageCache.shared('embroider', this.options.appRoot);
@@ -154,9 +201,6 @@ class Resolver {
154
201
  return owningPackage;
155
202
  }
156
203
  generateFastbootSwitch(request) {
157
- if (isTerminal(request)) {
158
- return request;
159
- }
160
204
  let pkg = this.packageCache.ownerOfFile(request.fromFile);
161
205
  if (!pkg) {
162
206
  return request;
@@ -174,9 +218,7 @@ class Resolver {
174
218
  let fastbootFile = engineConfig.fastbootFiles[candidate];
175
219
  if (fastbootFile) {
176
220
  if (fastbootFile.shadowedFilename) {
177
- let { names } = (0, describe_exports_1.describeExports)((0, fs_1.readFileSync)((0, path_1.resolve)(pkg.root, fastbootFile.shadowedFilename), 'utf8'), {
178
- configFile: false,
179
- });
221
+ let { names } = (0, describe_exports_1.describeExports)((0, fs_1.readFileSync)((0, path_1.resolve)(pkg.root, fastbootFile.shadowedFilename), 'utf8'), {});
180
222
  let switchFile = (0, virtual_content_1.fastbootSwitch)(candidate, (0, path_1.resolve)(pkg.root, 'package.json'), names);
181
223
  if (switchFile === request.fromFile) {
182
224
  return logTransition('internal lookup from fastbootSwitch', request);
@@ -195,9 +237,6 @@ class Resolver {
195
237
  }
196
238
  handleFastbootSwitch(request) {
197
239
  var _a;
198
- if (isTerminal(request)) {
199
- return request;
200
- }
201
240
  let match = (0, virtual_content_1.decodeFastbootSwitch)(request.fromFile);
202
241
  if (!match) {
203
242
  return request;
@@ -236,15 +275,12 @@ class Resolver {
236
275
  }
237
276
  let entry = (_a = this.getEntryFromMergeMap(rel, pkg.root)) === null || _a === void 0 ? void 0 : _a.entry;
238
277
  if ((entry === null || entry === void 0 ? void 0 : entry.type) === 'both') {
239
- return logTransition('matched addon entry', request, request.alias(entry[section].specifier).rehome(entry[section].fromFile));
278
+ return logTransition('matched addon entry', request, request.alias(entry[section].localPath).rehome((0, path_1.resolve)(entry[section].packageRoot, 'package.json')));
240
279
  }
241
280
  }
242
281
  return logTransition('failed to match in fastboot switch', request);
243
282
  }
244
283
  handleImplicitModules(request) {
245
- if (isTerminal(request)) {
246
- return request;
247
- }
248
284
  let im = (0, virtual_content_1.decodeImplicitModules)(request.specifier);
249
285
  if (!im) {
250
286
  return request;
@@ -262,42 +298,7 @@ class Resolver {
262
298
  return logTransition(`own implicit modules`, request, request.virtualize((0, path_1.resolve)(pkg.root, `-embroider-${im.type}.js`)));
263
299
  }
264
300
  }
265
- handleImplicitTestScripts(request) {
266
- //TODO move the extra forwardslash handling out into the vite plugin
267
- const candidates = [
268
- '@embroider/core/test-support.js',
269
- '/@embroider/core/test-support.js',
270
- './@embroider/core/test-support.js',
271
- ];
272
- if (!candidates.includes(request.specifier)) {
273
- return request;
274
- }
275
- let pkg = this.packageCache.ownerOfFile(request.fromFile);
276
- if ((pkg === null || pkg === void 0 ? void 0 : pkg.root) !== this.options.engines[0].root) {
277
- throw new Error(`bug: found an import of ${request.specifier} in ${request.fromFile}, but this is not the top-level Ember app. The top-level Ember app is the only one that has support for @embroider/core/test-support.js. If you think something should be fixed in Embroider, please open an issue on https://github.com/embroider-build/embroider/issues.`);
278
- }
279
- return logTransition('test-support', request, request.virtualize((0, path_1.resolve)(pkg.root, '-embroider-test-support.js')));
280
- }
281
- handleTestSupportStyles(request) {
282
- //TODO move the extra forwardslash handling out into the vite plugin
283
- const candidates = [
284
- '@embroider/core/test-support.css',
285
- '/@embroider/core/test-support.css',
286
- './@embroider/core/test-support.css',
287
- ];
288
- if (!candidates.includes(request.specifier)) {
289
- return request;
290
- }
291
- let pkg = this.packageCache.ownerOfFile(request.fromFile);
292
- if ((pkg === null || pkg === void 0 ? void 0 : pkg.root) !== this.options.engines[0].root) {
293
- throw new Error(`bug: found an import of ${request.specifier} in ${request.fromFile}, but this is not the top-level Ember app. The top-level Ember app is the only one that has support for @embroider/core/test-support.css. If you think something should be fixed in Embroider, please open an issue on https://github.com/embroider-build/embroider/issues.`);
294
- }
295
- return logTransition('test-support-styles', request, request.virtualize((0, path_1.resolve)(pkg.root, '-embroider-test-support-styles.css')));
296
- }
297
- async handleGlobalsCompat(request) {
298
- if (isTerminal(request)) {
299
- return request;
300
- }
301
+ handleGlobalsCompat(request) {
301
302
  let match = compatPattern.exec(request.specifier);
302
303
  if (!match) {
303
304
  return request;
@@ -321,76 +322,56 @@ class Resolver {
321
322
  throw new Error(`bug: unexepected #embroider_compat specifier: ${request.specifier}`);
322
323
  }
323
324
  }
324
- handleVendorStyles(request) {
325
- //TODO move the extra forwardslash handling out into the vite plugin
326
- const candidates = ['@embroider/core/vendor.css', '/@embroider/core/vendor.css', './@embroider/core/vendor.css'];
327
- if (!candidates.includes(request.specifier)) {
328
- return request;
329
- }
330
- let pkg = this.packageCache.ownerOfFile(request.fromFile);
331
- if ((pkg === null || pkg === void 0 ? void 0 : pkg.root) !== this.options.engines[0].root) {
332
- throw new Error(`bug: found an import of ${request.specifier} in ${request.fromFile}, but this is not the top-level Ember app. The top-level Ember app is the only one that has support for @embroider/core/vendor.css. If you think something should be fixed in Embroider, please open an issue on https://github.com/embroider-build/embroider/issues.`);
333
- }
334
- return logTransition('vendor-styles', request, request.virtualize((0, path_1.resolve)(pkg.root, '-embroider-vendor-styles.css')));
335
- }
336
325
  resolveHelper(path, inEngine, request) {
337
326
  let target = this.parseGlobalPath(path, inEngine);
338
327
  return logTransition('resolveHelper', request, request.alias(`${target.packageName}/helpers/${target.memberName}`).rehome((0, path_1.resolve)(inEngine.root, 'package.json')));
339
328
  }
340
- async resolveComponent(path, inEngine, request) {
329
+ resolveComponent(path, inEngine, request) {
341
330
  let target = this.parseGlobalPath(path, inEngine);
342
331
  let hbsModule = null;
343
332
  let jsModule = null;
344
333
  // first, the various places our template might be.
345
334
  for (let candidate of this.componentTemplateCandidates(target.packageName)) {
346
- let candidateSpecifier = `${target.packageName}${candidate.prefix}${target.memberName}${candidate.suffix}`;
347
- let resolution = await this.resolve(request.alias(candidateSpecifier).rehome(target.from).withMeta({
348
- runtimeFallback: false,
349
- }));
350
- if (resolution.type === 'found') {
351
- hbsModule = resolution;
335
+ let resolution = this.nodeResolve(`${target.packageName}${candidate.prefix}${target.memberName}${candidate.suffix}`, target.from);
336
+ if (resolution.type === 'real') {
337
+ hbsModule = resolution.filename;
352
338
  break;
353
339
  }
354
340
  }
355
341
  // then the various places our javascript might be.
356
342
  for (let candidate of this.componentJSCandidates(target.packageName)) {
357
- let candidateSpecifier = `${target.packageName}${candidate.prefix}${target.memberName}${candidate.suffix}`;
358
- let resolution = await this.resolve(request.alias(candidateSpecifier).rehome(target.from).withMeta({
359
- runtimeFallback: false,
360
- }));
343
+ let resolution = this.nodeResolve(`${target.packageName}${candidate.prefix}${target.memberName}${candidate.suffix}`, target.from);
361
344
  // .hbs is a resolvable extension for us, so we need to exclude it here.
362
345
  // It matches as a priority lower than .js, so finding an .hbs means
363
346
  // there's definitely not a .js.
364
- if (resolution.type === 'found' && !resolution.filename.endsWith('.hbs')) {
365
- jsModule = resolution;
347
+ if (resolution.type === 'real' && !resolution.filename.endsWith('.hbs')) {
348
+ jsModule = resolution.filename;
366
349
  break;
367
350
  }
368
351
  }
369
352
  if (hbsModule) {
370
- return logTransition(`resolveComponent found legacy HBS`, request, request.virtualize((0, virtual_content_1.virtualPairComponent)(hbsModule.filename, jsModule === null || jsModule === void 0 ? void 0 : jsModule.filename)));
353
+ return logTransition(`resolveComponent found legacy HBS`, request, request.virtualize((0, virtual_content_1.virtualPairComponent)(hbsModule, jsModule)));
371
354
  }
372
355
  else if (jsModule) {
373
- return logTransition(`resolving to resolveComponent found only JS`, request, request.resolveTo(jsModule));
356
+ return logTransition(`resolveComponent found only JS`, request, request.alias(jsModule).rehome(target.from));
374
357
  }
375
358
  else {
376
359
  return logTransition(`resolveComponent failed`, request);
377
360
  }
378
361
  }
379
- async resolveHelperOrComponent(path, inEngine, request) {
362
+ resolveHelperOrComponent(path, inEngine, request) {
380
363
  // resolveHelper just rewrites our request to one that should target the
381
364
  // component, so here to resolve the ambiguity we need to actually resolve
382
365
  // that candidate to see if it works.
383
366
  let helperCandidate = this.resolveHelper(path, inEngine, request);
384
- let helperMatch = await this.resolve(request.alias(helperCandidate.specifier).rehome(helperCandidate.fromFile).withMeta({
385
- runtimeFallback: false,
386
- }));
387
- if (helperMatch.type === 'found') {
388
- return logTransition('resolve to ambiguous case matched a helper', request, request.resolveTo(helperMatch));
367
+ let helperMatch = this.nodeResolve(helperCandidate.specifier, helperCandidate.fromFile);
368
+ if (helperMatch.type === 'real') {
369
+ return logTransition('ambiguous case matched a helper', request, helperCandidate);
389
370
  }
390
371
  // unlike resolveHelper, resolveComponent already does pre-resolution in
391
372
  // order to deal with its own internal ambiguity around JS vs HBS vs
392
373
  // colocation.≥
393
- let componentMatch = await this.resolveComponent(path, inEngine, request);
374
+ let componentMatch = this.resolveComponent(path, inEngine, request);
394
375
  if (componentMatch !== request) {
395
376
  return logTransition('ambiguous case matched a cmoponent', request, componentMatch);
396
377
  }
@@ -415,7 +396,6 @@ class Resolver {
415
396
  }
416
397
  *componentJSCandidates(inPackageName) {
417
398
  yield { prefix: '/components/', suffix: '' };
418
- yield { prefix: '/components/', suffix: '/index' };
419
399
  yield { prefix: '/components/', suffix: '/component' };
420
400
  let pods = this.podPrefix(inPackageName);
421
401
  if (pods) {
@@ -434,10 +414,10 @@ class Resolver {
434
414
  parseGlobalPath(path, inEngine) {
435
415
  let parts = path.split('@');
436
416
  if (parts.length > 1 && parts[0].length > 0) {
437
- return { packageName: parts[0], memberName: parts[1], from: (0, path_1.resolve)(inEngine.root, 'package.json') };
417
+ return { packageName: parts[0], memberName: parts[1], from: (0, path_1.resolve)(inEngine.root, 'pacakge.json') };
438
418
  }
439
419
  else {
440
- return { packageName: inEngine.packageName, memberName: path, from: (0, path_1.resolve)(inEngine.root, 'package.json') };
420
+ return { packageName: inEngine.packageName, memberName: path, from: (0, path_1.resolve)(inEngine.root, 'pacakge.json') };
441
421
  }
442
422
  }
443
423
  engineConfig(packageName) {
@@ -469,8 +449,8 @@ class Resolver {
469
449
  engineModules.set(inEngineName, {
470
450
  type: 'app-only',
471
451
  'app-js': {
472
- specifier: (0, reverse_exports_1.default)(addon.packageJSON, inAddonName),
473
- fromFile: addonConfig.canResolveFromFile,
452
+ localPath: inAddonName,
453
+ packageRoot: addon.root,
474
454
  fromPackageName: addon.name,
475
455
  },
476
456
  });
@@ -483,8 +463,8 @@ class Resolver {
483
463
  engineModules.set(inEngineName, {
484
464
  type: 'both',
485
465
  'app-js': {
486
- specifier: (0, reverse_exports_1.default)(addon.packageJSON, inAddonName),
487
- fromFile: addonConfig.canResolveFromFile,
466
+ localPath: inAddonName,
467
+ packageRoot: addon.root,
488
468
  fromPackageName: addon.name,
489
469
  },
490
470
  'fastboot-js': prevEntry['fastboot-js'],
@@ -508,8 +488,8 @@ class Resolver {
508
488
  engineModules.set(inEngineName, {
509
489
  type: 'fastboot-only',
510
490
  'fastboot-js': {
511
- specifier: (0, reverse_exports_1.default)(addon.packageJSON, inAddonName),
512
- fromFile: addonConfig.canResolveFromFile,
491
+ localPath: inAddonName,
492
+ packageRoot: addon.root,
513
493
  fromPackageName: addon.name,
514
494
  },
515
495
  });
@@ -522,8 +502,8 @@ class Resolver {
522
502
  engineModules.set(inEngineName, {
523
503
  type: 'both',
524
504
  'fastboot-js': {
525
- specifier: (0, reverse_exports_1.default)(addon.packageJSON, inAddonName),
526
- fromFile: addonConfig.canResolveFromFile,
505
+ localPath: inAddonName,
506
+ packageRoot: addon.root,
527
507
  fromPackageName: addon.name,
528
508
  },
529
509
  'app-js': prevEntry['app-js'],
@@ -545,7 +525,7 @@ class Resolver {
545
525
  return owningEngine;
546
526
  }
547
527
  handleRewrittenPackages(request) {
548
- if (isTerminal(request)) {
528
+ if (request.isVirtual) {
549
529
  return request;
550
530
  }
551
531
  let requestingPkg = this.packageCache.ownerOfFile(request.fromFile);
@@ -564,6 +544,10 @@ class Resolver {
564
544
  targetPkg = this.packageCache.resolve(packageName, requestingPkg);
565
545
  }
566
546
  catch (err) {
547
+ // this is not the place to report resolution failures. If the thing
548
+ // doesn't resolve, we're just not interested in redirecting it for
549
+ // backward-compat, that's all. The rest of the system will take care of
550
+ // reporting a failure to resolve (or handling it a different way)
567
551
  if (err.code !== 'MODULE_NOT_FOUND') {
568
552
  throw err;
569
553
  }
@@ -579,26 +563,14 @@ class Resolver {
579
563
  return logTransition('request targets a moved package', request, this.resolveWithinMovedPackage(request, targetPkg));
580
564
  }
581
565
  else if (originalRequestingPkg !== requestingPkg) {
582
- if (targetPkg) {
583
- // in this case, the requesting package is moved but its destination is
584
- // not, so we need to rehome the request back to the original location.
585
- return logTransition('outbound request from moved package', request, request
586
- // setting meta here because if this fails, we want the fallback
587
- // logic to revert our rehome and continue from the *moved* package.
588
- .withMeta({ originalFromFile: request.fromFile })
589
- .rehome((0, path_1.resolve)(originalRequestingPkg.root, 'package.json')));
590
- }
591
- else {
592
- // requesting package was moved and we failed to find its target. We
593
- // can't let that accidentally succeed in the defaultResolve because we
594
- // could escape the moved package system.
595
- return logTransition('missing outbound request from moved package', request, request.notFound());
596
- }
566
+ // in this case, the requesting package is moved but its destination is
567
+ // not, so we need to rehome the request back to the original location.
568
+ return logTransition('outbound request from moved package', request, request.withMeta({ wasMovedTo: request.fromFile }).rehome((0, path_1.resolve)(originalRequestingPkg.root, 'package.json')));
597
569
  }
598
570
  return request;
599
571
  }
600
572
  handleRenaming(request) {
601
- if (isTerminal(request)) {
573
+ if (request.isVirtual) {
602
574
  return request;
603
575
  }
604
576
  let packageName = (0, shared_internals_1.packageName)(request.specifier);
@@ -631,65 +603,30 @@ class Resolver {
631
603
  return logTransition(`renamePackages`, request, request.alias(request.specifier.replace(packageName, this.options.renamePackages[packageName])));
632
604
  }
633
605
  }
634
- if (pkg.name === packageName) {
635
- // we found a self-import
636
- if (pkg.meta['auto-upgraded']) {
637
- // auto-upgraded packages always get automatically adjusted. They never
638
- // supported fancy package.json exports features so this direct mapping
639
- // to the root is always right.
640
- // "my-package/foo" -> "./foo"
641
- // "my-package" -> "./" (this can't be just "." because node's require.resolve doesn't reliable support that)
642
- let selfImportPath = request.specifier === pkg.name ? './' : request.specifier.replace(pkg.name, '.');
643
- return logTransition(`v1 self-import`, request, request.alias(selfImportPath).rehome((0, path_1.resolve)(pkg.root, 'package.json')));
644
- }
645
- else {
646
- // v2 packages are supposed to use package.json `exports` to enable
647
- // self-imports, but not all build tools actually follow the spec. This
648
- // is a workaround for badly behaved packagers.
649
- //
650
- // Known upstream bugs this works around:
651
- // - https://github.com/vitejs/vite/issues/9731
652
- if (pkg.packageJSON.exports) {
653
- let found = (0, resolve_exports_1.exports)(pkg.packageJSON, request.specifier, {
654
- browser: true,
655
- conditions: ['default', 'imports'],
656
- });
657
- if (found === null || found === void 0 ? void 0 : found[0]) {
658
- return logTransition(`v2 self-import with package.json exports`, request, request.alias(found === null || found === void 0 ? void 0 : found[0]).rehome((0, path_1.resolve)(pkg.root, 'package.json')));
659
- }
660
- }
661
- }
606
+ if (pkg.meta['auto-upgraded'] && pkg.name === packageName) {
607
+ // we found a self-import, resolve it for them. Only auto-upgraded
608
+ // packages get this help, v2 packages are natively supposed to make their
609
+ // own modules resolvable, and we want to push them all to do that
610
+ // correctly.
611
+ return logTransition(`v1 self-import`, request, request.alias(request.specifier.replace(pkg.name, '.')).rehome((0, path_1.resolve)(pkg.root, 'package.json')));
662
612
  }
663
613
  return request;
664
614
  }
665
- handleVendor(request) {
666
- //TODO move the extra forwardslash handling out into the vite plugin
667
- const candidates = ['@embroider/core/vendor.js', '/@embroider/core/vendor.js', './@embroider/core/vendor.js'];
668
- if (!candidates.includes(request.specifier)) {
669
- return request;
670
- }
671
- let pkg = this.packageCache.ownerOfFile(request.fromFile);
672
- if ((pkg === null || pkg === void 0 ? void 0 : pkg.root) !== this.options.engines[0].root) {
673
- throw new Error(`bug: found an import of ${request.specifier} in ${request.fromFile}, but this is not the top-level Ember app. The top-level Ember app is the only one that has support for @embroider/core/vendor.js. If you think something should be fixed in Embroider, please open an issue on https://github.com/embroider-build/embroider/issues.`);
674
- }
675
- return logTransition('vendor', request, request.virtualize((0, path_1.resolve)(pkg.root, '-embroider-vendor.js')));
676
- }
677
615
  resolveWithinMovedPackage(request, pkg) {
678
616
  let levels = ['..'];
679
617
  if (pkg.name.startsWith('@')) {
680
618
  levels.push('..');
681
619
  }
682
- let originalFromFile = request.fromFile;
683
620
  let newRequest = request.rehome((0, path_1.resolve)(pkg.root, ...levels, 'moved-package-target.js'));
684
621
  if (newRequest === request) {
685
622
  return request;
686
623
  }
687
- // setting meta because if this fails, we want the fallback to pick up back
688
- // in the original requesting package.
689
- return newRequest.withMeta({ originalFromFile });
624
+ return newRequest.withMeta({
625
+ resolvedWithinPackage: pkg.root,
626
+ });
690
627
  }
691
628
  preHandleExternal(request) {
692
- if (isTerminal(request)) {
629
+ if (request.isVirtual) {
693
630
  return request;
694
631
  }
695
632
  let { specifier, fromFile } = request;
@@ -722,15 +659,7 @@ class Resolver {
722
659
  // engine
723
660
  let logicalLocation = this.reverseSearchAppTree(pkg, request.fromFile);
724
661
  if (logicalLocation) {
725
- return logTransition('beforeResolve: relative import in app-js', request, request
726
- .alias('./' + path_1.posix.join((0, path_1.dirname)(logicalLocation.inAppName), request.specifier))
727
- // it's important that we're rehoming this to the root of the engine
728
- // (which we know really exists), and not to a subdir like
729
- // logicalLocation.inAppName (which might not physically exist),
730
- // because some environments (including node's require.resolve) will
731
- // refuse to do resolution from a notional path that doesn't
732
- // physically exist.
733
- .rehome((0, path_1.resolve)(logicalLocation.owningEngine.root, 'package.json')));
662
+ return logTransition('beforeResolve: relative import in app-js', request, request.rehome((0, path_1.resolve)(logicalLocation.owningEngine.root, logicalLocation.inAppName)));
734
663
  }
735
664
  return request;
736
665
  }
@@ -745,11 +674,11 @@ class Resolver {
745
674
  if (shared_internals_1.emberVirtualPeerDeps.has(packageName) && !pkg.hasDependency(packageName)) {
746
675
  // addons (whether auto-upgraded or not) may use the app's
747
676
  // emberVirtualPeerDeps, like "@glimmer/component" etc.
748
- let addon = this.locateActiveAddon(packageName);
749
- if (!addon) {
750
- throw new Error(`${pkg.name} is trying to import the emberVirtualPeerDep "${packageName}", but it seems to be missing`);
677
+ if (!this.options.activeAddons[packageName]) {
678
+ throw new Error(`${pkg.name} is trying to import the app's ${packageName} package, but it seems to be missing`);
751
679
  }
752
- return logTransition(`emberVirtualPeerDeps`, request, request.rehome(addon.canResolveFromFile));
680
+ let newHome = (0, path_1.resolve)(this.packageCache.maybeMoved(this.packageCache.get(this.options.appRoot)).root, 'package.json');
681
+ return logTransition(`emberVirtualPeerDeps in v2 addon`, request, request.rehome(newHome));
753
682
  }
754
683
  // if this file is part of an addon's app-js, it's really the logical
755
684
  // package to which it belongs (normally the app) that affects some policy
@@ -780,22 +709,6 @@ class Resolver {
780
709
  }
781
710
  return request;
782
711
  }
783
- locateActiveAddon(packageName) {
784
- if (packageName === this.options.modulePrefix) {
785
- // the app itself is something that addon's can classically resolve if they know it's name.
786
- return {
787
- root: this.options.appRoot,
788
- canResolveFromFile: (0, path_1.resolve)(this.packageCache.maybeMoved(this.packageCache.get(this.options.appRoot)).root, 'package.json'),
789
- };
790
- }
791
- for (let engine of this.options.engines) {
792
- for (let addon of engine.activeAddons) {
793
- if (addon.name === packageName) {
794
- return addon;
795
- }
796
- }
797
- }
798
- }
799
712
  external(label, request, specifier) {
800
713
  if (this.options.amdCompatibility === 'cjs') {
801
714
  let filename = (0, virtual_content_1.virtualExternalCJSModule)(specifier);
@@ -828,11 +741,8 @@ class Resolver {
828
741
  throw new Error(`Embroider's amdCompatibility option is disabled, but something tried to use it to access "${request.specifier}"`);
829
742
  }
830
743
  }
831
- async fallbackResolve(request) {
744
+ fallbackResolve(request) {
832
745
  var _a, _b, _c;
833
- if (request.isVirtual) {
834
- throw new Error('Build tool bug detected! Fallback resolve should never see a virtual request. It is expected that the defaultResolve for your bundler has already resolved this request');
835
- }
836
746
  if (request.specifier === '@embroider/macros') {
837
747
  // the macros package is always handled directly within babel (not
838
748
  // necessarily as a real resolvable package), so we should not mess with it.
@@ -840,7 +750,8 @@ class Resolver {
840
750
  // why we need to know about it.
841
751
  return logTransition('fallback early exit', request);
842
752
  }
843
- if (compatPattern.test(request.specifier)) {
753
+ let { specifier, fromFile } = request;
754
+ if (compatPattern.test(specifier)) {
844
755
  // Some kinds of compat requests get rewritten into other things
845
756
  // deterministically. For example, "#embroider_compat/helpers/whatever"
846
757
  // means only "the-current-engine/helpers/whatever", and if that doesn't
@@ -856,33 +767,39 @@ class Resolver {
856
767
  // here.
857
768
  return request;
858
769
  }
859
- let pkg = this.packageCache.ownerOfFile(request.fromFile);
770
+ if (fromFile.endsWith('moved-package-target.js')) {
771
+ if (!((_a = request.meta) === null || _a === void 0 ? void 0 : _a.resolvedWithinPackage)) {
772
+ throw new Error(`bug: embroider resolver's meta is not propagating`);
773
+ }
774
+ fromFile = (0, path_1.resolve)((_b = request.meta) === null || _b === void 0 ? void 0 : _b.resolvedWithinPackage, 'package.json');
775
+ }
776
+ let pkg = this.packageCache.ownerOfFile(fromFile);
860
777
  if (!pkg) {
861
778
  return logTransition('no identifiable owningPackage', request);
862
779
  }
863
- // meta.originalFromFile gets set when we want to try to rehome a request
864
- // but then come back to the original location here in the fallback when the
865
- // rehomed request fails
780
+ // if we rehomed this request to its un-rewritten location in order to try
781
+ // to do the defaultResolve from there, now we refer back to the rewritten
782
+ // location because that's what we want to use when asking things like
783
+ // isV2Ember()
866
784
  let movedPkg = this.packageCache.maybeMoved(pkg);
867
785
  if (movedPkg !== pkg) {
868
- let originalFromFile = (_a = request.meta) === null || _a === void 0 ? void 0 : _a.originalFromFile;
869
- if (typeof originalFromFile !== 'string') {
786
+ if (!((_c = request.meta) === null || _c === void 0 ? void 0 : _c.wasMovedTo)) {
870
787
  throw new Error(`bug: embroider resolver's meta is not propagating`);
871
788
  }
872
- request = request.rehome(originalFromFile);
789
+ fromFile = request.meta.wasMovedTo;
873
790
  pkg = movedPkg;
874
791
  }
875
792
  if (!pkg.isV2Ember()) {
876
793
  return logTransition('fallbackResolve: not in an ember package', request);
877
794
  }
878
- let packageName = (0, shared_internals_1.packageName)(request.specifier);
795
+ let packageName = (0, shared_internals_1.packageName)(specifier);
879
796
  if (!packageName) {
880
797
  // this is a relative import
881
798
  let withinEngine = this.engineConfig(pkg.name);
882
799
  if (withinEngine) {
883
800
  // it's a relative import inside an engine (which also means app), which
884
801
  // means we may need to satisfy the request via app tree merging.
885
- let appJSMatch = await this.searchAppTree(request, withinEngine, (0, shared_internals_2.explicitRelative)(pkg.root, (0, path_1.resolve)((0, path_1.dirname)(request.fromFile), request.specifier)));
802
+ let appJSMatch = this.searchAppTree(request, withinEngine, (0, shared_internals_2.explicitRelative)(pkg.root, (0, path_1.resolve)((0, path_1.dirname)(fromFile), specifier)));
886
803
  if (appJSMatch) {
887
804
  return logTransition('fallbackResolve: relative appJsMatch', request, appJSMatch);
888
805
  }
@@ -896,49 +813,40 @@ class Resolver {
896
813
  }
897
814
  }
898
815
  // auto-upgraded packages can fall back to the set of known active addons
899
- if (pkg.meta['auto-upgraded']) {
900
- let addon = this.locateActiveAddon(packageName);
901
- if (addon) {
902
- const rehomed = request.rehome(addon.canResolveFromFile);
903
- if (rehomed !== request) {
904
- return logTransition(`activeAddons`, request, rehomed);
905
- }
816
+ if (pkg.meta['auto-upgraded'] && this.options.activeAddons[packageName]) {
817
+ const rehomed = this.resolveWithinMovedPackage(request, this.packageCache.get(this.options.activeAddons[packageName]));
818
+ if (rehomed !== request) {
819
+ return logTransition(`activeAddons`, request, rehomed);
906
820
  }
907
821
  }
908
- let logicalLocation = this.reverseSearchAppTree(pkg, request.fromFile);
822
+ let logicalLocation = this.reverseSearchAppTree(pkg, fromFile);
909
823
  if (logicalLocation) {
910
824
  // the requesting file is in an addon's appTree. We didn't succeed in
911
825
  // resolving this (non-relative) request from inside the actual addon, so
912
826
  // next try to resolve it from the corresponding logical location in the
913
827
  // app.
914
- return logTransition('fallbackResolve: retry from logical home of app-js file', request,
915
- // it might look more precise to rehome into logicalLocation.inAppName
916
- // rather than package.json. But that logical location may not actually
917
- // exist, and some systems (including node's require.resolve) will be
918
- // mad about trying to resolve from notional paths that don't really
919
- // exist.
920
- request.rehome((0, path_1.resolve)(logicalLocation.owningEngine.root, 'package.json')));
828
+ return logTransition('fallbackResolve: retry from logical home of app-js file', request, request.rehome((0, path_1.resolve)(logicalLocation.owningEngine.root, logicalLocation.inAppName)));
921
829
  }
922
830
  let targetingEngine = this.engineConfig(packageName);
923
831
  if (targetingEngine) {
924
- let appJSMatch = await this.searchAppTree(request, targetingEngine, request.specifier.replace(packageName, '.'));
832
+ let appJSMatch = this.searchAppTree(request, targetingEngine, specifier.replace(packageName, '.'));
925
833
  if (appJSMatch) {
926
834
  return logTransition('fallbackResolve: non-relative appJsMatch', request, appJSMatch);
927
835
  }
928
836
  }
929
- if (pkg.meta['auto-upgraded'] && ((_c = (_b = request.meta) === null || _b === void 0 ? void 0 : _b.runtimeFallback) !== null && _c !== void 0 ? _c : true)) {
837
+ if (pkg.meta['auto-upgraded']) {
930
838
  // auto-upgraded packages can fall back to attempting to find dependencies at
931
839
  // runtime. Native v2 packages can only get this behavior in the
932
840
  // isExplicitlyExternal case above because they need to explicitly ask for
933
841
  // externals.
934
- return this.external('v1 catch-all fallback', request, request.specifier);
842
+ return this.external('v1 catch-all fallback', request, specifier);
935
843
  }
936
844
  else {
937
845
  // native v2 packages don't automatically externalize *everything* the way
938
846
  // auto-upgraded packages do, but they still externalize known and approved
939
847
  // ember virtual packages (like @ember/component)
940
848
  if (shared_internals_1.emberVirtualPackages.has(packageName)) {
941
- return this.external('emberVirtualPackages', request, request.specifier);
849
+ return this.external('emberVirtualPackages', request, specifier);
942
850
  }
943
851
  }
944
852
  // this is falling through with the original specifier which was
@@ -965,23 +873,25 @@ class Resolver {
965
873
  }
966
874
  }
967
875
  }
968
- async searchAppTree(request, engine, inEngineSpecifier) {
876
+ searchAppTree(request, engine, inEngineSpecifier) {
969
877
  let matched = this.getEntryFromMergeMap(inEngineSpecifier, engine.root);
970
878
  switch (matched === null || matched === void 0 ? void 0 : matched.entry.type) {
971
879
  case undefined:
972
880
  return undefined;
973
881
  case 'app-only':
974
- return request.alias(matched.entry['app-js'].specifier).rehome(matched.entry['app-js'].fromFile);
882
+ return request
883
+ .alias(matched.entry['app-js'].localPath)
884
+ .rehome((0, path_1.resolve)(matched.entry['app-js'].packageRoot, 'package.json'));
975
885
  case 'fastboot-only':
976
- return request.alias(matched.entry['fastboot-js'].specifier).rehome(matched.entry['fastboot-js'].fromFile);
886
+ return request
887
+ .alias(matched.entry['fastboot-js'].localPath)
888
+ .rehome((0, path_1.resolve)(matched.entry['fastboot-js'].packageRoot, 'package.json'));
977
889
  case 'both':
978
- let foundAppJS = await this.resolve(request.alias(matched.entry['app-js'].specifier).rehome(matched.entry['app-js'].fromFile).withMeta({
979
- runtimeFallback: false,
980
- }));
981
- if (foundAppJS.type !== 'found') {
890
+ let foundAppJS = this.nodeResolve(matched.entry['app-js'].localPath, (0, path_1.resolve)(matched.entry['app-js'].packageRoot, 'package.json'));
891
+ if (foundAppJS.type !== 'real') {
982
892
  throw new Error(`${matched.entry['app-js'].fromPackageName} declared ${inEngineSpecifier} in packageJSON.ember-addon.app-js, but that module does not exist`);
983
893
  }
984
- let { names } = (0, describe_exports_1.describeExports)((0, fs_1.readFileSync)(foundAppJS.filename, 'utf8'), { configFile: false });
894
+ let { names } = (0, describe_exports_1.describeExports)((0, fs_1.readFileSync)(foundAppJS.filename, 'utf8'), {});
985
895
  return request.virtualize((0, virtual_content_1.fastbootSwitch)(matched.matched, (0, path_1.resolve)(engine.root, 'package.json'), names));
986
896
  }
987
897
  }