forked from evanw/source-map-visualization
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode.js
2398 lines (2153 loc) · 79.7 KB
/
code.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
/***********************************************
** Copyright (C) Evan Wallace <@evanw> **
** **
** github.com/evanw/source-map-visualization **
***********************************************/
/* $$\ $$\ $$$$$$\ $$$$$$$$\ $$$$$$\ $$$$$$$\ $$$$$$$\
$$ | $$ $$ __$$\\____$$ $$ __$$\$$ __$$\$$ __$$\
$$ | $$ $$ / $$ | $$ /$$ / $$ $$ | $$ $$ | $$ |
$$$$$$$$ $$$$$$$$ | $$ / $$$$$$$$ $$$$$$$ $$ | $$ |
$$ __$$ $$ __$$ | $$ / $$ __$$ $$ __$$<$$ | $$ |
$$ | $$ $$ | $$ |$$ / $$ | $$ $$ | $$ $$ | $$ |
$$ | $$ $$ | $$ $$$$$$$$\$$ | $$ $$ | $$ $$$$$$$ |
\__| \__\__| \__\________\__| \__\__| \__\_______/
$$$$$$\ $$\ $$\$$$$$$$$\ $$$$$$\ $$$$$$$\
$$ __$$\$$ | $$ $$ _____$$ __$$\$$ __$$\
$$ / $$ $$ | $$ $$ | $$ / $$ $$ | $$ |
$$$$$$$$ $$$$$$$$ $$$$$\ $$$$$$$$ $$ | $$ |
$$ __$$ $$ __$$ $$ __| $$ __$$ $$ | $$ |
$$ | $$ $$ | $$ $$ | $$ | $$ $$ | $$ |
$$ | $$ $$ | $$ $$$$$$$$\$$ | $$ $$$$$$$ |
\__| \__\__| \__\________\__| \__\_______/
---- ☢CONTINUE AT YOUR OWN RISK ☢----
-------------------------
HISTORICAL CONTEXT:
https://github.com/metaory/source-map-visualization/blob/f3e9dfec20e7bfd9625d03dd0d427affa74a9c43/code.js
https://github.com/evanw/source-map-visualization/compare/gh-pages...metaory:source-map-visualization:gh-pages
https://github.com/evanw/source-map-visualization/compare/gh-pages...metaory:source-map-visualization:gh-pages#diff-b513959b106b2abec77a76ef5740ce223aeb8d239bfc6f7c7aa850f0390b176e */
/* ##################################################### */
const [
loadRemoteBtn,
remoteUrl,
dragTarget,
uploadFiles,
loadExample,
loadExampleURL,
promptText,
errorText,
originalStatus,
generatedStatus,
] = [
'#loadRemote',
'#remoteUrl',
'#dragTarget',
'#uploadFiles',
'#loadExample',
'#loadExampleURL',
'#promptText',
'#errorText',
'#originalStatus',
'#generatedStatus',
].map(document.querySelector.bind(document))
let dragging = 0
let filesInput
const isFilesDragEvent = e =>
e.dataTransfer?.types && Array.prototype.indexOf.call(e.dataTransfer.types, 'Files') !== -1
loadExampleURL.onclick = () => {
window.location.search = 'url=https://github.githubassets.com/assets/settings-fe0ee97d5327.js.map'
}
////////////////////////////////////////////////////////////////////////////////
document.ondragover = e => e.preventDefault()
document.ondragenter = e => {
e.preventDefault()
if (!isFilesDragEvent(e)) return
dragTarget.style.display = 'block'
dragging++
}
document.ondragleave = e => {
e.preventDefault()
if (!isFilesDragEvent(e)) return
if (--dragging === 0) dragTarget.style.display = 'none'
}
document.ondrop = e => {
e.preventDefault()
dragTarget.style.display = 'none'
dragging = 0
if (e.dataTransfer?.files) startLoading(e.dataTransfer.files)
}
uploadFiles.onclick = () => {
if (filesInput) document.body.removeChild(filesInput)
filesInput = document.createElement('input')
filesInput.type = 'file'
filesInput.accept = '.map'
filesInput.multiple = true
filesInput.style.display = 'none'
document.body.appendChild(filesInput)
filesInput.click()
filesInput.onchange = () => startLoading(filesInput.files)
}
loadRemoteBtn.onclick = async () => {
const url = remoteUrl?.value
if (!url) return
window.location.search = `?url=${url}`
const code = await fetch(url).then(r => r.text())
return finishLoading('', code)
}
// Add paste handler for remoteUrl input
remoteUrl.addEventListener('paste', e => {
const url = e.clipboardData.getData('text/plain')
e.target.value = url
e.preventDefault()
})
loadExample.onclick = () => finishLoading(exampleJS, exampleMap)
const isProbablySourceMap = file => file.name.endsWith('.map') || file.name.endsWith('.json')
const loadFile = file =>
new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onerror = reject
reader.onloadend = () => resolve(reader.result)
reader.readAsText(file)
})
const resetLoadingState = () => {
promptText.style.display = 'block'
// toolbar.style.display = 'none'
// statusBar.style.display = 'none'
canvas.style.display = 'none'
}
const showLoadingError = text => {
resetLoadingState()
errorText.style.display = 'block'
errorText.textContent = text
}
async function finishEmbeddedSourceMap(code, file) {
let url
// Check for both "//" and "/*" comments. This is mostly done manually
// instead of doing it all with a regular expression because Firefox's
// regular expression engine crashes with an internal error when the
// match is too big.
const regex = /\/([*/])[#@] *sourceMappingURL=/g
let currentMatch = regex.exec(code)
while (currentMatch !== null) {
const start = currentMatch.index + currentMatch[0].length
const n = code.length
let end = start
while (end < n && code.charCodeAt(end) > 32) {
end++
}
if (end > start && (currentMatch[1] === '/' || code.slice(end).indexOf('*/') > 0)) {
url = code.slice(start, end)
break
}
currentMatch = regex.exec(code)
}
const showFetchError = (e, match = []) =>
showLoadingError(
`Failed to parse the URL in the "/${match[1]}# sourceMappingURL=" comment: ${e?.message || e}`,
)
const fetchUrlMap = url =>
fetch(new URL(url))
.then(r => r.text())
.catch(showFetchError)
// Check for a non-empty data URL payload
if (url) {
const map = await fetchUrlMap(url)
if (!map) return
return finishLoading(code, map)
}
if (file && isProbablySourceMap(file)) {
// Allow loading a source map without a generated file because why not
return finishLoading('', code)
}
const c = file?.name?.endsWith('ss') ? '*' : '/'
// biome-ignore format: hellscape
return showLoadingError(`Failed to find an embedded "/${c}# sourceMappingURL=" comment in the ${file ? 'imported file' : 'pasted text'}.`)
}
async function startLoading(files) {
switch (files.length) {
case 1: {
const [file0] = files
const code = await loadFile(file0)
return finishEmbeddedSourceMap(code, file0)
}
case 2: {
const file0 = files[0]
const file1 = files[1]
const pair = []
if (isProbablySourceMap(file0)) {
pair[0] = file1
pair[1] = file0
}
// return finishLoading(code, map)
if (isProbablySourceMap(file1)) {
pair[0] = file0
pair[1] = file1
}
if (pair.length) {
const code = await loadFile(pair[0])
const map = await loadFile(pair[1])
return finishLoading(code, map)
}
return showLoadingError(
'The source map file must end in either ".map" or ".json" to be detected.',
)
}
}
return showLoadingError('Please import either 1 or 2 files.')
}
document.body.addEventListener('paste', e => {
// Don't intercept paste events on input elements
if (e.target.tagName === 'INPUT') {
return
}
e.preventDefault()
const code = e.clipboardData.getData('text/plain')
finishEmbeddedSourceMap(code, null)
})
// Accelerate VLQ decoding with a lookup table
const vlqTable = new Uint8Array(128)
// biome-ignore lint/nursery/noSecrets: hellscape
const vlqChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (let i = 0; i < vlqTable.length; i++) vlqTable[i] = 0xff
for (let i = 0; i < vlqChars.length; i++) vlqTable[vlqChars.charCodeAt(i)] = i
function decodeError(text, i) {
const error = `Invalid VLQ data at index ${i}: ${text}`
showLoadingError(
`The "mappings" field of the imported source map contains invalid data. ${error}.`,
)
throw new Error(error)
}
function decodeVLQ(mappings, i) {
let shift = 0
let vlq = 0
let inner = i
// Scan over the input
while (true) {
// Read a byte
if (inner >= mappings.length) decodeError('Unexpected early end of mapping data', inner)
const c = mappings.charCodeAt(inner)
if ((c & 0x7f) !== c)
decodeError(`Invalid mapping character: ${JSON.stringify(String.fromCharCode(c))}`, inner)
const index = vlqTable[c & 0x7f]
if (index === 0xff)
decodeError(`Invalid mapping character: ${JSON.stringify(String.fromCharCode(c))}`, inner)
inner++
// Decode the byte
vlq |= (index & 31) << shift
shift += 5
// Stop if there's no continuation bit
if ((index & 32) === 0) break
}
// Recover the signed value
return [vlq & 1 ? -(vlq >> 1) : vlq >> 1, inner]
}
function decodeMappings(mappings, sourcesCount, namesCount) {
const n = mappings.length
let data = new Int32Array(1024)
let dataLength = 0
let generatedLine = 0
let generatedLineStart = 0
let generatedColumn = 0
let originalSource = 0
let originalLine = 0
let originalColumn = 0
let originalName = 0
let needToSortGeneratedColumns = false
let i = 0
while (i < n) {
let c = mappings.charCodeAt(i)
// Handle a line break
if (c === 59 /* ; */) {
// The generated columns are very rarely out of order. In that case,
// sort them with insertion since they are very likely almost ordered.
if (needToSortGeneratedColumns) {
for (let j = generatedLineStart + 6; j < dataLength; j += 6) {
const genL = data[j]
const genC = data[j + 1]
const origS = data[j + 2]
const origL = data[j + 3]
const origC = data[j + 4]
const origN = data[j + 5]
let k = j - 6
for (; k >= generatedLineStart && data[k + 1] > genC; k -= 6) {
data[k + 6] = data[k]
data[k + 7] = data[k + 1]
data[k + 8] = data[k + 2]
data[k + 9] = data[k + 3]
data[k + 10] = data[k + 4]
data[k + 11] = data[k + 5]
}
data[k + 6] = genL
data[k + 7] = genC
data[k + 8] = origS
data[k + 9] = origL
data[k + 10] = origC
data[k + 11] = origN
}
}
generatedLine++
generatedColumn = 0
generatedLineStart = dataLength
needToSortGeneratedColumns = false
i++
continue
}
// Ignore stray commas
if (c === 44 /* , */) {
i++
continue
}
// Read the generated column
const [generatedColumnDelta, ii1] = decodeVLQ(mappings, i)
i = ii1
if (generatedColumnDelta < 0) needToSortGeneratedColumns = true
generatedColumn += generatedColumnDelta
if (generatedColumn < 0) decodeError(`Invalid generated column: ${generatedColumn}`, i)
// It's valid for a mapping to have 1, 4, or 5 variable-length fields
let isOriginalSourceMissing = true
let isOriginalNameMissing = true
if (i < n) {
c = mappings.charCodeAt(i)
if (c === 44 /* , */) {
i++
} else if (c !== 59 /* ; */) {
isOriginalSourceMissing = false
// Read the original source
const [originalSourceDelta, ii2] = decodeVLQ(mappings, i)
i = ii2
originalSource += originalSourceDelta
if (originalSource < 0 || originalSource >= sourcesCount)
decodeError(
`Original source index ${originalSource} is invalid (there are ${sourcesCount} sources)`,
i,
)
// Read the original line
const [originalLineDelta, ii3] = decodeVLQ(mappings, i)
i = ii3
originalLine += originalLineDelta
if (originalLine < 0) decodeError(`Invalid original line: ${originalLine}`, i)
// Read the original column
const [originalColumnDelta, ii4] = decodeVLQ(mappings, i)
i = ii4
originalColumn += originalColumnDelta
if (originalColumn < 0) decodeError(`Invalid original column: ${originalColumn}`, i)
// Check for the optional name index
if (i < n) {
c = mappings.charCodeAt(i)
if (c === 44 /* , */) {
i++
} else if (c !== 59 /* ; */) {
isOriginalNameMissing = false
// Read the optional name index
const [originalNameDelta, ii5] = decodeVLQ(mappings, i)
i = ii5
originalName += originalNameDelta
if (originalName < 0 || originalName >= namesCount)
decodeError(
`Original name index ${originalName} is invalid (there are ${namesCount} names)`,
i,
)
// Handle the next character
if (i < n) {
c = mappings.charCodeAt(i)
if (c === 44 /* , */) {
i++
} else if (c !== 59 /* ; */) {
decodeError(
`Invalid character after mapping: ${JSON.stringify(String.fromCharCode(c))}`,
i,
)
}
/* XXX: WHAT IS THIS NIGHTMARE */
}
}
}
}
}
// Append the mapping to the typed array
if (dataLength + 6 > data.length) {
const newData = new Int32Array(data.length << 1)
newData.set(data)
data = newData
}
data[dataLength] = generatedLine
data[dataLength + 1] = generatedColumn
if (isOriginalSourceMissing) {
data[dataLength + 2] = -1
data[dataLength + 3] = -1
data[dataLength + 4] = -1
} else {
data[dataLength + 2] = originalSource
data[dataLength + 3] = originalLine
data[dataLength + 4] = originalColumn
}
data[dataLength + 5] = isOriginalNameMissing ? -1 : originalName
dataLength += 6
}
return data.subarray(0, dataLength)
}
function generateInverseMappings(sources, data) {
let longestDataLength = 0
// Scatter the mappings to the individual sources
for (let i = 0, n = data.length; i < n; i += 6) {
const originalSource = data[i + 2]
if (originalSource === -1) continue
const source = sources[originalSource]
let inverseData = source.data
let j = source.dataLength
// Append the mapping to the typed array
if (j + 6 > inverseData.length) {
const newLength = inverseData.length << 1
const newData = new Int32Array(newLength > 1_024 ? newLength : 1_024)
newData.set(inverseData)
source.data = inverseData = newData
}
inverseData[j] = data[i]
inverseData[j + 1] = data[i + 1]
inverseData[j + 2] = originalSource
inverseData[j + 3] = data[i + 3]
inverseData[j + 4] = data[i + 4]
inverseData[j + 5] = data[i + 5]
j += 6
source.dataLength = j
if (j > longestDataLength) longestDataLength = j
}
// Sort the mappings for each individual source
const temp = new Int32Array(longestDataLength)
for (const source of sources) {
const data = source.data.subarray(0, source.dataLength)
// Sort lazily for performance
let isSorted = false
Object.defineProperty(source, 'data', {
get() {
if (!isSorted) {
temp.set(data)
topDownSplitMerge(temp, 0, data.length, data)
isSorted = true
}
return data
},
})
}
// From: https://en.wikipedia.org/wiki/Merge_sort
function topDownSplitMerge(B, iBegin, iEnd, A) {
if (iEnd - iBegin <= 6) return
// Optimization: Don't do merge sort if it's already sorted
let isAlreadySorted = true
for (let i = iBegin + 3, j = i + 6; j < iEnd; i = j, j += 6) {
// Compare mappings first by original line (index 3) and then by original column (index 4)
if (A[i] < A[j] || (A[i] === A[j] && A[i + 1] <= A[j + 1])) continue
isAlreadySorted = false
break
}
if (isAlreadySorted) {
return
}
const iMiddle = ((iEnd / 6 + iBegin / 6) >> 1) * 6
topDownSplitMerge(A, iBegin, iMiddle, B)
topDownSplitMerge(A, iMiddle, iEnd, B)
topDownMerge(B, iBegin, iMiddle, iEnd, A)
}
// From: https://en.wikipedia.org/wiki/Merge_sort
function topDownMerge(A, iBegin, iMiddle, iEnd, B) {
let i = iBegin
let j = iMiddle
for (let k = iBegin; k < iEnd; k += 6) {
if (
i < iMiddle &&
(j >= iEnd ||
// Compare mappings first by original line (index 3) and then by original column (index 4)
A[i + 3] < A[j + 3] ||
(A[i + 3] === A[j + 3] && A[i + 4] <= A[j + 4]))
) {
B[k] = A[i]
B[k + 1] = A[i + 1]
B[k + 2] = A[i + 2]
B[k + 3] = A[i + 3]
B[k + 4] = A[i + 4]
B[k + 5] = A[i + 5]
i += 6
} else {
B[k] = A[j]
B[k + 1] = A[j + 1]
B[k + 2] = A[j + 2]
B[k + 3] = A[j + 3]
B[k + 4] = A[j + 4]
B[k + 5] = A[j + 5]
j += 6
}
}
}
}
const validateSourceMapVersion = json => {
if (json?.version !== 3) {
showLoadingError(
`The imported source map is invalid. Expected the "version" field to be 3 but got ${json?.version}.`,
)
throw new Error('Invalid source map')
}
}
const validateSourceMapSources = (map, sectionIndex = null) => {
if (!Array.isArray(map.sources) || map.sources.some(x => typeof x !== 'string')) {
const context = sectionIndex !== null ? ` for section ${sectionIndex}` : ''
showLoadingError(
`The imported source map is invalid. Expected the "sources" field${context} to be an array of strings.`,
)
throw new Error('Invalid source map')
}
}
const validateSourceMapMappings = (map, sectionIndex = null) => {
if (typeof map.mappings !== 'string') {
const context = sectionIndex !== null ? ` for section ${sectionIndex}` : ''
showLoadingError(
`The imported source map is invalid. Expected the "mappings" field${context} to be a string.`,
)
throw new Error('Invalid source map')
}
}
const initializeSourceData = (sources, sourcesContent) => {
const emptyData = new Int32Array(0)
return sources.map((x, i) => ({
name: x,
content: sourcesContent?.[i] ?? '',
data: emptyData,
dataLength: 0,
}))
}
const parseSourceMap = sourceMapJson => {
const parsedJson = JSON.parse(sourceMapJson)
try {
validateSourceMapVersion(parsedJson)
if (Array.isArray(parsedJson.sections)) {
const sections = parsedJson.sections
const decodedSections = []
let totalDataLength = 0
for (let i = 0; i < sections.length; i++) {
const {
offset: { line, column },
map,
} = sections[i]
if (typeof line !== 'number' || typeof column !== 'number') {
showLoadingError(
`The imported source map is invalid. Expected the "offset" field for section ${i} to have a line and column.`,
)
throw new Error('Invalid source map')
}
if (!map) {
showLoadingError(
`The imported source map is unsupported. Section ${i} does not contain a "map" field.`,
)
throw new Error('Invalid source map')
}
validateSourceMapVersion(map, i)
validateSourceMapSources(map, i)
validateSourceMapMappings(map, i)
const { sources, sourcesContent, names, mappings } = map
initializeSourceData(sources, sourcesContent)
const data = decodeMappings(mappings, sources.length, names?.length ?? 0)
decodedSections.push({ offset: { line, column }, sources, names, data })
totalDataLength += data.length
}
decodedSections.sort((a, b) => {
if (a.offset.line < b.offset.line) return -1
if (a.offset.line > b.offset.line) return 1
if (a.offset.column < b.offset.column) return -1
if (a.offset.column > b.offset.column) return 1
return 0
})
const mergedData = new Int32Array(totalDataLength)
const mergedSources = []
const mergedNames = []
// const dataOffset = 0
for (const section of decodedSections) {
const {
offset: { line, column },
// sources,
// names,
data,
} = section
// const sourcesOffset = mergedSources.length
// const nameOffset = mergedNames.length
for (let i = 0; i < data.length; i += 6) {
const isZeroLine = data[i] === 0
if (isZeroLine) {
data[i + 1] += column
}
data[i] += line
}
}
generateInverseMappings(mergedSources, mergedData)
return {
sources: mergedSources,
names: mergedNames,
data: mergedData,
}
}
if (
!Array.isArray(parsedJson?.sources) ||
parsedJson?.sources?.some(x => typeof x !== 'string')
) {
showLoadingError(
'The imported source map is invalid. Expected the "sources" field to be an array of strings.',
)
throw new Error('Invalid source map')
}
if (typeof parsedJson?.mappings !== 'string') {
showLoadingError(
'The imported source map is invalid. Expected the "mappings" field to be a string.',
)
throw new Error('Invalid source map')
}
const { sources, sourcesContent, names, mappings } = parsedJson
const emptyData = new Int32Array(0)
for (let i = 0; i < sources?.length ?? 0; i++) {
sources[i] = {
name: sources[i],
content: sourcesContent?.[i] ?? '',
data: emptyData,
dataLength: 0,
}
}
const data = decodeMappings(mappings, sources.length, names ? names.length : 0)
generateInverseMappings(sources, data)
return { sources, names, data }
} catch (e) {
showLoadingError(`The imported source map contains invalid JSON data: ${e?.message ?? e}`)
throw e
}
}
function waitForDOM() {
return new Promise(r => setTimeout(r, 1))
}
async function finishLoading(code, map) {
const startTime = Date.now()
promptText.style.display = 'none'
// toolbar.style.display = 'flex'
// statusBar.style.display = 'flex'
canvas.style.display = 'block'
// originalStatus.textContent = generatedStatus.textContent = ''
// fileList.innerHTML = ''
// const option = document.createElement('option')
// option.textContent = 'Loading...'
// fileList.appendChild(option)
// fileList.disabled = true
// fileList.selectedIndex = 0
originalTextArea = generatedTextArea = hover = null
isInvalid = true
// Let the browser update before parsing the source map, which may be slow
await waitForDOM()
const sm = parseSourceMap(map)
// Show a progress bar if this is is going to take a while
let charsSoFar = 0
let progressCalls = 0
let isProgressVisible = false
const progressStart = Date.now()
const totalChars = code.length + (sm.sources.length > 0 ? sm.sources[0].content.length : 0)
const progress = chars => {
charsSoFar += chars
if (!isProgressVisible && progressCalls++ > 2 && charsSoFar) {
const estimatedTimeLeftMS =
((Date.now() - progressStart) / charsSoFar) * (totalChars - charsSoFar)
if (estimatedTimeLeftMS > 250) {
// progressBarOverlay.style.display = 'block'
isProgressVisible = true
}
}
if (isProgressVisible) {
// progressBar.style.transform = `scaleX(${charsSoFar / totalChars})`
return waitForDOM()
}
}
// progressBar.style.transform = 'scaleX(0)'
// Update the original text area when the source changes
const otherSource = index => (index === -1 ? null : sm.sources[index].name)
const originalName = index => sm.names[index]
let finalOriginalTextArea = null
if (sm.sources.length > 0) {
const updateOriginalSource = (sourceIndex, progress) => {
const source = sm.sources[sourceIndex]
return createTextArea({
sourceIndex,
text: source.content,
progress,
mappings: source.data,
mappingsOffset: 3,
otherSource,
originalName,
bounds() {
return {
x: 0,
y: 0,
width: (innerWidth >>> 1) - (splitterWidth >> 1),
height: innerHeight,
}
},
})
}
// fileList.onchange = async () => {
// originalTextArea = await updateOriginalSource(fileList.selectedIndex)
// isInvalid = true
// }
finalOriginalTextArea = await updateOriginalSource(0, progress)
}
generatedTextArea = await createTextArea({
sourceIndex: null,
text: code,
progress,
mappings: sm.data,
mappingsOffset: 0,
otherSource,
originalName,
bounds() {
const x = (innerWidth >> 1) + ((splitterWidth + 1) >> 1)
return {
x,
y: 0,
width: innerWidth - x,
height: innerHeight,
}
},
})
// Only render the original text area once the generated text area is ready
originalTextArea = finalOriginalTextArea
isInvalid = true
// Populate the file picker once there will be no more await points
// fileList.innerHTML = ''
if (sm.sources.length) {
for (let sources = sm.sources, i = 0, n = sources.length; i < n; i++) {
const option = document.createElement('option')
option.textContent = `${i}: ${sources[i].name}`
// fileList.appendChild(option)
}
// fileList.disabled = false
} else {
const option = document.createElement('option')
option.textContent = '(no original code)'
// fileList.appendChild(option)
}
// fileList.selectedIndex = 0
const endTime = Date.now()
console.log(`Finished loading in ${endTime - startTime}ms`)
}
////////////////////////////////////////////////////////////////////////////////
// Drawing
const originalLineColors = [
'rgba(25, 133, 255, 0.3)', // Blue
'rgba(174, 97, 174, 0.3)', // Purple
'rgba(255, 97, 106, 0.3)', // Red
'rgba(250, 192, 61, 0.3)', // Yellow
'rgba(115, 192, 88, 0.3)', // Green
]
// Use a striped pattern for bad mappings (good mappings are solid)
const patternContours = [
[0, 24, 24, 0, 12, 0, 0, 12, 0, 24],
[0, 28, 28, 0, 40, 0, 0, 40, 0, 28],
[0, 44, 44, 0, 56, 0, 0, 56, 0, 44],
[12, 64, 24, 64, 64, 24, 64, 12, 12, 64],
[0, 60, 0, 64, 8, 64, 64, 8, 64, 0, 60, 0, 0, 60],
[28, 64, 40, 64, 64, 40, 64, 28, 28, 64],
[0, 8, 8, 0, 0, 0, 0, 8],
[44, 64, 56, 64, 64, 56, 64, 44, 44, 64],
[64, 64, 64, 60, 60, 64, 64, 64],
]
const badMappingPatterns = originalLineColors.map(color => {
const patternCanvas = document.createElement('canvas')
const patternContext = patternCanvas.getContext('2d')
let canvasWidth = 0
let canvasHeight = 0
// let ratio
let scale
let pattern
return (dx, dy) => {
const width = Math.ceil(dx)
const height = Math.ceil(dy)
if (canvasWidth < width || canvasHeight < height) {
canvasWidth = Math.max(canvasWidth, width)
canvasHeight = Math.max(canvasHeight, height)
patternCanvas.width = canvasWidth
patternCanvas.height = canvasHeight
pattern = null
}
if (pattern === null) {
patternContext.clearRect(0, 0, canvasWidth, canvasHeight)
patternContext.beginPath()
for (const contour of patternContours) {
for (let i = 0; i < contour.length; i += 2) {
if (i === 0) patternContext.moveTo(contour[i], contour[i + 1])
else patternContext.lineTo(contour[i], contour[i + 1])
}
}
patternContext.fillStyle = color.replace(' 0.3)', ' 0.2)')
patternContext.fill()
pattern = c.createPattern(patternCanvas, 'repeat')
}
if (pattern) {
pattern.setTransform(new DOMMatrix([1 / scale, 0, 0, 1 / scale, dx, dy]))
return pattern
}
return color // Fallback to solid color if pattern creation fails
}
})
const canvas = document.createElement('canvas')
const c = canvas.getContext('2d')
const monospaceFont = '14px monospace'
const rowHeight = 21
const splitterWidth = 6
const margin = 40
let isInvalid = true
let originalTextArea
let generatedTextArea
let hover = null
// const wrapCheckbox = document.getElementById('wrap')
// const wrap = localStorage.getItem('wrap') !== 'false'
// wrapCheckbox.checked = wrap
// wrapCheckbox.onchange = () => {
// localStorage.setItem('wrap', wrapCheckbox.checked)
// if (originalTextArea) originalTextArea.updateAfterWrapChange()
// if (generatedTextArea) generatedTextArea.updateAfterWrapChange()
// isInvalid = true
// }
async function splitTextIntoLinesAndRuns(text, progress) {
c.font = monospaceFont
const spaceWidth = c.measureText(' ').width
const spacesPerTab = 2
const parts = text.split(/(\r\n|\r|\n)/g)
const unicodeWidthCache = new Map()
const lines = []
const progressChunkSize = 1 << 20
let longestColumnForLine = new Int32Array(1024)
let runData = new Int32Array(1024)
let runDataLength = 0
let prevProgressPoint = 0
let longestLineInColumns = 0
let lineStartOffset = 0
for (let part = 0; part < parts.length; part++) {
const raw = parts[part]
if (part & 1) {
// Accumulate the length of the newline (CRLF uses two code units)
lineStartOffset += raw.length
continue
}
const runBase = runDataLength
const n = raw.length + 1 // Add 1 for the extra character at the end
let nextProgressPoint = progress
? prevProgressPoint + progressChunkSize - lineStartOffset
: Number.POSITIVE_INFINITY
let i = 0
let column = 0
while (i < n) {
const startIndex = i
const startColumn = column
let whitespace = 0
let isSingleChunk = false
// Update the progress bar occasionally
if (i > nextProgressPoint) {
await progress(lineStartOffset + i - prevProgressPoint)
prevProgressPoint = lineStartOffset + i
nextProgressPoint = i + progressChunkSize
}
while (i < n) {
let c1 = raw.charCodeAt(i)
let c2
// Draw each tab into its own run
if (c1 === 0x09 /* tab */) {
if (i > startIndex) break
isSingleChunk = true
column += spacesPerTab
column -= column % spacesPerTab
i++
whitespace = c1
break
}
// Draw each newline into its own run
if (Number.isNaN(c1)) {
if (i > startIndex) break
isSingleChunk = true
column++
i++
whitespace = 0x0a /* newline */
break
}
// Draw each non-ASCII character into its own run (e.g. emoji)
if (c1 < 0x20 || c1 > 0x7e) {
if (i > startIndex) break
isSingleChunk = true
i++
// Consume another code unit if this code unit is a high surrogate
// and the next code point is a low surrogate. This handles code
// points that span two UTF-16 code units.
if (i < n && c1 >= 0xd800 && c1 <= 0xdbff) {
c2 = raw.charCodeAt(i)
if (c2 >= 0xdc00 && c2 <= 0xdfff) {
i++
}
}