@lincyaw/language-server 0.0.0-stage → 1.0.0-rc.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/LICENSE +202 -0
- package/README.md +26 -2
- package/bin/presmium-language-server.mjs +14 -0
- package/package.json +49 -3
- package/src/domain/document.ts +92 -0
- package/src/domain/index.ts +6 -0
- package/src/domain/messages.ts +30 -0
- package/src/domain/preview-url.ts +11 -0
- package/src/domain/protocol.ts +25 -0
- package/src/node/anchors.ts +60 -0
- package/src/node/decks.ts +103 -0
- package/src/node/dev-server-launcher.ts +89 -0
- package/src/node/diagnostics.ts +40 -0
- package/src/node/document-cli.ts +19 -0
- package/src/node/server.ts +126 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,27 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @lincyaw/language-server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Language server for canonical `lecture.json` teaching documents: shared validation, normalized entity definitions, project code anchor definitions and hovers, and preview synchronization by stable page ownership.
|
|
4
|
+
|
|
5
|
+
Part of [Presmium](https://github.com/Lincyaw/presmium), which derives web pages, slides, Jupyter notebooks and narrated playback from the same teaching document.
|
|
6
|
+
|
|
7
|
+
## Usage
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pnpm exec presmium-language-server --stdio
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
It also takes `--node-ipc` and `--socket=<port>`. Clients select `**/lecture.json` using their native JSON editor and associate the public kernel schema for completion. The VS Code extension generates and bundles this schema from `DOCUMENT_JSON_SCHEMA`; the server adds syntax and domain graph diagnostics using `validateDocument`.
|
|
14
|
+
|
|
15
|
+
Opened buffers are validated without writing or compiling unsaved text. Saving JSON and notifications for watched project inputs trigger a real compiler run. Diagnostics resolve JSON pointers to token ranges; entity and `origin.anchor` definitions navigate to their authoritative JSON or project code. `presmium/section` locates a page from the entity under the cursor, including normalized blocks, steps and narration. `presmium/preview` starts a real `presmium dev` web server for the canonical entry and stops it when the language server closes.
|
|
16
|
+
|
|
17
|
+
Compilation and preview prefer the document's installed `@lincyaw/presmium` package, which supplies its bundled plugins and renderers. A standalone installation uses the project's CLI or the language server's own CLI dependencies.
|
|
18
|
+
|
|
19
|
+
The server does not register its own completion provider: JSON schema completion remains with the editor. The studio provides native rich-text editing of the same `lecture.json` document.
|
|
20
|
+
|
|
21
|
+
## Documentation
|
|
22
|
+
|
|
23
|
+
- [Author guide](https://github.com/Lincyaw/presmium/blob/main/site/guide/locales/en/lecture.json)
|
|
24
|
+
|
|
25
|
+
## License
|
|
26
|
+
|
|
27
|
+
Apache-2.0
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createJiti } from 'jiti'
|
|
3
|
+
|
|
4
|
+
console.log = console.info = console.debug = console.error
|
|
5
|
+
|
|
6
|
+
const emitWarning = process.emitWarning
|
|
7
|
+
process.emitWarning = (warning, ...args) => {
|
|
8
|
+
const code = typeof args[0] === 'object' ? args[0]?.code : args[1]
|
|
9
|
+
if (code !== 'DEP0040') emitWarning.call(process, warning, ...args)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const jiti = createJiti(import.meta.url)
|
|
13
|
+
const { startServer } = await jiti.import('../src/node/server.ts')
|
|
14
|
+
startServer()
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lincyaw/language-server",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0-rc.1",
|
|
4
|
+
"description": "Language server for canonical lecture.json documents: validation, entity navigation, code anchors and preview sync",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/Lincyaw/presmium.git",
|
|
9
|
+
"directory": "packages/language-server"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/Lincyaw/presmium/tree/main/packages/language-server#readme",
|
|
12
|
+
"bugs": "https://github.com/Lincyaw/presmium/issues",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"presmium",
|
|
15
|
+
"lsp",
|
|
16
|
+
"language-server"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=22.19"
|
|
21
|
+
},
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"bin": {
|
|
26
|
+
"presmium-language-server": "./bin/presmium-language-server.mjs"
|
|
27
|
+
},
|
|
28
|
+
"exports": {
|
|
29
|
+
"./domain": "./src/domain/index.ts",
|
|
30
|
+
"./protocol": "./src/domain/protocol.ts",
|
|
31
|
+
"./package.json": "./package.json"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"bin",
|
|
35
|
+
"src"
|
|
36
|
+
],
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"jiti": "^2.7.0",
|
|
39
|
+
"jsonc-parser": "3.3.1",
|
|
40
|
+
"vscode-languageserver": "10.1.2",
|
|
41
|
+
"vscode-languageserver-textdocument": "1.0.15",
|
|
42
|
+
"@lincyaw/cli": "1.0.0-rc.1",
|
|
43
|
+
"@lincyaw/compiler": "1.0.0-rc.1",
|
|
44
|
+
"@lincyaw/kernel": "1.0.0-rc.1",
|
|
45
|
+
"@lincyaw/viewer": "1.0.0-rc.1",
|
|
46
|
+
"@lincyaw/host": "1.0.0-rc.1",
|
|
47
|
+
"@lincyaw/web": "1.0.0-rc.1"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"typecheck": "tsc -p tsconfig.json"
|
|
51
|
+
}
|
|
6
52
|
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { isRecord, validateDocument } from '@lincyaw/kernel'
|
|
2
|
+
import type { TeachingDocument } from '@lincyaw/kernel'
|
|
3
|
+
import { findNodeAtLocation, findNodeAtOffset, getNodePath, getNodeValue, parseTree } from 'jsonc-parser'
|
|
4
|
+
import type { JSONPath, Node, ParseError } from 'jsonc-parser'
|
|
5
|
+
|
|
6
|
+
/** Strict JSON syntax, using parser offsets unchanged even when the entry has a BOM. */
|
|
7
|
+
export function readDocument(text: string) {
|
|
8
|
+
const errors: ParseError[] = []
|
|
9
|
+
const tree = parseTree(text.replace(/^\uFEFF/, ' '), errors, { disallowComments: true, allowTrailingComma: false, allowEmptyContent: false })
|
|
10
|
+
const validation = tree && !errors.length ? validateDocument(getNodeValue(tree)) : undefined
|
|
11
|
+
return { tree, errors, validation, document: validation?.document }
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function nodeAt(tree: Node, offset: number): { node: Node, path: JSONPath } | undefined {
|
|
15
|
+
const node = findNodeAtOffset(tree, offset, true)
|
|
16
|
+
return node ? { node, path: getNodePath(node) } : undefined
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Missing properties point at the closest existing parent, rather than an invented source line. */
|
|
20
|
+
export function nodeAtPointer(tree: Node, pointer: string): Node {
|
|
21
|
+
const path = pointer.replace(/^#/, '').split('/').slice(1).map(key => key.replaceAll('~1', '/').replaceAll('~0', '~'))
|
|
22
|
+
let node = tree
|
|
23
|
+
for (const key of path) {
|
|
24
|
+
const found = findNodeAtLocation(node, [node.type === 'array' ? Number(key) : key])
|
|
25
|
+
if (!found) break
|
|
26
|
+
node = found
|
|
27
|
+
}
|
|
28
|
+
return node
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function owners(document: TeachingDocument): Map<string, string> {
|
|
32
|
+
const result = new Map<string, string>()
|
|
33
|
+
const rich = (node: unknown, section: string) => {
|
|
34
|
+
if (!isRecord(node)) return
|
|
35
|
+
if (typeof node.id === 'string') result.set(node.id, section)
|
|
36
|
+
if (Array.isArray(node.children)) node.children.forEach(child => rich(child, section))
|
|
37
|
+
if (Array.isArray(node.fallback)) node.fallback.forEach(child => rich(child, section))
|
|
38
|
+
}
|
|
39
|
+
const visit = (id: string, section: string) => {
|
|
40
|
+
result.set(id, section)
|
|
41
|
+
const block = document.blocks[id]!
|
|
42
|
+
if (block.type === 'container' || block.type === 'component') block.children?.forEach(child => visit(child, section))
|
|
43
|
+
if (block.type === 'text') block.content.forEach(node => rich(node, section))
|
|
44
|
+
}
|
|
45
|
+
for (const id of document.sectionOrder) {
|
|
46
|
+
result.set(`page:${id}`, id)
|
|
47
|
+
document.sections[id]!.children.forEach(child => visit(child, id))
|
|
48
|
+
}
|
|
49
|
+
return result
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Entity ownership determines the page even if normalized maps are reordered or minified. */
|
|
53
|
+
export function sectionAtPath(document: TeachingDocument, path: JSONPath): string | undefined {
|
|
54
|
+
const [map, id, field, key] = path
|
|
55
|
+
const owner = owners(document)
|
|
56
|
+
const narration = (id: string) => document.sectionOrder.find(section => document.sections[section]!.stepOrder.some(step => document.steps[step]!.narrationIds.includes(id)))
|
|
57
|
+
const usedBlock = (predicate: (block: TeachingDocument['blocks'][string]) => boolean) => Object.values(document.blocks).find(predicate)?.id
|
|
58
|
+
if (map === 'sections' && typeof id === 'string') return document.sections[id]?.id
|
|
59
|
+
if (map === 'sectionOrder' && typeof id === 'number') return document.sectionOrder[id]
|
|
60
|
+
if (map === 'blocks' && typeof id === 'string') return owner.get(id)
|
|
61
|
+
if (map === 'steps' && typeof id === 'string') return document.steps[id]?.sectionId
|
|
62
|
+
if (map === 'narrations' && typeof id === 'string') return narration(id)
|
|
63
|
+
if (map === 'definitions' && typeof id === 'string') return owner.get(usedBlock(block => block.type === 'component' && block.definitionId === id) ?? '')
|
|
64
|
+
if (map === 'assets' && typeof id === 'string') return owner.get(usedBlock(block => block.type === 'image' && block.assetId === id) ?? '')
|
|
65
|
+
if (map === 'production') {
|
|
66
|
+
if (id === 'sectionOverrides' && typeof field === 'string') return document.sections[field]?.id
|
|
67
|
+
if (id === 'stepOverrides' && typeof field === 'string') return document.steps[field]?.sectionId
|
|
68
|
+
if (id === 'narrationOverrides' && typeof field === 'string') return narration(field)
|
|
69
|
+
if (id === 'cueTimings' && typeof field === 'string') {
|
|
70
|
+
const owner = Object.values(document.narrations).find(value => value.content.some(node => node.type === 'cue' && node.id === field))
|
|
71
|
+
return owner && narration(owner.id)
|
|
72
|
+
}
|
|
73
|
+
if (id === 'mediaClips' && typeof field === 'number') return document.steps[document.production.mediaClips[field]?.attachment.stepId ?? '']?.sectionId
|
|
74
|
+
}
|
|
75
|
+
if (map === 'comments' && typeof id === 'string') return owner.get(document.comments?.[id]?.anchor?.[key === 'to' ? 'to' : 'from'].blockId ?? '')
|
|
76
|
+
return map === 'metadata' || !path.length ? document.sectionOrder[0] : undefined
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function entityReference(document: TeachingDocument, path: JSONPath, value: unknown): JSONPath | undefined {
|
|
80
|
+
if (typeof value !== 'string') return undefined
|
|
81
|
+
const [root, , field] = path, last = path.at(-1)
|
|
82
|
+
const child = path.length === 4 && field === 'children' && (root === 'sections' || root === 'blocks')
|
|
83
|
+
const visual = root === 'steps' && field === 'visuals' && path.length === 5 && last === 'blockId'
|
|
84
|
+
const cue = root === 'narrations' && field === 'content' && path.length === 6 && path.at(-2) === 'target' && last === 'blockId'
|
|
85
|
+
const asset = last === 'assetId' && (root === 'blocks' && path.length === 3 || root === 'production' && (path.at(-2) === 'voiceSource' || path[1] === 'mediaClips' && path.length === 4))
|
|
86
|
+
const map = root === 'sectionOrder' && path.length === 2 || root === 'steps' && field === 'sectionId' && path.length === 3 ? 'sections'
|
|
87
|
+
: root === 'blocks' && field === 'definitionId' && path.length === 3 ? 'definitions'
|
|
88
|
+
: asset ? 'assets' : child || visual || cue ? 'blocks'
|
|
89
|
+
: root === 'sections' && field === 'stepOrder' && path.length === 4 || root === 'steps' && field === 'inherits' && path.length === 3 || root === 'production' && path[1] === 'mediaClips' && path.at(-2) === 'attachment' && last === 'stepId' ? 'steps'
|
|
90
|
+
: root === 'steps' && field === 'narrationIds' && path.length === 4 ? 'narrations' : undefined
|
|
91
|
+
return map && Object.hasOwn(document[map], value) ? [map, value] : undefined
|
|
92
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { entityReference, nodeAt, nodeAtPointer, readDocument, sectionAtPath } from './document.ts'
|
|
2
|
+
export { LS_MESSAGES } from './messages.ts'
|
|
3
|
+
export type { LsMessages } from './messages.ts'
|
|
4
|
+
export { previewUrl } from './preview-url.ts'
|
|
5
|
+
export { PREVIEW_REQUEST, SECTION_REQUEST } from './protocol.ts'
|
|
6
|
+
export type { DocumentParams, PositionParams, Preview, SectionLocation } from './protocol.ts'
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Locale } from '@lincyaw/kernel'
|
|
2
|
+
|
|
3
|
+
export const LS_MESSAGES = {
|
|
4
|
+
'zh-CN': {
|
|
5
|
+
status: { exact: '已解析', moved: '已移动', fuzzy: '待确认', lost: '已失效' } as Record<string, string>,
|
|
6
|
+
pinnedAt: (commit: string) => `锁定在 ${commit}`,
|
|
7
|
+
drifted: '锁定之后已漂移',
|
|
8
|
+
recordedOutput: '录制的输出',
|
|
9
|
+
timedOut: '超时',
|
|
10
|
+
exitCode: (code: number | null) => `退出码 ${code}`,
|
|
11
|
+
noOutput: '(没有输出)',
|
|
12
|
+
runsLive: '*配置为在浏览器中执行,尚无录制输出。*',
|
|
13
|
+
notRecorded: '*还没有录制的输出。*',
|
|
14
|
+
moreLines: (count: number) => `…… 另有 ${count} 行`,
|
|
15
|
+
},
|
|
16
|
+
'en': {
|
|
17
|
+
status: { exact: 'exact', moved: 'moved', fuzzy: 'to confirm', lost: 'lost' } as Record<string, string>,
|
|
18
|
+
pinnedAt: (commit: string) => `pinned at ${commit}`,
|
|
19
|
+
drifted: 'drifted since the pin',
|
|
20
|
+
recordedOutput: 'Recorded output',
|
|
21
|
+
timedOut: 'timed out',
|
|
22
|
+
exitCode: (code: number | null) => `exit code ${code}`,
|
|
23
|
+
noOutput: '(no output)',
|
|
24
|
+
runsLive: '*Configured to run in the browser; no recorded output.*',
|
|
25
|
+
notRecorded: '*No recorded output yet.*',
|
|
26
|
+
moreLines: (count: number) => `… ${count} more lines`,
|
|
27
|
+
},
|
|
28
|
+
} satisfies Record<Locale, unknown>
|
|
29
|
+
|
|
30
|
+
export type LsMessages = (typeof LS_MESSAGES)[Locale]
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { SectionLocation } from './protocol.ts'
|
|
2
|
+
|
|
3
|
+
const page = (link: string) => link.split('#')[0]!
|
|
4
|
+
|
|
5
|
+
export function previewUrl(base: string, section: SectionLocation | null | undefined, shown?: SectionLocation): string {
|
|
6
|
+
const root = base.replace(/\/?$/, '/')
|
|
7
|
+
if (!section) return root
|
|
8
|
+
const id = encodeURIComponent(section.id)
|
|
9
|
+
const target = shown && page(shown.link) === page(section.link) ? `${page(section.link)}#${id}` : `${page(section.link)}?section=${id}`
|
|
10
|
+
return new URL(target.replace(/^\//, ''), root).href
|
|
11
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export interface DocumentParams {
|
|
2
|
+
textDocument: { uri: string }
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export interface PositionParams extends DocumentParams {
|
|
6
|
+
position: { line: number, character: number }
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export const PREVIEW_REQUEST = 'presmium/preview'
|
|
10
|
+
|
|
11
|
+
export interface Preview {
|
|
12
|
+
entry: string
|
|
13
|
+
url: string
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const SECTION_REQUEST = 'presmium/section'
|
|
17
|
+
|
|
18
|
+
/** The section at a position in a source file, and its page in the web form. */
|
|
19
|
+
export interface SectionLocation {
|
|
20
|
+
entry: string
|
|
21
|
+
id: string
|
|
22
|
+
index: number
|
|
23
|
+
title: string
|
|
24
|
+
link: string
|
|
25
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { resolve } from 'node:path'
|
|
2
|
+
import { pathToFileURL } from 'node:url'
|
|
3
|
+
import type { Compilation } from '@lincyaw/compiler'
|
|
4
|
+
import { docBlocks, isRenderable } from '@lincyaw/kernel'
|
|
5
|
+
import type { AnchorString, CodeNode, Resolution, ResolvedLocation } from '@lincyaw/kernel'
|
|
6
|
+
import { MarkupKind } from 'vscode-languageserver/node'
|
|
7
|
+
import type { Hover, Location, Range } from 'vscode-languageserver/node'
|
|
8
|
+
import type { LsMessages } from '../domain/index.ts'
|
|
9
|
+
|
|
10
|
+
const MAX_LINES = 60
|
|
11
|
+
export interface AnchorRef { anchor: AnchorString, blockId: string, pin?: string, range: Range }
|
|
12
|
+
|
|
13
|
+
function resolveAnchor(compilation: Compilation, ref: AnchorRef): Promise<Resolution> {
|
|
14
|
+
return compilation.resolvers.resolve(ref.anchor, compilation.src, compilation.lock.get(ref.anchor), ref.pin)
|
|
15
|
+
}
|
|
16
|
+
function locationOf(compilation: Compilation, location: ResolvedLocation): Location {
|
|
17
|
+
const last = location.text.split(/\r?\n/).at(-1) ?? ''
|
|
18
|
+
return { uri: pathToFileURL(resolve(compilation.workspaceRoot, location.file)).href,
|
|
19
|
+
range: { start: { line: location.startLine - 1, character: 0 }, end: { line: location.endLine - 1, character: last.length } } }
|
|
20
|
+
}
|
|
21
|
+
export async function anchorDefinition(compilation: Compilation, ref: AnchorRef): Promise<Location[]> {
|
|
22
|
+
const resolution = await resolveAnchor(compilation, ref)
|
|
23
|
+
return (resolution.location ? [resolution.location] : resolution.candidates ?? []).map(location => locationOf(compilation, location))
|
|
24
|
+
}
|
|
25
|
+
function fenced(t: LsMessages, text: string, lang = ''): string {
|
|
26
|
+
const lines = text.replace(/\n+$/, '').split('\n')
|
|
27
|
+
const shown = lines.length > MAX_LINES ? [...lines.slice(0, MAX_LINES), t.moreLines(lines.length - MAX_LINES)] : lines
|
|
28
|
+
const fence = '`'.repeat(Math.max(3, ...[...text.matchAll(/`+/g)].map(m => m[0].length + 1)))
|
|
29
|
+
return `${fence}${lang}\n${shown.join('\n')}\n${fence}`
|
|
30
|
+
}
|
|
31
|
+
function where(file: string, startLine: number, endLine: number): string { return `\`${file}:${startLine}-${endLine}\`` }
|
|
32
|
+
export async function anchorHover(compilation: Compilation, ref: AnchorRef, t: LsMessages): Promise<Hover> {
|
|
33
|
+
const block = [...docBlocks(compilation.doc)].find(({ block }) => block.id === ref.blockId)?.block
|
|
34
|
+
const node = block?.node.type === 'code' && block.node.origin?.anchor === ref.anchor && block.node.origin?.pin === ref.pin ? block.node : undefined
|
|
35
|
+
const parts = node?.origin && node.origin.startLine > 0 ? codeNodeHover(node, t) : await resolvedHover(compilation, ref, t)
|
|
36
|
+
return { contents: { kind: MarkupKind.Markdown, value: parts.join('\n\n') }, range: ref.range }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function codeNodeHover(node: CodeNode, t: LsMessages): string[] {
|
|
40
|
+
const origin = node.origin!
|
|
41
|
+
const notes = [t.status[origin.status] ?? origin.status, origin.pin && t.pinnedAt(origin.pin.slice(0, 7)), origin.drift === 'drifted' && t.drifted].filter(Boolean)
|
|
42
|
+
const parts = [`**${origin.anchor}** ${where(origin.file, origin.startLine, origin.endLine)} (${notes.join(', ')})`, fenced(t, node.value, node.lang)]
|
|
43
|
+
const run = node.outputs?.[0]
|
|
44
|
+
if (run) {
|
|
45
|
+
const status = run.timedOut ? t.timedOut : run.ok ? `${run.durationMs} ms` : t.exitCode(run.exitCode)
|
|
46
|
+
parts.push(`**${t.recordedOutput}** (${run.executorId}, ${status})`, fenced(t, [run.stdout, run.stderr].filter(Boolean).join('\n') || t.noOutput))
|
|
47
|
+
} else if (node.run) {
|
|
48
|
+
parts.push(node.run.when === 'live' ? t.runsLive : t.notRecorded)
|
|
49
|
+
}
|
|
50
|
+
return parts
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function resolvedHover(compilation: Compilation, ref: AnchorRef, t: LsMessages): Promise<string[]> {
|
|
54
|
+
const resolution = await resolveAnchor(compilation, ref)
|
|
55
|
+
const { location } = resolution
|
|
56
|
+
const parts = [[`**${ref.anchor}**`, location && where(location.file, location.startLine, location.endLine), `(${t.status[resolution.status] ?? resolution.status})`].filter(Boolean).join(' ')]
|
|
57
|
+
if (resolution.message) parts.push(resolution.message)
|
|
58
|
+
if (location && isRenderable(resolution)) parts.push(fenced(t, location.text, /\.([\w-]+)$/.exec(location.file)?.[1] ?? ''))
|
|
59
|
+
return parts
|
|
60
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { basename, join } from 'node:path'
|
|
2
|
+
import { readFileSync } from 'node:fs'
|
|
3
|
+
import { Compiler, DECK_ENTRY } from '@lincyaw/compiler'
|
|
4
|
+
import type { Compilation } from '@lincyaw/compiler'
|
|
5
|
+
import { ANCHOR_LOCK_PATH, errorMessage, fnv1a64 } from '@lincyaw/kernel'
|
|
6
|
+
import type { Finding } from '@lincyaw/kernel'
|
|
7
|
+
import { documentCli } from './document-cli.ts'
|
|
8
|
+
|
|
9
|
+
export class Deck {
|
|
10
|
+
readonly entry: string
|
|
11
|
+
readonly #compiler: Compiler
|
|
12
|
+
readonly #compiled: (deck: Deck) => void
|
|
13
|
+
compilation?: Compilation
|
|
14
|
+
findings: Finding[] = []
|
|
15
|
+
sourceFingerprint?: string
|
|
16
|
+
#running?: Promise<void>
|
|
17
|
+
#again = false
|
|
18
|
+
#version = 0
|
|
19
|
+
#completedVersion = -1
|
|
20
|
+
|
|
21
|
+
constructor(entry: string, compiled: (deck: Deck) => void) {
|
|
22
|
+
this.entry = entry
|
|
23
|
+
this.#compiler = new Compiler(entry, { bundled: documentCli(entry).bundled })
|
|
24
|
+
this.#compiled = compiled
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
compile(): Promise<void> {
|
|
28
|
+
if (this.#running) {
|
|
29
|
+
this.#again = true
|
|
30
|
+
return this.#running
|
|
31
|
+
}
|
|
32
|
+
this.#running = (async () => {
|
|
33
|
+
do {
|
|
34
|
+
this.#again = false
|
|
35
|
+
await this.#compileOnce()
|
|
36
|
+
} while (this.#again)
|
|
37
|
+
this.#running = undefined
|
|
38
|
+
})()
|
|
39
|
+
return this.#running
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
ready(): Promise<void> {
|
|
43
|
+
return this.#running ?? Promise.resolve()
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
invalidate(): void { this.#version++ }
|
|
47
|
+
get findingsCurrent(): boolean { return this.#completedVersion === this.#version }
|
|
48
|
+
|
|
49
|
+
dependsOn(file: string): boolean {
|
|
50
|
+
const { compilation } = this
|
|
51
|
+
if (!compilation) return file === this.entry
|
|
52
|
+
return compilation.sourceFiles.includes(file) || compilation.inputs.files.includes(file) || file === join(compilation.deckDir, ANCHOR_LOCK_PATH)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async #compileOnce(): Promise<void> {
|
|
56
|
+
const version = this.#version
|
|
57
|
+
let attemptedFingerprint: string | undefined
|
|
58
|
+
try { attemptedFingerprint = fnv1a64(readFileSync(this.entry, 'utf8')) } catch { /* The compiler reports unavailable entries. */ }
|
|
59
|
+
try {
|
|
60
|
+
const compilation = await this.#compiler.compile()
|
|
61
|
+
this.findings = [...compilation.doc.diagnostics, ...await compilation.check()]
|
|
62
|
+
this.compilation = compilation
|
|
63
|
+
this.sourceFingerprint = compilation.sourceFingerprints?.[this.entry]
|
|
64
|
+
} catch (error) {
|
|
65
|
+
this.compilation = undefined
|
|
66
|
+
this.sourceFingerprint = attemptedFingerprint
|
|
67
|
+
this.findings = [{ checkId: 'presmium.compile', severity: 'error', message: errorMessage(error), source: { file: this.entry, line: 1 } }]
|
|
68
|
+
}
|
|
69
|
+
this.#completedVersion = version
|
|
70
|
+
if (this.findingsCurrent && !this.#again) this.#compiled(this)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export class Decks {
|
|
75
|
+
readonly #decks = new Map<string, Deck>()
|
|
76
|
+
readonly #compiled: (deck: Deck) => void
|
|
77
|
+
|
|
78
|
+
constructor(compiled: (deck: Deck) => void) {
|
|
79
|
+
this.#compiled = compiled
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
all(): Deck[] {
|
|
83
|
+
return [...this.#decks.values()]
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
open(entry: string): Deck {
|
|
87
|
+
let deck = this.#decks.get(entry)
|
|
88
|
+
if (!deck) {
|
|
89
|
+
deck = new Deck(entry, this.#compiled)
|
|
90
|
+
this.#decks.set(entry, deck)
|
|
91
|
+
void deck.compile()
|
|
92
|
+
}
|
|
93
|
+
return deck
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Only the canonical JSON entry opens a document; project inputs are watched dependencies. */
|
|
97
|
+
async findByFile(file: string): Promise<Deck | undefined> {
|
|
98
|
+
if (basename(file) !== DECK_ENTRY) return undefined
|
|
99
|
+
const deck = this.open(file)
|
|
100
|
+
await deck.ready()
|
|
101
|
+
return deck
|
|
102
|
+
}
|
|
103
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import type { ChildProcess } from 'node:child_process'
|
|
3
|
+
import { dirname, join } from 'node:path'
|
|
4
|
+
import { createInterface } from 'node:readline'
|
|
5
|
+
import { documentCli } from './document-cli.ts'
|
|
6
|
+
|
|
7
|
+
const START_TIMEOUT = 120_000
|
|
8
|
+
const PREVIEW_DIR = '.presmium/preview'
|
|
9
|
+
|
|
10
|
+
function stopProcess(child: ChildProcess, signal: NodeJS.Signals = 'SIGTERM'): void {
|
|
11
|
+
if (!child.pid || child.exitCode !== null || child.signalCode !== null) return
|
|
12
|
+
if (process.platform === 'win32') {
|
|
13
|
+
const task = spawn('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
|
|
14
|
+
task.once('error', () => { child.kill(signal) })
|
|
15
|
+
} else child.kill(signal)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Starts a `presmium dev` web server for each deck the editor previews, once, and stops them all on close. */
|
|
19
|
+
export class DevServerLauncher {
|
|
20
|
+
readonly #urls = new Map<string, Promise<string>>()
|
|
21
|
+
readonly #children = new Set<ChildProcess>()
|
|
22
|
+
readonly #log: (line: string) => void
|
|
23
|
+
|
|
24
|
+
constructor(log: (line: string) => void) {
|
|
25
|
+
this.#log = log
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The address of the deck's dev server, started on first use. */
|
|
29
|
+
urlOf(entry: string): Promise<string> {
|
|
30
|
+
const known = this.#urls.get(entry)
|
|
31
|
+
if (known) return known
|
|
32
|
+
const forget = () => {
|
|
33
|
+
if (this.#urls.get(entry) === url) this.#urls.delete(entry)
|
|
34
|
+
}
|
|
35
|
+
const url: Promise<string> = this.#start(entry, forget)
|
|
36
|
+
this.#urls.set(entry, url)
|
|
37
|
+
url.catch(forget)
|
|
38
|
+
return url
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
#start(entry: string, forget: () => void): Promise<string> {
|
|
42
|
+
const deckDir = dirname(entry)
|
|
43
|
+
const args = [documentCli(entry).bin, 'dev', entry, '--to', 'web', '--out', join(deckDir, PREVIEW_DIR)]
|
|
44
|
+
// The lines read below are the English ones: `presmium dev` prints in the system's language.
|
|
45
|
+
const child = spawn(process.execPath, args, { cwd: deckDir, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, LC_ALL: 'en_US.UTF-8' } })
|
|
46
|
+
this.#children.add(child)
|
|
47
|
+
return new Promise((resolve, reject) => {
|
|
48
|
+
let started = false
|
|
49
|
+
const fail = (error: Error) => {
|
|
50
|
+
clearTimeout(timer)
|
|
51
|
+
reject(error)
|
|
52
|
+
if (!started) stopProcess(child)
|
|
53
|
+
}
|
|
54
|
+
const timer = setTimeout(() => fail(new Error('presmium dev did not start the web server in time')), START_TIMEOUT)
|
|
55
|
+
createInterface({ input: child.stderr! }).on('line', line => this.#log(line))
|
|
56
|
+
createInterface({ input: child.stdout! }).on('line', (line) => {
|
|
57
|
+
this.#log(line)
|
|
58
|
+
if (started) return
|
|
59
|
+
const url = /^web\s+(https?:\/\/\S+)/.exec(line)?.[1]
|
|
60
|
+
if (url) {
|
|
61
|
+
started = true
|
|
62
|
+
clearTimeout(timer)
|
|
63
|
+
resolve(url)
|
|
64
|
+
} else if (line.startsWith('watching;')) {
|
|
65
|
+
fail(new Error('presmium dev started no web server; is the web renderer installed?'))
|
|
66
|
+
}
|
|
67
|
+
})
|
|
68
|
+
child.once('error', fail)
|
|
69
|
+
child.once('exit', (code) => {
|
|
70
|
+
this.#children.delete(child)
|
|
71
|
+
forget()
|
|
72
|
+
fail(new Error(`presmium dev exited with code ${code}`))
|
|
73
|
+
})
|
|
74
|
+
})
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async close(): Promise<void> {
|
|
78
|
+
const exits = [...this.#children].map(child => new Promise<void>((done) => {
|
|
79
|
+
const timer = setTimeout(() => {
|
|
80
|
+
stopProcess(child, 'SIGKILL')
|
|
81
|
+
done()
|
|
82
|
+
}, 5000).unref()
|
|
83
|
+
child.once('exit', () => { clearTimeout(timer); done() })
|
|
84
|
+
stopProcess(child)
|
|
85
|
+
}))
|
|
86
|
+
this.#urls.clear()
|
|
87
|
+
await Promise.all(exits)
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { Finding, Severity, SourcePos } from '@lincyaw/kernel'
|
|
2
|
+
import { printParseErrorCode } from 'jsonc-parser'
|
|
3
|
+
import { TextDocument } from 'vscode-languageserver-textdocument'
|
|
4
|
+
import { DiagnosticSeverity } from 'vscode-languageserver/node'
|
|
5
|
+
import type { Diagnostic, Range } from 'vscode-languageserver/node'
|
|
6
|
+
import { nodeAtPointer, readDocument } from '../domain/document.ts'
|
|
7
|
+
|
|
8
|
+
const SEVERITY: Record<Severity, DiagnosticSeverity> = { error: DiagnosticSeverity.Error, warning: DiagnosticSeverity.Warning, info: DiagnosticSeverity.Information }
|
|
9
|
+
export const offsetRange = (document: TextDocument, offset: number, length: number): Range => ({ start: document.positionAt(offset), end: document.positionAt(offset + Math.max(1, length)) })
|
|
10
|
+
|
|
11
|
+
/** The same syntax and graph validator used by source saves, before compilation is available. */
|
|
12
|
+
export function documentDiagnostics(text: string): Diagnostic[] {
|
|
13
|
+
const document = TextDocument.create('', 'json', 0, text), source = readDocument(text)
|
|
14
|
+
return [
|
|
15
|
+
...source.errors.map(error => ({ range: offsetRange(document, error.offset, error.length), severity: DiagnosticSeverity.Error, source: 'presmium', code: 'document.json', message: printParseErrorCode(error.error) })),
|
|
16
|
+
...(source.validation?.issues.map(issue => {
|
|
17
|
+
const node = nodeAtPointer(source.tree!, issue.path)
|
|
18
|
+
return { range: offsetRange(document, node.offset, node.length), severity: SEVERITY[issue.severity], source: 'presmium', code: issue.code, message: issue.message }
|
|
19
|
+
}) ?? []),
|
|
20
|
+
]
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Compiler JSON pointers resolve to real token ranges; project findings retain their code lines. */
|
|
24
|
+
export function diagnosticsByFile(findings: Finding[], entry: string, textOf: (file: string) => string): Map<string, Diagnostic[]> {
|
|
25
|
+
const byFile = new Map<string, Diagnostic[]>(), documents = new Map<string, TextDocument>()
|
|
26
|
+
const trees = new Map<string, ReturnType<typeof readDocument>['tree']>()
|
|
27
|
+
for (const finding of findings) {
|
|
28
|
+
const source = finding.source as SourcePos | undefined, file = source?.file ?? entry
|
|
29
|
+
let document = documents.get(file)
|
|
30
|
+
if (!document) { document = TextDocument.create('', 'json', 0, textOf(file)); documents.set(file, document) }
|
|
31
|
+
if (source?.pointer && !trees.has(file)) trees.set(file, readDocument(document.getText()).tree)
|
|
32
|
+
const tree = trees.get(file)
|
|
33
|
+
const node = tree && source?.pointer ? nodeAtPointer(tree, source.pointer) : undefined
|
|
34
|
+
const line = Math.max(1, source?.line ?? 1) - 1, text = document.getText().split(/\r?\n/)[line] ?? ''
|
|
35
|
+
const range = node ? offsetRange(document, node.offset, node.length) : { start: { line, character: text.length - text.trimStart().length }, end: { line, character: text.trimEnd().length } }
|
|
36
|
+
const diagnostic: Diagnostic = { range, severity: SEVERITY[finding.severity], source: 'presmium', code: finding.checkId, message: finding.hint ? `${finding.message}\n${finding.hint}` : finding.message }
|
|
37
|
+
byFile.set(file, [...byFile.get(file) ?? [], diagnostic])
|
|
38
|
+
}
|
|
39
|
+
return byFile
|
|
40
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { dirname, join } from 'node:path'
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
|
+
import { findPackageDir } from '@lincyaw/compiler'
|
|
4
|
+
import { findPackageBin } from '@lincyaw/kernel/node'
|
|
5
|
+
|
|
6
|
+
/** The document's installed command and the package that supplies its bundled plugins. */
|
|
7
|
+
export function documentCli(entry: string): { bin: string, bundled: string } {
|
|
8
|
+
const project = dirname(entry)
|
|
9
|
+
for (const [name, from] of [
|
|
10
|
+
['@lincyaw/presmium', project],
|
|
11
|
+
['@lincyaw/cli', project],
|
|
12
|
+
['@lincyaw/cli', dirname(fileURLToPath(import.meta.url))],
|
|
13
|
+
] as const) {
|
|
14
|
+
const bundled = findPackageDir(name, from)
|
|
15
|
+
const bin = findPackageBin(name, 'presmium', join(from, 'package.json'))
|
|
16
|
+
if (bundled && bin) return { bin, bundled }
|
|
17
|
+
}
|
|
18
|
+
throw new Error('@lincyaw/cli is not installed')
|
|
19
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs'
|
|
2
|
+
import { basename } from 'node:path'
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
4
|
+
import { DOCUMENT_ENTRY, fnv1a64 } from '@lincyaw/kernel'
|
|
5
|
+
import type { AnchorString } from '@lincyaw/kernel'
|
|
6
|
+
import { sectionLinks, webPages } from '@lincyaw/web/domain'
|
|
7
|
+
import { findNodeAtLocation, getNodeValue } from 'jsonc-parser'
|
|
8
|
+
import { TextDocument } from 'vscode-languageserver-textdocument'
|
|
9
|
+
import { createConnection, DidChangeWatchedFilesNotification, ProposedFeatures, TextDocuments, TextDocumentSyncKind } from 'vscode-languageserver/node'
|
|
10
|
+
import { entityReference, LS_MESSAGES, nodeAt, readDocument, sectionAtPath, PREVIEW_REQUEST, SECTION_REQUEST } from '../domain/index.ts'
|
|
11
|
+
import type { DocumentParams, PositionParams, Preview, SectionLocation } from '../domain/index.ts'
|
|
12
|
+
import { anchorDefinition, anchorHover } from './anchors.ts'
|
|
13
|
+
import type { AnchorRef } from './anchors.ts'
|
|
14
|
+
import { Decks } from './decks.ts'
|
|
15
|
+
import type { Deck } from './decks.ts'
|
|
16
|
+
import { DevServerLauncher } from './dev-server-launcher.ts'
|
|
17
|
+
import { diagnosticsByFile, documentDiagnostics, offsetRange } from './diagnostics.ts'
|
|
18
|
+
|
|
19
|
+
const COMPILE_DELAY = 50
|
|
20
|
+
const fileOf = (uri: string): string | undefined => uri.startsWith('file:') ? fileURLToPath(uri) : undefined
|
|
21
|
+
const canonical = (file: string | undefined): file is string => !!file && basename(file) === DOCUMENT_ENTRY
|
|
22
|
+
function fileText(file: string): string { try { return readFileSync(file, 'utf8') } catch { return '' } }
|
|
23
|
+
|
|
24
|
+
export function startServer(): void {
|
|
25
|
+
const connection = createConnection(ProposedFeatures.all), documents = new TextDocuments(TextDocument)
|
|
26
|
+
const devServers = new DevServerLauncher(line => connection.console.log(line))
|
|
27
|
+
const published = new Map<Deck, Set<string>>(), timers = new Map<Deck, NodeJS.Timeout>()
|
|
28
|
+
const textOf = (file: string) => documents.get(pathToFileURL(file).href)?.getText() ?? fileText(file)
|
|
29
|
+
const publishDiagnostics = (deck: Deck) => {
|
|
30
|
+
const text = textOf(deck.entry), disk = fileText(deck.entry), source = documentDiagnostics(text)
|
|
31
|
+
const findings = !deck.findingsCurrent || deck.sourceFingerprint !== fnv1a64(disk) || source.some(d => d.severity === 1) || text.replace(/^\uFEFF/, '') !== disk.replace(/^\uFEFF/, '') ? [] : deck.findings
|
|
32
|
+
const byFile = diagnosticsByFile(findings, deck.entry, textOf)
|
|
33
|
+
byFile.set(deck.entry, [...source, ...byFile.get(deck.entry) ?? []])
|
|
34
|
+
const files = new Set([...deck.compilation?.sourceFiles ?? [deck.entry], ...byFile.keys()])
|
|
35
|
+
const uris = new Set([...files].map(file => pathToFileURL(file).href))
|
|
36
|
+
for (const file of files) {
|
|
37
|
+
const uri = pathToFileURL(file).href
|
|
38
|
+
void connection.sendDiagnostics({ uri, version: documents.get(uri)?.version, diagnostics: byFile.get(file) ?? [] })
|
|
39
|
+
}
|
|
40
|
+
for (const uri of published.get(deck) ?? []) if (!uris.has(uri)) void connection.sendDiagnostics({ uri, diagnostics: [] })
|
|
41
|
+
published.set(deck, uris)
|
|
42
|
+
}
|
|
43
|
+
const decks = new Decks(publishDiagnostics)
|
|
44
|
+
const changed = (files: string[]) => {
|
|
45
|
+
for (const deck of decks.all().filter(d => files.some(file => d.dependsOn(file)))) {
|
|
46
|
+
deck.invalidate()
|
|
47
|
+
clearTimeout(timers.get(deck))
|
|
48
|
+
timers.set(deck, setTimeout(() => { timers.delete(deck); void deck.compile() }, COMPILE_DELAY))
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
let watchFiles = false
|
|
53
|
+
connection.onInitialize(({ capabilities }) => {
|
|
54
|
+
watchFiles = capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration === true
|
|
55
|
+
return { capabilities: {
|
|
56
|
+
textDocumentSync: { openClose: true, change: TextDocumentSyncKind.Incremental, save: { includeText: false } },
|
|
57
|
+
definitionProvider: true, hoverProvider: true,
|
|
58
|
+
}, serverInfo: { name: 'presmium-language-server' } }
|
|
59
|
+
})
|
|
60
|
+
connection.onInitialized(() => {
|
|
61
|
+
if (watchFiles) void connection.client.register(DidChangeWatchedFilesNotification.type, { watchers: [{ globPattern: '**/*' }] })
|
|
62
|
+
})
|
|
63
|
+
documents.onDidOpen(({ document }) => {
|
|
64
|
+
const file = fileOf(document.uri)
|
|
65
|
+
if (!canonical(file)) return
|
|
66
|
+
void connection.sendDiagnostics({ uri: document.uri, version: document.version, diagnostics: documentDiagnostics(document.getText()) })
|
|
67
|
+
void decks.findByFile(file)
|
|
68
|
+
})
|
|
69
|
+
documents.onDidChangeContent(({ document }) => {
|
|
70
|
+
if (canonical(fileOf(document.uri))) void connection.sendDiagnostics({ uri: document.uri, version: document.version, diagnostics: documentDiagnostics(document.getText()) })
|
|
71
|
+
})
|
|
72
|
+
documents.onDidSave(({ document }) => { const file = fileOf(document.uri); if (canonical(file)) changed([file]) })
|
|
73
|
+
documents.onDidClose(({ document }) => { const deck = decks.all().find(deck => pathToFileURL(deck.entry).href === document.uri); if (deck) publishDiagnostics(deck) })
|
|
74
|
+
connection.onDidChangeWatchedFiles(({ changes }) => changed(changes.flatMap(change => fileOf(change.uri) ?? [])))
|
|
75
|
+
|
|
76
|
+
const sourceAt = (uri: string, position: { line: number, character: number }) => {
|
|
77
|
+
const file = fileOf(uri)
|
|
78
|
+
if (!canonical(file)) return undefined
|
|
79
|
+
const document = documents.get(uri) ?? TextDocument.create(uri, 'json', 0, fileText(file))
|
|
80
|
+
const source = readDocument(document.getText())
|
|
81
|
+
const found = source.tree && source.document ? nodeAt(source.tree, document.offsetAt(position)) : undefined
|
|
82
|
+
return found && source.document ? { ...found, document, file, tree: source.tree!, content: source.document } : undefined
|
|
83
|
+
}
|
|
84
|
+
const anchorOf = async (uri: string, position: { line: number, character: number }) => {
|
|
85
|
+
const found = sourceAt(uri, position)
|
|
86
|
+
if (!found || found.path[0] !== 'blocks' || found.path.at(-1) !== 'anchor' || found.path.at(-2) !== 'origin' || found.node.type !== 'string') return undefined
|
|
87
|
+
const block = found.content.blocks[String(found.path[1])]
|
|
88
|
+
if (block?.type !== 'code') return undefined
|
|
89
|
+
const deck = await decks.findByFile(found.file)
|
|
90
|
+
if (!deck?.compilation) return undefined
|
|
91
|
+
const origin = findNodeAtLocation(found.tree, found.path.slice(0, -1)), pin = origin && getNodeValue(origin)?.pin
|
|
92
|
+
const ref: AnchorRef = { anchor: found.node.value as AnchorString, blockId: block.id, range: offsetRange(found.document, found.node.offset + 1, found.node.length - 2), ...typeof pin === 'string' ? { pin } : {} }
|
|
93
|
+
return { compilation: deck.compilation, ref, t: LS_MESSAGES[found.content.metadata.lang === 'en' ? 'en' : 'zh-CN'] }
|
|
94
|
+
}
|
|
95
|
+
connection.onDefinition(async ({ textDocument, position }) => {
|
|
96
|
+
const anchor = await anchorOf(textDocument.uri, position)
|
|
97
|
+
if (anchor) return anchorDefinition(anchor.compilation, anchor.ref)
|
|
98
|
+
const found = sourceAt(textDocument.uri, position)
|
|
99
|
+
const target = found && entityReference(found.content, found.path, found.node.value)
|
|
100
|
+
const node = target && found ? findNodeAtLocation(found.tree, target) : undefined
|
|
101
|
+
return node && found ? [{ uri: textDocument.uri, range: offsetRange(found.document, node.offset, node.length) }] : null
|
|
102
|
+
})
|
|
103
|
+
connection.onHover(async ({ textDocument, position }) => {
|
|
104
|
+
const found = await anchorOf(textDocument.uri, position)
|
|
105
|
+
return found ? anchorHover(found.compilation, found.ref, found.t) : null
|
|
106
|
+
})
|
|
107
|
+
connection.onRequest(SECTION_REQUEST, async ({ textDocument, position }: PositionParams): Promise<SectionLocation | null> => {
|
|
108
|
+
const found = sourceAt(textDocument.uri, position)
|
|
109
|
+
const id = found && sectionAtPath(found.content, found.path)
|
|
110
|
+
const section = id && found?.content.sections[id]
|
|
111
|
+
if (!found || !id || !section) return null
|
|
112
|
+
const deck = await decks.findByFile(found.file)
|
|
113
|
+
const link = deck?.compilation ? sectionLinks(webPages(deck.compilation.doc))[id] ?? '/' : '/'
|
|
114
|
+
return { entry: found.file, id, index: found.content.sectionOrder.indexOf(id) + 1, title: section.title, link }
|
|
115
|
+
})
|
|
116
|
+
connection.onRequest(PREVIEW_REQUEST, async ({ textDocument }: DocumentParams): Promise<Preview> => {
|
|
117
|
+
const file = fileOf(textDocument.uri), deck = canonical(file) ? await decks.findByFile(file) : undefined
|
|
118
|
+
if (!deck) throw new Error(`Preview requires a canonical ${DOCUMENT_ENTRY} document.`)
|
|
119
|
+
return { entry: deck.entry, url: await devServers.urlOf(deck.entry) }
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
connection.onShutdown(() => { for (const timer of timers.values()) clearTimeout(timer); timers.clear(); return devServers.close() })
|
|
123
|
+
process.once('exit', () => void devServers.close())
|
|
124
|
+
documents.listen(connection)
|
|
125
|
+
connection.listen()
|
|
126
|
+
}
|