@atlaspack/query 2.12.1-canary.3354

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.
package/lib/cli.js ADDED
@@ -0,0 +1,850 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.run = run;
7
+ function _path() {
8
+ const data = _interopRequireDefault(require("path"));
9
+ _path = function () {
10
+ return data;
11
+ };
12
+ return data;
13
+ }
14
+ function _fs() {
15
+ const data = _interopRequireDefault(require("fs"));
16
+ _fs = function () {
17
+ return data;
18
+ };
19
+ return data;
20
+ }
21
+ function _repl() {
22
+ const data = _interopRequireDefault(require("repl"));
23
+ _repl = function () {
24
+ return data;
25
+ };
26
+ return data;
27
+ }
28
+ function _os() {
29
+ const data = _interopRequireDefault(require("os"));
30
+ _os = function () {
31
+ return data;
32
+ };
33
+ return data;
34
+ }
35
+ function _nullthrows() {
36
+ const data = _interopRequireDefault(require("nullthrows"));
37
+ _nullthrows = function () {
38
+ return data;
39
+ };
40
+ return data;
41
+ }
42
+ function _assert() {
43
+ const data = _interopRequireDefault(require("assert"));
44
+ _assert = function () {
45
+ return data;
46
+ };
47
+ return data;
48
+ }
49
+ function _v() {
50
+ const data = require("v8");
51
+ _v = function () {
52
+ return data;
53
+ };
54
+ return data;
55
+ }
56
+ function _table() {
57
+ const data = require("table");
58
+ _table = function () {
59
+ return data;
60
+ };
61
+ return data;
62
+ }
63
+ var _index = require("./index.js");
64
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
65
+ /* eslint-disable no-console, monorepo/no-internal-import */
66
+ // $FlowFixMe
67
+ const {
68
+ BundleGraph: {
69
+ bundleGraphEdgeTypes: bundleGraphEdgeTypes
70
+ },
71
+ Priority,
72
+ fromProjectPathRelative
73
+ } = require('./deep-imports.js');
74
+ async function run(input) {
75
+ let args = input;
76
+ let cacheDir = _path().default.join(process.cwd(), '.atlaspack-cache');
77
+ if (args[0] === '--cache') {
78
+ cacheDir = _path().default.resolve(process.cwd(), args[1]);
79
+ args = args.slice(2);
80
+ }
81
+ let initialCmd = args[0];
82
+ try {
83
+ _fs().default.accessSync(cacheDir);
84
+ } catch (e) {
85
+ console.error("Can't find cache dir", cacheDir);
86
+ process.exit(1);
87
+ }
88
+ console.log('Loading graphs...');
89
+ let {
90
+ assetGraph,
91
+ bundleGraph,
92
+ bundleInfo,
93
+ requestTracker,
94
+ cacheInfo
95
+ } = await (0, _index.loadGraphs)(cacheDir);
96
+ function hasRequestTracker() {
97
+ if (requestTracker == null) {
98
+ console.error('Request Graph could not be found');
99
+ return false;
100
+ }
101
+ return true;
102
+ }
103
+ function hasBundleGraph() {
104
+ if (bundleGraph == null) {
105
+ console.error('Bundle Graph could not be found');
106
+ return false;
107
+ }
108
+ return true;
109
+ }
110
+ function hasAssetGraph() {
111
+ if (assetGraph == null) {
112
+ console.error('Asset Graph could not be found');
113
+ return false;
114
+ }
115
+ return true;
116
+ }
117
+ function hasBundleInfo() {
118
+ if (bundleInfo == null) {
119
+ console.error('Bundle Info could not be found');
120
+ return false;
121
+ }
122
+ return true;
123
+ }
124
+
125
+ // -------------------------------------------------------
126
+
127
+ function getBundleFilePath(id) {
128
+ var _bundleInfo$get;
129
+ if (!hasBundleInfo()) {
130
+ return;
131
+ }
132
+ (0, _assert().default)(bundleInfo != null);
133
+ return fromProjectPathRelative((0, _nullthrows().default)((_bundleInfo$get = bundleInfo.get(id)) === null || _bundleInfo$get === void 0 ? void 0 : _bundleInfo$get.filePath));
134
+ }
135
+ function parseAssetLocator(v) {
136
+ let id = null;
137
+ if (v.length === 16) {
138
+ id = v;
139
+ } else {
140
+ if (!hasBundleGraph()) {
141
+ return;
142
+ }
143
+ (0, _assert().default)(bundleGraph != null);
144
+ for (let [assetId, publicId] of bundleGraph._publicIdByAssetId) {
145
+ if (publicId === v) {
146
+ id = assetId;
147
+ break;
148
+ }
149
+ }
150
+ }
151
+ if (id == null && v.length > 0) {
152
+ if (!hasAssetGraph()) {
153
+ return;
154
+ }
155
+ (0, _assert().default)(assetGraph != null);
156
+ let assetRegex = new RegExp(v);
157
+ for (let node of assetGraph.nodes.values()) {
158
+ if ((node === null || node === void 0 ? void 0 : node.type) === 'asset' && assetRegex.test(fromProjectPathRelative(node.value.filePath))) {
159
+ id = node.id;
160
+ break;
161
+ }
162
+ }
163
+ }
164
+ return id;
165
+ }
166
+ function parseBundleLocator(v) {
167
+ if (!hasBundleGraph()) {
168
+ return;
169
+ }
170
+ (0, _assert().default)(bundleGraph != null);
171
+ let bundleRegex = new RegExp(v);
172
+ for (let b of bundleGraph.getBundles()) {
173
+ let bundleFilePath = getBundleFilePath(b.id);
174
+ if (bundleFilePath !== undefined && bundleRegex.test(bundleFilePath) || b.id === v) {
175
+ return b.id;
176
+ }
177
+ }
178
+ }
179
+ function getAsset(v) {
180
+ let id = parseAssetLocator(v);
181
+ if (id == null) {
182
+ console.log(null);
183
+ } else {
184
+ try {
185
+ if (!hasBundleGraph()) {
186
+ return;
187
+ }
188
+ (0, _assert().default)(bundleGraph != null);
189
+ let asset = bundleGraph.getAssetById(id);
190
+ console.log('Public id', bundleGraph.getAssetPublicId(asset));
191
+ console.log(asset);
192
+ } catch (e) {
193
+ if (!hasAssetGraph()) {
194
+ return;
195
+ }
196
+ (0, _assert().default)(assetGraph != null);
197
+ let node = (0, _nullthrows().default)(assetGraph.getNodeByContentKey(id));
198
+ (0, _assert().default)(node.type === 'asset');
199
+ console.log(node.value);
200
+ }
201
+ }
202
+ }
203
+ function _findAssetNode(v) {
204
+ if (!hasAssetGraph()) {
205
+ return;
206
+ }
207
+ (0, _assert().default)(assetGraph != null);
208
+ let assetRegex = new RegExp(v);
209
+ for (let node of assetGraph.nodes.values()) {
210
+ if ((node === null || node === void 0 ? void 0 : node.type) === 'asset' && assetRegex.test(fromProjectPathRelative(node.value.filePath))) {
211
+ return node;
212
+ }
213
+ }
214
+ }
215
+ function findAsset(v) {
216
+ let node = _findAssetNode(v);
217
+ if (node) {
218
+ try {
219
+ if (!hasBundleGraph()) {
220
+ return;
221
+ }
222
+ (0, _assert().default)(bundleGraph != null);
223
+ console.log(`${bundleGraph.getAssetPublicId(bundleGraph.getAssetById(node.id))} ${fromProjectPathRelative(node.value.filePath)}`);
224
+ } catch (e) {
225
+ console.log(fromProjectPathRelative(node.value.filePath));
226
+ }
227
+ }
228
+ }
229
+ function findAssetWithSymbol(local) {
230
+ if (!hasBundleGraph() || !hasAssetGraph()) {
231
+ return;
232
+ }
233
+ (0, _assert().default)(bundleGraph != null);
234
+ (0, _assert().default)(assetGraph != null);
235
+ let [, assetId, binding, ref] = (0, _nullthrows().default)(local.match(/^\$([^$]+)\$([^$]+)\$(.*)$/), `symbol ${local} could not be resolved`);
236
+ let asset;
237
+ // Search against the id used by the JSTransformer and ScopeHoistingPackager,
238
+ // not the final asset id, as it may have changed with further transformation.
239
+ for (let node of assetGraph.nodes.values()) {
240
+ if ((node === null || node === void 0 ? void 0 : node.type) === 'asset' && node.value.meta.id === assetId) {
241
+ asset = node;
242
+ break;
243
+ }
244
+ }
245
+
246
+ // If the asset couldn't be found by searching for the id,
247
+ // search for the local name in asset used symbols.
248
+ if (asset == null) {
249
+ outer: for (let node of assetGraph.nodes.values()) {
250
+ if ((node === null || node === void 0 ? void 0 : node.type) === 'asset' && node.value.symbols) {
251
+ for (let symbol of node.value.symbols.values()) {
252
+ if (symbol.local === local) {
253
+ asset = node;
254
+ break outer;
255
+ }
256
+ }
257
+ }
258
+ }
259
+ }
260
+ (0, _assert().default)(asset, `An asset for ${assetId} could not be found`);
261
+ (0, _assert().default)(asset.type === 'asset', `Expected ${assetId} to be an asset, but found a ${asset.type}`);
262
+ try {
263
+ console.log(`${bundleGraph.getAssetPublicId(bundleGraph.getAssetById(asset.id))} ${fromProjectPathRelative(asset.value.filePath)}`);
264
+ } catch (e) {
265
+ console.log(fromProjectPathRelative(asset.value.filePath));
266
+ }
267
+ if (binding === 'export' && asset.value.symbols) {
268
+ for (let [symbolName, symbol] of asset.value.symbols) {
269
+ if (symbol.local === local) {
270
+ if (symbol.loc) {
271
+ let locPath = symbol.loc.filePath;
272
+ let locAsset = _findAssetNode(String(locPath));
273
+ if (locAsset != null) {
274
+ try {
275
+ console.log(`${bundleGraph.getAssetPublicId(bundleGraph.getAssetById(locAsset.id))} ${fromProjectPathRelative(locAsset.value.filePath)}`);
276
+ } catch (e) {
277
+ console.log(`imported as ${symbolName} from ${fromProjectPathRelative(locAsset.value.filePath)}`);
278
+ }
279
+ } else {
280
+ console.log(`imported as ${symbolName} from ${fromProjectPathRelative(locPath)}`);
281
+ }
282
+ } else {
283
+ console.log(`imported as ${symbolName}`);
284
+ }
285
+ }
286
+ }
287
+ } else if (ref) {
288
+ console.log(`possibly defined as ${ref}`);
289
+ }
290
+ }
291
+ function getNodeAssetGraph(v) {
292
+ if (!hasAssetGraph()) {
293
+ return;
294
+ }
295
+ (0, _assert().default)(assetGraph != null);
296
+ console.log(assetGraph.getNodeByContentKey(v));
297
+ }
298
+ function getNodeBundleGraph(v) {
299
+ if (!hasBundleGraph()) {
300
+ return;
301
+ }
302
+ (0, _assert().default)(bundleGraph != null);
303
+ console.log(bundleGraph._graph.getNodeByContentKey(v));
304
+ }
305
+ class Paths {
306
+ children = [];
307
+ constructor(value, label = '-', suffix = '') {
308
+ this.value = value;
309
+ this.label = label;
310
+ this.suffix = suffix;
311
+ }
312
+ add(v, label, suffix) {
313
+ let next = new Paths(v, label, suffix);
314
+ this.children.push(next);
315
+ return next;
316
+ }
317
+ print(format, prefix = '') {
318
+ console.log(`${prefix}${this.label} ${format(this.value)} ${this.suffix}`);
319
+ for (let i = 0; i < this.children.length; i++) {
320
+ this.children[i].print(format, prefix + ' ');
321
+ }
322
+ }
323
+ }
324
+ function _findEntries(graph, v) {
325
+ let asset = (0, _nullthrows().default)(parseAssetLocator(v), 'Asset not found');
326
+ let paths = new Paths(graph.getNodeIdByContentKey(asset), ' ');
327
+ let cb = (id, ctx, revisiting) => {
328
+ let {
329
+ paths,
330
+ lazyOutgoing
331
+ } = ctx;
332
+ let node = (0, _nullthrows().default)(graph.getNode(id));
333
+ if (node.id === asset) return ctx;
334
+ if (node.type === 'asset') {
335
+ paths = paths.add(id, lazyOutgoing ? '<' : undefined, revisiting ? '(revisiting)' : undefined);
336
+ lazyOutgoing = false;
337
+ } else if (node.type === 'dependency') {
338
+ if (node.value.priority === Priority.lazy) {
339
+ lazyOutgoing = true;
340
+ }
341
+ }
342
+ return {
343
+ paths,
344
+ lazyOutgoing
345
+ };
346
+ };
347
+
348
+ // like graph.dfs, but revisiting nodes and skipping its children
349
+ let seen = new Set();
350
+ function walk(id, ctx) {
351
+ let revisiting = seen.has(id);
352
+ let newCtx = cb(id, ctx, revisiting);
353
+ if (revisiting) return;
354
+ seen.add(id);
355
+ for (let parent of graph.getNodeIdsConnectedTo(id)) {
356
+ walk(parent, newCtx);
357
+ }
358
+ }
359
+ walk(graph.getNodeIdByContentKey(asset), {
360
+ paths,
361
+ lazyOutgoing: false
362
+ });
363
+ paths.print(id => {
364
+ let node = (0, _nullthrows().default)(graph.getNode(id));
365
+ (0, _assert().default)(node.type === 'asset');
366
+ return fromProjectPathRelative(node.value.filePath);
367
+ });
368
+ }
369
+ function findEntriesAssetGraph(v) {
370
+ if (!hasAssetGraph()) {
371
+ return;
372
+ }
373
+ (0, _assert().default)(assetGraph != null);
374
+ _findEntries(assetGraph, v);
375
+ }
376
+ function findEntriesBundleGraph(v) {
377
+ if (!hasBundleGraph()) {
378
+ return;
379
+ }
380
+ (0, _assert().default)(bundleGraph != null);
381
+ _findEntries(bundleGraph._graph, v);
382
+ }
383
+ function findEntries(v) {
384
+ findEntriesBundleGraph(v);
385
+ }
386
+ function getBundlesWithAsset(v) {
387
+ if (!hasBundleGraph()) {
388
+ return;
389
+ }
390
+ (0, _assert().default)(bundleGraph != null);
391
+ let asset = (0, _nullthrows().default)(parseAssetLocator(v), 'Asset not found');
392
+ for (let b of bundleGraph.getBundlesWithAsset(bundleGraph.getAssetById(asset))) {
393
+ let bundleFilePath = getBundleFilePath(b.id);
394
+ if (bundleFilePath !== undefined) {
395
+ console.log(`${b.id} ${bundleFilePath} ${b.mainEntryId != null ? `(main: ${b.mainEntryId})` : ''}`);
396
+ }
397
+ }
398
+ }
399
+ function getBundlesWithDependency(v) {
400
+ if (!hasBundleGraph()) {
401
+ return;
402
+ }
403
+ (0, _assert().default)(bundleGraph != null);
404
+ let node = (0, _nullthrows().default)(bundleGraph._graph.getNodeByContentKey(v));
405
+ (0, _assert().default)(node.type === 'dependency');
406
+ for (let b of bundleGraph.getBundlesWithDependency(node.value)) {
407
+ let bundleFilePath = getBundleFilePath(b.id);
408
+ if (bundleFilePath !== undefined) {
409
+ console.log(`${b.id} ${bundleFilePath} ${b.mainEntryId != null ? `(main: ${b.mainEntryId})` : ''}`);
410
+ }
411
+ }
412
+ }
413
+
414
+ // eslint-disable-next-line no-unused-vars
415
+ function getBundles(_) {
416
+ if (!hasBundleGraph()) {
417
+ return;
418
+ }
419
+ (0, _assert().default)(bundleGraph != null);
420
+ for (let b of bundleGraph.getBundles()) {
421
+ let bundleFilePath = getBundleFilePath(b.id);
422
+ if (bundleFilePath !== undefined) {
423
+ console.log(`${b.id} ${bundleFilePath} ${b.mainEntryId != null ? `(main: ${b.mainEntryId})` : ''}`);
424
+ }
425
+ }
426
+ }
427
+ function getReferencingBundles(v) {
428
+ if (!hasBundleGraph()) {
429
+ return;
430
+ }
431
+ (0, _assert().default)(bundleGraph != null);
432
+ let bundleId = (0, _nullthrows().default)(parseBundleLocator(v), 'Bundle not found');
433
+ let bundleNodeId = bundleGraph._graph.getNodeIdByContentKey(bundleId);
434
+ let bundleNode = (0, _nullthrows().default)(bundleGraph._graph.getNode(bundleNodeId), 'Bundle not found');
435
+ (0, _assert().default)(bundleNode.type === 'bundle', 'Not a bundle');
436
+ for (let b of bundleGraph.getReferencingBundles(bundleNode.value)) {
437
+ let bundleFilePath = getBundleFilePath(b.id);
438
+ if (bundleFilePath !== undefined) {
439
+ console.log(`${b.id} ${bundleFilePath} ${b.mainEntryId != null ? `(main: ${b.mainEntryId})` : ''}`);
440
+ }
441
+ }
442
+ }
443
+ function getIncomingDependenciesAssetGraph(v) {
444
+ if (!hasAssetGraph()) {
445
+ return;
446
+ }
447
+ (0, _assert().default)(assetGraph != null);
448
+ let asset = (0, _nullthrows().default)(parseAssetLocator(v), 'Asset not found');
449
+ let node = (0, _nullthrows().default)(assetGraph.getNodeByContentKey(asset));
450
+ (0, _assert().default)(node.type === 'asset');
451
+ console.log(assetGraph.getIncomingDependencies(node.value));
452
+ }
453
+ function getIncomingDependenciesBundleGraph(v) {
454
+ if (!hasBundleGraph()) {
455
+ return;
456
+ }
457
+ (0, _assert().default)(bundleGraph != null);
458
+ let asset = (0, _nullthrows().default)(parseAssetLocator(v), 'Asset not found');
459
+ let value = (0, _nullthrows().default)(bundleGraph.getAssetById(asset));
460
+ console.log(bundleGraph.getIncomingDependencies(value));
461
+ }
462
+ function getIncomingDependencies(v) {
463
+ getIncomingDependenciesBundleGraph(v);
464
+ }
465
+ function getResolvedAsset(v) {
466
+ if (!hasBundleGraph()) {
467
+ return;
468
+ }
469
+ (0, _assert().default)(bundleGraph != null);
470
+ let node = (0, _nullthrows().default)(bundleGraph._graph.getNodeByContentKey(v), 'Dependency not found');
471
+ (0, _assert().default)(node.type === 'dependency', 'Node is not a dependency, but a ' + node.type);
472
+ console.log(bundleGraph.getResolvedAsset(node.value));
473
+ }
474
+ function getAssetWithDependency(v) {
475
+ if (!hasBundleGraph()) {
476
+ return;
477
+ }
478
+ (0, _assert().default)(bundleGraph != null);
479
+ let node = (0, _nullthrows().default)(bundleGraph._graph.getNodeByContentKey(v), 'Dependency not found');
480
+ (0, _assert().default)(node.type === 'dependency', 'Node is not a dependency, but a ' + node.type);
481
+ console.log(bundleGraph.getAssetWithDependency(node.value));
482
+ }
483
+ function traverseAssets(v) {
484
+ if (!hasBundleGraph()) {
485
+ return;
486
+ }
487
+ (0, _assert().default)(bundleGraph != null);
488
+ let bundleId = (0, _nullthrows().default)(parseBundleLocator(v), 'Bundle not found');
489
+ let node = (0, _nullthrows().default)(bundleGraph._graph.getNodeByContentKey(bundleId), 'Bundle not found');
490
+ (0, _assert().default)(node.type === 'bundle', 'Node is not a bundle, but a ' + node.type);
491
+ bundleGraph.traverseAssets(node.value, asset => {
492
+ console.log(asset.id, asset.filePath);
493
+ });
494
+ }
495
+ function traverseBundle(v) {
496
+ if (!hasBundleGraph()) {
497
+ return;
498
+ }
499
+ (0, _assert().default)(bundleGraph != null);
500
+ let bundleId = (0, _nullthrows().default)(parseBundleLocator(v), 'Bundle not found');
501
+ let node = (0, _nullthrows().default)(bundleGraph._graph.getNodeByContentKey(bundleId), 'Bundle not found');
502
+ (0, _assert().default)(node.type === 'bundle', 'Node is not a bundle, but a ' + node.type);
503
+ bundleGraph.traverseBundle(node.value, node => {
504
+ if (node.type === 'asset') {
505
+ console.log(node.id, node.value.filePath);
506
+ } else {
507
+ console.log(node.id, node.value.sourcePath, '->', node.value.specifier, node.value.symbols ? `(${[...node.value.symbols.keys()].join(',')})` : '', node.excluded ? `- excluded` : '');
508
+ }
509
+ });
510
+ }
511
+ function getBundle(v) {
512
+ if (!hasBundleGraph()) {
513
+ return;
514
+ }
515
+ (0, _assert().default)(bundleGraph != null);
516
+ let bundleRegex = new RegExp(v);
517
+ for (let b of bundleGraph.getBundles()) {
518
+ let bundleFilePath = getBundleFilePath(b.id);
519
+ if (bundleFilePath !== undefined && bundleRegex.test(bundleFilePath) || b.id === v) {
520
+ console.log(getBundleFilePath(b.id), b);
521
+ }
522
+ }
523
+ }
524
+ function findBundleReason(bundle, asset) {
525
+ if (!hasBundleGraph()) {
526
+ return;
527
+ }
528
+ (0, _assert().default)(bundleGraph != null);
529
+ let bundleId = (0, _nullthrows().default)(parseBundleLocator(bundle), 'Bundle not found');
530
+ let bundleNodeId = bundleGraph._graph.getNodeIdByContentKey(bundleId);
531
+ let bundleNode = (0, _nullthrows().default)(bundleGraph._graph.getNode(bundleNodeId), 'Bundle not found');
532
+ (0, _assert().default)(bundleNode.type === 'bundle', 'Not a bundle');
533
+ let assetId = (0, _nullthrows().default)(parseAssetLocator(asset), 'Asset not found');
534
+ let assetNodeId = bundleGraph._graph.getNodeIdByContentKey(assetId);
535
+ let assetNode = (0, _nullthrows().default)(bundleGraph._graph.getNode(assetNodeId), 'Asset not found');
536
+ (0, _assert().default)(assetNode.type === 'asset', 'Not an asset');
537
+ (0, _assert().default)(bundleGraph._graph.hasEdge(bundleNodeId, assetNodeId, bundleGraphEdgeTypes.contains), 'Asset is not part of the bundle');
538
+ console.log('# Asset is main entry of bundle:', bundleNode.value.mainEntryId === assetId);
539
+ console.log('# Asset is an entry of bundle:', bundleNode.value.entryAssetIds.includes(assetId));
540
+ console.log('# Incoming dependencies contained in the bundle:');
541
+ for (let incoming of bundleGraph._graph.getNodeIdsConnectedTo(assetNodeId)) {
542
+ if (bundleGraph._graph.hasEdge(bundleNodeId, incoming, bundleGraphEdgeTypes.contains)) {
543
+ console.log(bundleGraph._graph.getNode(incoming));
544
+ }
545
+ }
546
+ console.log('# Incoming dependencies contained in referencing bundles (using this bundle as a shared bundle)');
547
+ let referencingBundles = bundleGraph.getReferencingBundles(bundleNode.value);
548
+ for (let incoming of bundleGraph._graph.getNodeIdsConnectedTo(assetNodeId)) {
549
+ if (referencingBundles.some(ref => bundleGraph._graph.hasEdge(bundleGraph._graph.getNodeIdByContentKey(ref.id), incoming, bundleGraphEdgeTypes.contains))) {
550
+ console.log(bundleGraph._graph.getNode(incoming));
551
+ }
552
+ }
553
+ }
554
+ function _getIncomingNodeOfType(bundleGraph, node, type) {
555
+ if (!hasBundleGraph()) {
556
+ return;
557
+ }
558
+ (0, _assert().default)(bundleGraph != null);
559
+ const bundleGraphNodeId = bundleGraph._graph.getNodeIdByContentKey(node.id);
560
+ return bundleGraph._graph.getNodeIdsConnectedTo(bundleGraphNodeId, -1).map(id => (0, _nullthrows().default)(bundleGraph._graph.getNode(id))).find(node => node.type == type);
561
+ }
562
+
563
+ // We find the priority of a Bundle or BundleGroup by looking at its incoming dependencies.
564
+ // If a Bundle does not have an incoming dependency, we look for an incoming BundleGroup and its dependency
565
+ // e.g. Dep(priority = 1) -> BundleGroup -> Bundle means that the Bundle has priority 1.
566
+ function _getBundlePriority(bundleGraph, bundle) {
567
+ if (!hasBundleGraph()) {
568
+ return;
569
+ }
570
+ (0, _assert().default)(bundleGraph != null);
571
+ let node = _getIncomingNodeOfType(bundleGraph, bundle, 'dependency');
572
+ if (node == null) {
573
+ node = _getIncomingNodeOfType(bundleGraph, bundle, 'bundle_group');
574
+ if (node == null) return null;
575
+ node = _getIncomingNodeOfType(bundleGraph, node, 'dependency');
576
+ }
577
+ if (node == null) return null;
578
+ (0, _assert().default)(node.type === 'dependency', 'Not a dependency');
579
+ return node.value.priority;
580
+ }
581
+ function _findEntryBundle(bundleGraph, node) {
582
+ if (!hasBundleGraph()) {
583
+ return;
584
+ }
585
+ (0, _assert().default)(bundleGraph != null);
586
+ const bundleGraphNodeId = bundleGraph._graph.getNodeIdByContentKey(node.id);
587
+ const entryBundleGroup = bundleGraph._graph.getNodeIdsConnectedTo(bundleGraphNodeId, -1).map(id => (0, _nullthrows().default)(bundleGraph._graph.getNode(id))).find(node => node.type === 'bundle_group' && bundleGraph.isEntryBundleGroup(node.value));
588
+ return entryBundleGroup;
589
+ }
590
+ // eslint-disable-next-line no-unused-vars
591
+ function inspectCache(_) {
592
+ // displays sizing of various entries of the cache
593
+ let table = [];
594
+ table.push(['Graphs', 'Size (bytes)', 'Deserialize (ms)', 'Serialize (ms)']);
595
+ let serialized = new Map();
596
+ serialized.set('RequestGraph', timeSerialize(requestTracker));
597
+ serialized.set('BundleGraph', timeSerialize(bundleGraph));
598
+ serialized.set('AssetGraph', timeSerialize(assetGraph));
599
+ for (let [name, info] of (0, _nullthrows().default)(cacheInfo).entries()) {
600
+ if (name === 'RequestGraph' && !hasRequestTracker() || name === 'BundleGraph' && !hasBundleGraph() || name === 'AssetGraph' && !hasAssetGraph()) {
601
+ continue;
602
+ }
603
+ let s = serialized.get(name);
604
+ (0, _assert().default)(s != null);
605
+ table.push([name, ...info, s]);
606
+ }
607
+ function getColumnSum(t, col) {
608
+ if (t == null) {
609
+ return '';
610
+ }
611
+ const initialValue = 0;
612
+ let column = t.map(r => r[col]);
613
+ column.shift();
614
+ (0, _assert().default)(column != null);
615
+ return column.reduce((accumulator, currentValue) => accumulator + currentValue, initialValue);
616
+ }
617
+ table.push(['Totals', getColumnSum(table, 1), getColumnSum(table, 2), getColumnSum(table, 3)]);
618
+ _printStatsTable('Cache Info', table);
619
+ }
620
+ function timeSerialize(graph) {
621
+ let date = Date.now();
622
+ (0, _v().serialize)(graph);
623
+ date = Date.now() - date;
624
+ return date;
625
+ }
626
+ function _printStatsTable(header, data) {
627
+ const config = {
628
+ columnDefault: {
629
+ width: 18
630
+ },
631
+ header: {
632
+ alignment: 'center',
633
+ content: header
634
+ }
635
+ };
636
+ console.log((0, _table().table)(data, config));
637
+ }
638
+
639
+ // eslint-disable-next-line no-unused-vars
640
+ function stats(_) {
641
+ let ag = {
642
+ asset: 0,
643
+ dependency: 0,
644
+ asset_group: 0
645
+ };
646
+ if (hasAssetGraph()) {
647
+ (0, _assert().default)(assetGraph != null);
648
+ for (let n of assetGraph.nodes) {
649
+ if (n && n.type in ag) {
650
+ // $FlowFixMe
651
+ ag[n.type]++;
652
+ }
653
+ }
654
+ _printStatsTable('# Asset Graph Node Counts', Object.entries(ag));
655
+ }
656
+ if (!hasBundleGraph()) {
657
+ return;
658
+ }
659
+ (0, _assert().default)(bundleGraph != null);
660
+ let bg = {
661
+ dependency: 0,
662
+ bundle: 0,
663
+ bundle_group: 0,
664
+ asset_node_modules: 0,
665
+ asset_source: 0
666
+ };
667
+ let b_type = {
668
+ entry: 0,
669
+ shared: 0,
670
+ async: 0,
671
+ parallel: 0,
672
+ sync: 0
673
+ };
674
+ let b_ext = {};
675
+ const entries = new Set();
676
+ for (let n of bundleGraph._graph.nodes) {
677
+ if ((n === null || n === void 0 ? void 0 : n.type) === 'bundle_group') {
678
+ bg.bundle_group++;
679
+ } else if ((n === null || n === void 0 ? void 0 : n.type) === 'bundle') {
680
+ bg.bundle++;
681
+
682
+ // $FlowFixMe
683
+ b_ext[n.value.type] = (b_ext[n.value.type] || 0) + 1;
684
+
685
+ // $FlowFixMe
686
+ const entry_group = _findEntryBundle(bundleGraph, n);
687
+ if (entry_group != null && !entries.has(entry_group.id)) {
688
+ b_type.entry++;
689
+ entries.add(entry_group.id);
690
+ } else if (n.value.mainEntryId == null) {
691
+ // In general, !bundle.mainEntryId means that it is shared. In the case of an async and shared bundle, only count it as shared.
692
+ b_type.shared++;
693
+ } else {
694
+ const priority = _getBundlePriority(bundleGraph, n);
695
+ if (priority == Priority.lazy) {
696
+ b_type.async++;
697
+ } else if (priority == Priority.parallel) {
698
+ b_type.parallel++;
699
+ } else if (priority == Priority.sync) {
700
+ b_type.sync++;
701
+ }
702
+ }
703
+ } else if ((n === null || n === void 0 ? void 0 : n.type) === 'asset') {
704
+ if (
705
+ // $FlowFixMe
706
+ fromProjectPathRelative(n.value.filePath).includes('node_modules')) {
707
+ bg.asset_node_modules++;
708
+ } else {
709
+ bg.asset_source++;
710
+ }
711
+ } else if ((n === null || n === void 0 ? void 0 : n.type) === 'dependency') {
712
+ bg.dependency++;
713
+ }
714
+ }
715
+ _printStatsTable('# Bundle Graph Node Counts', Object.entries(bg));
716
+ _printStatsTable('# Bundles By Type', Object.entries(b_type));
717
+ _printStatsTable('# Bundles By Extension', Object.entries(b_ext));
718
+
719
+ // Assert that counts for each breakdown are correct
720
+
721
+ let sum_b_ext = 0;
722
+ for (let k in b_ext) {
723
+ sum_b_ext += b_ext[k];
724
+ }
725
+ let sum_b_type = 0;
726
+ for (let k in b_type) {
727
+ sum_b_type += b_type[k];
728
+ }
729
+ (0, _assert().default)(bg.bundle == sum_b_type, `Bundles by type ${sum_b_type} does not equal total ${bg.bundle}`);
730
+ (0, _assert().default)(bg.bundle == sum_b_ext, `Bundles by extension ${sum_b_ext} does not equal total ${bg.bundle}`);
731
+ }
732
+
733
+ // -------------------------------------------------------
734
+
735
+ if (initialCmd != null) {
736
+ (async () => {
737
+ await eval(initialCmd);
738
+ process.exit(0);
739
+ })();
740
+ } else {
741
+ console.log('See .help. The graphs can be accessed via `assetGraph`, `bundleGraph` and `requestTracker`.');
742
+ process.on('uncaughtException', function (err) {
743
+ console.error(err);
744
+ server.displayPrompt();
745
+ });
746
+ const server = _repl().default.start({
747
+ useColors: true,
748
+ useGlobal: true
749
+ });
750
+ // $FlowFixMe[prop-missing]
751
+ server.setupHistory(_path().default.join(_os().default.homedir(), '.atlaspack_query_history'), () => {});
752
+
753
+ // $FlowFixMe[prop-missing]
754
+ server.context.bundleGraph = bundleGraph;
755
+ // $FlowFixMe[prop-missing]
756
+ server.context.assetGraph = assetGraph;
757
+ // $FlowFixMe[prop-missing]
758
+ server.context.requestTracker = requestTracker;
759
+ // $FlowFixMe[prop-missing]
760
+ server.context.cacheInfo = cacheInfo;
761
+ for (let [name, cmd] of new Map([['getAsset', {
762
+ help: 'args: <id | public id | filepath>',
763
+ action: getAsset
764
+ }], ['getNodeAssetGraph', {
765
+ help: 'args: <content key>. Find node by content key in the asset graph',
766
+ action: getNodeAssetGraph
767
+ }], ['getNodeBundleGraph', {
768
+ help: 'args: <content key>. Find node by content key in the bundle graph',
769
+ action: getNodeBundleGraph
770
+ }], ['findEntriesAssetGraph', {
771
+ help: 'args: <id | public id | filepath>. List paths from an asset to entry points (in asset graph)',
772
+ action: findEntriesAssetGraph
773
+ }], ['findEntriesBundleGraph', {
774
+ help: 'args: <id | public id | filepath>. List paths from an asset to entry points (in bundle graph)',
775
+ action: findEntriesBundleGraph
776
+ }], ['findEntries', {
777
+ help: '= findEntriesBundleGraph',
778
+ action: findEntries
779
+ }], ['getBundlesWithAsset', {
780
+ help: 'args: <id | public id | filepath>. Gets bundles containing the asset',
781
+ action: getBundlesWithAsset
782
+ }], ['getBundlesWithDependency', {
783
+ help: 'args: <id>. Gets bundles containing the dependency',
784
+ action: getBundlesWithDependency
785
+ }], ['getIncomingDependenciesAssetGraph', {
786
+ help: 'args: <asset: id | public id | filepath regex>',
787
+ action: getIncomingDependenciesAssetGraph
788
+ }], ['getIncomingDependenciesBundleGraph', {
789
+ help: 'args: <asset: id | public id | filepath regex>',
790
+ action: getIncomingDependenciesBundleGraph
791
+ }], ['getIncomingDependencies', {
792
+ help: '= getIncomingDependenciesBundleGraph',
793
+ action: getIncomingDependencies
794
+ }], ['getResolvedAsset', {
795
+ help: 'args: <dependency id>. Resolve the dependency',
796
+ action: getResolvedAsset
797
+ }], ['getAssetWithDependency', {
798
+ help: 'args: <dependency id>. Show which asset created the dependency',
799
+ action: getAssetWithDependency
800
+ }], ['traverseAssets', {
801
+ help: 'args: <bundle id>. List assets in bundle',
802
+ action: traverseAssets
803
+ }], ['traverseBundle', {
804
+ help: 'args: <bundle id>. List assets and dependencies in bundle',
805
+ action: traverseBundle
806
+ }], ['getBundle', {
807
+ help: 'args: <name prefix|bundle id>. List matching bundles',
808
+ action: getBundle
809
+ }], ['findBundleReason', {
810
+ help: 'args: <bundle> <asset>. Why is the asset in the bundle',
811
+ action: v => findBundleReason(...v.split(' '))
812
+ }], ['getBundles', {
813
+ help: 'List all bundles',
814
+ action: getBundles
815
+ }], ['getReferencingBundles', {
816
+ help: 'args: <bundle>. List bundles that reference the bundle',
817
+ action: getReferencingBundles
818
+ }], ['stats', {
819
+ help: 'Statistics',
820
+ action: stats
821
+ }], ['findAsset', {
822
+ help: 'args: <regex>. List assets matching the filepath regex',
823
+ action: findAsset
824
+ }], ['inspectCache', {
825
+ help: 'Cache Information',
826
+ action: inspectCache
827
+ }], ['findAssetWithSymbol', {
828
+ help: 'args: <local>. Get the asset that defines the symbol with the given local name',
829
+ action: findAssetWithSymbol
830
+ }]])) {
831
+ // $FlowFixMe
832
+ server.context[name] = cmd.action;
833
+ // $FlowFixMe
834
+ server.defineCommand(name, {
835
+ // $FlowFixMe
836
+ help: '📦 ' + cmd.help,
837
+ action: v => {
838
+ // $FlowFixMe
839
+ server.clearBufferedCommand();
840
+ // $FlowFixMe
841
+ try {
842
+ cmd.action(v);
843
+ } finally {
844
+ server.displayPrompt();
845
+ }
846
+ }
847
+ });
848
+ }
849
+ }
850
+ }