@mdsvex/source-map 0.0.0 → 0.1.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # @mdsvex/source-map
2
+
3
+ ## 0.1.0-next.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#799](https://github.com/pngwn/MDsveX/pull/799) [`5b54692`](https://github.com/pngwn/MDsveX/commit/5b54692d6c895f02c947ce620a46c7a9beb856e9) Thanks [@pngwn](https://github.com/pngwn)! - Add language tools
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [[`6ac3826`](https://github.com/pngwn/MDsveX/commit/6ac382615eb410230e8423d5ca4202005588869e), [`46f655f`](https://github.com/pngwn/MDsveX/commit/46f655f90a838726eda34e1b07667e86fa61e7cb), [`e5b7abe`](https://github.com/pngwn/MDsveX/commit/e5b7abe1ebf868b1df1e934fb96e1e363696f3e9), [`5b54692`](https://github.com/pngwn/MDsveX/commit/5b54692d6c895f02c947ce620a46c7a9beb856e9)]:
12
+ - @mdsvex/render@1.0.0-next.0
13
+ - @mdsvex/parse@1.0.0-next.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 pngwn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json CHANGED
@@ -1,15 +1,45 @@
1
1
  {
2
2
  "name": "@mdsvex/source-map",
3
- "version": "0.0.0",
4
- "description": "Placeholder release so npm trusted publishing can be configured.",
5
- "license": "MIT",
6
- "homepage": "https://mdsvex.pngwn.io",
3
+ "version": "0.1.0-next.0",
7
4
  "repository": {
8
5
  "type": "git",
9
- "url": "https://github.com/pngwn/MDsveX",
6
+ "url": "git+https://github.com/pngwn/MDsveX.git",
10
7
  "directory": "language-tools/source-map"
11
8
  },
12
- "publishConfig": {
13
- "access": "public"
9
+ "description": "PFM to Svelte source map pipeline for language tooling",
10
+ "type": "module",
11
+ "exports": {
12
+ ".": {
13
+ "import": "./src/index.ts",
14
+ "types": "./src/index.ts"
15
+ },
16
+ "./pfm-to-svelte": {
17
+ "import": "./src/pfm_to_svelte.ts",
18
+ "types": "./src/pfm_to_svelte.ts"
19
+ },
20
+ "./v3-to-volar": {
21
+ "import": "./src/v3_to_volar.ts",
22
+ "types": "./src/v3_to_volar.ts"
23
+ },
24
+ "./compose-mappings": {
25
+ "import": "./src/compose_mappings.ts",
26
+ "types": "./src/compose_mappings.ts"
27
+ }
28
+ },
29
+ "dependencies": {
30
+ "@jridgewell/trace-mapping": "^0.3.31",
31
+ "@mdsvex/parse": "1.0.0-next.0",
32
+ "@mdsvex/render": "1.0.0-next.0"
33
+ },
34
+ "devDependencies": {
35
+ "svelte": "^5.0.0",
36
+ "svelte2tsx": "^0.7.53",
37
+ "typescript": "^5.0.0"
38
+ },
39
+ "author": "pngwn <hello@pngwn.io>",
40
+ "license": "MIT",
41
+ "scripts": {
42
+ "test": "vitest --disableConsoleIntercept",
43
+ "test:run": "vitest run --silent"
14
44
  }
15
45
  }
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Compose two sets of Volar mappings: A to B + B to C = A to C.
3
+ *
4
+ * For each mapping in A (PFM to Svelte), find overlapping mappings in B
5
+ * (Svelte to TS), and produce composed mappings (PFM to TS).
6
+ */
7
+
8
+ import type { Mapping, CodeInformation } from "@mdsvex/render/mappings";
9
+
10
+ export type { Mapping, CodeInformation } from "@mdsvex/render/mappings";
11
+
12
+ interface Segment {
13
+ srcStart: number;
14
+ srcEnd: number;
15
+ genStart: number;
16
+ genEnd: number;
17
+ }
18
+
19
+ /** extract flat segments from a mapping (handles multi-entry sourceOffsets). */
20
+ function toSegments<T>(m: Mapping<T>): Segment[] {
21
+ const segs: Segment[] = [];
22
+ for (let i = 0; i < m.sourceOffsets.length; i++) {
23
+ const srcLen = m.lengths[i];
24
+ const genLen = m.generatedLengths ? m.generatedLengths[i] : m.lengths[i];
25
+ segs.push({
26
+ srcStart: m.sourceOffsets[i],
27
+ srcEnd: m.sourceOffsets[i] + srcLen,
28
+ genStart: m.generatedOffsets[i],
29
+ genEnd: m.generatedOffsets[i] + genLen,
30
+ });
31
+ }
32
+ return segs;
33
+ }
34
+
35
+ /** merge CodeInformation via intersection: capability present only if both legs have it. */
36
+ function intersectCapabilities(
37
+ a: CodeInformation,
38
+ b: CodeInformation,
39
+ ): CodeInformation {
40
+ const result: CodeInformation = {};
41
+ if (a.verification && b.verification) result.verification = true;
42
+ if (a.completion && b.completion) result.completion = true;
43
+ if (a.semantic && b.semantic) result.semantic = true;
44
+ if (a.navigation && b.navigation) result.navigation = true;
45
+ if (a.structure && b.structure) result.structure = true;
46
+ if (a.format && b.format) result.format = true;
47
+ return result;
48
+ }
49
+
50
+ /**
51
+ * Compose mappings A to B and B to C into A to C.
52
+ *
53
+ * For each A segment that maps A-source to B (generated), finds overlapping
54
+ * B segments that map B-source to C (generated). The overlap region in B-space
55
+ * determines the composed A to C mapping.
56
+ *
57
+ * @param a - Mappings from A to B (e.g., PFM to Svelte)
58
+ * @param b - Mappings from B to C (e.g., Svelte to TS)
59
+ * @param mergeData - Optional custom data merger. Defaults to intersectCapabilities.
60
+ */
61
+ export function composeMappings<
62
+ DA extends CodeInformation,
63
+ DB extends CodeInformation,
64
+ >(
65
+ a: Mapping<DA>[],
66
+ b: Mapping<DB>[],
67
+ mergeData?: (da: DA, db: DB) => DA,
68
+ ): Mapping<DA>[] {
69
+ // flatten B into sorted segments keyed by source offset
70
+ const bSegs: (Segment & { data: DB })[] = [];
71
+ for (const bm of b) {
72
+ const segs = toSegments(bm);
73
+ for (const s of segs) {
74
+ bSegs.push({ ...s, data: bm.data });
75
+ }
76
+ }
77
+ bSegs.sort((x, y) => x.srcStart - y.srcStart);
78
+
79
+ const merge =
80
+ mergeData ??
81
+ ((da: DA, db: DB) => intersectCapabilities(da, db) as DA);
82
+
83
+ const result: Mapping<DA>[] = [];
84
+
85
+ for (const am of a) {
86
+ const aSegs = toSegments(am);
87
+
88
+ for (const aSeg of aSegs) {
89
+ // A maps A-source [aSeg.srcStart, aSeg.srcEnd) to B [aSeg.genStart, aSeg.genEnd)
90
+ // Find B segments whose source range overlaps with A's generated range
91
+ const aGenStart = aSeg.genStart;
92
+ const aGenEnd = aSeg.genEnd;
93
+ const aIsIdentity = aSeg.srcEnd - aSeg.srcStart === aGenEnd - aGenStart;
94
+
95
+ // binary search for first B segment that might overlap
96
+ let lo = 0,
97
+ hi = bSegs.length;
98
+ while (lo < hi) {
99
+ const mid = (lo + hi) >>> 1;
100
+ if (bSegs[mid].srcEnd <= aGenStart) lo = mid + 1;
101
+ else hi = mid;
102
+ }
103
+
104
+ // scan through potentially overlapping B segments
105
+ for (let j = lo; j < bSegs.length; j++) {
106
+ const bSeg = bSegs[j];
107
+ if (bSeg.srcStart >= aGenEnd) break; // past overlap
108
+
109
+ // compute overlap in B-source space (= A's generated space)
110
+ const overlapStart = Math.max(aGenStart, bSeg.srcStart);
111
+ const overlapEnd = Math.min(aGenEnd, bSeg.srcEnd);
112
+ if (overlapEnd <= overlapStart) continue;
113
+
114
+ const overlapLen = overlapEnd - overlapStart;
115
+
116
+ // map overlap back to A-source
117
+ let composedSrcStart: number;
118
+ let composedSrcLen: number;
119
+ if (aIsIdentity) {
120
+ composedSrcStart = aSeg.srcStart + (overlapStart - aGenStart);
121
+ composedSrcLen = overlapLen;
122
+ } else {
123
+ // non-identity A, can only use the start anchor
124
+ composedSrcStart = aSeg.srcStart;
125
+ composedSrcLen = aSeg.srcEnd - aSeg.srcStart;
126
+ }
127
+
128
+ // map overlap forward to C (B's generated space)
129
+ const bIsIdentity =
130
+ bSeg.srcEnd - bSeg.srcStart === bSeg.genEnd - bSeg.genStart;
131
+ let composedGenStart: number;
132
+ let composedGenLen: number;
133
+ if (bIsIdentity) {
134
+ composedGenStart = bSeg.genStart + (overlapStart - bSeg.srcStart);
135
+ composedGenLen = overlapLen;
136
+ } else {
137
+ composedGenStart = bSeg.genStart;
138
+ composedGenLen = bSeg.genEnd - bSeg.genStart;
139
+ }
140
+
141
+ const m: Mapping<DA> = {
142
+ sourceOffsets: [composedSrcStart],
143
+ generatedOffsets: [composedGenStart],
144
+ lengths: [composedSrcLen],
145
+ data: merge(am.data, bSeg.data),
146
+ };
147
+ if (composedGenLen !== composedSrcLen) {
148
+ m.generatedLengths = [composedGenLen];
149
+ }
150
+ result.push(m);
151
+ }
152
+ }
153
+ }
154
+
155
+ return result;
156
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export { pfmToSvelte } from "./pfm_to_svelte";
2
+ export type { PfmToSvelteResult, StyleBlock } from "./pfm_to_svelte";
3
+ export { v3ToVolarMappings } from "./v3_to_volar";
4
+ export { composeMappings } from "./compose_mappings";
@@ -0,0 +1,304 @@
1
+ /**
2
+ * PFM to Svelte component transform with source mappings.
3
+ *
4
+ * Takes PFM source, parses it, and produces a valid Svelte component string
5
+ * along with Volar-compatible source mappings. The output is suitable for
6
+ * feeding into svelte2tsx for TypeScript virtual code generation.
7
+ *
8
+ * Pipeline:
9
+ * PFM source -> parse -> classify nodes -> build <script> block -> render body -> mappings
10
+ */
11
+
12
+ import { PFMParser } from "@mdsvex/parse";
13
+ import { TreeBuilder } from "@mdsvex/parse/tree-builder";
14
+ import { Cursor } from "@mdsvex/parse/cursor";
15
+ import {
16
+ _emit,
17
+ _node,
18
+ _resolve_mappings,
19
+ K_HTML,
20
+ K_LINE_BREAK,
21
+ K_FRONTMATTER,
22
+ K_IMPORT_STATEMENT,
23
+ } from "@mdsvex/render/html-cursor";
24
+ import type { PendingMapping } from "@mdsvex/render/html-cursor";
25
+ import { CI_SVELTE, CI_STRUCTURE } from "@mdsvex/render/mappings";
26
+ import type { Mapping, MappingData } from "@mdsvex/render/mappings";
27
+
28
+ export type { Mapping, MappingData } from "@mdsvex/render/mappings";
29
+
30
+ /** A <style> block found in the PFM source, with positions in both source and generated output. */
31
+ export interface StyleBlock {
32
+ /** Byte offset of the CSS content start in the PFM source. */
33
+ sourceStart: number;
34
+ /** Byte offset of the CSS content end in the PFM source. */
35
+ sourceEnd: number;
36
+ /** Byte offset of the CSS content start in the generated Svelte code. */
37
+ generatedStart: number;
38
+ /** Byte offset of the CSS content end in the generated Svelte code. */
39
+ generatedEnd: number;
40
+ }
41
+
42
+ /** A region in the PFM source to exclude from the markdown VirtualCode. */
43
+ export interface ExcludedRegion {
44
+ /** Byte offset of the region start in the PFM source (includes opening tag/fence). */
45
+ start: number;
46
+ /** Byte offset of the region end in the PFM source (includes closing tag/fence). */
47
+ end: number;
48
+ }
49
+
50
+ export interface PfmToSvelteResult {
51
+ code: string;
52
+ mappings: Mapping<MappingData>[];
53
+ /** Style blocks found in the source, with positions for CSS VirtualCode extraction. */
54
+ styleBlocks: StyleBlock[];
55
+ /** Regions to exclude from the markdown VirtualCode (frontmatter, script, style). */
56
+ excludedRegions: ExcludedRegion[];
57
+ }
58
+
59
+ /** regex to extract top-level YAML key-value pairs (valid JS identifiers only). */
60
+ const YAML_KV_RE = /^([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:(.*)/gm;
61
+
62
+ interface YamlEntry {
63
+ name: string;
64
+ /** byte offset of the key name within the PFM source. */
65
+ sourceOffset: number;
66
+ /** JavaScript literal representation of the value. */
67
+ jsValue: string;
68
+ }
69
+
70
+ /**
71
+ * Convert a YAML scalar value to a JavaScript literal string.
72
+ * Handles numbers, booleans, null, and falls back to string.
73
+ */
74
+ function yamlValueToJs(raw: string): string {
75
+ const v = raw.trim();
76
+ if (v === "" || v === "~" || v === "null") return "null";
77
+ if (v === "true") return "true";
78
+ if (v === "false") return "false";
79
+ // integer or float
80
+ if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(v)) return v;
81
+ // block scalar indicator (|, >, |-, >+, etc.), can't parse inline
82
+ if (/^[|>]/.test(v)) return '"" as string';
83
+ // inline array [a, b] or object {a: b}, too complex, fall back
84
+ if (/^\[/.test(v) || /^\{/.test(v)) return `${v} as any`;
85
+ // plain string, quote it, escaping internal quotes and backslashes
86
+ return JSON.stringify(v);
87
+ }
88
+
89
+ /**
90
+ * Extract top-level YAML key-value pairs from frontmatter text.
91
+ * Only extracts keys that are valid JavaScript identifiers.
92
+ * Values are converted to JavaScript literals for type inference.
93
+ */
94
+ function extractYamlEntries(yaml: string, yamlSourceOffset: number): YamlEntry[] {
95
+ const entries: YamlEntry[] = [];
96
+ YAML_KV_RE.lastIndex = 0;
97
+ let match: RegExpExecArray | null;
98
+ while ((match = YAML_KV_RE.exec(yaml)) !== null) {
99
+ entries.push({
100
+ name: match[1],
101
+ sourceOffset: yamlSourceOffset + match.index,
102
+ jsValue: yamlValueToJs(match[2]),
103
+ });
104
+ }
105
+ return entries;
106
+ }
107
+
108
+ /**
109
+ * Transform PFM source into a valid Svelte component with source mappings.
110
+ *
111
+ * - Frontmatter YAML keys become `let key: any;` declarations in `<script>`
112
+ * - Import statements become verbatim imports in `<script>`
113
+ * - Explicit `<script>` tags are merged into the generated `<script>` block
114
+ * - Body content is rendered as Svelte markup via the existing HTML renderer
115
+ */
116
+ export function pfmToSvelte(source: string): PfmToSvelteResult {
117
+ // parse
118
+ const tree = new TreeBuilder(source.length >> 3 || 128);
119
+ const parser = new PFMParser(tree);
120
+ parser.parse(source);
121
+ const buf = tree.get_buffer();
122
+
123
+ // classify root children
124
+ const cursor = new Cursor(buf, source);
125
+ cursor.reset();
126
+
127
+ let frontmatterNode: { valueStart: number; valueEnd: number } | null = null;
128
+ const importNodes: { valueStart: number; valueEnd: number }[] = [];
129
+ const scriptBodies: { valueStart: number; valueEnd: number }[] = [];
130
+ const bodySkipSet = new Set<number>();
131
+ const excludedRegions: ExcludedRegion[] = [];
132
+
133
+ if (cursor.goto_first_child()) {
134
+ do {
135
+ const kind = cursor.kind;
136
+ if (kind === K_FRONTMATTER) {
137
+ frontmatterNode = {
138
+ valueStart: cursor.value_start,
139
+ valueEnd: cursor.value_end,
140
+ };
141
+ excludedRegions.push({ start: cursor.start, end: cursor.end });
142
+ bodySkipSet.add(cursor.index);
143
+ } else if (kind === K_IMPORT_STATEMENT) {
144
+ importNodes.push({
145
+ valueStart: cursor.value_start,
146
+ valueEnd: cursor.value_end,
147
+ });
148
+ excludedRegions.push({ start: cursor.start, end: cursor.end });
149
+ bodySkipSet.add(cursor.index);
150
+ } else if (kind === K_HTML && cursor.meta()?.tag === "script") {
151
+ scriptBodies.push({
152
+ valueStart: cursor.value_start,
153
+ valueEnd: cursor.value_end,
154
+ });
155
+ excludedRegions.push({ start: cursor.start, end: cursor.end });
156
+ bodySkipSet.add(cursor.index);
157
+ }
158
+ } while (cursor.goto_next_sibling());
159
+ cursor.goto_parent();
160
+ }
161
+
162
+ const hasFrontmatter = frontmatterNode !== null;
163
+ const hasInstanceScript = importNodes.length > 0 || scriptBodies.length > 0;
164
+
165
+ const out: string[] = [];
166
+ const entries: PendingMapping[] = [];
167
+
168
+ // Phase A1: Build <script module> block for frontmatter exports
169
+ // Module-level exports are importable from .ts files AND accessible in template
170
+ if (hasFrontmatter) {
171
+ const moduleStart = out.length;
172
+ out.push("<script module lang=\"ts\">\n");
173
+
174
+ const yaml = source.slice(
175
+ frontmatterNode!.valueStart,
176
+ frontmatterNode!.valueEnd,
177
+ );
178
+ const fmEntries = extractYamlEntries(yaml, frontmatterNode!.valueStart);
179
+ for (const entry of fmEntries) {
180
+ out.push("export const ");
181
+ // character-level mapping for the key name
182
+ _emit(
183
+ entries,
184
+ out.length,
185
+ out.length + 1,
186
+ entry.sourceOffset,
187
+ entry.sourceOffset + entry.name.length,
188
+ { ...CI_SVELTE, nodeIndex: -1, role: "content" },
189
+ );
190
+ out.push(entry.name, " = ", entry.jsValue, ";\n");
191
+ }
192
+
193
+ out.push("</script>\n\n");
194
+
195
+ _emit(
196
+ entries,
197
+ moduleStart,
198
+ out.length,
199
+ 0,
200
+ 0,
201
+ { ...CI_STRUCTURE, nodeIndex: -1, role: "node" },
202
+ );
203
+ }
204
+
205
+ // Phase A2: Build <script> block for imports and user code (instance scope)
206
+ if (hasInstanceScript) {
207
+ const scriptStart = out.length;
208
+ out.push("<script lang=\"ts\">\n");
209
+
210
+ // imports (verbatim, identity-mapped)
211
+ for (const imp of importNodes) {
212
+ const text = source.slice(imp.valueStart, imp.valueEnd);
213
+ _emit(
214
+ entries,
215
+ out.length,
216
+ out.length + 1,
217
+ imp.valueStart,
218
+ imp.valueEnd,
219
+ { ...CI_SVELTE, nodeIndex: -1, role: "content" },
220
+ );
221
+ out.push(text, "\n");
222
+ }
223
+
224
+ // existing <script> body content (identity-mapped)
225
+ for (const script of scriptBodies) {
226
+ const text = source.slice(script.valueStart, script.valueEnd);
227
+ if (text.length > 0) {
228
+ _emit(
229
+ entries,
230
+ out.length,
231
+ out.length + 1,
232
+ script.valueStart,
233
+ script.valueEnd,
234
+ { ...CI_SVELTE, nodeIndex: -1, role: "content" },
235
+ );
236
+ out.push(text, "\n");
237
+ }
238
+ }
239
+
240
+ out.push("</script>\n\n");
241
+
242
+ _emit(
243
+ entries,
244
+ scriptStart,
245
+ out.length,
246
+ 0,
247
+ 0,
248
+ { ...CI_STRUCTURE, nodeIndex: -1, role: "node" },
249
+ );
250
+ }
251
+
252
+ // Phase B: Collect style block source positions before body rendering
253
+ const styleSourcePositions: { valueStart: number; valueEnd: number }[] = [];
254
+ cursor.reset();
255
+ if (cursor.goto_first_child()) {
256
+ do {
257
+ if (
258
+ cursor.kind === K_HTML &&
259
+ cursor.meta()?.tag === "style" &&
260
+ !bodySkipSet.has(cursor.index)
261
+ ) {
262
+ styleSourcePositions.push({
263
+ valueStart: cursor.value_start,
264
+ valueEnd: cursor.value_end,
265
+ });
266
+ excludedRegions.push({ start: cursor.start, end: cursor.end });
267
+ }
268
+ } while (cursor.goto_next_sibling());
269
+ cursor.goto_parent();
270
+ }
271
+
272
+ // Phase C: Render body nodes (skip frontmatter, imports, scripts)
273
+ cursor.reset();
274
+ if (cursor.goto_first_child()) {
275
+ do {
276
+ if (cursor.kind === K_LINE_BREAK) continue;
277
+ if (bodySkipSet.has(cursor.index)) continue;
278
+ _node(cursor, out, entries);
279
+ } while (cursor.goto_next_sibling());
280
+ cursor.goto_parent();
281
+ }
282
+
283
+ // resolve mappings
284
+ const code = out.join("");
285
+ const mappings = _resolve_mappings(out, entries);
286
+
287
+ // Phase D: Locate style blocks in generated output by matching source content
288
+ const styleBlocks: StyleBlock[] = [];
289
+ for (const sp of styleSourcePositions) {
290
+ const cssContent = source.slice(sp.valueStart, sp.valueEnd);
291
+ // find this exact CSS content in the generated code
292
+ const genIdx = code.indexOf(cssContent);
293
+ if (genIdx !== -1) {
294
+ styleBlocks.push({
295
+ sourceStart: sp.valueStart,
296
+ sourceEnd: sp.valueEnd,
297
+ generatedStart: genIdx,
298
+ generatedEnd: genIdx + cssContent.length,
299
+ });
300
+ }
301
+ }
302
+
303
+ return { code, mappings, styleBlocks, excludedRegions };
304
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Convert v3 source maps (VLQ line/column) to Volar offset-based Mapping[].
3
+ *
4
+ * Decodes a standard SourceMapV3 (as emitted by svelte2tsx) and produces
5
+ * coalesced range mappings suitable for Volar's SourceMap.
6
+ */
7
+
8
+ import { TraceMap, decodedMappings } from "@jridgewell/trace-mapping";
9
+ import { build_line_starts } from "@mdsvex/render/sourcemap";
10
+ import { CI_SVELTE } from "@mdsvex/render/mappings";
11
+ import type { Mapping, CodeInformation } from "@mdsvex/render/mappings";
12
+
13
+ export type { Mapping, CodeInformation } from "@mdsvex/render/mappings";
14
+
15
+ export interface SourceMapV3 {
16
+ version: 3;
17
+ file?: string;
18
+ sources: (string | null)[];
19
+ sourcesContent?: (string | null)[];
20
+ names?: string[];
21
+ mappings: string;
22
+ }
23
+
24
+ interface PointMapping {
25
+ genOffset: number;
26
+ srcOffset: number;
27
+ }
28
+
29
+ /**
30
+ * Convert a v3 source map to Volar-compatible Mapping[] format.
31
+ *
32
+ * Decodes VLQ segments, converts line/column to offsets, and coalesces
33
+ * adjacent identity-mapped points into compact range mappings.
34
+ */
35
+ export function v3ToVolarMappings(
36
+ v3Map: SourceMapV3,
37
+ generatedCode: string,
38
+ sourceCode: string,
39
+ defaultData?: CodeInformation,
40
+ ): Mapping<CodeInformation>[] {
41
+ const traced = new TraceMap(v3Map as any);
42
+ const decoded = decodedMappings(traced);
43
+
44
+ const srcLineStarts = build_line_starts(sourceCode);
45
+ const genLineStarts = build_line_starts(generatedCode);
46
+
47
+ // collect point mappings
48
+ const points: PointMapping[] = [];
49
+
50
+ for (let genLine = 0; genLine < decoded.length; genLine++) {
51
+ const segments = decoded[genLine];
52
+ if (!segments) continue;
53
+
54
+ for (const seg of segments) {
55
+ // segments with source info have >= 4 fields: [genCol, srcIdx, srcLine, srcCol]
56
+ if (seg.length < 4) continue;
57
+
58
+ const genCol = seg[0];
59
+ const srcLine = seg[2];
60
+ const srcCol = seg[3];
61
+
62
+ const genOff =
63
+ genLine < genLineStarts.length
64
+ ? genLineStarts[genLine] + genCol
65
+ : genCol;
66
+ const srcOff =
67
+ srcLine < srcLineStarts.length
68
+ ? srcLineStarts[srcLine] + srcCol
69
+ : srcCol;
70
+
71
+ points.push({ genOffset: genOff, srcOffset: srcOff });
72
+ }
73
+ }
74
+
75
+ // sort by generated offset
76
+ points.sort((a, b) => a.genOffset - b.genOffset);
77
+
78
+ // coalesce adjacent identity-mapped points into ranges
79
+ const data = defaultData ?? CI_SVELTE;
80
+ const mappings: Mapping<CodeInformation>[] = [];
81
+ let i = 0;
82
+
83
+ while (i < points.length) {
84
+ const start = points[i];
85
+ let runLen = 1;
86
+
87
+ // extend run while consecutive points are identity-mapped (delta gen === delta src === 1)
88
+ while (i + runLen < points.length) {
89
+ const prev = points[i + runLen - 1];
90
+ const next = points[i + runLen];
91
+ const genDelta = next.genOffset - prev.genOffset;
92
+ const srcDelta = next.srcOffset - prev.srcOffset;
93
+ if (genDelta === 1 && srcDelta === 1) {
94
+ runLen++;
95
+ } else if (genDelta === srcDelta && genDelta > 0) {
96
+ // larger identity stride (e.g., both advance by same amount)
97
+ // treat as a single range up to this point, then start new range
98
+ break;
99
+ } else {
100
+ break;
101
+ }
102
+ }
103
+
104
+ mappings.push({
105
+ sourceOffsets: [start.srcOffset],
106
+ generatedOffsets: [start.genOffset],
107
+ lengths: [runLen],
108
+ data,
109
+ });
110
+
111
+ i += runLen;
112
+ }
113
+
114
+ return mappings;
115
+ }