@lincyaw/cli 0.0.0-stage → 1.0.0-rc.0
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 +51 -2
- package/bin/presmium.mjs +12 -0
- package/package.json +41 -3
- package/src/check.ts +85 -0
- package/src/cli.ts +426 -0
- package/src/fake-model.ts +101 -0
- package/src/host.ts +30 -0
- package/src/index.ts +3 -0
- package/src/testing.ts +26 -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,52 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @lincyaw/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The `presmium` command: `new`, `check`, `ir`, `build`, `dev` and `serve` for Presmium documents and workspaces.
|
|
4
|
+
|
|
5
|
+
Part of [Presmium](https://github.com/Lincyaw/presmium), which turns lectures written in MyST Markdown into web pages, slides, Jupyter notebooks and narrated lectures.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Most people install the `presmium` package, which brings this command with the renderers and the official plugins:
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
pnpm add -g presmium
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
In a project that picks its own renderers and plugins, install the CLI with them (Node.js 22.19 or later):
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
pnpm add -D @lincyaw/cli @lincyaw/web @lincyaw/render-slides @lincyaw/render-notebook @lincyaw/slidev-addon-core
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Commands
|
|
22
|
+
|
|
23
|
+
| Command | What it does |
|
|
24
|
+
|---|---|
|
|
25
|
+
| `presmium check [deck]` | Compile and run the checks and publication checks (`--json`, `--update-lock`, `--env`, `--audience`, `--external-links`) |
|
|
26
|
+
| `presmium ir [deck]` | Print the IR as JSON (`--out`) |
|
|
27
|
+
| `presmium build [deck]` | Build `dist/ir.json` and `dist/<renderer>/` (`--to`, `--out`, `--audience`); at a workspace root, the workspace site in `dist/web/` |
|
|
28
|
+
| `presmium dev [deck]` | Dev servers that update on save (`--to`, `--out`, `--server-port`, `--allow`) |
|
|
29
|
+
| `presmium new [dir]` | A new lecture, workspace or plugin project (`--type`, `--title`, `--name`, `--no-git`); from `create-presmium`, which the `presmium` package brings |
|
|
30
|
+
| `presmium serve [dir]` | The workspace service, on this machine: the documents and their sites, compiled on demand (`--port`, `--host`, `--operator-dir`, `--preview-origin`) |
|
|
31
|
+
| `presmium studio [dir]` | The workbench (experimental), from `@lincyaw/studio` installed in the project (`--port`, `--host`); installed globally, it is `presmium-studio` |
|
|
32
|
+
|
|
33
|
+
`[deck]` is a directory with `lecture.md` or an entry file, by default the current directory. Exit codes: 0 no errors, 1 error findings, 2 usage or internal error. `presmium --help` lists every option.
|
|
34
|
+
|
|
35
|
+
## Testing plugins
|
|
36
|
+
|
|
37
|
+
`@lincyaw/cli/testing` runs the real command in a child process, for integration tests:
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
import { presmium } from '@lincyaw/cli/testing'
|
|
41
|
+
|
|
42
|
+
const { code, stdout } = await presmium(dir, ['build', '--to', 'web'])
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Documentation
|
|
46
|
+
|
|
47
|
+
- [Author guide](https://github.com/Lincyaw/presmium/blob/main/site/guide/lecture.en.md)
|
|
48
|
+
- [Plugin guide](https://github.com/Lincyaw/presmium/blob/main/site/plugins/lecture.en.md)
|
|
49
|
+
|
|
50
|
+
## License
|
|
51
|
+
|
|
52
|
+
Apache-2.0
|
package/bin/presmium.mjs
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createJiti } from 'jiti'
|
|
3
|
+
|
|
4
|
+
const emitWarning = process.emitWarning
|
|
5
|
+
process.emitWarning = (warning, ...args) => {
|
|
6
|
+
const code = typeof args[0] === 'object' ? args[0]?.code : args[1]
|
|
7
|
+
if (code !== 'DEP0040') emitWarning.call(process, warning, ...args)
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const jiti = createJiti(import.meta.url)
|
|
11
|
+
const { main } = await jiti.import('../src/cli.ts')
|
|
12
|
+
process.exitCode = await main(process.argv.slice(2))
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lincyaw/cli",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0-rc.0",
|
|
4
|
+
"description": "The presmium command: build, dev, ir, check and serve for Presmium documents",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/Lincyaw/presmium.git",
|
|
9
|
+
"directory": "packages/cli"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/Lincyaw/presmium/tree/main/packages/cli#readme",
|
|
12
|
+
"bugs": "https://github.com/Lincyaw/presmium/issues",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"presmium",
|
|
15
|
+
"cli",
|
|
16
|
+
"myst",
|
|
17
|
+
"slides"
|
|
18
|
+
],
|
|
19
|
+
"type": "module",
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=22.19"
|
|
22
|
+
},
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"bin": {
|
|
27
|
+
"presmium": "./bin/presmium.mjs"
|
|
28
|
+
},
|
|
29
|
+
"exports": {
|
|
30
|
+
".": "./src/index.ts",
|
|
31
|
+
"./testing": "./src/testing.ts"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"bin",
|
|
35
|
+
"src"
|
|
36
|
+
],
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"jiti": "^2.7.0",
|
|
39
|
+
"@lincyaw/kernel": "1.0.0-rc.0",
|
|
40
|
+
"@lincyaw/workspace": "1.0.0-rc.0",
|
|
41
|
+
"@lincyaw/server": "1.0.0-rc.0",
|
|
42
|
+
"@lincyaw/compiler": "1.0.0-rc.0"
|
|
43
|
+
}
|
|
6
44
|
}
|
package/src/check.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { dirname, join } from 'node:path'
|
|
3
|
+
import { ANCHOR_LOCK_PATH, errorMessage } from '@lincyaw/kernel'
|
|
4
|
+
import type { AnchorString, Finding } from '@lincyaw/kernel'
|
|
5
|
+
import { checkContext, Compiler, frontmatterLine, sortFindings } from '@lincyaw/compiler'
|
|
6
|
+
import type { Compilation, CompilerOptions } from '@lincyaw/compiler'
|
|
7
|
+
|
|
8
|
+
export interface CheckOptions {
|
|
9
|
+
deck: string
|
|
10
|
+
updateLock?: boolean
|
|
11
|
+
compiler?: CompilerOptions
|
|
12
|
+
environments?: boolean
|
|
13
|
+
externalLinks?: boolean
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface LockUpdate {
|
|
17
|
+
file: string
|
|
18
|
+
anchors: number
|
|
19
|
+
changed: boolean
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface CheckResult {
|
|
23
|
+
entry: string
|
|
24
|
+
findings: Finding[]
|
|
25
|
+
lock?: LockUpdate
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function runCheck(options: CheckOptions): Promise<CheckResult> {
|
|
29
|
+
const compiler = new Compiler(options.deck, options.compiler)
|
|
30
|
+
let compilation = await compiler.compile()
|
|
31
|
+
const entryText = await readFile(compilation.entry, 'utf8')
|
|
32
|
+
const findings: Finding[] = []
|
|
33
|
+
const fail = (message: string, line: number) =>
|
|
34
|
+
findings.push({ checkId: 'presmium.plugins', severity: 'error', message, source: { file: compilation.entry, line } })
|
|
35
|
+
|
|
36
|
+
let lock: LockUpdate | undefined
|
|
37
|
+
if (options.updateLock) {
|
|
38
|
+
lock = await updateLock(compilation, (name, error) => fail(`plugin "${name}" failed to list anchors: ${errorMessage(error)}`, frontmatterLine(entryText, name)))
|
|
39
|
+
compilation = await compiler.compile()
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
findings.push(...await compilation.check({ externalLinks: options.externalLinks }))
|
|
43
|
+
if (options.environments) findings.push(...await probeEnvironments(compilation, entryText))
|
|
44
|
+
const all = [...compilation.doc.diagnostics, ...findings].map(f => f.source ? f : { ...f, source: { file: compilation.entry, line: 1 } })
|
|
45
|
+
return { entry: compilation.entry, findings: sortFindings(all), lock }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function probeEnvironments(compilation: Compilation, text: string): Promise<Finding[]> {
|
|
49
|
+
const findings: Finding[] = []
|
|
50
|
+
for (const { name, spec, provider, context } of compilation.environments) {
|
|
51
|
+
let reason: string | undefined
|
|
52
|
+
try {
|
|
53
|
+
reason = await provider.probe?.(name, spec, context)
|
|
54
|
+
} catch (error) {
|
|
55
|
+
reason = errorMessage(error)
|
|
56
|
+
}
|
|
57
|
+
if (reason) findings.push({ checkId: 'presmium.execute', severity: 'error', message: `environment "${name}" (${spec.kind}) is not reachable: ${reason}`, source: { file: compilation.entry, line: frontmatterLine(text, `${name}:`) } })
|
|
58
|
+
}
|
|
59
|
+
return findings
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function updateLock(compilation: Compilation, onError: (plugin: string, error: unknown) => void): Promise<LockUpdate> {
|
|
63
|
+
const file = join(compilation.deckDir, ANCHOR_LOCK_PATH)
|
|
64
|
+
const before = await readFile(file, 'utf8').catch(() => undefined)
|
|
65
|
+
const ctx = checkContext(compilation)
|
|
66
|
+
const anchors = new Set<AnchorString>()
|
|
67
|
+
let complete = true
|
|
68
|
+
for (const { name, plugin } of compilation.plugins) {
|
|
69
|
+
try {
|
|
70
|
+
for (const anchor of await plugin?.anchors?.(ctx) ?? []) anchors.add(anchor)
|
|
71
|
+
} catch (error) {
|
|
72
|
+
complete = false
|
|
73
|
+
onError(name, error)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const { lock } = compilation
|
|
77
|
+
for (const anchor of [...anchors].sort()) lock.record(anchor, await compilation.resolvers.resolve(anchor, ctx.src, lock.get(anchor)))
|
|
78
|
+
if (complete) lock.retain(anchors)
|
|
79
|
+
const text = lock.serialize()
|
|
80
|
+
if (text !== before) {
|
|
81
|
+
await mkdir(dirname(file), { recursive: true })
|
|
82
|
+
await writeFile(file, text)
|
|
83
|
+
}
|
|
84
|
+
return { file, anchors: lock.size, changed: text !== before }
|
|
85
|
+
}
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
import { existsSync, statSync } from 'node:fs'
|
|
2
|
+
import { mkdir, writeFile } from 'node:fs/promises'
|
|
3
|
+
import { createRequire } from 'node:module'
|
|
4
|
+
import { dirname, join, relative, resolve } from 'node:path'
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
6
|
+
import { parseArgs } from 'node:util'
|
|
7
|
+
import { createJiti } from 'jiti'
|
|
8
|
+
import { errorMessage } from '@lincyaw/kernel'
|
|
9
|
+
import type { ApprovalKind, Finding, Severity } from '@lincyaw/kernel'
|
|
10
|
+
import { build, Compiler, dev, resolveEntry } from '@lincyaw/compiler'
|
|
11
|
+
import type { BuildReport, Compilation, RunStats } from '@lincyaw/compiler'
|
|
12
|
+
import { anyAddress, isLoopback, networkAddresses, servedDocument, startServer } from '@lincyaw/server'
|
|
13
|
+
import type { ApprovalPolicy } from '@lincyaw/server'
|
|
14
|
+
import { buildWorkspace, isWorkspaceRoot, serveWorkspace } from '@lincyaw/workspace'
|
|
15
|
+
import type { WorkspaceBuild } from '@lincyaw/workspace'
|
|
16
|
+
import { runCheck } from './check.ts'
|
|
17
|
+
import type { CheckResult } from './check.ts'
|
|
18
|
+
import { devHost } from './host.ts'
|
|
19
|
+
|
|
20
|
+
export const BUNDLED = fileURLToPath(new URL('..', import.meta.url))
|
|
21
|
+
|
|
22
|
+
export interface MainOptions {
|
|
23
|
+
bundled?: string
|
|
24
|
+
bin?: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
let bundled = BUNDLED
|
|
28
|
+
let presmiumBin = fileURLToPath(new URL('../bin/presmium.mjs', import.meta.url))
|
|
29
|
+
|
|
30
|
+
const USAGE = `Usage: presmium <command> [deck] [options]
|
|
31
|
+
|
|
32
|
+
The deck is a directory holding lecture.md, or an entry file (default: .).
|
|
33
|
+
|
|
34
|
+
Commands:
|
|
35
|
+
new a new project in the directory (default: asks), from create-presmium
|
|
36
|
+
--type <kind> lecture, workspace or plugin (default: asks)
|
|
37
|
+
--title <text> the lecture's or the workspace's title
|
|
38
|
+
--name <name> the plugin's package name
|
|
39
|
+
--no-git do not run git init
|
|
40
|
+
build compile and render; writes <out>/ir.json and <out>/<renderer>/; at a workspace root
|
|
41
|
+
(presmium.workspace.yaml) builds the workspace site into <out>/web/
|
|
42
|
+
--to <ids> renderers to run, comma-separated (default: the deck's renderers)
|
|
43
|
+
--out <dir> output directory (default: <deck>/dist)
|
|
44
|
+
--audience <name> only the content for this audience (e.g. student); then every file
|
|
45
|
+
written is scanned for the sentences of the content left out
|
|
46
|
+
dev compile, start the Presmium server and the renderers' dev servers, recompile on save
|
|
47
|
+
--to <ids> renderers to run, comma-separated
|
|
48
|
+
--out <dir> working directory (default: <deck>/.presmium/dev)
|
|
49
|
+
--server-port <n> port of the Presmium server (default: a free port)
|
|
50
|
+
--allow <kinds> approvals given without asking: operate, spend, write, agent
|
|
51
|
+
ir print the IR as JSON
|
|
52
|
+
--out <file> write it to a file instead
|
|
53
|
+
check compile and run the plugins' checks
|
|
54
|
+
--json print the result as JSON
|
|
55
|
+
--update-lock re-resolve anchors and rewrite .presmium/anchors.lock.json
|
|
56
|
+
--env also connect to the environments of execute.environments
|
|
57
|
+
--audience <name> check the deck as compiled for this audience
|
|
58
|
+
--external-links also check the external links, with lychee when it is installed
|
|
59
|
+
serve the workspace service for you on this machine (the argument is the workspace root, or
|
|
60
|
+
a deck): the workspace site, the documents and their history, the reviews, the plugins'
|
|
61
|
+
routes, the classroom sync; without --host it listens on this machine only
|
|
62
|
+
--port <n> port (default: 4310)
|
|
63
|
+
--host <addr> address to listen on (default: 127.0.0.1); 0.0.0.0 or an address on the
|
|
64
|
+
local network opens it to your other devices there, with no login:
|
|
65
|
+
whoever reaches the port works as you
|
|
66
|
+
--operator-dir <dir> the operator directory (default: the user's state directory)
|
|
67
|
+
--preview-origin <origin> (repeatable) the origin of a workbench whose pages embed the
|
|
68
|
+
previews, e.g. http://127.0.0.1:4320; with PRESMIUM_SERVICE_TOKEN set, the
|
|
69
|
+
workspace's routes ask for it (Authorization: Bearer)
|
|
70
|
+
studio the workbench (experimental): DeepSeek Harness with Presmium's bundle and the workspace
|
|
71
|
+
service of the directory (the workspace root, or a deck); prints the one address to open.
|
|
72
|
+
It is the package @lincyaw/studio (with DeepSeek Harness, about 865 MB), installed beside
|
|
73
|
+
this one
|
|
74
|
+
--port <n> the workbench's port (default: 4320, or a free one when that is in use)
|
|
75
|
+
--host <addr> listen on this address of the machine on the local network instead of
|
|
76
|
+
127.0.0.1, with no login: whoever reaches the port works as you
|
|
77
|
+
|
|
78
|
+
-h, --help show this help
|
|
79
|
+
|
|
80
|
+
Exit codes: 0 no errors, 1 error findings, 2 usage or internal error.`
|
|
81
|
+
|
|
82
|
+
const OPTIONS = {
|
|
83
|
+
'build': ['to', 'out', 'audience'],
|
|
84
|
+
'dev': ['to', 'out', 'server-port', 'allow'],
|
|
85
|
+
'ir': ['out'],
|
|
86
|
+
'check': ['json', 'update-lock', 'env', 'audience', 'external-links'],
|
|
87
|
+
'serve': ['port', 'host', 'operator-dir', 'preview-origin'],
|
|
88
|
+
} as const
|
|
89
|
+
|
|
90
|
+
type Name = keyof typeof OPTIONS
|
|
91
|
+
|
|
92
|
+
const KINDS: readonly ApprovalKind[] = ['operate', 'spend', 'write', 'agent']
|
|
93
|
+
|
|
94
|
+
interface Command {
|
|
95
|
+
name: Name
|
|
96
|
+
entry: string
|
|
97
|
+
workspace?: string
|
|
98
|
+
to?: string[]
|
|
99
|
+
out?: string
|
|
100
|
+
json: boolean
|
|
101
|
+
updateLock: boolean
|
|
102
|
+
env: boolean
|
|
103
|
+
audience?: string
|
|
104
|
+
externalLinks: boolean
|
|
105
|
+
serverPort?: number
|
|
106
|
+
allow: ApprovalKind[]
|
|
107
|
+
operatorDir?: string
|
|
108
|
+
port?: number
|
|
109
|
+
host?: string
|
|
110
|
+
previewOrigins: string[]
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export async function main(argv: string[], options: MainOptions = {}): Promise<number> {
|
|
114
|
+
bundled = options.bundled ?? BUNDLED
|
|
115
|
+
if (options.bin) presmiumBin = options.bin
|
|
116
|
+
if (argv[0] === 'new') return create(argv.slice(1))
|
|
117
|
+
if (argv[0] === 'studio') return studio(argv.slice(1))
|
|
118
|
+
let command: Command | 'help'
|
|
119
|
+
try {
|
|
120
|
+
command = parseCommand(argv)
|
|
121
|
+
} catch (error) {
|
|
122
|
+
process.stderr.write(`presmium: ${errorMessage(error)}\n\n${USAGE}\n`)
|
|
123
|
+
return 2
|
|
124
|
+
}
|
|
125
|
+
if (command === 'help') {
|
|
126
|
+
process.stdout.write(`${USAGE}\n`)
|
|
127
|
+
return 0
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
switch (command.name) {
|
|
131
|
+
case 'check': return await check(command)
|
|
132
|
+
case 'ir': return await ir(command)
|
|
133
|
+
case 'build': return await buildDeck(command)
|
|
134
|
+
case 'dev': return await devDeck(command)
|
|
135
|
+
case 'serve': return await serve(command)
|
|
136
|
+
}
|
|
137
|
+
} catch (error) {
|
|
138
|
+
process.stderr.write(`presmium: ${errorMessage(error)}\n`)
|
|
139
|
+
return 2
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function parseCommand(argv: string[]): Command | 'help' {
|
|
144
|
+
const { values, positionals } = parseArgs({
|
|
145
|
+
args: argv,
|
|
146
|
+
allowPositionals: true,
|
|
147
|
+
options: {
|
|
148
|
+
'to': { type: 'string' },
|
|
149
|
+
'out': { type: 'string' },
|
|
150
|
+
'json': { type: 'boolean', default: false },
|
|
151
|
+
'update-lock': { type: 'boolean', default: false },
|
|
152
|
+
'env': { type: 'boolean', default: false },
|
|
153
|
+
'audience': { type: 'string' },
|
|
154
|
+
'external-links': { type: 'boolean', default: false },
|
|
155
|
+
'server-port': { type: 'string' },
|
|
156
|
+
'allow': { type: 'string' },
|
|
157
|
+
'operator-dir': { type: 'string' },
|
|
158
|
+
'port': { type: 'string' },
|
|
159
|
+
'host': { type: 'string' },
|
|
160
|
+
'preview-origin': { type: 'string', multiple: true },
|
|
161
|
+
'help': { type: 'boolean', short: 'h', default: false },
|
|
162
|
+
},
|
|
163
|
+
})
|
|
164
|
+
if (values.help) return 'help'
|
|
165
|
+
const [name, deck = '.', ...extra] = positionals
|
|
166
|
+
if (!name) throw new Error('missing command')
|
|
167
|
+
if (!(name in OPTIONS)) throw new Error(`unknown command "${name}"`)
|
|
168
|
+
const allowed: readonly string[] = OPTIONS[name as Name]
|
|
169
|
+
const given = Object.entries(values).filter(([key, value]) => key !== 'help' && value !== undefined && value !== false)
|
|
170
|
+
const wrong = given.find(([key]) => !allowed.includes(key))
|
|
171
|
+
if (wrong) throw new Error(`option --${wrong[0]} does not apply to ${name}`)
|
|
172
|
+
if (extra.length > 0) throw new Error(`unexpected argument "${extra[0]}"`)
|
|
173
|
+
const workspace = name === 'build' && existsSync(deck) && statSync(deck).isDirectory() && isWorkspaceRoot(resolve(deck)) ? resolve(deck) : undefined
|
|
174
|
+
if (workspace && values.to) throw new Error('--to does not apply to a workspace: its site is the web form')
|
|
175
|
+
if (workspace && values.audience !== undefined) throw new Error('--audience does not apply to a workspace yet: build each document for its audience')
|
|
176
|
+
const audience = values.audience?.trim()
|
|
177
|
+
if (values.audience !== undefined && !/^[\w.-]+$/.test(audience ?? '')) throw new Error(`--audience takes the name of an audience, e.g. student, not "${values.audience}"`)
|
|
178
|
+
const directory = name === 'serve'
|
|
179
|
+
const entry = directory || workspace ? resolve(deck) : resolveEntry(deck)
|
|
180
|
+
if (!existsSync(entry) || (directory && !statSync(entry).isDirectory())) throw new Error(`${entry} not found`)
|
|
181
|
+
const to = values.to?.split(',').map(id => id.trim()).filter(Boolean)
|
|
182
|
+
if (to?.length === 0) throw new Error('--to needs at least one renderer id')
|
|
183
|
+
const allow = values.allow?.split(',').map(kind => kind.trim()).filter(Boolean) ?? []
|
|
184
|
+
const unknown = allow.find(kind => !(KINDS as string[]).includes(kind))
|
|
185
|
+
if (unknown) throw new Error(`--allow takes ${KINDS.join(', ')}, not "${unknown}"`)
|
|
186
|
+
const previewOrigins = values['preview-origin'] ?? []
|
|
187
|
+
const notOrigin = previewOrigins.find(origin => !isOrigin(origin))
|
|
188
|
+
if (notOrigin !== undefined) throw new Error(`--preview-origin takes an origin such as http://127.0.0.1:4320, not "${notOrigin}"`)
|
|
189
|
+
return {
|
|
190
|
+
name: name as Name,
|
|
191
|
+
entry,
|
|
192
|
+
...workspace ? { workspace } : {},
|
|
193
|
+
to,
|
|
194
|
+
out: values.out,
|
|
195
|
+
json: values.json,
|
|
196
|
+
updateLock: values['update-lock'],
|
|
197
|
+
env: values.env,
|
|
198
|
+
...audience ? { audience } : {},
|
|
199
|
+
externalLinks: values['external-links'],
|
|
200
|
+
serverPort: port(values['server-port'], '--server-port'),
|
|
201
|
+
allow: allow as ApprovalKind[],
|
|
202
|
+
operatorDir: values['operator-dir'],
|
|
203
|
+
port: port(values.port, '--port'),
|
|
204
|
+
host: values.host,
|
|
205
|
+
previewOrigins,
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function isOrigin(value: string): boolean {
|
|
210
|
+
try {
|
|
211
|
+
const url = new URL(value)
|
|
212
|
+
return /^https?:$/.test(url.protocol) && url.origin === value
|
|
213
|
+
} catch {
|
|
214
|
+
return false
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function port(value: string | undefined, option: string): number | undefined {
|
|
219
|
+
if (value === undefined) return undefined
|
|
220
|
+
const n = Number(value)
|
|
221
|
+
if (!Number.isInteger(n) || n < 0 || n > 65535) throw new Error(`${option} takes a port number, not "${value}"`)
|
|
222
|
+
return n
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
async function check(command: Command): Promise<number> {
|
|
226
|
+
const result = await runCheck({
|
|
227
|
+
deck: command.entry,
|
|
228
|
+
updateLock: command.updateLock,
|
|
229
|
+
environments: command.env,
|
|
230
|
+
externalLinks: command.externalLinks,
|
|
231
|
+
compiler: { bundled, ...command.audience ? { audience: command.audience } : {} },
|
|
232
|
+
})
|
|
233
|
+
process.stdout.write(command.json ? `${JSON.stringify(checkJson(result), null, 2)}\n` : checkText(result))
|
|
234
|
+
return exitCode(result.findings)
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
async function ir(command: Command): Promise<number> {
|
|
238
|
+
const { doc } = await new Compiler(command.entry, { bundled }).compile()
|
|
239
|
+
const json = `${JSON.stringify(doc, null, 2)}\n`
|
|
240
|
+
if (command.out) {
|
|
241
|
+
const file = resolve(command.out)
|
|
242
|
+
await mkdir(dirname(file), { recursive: true })
|
|
243
|
+
await writeFile(file, json)
|
|
244
|
+
} else {
|
|
245
|
+
process.stdout.write(json)
|
|
246
|
+
}
|
|
247
|
+
process.stderr.write(findingLines(doc.diagnostics).join('\n') + (doc.diagnostics.length ? '\n' : ''))
|
|
248
|
+
return exitCode(doc.diagnostics)
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async function buildDeck(command: Command): Promise<number> {
|
|
252
|
+
if (command.workspace) {
|
|
253
|
+
const report = await buildWorkspace(command.workspace, { outDir: command.out, bundled })
|
|
254
|
+
process.stdout.write(workspaceText(report))
|
|
255
|
+
return exitCode(report.findings)
|
|
256
|
+
}
|
|
257
|
+
const compilation = await new Compiler(command.entry, { bundled, ...command.audience ? { audience: command.audience } : {} }).compile({ pruneCache: true })
|
|
258
|
+
const outDir = resolve(command.out ?? join(compilation.deckDir, 'dist'))
|
|
259
|
+
const report = await build(compilation, { outDir, to: command.to })
|
|
260
|
+
process.stdout.write(buildText(report, compilation.runs, compilation.audience?.name))
|
|
261
|
+
return exitCode(report.findings)
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async function devDeck(command: Command): Promise<number> {
|
|
265
|
+
let latest: Compilation | undefined
|
|
266
|
+
const deckDir = dirname(command.entry)
|
|
267
|
+
const approvals: Partial<Record<ApprovalKind, ApprovalPolicy>> = Object.fromEntries(command.allow.map(kind => [kind, 'allow']))
|
|
268
|
+
const host = devHost(() => latest)
|
|
269
|
+
const server = await startServer({
|
|
270
|
+
mode: 'dev',
|
|
271
|
+
port: command.serverPort,
|
|
272
|
+
approvals,
|
|
273
|
+
serverHost: host,
|
|
274
|
+
document: async dir => (dir === '' && latest ? servedDocument(latest) : undefined),
|
|
275
|
+
stateFile: join(deckDir, '.presmium', 'server.json'),
|
|
276
|
+
})
|
|
277
|
+
const compiler = new Compiler(command.entry, { bundled, services: server.services })
|
|
278
|
+
const outDir = resolve(command.out ?? join(compiler.deckDir, '.presmium', 'dev'))
|
|
279
|
+
await mkdir(outDir, { recursive: true })
|
|
280
|
+
await writeFile(join(outDir, '.gitignore'), '*\n')
|
|
281
|
+
let session
|
|
282
|
+
try {
|
|
283
|
+
session = await dev(compiler, {
|
|
284
|
+
outDir,
|
|
285
|
+
to: command.to,
|
|
286
|
+
server: { url: server.url },
|
|
287
|
+
onCompile(compilation, findings) {
|
|
288
|
+
latest = compilation
|
|
289
|
+
const lines = findingLines(findings)
|
|
290
|
+
lines.push(`compiled ${compilation.doc.sections.length} sections; ${summary(findings)}`)
|
|
291
|
+
process.stdout.write(`${lines.join('\n')}\n`)
|
|
292
|
+
},
|
|
293
|
+
})
|
|
294
|
+
} catch (error) {
|
|
295
|
+
await server.close()
|
|
296
|
+
throw error
|
|
297
|
+
}
|
|
298
|
+
for (const { renderer, url } of session.servers) process.stdout.write(`${renderer} ${url}\n`)
|
|
299
|
+
process.stdout.write(`server ${server.url}\nmcp ${server.url}/mcp (its token is in ${relative(process.cwd(), join(deckDir, '.presmium', 'server.json'))})\n`)
|
|
300
|
+
process.stdout.write(`watching; IR in ${relative(process.cwd(), session.ir)}\n`)
|
|
301
|
+
await new Promise<void>((done) => {
|
|
302
|
+
process.once('SIGINT', done)
|
|
303
|
+
process.once('SIGTERM', done)
|
|
304
|
+
})
|
|
305
|
+
await session.close()
|
|
306
|
+
await server.close()
|
|
307
|
+
return 0
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async function serve(command: Command): Promise<number> {
|
|
311
|
+
const started = await serveWorkspace({
|
|
312
|
+
dir: command.entry,
|
|
313
|
+
host: command.host,
|
|
314
|
+
port: command.port,
|
|
315
|
+
...command.operatorDir ? { operatorDir: resolve(command.operatorDir) } : {},
|
|
316
|
+
bundled,
|
|
317
|
+
check: compilation => compilation.check(),
|
|
318
|
+
previewOrigins: command.previewOrigins,
|
|
319
|
+
})
|
|
320
|
+
process.stdout.write(`serve ${started.url}\n${networkLines(command.host, started.url)}workspace ${started.root}\nmcp ${started.mcp.url} (its token is in ${started.mcp.stateFile})\n`)
|
|
321
|
+
if (command.host && !isLoopback(command.host)) {
|
|
322
|
+
process.stderr.write(`presmium serve: listening on ${command.host}, on the local network, with no login: anyone who reaches port ${new URL(started.url).port} uses this workspace as you (edits, runs code, approves). Use it on a network you trust; without --host it listens on this machine only.\n`)
|
|
323
|
+
}
|
|
324
|
+
await new Promise<void>((done) => {
|
|
325
|
+
process.once('SIGINT', done)
|
|
326
|
+
process.once('SIGTERM', done)
|
|
327
|
+
})
|
|
328
|
+
await started.close()
|
|
329
|
+
return 0
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function installed(name: string): string | undefined {
|
|
333
|
+
for (const from of [pathToFileURL(join(bundled, 'package.json')).href, import.meta.url, pathToFileURL(join(process.cwd(), 'package.json')).href]) {
|
|
334
|
+
try {
|
|
335
|
+
return createRequire(from).resolve(name)
|
|
336
|
+
} catch {
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
return undefined
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
async function create(argv: string[]): Promise<number> {
|
|
343
|
+
const entry = installed('create-presmium')
|
|
344
|
+
if (!entry) {
|
|
345
|
+
process.stderr.write('presmium new: create-presmium is not installed; it comes with the presmium package: pnpm add -g presmium\n')
|
|
346
|
+
return 2
|
|
347
|
+
}
|
|
348
|
+
const { main: createMain } = await createJiti(import.meta.url).import<{ main(argv: string[]): Promise<number> }>(entry)
|
|
349
|
+
return createMain(argv)
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
async function studio(argv: string[]): Promise<number> {
|
|
353
|
+
const entry = installed('@lincyaw/studio')
|
|
354
|
+
if (!entry) {
|
|
355
|
+
process.stderr.write('presmium studio: the workbench is not installed here. It is the package @lincyaw/studio (experimental; with DeepSeek Harness, about 865 MB): pnpm add -g @lincyaw/studio, then run presmium-studio; or pnpm add -D @lincyaw/studio in this project.\n')
|
|
356
|
+
return 2
|
|
357
|
+
}
|
|
358
|
+
const { main: studioMain } = await createJiti(import.meta.url).import<{ main(argv: string[], options: { presmium: string }): Promise<number> }>(entry)
|
|
359
|
+
return studioMain(argv, { presmium: presmiumBin })
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function networkLines(host: string | undefined, url: string): string {
|
|
363
|
+
if (!host || isLoopback(host)) return ''
|
|
364
|
+
const { port } = new URL(url)
|
|
365
|
+
const addresses = anyAddress(host) ? networkAddresses() : [host.includes(':') && !host.startsWith('[') ? `[${host}]` : host]
|
|
366
|
+
return addresses.map(address => `network http://${address}:${port}/\n`).join('')
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function exitCode(findings: Finding[]): number {
|
|
370
|
+
return findings.some(f => f.severity === 'error') ? 1 : 0
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function counts(findings: Finding[]): Record<Severity, number> {
|
|
374
|
+
const result: Record<Severity, number> = { error: 0, warning: 0, info: 0 }
|
|
375
|
+
for (const f of findings) result[f.severity]++
|
|
376
|
+
return result
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function summary(findings: Finding[]): string {
|
|
380
|
+
const n = counts(findings)
|
|
381
|
+
return findings.length === 0 ? 'no problems' : `${n.error} errors, ${n.warning} warnings, ${n.info} infos`
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function findingLines(findings: Finding[], cwd = process.cwd()): string[] {
|
|
385
|
+
return findings.flatMap((f) => {
|
|
386
|
+
const where = f.source ? `${relative(cwd, f.source.file)}${f.source.line ? `:${f.source.line}` : ''}` : ''
|
|
387
|
+
return [`${where} ${f.severity} ${f.message} (${f.checkId})`, ...f.hint ? [` hint: ${f.hint}`] : []]
|
|
388
|
+
})
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function checkJson(result: CheckResult) {
|
|
392
|
+
return { entry: result.entry, counts: counts(result.findings), findings: result.findings, lock: result.lock }
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function checkText(result: CheckResult, cwd = process.cwd()): string {
|
|
396
|
+
const out = findingLines(result.findings, cwd)
|
|
397
|
+
if (result.lock) {
|
|
398
|
+
const state = result.lock.changed ? 'updated' : 'unchanged'
|
|
399
|
+
out.push(`${relative(cwd, result.lock.file)} ${state} (${result.lock.anchors} anchors)`)
|
|
400
|
+
}
|
|
401
|
+
out.push(summary(result.findings))
|
|
402
|
+
return `${out.join('\n')}\n`
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function workspaceText(report: WorkspaceBuild, cwd = process.cwd()): string {
|
|
406
|
+
const out = findingLines(report.findings, cwd)
|
|
407
|
+
for (const { dir, title, runs } of report.documents) {
|
|
408
|
+
out.push(`document ${dir || '.'} ${title}${runs.executed + runs.cached > 0 ? ` (code runs: ${runs.executed} executed, ${runs.cached} from cache)` : ''}`)
|
|
409
|
+
}
|
|
410
|
+
out.push(`web ${relative(cwd, report.outDir)}`)
|
|
411
|
+
out.push(summary(report.findings))
|
|
412
|
+
return `${out.join('\n')}\n`
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function buildText(report: BuildReport, runs: RunStats, audience?: string, cwd = process.cwd()): string {
|
|
416
|
+
const out = findingLines(report.findings, cwd)
|
|
417
|
+
if (audience) out.push(`audience ${audience}`)
|
|
418
|
+
out.push(`ir ${relative(cwd, report.ir)}`)
|
|
419
|
+
for (const { renderer, outDir, skipped } of report.outputs) {
|
|
420
|
+
out.push(`${renderer} ${relative(cwd, outDir)}${skipped.length ? ` (${skipped.length} blocks not rendered)` : ''}`)
|
|
421
|
+
for (const s of skipped) out.push(` ${s.section}#${s.block}: ${s.reason}`)
|
|
422
|
+
}
|
|
423
|
+
if (runs.executed + runs.cached > 0) out.push(`code runs: ${runs.executed} executed, ${runs.cached} from cache${runs.sandbox && runs.executed > 0 ? `, isolated by ${runs.sandbox}` : ''}`)
|
|
424
|
+
out.push(summary(report.findings))
|
|
425
|
+
return `${out.join('\n')}\n`
|
|
426
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { createServer } from 'node:http'
|
|
2
|
+
import type { IncomingHttpHeaders } from 'node:http'
|
|
3
|
+
import type { AddressInfo } from 'node:net'
|
|
4
|
+
|
|
5
|
+
export type Step = { text: string } | { tool: string, input: Record<string, unknown> }
|
|
6
|
+
|
|
7
|
+
export interface Received {
|
|
8
|
+
path: string
|
|
9
|
+
headers: IncomingHttpHeaders
|
|
10
|
+
body: Record<string, any>
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface FakeModel {
|
|
14
|
+
url: string
|
|
15
|
+
received: Received[]
|
|
16
|
+
hold(): void
|
|
17
|
+
release(): void
|
|
18
|
+
close(): Promise<void>
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const event = (name: string, data: unknown) => `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`
|
|
22
|
+
|
|
23
|
+
function stream(step: Step, n: number): string {
|
|
24
|
+
const start = { type: 'message_start', message: { id: `msg_${n}`, type: 'message', role: 'assistant', model: 'fake-model', content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 10, output_tokens: 0 } } }
|
|
25
|
+
const block = 'text' in step
|
|
26
|
+
? [event('content_block_start', { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }), event('content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: step.text } })]
|
|
27
|
+
: [event('content_block_start', { type: 'content_block_start', index: 0, content_block: { type: 'tool_use', id: `toolu_${n}`, name: step.tool, input: {} } }), event('content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'input_json_delta', partial_json: JSON.stringify(step.input) } })]
|
|
28
|
+
return [
|
|
29
|
+
event('message_start', start),
|
|
30
|
+
...block,
|
|
31
|
+
event('content_block_stop', { type: 'content_block_stop', index: 0 }),
|
|
32
|
+
event('message_delta', { type: 'message_delta', delta: { stop_reason: 'text' in step ? 'end_turn' : 'tool_use', stop_sequence: null }, usage: { output_tokens: 5 } }),
|
|
33
|
+
event('message_stop', { type: 'message_stop' }),
|
|
34
|
+
].join('')
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function fakeModel(script: Step[]): Promise<FakeModel> {
|
|
38
|
+
const received: Received[] = []
|
|
39
|
+
let held: Promise<void> | undefined
|
|
40
|
+
let release = () => {}
|
|
41
|
+
const server = createServer((req, res) => {
|
|
42
|
+
let body = ''
|
|
43
|
+
req.setEncoding('utf8').on('data', (chunk: string) => body += chunk)
|
|
44
|
+
req.on('end', async () => {
|
|
45
|
+
let parsed: Record<string, any> = {}
|
|
46
|
+
try {
|
|
47
|
+
parsed = JSON.parse(body) as Record<string, any>
|
|
48
|
+
} catch {
|
|
49
|
+
}
|
|
50
|
+
const record: Received = { path: req.url ?? '', headers: req.headers, body: parsed }
|
|
51
|
+
received.push(record)
|
|
52
|
+
if (req.method !== 'POST' || !(req.url ?? '').endsWith('/v1/messages')) {
|
|
53
|
+
res.writeHead(404).end()
|
|
54
|
+
return
|
|
55
|
+
}
|
|
56
|
+
await held
|
|
57
|
+
const turn = (r: Received) => r.path.endsWith('/v1/messages') && Array.isArray(r.body.tools) && r.body.tools.length > 0
|
|
58
|
+
const n = received.filter(r => r.path.endsWith('/v1/messages')).length
|
|
59
|
+
const step = turn(record) ? script[received.filter(turn).indexOf(record)] ?? { text: '完毕。' } : { text: 'Presmium' }
|
|
60
|
+
res.writeHead(200, { 'Content-Type': 'text/event-stream' }).end(stream(step, n))
|
|
61
|
+
})
|
|
62
|
+
})
|
|
63
|
+
const port = await new Promise<number>(done => server.listen(0, '127.0.0.1', () => done((server.address() as AddressInfo).port)))
|
|
64
|
+
return {
|
|
65
|
+
url: `http://127.0.0.1:${port}`,
|
|
66
|
+
received,
|
|
67
|
+
hold() {
|
|
68
|
+
held = new Promise(done => release = done)
|
|
69
|
+
},
|
|
70
|
+
release() {
|
|
71
|
+
release()
|
|
72
|
+
held = undefined
|
|
73
|
+
},
|
|
74
|
+
close: () => new Promise<void>((done) => {
|
|
75
|
+
release()
|
|
76
|
+
server.close(() => done())
|
|
77
|
+
server.closeAllConnections()
|
|
78
|
+
}),
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export async function recordingProxy(): Promise<{ url: string, attempts: string[], close(): Promise<void> }> {
|
|
83
|
+
const attempts: string[] = []
|
|
84
|
+
const server = createServer((req, res) => {
|
|
85
|
+
attempts.push(`${req.method} ${req.url}`)
|
|
86
|
+
res.writeHead(502).end()
|
|
87
|
+
})
|
|
88
|
+
server.on('connect', (req, socket) => {
|
|
89
|
+
attempts.push(`CONNECT ${req.url}`)
|
|
90
|
+
socket.end('HTTP/1.1 502 Bad Gateway\r\n\r\n')
|
|
91
|
+
})
|
|
92
|
+
const port = await new Promise<number>(done => server.listen(0, '127.0.0.1', () => done((server.address() as AddressInfo).port)))
|
|
93
|
+
return {
|
|
94
|
+
url: `http://127.0.0.1:${port}`,
|
|
95
|
+
attempts,
|
|
96
|
+
close: () => new Promise<void>((done) => {
|
|
97
|
+
server.close(() => done())
|
|
98
|
+
server.closeAllConnections()
|
|
99
|
+
}),
|
|
100
|
+
}
|
|
101
|
+
}
|
package/src/host.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { buildView, runBlock } from '@lincyaw/compiler'
|
|
2
|
+
import type { Compilation } from '@lincyaw/compiler'
|
|
3
|
+
import type { ServerHost } from '@lincyaw/server'
|
|
4
|
+
|
|
5
|
+
export function devHost(latest: () => Compilation | undefined): ServerHost {
|
|
6
|
+
const current = (document: string): Compilation => {
|
|
7
|
+
const compilation = latest()
|
|
8
|
+
if (document !== '' || !compilation) throw new Error(document === '' ? 'the deck is still compiling' : `no document ${JSON.stringify(document)} in presmium dev`)
|
|
9
|
+
return compilation
|
|
10
|
+
}
|
|
11
|
+
return {
|
|
12
|
+
async documents() {
|
|
13
|
+
const compilation = latest()
|
|
14
|
+
return compilation ? [{ dir: '', title: compilation.doc.meta.title, lang: compilation.doc.meta.lang }] : []
|
|
15
|
+
},
|
|
16
|
+
async compile(document) {
|
|
17
|
+
const { doc } = current(document)
|
|
18
|
+
return { doc, diagnostics: doc.diagnostics }
|
|
19
|
+
},
|
|
20
|
+
async check(document) {
|
|
21
|
+
const compilation = current(document)
|
|
22
|
+
return [...compilation.doc.diagnostics, ...await compilation.check()]
|
|
23
|
+
},
|
|
24
|
+
async build(document, options = {}) {
|
|
25
|
+
const report = await buildView(current(document), options)
|
|
26
|
+
return { outputs: report.outputs.map(({ renderer, outDir }) => ({ renderer, outDir })), findings: report.findings }
|
|
27
|
+
},
|
|
28
|
+
run: async (document, target, signal) => runBlock(current(document), target, signal),
|
|
29
|
+
}
|
|
30
|
+
}
|
package/src/index.ts
ADDED
package/src/testing.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process'
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
|
+
|
|
4
|
+
export const PRESMIUM_BIN = fileURLToPath(new URL('../bin/presmium.mjs', import.meta.url))
|
|
5
|
+
|
|
6
|
+
export interface Run {
|
|
7
|
+
code: number
|
|
8
|
+
stdout: string
|
|
9
|
+
stderr: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function run(command: string, args: string[], options: { cwd?: string, env?: NodeJS.ProcessEnv } = {}): Promise<Run> {
|
|
13
|
+
return new Promise((resolve) => {
|
|
14
|
+
execFile(command, args, { cwd: options.cwd, env: options.env, maxBuffer: 256 << 20 }, (error, stdout, stderr) => {
|
|
15
|
+
resolve({ code: !error ? 0 : typeof error.code === 'number' ? error.code : -1, stdout, stderr })
|
|
16
|
+
})
|
|
17
|
+
})
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function presmium(cwd: string, args: string[], env: Record<string, string> = {}): Promise<Run> {
|
|
21
|
+
const { NODE_ENV: _test, ...inherited } = process.env
|
|
22
|
+
return run(process.execPath, [PRESMIUM_BIN, ...args], { cwd, env: { ...inherited, ...env } })
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export { fakeModel, recordingProxy } from './fake-model.ts'
|
|
26
|
+
export type { FakeModel, Received, Step } from './fake-model.ts'
|