@mdsvex/source-map 0.1.0-next.0 → 0.1.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.
@@ -81,10 +81,12 @@ describe("pfmToSvelte", () => {
81
81
  const result = pfmToSvelte(source);
82
82
  assertMappingsValid(source, result);
83
83
 
84
- expect(result.code).toContain("<script");
85
- expect(result.code).toContain("export const title = ");
84
+ // the metadata export compile emits, with bare keys
85
+ expect(result.code).toContain("<script module>");
86
+ expect(result.code).toContain('export const metadata = {title: "hello"};');
86
87
  expect(result.code).toContain("</script>");
87
88
  expect(result.code).toContain("<h1>Hello</h1>");
89
+ expect(result.metadata).toEqual({ title: "hello" });
88
90
 
89
91
  // title key maps back to source
90
92
  const titleMapping = findContentByGenerated(
@@ -126,14 +128,14 @@ describe("pfmToSvelte", () => {
126
128
  const result = pfmToSvelte(source);
127
129
  assertMappingsValid(source, result);
128
130
 
129
- expect(result.code).toContain("<script");
130
131
  expect(result.code).toContain('import A from "./A.svelte"');
131
- expect(result.code).toContain("export const title = ");
132
+ expect(result.code).toContain("export const metadata = {title: ");
132
133
 
133
134
  // frontmatter exports in <script module>, imports in <script>
134
- const moduleIdx = result.code.indexOf("<script module");
135
- const scriptIdx = result.code.indexOf("<script lang");
136
- expect(moduleIdx).toBeLessThan(scriptIdx);
135
+ const module = /<script module>[^]*?<\/script>/.exec(result.code)![0];
136
+ const instance = /<script>[^]*?<\/script>/.exec(result.code)![0];
137
+ expect(module).toContain("export const metadata");
138
+ expect(instance).toContain('import A from "./A.svelte"');
137
139
  });
138
140
 
139
141
  it("multiple imports", () => {
@@ -152,9 +154,9 @@ describe("pfmToSvelte", () => {
152
154
  const result = pfmToSvelte(source);
153
155
  assertMappingsValid(source, result);
154
156
 
155
- expect(result.code).toContain("export const title = ");
156
- expect(result.code).toContain("export const count = ");
157
- expect(result.code).toContain("const description = ");
157
+ expect(result.code).toContain(
158
+ 'export const metadata = {title: "hello", count: 42, description: "world"};',
159
+ );
158
160
 
159
161
  // each key maps to its source position
160
162
  for (const keyName of ["title", "count", "description"]) {
@@ -170,12 +172,17 @@ describe("pfmToSvelte", () => {
170
172
  const result = pfmToSvelte(source);
171
173
  assertMappingsValid(source, result);
172
174
 
173
- // should extract title, body, tags (not line1, line2)
174
- expect(result.code).toContain("export const title = ");
175
- expect(result.code).toContain("const body = ");
176
- expect(result.code).toContain("const tags = ");
177
- expect(result.code).not.toContain("let line1");
178
- expect(result.code).not.toContain("let line2");
175
+ // the core yaml parser reads the block, its lines are no keys
176
+ expect(result.metadata).toEqual({
177
+ title: "hello",
178
+ body: "line1\nline2\n",
179
+ tags: "foo",
180
+ });
181
+ expect(result.code).toContain('body: "line1\\nline2\\n"');
182
+ for (const key of ["title", "body", "tags"]) {
183
+ const m = findContentBySource(source, result.mappings, key);
184
+ expect(srcSlice(source, m!)).toBe(key);
185
+ }
179
186
  });
180
187
 
181
188
  it("empty frontmatter", () => {
@@ -183,9 +190,9 @@ describe("pfmToSvelte", () => {
183
190
  const result = pfmToSvelte(source);
184
191
  assertMappingsValid(source, result);
185
192
 
186
- // empty frontmatter still generates a script block (but with no declarations)
187
- expect(result.code).toContain("<script");
188
- expect(result.code).not.toContain("export const ");
193
+ // empty frontmatter is empty metadata
194
+ expect(result.code).toContain("export const metadata = {};");
195
+ expect(result.metadata).toEqual({});
189
196
  expect(result.code).toContain("<h1>Hello</h1>");
190
197
  });
191
198
 
@@ -210,7 +217,7 @@ describe("pfmToSvelte", () => {
210
217
  const result = pfmToSvelte(source);
211
218
  assertMappingsValid(source, result);
212
219
 
213
- expect(result.code).toContain("export const title = ");
220
+ expect(result.code).toContain("export const metadata = {title: ");
214
221
  expect(result.code).toContain("let x = 1;");
215
222
 
216
223
  // two script blocks: <script module> for frontmatter + <script> for user code
@@ -245,15 +252,17 @@ describe("pfmToSvelte", () => {
245
252
  expect(result.code).toContain("value={count}");
246
253
  });
247
254
 
248
- it("frontmatter keys with invalid JS identifiers are skipped", () => {
255
+ it("frontmatter keys that are not identifiers stay quoted and mapped", () => {
249
256
  const source = "---\ntitle: hello\nmy-key: value\n$valid: yes\n---\n\n# Hello\n";
250
257
  const result = pfmToSvelte(source);
251
258
  assertMappingsValid(source, result);
252
259
 
253
- expect(result.code).toContain("export const title = ");
254
- expect(result.code).toContain("export const $valid = ");
255
- // hyphenated key should be skipped
256
- expect(result.code).not.toContain("my-key");
260
+ expect(result.code).toContain(
261
+ 'export const metadata = {title: "hello", "my-key": "value", $valid: "yes"};',
262
+ );
263
+ const m = findContentBySource(source, result.mappings, "my-key");
264
+ expect(srcSlice(source, m!)).toBe("my-key");
265
+ expect(genSlice(result.code, m!)).toBe('"my-key"');
257
266
  });
258
267
 
259
268
  it("preserves mapping accuracy for identity-mapped imports", () => {
@@ -0,0 +1,339 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { pfmToSvelte, template_value_at } from "../src/pfm_to_svelte";
3
+ import type {
4
+ EditorMappingData,
5
+ PfmToSvelteOptions,
6
+ PfmToSvelteResult,
7
+ } from "../src/pfm_to_svelte";
8
+ import type { Mapping, MappingData } from "@mdsvex/render/mappings";
9
+
10
+ function src_of(source: string, m: Mapping<MappingData>) {
11
+ return source.slice(m.sourceOffsets[0], m.sourceOffsets[0] + m.lengths[0]);
12
+ }
13
+
14
+ function gen_of(code: string, m: Mapping<MappingData>) {
15
+ const len = m.generatedLengths ? m.generatedLengths[0] : m.lengths[0];
16
+ return code.slice(m.generatedOffsets[0], m.generatedOffsets[0] + len);
17
+ }
18
+
19
+ /** the source, generated text and capabilities of each mapping the converter added */
20
+ function added(source: string, r: PfmToSvelteResult) {
21
+ return r.mappings
22
+ .filter((m) => (m.data as EditorMappingData).editor)
23
+ .map((m) => {
24
+ const d = m.data;
25
+ const caps =
26
+ (d.verification ? "v" : "") +
27
+ (d.completion ? "c" : "") +
28
+ (d.semantic ? "s" : "") +
29
+ (d.navigation ? "n" : "");
30
+ return [src_of(source, m), gen_of(r.code, m), caps];
31
+ });
32
+ }
33
+
34
+ function valid(source: string, r: PfmToSvelteResult) {
35
+ for (const m of r.mappings) {
36
+ const len = m.generatedLengths ? m.generatedLengths[0] : m.lengths[0];
37
+ expect(m.sourceOffsets[0] + m.lengths[0]).toBeLessThanOrEqual(source.length);
38
+ expect(m.generatedOffsets[0] + len).toBeLessThanOrEqual(r.code.length);
39
+ }
40
+ }
41
+
42
+ const FILES: Record<string, string> = {
43
+ "mdsvex:template/docs": "./lib/Docs.svelte",
44
+ "mdsvex:template-directives/docs": "./lib/directives.js",
45
+ "mdsvex:components": "./lib/markdown.js",
46
+ "mdsvex:directives": "./lib/root-directives.js",
47
+ };
48
+
49
+ const docs: PfmToSvelteOptions = {
50
+ compile: {
51
+ templates: {
52
+ docs: {
53
+ specifier: "mdsvex:template/docs",
54
+ components: ["h2"],
55
+ directives: [
56
+ { specifier: "mdsvex:template-directives/docs", names: ["Callout"] },
57
+ ],
58
+ },
59
+ },
60
+ components: [{ specifier: "mdsvex:components", names: ["img", "a"] }],
61
+ },
62
+ resolve: (id) => FILES[id],
63
+ report_directives: true,
64
+ };
65
+
66
+ describe("pfmToSvelte with a config", () => {
67
+ it("compiles as core does, imports pointing at the resolved files", () => {
68
+ const source = "---\ntemplate: docs\n---\n\n## Two\n\n![cat](/c.png)\n";
69
+ const r = pfmToSvelte(source, docs);
70
+ valid(source, r);
71
+ expect(r.template).toBe("docs");
72
+ expect(r.code).toContain('import Template_MDSVEX from "./lib/Docs.svelte";');
73
+ expect(r.code).toContain(
74
+ 'import { h2 as H2_MDSVEX_T } from "./lib/Docs.svelte";',
75
+ );
76
+ expect(r.code).toContain(
77
+ 'import { img as Img_MDSVEX_G } from "./lib/markdown.js";',
78
+ );
79
+ expect(r.code).not.toContain("mdsvex:");
80
+ expect(r.code).toContain("<Template_MDSVEX {...metadata} {...__mdsvex_props}>");
81
+ expect(r.code).toContain("<H2_MDSVEX_T level={2}>Two</H2_MDSVEX_T>");
82
+ expect(r.diagnostics).toEqual([]);
83
+ });
84
+
85
+ it("keeps the virtual id of an import it can not resolve", () => {
86
+ const source = "## Two\n\n![cat](/c.png)\n";
87
+ const r = pfmToSvelte(source, {
88
+ ...docs,
89
+ compile: { ...docs.compile, default_template: "docs" },
90
+ resolve: (id, name) => (name === "h2" ? "./lib/Docs.svelte" : undefined),
91
+ });
92
+ expect(r.code).toContain(
93
+ 'import { h2 as H2_MDSVEX_T } from "./lib/Docs.svelte";',
94
+ );
95
+ expect(r.code).toContain(
96
+ "import { default as Template_MDSVEX } from 'mdsvex:template/docs';",
97
+ );
98
+ expect(r.code).toContain("import { img as Img_MDSVEX_G } from 'mdsvex:components';");
99
+ });
100
+
101
+ it("points each replaced element and directive at its export", () => {
102
+ const source =
103
+ "---\ntemplate: docs\n---\n\n## Two\n\n![cat](/c.png) [l](/x)\n\n:::Callout[Hi](kind=warn)\nbody\n:::\n";
104
+ const r = pfmToSvelte(source, docs);
105
+ valid(source, r);
106
+ const hovers = added(source, r).filter(([, , caps]) => caps === "sn");
107
+ expect(hovers).toContainEqual(["##", "h2", "sn"]);
108
+ expect(hovers).toContainEqual(["!", "img", "sn"]);
109
+ expect(hovers).toContainEqual(["](/x)", "a", "sn"]);
110
+ expect(hovers).toContainEqual(["Callout", "Callout", "sn"]);
111
+ // the template value points at the template
112
+ expect(hovers).toContainEqual(["docs", "Template_MDSVEX", "sn"]);
113
+ });
114
+
115
+ it("drops the capabilities of syntax that maps onto a whole component tag", () => {
116
+ const source = "---\ntemplate: docs\n---\n\n## Two\n";
117
+ const r = pfmToSvelte(source, docs);
118
+ const open = r.mappings.find((m) => gen_of(r.code, m) === "<H2_MDSVEX_T level={2}>");
119
+ expect(open).toBeDefined();
120
+ const d = open!.data;
121
+ expect(d.verification || d.semantic || d.navigation || d.completion).toBeFalsy();
122
+ });
123
+
124
+ it("maps directive args to the props they become, checked", () => {
125
+ const source =
126
+ '---\ntemplate: docs\n---\n\n:::Callout[Hi](kind=warn, title="a b")\nbody\n:::\n';
127
+ const r = pfmToSvelte(source, {
128
+ ...docs,
129
+ compile: {
130
+ ...docs.compile,
131
+ templates: {
132
+ docs: {
133
+ ...docs.compile!.templates!.docs,
134
+ },
135
+ },
136
+ },
137
+ });
138
+ valid(source, r);
139
+ expect(r.code).toContain('<Callout_MDSVEX_D_T kind="warn" title="a b">');
140
+ const args = added(source, r).filter(([, , caps]) => caps === "vsn");
141
+ expect(args).toEqual([
142
+ ["kind", "kind", "vsn"],
143
+ ["warn", "warn", "vsn"],
144
+ ["title", "title", "vsn"],
145
+ ["a b", "a b", "vsn"],
146
+ ]);
147
+ });
148
+
149
+ it("checks typed attribute values of a replaced element but not their names", () => {
150
+ const source = '<script>\nlet u = "/a.png";\n</script>\n\n<img src={u} loading="lazy" />\n';
151
+ const r = pfmToSvelte(source, {
152
+ ...docs,
153
+ compile: { ...docs.compile, component_mode: "all" },
154
+ });
155
+ valid(source, r);
156
+ expect(r.code).toContain('<Img_MDSVEX_G src={u} loading="lazy" />');
157
+ const attrs = added(source, r).filter(([, , caps]) => caps.includes("c"));
158
+ expect(attrs).toEqual([
159
+ ["src", "src", "csn"],
160
+ ["{u}", "{u}", "vcsn"],
161
+ ["loading", "loading", "csn"],
162
+ ['"lazy"', '"lazy"', "vcsn"],
163
+ ]);
164
+ // the tag name hovers the replacement
165
+ expect(added(source, r)).toContainEqual(["img", "img", "sn"]);
166
+ });
167
+
168
+ it("checks the frontmatter against the props of the template", () => {
169
+ const source = "---\ntitle: Hi\nmy-key: 1\ntemplate: docs\n---\n\n# x\n";
170
+ const r = pfmToSvelte(source, docs);
171
+ valid(source, r);
172
+ expect(r.code).toContain(
173
+ ';({ title: "Hi", "my-key": 1, template: "docs" }) satisfies ' +
174
+ "Partial<import('svelte').ComponentProps<typeof Template_MDSVEX>> & Record<string, unknown>;",
175
+ );
176
+ const checks = added(source, r).filter(([, , caps]) => caps === "v");
177
+ expect(checks).toEqual([
178
+ ["title", "title", "v"],
179
+ ["my-key", '"my-key"', "v"],
180
+ ["template", "template", "v"],
181
+ ]);
182
+ // the check sits in the instance script, where the template is in scope
183
+ const instance = /<script>[^]*?<\/script>/.exec(r.code)![0];
184
+ expect(instance).toContain("satisfies");
185
+ });
186
+
187
+ it("types the template key as the union of template names and false", () => {
188
+ const source = "---\ntitle: Hi\ntemplate: docs\n---\n\n# x\n";
189
+ const r = pfmToSvelte(source, docs);
190
+ expect(r.code).toContain(
191
+ 'export const metadata = {title: "Hi", template: "docs" as "docs" | false};',
192
+ );
193
+ expect(r.frontmatter).toEqual({ start: 4, end: 29 });
194
+ // without templates the key is whatever the frontmatter holds
195
+ expect(pfmToSvelte(source).code).toContain(
196
+ 'export const metadata = {title: "Hi", template: "docs"};',
197
+ );
198
+ });
199
+
200
+ it("emits a props type for every template and directive the config knows", () => {
201
+ const r = pfmToSvelte("# x\n", {
202
+ ...docs,
203
+ compile: {
204
+ ...docs.compile,
205
+ directives: [{ specifier: "mdsvex:directives", names: ["box"] }],
206
+ },
207
+ });
208
+ expect(r.probes).toEqual([
209
+ { kind: "template", name: "docs", alias: "__mdsvex_props_0" },
210
+ { kind: "directive", name: "Callout", template: "docs", alias: "__mdsvex_props_1" },
211
+ { kind: "directive", name: "box", alias: "__mdsvex_props_2" },
212
+ ]);
213
+ // a document with no instance script gets one to hold them
214
+ expect(r.code).toContain(
215
+ '<script lang="ts">\n' +
216
+ "type __mdsvex_props_0 = import('svelte').ComponentProps<typeof import(\"./lib/Docs.svelte\")[\"default\"]>;\n" +
217
+ "type __mdsvex_props_1 = import('svelte').ComponentProps<typeof import(\"./lib/directives.js\")[\"Callout\"]>;\n" +
218
+ "type __mdsvex_props_2 = import('svelte').ComponentProps<typeof import(\"./lib/root-directives.js\")[\"box\"]>;\n" +
219
+ "</script>\n<h1>x</h1>",
220
+ );
221
+ expect(pfmToSvelte("# x\n").probes).toEqual([]);
222
+ });
223
+
224
+ it("checks nothing without a template", () => {
225
+ const source = "---\ntitle: Hi\n---\n\n# x\n";
226
+ const r = pfmToSvelte(source, docs);
227
+ expect(r.code).not.toContain("satisfies");
228
+ });
229
+
230
+ it("passes select_template through, as the plugin binds it", () => {
231
+ const source = "## Two\n";
232
+ const r = pfmToSvelte(source, {
233
+ ...docs,
234
+ compile: { ...docs.compile, select_template: () => "docs" },
235
+ });
236
+ expect(r.template).toBe("docs");
237
+ expect(r.code).toContain("<H2_MDSVEX_T");
238
+ });
239
+ });
240
+
241
+ describe("pfmToSvelte compile diagnostics", () => {
242
+ it("reports a directive no component renders and renders its children", () => {
243
+ const source = "# t\n\n:::thing[x]\nbody\n:::\n";
244
+ const r = pfmToSvelte(source, docs);
245
+ expect(r.diagnostics).toHaveLength(1);
246
+ const [d] = r.diagnostics;
247
+ expect(source.slice(d.start, d.end)).toBe(":::thing");
248
+ expect(d.severity).toBe("error");
249
+ expect(d.message).toContain(":::thing");
250
+ expect(r.code).toContain("<p>body</p>");
251
+ });
252
+
253
+ it("never reports directives without a known config", () => {
254
+ const source = "# t\n\n:::thing[x]\nbody\n:::\n\n:inline[y]\n";
255
+ const r = pfmToSvelte(source);
256
+ expect(r.diagnostics).toEqual([]);
257
+ expect(r.code).toContain("<p>body</p>");
258
+ });
259
+
260
+ it("reports an argument a snippet takes and still renders", () => {
261
+ const source = "::leaf[x](children=a)\n\n# after\n";
262
+ const r = pfmToSvelte(source, {
263
+ compile: { directives: [{ specifier: "mdsvex:directives", names: ["leaf"] }] },
264
+ resolve: (id) => FILES[id],
265
+ });
266
+ expect(r.diagnostics).toHaveLength(1);
267
+ expect(r.diagnostics[0].message).toContain("children");
268
+ expect(r.code).toContain("<h1>after</h1>");
269
+ });
270
+
271
+ it("reports an unknown template at its line and renders without one", () => {
272
+ const source = "---\ntitle: x\ntemplate: nope\n---\n\n## Two\n";
273
+ const r = pfmToSvelte(source, docs);
274
+ expect(r.diagnostics).toHaveLength(1);
275
+ const [d] = r.diagnostics;
276
+ expect(source.slice(d.start, d.end)).toBe("nope");
277
+ expect(d.message).toContain('Unknown template "nope"');
278
+ expect(r.template).toBeUndefined();
279
+ expect(r.code).not.toContain("Template_MDSVEX");
280
+ expect(r.metadata).toEqual({ title: "x", template: "nope" });
281
+ });
282
+
283
+ it("reports frontmatter the core parser rejects and types metadata loosely", () => {
284
+ const source = "---\ntitle: x\nanchor: &a 1\n---\n\n{metadata.anything}\n";
285
+ const r = pfmToSvelte(source);
286
+ expect(r.diagnostics).toHaveLength(1);
287
+ expect(source.slice(r.diagnostics[0].start, r.diagnostics[0].end)).toBe(
288
+ "anchor: &a 1",
289
+ );
290
+ expect(r.metadata).toBeUndefined();
291
+ expect(r.code).toContain("export const metadata: Record<string, any> = {};");
292
+ });
293
+
294
+ it("leaves rejected frontmatter to a custom parser", () => {
295
+ const source = "---\nanchor: &a 1\n---\n\n# x\n";
296
+ const r = pfmToSvelte(source, { lenient_frontmatter: true });
297
+ expect(r.diagnostics).toEqual([]);
298
+ expect(r.code).toContain("export const metadata: Record<string, any> = {};");
299
+ });
300
+
301
+ it("reports an element all mode keeps as a warning", () => {
302
+ const source = "<img src=\"/a.png\" use:act />\n";
303
+ const r = pfmToSvelte(source, {
304
+ ...docs,
305
+ compile: { ...docs.compile, component_mode: "all" },
306
+ });
307
+ expect(r.diagnostics).toHaveLength(1);
308
+ const [d] = r.diagnostics;
309
+ expect(d.severity).toBe("warning");
310
+ expect(source.slice(d.start, d.end)).toBe("<img");
311
+ });
312
+ });
313
+
314
+ describe("template_value_at", () => {
315
+ const source = "---\ntitle: x\ntemplate: docs # main\n'template':\n---\n";
316
+ const frontmatter = { start: 4, end: source.indexOf("\n---", 4) };
317
+ const value = (offset: number) => {
318
+ const r = template_value_at(source, offset, frontmatter);
319
+ return r && [source.slice(r.start, r.end), r.start];
320
+ };
321
+
322
+ it("gives the value of the template key the offset is in, without a comment", () => {
323
+ const at = source.indexOf("docs");
324
+ expect(value(at)).toEqual(["docs", at]);
325
+ expect(value(at + 2)).toEqual(["docs", at]);
326
+ expect(value(at + 4)).toEqual(["docs", at]);
327
+ });
328
+
329
+ it("gives an empty range for a key with no value yet", () => {
330
+ const end = source.indexOf("\n---");
331
+ expect(value(end)).toEqual(["", end]);
332
+ });
333
+
334
+ it("is null before the value, on another key or outside the frontmatter", () => {
335
+ expect(value(source.indexOf("template:") + 3)).toBeNull();
336
+ expect(value(source.indexOf("title") + 8)).toBeNull();
337
+ expect(value(source.length)).toBeNull();
338
+ });
339
+ });
@@ -115,6 +115,7 @@ draft: true
115
115
  import Counter from "./Counter.svelte"
116
116
 
117
117
  <script lang="ts">
118
+ const { count, draft } = metadata;
118
119
  const doubled = count * 2;
119
120
  </script>
120
121
 
@@ -123,7 +124,7 @@ import Counter from "./Counter.svelte"
123
124
  p { margin: 1rem; }
124
125
  </style>
125
126
 
126
- # {title}
127
+ # {metadata.title}
127
128
 
128
129
  {#if !draft}
129
130
  <Counter value={count} />
@@ -133,7 +134,7 @@ import Counter from "./Counter.svelte"
133
134
 
134
135
  The doubled value is {doubled}.
135
136
 
136
- > A blockquote with {title}
137
+ > A blockquote with {metadata.title}
137
138
 
138
139
  - Item {count}
139
140
  - Item {count + 1}
@@ -148,9 +149,9 @@ const x: number = 42;
148
149
  // script block merged
149
150
  expect(result.code).toContain("const doubled = count * 2");
150
151
  expect(result.code).toContain('import Counter from "./Counter.svelte"');
151
- expect(result.code).toContain("export const title = ");
152
- expect(result.code).toContain("export const count = ");
153
- expect(result.code).toContain("export const draft = ");
152
+ expect(result.code).toContain(
153
+ 'export const metadata = {title: "My Page", count: 42, draft: true};',
154
+ );
154
155
 
155
156
  // style block detected
156
157
  expect(result.styleBlocks.length).toBe(1);
@@ -178,7 +179,7 @@ const x: number = 42;
178
179
  const source = "---\ntitle: hello\n---\n";
179
180
  const result = pfmToSvelte(source);
180
181
  assertValid(source, result);
181
- expect(result.code).toContain("export const title = ");
182
+ expect(result.code).toContain('export const metadata = {title: "hello"};');
182
183
  });
183
184
 
184
185
  it("frontmatter with all YAML scalar types", () => {
@@ -186,13 +187,19 @@ const x: number = 42;
186
187
  const result = pfmToSvelte(source);
187
188
  assertValid(source, result);
188
189
 
189
- expect(result.code).toContain('export const str = "hello world"');
190
- expect(result.code).toContain("export const num = 3.14");
191
- expect(result.code).toContain("export const bool = false");
192
- expect(result.code).toContain("export const null_val = null");
193
- expect(result.code).toContain("export const tilde_null = null");
194
- expect(result.code).toContain("export const empty = null");
195
- expect(result.code).toContain("export const int = -42");
196
- expect(result.code).toContain("export const sci = 1e10");
190
+ // values are what the core yaml parser gives, the build exports the same
191
+ expect(result.metadata).toEqual({
192
+ str: "hello world",
193
+ num: 3.14,
194
+ bool: false,
195
+ null_val: null,
196
+ tilde_null: null,
197
+ empty: null,
198
+ int: -42,
199
+ sci: 1e10,
200
+ });
201
+ expect(result.code).toContain(
202
+ '{str: "hello world", num: 3.14, bool: false, null_val: null, tilde_null: null, empty: null, int: -42, sci: 10000000000}',
203
+ );
197
204
  });
198
205
  });
@@ -0,0 +1,84 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { svelte2tsx } from 'svelte2tsx';
3
+ import { create_highlight } from 'mdsvex/highlight';
4
+ import { default_languages } from 'mdsvex/highlight/languages';
5
+ import type { Mapping, MappingData } from '@mdsvex/render/mappings';
6
+
7
+ import { pfmToSvelte } from '../src/pfm_to_svelte';
8
+
9
+ const highlight = create_highlight({ languages: default_languages });
10
+
11
+ function src_of(source: string, m: Mapping<MappingData>) {
12
+ return source.slice(m.sourceOffsets[0], m.sourceOffsets[0] + m.lengths[0]);
13
+ }
14
+
15
+ function gen_of(code: string, m: Mapping<MappingData>) {
16
+ const len = m.generatedLengths ? m.generatedLengths[0] : m.lengths[0];
17
+ return code.slice(m.generatedOffsets[0], m.generatedOffsets[0] + len);
18
+ }
19
+
20
+ const DOC = [
21
+ '<script>',
22
+ ' let some_val = 1;',
23
+ '</script>',
24
+ '',
25
+ '```js',
26
+ 'function my_func() {',
27
+ ' console.log({ a: {some_val} }) // [!eval ="{some_val}"]',
28
+ '}',
29
+ '```',
30
+ '',
31
+ ].join('\n');
32
+
33
+ describe('live expressions in code', () => {
34
+ it('each maps one to one with every capability', () => {
35
+ const r = pfmToSvelte(DOC, { compile: { highlight } });
36
+ expect(r.diagnostics).toEqual([]);
37
+ const live = r.mappings.filter(
38
+ (m) =>
39
+ src_of(DOC, m) === '{some_val}' && gen_of(r.code, m) === '{some_val}'
40
+ );
41
+ expect(live).toHaveLength(1);
42
+ expect(live[0].data).toMatchObject({
43
+ verification: true,
44
+ completion: true,
45
+ semantic: true,
46
+ navigation: true,
47
+ role: 'content',
48
+ });
49
+ const g = live[0].generatedOffsets[0];
50
+ const over = r.mappings.filter((m) => {
51
+ if (m.data.role !== 'content') return false;
52
+ const start = m.generatedOffsets[0];
53
+ const end = start + (m.generatedLengths?.[0] ?? m.lengths[0]);
54
+ return start < g + 10 && end > g;
55
+ });
56
+ expect(over).toEqual(live);
57
+ });
58
+
59
+ it('svelte2tsx reads it as a reference', () => {
60
+ const r = pfmToSvelte(DOC, { compile: { highlight } });
61
+ const tsx = svelte2tsx(r.code, { filename: 'doc.svelte', mode: 'ts' }).code;
62
+ expect(tsx).toMatch(/\bsome_val\b[^]*\bsome_val\b/);
63
+ expect(tsx).not.toContain('my_func');
64
+ });
65
+
66
+ it('a half typed live expression is a diagnostic, the document still converts', () => {
67
+ const doc = DOC.replace(
68
+ 'console.log',
69
+ 'f({some_val) // [!eval]\n console.log'
70
+ );
71
+ const r = pfmToSvelte(doc, { compile: { highlight } });
72
+ expect(r.diagnostics).toHaveLength(1);
73
+ const [d] = r.diagnostics;
74
+ expect(d.severity).toBe('error');
75
+ expect(d.message).toMatch(/must close on its line/);
76
+ expect(doc.slice(d.start, d.start + 4)).toBe('{som');
77
+ expect(r.code).toContain('<pre><code');
78
+ });
79
+
80
+ it('without highlight nothing is live', () => {
81
+ const r = pfmToSvelte(DOC);
82
+ expect(r.code).not.toContain('{some_val}');
83
+ });
84
+ });