@embroider/core 3.4.19 → 3.4.20-unstable.0aa8fc6

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.
Files changed (61) hide show
  1. package/package.json +18 -8
  2. package/src/app-files.d.ts +3 -5
  3. package/src/app-files.js +25 -8
  4. package/src/app-files.js.map +1 -1
  5. package/src/index.d.ts +2 -3
  6. package/src/index.js +1 -3
  7. package/src/index.js.map +1 -1
  8. package/src/measure-concat.js +1 -2
  9. package/src/measure-concat.js.map +1 -1
  10. package/src/module-resolver-options.d.ts +42 -0
  11. package/src/module-resolver-options.js +164 -0
  12. package/src/module-resolver-options.js.map +1 -0
  13. package/src/module-resolver.d.ts +28 -44
  14. package/src/module-resolver.js +430 -304
  15. package/src/module-resolver.js.map +1 -1
  16. package/src/node-resolve.d.ts +33 -0
  17. package/src/node-resolve.js +131 -0
  18. package/src/node-resolve.js.map +1 -0
  19. package/src/options.d.ts +0 -7
  20. package/src/options.js +0 -1
  21. package/src/options.js.map +1 -1
  22. package/src/resolver-loader.js +8 -1
  23. package/src/resolver-loader.js.map +1 -1
  24. package/src/virtual-content.d.ts +6 -4
  25. package/src/virtual-content.js +67 -99
  26. package/src/virtual-content.js.map +1 -1
  27. package/src/virtual-entrypoint.d.ts +19 -0
  28. package/src/virtual-entrypoint.js +289 -0
  29. package/src/virtual-entrypoint.js.map +1 -0
  30. package/src/virtual-route-entrypoint.d.ts +15 -0
  31. package/src/virtual-route-entrypoint.js +94 -0
  32. package/src/virtual-route-entrypoint.js.map +1 -0
  33. package/src/virtual-test-support-styles.d.ts +4 -0
  34. package/src/virtual-test-support-styles.js +64 -0
  35. package/src/virtual-test-support-styles.js.map +1 -0
  36. package/src/virtual-test-support.d.ts +4 -0
  37. package/src/virtual-test-support.js +68 -0
  38. package/src/virtual-test-support.js.map +1 -0
  39. package/src/virtual-vendor-styles.d.ts +4 -0
  40. package/src/virtual-vendor-styles.js +82 -0
  41. package/src/virtual-vendor-styles.js.map +1 -0
  42. package/src/virtual-vendor.d.ts +4 -0
  43. package/src/virtual-vendor.js +57 -0
  44. package/src/virtual-vendor.js.map +1 -0
  45. package/types/virtual/index.d.ts +9 -0
  46. package/types/virtual/index.js +3 -0
  47. package/src/asset.d.ts +0 -32
  48. package/src/asset.js +0 -3
  49. package/src/asset.js.map +0 -1
  50. package/src/ember-html.d.ts +0 -43
  51. package/src/ember-html.js +0 -110
  52. package/src/ember-html.js.map +0 -1
  53. package/src/portable-babel-config.d.ts +0 -11
  54. package/src/portable-babel-config.js +0 -132
  55. package/src/portable-babel-config.js.map +0 -1
  56. package/src/portable-babel-launcher.d.ts +0 -6
  57. package/src/portable-babel-launcher.js +0 -75
  58. package/src/portable-babel-launcher.js.map +0 -1
  59. package/src/to-broccoli-plugin.d.ts +0 -8
  60. package/src/to-broccoli-plugin.js +0 -30
  61. package/src/to-broccoli-plugin.js.map +0 -1
@@ -15,64 +15,61 @@ 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 resolve_1 = __importDefault(require("resolve"));
18
+ const reverse_exports_1 = require("@embroider/reverse-exports");
19
+ const resolve_exports_1 = require("resolve.exports");
19
20
  const virtual_content_1 = require("./virtual-content");
20
21
  const typescript_memoize_1 = require("typescript-memoize");
21
22
  const describe_exports_1 = require("./describe-exports");
22
23
  const fs_1 = require("fs");
24
+ const node_resolve_1 = require("./node-resolve");
25
+ const virtual_route_entrypoint_1 = require("./virtual-route-entrypoint");
23
26
  const semver_1 = require("semver");
24
27
  const debug = (0, debug_1.default)('embroider:resolver');
28
+ // Using a formatter makes this work lazy so nothing happens when we aren't
29
+ // logging. It is unfortunate that formatters are a globally mutable config and
30
+ // you can only use single character names, but oh well.
31
+ debug_1.default.formatters.p = (s) => {
32
+ let cwd = process.cwd();
33
+ if (s.startsWith(cwd)) {
34
+ return s.slice(cwd.length + 1);
35
+ }
36
+ return s;
37
+ };
25
38
  function logTransition(reason, before, after = before) {
26
39
  if (after.isVirtual) {
27
- debug(`virtualized %s in %s because %s`, before.specifier, before.fromFile, reason);
40
+ debug(`[%s:virtualized] %s because %s\n in %p`, before.debugType, before.specifier, reason, before.fromFile);
41
+ }
42
+ else if (after.resolvedTo) {
43
+ debug(`[%s:resolvedTo] %s because %s\n in %p`, before.debugType, before.specifier, reason, before.fromFile);
28
44
  }
29
45
  else if (before.specifier !== after.specifier) {
30
46
  if (before.fromFile !== after.fromFile) {
31
- debug(`aliased and rehomed: %s to %s, from %s to %s because %s`, before.specifier, after.specifier, before.fromFile, after.fromFile, reason);
47
+ 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);
32
48
  }
33
49
  else {
34
- debug(`aliased: %s to %s in %s because`, before.specifier, after.specifier, before.fromFile, reason);
50
+ debug(`[%s:aliased] %s to %s\n because %s`, before.debugType, before.specifier, after.specifier, reason);
35
51
  }
36
52
  }
37
53
  else if (before.fromFile !== after.fromFile) {
38
- debug(`rehomed: %s from %s to %s because`, before.specifier, before.fromFile, after.fromFile, reason);
54
+ debug(`[%s:rehomed] %s, because %s\n from %p\n to %p`, before.debugType, before.specifier, reason, before.fromFile, after.fromFile);
55
+ }
56
+ else if (after.isNotFound) {
57
+ debug(`[%s:not-found] %s because %s\n in %p`, before.debugType, before.specifier, reason, before.fromFile);
39
58
  }
40
59
  else {
41
- debug(`unchanged: %s in %s because %s`, before.specifier, before.fromFile, reason);
60
+ debug(`[%s:unchanged] %s because %s\n in %p`, before.debugType, before.specifier, reason, before.fromFile);
42
61
  }
43
62
  return after;
44
63
  }
45
- const compatPattern = /#embroider_compat\/(?<type>[^\/]+)\/(?<rest>.*)/;
46
- class NodeModuleRequest {
47
- constructor(specifier, fromFile, isVirtual, meta) {
48
- this.specifier = specifier;
49
- this.fromFile = fromFile;
50
- this.isVirtual = isVirtual;
51
- this.meta = meta;
52
- }
53
- alias(specifier) {
54
- return new NodeModuleRequest(specifier, this.fromFile, false, this.meta);
55
- }
56
- rehome(fromFile) {
57
- if (this.fromFile === fromFile) {
58
- return this;
59
- }
60
- else {
61
- return new NodeModuleRequest(this.specifier, fromFile, false, this.meta);
62
- }
63
- }
64
- virtualize(filename) {
65
- return new NodeModuleRequest(filename, this.fromFile, true, this.meta);
66
- }
67
- withMeta(meta) {
68
- return new NodeModuleRequest(this.specifier, this.fromFile, this.isVirtual, meta);
69
- }
64
+ function isTerminal(request) {
65
+ return request.isVirtual || request.isNotFound || Boolean(request.resolvedTo);
70
66
  }
67
+ const compatPattern = /@embroider\/virtual\/(?<type>[^\/]+)\/(?<rest>.*)/;
71
68
  class Resolver {
72
69
  constructor(options) {
73
70
  this.options = options;
74
71
  }
75
- beforeResolve(request) {
72
+ async beforeResolve(request) {
76
73
  if (request.specifier === '@embroider/macros') {
77
74
  // the macros package is always handled directly within babel (not
78
75
  // necessarily as a real resolvable package), so we should not mess with it.
@@ -81,9 +78,15 @@ class Resolver {
81
78
  return logTransition('early exit', request);
82
79
  }
83
80
  request = this.handleFastbootSwitch(request);
84
- request = this.handleGlobalsCompat(request);
81
+ request = await this.handleGlobalsCompat(request);
85
82
  request = this.handleImplicitModules(request);
83
+ request = this.handleImplicitTestScripts(request);
84
+ request = this.handleVendorStyles(request);
85
+ request = this.handleTestSupportStyles(request);
86
+ request = this.handleEntrypoint(request);
87
+ request = this.handleRouteEntrypoint(request);
86
88
  request = this.handleRenaming(request);
89
+ request = this.handleVendor(request);
87
90
  // we expect the specifier to be app relative at this point - must be after handleRenaming
88
91
  request = this.generateFastbootSwitch(request);
89
92
  request = this.preHandleExternal(request);
@@ -97,95 +100,45 @@ class Resolver {
97
100
  // that calls your build system's normal module resolver, this does both pre-
98
101
  // and post-resolution adjustments as needed to implement our compatibility
99
102
  // rules.
100
- //
101
- // Depending on the plugin architecture you're working in, it may be easier to
102
- // call beforeResolve and fallbackResolve directly, in which case matching the
103
- // details of the recursion to what this method does are your responsibility.
104
- async resolve(request, defaultResolve) {
105
- let gen = this.internalResolve(request, defaultResolve);
106
- let out = gen.next();
107
- while (!out.done) {
108
- out = gen.next(await out.value);
109
- }
110
- return out.value;
111
- }
112
- // synchronous alternative to resolve() above. Because our own internals are
113
- // all synchronous, you can use this if your defaultResolve function is
114
- // synchronous.
115
- resolveSync(request, defaultResolve) {
116
- let gen = this.internalResolve(request, defaultResolve);
117
- let out = gen.next();
118
- while (!out.done) {
119
- out = gen.next(out.value);
120
- }
121
- return out.value;
122
- }
123
- // Our core implementation is a generator so it can power both resolve() and
124
- // resolveSync()
125
- *internalResolve(request, defaultResolve) {
126
- request = this.beforeResolve(request);
127
- let resolution = yield defaultResolve(request);
103
+ async resolve(request) {
104
+ request = await this.beforeResolve(request);
105
+ if (request.resolvedTo) {
106
+ return request.resolvedTo;
107
+ }
108
+ let resolution = await request.defaultResolve();
128
109
  switch (resolution.type) {
129
110
  case 'found':
111
+ case 'ignored':
130
112
  return resolution;
131
113
  case 'not_found':
132
114
  break;
133
115
  default:
134
116
  throw (0, assert_never_1.default)(resolution);
135
117
  }
136
- let nextRequest = this.fallbackResolve(request);
118
+ let nextRequest = await this.fallbackResolve(request);
137
119
  if (nextRequest === request) {
138
120
  // no additional fallback is available.
139
121
  return resolution;
140
122
  }
123
+ if (nextRequest.resolvedTo) {
124
+ return nextRequest.resolvedTo;
125
+ }
141
126
  if (nextRequest.fromFile === request.fromFile && nextRequest.specifier === request.specifier) {
142
127
  throw new Error('Bug Discovered! New request is not === original request but has the same fromFile and specifier. This will likely create a loop.');
143
128
  }
144
- if (nextRequest.isVirtual) {
145
- // virtual requests are terminal, there is no more beforeResolve or
146
- // fallbackResolve around them. The defaultResolve is expected to know how
147
- // to implement them.
148
- return yield defaultResolve(nextRequest);
129
+ if (nextRequest.isVirtual || nextRequest.isNotFound) {
130
+ // virtual and NotFound requests are terminal, there is no more
131
+ // beforeResolve or fallbackResolve around them. The defaultResolve is
132
+ // expected to know how to implement them.
133
+ return nextRequest.defaultResolve();
149
134
  }
150
- return yield* this.internalResolve(nextRequest, defaultResolve);
135
+ return this.resolve(nextRequest);
151
136
  }
152
137
  // Use standard NodeJS resolving, with our required compatibility rules on
153
138
  // top. This is a convenience method for calling resolveSync with the
154
139
  // defaultResolve already configured to be "do the normal node thing".
155
- nodeResolve(specifier, fromFile) {
156
- let resolution = this.resolveSync(new NodeModuleRequest(specifier, fromFile, false, undefined), request => {
157
- if (request.isVirtual) {
158
- return {
159
- type: 'found',
160
- result: {
161
- type: 'virtual',
162
- content: (0, virtual_content_1.virtualContent)(request.specifier, this),
163
- filename: request.specifier,
164
- },
165
- };
166
- }
167
- try {
168
- let filename = resolve_1.default.sync(request.specifier, {
169
- basedir: (0, path_1.dirname)(request.fromFile),
170
- extensions: this.options.resolvableExtensions,
171
- });
172
- return { type: 'found', result: { type: 'real', filename } };
173
- }
174
- catch (err) {
175
- if (err.code !== 'MODULE_NOT_FOUND') {
176
- throw err;
177
- }
178
- return { type: 'not_found', err };
179
- }
180
- });
181
- switch (resolution.type) {
182
- case 'not_found':
183
- return resolution;
184
- case 'found':
185
- return resolution.result;
186
- default:
187
- throw (0, assert_never_1.default)(resolution);
188
- }
140
+ async nodeResolve(specifier, fromFile) {
141
+ return (0, node_resolve_1.nodeResolve)(this, specifier, fromFile);
189
142
  }
190
143
  get packageCache() {
191
144
  return shared_internals_2.RewrittenPackageCache.shared('embroider', this.options.appRoot);
@@ -202,6 +155,9 @@ class Resolver {
202
155
  return owningPackage;
203
156
  }
204
157
  generateFastbootSwitch(request) {
158
+ if (isTerminal(request)) {
159
+ return request;
160
+ }
205
161
  let pkg = this.packageCache.ownerOfFile(request.fromFile);
206
162
  if (!pkg) {
207
163
  return request;
@@ -219,7 +175,9 @@ class Resolver {
219
175
  let fastbootFile = engineConfig.fastbootFiles[candidate];
220
176
  if (fastbootFile) {
221
177
  if (fastbootFile.shadowedFilename) {
222
- let { names } = (0, describe_exports_1.describeExports)((0, fs_1.readFileSync)((0, path_1.resolve)(pkg.root, fastbootFile.shadowedFilename), 'utf8'), {});
178
+ let { names } = (0, describe_exports_1.describeExports)((0, fs_1.readFileSync)((0, path_1.resolve)(pkg.root, fastbootFile.shadowedFilename), 'utf8'), {
179
+ configFile: false,
180
+ });
223
181
  let switchFile = (0, virtual_content_1.fastbootSwitch)(candidate, (0, path_1.resolve)(pkg.root, 'package.json'), names);
224
182
  if (switchFile === request.fromFile) {
225
183
  return logTransition('internal lookup from fastbootSwitch', request);
@@ -238,6 +196,9 @@ class Resolver {
238
196
  }
239
197
  handleFastbootSwitch(request) {
240
198
  var _a;
199
+ if (isTerminal(request)) {
200
+ return request;
201
+ }
241
202
  let match = (0, virtual_content_1.decodeFastbootSwitch)(request.fromFile);
242
203
  if (!match) {
243
204
  return request;
@@ -276,12 +237,15 @@ class Resolver {
276
237
  }
277
238
  let entry = (_a = this.getEntryFromMergeMap(rel, pkg.root)) === null || _a === void 0 ? void 0 : _a.entry;
278
239
  if ((entry === null || entry === void 0 ? void 0 : entry.type) === 'both') {
279
- return logTransition('matched addon entry', request, request.alias(entry[section].localPath).rehome((0, path_1.resolve)(entry[section].packageRoot, 'package.json')));
240
+ return logTransition('matched addon entry', request, request.alias(entry[section].specifier).rehome(entry[section].fromFile));
280
241
  }
281
242
  }
282
243
  return logTransition('failed to match in fastboot switch', request);
283
244
  }
284
245
  handleImplicitModules(request) {
246
+ if (isTerminal(request)) {
247
+ return request;
248
+ }
285
249
  let im = (0, virtual_content_1.decodeImplicitModules)(request.specifier);
286
250
  if (!im) {
287
251
  return request;
@@ -299,7 +263,97 @@ class Resolver {
299
263
  return logTransition(`own implicit modules`, request, request.virtualize((0, path_1.resolve)(pkg.root, `-embroider-${im.type}.js`)));
300
264
  }
301
265
  }
302
- handleGlobalsCompat(request) {
266
+ handleEntrypoint(request) {
267
+ var _a;
268
+ if (isTerminal(request)) {
269
+ return request;
270
+ }
271
+ //TODO move the extra forwardslash handling out into the vite plugin
272
+ const candidates = [
273
+ '@embroider/virtual/compat-modules',
274
+ '/@embroider/virtual/compat-modules',
275
+ './@embroider/virtual/compat-modules',
276
+ ];
277
+ if (!candidates.some(c => request.specifier.startsWith(c + '/') || request.specifier === c)) {
278
+ return request;
279
+ }
280
+ const result = /\.?\/?@embroider\/virtual\/compat-modules(?:\/(?<packageName>.*))?/.exec(request.specifier);
281
+ if (!result) {
282
+ // TODO make a better error
283
+ throw new Error('entrypoint does not match pattern' + request.specifier);
284
+ }
285
+ const { packageName } = result.groups;
286
+ const requestingPkg = this.packageCache.ownerOfFile(request.fromFile);
287
+ if (!(requestingPkg === null || requestingPkg === void 0 ? void 0 : requestingPkg.isV2Ember())) {
288
+ throw new Error(`bug: found entrypoint import in non-ember package at ${request.fromFile}`);
289
+ }
290
+ let pkg;
291
+ if (packageName) {
292
+ pkg = this.packageCache.resolve(packageName, requestingPkg);
293
+ }
294
+ else {
295
+ pkg = requestingPkg;
296
+ }
297
+ let matched = (0, resolve_exports_1.exports)(pkg.packageJSON, '-embroider-entrypoint.js', {
298
+ browser: true,
299
+ conditions: ['default', 'imports'],
300
+ });
301
+ return logTransition('entrypoint', request, request.virtualize((0, path_1.resolve)(pkg.root, (_a = matched === null || matched === void 0 ? void 0 : matched[0]) !== null && _a !== void 0 ? _a : '-embroider-entrypoint.js')));
302
+ }
303
+ handleRouteEntrypoint(request) {
304
+ if (isTerminal(request)) {
305
+ return request;
306
+ }
307
+ let routeName = (0, virtual_route_entrypoint_1.decodePublicRouteEntrypoint)(request.specifier);
308
+ if (!routeName) {
309
+ return request;
310
+ }
311
+ let pkg = this.packageCache.ownerOfFile(request.fromFile);
312
+ if (!(pkg === null || pkg === void 0 ? void 0 : pkg.isV2Ember())) {
313
+ throw new Error(`bug: found entrypoint import in non-ember package at ${request.fromFile}`);
314
+ }
315
+ let matched = (0, resolve_exports_1.exports)(pkg.packageJSON, '-embroider-route-entrypoint.js', {
316
+ browser: true,
317
+ conditions: ['default', 'imports'],
318
+ });
319
+ return logTransition('route entrypoint', request, request.virtualize((0, virtual_route_entrypoint_1.encodeRouteEntrypoint)(pkg.root, matched === null || matched === void 0 ? void 0 : matched[0], routeName)));
320
+ }
321
+ handleImplicitTestScripts(request) {
322
+ //TODO move the extra forwardslash handling out into the vite plugin
323
+ const candidates = [
324
+ '@embroider/virtual/test-support.js',
325
+ '/@embroider/virtual/test-support.js',
326
+ './@embroider/virtual/test-support.js',
327
+ ];
328
+ if (!candidates.includes(request.specifier)) {
329
+ return request;
330
+ }
331
+ let pkg = this.packageCache.ownerOfFile(request.fromFile);
332
+ if ((pkg === null || pkg === void 0 ? void 0 : pkg.root) !== this.options.engines[0].root) {
333
+ 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/virtual/test-support.js. If you think something should be fixed in Embroider, please open an issue on https://github.com/embroider-build/embroider/issues.`);
334
+ }
335
+ return logTransition('test-support', request, request.virtualize((0, path_1.resolve)(pkg.root, '-embroider-test-support.js')));
336
+ }
337
+ handleTestSupportStyles(request) {
338
+ //TODO move the extra forwardslash handling out into the vite plugin
339
+ const candidates = [
340
+ '@embroider/virtual/test-support.css',
341
+ '/@embroider/virtual/test-support.css',
342
+ './@embroider/virtual/test-support.css',
343
+ ];
344
+ if (!candidates.includes(request.specifier)) {
345
+ return request;
346
+ }
347
+ let pkg = this.packageCache.ownerOfFile(request.fromFile);
348
+ if ((pkg === null || pkg === void 0 ? void 0 : pkg.root) !== this.options.engines[0].root) {
349
+ 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/virtual/test-support.css. If you think something should be fixed in Embroider, please open an issue on https://github.com/embroider-build/embroider/issues.`);
350
+ }
351
+ return logTransition('test-support-styles', request, request.virtualize((0, path_1.resolve)(pkg.root, '-embroider-test-support-styles.css')));
352
+ }
353
+ async handleGlobalsCompat(request) {
354
+ if (isTerminal(request)) {
355
+ return request;
356
+ }
303
357
  let match = compatPattern.exec(request.specifier);
304
358
  if (!match) {
305
359
  return request;
@@ -320,62 +374,92 @@ class Resolver {
320
374
  case 'ambiguous':
321
375
  return this.resolveHelperOrComponent(rest, engine, request);
322
376
  default:
323
- throw new Error(`bug: unexepected #embroider_compat specifier: ${request.specifier}`);
377
+ throw new Error(`bug: unexepected @embroider/virtual specifier: ${request.specifier}`);
324
378
  }
325
379
  }
380
+ handleVendorStyles(request) {
381
+ //TODO move the extra forwardslash handling out into the vite plugin
382
+ const candidates = [
383
+ '@embroider/virtual/vendor.css',
384
+ '/@embroider/virtual/vendor.css',
385
+ './@embroider/virtual/vendor.css',
386
+ ];
387
+ if (!candidates.includes(request.specifier)) {
388
+ return request;
389
+ }
390
+ let pkg = this.packageCache.ownerOfFile(request.fromFile);
391
+ if (!pkg || !this.options.engines.some(e => e.root === (pkg === null || pkg === void 0 ? void 0 : pkg.root))) {
392
+ throw new Error(`bug: found an import of ${request.specifier} in ${request.fromFile}, but this is not the top-level Ember app or Engine. The top-level Ember app is the only one that has support for @embroider/virtual/vendor.css. If you think something should be fixed in Embroider, please open an issue on https://github.com/embroider-build/embroider/issues.`);
393
+ }
394
+ return logTransition('vendor-styles', request, request.virtualize((0, path_1.resolve)(pkg.root, '-embroider-vendor-styles.css')));
395
+ }
326
396
  resolveHelper(path, inEngine, request) {
327
397
  let target = this.parseGlobalPath(path, inEngine);
328
398
  return logTransition('resolveHelper', request, request.alias(`${target.packageName}/helpers/${target.memberName}`).rehome((0, path_1.resolve)(inEngine.root, 'package.json')));
329
399
  }
330
- resolveComponent(path, inEngine, request) {
400
+ async resolveComponent(path, inEngine, request) {
331
401
  let target = this.parseGlobalPath(path, inEngine);
332
402
  let hbsModule = null;
333
403
  let jsModule = null;
334
404
  // first, the various places our template might be.
335
405
  for (let candidate of this.componentTemplateCandidates(target.packageName)) {
336
- let resolution = this.nodeResolve(`${target.packageName}${candidate.prefix}${target.memberName}${candidate.suffix}`, target.from);
337
- if (resolution.type === 'real') {
338
- hbsModule = resolution.filename;
406
+ let candidateSpecifier = `${target.packageName}${candidate.prefix}${target.memberName}${candidate.suffix}`;
407
+ let resolution = await this.resolve(request.alias(candidateSpecifier).rehome(target.from).withMeta({
408
+ runtimeFallback: false,
409
+ }));
410
+ if (resolution.type === 'found') {
411
+ hbsModule = resolution;
339
412
  break;
340
413
  }
341
414
  }
342
415
  // then the various places our javascript might be.
343
416
  for (let candidate of this.componentJSCandidates(target.packageName)) {
344
- let resolution = this.nodeResolve(`${target.packageName}${candidate.prefix}${target.memberName}${candidate.suffix}`, target.from);
417
+ let candidateSpecifier = `${target.packageName}${candidate.prefix}${target.memberName}${candidate.suffix}`;
418
+ let resolution = await this.resolve(request.alias(candidateSpecifier).rehome(target.from).withMeta({
419
+ runtimeFallback: false,
420
+ }));
421
+ if (resolution.type === 'ignored') {
422
+ return logTransition(`resolving to ignored component`, request, request.resolveTo(resolution));
423
+ }
345
424
  // .hbs is a resolvable extension for us, so we need to exclude it here.
346
425
  // It matches as a priority lower than .js, so finding an .hbs means
347
426
  // there's definitely not a .js.
348
- if (resolution.type === 'real' && !resolution.filename.endsWith('.hbs')) {
349
- jsModule = resolution.filename;
427
+ if (resolution.type === 'found' && !resolution.filename.endsWith('.hbs')) {
428
+ jsModule = resolution;
350
429
  break;
351
430
  }
352
431
  }
353
432
  if (hbsModule) {
354
433
  if (!this.emberVersionSupportsSeparateTemplates) {
355
- throw new Error(`Components with separately resolved templates were removed at Ember 6.0. Migrate to either co-located js/ts + hbs files or to gjs/gts. https://deprecations.emberjs.com/id/component-template-resolving/. Bad template was: ${hbsModule}.`);
434
+ throw new Error(`Components with separately resolved templates were removed at Ember 6.0. Migrate to either co-located js/ts + hbs files or to gjs/gts. https://deprecations.emberjs.com/id/component-template-resolving/. Bad template was: ${hbsModule.filename}.`);
356
435
  }
357
- return logTransition(`resolveComponent found legacy HBS`, request, request.virtualize((0, virtual_content_1.virtualPairComponent)(hbsModule, jsModule)));
436
+ 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)));
358
437
  }
359
438
  else if (jsModule) {
360
- return logTransition(`resolveComponent found only JS`, request, request.alias(jsModule).rehome(target.from));
439
+ return logTransition(`resolving to resolveComponent found only JS`, request, request.resolveTo(jsModule));
361
440
  }
362
441
  else {
363
442
  return logTransition(`resolveComponent failed`, request);
364
443
  }
365
444
  }
366
- resolveHelperOrComponent(path, inEngine, request) {
445
+ async resolveHelperOrComponent(path, inEngine, request) {
367
446
  // resolveHelper just rewrites our request to one that should target the
368
447
  // component, so here to resolve the ambiguity we need to actually resolve
369
448
  // that candidate to see if it works.
370
449
  let helperCandidate = this.resolveHelper(path, inEngine, request);
371
- let helperMatch = this.nodeResolve(helperCandidate.specifier, helperCandidate.fromFile);
372
- if (helperMatch.type === 'real') {
373
- return logTransition('ambiguous case matched a helper', request, helperCandidate);
450
+ let helperMatch = await this.resolve(request.alias(helperCandidate.specifier).rehome(helperCandidate.fromFile).withMeta({
451
+ runtimeFallback: false,
452
+ }));
453
+ // for the case of 'ignored' that means that esbuild found this helper in an external
454
+ // package so it should be considered found in this case and we should not look for a
455
+ // component with this name
456
+ if (helperMatch.type === 'found' || helperMatch.type === 'ignored') {
457
+ return logTransition('resolve to ambiguous case matched a helper', request, request.resolveTo(helperMatch));
374
458
  }
375
459
  // unlike resolveHelper, resolveComponent already does pre-resolution in
376
460
  // order to deal with its own internal ambiguity around JS vs HBS vs
377
461
  // colocation.≥
378
- let componentMatch = this.resolveComponent(path, inEngine, request);
462
+ let componentMatch = await this.resolveComponent(path, inEngine, request);
379
463
  if (componentMatch !== request) {
380
464
  return logTransition('ambiguous case matched a cmoponent', request, componentMatch);
381
465
  }
@@ -400,6 +484,7 @@ class Resolver {
400
484
  }
401
485
  *componentJSCandidates(inPackageName) {
402
486
  yield { prefix: '/components/', suffix: '' };
487
+ yield { prefix: '/components/', suffix: '/index' };
403
488
  yield { prefix: '/components/', suffix: '/component' };
404
489
  let pods = this.podPrefix(inPackageName);
405
490
  if (pods) {
@@ -418,10 +503,10 @@ class Resolver {
418
503
  parseGlobalPath(path, inEngine) {
419
504
  let parts = path.split('@');
420
505
  if (parts.length > 1 && parts[0].length > 0) {
421
- return { packageName: parts[0], memberName: parts[1], from: (0, path_1.resolve)(inEngine.root, 'pacakge.json') };
506
+ return { packageName: parts[0], memberName: parts[1], from: (0, path_1.resolve)(inEngine.root, 'package.json') };
422
507
  }
423
508
  else {
424
- return { packageName: inEngine.packageName, memberName: path, from: (0, path_1.resolve)(inEngine.root, 'pacakge.json') };
509
+ return { packageName: inEngine.packageName, memberName: path, from: (0, path_1.resolve)(inEngine.root, 'package.json') };
425
510
  }
426
511
  }
427
512
  engineConfig(packageName) {
@@ -447,14 +532,18 @@ class Resolver {
447
532
  if (!inAddonName.startsWith('./')) {
448
533
  throw new Error(`addon ${addon.name} declares app-js in its package.json with the illegal name "${inAddonName}". It must start with "./" to make it clear that it's relative to the addon`);
449
534
  }
535
+ let specifier = (0, reverse_exports_1.externalName)(addon.packageJSON, inAddonName);
536
+ if (!specifier) {
537
+ throw new Error(`${addon.name}'s package.json app-js refers to ${inAddonName}, but that module is not accessible from outside the package`);
538
+ }
450
539
  let prevEntry = engineModules.get(inEngineName);
451
540
  switch (prevEntry === null || prevEntry === void 0 ? void 0 : prevEntry.type) {
452
541
  case undefined:
453
542
  engineModules.set(inEngineName, {
454
543
  type: 'app-only',
455
544
  'app-js': {
456
- localPath: inAddonName,
457
- packageRoot: addon.root,
545
+ specifier,
546
+ fromFile: addonConfig.canResolveFromFile,
458
547
  fromPackageName: addon.name,
459
548
  },
460
549
  });
@@ -467,8 +556,8 @@ class Resolver {
467
556
  engineModules.set(inEngineName, {
468
557
  type: 'both',
469
558
  'app-js': {
470
- localPath: inAddonName,
471
- packageRoot: addon.root,
559
+ specifier,
560
+ fromFile: addonConfig.canResolveFromFile,
472
561
  fromPackageName: addon.name,
473
562
  },
474
563
  'fastboot-js': prevEntry['fastboot-js'],
@@ -486,14 +575,18 @@ class Resolver {
486
575
  if (!inAddonName.startsWith('./')) {
487
576
  throw new Error(`addon ${addon.name} declares fastboot-js in its package.json with the illegal name "${inAddonName}". It must start with "./" to make it clear that it's relative to the addon`);
488
577
  }
578
+ let specifier = (0, reverse_exports_1.externalName)(addon.packageJSON, inAddonName);
579
+ if (!specifier) {
580
+ throw new Error(`${addon.name}'s package.json fastboot-js refers to ${inAddonName}, but that module is not accessible from outside the package`);
581
+ }
489
582
  let prevEntry = engineModules.get(inEngineName);
490
583
  switch (prevEntry === null || prevEntry === void 0 ? void 0 : prevEntry.type) {
491
584
  case undefined:
492
585
  engineModules.set(inEngineName, {
493
586
  type: 'fastboot-only',
494
587
  'fastboot-js': {
495
- localPath: inAddonName,
496
- packageRoot: addon.root,
588
+ specifier,
589
+ fromFile: addonConfig.canResolveFromFile,
497
590
  fromPackageName: addon.name,
498
591
  },
499
592
  });
@@ -506,8 +599,8 @@ class Resolver {
506
599
  engineModules.set(inEngineName, {
507
600
  type: 'both',
508
601
  'fastboot-js': {
509
- localPath: inAddonName,
510
- packageRoot: addon.root,
602
+ specifier,
603
+ fromFile: addonConfig.canResolveFromFile,
511
604
  fromPackageName: addon.name,
512
605
  },
513
606
  'app-js': prevEntry['app-js'],
@@ -538,7 +631,7 @@ class Resolver {
538
631
  });
539
632
  }
540
633
  handleRewrittenPackages(request) {
541
- if (request.isVirtual) {
634
+ if (isTerminal(request)) {
542
635
  return request;
543
636
  }
544
637
  let requestingPkg = this.packageCache.ownerOfFile(request.fromFile);
@@ -557,10 +650,6 @@ class Resolver {
557
650
  targetPkg = this.packageCache.resolve(packageName, requestingPkg);
558
651
  }
559
652
  catch (err) {
560
- // this is not the place to report resolution failures. If the thing
561
- // doesn't resolve, we're just not interested in redirecting it for
562
- // backward-compat, that's all. The rest of the system will take care of
563
- // reporting a failure to resolve (or handling it a different way)
564
653
  if (err.code !== 'MODULE_NOT_FOUND') {
565
654
  throw err;
566
655
  }
@@ -576,14 +665,26 @@ class Resolver {
576
665
  return logTransition('request targets a moved package', request, this.resolveWithinMovedPackage(request, targetPkg));
577
666
  }
578
667
  else if (originalRequestingPkg !== requestingPkg) {
579
- // in this case, the requesting package is moved but its destination is
580
- // not, so we need to rehome the request back to the original location.
581
- return logTransition('outbound request from moved package', request, request.withMeta({ wasMovedTo: request.fromFile }).rehome((0, path_1.resolve)(originalRequestingPkg.root, 'package.json')));
668
+ if (targetPkg) {
669
+ // in this case, the requesting package is moved but its destination is
670
+ // not, so we need to rehome the request back to the original location.
671
+ return logTransition('outbound request from moved package', request, request
672
+ // setting meta here because if this fails, we want the fallback
673
+ // logic to revert our rehome and continue from the *moved* package.
674
+ .withMeta({ originalFromFile: request.fromFile })
675
+ .rehome((0, path_1.resolve)(originalRequestingPkg.root, 'package.json')));
676
+ }
677
+ else {
678
+ // requesting package was moved and we failed to find its target. We
679
+ // can't let that accidentally succeed in the defaultResolve because we
680
+ // could escape the moved package system.
681
+ return logTransition('missing outbound request from moved package', request, request.notFound());
682
+ }
582
683
  }
583
684
  return request;
584
685
  }
585
686
  handleRenaming(request) {
586
- if (request.isVirtual) {
687
+ if (isTerminal(request)) {
587
688
  return request;
588
689
  }
589
690
  let packageName = (0, shared_internals_1.packageName)(request.specifier);
@@ -591,14 +692,11 @@ class Resolver {
591
692
  return request;
592
693
  }
593
694
  let pkg = this.packageCache.ownerOfFile(request.fromFile);
594
- if (!pkg || !pkg.isV2Ember()) {
595
- return request;
596
- }
597
695
  // real deps take precedence over renaming rules. That is, a package like
598
696
  // ember-source might provide backburner via module renaming, but if you
599
697
  // have an explicit dependency on backburner you should still get that real
600
698
  // copy.
601
- if (!pkg.hasDependency(packageName)) {
699
+ if (!(pkg === null || pkg === void 0 ? void 0 : pkg.hasDependency(packageName))) {
602
700
  for (let [candidate, replacement] of Object.entries(this.options.renameModules)) {
603
701
  if (candidate === request.specifier) {
604
702
  return logTransition(`renameModules`, request, request.alias(replacement));
@@ -616,30 +714,79 @@ class Resolver {
616
714
  return logTransition(`renamePackages`, request, request.alias(request.specifier.replace(packageName, this.options.renamePackages[packageName])));
617
715
  }
618
716
  }
619
- if (pkg.meta['auto-upgraded'] && pkg.name === packageName) {
620
- // we found a self-import, resolve it for them. Only auto-upgraded
621
- // packages get this help, v2 packages are natively supposed to make their
622
- // own modules resolvable, and we want to push them all to do that
623
- // correctly.
624
- return logTransition(`v1 self-import`, request, request.alias(request.specifier.replace(pkg.name, '.')).rehome((0, path_1.resolve)(pkg.root, 'package.json')));
717
+ if (!pkg || !pkg.isV2Ember()) {
718
+ return request;
719
+ }
720
+ if (pkg.name === packageName) {
721
+ // we found a self-import
722
+ if (pkg.meta['auto-upgraded']) {
723
+ // auto-upgraded packages always get automatically adjusted. They never
724
+ // supported fancy package.json exports features so this direct mapping
725
+ // to the root is always right.
726
+ // "my-app/foo" -> "./foo" from app's package.json
727
+ // "my-addon/foo" -> "my-addon/foo" from a package that's guaranteed to be able to resolve my-addon
728
+ let owningEngine = this.owningEngine(pkg);
729
+ let addonConfig = owningEngine.activeAddons.find(a => a.root === pkg.root);
730
+ if (addonConfig) {
731
+ // auto-upgraded addons get special support for self-resolving here.
732
+ return logTransition(`v1 addon self-import`, request, request.rehome(addonConfig.canResolveFromFile));
733
+ }
734
+ else {
735
+ // auto-upgraded apps will necessarily have packageJSON.exports
736
+ // because we insert them, so for that support we can fall through to
737
+ // that support below.
738
+ }
739
+ }
740
+ // v2 packages are supposed to use package.json `exports` to enable
741
+ // self-imports, but not all build tools actually follow the spec. This
742
+ // is a workaround for badly behaved packagers.
743
+ //
744
+ // Known upstream bugs this works around:
745
+ // - https://github.com/vitejs/vite/issues/9731
746
+ if (pkg.packageJSON.exports) {
747
+ let found = (0, resolve_exports_1.exports)(pkg.packageJSON, request.specifier, {
748
+ browser: true,
749
+ conditions: ['default', 'imports'],
750
+ });
751
+ if (found === null || found === void 0 ? void 0 : found[0]) {
752
+ 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')));
753
+ }
754
+ }
625
755
  }
626
756
  return request;
627
757
  }
758
+ handleVendor(request) {
759
+ //TODO move the extra forwardslash handling out into the vite plugin
760
+ const candidates = [
761
+ '@embroider/virtual/vendor.js',
762
+ '/@embroider/virtual/vendor.js',
763
+ './@embroider/virtual/vendor.js',
764
+ ];
765
+ if (!candidates.includes(request.specifier)) {
766
+ return request;
767
+ }
768
+ let pkg = this.packageCache.ownerOfFile(request.fromFile);
769
+ if ((pkg === null || pkg === void 0 ? void 0 : pkg.root) !== this.options.engines[0].root) {
770
+ 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/virtual/vendor.js. If you think something should be fixed in Embroider, please open an issue on https://github.com/embroider-build/embroider/issues.`);
771
+ }
772
+ return logTransition('vendor', request, request.virtualize((0, path_1.resolve)(pkg.root, '-embroider-vendor.js')));
773
+ }
628
774
  resolveWithinMovedPackage(request, pkg) {
629
775
  let levels = ['..'];
630
776
  if (pkg.name.startsWith('@')) {
631
777
  levels.push('..');
632
778
  }
779
+ let originalFromFile = request.fromFile;
633
780
  let newRequest = request.rehome((0, path_1.resolve)(pkg.root, ...levels, 'moved-package-target.js'));
634
781
  if (newRequest === request) {
635
782
  return request;
636
783
  }
637
- return newRequest.withMeta({
638
- resolvedWithinPackage: pkg.root,
639
- });
784
+ // setting meta because if this fails, we want the fallback to pick up back
785
+ // in the original requesting package.
786
+ return newRequest.withMeta({ originalFromFile });
640
787
  }
641
788
  preHandleExternal(request) {
642
- if (request.isVirtual) {
789
+ if (isTerminal(request)) {
643
790
  return request;
644
791
  }
645
792
  let { specifier, fromFile } = request;
@@ -649,11 +796,6 @@ class Resolver {
649
796
  }
650
797
  let packageName = (0, shared_internals_1.packageName)(specifier);
651
798
  if (!packageName) {
652
- // This is a relative import. We don't automatically externalize those
653
- // because it's rare, and by keeping them static we give better errors. But
654
- // we do allow them to be explicitly externalized by the package author (or
655
- // a compat adapter). In the metadata, they would be listed in
656
- // package-relative form, so we need to convert this specifier to that.
657
799
  let absoluteSpecifier = (0, path_1.resolve)((0, path_1.dirname)(fromFile), specifier);
658
800
  if (!absoluteSpecifier.startsWith(pkg.root)) {
659
801
  // this relative path escape its package. So it's not really using
@@ -662,36 +804,23 @@ class Resolver {
662
804
  // references to runtime utilities, like we do in @embroider/macros.
663
805
  return logTransition('beforeResolve: relative path escapes its package', request);
664
806
  }
665
- let packageRelativeSpecifier = (0, shared_internals_2.explicitRelative)(pkg.root, absoluteSpecifier);
666
- if (isExplicitlyExternal(packageRelativeSpecifier, pkg)) {
667
- let publicSpecifier = absoluteSpecifier.replace(pkg.root, pkg.name);
668
- return this.external('beforeResolve', request, publicSpecifier);
669
- }
670
807
  // if the requesting file is in an addon's app-js, the relative request
671
808
  // should really be understood as a request for a module in the containing
672
- // engine
809
+ // engine.
673
810
  let logicalLocation = this.reverseSearchAppTree(pkg, request.fromFile);
674
811
  if (logicalLocation) {
675
- return logTransition('beforeResolve: relative import in app-js', request, request.rehome((0, path_1.resolve)(logicalLocation.owningEngine.root, logicalLocation.inAppName)));
812
+ return logTransition('beforeResolve: relative import in app-js', request, request.alias(path_1.posix.join(logicalLocation.owningEngine.packageName, (0, path_1.dirname)(logicalLocation.inAppName), request.specifier)));
676
813
  }
677
814
  return request;
678
815
  }
679
- // absolute package imports can also be explicitly external based on their
680
- // full specifier name
681
- if (isExplicitlyExternal(specifier, pkg)) {
682
- return this.external('beforeResolve', request, specifier);
683
- }
684
- if (shared_internals_1.emberVirtualPackages.has(packageName) && !pkg.hasDependency(packageName)) {
685
- return this.external('beforeResolve emberVirtualPackages', request, specifier);
686
- }
687
816
  if (shared_internals_1.emberVirtualPeerDeps.has(packageName) && !pkg.hasDependency(packageName)) {
688
817
  // addons (whether auto-upgraded or not) may use the app's
689
818
  // emberVirtualPeerDeps, like "@glimmer/component" etc.
690
- if (!this.options.activeAddons[packageName]) {
691
- throw new Error(`${pkg.name} is trying to import the app's ${packageName} package, but it seems to be missing`);
819
+ let addon = this.locateActiveAddon(packageName);
820
+ if (!addon) {
821
+ throw new Error(`${pkg.name} is trying to import the emberVirtualPeerDep "${packageName}", but it seems to be missing`);
692
822
  }
693
- let newHome = (0, path_1.resolve)(this.packageCache.maybeMoved(this.packageCache.get(this.options.appRoot)).root, 'package.json');
694
- return logTransition(`emberVirtualPeerDeps in v2 addon`, request, request.rehome(newHome));
823
+ return logTransition(`emberVirtualPeerDeps`, request, request.rehome(addon.canResolveFromFile));
695
824
  }
696
825
  // if this file is part of an addon's app-js, it's really the logical
697
826
  // package to which it belongs (normally the app) that affects some policy
@@ -700,10 +829,10 @@ class Resolver {
700
829
  if (logicalPackage.meta['auto-upgraded'] && !logicalPackage.hasDependency('ember-auto-import')) {
701
830
  try {
702
831
  let dep = this.packageCache.resolve(packageName, logicalPackage);
703
- if (!dep.isEmberPackage()) {
832
+ if (!dep.isEmberAddon()) {
704
833
  // classic ember addons can only import non-ember dependencies if they
705
834
  // have ember-auto-import.
706
- return this.external('v1 package without auto-import', request, specifier);
835
+ return logTransition('v1 package without auto-import', request, request.notFound());
707
836
  }
708
837
  }
709
838
  catch (err) {
@@ -713,49 +842,33 @@ class Resolver {
713
842
  }
714
843
  }
715
844
  // assertions on what native v2 addons can import
716
- if (!pkg.meta['auto-upgraded']) {
717
- if (!pkg.meta['auto-upgraded'] &&
718
- !appImportInAppTree(pkg, logicalPackage, packageName) &&
719
- !reliablyResolvable(pkg, packageName)) {
720
- throw new Error(`${pkg.name} is trying to import from ${packageName} but that is not one of its explicit dependencies`);
721
- }
845
+ if (!pkg.needsLooseResolving() &&
846
+ !appImportInAppTree(pkg, logicalPackage, packageName) &&
847
+ !reliablyResolvable(pkg, packageName)) {
848
+ throw new Error(`${pkg.name} is trying to import from ${packageName} but that is not one of its explicit dependencies`);
722
849
  }
723
850
  return request;
724
851
  }
725
- external(label, request, specifier) {
726
- if (this.options.amdCompatibility === 'cjs') {
727
- let filename = (0, virtual_content_1.virtualExternalCJSModule)(specifier);
728
- return logTransition(label, request, request.virtualize(filename));
729
- }
730
- else if (this.options.amdCompatibility) {
731
- let entry = this.options.amdCompatibility.es.find(entry => entry[0] === specifier || entry[0] + '/index' === specifier);
732
- if (!entry && request.specifier === 'require') {
733
- entry = ['require', ['default', 'has']];
734
- }
735
- if (!entry) {
736
- throw new Error(`A module tried to resolve "${request.specifier}" and didn't find it (${label}).
737
-
738
- - Maybe a dependency declaration is missing?
739
- - Remember that v1 addons can only import non-Ember-addon NPM dependencies if they include ember-auto-import in their dependencies.
740
- - If this dependency is available in the AMD loader (because someone manually called "define()" for it), you can configure a shim like:
741
-
742
- amdCompatibility: {
743
- es: [
744
- ["${request.specifier}", ["default", "yourNamedExportsGoHere"]],
745
- ]
746
- }
747
-
748
- `);
749
- }
750
- let filename = (0, virtual_content_1.virtualExternalESModule)(specifier, entry[1]);
751
- return logTransition(label, request, request.virtualize(filename));
852
+ locateActiveAddon(packageName) {
853
+ if (packageName === this.options.modulePrefix) {
854
+ // the app itself is something that addon's can classically resolve if they know it's name.
855
+ return {
856
+ root: this.options.appRoot,
857
+ canResolveFromFile: (0, path_1.resolve)(this.packageCache.maybeMoved(this.packageCache.get(this.options.appRoot)).root, 'package.json'),
858
+ };
752
859
  }
753
- else {
754
- throw new Error(`Embroider's amdCompatibility option is disabled, but something tried to use it to access "${request.specifier}"`);
860
+ for (let engine of this.options.engines) {
861
+ for (let addon of engine.activeAddons) {
862
+ if (addon.name === packageName) {
863
+ return addon;
864
+ }
865
+ }
755
866
  }
756
867
  }
757
- fallbackResolve(request) {
758
- var _a, _b, _c;
868
+ async fallbackResolve(request) {
869
+ if (request.isVirtual) {
870
+ 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');
871
+ }
759
872
  if (request.specifier === '@embroider/macros') {
760
873
  // the macros package is always handled directly within babel (not
761
874
  // necessarily as a real resolvable package), so we should not mess with it.
@@ -763,108 +876,124 @@ class Resolver {
763
876
  // why we need to know about it.
764
877
  return logTransition('fallback early exit', request);
765
878
  }
766
- let { specifier, fromFile } = request;
767
- if (compatPattern.test(specifier)) {
879
+ if (compatPattern.test(request.specifier)) {
768
880
  // Some kinds of compat requests get rewritten into other things
769
- // deterministically. For example, "#embroider_compat/helpers/whatever"
881
+ // deterministically. For example, "@embroider/virtual/helpers/whatever"
770
882
  // means only "the-current-engine/helpers/whatever", and if that doesn't
771
883
  // actually exist it's that path that will show up as a missing import.
772
884
  //
773
885
  // But others have an ambiguous meaning. For example,
774
- // #embroider_compat/components/whatever can mean several different
886
+ // @embroider/virtual/components/whatever can mean several different
775
887
  // things. If we're unable to find any of them, the actual
776
- // "#embroider_compat" request will fall through all the way to here.
888
+ // "@embroider/virtual" request will fall through all the way to here.
777
889
  //
778
890
  // In that case, we don't want to externalize that failure. We know it's
779
891
  // not a classic runtime thing. It's better to let it be a build error
780
892
  // here.
781
893
  return request;
782
894
  }
783
- if (fromFile.endsWith('moved-package-target.js')) {
784
- if (!((_a = request.meta) === null || _a === void 0 ? void 0 : _a.resolvedWithinPackage)) {
785
- throw new Error(`bug: embroider resolver's meta is not propagating`);
786
- }
787
- fromFile = (0, path_1.resolve)((_b = request.meta) === null || _b === void 0 ? void 0 : _b.resolvedWithinPackage, 'package.json');
788
- }
789
- let pkg = this.packageCache.ownerOfFile(fromFile);
790
- if (!pkg) {
791
- return logTransition('no identifiable owningPackage', request);
895
+ let pkg = this.packageCache.ownerOfFile(request.fromFile);
896
+ if (pkg) {
897
+ ({ pkg, request } = this.restoreRehomedRequest(pkg, request));
792
898
  }
793
- // if we rehomed this request to its un-rewritten location in order to try
794
- // to do the defaultResolve from there, now we refer back to the rewritten
795
- // location because that's what we want to use when asking things like
796
- // isV2Ember()
797
- let movedPkg = this.packageCache.maybeMoved(pkg);
798
- if (movedPkg !== pkg) {
799
- if (!((_c = request.meta) === null || _c === void 0 ? void 0 : _c.wasMovedTo)) {
800
- throw new Error(`bug: embroider resolver's meta is not propagating`);
899
+ if (!(pkg === null || pkg === void 0 ? void 0 : pkg.isV2Ember())) {
900
+ // this request is coming from a file that appears to be owned by no ember
901
+ // package. We offer one fallback behavior for such files. They're allowed
902
+ // to resolve from the app's namespace.
903
+ //
904
+ // This makes it possible for integrations like vite to leave references
905
+ // to the app in their pre-bundled dependencies, which will end up in an
906
+ // arbitrary cache that is not inside any particular package.
907
+ let description = pkg ? 'non-ember package' : 'unowned module';
908
+ let packageName = (0, shared_internals_1.packageName)(request.specifier);
909
+ if (packageName === this.options.modulePrefix) {
910
+ return logTransition(`fallbackResolver: ${description} resolved app namespace`, request, request.rehome(this.packageCache.maybeMoved(this.packageCache.get(this.options.appRoot)).root));
801
911
  }
802
- fromFile = request.meta.wasMovedTo;
803
- pkg = movedPkg;
804
- }
805
- if (!pkg.isV2Ember()) {
806
- return logTransition('fallbackResolve: not in an ember package', request);
912
+ return logTransition(`fallbackResolver: ${description}`, request);
807
913
  }
808
- let packageName = (0, shared_internals_1.packageName)(specifier);
914
+ let packageName = (0, shared_internals_1.packageName)(request.specifier);
809
915
  if (!packageName) {
810
916
  // this is a relative import
811
- let withinEngine = this.engineConfig(pkg.name);
812
- if (withinEngine) {
813
- // it's a relative import inside an engine (which also means app), which
814
- // means we may need to satisfy the request via app tree merging.
815
- let appJSMatch = this.searchAppTree(request, withinEngine, (0, shared_internals_2.explicitRelative)(pkg.root, (0, path_1.resolve)((0, path_1.dirname)(fromFile), specifier)));
816
- if (appJSMatch) {
817
- return logTransition('fallbackResolve: relative appJsMatch', request, appJSMatch);
818
- }
819
- else {
820
- return logTransition('fallbackResolve: relative appJs search failure', request);
821
- }
822
- }
823
- else {
824
- // nothing else to do for relative imports
825
- return logTransition('fallbackResolve: relative failure', request);
826
- }
917
+ return this.relativeFallbackResolve(pkg, request);
827
918
  }
828
- // auto-upgraded packages can fall back to the set of known active addons
829
- if (pkg.meta['auto-upgraded'] && this.options.activeAddons[packageName]) {
830
- const rehomed = this.resolveWithinMovedPackage(request, this.packageCache.get(this.options.activeAddons[packageName]));
831
- if (rehomed !== request) {
832
- return logTransition(`activeAddons`, request, rehomed);
919
+ if (pkg.needsLooseResolving()) {
920
+ let activeAddon = this.maybeFallbackToActiveAddon(request, packageName);
921
+ if (activeAddon) {
922
+ return activeAddon;
833
923
  }
834
924
  }
835
- let logicalLocation = this.reverseSearchAppTree(pkg, fromFile);
925
+ let logicalLocation = this.reverseSearchAppTree(pkg, request.fromFile);
836
926
  if (logicalLocation) {
837
927
  // the requesting file is in an addon's appTree. We didn't succeed in
838
928
  // resolving this (non-relative) request from inside the actual addon, so
839
929
  // next try to resolve it from the corresponding logical location in the
840
930
  // app.
841
- return logTransition('fallbackResolve: retry from logical home of app-js file', request, request.rehome((0, path_1.resolve)(logicalLocation.owningEngine.root, logicalLocation.inAppName)));
931
+ return logTransition('fallbackResolve: retry from logical home of app-js file', request,
932
+ // it might look more precise to rehome into logicalLocation.inAppName
933
+ // rather than package.json. But that logical location may not actually
934
+ // exist, and some systems (including node's require.resolve) will be
935
+ // mad about trying to resolve from notional paths that don't really
936
+ // exist.
937
+ request.rehome((0, path_1.resolve)(logicalLocation.owningEngine.root, 'package.json')));
842
938
  }
843
939
  let targetingEngine = this.engineConfig(packageName);
844
940
  if (targetingEngine) {
845
- let appJSMatch = this.searchAppTree(request, targetingEngine, specifier.replace(packageName, '.'));
941
+ let appJSMatch = await this.searchAppTree(request, targetingEngine, request.specifier.replace(packageName, '.'));
846
942
  if (appJSMatch) {
847
943
  return logTransition('fallbackResolve: non-relative appJsMatch', request, appJSMatch);
848
944
  }
849
945
  }
850
- if (pkg.meta['auto-upgraded']) {
851
- // auto-upgraded packages can fall back to attempting to find dependencies at
852
- // runtime. Native v2 packages can only get this behavior in the
853
- // isExplicitlyExternal case above because they need to explicitly ask for
854
- // externals.
855
- return this.external('v1 catch-all fallback', request, specifier);
946
+ // this is falling through with the original specifier which was
947
+ // non-resolvable, which will presumably cause a static build error in stage3.
948
+ return logTransition('fallbackResolve final exit', request);
949
+ }
950
+ restoreRehomedRequest(pkg, request) {
951
+ var _a;
952
+ // meta.originalFromFile gets set when we want to try to rehome a request
953
+ // but then come back to the original location here in the fallback when the
954
+ // rehomed request fails
955
+ let movedPkg = this.packageCache.maybeMoved(pkg);
956
+ if (movedPkg !== pkg) {
957
+ let originalFromFile = (_a = request.meta) === null || _a === void 0 ? void 0 : _a.originalFromFile;
958
+ if (typeof originalFromFile !== 'string') {
959
+ throw new Error(`bug: embroider resolver's meta is not propagating`);
960
+ }
961
+ request = request.rehome(originalFromFile);
962
+ pkg = movedPkg;
963
+ }
964
+ return { pkg, request };
965
+ }
966
+ async relativeFallbackResolve(pkg, request) {
967
+ let withinEngine = this.engineConfig(pkg.name);
968
+ if (withinEngine) {
969
+ // it's a relative import inside an engine (which also means app), which
970
+ // means we may need to satisfy the request via app tree merging.
971
+ let logicalName = engineRelativeName(pkg, (0, path_1.resolve)((0, path_1.dirname)(request.fromFile), request.specifier));
972
+ if (!logicalName) {
973
+ return logTransition('fallbackResolve: relative failure because this file is not externally accessible', request);
974
+ }
975
+ let appJSMatch = await this.searchAppTree(request, withinEngine, logicalName);
976
+ if (appJSMatch) {
977
+ return logTransition('fallbackResolve: relative appJsMatch', request, appJSMatch);
978
+ }
979
+ else {
980
+ return logTransition('fallbackResolve: relative appJs search failure', request);
981
+ }
856
982
  }
857
983
  else {
858
- // native v2 packages don't automatically externalize *everything* the way
859
- // auto-upgraded packages do, but they still externalize known and approved
860
- // ember virtual packages (like @ember/component)
861
- if (shared_internals_1.emberVirtualPackages.has(packageName)) {
862
- return this.external('emberVirtualPackages', request, specifier);
984
+ // nothing else to do for relative imports
985
+ return logTransition('fallbackResolve: relative failure', request);
986
+ }
987
+ }
988
+ maybeFallbackToActiveAddon(request, requestedPackageName) {
989
+ // auto-upgraded packages can fall back to the set of known active addons
990
+ let addon = this.locateActiveAddon(requestedPackageName);
991
+ if (addon) {
992
+ const rehomed = request.rehome(addon.canResolveFromFile);
993
+ if (rehomed !== request) {
994
+ return logTransition(`activeAddons`, request, rehomed);
863
995
  }
864
996
  }
865
- // this is falling through with the original specifier which was
866
- // non-resolvable, which will presumably cause a static build error in stage3.
867
- return logTransition('fallbackResolve final exit', request);
868
997
  }
869
998
  getEntryFromMergeMap(inEngineSpecifier, root) {
870
999
  var _a;
@@ -886,25 +1015,23 @@ class Resolver {
886
1015
  }
887
1016
  }
888
1017
  }
889
- searchAppTree(request, engine, inEngineSpecifier) {
1018
+ async searchAppTree(request, engine, inEngineSpecifier) {
890
1019
  let matched = this.getEntryFromMergeMap(inEngineSpecifier, engine.root);
891
1020
  switch (matched === null || matched === void 0 ? void 0 : matched.entry.type) {
892
1021
  case undefined:
893
1022
  return undefined;
894
1023
  case 'app-only':
895
- return request
896
- .alias(matched.entry['app-js'].localPath)
897
- .rehome((0, path_1.resolve)(matched.entry['app-js'].packageRoot, 'package.json'));
1024
+ return request.alias(matched.entry['app-js'].specifier).rehome(matched.entry['app-js'].fromFile);
898
1025
  case 'fastboot-only':
899
- return request
900
- .alias(matched.entry['fastboot-js'].localPath)
901
- .rehome((0, path_1.resolve)(matched.entry['fastboot-js'].packageRoot, 'package.json'));
1026
+ return request.alias(matched.entry['fastboot-js'].specifier).rehome(matched.entry['fastboot-js'].fromFile);
902
1027
  case 'both':
903
- let foundAppJS = this.nodeResolve(matched.entry['app-js'].localPath, (0, path_1.resolve)(matched.entry['app-js'].packageRoot, 'package.json'));
904
- if (foundAppJS.type !== 'real') {
1028
+ let foundAppJS = await this.resolve(request.alias(matched.entry['app-js'].specifier).rehome(matched.entry['app-js'].fromFile).withMeta({
1029
+ runtimeFallback: false,
1030
+ }));
1031
+ if (foundAppJS.type !== 'found') {
905
1032
  throw new Error(`${matched.entry['app-js'].fromPackageName} declared ${inEngineSpecifier} in packageJSON.ember-addon.app-js, but that module does not exist`);
906
1033
  }
907
- let { names } = (0, describe_exports_1.describeExports)((0, fs_1.readFileSync)(foundAppJS.filename, 'utf8'), {});
1034
+ let { names } = (0, describe_exports_1.describeExports)((0, fs_1.readFileSync)(foundAppJS.filename, 'utf8'), { configFile: false });
908
1035
  return request.virtualize((0, virtual_content_1.fastbootSwitch)(matched.matched, (0, path_1.resolve)(engine.root, 'package.json'), names));
909
1036
  }
910
1037
  }
@@ -939,14 +1066,10 @@ class Resolver {
939
1066
  if (engineConfig) {
940
1067
  // we're directly inside an engine, so we're potentially resolvable as a
941
1068
  // global component
942
- // this kind of mapping is not true in general for all packages, but it
943
- // *is* true for all classical engines (which includes apps) since they
944
- // don't support package.json `exports`. As for a future v2 engine or app:
945
- // this whole method is only relevant for implementing packageRules, which
946
- // should only be for classic stuff. v2 packages should do the right
947
- // things from the beginning and not need packageRules about themselves.
948
- let inAppName = (0, shared_internals_2.explicitRelative)(engineConfig.root, filename);
949
- return this.tryReverseComponent(engineConfig.packageName, inAppName);
1069
+ let inAppName = engineRelativeName(owningPackage, filename);
1070
+ if (inAppName) {
1071
+ return this.tryReverseComponent(engineConfig.packageName, inAppName);
1072
+ }
950
1073
  }
951
1074
  let engineInfo = this.reverseSearchAppTree(owningPackage, filename);
952
1075
  if (engineInfo) {
@@ -973,9 +1096,6 @@ __decorate([
973
1096
  __decorate([
974
1097
  (0, typescript_memoize_1.Memoize)()
975
1098
  ], Resolver.prototype, "emberVersionSupportsSeparateTemplates", null);
976
- function isExplicitlyExternal(specifier, fromPkg) {
977
- return Boolean(fromPkg.isV2Addon() && fromPkg.meta['externals'] && fromPkg.meta['externals'].includes(specifier));
978
- }
979
1099
  // we don't want to allow things that resolve only by accident that are likely
980
1100
  // to break in other setups. For example: import your dependencies'
981
1101
  // dependencies, or importing your own name from within a monorepo (which will
@@ -997,4 +1117,10 @@ function reliablyResolvable(pkg, packageName) {
997
1117
  function appImportInAppTree(inPackage, inLogicalPackage, importedPackageName) {
998
1118
  return inPackage !== inLogicalPackage && importedPackageName === inLogicalPackage.name;
999
1119
  }
1120
+ function engineRelativeName(pkg, filename) {
1121
+ let outsideName = (0, reverse_exports_1.externalName)(pkg.packageJSON, (0, shared_internals_2.explicitRelative)(pkg.root, filename));
1122
+ if (outsideName) {
1123
+ return '.' + outsideName.slice(pkg.name.length);
1124
+ }
1125
+ }
1000
1126
  //# sourceMappingURL=module-resolver.js.map