@mdsvex/render 1.0.0-next.0 → 1.0.0-next.1

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.
@@ -0,0 +1,225 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { PFMParser } from '@mdsvex/parse';
3
+ import { TreeBuilder } from '@mdsvex/parse/tree-builder';
4
+ import { CursorHTMLRenderer } from '../src/html_cursor';
5
+
6
+ function parse(source: string) {
7
+ const tree = new TreeBuilder(source.length >> 3 || 128);
8
+ new PFMParser(tree).parse(source);
9
+ return tree.get_buffer();
10
+ }
11
+
12
+ /** the html of every render path, which must agree */
13
+ function render_all(source: string, module_code = ''): string[] {
14
+ const buf = parse(source);
15
+ const plain = new CursorHTMLRenderer({ cache: false });
16
+ plain.update(buf, source, module_code);
17
+ const cached = new CursorHTMLRenderer();
18
+ cached.update(buf, source, module_code);
19
+ const mapped = new CursorHTMLRenderer({ cache: false });
20
+ mapped.update_mapped(buf, source, null, module_code);
21
+ const v3 = new CursorHTMLRenderer({ cache: false });
22
+ v3.update_v3(buf, source, source, undefined, module_code);
23
+ const trace = new CursorHTMLRenderer({ cache: false });
24
+ trace.update_trace(buf, source, module_code);
25
+ return [plain.html, cached.html, mapped.html, v3.html, trace.html];
26
+ }
27
+
28
+ function render(source: string, module_code = ''): string {
29
+ const all = render_all(source, module_code);
30
+ for (const html of all) expect(html).toBe(all[0]);
31
+ return all[0];
32
+ }
33
+
34
+ describe('bare imports', () => {
35
+ it('become a script when the document has none', () => {
36
+ expect(
37
+ render("import Chart from './Chart.svelte'\n\n# Hi\n\n<Chart />\n")
38
+ ).toBe(
39
+ "<script>\nimport Chart from './Chart.svelte'\n</script><h1>Hi</h1><Chart />"
40
+ );
41
+ });
42
+
43
+ it('share one script', () => {
44
+ expect(
45
+ render("import A from './A.svelte'\nimport { b } from 'b'\n\n<A />\n")
46
+ ).toBe(
47
+ "<script>\nimport A from './A.svelte'\nimport { b } from 'b'\n</script><A />"
48
+ );
49
+ });
50
+
51
+ it('go into the instance script', () => {
52
+ expect(
53
+ render(
54
+ "import Chart from './Chart.svelte'\n\n<script>\n let x = 1;\n</script>\n\n<Chart />\n"
55
+ )
56
+ ).toBe(
57
+ "<script>\nimport Chart from './Chart.svelte'\n\n let x = 1;\n</script><Chart />"
58
+ );
59
+ });
60
+
61
+ it('skip a module script for the instance script', () => {
62
+ expect(
63
+ render(
64
+ 'import A from \'a\'\n\n<script module>\n export const m = 1;\n</script>\n\n<script lang="ts">\n let x = 1;\n</script>\n'
65
+ )
66
+ ).toBe(
67
+ '<script module>\n export const m = 1;\n</script><script lang="ts">\nimport A from \'a\'\n\n let x = 1;\n</script>'
68
+ );
69
+ });
70
+
71
+ it('make their own script beside a module script only', () => {
72
+ expect(
73
+ render('import A from \'a\'\n\n<script context="module">\n</script>\n')
74
+ ).toBe(
75
+ '<script>\nimport A from \'a\'\n</script><script context="module">\n</script>'
76
+ );
77
+ });
78
+
79
+ it('map to their source', () => {
80
+ const source = "import A from 'a'\n\n<A />\n";
81
+ const r = new CursorHTMLRenderer({ cache: false });
82
+ const { mappings } = r.update_mapped(parse(source), source);
83
+ const at = r.html.indexOf("import A from 'a'");
84
+ const hit = mappings.find((m) => m.generatedOffsets[0] === at);
85
+ expect(hit?.sourceOffsets[0]).toBe(0);
86
+ expect(hit?.lengths[0]).toBe("import A from 'a'".length);
87
+ });
88
+ });
89
+
90
+ describe('top level external scripts', () => {
91
+ const embed =
92
+ '<blockquote class="twitter-tweet"><p>Hi</p>by H</blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>\n';
93
+
94
+ it('render as svelte:element', () => {
95
+ expect(render(embed + '\n' + embed)).toBe(
96
+ (
97
+ '<blockquote class="twitter-tweet"><p>Hi</p>by H</blockquote> ' +
98
+ '<svelte:element this={"script"} async src="https://platform.twitter.com/widgets.js" charset="utf-8"></svelte:element>'
99
+ ).repeat(2)
100
+ );
101
+ });
102
+
103
+ it('leave the instance script alone', () => {
104
+ expect(
105
+ render(
106
+ '<script>\n let x = 1;\n</script>\n\n<script src="a.js"></script>\n'
107
+ )
108
+ ).toBe(
109
+ '<script>\n let x = 1;\n</script><svelte:element this={"script"} src="a.js"></svelte:element>'
110
+ );
111
+ });
112
+
113
+ it('stay scripts inside markup', () => {
114
+ expect(render('<div>\n<script src="a.js"></script>\n</div>\n')).toBe(
115
+ '<div><script src="a.js"></script></div>'
116
+ );
117
+ });
118
+
119
+ it('stay scripts with a body', () => {
120
+ expect(render('<script src="a.js">x()</script>\n')).toBe(
121
+ '<script src="a.js">x()</script>'
122
+ );
123
+ });
124
+ });
125
+
126
+ describe('module code', () => {
127
+ const code = 'export const metadata = {"title":"Hi"};';
128
+
129
+ it('renders as a module script in place of the frontmatter', () => {
130
+ expect(render('---\ntitle: Hi\n---\n\n# Hi\n', code)).toBe(
131
+ '<script module>\n' + code + '\n</script><h1>Hi</h1>'
132
+ );
133
+ });
134
+
135
+ it('goes into the module script', () => {
136
+ expect(
137
+ render(
138
+ '---\ntitle: Hi\n---\n\n<script module>\n export const x = 1;\n</script>\n\n# Hi\n',
139
+ code
140
+ )
141
+ ).toBe(
142
+ '<script module>\n' +
143
+ code +
144
+ '\n\n export const x = 1;\n</script><h1>Hi</h1>'
145
+ );
146
+ });
147
+
148
+ it('goes into a svelte 4 module script after the instance script', () => {
149
+ expect(
150
+ render(
151
+ '---\ntitle: Hi\n---\n<script>\n let y = 2;\n</script>\n\n<script context="module" lang="ts">\n export const x = 1;\n</script>\n',
152
+ code
153
+ )
154
+ ).toBe(
155
+ '<script>\n let y = 2;\n</script><script context="module" lang="ts">\n' +
156
+ code +
157
+ '\n\n export const x = 1;\n</script>'
158
+ );
159
+ });
160
+
161
+ it('shares the document with hoisted imports', () => {
162
+ expect(
163
+ render(
164
+ "---\ntitle: Hi\n---\nimport A from 'a'\n\n<script module>\n</script>\n\n<A />\n",
165
+ code
166
+ )
167
+ ).toBe(
168
+ "<script>\nimport A from 'a'\n</script><script module>\n" +
169
+ code +
170
+ '\n\n</script><A />'
171
+ );
172
+ expect(
173
+ render("---\ntitle: Hi\n---\nimport A from 'a'\n\n<A />\n", code)
174
+ ).toBe(
175
+ '<script module>\n' +
176
+ code +
177
+ "\n</script><script>\nimport A from 'a'\n</script><A />"
178
+ );
179
+ });
180
+
181
+ it('skips nested and external module scripts', () => {
182
+ expect(
183
+ render(
184
+ '---\ntitle: Hi\n---\n<div>\n<script module>\n</script>\n</div>\n\n<script module src="a.js"></script>\n',
185
+ code
186
+ )
187
+ ).toBe(
188
+ '<script module>\n' +
189
+ code +
190
+ '\n</script><div><script module>\n</script></div><svelte:element this={"script"} module src="a.js"></svelte:element>'
191
+ );
192
+ });
193
+
194
+ it('renders nothing without code', () => {
195
+ expect(render('---\ntitle: Hi\n---\n\n# Hi\n')).toBe('<h1>Hi</h1>');
196
+ });
197
+
198
+ it('is not cached between updates', () => {
199
+ const source = '---\ntitle: Hi\n---\n\n# Hi\n';
200
+ const buf = parse(source);
201
+ const r = new CursorHTMLRenderer();
202
+ r.update(buf, source, code);
203
+ r.update(buf, source, 'export const metadata = {};');
204
+ expect(r.html).toBe(
205
+ '<script module>\nexport const metadata = {};\n</script><h1>Hi</h1>'
206
+ );
207
+ });
208
+
209
+ it('leaves the instance script mapped to its source', () => {
210
+ const source =
211
+ '---\ntitle: Hi\n---\n<script module>\nlet m = 1;\n</script>\n';
212
+ const r = new CursorHTMLRenderer({ cache: false });
213
+ const { mappings } = r.update_mapped(parse(source), source, null, code);
214
+ const at = r.html.indexOf('let m = 1;');
215
+ const hit = mappings.find(
216
+ (m) =>
217
+ m.generatedOffsets[0] <= at &&
218
+ at < m.generatedOffsets[0] + m.lengths[0] &&
219
+ m.generatedLengths === undefined
220
+ );
221
+ expect(hit).toBeDefined();
222
+ const s = hit!.sourceOffsets[0] + (at - hit!.generatedOffsets[0]);
223
+ expect(source.slice(s, s + 10)).toBe('let m = 1;');
224
+ });
225
+ });
@@ -0,0 +1,247 @@
1
+ import { readdirSync, readFileSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ import { decode, encode } from '@jridgewell/sourcemap-codec';
6
+ import type { SourceMapMappings } from '@jridgewell/sourcemap-codec';
7
+ import { describe, expect, it } from 'vitest';
8
+ import { PFMParser } from '@mdsvex/parse';
9
+ import { TreeBuilder } from '@mdsvex/parse/tree-builder';
10
+
11
+ import { CursorHTMLRenderer, _capture_trace, _emit } from '../src/html_cursor';
12
+ import {
13
+ MapSink,
14
+ P_CODE,
15
+ P_STRUCTURE,
16
+ P_SVELTE,
17
+ P_TEXT,
18
+ R_CLOSE_SYNTAX,
19
+ R_CONTENT,
20
+ R_NODE,
21
+ R_OPEN_SYNTAX,
22
+ record_code,
23
+ } from '../src/mappings';
24
+ import {
25
+ mapped_source_lines,
26
+ trace_to_decoded,
27
+ trace_to_v3,
28
+ } from '../src/sourcemap';
29
+ import type { MapTrace } from '../src/sourcemap';
30
+
31
+ const FIXTURES = resolve(
32
+ dirname(fileURLToPath(import.meta.url)),
33
+ '../../parse/test/fixtures'
34
+ );
35
+
36
+ function fixture_files(dir: string): string[] {
37
+ const files: string[] = [];
38
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
39
+ const path = join(dir, entry.name);
40
+ if (entry.isDirectory()) files.push(...fixture_files(path));
41
+ else if (/\.(md|svx)$/.test(entry.name)) files.push(path);
42
+ }
43
+ return files.sort();
44
+ }
45
+
46
+ const DOCS = [
47
+ '',
48
+ 'plain\n',
49
+ '# Title\n\nSome *emphasis* and `code` and [a link](/x).\n',
50
+ '> quote\n> more\n\n- a\n- b\n\n1. one\n2. two\n',
51
+ '<script>\n\tlet x = 1;\n</script>\n\n{x} and {#if x}yes{/if}\n',
52
+ '```js\nconst a = 1;\nconst b = 2;\n```\n\n| a | b |\n| - | - |\n| 1 | 2 |\n',
53
+ 'line one\r\nline two\rline three\n\ntext &amp; <b>html</b>\n',
54
+ 'a \nb\\\nc\n\n***\n\n<div>\n\nx\n\n</div>\n',
55
+ '| h || *a* | b || r |\n|---||:-:|---||--:|\n| 1 || `x` |> | 2 |\n|^ ||^ |^ | 3 |\n',
56
+ ];
57
+
58
+ function render(source: string) {
59
+ const tree = new TreeBuilder(source.length >> 3 || 128);
60
+ new PFMParser(tree).parse(source);
61
+ return tree.get_buffer();
62
+ }
63
+
64
+ function full_lines(map: { mappings: string }, count: number) {
65
+ const decoded = decode(map.mappings);
66
+ const lines: SourceMapMappings = [];
67
+ for (let i = 0; i < count; i++) lines.push(decoded[i] ?? []);
68
+ return lines;
69
+ }
70
+
71
+ function check_trace(trace: MapTrace, source: string, html: string) {
72
+ const full = trace_to_v3(trace, source, html, '/a/doc.svx');
73
+ const count = html.split(/\r\n|\r|\n/).length;
74
+ const want = full_lines(full, count);
75
+
76
+ const every = Array.from({ length: count + 2 }, (_, i) => i);
77
+ const all = trace_to_decoded(trace, source, html, every, '/a/doc.svx');
78
+ expect({ ...all, mappings: '' }).toEqual({ ...full, mappings: '' });
79
+ for (let i = 0; i < count + 2; i++) {
80
+ expect(all.mappings[i] ?? [], `line ${i}`).toEqual(want[i] ?? []);
81
+ }
82
+
83
+ const some = every.filter((i) => i % 3 === 1);
84
+ const sparse = trace_to_decoded(trace, source, html, some, '/a/doc.svx');
85
+ for (let i = 0; i < sparse.mappings.length; i++) {
86
+ const expected = i % 3 === 1 ? (want[i] ?? []) : [];
87
+ expect(sparse.mappings[i], `sparse line ${i}`).toEqual(expected);
88
+ }
89
+ expect(trace_to_decoded(trace, source, html, []).mappings).toEqual([]);
90
+ }
91
+
92
+ describe('update_trace', () => {
93
+ it.each(DOCS)('trace_to_v3 equals update_v3: %j', (source) => {
94
+ const nodes = render(source);
95
+ const fused = new CursorHTMLRenderer({ cache: false });
96
+ const want = fused.update_v3(nodes, source, source, '/a/doc.svx');
97
+ const renderer = new CursorHTMLRenderer({ cache: false });
98
+ const trace = renderer.update_trace(nodes, source);
99
+ expect(renderer.html).toBe(fused.html);
100
+ expect(
101
+ JSON.stringify(trace_to_v3(trace, source, renderer.html, '/a/doc.svx'))
102
+ ).toBe(JSON.stringify(want));
103
+ });
104
+
105
+ it('keeps its trace when the renderer renders again', () => {
106
+ const renderer = new CursorHTMLRenderer({ cache: false });
107
+ const first = renderer.update_trace(render(DOCS[2]), DOCS[2]);
108
+ const html = renderer.html;
109
+ const before = JSON.stringify(trace_to_v3(first, DOCS[2], html));
110
+ renderer.update_trace(render(DOCS[5]), DOCS[5]);
111
+ expect(JSON.stringify(trace_to_v3(first, DOCS[2], html))).toBe(before);
112
+ });
113
+
114
+ it('keeps traces apart across slabs and for large documents', () => {
115
+ const large = Array.from(
116
+ { length: 400 },
117
+ (_, i) => `para ${i} with *em* and \`code\`\n`
118
+ ).join('\n');
119
+ const sources = [...DOCS, large];
120
+ const renderer = new CursorHTMLRenderer({ cache: false });
121
+ const kept: { trace: MapTrace; source: string; html: string }[] = [];
122
+ const want: string[] = [];
123
+ for (let round = 0; round < 200; round++) {
124
+ const source = sources[round % sources.length];
125
+ const trace = renderer.update_trace(render(source), source);
126
+ const html = renderer.html;
127
+ expect(trace.split - trace.start).toBeGreaterThanOrEqual(0);
128
+ expect(trace.end).toBeLessThanOrEqual(trace.buf.length);
129
+ kept.push({ trace, source, html });
130
+ const fused = new CursorHTMLRenderer({ cache: false });
131
+ want.push(
132
+ JSON.stringify(fused.update_v3(render(source), source, source))
133
+ );
134
+ }
135
+ for (let i = 0; i < kept.length; i++) {
136
+ const { trace, source, html } = kept[i];
137
+ expect(
138
+ JSON.stringify(trace_to_v3(trace, source, html)),
139
+ `trace ${i}`
140
+ ).toBe(want[i]);
141
+ }
142
+ const regions = kept
143
+ .map(({ trace }) => trace)
144
+ .filter((t) => t.end > t.start);
145
+ const bufs = new Set(regions.map((t) => t.buf));
146
+ expect(bufs.size).toBeGreaterThan(3);
147
+ const last = kept[sources.length - 1].trace;
148
+ expect(last.start === 0 && last.end === last.buf.length).toBe(true);
149
+ for (let i = 0; i < regions.length; i++) {
150
+ for (let j = i + 1; j < regions.length; j++) {
151
+ const a = regions[i];
152
+ const b = regions[j];
153
+ if (a.buf !== b.buf) continue;
154
+ expect(a.end <= b.start || b.end <= a.start).toBe(true);
155
+ }
156
+ }
157
+ });
158
+ });
159
+
160
+ describe('trace_to_decoded', () => {
161
+ it.each(DOCS)('matches the decoded full map: %j', (source) => {
162
+ const renderer = new CursorHTMLRenderer({ cache: false });
163
+ const trace = renderer.update_trace(render(source), source);
164
+ check_trace(trace, source, renderer.html);
165
+ });
166
+
167
+ it('matches the decoded full map for every parser fixture', () => {
168
+ const files = fixture_files(FIXTURES);
169
+ expect(files.length).toBeGreaterThan(100);
170
+ const renderer = new CursorHTMLRenderer({ cache: false });
171
+ for (const file of files) {
172
+ const source = readFileSync(file, 'utf8');
173
+ const trace = renderer.update_trace(render(source), source);
174
+ check_trace(trace, source, renderer.html);
175
+ }
176
+ });
177
+
178
+ it('orders overlapping runs one character at a time like the encoder', () => {
179
+ const source = 'abcdef\nghijkl\nmnopqr\n';
180
+ const out = ['abc', 'd\nf', 'X', 'yz\n', 'w'];
181
+ const sink = new MapSink();
182
+ sink.begin(true);
183
+ _emit(sink, 0, 2, 0, 6, 0, record_code(P_TEXT, R_CONTENT));
184
+ _emit(sink, 1, 2, 8, 9, 1, record_code(P_CODE, R_CONTENT));
185
+ _emit(sink, 2, 3, 14, 15, 2, record_code(P_SVELTE, R_NODE));
186
+ _emit(sink, 3, 4, 7, 10, 3, record_code(P_TEXT, R_CONTENT));
187
+ _emit(sink, 1, 2, 3, 3, 3, record_code(P_TEXT, R_CONTENT));
188
+ _emit(sink, 0, 1, 0, 0, 0, record_code(P_STRUCTURE, R_OPEN_SYNTAX));
189
+ _emit(sink, 4, 5, 20, 21, 4, record_code(P_STRUCTURE, R_CLOSE_SYNTAX));
190
+ const trace = _capture_trace(sink, out);
191
+ check_trace(trace, source, out.join(''));
192
+ });
193
+ });
194
+
195
+ describe('mapped_source_lines', () => {
196
+ function lines_of(mappings: SourceMapMappings) {
197
+ const lines = new Set<number>();
198
+ for (const line of mappings)
199
+ for (const segment of line) if (segment.length > 1) lines.add(segment[2]);
200
+ return [...lines].sort((a, b) => a - b);
201
+ }
202
+ const sorted = (lines: number[] | null) =>
203
+ lines && [...new Set(lines)].sort((a, b) => a - b);
204
+
205
+ it('finds the source lines of encoded and decoded mappings', () => {
206
+ const cases: SourceMapMappings[] = [
207
+ [],
208
+ [[]],
209
+ [[[0]], [], [[4], [7]]],
210
+ [[[0, 0, 0, 0], [3]], [[1, 0, 5, 2, 0]], [], [[0, 0, 2, 9]]],
211
+ [
212
+ [
213
+ [0, 0, 900, 0],
214
+ [2, 0, 17, 33],
215
+ [5, 0, 0, 1],
216
+ ],
217
+ [[1, 0, 1000000, 2]],
218
+ ],
219
+ ];
220
+ for (const mappings of cases) {
221
+ const want = lines_of(mappings);
222
+ expect(sorted(mapped_source_lines(encode(mappings)))).toEqual(want);
223
+ expect(sorted(mapped_source_lines(mappings))).toEqual(want);
224
+ }
225
+ });
226
+
227
+ it('gives up on mappings decoders could read differently', () => {
228
+ const bad = [
229
+ 'AA', // two fields
230
+ 'AAA', // three fields
231
+ 'AAAAAA', // six fields
232
+ 'A,,A', // an empty segment
233
+ 'AACA,ACBA', // a second source
234
+ 'AABA', // a negative zero line
235
+ 'A!AA', // not a base64 digit
236
+ 'AAg', // a value cut short
237
+ 'AAggggggggA', // a value too long for int32
238
+ ];
239
+ for (const mappings of bad) {
240
+ expect(mapped_source_lines(mappings), mappings).toBeNull();
241
+ }
242
+ expect(mapped_source_lines([[[0, 1, 0, 0]]])).toBeNull();
243
+ expect(mapped_source_lines([[[0, 0]]])).toBeNull();
244
+ expect(mapped_source_lines([[[0, 0, -1, 0]]])).toBeNull();
245
+ expect(mapped_source_lines({} as never)).toBeNull();
246
+ });
247
+ });
@@ -107,12 +107,29 @@ describe('WireTreeBuilder produces same HTML as TreeBuilder', () => {
107
107
  assert_same(
108
108
  '| left | center | right |\n| :--- | :---: | ---: |\n| a | b | c |\n'
109
109
  ));
110
+ describe('extended tables', () => {
111
+ const sources = [
112
+ '| h || a || r |\n|:--||---||--:|\n| 1 || 2 || 3 |\n',
113
+ '| a | b |> | c |\n|---|---|---|---|\n| 1 | 2 |> |> |\n',
114
+ '| a | b | c |\n|:-:|---|--:|\n| x |> | 1 |\n|^ |^ | 2 |\n|^ |^ | 3 |\n',
115
+ '| h || a | b |\n|---||---|---|\n| 1 || x |> |\n|^ || y | z |\n',
116
+ ];
117
+ it.each(sources)('%j', (source) => {
118
+ assert_same(source);
119
+ assert_same_incremental(source);
120
+ expect(via_tree(source)).toMatch(/colspan|scope/);
121
+ });
122
+ });
110
123
 
111
124
  it('html self-closing', () => assert_same('text <br /> more\n'));
112
125
  it('html paired', () => assert_same('text <span>inside</span> end\n'));
113
126
  it('html block', () =>
114
127
  assert_same('<section>\n\n# Heading\n\nParagraph.\n\n</section>\n'));
115
128
  it('html comment', () => assert_same('text <!-- hidden --> more\n'));
129
+ it('html attribute values as typed', () =>
130
+ assert_same(
131
+ `text <span title='"a" &amp; <b>'>x</span> <img alt="a &amp; b" />\n`
132
+ ));
116
133
 
117
134
  it('code span with leading space preserved', () => assert_same('` a`\n'));
118
135
  it('code span with both spaces stripped', () =>