@atlaspack/core 2.24.1 → 2.24.2-dev-ts-project-refs-d30e9754f.0

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 (86) hide show
  1. package/LICENSE +201 -0
  2. package/dist/AssetGraph.js +591 -0
  3. package/dist/Atlaspack.js +656 -0
  4. package/dist/AtlaspackConfig.js +324 -0
  5. package/dist/AtlaspackConfig.schema.js +108 -0
  6. package/dist/BundleGraph.js +1628 -0
  7. package/dist/CommittedAsset.js +142 -0
  8. package/dist/Dependency.js +125 -0
  9. package/dist/Environment.js +132 -0
  10. package/dist/EnvironmentManager.js +108 -0
  11. package/dist/IdentifierRegistry.js +38 -0
  12. package/dist/InternalConfig.js +37 -0
  13. package/dist/PackagerRunner.js +531 -0
  14. package/dist/ReporterRunner.js +151 -0
  15. package/dist/RequestTracker.js +1368 -0
  16. package/dist/SymbolPropagation.js +620 -0
  17. package/dist/TargetDescriptor.schema.js +143 -0
  18. package/dist/Transformation.js +487 -0
  19. package/dist/UncommittedAsset.js +315 -0
  20. package/dist/Validation.js +196 -0
  21. package/dist/applyRuntimes.js +305 -0
  22. package/dist/assetUtils.js +168 -0
  23. package/dist/atlaspack-v3/AtlaspackV3.js +70 -0
  24. package/dist/atlaspack-v3/NapiWorkerPool.js +57 -0
  25. package/dist/atlaspack-v3/fs.js +52 -0
  26. package/dist/atlaspack-v3/index.js +25 -0
  27. package/dist/atlaspack-v3/jsCallable.js +16 -0
  28. package/dist/atlaspack-v3/worker/compat/asset-symbols.js +190 -0
  29. package/dist/atlaspack-v3/worker/compat/bitflags.js +94 -0
  30. package/dist/atlaspack-v3/worker/compat/dependency.js +43 -0
  31. package/dist/atlaspack-v3/worker/compat/environment.js +57 -0
  32. package/dist/atlaspack-v3/worker/compat/index.js +25 -0
  33. package/dist/atlaspack-v3/worker/compat/mutable-asset.js +152 -0
  34. package/dist/atlaspack-v3/worker/compat/plugin-config.js +76 -0
  35. package/dist/atlaspack-v3/worker/compat/plugin-logger.js +26 -0
  36. package/dist/atlaspack-v3/worker/compat/plugin-options.js +122 -0
  37. package/dist/atlaspack-v3/worker/compat/plugin-tracer.js +10 -0
  38. package/dist/atlaspack-v3/worker/compat/target.js +14 -0
  39. package/dist/atlaspack-v3/worker/worker.js +292 -0
  40. package/dist/constants.js +17 -0
  41. package/dist/dumpGraphToGraphViz.js +281 -0
  42. package/dist/index.js +62 -0
  43. package/dist/loadAtlaspackPlugin.js +128 -0
  44. package/dist/loadDotEnv.js +41 -0
  45. package/dist/projectPath.js +83 -0
  46. package/dist/public/Asset.js +279 -0
  47. package/dist/public/Bundle.js +224 -0
  48. package/dist/public/BundleGraph.js +359 -0
  49. package/dist/public/BundleGroup.js +53 -0
  50. package/dist/public/Config.js +286 -0
  51. package/dist/public/Dependency.js +138 -0
  52. package/dist/public/Environment.js +278 -0
  53. package/dist/public/MutableBundleGraph.js +277 -0
  54. package/dist/public/PluginOptions.js +80 -0
  55. package/dist/public/Symbols.js +248 -0
  56. package/dist/public/Target.js +69 -0
  57. package/dist/registerCoreWithSerializer.js +38 -0
  58. package/dist/requests/AssetGraphRequest.js +429 -0
  59. package/dist/requests/AssetGraphRequestRust.js +246 -0
  60. package/dist/requests/AssetRequest.js +130 -0
  61. package/dist/requests/AtlaspackBuildRequest.js +60 -0
  62. package/dist/requests/AtlaspackConfigRequest.js +490 -0
  63. package/dist/requests/BundleGraphRequest.js +441 -0
  64. package/dist/requests/ConfigRequest.js +222 -0
  65. package/dist/requests/DevDepRequest.js +204 -0
  66. package/dist/requests/EntryRequest.js +314 -0
  67. package/dist/requests/PackageRequest.js +65 -0
  68. package/dist/requests/PathRequest.js +349 -0
  69. package/dist/requests/TargetRequest.js +1310 -0
  70. package/dist/requests/ValidationRequest.js +49 -0
  71. package/dist/requests/WriteBundleRequest.js +254 -0
  72. package/dist/requests/WriteBundlesRequest.js +165 -0
  73. package/dist/requests/asset-graph-diff.js +126 -0
  74. package/dist/requests/asset-graph-dot.js +131 -0
  75. package/dist/resolveOptions.js +268 -0
  76. package/dist/rustWorkerThreadDylibHack.js +19 -0
  77. package/dist/serializerCore.browser.js +43 -0
  78. package/dist/summarizeRequest.js +39 -0
  79. package/dist/types.js +31 -0
  80. package/dist/utils.js +172 -0
  81. package/dist/worker.js +130 -0
  82. package/lib/AssetGraph.js +1 -0
  83. package/package.json +22 -22
  84. package/src/AssetGraph.ts +1 -0
  85. package/tsconfig.json +55 -2
  86. package/tsconfig.tsbuildinfo +1 -0
@@ -0,0 +1,1310 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.TargetResolver = void 0;
40
+ exports.default = createTargetRequest;
41
+ exports.skipTarget = skipTarget;
42
+ const diagnostic_1 = __importStar(require("@atlaspack/diagnostic"));
43
+ const path_1 = __importDefault(require("path"));
44
+ const utils_1 = require("@atlaspack/utils");
45
+ const logger_1 = __importDefault(require("@atlaspack/logger"));
46
+ const Environment_1 = require("../Environment");
47
+ const AtlaspackConfigRequest_1 = __importStar(require("./AtlaspackConfigRequest"));
48
+ const browserslist_1 = __importDefault(require("browserslist"));
49
+ const json_sourcemap_1 = require("@mischnic/json-sourcemap");
50
+ const assert_1 = __importDefault(require("assert"));
51
+ const nullthrows_1 = __importDefault(require("nullthrows"));
52
+ const TargetDescriptor_schema_1 = require("../TargetDescriptor.schema");
53
+ const Environment_2 = require("../public/Environment");
54
+ const utils_2 = require("../utils");
55
+ const projectPath_1 = require("../projectPath");
56
+ const RequestTracker_1 = require("../RequestTracker");
57
+ const EnvironmentManager_1 = require("../EnvironmentManager");
58
+ const feature_flags_1 = require("@atlaspack/feature-flags");
59
+ const DEFAULT_DIST_DIRNAME = 'dist';
60
+ const JS_RE = /\.[mc]?js$/;
61
+ const JS_EXTENSIONS = ['.js', '.mjs', '.cjs'];
62
+ const COMMON_TARGETS = {
63
+ main: {
64
+ match: JS_RE,
65
+ extensions: JS_EXTENSIONS,
66
+ },
67
+ module: {
68
+ // module field is always ESM. Don't allow .cjs extension here.
69
+ match: /\.m?js$/,
70
+ extensions: ['.js', '.mjs'],
71
+ },
72
+ browser: {
73
+ match: JS_RE,
74
+ extensions: JS_EXTENSIONS,
75
+ },
76
+ types: {
77
+ match: /\.d\.ts$/,
78
+ extensions: ['.d.ts'],
79
+ },
80
+ };
81
+ const DEFAULT_ENGINES = {
82
+ node: 'current',
83
+ browsers: [
84
+ 'last 1 Chrome version',
85
+ 'last 1 Safari version',
86
+ 'last 1 Firefox version',
87
+ 'last 1 Edge version',
88
+ ],
89
+ };
90
+ const type = 'target_request';
91
+ function createTargetRequest(input) {
92
+ return {
93
+ id: `${type}:${(0, utils_1.hashObject)(input)}`,
94
+ type: RequestTracker_1.requestTypes.target_request,
95
+ run,
96
+ input,
97
+ };
98
+ }
99
+ function skipTarget(targetName, exclusiveTarget, descriptorSource) {
100
+ // We skip targets if they have a descriptor.source and don't match the current exclusiveTarget
101
+ // They will be handled by a separate resolvePackageTargets call from their Entry point
102
+ // but with exclusiveTarget set.
103
+ return exclusiveTarget == null
104
+ ? descriptorSource != null
105
+ : targetName !== exclusiveTarget;
106
+ }
107
+ async function run({ input, api, options }) {
108
+ let targetResolver = new TargetResolver(api, (0, utils_2.optionsProxy)(options, api.invalidateOnOptionChange));
109
+ let targets = await targetResolver.resolve((0, projectPath_1.fromProjectPath)(options.projectRoot, input.packagePath), input.target);
110
+ // Filter targets based on allowExplicitTargetEntries feature flag
111
+ if ((0, feature_flags_1.getFeatureFlag)('allowExplicitTargetEntries') &&
112
+ options.targets &&
113
+ // Only explicit targets are allowed (i.e. an object of targets)
114
+ !Array.isArray(options.targets)) {
115
+ // Check if ALL targets have sources - only apply new behavior if they do
116
+ const allTargetsHaveSources = targets.every((t) => t.source);
117
+ if (allTargetsHaveSources) {
118
+ // Get the current entry file path relative to project root
119
+ const currentEntryPath = input.filePath;
120
+ // Filter targets to only include those whose source matches the current entry
121
+ targets = targets.filter((target) => {
122
+ // Handle both string and array sources
123
+ const sources = Array.isArray(target.source)
124
+ ? target.source
125
+ : [target.source];
126
+ // Check if current entry matches any of the target sources
127
+ return sources.some((source) => {
128
+ const targetSourcePath = (0, projectPath_1.toProjectPath)(options.projectRoot, path_1.default.resolve((0, projectPath_1.fromProjectPath)(options.projectRoot, input.packagePath), (0, nullthrows_1.default)(source, 'Source must be not be undefined when specified')));
129
+ return targetSourcePath === currentEntryPath;
130
+ });
131
+ });
132
+ }
133
+ else {
134
+ // If not all targets have sources, fall back to old behavior (skip targets with sources)
135
+ targets = targets.filter((target) => !target.source);
136
+ }
137
+ }
138
+ assertTargetsAreNotEntries(targets, input, options);
139
+ let configResult = (0, nullthrows_1.default)(await api.runRequest((0, AtlaspackConfigRequest_1.default)()));
140
+ let atlaspackConfig = (0, AtlaspackConfigRequest_1.getCachedAtlaspackConfig)(configResult, options);
141
+ // Find named pipelines for each target.
142
+ let pipelineNames = new Set(atlaspackConfig.getNamedPipelines());
143
+ for (let target of targets) {
144
+ if (pipelineNames.has(target.name)) {
145
+ target.pipeline = target.name;
146
+ }
147
+ }
148
+ if (options.logLevel === 'verbose') {
149
+ await debugResolvedTargets(input, targets, targetResolver.targetInfo, options);
150
+ }
151
+ return targets;
152
+ }
153
+ class TargetResolver {
154
+ constructor(api, options) {
155
+ this.api = api;
156
+ this.fs = options.inputFS;
157
+ this.options = options;
158
+ this.targetInfo = new Map();
159
+ }
160
+ async resolve(rootDir, exclusiveTarget) {
161
+ let optionTargets = this.options.targets;
162
+ if (exclusiveTarget != null && optionTargets == null) {
163
+ optionTargets = [exclusiveTarget];
164
+ }
165
+ let packageTargets = await this.resolvePackageTargets(rootDir, exclusiveTarget);
166
+ let targets;
167
+ if (optionTargets) {
168
+ if (Array.isArray(optionTargets)) {
169
+ if (optionTargets.length === 0) {
170
+ throw new diagnostic_1.default({
171
+ diagnostic: {
172
+ message: `Targets option is an empty array`,
173
+ origin: '@atlaspack/core',
174
+ },
175
+ });
176
+ }
177
+ // Only build the intersection of the exclusive target and option targets.
178
+ if (exclusiveTarget != null) {
179
+ optionTargets = optionTargets.filter((target) => target === exclusiveTarget);
180
+ }
181
+ // If an array of strings is passed, it's a filter on the resolved package
182
+ // targets. Load them, and find the matching targets.
183
+ // @ts-expect-error TS2322
184
+ targets = optionTargets
185
+ .map((target) => {
186
+ // null means skipped.
187
+ if (!packageTargets.has(target)) {
188
+ throw new diagnostic_1.default({
189
+ diagnostic: {
190
+ message: (0, diagnostic_1.md) `Could not find target with name "${target}"`,
191
+ origin: '@atlaspack/core',
192
+ },
193
+ });
194
+ }
195
+ return packageTargets.get(target);
196
+ })
197
+ .filter(Boolean);
198
+ }
199
+ else {
200
+ // Otherwise, it's an object map of target descriptors (similar to those
201
+ // in package.json). Adapt them to native targets.
202
+ targets = Object.entries(optionTargets)
203
+ .map(([name, _descriptor]) => {
204
+ let { distDir, ...descriptor } = parseDescriptor(name, _descriptor, null, JSON.stringify({ targets: optionTargets }, null, '\t'));
205
+ if (distDir == null) {
206
+ let optionTargetsString = JSON.stringify(optionTargets, null, '\t');
207
+ throw new diagnostic_1.default({
208
+ diagnostic: {
209
+ message: (0, diagnostic_1.md) `Missing distDir for target "${name}"`,
210
+ origin: '@atlaspack/core',
211
+ codeFrames: [
212
+ {
213
+ code: optionTargetsString,
214
+ codeHighlights: (0, diagnostic_1.generateJSONCodeHighlights)(optionTargetsString || '', [
215
+ {
216
+ key: `/${name}`,
217
+ type: 'value',
218
+ },
219
+ ]),
220
+ },
221
+ ],
222
+ },
223
+ });
224
+ }
225
+ let target = {
226
+ name,
227
+ distDir: (0, projectPath_1.toProjectPath)(this.options.projectRoot, path_1.default.resolve(this.fs.cwd(), distDir)),
228
+ publicUrl: descriptor.publicUrl ??
229
+ this.options.defaultTargetOptions.publicUrl,
230
+ env: (0, Environment_1.createEnvironment)({
231
+ engines: descriptor.engines,
232
+ context: descriptor.context,
233
+ isLibrary: descriptor.isLibrary ??
234
+ this.options.defaultTargetOptions.isLibrary,
235
+ includeNodeModules: descriptor.includeNodeModules,
236
+ outputFormat: descriptor.outputFormat ??
237
+ this.options.defaultTargetOptions.outputFormat,
238
+ shouldOptimize: this.options.defaultTargetOptions.shouldOptimize &&
239
+ descriptor.optimize !== false,
240
+ shouldScopeHoist: this.options.defaultTargetOptions.shouldScopeHoist &&
241
+ descriptor.scopeHoist !== false,
242
+ sourceMap: normalizeSourceMap(this.options, descriptor.sourceMap),
243
+ unstableSingleFileOutput: descriptor.__unstable_singleFileOutput,
244
+ customEnv: descriptor.env,
245
+ }),
246
+ };
247
+ if (descriptor.distEntry != null) {
248
+ target.distEntry = descriptor.distEntry;
249
+ }
250
+ if (descriptor.source != null) {
251
+ target.source = descriptor.source;
252
+ }
253
+ return target;
254
+ })
255
+ .filter((target) => ((0, feature_flags_1.getFeatureFlag)('allowExplicitTargetEntries') &&
256
+ this.options.entries.length !== 0) ||
257
+ !skipTarget(target.name, exclusiveTarget, target.source));
258
+ // Apply allowExplicitTargetEntries filtering logic
259
+ if ((0, feature_flags_1.getFeatureFlag)('allowExplicitTargetEntries')) {
260
+ // Check if ALL targets have sources - only apply new behavior if they do
261
+ const allTargetsHaveSources = targets.every((t) => t.source);
262
+ if (!allTargetsHaveSources) {
263
+ // If not all targets have sources, fall back to old behavior (skip targets with sources)
264
+ targets = targets.filter((target) => !target.source);
265
+ }
266
+ }
267
+ }
268
+ let serve = this.options.serveOptions;
269
+ if (serve && targets.length > 0) {
270
+ // In serve mode, we only support a single browser target. If the user
271
+ // provided more than one, or the matching target is not a browser, throw.
272
+ if (targets.length > 1) {
273
+ throw new diagnostic_1.default({
274
+ diagnostic: {
275
+ message: `More than one target is not supported in serve mode`,
276
+ origin: '@atlaspack/core',
277
+ },
278
+ });
279
+ }
280
+ if (!Environment_2.BROWSER_ENVS.has((0, EnvironmentManager_1.fromEnvironmentId)(targets[0].env).context)) {
281
+ throw new diagnostic_1.default({
282
+ diagnostic: {
283
+ message: `Only browser targets are supported in serve mode`,
284
+ origin: '@atlaspack/core',
285
+ },
286
+ });
287
+ }
288
+ targets[0].distDir = (0, projectPath_1.toProjectPath)(this.options.projectRoot, serve.distDir);
289
+ }
290
+ }
291
+ else {
292
+ // Explicit targets were not provided. Either use a modern target for server
293
+ // mode, or simply use the package.json targets.
294
+ if (this.options.serveOptions) {
295
+ // In serve mode, we only support a single browser target. Since the user
296
+ // hasn't specified a target, use one targeting modern browsers for development
297
+ targets = [
298
+ {
299
+ name: 'default',
300
+ distDir: (0, projectPath_1.toProjectPath)(this.options.projectRoot, this.options.serveOptions.distDir),
301
+ publicUrl: this.options.defaultTargetOptions.publicUrl ?? '/',
302
+ env: (0, Environment_1.createEnvironment)({
303
+ context: 'browser',
304
+ engines: {
305
+ // @ts-expect-error TS2322
306
+ browsers: DEFAULT_ENGINES.browsers,
307
+ },
308
+ shouldOptimize: this.options.defaultTargetOptions.shouldOptimize,
309
+ outputFormat: this.options.defaultTargetOptions.outputFormat,
310
+ shouldScopeHoist: this.options.defaultTargetOptions.shouldScopeHoist,
311
+ sourceMap: this.options.defaultTargetOptions.sourceMaps
312
+ ? {}
313
+ : undefined,
314
+ }),
315
+ },
316
+ ];
317
+ }
318
+ else {
319
+ // @ts-expect-error TS2322
320
+ targets = Array.from(packageTargets.values())
321
+ .filter(Boolean)
322
+ .filter((descriptor) => {
323
+ return (descriptor &&
324
+ !skipTarget(descriptor.name, exclusiveTarget, descriptor.source));
325
+ });
326
+ }
327
+ }
328
+ return targets;
329
+ }
330
+ async resolvePackageTargets(rootDir, exclusiveTarget) {
331
+ let rootFile = path_1.default.join(rootDir, 'index');
332
+ let conf = await (0, utils_1.loadConfig)(this.fs, rootFile, ['package.json'], this.options.projectRoot);
333
+ let rootFileProject = (0, projectPath_1.toProjectPath)(this.options.projectRoot, rootFile);
334
+ // Invalidate whenever a package.json file is added.
335
+ this.api.invalidateOnFileCreate({
336
+ fileName: 'package.json',
337
+ aboveFilePath: rootFileProject,
338
+ });
339
+ let pkg;
340
+ let pkgContents;
341
+ let pkgFilePath;
342
+ let pkgDir;
343
+ let pkgMap;
344
+ if (conf) {
345
+ pkg = conf.config;
346
+ let pkgFile = conf.files[0];
347
+ if (pkgFile == null) {
348
+ throw new diagnostic_1.default({
349
+ diagnostic: {
350
+ message: (0, diagnostic_1.md) `Expected package.json file in ${rootDir}`,
351
+ origin: '@atlaspack/core',
352
+ },
353
+ });
354
+ }
355
+ let _pkgFilePath = (pkgFilePath = pkgFile.filePath); // For Flow
356
+ pkgDir = path_1.default.dirname(_pkgFilePath);
357
+ pkgContents = await this.fs.readFile(_pkgFilePath, 'utf8');
358
+ pkgMap = (0, json_sourcemap_1.parse)(pkgContents, undefined, { tabWidth: 1 });
359
+ let pp = (0, projectPath_1.toProjectPath)(this.options.projectRoot, _pkgFilePath);
360
+ this.api.invalidateOnFileUpdate(pp);
361
+ this.api.invalidateOnFileDelete(pp);
362
+ }
363
+ else {
364
+ pkg = {};
365
+ pkgDir = this.fs.cwd();
366
+ }
367
+ let pkgTargets = pkg.targets || {};
368
+ let pkgEngines = parseEngines(pkg.engines, pkgFilePath, pkgContents, '/engines', 'Invalid engines in package.json') || {};
369
+ let browsersLoc = { path: '/engines/browsers' };
370
+ let nodeLoc = { path: '/engines/node' };
371
+ if (pkgEngines.browsers == null) {
372
+ let env = this.options.env.BROWSERSLIST_ENV ??
373
+ this.options.env.NODE_ENV ??
374
+ this.options.mode;
375
+ if (pkg.browserslist != null) {
376
+ let pkgBrowserslist = pkg.browserslist;
377
+ let browserslist = typeof pkgBrowserslist === 'object' && !Array.isArray(pkgBrowserslist)
378
+ ? pkgBrowserslist[env]
379
+ : pkgBrowserslist;
380
+ pkgEngines = {
381
+ ...pkgEngines,
382
+ browsers: browserslist,
383
+ };
384
+ browsersLoc = { path: '/browserslist' };
385
+ }
386
+ else {
387
+ let browserslistConfig = await (0, utils_1.resolveConfig)(this.fs, path_1.default.join(rootDir, 'index'), ['browserslist', '.browserslistrc'], this.options.projectRoot);
388
+ this.api.invalidateOnFileCreate({
389
+ fileName: 'browserslist',
390
+ aboveFilePath: rootFileProject,
391
+ });
392
+ this.api.invalidateOnFileCreate({
393
+ fileName: '.browserslistrc',
394
+ aboveFilePath: rootFileProject,
395
+ });
396
+ if (browserslistConfig != null) {
397
+ let contents = await this.fs.readFile(browserslistConfig, 'utf8');
398
+ let config = browserslist_1.default.parseConfig(contents);
399
+ let browserslistBrowsers = config[env] || config.defaults;
400
+ let pp = (0, projectPath_1.toProjectPath)(this.options.projectRoot, browserslistConfig);
401
+ if (browserslistBrowsers?.length > 0) {
402
+ pkgEngines = {
403
+ ...pkgEngines,
404
+ browsers: browserslistBrowsers,
405
+ };
406
+ browsersLoc = {
407
+ // @ts-expect-error TS2353
408
+ message: `(defined in ${path_1.default.relative(process.cwd(), browserslistConfig)})`,
409
+ };
410
+ }
411
+ // Invalidate whenever browserslist config file or relevant environment variables change
412
+ this.api.invalidateOnFileUpdate(pp);
413
+ this.api.invalidateOnFileDelete(pp);
414
+ this.api.invalidateOnEnvChange('BROWSERSLIST_ENV');
415
+ this.api.invalidateOnEnvChange('NODE_ENV');
416
+ }
417
+ }
418
+ }
419
+ let targets = new Map();
420
+ let node = pkgEngines.node;
421
+ let browsers = pkgEngines.browsers;
422
+ let defaultEngines = this.options.defaultTargetOptions.engines;
423
+ let context = (browsers ?? node == null) ? 'browser' : 'node';
424
+ if (context === 'browser' && pkgEngines.browsers == null) {
425
+ pkgEngines = {
426
+ ...pkgEngines,
427
+ // @ts-expect-error TS2322
428
+ browsers: defaultEngines?.browsers ?? DEFAULT_ENGINES.browsers,
429
+ };
430
+ // @ts-expect-error TS2353
431
+ browsersLoc = { message: '(default)' };
432
+ }
433
+ else if (context === 'node' && pkgEngines.node == null) {
434
+ pkgEngines = {
435
+ ...pkgEngines,
436
+ node: defaultEngines?.node ?? DEFAULT_ENGINES.node,
437
+ };
438
+ // @ts-expect-error TS2353
439
+ nodeLoc = { message: '(default)' };
440
+ }
441
+ // If there is a separate `browser` target, or an `engines.node` field but no browser targets, then
442
+ // the `main` and `module` targets refer to node, otherwise browser.
443
+ let mainContext = (pkg.browser ?? pkgTargets.browser ?? (node != null && browsers == null))
444
+ ? 'node'
445
+ : 'browser';
446
+ let mainContextLoc = pkg.browser != null
447
+ ? {
448
+ inferred: '/browser',
449
+ message: '(because a browser field also exists)',
450
+ type: 'key',
451
+ }
452
+ : pkgTargets.browser
453
+ ? {
454
+ inferred: '/targets/browser',
455
+ message: '(because a browser target also exists)',
456
+ type: 'key',
457
+ }
458
+ : node != null && browsers == null
459
+ ? nodeLoc.path
460
+ ? {
461
+ inferred: nodeLoc.path,
462
+ message: '(because node engines were defined)',
463
+ type: 'key',
464
+ }
465
+ : nodeLoc
466
+ : { message: '(default)' };
467
+ let moduleContext = (pkg.browser ?? pkgTargets.browser) ? 'browser' : mainContext;
468
+ let moduleContextLoc = pkg.browser != null
469
+ ? {
470
+ inferred: '/browser',
471
+ message: '(because a browser field also exists)',
472
+ type: 'key',
473
+ }
474
+ : pkgTargets.browser
475
+ ? {
476
+ inferred: '/targets/browser',
477
+ message: '(becausea browser target also exists)',
478
+ type: 'key',
479
+ }
480
+ : mainContextLoc;
481
+ let getEnginesLoc = (targetName, descriptor) => {
482
+ let enginesLoc = `/targets/${targetName}/engines`;
483
+ switch (context) {
484
+ case 'browser':
485
+ case 'web-worker':
486
+ case 'service-worker':
487
+ case 'worklet': {
488
+ if (descriptor.engines) {
489
+ return { path: enginesLoc + '/browsers' };
490
+ }
491
+ else {
492
+ return browsersLoc;
493
+ }
494
+ }
495
+ case 'node': {
496
+ if (descriptor.engines) {
497
+ return { path: enginesLoc + '/node' };
498
+ }
499
+ else {
500
+ return nodeLoc;
501
+ }
502
+ }
503
+ case 'electron-main':
504
+ case 'electron-renderer': {
505
+ if (descriptor.engines?.electron != null) {
506
+ return { path: enginesLoc + '/electron' };
507
+ }
508
+ else if (pkgEngines?.electron != null) {
509
+ return { path: '/engines/electron' };
510
+ }
511
+ }
512
+ }
513
+ return { message: '(default)' };
514
+ };
515
+ for (let targetName in COMMON_TARGETS) {
516
+ let _targetDist;
517
+ let pointer;
518
+ if (targetName === 'browser' &&
519
+ pkg[targetName] != null &&
520
+ typeof pkg[targetName] === 'object' &&
521
+ pkg.name) {
522
+ // The `browser` field can be a file path or an alias map.
523
+ _targetDist = pkg[targetName][pkg.name];
524
+ pointer = `/${targetName}/${(0, diagnostic_1.encodeJSONKeyComponent)(pkg.name)}`;
525
+ }
526
+ else {
527
+ // @ts-expect-error TS7053
528
+ _targetDist = pkg[targetName];
529
+ pointer = `/${targetName}`;
530
+ }
531
+ // For Flow
532
+ let targetDist = _targetDist;
533
+ if (typeof targetDist === 'string' || pkgTargets[targetName]) {
534
+ let distDir;
535
+ let distEntry;
536
+ let loc;
537
+ (0, assert_1.default)(pkgMap != null);
538
+ let _descriptor = pkgTargets[targetName] ?? {};
539
+ if (typeof targetDist === 'string') {
540
+ distDir = (0, projectPath_1.toProjectPath)(this.options.projectRoot, path_1.default.resolve(pkgDir, path_1.default.dirname(targetDist)));
541
+ distEntry = path_1.default.basename(targetDist);
542
+ loc = {
543
+ filePath: (0, nullthrows_1.default)(pkgFilePath),
544
+ ...(0, diagnostic_1.getJSONSourceLocation)(pkgMap.pointers[pointer], 'value'),
545
+ };
546
+ }
547
+ else {
548
+ distDir =
549
+ this.options.defaultTargetOptions.distDir ??
550
+ (0, projectPath_1.toProjectPath)(this.options.projectRoot, path_1.default.join(pkgDir, DEFAULT_DIST_DIRNAME, targetName));
551
+ }
552
+ if (_descriptor == false) {
553
+ continue;
554
+ }
555
+ let descriptor = parseCommonTargetDescriptor(targetName, _descriptor, pkgFilePath, pkgContents);
556
+ if (skipTarget(targetName, exclusiveTarget, descriptor.source)) {
557
+ targets.set(targetName, null);
558
+ continue;
559
+ }
560
+ if (distEntry != null &&
561
+ // @ts-expect-error TS7053
562
+ !COMMON_TARGETS[targetName].match.test(distEntry)) {
563
+ let contents = typeof pkgContents === 'string'
564
+ ? pkgContents
565
+ : JSON.stringify(pkgContents, null, '\t');
566
+ let listFormat = new Intl.ListFormat('en-US', { type: 'disjunction' });
567
+ let extensions = listFormat.format(
568
+ // @ts-expect-error TS7053
569
+ COMMON_TARGETS[targetName].extensions);
570
+ let ext = path_1.default.extname(distEntry);
571
+ throw new diagnostic_1.default({
572
+ diagnostic: {
573
+ message: (0, diagnostic_1.md) `Unexpected output file type ${ext} in target "${targetName}"`,
574
+ origin: '@atlaspack/core',
575
+ codeFrames: [
576
+ {
577
+ language: 'json',
578
+ filePath: pkgFilePath ?? undefined,
579
+ code: contents,
580
+ codeHighlights: (0, diagnostic_1.generateJSONCodeHighlights)(contents, [
581
+ {
582
+ key: pointer,
583
+ type: 'value',
584
+ message: `File extension must be ${extensions}`,
585
+ },
586
+ ]),
587
+ },
588
+ ],
589
+ hints: [
590
+ `The "${targetName}" field is meant for libraries. If you meant to output a ${ext} file, either remove the "${targetName}" field or choose a different target name.`,
591
+ ],
592
+ documentationURL: 'https://parceljs.org/features/targets/#library-targets',
593
+ },
594
+ });
595
+ }
596
+ if (descriptor.outputFormat === 'global') {
597
+ let contents = typeof pkgContents === 'string'
598
+ ? pkgContents
599
+ : JSON.stringify(pkgContents, null, '\t');
600
+ throw new diagnostic_1.default({
601
+ diagnostic: {
602
+ message: (0, diagnostic_1.md) `The "global" output format is not supported in the "${targetName}" target.`,
603
+ origin: '@atlaspack/core',
604
+ codeFrames: [
605
+ {
606
+ language: 'json',
607
+ filePath: pkgFilePath ?? undefined,
608
+ code: contents,
609
+ codeHighlights: (0, diagnostic_1.generateJSONCodeHighlights)(contents, [
610
+ {
611
+ key: `/targets/${targetName}/outputFormat`,
612
+ type: 'value',
613
+ },
614
+ ]),
615
+ },
616
+ ],
617
+ hints: [
618
+ `The "${targetName}" field is meant for libraries. The outputFormat must be either "commonjs" or "esmodule". Either change or remove the declared outputFormat.`,
619
+ ],
620
+ documentationURL: 'https://parceljs.org/features/targets/#library-targets',
621
+ },
622
+ });
623
+ }
624
+ let [inferredOutputFormat, inferredOutputFormatField] = this.inferOutputFormat(distEntry, descriptor, targetName,
625
+ // @ts-expect-error TS2345
626
+ pkg, pkgFilePath, pkgContents);
627
+ let outputFormat = descriptor.outputFormat ??
628
+ this.options.defaultTargetOptions.outputFormat ??
629
+ inferredOutputFormat ??
630
+ (targetName === 'module' ? 'esmodule' : 'commonjs');
631
+ let isModule = outputFormat === 'esmodule';
632
+ if (targetName === 'main' &&
633
+ outputFormat === 'esmodule' &&
634
+ inferredOutputFormat !== 'esmodule') {
635
+ let contents = typeof pkgContents === 'string'
636
+ ? pkgContents
637
+ : JSON.stringify(pkgContents, null, '\t');
638
+ throw new diagnostic_1.default({
639
+ diagnostic: {
640
+ // prettier-ignore
641
+ message: (0, diagnostic_1.md) `Output format "esmodule" cannot be used in the "main" target without a .mjs extension or "type": "module" field.`,
642
+ origin: '@atlaspack/core',
643
+ codeFrames: [
644
+ {
645
+ language: 'json',
646
+ filePath: pkgFilePath ?? undefined,
647
+ code: contents,
648
+ codeHighlights: (0, diagnostic_1.generateJSONCodeHighlights)(contents, [
649
+ {
650
+ key: `/targets/${targetName}/outputFormat`,
651
+ type: 'value',
652
+ message: 'Declared output format defined here',
653
+ },
654
+ {
655
+ key: '/main',
656
+ type: 'value',
657
+ message: 'Inferred output format defined here',
658
+ },
659
+ ]),
660
+ },
661
+ ],
662
+ hints: [
663
+ `Either change the output file extension to .mjs, add "type": "module" to package.json, or remove the declared outputFormat.`,
664
+ ],
665
+ documentationURL: 'https://parceljs.org/features/targets/#library-targets',
666
+ },
667
+ });
668
+ }
669
+ if (descriptor.scopeHoist === false) {
670
+ let contents = typeof pkgContents === 'string'
671
+ ? pkgContents
672
+ : JSON.stringify(pkgContents, null, '\t');
673
+ throw new diagnostic_1.default({
674
+ diagnostic: {
675
+ message: 'Scope hoisting cannot be disabled for library targets.',
676
+ origin: '@atlaspack/core',
677
+ codeFrames: [
678
+ {
679
+ language: 'json',
680
+ filePath: pkgFilePath ?? undefined,
681
+ code: contents,
682
+ codeHighlights: (0, diagnostic_1.generateJSONCodeHighlights)(contents, [
683
+ {
684
+ key: `/targets/${targetName}/scopeHoist`,
685
+ type: 'value',
686
+ },
687
+ ]),
688
+ },
689
+ ],
690
+ hints: [
691
+ `The "${targetName}" target is meant for libraries. Either remove the "scopeHoist" option, or use a different target name.`,
692
+ ],
693
+ documentationURL: 'https://parceljs.org/features/targets/#library-targets',
694
+ },
695
+ });
696
+ }
697
+ let context = descriptor.context ??
698
+ (targetName === 'browser'
699
+ ? 'browser'
700
+ : isModule
701
+ ? moduleContext
702
+ : mainContext);
703
+ targets.set(targetName, {
704
+ name: targetName,
705
+ distDir,
706
+ distEntry,
707
+ publicUrl: descriptor.publicUrl ?? this.options.defaultTargetOptions.publicUrl,
708
+ env: (0, Environment_1.createEnvironment)({
709
+ engines: descriptor.engines ?? pkgEngines,
710
+ // @ts-expect-error TS2322
711
+ context,
712
+ includeNodeModules: descriptor.includeNodeModules ?? false,
713
+ outputFormat,
714
+ isLibrary: true,
715
+ shouldOptimize: this.options.defaultTargetOptions.shouldOptimize &&
716
+ descriptor.optimize === true,
717
+ shouldScopeHoist: true,
718
+ sourceMap: normalizeSourceMap(this.options, descriptor.sourceMap),
719
+ }),
720
+ loc: (0, utils_2.toInternalSourceLocation)(this.options.projectRoot, loc),
721
+ });
722
+ this.targetInfo.set(targetName, {
723
+ output: { path: pointer },
724
+ engines: getEnginesLoc(targetName, descriptor),
725
+ context: descriptor.context
726
+ ? { path: `/targets/${targetName}/context` }
727
+ : targetName === 'browser'
728
+ ? {
729
+ message: '(inferred from target name)',
730
+ inferred: pointer,
731
+ type: 'key',
732
+ }
733
+ : isModule
734
+ ? moduleContextLoc
735
+ : mainContextLoc,
736
+ includeNodeModules: descriptor.includeNodeModules
737
+ ? { path: `/targets/${targetName}/includeNodeModules`, type: 'key' }
738
+ : { message: '(default)' },
739
+ outputFormat: descriptor.outputFormat
740
+ ? { path: `/targets/${targetName}/outputFormat` }
741
+ : inferredOutputFormatField === '/type'
742
+ ? {
743
+ message: `(inferred from package.json#type)`,
744
+ inferred: inferredOutputFormatField,
745
+ }
746
+ : inferredOutputFormatField != null
747
+ ? {
748
+ message: `(inferred from file extension)`,
749
+ inferred: inferredOutputFormatField,
750
+ }
751
+ : { message: '(default)' },
752
+ isLibrary: { message: '(default)' },
753
+ shouldOptimize: descriptor.optimize
754
+ ? { path: `/targets/${targetName}/optimize` }
755
+ : { message: '(default)' },
756
+ shouldScopeHoist: { message: '(default)' },
757
+ });
758
+ }
759
+ }
760
+ let customTargets = Object.keys(pkgTargets).filter(
761
+ // @ts-expect-error TS7053
762
+ (targetName) => !COMMON_TARGETS[targetName]);
763
+ // Custom targets
764
+ for (let targetName of customTargets) {
765
+ // @ts-expect-error TS7053
766
+ let distPath = pkg[targetName];
767
+ let distDir;
768
+ let distEntry;
769
+ let loc;
770
+ let pointer;
771
+ if (distPath == null) {
772
+ distDir =
773
+ (0, projectPath_1.fromProjectPath)(this.options.projectRoot, this.options.defaultTargetOptions.distDir) ?? path_1.default.join(pkgDir, DEFAULT_DIST_DIRNAME);
774
+ if (customTargets.length >= 2) {
775
+ distDir = path_1.default.join(distDir, targetName);
776
+ }
777
+ (0, assert_1.default)(pkgMap != null);
778
+ (0, assert_1.default)(typeof pkgFilePath === 'string');
779
+ loc = {
780
+ filePath: pkgFilePath,
781
+ ...(0, diagnostic_1.getJSONSourceLocation)(pkgMap.pointers[`/targets/${targetName}`], 'key'),
782
+ };
783
+ }
784
+ else {
785
+ if (typeof distPath !== 'string') {
786
+ let contents = typeof pkgContents === 'string'
787
+ ? pkgContents
788
+ : JSON.stringify(pkgContents, null, '\t');
789
+ throw new diagnostic_1.default({
790
+ diagnostic: {
791
+ message: (0, diagnostic_1.md) `Invalid distPath for target "${targetName}"`,
792
+ origin: '@atlaspack/core',
793
+ codeFrames: [
794
+ {
795
+ language: 'json',
796
+ filePath: pkgFilePath ?? undefined,
797
+ code: contents,
798
+ codeHighlights: (0, diagnostic_1.generateJSONCodeHighlights)(contents, [
799
+ {
800
+ key: `/${targetName}`,
801
+ type: 'value',
802
+ message: 'Expected type string',
803
+ },
804
+ ]),
805
+ },
806
+ ],
807
+ },
808
+ });
809
+ }
810
+ distDir = path_1.default.resolve(pkgDir, path_1.default.dirname(distPath));
811
+ distEntry = path_1.default.basename(distPath);
812
+ (0, assert_1.default)(typeof pkgFilePath === 'string');
813
+ (0, assert_1.default)(pkgMap != null);
814
+ loc = {
815
+ filePath: pkgFilePath,
816
+ ...(0, diagnostic_1.getJSONSourceLocation)(pkgMap.pointers[`/${targetName}`], 'value'),
817
+ };
818
+ pointer = `/${targetName}`;
819
+ }
820
+ if (targetName in pkgTargets) {
821
+ let descriptor = parsePackageDescriptor(targetName, pkgTargets[targetName], pkgFilePath, pkgContents);
822
+ let pkgDir = path_1.default.dirname((0, nullthrows_1.default)(pkgFilePath));
823
+ if (skipTarget(targetName, exclusiveTarget, descriptor.source)) {
824
+ targets.set(targetName, null);
825
+ continue;
826
+ }
827
+ let [inferredOutputFormat, inferredOutputFormatField] = this.inferOutputFormat(distEntry, descriptor, targetName,
828
+ // @ts-expect-error TS2345
829
+ pkg, pkgFilePath, pkgContents);
830
+ if (descriptor.scopeHoist === false && descriptor.isLibrary) {
831
+ let contents = typeof pkgContents === 'string'
832
+ ? pkgContents
833
+ : JSON.stringify(pkgContents, null, '\t');
834
+ throw new diagnostic_1.default({
835
+ diagnostic: {
836
+ message: 'Scope hoisting cannot be disabled for library targets.',
837
+ origin: '@atlaspack/core',
838
+ codeFrames: [
839
+ {
840
+ language: 'json',
841
+ filePath: pkgFilePath ?? undefined,
842
+ code: contents,
843
+ codeHighlights: (0, diagnostic_1.generateJSONCodeHighlights)(contents, [
844
+ {
845
+ key: `/targets/${targetName}/scopeHoist`,
846
+ type: 'value',
847
+ },
848
+ {
849
+ key: `/targets/${targetName}/isLibrary`,
850
+ type: 'value',
851
+ },
852
+ ]),
853
+ },
854
+ ],
855
+ hints: [`Either remove the "scopeHoist" or "isLibrary" option.`],
856
+ documentationURL: 'https://parceljs.org/features/targets/#library-targets',
857
+ },
858
+ });
859
+ }
860
+ let isLibrary = descriptor.isLibrary ??
861
+ this.options.defaultTargetOptions.isLibrary ??
862
+ false;
863
+ let shouldScopeHoist = isLibrary
864
+ ? true
865
+ : this.options.defaultTargetOptions.shouldScopeHoist;
866
+ targets.set(targetName, {
867
+ name: targetName,
868
+ distDir: (0, projectPath_1.toProjectPath)(this.options.projectRoot, descriptor.distDir != null
869
+ ? path_1.default.resolve(pkgDir, descriptor.distDir)
870
+ : distDir),
871
+ distEntry,
872
+ publicUrl: descriptor.publicUrl ?? this.options.defaultTargetOptions.publicUrl,
873
+ env: (0, Environment_1.createEnvironment)({
874
+ engines: descriptor.engines ?? pkgEngines,
875
+ context: descriptor.context,
876
+ includeNodeModules: descriptor.includeNodeModules,
877
+ unstableSingleFileOutput: descriptor.__unstable_singleFileOutput,
878
+ outputFormat: descriptor.outputFormat ??
879
+ this.options.defaultTargetOptions.outputFormat ??
880
+ inferredOutputFormat ??
881
+ undefined,
882
+ isLibrary,
883
+ shouldOptimize: this.options.defaultTargetOptions.shouldOptimize &&
884
+ // Libraries are not optimized by default, users must explicitly configure this.
885
+ (isLibrary
886
+ ? descriptor.optimize === true
887
+ : descriptor.optimize !== false),
888
+ shouldScopeHoist: shouldScopeHoist && descriptor.scopeHoist !== false,
889
+ sourceMap: normalizeSourceMap(this.options, descriptor.sourceMap),
890
+ }),
891
+ loc: (0, utils_2.toInternalSourceLocation)(this.options.projectRoot, loc),
892
+ });
893
+ this.targetInfo.set(targetName, {
894
+ output: pointer != null ? { path: pointer } : { message: '(default)' },
895
+ engines: getEnginesLoc(targetName, descriptor),
896
+ context: descriptor.context
897
+ ? { path: `/targets/${targetName}/context` }
898
+ : { message: '(default)' },
899
+ includeNodeModules: descriptor.includeNodeModules
900
+ ? { path: `/targets/${targetName}/includeNodeModules`, type: 'key' }
901
+ : { message: '(default)' },
902
+ outputFormat: descriptor.outputFormat
903
+ ? { path: `/targets/${targetName}/outputFormat` }
904
+ : inferredOutputFormatField === '/type'
905
+ ? {
906
+ message: `(inferred from package.json#type)`,
907
+ inferred: inferredOutputFormatField,
908
+ }
909
+ : inferredOutputFormatField != null
910
+ ? {
911
+ message: `(inferred from file extension)`,
912
+ inferred: inferredOutputFormatField,
913
+ }
914
+ : { message: '(default)' },
915
+ isLibrary: descriptor.isLibrary != null
916
+ ? { path: `/targets/${targetName}/isLibrary` }
917
+ : { message: '(default)' },
918
+ shouldOptimize: descriptor.optimize != null
919
+ ? { path: `/targets/${targetName}/optimize` }
920
+ : { message: '(default)' },
921
+ shouldScopeHoist: descriptor.scopeHoist != null
922
+ ? { path: `/targets/${targetName}/scopeHoist` }
923
+ : { message: '(default)' },
924
+ });
925
+ }
926
+ }
927
+ // If no explicit targets were defined, add a default.
928
+ if (targets.size === 0) {
929
+ targets.set('default', {
930
+ name: 'default',
931
+ distDir: this.options.defaultTargetOptions.distDir ??
932
+ (0, projectPath_1.toProjectPath)(this.options.projectRoot, path_1.default.join(pkgDir, DEFAULT_DIST_DIRNAME)),
933
+ publicUrl: this.options.defaultTargetOptions.publicUrl,
934
+ env: (0, Environment_1.createEnvironment)({
935
+ engines: pkgEngines,
936
+ // @ts-expect-error TS2322
937
+ context,
938
+ outputFormat: this.options.defaultTargetOptions.outputFormat,
939
+ isLibrary: this.options.defaultTargetOptions.isLibrary,
940
+ shouldOptimize: this.options.defaultTargetOptions.shouldOptimize,
941
+ shouldScopeHoist: this.options.defaultTargetOptions.shouldScopeHoist ??
942
+ (this.options.mode === 'production' &&
943
+ !this.options.defaultTargetOptions.isLibrary),
944
+ sourceMap: this.options.defaultTargetOptions.sourceMaps
945
+ ? {}
946
+ : undefined,
947
+ }),
948
+ });
949
+ }
950
+ assertNoDuplicateTargets(this.options, targets, pkgFilePath, pkgContents);
951
+ return targets;
952
+ }
953
+ inferOutputFormat(distEntry, descriptor, targetName, pkg, pkgFilePath, pkgContents) {
954
+ // Infer the outputFormat based on package.json properties.
955
+ // If the extension is .mjs it's always a module.
956
+ // If the extension is .cjs, it's always commonjs.
957
+ // If the "type" field is set to "module" and the extension is .js, it's a module.
958
+ let ext = distEntry != null ? path_1.default.extname(distEntry) : null;
959
+ let inferredOutputFormat, inferredOutputFormatField;
960
+ switch (ext) {
961
+ case '.mjs':
962
+ inferredOutputFormat = 'esmodule';
963
+ inferredOutputFormatField = `/${targetName}`;
964
+ break;
965
+ case '.cjs':
966
+ inferredOutputFormat = 'commonjs';
967
+ inferredOutputFormatField = `/${targetName}`;
968
+ break;
969
+ case '.js':
970
+ if (pkg.type === 'module') {
971
+ inferredOutputFormat = 'esmodule';
972
+ inferredOutputFormatField = '/type';
973
+ }
974
+ break;
975
+ }
976
+ if (descriptor.outputFormat &&
977
+ inferredOutputFormat &&
978
+ descriptor.outputFormat !== inferredOutputFormat) {
979
+ let contents = typeof pkgContents === 'string'
980
+ ? pkgContents
981
+ : JSON.stringify(pkgContents, null, '\t');
982
+ let expectedExtensions;
983
+ switch (descriptor.outputFormat) {
984
+ case 'esmodule':
985
+ expectedExtensions = ['.mjs', '.js'];
986
+ break;
987
+ case 'commonjs':
988
+ expectedExtensions = ['.cjs', '.js'];
989
+ break;
990
+ case 'global':
991
+ expectedExtensions = ['.js'];
992
+ break;
993
+ }
994
+ let listFormat = new Intl.ListFormat('en-US', { type: 'disjunction' });
995
+ throw new diagnostic_1.default({
996
+ diagnostic: {
997
+ message: (0, diagnostic_1.md) `Declared output format "${descriptor.outputFormat}" does not match expected output format "${inferredOutputFormat}".`,
998
+ origin: '@atlaspack/core',
999
+ codeFrames: [
1000
+ {
1001
+ language: 'json',
1002
+ filePath: pkgFilePath ?? undefined,
1003
+ code: contents,
1004
+ codeHighlights: (0, diagnostic_1.generateJSONCodeHighlights)(contents, [
1005
+ {
1006
+ key: `/targets/${targetName}/outputFormat`,
1007
+ type: 'value',
1008
+ message: 'Declared output format defined here',
1009
+ },
1010
+ {
1011
+ key: (0, nullthrows_1.default)(inferredOutputFormatField),
1012
+ type: 'value',
1013
+ message: 'Inferred output format defined here',
1014
+ },
1015
+ ]),
1016
+ },
1017
+ ],
1018
+ hints: [
1019
+ inferredOutputFormatField === '/type'
1020
+ ? 'Either remove the target\'s declared "outputFormat" or remove the "type" field.'
1021
+ : `Either remove the target's declared "outputFormat" or change the extension to ${listFormat.format(expectedExtensions)}.`,
1022
+ ],
1023
+ documentationURL: 'https://parceljs.org/features/targets/#library-targets',
1024
+ },
1025
+ });
1026
+ }
1027
+ // @ts-expect-error TS2322
1028
+ return [inferredOutputFormat, inferredOutputFormatField];
1029
+ }
1030
+ }
1031
+ exports.TargetResolver = TargetResolver;
1032
+ function parseEngines(engines, pkgPath, pkgContents, prependKey, message) {
1033
+ if (engines === undefined) {
1034
+ return engines;
1035
+ }
1036
+ else {
1037
+ utils_1.validateSchema.diagnostic(TargetDescriptor_schema_1.ENGINES_SCHEMA, { data: engines, source: pkgContents, filePath: pkgPath, prependKey }, '@atlaspack/core', message);
1038
+ // @ts-expect-error TS2322
1039
+ return engines;
1040
+ }
1041
+ }
1042
+ function parseDescriptor(targetName, descriptor, pkgPath, pkgContents) {
1043
+ utils_1.validateSchema.diagnostic(TargetDescriptor_schema_1.DESCRIPTOR_SCHEMA, {
1044
+ data: descriptor,
1045
+ source: pkgContents,
1046
+ filePath: pkgPath,
1047
+ prependKey: `/targets/${targetName}`,
1048
+ }, '@atlaspack/core', `Invalid target descriptor for target "${targetName}"`);
1049
+ // @ts-expect-error TS2322
1050
+ return descriptor;
1051
+ }
1052
+ function parsePackageDescriptor(targetName, descriptor, pkgPath, pkgContents) {
1053
+ utils_1.validateSchema.diagnostic(TargetDescriptor_schema_1.PACKAGE_DESCRIPTOR_SCHEMA, {
1054
+ data: descriptor,
1055
+ source: pkgContents,
1056
+ filePath: pkgPath,
1057
+ prependKey: `/targets/${targetName}`,
1058
+ }, '@atlaspack/core', `Invalid target descriptor for target "${targetName}"`);
1059
+ // @ts-expect-error TS2322
1060
+ return descriptor;
1061
+ }
1062
+ function parseCommonTargetDescriptor(targetName, descriptor, pkgPath, pkgContents) {
1063
+ utils_1.validateSchema.diagnostic(TargetDescriptor_schema_1.COMMON_TARGET_DESCRIPTOR_SCHEMA, {
1064
+ data: descriptor,
1065
+ source: pkgContents,
1066
+ filePath: pkgPath,
1067
+ prependKey: `/targets/${targetName}`,
1068
+ }, '@atlaspack/core', `Invalid target descriptor for target "${targetName}"`);
1069
+ // @ts-expect-error TS2322
1070
+ return descriptor;
1071
+ }
1072
+ function assertNoDuplicateTargets(options, targets, pkgFilePath, pkgContents) {
1073
+ // Detect duplicate targets by destination path and provide a nice error.
1074
+ // Without this, an assertion is thrown much later after naming the bundles and finding duplicates.
1075
+ let targetsByPath = new Map();
1076
+ for (let target of targets.values()) {
1077
+ if (!target) {
1078
+ continue;
1079
+ }
1080
+ let { distEntry } = target;
1081
+ if (distEntry != null) {
1082
+ let distPath = path_1.default.join((0, projectPath_1.fromProjectPath)(options.projectRoot, target.distDir), distEntry);
1083
+ if (!targetsByPath.has(distPath)) {
1084
+ targetsByPath.set(distPath, []);
1085
+ }
1086
+ targetsByPath.get(distPath)?.push(target.name);
1087
+ }
1088
+ }
1089
+ let diagnostics = [];
1090
+ for (let [targetPath, targetNames] of targetsByPath) {
1091
+ if (targetNames.length > 1 && pkgContents != null && pkgFilePath != null) {
1092
+ diagnostics.push({
1093
+ message: (0, diagnostic_1.md) `Multiple targets have the same destination path "${path_1.default.relative(path_1.default.dirname(pkgFilePath), targetPath)}"`,
1094
+ origin: '@atlaspack/core',
1095
+ codeFrames: [
1096
+ {
1097
+ language: 'json',
1098
+ filePath: pkgFilePath || undefined,
1099
+ code: pkgContents,
1100
+ codeHighlights: (0, diagnostic_1.generateJSONCodeHighlights)(pkgContents, targetNames.map((t) => ({
1101
+ key: `/${t}`,
1102
+ type: 'value',
1103
+ }))),
1104
+ },
1105
+ ],
1106
+ });
1107
+ }
1108
+ }
1109
+ if (diagnostics.length > 0) {
1110
+ // Only add hints to the last diagnostic so it isn't duplicated on each one
1111
+ diagnostics[diagnostics.length - 1].hints = [
1112
+ 'Try removing the duplicate targets, or changing the destination paths.',
1113
+ ];
1114
+ throw new diagnostic_1.default({
1115
+ diagnostic: diagnostics,
1116
+ });
1117
+ }
1118
+ }
1119
+ function normalizeSourceMap(options,
1120
+ // @ts-expect-error TS2304
1121
+ sourceMap) {
1122
+ if (options.defaultTargetOptions.sourceMaps) {
1123
+ if (typeof sourceMap === 'boolean') {
1124
+ return sourceMap ? {} : undefined;
1125
+ }
1126
+ else {
1127
+ return sourceMap ?? {};
1128
+ }
1129
+ }
1130
+ else {
1131
+ return undefined;
1132
+ }
1133
+ }
1134
+ function assertTargetsAreNotEntries(targets, input, options) {
1135
+ for (const target of targets) {
1136
+ if (target.distEntry != null &&
1137
+ (0, projectPath_1.joinProjectPath)(target.distDir, target.distEntry) === input.filePath) {
1138
+ let loc = target.loc;
1139
+ let relativeEntry = path_1.default.relative(process.cwd(), (0, projectPath_1.fromProjectPath)(options.projectRoot, input.filePath));
1140
+ // @ts-expect-error TS2304
1141
+ let codeFrames = [];
1142
+ if (loc) {
1143
+ codeFrames.push({
1144
+ filePath: (0, projectPath_1.fromProjectPath)(options.projectRoot, loc.filePath),
1145
+ codeHighlights: [
1146
+ (0, diagnostic_1.convertSourceLocationToHighlight)(loc, 'Target defined here'),
1147
+ ],
1148
+ });
1149
+ let inputLoc = input.loc;
1150
+ if (inputLoc) {
1151
+ let highlight = (0, diagnostic_1.convertSourceLocationToHighlight)(inputLoc, 'Entry defined here');
1152
+ if (inputLoc.filePath === loc.filePath) {
1153
+ codeFrames[0].codeHighlights.push(highlight);
1154
+ }
1155
+ else {
1156
+ codeFrames.push({
1157
+ filePath: (0, projectPath_1.fromProjectPath)(options.projectRoot, inputLoc.filePath),
1158
+ codeHighlights: [highlight],
1159
+ });
1160
+ }
1161
+ }
1162
+ }
1163
+ throw new diagnostic_1.default({
1164
+ diagnostic: {
1165
+ origin: '@atlaspack/core',
1166
+ message: `Target "${target.name}" is configured to overwrite entry "${relativeEntry}".`,
1167
+ codeFrames,
1168
+ hints: [
1169
+ // @ts-expect-error TS7053
1170
+ (COMMON_TARGETS[target.name]
1171
+ ? `The "${target.name}" field is an _output_ file path so that your build can be consumed by other tools. `
1172
+ : '') +
1173
+ `Change the "${target.name}" field to point to an output file rather than your source code.`,
1174
+ ],
1175
+ documentationURL: 'https://parceljs.org/features/targets/',
1176
+ },
1177
+ });
1178
+ }
1179
+ }
1180
+ }
1181
+ async function debugResolvedTargets(input, targets, targetInfo, options) {
1182
+ for (let target of targets) {
1183
+ let info = targetInfo.get(target.name);
1184
+ let loc = target.loc;
1185
+ if (!loc || !info) {
1186
+ continue;
1187
+ }
1188
+ let output = (0, projectPath_1.fromProjectPath)(options.projectRoot, target.distDir);
1189
+ if (target.distEntry != null) {
1190
+ output = path_1.default.join(output, target.distEntry);
1191
+ }
1192
+ // Resolve relevant engines for context.
1193
+ let engines;
1194
+ const env = (0, EnvironmentManager_1.fromEnvironmentId)(target.env);
1195
+ switch (env.context) {
1196
+ case 'browser':
1197
+ case 'web-worker':
1198
+ case 'service-worker':
1199
+ case 'worklet': {
1200
+ let browsers = env.engines.browsers;
1201
+ engines = Array.isArray(browsers) ? browsers.join(', ') : browsers;
1202
+ break;
1203
+ }
1204
+ case 'node':
1205
+ engines = env.engines.node;
1206
+ break;
1207
+ case 'electron-main':
1208
+ case 'electron-renderer':
1209
+ engines = env.engines.electron;
1210
+ break;
1211
+ }
1212
+ // @ts-expect-error TS2304
1213
+ let highlights = [];
1214
+ if (input.loc) {
1215
+ highlights.push((0, diagnostic_1.convertSourceLocationToHighlight)(input.loc, 'entry defined here'));
1216
+ }
1217
+ // Read package.json where target is defined.
1218
+ let targetFilePath = (0, projectPath_1.fromProjectPath)(options.projectRoot, loc.filePath);
1219
+ let contents = await options.inputFS.readFile(targetFilePath, 'utf8');
1220
+ // Builds up map of code highlights for each defined/inferred path in the package.json.
1221
+ let jsonHighlights = new Map();
1222
+ for (let key in info) {
1223
+ // @ts-expect-error TS7053
1224
+ let keyInfo = info[key];
1225
+ let path = keyInfo.path || keyInfo.inferred;
1226
+ if (!path) {
1227
+ continue;
1228
+ }
1229
+ let type = keyInfo.type || 'value';
1230
+ let highlight = jsonHighlights.get(path);
1231
+ if (!highlight) {
1232
+ highlight = {
1233
+ type: type,
1234
+ defined: '',
1235
+ inferred: [],
1236
+ };
1237
+ jsonHighlights.set(path, highlight);
1238
+ }
1239
+ else if (highlight.type !== type) {
1240
+ highlight.type = null;
1241
+ }
1242
+ if (keyInfo.path) {
1243
+ highlight.defined = (0, diagnostic_1.md) `${key} defined here`;
1244
+ }
1245
+ if (keyInfo.inferred) {
1246
+ // @ts-expect-error TS2345
1247
+ highlight.inferred.push((0, diagnostic_1.md) `${key} to be ${JSON.stringify(env[key])}`);
1248
+ }
1249
+ }
1250
+ let listFormat = new Intl.ListFormat('en-US');
1251
+ // Generate human friendly messages for each field.
1252
+ let highlightsWithMessages = [...jsonHighlights].map(([k, v]) => {
1253
+ let message = v.defined;
1254
+ if (v.inferred.length > 0) {
1255
+ message += (message ? ', ' : '') + 'caused ';
1256
+ message += listFormat.format(v.inferred);
1257
+ }
1258
+ return {
1259
+ key: k,
1260
+ type: v.type,
1261
+ message,
1262
+ };
1263
+ });
1264
+ // Get code highlights from JSON paths.
1265
+ highlights.push(...(0, diagnostic_1.generateJSONCodeHighlights)(contents, highlightsWithMessages));
1266
+ // Format includeNodeModules to be human readable.
1267
+ let includeNodeModules;
1268
+ if (typeof env.includeNodeModules === 'boolean') {
1269
+ includeNodeModules = String(env.includeNodeModules);
1270
+ }
1271
+ else if (Array.isArray(env.includeNodeModules)) {
1272
+ includeNodeModules =
1273
+ 'only ' +
1274
+ listFormat.format(env.includeNodeModules.map((m) => JSON.stringify(m)));
1275
+ }
1276
+ else if (env.includeNodeModules &&
1277
+ typeof env.includeNodeModules === 'object') {
1278
+ includeNodeModules =
1279
+ 'all except ' +
1280
+ listFormat.format(Object.entries(env.includeNodeModules)
1281
+ .filter(([, v]) => v === false)
1282
+ // @ts-expect-error TS2345
1283
+ .map(([k]) => JSON.stringify(k)));
1284
+ }
1285
+ let format = (v) =>
1286
+ // @ts-expect-error TS2339
1287
+ v.message != null ? diagnostic_1.md.italic(v.message) : '';
1288
+ logger_1.default.verbose({
1289
+ origin: '@atlaspack/core',
1290
+ message: (0, diagnostic_1.md) `**Target** "${target.name}"
1291
+
1292
+ **Entry**: ${path_1.default.relative(process.cwd(), (0, projectPath_1.fromProjectPath)(options.projectRoot, input.filePath))}
1293
+ **Output**: ${path_1.default.relative(process.cwd(), output)}
1294
+ **Format**: ${env.outputFormat} ${format(info.outputFormat)}
1295
+ **Context**: ${env.context} ${format(info.context)}
1296
+ **Engines**: ${engines || ''} ${format(info.engines)}
1297
+ **Library Mode**: ${String(env.isLibrary)} ${format(info.isLibrary)}
1298
+ **Include Node Modules**: ${includeNodeModules} ${format(info.includeNodeModules)}
1299
+ **Optimize**: ${String(env.shouldOptimize)} ${format(info.shouldOptimize)}`,
1300
+ codeFrames: target.loc
1301
+ ? [
1302
+ {
1303
+ filePath: targetFilePath,
1304
+ codeHighlights: highlights,
1305
+ },
1306
+ ]
1307
+ : [],
1308
+ });
1309
+ }
1310
+ }