@embroider/core 3.5.0 → 3.5.1-unstable.0f6c294

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 (68) hide show
  1. package/package.json +22 -11
  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 +5 -5
  6. package/src/index.js +3 -4
  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/messages.js.map +1 -1
  11. package/src/module-request.d.ts +44 -0
  12. package/src/module-request.js +100 -0
  13. package/src/module-request.js.map +1 -0
  14. package/src/module-resolver-options.d.ts +42 -0
  15. package/src/module-resolver-options.js +164 -0
  16. package/src/module-resolver-options.js.map +1 -0
  17. package/src/module-resolver.d.ts +24 -61
  18. package/src/module-resolver.js +469 -322
  19. package/src/module-resolver.js.map +1 -1
  20. package/src/node-resolve.d.ts +35 -0
  21. package/src/node-resolve.js +130 -0
  22. package/src/node-resolve.js.map +1 -0
  23. package/src/options.d.ts +0 -7
  24. package/src/options.js +0 -1
  25. package/src/options.js.map +1 -1
  26. package/src/packager.d.ts +0 -8
  27. package/src/packager.js +0 -9
  28. package/src/packager.js.map +1 -1
  29. package/src/resolver-loader.js +8 -1
  30. package/src/resolver-loader.js.map +1 -1
  31. package/src/virtual-content.d.ts +32 -12
  32. package/src/virtual-content.js +83 -184
  33. package/src/virtual-content.js.map +1 -1
  34. package/src/virtual-entrypoint.d.ts +21 -0
  35. package/src/virtual-entrypoint.js +273 -0
  36. package/src/virtual-entrypoint.js.map +1 -0
  37. package/src/virtual-route-entrypoint.d.ts +10 -0
  38. package/src/virtual-route-entrypoint.js +62 -0
  39. package/src/virtual-route-entrypoint.js.map +1 -0
  40. package/src/virtual-test-support-styles.d.ts +7 -0
  41. package/src/virtual-test-support-styles.js +61 -0
  42. package/src/virtual-test-support-styles.js.map +1 -0
  43. package/src/virtual-test-support.d.ts +7 -0
  44. package/src/virtual-test-support.js +65 -0
  45. package/src/virtual-test-support.js.map +1 -0
  46. package/src/virtual-vendor-styles.d.ts +8 -0
  47. package/src/virtual-vendor-styles.js +83 -0
  48. package/src/virtual-vendor-styles.js.map +1 -0
  49. package/src/virtual-vendor.d.ts +7 -0
  50. package/src/virtual-vendor.js +53 -0
  51. package/src/virtual-vendor.js.map +1 -0
  52. package/types/virtual/index.d.ts +9 -0
  53. package/types/virtual/index.js +3 -0
  54. package/src/asset.d.ts +0 -32
  55. package/src/asset.js +0 -3
  56. package/src/asset.js.map +0 -1
  57. package/src/ember-html.d.ts +0 -43
  58. package/src/ember-html.js +0 -110
  59. package/src/ember-html.js.map +0 -1
  60. package/src/portable-babel-config.d.ts +0 -11
  61. package/src/portable-babel-config.js +0 -132
  62. package/src/portable-babel-config.js.map +0 -1
  63. package/src/portable-babel-launcher.d.ts +0 -6
  64. package/src/portable-babel-launcher.js +0 -75
  65. package/src/portable-babel-launcher.js.map +0 -1
  66. package/src/to-broccoli-plugin.d.ts +0 -8
  67. package/src/to-broccoli-plugin.js +0 -30
  68. package/src/to-broccoli-plugin.js.map +0 -1
@@ -15,64 +15,51 @@ 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"));
19
- const virtual_content_1 = require("./virtual-content");
18
+ const reverse_exports_1 = require("@embroider/reverse-exports");
19
+ const resolve_exports_1 = require("resolve.exports");
20
20
  const typescript_memoize_1 = require("typescript-memoize");
21
21
  const describe_exports_1 = require("./describe-exports");
22
22
  const fs_1 = require("fs");
23
+ const node_resolve_1 = require("./node-resolve");
23
24
  const semver_1 = require("semver");
25
+ const module_request_1 = require("./module-request");
24
26
  const debug = (0, debug_1.default)('embroider:resolver');
27
+ // Using a formatter makes this work lazy so nothing happens when we aren't
28
+ // logging. It is unfortunate that formatters are a globally mutable config and
29
+ // you can only use single character names, but oh well.
30
+ debug_1.default.formatters.p = (s) => {
31
+ let cwd = process.cwd();
32
+ if (s.startsWith(cwd)) {
33
+ return s.slice(cwd.length + 1);
34
+ }
35
+ return s;
36
+ };
25
37
  function logTransition(reason, before, after = before) {
26
- if (after.isVirtual) {
27
- debug(`virtualized %s in %s because %s`, before.specifier, before.fromFile, reason);
38
+ if (after.resolvedTo) {
39
+ debug(`[%s:resolvedTo] %s because %s\n in %p`, before.debugType, before.specifier, reason, before.fromFile);
28
40
  }
29
41
  else if (before.specifier !== after.specifier) {
30
42
  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);
43
+ 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
44
  }
33
45
  else {
34
- debug(`aliased: %s to %s in %s because`, before.specifier, after.specifier, before.fromFile, reason);
46
+ debug(`[%s:aliased] %s to %s\n because %s`, before.debugType, before.specifier, after.specifier, reason);
35
47
  }
36
48
  }
37
49
  else if (before.fromFile !== after.fromFile) {
38
- debug(`rehomed: %s from %s to %s because`, before.specifier, before.fromFile, after.fromFile, reason);
50
+ debug(`[%s:rehomed] %s, because %s\n from %p\n to %p`, before.debugType, before.specifier, reason, before.fromFile, after.fromFile);
39
51
  }
40
52
  else {
41
- debug(`unchanged: %s in %s because %s`, before.specifier, before.fromFile, reason);
53
+ debug(`[%s:unchanged] %s because %s\n in %p`, before.debugType, before.specifier, reason, before.fromFile);
42
54
  }
43
55
  return after;
44
56
  }
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
- }
70
- }
57
+ const compatPattern = /@embroider\/virtual\/(?<type>[^\/]+)\/(?<rest>.*)/;
71
58
  class Resolver {
72
59
  constructor(options) {
73
60
  this.options = options;
74
61
  }
75
- beforeResolve(request) {
62
+ async beforeResolve(request) {
76
63
  if (request.specifier === '@embroider/macros') {
77
64
  // the macros package is always handled directly within babel (not
78
65
  // necessarily as a real resolvable package), so we should not mess with it.
@@ -81,9 +68,15 @@ class Resolver {
81
68
  return logTransition('early exit', request);
82
69
  }
83
70
  request = this.handleFastbootSwitch(request);
84
- request = this.handleGlobalsCompat(request);
71
+ request = await this.handleGlobalsCompat(request);
85
72
  request = this.handleImplicitModules(request);
73
+ request = this.handleImplicitTestScripts(request);
74
+ request = this.handleVendorStyles(request);
75
+ request = this.handleTestSupportStyles(request);
76
+ request = this.handleEntrypoint(request);
77
+ request = this.handleRouteEntrypoint(request);
86
78
  request = this.handleRenaming(request);
79
+ request = this.handleVendor(request);
87
80
  // we expect the specifier to be app relative at this point - must be after handleRenaming
88
81
  request = this.generateFastbootSwitch(request);
89
82
  request = this.preHandleExternal(request);
@@ -97,34 +90,16 @@ class Resolver {
97
90
  // that calls your build system's normal module resolver, this does both pre-
98
91
  // and post-resolution adjustments as needed to implement our compatibility
99
92
  // 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);
93
+ async resolve(request) {
94
+ request = await this.beforeResolve(request);
95
+ let resolution;
96
+ if (request.resolvedTo) {
97
+ resolution = await (0, module_request_1.extractResolution)(request.resolvedTo);
98
+ }
99
+ else {
100
+ resolution = await request.defaultResolve();
101
+ }
102
+ resolution = await this.afterResolve(request, resolution);
128
103
  switch (resolution.type) {
129
104
  case 'found':
130
105
  return resolution;
@@ -133,63 +108,57 @@ class Resolver {
133
108
  default:
134
109
  throw (0, assert_never_1.default)(resolution);
135
110
  }
136
- let nextRequest = this.fallbackResolve(request);
111
+ request = request.clone();
112
+ let nextRequest = await this.fallbackResolve(request);
137
113
  if (nextRequest === request) {
138
114
  // no additional fallback is available.
139
115
  return resolution;
140
116
  }
117
+ if (nextRequest.resolvedTo) {
118
+ return await (0, module_request_1.extractResolution)(nextRequest.resolvedTo);
119
+ }
141
120
  if (nextRequest.fromFile === request.fromFile && nextRequest.specifier === request.specifier) {
142
121
  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
122
  }
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);
149
- }
150
- return yield* this.internalResolve(nextRequest, defaultResolve);
123
+ return this.resolve(nextRequest);
151
124
  }
152
125
  // Use standard NodeJS resolving, with our required compatibility rules on
153
126
  // top. This is a convenience method for calling resolveSync with the
154
127
  // 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
- }
128
+ async nodeResolve(specifier, fromFile, opts) {
129
+ return (0, node_resolve_1.nodeResolve)(this, specifier, fromFile, opts);
189
130
  }
190
131
  get packageCache() {
191
132
  return shared_internals_2.RewrittenPackageCache.shared('embroider', this.options.appRoot);
192
133
  }
134
+ async afterResolve(request, resolution) {
135
+ resolution = await this.handleSyntheticComponents(request, resolution);
136
+ return resolution;
137
+ }
138
+ async handleSyntheticComponents(request, resolution) {
139
+ // Key assumption: the system's defaultResolve performs extension search for
140
+ // extensionless requests, with JS at a higher priority than HBS.
141
+ // When the request had an explicit ".js" extension, the system default
142
+ // extension search doesn't help us locate an HBS, so we need to check for
143
+ // it ourselves here.
144
+ if (resolution.type === 'not_found') {
145
+ let hbsSpecifier = (0, shared_internals_1.syntheticJStoHBS)(request.specifier);
146
+ if (hbsSpecifier) {
147
+ resolution = await this.resolve(request.alias(hbsSpecifier));
148
+ }
149
+ }
150
+ // At this point, we might have resolved an HBS file (either because the
151
+ // request was extensionless and the default search found it, or because of
152
+ // our own code above) when the request was for a JS file.
153
+ if (resolution.type === 'found') {
154
+ let syntheticId = (0, shared_internals_1.needsSyntheticComponentJS)(request.specifier, resolution.filename);
155
+ if (syntheticId && (0, shared_internals_1.isInComponents)(resolution.filename, this.packageCache)) {
156
+ let newRequest = logTransition(`synthetic component JS`, request, request.virtualize({ type: 'template-only-component-js', specifier: syntheticId }));
157
+ return await (0, module_request_1.extractResolution)(newRequest.resolvedTo);
158
+ }
159
+ }
160
+ return resolution;
161
+ }
193
162
  logicalPackage(owningPackage, file) {
194
163
  let logicalLocation = this.reverseSearchAppTree(owningPackage, file);
195
164
  if (logicalLocation) {
@@ -202,6 +171,9 @@ class Resolver {
202
171
  return owningPackage;
203
172
  }
204
173
  generateFastbootSwitch(request) {
174
+ if (request.resolvedTo) {
175
+ return request;
176
+ }
205
177
  let pkg = this.packageCache.ownerOfFile(request.fromFile);
206
178
  if (!pkg) {
207
179
  return request;
@@ -219,9 +191,11 @@ class Resolver {
219
191
  let fastbootFile = engineConfig.fastbootFiles[candidate];
220
192
  if (fastbootFile) {
221
193
  if (fastbootFile.shadowedFilename) {
222
- let { names } = (0, describe_exports_1.describeExports)((0, fs_1.readFileSync)((0, path_1.resolve)(pkg.root, fastbootFile.shadowedFilename), 'utf8'), {});
223
- let switchFile = (0, virtual_content_1.fastbootSwitch)(candidate, (0, path_1.resolve)(pkg.root, 'package.json'), names);
224
- if (switchFile === request.fromFile) {
194
+ let { names } = (0, describe_exports_1.describeExports)((0, fs_1.readFileSync)((0, path_1.resolve)(pkg.root, fastbootFile.shadowedFilename), 'utf8'), {
195
+ configFile: false,
196
+ });
197
+ let switchFile = fastbootSwitch(candidate, (0, path_1.resolve)(pkg.root, 'package.json'), names);
198
+ if (switchFile.specifier === request.fromFile) {
225
199
  return logTransition('internal lookup from fastbootSwitch', request);
226
200
  }
227
201
  else {
@@ -238,7 +212,10 @@ class Resolver {
238
212
  }
239
213
  handleFastbootSwitch(request) {
240
214
  var _a;
241
- let match = (0, virtual_content_1.decodeFastbootSwitch)(request.fromFile);
215
+ if (request.resolvedTo) {
216
+ return request;
217
+ }
218
+ let match = decodeFastbootSwitch(request.fromFile);
242
219
  if (!match) {
243
220
  return request;
244
221
  }
@@ -276,30 +253,122 @@ class Resolver {
276
253
  }
277
254
  let entry = (_a = this.getEntryFromMergeMap(rel, pkg.root)) === null || _a === void 0 ? void 0 : _a.entry;
278
255
  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')));
256
+ return logTransition('matched addon entry', request, request.alias(entry[section].specifier).rehome(entry[section].fromFile));
280
257
  }
281
258
  }
282
259
  return logTransition('failed to match in fastboot switch', request);
283
260
  }
284
261
  handleImplicitModules(request) {
285
- let im = (0, virtual_content_1.decodeImplicitModules)(request.specifier);
286
- if (!im) {
262
+ if (request.resolvedTo) {
287
263
  return request;
288
264
  }
265
+ for (let variant of ['', 'test-']) {
266
+ let suffix = `-embroider-implicit-${variant}modules.js`;
267
+ if (!request.specifier.endsWith(suffix)) {
268
+ continue;
269
+ }
270
+ let filename = request.specifier.slice(0, -1 * suffix.length);
271
+ if (!filename.endsWith('/') && filename.endsWith('\\')) {
272
+ continue;
273
+ }
274
+ filename = filename.slice(0, -1);
275
+ let pkg = this.packageCache.ownerOfFile(request.fromFile);
276
+ if (!(pkg === null || pkg === void 0 ? void 0 : pkg.isV2Ember())) {
277
+ throw new Error(`bug: found implicit modules import in non-ember package at ${request.fromFile}`);
278
+ }
279
+ let type = `implicit-${variant}modules`;
280
+ let packageName = (0, shared_internals_1.packageName)(filename);
281
+ if (packageName) {
282
+ let dep = this.packageCache.resolve(packageName, pkg);
283
+ return logTransition(`dep's implicit modules`, request, request.virtualize({ type, specifier: (0, path_1.resolve)(dep.root, `-embroider-${type}.js`), fromFile: dep.root }));
284
+ }
285
+ else {
286
+ return logTransition(`own implicit modules`, request, request.virtualize({ type, specifier: (0, path_1.resolve)(pkg.root, `-embroider-${type}.js`), fromFile: pkg.root }));
287
+ }
288
+ }
289
+ return request;
290
+ }
291
+ handleEntrypoint(request) {
292
+ var _a;
293
+ if (request.resolvedTo) {
294
+ return request;
295
+ }
296
+ const compatModulesSpecifier = '@embroider/virtual/compat-modules';
297
+ let isCompatModules = request.specifier === compatModulesSpecifier || request.specifier.startsWith(compatModulesSpecifier + '/');
298
+ if (!isCompatModules) {
299
+ return request;
300
+ }
301
+ const requestingPkg = this.packageCache.ownerOfFile(request.fromFile);
302
+ if (!(requestingPkg === null || requestingPkg === void 0 ? void 0 : requestingPkg.isV2Ember())) {
303
+ throw new Error(`bug: found entrypoint import in non-ember package at ${request.fromFile}`);
304
+ }
305
+ let pkg;
306
+ if (request.specifier === compatModulesSpecifier) {
307
+ pkg = requestingPkg;
308
+ }
309
+ else {
310
+ let packageName = request.specifier.slice(compatModulesSpecifier.length + 1);
311
+ pkg = this.packageCache.resolve(packageName, requestingPkg);
312
+ }
313
+ let matched = (0, resolve_exports_1.exports)(pkg.packageJSON, '-embroider-entrypoint.js', {
314
+ browser: true,
315
+ conditions: ['default', 'imports'],
316
+ });
317
+ let specifier = (0, path_1.resolve)(pkg.root, (_a = matched === null || matched === void 0 ? void 0 : matched[0]) !== null && _a !== void 0 ? _a : '-embroider-entrypoint.js');
318
+ return logTransition('entrypoint', request, request.virtualize({
319
+ type: 'entrypoint',
320
+ specifier,
321
+ fromDir: (0, path_1.dirname)(specifier),
322
+ }));
323
+ }
324
+ handleRouteEntrypoint(request) {
325
+ if (request.resolvedTo) {
326
+ return request;
327
+ }
328
+ const publicPrefix = '@embroider/core/route/';
329
+ if (!request.specifier.startsWith(publicPrefix)) {
330
+ return request;
331
+ }
332
+ let routeName = request.specifier.slice(publicPrefix.length);
289
333
  let pkg = this.packageCache.ownerOfFile(request.fromFile);
290
334
  if (!(pkg === null || pkg === void 0 ? void 0 : pkg.isV2Ember())) {
291
- throw new Error(`bug: found implicit modules import in non-ember package at ${request.fromFile}`);
335
+ throw new Error(`bug: found entrypoint import in non-ember package at ${request.fromFile}`);
292
336
  }
293
- let packageName = (0, shared_internals_1.packageName)(im.fromFile);
294
- if (packageName) {
295
- let dep = this.packageCache.resolve(packageName, pkg);
296
- return logTransition(`dep's implicit modules`, request, request.virtualize((0, path_1.resolve)(dep.root, `-embroider-${im.type}.js`)));
337
+ let matched = (0, resolve_exports_1.exports)(pkg.packageJSON, '-embroider-route-entrypoint.js', {
338
+ browser: true,
339
+ conditions: ['default', 'imports'],
340
+ });
341
+ let target = matched ? `${matched}:route=${routeName}` : `-embroider-route-entrypoint.js:route=${routeName}`;
342
+ let specifier = (0, path_1.resolve)(pkg.root, target);
343
+ return logTransition('route entrypoint', request, request.virtualize({ type: 'route-entrypoint', specifier, route: routeName, fromDir: (0, path_1.dirname)(specifier) }));
344
+ }
345
+ handleImplicitTestScripts(request) {
346
+ if (request.specifier !== '@embroider/virtual/test-support.js') {
347
+ return request;
297
348
  }
298
- else {
299
- return logTransition(`own implicit modules`, request, request.virtualize((0, path_1.resolve)(pkg.root, `-embroider-${im.type}.js`)));
349
+ let pkg = this.packageCache.ownerOfFile(request.fromFile);
350
+ if ((pkg === null || pkg === void 0 ? void 0 : pkg.root) !== this.options.engines[0].root) {
351
+ 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.`);
300
352
  }
353
+ return logTransition('test-support', request, request.virtualize({ type: 'test-support-js', specifier: (0, path_1.resolve)(pkg.root, '-embroider-test-support.js') }));
301
354
  }
302
- handleGlobalsCompat(request) {
355
+ handleTestSupportStyles(request) {
356
+ if (request.specifier !== '@embroider/virtual/test-support.css') {
357
+ return request;
358
+ }
359
+ let pkg = this.packageCache.ownerOfFile(request.fromFile);
360
+ if ((pkg === null || pkg === void 0 ? void 0 : pkg.root) !== this.options.engines[0].root) {
361
+ 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.`);
362
+ }
363
+ return logTransition('test-support-styles', request, request.virtualize({
364
+ type: 'test-support-css',
365
+ specifier: (0, path_1.resolve)(pkg.root, '-embroider-test-support-styles.css'),
366
+ }));
367
+ }
368
+ async handleGlobalsCompat(request) {
369
+ if (request.resolvedTo) {
370
+ return request;
371
+ }
303
372
  let match = compatPattern.exec(request.specifier);
304
373
  if (!match) {
305
374
  return request;
@@ -320,62 +389,81 @@ class Resolver {
320
389
  case 'ambiguous':
321
390
  return this.resolveHelperOrComponent(rest, engine, request);
322
391
  default:
323
- throw new Error(`bug: unexepected #embroider_compat specifier: ${request.specifier}`);
392
+ throw new Error(`bug: unexepected @embroider/virtual specifier: ${request.specifier}`);
393
+ }
394
+ }
395
+ handleVendorStyles(request) {
396
+ if (request.specifier !== '@embroider/virtual/vendor.css') {
397
+ return request;
398
+ }
399
+ let pkg = this.packageCache.ownerOfFile(request.fromFile);
400
+ if (!pkg || !this.options.engines.some(e => e.root === (pkg === null || pkg === void 0 ? void 0 : pkg.root))) {
401
+ 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.`);
324
402
  }
403
+ return logTransition('vendor-styles', request, request.virtualize({ type: 'vendor-css', specifier: (0, path_1.resolve)(pkg.root, '-embroider-vendor-styles.css') }));
325
404
  }
326
405
  resolveHelper(path, inEngine, request) {
327
406
  let target = this.parseGlobalPath(path, inEngine);
328
407
  return logTransition('resolveHelper', request, request.alias(`${target.packageName}/helpers/${target.memberName}`).rehome((0, path_1.resolve)(inEngine.root, 'package.json')));
329
408
  }
330
- resolveComponent(path, inEngine, request) {
409
+ async resolveComponent(path, inEngine, request) {
410
+ var _a, _b;
331
411
  let target = this.parseGlobalPath(path, inEngine);
332
412
  let hbsModule = null;
333
413
  let jsModule = null;
334
414
  // first, the various places our template might be.
335
415
  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;
416
+ let candidateSpecifier = `${target.packageName}${candidate.prefix}${target.memberName}${candidate.suffix}`;
417
+ let resolution = await this.resolve(request.alias(candidateSpecifier).rehome(target.from));
418
+ if (resolution.type === 'found') {
419
+ hbsModule = resolution;
339
420
  break;
340
421
  }
341
422
  }
342
423
  // then the various places our javascript might be.
343
424
  for (let candidate of this.componentJSCandidates(target.packageName)) {
344
- let resolution = this.nodeResolve(`${target.packageName}${candidate.prefix}${target.memberName}${candidate.suffix}`, target.from);
425
+ let candidateSpecifier = `${target.packageName}${candidate.prefix}${target.memberName}${candidate.suffix}`;
426
+ let resolution = await this.resolve(request.alias(candidateSpecifier).rehome(target.from));
345
427
  // .hbs is a resolvable extension for us, so we need to exclude it here.
346
428
  // It matches as a priority lower than .js, so finding an .hbs means
347
429
  // there's definitely not a .js.
348
- if (resolution.type === 'real' && !resolution.filename.endsWith('.hbs')) {
349
- jsModule = resolution.filename;
430
+ if (resolution.type === 'found' && !resolution.filename.endsWith('.hbs')) {
431
+ jsModule = resolution;
350
432
  break;
351
433
  }
352
434
  }
353
435
  if (hbsModule) {
354
436
  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}.`);
437
+ 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
438
  }
357
- return logTransition(`resolveComponent found legacy HBS`, request, request.virtualize((0, virtual_content_1.virtualPairComponent)(hbsModule, jsModule)));
439
+ return logTransition(`resolveComponent found legacy HBS`, request, request.virtualize({
440
+ type: 'component-pair',
441
+ hbsModule: hbsModule.filename,
442
+ jsModule: (_a = jsModule === null || jsModule === void 0 ? void 0 : jsModule.filename) !== null && _a !== void 0 ? _a : null,
443
+ debugName: (0, path_1.basename)(hbsModule.filename).replace(/\.(js|hbs)$/, ''),
444
+ specifier: `${this.options.appRoot}/embroider-pair-component/${encodeURIComponent(hbsModule.filename)}/__vpc__/${encodeURIComponent((_b = jsModule === null || jsModule === void 0 ? void 0 : jsModule.filename) !== null && _b !== void 0 ? _b : '')}`,
445
+ }));
358
446
  }
359
447
  else if (jsModule) {
360
- return logTransition(`resolveComponent found only JS`, request, request.alias(jsModule).rehome(target.from));
448
+ return logTransition(`resolving to resolveComponent found only JS`, request, request.resolveTo(jsModule));
361
449
  }
362
450
  else {
363
451
  return logTransition(`resolveComponent failed`, request);
364
452
  }
365
453
  }
366
- resolveHelperOrComponent(path, inEngine, request) {
454
+ async resolveHelperOrComponent(path, inEngine, request) {
367
455
  // resolveHelper just rewrites our request to one that should target the
368
456
  // component, so here to resolve the ambiguity we need to actually resolve
369
457
  // that candidate to see if it works.
370
458
  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);
459
+ let helperMatch = await this.resolve(request.alias(helperCandidate.specifier).rehome(helperCandidate.fromFile));
460
+ if (helperMatch.type === 'found') {
461
+ return logTransition('resolve to ambiguous case matched a helper', request, request.resolveTo(helperMatch));
374
462
  }
375
463
  // unlike resolveHelper, resolveComponent already does pre-resolution in
376
464
  // order to deal with its own internal ambiguity around JS vs HBS vs
377
465
  // colocation.≥
378
- let componentMatch = this.resolveComponent(path, inEngine, request);
466
+ let componentMatch = await this.resolveComponent(path, inEngine, request);
379
467
  if (componentMatch !== request) {
380
468
  return logTransition('ambiguous case matched a cmoponent', request, componentMatch);
381
469
  }
@@ -400,6 +488,7 @@ class Resolver {
400
488
  }
401
489
  *componentJSCandidates(inPackageName) {
402
490
  yield { prefix: '/components/', suffix: '' };
491
+ yield { prefix: '/components/', suffix: '/index' };
403
492
  yield { prefix: '/components/', suffix: '/component' };
404
493
  let pods = this.podPrefix(inPackageName);
405
494
  if (pods) {
@@ -418,10 +507,10 @@ class Resolver {
418
507
  parseGlobalPath(path, inEngine) {
419
508
  let parts = path.split('@');
420
509
  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') };
510
+ return { packageName: parts[0], memberName: parts[1], from: (0, path_1.resolve)(inEngine.root, 'package.json') };
422
511
  }
423
512
  else {
424
- return { packageName: inEngine.packageName, memberName: path, from: (0, path_1.resolve)(inEngine.root, 'pacakge.json') };
513
+ return { packageName: inEngine.packageName, memberName: path, from: (0, path_1.resolve)(inEngine.root, 'package.json') };
425
514
  }
426
515
  }
427
516
  engineConfig(packageName) {
@@ -447,14 +536,18 @@ class Resolver {
447
536
  if (!inAddonName.startsWith('./')) {
448
537
  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
538
  }
539
+ let specifier = (0, reverse_exports_1.externalName)(addon.packageJSON, inAddonName);
540
+ if (!specifier) {
541
+ throw new Error(`${addon.name}'s package.json app-js refers to ${inAddonName}, but that module is not accessible from outside the package`);
542
+ }
450
543
  let prevEntry = engineModules.get(inEngineName);
451
544
  switch (prevEntry === null || prevEntry === void 0 ? void 0 : prevEntry.type) {
452
545
  case undefined:
453
546
  engineModules.set(inEngineName, {
454
547
  type: 'app-only',
455
548
  'app-js': {
456
- localPath: inAddonName,
457
- packageRoot: addon.root,
549
+ specifier,
550
+ fromFile: addonConfig.canResolveFromFile,
458
551
  fromPackageName: addon.name,
459
552
  },
460
553
  });
@@ -467,8 +560,8 @@ class Resolver {
467
560
  engineModules.set(inEngineName, {
468
561
  type: 'both',
469
562
  'app-js': {
470
- localPath: inAddonName,
471
- packageRoot: addon.root,
563
+ specifier,
564
+ fromFile: addonConfig.canResolveFromFile,
472
565
  fromPackageName: addon.name,
473
566
  },
474
567
  'fastboot-js': prevEntry['fastboot-js'],
@@ -486,14 +579,18 @@ class Resolver {
486
579
  if (!inAddonName.startsWith('./')) {
487
580
  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
581
  }
582
+ let specifier = (0, reverse_exports_1.externalName)(addon.packageJSON, inAddonName);
583
+ if (!specifier) {
584
+ throw new Error(`${addon.name}'s package.json fastboot-js refers to ${inAddonName}, but that module is not accessible from outside the package`);
585
+ }
489
586
  let prevEntry = engineModules.get(inEngineName);
490
587
  switch (prevEntry === null || prevEntry === void 0 ? void 0 : prevEntry.type) {
491
588
  case undefined:
492
589
  engineModules.set(inEngineName, {
493
590
  type: 'fastboot-only',
494
591
  'fastboot-js': {
495
- localPath: inAddonName,
496
- packageRoot: addon.root,
592
+ specifier,
593
+ fromFile: addonConfig.canResolveFromFile,
497
594
  fromPackageName: addon.name,
498
595
  },
499
596
  });
@@ -506,8 +603,8 @@ class Resolver {
506
603
  engineModules.set(inEngineName, {
507
604
  type: 'both',
508
605
  'fastboot-js': {
509
- localPath: inAddonName,
510
- packageRoot: addon.root,
606
+ specifier,
607
+ fromFile: addonConfig.canResolveFromFile,
511
608
  fromPackageName: addon.name,
512
609
  },
513
610
  'app-js': prevEntry['app-js'],
@@ -538,7 +635,7 @@ class Resolver {
538
635
  });
539
636
  }
540
637
  handleRewrittenPackages(request) {
541
- if (request.isVirtual) {
638
+ if (request.resolvedTo) {
542
639
  return request;
543
640
  }
544
641
  let requestingPkg = this.packageCache.ownerOfFile(request.fromFile);
@@ -557,10 +654,6 @@ class Resolver {
557
654
  targetPkg = this.packageCache.resolve(packageName, requestingPkg);
558
655
  }
559
656
  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
657
  if (err.code !== 'MODULE_NOT_FOUND') {
565
658
  throw err;
566
659
  }
@@ -576,14 +669,27 @@ class Resolver {
576
669
  return logTransition('request targets a moved package', request, this.resolveWithinMovedPackage(request, targetPkg));
577
670
  }
578
671
  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')));
672
+ if (targetPkg) {
673
+ // in this case, the requesting package is moved but its destination is
674
+ // not, so we need to rehome the request back to the original location.
675
+ return logTransition('outbound request from moved package', request, request
676
+ // setting meta here because if this fails, we want the fallback
677
+ // logic to revert our rehome and continue from the *moved* package.
678
+ .withMeta({ originalFromFile: request.fromFile })
679
+ .rehome((0, path_1.resolve)(originalRequestingPkg.root, 'package.json')));
680
+ }
681
+ else {
682
+ // requesting package was moved and we failed to find its target. We
683
+ // can't let that accidentally succeed in the defaultResolve because we
684
+ // could escape the moved package system.
685
+ return logTransition('missing outbound request from moved package', request, request.notFound());
686
+ }
582
687
  }
583
688
  return request;
584
689
  }
585
690
  handleRenaming(request) {
586
- if (request.isVirtual) {
691
+ var _a;
692
+ if (request.resolvedTo) {
587
693
  return request;
588
694
  }
589
695
  let packageName = (0, shared_internals_1.packageName)(request.specifier);
@@ -591,14 +697,11 @@ class Resolver {
591
697
  return request;
592
698
  }
593
699
  let pkg = this.packageCache.ownerOfFile(request.fromFile);
594
- if (!pkg || !pkg.isV2Ember()) {
595
- return request;
596
- }
597
700
  // real deps take precedence over renaming rules. That is, a package like
598
701
  // ember-source might provide backburner via module renaming, but if you
599
702
  // have an explicit dependency on backburner you should still get that real
600
703
  // copy.
601
- if (!pkg.hasDependency(packageName)) {
704
+ if (!(pkg === null || pkg === void 0 ? void 0 : pkg.hasDependency(packageName))) {
602
705
  for (let [candidate, replacement] of Object.entries(this.options.renameModules)) {
603
706
  if (candidate === request.specifier) {
604
707
  return logTransition(`renameModules`, request, request.alias(replacement));
@@ -616,30 +719,74 @@ class Resolver {
616
719
  return logTransition(`renamePackages`, request, request.alias(request.specifier.replace(packageName, this.options.renamePackages[packageName])));
617
720
  }
618
721
  }
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')));
722
+ if (!pkg || !pkg.isV2Ember()) {
723
+ return request;
724
+ }
725
+ if (pkg.name === packageName) {
726
+ // we found a self-import
727
+ if ((_a = pkg.meta) === null || _a === void 0 ? void 0 : _a['auto-upgraded']) {
728
+ // auto-upgraded packages always get automatically adjusted. They never
729
+ // supported fancy package.json exports features so this direct mapping
730
+ // to the root is always right.
731
+ // "my-app/foo" -> "./foo" from app's package.json
732
+ // "my-addon/foo" -> "my-addon/foo" from a package that's guaranteed to be able to resolve my-addon
733
+ let owningEngine = this.owningEngine(pkg);
734
+ let addonConfig = owningEngine.activeAddons.find(a => a.root === pkg.root);
735
+ if (addonConfig) {
736
+ // auto-upgraded addons get special support for self-resolving here.
737
+ return logTransition(`v1 addon self-import`, request, request.rehome(addonConfig.canResolveFromFile));
738
+ }
739
+ else {
740
+ // auto-upgraded apps will necessarily have packageJSON.exports
741
+ // because we insert them, so for that support we can fall through to
742
+ // that support below.
743
+ }
744
+ }
745
+ // v2 packages are supposed to use package.json `exports` to enable
746
+ // self-imports, but not all build tools actually follow the spec. This
747
+ // is a workaround for badly behaved packagers.
748
+ //
749
+ // Known upstream bugs this works around:
750
+ // - https://github.com/vitejs/vite/issues/9731
751
+ if (pkg.packageJSON.exports) {
752
+ let found = (0, resolve_exports_1.exports)(pkg.packageJSON, request.specifier, {
753
+ browser: true,
754
+ conditions: ['default', 'imports'],
755
+ });
756
+ if (found === null || found === void 0 ? void 0 : found[0]) {
757
+ 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')));
758
+ }
759
+ }
625
760
  }
626
761
  return request;
627
762
  }
763
+ handleVendor(request) {
764
+ if (request.specifier !== '@embroider/virtual/vendor.js') {
765
+ return request;
766
+ }
767
+ let pkg = this.packageCache.ownerOfFile(request.fromFile);
768
+ if ((pkg === null || pkg === void 0 ? void 0 : pkg.root) !== this.options.engines[0].root) {
769
+ 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.`);
770
+ }
771
+ return logTransition('vendor', request, request.virtualize({ type: 'vendor-js', specifier: (0, path_1.resolve)(pkg.root, '-embroider-vendor.js') }));
772
+ }
628
773
  resolveWithinMovedPackage(request, pkg) {
629
774
  let levels = ['..'];
630
775
  if (pkg.name.startsWith('@')) {
631
776
  levels.push('..');
632
777
  }
778
+ let originalFromFile = request.fromFile;
633
779
  let newRequest = request.rehome((0, path_1.resolve)(pkg.root, ...levels, 'moved-package-target.js'));
634
780
  if (newRequest === request) {
635
781
  return request;
636
782
  }
637
- return newRequest.withMeta({
638
- resolvedWithinPackage: pkg.root,
639
- });
783
+ // setting meta because if this fails, we want the fallback to pick up back
784
+ // in the original requesting package.
785
+ return newRequest.withMeta({ originalFromFile });
640
786
  }
641
787
  preHandleExternal(request) {
642
- if (request.isVirtual) {
788
+ var _a;
789
+ if (request.resolvedTo) {
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,48 +804,35 @@ 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
698
827
  // choices about what it can import
699
828
  let logicalPackage = this.logicalPackage(pkg, fromFile);
700
- if (logicalPackage.meta['auto-upgraded'] && !logicalPackage.hasDependency('ember-auto-import')) {
829
+ if (((_a = logicalPackage.meta) === null || _a === void 0 ? void 0 : _a['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.resolvedTo) {
870
+ throw new Error('Build tool bug detected! Fallback resolve should never see an already-resolved 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;
912
+ return logTransition(`fallbackResolver: ${description}`, request);
804
913
  }
805
- if (!pkg.isV2Ember()) {
806
- return logTransition('fallbackResolve: not in an ember package', request);
807
- }
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,26 +1015,22 @@ 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));
1029
+ if (foundAppJS.type !== 'found') {
905
1030
  throw new Error(`${matched.entry['app-js'].fromPackageName} declared ${inEngineSpecifier} in packageJSON.ember-addon.app-js, but that module does not exist`);
906
1031
  }
907
- let { names } = (0, describe_exports_1.describeExports)((0, fs_1.readFileSync)(foundAppJS.filename, 'utf8'), {});
908
- return request.virtualize((0, virtual_content_1.fastbootSwitch)(matched.matched, (0, path_1.resolve)(engine.root, 'package.json'), names));
1032
+ let { names } = (0, describe_exports_1.describeExports)((0, fs_1.readFileSync)(foundAppJS.filename, 'utf8'), { configFile: false });
1033
+ return request.virtualize(fastbootSwitch(matched.matched, (0, path_1.resolve)(engine.root, 'package.json'), names));
909
1034
  }
910
1035
  }
911
1036
  // check whether the given file with the given owningPackage is an addon's
@@ -939,14 +1064,10 @@ class Resolver {
939
1064
  if (engineConfig) {
940
1065
  // we're directly inside an engine, so we're potentially resolvable as a
941
1066
  // 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);
1067
+ let inAppName = engineRelativeName(owningPackage, filename);
1068
+ if (inAppName) {
1069
+ return this.tryReverseComponent(engineConfig.packageName, inAppName);
1070
+ }
950
1071
  }
951
1072
  let engineInfo = this.reverseSearchAppTree(owningPackage, filename);
952
1073
  if (engineInfo) {
@@ -973,9 +1094,6 @@ __decorate([
973
1094
  __decorate([
974
1095
  (0, typescript_memoize_1.Memoize)()
975
1096
  ], Resolver.prototype, "emberVersionSupportsSeparateTemplates", null);
976
- function isExplicitlyExternal(specifier, fromPkg) {
977
- return Boolean(fromPkg.isV2Addon() && fromPkg.meta['externals'] && fromPkg.meta['externals'].includes(specifier));
978
- }
979
1097
  // we don't want to allow things that resolve only by accident that are likely
980
1098
  // to break in other setups. For example: import your dependencies'
981
1099
  // dependencies, or importing your own name from within a monorepo (which will
@@ -997,4 +1115,33 @@ function reliablyResolvable(pkg, packageName) {
997
1115
  function appImportInAppTree(inPackage, inLogicalPackage, importedPackageName) {
998
1116
  return inPackage !== inLogicalPackage && importedPackageName === inLogicalPackage.name;
999
1117
  }
1118
+ function engineRelativeName(pkg, filename) {
1119
+ let outsideName = (0, reverse_exports_1.externalName)(pkg.packageJSON, (0, shared_internals_2.explicitRelative)(pkg.root, filename));
1120
+ if (outsideName) {
1121
+ return '.' + outsideName.slice(pkg.name.length);
1122
+ }
1123
+ }
1124
+ const fastbootSwitchSuffix = '/embroider_fastboot_switch';
1125
+ function fastbootSwitch(specifier, fromFile, names) {
1126
+ let filename = `${(0, path_1.resolve)((0, path_1.dirname)(fromFile), specifier)}${fastbootSwitchSuffix}`;
1127
+ let virtualSpecifier;
1128
+ if (names.size > 0) {
1129
+ virtualSpecifier = `${filename}?names=${[...names].join(',')}`;
1130
+ }
1131
+ else {
1132
+ virtualSpecifier = filename;
1133
+ }
1134
+ return {
1135
+ type: 'fastboot-switch',
1136
+ specifier: virtualSpecifier,
1137
+ names,
1138
+ hasDefaultExport: 'x',
1139
+ };
1140
+ }
1141
+ function decodeFastbootSwitch(filename) {
1142
+ let index = filename.indexOf(fastbootSwitchSuffix);
1143
+ if (index >= 0) {
1144
+ return { filename: filename.slice(0, index) };
1145
+ }
1146
+ }
1000
1147
  //# sourceMappingURL=module-resolver.js.map