@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,441 @@
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.default = createBundleGraphRequest;
40
+ const fs_1 = __importDefault(require("fs"));
41
+ const assert_1 = __importDefault(require("assert"));
42
+ const assert_2 = __importDefault(require("assert"));
43
+ const nullthrows_1 = __importDefault(require("nullthrows"));
44
+ const logger_1 = require("@atlaspack/logger");
45
+ const feature_flags_1 = require("@atlaspack/feature-flags");
46
+ const diagnostic_1 = __importStar(require("@atlaspack/diagnostic"));
47
+ const BundleGraph_1 = __importDefault(require("../public/BundleGraph"));
48
+ const BundleGraph_2 = __importStar(require("../BundleGraph"));
49
+ const MutableBundleGraph_1 = __importDefault(require("../public/MutableBundleGraph"));
50
+ const Bundle_1 = require("../public/Bundle");
51
+ const ReporterRunner_1 = require("../ReporterRunner");
52
+ const dumpGraphToGraphViz_1 = __importDefault(require("../dumpGraphToGraphViz"));
53
+ const utils_1 = require("@atlaspack/utils");
54
+ const rust_1 = require("@atlaspack/rust");
55
+ const PluginOptions_1 = __importDefault(require("../public/PluginOptions"));
56
+ const applyRuntimes_1 = __importDefault(require("../applyRuntimes"));
57
+ const constants_1 = require("../constants");
58
+ const utils_2 = require("../utils");
59
+ const AtlaspackConfigRequest_1 = __importStar(require("./AtlaspackConfigRequest"));
60
+ const DevDepRequest_1 = require("./DevDepRequest");
61
+ const InternalConfig_1 = require("../InternalConfig");
62
+ const ConfigRequest_1 = require("./ConfigRequest");
63
+ const projectPath_1 = require("../projectPath");
64
+ const AssetGraphRequest_1 = __importDefault(require("./AssetGraphRequest"));
65
+ const AssetGraphRequestRust_1 = require("./AssetGraphRequestRust");
66
+ const profiler_1 = require("@atlaspack/profiler");
67
+ const RequestTracker_1 = require("../RequestTracker");
68
+ const asset_graph_dot_1 = require("./asset-graph-dot");
69
+ const types_1 = require("../types");
70
+ function applySideEffectsForLoadableImports(assetGraph) {
71
+ // Avoid revisiting nodes
72
+ let updatedAssetIds = new Set();
73
+ assetGraph.traverse((nodeId) => {
74
+ let node = (0, nullthrows_1.default)(assetGraph.getNode(nodeId));
75
+ if (node.type !== 'dependency' ||
76
+ node.value.specifier.indexOf('@confluence/loadable') === -1) {
77
+ return;
78
+ }
79
+ assetGraph.traverseAncestors(nodeId, (ancestorNodeId, _, actions) => {
80
+ if (updatedAssetIds.has(ancestorNodeId)) {
81
+ actions.skipChildren();
82
+ return;
83
+ }
84
+ let ancestorNode = (0, nullthrows_1.default)(assetGraph.getNode(ancestorNodeId));
85
+ // Async boundaries will catch the side effects
86
+ if (ancestorNode.type === 'dependency' &&
87
+ ancestorNode.value.priority !== types_1.Priority.sync) {
88
+ actions.skipChildren();
89
+ }
90
+ // inline-requires optimizer is only checking assets
91
+ if (ancestorNode.type !== 'asset') {
92
+ return;
93
+ }
94
+ updatedAssetIds.add(ancestorNodeId);
95
+ ancestorNode.value.sideEffects = true;
96
+ });
97
+ }, assetGraph.rootNodeId);
98
+ }
99
+ function createBundleGraphRequest(input) {
100
+ return {
101
+ type: RequestTracker_1.requestTypes.bundle_graph_request,
102
+ id: 'BundleGraph',
103
+ run: async (input) => {
104
+ let { options, api, invalidateReason } = input;
105
+ let { optionsRef, requestedAssetIds, signal } = input.input;
106
+ let measurement = profiler_1.tracer.createMeasurement('building');
107
+ let createAssetGraphRequest = input.rustAtlaspack
108
+ ? (0, AssetGraphRequestRust_1.createAssetGraphRequestRust)(input.rustAtlaspack)
109
+ : AssetGraphRequest_1.default;
110
+ let request = createAssetGraphRequest({
111
+ name: 'Main',
112
+ entries: options.entries,
113
+ optionsRef,
114
+ shouldBuildLazily: options.shouldBuildLazily,
115
+ lazyIncludes: options.lazyIncludes,
116
+ lazyExcludes: options.lazyExcludes,
117
+ requestedAssetIds,
118
+ });
119
+ let { assetGraph, changedAssets, assetRequests } = await api.runRequest(request, {
120
+ force: Boolean(input.rustAtlaspack) ||
121
+ (options.shouldBuildLazily && requestedAssetIds.size > 0),
122
+ });
123
+ if (input.options.featureFlags?.loadableSideEffects) {
124
+ applySideEffectsForLoadableImports(assetGraph);
125
+ }
126
+ let debugAssetGraphDotPath = (0, asset_graph_dot_1.getDebugAssetGraphDotPath)();
127
+ if (debugAssetGraphDotPath !== null) {
128
+ await fs_1.default.promises.writeFile(debugAssetGraphDotPath, (0, asset_graph_dot_1.assetGraphToDot)(assetGraph, (0, asset_graph_dot_1.getDebugAssetGraphDotOptions)()), 'utf8');
129
+ }
130
+ // if (input.rustAtlaspack && process.env.NATIVE_COMPARE === 'true') {
131
+ // let {assetGraph: jsAssetGraph} = await api.runRequest(
132
+ // createAssetGraphRequestJS({
133
+ // name: 'Main',
134
+ // entries: options.entries,
135
+ // optionsRef,
136
+ // shouldBuildLazily: options.shouldBuildLazily,
137
+ // lazyIncludes: options.lazyIncludes,
138
+ // lazyExcludes: options.lazyExcludes,
139
+ // requestedAssetIds,
140
+ // }),
141
+ // {
142
+ // force: true,
143
+ // },
144
+ // );
145
+ // require('./asset-graph-diff.js')(jsAssetGraph, assetGraph);
146
+ // }
147
+ measurement && measurement.end();
148
+ (0, utils_2.assertSignalNotAborted)(signal);
149
+ // If any subrequests are invalid (e.g. dev dep requests or config requests),
150
+ // bail on incremental bundling. We also need to invalidate for option changes,
151
+ // which are hoisted to direct invalidations on the bundle graph request.
152
+ let subRequestsInvalid = Boolean(invalidateReason & constants_1.OPTION_CHANGE) ||
153
+ input.api
154
+ .getSubRequests()
155
+ .some((req) => !input.api.canSkipSubrequest(req.id));
156
+ if (subRequestsInvalid) {
157
+ assetGraph.safeToIncrementallyBundle = false;
158
+ assetGraph.setNeedsBundling();
159
+ }
160
+ let configResult = (0, nullthrows_1.default)(await input.api.runRequest((0, AtlaspackConfigRequest_1.default)()));
161
+ (0, utils_2.assertSignalNotAborted)(signal);
162
+ let atlaspackConfig = (0, AtlaspackConfigRequest_1.getCachedAtlaspackConfig)(configResult, input.options);
163
+ let { devDeps, invalidDevDeps } = await (0, DevDepRequest_1.getDevDepRequests)(input.api);
164
+ (0, DevDepRequest_1.invalidateDevDeps)(invalidDevDeps, input.options, atlaspackConfig);
165
+ let bundlingMeasurement = profiler_1.tracer.createMeasurement('bundling');
166
+ let builder = new BundlerRunner(input, atlaspackConfig, devDeps);
167
+ let res = await builder.bundle({
168
+ graph: assetGraph,
169
+ changedAssets: changedAssets,
170
+ assetRequests,
171
+ });
172
+ bundlingMeasurement && bundlingMeasurement.end();
173
+ for (let [id, asset] of changedAssets) {
174
+ res.changedAssets.set(id, asset);
175
+ }
176
+ await (0, dumpGraphToGraphViz_1.default)(
177
+ // @ts-expect-error TS2345
178
+ res.bundleGraph._graph, 'BundleGraph', BundleGraph_2.bundleGraphEdgeTypes);
179
+ return res;
180
+ },
181
+ input,
182
+ };
183
+ }
184
+ class BundlerRunner {
185
+ constructor({ input, api, options }, config, previousDevDeps) {
186
+ this.options = options;
187
+ this.api = api;
188
+ this.optionsRef = input.optionsRef;
189
+ this.config = config;
190
+ this.previousDevDeps = previousDevDeps;
191
+ this.devDepRequests = new Map();
192
+ this.configs = new Map();
193
+ this.pluginOptions = new PluginOptions_1.default((0, utils_2.optionsProxy)(this.options, api.invalidateOnOptionChange));
194
+ if ((0, feature_flags_1.getFeatureFlag)('cachePerformanceImprovements')) {
195
+ const key = (0, rust_1.hashString)(`${constants_1.ATLASPACK_VERSION}:BundleGraph:${JSON.stringify(options.entries) ?? ''}${options.mode}${options.shouldBuildLazily ? 'lazy' : 'eager'}`);
196
+ this.cacheKey = `BundleGraph/${constants_1.ATLASPACK_VERSION}/${options.mode}/${key}`;
197
+ }
198
+ else {
199
+ this.cacheKey =
200
+ (0, rust_1.hashString)(`${constants_1.ATLASPACK_VERSION}:BundleGraph:${JSON.stringify(options.entries) ?? ''}${options.mode}${options.shouldBuildLazily ? 'lazy' : 'eager'}`) + '-BundleGraph';
201
+ }
202
+ }
203
+ async loadConfigs() {
204
+ // Load all configs up front so we can use them in the cache key
205
+ let bundler = await this.config.getBundler();
206
+ await this.loadConfig(bundler);
207
+ let namers = await this.config.getNamers();
208
+ for (let namer of namers) {
209
+ await this.loadConfig(namer);
210
+ }
211
+ let runtimes = await this.config.getRuntimes();
212
+ for (let runtime of runtimes) {
213
+ await this.loadConfig(runtime);
214
+ }
215
+ }
216
+ async loadConfig(plugin) {
217
+ let config = (0, InternalConfig_1.createConfig)({
218
+ plugin: plugin.name,
219
+ searchPath: (0, projectPath_1.toProjectPathUnsafe)('index'),
220
+ });
221
+ await (0, ConfigRequest_1.loadPluginConfig)(plugin, config, this.options);
222
+ await (0, ConfigRequest_1.runConfigRequest)(this.api, config);
223
+ for (let devDep of config.devDeps) {
224
+ let devDepRequest = await (0, DevDepRequest_1.createDevDependency)(devDep, this.previousDevDeps, this.options);
225
+ await this.runDevDepRequest(devDepRequest);
226
+ }
227
+ this.configs.set(plugin.name, config);
228
+ }
229
+ async runDevDepRequest(devDepRequest) {
230
+ let { specifier, resolveFrom } = devDepRequest;
231
+ let key = `${specifier}:${(0, projectPath_1.fromProjectPathRelative)(resolveFrom)}`;
232
+ this.devDepRequests.set(key, devDepRequest);
233
+ await (0, DevDepRequest_1.runDevDepRequest)(this.api, devDepRequest);
234
+ }
235
+ async bundle({ graph, changedAssets, assetRequests, }) {
236
+ (0, ReporterRunner_1.report)({
237
+ type: 'buildProgress',
238
+ phase: 'bundling',
239
+ });
240
+ await this.loadConfigs();
241
+ let plugin = await this.config.getBundler();
242
+ let { plugin: bundler, name, resolveFrom } = plugin;
243
+ // if a previous asset graph hash is passed in, check if the bundle graph is also available
244
+ const previousBundleGraphResult = await this.api.getPreviousResult();
245
+ const canIncrementallyBundle = previousBundleGraphResult?.assetGraphBundlingVersion != null &&
246
+ graph.canIncrementallyBundle(previousBundleGraphResult.assetGraphBundlingVersion);
247
+ if (graph.safeToIncrementallyBundle && previousBundleGraphResult == null) {
248
+ graph.safeToIncrementallyBundle = false;
249
+ graph.setNeedsBundling();
250
+ }
251
+ let internalBundleGraph;
252
+ let logger = new logger_1.PluginLogger({ origin: name });
253
+ let tracer = new profiler_1.PluginTracer({
254
+ origin: name,
255
+ category: 'bundle',
256
+ });
257
+ try {
258
+ if (canIncrementallyBundle && previousBundleGraphResult) {
259
+ internalBundleGraph = previousBundleGraphResult.bundleGraph;
260
+ for (let changedAssetId of changedAssets.keys()) {
261
+ // Copy over the whole node to also have correct symbol data
262
+ let changedAssetNode = (0, nullthrows_1.default)(graph.getNodeByContentKey(changedAssetId));
263
+ (0, assert_1.default)(changedAssetNode.type === 'asset');
264
+ internalBundleGraph.updateAsset(changedAssetNode);
265
+ }
266
+ }
267
+ else {
268
+ internalBundleGraph = BundleGraph_2.default.fromAssetGraph(graph, this.options.mode === 'production');
269
+ (0, assert_1.default)(internalBundleGraph != null); // ensures the graph was created
270
+ await (0, dumpGraphToGraphViz_1.default)(
271
+ // @ts-expect-error TS2345
272
+ internalBundleGraph._graph, 'before_bundle', BundleGraph_2.bundleGraphEdgeTypes);
273
+ let mutableBundleGraph = new MutableBundleGraph_1.default(internalBundleGraph, this.options);
274
+ let measurement;
275
+ let measurementFilename;
276
+ if (tracer.enabled) {
277
+ measurementFilename = graph
278
+ .getEntryAssets()
279
+ .map((asset) => (0, projectPath_1.fromProjectPathRelative)(asset.filePath))
280
+ .join(', ');
281
+ measurement = tracer.createMeasurement(plugin.name, 'bundling:bundle', measurementFilename);
282
+ }
283
+ // this the normal bundle workflow (bundle, optimizing, run-times, naming)
284
+ await bundler.bundle({
285
+ bundleGraph: mutableBundleGraph,
286
+ config: this.configs.get(plugin.name)?.result,
287
+ options: this.pluginOptions,
288
+ logger,
289
+ tracer,
290
+ });
291
+ measurement && measurement.end();
292
+ if (this.pluginOptions.mode === 'production') {
293
+ let optimizeMeasurement;
294
+ try {
295
+ if (tracer.enabled) {
296
+ optimizeMeasurement = tracer.createMeasurement(plugin.name, 'bundling:optimize', (0, nullthrows_1.default)(measurementFilename));
297
+ }
298
+ await bundler.optimize({
299
+ bundleGraph: mutableBundleGraph,
300
+ config: this.configs.get(plugin.name)?.result,
301
+ options: this.pluginOptions,
302
+ logger,
303
+ });
304
+ }
305
+ catch (e) {
306
+ throw new diagnostic_1.default({
307
+ diagnostic: (0, diagnostic_1.errorToDiagnostic)(e, {
308
+ origin: plugin.name,
309
+ }),
310
+ });
311
+ }
312
+ finally {
313
+ optimizeMeasurement && optimizeMeasurement.end();
314
+ await (0, dumpGraphToGraphViz_1.default)(
315
+ // @ts-expect-error TS2345
316
+ internalBundleGraph._graph, 'after_optimize');
317
+ }
318
+ }
319
+ // Add dev dependency for the bundler. This must be done AFTER running it due to
320
+ // the potential for lazy require() that aren't executed until the request runs.
321
+ let devDepRequest = await (0, DevDepRequest_1.createDevDependency)({
322
+ specifier: name,
323
+ resolveFrom,
324
+ }, this.previousDevDeps, this.options);
325
+ await this.runDevDepRequest(devDepRequest);
326
+ }
327
+ }
328
+ catch (e) {
329
+ if (internalBundleGraph != null) {
330
+ this.api.storeResult({
331
+ bundleGraph: internalBundleGraph,
332
+ assetGraphBundlingVersion: graph.getBundlingVersion(),
333
+ changedAssets: new Map(),
334
+ assetRequests: [],
335
+ }, this.cacheKey);
336
+ }
337
+ throw new diagnostic_1.default({
338
+ diagnostic: (0, diagnostic_1.errorToDiagnostic)(e, {
339
+ origin: name,
340
+ }),
341
+ });
342
+ }
343
+ finally {
344
+ if (internalBundleGraph != null) {
345
+ await (0, dumpGraphToGraphViz_1.default)(
346
+ // @ts-expect-error TS2345
347
+ internalBundleGraph._graph, 'after_bundle', BundleGraph_2.bundleGraphEdgeTypes);
348
+ }
349
+ }
350
+ let changedRuntimes = new Map();
351
+ if (!previousBundleGraphResult || !canIncrementallyBundle) {
352
+ let namers = await this.config.getNamers();
353
+ // inline bundles must still be named so the PackagerRunner
354
+ // can match them to the correct packager/optimizer plugins.
355
+ let bundles = internalBundleGraph.getBundles({ includeInline: true });
356
+ await Promise.all(bundles.map((bundle) => this.nameBundle(namers, bundle, internalBundleGraph)));
357
+ changedRuntimes = await (0, applyRuntimes_1.default)({
358
+ bundleGraph: internalBundleGraph,
359
+ api: this.api,
360
+ config: this.config,
361
+ options: this.options,
362
+ optionsRef: this.optionsRef,
363
+ pluginOptions: this.pluginOptions,
364
+ previousDevDeps: this.previousDevDeps,
365
+ devDepRequests: this.devDepRequests,
366
+ configs: this.configs,
367
+ });
368
+ // Add dev deps for namers, AFTER running them to account for lazy require().
369
+ for (let namer of namers) {
370
+ let devDepRequest = await (0, DevDepRequest_1.createDevDependency)({
371
+ specifier: namer.name,
372
+ resolveFrom: namer.resolveFrom,
373
+ }, this.previousDevDeps, this.options);
374
+ await this.runDevDepRequest(devDepRequest);
375
+ }
376
+ this.validateBundles(internalBundleGraph);
377
+ // Pre-compute the hashes for each bundle so they are only computed once and shared between workers.
378
+ internalBundleGraph.getBundleGraphHash();
379
+ }
380
+ await (0, dumpGraphToGraphViz_1.default)(
381
+ // @ts-expect-error TS2345
382
+ internalBundleGraph._graph, 'after_runtimes', BundleGraph_2.bundleGraphEdgeTypes);
383
+ this.api.storeResult({
384
+ bundleGraph: internalBundleGraph,
385
+ assetGraphBundlingVersion: graph.getBundlingVersion(),
386
+ changedAssets: new Map(),
387
+ assetRequests: [],
388
+ }, this.cacheKey);
389
+ return {
390
+ bundleGraph: internalBundleGraph,
391
+ assetGraphBundlingVersion: graph.getBundlingVersion(),
392
+ changedAssets: changedRuntimes,
393
+ assetRequests,
394
+ };
395
+ }
396
+ validateBundles(bundleGraph) {
397
+ let bundles = bundleGraph.getBundles();
398
+ let bundleNames = bundles.map((b) => (0, projectPath_1.joinProjectPath)(b.target.distDir, (0, nullthrows_1.default)(b.name)));
399
+ assert_2.default.deepEqual(bundleNames, (0, utils_1.unique)(bundleNames), 'Bundles must have unique name. Conflicting names: ' +
400
+ [
401
+ ...(0, utils_1.setSymmetricDifference)(new Set(bundleNames), new Set((0, utils_1.unique)(bundleNames))),
402
+ ].join());
403
+ }
404
+ async nameBundle(namers, internalBundle, internalBundleGraph) {
405
+ let bundle = Bundle_1.Bundle.get(internalBundle, internalBundleGraph, this.options);
406
+ let bundleGraph = new BundleGraph_1.default(internalBundleGraph, Bundle_1.NamedBundle.get.bind(Bundle_1.NamedBundle), this.options);
407
+ for (let namer of namers) {
408
+ let measurement;
409
+ try {
410
+ measurement = profiler_1.tracer.createMeasurement(namer.name, 'namer', bundle.id);
411
+ let name = await namer.plugin.name({
412
+ bundle,
413
+ bundleGraph,
414
+ config: this.configs.get(namer.name)?.result,
415
+ options: this.pluginOptions,
416
+ logger: new logger_1.PluginLogger({ origin: namer.name }),
417
+ tracer: new profiler_1.PluginTracer({ origin: namer.name, category: 'namer' }),
418
+ });
419
+ if (name != null) {
420
+ internalBundle.name = name;
421
+ let { hashReference } = internalBundle;
422
+ internalBundle.displayName = name.includes(hashReference)
423
+ ? name.replace(hashReference, '[hash]')
424
+ : name;
425
+ return;
426
+ }
427
+ }
428
+ catch (e) {
429
+ throw new diagnostic_1.default({
430
+ diagnostic: (0, diagnostic_1.errorToDiagnostic)(e, {
431
+ origin: namer.name,
432
+ }),
433
+ });
434
+ }
435
+ finally {
436
+ measurement && measurement.end();
437
+ }
438
+ }
439
+ throw new Error('Unable to name bundle');
440
+ }
441
+ }
@@ -0,0 +1,222 @@
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.loadPluginConfig = loadPluginConfig;
40
+ exports.getValueAtPath = getValueAtPath;
41
+ exports.getConfigKeyContentHash = getConfigKeyContentHash;
42
+ exports.runConfigRequest = runConfigRequest;
43
+ exports.getConfigHash = getConfigHash;
44
+ exports.getConfigRequests = getConfigRequests;
45
+ const utils_1 = require("@atlaspack/utils");
46
+ const build_cache_1 = require("@atlaspack/build-cache");
47
+ const logger_1 = require("@atlaspack/logger");
48
+ const PluginOptions_1 = __importDefault(require("../public/PluginOptions"));
49
+ const diagnostic_1 = __importStar(require("@atlaspack/diagnostic"));
50
+ const Config_1 = __importDefault(require("../public/Config"));
51
+ const utils_2 = require("../utils");
52
+ const assetUtils_1 = require("../assetUtils");
53
+ const rust_1 = require("@atlaspack/rust");
54
+ const profiler_1 = require("@atlaspack/profiler");
55
+ const RequestTracker_1 = require("../RequestTracker");
56
+ const projectPath_1 = require("../projectPath");
57
+ async function loadPluginConfig(loadedPlugin, config, options) {
58
+ let loadConfig = loadedPlugin.plugin.loadConfig;
59
+ if (!loadConfig) {
60
+ return;
61
+ }
62
+ try {
63
+ config.result = await loadConfig({
64
+ config: new Config_1.default(config, options),
65
+ options: new PluginOptions_1.default((0, utils_2.optionsProxy)(options, (option) => {
66
+ config.invalidateOnOptionChange.add(option);
67
+ })),
68
+ logger: new logger_1.PluginLogger({ origin: loadedPlugin.name }),
69
+ tracer: new profiler_1.PluginTracer({
70
+ origin: loadedPlugin.name,
71
+ category: 'loadConfig',
72
+ }),
73
+ });
74
+ }
75
+ catch (e) {
76
+ throw new diagnostic_1.default({
77
+ diagnostic: (0, diagnostic_1.errorToDiagnostic)(e, {
78
+ origin: loadedPlugin.name,
79
+ }),
80
+ });
81
+ }
82
+ }
83
+ /**
84
+ * Return value at a given key path within an object.
85
+ *
86
+ * @example
87
+ * const obj = { a: { b: { c: 'd' } } };
88
+ * getValueAtPath(obj, ['a', 'b', 'c']); // 'd'
89
+ * getValueAtPath(obj, ['a', 'b', 'd']); // undefined
90
+ * getValueAtPath(obj, ['a', 'b']); // { c: 'd' }
91
+ * getValueAtPath(obj, ['a', 'b', 'c', 'd']); // undefined
92
+ */
93
+ function getValueAtPath(obj, key) {
94
+ let current = obj;
95
+ for (let part of key) {
96
+ if (current == null) {
97
+ return undefined;
98
+ }
99
+ current = current[part];
100
+ }
101
+ return current;
102
+ }
103
+ const configKeyCache = (0, build_cache_1.createBuildCache)();
104
+ async function getConfigKeyContentHash(filePath, configKey, options) {
105
+ let cacheKey = `${(0, projectPath_1.fromProjectPathRelative)(filePath)}:${JSON.stringify(configKey)}`;
106
+ let cachedValue = configKeyCache.get(cacheKey);
107
+ if (cachedValue) {
108
+ // @ts-expect-error TS2322
109
+ return cachedValue;
110
+ }
111
+ const conf = await (0, utils_1.readConfig)(options.inputFS, (0, projectPath_1.fromProjectPath)(options.projectRoot, filePath));
112
+ const value = getValueAtPath(conf?.config, configKey);
113
+ if (conf == null || value == null) {
114
+ // This can occur when a config key has been removed entirely during `respondToFSEvents`
115
+ return '';
116
+ }
117
+ const contentHash = typeof value === 'object'
118
+ ? (0, utils_1.hashObject)(value)
119
+ : (0, rust_1.hashString)(JSON.stringify(value));
120
+ configKeyCache.set(cacheKey, contentHash);
121
+ return contentHash;
122
+ }
123
+ async function runConfigRequest(api, configRequest) {
124
+ let { invalidateOnFileChange, invalidateOnConfigKeyChange, invalidateOnFileCreate, invalidateOnEnvChange, invalidateOnOptionChange, invalidateOnStartup, invalidateOnBuild, } = configRequest;
125
+ // If there are no invalidations, then no need to create a node.
126
+ if (invalidateOnFileChange.size === 0 &&
127
+ invalidateOnConfigKeyChange.length === 0 &&
128
+ invalidateOnFileCreate.length === 0 &&
129
+ invalidateOnOptionChange.size === 0 &&
130
+ invalidateOnEnvChange.size === 0 &&
131
+ !invalidateOnStartup &&
132
+ !invalidateOnBuild) {
133
+ return;
134
+ }
135
+ await api.runRequest({
136
+ id: 'config_request:' + configRequest.id,
137
+ type: RequestTracker_1.requestTypes.config_request,
138
+ run: async ({ api, options }) => {
139
+ for (let filePath of invalidateOnFileChange) {
140
+ api.invalidateOnFileUpdate(filePath);
141
+ api.invalidateOnFileDelete(filePath);
142
+ }
143
+ for (let { filePath, configKey } of invalidateOnConfigKeyChange) {
144
+ let contentHash = await getConfigKeyContentHash(filePath, configKey, options);
145
+ api.invalidateOnConfigKeyChange(filePath, configKey, contentHash);
146
+ }
147
+ for (let invalidation of invalidateOnFileCreate) {
148
+ api.invalidateOnFileCreate(invalidation);
149
+ }
150
+ for (let env of invalidateOnEnvChange) {
151
+ api.invalidateOnEnvChange(env);
152
+ }
153
+ for (let option of invalidateOnOptionChange) {
154
+ api.invalidateOnOptionChange(option);
155
+ }
156
+ if (invalidateOnStartup) {
157
+ api.invalidateOnStartup();
158
+ }
159
+ if (invalidateOnBuild) {
160
+ api.invalidateOnBuild();
161
+ }
162
+ },
163
+ input: null,
164
+ });
165
+ }
166
+ async function getConfigHash(config, pluginName, options) {
167
+ if (config.result == null) {
168
+ return '';
169
+ }
170
+ let hash = new rust_1.Hash();
171
+ hash.writeString(config.id);
172
+ // If there is no result hash set by the transformer, default to hashing the included
173
+ // files if any, otherwise try to hash the config result itself.
174
+ if (config.cacheKey == null) {
175
+ if (config.invalidateOnFileChange.size > 0) {
176
+ hash.writeString(await (0, assetUtils_1.getInvalidationHash)([...config.invalidateOnFileChange].map((filePath) => ({
177
+ type: 'file',
178
+ filePath,
179
+ })), options));
180
+ }
181
+ else if (config.result != null) {
182
+ try {
183
+ hash.writeBuffer((0, build_cache_1.serializeRaw)(config.result));
184
+ }
185
+ catch (err) {
186
+ throw new diagnostic_1.default({
187
+ diagnostic: {
188
+ message: 'Config result is not hashable because it contains non-serializable objects. Please use config.setCacheKey to set the hash manually.',
189
+ origin: pluginName,
190
+ },
191
+ });
192
+ }
193
+ }
194
+ }
195
+ else {
196
+ hash.writeString(config.cacheKey ?? '');
197
+ }
198
+ return hash.finish();
199
+ }
200
+ function getConfigRequests(configs) {
201
+ return configs
202
+ .filter((config) => {
203
+ // No need to send to the graph if there are no invalidations.
204
+ return (config.invalidateOnFileChange.size > 0 ||
205
+ config.invalidateOnConfigKeyChange.length > 0 ||
206
+ config.invalidateOnFileCreate.length > 0 ||
207
+ config.invalidateOnEnvChange.size > 0 ||
208
+ config.invalidateOnOptionChange.size > 0 ||
209
+ config.invalidateOnStartup ||
210
+ config.invalidateOnBuild);
211
+ })
212
+ .map((config) => ({
213
+ id: config.id,
214
+ invalidateOnFileChange: config.invalidateOnFileChange,
215
+ invalidateOnConfigKeyChange: config.invalidateOnConfigKeyChange,
216
+ invalidateOnFileCreate: config.invalidateOnFileCreate,
217
+ invalidateOnEnvChange: config.invalidateOnEnvChange,
218
+ invalidateOnOptionChange: config.invalidateOnOptionChange,
219
+ invalidateOnStartup: config.invalidateOnStartup,
220
+ invalidateOnBuild: config.invalidateOnBuild,
221
+ }));
222
+ }