@atlaspack/utils 2.14.5-canary.35 → 2.14.5-canary.351

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 (197) hide show
  1. package/CHANGELOG.md +446 -0
  2. package/benchmark.js +23 -0
  3. package/dist/DefaultMap.js +41 -0
  4. package/dist/Deferred.js +16 -0
  5. package/dist/PromiseQueue.js +107 -0
  6. package/dist/TapStream.js +23 -0
  7. package/dist/alternatives.js +97 -0
  8. package/dist/ansi-html.js +12 -0
  9. package/dist/blob.js +29 -0
  10. package/dist/bundle-url.js +32 -0
  11. package/dist/collection.js +106 -0
  12. package/dist/config.js +138 -0
  13. package/dist/countLines.js +12 -0
  14. package/dist/debounce.js +15 -0
  15. package/dist/debug-tools.js +39 -0
  16. package/dist/dependency-location.js +22 -0
  17. package/dist/escape-html.js +19 -0
  18. package/dist/generateBuildMetrics.js +111 -0
  19. package/dist/generateCertificate.js +124 -0
  20. package/dist/getCertificate.js +13 -0
  21. package/dist/getExisting.js +20 -0
  22. package/dist/getModuleParts.js +27 -0
  23. package/dist/getRootDir.js +46 -0
  24. package/dist/getTimeId.js +13 -0
  25. package/dist/glob.js +129 -0
  26. package/dist/hash.js +45 -0
  27. package/dist/http-server.js +55 -0
  28. package/dist/index.js +148 -0
  29. package/dist/is-url.js +15 -0
  30. package/dist/isDirectoryInside.js +11 -0
  31. package/dist/objectHash.js +20 -0
  32. package/dist/openInBrowser.js +61 -0
  33. package/dist/parseCSSImport.js +14 -0
  34. package/dist/path.js +36 -0
  35. package/dist/prettifyTime.js +6 -0
  36. package/dist/prettyDiagnostic.js +108 -0
  37. package/dist/progress-message.js +31 -0
  38. package/dist/relativeBundlePath.js +13 -0
  39. package/dist/relativeUrl.js +11 -0
  40. package/dist/replaceBundleReferences.js +131 -0
  41. package/dist/schema.js +404 -0
  42. package/dist/shared-buffer.js +24 -0
  43. package/dist/sourcemap.js +121 -0
  44. package/dist/stream.js +69 -0
  45. package/dist/throttle.js +12 -0
  46. package/dist/urlJoin.js +22 -0
  47. package/lib/DefaultMap.js +42 -0
  48. package/lib/Deferred.js +30 -0
  49. package/lib/PromiseQueue.js +112 -0
  50. package/lib/TapStream.js +34 -0
  51. package/lib/alternatives.js +116 -0
  52. package/lib/ansi-html.js +20 -0
  53. package/lib/blob.js +40 -0
  54. package/lib/bundle-url.js +34 -0
  55. package/lib/collection.js +111 -0
  56. package/lib/config.js +174 -0
  57. package/lib/countLines.js +15 -0
  58. package/lib/debounce.js +18 -0
  59. package/lib/debug-tools.js +40 -0
  60. package/lib/dependency-location.js +21 -0
  61. package/lib/escape-html.js +22 -0
  62. package/lib/generateBuildMetrics.js +121 -0
  63. package/lib/generateCertificate.js +129 -0
  64. package/lib/getCertificate.js +18 -0
  65. package/lib/getExisting.js +25 -0
  66. package/lib/getModuleParts.js +30 -0
  67. package/lib/getRootDir.js +52 -0
  68. package/lib/getTimeId.js +10 -0
  69. package/lib/glob.js +110 -0
  70. package/lib/hash.js +50 -0
  71. package/lib/http-server.js +85 -0
  72. package/lib/index.js +643 -37310
  73. package/lib/is-url.js +24 -0
  74. package/lib/isDirectoryInside.js +18 -0
  75. package/lib/objectHash.js +26 -0
  76. package/lib/openInBrowser.js +74 -0
  77. package/lib/parseCSSImport.js +15 -0
  78. package/lib/path.js +39 -0
  79. package/lib/prettifyTime.js +9 -0
  80. package/lib/prettyDiagnostic.js +154 -0
  81. package/lib/progress-message.js +39 -0
  82. package/lib/relativeBundlePath.js +22 -0
  83. package/lib/relativeUrl.js +24 -0
  84. package/lib/replaceBundleReferences.js +182 -0
  85. package/lib/schema.js +353 -0
  86. package/lib/shared-buffer.js +31 -0
  87. package/lib/sourcemap.js +138 -0
  88. package/lib/stream.js +76 -0
  89. package/lib/throttle.js +15 -0
  90. package/lib/types/DefaultMap.d.ts +13 -0
  91. package/lib/types/Deferred.d.ts +8 -0
  92. package/lib/types/PromiseQueue.d.ts +25 -0
  93. package/lib/types/TapStream.d.ts +6 -0
  94. package/lib/types/alternatives.d.ts +3 -0
  95. package/lib/types/ansi-html.d.ts +1 -0
  96. package/lib/types/blob.d.ts +4 -0
  97. package/lib/types/bundle-url.d.ts +4 -0
  98. package/lib/types/collection.d.ts +33 -0
  99. package/lib/types/config.d.ts +17 -0
  100. package/lib/types/countLines.d.ts +1 -0
  101. package/lib/types/debounce.d.ts +1 -0
  102. package/lib/types/debug-tools.d.ts +8 -0
  103. package/lib/types/dependency-location.d.ts +14 -0
  104. package/lib/types/escape-html.d.ts +1 -0
  105. package/lib/types/generateBuildMetrics.d.ts +18 -0
  106. package/lib/types/generateCertificate.d.ts +5 -0
  107. package/lib/types/getCertificate.d.ts +5 -0
  108. package/lib/types/getExisting.d.ts +8 -0
  109. package/lib/types/getModuleParts.d.ts +4 -0
  110. package/lib/types/getRootDir.d.ts +2 -0
  111. package/lib/types/getTimeId.d.ts +1 -0
  112. package/lib/types/glob.d.ts +9 -0
  113. package/lib/types/hash.d.ts +7 -0
  114. package/lib/types/http-server.d.ts +19 -0
  115. package/lib/types/index.d.ts +49 -0
  116. package/lib/types/is-url.d.ts +1 -0
  117. package/lib/types/isDirectoryInside.d.ts +2 -0
  118. package/lib/types/objectHash.d.ts +3 -0
  119. package/lib/types/openInBrowser.d.ts +1 -0
  120. package/lib/types/parseCSSImport.d.ts +1 -0
  121. package/lib/types/path.d.ts +8 -0
  122. package/lib/types/prettifyTime.d.ts +1 -0
  123. package/lib/types/prettyDiagnostic.d.ts +18 -0
  124. package/lib/types/progress-message.d.ts +3 -0
  125. package/lib/types/relativeBundlePath.d.ts +4 -0
  126. package/lib/types/relativeUrl.d.ts +1 -0
  127. package/lib/types/replaceBundleReferences.d.ts +39 -0
  128. package/lib/types/schema.d.ts +107 -0
  129. package/lib/types/shared-buffer.d.ts +2 -0
  130. package/lib/types/sourcemap.d.ts +15 -0
  131. package/lib/types/stream.d.ts +8 -0
  132. package/lib/types/throttle.d.ts +1 -0
  133. package/lib/types/urlJoin.d.ts +5 -0
  134. package/lib/urlJoin.js +35 -0
  135. package/package.json +27 -18
  136. package/src/{DefaultMap.js → DefaultMap.ts} +8 -12
  137. package/src/Deferred.ts +26 -0
  138. package/src/{PromiseQueue.js → PromiseQueue.ts} +40 -35
  139. package/src/{TapStream.js → TapStream.ts} +8 -7
  140. package/src/{alternatives.js → alternatives.ts} +15 -16
  141. package/src/{ansi-html.js → ansi-html.ts} +1 -1
  142. package/src/{blob.js → blob.ts} +3 -5
  143. package/src/{bundle-url.js → bundle-url.ts} +3 -5
  144. package/src/{collection.js → collection.ts} +23 -20
  145. package/src/{config.js → config.ts} +20 -21
  146. package/src/{countLines.js → countLines.ts} +0 -2
  147. package/src/{debounce.js → debounce.ts} +3 -5
  148. package/src/debug-tools.ts +48 -0
  149. package/src/{dependency-location.js → dependency-location.ts} +15 -11
  150. package/src/{escape-html.js → escape-html.ts} +5 -3
  151. package/src/{generateBuildMetrics.js → generateBuildMetrics.ts} +19 -21
  152. package/src/{generateCertificate.js → generateCertificate.ts} +8 -6
  153. package/src/{getCertificate.js → getCertificate.ts} +6 -5
  154. package/src/{getExisting.js → getExisting.ts} +4 -3
  155. package/src/{getModuleParts.js → getModuleParts.ts} +3 -2
  156. package/src/{getRootDir.js → getRootDir.ts} +1 -3
  157. package/src/getTimeId.ts +12 -0
  158. package/src/{glob.js → glob.ts} +13 -14
  159. package/src/{hash.js → hash.ts} +23 -18
  160. package/src/{http-server.js → http-server.ts} +34 -40
  161. package/src/{index.js → index.ts} +14 -10
  162. package/src/{is-url.js → is-url.ts} +1 -2
  163. package/src/{isDirectoryInside.js → isDirectoryInside.ts} +1 -2
  164. package/src/{objectHash.js → objectHash.ts} +1 -4
  165. package/src/{openInBrowser.js → openInBrowser.ts} +2 -4
  166. package/src/{parseCSSImport.js → parseCSSImport.ts} +0 -2
  167. package/src/{path.js → path.ts} +2 -4
  168. package/src/{prettifyTime.js → prettifyTime.ts} +0 -2
  169. package/src/{prettyDiagnostic.js → prettyDiagnostic.ts} +47 -24
  170. package/src/progress-message.ts +43 -0
  171. package/src/{relativeBundlePath.js → relativeBundlePath.ts} +4 -4
  172. package/src/{relativeUrl.js → relativeUrl.ts} +0 -1
  173. package/src/{replaceBundleReferences.js → replaceBundleReferences.ts} +67 -51
  174. package/src/schema.ts +552 -0
  175. package/src/{shared-buffer.js → shared-buffer.ts} +5 -3
  176. package/src/{sourcemap.js → sourcemap.ts} +28 -10
  177. package/src/{stream.js → stream.ts} +30 -22
  178. package/src/throttle.ts +13 -0
  179. package/src/{urlJoin.js → urlJoin.ts} +1 -3
  180. package/test/{DefaultMap.test.js → DefaultMap.test.ts} +4 -6
  181. package/test/{PromiseQueue.test.js → PromiseQueue.test.ts} +5 -6
  182. package/test/{collection.test.js → collection.test.ts} +0 -2
  183. package/test/{config.test.js → config.test.ts} +0 -3
  184. package/test/{objectHash.test.js → objectHash.test.ts} +4 -5
  185. package/test/{prettifyTime.test.js → prettifyTime.test.ts} +0 -1
  186. package/test/{replaceBundleReferences.test.js → replaceBundleReferences.test.ts} +0 -32
  187. package/test/schema.test.ts +748 -0
  188. package/test/{sourcemap.test.js → sourcemap.test.ts} +0 -1
  189. package/test/{throttle.test.js → throttle.test.ts} +1 -3
  190. package/test/{urlJoin.test.js → urlJoin.test.ts} +0 -2
  191. package/tsconfig.json +36 -0
  192. package/tsconfig.tsbuildinfo +1 -0
  193. package/lib/index.js.map +0 -1
  194. package/src/Deferred.js +0 -23
  195. package/src/progress-message.js +0 -22
  196. package/src/schema.js +0 -504
  197. package/src/throttle.js +0 -15
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const stream_1 = require("stream");
4
+ /*
5
+ * "Taps" into the contents of a flowing stream, yielding chunks to the passed
6
+ * callback. Continues to pass data chunks down the stream.
7
+ */
8
+ class TapStream extends stream_1.Transform {
9
+ constructor(tap, options) {
10
+ super({ ...options });
11
+ this._tap = tap;
12
+ }
13
+ _transform(chunk, encoding, callback) {
14
+ try {
15
+ this._tap(Buffer.from(chunk));
16
+ callback(null, chunk);
17
+ }
18
+ catch (err) {
19
+ callback(err);
20
+ }
21
+ }
22
+ }
23
+ exports.default = TapStream;
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.findAlternativeNodeModules = findAlternativeNodeModules;
7
+ exports.findAlternativeFiles = findAlternativeFiles;
8
+ const path_1 = __importDefault(require("path"));
9
+ const schema_1 = require("./schema");
10
+ const path_2 = require("./path");
11
+ const config_1 = require("./config");
12
+ async function findAlternativeNodeModules(fs, moduleName, dir) {
13
+ let potentialModules = [];
14
+ let root = path_1.default.parse(dir).root;
15
+ let isOrganisationModule = moduleName.startsWith('@');
16
+ while (dir !== root) {
17
+ // Skip node_modules directories
18
+ if (path_1.default.basename(dir) === 'node_modules') {
19
+ dir = path_1.default.dirname(dir);
20
+ }
21
+ try {
22
+ let modulesDir = path_1.default.join(dir, 'node_modules');
23
+ let stats = await fs.stat(modulesDir);
24
+ if (stats.isDirectory()) {
25
+ let dirContent = (await fs.readdir(modulesDir)).sort();
26
+ // Filter out the modules that interest us
27
+ let modules = dirContent.filter((i) => isOrganisationModule ? i.startsWith('@') : !i.startsWith('@'));
28
+ // If it's an organisation module, loop through all the modules of that organisation
29
+ if (isOrganisationModule) {
30
+ await Promise.all(modules.map(async (item) => {
31
+ let orgDirPath = path_1.default.join(modulesDir, item);
32
+ let orgDirContent = (await fs.readdir(orgDirPath)).sort();
33
+ // Add all org packages
34
+ potentialModules.push(...orgDirContent.map((i) => `${item}/${i}`));
35
+ }));
36
+ }
37
+ else {
38
+ potentialModules.push(...modules);
39
+ }
40
+ }
41
+ }
42
+ catch (err) {
43
+ // ignore
44
+ }
45
+ // Move up a directory
46
+ dir = path_1.default.dirname(dir);
47
+ }
48
+ return (0, schema_1.fuzzySearch)(potentialModules.sort(), moduleName).slice(0, 2);
49
+ }
50
+ async function findAllFilesUp({ fs, dir, root, basedir, maxlength, collected, leadingDotSlash = true, includeDirectories = true, }) {
51
+ let dirContent = (await fs.readdir(dir)).sort();
52
+ return Promise.all(dirContent.map(async (item) => {
53
+ let fullPath = path_1.default.join(dir, item);
54
+ let relativeFilePath = (0, path_2.relativePath)(basedir, fullPath, leadingDotSlash);
55
+ if (relativeFilePath.length < maxlength) {
56
+ let stats = await fs.stat(fullPath);
57
+ let isDir = stats.isDirectory();
58
+ if ((isDir && includeDirectories) || stats.isFile()) {
59
+ collected.push(relativeFilePath);
60
+ }
61
+ // If it's a directory, run over each item within said directory...
62
+ if (isDir) {
63
+ return findAllFilesUp({
64
+ fs,
65
+ dir: fullPath,
66
+ root,
67
+ basedir,
68
+ maxlength,
69
+ collected,
70
+ });
71
+ }
72
+ }
73
+ }));
74
+ }
75
+ async function findAlternativeFiles(fs, fileSpecifier, dir, projectRoot, leadingDotSlash = true, includeDirectories = true, includeExtension = false) {
76
+ let potentialFiles = [];
77
+ // Find our root, we won't recommend files above the package root as that's bad practise
78
+ let pkg = await (0, config_1.resolveConfig)(fs, path_1.default.join(dir, 'index'), ['package.json'], projectRoot);
79
+ let pkgRoot = pkg ? path_1.default.dirname(pkg) : projectRoot;
80
+ await findAllFilesUp({
81
+ fs,
82
+ dir: pkgRoot,
83
+ root: pkgRoot,
84
+ basedir: dir,
85
+ maxlength: fileSpecifier.length + 10,
86
+ collected: potentialFiles,
87
+ leadingDotSlash,
88
+ includeDirectories,
89
+ });
90
+ if (path_1.default.extname(fileSpecifier) === '' && !includeExtension) {
91
+ potentialFiles = potentialFiles.map((p) => {
92
+ let ext = path_1.default.extname(p);
93
+ return ext.length > 0 ? p.slice(0, -ext.length) : p;
94
+ });
95
+ }
96
+ return (0, schema_1.fuzzySearch)(potentialFiles.sort(), fileSpecifier).slice(0, 2);
97
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ansiHtml = ansiHtml;
7
+ // @ts-expect-error ansi-html-community is not typed
8
+ const ansi_html_community_1 = __importDefault(require("ansi-html-community"));
9
+ const escape_html_1 = require("./escape-html");
10
+ function ansiHtml(ansi) {
11
+ return (0, ansi_html_community_1.default)((0, escape_html_1.escapeHTML)(ansi));
12
+ }
package/dist/blob.js ADDED
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.blobToBuffer = blobToBuffer;
4
+ exports.blobToString = blobToString;
5
+ const buffer_1 = require("buffer");
6
+ const _1 = require("./");
7
+ const stream_1 = require("stream");
8
+ function blobToBuffer(blob) {
9
+ if (blob instanceof stream_1.Readable) {
10
+ return (0, _1.bufferStream)(blob);
11
+ }
12
+ else if (blob instanceof buffer_1.Buffer) {
13
+ return Promise.resolve(buffer_1.Buffer.from(blob));
14
+ }
15
+ else {
16
+ return Promise.resolve(buffer_1.Buffer.from(blob, 'utf8'));
17
+ }
18
+ }
19
+ async function blobToString(blob) {
20
+ if (blob instanceof stream_1.Readable) {
21
+ return (await (0, _1.bufferStream)(blob)).toString();
22
+ }
23
+ else if (blob instanceof buffer_1.Buffer) {
24
+ return blob.toString();
25
+ }
26
+ else {
27
+ return blob;
28
+ }
29
+ }
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getBundleURL = void 0;
4
+ exports.getBaseURL = getBaseURL;
5
+ let bundleURL = null;
6
+ function getBundleURLCached() {
7
+ if (bundleURL == null) {
8
+ bundleURL = _getBundleURL();
9
+ }
10
+ return bundleURL;
11
+ }
12
+ function _getBundleURL() {
13
+ // Attempt to find the URL of the current script and use that as the base URL
14
+ try {
15
+ throw new Error();
16
+ }
17
+ catch (err) {
18
+ let stack = typeof err.stack === 'string' ? err.stack : '';
19
+ let matches = stack.match(/(https?|file|ftp):\/\/[^)\n]+/g);
20
+ if (matches) {
21
+ return getBaseURL(matches[0]);
22
+ }
23
+ }
24
+ return '/';
25
+ }
26
+ function getBaseURL(url) {
27
+ if (url == null) {
28
+ return '/';
29
+ }
30
+ return url.replace(/^((?:https?|file|ftp):\/\/.+)\/[^/]+$/, '$1') + '/';
31
+ }
32
+ exports.getBundleURL = getBundleURLCached;
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.unique = unique;
4
+ exports.objectSortedEntries = objectSortedEntries;
5
+ exports.objectSortedEntriesDeep = objectSortedEntriesDeep;
6
+ exports.setDifference = setDifference;
7
+ exports.setSymmetricDifference = setSymmetricDifference;
8
+ exports.setIntersect = setIntersect;
9
+ exports.setIntersectStatic = setIntersectStatic;
10
+ exports.setUnion = setUnion;
11
+ exports.setEqual = setEqual;
12
+ function unique(array) {
13
+ return [...new Set(array)];
14
+ }
15
+ function objectSortedEntries(obj) {
16
+ return Object.entries(obj).sort(([keyA], [keyB]) => keyA.localeCompare(keyB));
17
+ }
18
+ function objectSortedEntriesDeep(object) {
19
+ let sortedEntries = objectSortedEntries(object);
20
+ for (let i = 0; i < sortedEntries.length; i++) {
21
+ sortedEntries[i][1] = sortEntry(sortedEntries[i][1]);
22
+ }
23
+ return sortedEntries;
24
+ }
25
+ function sortEntry(entry) {
26
+ if (Array.isArray(entry)) {
27
+ return entry.map(sortEntry);
28
+ }
29
+ if (typeof entry === 'object' && entry != null) {
30
+ return objectSortedEntriesDeep(entry);
31
+ }
32
+ return entry;
33
+ }
34
+ /**
35
+ * Get the difference of A and B sets
36
+ *
37
+ * This is the set of elements which are in A but not in B
38
+ * For example, the difference of the sets {1,2,3} and {3,4} is {1,2}
39
+ *
40
+ * @param {*} a Set A
41
+ * @param {*} b Set B
42
+ * @returns A \ B
43
+ */
44
+ function setDifference(a, b) {
45
+ let difference = new Set();
46
+ for (let e of a) {
47
+ if (!b.has(e)) {
48
+ difference.add(e);
49
+ }
50
+ }
51
+ return difference;
52
+ }
53
+ /**
54
+ * Get the symmetric difference of A and B sets
55
+ *
56
+ * This is the set of elements which are in either of the sets, but not in their intersection.
57
+ * For example, the symmetric difference of the sets {1,2,3} and {3,4} is {1,2,4}
58
+ *
59
+ * @param {*} a Set A
60
+ * @param {*} b Set B
61
+ * @returns A Δ B
62
+ */
63
+ function setSymmetricDifference(a, b) {
64
+ let difference = new Set();
65
+ for (let e of a) {
66
+ if (!b.has(e)) {
67
+ difference.add(e);
68
+ }
69
+ }
70
+ for (let d of b) {
71
+ if (!a.has(d)) {
72
+ difference.add(d);
73
+ }
74
+ }
75
+ return difference;
76
+ }
77
+ function setIntersect(a, b) {
78
+ for (let entry of a) {
79
+ if (!b.has(entry)) {
80
+ a.delete(entry);
81
+ }
82
+ }
83
+ }
84
+ function setIntersectStatic(a, b) {
85
+ let intersection = new Set();
86
+ for (let entry of a) {
87
+ if (b.has(entry)) {
88
+ intersection.add(entry);
89
+ }
90
+ }
91
+ return intersection;
92
+ }
93
+ function setUnion(a, b) {
94
+ return new Set([...a, ...b]);
95
+ }
96
+ function setEqual(a, b) {
97
+ if (a.size != b.size) {
98
+ return false;
99
+ }
100
+ for (let entry of a) {
101
+ if (!b.has(entry)) {
102
+ return false;
103
+ }
104
+ }
105
+ return true;
106
+ }
package/dist/config.js ADDED
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.resolveConfig = resolveConfig;
7
+ exports.resolveConfigSync = resolveConfigSync;
8
+ exports.loadConfig = loadConfig;
9
+ exports.readConfig = readConfig;
10
+ const diagnostic_1 = __importDefault(require("@atlaspack/diagnostic"));
11
+ const path_1 = __importDefault(require("path"));
12
+ // @ts-expect-error TS7016
13
+ const clone_1 = __importDefault(require("clone"));
14
+ const json5_1 = __importDefault(require("json5"));
15
+ const toml_1 = require("@iarna/toml");
16
+ const lru_cache_1 = __importDefault(require("lru-cache"));
17
+ // @ts-expect-error TS2351
18
+ const configCache = new lru_cache_1.default({ max: 500 });
19
+ const resolveCache = new Map();
20
+ function resolveConfig(fs, filepath, filenames, projectRoot) {
21
+ // Cache the result of resolving config for this directory.
22
+ // This is automatically invalidated at the end of the current build.
23
+ let key = path_1.default.dirname(filepath) + filenames.join(',');
24
+ let cached = resolveCache.get(key);
25
+ if (cached !== undefined) {
26
+ return Promise.resolve(cached);
27
+ }
28
+ let resolved = fs.findAncestorFile(filenames, path_1.default.dirname(filepath), projectRoot);
29
+ resolveCache.set(key, resolved);
30
+ return Promise.resolve(resolved);
31
+ }
32
+ function resolveConfigSync(fs, filepath, filenames, projectRoot) {
33
+ return fs.findAncestorFile(filenames, path_1.default.dirname(filepath), projectRoot);
34
+ }
35
+ async function loadConfig(fs, filepath, filenames, projectRoot, opts) {
36
+ let parse = opts?.parse ?? true;
37
+ let configFile = await resolveConfig(fs, filepath, filenames, projectRoot);
38
+ if (configFile) {
39
+ let cachedOutput = configCache.get(String(parse) + configFile);
40
+ if (cachedOutput) {
41
+ return cachedOutput;
42
+ }
43
+ try {
44
+ let extname = path_1.default.extname(configFile).slice(1);
45
+ if (extname === 'js' || extname === 'cjs') {
46
+ let output = {
47
+ config: (0, clone_1.default)(module.require(configFile)),
48
+ files: [{ filePath: configFile }],
49
+ };
50
+ configCache.set(configFile, output);
51
+ return output;
52
+ }
53
+ return readConfig(fs, configFile, opts);
54
+ }
55
+ catch (err) {
56
+ if (err.code === 'MODULE_NOT_FOUND' || err.code === 'ENOENT') {
57
+ return null;
58
+ }
59
+ throw err;
60
+ }
61
+ }
62
+ return null;
63
+ }
64
+ loadConfig.clear = () => {
65
+ configCache.reset();
66
+ resolveCache.clear();
67
+ };
68
+ async function readConfig(fs, configFile, opts) {
69
+ let parse = opts?.parse ?? true;
70
+ let cachedOutput = configCache.get(String(parse) + configFile);
71
+ if (cachedOutput) {
72
+ return cachedOutput;
73
+ }
74
+ try {
75
+ let configContent = await fs.readFile(configFile, 'utf8');
76
+ let config;
77
+ if (parse === false) {
78
+ config = configContent;
79
+ }
80
+ else {
81
+ let extname = path_1.default.extname(configFile).slice(1);
82
+ let parse = opts?.parser ?? getParser(extname);
83
+ try {
84
+ config = parse(configContent);
85
+ }
86
+ catch (e) {
87
+ if (extname !== '' && extname !== 'json') {
88
+ throw e;
89
+ }
90
+ let pos = {
91
+ line: e.lineNumber,
92
+ column: e.columnNumber,
93
+ };
94
+ throw new diagnostic_1.default({
95
+ diagnostic: {
96
+ message: `Failed to parse ${path_1.default.basename(configFile)}`,
97
+ origin: '@atlaspack/utils',
98
+ codeFrames: [
99
+ {
100
+ language: 'json5',
101
+ filePath: configFile,
102
+ code: configContent,
103
+ codeHighlights: [
104
+ {
105
+ start: pos,
106
+ end: pos,
107
+ message: e.message,
108
+ },
109
+ ],
110
+ },
111
+ ],
112
+ },
113
+ });
114
+ }
115
+ }
116
+ let output = {
117
+ config,
118
+ files: [{ filePath: configFile }],
119
+ };
120
+ configCache.set(String(parse) + configFile, output);
121
+ return output;
122
+ }
123
+ catch (err) {
124
+ if (err.code === 'MODULE_NOT_FOUND' || err.code === 'ENOENT') {
125
+ return null;
126
+ }
127
+ throw err;
128
+ }
129
+ }
130
+ function getParser(extname) {
131
+ switch (extname) {
132
+ case 'toml':
133
+ return toml_1.parse;
134
+ case 'json':
135
+ default:
136
+ return json5_1.default.parse;
137
+ }
138
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = countLines;
4
+ function countLines(string, startIndex = 0) {
5
+ let lines = 1;
6
+ for (let i = startIndex; i < string.length; i++) {
7
+ if (string.charAt(i) === '\n') {
8
+ lines++;
9
+ }
10
+ }
11
+ return lines;
12
+ }
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = debounce;
4
+ function debounce(fn, delay) {
5
+ let timeout;
6
+ return function (...args) {
7
+ if (timeout) {
8
+ clearTimeout(timeout);
9
+ }
10
+ timeout = setTimeout(() => {
11
+ timeout = null;
12
+ fn(...args);
13
+ }, delay);
14
+ };
15
+ }
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ /*
3
+ * These tools are intended for Atlaspack developers, to provide extra utilities
4
+ * to make debugging Atlaspack issues more straightforward.
5
+ *
6
+ * To enable a tool, set the `ATLASPACK_DEBUG_TOOLS` environment variable to a
7
+ * comma-separated list of tool names. For example:
8
+ * `ATLASPACK_DEBUG_TOOLS="asset-file-names-in-output,simple-cli-reporter"`
9
+ *
10
+ * You can enable all tools by setting `ATLASPACK_DEBUG_TOOLS=all`.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.debugTools = void 0;
14
+ exports.debugTools = {
15
+ 'asset-file-names-in-output': false,
16
+ 'simple-cli-reporter': false,
17
+ 'bundle-stats': false,
18
+ 'scope-hoisting-stats': false,
19
+ };
20
+ const envVarValue = process.env.ATLASPACK_DEBUG_TOOLS ?? '';
21
+ for (let tool of envVarValue.split(',')) {
22
+ tool = tool.trim();
23
+ if (tool === 'all') {
24
+ for (let key in exports.debugTools) {
25
+ exports.debugTools[key] = true;
26
+ }
27
+ break;
28
+ }
29
+ else if (exports.debugTools.hasOwnProperty(tool)) {
30
+ exports.debugTools[tool] = true;
31
+ }
32
+ else if (tool === '') {
33
+ continue;
34
+ }
35
+ else {
36
+ // eslint-disable-next-line no-console
37
+ console.warn(`Unknown debug tool option: ${tool}. Valid options are: ${Object.keys(exports.debugTools).join(', ')}`);
38
+ }
39
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = createDependencyLocation;
4
+ function createDependencyLocation(start, specifier, lineOffset = 0, columnOffset = 0,
5
+ // Imports are usually wrapped in quotes
6
+ importWrapperLength = 2) {
7
+ return {
8
+ filePath: specifier,
9
+ start: {
10
+ line: start.line + lineOffset,
11
+ column: start.column + columnOffset,
12
+ },
13
+ end: {
14
+ line: start.line + lineOffset,
15
+ column: start.column +
16
+ specifier.length -
17
+ 1 +
18
+ importWrapperLength +
19
+ columnOffset,
20
+ },
21
+ };
22
+ }
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.escapeHTML = escapeHTML;
4
+ // Based on _.escape https://github.com/lodash/lodash/blob/master/escape.js
5
+ const reUnescapedHtml = /[&<>"']/g;
6
+ const reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
7
+ const htmlEscapes = {
8
+ '&': '&amp;',
9
+ '<': '&lt;',
10
+ '>': '&gt;',
11
+ '"': '&quot;',
12
+ "'": '&#39;',
13
+ };
14
+ function escapeHTML(s) {
15
+ if (reHasUnescapedHtml.test(s)) {
16
+ return s.replace(reUnescapedHtml, (c) => htmlEscapes[c]);
17
+ }
18
+ return s;
19
+ }
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.default = generateBuildMetrics;
7
+ const source_map_1 = __importDefault(require("@atlaspack/source-map"));
8
+ const nullthrows_1 = __importDefault(require("nullthrows"));
9
+ const path_1 = __importDefault(require("path"));
10
+ const _1 = require("./");
11
+ async function getSourcemapSizes(filePath, fs, projectRoot) {
12
+ let bundleContents = await fs.readFile(filePath, 'utf-8');
13
+ let mapUrlData = await (0, _1.loadSourceMapUrl)(fs, filePath, bundleContents);
14
+ if (!mapUrlData) {
15
+ return null;
16
+ }
17
+ let rawMap = mapUrlData.map;
18
+ let sourceMap = new source_map_1.default(projectRoot);
19
+ sourceMap.addVLQMap(rawMap);
20
+ let parsedMapData = sourceMap.getMap();
21
+ if (parsedMapData.mappings.length > 2) {
22
+ let sources = parsedMapData.sources.map((s) => path_1.default.normalize(path_1.default.join(projectRoot, s)));
23
+ let currLine = 1;
24
+ let currColumn = 0;
25
+ let currMappingIndex = 0;
26
+ let currMapping = parsedMapData.mappings[currMappingIndex];
27
+ let nextMapping = parsedMapData.mappings[currMappingIndex + 1];
28
+ let sourceSizes = new Array(sources.length).fill(0);
29
+ let unknownOrigin = 0;
30
+ for (let i = 0; i < bundleContents.length; i++) {
31
+ let character = bundleContents[i];
32
+ while (nextMapping &&
33
+ nextMapping.generated.line === currLine &&
34
+ nextMapping.generated.column <= currColumn) {
35
+ currMappingIndex++;
36
+ currMapping = parsedMapData.mappings[currMappingIndex];
37
+ nextMapping = parsedMapData.mappings[currMappingIndex + 1];
38
+ }
39
+ let currentSource = currMapping.source;
40
+ let charSize = Buffer.byteLength(character, 'utf8');
41
+ if (currentSource != null &&
42
+ currMapping.generated.line === currLine &&
43
+ currMapping.generated.column <= currColumn) {
44
+ sourceSizes[currentSource] += charSize;
45
+ }
46
+ else {
47
+ unknownOrigin += charSize;
48
+ }
49
+ if (character === '\n') {
50
+ currColumn = 0;
51
+ currLine++;
52
+ }
53
+ else {
54
+ currColumn++;
55
+ }
56
+ }
57
+ let sizeMap = new Map();
58
+ for (let i = 0; i < sourceSizes.length; i++) {
59
+ sizeMap.set(sources[i], sourceSizes[i]);
60
+ }
61
+ sizeMap.set('', unknownOrigin);
62
+ return sizeMap;
63
+ }
64
+ }
65
+ async function createBundleStats(bundle, fs, projectRoot) {
66
+ let filePath = bundle.filePath;
67
+ let sourcemapSizes = await getSourcemapSizes(filePath, fs, projectRoot);
68
+ let assets = new Map();
69
+ bundle.traverseAssets((asset) => {
70
+ let filePath = path_1.default.normalize(asset.filePath);
71
+ assets.set(filePath, {
72
+ filePath,
73
+ size: asset.stats.size,
74
+ originalSize: asset.stats.size,
75
+ time: asset.stats.time,
76
+ });
77
+ });
78
+ let assetsReport = [];
79
+ if (sourcemapSizes && sourcemapSizes.size) {
80
+ assetsReport = Array.from(sourcemapSizes.keys()).map((filePath) => {
81
+ let foundSize = sourcemapSizes.get(filePath) || 0;
82
+ let stats = assets.get(filePath) || {
83
+ filePath,
84
+ size: foundSize,
85
+ originalSize: foundSize,
86
+ time: 0,
87
+ };
88
+ return {
89
+ ...stats,
90
+ size: foundSize,
91
+ };
92
+ });
93
+ }
94
+ else {
95
+ assetsReport = Array.from(assets.values());
96
+ }
97
+ return {
98
+ filePath: (0, nullthrows_1.default)(bundle.filePath),
99
+ size: bundle.stats.size,
100
+ time: bundle.stats.time,
101
+ assets: assetsReport.sort((a, b) => b.size - a.size),
102
+ };
103
+ }
104
+ async function generateBuildMetrics(bundles, fs, projectRoot) {
105
+ bundles
106
+ .sort((a, b) => b.stats.size - a.stats.size)
107
+ .filter((b) => !!b.filePath);
108
+ return {
109
+ bundles: (await Promise.all(bundles.map((b) => createBundleStats(b, fs, projectRoot)))).filter((e) => !!e),
110
+ };
111
+ }