@mdsvex/language-core 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.
@@ -0,0 +1,314 @@
1
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
2
+
3
+ import { project } from "./ts_harness";
4
+ import type { Project } from "./ts_harness";
5
+
6
+ const svelte = (props: string, module = "") =>
7
+ [
8
+ ...(module ? ['<script module lang="ts">', module, "</script>"] : []),
9
+ '<script lang="ts">',
10
+ " import type { Snippet } from 'svelte';",
11
+ ` let p: { ${props} } = $props();`,
12
+ "</script>",
13
+ "<div></div>",
14
+ "",
15
+ ].join("\n");
16
+
17
+ /** a vite app whose templates and replacements a manifest describes */
18
+ const APP: Record<string, string> = {
19
+ "src/lib/templates/Docs.svelte": svelte(
20
+ "title: string; draft?: boolean; children: Snippet",
21
+ [
22
+ " export { default as h2 } from '../Heading.svelte';",
23
+ " export * as directives from '../directives.ts';",
24
+ ].join("\n"),
25
+ ),
26
+ // no level prop, which the replacement still receives
27
+ "src/lib/Heading.svelte": svelte("id?: string; children?: Snippet"),
28
+ "src/lib/directives.ts": "export { default as Callout } from './Callout.svelte';\n",
29
+ "src/lib/Callout.svelte": svelte(
30
+ "kind: 'info' | 'warn'; label?: Snippet; children?: Snippet",
31
+ ),
32
+ "src/lib/Img.svelte": svelte("src: string; alt: string"),
33
+ "src/lib/Pre.svelte": svelte("lang?: string; code: string; children?: Snippet"),
34
+ "src/lib/A.svelte": svelte("href: string; children?: Snippet"),
35
+ "src/lib/Badge.svelte": svelte("tone?: 'info' | 'warn'; children?: Snippet"),
36
+ "src/lib/markdown.ts": [
37
+ "export { default as img } from './Img.svelte';",
38
+ "export { default as pre } from './Pre.svelte';",
39
+ "export { default as a } from './A.svelte';",
40
+ "export * as directives from './root-directives.ts';",
41
+ "",
42
+ ].join("\n"),
43
+ "src/lib/root-directives.ts": "export { default as badge } from './Badge.svelte';\n",
44
+ };
45
+
46
+ function manifest(root: string) {
47
+ const lib = root + "/src/lib/";
48
+ return JSON.stringify({
49
+ version: 1,
50
+ root,
51
+ extensions: [".svx"],
52
+ component_mode: "all",
53
+ frontmatter_parse: false,
54
+ directive_plugins: false,
55
+ select_template: false,
56
+ templates: {
57
+ docs: {
58
+ id: "mdsvex:template/docs",
59
+ file: lib + "templates/Docs.svelte",
60
+ components: ["h2"],
61
+ extra: null,
62
+ directives: [
63
+ {
64
+ id: "mdsvex:template-directives/docs",
65
+ file: lib + "directives.ts",
66
+ names: ["Callout"],
67
+ },
68
+ ],
69
+ },
70
+ },
71
+ components: [
72
+ { id: "mdsvex:components", file: lib + "markdown.ts", names: ["img", "pre", "a"] },
73
+ ],
74
+ directives: [
75
+ { id: "mdsvex:directives", file: lib + "root-directives.ts", names: ["badge"] },
76
+ ],
77
+ documents: {},
78
+ });
79
+ }
80
+
81
+ const VALID = `---
82
+ title: Hello
83
+ tags: [a, b]
84
+ nested:
85
+ deep: 1
86
+ template: docs
87
+ ---
88
+
89
+ <script>
90
+ let n = $state(1);
91
+ let url = '/a.png';
92
+ </script>
93
+
94
+ ## Heading {n}
95
+
96
+ Text ![cat](./cat.png) and <img src={url} alt="x" loading="lazy" /> and [l](/x "t").
97
+
98
+ <a href="/y" class="c">typed</a>
99
+
100
+ \`\`\`js title="x"
101
+ const a = 1;
102
+ \`\`\`
103
+
104
+ :::Callout[Heads *up*](kind=warn)
105
+ Body :badge[new](tone=info)
106
+ :::
107
+
108
+ {metadata.title} {metadata.nested.deep} {metadata.tags.length}
109
+ `;
110
+
111
+ describe("with a plugin manifest", () => {
112
+ let p: Project;
113
+ beforeAll(() => {
114
+ p = project({
115
+ ...APP,
116
+ "src/valid.svx": VALID,
117
+ "src/wrong.svx": [
118
+ "---",
119
+ "title: 3",
120
+ "draft: yes",
121
+ "extra: kept",
122
+ "template: docs",
123
+ "---",
124
+ "",
125
+ ":::Callout[Hi](kind=warning)",
126
+ "body",
127
+ ":::",
128
+ "",
129
+ "<img src={nope} alt=\"x\" />",
130
+ "",
131
+ "{title}",
132
+ "",
133
+ ].join("\n"),
134
+ });
135
+ p.write("node_modules/.mdsvex/manifest.json", manifest(p.root));
136
+ });
137
+ afterAll(() => p.dispose());
138
+
139
+ it("reports nothing on a valid document", () => {
140
+ expect(p.diagnostics("src/valid.svx")).toEqual([]);
141
+ });
142
+
143
+ it("checks frontmatter against the template, directive args and expressions", () => {
144
+ const found = p.diagnostics("src/wrong.svx").map((d) => [d.text, d.message]);
145
+ expect(found).toEqual([
146
+ ["title", "Type 'number' is not assignable to type 'string'."],
147
+ ["draft", "Type 'string' is not assignable to type 'boolean | undefined'."],
148
+ ["kind", `Type '"warning"' is not assignable to type '"info" | "warn"'.`],
149
+ ["nope", "Cannot find name 'nope'."],
150
+ // frontmatter is metadata, as compile makes it
151
+ ["title", "Cannot find name 'title'."],
152
+ ]);
153
+ });
154
+
155
+ it("hovers the replacement of a markdown element, typed element and directive", () => {
156
+ const doc = "src/valid.svx";
157
+ expect(p.hover(doc, "## Heading")).toContain("const h2: Component<");
158
+ expect(p.hover(doc, "![cat]")).toContain("const img: Component<");
159
+ expect(p.hover(doc, "img src", 1)).toContain("const img: Component<");
160
+ expect(p.hover(doc, "```js")).toContain("const pre: Component<");
161
+ expect(p.hover(doc, "Callout[", 1)).toContain("const Callout: Component<");
162
+ expect(p.hover(doc, "badge[")).toContain("const badge: Component<");
163
+ expect(p.hover(doc, "docs\n---")).toContain("Template_MDSVEX: Component<");
164
+ });
165
+
166
+ it("hovers frontmatter keys and directive args with their types", () => {
167
+ const doc = "src/valid.svx";
168
+ expect(p.hover(doc, "title:")).toBe("(property) title: string");
169
+ // the names of the configured templates, as only they or false compile
170
+ expect(p.hover(doc, "template:")).toBe('(property) template: false | "docs"');
171
+ expect(p.hover(doc, "tags:")).toBe("(property) tags: string[]");
172
+ // the prop the arg becomes, as the component declares it
173
+ expect(p.hover(doc, "kind=")).toBe('(property) kind: "info" | "warn"');
174
+ expect(p.hover(doc, "metadata.title", 9)).toBe("(property) title: string");
175
+ });
176
+ });
177
+
178
+ describe("live expressions in code", () => {
179
+ const LIVE = [
180
+ "<script lang=\"ts\">",
181
+ " let install_command = 'pnpm add';",
182
+ " let count = 1;",
183
+ " let unread = 2;",
184
+ "</script>",
185
+ "",
186
+ "```sh",
187
+ "{install_command} @pkg/my-pkg # [!eval]",
188
+ "{count.nope} # [!eval]",
189
+ "```",
190
+ "",
191
+ "```js eval",
192
+ "run({install_command})",
193
+ "```",
194
+ "",
195
+ ].join("\n");
196
+ let p: Project;
197
+ beforeAll(() => {
198
+ p = project({ ...APP, "src/live.svx": LIVE });
199
+ p.write("node_modules/.mdsvex/manifest.json", manifest(p.root));
200
+ });
201
+ afterAll(() => p.dispose());
202
+
203
+ it("checks a live expression", () => {
204
+ expect(p.diagnostics("src/live.svx").map((d) => [d.text, d.message])).toEqual([
205
+ ["nope", "Property 'nope' does not exist on type 'number'."],
206
+ ]);
207
+ });
208
+
209
+ it("hovers a live expression", () => {
210
+ expect(p.hover("src/live.svx", "install_command} @")).toBe(
211
+ "let install_command: string",
212
+ );
213
+ expect(p.hover("src/live.svx", "install_command})")).toBe(
214
+ "let install_command: string",
215
+ );
216
+ });
217
+
218
+ it("renames through a live expression", () => {
219
+ const at = (needle: string) => LIVE.indexOf(needle);
220
+ expect(p.rename("src/live.svx", "install_command} @").sort()).toEqual(
221
+ [
222
+ ["src/live.svx", at("install_command =")],
223
+ ["src/live.svx", at("install_command} @")],
224
+ ["src/live.svx", at("install_command})")],
225
+ ].sort(),
226
+ );
227
+ });
228
+
229
+ it("counts a live expression as a read", () => {
230
+ const unread = p
231
+ .suggestions("src/live.svx")
232
+ .filter((d) => d.code === 6133)
233
+ .map((d) => d.text);
234
+ expect(unread).toEqual(["unread"]);
235
+ });
236
+
237
+ it("reads nothing live when the plugin renders code plain", () => {
238
+ const q = project({ ...APP, "src/live.svx": LIVE });
239
+ try {
240
+ q.write(
241
+ "node_modules/.mdsvex/manifest.json",
242
+ JSON.stringify({ ...JSON.parse(manifest(q.root)), highlight: false }),
243
+ );
244
+ expect(q.diagnostics("src/live.svx")).toEqual([]);
245
+ } finally {
246
+ q.dispose();
247
+ }
248
+ });
249
+ });
250
+
251
+ describe("without a config", () => {
252
+ let p: Project;
253
+ beforeAll(() => {
254
+ p = project({
255
+ "doc.pfm": [
256
+ "---",
257
+ "title: x",
258
+ "---",
259
+ "",
260
+ ":::anything[x](a=b)",
261
+ "body :inline[y]",
262
+ ":::",
263
+ "",
264
+ "::leaf[z]",
265
+ "",
266
+ "{metadata.title}",
267
+ "",
268
+ ].join("\n"),
269
+ });
270
+ });
271
+ afterAll(() => p.dispose());
272
+
273
+ it("reports nothing, a directive no config names may be rendered at build", () => {
274
+ expect(p.diagnostics("doc.pfm")).toEqual([]);
275
+ });
276
+ });
277
+
278
+ describe("with a mdsvex.config.json", () => {
279
+ let p: Project;
280
+ beforeAll(() => {
281
+ p = project({
282
+ ...APP,
283
+ "package.json": JSON.stringify({ imports: { "#lib/*": "./src/lib/*" } }),
284
+ "mdsvex.config.json": JSON.stringify({
285
+ templates: { docs: "#lib/templates/Docs.svelte" },
286
+ components: "#lib/markdown.ts",
287
+ }),
288
+ "src/doc.svx": [
289
+ "---",
290
+ "draft: yes",
291
+ "template: docs",
292
+ "---",
293
+ "",
294
+ "## Two",
295
+ "",
296
+ ":::Callout[x](kind=info)",
297
+ ":::",
298
+ "",
299
+ "![c](/c.png)",
300
+ "",
301
+ ].join("\n"),
302
+ });
303
+ });
304
+ afterAll(() => p.dispose());
305
+
306
+ it("resolves and scans the config itself", () => {
307
+ expect(p.diagnostics("src/doc.svx").map((d) => d.text)).toEqual(["draft"]);
308
+ expect(p.hover("src/doc.svx", "## Two")).toContain("const h2: Component<");
309
+ expect(p.hover("src/doc.svx", "Callout[", 1)).toContain(
310
+ "const Callout: Component<",
311
+ );
312
+ expect(p.hover("src/doc.svx", "![c]")).toContain("const img: Component<");
313
+ });
314
+ });
@@ -0,0 +1,168 @@
1
+ /** a typescript language service decorated with the pfm and svelte plugins as tsserver is */
2
+
3
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
+ import * as fs from 'node:fs';
5
+ import { dirname, join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ import ts from 'typescript';
9
+ import { createLanguage, FileMap } from '@volar/language-core';
10
+ import type { LanguagePlugin } from '@volar/language-core';
11
+ import {
12
+ createProxyLanguageService,
13
+ decorateLanguageServiceHost,
14
+ resolveFileLanguageId,
15
+ } from '@volar/typescript';
16
+
17
+ import {
18
+ create_pfm_language_plugin,
19
+ create_svelte_language_plugin,
20
+ } from '../src/index';
21
+
22
+ const HERE = dirname(fileURLToPath(import.meta.url));
23
+
24
+ export interface Project {
25
+ root: string;
26
+ /** absolute path of a project file */
27
+ path(file: string): string;
28
+ write(file: string, content: string): void;
29
+ /** the plain text of the quick info at the first offset of needle in file */
30
+ hover(file: string, needle: string, delta?: number): string | undefined;
31
+ /** syntactic and semantic diagnostics of file, with the text they cover */
32
+ diagnostics(file: string): { text: string; message: string; code: number }[];
33
+ /** suggestion diagnostics of file, such as a declaration never read */
34
+ suggestions(file: string): { text: string; message: string; code: number }[];
35
+ /** where a rename at the first offset of needle in file edits, as file and offset */
36
+ rename(file: string, needle: string, delta?: number): [string, number][];
37
+ /** the program over the generated typescript, as the language server holds it */
38
+ program(): ts.Program;
39
+ dispose(): void;
40
+ }
41
+
42
+ /** files are written under the package, so svelte resolves from its node_modules */
43
+ export function project(files: Record<string, string>): Project {
44
+ const root = mkdtempSync(join(HERE, '.tmp-project-'));
45
+ const versions = new Map<string, number>();
46
+ const write = (file: string, content: string) => {
47
+ const at = join(root, file);
48
+ mkdirSync(dirname(at), { recursive: true });
49
+ writeFileSync(at, content);
50
+ versions.set(at, (versions.get(at) ?? 0) + 1);
51
+ };
52
+ for (const [file, content] of Object.entries(files)) write(file, content);
53
+
54
+ const plugins: LanguagePlugin<string>[] = [
55
+ create_pfm_language_plugin({ typescript: ts }),
56
+ create_svelte_language_plugin(),
57
+ { getLanguageId: resolveFileLanguageId },
58
+ ];
59
+ const snapshot = (file: string) =>
60
+ fs.existsSync(file)
61
+ ? ts.ScriptSnapshot.fromString(readFileSync(file, 'utf8'))
62
+ : undefined;
63
+ const language = createLanguage(
64
+ plugins,
65
+ new FileMap(ts.sys.useCaseSensitiveFileNames),
66
+ (file) => {
67
+ const snap = snapshot(file);
68
+ if (snap) language.scripts.set(file, snap);
69
+ else language.scripts.delete(file);
70
+ }
71
+ );
72
+ const options: ts.CompilerOptions = {
73
+ target: ts.ScriptTarget.ESNext,
74
+ module: ts.ModuleKind.ESNext,
75
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
76
+ strict: true,
77
+ allowJs: true,
78
+ checkJs: false,
79
+ skipLibCheck: true,
80
+ types: [],
81
+ noEmit: true,
82
+ allowImportingTsExtensions: true,
83
+ verbatimModuleSyntax: false,
84
+ // what tsserver sets for extensions a plugin adds
85
+ allowNonTsExtensions: true,
86
+ };
87
+ const host: ts.LanguageServiceHost = {
88
+ getCompilationSettings: () => options,
89
+ getScriptFileNames: () =>
90
+ [...versions.keys()].filter((f) => /\.(pfm|svx|ts)$/.test(f)),
91
+ getScriptVersion: (file) => String(versions.get(file) ?? 0),
92
+ getScriptSnapshot: snapshot,
93
+ getCurrentDirectory: () => root,
94
+ getDefaultLibFileName: (o) => ts.getDefaultLibFilePath(o),
95
+ fileExists: ts.sys.fileExists,
96
+ readFile: ts.sys.readFile,
97
+ readDirectory: ts.sys.readDirectory,
98
+ directoryExists: ts.sys.directoryExists,
99
+ getDirectories: ts.sys.getDirectories,
100
+ realpath: ts.sys.realpath,
101
+ // the decoration resolves plugin extensions and gives their script kind through these
102
+ getScriptKind(file) {
103
+ if (file.endsWith('.ts')) return ts.ScriptKind.TS;
104
+ if (file.endsWith('.js')) return ts.ScriptKind.JS;
105
+ if (file.endsWith('.json')) return ts.ScriptKind.JSON;
106
+ return ts.ScriptKind.Deferred;
107
+ },
108
+ resolveModuleNameLiterals(literals, containing, redirected, options) {
109
+ return literals.map((literal) =>
110
+ ts.resolveModuleName(literal.text, containing, options, ts.sys)
111
+ );
112
+ },
113
+ };
114
+ // volar types against its own typescript version
115
+ decorateLanguageServiceHost(ts as any, language, host as any);
116
+ const { proxy, initialize } = createProxyLanguageService(
117
+ ts.createLanguageService(host) as any
118
+ );
119
+ initialize(language);
120
+
121
+ const text = (file: string) => readFileSync(join(root, file), 'utf8');
122
+ return {
123
+ root,
124
+ path: (file) => join(root, file),
125
+ write,
126
+ hover(file, needle, delta = 0) {
127
+ const at = text(file).indexOf(needle);
128
+ if (at < 0) throw new Error(`${needle} is not in ${file}`);
129
+ const info = proxy.getQuickInfoAtPosition(join(root, file), at + delta);
130
+ return info && ts.displayPartsToString(info.displayParts);
131
+ },
132
+ diagnostics(file) {
133
+ const at = join(root, file);
134
+ const source = text(file);
135
+ return [
136
+ ...proxy.getSyntacticDiagnostics(at),
137
+ ...proxy.getSemanticDiagnostics(at),
138
+ ].map((d) => ({
139
+ text: source.slice(d.start!, d.start! + d.length!),
140
+ message: ts.flattenDiagnosticMessageText(d.messageText, '\n'),
141
+ code: d.code,
142
+ }));
143
+ },
144
+ suggestions(file) {
145
+ const source = text(file);
146
+ return proxy.getSuggestionDiagnostics(join(root, file)).map((d) => ({
147
+ text: source.slice(d.start!, d.start! + d.length!),
148
+ message: ts.flattenDiagnosticMessageText(d.messageText, '\n'),
149
+ code: d.code,
150
+ }));
151
+ },
152
+ rename(file, needle, delta = 0) {
153
+ const at = text(file).indexOf(needle);
154
+ if (at < 0) throw new Error(`${needle} is not in ${file}`);
155
+ const found =
156
+ proxy.findRenameLocations(join(root, file), at + delta, false, false, {}) ??
157
+ [];
158
+ return found.map((l) => [
159
+ l.fileName.slice(root.length + 1),
160
+ l.textSpan.start,
161
+ ]);
162
+ },
163
+ program: () => proxy.getProgram()!,
164
+ dispose() {
165
+ rmSync(root, { recursive: true, force: true });
166
+ },
167
+ };
168
+ }