@atlaspack/utils 2.19.3 → 3.0.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 (52) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/DefaultMap.js +41 -0
  3. package/dist/Deferred.js +16 -0
  4. package/dist/PromiseQueue.js +107 -0
  5. package/dist/TapStream.js +23 -0
  6. package/dist/alternatives.js +97 -0
  7. package/dist/ansi-html.js +12 -0
  8. package/dist/blob.js +29 -0
  9. package/dist/bundle-url.js +32 -0
  10. package/dist/collection.js +106 -0
  11. package/dist/config.js +138 -0
  12. package/dist/countLines.js +12 -0
  13. package/dist/debounce.js +15 -0
  14. package/dist/debug-tools.js +37 -0
  15. package/dist/dependency-location.js +22 -0
  16. package/dist/escape-html.js +19 -0
  17. package/dist/generateBuildMetrics.js +111 -0
  18. package/dist/generateCertificate.js +124 -0
  19. package/dist/getCertificate.js +13 -0
  20. package/dist/getExisting.js +20 -0
  21. package/dist/getModuleParts.js +27 -0
  22. package/dist/getRootDir.js +46 -0
  23. package/dist/glob.js +133 -0
  24. package/dist/hash.js +45 -0
  25. package/dist/http-server.js +55 -0
  26. package/dist/index.js +146 -0
  27. package/dist/is-url.js +15 -0
  28. package/dist/isDirectoryInside.js +11 -0
  29. package/dist/objectHash.js +20 -0
  30. package/dist/openInBrowser.js +61 -0
  31. package/dist/parseCSSImport.js +14 -0
  32. package/dist/path.js +36 -0
  33. package/dist/prettifyTime.js +6 -0
  34. package/dist/prettyDiagnostic.js +104 -0
  35. package/dist/progress-message.js +31 -0
  36. package/dist/relativeBundlePath.js +13 -0
  37. package/dist/relativeUrl.js +11 -0
  38. package/dist/replaceBundleReferences.js +140 -0
  39. package/dist/schema.js +389 -0
  40. package/dist/shared-buffer.js +24 -0
  41. package/dist/sourcemap.js +121 -0
  42. package/dist/stream.js +69 -0
  43. package/dist/throttle.js +12 -0
  44. package/dist/urlJoin.js +22 -0
  45. package/lib/prettyDiagnostic.js +17 -1
  46. package/lib/sourcemap.js +13 -2
  47. package/lib/types/sourcemap.d.ts +1 -1
  48. package/package.json +6 -7
  49. package/src/prettyDiagnostic.ts +11 -1
  50. package/src/sourcemap.ts +10 -1
  51. package/tsconfig.json +31 -2
  52. package/tsconfig.tsbuildinfo +1 -0
package/dist/schema.js ADDED
@@ -0,0 +1,389 @@
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.fuzzySearch = fuzzySearch;
40
+ const diagnostic_1 = __importStar(require("@atlaspack/diagnostic"));
41
+ const nullthrows_1 = __importDefault(require("nullthrows"));
42
+ const levenshtein = __importStar(require("fastest-levenshtein"));
43
+ function validateSchema(schema, data) {
44
+ function walk(
45
+ // @ts-expect-error TS7006
46
+ schemaAncestors, dataNode, dataPath) {
47
+ let [schemaNode] = schemaAncestors;
48
+ if (schemaNode.type) {
49
+ let type = Array.isArray(dataNode) ? 'array' : typeof dataNode;
50
+ if (schemaNode.type !== type) {
51
+ return {
52
+ type: 'type',
53
+ dataType: 'value',
54
+ dataPath,
55
+ expectedTypes: [schemaNode.type],
56
+ ancestors: schemaAncestors,
57
+ prettyType: schemaNode.__type,
58
+ };
59
+ }
60
+ else {
61
+ switch (schemaNode.type) {
62
+ case 'array': {
63
+ if (schemaNode.items) {
64
+ let results = [];
65
+ // @ts-expect-error TS18046
66
+ for (let i = 0; i < dataNode.length; i++) {
67
+ let result = walk([schemaNode.items].concat(schemaAncestors),
68
+ // @ts-expect-error TS18046
69
+ dataNode[i], dataPath + '/' + i);
70
+ if (result)
71
+ results.push(result);
72
+ }
73
+ if (results.length)
74
+ return results.reduce((acc, v) => acc.concat(v), []);
75
+ }
76
+ break;
77
+ }
78
+ case 'string': {
79
+ // @ts-expect-error TS2322
80
+ let value = dataNode;
81
+ if (schemaNode.enum) {
82
+ if (!schemaNode.enum.includes(value)) {
83
+ return {
84
+ type: 'enum',
85
+ dataType: 'value',
86
+ dataPath,
87
+ expectedValues: schemaNode.enum,
88
+ actualValue: value,
89
+ ancestors: schemaAncestors,
90
+ };
91
+ }
92
+ }
93
+ else if (schemaNode.__validate) {
94
+ let validationError = schemaNode.__validate(value);
95
+ if (typeof validationError == 'string') {
96
+ return {
97
+ type: 'other',
98
+ dataType: 'value',
99
+ dataPath,
100
+ message: validationError,
101
+ actualValue: value,
102
+ ancestors: schemaAncestors,
103
+ };
104
+ }
105
+ }
106
+ break;
107
+ }
108
+ case 'number': {
109
+ // @ts-expect-error TS2322
110
+ let value = dataNode;
111
+ if (schemaNode.enum) {
112
+ if (!schemaNode.enum.includes(value)) {
113
+ return {
114
+ type: 'enum',
115
+ dataType: 'value',
116
+ dataPath,
117
+ expectedValues: schemaNode.enum,
118
+ actualValue: value,
119
+ ancestors: schemaAncestors,
120
+ };
121
+ }
122
+ }
123
+ break;
124
+ }
125
+ case 'object': {
126
+ let results = [];
127
+ let invalidProps;
128
+ if (schemaNode.__forbiddenProperties) {
129
+ // @ts-expect-error TS2769
130
+ let keys = Object.keys(dataNode);
131
+ // @ts-expect-error TS7006
132
+ invalidProps = schemaNode.__forbiddenProperties.filter((val) => keys.includes(val));
133
+ results.push(...invalidProps.map(
134
+ // @ts-expect-error TS7006
135
+ (k) => ({
136
+ type: 'forbidden-prop',
137
+ dataPath: dataPath + '/' + (0, diagnostic_1.encodeJSONKeyComponent)(k),
138
+ dataType: 'key',
139
+ prop: k,
140
+ expectedProps: Object.keys(schemaNode.properties),
141
+ actualProps: keys,
142
+ ancestors: schemaAncestors,
143
+ })));
144
+ }
145
+ if (schemaNode.required) {
146
+ // @ts-expect-error TS2769
147
+ let keys = Object.keys(dataNode);
148
+ let missingKeys = schemaNode.required.filter(
149
+ // @ts-expect-error TS7006
150
+ (val) => !keys.includes(val));
151
+ results.push(...missingKeys.map(
152
+ // @ts-expect-error TS7006
153
+ (k) => ({
154
+ type: 'missing-prop',
155
+ dataPath,
156
+ dataType: 'value',
157
+ prop: k,
158
+ expectedProps: schemaNode.required,
159
+ actualProps: keys,
160
+ ancestors: schemaAncestors,
161
+ })));
162
+ }
163
+ if (schemaNode.properties) {
164
+ let { additionalProperties = true } = schemaNode;
165
+ // @ts-expect-error TS2407
166
+ for (let k in dataNode) {
167
+ if (invalidProps && invalidProps.includes(k)) {
168
+ // Don't check type on forbidden props
169
+ continue;
170
+ }
171
+ else if (k in schemaNode.properties) {
172
+ let result = walk([schemaNode.properties[k]].concat(schemaAncestors),
173
+ // @ts-expect-error TS18046
174
+ dataNode[k], dataPath + '/' + (0, diagnostic_1.encodeJSONKeyComponent)(k));
175
+ if (result)
176
+ results.push(result);
177
+ }
178
+ else {
179
+ if (typeof additionalProperties === 'boolean') {
180
+ if (!additionalProperties) {
181
+ results.push({
182
+ type: 'enum',
183
+ dataType: 'key',
184
+ dataPath: dataPath + '/' + (0, diagnostic_1.encodeJSONKeyComponent)(k),
185
+ expectedValues: Object.keys(schemaNode.properties).filter((p) => !(p in dataNode)),
186
+ actualValue: k,
187
+ ancestors: schemaAncestors,
188
+ prettyType: schemaNode.__type,
189
+ });
190
+ }
191
+ }
192
+ else {
193
+ let result = walk([additionalProperties].concat(schemaAncestors),
194
+ // @ts-expect-error TS18046
195
+ dataNode[k], dataPath + '/' + (0, diagnostic_1.encodeJSONKeyComponent)(k));
196
+ if (result)
197
+ results.push(result);
198
+ }
199
+ }
200
+ }
201
+ }
202
+ if (results.length)
203
+ return results.reduce((acc, v) => acc.concat(v), []);
204
+ break;
205
+ }
206
+ case 'boolean':
207
+ // NOOP, type was checked already
208
+ break;
209
+ default:
210
+ throw new Error(`Unimplemented schema type ${type}?`);
211
+ }
212
+ }
213
+ }
214
+ else {
215
+ if (schemaNode.enum && !schemaNode.enum.includes(dataNode)) {
216
+ return {
217
+ type: 'enum',
218
+ dataType: 'value',
219
+ dataPath: dataPath,
220
+ expectedValues: schemaNode.enum,
221
+ actualValue: schemaNode,
222
+ ancestors: schemaAncestors,
223
+ };
224
+ }
225
+ if (schemaNode.oneOf || schemaNode.allOf) {
226
+ let list = schemaNode.oneOf || schemaNode.allOf;
227
+ let results = [];
228
+ for (let f of list) {
229
+ let result = walk([f].concat(schemaAncestors), dataNode, dataPath);
230
+ if (result)
231
+ results.push(result);
232
+ }
233
+ if (schemaNode.oneOf
234
+ ? results.length == schemaNode.oneOf.length
235
+ : results.length > 0) {
236
+ // return the result with more values / longer key
237
+ results.sort((a, b) => Array.isArray(a) || Array.isArray(b)
238
+ ? Array.isArray(a) && !Array.isArray(b)
239
+ ? -1
240
+ : !Array.isArray(a) && Array.isArray(b)
241
+ ? 1
242
+ : Array.isArray(a) && Array.isArray(b)
243
+ ? b.length - a.length
244
+ : 0
245
+ : b.dataPath.length - a.dataPath.length);
246
+ return results[0];
247
+ }
248
+ }
249
+ else if (schemaNode.not) {
250
+ let result = walk([schemaNode.not].concat(schemaAncestors), dataNode, dataPath);
251
+ // @ts-expect-error TS2339
252
+ if (!result || result.length == 0) {
253
+ return {
254
+ type: 'other',
255
+ dataPath,
256
+ dataType: null,
257
+ message: schemaNode.__message,
258
+ actualValue: dataNode,
259
+ ancestors: schemaAncestors,
260
+ };
261
+ }
262
+ }
263
+ }
264
+ return undefined;
265
+ }
266
+ let result = walk([schema], data, '');
267
+ return Array.isArray(result) ? result : result ? [result] : [];
268
+ }
269
+ exports.default = validateSchema;
270
+ function fuzzySearch(expectedValues, actualValue) {
271
+ let result = expectedValues
272
+ .map((exp) => [exp, levenshtein.distance(exp, actualValue)])
273
+ .filter(
274
+ // Remove if more than half of the string would need to be changed
275
+ // @ts-expect-error TS2769
276
+ ([, d]) => d * 2 < actualValue.length);
277
+ // @ts-expect-error TS2345
278
+ result.sort(([, a], [, b]) => a - b);
279
+ // @ts-expect-error TS2345
280
+ return result.map(([v]) => v);
281
+ }
282
+ validateSchema.diagnostic = function (schema, data, origin, message) {
283
+ if ('source' in data &&
284
+ 'data' in data &&
285
+ typeof data.source !== 'string' &&
286
+ !data) {
287
+ throw new Error('At least one of data.source and data.data must be defined!');
288
+ }
289
+ // @ts-expect-error TS2339
290
+ let object = data.map
291
+ ? // @ts-expect-error TS2339
292
+ data.map.data
293
+ : // @ts-expect-error TS2339
294
+ (data.data ?? JSON.parse(data.source));
295
+ let errors = validateSchema(schema, object);
296
+ if (errors.length) {
297
+ let keys = errors.map((e) => {
298
+ let message;
299
+ if (e.type === 'enum') {
300
+ let { actualValue } = e;
301
+ let expectedValues = e.expectedValues.map(String);
302
+ let likely = actualValue != null
303
+ ? fuzzySearch(expectedValues, String(actualValue))
304
+ : [];
305
+ if (likely.length > 0) {
306
+ message = `Did you mean ${likely
307
+ .map((v) => JSON.stringify(v))
308
+ .join(', ')}?`;
309
+ }
310
+ else if (expectedValues.length > 0) {
311
+ message = `Possible values: ${expectedValues
312
+ .map((v) => JSON.stringify(v))
313
+ .join(', ')}`;
314
+ }
315
+ else {
316
+ message = 'Unexpected value';
317
+ }
318
+ }
319
+ else if (e.type === 'forbidden-prop') {
320
+ let { prop, expectedProps, actualProps } = e;
321
+ let likely = fuzzySearch(expectedProps, prop).filter((v) => !actualProps.includes(v));
322
+ if (likely.length > 0) {
323
+ message = `Did you mean ${likely
324
+ .map((v) => JSON.stringify(v))
325
+ .join(', ')}?`;
326
+ }
327
+ else {
328
+ message = 'Unexpected property';
329
+ }
330
+ }
331
+ else if (e.type === 'missing-prop') {
332
+ let { prop, actualProps } = e;
333
+ let likely = fuzzySearch(actualProps, prop);
334
+ if (likely.length > 0) {
335
+ message = `Did you mean ${JSON.stringify(prop)}?`;
336
+ e.dataPath += '/' + likely[0];
337
+ e.dataType = 'key';
338
+ }
339
+ else {
340
+ message = `Missing property ${prop}`;
341
+ }
342
+ }
343
+ else if (e.type === 'type') {
344
+ if (e.prettyType != null) {
345
+ message = `Expected ${e.prettyType}`;
346
+ }
347
+ else {
348
+ message = `Expected type ${e.expectedTypes.join(', ')}`;
349
+ }
350
+ }
351
+ else {
352
+ message = e.message;
353
+ }
354
+ return { key: e.dataPath, type: e.dataType, message };
355
+ });
356
+ let map, code;
357
+ // @ts-expect-error TS2339
358
+ if (data.map) {
359
+ // @ts-expect-error TS2339
360
+ map = data.map;
361
+ code = data.source;
362
+ }
363
+ else {
364
+ // @ts-expect-error TS2339
365
+ map = data.source ?? JSON.stringify((0, nullthrows_1.default)(data.data), 0, '\t');
366
+ code = map;
367
+ }
368
+ let codeFrames = [
369
+ {
370
+ filePath: data.filePath ?? undefined,
371
+ language: 'json',
372
+ code,
373
+ codeHighlights: (0, diagnostic_1.generateJSONCodeHighlights)(map, keys.map(({ key, type, message }) => ({
374
+ key: (data.prependKey ?? '') + key,
375
+ type: type,
376
+ message: message != null ? (0, diagnostic_1.escapeMarkdown)(message) : message,
377
+ }))),
378
+ },
379
+ ];
380
+ throw new diagnostic_1.default({
381
+ diagnostic: {
382
+ message: message,
383
+ origin,
384
+ // @ts-expect-error TS2322
385
+ codeFrames,
386
+ },
387
+ });
388
+ }
389
+ };
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SharedBuffer = void 0;
4
+ // @ts-expect-error process.browser is a browser-specific property
5
+ if (process.browser) {
6
+ exports.SharedBuffer = ArrayBuffer;
7
+ // Safari has removed the constructor
8
+ if (typeof SharedArrayBuffer !== 'undefined') {
9
+ let channel = new MessageChannel();
10
+ try {
11
+ // Firefox might throw when sending the Buffer over a MessagePort
12
+ channel.port1.postMessage(new SharedArrayBuffer(0));
13
+ exports.SharedBuffer = SharedArrayBuffer;
14
+ }
15
+ catch (_) {
16
+ // NOOP
17
+ }
18
+ channel.port1.close();
19
+ channel.port2.close();
20
+ }
21
+ }
22
+ else {
23
+ exports.SharedBuffer = SharedArrayBuffer;
24
+ }
@@ -0,0 +1,121 @@
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.SOURCEMAP_EXTENSIONS = exports.SOURCEMAP_RE = void 0;
7
+ exports.matchSourceMappingURL = matchSourceMappingURL;
8
+ exports.loadSourceMapUrl = loadSourceMapUrl;
9
+ exports.loadSourceMap = loadSourceMap;
10
+ exports.remapSourceLocation = remapSourceLocation;
11
+ const feature_flags_1 = require("@atlaspack/feature-flags");
12
+ const source_map_1 = __importDefault(require("@parcel/source-map"));
13
+ const path_1 = __importDefault(require("path"));
14
+ const path_2 = require("./path");
15
+ exports.SOURCEMAP_RE = /(?:\/\*|\/\/)\s*[@#]\s*sourceMappingURL\s*=\s*([^\s*]+)(?:\s*\*\/)?\s*$/;
16
+ const DATA_URL_RE = /^data:[^;]+(?:;charset=[^;]+)?;base64,(.*)/;
17
+ exports.SOURCEMAP_EXTENSIONS = new Set([
18
+ 'css',
19
+ 'es',
20
+ 'es6',
21
+ 'js',
22
+ 'jsx',
23
+ 'mjs',
24
+ 'ts',
25
+ 'tsx',
26
+ ]);
27
+ function matchSourceMappingURL(contents) {
28
+ return contents.match(exports.SOURCEMAP_RE);
29
+ }
30
+ async function loadSourceMapUrl(fs, filename, contents) {
31
+ let match = matchSourceMappingURL(contents);
32
+ if (match) {
33
+ let url = match[1].trim();
34
+ let dataURLMatch = url.match(DATA_URL_RE);
35
+ let mapFilePath;
36
+ if (dataURLMatch) {
37
+ mapFilePath = filename;
38
+ }
39
+ else {
40
+ mapFilePath = url.replace(/^file:\/\//, '');
41
+ mapFilePath = (0, path_2.isAbsolute)(mapFilePath)
42
+ ? mapFilePath
43
+ : path_1.default.join(path_1.default.dirname(filename), mapFilePath);
44
+ }
45
+ return {
46
+ url,
47
+ filename: mapFilePath,
48
+ map: JSON.parse(dataURLMatch
49
+ ? Buffer.from(dataURLMatch[1], 'base64').toString()
50
+ : await fs.readFile(mapFilePath, 'utf8')),
51
+ };
52
+ }
53
+ }
54
+ async function loadSourceMap(filename, contents, options) {
55
+ let foundMap = await loadSourceMapUrl(options.fs, filename, contents);
56
+ if (foundMap) {
57
+ let mapSourceRoot = path_1.default.dirname(filename);
58
+ if (foundMap.map.sourceRoot &&
59
+ !(0, path_2.normalizeSeparators)(foundMap.map.sourceRoot).startsWith('/')) {
60
+ mapSourceRoot = path_1.default.join(mapSourceRoot, foundMap.map.sourceRoot);
61
+ }
62
+ let sourcemapInstance = new source_map_1.default(options.projectRoot);
63
+ sourcemapInstance.addVLQMap({
64
+ ...foundMap.map,
65
+ sources: foundMap.map.sources.map((s) => {
66
+ return path_1.default.join(mapSourceRoot, s);
67
+ }),
68
+ });
69
+ return sourcemapInstance;
70
+ }
71
+ }
72
+ function remapSourceLocation(loc, originalMap, projectRoot) {
73
+ let { filePath, start: { line: startLine, column: startCol }, end: { line: endLine, column: endCol }, } = loc;
74
+ let lineDiff = endLine - startLine;
75
+ let colDiff = endCol - startCol;
76
+ let start = originalMap.findClosestMapping(startLine, startCol - 1);
77
+ let end = originalMap.findClosestMapping(endLine, endCol - 1);
78
+ if (start?.original) {
79
+ if (start.source) {
80
+ if ((0, feature_flags_1.getFeatureFlag)('symbolLocationFix') &&
81
+ !path_1.default.isAbsolute(start.source)) {
82
+ filePath = path_1.default.join(projectRoot, start.source);
83
+ }
84
+ else {
85
+ filePath = start.source;
86
+ }
87
+ }
88
+ ({ line: startLine, column: startCol } = start.original);
89
+ startCol++; // source map columns are 0-based
90
+ }
91
+ if (end?.original) {
92
+ ({ line: endLine, column: endCol } = end.original);
93
+ endCol++; // source map columns are 0-based
94
+ if (endLine < startLine) {
95
+ endLine = startLine;
96
+ endCol = startCol;
97
+ }
98
+ else if (endLine === startLine && endCol < startCol && lineDiff === 0) {
99
+ endCol = startCol + colDiff;
100
+ }
101
+ else if (endLine === startLine && startCol === endCol && lineDiff === 0) {
102
+ // Prevent 0-length ranges
103
+ endCol = startCol + 1;
104
+ }
105
+ }
106
+ else {
107
+ endLine = startLine;
108
+ endCol = startCol;
109
+ }
110
+ return {
111
+ filePath,
112
+ start: {
113
+ line: startLine,
114
+ column: startCol,
115
+ },
116
+ end: {
117
+ line: endLine,
118
+ column: endCol,
119
+ },
120
+ };
121
+ }
package/dist/stream.js ADDED
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.measureStreamLength = measureStreamLength;
4
+ exports.readableFromStringOrBuffer = readableFromStringOrBuffer;
5
+ exports.bufferStream = bufferStream;
6
+ exports.blobToStream = blobToStream;
7
+ exports.streamFromPromise = streamFromPromise;
8
+ exports.fallbackStream = fallbackStream;
9
+ const stream_1 = require("stream");
10
+ function measureStreamLength(stream) {
11
+ return new Promise((resolve, reject) => {
12
+ let length = 0;
13
+ stream.on('data', (chunk) => {
14
+ length += chunk;
15
+ });
16
+ stream.on('end', () => resolve(length));
17
+ stream.on('error', reject);
18
+ });
19
+ }
20
+ function readableFromStringOrBuffer(str) {
21
+ // https://stackoverflow.com/questions/12755997/how-to-create-streams-from-string-in-node-js
22
+ const stream = new stream_1.Readable();
23
+ stream.push(str);
24
+ stream.push(null);
25
+ return stream;
26
+ }
27
+ function bufferStream(stream) {
28
+ return new Promise((resolve, reject) => {
29
+ let buf = Buffer.from([]);
30
+ stream.on('data', (data) => {
31
+ buf = Buffer.concat([buf, data]);
32
+ });
33
+ stream.on('end', () => {
34
+ resolve(buf);
35
+ });
36
+ stream.on('error', reject);
37
+ });
38
+ }
39
+ function blobToStream(blob) {
40
+ if (blob instanceof stream_1.Readable) {
41
+ return blob;
42
+ }
43
+ return readableFromStringOrBuffer(blob);
44
+ }
45
+ function streamFromPromise(promise) {
46
+ const stream = new stream_1.PassThrough();
47
+ promise.then((blob) => {
48
+ if (blob instanceof stream_1.Readable) {
49
+ blob.pipe(stream);
50
+ }
51
+ else {
52
+ stream.end(blob);
53
+ }
54
+ });
55
+ return stream;
56
+ }
57
+ function fallbackStream(stream, fallback) {
58
+ const res = new stream_1.PassThrough();
59
+ stream.on('error', (err) => {
60
+ if (err.code === 'ENOENT') {
61
+ fallback().pipe(res);
62
+ }
63
+ else {
64
+ res.emit('error', err);
65
+ }
66
+ });
67
+ stream.pipe(res);
68
+ return res;
69
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = throttle;
4
+ function throttle(fn, delay) {
5
+ let lastCalled;
6
+ return function throttled(...args) {
7
+ if (lastCalled == null || lastCalled + delay <= Date.now()) {
8
+ fn.call(this, ...args);
9
+ lastCalled = Date.now();
10
+ }
11
+ };
12
+ }
@@ -0,0 +1,22 @@
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 = urlJoin;
7
+ const url_1 = __importDefault(require("url"));
8
+ const path_1 = __importDefault(require("path"));
9
+ /**
10
+ * Joins a path onto a URL, and normalizes Windows paths
11
+ * e.g. from \path\to\res.js to /path/to/res.js.
12
+ */
13
+ function urlJoin(publicURL, assetPath) {
14
+ const url = url_1.default.parse(publicURL, false, true);
15
+ // Leading / ensures that paths with colons are not parsed as a protocol.
16
+ let p = assetPath.startsWith('/') ? assetPath : '/' + assetPath;
17
+ const assetUrl = url_1.default.parse(p);
18
+ url.pathname = path_1.default.posix.join(url.pathname ?? '', assetUrl.pathname ?? '');
19
+ url.search = assetUrl.search;
20
+ url.hash = assetUrl.hash;
21
+ return url_1.default.format(url);
22
+ }
@@ -11,6 +11,13 @@ function _codeframe() {
11
11
  };
12
12
  return data;
13
13
  }
14
+ function _logger() {
15
+ const data = _interopRequireDefault(require("@atlaspack/logger"));
16
+ _logger = function () {
17
+ return data;
18
+ };
19
+ return data;
20
+ }
14
21
  function _markdownAnsi() {
15
22
  const data = _interopRequireDefault(require("@atlaspack/markdown-ansi"));
16
23
  _markdownAnsi = function () {
@@ -87,7 +94,16 @@ async function prettyDiagnostic(diagnostic, options, terminalWidth, format = 'an
87
94
  let highlights = codeFrame.codeHighlights;
88
95
  let code = codeFrame.code;
89
96
  if (code == null && options && filePath != null) {
90
- code = await options.inputFS.readFile(filePath, 'utf8');
97
+ try {
98
+ code = await options.inputFS.readFile(filePath, 'utf8');
99
+ } catch (e) {
100
+ // In strange cases this can fail and hide the underlying error.
101
+ _logger().default.warn({
102
+ origin: '@atlaspack/utils',
103
+ message: `Failed to read file for generating codeframe: "${filePath}"`,
104
+ skipFormatting: true
105
+ });
106
+ }
91
107
  }
92
108
  let formattedCodeFrame = '';
93
109
  if (code != null) {