@lincyaw/cli 1.0.0-rc.11 → 1.0.0-rc.111
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/README.md +2 -2
- package/bin/presmium.mjs +1 -1
- package/package.json +7 -6
- package/src/cli.ts +213 -7
- package/src/document-file.ts +59 -0
- package/src/import.ts +2 -0
- package/src/index.ts +17 -1
- package/src/markdown.ts +2 -0
- package/src/mcp-workspace.ts +77 -0
- package/src/messages.ts +357 -9
- package/src/script.ts +152 -0
- package/src/speech-key.ts +73 -0
- package/src/voiceover.ts +241 -0
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ Part of [Presmium](https://github.com/Lincyaw/presmium), which turns structured
|
|
|
6
6
|
|
|
7
7
|
## Install
|
|
8
8
|
|
|
9
|
-
Most people install the `presmium` package, which brings this command with the renderers and the official plugins:
|
|
9
|
+
Most people install the `presmium` package, which brings this command with Studio, the renderers and the official plugins:
|
|
10
10
|
|
|
11
11
|
```sh
|
|
12
12
|
pnpm add -g @lincyaw/presmium
|
|
@@ -28,7 +28,7 @@ pnpm add -D @lincyaw/cli @lincyaw/web @lincyaw/render-slides @lincyaw/render-not
|
|
|
28
28
|
| `presmium dev [deck]` | Dev servers that update on save (`--to`, `--out`, `--server-port`, `--allow`) |
|
|
29
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
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),
|
|
31
|
+
| `presmium studio [dir]` | The workbench (experimental), included with Presmium (`--port`, `--host`); uses the running command's bundled version |
|
|
32
32
|
|
|
33
33
|
`[deck]` is a directory with `lecture.json` 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
34
|
|
package/bin/presmium.mjs
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lincyaw/cli",
|
|
3
|
-
"version": "1.0.0-rc.
|
|
3
|
+
"version": "1.0.0-rc.111",
|
|
4
4
|
"description": "The presmium command: build, dev, ir, check and serve for Presmium documents",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -36,10 +36,11 @@
|
|
|
36
36
|
],
|
|
37
37
|
"dependencies": {
|
|
38
38
|
"jiti": "^2.7.0",
|
|
39
|
-
"
|
|
40
|
-
"@lincyaw/
|
|
41
|
-
"@lincyaw/workspace": "1.0.0-rc.
|
|
42
|
-
"@lincyaw/server": "1.0.0-rc.
|
|
43
|
-
"@lincyaw/
|
|
39
|
+
"yaml": "^2.9.1",
|
|
40
|
+
"@lincyaw/compiler": "1.0.0-rc.111",
|
|
41
|
+
"@lincyaw/workspace": "1.0.0-rc.111",
|
|
42
|
+
"@lincyaw/server": "1.0.0-rc.111",
|
|
43
|
+
"@lincyaw/kernel": "1.0.0-rc.111",
|
|
44
|
+
"@lincyaw/skills": "1.0.0-rc.111"
|
|
44
45
|
}
|
|
45
46
|
}
|
package/src/cli.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { existsSync, statSync } from 'node:fs'
|
|
2
|
-
import { mkdir, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
3
3
|
import { createRequire } from 'node:module'
|
|
4
4
|
import { dirname, join, relative, resolve } from 'node:path'
|
|
5
5
|
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
6
6
|
import { parseArgs } from 'node:util'
|
|
7
7
|
import { createJiti } from 'jiti'
|
|
8
|
-
import { APPROVAL_KINDS, errorMessage } from '@lincyaw/kernel'
|
|
9
|
-
import { bracketIPv6,
|
|
10
|
-
import type { ApprovalKind, Finding, Severity } from '@lincyaw/kernel'
|
|
8
|
+
import { APPROVAL_KINDS, deckLocale, errorMessage } from '@lincyaw/kernel'
|
|
9
|
+
import { bracketIPv6, irRevision, lanAddresses } from '@lincyaw/kernel/node'
|
|
10
|
+
import type { ApprovalKind, Finding, Severity, SpeechVoice } from '@lincyaw/kernel'
|
|
11
11
|
import { build, Compiler, dev, resolveEntry } from '@lincyaw/compiler'
|
|
12
12
|
import type { BuildReport, Compilation, RunStats } from '@lincyaw/compiler'
|
|
13
13
|
import { isAnyAddress, isLoopback, serverConfigKey, servedDocument, startServer } from '@lincyaw/server'
|
|
@@ -15,9 +15,15 @@ import type { ApprovalPolicy } from '@lincyaw/server'
|
|
|
15
15
|
import { buildWorkspace, isWorkspaceRoot, serveWorkspace } from '@lincyaw/workspace'
|
|
16
16
|
import type { WorkspaceBuild } from '@lincyaw/workspace'
|
|
17
17
|
import { runCheck } from './check.ts'
|
|
18
|
+
import { documentPatterns, importDocuments } from '@lincyaw/compiler'
|
|
18
19
|
import type { CheckResult } from './check.ts'
|
|
19
20
|
import { devHost } from './dev-host.ts'
|
|
21
|
+
import { DocumentFileError, readDocumentFile, saveDocumentFile } from './document-file.ts'
|
|
20
22
|
import { CLI_MESSAGES, systemLocale } from './messages.ts'
|
|
23
|
+
import { exportScript, importScript, ScriptError } from './script.ts'
|
|
24
|
+
import { runSpeechKey, SpeechKeyFailure } from './speech-key.ts'
|
|
25
|
+
import { runVoiceover, VoiceoverFailure } from './voiceover.ts'
|
|
26
|
+
import { mcpWorkspaceSession } from './mcp-workspace.ts'
|
|
21
27
|
|
|
22
28
|
const BUNDLED = fileURLToPath(new URL('..', import.meta.url))
|
|
23
29
|
const PRESMIUM_BIN = fileURLToPath(new URL('../bin/presmium.mjs', import.meta.url))
|
|
@@ -36,7 +42,7 @@ const OPTIONS = {
|
|
|
36
42
|
'dev': ['to', 'out', 'server-port', 'allow'],
|
|
37
43
|
'ir': ['out'],
|
|
38
44
|
'check': ['json', 'update-lock', 'env', 'audience', 'external-links'],
|
|
39
|
-
'serve': ['port', 'host', 'operator-dir', 'preview-origin', 'public-url'],
|
|
45
|
+
'serve': ['port', 'host', 'operator-dir', 'preview-origin', 'public-url', 'allow'],
|
|
40
46
|
} as const
|
|
41
47
|
|
|
42
48
|
type Name = keyof typeof OPTIONS
|
|
@@ -66,6 +72,11 @@ export async function main(argv: string[], options: MainOptions = {}): Promise<n
|
|
|
66
72
|
if (argv[0] === 'new') return runNewCommand(argv.slice(1), bundled)
|
|
67
73
|
if (argv[0] === 'skills') return (await import('@lincyaw/skills')).main(argv.slice(1))
|
|
68
74
|
if (argv[0] === 'studio') return runStudioCommand(argv.slice(1), bundled, options.bin ?? PRESMIUM_BIN)
|
|
75
|
+
if (argv[0] === 'mcp') return runMcpCommand(argv.slice(1), bundled)
|
|
76
|
+
if (argv[0] === 'import') return runImportCommand(argv.slice(1))
|
|
77
|
+
if (argv[0] === 'voiceover') return runVoiceoverCommand(argv.slice(1), bundled)
|
|
78
|
+
if (argv[0] === 'speech') return runSpeechCommand(argv.slice(1))
|
|
79
|
+
if (argv[0] === 'script') return runScriptCommand(argv.slice(1))
|
|
69
80
|
let command: Command | 'help'
|
|
70
81
|
try {
|
|
71
82
|
command = parseCommand(argv)
|
|
@@ -86,7 +97,7 @@ export async function main(argv: string[], options: MainOptions = {}): Promise<n
|
|
|
86
97
|
case 'serve': return await runServeCommand(command, bundled)
|
|
87
98
|
}
|
|
88
99
|
} catch (error) {
|
|
89
|
-
process.stderr.write(`presmium: ${errorMessage(error)}\n`)
|
|
100
|
+
process.stderr.write(`presmium: ${typeof error === 'object' && error !== null && 'code' in error && error.code === 'workspace-service-already-running' ? t.workspaceServiceBusy('url' in error && typeof error.url === 'string' ? error.url : undefined) : errorMessage(error)}\n`)
|
|
90
101
|
return 2
|
|
91
102
|
}
|
|
92
103
|
}
|
|
@@ -289,12 +300,12 @@ async function runServeCommand(command: Command, bundled: string): Promise<numbe
|
|
|
289
300
|
check: compilation => compilation.check(),
|
|
290
301
|
previewOrigins: command.previewOrigins,
|
|
291
302
|
...command.publicUrl ? { publicUrl: command.publicUrl } : {},
|
|
303
|
+
allow: command.allow,
|
|
292
304
|
})
|
|
293
305
|
process.stdout.write(`serve ${started.url}\n${networkLines(command.listenAddress, started.url)}workspace ${started.root}\nmcp ${started.mcp.url}${t.token(started.mcp.stateFile)}\n`)
|
|
294
306
|
if (command.listenAddress && !isLoopback(command.listenAddress)) {
|
|
295
307
|
process.stderr.write(`${t.serveOpen(command.listenAddress, new URL(started.url).port)}\n`)
|
|
296
308
|
}
|
|
297
|
-
if (!findFfmpeg()) process.stderr.write(`${t.noFfmpeg(ffmpegInstallCommand())}\n`)
|
|
298
309
|
await new Promise<void>((done) => {
|
|
299
310
|
process.once('SIGINT', done)
|
|
300
311
|
process.once('SIGTERM', done)
|
|
@@ -323,6 +334,186 @@ async function runNewCommand(argv: string[], bundled: string): Promise<number> {
|
|
|
323
334
|
return createMain(argv)
|
|
324
335
|
}
|
|
325
336
|
|
|
337
|
+
/** Markdown notes to documents; prints what it wrote, the links it could not resolve and the patterns that list them. */
|
|
338
|
+
async function runImportCommand(argv: string[]): Promise<number> {
|
|
339
|
+
let parsed
|
|
340
|
+
try {
|
|
341
|
+
parsed = parseArgs({ args: argv, allowPositionals: true, options: {
|
|
342
|
+
out: { type: 'string' }, exclude: { type: 'string', multiple: true }, lang: { type: 'string' }, group: { type: 'string' }, help: { type: 'boolean', short: 'h', default: false },
|
|
343
|
+
} })
|
|
344
|
+
} catch (error) {
|
|
345
|
+
process.stderr.write(`presmium: ${errorMessage(error)}\n\n${t.usage}\n`)
|
|
346
|
+
return 2
|
|
347
|
+
}
|
|
348
|
+
const { values, positionals } = parsed
|
|
349
|
+
if (values.help) {
|
|
350
|
+
process.stdout.write(`${t.usage}\n`)
|
|
351
|
+
return 0
|
|
352
|
+
}
|
|
353
|
+
const [input, ...extra] = positionals
|
|
354
|
+
if (!input) {
|
|
355
|
+
process.stderr.write(`presmium: ${t.importMissing}\n`)
|
|
356
|
+
return 2
|
|
357
|
+
}
|
|
358
|
+
if (extra.length > 0) {
|
|
359
|
+
process.stderr.write(`presmium: ${t.unexpectedArgument(extra[0]!)}\n`)
|
|
360
|
+
return 2
|
|
361
|
+
}
|
|
362
|
+
if (!existsSync(input)) {
|
|
363
|
+
process.stderr.write(`presmium: ${t.notFound(input)}\n`)
|
|
364
|
+
return 2
|
|
365
|
+
}
|
|
366
|
+
const group = values.group === undefined ? undefined : Number(values.group)
|
|
367
|
+
if (group !== undefined && !(Number.isInteger(group) && group >= 1)) {
|
|
368
|
+
process.stderr.write(`presmium: ${t.badGroup(values.group!)}\n`)
|
|
369
|
+
return 2
|
|
370
|
+
}
|
|
371
|
+
const out = resolve(values.out ?? '.')
|
|
372
|
+
const report = await importDocuments(input, { out, exclude: values.exclude, lang: values.lang, group, preserveOriginal: true }).catch(() => undefined)
|
|
373
|
+
if (!report) return fail(t.importFailed, 1)
|
|
374
|
+
for (const { note, link } of report.unresolved) process.stderr.write(`${t.importUnresolved(note, link)}\n`)
|
|
375
|
+
process.stdout.write(`${t.imported(report.documents.length, report.files, relative(process.cwd(), out) || '.')}\n`)
|
|
376
|
+
if (report.documents.length > 0) process.stdout.write(`${t.importPatterns(documentPatterns(report.documents))}\n`)
|
|
377
|
+
return 0
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const HELP = { type: 'boolean', short: 'h', default: false } as const
|
|
381
|
+
|
|
382
|
+
function usageError(error: unknown): number {
|
|
383
|
+
process.stderr.write(`presmium: ${errorMessage(error)}\n\n${t.usage}\n`)
|
|
384
|
+
return 2
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function fail(message: string, code: number): number {
|
|
388
|
+
process.stderr.write(`presmium: ${message}\n`)
|
|
389
|
+
return code
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** A path as typed from here: relative below the working directory, absolute elsewhere. */
|
|
393
|
+
function shownPath(path: string): string {
|
|
394
|
+
const shown = relative(process.cwd(), path)
|
|
395
|
+
return !shown ? '.' : shown.startsWith('..') ? path : shown
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
function documentFileMessage(error: DocumentFileError): string {
|
|
399
|
+
return error.code === 'document-changed' ? t.documentChanged : t.documentInvalid(error.detail)
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** The deck's entry, or a usage error already printed. */
|
|
403
|
+
function deckEntry(deck: string): string | undefined {
|
|
404
|
+
try {
|
|
405
|
+
const entry = resolveEntry(deck)
|
|
406
|
+
if (existsSync(entry)) return entry
|
|
407
|
+
fail(t.notFound(entry), 2)
|
|
408
|
+
} catch (error) {
|
|
409
|
+
fail(errorMessage(error), 2)
|
|
410
|
+
}
|
|
411
|
+
return undefined
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
async function runVoiceoverCommand(argv: string[], bundled: string): Promise<number> {
|
|
415
|
+
let parsed
|
|
416
|
+
try {
|
|
417
|
+
parsed = parseArgs({ args: argv, allowPositionals: true, options: { voice: { type: 'string' }, yes: { type: 'boolean', default: false }, prune: { type: 'boolean', default: false }, json: { type: 'boolean', default: false }, help: HELP } })
|
|
418
|
+
} catch (error) {
|
|
419
|
+
return usageError(error)
|
|
420
|
+
}
|
|
421
|
+
const { values, positionals } = parsed
|
|
422
|
+
if (values.help) {
|
|
423
|
+
process.stdout.write(`${t.usage}\n`)
|
|
424
|
+
return 0
|
|
425
|
+
}
|
|
426
|
+
const [deck = '.', ...extra] = positionals
|
|
427
|
+
if (extra.length > 0) return fail(t.unexpectedArgument(extra[0]!), 2)
|
|
428
|
+
let voice: SpeechVoice | undefined
|
|
429
|
+
if (values.voice !== undefined) {
|
|
430
|
+
const at = values.voice.indexOf(':'), engine = values.voice.slice(0, Math.max(at, 0)).trim(), id = values.voice.slice(at + 1).trim()
|
|
431
|
+
if (at < 0 || !engine || !id) return fail(t.badVoice(values.voice), 2)
|
|
432
|
+
voice = { engine, voice: id }
|
|
433
|
+
}
|
|
434
|
+
const entry = deckEntry(deck)
|
|
435
|
+
if (!entry) return 2
|
|
436
|
+
try {
|
|
437
|
+
return await runVoiceover({ entry, ...voice ? { voice } : {}, yes: values.yes, prune: values.prune, json: values.json, bundled }, t)
|
|
438
|
+
} catch (error) {
|
|
439
|
+
if (error instanceof VoiceoverFailure) return fail(error.message, 1)
|
|
440
|
+
if (error instanceof DocumentFileError) return fail(documentFileMessage(error), 1)
|
|
441
|
+
return fail(errorMessage(error), 2)
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
async function runSpeechCommand(argv: string[]): Promise<number> {
|
|
446
|
+
let parsed
|
|
447
|
+
try {
|
|
448
|
+
parsed = parseArgs({ args: argv, allowPositionals: true, options: { help: HELP } })
|
|
449
|
+
} catch (error) {
|
|
450
|
+
return usageError(error)
|
|
451
|
+
}
|
|
452
|
+
const { values, positionals } = parsed
|
|
453
|
+
if (values.help) {
|
|
454
|
+
process.stdout.write(`${t.usage}\n`)
|
|
455
|
+
return 0
|
|
456
|
+
}
|
|
457
|
+
const [group, action, dir = '.', ...extra] = positionals
|
|
458
|
+
if (group !== 'key' || (action !== 'set' && action !== 'clear' && action !== 'status')) return fail(t.speechUsage, 2)
|
|
459
|
+
if (extra.length > 0) return fail(t.unexpectedArgument(extra[0]!), 2)
|
|
460
|
+
if (!existsSync(dir) || !statSync(dir).isDirectory()) return fail(t.notFound(resolve(dir)), 2)
|
|
461
|
+
try {
|
|
462
|
+
return await runSpeechKey(action, resolve(dir), t)
|
|
463
|
+
} catch (error) {
|
|
464
|
+
return fail(errorMessage(error), error instanceof SpeechKeyFailure ? 1 : 2)
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** The narration as one Markdown file to polish (`export`), and the polished file back into lecture.json (`import`). */
|
|
469
|
+
async function runScriptCommand(argv: string[]): Promise<number> {
|
|
470
|
+
let parsed
|
|
471
|
+
try {
|
|
472
|
+
parsed = parseArgs({ args: argv, allowPositionals: true, options: { out: { type: 'string' }, help: HELP } })
|
|
473
|
+
} catch (error) {
|
|
474
|
+
return usageError(error)
|
|
475
|
+
}
|
|
476
|
+
const { values, positionals } = parsed
|
|
477
|
+
if (values.help) {
|
|
478
|
+
process.stdout.write(`${t.usage}\n`)
|
|
479
|
+
return 0
|
|
480
|
+
}
|
|
481
|
+
const [action, deck, file, ...extra] = positionals
|
|
482
|
+
if (action !== 'export' && action !== 'import') return fail(t.scriptUsage, 2)
|
|
483
|
+
if (!deck) return fail(t.scriptUsage, 2)
|
|
484
|
+
const unexpected = action === 'export' ? file ?? extra[0] : extra[0]
|
|
485
|
+
if (unexpected !== undefined) return fail(t.unexpectedArgument(unexpected), 2)
|
|
486
|
+
if (action === 'import' && values.out !== undefined) return fail(t.optionNotFor('out', 'script import'), 2)
|
|
487
|
+
const entry = deckEntry(deck)
|
|
488
|
+
if (!entry) return 2
|
|
489
|
+
const fallback = join(dirname(entry), 'dist', 'script.md')
|
|
490
|
+
try {
|
|
491
|
+
const source = readDocumentFile(entry)
|
|
492
|
+
if (action === 'export') {
|
|
493
|
+
const out = resolve(values.out ?? fallback)
|
|
494
|
+
const written = exportScript(source.document, CLI_MESSAGES[deckLocale(source.document.metadata.lang)].scriptInstructions)
|
|
495
|
+
await mkdir(dirname(out), { recursive: true })
|
|
496
|
+
await writeFile(out, written.text)
|
|
497
|
+
process.stdout.write(`${t.scriptExported(shownPath(out), written.narrations, written.steps)}\n`)
|
|
498
|
+
return 0
|
|
499
|
+
}
|
|
500
|
+
const input = resolve(file ?? fallback)
|
|
501
|
+
if (!existsSync(input)) return fail(t.notFound(input), 2)
|
|
502
|
+
const { document, changed } = importScript(source.document, await readFile(input, 'utf8'))
|
|
503
|
+
if (changed.length === 0) {
|
|
504
|
+
process.stdout.write(`${t.scriptUnchanged}\n`)
|
|
505
|
+
return 0
|
|
506
|
+
}
|
|
507
|
+
saveDocumentFile(source, document)
|
|
508
|
+
process.stdout.write(`${t.scriptImported(changed)}\n${t.scriptNext(shownPath(dirname(entry)))}\n`)
|
|
509
|
+
return 0
|
|
510
|
+
} catch (error) {
|
|
511
|
+
if (error instanceof ScriptError) return fail(t.scriptErrors[error.code](error.detail, error.line), 1)
|
|
512
|
+
if (error instanceof DocumentFileError) return fail(documentFileMessage(error), 1)
|
|
513
|
+
return fail(errorMessage(error), 2)
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
326
517
|
async function runStudioCommand(argv: string[], bundled: string, presmiumBin: string): Promise<number> {
|
|
327
518
|
const entry = resolveInstalled('@lincyaw/studio', bundled)
|
|
328
519
|
if (!entry) {
|
|
@@ -333,6 +524,21 @@ async function runStudioCommand(argv: string[], bundled: string, presmiumBin: st
|
|
|
333
524
|
return studioMain(argv, { presmium: presmiumBin })
|
|
334
525
|
}
|
|
335
526
|
|
|
527
|
+
/** MCP on stdio, from the installed `@lincyaw/mcp`; stdout carries only its messages. */
|
|
528
|
+
async function runMcpCommand(argv: string[], bundled: string): Promise<number> {
|
|
529
|
+
const entry = resolveInstalled('@lincyaw/mcp/cli', bundled)
|
|
530
|
+
if (!entry) {
|
|
531
|
+
process.stderr.write(`${t.mcpMissing}\n`)
|
|
532
|
+
return 2
|
|
533
|
+
}
|
|
534
|
+
console.log = console.info = console.debug = console.error
|
|
535
|
+
const workspace = mcpWorkspaceSession(bundled)
|
|
536
|
+
const { main: mcpMain } = await createJiti(import.meta.url).import<{ main(argv: string[], options: { bundled: string, startWorkspace: typeof workspace.startWorkspace }): Promise<number | undefined> }>(entry)
|
|
537
|
+
try { return await mcpMain(argv, { bundled, startWorkspace: workspace.startWorkspace }) ?? 0 }
|
|
538
|
+
catch (error) { return fail(errorMessage(error), 2) }
|
|
539
|
+
finally { await workspace.close() }
|
|
540
|
+
}
|
|
541
|
+
|
|
336
542
|
function networkLines(listenAddress: string | undefined, url: string): string {
|
|
337
543
|
if (!listenAddress || isLoopback(listenAddress)) return ''
|
|
338
544
|
const { port } = new URL(url)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto'
|
|
2
|
+
import { readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { validateDocument } from '@lincyaw/kernel'
|
|
4
|
+
import type { TeachingDocument } from '@lincyaw/kernel'
|
|
5
|
+
|
|
6
|
+
/** `lecture.json` as it was read: its exact text, to save a change in the same formatting and only if it is unchanged. */
|
|
7
|
+
export interface DocumentFile {
|
|
8
|
+
entry: string
|
|
9
|
+
text: string
|
|
10
|
+
document: TeachingDocument
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export class DocumentFileError extends Error {
|
|
14
|
+
readonly code: 'document-invalid' | 'document-changed'
|
|
15
|
+
readonly detail: string
|
|
16
|
+
constructor(code: DocumentFileError['code'], detail = '') {
|
|
17
|
+
super(code)
|
|
18
|
+
this.code = code
|
|
19
|
+
this.detail = detail
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const BOM = String.fromCharCode(0xfeff)
|
|
24
|
+
const issuesOf = (checked: ReturnType<typeof validateDocument>) => checked.issues.slice(0, 3).map(issue => `${issue.path || '/'}: ${issue.message}`).join('; ')
|
|
25
|
+
|
|
26
|
+
export function readDocumentFile(entry: string): DocumentFile {
|
|
27
|
+
const text = readFileSync(entry, 'utf8')
|
|
28
|
+
let value: unknown
|
|
29
|
+
try { value = JSON.parse(text.startsWith(BOM) ? text.slice(1) : text) }
|
|
30
|
+
catch (error) { throw new DocumentFileError('document-invalid', error instanceof Error ? error.message : String(error)) }
|
|
31
|
+
const checked = validateDocument(value)
|
|
32
|
+
if (!checked.document) throw new DocumentFileError('document-invalid', issuesOf(checked))
|
|
33
|
+
return { entry, text, document: checked.document }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Validates the changed document as the workspace does before saving, then replaces the file atomically in its own
|
|
38
|
+
* indentation, line endings and byte order mark, so that the change is the only difference. Refuses when the file
|
|
39
|
+
* changed since it was read (another editor saved it).
|
|
40
|
+
*/
|
|
41
|
+
export function saveDocumentFile(file: DocumentFile, document: TeachingDocument): void {
|
|
42
|
+
const checked = validateDocument(document)
|
|
43
|
+
if (!checked.document) throw new DocumentFileError('document-invalid', issuesOf(checked))
|
|
44
|
+
const body = file.text.startsWith(BOM) ? file.text.slice(1) : file.text
|
|
45
|
+
const indent = /^\{\r?\n([ \t]+)"/.exec(body)?.[1] ?? ' '
|
|
46
|
+
const newline = body.includes('\r\n') ? '\r\n' : '\n'
|
|
47
|
+
let text = JSON.stringify(checked.document, null, indent)
|
|
48
|
+
if (newline !== '\n') text = text.replaceAll('\n', newline)
|
|
49
|
+
if (body.endsWith('\n')) text += newline
|
|
50
|
+
if (body !== file.text) text = BOM + text
|
|
51
|
+
if (readFileSync(file.entry, 'utf8') !== file.text) throw new DocumentFileError('document-changed')
|
|
52
|
+
const temporary = `${file.entry}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`
|
|
53
|
+
try {
|
|
54
|
+
writeFileSync(temporary, text, { flag: 'wx', mode: statSync(file.entry).mode & 0o777 })
|
|
55
|
+
renameSync(temporary, file.entry)
|
|
56
|
+
} finally {
|
|
57
|
+
rmSync(temporary, { force: true })
|
|
58
|
+
}
|
|
59
|
+
}
|
package/src/import.ts
ADDED
package/src/index.ts
CHANGED
|
@@ -1,2 +1,18 @@
|
|
|
1
|
-
|
|
1
|
+
import { createRequire } from 'node:module'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { fileURLToPath } from 'node:url'
|
|
4
|
+
import { createJiti } from 'jiti'
|
|
5
|
+
import { CLI_MESSAGES, systemLocale } from './messages.ts'
|
|
6
|
+
import type { MainOptions } from './cli.ts'
|
|
2
7
|
export type { MainOptions } from './cli.ts'
|
|
8
|
+
|
|
9
|
+
/** Starting the editor does not need to import the compiler, exporters or MCP tool tree first. */
|
|
10
|
+
export async function main(argv: string[], options: MainOptions = {}): Promise<number> {
|
|
11
|
+
if (argv[0] !== 'studio') return (await import('./cli.ts')).main(argv, options)
|
|
12
|
+
const bundled = options.bundled ?? fileURLToPath(new URL('..', import.meta.url))
|
|
13
|
+
let entry: string
|
|
14
|
+
try { entry = createRequire(join(bundled, 'package.json')).resolve('@lincyaw/studio') }
|
|
15
|
+
catch { process.stderr.write(`${CLI_MESSAGES[systemLocale()].studioMissing}\n`); return 2 }
|
|
16
|
+
const studio = await createJiti(import.meta.url).import<{ main(argv: string[], options: { presmium: string }): Promise<number> }>(entry)
|
|
17
|
+
return studio.main(argv.slice(1), { presmium: options.bin ?? fileURLToPath(new URL('../bin/presmium.mjs', import.meta.url)) })
|
|
18
|
+
}
|
package/src/markdown.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { existsSync, realpathSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { setTimeout as delay } from 'node:timers/promises'
|
|
4
|
+
import { findWorkspaceRoot, WORKSPACE_CONFIG } from '@lincyaw/compiler'
|
|
5
|
+
import { findWorkspaceServiceState, readServiceState, serveStateDir, tryAcquireServiceHostLease } from '@lincyaw/kernel/node'
|
|
6
|
+
import type { ApprovalKind } from '@lincyaw/kernel'
|
|
7
|
+
import type { ServiceHostLease, ServiceState } from '@lincyaw/kernel/node'
|
|
8
|
+
import { serveWorkspace } from '@lincyaw/workspace'
|
|
9
|
+
import type { WorkspaceServer } from '@lincyaw/workspace'
|
|
10
|
+
|
|
11
|
+
interface WorkspaceTarget { mcp: string, token: string, pid: number }
|
|
12
|
+
export interface McpWorkspaceConnection { target: WorkspaceTarget, close(): Promise<void> }
|
|
13
|
+
|
|
14
|
+
/** One stdio session may own the shared host; every other session borrows its published endpoint. */
|
|
15
|
+
export function mcpWorkspaceSession(bundled: string) {
|
|
16
|
+
let root: Promise<string> | undefined, owned: { server: WorkspaceServer, lease: ServiceHostLease } | undefined
|
|
17
|
+
let closed = false, pending: Promise<McpWorkspaceConnection> | undefined, closing: Promise<void> | undefined
|
|
18
|
+
const closeOwned = async () => {
|
|
19
|
+
const current = owned
|
|
20
|
+
owned = undefined
|
|
21
|
+
await current?.server.close()
|
|
22
|
+
}
|
|
23
|
+
const close = (): Promise<void> => closing ??= Promise.resolve().then(async () => {
|
|
24
|
+
closed = true
|
|
25
|
+
await pending?.catch(() => undefined)
|
|
26
|
+
await closeOwned()
|
|
27
|
+
})
|
|
28
|
+
const target = (state: ServiceState): WorkspaceTarget => ({ mcp: state.mcp, token: state.token, pid: state.pid })
|
|
29
|
+
return {
|
|
30
|
+
startWorkspace(dir: string, allow: readonly ApprovalKind[], signal: AbortSignal): Promise<McpWorkspaceConnection> {
|
|
31
|
+
if (pending) return pending
|
|
32
|
+
const work = async () => {
|
|
33
|
+
signal.throwIfAborted()
|
|
34
|
+
if (closed) throw new Error('mcp-workspace-session-closed')
|
|
35
|
+
if (!root) {
|
|
36
|
+
const existing = findWorkspaceServiceState(dir)
|
|
37
|
+
root = existing ? Promise.resolve(existing.root) : findWorkspaceRoot(dir).then(found => realpathSync(existsSync(join(found, WORKSPACE_CONFIG)) ? found : dir))
|
|
38
|
+
}
|
|
39
|
+
const directory = await root, file = join(serveStateDir(directory), 'server.json')
|
|
40
|
+
const deadline = Date.now() + 30_000
|
|
41
|
+
for (;;) {
|
|
42
|
+
signal.throwIfAborted()
|
|
43
|
+
if (closed) throw new Error('mcp-workspace-session-closed')
|
|
44
|
+
if (owned?.lease.signal.aborted) await closeOwned()
|
|
45
|
+
const state = readServiceState(file)
|
|
46
|
+
if (state) return { target: target(state), close }
|
|
47
|
+
if (Date.now() >= deadline) throw new Error('mcp-workspace-start-timeout')
|
|
48
|
+
const lease = await tryAcquireServiceHostLease(directory)
|
|
49
|
+
if (!lease) { await delay(100, undefined, { signal }); continue }
|
|
50
|
+
// A previous host may have published while this process was waiting for its lease.
|
|
51
|
+
const appeared = readServiceState(file)
|
|
52
|
+
if (appeared) { await lease.release(); return { target: target(appeared), close } }
|
|
53
|
+
let server: WorkspaceServer | undefined
|
|
54
|
+
const startup = AbortSignal.any([signal, AbortSignal.timeout(Math.max(1, deadline - Date.now()))])
|
|
55
|
+
try {
|
|
56
|
+
signal.throwIfAborted()
|
|
57
|
+
server = await serveWorkspace({ dir: directory, bundled, port: 0, listenAddress: '127.0.0.1', allow: [...allow], hostLease: lease, signal: startup })
|
|
58
|
+
startup.throwIfAborted()
|
|
59
|
+
if (closed) throw new Error('mcp-workspace-session-closed')
|
|
60
|
+
const ready = readServiceState(file)
|
|
61
|
+
if (!ready || ready.pid !== process.pid || ready.mcp !== server.mcp.url) throw new Error('mcp-workspace-state-unavailable')
|
|
62
|
+
owned = { server, lease }
|
|
63
|
+
return { target: target(ready), close }
|
|
64
|
+
} catch (error) {
|
|
65
|
+
if (server) await server.close()
|
|
66
|
+
else await lease.release()
|
|
67
|
+
if (!signal.aborted && startup.aborted) throw new Error('mcp-workspace-start-timeout')
|
|
68
|
+
throw error
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
pending = work().finally(() => { pending = undefined })
|
|
73
|
+
return pending
|
|
74
|
+
},
|
|
75
|
+
close,
|
|
76
|
+
}
|
|
77
|
+
}
|