forked from cspotcode/node-source-map-support
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.js
1103 lines (1011 loc) · 41.2 KB
/
test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @ts-check
// Note: some tests rely on side-effects from prior tests.
// You may not get meaningful results running a subset of tests.
const Module = require('module');
const priorErrorPrepareStackTrace = Error.prepareStackTrace;
const priorProcessEmit = process.emit;
const priorResolveFilename = Module._resolveFilename;
const underTest = require('./source-map-support');
var SourceMapGenerator = require('source-map').SourceMapGenerator;
var child_process = require('child_process');
var assert = require('assert');
var fs = require('fs');
var util = require('util');
var path = require('path');
const { pathToFileURL } = require('url');
var bufferFrom = Buffer.from;
const semver = require('semver');
const { once, mapValues, flow } = require('lodash');
// Helper to create regular expressions from string templates, to use interpolation
function re(...args) {
return new RegExp(String.raw(...args));
}
//#region module format differences
function namedExportDeclaration() {
// same length so that offsets are the same either way
return extension === 'mjs'
? 'export const test'
: 'exports.test ';
}
/**
* How stack frame will describe invocations of the `test` function, when it is imported and invoked by a different file.
* This varies across CJS / ESM and node versions.
* Example: ` at Module.exports.test (`...
*/
function stackFrameAtTest() {
if(semver.gte(process.versions.node, '18.0.0')) {
return extension === 'mjs' ? 'Module\\.test' : '(?:Module\\.)?exports\\.test';
} else {
return extension === 'mjs' ? 'Module\\.test' : 'Module\\.exports\\.test';
}
}
/**
* Describes the first stack frame for `console.trace` which is slightly different in ESM and CJS
*/
function stackFrameAtTrace(fileRe) {
return extension === 'mjs' ? `${fileRe}` : `Object\\.<anonymous> \\(${fileRe}\\)`;
}
/**
* Describe how the source path in a stack frame is expected to start.
* If generated module is ESM, node uses file:// URL, so we expect mapped original path to also be file:// to match
* On windows, when not doing file:// URIs, expect windows-style paths
*/
function stackFramePathStartsWith() {
if(extension === 'mjs') return 'file:/';
// Escape backslashes since we are returning regexp syntax
return path.parse(process.cwd()).root.replace(/\\/g, '\\\\');
// this re \((?:.*[/\\])?
}
/**
* Tests were initially written as CJS with require() calls.
* We can support require() calls in MJS tests, too, as long as we create a require() function.
* Keep both prefixes the same length so that offsets are the same
*/
function srcPrefix() {
return extension === 'mjs'
? `import {createRequire} from 'module';const require = createRequire(import.meta.url);`
: ` `;
}
//#endregion
// Assign each test a unique ID, to be used in filenames.
// Eliminates need for cache invalidation, because node ESM has no way to
// invalidate cache.
let id = 0;
let extension;
beforeEach(function() {
id++;
extension = 'js';
});
// Consolidate cleanup into a hook so that failed assertions do not leave files
// on disk.
afterEach(function() {
for(const name of [`generated`, `generated2`, `original`, `original2`]) {
for(const suffix of [``, `-separate`, `-inline`]) {
for(const ext of [`js`, `cjs`, `mjs`]) {
for(const ext2 of [``, `.map`, `.map.extra`]) {
const file = `.${name}-${id}${suffix}.${ext}${ext2}`;
fs.existsSync(file) && fs.unlinkSync(file);
}
}
}
}
});
function compareLines(actual, expected) {
assert(actual.length >= expected.length, 'got ' + actual.length + ' lines but expected at least ' + expected.length + ' lines\n' + util.inspect({actual, expected}));
for (var i = 0; i < expected.length; i++) {
// Some tests are regular expressions because the output format changed slightly between node v0.9.2 and v0.9.3
if (expected[i] instanceof RegExp) {
assert(expected[i].test(actual[i]), JSON.stringify(actual[i]) + ' does not match ' + expected[i] + '\n' + JSON.stringify({actual, expected: expected.map(v => typeof v === 'string' ? v : v.toString())}, null, 2));
} else {
assert.equal(actual[i], expected[i]);
}
}
}
function sourceMapCreators() {
return {
createEmptySourceMap,
createSourceMapWithGap,
createSingleLineSourceMap,
createSecondLineSourceMap,
createMultiLineSourceMap,
createMultiLineSourceMapWithSourcesContent
};
function createEmptySourceMap() {
return new SourceMapGenerator({
file: `.generated-${id}.${extension}`,
sourceRoot: '.'
});
}
function createSourceMapWithGap() {
var sourceMap = createEmptySourceMap();
sourceMap.addMapping({
generated: { line: 100, column: 0 },
original: { line: 100, column: 0 },
source: `.original-${id}.js`
});
return sourceMap;
}
function createSingleLineSourceMap() {
var sourceMap = createEmptySourceMap();
sourceMap.addMapping({
generated: { line: 1, column: 0 },
original: { line: 1, column: 0 },
source: `.original-${id}.js`
});
return sourceMap;
}
function createSecondLineSourceMap() {
var sourceMap = createEmptySourceMap();
sourceMap.addMapping({
generated: { line: 2, column: 0 },
original: { line: 1, column: 0 },
source: `.original-${id}.js`
});
return sourceMap;
}
function createMultiLineSourceMap() {
var sourceMap = createEmptySourceMap();
for (var i = 1; i <= 100; i++) {
sourceMap.addMapping({
generated: { line: i, column: 0 },
original: { line: 1000 + i, column: 99 + i },
source: 'line' + i + '.js'
});
}
return sourceMap;
}
function createMultiLineSourceMapWithSourcesContent() {
var sourceMap = createEmptySourceMap();
var original = new Array(1001).join('\n');
for (var i = 1; i <= 100; i++) {
sourceMap.addMapping({
generated: { line: i, column: 0 },
original: { line: 1000 + i, column: 4 },
source: `original-${id}.js`
});
original += ' line ' + i + '\n';
}
sourceMap.setSourceContent(`original-${id}.js`, original);
return sourceMap;
}
}
function rewriteExpectation(expected, generatedFilenameIn, generatedFilenameOut) {
return expected.map(v => {
if(v instanceof RegExp) return new RegExp(v.source.replace(generatedFilenameIn, generatedFilenameOut));
return v.replace(generatedFilenameIn, generatedFilenameOut);
});
}
async function compareStackTrace(sourceMap, source, expected) {
const header = srcPrefix();
// Check once with a separate source map
fs.writeFileSync(`.generated-${id}-separate.${extension}.map`, sourceMap.toString());
fs.writeFileSync(`.generated-${id}-separate.${extension}`, `${header}${namedExportDeclaration()} = function() {` +
source.join('\n') + `};//@ sourceMappingURL=.generated-${id}-separate.${extension}.map`);
let caught = false;
try {
await (await import(`./.generated-${id}-separate.${extension}`)).test();
} catch (e) {
caught = true;
compareLines(e.stack.split(/\r\n|\n/), rewriteExpectation(expected, `.generated-${id}`, `.generated-${id}-separate`));
}
if(!caught) throw new Error('expected to catch an error but none was thrown.');
// Check again with an inline source map (in a data URL)
fs.writeFileSync(`.generated-${id}-inline.${extension}`, `${header}${namedExportDeclaration()} = function() {` +
source.join('\n') + '};//@ sourceMappingURL=data:application/json;base64,' +
bufferFrom(sourceMap.toString()).toString('base64'));
caught = false;
try {
await (await import (`./.generated-${id}-inline.${extension}`)).test();
} catch (e) {
caught = true;
compareLines(e.stack.split(/\r\n|\n/), rewriteExpectation(expected, `.generated-${id}`, `.generated-${id}-inline`));
}
if(!caught) throw new Error('expected to catch an error but none was thrown.');
}
function compareStdout(done, sourceMap, source, expected) {
let header = srcPrefix();
fs.writeFileSync(`.original-${id}.js`, 'this is the original code');
fs.writeFileSync(`.generated-${id}.${extension}.map`, sourceMap.toString());
fs.writeFileSync(`.generated-${id}.${extension}`, header + source.join('\n') +
`//@ sourceMappingURL=.generated-${id}.${extension}.map`);
child_process.exec(`node ./.generated-${id}.${extension}`, function(error, stdout, stderr) {
try {
compareLines(
(stdout + stderr)
.trim()
.split(/\r\n|\n/)
// Empty lines are not relevant.
// Running in a debugger causes additional output.
.filter(function (line) { return line !== '' && line !== 'Debugger attached.' }),
expected
);
} catch (e) {
return done(e);
}
done();
});
}
function installSms() {
underTest.install({
emptyCacheBetweenOperations: true // Needed to be able to test for failure
});
}
const installSmsOnce = once(installSms);
function getTestMacros(sourceMapConstructors) {
return {normalThrow, normalThrowWithoutSourceMapSupportInstalled};
async function normalThrow() {
await compareStackTrace(sourceMapConstructors.createMultiLineSourceMap(), [
'throw new Error("test");'
], [
'Error: test',
re`^ at ${stackFrameAtTest()} \(${stackFramePathStartsWith()}(?:.*[/\\])?line1\.js:1001:101\)$`
]);
}
async function normalThrowWithoutSourceMapSupportInstalled() {
await compareStackTrace(sourceMapConstructors.createMultiLineSourceMap(), [
'throw new Error("test");'
], [
'Error: test',
re`^ at ${stackFrameAtTest()} \(${stackFramePathStartsWith()}(?:.*[/\\])?\.generated-${id}\.${extension}:1:123\)$`
]);
}
}
function describePerModuleType(fn, ...args) {
for(const ext of ['cjs', 'mjs']) {
describe(`${ext} >`, () => {
beforeEach(function() {
extension = ext;
});
fn(...args);
});
}
}
describe('Without source-map-support installed', function() {
describePerModuleType(() => {
const sourceMapConstructors = sourceMapCreators();
const macros = getTestMacros(sourceMapConstructors);
const {normalThrowWithoutSourceMapSupportInstalled} = macros;
it('normal throw without source-map-support installed', async function () {
await normalThrowWithoutSourceMapSupportInstalled();
});
});
});
function identity(v) {return v}
function addRelativePrefixToSourceMapPaths(sourceMap) {
addPrefixToSourceMapPaths(sourceMap, './');
return sourceMap;
}
function addAbsolutePrefixToSourceMapPaths(sourceMap) {
addPrefixToSourceMapPaths(sourceMap, '/root/project/');
return sourceMap;
}
function addFileUrlAbsolutePrefixToSourceMapPaths(sourceMap) {
addPrefixToSourceMapPaths(sourceMap, 'file:///root/project/');
return sourceMap;
}
function addPrefixToSourceMapPaths(sourceMap, prefix) {
function addPrefix(path) {return `${prefix}${path}`}
sourceMap.file = addPrefix(sourceMap.file);
if(sourceMap.sources) sourceMap.sources = sourceMap.sources.map(addPrefix);
return sourceMap;
}
describe('sourcemap style: relative paths sans ./ prefix, e.g. "original-1.js" >', () => {
describePerModuleType(tests, identity);
});
describe('sourcemap style: relative paths with ./ prefix, e.g. "./original-1.js" >', () => {
describePerModuleType(tests, addRelativePrefixToSourceMapPaths);
});
describe('sourcemap style: absolute paths and sourceRoot removed, e.g. "/abs/path/original-1.js" >', () => {
describePerModuleType(tests, addAbsolutePrefixToSourceMapPaths);
});
describe('sourcemap style: file urls with absolute paths and sourceRoot removed, e.g. "file:///abs/path/original-1.js" >', () => {
describePerModuleType(tests, addFileUrlAbsolutePrefixToSourceMapPaths);
});
function tests(sourceMapPostprocessor) {
// let createEmptySourceMap, createMultiLineSourceMap, createMultiLineSourceMapWithSourcesContent, createSecondLineSourceMap, createSingleLineSourceMap, createSourceMapWithGap})
const sourceMapConstructors = mapValues(sourceMapCreators(), v => flow(v, sourceMapPostprocessor));
const {createEmptySourceMap, createMultiLineSourceMap, createMultiLineSourceMapWithSourcesContent, createSecondLineSourceMap, createSingleLineSourceMap, createSourceMapWithGap} = sourceMapConstructors;
const {normalThrow} = getTestMacros(sourceMapConstructors);
// Run as a hook to ensure it runs even when we execute a subset of tests
before(installSmsOnce);
it('normal throw', async function() {
await normalThrow();
});
/* The following test duplicates some of the code in
* `normal throw` but triggers file read failure.
*/
it('fs.readFileSync failure', async function() {
await compareStackTrace(createMultiLineSourceMap(), [
'var fs = require("fs");',
'var rfs = fs.readFileSync;',
'fs.readFileSync = function() {',
' throw new Error("no rfs for you");',
'};',
'try {',
' throw new Error("test");',
'} finally {',
' fs.readFileSync = rfs;',
'}'
], [
'Error: test',
re`^ at ${stackFrameAtTest()} \(${stackFramePathStartsWith()}(?:.*[/\\])?line7\.js:1007:107\)$`
]);
});
it('throw inside function', async function() {
await compareStackTrace(createMultiLineSourceMap(), [
'function foo() {',
' throw new Error("test");',
'}',
'foo();'
], [
'Error: test',
re`^ at foo \(${stackFramePathStartsWith()}(?:.*[/\\])?line2\.js:1002:102\)$`,
re`^ at ${stackFrameAtTest()} \(${stackFramePathStartsWith()}(?:.*[/\\])?line4\.js:1004:104\)$`
]);
});
it('throw inside function inside function', async function() {
await compareStackTrace(createMultiLineSourceMap(), [
'function foo() {',
' function bar() {',
' throw new Error("test");',
' }',
' bar();',
'}',
'foo();'
], [
'Error: test',
re`^ at bar \(${stackFramePathStartsWith()}(?:.*[/\\])?line3\.js:1003:103\)$`,
re`^ at foo \(${stackFramePathStartsWith()}(?:.*[/\\])?line5\.js:1005:105\)$`,
re`^ at ${stackFrameAtTest()} \(${stackFramePathStartsWith()}(?:.*[/\\])?line7\.js:1007:107\)$`
]);
});
it('eval', async function() {
await compareStackTrace(createMultiLineSourceMap(), [
'eval("throw new Error(\'test\')");'
], [
'Error: test',
re`^ at eval \(eval at (<anonymous>|exports\.test|test) \(${stackFramePathStartsWith()}(?:.*[/\\])?line1\.js:1001:101\)`,
re`^ at ${stackFrameAtTest()} \(${stackFramePathStartsWith()}(?:.*[/\\])?line1\.js:1001:101\)$`
]);
});
it('eval inside eval', async function() {
await compareStackTrace(createMultiLineSourceMap(), [
'eval("eval(\'throw new Error(\\"test\\")\')");'
], [
'Error: test',
re`^ at eval \(eval at (<anonymous>|exports\.test|test) \(eval at (<anonymous>|exports\.test|test) \(${stackFramePathStartsWith()}(?:.*[/\\])?line1\.js:1001:101\)`,
re`^ at eval \(eval at (<anonymous>|exports\.test|test) \(${stackFramePathStartsWith()}(?:.*[/\\])?line1\.js:1001:101\)`,
re`^ at ${stackFrameAtTest()} \(${stackFramePathStartsWith()}(?:.*[/\\])?line1\.js:1001:101\)$`
]);
});
it('eval inside function', async function() {
await compareStackTrace(createMultiLineSourceMap(), [
'function foo() {',
' eval("throw new Error(\'test\')");',
'}',
'foo();'
], [
'Error: test',
re`^ at eval \(eval at foo \(${stackFramePathStartsWith()}(?:.*[/\\])?line2\.js:1002:102\)`,
re`^ at foo \(${stackFramePathStartsWith()}(?:.*[/\\])?line2\.js:1002:102\)`,
re`^ at ${stackFrameAtTest()} \(${stackFramePathStartsWith()}(?:.*[/\\])?line4\.js:1004:104\)$`
]);
});
it('eval with sourceURL', async function() {
await compareStackTrace(createMultiLineSourceMap(), [
'eval("throw new Error(\'test\')//@ sourceURL=sourceURL.js");'
], [
'Error: test',
/^ at eval \(sourceURL\.js:1:7\)$/,
re`^ at ${stackFrameAtTest()} \(${stackFramePathStartsWith()}(?:.*[/\\])?line1\.js:1001:101\)$`
]);
});
it('eval with sourceURL inside eval', async function() {
await compareStackTrace(createMultiLineSourceMap(), [
'eval("eval(\'throw new Error(\\"test\\")//@ sourceURL=sourceURL.js\')");'
], [
'Error: test',
/^ at eval \(sourceURL\.js:1:7\)$/,
re`^ at eval \(eval at (<anonymous>|exports.test|test) \(${stackFramePathStartsWith()}(?:.*[/\\])?line1\.js:1001:101\)`,
re`^ at ${stackFrameAtTest()} \(${stackFramePathStartsWith()}(?:.*[/\\])?line1\.js:1001:101\)$`
]);
});
it('native function', async function() {
await compareStackTrace(createSingleLineSourceMap(), [
'[1].map(function(x) { throw new Error(x); });'
], [
'Error: 1',
re`${stackFramePathStartsWith()}(?:.*[/\\])?.original-${id}.js`,
/at Array\.map \((native|<anonymous>)\)/
]);
});
it('function constructor', async function() {
await compareStackTrace(createMultiLineSourceMap(), [
'throw new Function(")");'
], [
/SyntaxError: Unexpected token '?\)'?/,
]);
});
if(semver.gte(process.version, '18.0.0')) {
it('async stack frames: async, Promise.allSettled', async function() {
await compareStackTrace(createMultiLineSourceMap(), [
'async function foo() { throw (await bar())[0].reason; }',
'async function bar() { return await Promise.allSettled([baz()]) }',
'async function baz() { await null; throw new Error("test"); }',
'return foo();'
], [
'Error: test',
re`^ at baz \(${stackFramePathStartsWith()}(?:.*[/\\])?line3.js:1003:103\)$`,
re`^ at async Promise\.allSettled \(index 0\)$`,
re`^ at async bar \(${stackFramePathStartsWith()}(?:.*[/\\])?line2.js:1002:102\)$`,
re`^ at async foo \(${stackFramePathStartsWith()}(?:.*[/\\])?line1.js:1001:101\)$`
]);
});
} else {
it('Verify node does not support Promise.allSettled stack frames. When this test starts breaking, we need to start testing for Promise.allSettled.', async () => {
// results1/driver1 is not strictly necessary to test allSettled; it is here to remind myself how to correctly get Promise.* methods to appear in a stack trace.
let result1;
await driver1().catch(e => result1 = e);
assert.match(result1.stack, /\bPromise\.all\b/);
// Copied from V8 tests: https://github.com/v8/v8/commit/89ed081c176e286f9d65f3821d43f568cd56a035#diff-1a0a032688d7546dcfe5730eaab2854fb1b8dab656d8bb940dffc71b7b975aae
async function fine() { }
async function thrower() {
await fine();
throw new Error();
}
async function driver1() {
return await Promise.all([fine(), fine(), thrower(), thrower()]);
}
async function driver2() {
return await Promise.allSettled([fine(), fine(), thrower(), thrower()]);
}
const results2 = await driver2();
assert.equal(results2[2].status, 'rejected');
assert.doesNotMatch(results2[2].reason.stack, /\bPromise\.allSettled\b/);
});
}
it('async stack frames: async, Promise.all'/*Promise.allSettled*/, async function() {
await compareStackTrace(createMultiLineSourceMap(), [
// Add once node upgrades to v8 10.2, where this was added: https://github.com/v8/v8/commit/89ed081c176e286f9d65f3821d43f568cd56a035
// 'async function foo() { return await bar(); }',
// 'async function bar() { return await Promise.allSettled([baz()]) }',
'async function foo() { return await bar(); }',
'async function bar() { await Promise.all([baz()]) }',
'async function baz() { await null; throw new Error("test"); }',
'return foo();'
], [
'Error: test',
re`^ at baz \(${stackFramePathStartsWith()}(?:.*[/\\])?line3.js:1003:103\)$`,
re`^ at async Promise\.all \(index 0\)$`,
re`^ at async bar \(${stackFramePathStartsWith()}(?:.*[/\\])?line2.js:1002:102\)$`,
re`^ at async foo \(${stackFramePathStartsWith()}(?:.*[/\\])?line1.js:1001:101\)$`
]);
});
it('async stack frames: Promise.any', async function() {
// node 14 and older does not have Promise.any
if(semver.lt(process.versions.node, '16.0.0')) return this.skip();
await compareStackTrace(createMultiLineSourceMap(), [
// Add once node upgrades to v8 10.2, where this was added: https://github.com/v8/v8/commit/89ed081c176e286f9d65f3821d43f568cd56a035
// 'async function foo() { return await bar(); }',
// 'async function bar() { return await Promise.allSettled([baz()]) }',
'async function foo() { return await bar(); }',
'async function bar() { await Promise.any([baz()]); }',
'async function baz() { await null; throw new Error("test"); }',
'return foo().catch(e => { throw e.errors[0] })'
], [
'Error: test',
re`^ at baz \(${stackFramePathStartsWith()}(?:.*[/\\])?line3.js:1003:103\)$`,
re`^ at async Promise\.any \(index 0\)$`,
re`^ at async bar \(${stackFramePathStartsWith()}(?:.*[/\\])?line2.js:1002:102\)$`,
re`^ at async foo \(${stackFramePathStartsWith()}(?:.*[/\\])?line1.js:1001:101\)$`
]);
});
it('wasm stack frames', async function() {
const wasmFrame = semver.gte(process.versions.node, '16.0.0')
? String.raw`wasm:\/\/wasm\/c2de0ab2:wasm-function\[1\]:0x3b`
: semver.gte(process.versions.node, '14.0.0')
? String.raw`call_js_function \(<anonymous>:wasm-function\[1\]:0x3b\)`
// Node 12
: String.raw`wasm-function\[1\]:0x3b`;
await compareStackTrace(createMultiLineSourceMap(), [
'return require("./test-fixtures/wasm/wasm.js").call_js_function(() => { throw new Error("test"); });'
], [
'Error: test',
re`^ at ${stackFramePathStartsWith()}(?:.*[/\\])?line1.js:1001:101$`,
re`^ at ${wasmFrame}$`,
re`^ at Object\.exports\.call_js_function \(.*[/\\]wasm\.js:13:24\)$`,
]);
});
it('throw with empty source map', async function() {
await compareStackTrace(createEmptySourceMap(), [
'throw new Error("test");'
], [
'Error: test',
re`^ at ${stackFrameAtTest()} \(${stackFramePathStartsWith()}(?:.*[/\\])?\.generated-${id}.${extension}:1:123\)$`
]);
});
it('throw in Timeout with empty source map', function(done) {
compareStdout(done, createEmptySourceMap(), [
'require("./source-map-support").install();',
'setTimeout(function () {',
' throw new Error("this is the error")',
'})'
], [
re`${stackFramePathStartsWith()}(?:.*[/\\])?.generated-${id}.${extension}:3$`,
' throw new Error("this is the error")',
/^ \^$/,
'Error: this is the error',
re`^ at ((null)|(Timeout))\._onTimeout \(${stackFramePathStartsWith()}(?:.*[/\\])?.generated-${id}\.${extension}:3:11\)$`
]);
});
it('throw with source map with gap', async function() {
await compareStackTrace(createSourceMapWithGap(), [
'throw new Error("test");'
], [
'Error: test',
re`^ at ${stackFrameAtTest()} \(${stackFramePathStartsWith()}(?:.*[/\\])?\.generated-${id}\.${extension}:1:123\)$`
]);
});
it('sourcesContent with data URL', async function() {
await compareStackTrace(createMultiLineSourceMapWithSourcesContent(), [
'throw new Error("test");'
], [
'Error: test',
re`^ at ${stackFrameAtTest()} \(${stackFramePathStartsWith()}(?:.*[/\\])?original-${id}\.js:1001:5\)$`
]);
});
it('finds the last sourceMappingURL', async function() {
await compareStackTrace(createMultiLineSourceMapWithSourcesContent(), [
'//# sourceMappingURL=missing.map.js', // NB: compareStackTrace adds another source mapping.
'throw new Error("test");'
], [
'Error: test',
re`^ at ${stackFrameAtTest()} \(${stackFramePathStartsWith()}(?:.*[/\\])?original-${id}\.js:1002:5\)$`
]);
});
it('maps original name from source', async function() {
var sourceMap = createEmptySourceMap();
sourceMap.addMapping({
generated: { line: 2, column: 8 },
original: { line: 1000, column: 10 },
source: `.original-${id}.js`,
});
sourceMap.addMapping({
generated: { line: 4, column: 0 },
original: { line: 1002, column: 1 },
source: `.original-${id}.js`,
name: "myOriginalName"
});
await compareStackTrace(sourceMap, [
'function foo() {',
' throw new Error("test");',
'}',
'foo();'
], [
'Error: test',
re`^ at myOriginalName \(${stackFramePathStartsWith()}(?:.*[/\\])?\.original-${id}.js:1000:11\)$`,
re`^ at ${stackFrameAtTest()} \(${stackFramePathStartsWith()}(?:.*[/\\])?\.original-${id}.js:1002:2\)$`
]);
});
it('default options', function(done) {
compareStdout(done, createSecondLineSourceMap(), [
'',
'function foo() { throw new Error("this is the error"); }',
'require("./source-map-support").install();',
'process.nextTick(foo);',
'process.nextTick(function() { process.exit(1); });'
], [
re`${stackFramePathStartsWith()}(?:.*[/\\])?.original-${id}\.js:1$`,
'this is the original code',
'^',
'Error: this is the error',
re`^ at foo \(${stackFramePathStartsWith()}(?:.*[/\\])?\.original-${id}\.js:1:1\)$`
]);
});
it('handleUncaughtExceptions is true', function(done) {
compareStdout(done, createSecondLineSourceMap(), [
'',
'function foo() { throw new Error("this is the error"); }',
'require("./source-map-support").install({ handleUncaughtExceptions: true });',
'process.nextTick(foo);'
], [
re`${stackFramePathStartsWith()}(?:.*[/\\])?.original-${id}\.js:1$`,
'this is the original code',
'^',
'Error: this is the error',
re`^ at foo \(${stackFramePathStartsWith()}(?:.*[/\\])?\.original-${id}\.js:1:1\)$`
]);
});
it('handleUncaughtExceptions is false', function(done) {
compareStdout(done, createSecondLineSourceMap(), [
'',
'function foo() { throw new Error("this is the error"); }',
'require("./source-map-support").install({ handleUncaughtExceptions: false });',
'process.nextTick(foo);'
], [
re`${stackFramePathStartsWith()}(?:.*[/\\])?.generated-${id}.${extension}:2$`,
'function foo() { throw new Error("this is the error"); }',
' ^',
'Error: this is the error',
re`^ at foo \(${stackFramePathStartsWith()}(?:.*[/\\])?.original-${id}\.js:1:1\)$`
]);
});
it('default options with empty source map', function(done) {
compareStdout(done, createEmptySourceMap(), [
'',
'function foo() { throw new Error("this is the error"); }',
'require("./source-map-support").install();',
'process.nextTick(foo);'
], [
re`${stackFramePathStartsWith()}(?:.*[/\\])?.generated-${id}.${extension}:2$`,
'function foo() { throw new Error("this is the error"); }',
' ^',
'Error: this is the error',
re`^ at foo \(${stackFramePathStartsWith()}(?:.*[/\\])?.generated-${id}.${extension}:2:24\)$`
]);
});
it('default options with source map with gap', function(done) {
compareStdout(done, createSourceMapWithGap(), [
'',
'function foo() { throw new Error("this is the error"); }',
'require("./source-map-support").install();',
'process.nextTick(foo);'
], [
re`${stackFramePathStartsWith()}(?:.*[/\\])?.generated-${id}.${extension}:2$`,
'function foo() { throw new Error("this is the error"); }',
' ^',
'Error: this is the error',
re`^ at foo \(${stackFramePathStartsWith()}(?:.*[/\\])?.generated-${id}.${extension}:2:24\)$`
]);
});
it('specifically requested error source', function(done) {
compareStdout(done, createSecondLineSourceMap(), [
'',
'function foo() { throw new Error("this is the error"); }',
'var sms = require("./source-map-support");',
'sms.install({ handleUncaughtExceptions: false });',
'process.on("uncaughtException", function (e) { console.log("SRC:" + sms.getErrorSource(e)); });',
'process.nextTick(foo);'
], [
re`^SRC:.*[/\\]\.original-${id}\.js:1$`,
'this is the original code',
'^'
]);
});
it('sourcesContent', function(done) {
compareStdout(done, createMultiLineSourceMapWithSourcesContent(), [
'',
'function foo() { throw new Error("this is the error"); }',
'require("./source-map-support").install();',
'process.nextTick(foo);',
'process.nextTick(function() { process.exit(1); });'
], [
re`${stackFramePathStartsWith()}(?:.*[/\\])?original-${id}\.js:1002$`,
' line 2',
' ^',
'Error: this is the error',
re`^ at foo \(${stackFramePathStartsWith()}(?:.*[/\\])?original-${id}\.js:1002:5\)$`
]);
});
it('missing source maps should also be cached', function(done) {
compareStdout(done, createSingleLineSourceMap(), [
'',
'var count = 0;',
'function foo() {',
' console.log(new Error("this is the error").stack.split("\\n").slice(0, 2).join("\\n"));',
'}',
'require("./source-map-support").install({',
' overrideRetrieveSourceMap: true,',
' retrieveSourceMap: function(name) {',
' if (/\\.generated-\\d+\\.(js|cjs|mjs)$/.test(name)) count++;',
' return null;',
' }',
'});',
'process.nextTick(foo);',
'process.nextTick(foo);',
'process.nextTick(function() { console.log(count); });',
], [
'Error: this is the error',
re`^ at foo \(${stackFramePathStartsWith()}(?:.*[/\\])?.generated-${id}.${extension}:4:15\)$`,
'Error: this is the error',
re`^ at foo \(${stackFramePathStartsWith()}(?:.*[/\\])?.generated-${id}.${extension}:4:15\)$`,
'1', // The retrieval should only be attempted once
]);
});
it('should consult all retrieve source map providers', function(done) {
// TODO are we supposed to be resolving this URL to absolute? Or should we test that non-absolute is supported?
// Test in vanilla source-map-support
let originalPath = path.resolve(`.original-${id}.js`);
if(extension === 'mjs') originalPath = pathToFileURL(originalPath).toString();
compareStdout(done, createSingleLineSourceMap(), [
'',
'var count = 0;',
'function foo() {',
' console.log(new Error("this is the error").stack.split("\\n").slice(0, 2).join("\\n"));',
'}',
'require("./source-map-support").install({',
' retrieveSourceMap: function(name) {',
` if (/\\.generated-${id}\\.${extension}$/.test(name)) count++;`,
' return undefined;',
' }',
'});',
'require("./source-map-support").install({',
' retrieveSourceMap: function(name) {',
` if (/\\.generated-${id}\\.${extension}$/.test(name)) {`,
' count++;',
' return ' + JSON.stringify({url: originalPath, map: createMultiLineSourceMapWithSourcesContent().toJSON()}) + ';',
' }',
' }',
'});',
'process.nextTick(foo);',
'process.nextTick(foo);',
'process.nextTick(function() { console.log(count); });',
], [
'Error: this is the error',
re`^ at foo \(${stackFramePathStartsWith()}(?:.*[/\\])?original-${id}\.js:1004:5\)$`,
'Error: this is the error',
re`^ at foo \(${stackFramePathStartsWith()}(?:.*[/\\])?original-${id}\.js:1004:5\)$`,
'1', // The retrieval should only be attempted once
]);
});
it('should allow for runtime inline source maps', function(done) {
var sourceMap = createMultiLineSourceMapWithSourcesContent();
fs.writeFileSync('.generated.jss', 'foo');
compareStdout(function(err) {
fs.unlinkSync('.generated.jss');
done(err);
}, createSingleLineSourceMap(), [
'require("./source-map-support").install({',
' hookRequire: true',
'});',
'require.extensions[".jss"] = function(module, filename) {',
' module._compile(',
JSON.stringify([
'',
'var count = 0;',
'function foo() {',
' console.log(new Error("this is the error").stack.split("\\n").slice(0, 2).join("\\n"));',
'}',
'process.nextTick(foo);',
'process.nextTick(foo);',
'process.nextTick(function() { console.log(count); });',
'//@ sourceMappingURL=data:application/json;charset=utf8;base64,' + bufferFrom(sourceMap.toString()).toString('base64')
].join('\n')),
', filename);',
'};',
'require("./.generated.jss");',
], [
'Error: this is the error',
re`^ at foo \(.*[/\\]original-${id}\.js:1004:5\)$`,
'Error: this is the error',
re`^ at foo \(.*[/\\]original-${id}\.js:1004:5\)$`,
'0', // The retrieval should only be attempted once
]);
});
/* The following test duplicates some of the code in
* `compareStackTrace` but appends a charset to the
* source mapping url.
*/
it('finds source maps with charset specified', async function() {
var sourceMap = createMultiLineSourceMap()
var source = [ 'throw new Error("test");' ];
var expected = [
'Error: test',
re`^ at ${stackFrameAtTest()} \(${stackFramePathStartsWith()}(?:.*[/\\])?line1\.js:1001:101\)$`
];
fs.writeFileSync(`.generated-${id}.${extension}`, `${namedExportDeclaration()} = function() {` +
source.join('\n') + '};//@ sourceMappingURL=data:application/json;charset=utf8;base64,' +
bufferFrom(sourceMap.toString()).toString('base64'));
try {
(await import(`./.generated-${id}.${extension}`)).test();
} catch (e) {
compareLines(e.stack.split(/\r\n|\n/), expected);
}
});
/* The following test duplicates some of the code in
* `compareStackTrace` but appends some code and a
* comment to the source mapping url.
*/
it('allows code/comments after sourceMappingURL', async function() {
var sourceMap = createMultiLineSourceMap()
var source = [ 'throw new Error("test");' ];
var expected = [
'Error: test',
re`^ at ${stackFrameAtTest()} \(${stackFramePathStartsWith()}(?:.*[/\\])?line1\.js:1001:101\)$`
];
fs.writeFileSync(`.generated-${id}.${extension}`, `${namedExportDeclaration()} = function() {` +
source.join('\n') + '};//# sourceMappingURL=data:application/json;base64,' +
bufferFrom(sourceMap.toString()).toString('base64') +
'\n// Some comment below the sourceMappingURL\nvar foo = 0;');
try {
(await import(`./.generated-${id}.${extension}`)).test();
} catch (e) {
compareLines(e.stack.split(/\r\n|\n/), expected);
}
});
it('handleUncaughtExceptions is true with existing listener', function(done) {
var source = [
'process.on("uncaughtException", function() { /* Silent */ });',
'function foo() { throw new Error("this is the error"); }',
'require("./source-map-support").install();',
'process.nextTick(foo);',
`//@ sourceMappingURL=.generated-${id}.${extension}.map`
];
fs.writeFileSync(`.original-${id}.js`, 'this is the original code');
fs.writeFileSync(`.generated-${id}.${extension}.map`, createSingleLineSourceMap().toString());
fs.writeFileSync(`.generated-${id}.${extension}`, source.join('\n'));
child_process.exec(`node ./.generated-${id}.${extension}`, function(error, stdout, stderr) {
assert.equal((stdout + stderr).trim(), '');
done();
});
});
it('normal console.trace', function(done) {
compareStdout(done, createMultiLineSourceMap(), [
'require("./source-map-support").install();',
'console.trace("test");'
], [
'Trace: test',
re`^ at ${stackFrameAtTrace(String.raw`(?:.*[/\\])?line2\.js:1002:102`)}$`
]);
});
it('supports multiple instances', function(done) {
var sourceMap = createEmptySourceMap();
sourceMap.addMapping({
generated: { line: 1, column: 0 },
original: { line: 1, column: 0 },
source: `.original2-${id}.js`
});
fs.writeFileSync(`.generated2-${id}.${extension}.map.extra`, sourceMap.toString());
fs.writeFileSync(`.generated2-${id}.${extension}`, [
`${namedExportDeclaration()} = function test() { throw new Error("this is the error"); }`,
`//@ sourceMappingURL=.generated2-${id}.${extension}.map`
].join('\n'));
fs.writeFileSync(`.original2-${id}.js`, 'this is some other original code');
compareStdout(done, createEmptySourceMap(), [
'(async function() {',
' require("./source-map-support").install({',
' retrieveFile: function(path) {',
' var fs = require("fs");',
' var url = require("url");',
' try { path = url.fileURLToPath(path) } catch {}',
' if (fs.existsSync(path + ".extra")) {',
' return fs.readFileSync(path + ".extra", "utf8");',
' }',
' }',
' });',
` var {test} = await import("./.generated2-${id}.${extension}");`,
' delete require.cache[require.resolve("./source-map-support")];',
' require("./source-map-support").install();',
' process.nextTick(test);',
' process.nextTick(function() { process.exit(1); });',
'})();'
], [
re`${stackFramePathStartsWith()}(?:.*[/\\])?.original2-${id}\.js:1$`,
'this is some other original code',
'^',
'Error: this is the error',
re`^ at test \(${stackFramePathStartsWith()}(?:.*[/\\])?.original2-${id}\.js:1:1\)$`
]);
});
}
describe('redirects require() of "source-map-support" to this module', function() {
before(installSmsOnce);
it('redirects', async function() {
assert.strictEqual(require.resolve('source-map-support'), require.resolve('.'));
assert.strictEqual(require.resolve('source-map-support/register'), require.resolve('./register'));
assert.strictEqual(require('source-map-support'), require('.'));
});
it('emits notifications', async function() {
let onConflictingLibraryRedirectCalls = [];
let onConflictingLibraryRedirectCalls2 = [];
underTest.install({
onConflictingLibraryRedirect(request, parent, isMain, redirectedRequest) {
onConflictingLibraryRedirectCalls.push([...arguments]);
}
});
underTest.install({
onConflictingLibraryRedirect(request, parent, isMain, redirectedRequest) {
onConflictingLibraryRedirectCalls2.push([...arguments]);
}
});
require.resolve('source-map-support');
assert.strictEqual(onConflictingLibraryRedirectCalls.length, 1);
assert.strictEqual(onConflictingLibraryRedirectCalls2.length, 1);
for(const args of [onConflictingLibraryRedirectCalls[0], onConflictingLibraryRedirectCalls2[0]]) {
const [request, parent, isMain, options, redirectedRequest] = args;
assert.strictEqual(request, 'source-map-support');