@atlaspack/core 2.14.0 → 2.14.1-canary.6

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 (81) hide show
  1. package/LICENSE +201 -0
  2. package/lib/AssetGraph.js +521 -0
  3. package/lib/Atlaspack.js +677 -0
  4. package/lib/AtlaspackConfig.js +298 -0
  5. package/lib/AtlaspackConfig.schema.js +103 -0
  6. package/lib/BundleGraph.js +1527 -0
  7. package/lib/CommittedAsset.js +155 -0
  8. package/lib/Dependency.js +136 -0
  9. package/lib/Environment.js +144 -0
  10. package/lib/IdentifierRegistry.js +36 -0
  11. package/lib/InternalConfig.js +56 -0
  12. package/lib/PackagerRunner.js +525 -0
  13. package/lib/ReporterRunner.js +151 -0
  14. package/lib/RequestTracker.js +1178 -0
  15. package/lib/SymbolPropagation.js +618 -0
  16. package/lib/TargetDescriptor.schema.js +118 -0
  17. package/lib/Transformation.js +522 -0
  18. package/lib/UncommittedAsset.js +348 -0
  19. package/lib/Validation.js +203 -0
  20. package/lib/applyRuntimes.js +355 -0
  21. package/lib/assetUtils.js +205 -0
  22. package/lib/atlaspack-v3/AtlaspackV3.js +66 -0
  23. package/lib/atlaspack-v3/NapiWorkerPool.js +71 -0
  24. package/lib/atlaspack-v3/fs.js +39 -0
  25. package/lib/atlaspack-v3/index.js +26 -0
  26. package/lib/atlaspack-v3/jsCallable.js +20 -0
  27. package/lib/atlaspack-v3/worker/compat/asset-symbols.js +197 -0
  28. package/lib/atlaspack-v3/worker/compat/bitflags.js +84 -0
  29. package/lib/atlaspack-v3/worker/compat/dependency.js +44 -0
  30. package/lib/atlaspack-v3/worker/compat/environment.js +57 -0
  31. package/lib/atlaspack-v3/worker/compat/index.js +104 -0
  32. package/lib/atlaspack-v3/worker/compat/mutable-asset.js +164 -0
  33. package/lib/atlaspack-v3/worker/compat/plugin-config.js +78 -0
  34. package/lib/atlaspack-v3/worker/compat/plugin-logger.js +29 -0
  35. package/lib/atlaspack-v3/worker/compat/plugin-options.js +113 -0
  36. package/lib/atlaspack-v3/worker/compat/plugin-tracer.js +12 -0
  37. package/lib/atlaspack-v3/worker/compat/target.js +17 -0
  38. package/lib/atlaspack-v3/worker/index.js +3 -0
  39. package/lib/atlaspack-v3/worker/worker.js +280 -0
  40. package/lib/constants.js +21 -0
  41. package/lib/dumpGraphToGraphViz.js +206 -0
  42. package/lib/index.js +70 -0
  43. package/lib/loadAtlaspackPlugin.js +115 -0
  44. package/lib/loadDotEnv.js +54 -0
  45. package/lib/projectPath.js +112 -0
  46. package/lib/public/Asset.js +259 -0
  47. package/lib/public/Bundle.js +236 -0
  48. package/lib/public/BundleGraph.js +279 -0
  49. package/lib/public/BundleGroup.js +50 -0
  50. package/lib/public/Config.js +202 -0
  51. package/lib/public/Dependency.js +131 -0
  52. package/lib/public/Environment.js +247 -0
  53. package/lib/public/MutableBundleGraph.js +204 -0
  54. package/lib/public/PluginOptions.js +71 -0
  55. package/lib/public/Symbols.js +247 -0
  56. package/lib/public/Target.js +64 -0
  57. package/lib/registerCoreWithSerializer.js +51 -0
  58. package/lib/requests/AssetGraphRequest.js +432 -0
  59. package/lib/requests/AssetGraphRequestRust.js +220 -0
  60. package/lib/requests/AssetRequest.js +132 -0
  61. package/lib/requests/AtlaspackBuildRequest.js +79 -0
  62. package/lib/requests/AtlaspackConfigRequest.js +479 -0
  63. package/lib/requests/BundleGraphRequest.js +485 -0
  64. package/lib/requests/ConfigRequest.js +203 -0
  65. package/lib/requests/DevDepRequest.js +193 -0
  66. package/lib/requests/EntryRequest.js +295 -0
  67. package/lib/requests/PackageRequest.js +88 -0
  68. package/lib/requests/PathRequest.js +357 -0
  69. package/lib/requests/TargetRequest.js +1179 -0
  70. package/lib/requests/ValidationRequest.js +66 -0
  71. package/lib/requests/WriteBundleRequest.js +252 -0
  72. package/lib/requests/WriteBundlesRequest.js +167 -0
  73. package/lib/requests/asset-graph-diff.js +128 -0
  74. package/lib/requests/asset-graph-dot.js +131 -0
  75. package/lib/resolveOptions.js +265 -0
  76. package/lib/serializerCore.browser.js +29 -0
  77. package/lib/summarizeRequest.js +55 -0
  78. package/lib/types.js +35 -0
  79. package/lib/utils.js +160 -0
  80. package/lib/worker.js +184 -0
  81. package/package.json +20 -19
@@ -0,0 +1,677 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.WORKER_PATH = exports.INTERNAL_TRANSFORM = exports.INTERNAL_RESOLVE = exports.BuildError = void 0;
7
+ exports.createWorkerFarm = createWorkerFarm;
8
+ exports.default = void 0;
9
+ function _path() {
10
+ const data = _interopRequireDefault(require("path"));
11
+ _path = function () {
12
+ return data;
13
+ };
14
+ return data;
15
+ }
16
+ function _assert() {
17
+ const data = _interopRequireDefault(require("assert"));
18
+ _assert = function () {
19
+ return data;
20
+ };
21
+ return data;
22
+ }
23
+ function _diagnostic() {
24
+ const data = _interopRequireWildcard(require("@atlaspack/diagnostic"));
25
+ _diagnostic = function () {
26
+ return data;
27
+ };
28
+ return data;
29
+ }
30
+ var _Asset = require("./public/Asset");
31
+ var _Bundle = require("./public/Bundle");
32
+ var _BundleGraph = _interopRequireDefault(require("./public/BundleGraph"));
33
+ function _workers() {
34
+ const data = _interopRequireDefault(require("@atlaspack/workers"));
35
+ _workers = function () {
36
+ return data;
37
+ };
38
+ return data;
39
+ }
40
+ function _nullthrows() {
41
+ const data = _interopRequireDefault(require("nullthrows"));
42
+ _nullthrows = function () {
43
+ return data;
44
+ };
45
+ return data;
46
+ }
47
+ var _utils = require("./utils");
48
+ var _AtlaspackConfigRequest = require("./requests/AtlaspackConfigRequest");
49
+ var _ReporterRunner = _interopRequireDefault(require("./ReporterRunner"));
50
+ var _dumpGraphToGraphViz = _interopRequireDefault(require("./dumpGraphToGraphViz"));
51
+ var _resolveOptions = _interopRequireDefault(require("./resolveOptions"));
52
+ function _events() {
53
+ const data = require("@atlaspack/events");
54
+ _events = function () {
55
+ return data;
56
+ };
57
+ return data;
58
+ }
59
+ var _registerCoreWithSerializer = require("./registerCoreWithSerializer");
60
+ function _utils2() {
61
+ const data = require("@atlaspack/utils");
62
+ _utils2 = function () {
63
+ return data;
64
+ };
65
+ return data;
66
+ }
67
+ var _AtlaspackConfig = require("./AtlaspackConfig");
68
+ function _logger() {
69
+ const data = _interopRequireDefault(require("@atlaspack/logger"));
70
+ _logger = function () {
71
+ return data;
72
+ };
73
+ return data;
74
+ }
75
+ var _RequestTracker = _interopRequireWildcard(require("./RequestTracker"));
76
+ var _ValidationRequest = _interopRequireDefault(require("./requests/ValidationRequest"));
77
+ var _AtlaspackBuildRequest = _interopRequireDefault(require("./requests/AtlaspackBuildRequest"));
78
+ var _AssetRequest = _interopRequireDefault(require("./requests/AssetRequest"));
79
+ var _PathRequest = _interopRequireDefault(require("./requests/PathRequest"));
80
+ var _Environment = require("./Environment");
81
+ var _Dependency = require("./Dependency");
82
+ function _sourceMap() {
83
+ const data = require("@parcel/source-map");
84
+ _sourceMap = function () {
85
+ return data;
86
+ };
87
+ return data;
88
+ }
89
+ function _cache() {
90
+ const data = require("@atlaspack/cache");
91
+ _cache = function () {
92
+ return data;
93
+ };
94
+ return data;
95
+ }
96
+ function _rust() {
97
+ const data = require("@atlaspack/rust");
98
+ _rust = function () {
99
+ return data;
100
+ };
101
+ return data;
102
+ }
103
+ var _projectPath = require("./projectPath");
104
+ function _profiler() {
105
+ const data = require("@atlaspack/profiler");
106
+ _profiler = function () {
107
+ return data;
108
+ };
109
+ return data;
110
+ }
111
+ function _featureFlags() {
112
+ const data = require("@atlaspack/feature-flags");
113
+ _featureFlags = function () {
114
+ return data;
115
+ };
116
+ return data;
117
+ }
118
+ var _atlaspackV = require("./atlaspack-v3");
119
+ var _AssetGraphRequest = _interopRequireDefault(require("./requests/AssetGraphRequest"));
120
+ var _AssetGraphRequestRust = require("./requests/AssetGraphRequestRust");
121
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
122
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
123
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
124
+ // eslint-disable-next-line no-unused-vars
125
+ (0, _registerCoreWithSerializer.registerCoreWithSerializer)();
126
+ const INTERNAL_TRANSFORM = exports.INTERNAL_TRANSFORM = Symbol('internal_transform');
127
+ const INTERNAL_RESOLVE = exports.INTERNAL_RESOLVE = Symbol('internal_resolve');
128
+ const WORKER_PATH = exports.WORKER_PATH = _path().default.join(__dirname, 'worker.js');
129
+ class Atlaspack {
130
+ #requestTracker /*: RequestTracker*/;
131
+ #config /*: AtlaspackConfig*/;
132
+ #farm /*: WorkerFarm*/;
133
+ #initialized /*: boolean*/ = false;
134
+ #disposable /*: Disposable */;
135
+ #initialOptions /*: InitialAtlaspackOptions */;
136
+ #reporterRunner /*: ReporterRunner*/;
137
+ #resolvedOptions /*: ?AtlaspackOptions*/ = null;
138
+ #optionsRef /*: SharedReference */;
139
+ #watchAbortController /*: AbortController*/;
140
+ #watchQueue /*: PromiseQueue<?BuildEvent>*/ = new (_utils2().PromiseQueue)({
141
+ maxConcurrent: 1
142
+ });
143
+ #watchEvents /*: ValueEmitter<
144
+ | {|
145
+ +error: Error,
146
+ +buildEvent?: void,
147
+ |}
148
+ | {|
149
+ +buildEvent: BuildEvent,
150
+ +error?: void,
151
+ |},
152
+ > */;
153
+ #watcherSubscription /*: ?AsyncSubscription*/;
154
+ #watcherCount /*: number*/ = 0;
155
+ #requestedAssetIds /*: Set<string>*/ = new Set();
156
+ constructor(options) {
157
+ this.#initialOptions = options;
158
+ }
159
+ async _init() {
160
+ if (this.#initialized) {
161
+ return;
162
+ }
163
+ const featureFlags = {
164
+ ..._featureFlags().DEFAULT_FEATURE_FLAGS,
165
+ ...this.#initialOptions.featureFlags
166
+ };
167
+ (0, _featureFlags().setFeatureFlags)(featureFlags);
168
+ await _sourceMap().init;
169
+ await (_rust().init === null || _rust().init === void 0 ? void 0 : (0, _rust().init)());
170
+ this.#disposable = new (_events().Disposable)();
171
+ try {
172
+ _rust().initializeMonitoring === null || _rust().initializeMonitoring === void 0 || (0, _rust().initializeMonitoring)();
173
+ const onExit = () => {
174
+ _rust().closeMonitoring === null || _rust().closeMonitoring === void 0 || (0, _rust().closeMonitoring)();
175
+ };
176
+ process.on('exit', onExit);
177
+ this.#disposable.add(() => {
178
+ process.off('exit', onExit);
179
+ onExit();
180
+ });
181
+ } catch (e) {
182
+ // Fallthrough
183
+ // eslint-disable-next-line no-console
184
+ console.warn(e);
185
+ }
186
+ let resolvedOptions = await (0, _resolveOptions.default)({
187
+ ...this.#initialOptions,
188
+ featureFlags
189
+ });
190
+ this.#resolvedOptions = resolvedOptions;
191
+ let rustAtlaspack;
192
+ if (resolvedOptions.featureFlags.atlaspackV3) {
193
+ // eslint-disable-next-line no-unused-vars
194
+ let {
195
+ entries,
196
+ inputFS,
197
+ outputFS,
198
+ ...options
199
+ } = this.#initialOptions;
200
+ if (!(resolvedOptions.cache instanceof _cache().LMDBLiteCache)) {
201
+ throw new Error('Atlaspack v3 must be run with lmdb lite cache');
202
+ }
203
+ const lmdb = resolvedOptions.cache.getNativeRef();
204
+
205
+ // $FlowFixMe
206
+ const version = require('../package.json').version;
207
+ await lmdb.put('current_session_version', Buffer.from(version));
208
+ rustAtlaspack = await _atlaspackV.AtlaspackV3.create({
209
+ ...options,
210
+ corePath: _path().default.join(__dirname, '..'),
211
+ threads: process.env.NODE_ENV === 'test' ? 2 : undefined,
212
+ entries: Array.isArray(entries) ? entries : entries == null ? undefined : [entries],
213
+ env: resolvedOptions.env,
214
+ fs: inputFS && new _atlaspackV.FileSystemV3(inputFS),
215
+ // $FlowFixMe ProjectPath is a string
216
+ defaultTargetOptions: resolvedOptions.defaultTargetOptions,
217
+ lmdb
218
+ });
219
+ }
220
+ this.rustAtlaspack = rustAtlaspack;
221
+ let {
222
+ config
223
+ } = await (0, _AtlaspackConfigRequest.loadAtlaspackConfig)(resolvedOptions);
224
+ this.#config = new _AtlaspackConfig.AtlaspackConfig(config, resolvedOptions);
225
+ if (this.#initialOptions.workerFarm) {
226
+ if (this.#initialOptions.workerFarm.ending) {
227
+ throw new Error('Supplied WorkerFarm is ending');
228
+ }
229
+ this.#farm = this.#initialOptions.workerFarm;
230
+ } else {
231
+ this.#farm = createWorkerFarm({
232
+ shouldPatchConsole: resolvedOptions.shouldPatchConsole,
233
+ shouldTrace: resolvedOptions.shouldTrace
234
+ });
235
+ }
236
+ await resolvedOptions.cache.ensure();
237
+ let {
238
+ dispose: disposeOptions,
239
+ ref: optionsRef
240
+ } = await this.#farm.createSharedReference(resolvedOptions, false);
241
+ this.#optionsRef = optionsRef;
242
+ if (this.#initialOptions.workerFarm) {
243
+ // If we don't own the farm, dispose of only these references when
244
+ // Atlaspack ends.
245
+ this.#disposable.add(disposeOptions);
246
+ } else {
247
+ // Otherwise, when shutting down, end the entire farm we created.
248
+ this.#disposable.add(() => this.#farm.end());
249
+ }
250
+ this.#watchEvents = new (_events().ValueEmitter)();
251
+ this.#disposable.add(() => this.#watchEvents.dispose());
252
+ this.#reporterRunner = new _ReporterRunner.default({
253
+ options: resolvedOptions,
254
+ reporters: await this.#config.getReporters(),
255
+ workerFarm: this.#farm
256
+ });
257
+ this.#disposable.add(this.#reporterRunner);
258
+ _logger().default.verbose({
259
+ origin: '@atlaspack/core',
260
+ message: 'Intializing request tracker...'
261
+ });
262
+ this.#requestTracker = await _RequestTracker.default.init({
263
+ farm: this.#farm,
264
+ options: resolvedOptions,
265
+ rustAtlaspack
266
+ });
267
+ this.#initialized = true;
268
+ }
269
+ async run() {
270
+ let startTime = Date.now();
271
+ if (!this.#initialized) {
272
+ await this._init();
273
+ }
274
+ let result = await this._build({
275
+ startTime
276
+ });
277
+ await this.#requestTracker.writeToCache();
278
+ await this._end();
279
+ if (result.type === 'buildFailure') {
280
+ throw new BuildError(result.diagnostics);
281
+ }
282
+ return result;
283
+ }
284
+ async _end() {
285
+ this.#initialized = false;
286
+ await this.#disposable.dispose();
287
+ }
288
+ async writeRequestTrackerToCache() {
289
+ if (this.#watchQueue.getNumWaiting() === 0) {
290
+ // If there's no queued events, we are safe to write the request graph to disk
291
+ const abortController = new AbortController();
292
+ const unsubscribe = this.#watchQueue.subscribeToAdd(() => {
293
+ abortController.abort();
294
+ });
295
+ try {
296
+ await this.#requestTracker.writeToCache(abortController.signal);
297
+ } catch (err) {
298
+ if (!abortController.signal.aborted) {
299
+ // We expect abort errors if we interrupt the cache write
300
+ throw err;
301
+ }
302
+ }
303
+ unsubscribe();
304
+ }
305
+ }
306
+ async _startNextBuild() {
307
+ this.#watchAbortController = new AbortController();
308
+ await this.clearBuildCaches();
309
+ try {
310
+ let buildEvent = await this._build({
311
+ signal: this.#watchAbortController.signal
312
+ });
313
+ this.#watchEvents.emit({
314
+ buildEvent
315
+ });
316
+ return buildEvent;
317
+ } catch (err) {
318
+ // Ignore BuildAbortErrors and only emit critical errors.
319
+ if (!(err instanceof _utils.BuildAbortError)) {
320
+ throw err;
321
+ }
322
+ } finally {
323
+ // If the build passes or fails, we want to cache the request graph
324
+ await this.writeRequestTrackerToCache();
325
+ }
326
+ }
327
+ async watch(cb) {
328
+ if (!this.#initialized) {
329
+ await this._init();
330
+ }
331
+ let watchEventsDisposable;
332
+ if (cb) {
333
+ watchEventsDisposable = this.#watchEvents.addListener(({
334
+ error,
335
+ buildEvent
336
+ }) => cb(error, buildEvent));
337
+ }
338
+ if (this.#watcherCount === 0) {
339
+ this.#watcherSubscription = await this._getWatcherSubscription();
340
+ await this.#reporterRunner.report({
341
+ type: 'watchStart'
342
+ });
343
+
344
+ // Kick off a first build, but don't await its results. Its results will
345
+ // be provided to the callback.
346
+ this.#watchQueue.add(() => this._startNextBuild());
347
+ this.#watchQueue.run();
348
+ }
349
+ this.#watcherCount++;
350
+ let unsubscribePromise;
351
+ const unsubscribe = async () => {
352
+ if (watchEventsDisposable) {
353
+ watchEventsDisposable.dispose();
354
+ }
355
+ this.#watcherCount--;
356
+ if (this.#watcherCount === 0) {
357
+ await (0, _nullthrows().default)(this.#watcherSubscription).unsubscribe();
358
+ this.#watcherSubscription = null;
359
+ await this.#reporterRunner.report({
360
+ type: 'watchEnd'
361
+ });
362
+ this.#watchAbortController.abort();
363
+ await this.#watchQueue.run();
364
+ await this._end();
365
+ }
366
+ };
367
+ return {
368
+ unsubscribe() {
369
+ if (unsubscribePromise == null) {
370
+ unsubscribePromise = unsubscribe();
371
+ }
372
+ return unsubscribePromise;
373
+ }
374
+ };
375
+ }
376
+ async _build({
377
+ signal,
378
+ startTime = Date.now()
379
+ } = {
380
+ /*::...null*/
381
+ }) {
382
+ this.#requestTracker.setSignal(signal);
383
+ let options = (0, _nullthrows().default)(this.#resolvedOptions);
384
+ try {
385
+ if (options.shouldProfile) {
386
+ await this.startProfiling();
387
+ }
388
+ if (options.shouldTrace) {
389
+ _profiler().tracer.enable();
390
+ }
391
+ await this.#reporterRunner.report({
392
+ type: 'buildStart'
393
+ });
394
+ this.#requestTracker.graph.invalidateOnBuildNodes();
395
+ let request = (0, _AtlaspackBuildRequest.default)({
396
+ optionsRef: this.#optionsRef,
397
+ requestedAssetIds: this.#requestedAssetIds,
398
+ signal
399
+ });
400
+ let {
401
+ bundleGraph,
402
+ bundleInfo,
403
+ changedAssets,
404
+ assetRequests
405
+ } = await this.#requestTracker.runRequest(request, {
406
+ force: true
407
+ });
408
+ this.#requestedAssetIds.clear();
409
+ await (0, _dumpGraphToGraphViz.default)(
410
+ // $FlowFixMe
411
+ this.#requestTracker.graph, 'RequestGraph', _RequestTracker.requestGraphEdgeTypes);
412
+ let event = {
413
+ type: 'buildSuccess',
414
+ changedAssets: new Map(Array.from(changedAssets).map(([id, asset]) => [id, (0, _Asset.assetFromValue)(asset, options)])),
415
+ bundleGraph: new _BundleGraph.default(bundleGraph, (bundle, bundleGraph, options) => _Bundle.PackagedBundle.getWithInfo(bundle, bundleGraph, options, bundleInfo.get(bundle.id)), options),
416
+ buildTime: Date.now() - startTime,
417
+ requestBundle: async bundle => {
418
+ let bundleNode = bundleGraph._graph.getNodeByContentKey(bundle.id);
419
+ (0, _assert().default)((bundleNode === null || bundleNode === void 0 ? void 0 : bundleNode.type) === 'bundle', 'Bundle does not exist');
420
+ if (!bundleNode.value.isPlaceholder) {
421
+ // Nothing to do.
422
+ return {
423
+ type: 'buildSuccess',
424
+ changedAssets: new Map(),
425
+ bundleGraph: event.bundleGraph,
426
+ buildTime: 0,
427
+ requestBundle: event.requestBundle,
428
+ unstable_requestStats: {}
429
+ };
430
+ }
431
+ for (let assetId of bundleNode.value.entryAssetIds) {
432
+ this.#requestedAssetIds.add(assetId);
433
+ }
434
+ if (this.#watchQueue.getNumWaiting() === 0) {
435
+ if (this.#watchAbortController) {
436
+ this.#watchAbortController.abort();
437
+ }
438
+ this.#watchQueue.add(() => this._startNextBuild());
439
+ }
440
+ let results = await this.#watchQueue.run();
441
+ let result = results.filter(Boolean).pop();
442
+ if (result.type === 'buildFailure') {
443
+ throw new BuildError(result.diagnostics);
444
+ }
445
+ return result;
446
+ },
447
+ unstable_requestStats: this.#requestTracker.flushStats()
448
+ };
449
+ await this.#reporterRunner.report(event);
450
+ await this.#requestTracker.runRequest((0, _ValidationRequest.default)({
451
+ optionsRef: this.#optionsRef,
452
+ assetRequests
453
+ }), {
454
+ force: assetRequests.length > 0
455
+ });
456
+ if (this.#reporterRunner.errors.length) {
457
+ throw this.#reporterRunner.errors;
458
+ }
459
+ return event;
460
+ } catch (e) {
461
+ if (e instanceof _utils.BuildAbortError) {
462
+ throw e;
463
+ }
464
+ let diagnostic = (0, _diagnostic().anyToDiagnostic)(e);
465
+ let event = {
466
+ type: 'buildFailure',
467
+ diagnostics: Array.isArray(diagnostic) ? diagnostic : [diagnostic],
468
+ unstable_requestStats: this.#requestTracker.flushStats()
469
+ };
470
+ await this.#reporterRunner.report(event);
471
+ return event;
472
+ } finally {
473
+ if (this.isProfiling) {
474
+ await this.stopProfiling();
475
+ }
476
+ await this.clearBuildCaches();
477
+ }
478
+ }
479
+ async _getWatcherSubscription() {
480
+ (0, _assert().default)(this.#watcherSubscription == null);
481
+ let resolvedOptions = (0, _nullthrows().default)(this.#resolvedOptions);
482
+ let opts = (0, _RequestTracker.getWatcherOptions)(resolvedOptions);
483
+ let sub = await resolvedOptions.inputFS.watch(resolvedOptions.watchDir, async (err, events) => {
484
+ var _events$, _events$2;
485
+ if (err) {
486
+ _logger().default.warn({
487
+ message: `File watch event error occured`,
488
+ meta: {
489
+ err,
490
+ trackableEvent: 'watcher_error'
491
+ }
492
+ });
493
+ this.#watchEvents.emit({
494
+ error: err
495
+ });
496
+ return;
497
+ }
498
+ _logger().default.verbose({
499
+ message: `File watch event emitted with ${events.length} events. Sample event: [${(_events$ = events[0]) === null || _events$ === void 0 ? void 0 : _events$.type}] ${(_events$2 = events[0]) === null || _events$2 === void 0 ? void 0 : _events$2.path}`
500
+ });
501
+ let nativeInvalid = false;
502
+ if (this.rustAtlaspack) {
503
+ nativeInvalid = await this.rustAtlaspack.respondToFsEvents(events);
504
+ }
505
+ let isInvalid = await this.#requestTracker.respondToFSEvents(events, Number.POSITIVE_INFINITY);
506
+ if ((nativeInvalid || isInvalid) && this.#watchQueue.getNumWaiting() === 0) {
507
+ if (this.#watchAbortController) {
508
+ this.#watchAbortController.abort();
509
+ }
510
+ this.#watchQueue.add(() => this._startNextBuild());
511
+ this.#watchQueue.run();
512
+ }
513
+ }, opts);
514
+ return {
515
+ unsubscribe: () => sub.unsubscribe()
516
+ };
517
+ }
518
+
519
+ // This is mainly for integration tests and it not public api!
520
+ _getResolvedAtlaspackOptions() {
521
+ return (0, _nullthrows().default)(this.#resolvedOptions, 'Resolved options is null, please let atlaspack initialize before accessing this.');
522
+ }
523
+ async startProfiling() {
524
+ if (this.isProfiling) {
525
+ throw new Error('Atlaspack is already profiling');
526
+ }
527
+ _logger().default.info({
528
+ origin: '@atlaspack/core',
529
+ message: 'Starting profiling...'
530
+ });
531
+ this.isProfiling = true;
532
+ await this.#farm.startProfile();
533
+ }
534
+ stopProfiling() {
535
+ if (!this.isProfiling) {
536
+ throw new Error('Atlaspack is not profiling');
537
+ }
538
+ _logger().default.info({
539
+ origin: '@atlaspack/core',
540
+ message: 'Stopping profiling...'
541
+ });
542
+ this.isProfiling = false;
543
+ return this.#farm.endProfile();
544
+ }
545
+ takeHeapSnapshot() {
546
+ _logger().default.info({
547
+ origin: '@atlaspack/core',
548
+ message: 'Taking heap snapshot...'
549
+ });
550
+ return this.#farm.takeHeapSnapshot();
551
+ }
552
+
553
+ /**
554
+ * Must be called between builds otherwise there is global state that will
555
+ * break things unexpectedly.
556
+ */
557
+ async clearBuildCaches() {
558
+ var _this$farm;
559
+ await ((_this$farm = this.#farm) === null || _this$farm === void 0 ? void 0 : _this$farm.callAllWorkers('clearWorkerBuildCaches', []));
560
+ }
561
+ async unstable_invalidate() {
562
+ await this._init();
563
+ }
564
+
565
+ /**
566
+ * Build the asset graph
567
+ */
568
+ async unstable_buildAssetGraph(writeToCache = true) {
569
+ await this._init();
570
+ const origin = '@atlaspack/core';
571
+ const input = {
572
+ optionsRef: this.#optionsRef,
573
+ name: 'Main',
574
+ entries: this.#config.options.entries,
575
+ shouldBuildLazily: false,
576
+ lazyIncludes: [],
577
+ lazyExcludes: [],
578
+ requestedAssetIds: this.#requestedAssetIds
579
+ };
580
+ const start = Date.now();
581
+ const result = await this.#requestTracker.runRequest(this.rustAtlaspack != null ? (0, _AssetGraphRequestRust.createAssetGraphRequestRust)(this.rustAtlaspack)(input) : (0, _AssetGraphRequest.default)(input), {
582
+ force: true
583
+ });
584
+ const duration = Date.now() - start;
585
+ _logger().default.info({
586
+ message: `Done building asset graph in ${duration / 1000}s!`,
587
+ origin
588
+ });
589
+ if (writeToCache) {
590
+ _logger().default.info({
591
+ message: 'Write request tracker to cache',
592
+ origin
593
+ });
594
+ await this.writeRequestTrackerToCache();
595
+ _logger().default.info({
596
+ message: 'Done writing request tracker to cache',
597
+ origin
598
+ });
599
+ }
600
+ return result;
601
+ }
602
+ async unstable_transform(options) {
603
+ var _options$env;
604
+ if (!this.#initialized) {
605
+ await this._init();
606
+ }
607
+ let projectRoot = (0, _nullthrows().default)(this.#resolvedOptions).projectRoot;
608
+ let request = (0, _AssetRequest.default)({
609
+ ...options,
610
+ filePath: (0, _projectPath.toProjectPath)(projectRoot, options.filePath),
611
+ optionsRef: this.#optionsRef,
612
+ env: (0, _Environment.createEnvironment)({
613
+ ...options.env,
614
+ loc: ((_options$env = options.env) === null || _options$env === void 0 ? void 0 : _options$env.loc) != null ? {
615
+ ...options.env.loc,
616
+ filePath: (0, _projectPath.toProjectPath)(projectRoot, options.env.loc.filePath)
617
+ } : undefined
618
+ })
619
+ });
620
+ let res = await this.#requestTracker.runRequest(request, {
621
+ force: true
622
+ });
623
+ return res.map(asset => (0, _Asset.assetFromValue)(asset, (0, _nullthrows().default)(this.#resolvedOptions)));
624
+ }
625
+ async unstable_resolve(request) {
626
+ var _request$env;
627
+ if (!this.#initialized) {
628
+ await this._init();
629
+ }
630
+ let projectRoot = (0, _nullthrows().default)(this.#resolvedOptions).projectRoot;
631
+ if (request.resolveFrom == null && _path().default.isAbsolute(request.specifier)) {
632
+ request.specifier = (0, _projectPath.fromProjectPathRelative)((0, _projectPath.toProjectPath)(projectRoot, request.specifier));
633
+ }
634
+ let dependency = (0, _Dependency.createDependency)(projectRoot, {
635
+ ...request,
636
+ env: (0, _Environment.createEnvironment)({
637
+ ...request.env,
638
+ loc: ((_request$env = request.env) === null || _request$env === void 0 ? void 0 : _request$env.loc) != null ? {
639
+ ...request.env.loc,
640
+ filePath: (0, _projectPath.toProjectPath)(projectRoot, request.env.loc.filePath)
641
+ } : undefined
642
+ })
643
+ });
644
+ let req = (0, _PathRequest.default)({
645
+ dependency,
646
+ name: request.specifier
647
+ });
648
+ let res = await this.#requestTracker.runRequest(req, {
649
+ force: true
650
+ });
651
+ if (!res) {
652
+ return null;
653
+ }
654
+ return {
655
+ filePath: (0, _projectPath.fromProjectPath)(projectRoot, res.filePath),
656
+ code: res.code,
657
+ query: res.query,
658
+ sideEffects: res.sideEffects
659
+ };
660
+ }
661
+ }
662
+ exports.default = Atlaspack;
663
+ class BuildError extends _diagnostic().default {
664
+ constructor(diagnostic) {
665
+ super({
666
+ diagnostic
667
+ });
668
+ this.name = 'BuildError';
669
+ }
670
+ }
671
+ exports.BuildError = BuildError;
672
+ function createWorkerFarm(options = {}) {
673
+ return new (_workers().default)({
674
+ ...options,
675
+ workerPath: WORKER_PATH
676
+ });
677
+ }