@preventive/triage 1.0.0-alpha.79 → 1.0.0-alpha.80

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 (60) hide show
  1. package/common/line-diff.d.ts +4 -0
  2. package/common/line-diff.js +72 -14
  3. package/common/managed/npm-packages.d.ts +2 -0
  4. package/common/managed/npm-packages.js +12 -0
  5. package/common/pretty-json.js +3 -0
  6. package/common/pretty-kinds.js +20 -0
  7. package/common/pretty-sourcemap.js +70 -0
  8. package/common/sourcemap-listing.js +78 -0
  9. package/common/sourcemap-mappings.js +136 -0
  10. package/common/sourcemap-unlist.js +85 -0
  11. package/out/activity.js +2 -2
  12. package/out/brotli-fallback.js +2 -2
  13. package/out/chunk-2XUEZHIP.js +1 -1
  14. package/out/{chunk-PLF4LBLE.js → chunk-5AVGKFMR.js} +1 -1
  15. package/out/{chunk-WB3NRZL7.js → chunk-5CJKUV53.js} +1 -1
  16. package/out/{chunk-6VXEPL32.js → chunk-5EAVJAD2.js} +1 -1
  17. package/out/{chunk-OWIBDEJJ.js → chunk-5M2X3QPK.js} +1 -1
  18. package/out/{chunk-26W3E5JE.js → chunk-5QWPKTCE.js} +1 -1
  19. package/out/chunk-74JZTGTO.js +1 -1
  20. package/out/{chunk-MKX6JODK.js → chunk-7YO4QV5P.js} +1 -1
  21. package/out/{chunk-EMNIV37E.js → chunk-DUS5ARE2.js} +1 -1
  22. package/out/{chunk-Z54AXVCK.js → chunk-GBMAXAYK.js} +2 -2
  23. package/out/chunk-GO7FT4OD.js +1 -1
  24. package/out/{chunk-V43XH2JQ.js → chunk-JXBRWLMA.js} +1 -1
  25. package/out/chunk-LBD3M3J6.js +1 -0
  26. package/out/chunk-MV66NL3G.js +3 -0
  27. package/out/chunk-N57OWFKY.js +15 -0
  28. package/out/{chunk-IIJK4F4U.js → chunk-OWSEQOL5.js} +1 -1
  29. package/out/chunk-PLGH63UC.js +2 -0
  30. package/out/{chunk-3S4YWYOM.js → chunk-PTFYDJUP.js} +1 -1
  31. package/out/chunk-QD3IBSF4.js +1 -1
  32. package/out/{chunk-ATT2QA77.js → chunk-VZPPX6MV.js} +1 -1
  33. package/out/chunk-YKCRCNYZ.js +266 -0
  34. package/out/client-managed-import.js +1 -1
  35. package/out/client-managed.js +1 -1
  36. package/out/client-sync.js +2 -2
  37. package/out/compare.js +13 -18
  38. package/out/dialogs.js +38 -38
  39. package/out/graph.js +3 -3
  40. package/out/index.html +11 -11
  41. package/out/prism.js +1 -1
  42. package/out/scan.js +2 -2
  43. package/out/terminal.js +167 -167
  44. package/out/view.js +8 -8
  45. package/package.json +14 -9
  46. package/risk/index.d.ts +3 -0
  47. package/risk/index.js +1 -1
  48. package/risk/npm/tarball.js +4 -4
  49. package/server-managed/http.ts +36 -80
  50. package/server-managed/npm-delta-worker.js +117 -44
  51. package/server-managed/npm-delta.ts +101 -22
  52. package/server-managed/npm-kept.ts +5 -0
  53. package/server-managed/npm-patch-paths.ts +29 -0
  54. package/server-managed/npm-patch.ts +11 -3
  55. package/out/chunk-4YZOXAXR.js +0 -2
  56. package/out/chunk-NTJJIEHS.js +0 -259
  57. package/out/chunk-PQPKHAI5.js +0 -15
  58. package/out/chunk-QBIUW5EF.js +0 -2
  59. package/out/chunk-XLX6XXJF.js +0 -1
  60. /package/out/{chunk-S5HSDGTP.js → chunk-DUASGS2O.js} +0 -0
@@ -6,5 +6,9 @@ export interface ChangeBlock { a0: number; a1: number; b0: number; b1: number }
6
6
  export function textLines(text: string): string[]
7
7
  export function changeBlocks(before: string, after: string, ignoreWhitespace?: boolean | 'leading'): ChangeBlock[]
8
8
  export function indentHiddenBlocks(before: string, after: string): ChangeBlock[]
9
+ export function markedCounts(blocks: readonly ChangeBlock[], marks: readonly ChangeBlock[] | null): { additions: number; deletions: number; renamed: number; marked: Set<number> }
10
+ export function diffSize(before: string, after: string, ignoreWhitespace?: boolean | 'leading'): { marks: number; lines: number }
11
+ export const isLargeDiff: (before: string, after: string) => boolean
12
+ export function typeFolds(before: string, after: string, runs: { runs: [number, number][]; otherRuns: [number, number][] }): { before: string; after: string; lineOf: { a: number[]; b: number[] }; lines: { a: number; b: number } } | null
9
13
  export function withSharedBlankLines(before: string, after: string, blankBefore: readonly number[], blankAfter: readonly number[]): { before: string; after: string }
10
14
  export function blocksHold(before: string, after: string, blocks: unknown, ignoreWhitespace?: boolean | 'leading'): boolean
@@ -1,12 +1,9 @@
1
- // The change blocks between two texts' lines, found by @preventive/diff: what
2
- // the viewer's Compare diffs (ui/view/bundle-compare-code-model.js); and the
3
- // server's check, apart from @preventive/compare's own, that its diff with
4
- // renamed names hidden takes the old side to the new (server-managed/rename-diff.ts).
1
+ // Two texts' lines diffed as Compare draws and the server counts them (@preventive/compare's lineBlocks), and the
2
+ // check that a diff found elsewhere (server-managed/rename-diff.ts) takes one to the other.
5
3
  //
6
4
  // Lines are numbered the way the diff numbers them: from zero, a final
7
5
  // newline ending the last line rather than starting an empty one.
8
- import { changeSet } from '@preventive/diff'
9
- import { hidesMixedWhitespace } from '@preventive/compare/view.js'
6
+ import { hidesMixedWhitespace, lineBlocks } from '@preventive/compare/view.js'
10
7
 
11
8
  export function textLines(text) {
12
9
  if (text === '') return []
@@ -31,16 +28,10 @@ const INDENT = /(?<=^|\n)[ \t\v\f]+/gu
31
28
  const unindent = text => (text === '' || text.endsWith('\n') ? text : `${text}\n`).replaceAll(INDENT, '')
32
29
  const unindentLine = line => line.replace(/^[ \t\v\f]+/u, '')
33
30
 
34
- // Each `a[a0..a1)` replaced by `b[b0..b1)`. `ignoreWhitespace` is diff -b
35
- // (true): lines differing only in how much whitespace they have pair up as
36
- // unchanged, whitespace added or removed between other characters still a
37
- // change; or `leading`: lines differing only in their indentation. Those a
38
- // unified diff with no context shows (horizon 0), found without printing one
39
- // and reading it back.
31
+ // The fewest lines where that costs little to find; `ignoreWhitespace` diff -b (true), or `leading`, indentation alone.
40
32
  export function changeBlocks(before, after, ignoreWhitespace = false) {
41
33
  const leading = ignoreWhitespace === 'leading'
42
- return changeSet(leading ? unindent(before) : before, leading ? unindent(after) : after, { horizon: 0, whitespace: ignoreWhitespace === true ? 'change' : 'none' })
43
- .map(({ a0, a1, b0, b1 }) => ({ a0, a1, b0, b1 }))
34
+ return lineBlocks(leading ? unindent(before) : before, leading ? unindent(after) : after, { horizon: 0, whitespace: ignoreWhitespace === true ? 'change' : 'none' })
44
35
  }
45
36
 
46
37
  // The blocks Compare draws with whitespace hidden: indentation set aside, but
@@ -96,6 +87,73 @@ export function withSharedBlankLines(before, after, blankBefore, blankAfter) {
96
87
  return { before: drawn(a, keptA, before), after: drawn(b, keptB, after) }
97
88
  }
98
89
 
90
+ // A file that changed in types alone but for what runs (type-only.js
91
+ // typeProof), its types set aside: `before` and `after` the texts of each
92
+ // side's lines that run (`runs`, `otherRuns`, `[from, to)` each), diffed in
93
+ // place of the files'; `lineOf` each of their lines' line in its file, and
94
+ // `lines` the file's count, for diffRows to show where the types stand. Null
95
+ // where that would hide no change or leave none to show.
96
+ export function typeFolds(before, after, { runs, otherRuns }) {
97
+ const side = (text, ranges) => {
98
+ const lineOf = [], lines = textLines(text)
99
+ for (const [from, to] of ranges) for (let i = from; i < Math.min(to, lines.length); i++) lineOf.push(i)
100
+ const run = lineOf.map(i => lines[i]), shown = new Set(lineOf)
101
+ // A last line with no newline after it stays so where it is shown.
102
+ const open = text !== '' && !text.endsWith('\n') && lineOf.at(-1) === lines.length - 1
103
+ return { text: run.length === 0 ? '' : `${run.join('\n')}${open ? '' : '\n'}`, lineOf, lines: lines.length, run: run.join('\n'),
104
+ types: lines.filter((_, i) => !shown.has(i)).join('\n') }
105
+ }
106
+ const a = side(before, runs), b = side(after, otherRuns)
107
+ if (a.types === b.types || a.run === b.run) return null
108
+ return { before: a.text, after: b.text, lineOf: { a: a.lineOf, b: b.lineOf }, lines: { a: a.lines, b: b.lines } }
109
+ }
110
+
111
+ // The lines `blocks` add and remove, but for those that are one of `marks`, counted apart (`renamed`, `marked`).
112
+ export function markedCounts(blocks, marks) {
113
+ const told = new Set((marks ?? []).map(({ a0, a1, b0, b1 }) => `${a0},${a1},${b0},${b1}`))
114
+ const marked = new Set()
115
+ let additions = 0, deletions = 0, renamed = 0
116
+ blocks.forEach(({ a0, a1, b0, b1 }, i) => {
117
+ if (told.has(`${a0},${a1},${b0},${b1}`) && a1 - a0 === b1 - b0) {
118
+ marked.add(i)
119
+ renamed += b1 - b0
120
+ } else {
121
+ additions += b1 - b0
122
+ deletions += a1 - a0
123
+ }
124
+ })
125
+ return { additions, deletions, renamed, marked }
126
+ }
127
+
128
+ const MARK = /[\p{L}\p{N}_$]+|\S/gu
129
+
130
+ // How much two texts' diff changes, `{ marks, lines }`: its lines removed and added, and its words and other
131
+ // characters but blanks (MARK) a block removes or adds and doesn't put back elsewhere in it, as a printer's
132
+ // semicolon changes a mark and no line. Whitespace hidden as the view hides it (mixed blanks shown).
133
+ export function diffSize(before, after, ignoreWhitespace = false) {
134
+ const a = textLines(before), b = textLines(after)
135
+ let blocks = changeBlocks(before, after, ignoreWhitespace), lines = 0, marks = 0
136
+ if (ignoreWhitespace && hidesMixedWhitespace(before, after, blocks)) blocks = changeBlocks(before, after)
137
+ for (const { a0, a1, b0, b1 } of blocks) {
138
+ const counts = new Map()
139
+ for (let i = a0; i < a1; i++) for (const [mark] of a[i].matchAll(MARK)) counts.set(mark, (counts.get(mark) ?? 0) + 1)
140
+ for (let j = b0; j < b1; j++) for (const [mark] of b[j].matchAll(MARK)) counts.set(mark, (counts.get(mark) ?? 0) - 1)
141
+ for (const count of counts.values()) marks += Math.abs(count)
142
+ lines += a1 - a0 + b1 - b0
143
+ }
144
+ return { marks, lines }
145
+ }
146
+
147
+ // Past these a diff is computed only when asked, as one of lines that share nothing takes seconds.
148
+ const LARGE_LINES = 100_000
149
+ const LARGE_CHARS = 16 * 1024 * 1024
150
+ const lineEnds = text => {
151
+ let count = 0
152
+ for (let at = text.indexOf('\n'); at !== -1; at = text.indexOf('\n', at + 1)) count++
153
+ return count
154
+ }
155
+ export const isLargeDiff = (before, after) => before.length + after.length > LARGE_CHARS || lineEnds(before) + lineEnds(after) > LARGE_LINES
156
+
99
157
  // Whether `blocks` take `before`'s lines to `after`'s: each in order and apart
100
158
  // from the last, within both texts, and every line between them alike on both
101
159
  // sides (alike but for how much whitespace they have where `ignoreWhitespace`,
@@ -5,3 +5,5 @@ export function isPatchHash(value: unknown): value is string
5
5
  export function isPatchPath(value: unknown): value is string
6
6
  export function npmPackageScope(name: string): string | null
7
7
  export function normalizeNpmScope(value: unknown): string | null
8
+ export function reviewBase(pkg: { name: string; version?: string | null | undefined; was?: string[] | undefined; patch?: unknown; base?: { name: string; version: string } | null | undefined },
9
+ review: { reviewedBases?: boolean | undefined } | null | undefined): { name: string; version: string } | null
@@ -49,3 +49,15 @@ export function normalizeNpmScope(value) {
49
49
  const scope = trimmed.startsWith('@') ? trimmed : `@${trimmed}`
50
50
  return scope.length <= 214 && SCOPE.test(scope) ? scope : null
51
51
  }
52
+
53
+ // The version a pull request's, default branch's or bundle's version wanting
54
+ // reviews is reviewed against, `{ name, version }`, null for its whole
55
+ // package: the one the host names (`review.reviewedBases`), else one it was,
56
+ // a patched one's the version it patches where it was that. Its rows count
57
+ // its lines against it (ui/view/npm-delta.js), and the server tells those
58
+ // counted already with it (http.ts teamDeltas).
59
+ export function reviewBase(pkg, review) {
60
+ if (review?.reviewedBases) return pkg.base ?? null
61
+ const was = pkg.patch && pkg.was?.includes(pkg.version) ? pkg.version : pkg.was?.find(prior => prior !== pkg.version)
62
+ return was ? { name: pkg.name, version: was } : null
63
+ }
@@ -3,6 +3,9 @@
3
3
  // Whether a path is JSON, which the viewer formats rather than the server.
4
4
  export const jsonPrinted = path => /\.json$/iu.test(path)
5
5
 
6
+ // The widths prettyJSON folds to in the pretty-print toggle's layouts.
7
+ export const JSON_LAYOUT_WIDTHS = { indented: 0, folded: 120 }
8
+
6
9
  const isContainer = value => value !== null && typeof value === 'object'
7
10
 
8
11
  // `value` on one line, `{ "a": [1, 2] }`, or null where that is longer than
@@ -0,0 +1,20 @@
1
+ // The files the viewer prints itself by their path (ui/view/pretty-source.js), as the server counts them too
2
+ // (npm-delta-worker.js): JSON in the toggle's layout, source maps listed, whose listings' diff is drawn only where
3
+ // it reads back to the new map (`refusal`: why not).
4
+ import { isSourceMap } from '../risk/files/source-map-link.js'
5
+ import { JSON_LAYOUT_WIDTHS, jsonPrinted, prettyJsonText } from './pretty-json.js'
6
+ import { printableSize } from './pretty-print.js'
7
+ import { listSourcemap, sourcemapDiffRebuilds, sourcemapPrinted } from './pretty-sourcemap.js'
8
+
9
+ const parses = text => {
10
+ try { JSON.parse(text); return true } catch { return false }
11
+ }
12
+ const KINDS = [
13
+ { printed: jsonPrinted, printable: parses, layouts: true, copy: (text, layout) => prettyJsonText(text, { width: JSON_LAYOUT_WIDTHS[layout] }) },
14
+ { printed: sourcemapPrinted, printable: isSourceMap, layouts: false, copy: text => listSourcemap(text),
15
+ refusal: (drawn, [before, after], [listed, listing]) => sourcemapDiffRebuilds(drawn, { text: before, listing: listed }, { text: after, listing }) },
16
+ ]
17
+
18
+ export const viewerKind = path => KINDS.find(kind => kind.printed(path)) ?? null
19
+ // Whether a file of `kind` can be printed: no larger than formatted, and read as one.
20
+ export const viewerPrintable = (kind, text) => printableSize(text) && kind.printable(text)
@@ -0,0 +1,70 @@
1
+ // A source map listed for the pretty-print toggle (ui/view/pretty-source.js):
2
+ // its values alone, laid out a value to a row (sourcemap-listing.js), so that
3
+ // a diff of two maps' listings reads as the changes between them. A listing
4
+ // reads back (sourcemap-unlist.js) to the very text it lists, and Compare
5
+ // draws a diff of two only where what it draws, the old map's listing and the
6
+ // changes it shows, reads back to the new map (sourcemapDiffRebuilds). A map
7
+ // that can't be listed, or a diff of two that doesn't read back, is shown as
8
+ // published.
9
+ import { UNSEEN } from '../risk/files/characters.js'
10
+ import { SOURCE_MAP } from '../risk/files/readability.js'
11
+ import { blocksHold } from './line-diff.js'
12
+ import { sourcemapListing } from './sourcemap-listing.js'
13
+ import { unlistSourcemap } from './sourcemap-unlist.js'
14
+
15
+ export { unlistSourcemap }
16
+
17
+ // Whether a path is a source map's, which the viewer lists rather than
18
+ // formats, where its text is one (risk/files/source-map-link.js isSourceMap).
19
+ export const sourcemapPrinted = path => SOURCE_MAP.test(path)
20
+
21
+ // What JSON.parse reads past after a value: a line end, mostly.
22
+ const BLANKS = /^[\t\n\r ]*$/u
23
+
24
+ // A source map's text listed. Throws, saying why, for a text that isn't a
25
+ // JSON object written as JSON.stringify writes it, but for blanks after it
26
+ // (spaced, keys repeated, a number or an escape spelled otherwise: a listing
27
+ // wouldn't read back to it), an index map, or a listing too long. Asserted of
28
+ // every listing before it is shown, as no map should fail them: that it reads
29
+ // back to the very text it lists, and that no row of it holds a character
30
+ // that shows as another or none.
31
+ export function listSourcemap(text) {
32
+ let value
33
+ try {
34
+ value = JSON.parse(text)
35
+ } catch {
36
+ throw new Error("Its text isn't JSON.")
37
+ }
38
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error("Its JSON isn't an object.")
39
+ const json = JSON.stringify(value), trailing = text.slice(json.length)
40
+ if (!text.startsWith(json) || !BLANKS.test(trailing)) throw new Error("Its text isn't written as JSON.stringify writes its JSON, so its listing wouldn't read back to it.")
41
+ if (Object.hasOwn(value, 'sections')) throw new Error("It is an index map, whose sections aren't listed.")
42
+ const listing = sourcemapListing(value, trailing)
43
+ if (unlistSourcemap(listing) !== text) throw new Error("Its listing doesn't read back to its text.")
44
+ if (UNSEEN.test(listing)) throw new Error('Its listing would show a character as another or none.')
45
+ return listing
46
+ }
47
+
48
+ const joined = lines => (lines.length === 0 ? '' : `${lines.join('\n')}\n`)
49
+
50
+ // Whether a diff drawn of two maps' listings shows every change between the
51
+ // maps: null where it does, else why not. `a` and `b` are the lines drawn of
52
+ // the old side and the new, `blocks` the changes drawn between them (each
53
+ // `a[a0..a1)` replaced by `b[b0..b1)`); `before` and `after` each side's map,
54
+ // `{ text, listing }`, its listing as listSourcemap made it (which reads back
55
+ // to the text), both '' where that side has none. The old side drawn must be
56
+ // the old map's listing; the changes drawn must take it to the new side drawn
57
+ // (line-diff.js blocksHold); that must be the new map's listing; and it must
58
+ // read back to the new map's very text.
59
+ export function sourcemapDiffRebuilds({ a, b, blocks }, before, after) {
60
+ const drawn = joined(b)
61
+ if (joined(a) !== before.listing) return "the old side drawn isn't the old map's listing."
62
+ if (!blocksHold(before.listing, drawn, blocks)) return "the changes drawn don't take the old map's listing to the new side drawn."
63
+ if (drawn !== after.listing) return "the new side drawn isn't the new map's listing."
64
+ if (after.text === '') return null
65
+ try {
66
+ return unlistSourcemap(drawn) === after.text ? null : 'the new side drawn reads back to another map than the new one.'
67
+ } catch (err) {
68
+ return err.message
69
+ }
70
+ }
@@ -0,0 +1,78 @@
1
+ // How a source map is listed (pretty-sourcemap.js): its values alone, each
2
+ // key in order, its value as JSON on the key's row, but a list's items each on
3
+ // a row of its own below it, sourcesContent's texts line by line, mappings a
4
+ // line of the generated file to a row, and what follows the JSON (a line end)
5
+ // as JSON on the last row. A segment is its values as the format writes them,
6
+ // from the one before (sourcemap-mappings.js mappingsDeltas), so that a line
7
+ // added above moves none of the rows below.
8
+ import { UNSEEN } from '../risk/files/characters.js'
9
+ import { COPY_LIMIT } from './pretty-json.js'
10
+ import { decodeMappings, encodeMappings, mappingsDeltas } from './sourcemap-mappings.js'
11
+
12
+ // A line of a text written as JSON (`┊`) where it holds a character that
13
+ // shows as another or none (risk/files/characters.js UNSEEN), so that a
14
+ // listing never leaves one to the viewer.
15
+ const UNSEEN_ALL = new RegExp(UNSEEN.source, 'gu')
16
+ function escapeUnseen(char) {
17
+ const point = char.codePointAt(0)
18
+ const units = point > 0xFFFF ? [Math.floor((point - 0x10000) / 0x400) + 0xD800, ((point - 0x10000) % 0x400) + 0xDC00] : [point]
19
+ return units.map(unit => `\\u${unit.toString(16).padStart(4, '0')}`).join('')
20
+ }
21
+ // A JSON value as JSON.stringify writes it, but for its UNSEEN characters
22
+ // escaped: JSON.parse reads it back to the same value.
23
+ export const literal = value => JSON.stringify(value).replaceAll(UNSEEN_ALL, escapeUnseen)
24
+
25
+ // What opens a map's mappings decoded, on its key's row; `}` closes them.
26
+ export const MAPPINGS_OPEN = '{'
27
+
28
+ // A map's mappings as lines of segments, or null where they are shown as
29
+ // written: `sources` (or `names`, where given) no list, mappings the format
30
+ // doesn't allow (decodeMappings), or written otherwise than in the fewest
31
+ // digits, which rows read back wouldn't be.
32
+ function decoded({ mappings, sources, names }) {
33
+ if (typeof mappings !== 'string' || !Array.isArray(sources) || !(names === undefined || Array.isArray(names))) return null
34
+ let lines
35
+ try {
36
+ lines = decodeMappings(mappings, sources.length, names?.length ?? 0)
37
+ } catch {
38
+ return null
39
+ }
40
+ return encodeMappings(lines) === mappings ? lines : null
41
+ }
42
+
43
+ // Whether a value is listed an item to a row: a list of values each of which
44
+ // is null or holds to `each`.
45
+ const listOf = (value, each) => Array.isArray(value) && value.length > 0 && value.every(item => item === null || each(item))
46
+
47
+ // The listing of a map JSON.parse made (`value`), and what followed its JSON
48
+ // in the text (`trailing`, blanks). Throws a RangeError past COPY_LIMIT.
49
+ export function sourcemapListing(value, trailing = '') {
50
+ const lines = [], mappings = decoded(value)
51
+ let length = 0
52
+ const push = line => {
53
+ if ((length += line.length + 1) > COPY_LIMIT) throw new RangeError(`Its listing would run past ${COPY_LIMIT.toLocaleString('en')} characters.`)
54
+ lines.push(line)
55
+ }
56
+ for (const key of Object.keys(value)) {
57
+ const head = `${literal(key)}: `, item = value[key]
58
+ if (key === 'mappings' && mappings) {
59
+ push(`${head}${MAPPINGS_OPEN}`)
60
+ for (const line of mappingsDeltas(mappings)) push(line.length === 0 ? '' : ` ${line.map(values => values.join(' ')).join(', ')}`)
61
+ push('}')
62
+ } else if (key === 'sourcesContent' && listOf(item, text => typeof text === 'string')) {
63
+ push(`${head}[`)
64
+ item.forEach((text, i) => {
65
+ if (text === null) return push(' null')
66
+ push(Array.isArray(value.sources) && i < value.sources.length ? ` ┌ ${literal(value.sources[i])}` : ' ┌')
67
+ for (const line of text.split('\n')) push(UNSEEN.test(line) ? ` ┊ ${literal(line)}` : line === '' ? ' │' : ` │ ${line}`)
68
+ })
69
+ push(']')
70
+ } else if (listOf(item, each => typeof each !== 'object')) {
71
+ push(`${head}[`)
72
+ for (const each of item) push(` ${literal(each)}`)
73
+ push(']')
74
+ } else push(`${head}${literal(item)}`)
75
+ }
76
+ if (trailing !== '') push(literal(trailing))
77
+ return `${lines.join('\n')}\n`
78
+ }
@@ -0,0 +1,136 @@
1
+ // A source map's `mappings` read and written by the format's rules
2
+ // (ECMA-426): a line of segments to each line of the generated file, `;`
3
+ // between lines and `,` between segments, each segment one, four or five
4
+ // base64 VLQ values. The first is a column of the generated line, from the
5
+ // one before on the line; the others are an index into `sources`, a line and
6
+ // a column of that source, and an index into `names`, each from the segment
7
+ // before, whatever its line. Read strictly: whatever the format doesn't allow
8
+ // throws, so a listing (pretty-sourcemap.js) shows mappings as they are or
9
+ // not at all.
10
+
11
+ const DIGITS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
12
+ const DIGIT_OF = new Int8Array(128).fill(-1)
13
+ for (let i = 0; i < DIGITS.length; i++) DIGIT_OF[DIGITS.codePointAt(i)] = i
14
+ // Values are 32-bit, as the format has them: no more than seven digits.
15
+ const LIMIT = 2 ** 31
16
+ const COMMA = 44, SEMICOLON = 59
17
+
18
+ export class MappingsError extends Error {
19
+ constructor(message) {
20
+ super(message)
21
+ this.name = 'MappingsError'
22
+ }
23
+ }
24
+
25
+ // `mappings` as `[line][segment]`, a segment `[column]` (mapped from no
26
+ // source) or `[column, source, line, column]`, with `name` after those where
27
+ // it has one, every value absolute and counted from zero. Throws a
28
+ // MappingsError for any character not a base64 digit or separator, a value
29
+ // cut short or past 32 bits, a segment of two, three or more than five
30
+ // values or none (`,,`, a `,` before a `;`), or one whose column, source,
31
+ // line or name falls outside zero, `sources` (`sourcesCount`) and `names`
32
+ // (`namesCount`).
33
+ export function decodeMappings(mappings, sourcesCount, namesCount) {
34
+ const lines = []
35
+ let line = []
36
+ // The values so far: each a segment's, from the one before.
37
+ let column = 0, name = 0, source = 0, sourceColumn = 0, sourceLine = 0
38
+ let fields = [], shift = 0, value = 0
39
+ const end = (separator, at) => {
40
+ if (shift !== 0) throw new MappingsError(`A value is cut short before ${at}.`)
41
+ if (fields.length === 0) {
42
+ if (separator === COMMA || line.length > 0) throw new MappingsError(`An empty segment at ${at}.`)
43
+ return
44
+ }
45
+ if (fields.length !== 1 && fields.length !== 4 && fields.length !== 5) throw new MappingsError(`A segment of ${fields.length} values before ${at}.`)
46
+ column += fields[0]
47
+ if (column < 0) throw new MappingsError(`A segment before ${at} is at a column before the line's first.`)
48
+ const segment = [column]
49
+ if (fields.length >= 4) {
50
+ source += fields[1]
51
+ sourceLine += fields[2]
52
+ sourceColumn += fields[3]
53
+ if (source < 0 || source >= sourcesCount) throw new MappingsError(`A segment before ${at} names source ${source}, of ${sourcesCount}.`)
54
+ if (sourceLine < 0 || sourceColumn < 0) throw new MappingsError(`A segment before ${at} maps from before its source's first line or column.`)
55
+ segment.push(source, sourceLine, sourceColumn)
56
+ if (fields.length === 5) {
57
+ name += fields[4]
58
+ if (name < 0 || name >= namesCount) throw new MappingsError(`A segment before ${at} names name ${name}, of ${namesCount}.`)
59
+ segment.push(name)
60
+ }
61
+ }
62
+ line.push(segment)
63
+ fields = []
64
+ }
65
+ for (let i = 0; i < mappings.length; i++) {
66
+ const code = mappings.codePointAt(i)
67
+ if (code === COMMA || code === SEMICOLON) {
68
+ end(code, i)
69
+ if (code === SEMICOLON) {
70
+ lines.push(line)
71
+ line = []
72
+ column = 0
73
+ }
74
+ continue
75
+ }
76
+ const digit = DIGIT_OF[code] ?? -1
77
+ if (digit < 0) throw new MappingsError(`${JSON.stringify(mappings[i])} at ${i} is no base64 digit.`)
78
+ value += (digit & 31) * 2 ** shift
79
+ shift += 5
80
+ if (digit & 32) {
81
+ if (shift >= 35) throw new MappingsError(`A value past 32 bits at ${i}.`)
82
+ continue
83
+ }
84
+ const magnitude = Math.floor(value / 2)
85
+ if (magnitude >= LIMIT) throw new MappingsError(`A value past 32 bits at ${i}.`)
86
+ fields.push(value % 2 === 1 ? -magnitude : magnitude)
87
+ value = 0
88
+ shift = 0
89
+ }
90
+ end(SEMICOLON, mappings.length)
91
+ lines.push(line)
92
+ return lines
93
+ }
94
+
95
+ function vlq(number) {
96
+ let text = '', value = number < 0 ? -number * 2 + 1 : number * 2
97
+ do {
98
+ let digit = value % 32
99
+ value = Math.floor(value / 32)
100
+ if (value > 0) digit += 32
101
+ text += DIGITS[digit]
102
+ } while (value > 0)
103
+ return text
104
+ }
105
+
106
+ // Lines of segments as decodeMappings reads them, each value from the one
107
+ // before as the format writes it: a column from the one before on its line,
108
+ // a source, line, column and name from the segment before, whatever its line.
109
+ export function mappingsDeltas(lines) {
110
+ let name = 0, source = 0, sourceColumn = 0, sourceLine = 0
111
+ return lines.map(line => {
112
+ let column = 0
113
+ return line.map(segment => {
114
+ const values = [segment[0] - column]
115
+ column = segment[0]
116
+ if (segment.length >= 4) {
117
+ values.push(segment[1] - source, segment[2] - sourceLine, segment[3] - sourceColumn)
118
+ ;[, source, sourceLine, sourceColumn] = segment
119
+ if (segment.length === 5) {
120
+ values.push(segment[4] - name)
121
+ name = segment[4]
122
+ }
123
+ }
124
+ return values
125
+ })
126
+ })
127
+ }
128
+
129
+ // Lines of segments of values from the one before (mappingsDeltas), written as
130
+ // mappings, each value in the fewest digits.
131
+ export const encodeDeltas = lines => lines.map(line => line.map(values => values.map(vlq).join('')).join(',')).join(';')
132
+
133
+ // Lines of segments as decodeMappings reads them, written as the format
134
+ // writes them: so for mappings as any generator writes them,
135
+ // `encodeMappings(decodeMappings(m, …))` is `m`.
136
+ export const encodeMappings = lines => encodeDeltas(mappingsDeltas(lines))
@@ -0,0 +1,85 @@
1
+ // A source map's listing (sourcemap-listing.js) read back to the text it
2
+ // lists. Any row that isn't a listing's throws.
3
+ import { MAPPINGS_OPEN } from './sourcemap-listing.js'
4
+ import { encodeDeltas } from './sourcemap-mappings.js'
5
+
6
+ const KEY_ROW = /^("(?:[^"\\]|\\.)*"): (.*)$/u
7
+ const STRING_ROW = /^"(?:[^"\\]|\\.)*"$/u
8
+ const VALUE = /^-?\d+$/u
9
+ // What JSON.parse reads past after a value.
10
+ const BLANKS = /^[\t\n\r ]+$/u
11
+
12
+ const fail = (row, why) => {
13
+ throw new Error(`Its listing's row ${row + 1} ${why}`)
14
+ }
15
+
16
+ // A line of a text (`│` as written, `┊` as JSON).
17
+ function textLine(row, i) {
18
+ if (row === ' │') return ''
19
+ if (row.startsWith(' │ ')) return row.slice(4)
20
+ const text = row.startsWith(' ┊ ') ? JSON.parse(row.slice(4)) : null
21
+ return typeof text === 'string' && !text.includes('\n') ? text : fail(i, 'is no line of a text.')
22
+ }
23
+
24
+ // A list's items, from row `i`, and the row past its `]`.
25
+ function itemsFrom(rows, i) {
26
+ const items = []
27
+ for (; i < rows.length; i++) {
28
+ const row = rows[i]
29
+ if (row === ']') return [items, i + 1]
30
+ if (row === ' ┌' || row.startsWith(' ┌ ')) {
31
+ const lines = []
32
+ while (rows[i + 1]?.startsWith(' │') || rows[i + 1]?.startsWith(' ┊')) lines.push(textLine(rows[++i], i))
33
+ if (lines.length === 0) fail(i, 'opens a text with no line.')
34
+ items.push(lines.join('\n'))
35
+ } else if (row.startsWith(' ')) items.push(JSON.parse(row.slice(2)))
36
+ else fail(i, 'is no item of a list.')
37
+ }
38
+ return fail(i - 1, 'ends a list with no `]` after.')
39
+ }
40
+
41
+ // Mappings written back of their rows, a line of the generated file to each
42
+ // (`from` the first's index), each segment its values from the one before.
43
+ function mappingsFrom(rows, from) {
44
+ return encodeDeltas(rows.map((row, k) => {
45
+ if (row === '') return []
46
+ if (!row.startsWith(' ')) fail(from + k, 'is no line of mappings.')
47
+ return row.slice(2).split(', ').map(segment => {
48
+ const values = segment.split(' ')
49
+ if (![1, 4, 5].includes(values.length) || !values.every(each => VALUE.test(each))) fail(from + k, 'gives a segment that reads as none.')
50
+ return values.map(Number)
51
+ })
52
+ }))
53
+ }
54
+
55
+ // The text a listing lists. Throws for rows that aren't a listing's.
56
+ export function unlistSourcemap(text) {
57
+ if (!text.endsWith('\n')) throw new Error('Its listing ends with no line end.')
58
+ const rows = text.slice(0, -1).split('\n'), value = {}
59
+ let i = 0, trailing = ''
60
+ while (i < rows.length) {
61
+ if (i === rows.length - 1 && STRING_ROW.test(rows[i])) {
62
+ trailing = JSON.parse(rows[i])
63
+ if (!BLANKS.test(trailing)) fail(i, 'follows the JSON with more than blanks.')
64
+ break
65
+ }
66
+ const match = KEY_ROW.exec(rows[i])
67
+ if (!match) fail(i, 'names no key.')
68
+ const key = JSON.parse(match[1])
69
+ if (Object.hasOwn(value, key)) fail(i, `names ${match[1]} again.`)
70
+ let item
71
+ if (match[2] === '[') [item, i] = itemsFrom(rows, i + 1)
72
+ else if (match[2] === MAPPINGS_OPEN && key === 'mappings') {
73
+ const end = rows.indexOf('}', i + 1)
74
+ if (end < 0) fail(i, 'opens mappings with no `}` after.')
75
+ item = mappingsFrom(rows.slice(i + 1, end), i + 1)
76
+ i = end + 1
77
+ } else {
78
+ item = JSON.parse(match[2])
79
+ i++
80
+ }
81
+ // Defined, not set: a `__proto__` key is a key like any other in JSON.
82
+ Object.defineProperty(value, key, { value: item, enumerable: true, writable: true, configurable: true })
83
+ }
84
+ return `${JSON.stringify(value)}${trailing}`
85
+ }