@mdsvex/language-server 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mdsvex/language-server",
3
- "version": "0.1.0-next.0",
3
+ "version": "0.1.0-next.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/pngwn/MDsveX.git",
@@ -27,7 +27,7 @@
27
27
  "volar-service-typescript": "^0.0.70",
28
28
  "vscode-languageserver": "^9.0.1",
29
29
  "vscode-uri": "^3.0.8",
30
- "@mdsvex/language-core": "0.1.0-next.0"
30
+ "@mdsvex/language-core": "0.1.0-next.1"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@volar/test-utils": "^2.4.28",
@@ -6,10 +6,19 @@
6
6
  */
7
7
  export function clean_svelte_hover(markdown: string): string {
8
8
  markdown = strip_svelte_component_type(markdown);
9
+ markdown = strip_runes_component_type(markdown);
9
10
  markdown = clean_isomorphic_component(markdown);
10
11
  return markdown;
11
12
  }
12
13
 
14
+ /** the $on and $set alias svelte2tsx declares beside a runes component */
15
+ function strip_runes_component_type(md: string): string {
16
+ const re = /^(?:\(alias\) )?type [\w$]+ = \{\n(?:[ \t]+\$(?:on|set)\?\(.*\n)+\}\n/m;
17
+ for (let m = re.exec(md); m !== null; m = re.exec(md))
18
+ md = md.slice(0, m.index) + md.slice(m.index + m[0].length);
19
+ return md;
20
+ }
21
+
13
22
  /** Remove `(alias) type X = SvelteComponent<...> & { ... }\n` lines. */
14
23
  function strip_svelte_component_type(md: string): string {
15
24
  const marker = "type ";
@@ -0,0 +1,36 @@
1
+ /** what compile rejects or warns about, typescript reports the rest */
2
+
3
+ import type { LanguageServicePlugin } from '@volar/language-server';
4
+ import { root_code } from './root_code';
5
+
6
+ const ERROR = 1;
7
+ const WARNING = 2;
8
+
9
+ export function create_compile_diagnostics(): LanguageServicePlugin {
10
+ return {
11
+ name: 'mdsvex-compile',
12
+ capabilities: {
13
+ diagnosticProvider: {
14
+ interFileDependencies: false,
15
+ workspaceDiagnostics: false,
16
+ },
17
+ },
18
+ create(context) {
19
+ return {
20
+ provideDiagnostics(document) {
21
+ const root = root_code(context, document);
22
+ if (root?.diagnostics === undefined) return;
23
+ return root.diagnostics.map((d) => ({
24
+ range: {
25
+ start: document.positionAt(d.start),
26
+ end: document.positionAt(d.end),
27
+ },
28
+ message: d.message,
29
+ severity: d.severity === 'error' ? ERROR : WARNING,
30
+ source: 'mdsvex',
31
+ }));
32
+ },
33
+ };
34
+ },
35
+ };
36
+ }
@@ -0,0 +1,163 @@
1
+ /** template names, frontmatter keys and values, and directive args, from the props of each component */
2
+
3
+ import { CompletionItemKind } from '@volar/language-server';
4
+ import type {
5
+ CompletionItem,
6
+ LanguageServicePlugin,
7
+ } from '@volar/language-server';
8
+ import type * as TS from 'typescript';
9
+ import type { Provide } from 'volar-service-typescript/lib/plugins/semantic';
10
+ import {
11
+ completion_context,
12
+ probe_for,
13
+ props_of,
14
+ template_named,
15
+ } from '@mdsvex/language-core';
16
+ import type { PfmVirtualCode, Prop } from '@mdsvex/language-core';
17
+ import { URI } from 'vscode-uri';
18
+ import { root_code } from './root_code';
19
+
20
+ const SUGGEST = { title: 'suggest', command: 'editor.action.triggerSuggest' };
21
+
22
+ /** a plain yaml scalar or arg value when it reads back as itself, quoted otherwise */
23
+ function written(value: string, plain: RegExp): string {
24
+ return plain.test(value) ? value : JSON.stringify(value);
25
+ }
26
+
27
+ export function create_completions(ts: typeof TS): LanguageServicePlugin {
28
+ return {
29
+ name: 'mdsvex-completions',
30
+ capabilities: {
31
+ // a value follows the space after a colon, args follow the paren, a comma or an equals sign
32
+ completionProvider: { triggerCharacters: [' ', '(', ',', '='] },
33
+ },
34
+ create(context) {
35
+ const props = (
36
+ root: PfmVirtualCode,
37
+ uri: string,
38
+ kind: 'template' | 'directive',
39
+ name: string | undefined,
40
+ template: string | undefined
41
+ ): Prop[] => {
42
+ if (name === undefined) return [];
43
+ const probe = probe_for(root.probes, kind, name, template);
44
+ const ls = context.inject<Provide, 'typescript/languageService'>(
45
+ 'typescript/languageService'
46
+ );
47
+ const decoded = context.decodeEmbeddedDocumentUri(URI.parse(uri));
48
+ if (!probe || !ls || !decoded) return [];
49
+ const file = context.inject<Provide, 'typescript/documentFileName'>(
50
+ 'typescript/documentFileName',
51
+ decoded[0]
52
+ );
53
+ const program = ls.getProgram();
54
+ if (!program || !file) return [];
55
+ // the program types against the typescript volar was built with
56
+ const typed = program as unknown as TS.Program;
57
+ return props_of(ts, typed, file, probe.alias) ?? [];
58
+ };
59
+
60
+ return {
61
+ provideCompletionItems(document, position) {
62
+ const root = root_code(context, document);
63
+ if (!root) return;
64
+ const source = document.getText();
65
+ const at = completion_context(
66
+ source,
67
+ document.offsetAt(position),
68
+ root.frontmatter
69
+ );
70
+ if (at === null) return;
71
+ const range = {
72
+ start: document.positionAt(at.range.start),
73
+ end: document.positionAt(at.range.end),
74
+ };
75
+ const named = template_named(source, root.frontmatter);
76
+ const template =
77
+ named === false ? undefined : (named ?? root.template);
78
+ let items: CompletionItem[] = [];
79
+
80
+ if (at.kind === 'template') {
81
+ items = root.templates.map((t, i) => ({
82
+ label: t.name,
83
+ kind: CompletionItemKind.EnumMember,
84
+ detail: t.file ?? 'template',
85
+ sortText: String(i).padStart(4, '0'),
86
+ textEdit: { range, newText: t.name },
87
+ }));
88
+ if (items.length !== 0)
89
+ items.push({
90
+ label: 'false',
91
+ kind: CompletionItemKind.Value,
92
+ detail: 'no template',
93
+ sortText: '9999',
94
+ textEdit: { range, newText: 'false' },
95
+ });
96
+ } else if (at.kind === 'frontmatter_key' || at.kind === 'arg_key') {
97
+ const list =
98
+ at.kind === 'frontmatter_key'
99
+ ? props(root, document.uri, 'template', template, undefined)
100
+ : props(
101
+ root,
102
+ document.uri,
103
+ 'directive',
104
+ at.directive,
105
+ template
106
+ );
107
+ // snippets, never props an author writes
108
+ const reserved =
109
+ at.kind === 'arg_key' && !at.inline
110
+ ? ['children', 'label']
111
+ : ['children'];
112
+ const sep = at.kind === 'frontmatter_key' ? ': ' : '=';
113
+ items = list
114
+ .filter(
115
+ (p) =>
116
+ !reserved.includes(p.name) && !at.existing.includes(p.name)
117
+ )
118
+ .map((p) => ({
119
+ label: p.name,
120
+ kind: CompletionItemKind.Property,
121
+ detail: p.optional ? `${p.type} (optional)` : p.type,
122
+ documentation: p.documentation || undefined,
123
+ sortText: (p.optional ? '1' : '0') + p.name,
124
+ textEdit: { range, newText: p.name + sep },
125
+ command: p.values.length !== 0 ? SUGGEST : undefined,
126
+ }));
127
+ } else {
128
+ const list =
129
+ at.kind === 'frontmatter_value'
130
+ ? props(root, document.uri, 'template', template, undefined)
131
+ : props(
132
+ root,
133
+ document.uri,
134
+ 'directive',
135
+ at.directive,
136
+ template
137
+ );
138
+ const prop = list.find((p) => p.name === at.key);
139
+ // yaml reads these plain scalars back as the same string, args stop at a comma or paren
140
+ const plain =
141
+ at.kind === 'frontmatter_value'
142
+ ? /^(?![-?:,[\]{}#&*!|>'"%@`]|true$|false$|null$|~$|[-+.\d])[^:#\n]*$/
143
+ : /^[^\s,)"']+$/;
144
+ items = (prop?.values ?? []).map((v, i) => {
145
+ const literal =
146
+ v === 'true' || v === 'false' || !Number.isNaN(Number(v));
147
+ return {
148
+ label: v,
149
+ kind: CompletionItemKind.EnumMember,
150
+ detail: prop!.type,
151
+ sortText: String(i).padStart(4, '0'),
152
+ textEdit: { range, newText: literal ? v : written(v, plain) },
153
+ };
154
+ });
155
+ }
156
+ return items.length === 0
157
+ ? undefined
158
+ : { isIncomplete: false, items };
159
+ },
160
+ };
161
+ },
162
+ };
163
+ }
@@ -0,0 +1,31 @@
1
+ import type {
2
+ Location,
3
+ LocationLink,
4
+ Position,
5
+ Range,
6
+ } from '@volar/language-server';
7
+
8
+ function contains(range: Range, at: Position): boolean {
9
+ const after_start =
10
+ at.line > range.start.line ||
11
+ (at.line === range.start.line && at.character >= range.start.character);
12
+ const before_end =
13
+ at.line < range.end.line ||
14
+ (at.line === range.end.line && at.character <= range.end.character);
15
+ return after_start && before_end;
16
+ }
17
+
18
+ /** drops the markdown self definition of a heading when another target exists, so a jump goes straight to its component */
19
+ export function without_self<T extends Location | LocationLink>(
20
+ results: T[] | null | undefined,
21
+ uri: string,
22
+ at: Position
23
+ ): T[] | null | undefined {
24
+ if (!Array.isArray(results) || results.length < 2) return results;
25
+ const others = results.filter((r) => {
26
+ const target = 'targetUri' in r ? r.targetUri : r.uri;
27
+ const range = 'targetUri' in r ? r.targetRange : r.range;
28
+ return target !== uri || !contains(range, at);
29
+ });
30
+ return others.length === 0 ? results : others;
31
+ }
package/src/index.ts CHANGED
@@ -11,8 +11,17 @@ import {
11
11
  import { create as createTypeScriptServices } from "volar-service-typescript";
12
12
  import { create as createCssService } from "volar-service-css";
13
13
  import { create as createMarkdownService } from "volar-service-markdown";
14
- import { create_pfm_language_plugin, create_svelte_language_plugin } from "@mdsvex/language-core";
14
+ import {
15
+ create_config_loader,
16
+ create_pfm_language_plugin,
17
+ create_svelte_language_plugin,
18
+ } from "@mdsvex/language-core";
19
+ import type { ConfigLoader } from "@mdsvex/language-core";
20
+ import { watch } from "node:fs";
15
21
  import { clean_svelte_hover } from "./clean_hover";
22
+ import { without_self } from "./definitions";
23
+ import { create_compile_diagnostics } from "./compile_diagnostics";
24
+ import { create_completions } from "./completions";
16
25
  import { URI } from "vscode-uri";
17
26
  import { forEachEmbeddedCode } from "@volar/language-core";
18
27
  import type { LanguagePlugin, VirtualCode } from "@volar/language-core";
@@ -24,15 +33,18 @@ import type * as ts from "typescript";
24
33
  * with the critical `typescript` property that registers .pfm
25
34
  * as a TypeScript-processable extension.
26
35
  */
27
- function createPfmLanguagePluginForServer(): LanguagePlugin<URI> {
28
- const inner = create_pfm_language_plugin();
36
+ function createPfmLanguagePluginForServer(
37
+ typescript: typeof ts,
38
+ config: ConfigLoader,
39
+ ): LanguagePlugin<URI> {
40
+ const inner = create_pfm_language_plugin({ typescript, config });
29
41
 
30
42
  return {
31
43
  getLanguageId(scriptId: URI): string | undefined {
32
- if (scriptId.path.endsWith(".pfm")) {
33
- return "pfm";
44
+ if (scriptId.scheme !== "file" && scriptId.scheme !== "untitled") {
45
+ return undefined;
34
46
  }
35
- return undefined;
47
+ return inner.getLanguageId(scriptId.fsPath);
36
48
  },
37
49
 
38
50
  createVirtualCode(scriptId, languageId, snapshot) {
@@ -66,15 +78,9 @@ function createPfmLanguagePluginForServer(): LanguagePlugin<URI> {
66
78
  }
67
79
  },
68
80
 
69
- // This is the critical piece: tells TypeScript about .pfm files
81
+ // tells typescript about the document extensions
70
82
  typescript: {
71
- extraFileExtensions: [
72
- {
73
- extension: "pfm",
74
- isMixedContent: true,
75
- scriptKind: 7 satisfies ts.ScriptKind.Deferred,
76
- },
77
- ],
83
+ extraFileExtensions: inner.typescript!.extraFileExtensions,
78
84
  getServiceScript(root: VirtualCode) {
79
85
  const tsCode = root.embeddedCodes?.find(
80
86
  (c) => c.languageId === "typescript",
@@ -151,15 +157,52 @@ const _on_hover = connection.onHover.bind(connection);
151
157
  });
152
158
  };
153
159
 
160
+ const _on_definition = connection.onDefinition.bind(connection);
161
+ (connection as any).onDefinition = (handler: Function) => {
162
+ _on_definition(
163
+ async (params: any, token: any) =>
164
+ without_self(await handler(params, token), params.textDocument.uri, params.position) as any,
165
+ );
166
+ };
167
+
154
168
  const server = createServer(connection);
155
169
 
156
170
  connection.listen();
157
171
 
172
+ // the manifest sits in node_modules, which editors do not watch, so the server does
173
+ const watched = new Set<string>();
174
+ let reload_timer: ReturnType<typeof setTimeout> | undefined;
175
+ function config_changed() {
176
+ clearTimeout(reload_timer);
177
+ reload_timer = setTimeout(() => {
178
+ server.project.reload();
179
+ server.languageFeatures.requestRefresh(false);
180
+ }, 100);
181
+ }
182
+ function watch_config(file: string) {
183
+ if (watched.has(file)) return;
184
+ watched.add(file);
185
+ try {
186
+ // a rename replaces the manifest, which ends a watch on its old inode
187
+ const watcher = watch(file, () => {
188
+ watcher.close();
189
+ watched.delete(file);
190
+ config_changed();
191
+ });
192
+ watcher.on("error", () => watched.delete(file));
193
+ } catch {
194
+ watched.delete(file);
195
+ }
196
+ }
197
+
158
198
  connection.onInitialize((params) => {
159
199
  const tsdk = loadTsdkByPath(
160
200
  params.initializationOptions?.typescript?.tsdk,
161
201
  params.locale,
162
202
  );
203
+ // the tsdk types against the typescript volar was built with
204
+ const typescript = tsdk.typescript as unknown as typeof ts;
205
+ const config = create_config_loader({ typescript, on_read: watch_config });
163
206
 
164
207
  return server.initialize(
165
208
  params,
@@ -168,7 +211,7 @@ connection.onInitialize((params) => {
168
211
  tsdk.diagnosticMessages,
169
212
  () => ({
170
213
  languagePlugins: [
171
- createPfmLanguagePluginForServer(),
214
+ createPfmLanguagePluginForServer(typescript, config),
172
215
  createSvelteLanguagePluginForServer(),
173
216
  ],
174
217
  }),
@@ -177,10 +220,30 @@ connection.onInitialize((params) => {
177
220
  ...createTypeScriptServices(tsdk.typescript),
178
221
  createCssService(),
179
222
  createMarkdownService(),
223
+ create_compile_diagnostics(),
224
+ create_completions(typescript),
180
225
  ],
181
226
  );
182
227
  });
183
228
 
184
- connection.onInitialized(server.initialized);
229
+ connection.onInitialized(() => {
230
+ server.initialized();
231
+ // a config that appears later, or one an editor does watch, reloads too
232
+ server.fileWatcher.watchFiles([
233
+ "**/mdsvex.config.json",
234
+ "**/node_modules/.mdsvex/manifest.json",
235
+ ]);
236
+ server.fileWatcher.onDidChangeWatchedFiles(({ changes }) => {
237
+ if (
238
+ changes.some(
239
+ (c) =>
240
+ c.uri.endsWith("/mdsvex.config.json") ||
241
+ c.uri.endsWith("/.mdsvex/manifest.json"),
242
+ )
243
+ ) {
244
+ config_changed();
245
+ }
246
+ });
247
+ });
185
248
 
186
249
  connection.onShutdown(server.shutdown);
@@ -0,0 +1,16 @@
1
+ import type { LanguageServiceContext } from '@volar/language-server';
2
+ import type { PfmVirtualCode } from '@mdsvex/language-core';
3
+ import { URI } from 'vscode-uri';
4
+
5
+ /** the pfm root code of a document, whose offsets are those of the source */
6
+ export function root_code(
7
+ context: LanguageServiceContext,
8
+ document: { uri: string; languageId: string }
9
+ ): PfmVirtualCode | undefined {
10
+ if (document.languageId !== 'pfm') return;
11
+ const decoded = context.decodeEmbeddedDocumentUri(URI.parse(document.uri));
12
+ if (decoded === undefined) return;
13
+ return context.language.scripts.get(decoded[0])?.generated?.root as
14
+ | PfmVirtualCode
15
+ | undefined;
16
+ }
@@ -46,6 +46,23 @@ import Test
46
46
  expect(result).not.toContain("}, {");
47
47
  });
48
48
 
49
+ it("strips the $on/$set alias of a runes component", () => {
50
+ const input = `\`\`\`typescript
51
+ (alias) type h2 = {
52
+ $on?(type: string, callback: (e: any) => void): () => void;
53
+ $set?(props: Partial<$$ComponentProps>): void;
54
+ }
55
+ (alias) const h2: Component<$$ComponentProps, {}, "">
56
+ export h2
57
+ \`\`\``;
58
+
59
+ const result = clean_svelte_hover(input);
60
+ expect(result).not.toContain("$on?");
61
+ expect(result).not.toContain("type h2");
62
+ expect(result).toContain('(alias) const h2: Component<$$ComponentProps, {}, "">');
63
+ expect(result).toContain("export h2");
64
+ });
65
+
49
66
  it("returns unchanged markdown when no marker present", () => {
50
67
  const input = "```typescript\nconst x: number\n```";
51
68
  expect(clean_svelte_hover(input)).toBe(input);
@@ -0,0 +1,60 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { URI } from "vscode-uri";
3
+ import { create_compile_diagnostics } from "../src/compile_diagnostics";
4
+
5
+ const SOURCE = "::nope[y]\n<img use:a />\n";
6
+
7
+ /** the slice of a volar context the plugin reads */
8
+ function context(diagnostics: unknown) {
9
+ const root = { diagnostics };
10
+ return {
11
+ decodeEmbeddedDocumentUri: (uri: URI) =>
12
+ uri.scheme === "volar-embedded-content"
13
+ ? [URI.file("/doc.svx"), "root"]
14
+ : undefined,
15
+ language: { scripts: { get: () => ({ generated: { root } }) } },
16
+ } as any;
17
+ }
18
+
19
+ function document(languageId: string) {
20
+ return {
21
+ uri: "volar-embedded-content://root/doc.svx",
22
+ languageId,
23
+ positionAt(offset: number) {
24
+ const before = SOURCE.slice(0, offset).split("\n");
25
+ return { line: before.length - 1, character: before.at(-1)!.length };
26
+ },
27
+ } as any;
28
+ }
29
+
30
+ describe("compile diagnostics", () => {
31
+ const plugin = create_compile_diagnostics();
32
+
33
+ it("reports the root diagnostics as errors and warnings from mdsvex", () => {
34
+ const instance = plugin.create(
35
+ context([
36
+ { start: 0, end: 6, message: "no component renders ::nope", severity: "error" },
37
+ { start: 10, end: 14, message: "<img> stays an element", severity: "warning" },
38
+ ]),
39
+ );
40
+ expect(instance.provideDiagnostics!(document("pfm"), {} as any)).toEqual([
41
+ {
42
+ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 6 } },
43
+ message: "no component renders ::nope",
44
+ severity: 1,
45
+ source: "mdsvex",
46
+ },
47
+ {
48
+ range: { start: { line: 1, character: 0 }, end: { line: 1, character: 4 } },
49
+ message: "<img> stays an element",
50
+ severity: 2,
51
+ source: "mdsvex",
52
+ },
53
+ ]);
54
+ });
55
+
56
+ it("leaves embedded typescript, css and markdown to their services", () => {
57
+ const instance = plugin.create(context([]));
58
+ expect(instance.provideDiagnostics!(document("typescript"), {} as any)).toBeUndefined();
59
+ });
60
+ });
@@ -0,0 +1,34 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { without_self } from "../src/definitions";
3
+
4
+ const range = (line: number, from: number, to: number) => ({
5
+ start: { line, character: from },
6
+ end: { line, character: to },
7
+ });
8
+
9
+ describe("without_self", () => {
10
+ const at = { line: 3, character: 1 };
11
+
12
+ it("drops a location holding the request when another target exists", () => {
13
+ const self = { uri: "file:///doc.svx", range: range(3, 0, 10) };
14
+ const component = { uri: "file:///Heading.svelte", range: range(0, 0, 0) };
15
+ expect(without_self([self, component], "file:///doc.svx", at)).toEqual([component]);
16
+ });
17
+
18
+ it("keeps a lone self location and other places in the document", () => {
19
+ const self = { uri: "file:///doc.svx", range: range(3, 0, 10) };
20
+ const elsewhere = { uri: "file:///doc.svx", range: range(9, 0, 4) };
21
+ expect(without_self([self], "file:///doc.svx", at)).toEqual([self]);
22
+ expect(without_self([self, elsewhere], "file:///doc.svx", at)).toEqual([elsewhere]);
23
+ });
24
+
25
+ it("reads location links by their target", () => {
26
+ const link = {
27
+ targetUri: "file:///doc.svx",
28
+ targetRange: range(3, 0, 10),
29
+ targetSelectionRange: range(3, 0, 2),
30
+ };
31
+ const other = { ...link, targetUri: "file:///Heading.svelte" };
32
+ expect(without_self([link, other], "file:///doc.svx", at)).toEqual([other]);
33
+ });
34
+ });