@lincyaw/cli 1.0.0-rc.6 → 1.0.0-rc.61

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/src/messages.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  export { systemLocale } from '@lincyaw/kernel/node'
2
2
  import { DOCUMENT_ENTRY } from '@lincyaw/kernel'
3
3
  import type { Locale } from '@lincyaw/kernel'
4
+ import type { SpeechSettingsError } from '@lincyaw/kernel/node'
5
+ import type { ScriptError } from './script.ts'
4
6
 
5
7
  // The lines that start with a key and two spaces (`serve <url>`, `workspace <root>`, `mcp <url>`, `<renderer> <url>`)
6
8
  // are read by programs (`@lincyaw/dsh/launch`, the tests): their keys, URLs and paths stay the same in both languages.
@@ -24,9 +26,9 @@ export interface CliMessages {
24
26
  token(file: string): string
25
27
  watching(ir: string): string
26
28
  serveOpen(address: string, port: string): string
27
- noFfmpeg(command: string): string
28
29
  newMissing: string
29
30
  studioMissing: string
31
+ mcpMissing: string
30
32
  noProblems: string
31
33
  counts(errors: number, warnings: number, infos: number): string
32
34
  severity: Record<'error' | 'warning' | 'info', string>
@@ -35,8 +37,72 @@ export interface CliMessages {
35
37
  documentRuns(executed: number, cached: number): string
36
38
  notRendered(blocks: number): string
37
39
  codeRuns(executed: number, cached: number, sandbox?: string): string
40
+ importMissing: string
41
+ badGroup(value: string): string
42
+ imported(documents: number, files: number, out: string): string
43
+ importUnresolved(note: string, link: string): string
44
+ importPatterns(patterns: string[]): string
45
+ badVoice(value: string): string
46
+ documentChanged: string
47
+ documentInvalid(detail: string): string
48
+ voiceoverUnavailable: string
49
+ voiceoverLabels: Record<'document' | 'voice' | 'service' | 'sentences' | 'missing' | 'blocked' | 'prune', string>
50
+ voiceoverPlace(page: number, step: number): string
51
+ voiceoverReasons: Record<string, string>
52
+ voiceoverReasonOther(code: string): string
53
+ voiceoverNoVoice: string
54
+ voiceoverUnset: string
55
+ voiceoverVoiceChange(next: string, previous: string): string
56
+ voiceoverVoiceDefault(voice: string): string
57
+ voiceoverService(id: string, provider: string, local: boolean): string
58
+ voiceoverServiceMissing(id: string): string
59
+ voiceoverCounts(total: number, cached: number, missing: number, skipped: number, blocked: number): string
60
+ voiceoverMissing(count: number, characters: number, voices: string[]): string
61
+ voiceoverCharges(providers: string[]): string
62
+ voiceoverLocal: string
63
+ voiceoverBlocked(count: number, reason: string, places: string[], more: boolean): string
64
+ voiceoverPruneErrors: string
65
+ voiceoverPruneUnavailable: string
66
+ voiceoverPruneEngineUnknown: string
67
+ voiceoverPruneWould(count: number, megabytes: string, kept: number): string
68
+ voiceoverDryRun: string
69
+ voiceoverNothing: string
70
+ voiceoverNothingElse: string
71
+ voiceoverVoiceRefused(voice: string, reason: string): string
72
+ voiceoverVoiceSaved(voice: string): string
73
+ voiceoverGenerating(done: number, total: number): string
74
+ voiceoverCancelled(generated: number): string
75
+ voiceoverStale(generated: number): string
76
+ voiceoverGenerated(generated: number): string
77
+ voiceoverRunError(reason: string): string
78
+ voiceoverPruned(count: number, megabytes: string): string
79
+ voiceoverLeft(missing: number, blocked: number): string
80
+ speechUsage: string
81
+ speechKeyLabels: Record<'workspace' | 'key' | 'file', string>
82
+ speechKeySaved(appId: boolean): string
83
+ speechKeyEnvironment(variable: string): string
84
+ speechKeyNone(variable: string): string
85
+ speechKeyPrompt: string
86
+ speechKeyCancelled: string
87
+ speechKeyEmpty: string
88
+ speechKeyStored(file: string): string
89
+ speechKeyCleared: string
90
+ speechKeyClearedEnvironment(variable: string): string
91
+ speechKeyErrors: Record<SpeechSettingsError['code'], (file: string) => string>
92
+ scriptUsage: string
93
+ /** Written into the exported file, in the document's language. */
94
+ scriptInstructions: string
95
+ scriptExported(file: string, narrations: number, steps: number): string
96
+ scriptUnchanged: string
97
+ scriptImported(changed: string[]): string
98
+ scriptNext(document: string): string
99
+ scriptErrors: Record<ScriptError['code'], (detail: string[], line?: number) => string>
38
100
  }
39
101
 
102
+ const list = (items: unknown, separator: string) => [items].flat().join(separator)
103
+ const sentences = (count: number) => `${count} ${count === 1 ? 'sentence' : 'sentences'}`
104
+ const entries = (count: number) => `${count} cached audio ${count === 1 ? 'entry' : 'entries'}`
105
+
40
106
  export const CLI_MESSAGES: Record<Locale, CliMessages> = {
41
107
  'zh-CN': {
42
108
  usage: `用法:presmium <命令> [<文稿>] [<选项>]
@@ -53,6 +119,7 @@ export const CLI_MESSAGES: Record<Locale, CliMessages> = {
53
119
  skills 安装内置技能(与 MCP 和可视化编辑器共用)
54
120
  install <目录> [--json] 安装缺少的 .agents/skills,保留已有技能
55
121
  --name <技能> 只安装指定技能,可重复
122
+ --update 把已有的技能换成这个版本的(升级 Presmium 之后)
56
123
  --json 以 JSON 打印安装结果
57
124
  build 导出文稿:写出 <输出>/ir.json 与 <输出>/<形态>/;在工作区的根目录
58
125
  (有 presmium.workspace.yaml)把整个工作区导出为网站,写到 <输出>/web/
@@ -67,12 +134,44 @@ export const CLI_MESSAGES: Record<Locale, CliMessages> = {
67
134
  --allow <种类> 无需询问即允许的操作:operate、spend、write、agent
68
135
  ir 以 JSON 打印文稿的运行快照
69
136
  --out <文件> 写入文件,而不是打印
137
+ import 把 Markdown 笔记转成文稿(参数是一个 .md 文件或一个文件夹):每份笔记成为
138
+ <输出>/<路径>/${DOCUMENT_ENTRY},一级与二级标题各开一个页面;[[笔记]] 与 [[笔记|文字]]
139
+ 按文件名或 frontmatter 的 aliases 找到对应的文稿,笔记链接的本地文件复制到文稿的
140
+ attachments/;再次导入时覆盖写过的文稿
141
+ --out <目录> 写到这个目录(默认为 .,通常是工作区的根目录)
142
+ --exclude <名称> (可重复)不导入、也不复制其中文件的文件夹或文件,可用 *,例如 raw
143
+ --lang <语言> 没有在 frontmatter 中写 lang 的笔记的语言(默认按文字判断)
144
+ --group <层数> 把笔记所在的第几层文件夹作为文稿的第一个标签;网站的侧栏按第一个
145
+ 标签分组,例如 --group 2 让 projects/<项目>/ 中的笔记成为一组
70
146
  check 检查文稿并运行插件的检查
71
147
  --json 以 JSON 打印结果
72
148
  --update-lock 重新定位代码锚点,并重写 .presmium/anchors.lock.json
73
149
  --env 同时连接 execute.environments 中的运行环境
74
150
  --audience <名称> 按面向这类读者的内容检查
75
151
  --external-links 同时检查外部链接(装有 lychee 时用它)
152
+ voiceover 生成文稿的配音。不加 --yes 时只报告要做什么:语音服务、音色、缺少配音的语句数与
153
+ 字符数(云端语音服务按字符计费),不生成配音,也不修改文件;加 --yes 时只生成缺少的配音,
154
+ 与 Presmium Studio 用同一套执行,不需要运行中的服务。语音服务与密钥按 presmium serve 的
155
+ 方式读取(工作区的运营者目录、PRESMIUM_SPEECH_* 环境变量)
156
+ --voice <服务>:<音色> 先把文稿的默认音色设为它,例如
157
+ volcengine:zh_female_tianmeitaozi_uranus_bigtts
158
+ --yes 确认执行:生成配音(可能由语音服务计费),写入 --voice 与 --prune 的修改
159
+ --prune 删除当前讲稿都不用的配音缓存(.presmium/speech/ 中的文件与 speech.lock.json
160
+ 中的条目)
161
+ --json 以 JSON 打印结果
162
+ script 把讲稿导出为一份 Markdown 文件润色,再导回文稿
163
+ export <文稿> 写出每一步的讲稿:每段在它的标记行 <!-- n: … --> 之下,换行与空行照原样,
164
+ {显示|读法} 是显示与读法不同的词,⟦cue:…⟧ 是提示点,\\ 使后面的 \\、{、}、⟦、⟧
165
+ (读音中还有 |)作为文字
166
+ import <文稿> [<文件>] 把改过的讲稿写回 lecture.json,只改动有变化的讲稿;标记缺失或未知、
167
+ 提示点被删除或移到别的段落时不写入
168
+ --out <文件> export 写到这个文件(默认为 <文稿>/dist/script.md,也是 import 默认读的文件)
169
+ speech 语音服务的设置
170
+ key set [<目录>] 从标准输入读入火山引擎的语音 API Key(不回显),保存在工作区的运营者
171
+ 目录中,与 Presmium Studio 的“设置 → 语音服务”是同一个文件
172
+ key clear [<目录>] 清除保存的密钥
173
+ key status [<目录>] 显示是否配置了密钥与它的来源,不显示密钥;运营者目录可以用
174
+ PRESMIUM_OPERATOR_DIR 指定
76
175
  serve 在本机提供工作区服务(参数是工作区的根目录或一份文稿):工作区网站、
77
176
  各文稿与其版本历史、审阅、插件的服务端路由与课堂同步;不加 --host 时
78
177
  只在本机监听
@@ -86,9 +185,13 @@ export const CLI_MESSAGES: Record<Locale, CliMessages> = {
86
185
  工作区的路由要求它(Authorization: Bearer)
87
186
  --public-url <网址> 反向代理在前面时浏览器使用的地址:信任它的主机,预览与产物
88
187
  的地址用它给出;带路径时代理原样转发该路径,服务的全部内容都在它下面
188
+ --allow <种类> 无需询问即允许的操作:operate、spend、write、agent(默认在打开的
189
+ Presmium 窗口中询问)
190
+ mcp 以标准输入输出提供 MCP 服务,供 Claude Code、Codex 等 AI 工具连接:这个目录的
191
+ Presmium Studio 或 presmium serve 正在运行时转接到它,AI 可以修改文稿;否则只编译
192
+ 文稿,提供阅读、检查与导出。详见 presmium mcp --help
89
193
  studio 启动 Presmium Studio(实验性):浏览器中的编辑应用与这个目录(工作区的
90
- 根目录或一份文稿)的工作区服务,只打印一个要打开的网址。需要另外安装
91
- @lincyaw/studio(约 865 MB)
194
+ 根目录或一份文稿)的工作区服务,只打印一个要打开的网址。随 Presmium 一起安装
92
195
  --port <端口> Presmium Studio 的端口(默认为 4320,被占用时取空闲端口)
93
196
  --host <地址> 改为监听本机在局域网中的这个地址,而不是 127.0.0.1,且没有
94
197
  登录:任何能访问这个端口的人都以你的身份操作
@@ -113,10 +216,10 @@ export const CLI_MESSAGES: Record<Locale, CliMessages> = {
113
216
  compiled: (sections, summary) => `已更新 ${sections} 个页面;${summary}`,
114
217
  token: file => ` (访问令牌在 ${file} 中)`,
115
218
  watching: ir => `正在监视修改;运行快照在 ${ir}`,
116
- noFfmpeg: command => `presmium serve: 没有找到 FFmpeg,讲授视频只能由浏览器导出为 WebM,画质较低。安装后可导出清晰的 MP4:${command}`,
117
219
  serveOpen: (address, port) => `presmium serve: 正在 ${address} 上监听,局域网中的设备可以访问,且没有登录:任何能访问端口 ${port} 的人都以你的身份使用这个工作区(编辑、运行代码、允许操作)。请只在可信的网络中使用;不加 --host 时只在本机监听。`,
118
220
  newMissing: 'presmium new: 没有安装 create-presmium。它随 presmium 一起安装,请运行 pnpm add -g @lincyaw/presmium。',
119
- studioMissing: 'presmium studio: 这里没有安装 Presmium Studio(实验性,约 865 MB)。请运行 pnpm add -g @lincyaw/studio 后使用 presmium-studio,或在本项目中运行 pnpm add -D @lincyaw/studio。',
221
+ studioMissing: 'presmium studio: 没有安装 Presmium Studio。它随 Presmium 一起安装,请运行 pnpm add -g @lincyaw/presmium。',
222
+ mcpMissing: 'presmium mcp: 没有安装 @lincyaw/mcp。它随 Presmium 一起安装,请运行 pnpm add -g @lincyaw/presmium。',
120
223
  noProblems: '没有问题',
121
224
  counts: (errors, warnings, infos) => `${errors} 个错误,${warnings} 个警告,${infos} 条信息`,
122
225
  severity: { error: '错误', warning: '警告', info: '信息' },
@@ -125,6 +228,102 @@ export const CLI_MESSAGES: Record<Locale, CliMessages> = {
125
228
  documentRuns: (executed, cached) => ` (代码运行:执行 ${executed} 个,取自缓存 ${cached} 个)`,
126
229
  notRendered: blocks => ` (${blocks} 个内容块未显示)`,
127
230
  codeRuns: (executed, cached, sandbox) => `代码运行:执行 ${executed} 个,取自缓存 ${cached} 个${sandbox ? `,隔离方式为 ${sandbox}` : ''}`,
231
+ badGroup: value => `--group 需要 1 或更大的整数,而不是“${value}”。`,
232
+ importMissing: '缺少要导入的笔记。请给出一个 .md 文件或一个文件夹,例如 presmium import notes --out site。',
233
+ imported: (documents, files, out) => `已导入 ${documents} 份文稿,复制了 ${files} 个文件,写在 ${out}`,
234
+ importUnresolved: (note, link) => `${note}:链接 ${link} 没有对应的笔记或文件,已改为普通文字`,
235
+ importPatterns: patterns => `presmium.workspace.yaml 的 documents 需要包含:\n${patterns.map(pattern => ` - '${pattern}'`).join('\n')}`,
236
+ badVoice: value => `--voice 需要“<服务>:<音色>”,例如 volcengine:zh_female_tianmeitaozi_uranus_bigtts,而不是“${value}”。`,
237
+ documentChanged: '文稿在读取之后被修改过,没有写入。请重新运行。',
238
+ documentInvalid: detail => `修改后的文稿无效,没有写入:${detail}`,
239
+ voiceoverUnavailable: '这份文稿不能生成配音:它的插件中需要有 @lincyaw/addon-lecture 与 @lincyaw/addon-speech(在 Presmium Studio 中启用视频制作时会加上)。',
240
+ voiceoverLabels: { document: '文稿', voice: '音色', service: '语音服务', sentences: '语句', missing: '需要生成', blocked: '无法生成', prune: '可清理' },
241
+ voiceoverPlace: (page, step) => `第 ${page} 页第 ${step} 步`,
242
+ voiceoverReasons: {
243
+ 'voice-unset': '没有设置音色',
244
+ 'cue-step': '讲稿中有换到下一步的提示点,而这一页按步骤设置了音色',
245
+ 'voice-step-binding-unavailable': '步骤与讲稿的对应已变化,需要重新检查音色设置',
246
+ 'step-binding-stale': '步骤与讲稿的对应已变化,需要重新检查音色设置',
247
+ 'speech-unavailable': '文稿没有语音服务插件',
248
+ 'voice-not-configured': '没有配置语音服务',
249
+ 'voice-engine-unknown': '没有配置这个语音服务',
250
+ 'voice-engine-unsupported': '这个语音服务不能生成配音',
251
+ 'voice-catalog-unavailable': '无法读取语音服务的音色列表',
252
+ 'voice-unavailable': '语音服务中没有这个音色,或它不支持文稿的语言',
253
+ 'voice-revision-changed': '文稿已更新',
254
+ 'voice-source-changed': '文稿已更新',
255
+ 'speech-authentication': '语音服务拒绝了密钥,可以用 presmium speech key set 更新',
256
+ 'speech-permission': '语音服务拒绝访问:检查是否已开通语音合成 2.0,以及密钥的服务与音色权限',
257
+ 'speech-quota': '语音服务额度不足',
258
+ 'speech-busy': '语音服务并发已满,稍后重试',
259
+ 'speech-network': '无法连接语音服务',
260
+ 'speech-empty-audio': '语音服务没有返回音频',
261
+ 'speech-invalid-request': '语音服务不接受这段讲稿或音色参数',
262
+ 'speech-provider': '语音服务暂时无法生成配音',
263
+ 'speech-cache-failed': '配音缓存无法写入,检查磁盘空间与目录权限',
264
+ },
265
+ voiceoverReasonOther: code => `其他原因(${code})`,
266
+ voiceoverNoVoice: '不配音',
267
+ voiceoverUnset: '未设置',
268
+ voiceoverVoiceChange: (next, previous) => `${next}(将取代 ${previous} 成为文稿的默认音色)`,
269
+ voiceoverVoiceDefault: voice => `${voice}(文稿的默认音色)`,
270
+ voiceoverService: (id, provider, local) => `${id}(${provider},${local ? '本机' : '云端'})`,
271
+ voiceoverServiceMissing: id => `${id}(未配置)`,
272
+ voiceoverCounts: (total, cached, missing, skipped, blocked) => `${total} 句:${cached} 句已有配音,${missing} 句需要生成${skipped ? `,${skipped} 句不配音或使用录音` : ''}${blocked ? `,${blocked} 句无法生成` : ''}`,
273
+ voiceoverMissing: (count, characters, voices) => `${count} 句,约 ${characters} 个字符,音色 ${list(voices, '、')}`,
274
+ voiceoverCharges: providers => `云端语音服务按字符计费(${list(providers, '、')});生成的配音由 AI 生成。`,
275
+ voiceoverLocal: '在本机生成;生成的配音由 AI 生成。',
276
+ voiceoverBlocked: (count, reason, places, more) => `${count} 句:${reason}(${list(places, '、')}${more ? '…' : ''})`,
277
+ voiceoverPruneErrors: '文稿有错误,没有清理配音缓存:讲稿可能没有全部读出。请先用 presmium check 检查并修复。',
278
+ voiceoverPruneUnavailable: '文稿的语音服务插件不能清理配音缓存。请更新 Presmium。',
279
+ voiceoverPruneEngineUnknown: '有的语句没有指定语音服务,也没有配置默认的语音服务,无法判断哪些配音缓存在用,没有清理。',
280
+ voiceoverPruneWould: (count, megabytes, kept) => `${count} 条配音缓存没有语句使用(${megabytes} MB),保留 ${kept} 条`,
281
+ voiceoverDryRun: '以上只是预览,没有生成配音,也没有修改文件。加 --yes 执行。',
282
+ voiceoverNothing: '每一句都有配音,没有要做的事。',
283
+ voiceoverNothingElse: '其余语句都有配音。',
284
+ voiceoverVoiceRefused: (voice, reason) => `没有把默认音色设为 ${voice}:${reason}。`,
285
+ voiceoverVoiceSaved: voice => `已把文稿的默认音色设为 ${voice}`,
286
+ voiceoverGenerating: (done, total) => `正在生成配音 ${done} / ${total}`,
287
+ voiceoverCancelled: generated => `已取消;已生成的 ${generated} 句配音保留。`,
288
+ voiceoverStale: generated => `文稿在生成时被修改,已停止;已生成的 ${generated} 句配音保留。`,
289
+ voiceoverGenerated: generated => `已完成:生成了 ${generated} 句配音`,
290
+ voiceoverRunError: reason => `生成失败:${reason}`,
291
+ voiceoverPruned: (count, megabytes) => `已删除 ${count} 条没有语句使用的配音缓存(${megabytes} MB)`,
292
+ voiceoverLeft: (missing, blocked) => `仍有 ${missing + blocked} 句没有配音。`,
293
+ speechUsage: 'presmium speech 的命令是 key set、key clear 与 key status,例如 presmium speech key status。',
294
+ speechKeyLabels: { workspace: '工作区', key: '语音密钥', file: '文件' },
295
+ speechKeySaved: appId => `已配置,保存在本机${appId ? '(带 App ID)' : ''};服务权限在生成配音时验证`,
296
+ speechKeyEnvironment: variable => `已配置,来自环境变量 ${variable}`,
297
+ speechKeyNone: variable => `未配置;用 presmium speech key set 保存,或设置环境变量 ${variable}`,
298
+ speechKeyPrompt: '火山引擎的语音 API Key(输入时不显示):',
299
+ speechKeyCancelled: '已取消,没有保存密钥。',
300
+ speechKeyEmpty: '没有读到密钥。请在提示后输入,或从标准输入传入,例如 presmium speech key set < key.txt。',
301
+ speechKeyStored: file => `已保存火山引擎的语音密钥:${file}。正在运行的 Presmium Studio 与 presmium serve 无需重启。`,
302
+ speechKeyCleared: '已清除本机保存的密钥。',
303
+ speechKeyClearedEnvironment: variable => `已清除本机保存的密钥;现在使用环境变量 ${variable} 中的密钥。`,
304
+ speechKeyErrors: {
305
+ 'speech-settings-conflict': () => '语音服务设置已在别处更新。请重新运行。',
306
+ 'speech-settings-invalid': () => '密钥无效:需要 8 到 8192 个可见字符,不含空格。',
307
+ 'speech-settings-busy': () => '语音服务设置正在被更新。请稍后重试。',
308
+ 'speech-settings-unavailable': file => `无法读取或写入语音服务设置:${file}`,
309
+ },
310
+ scriptUsage: '用法:presmium script export <文稿> [--out <文件>],或 presmium script import <文稿> [<文件>]。',
311
+ scriptInstructions: '讲稿:字幕与配音都由它生成。只改每段文字,不改每段上面的 n: 标记行;一段到下一个标记行或标题为止,其中的换行与空行原样写回。显示与读法不同的词写作 {显示|读法},⟦cue:…⟧ 是提示点,留在原来的段落中;作为文字的 \\、{、}、⟦、⟧(在 {显示|读法} 中还有 |)前面加 \\。改完运行 presmium script import <文稿>。',
312
+ scriptExported: (file, narrations, steps) => `已写出 ${steps} 个步骤的 ${narrations} 段讲稿:${file}`,
313
+ scriptUnchanged: '讲稿没有改动,文稿保持不变。',
314
+ scriptImported: changed => `已更新 ${[changed].flat().length} 段讲稿:${list(changed, '、')}`,
315
+ scriptNext: document => `配音按新讲稿重新生成:presmium voiceover ${document}`,
316
+ scriptErrors: {
317
+ 'script-duplicate': (detail, line) => `第 ${line} 行:标记 n: ${list(detail, '')} 出现了两次。每段讲稿只有一个标记。`,
318
+ 'script-stray': (detail, line) => `第 ${line} 行:“${list(detail, '')}”不在任何 n: 标记之下。讲稿写在它的标记行下面。`,
319
+ 'script-unknown': (detail, line) => `第 ${line} 行:文稿中没有 n: ${list(detail, '、')} 这些标记对应的讲稿。请从 presmium script export 写出的文件开始修改。`,
320
+ 'script-missing': detail => `文件中缺少 n: ${list(detail, '、')} 这些标记。不要删除标记行;删除讲稿请在 Presmium Studio 中进行。`,
321
+ 'script-empty': (detail, line) => `第 ${line} 行:讲稿 ${list(detail, '')} 是空的。这里不能删除一段讲稿。`,
322
+ 'script-cue-unknown': detail => `讲稿 ${[detail].flat()[0]} 中没有提示点 ⟦cue:${[detail].flat()[1]}⟧。提示点只能在原来的段落中移动,不能新增或移到别的段落。`,
323
+ 'script-cue-repeated': detail => `讲稿 ${[detail].flat()[0]} 中提示点 ⟦cue:${[detail].flat()[1]}⟧ 出现了两次。`,
324
+ 'script-cue-removed': detail => `讲稿 ${[detail].flat()[0]} 删除了提示点 ${[detail].flat().slice(1).map(cue => `⟦cue:${cue}⟧`).join('、')}。请把它们留在文字中。`,
325
+ 'script-node': detail => `讲稿中有不能写入文件的内容(${list(detail, '')})。`,
326
+ },
128
327
  },
129
328
  'en': {
130
329
  usage: `Usage: presmium <command> [deck] [options]
@@ -141,6 +340,7 @@ Commands:
141
340
  skills install bundled skills, shared with MCP and the visual editor
142
341
  install <dir> [--json] install missing .agents/skills; keep existing skills
143
342
  --name <skill> install only the named skill; repeat for more
343
+ --update replace the existing skills with this version's (after upgrading Presmium)
144
344
  --json print the installation result as JSON
145
345
  build export the deck: writes <out>/ir.json and <out>/<renderer>/; at a workspace root
146
346
  (presmium.workspace.yaml) exports the workspace as a website into <out>/web/
@@ -155,12 +355,52 @@ Commands:
155
355
  --allow <kinds> approvals given without asking: operate, spend, write, agent
156
356
  ir print the runtime snapshot as JSON
157
357
  --out <file> write it to a file instead
358
+ import Markdown notes to documents (the argument is a .md file or a folder): each note becomes
359
+ <out>/<path>/${DOCUMENT_ENTRY}, a page for each level-1 and level-2 heading; [[note]] and
360
+ [[note|text]] find their document by file name or the aliases of the frontmatter, and
361
+ the local files a note links to are copied into the document's attachments/; importing
362
+ again overwrites the documents it wrote
363
+ --out <dir> write there (default: ., usually the workspace root)
364
+ --exclude <name> (repeatable) a folder or file, * allowed, whose notes are not imported
365
+ and whose files are not copied, e.g. raw
366
+ --lang <tag> the language of notes whose frontmatter has no lang (default: from the text)
367
+ --group <n> make the note's folder at depth n the document's first tag; the site's
368
+ sidebar groups documents by it, e.g. --group 2 groups projects/<project>/
158
369
  check check the deck and run the plugins’ checks
159
370
  --json print the result as JSON
160
371
  --update-lock re-resolve anchors and rewrite .presmium/anchors.lock.json
161
372
  --env also connect to the environments of execute.environments
162
373
  --audience <name> check the content for this audience
163
374
  --external-links also check the external links, with lychee when it is installed
375
+ voiceover the document’s voiceover. Without --yes it only reports what it would do: the voice
376
+ service, the voice, and the sentences and characters without voiceover (a cloud service
377
+ charges by the character); it generates nothing and changes no file. With --yes it generates
378
+ the missing voiceover through the same execution as Presmium Studio, without a running
379
+ service. Voice services and keys are read as presmium serve reads them (the workspace’s
380
+ operator directory, PRESMIUM_SPEECH_* variables)
381
+ --voice <service>:<voice> first make it the document’s default voice, e.g.
382
+ volcengine:zh_female_tianmeitaozi_uranus_bigtts
383
+ --yes go ahead: generate (a voice service may charge for it) and write the changes of
384
+ --voice and --prune
385
+ --prune delete the voiceover cache that no sentence of the script uses (the files in
386
+ .presmium/speech/ and their speech.lock.json entries)
387
+ --json print the result as JSON
388
+ script the script as one Markdown file to polish, and back into the document
389
+ export <deck> write each step’s script: each paragraph below its marker line <!-- n: … --> with
390
+ its line breaks and blank lines, {shown|spoken} for a word shown one way and said
391
+ another, ⟦cue:…⟧ for a cue, and \\ before a \\, {, }, ⟦ or ⟧ meant as text
392
+ (and before a | inside {…|…})
393
+ import <deck> [<file>] write the edited paragraphs back into lecture.json, changing only those;
394
+ nothing is written when a marker is missing or unknown, or a cue was removed
395
+ or moved to another paragraph
396
+ --out <file> where export writes (default: <deck>/dist/script.md, which import reads by default)
397
+ speech voice service settings
398
+ key set [<dir>] read a Volcengine speech API key from standard input (not echoed) and save it
399
+ in the workspace’s operator directory, the file of Presmium Studio’s
400
+ Settings → Voice Service
401
+ key clear [<dir>] clear the saved key
402
+ key status [<dir>] whether a key is configured and where it comes from, never the key; set the
403
+ operator directory with PRESMIUM_OPERATOR_DIR
164
404
  serve the workspace service for you on this machine (the argument is the workspace root, or
165
405
  a deck): the workspace site, the documents and their history, the reviews, the plugins’
166
406
  routes, and the classroom sync; without --host it listens on this machine only
@@ -175,9 +415,14 @@ Commands:
175
415
  --public-url <url> the address browsers use when a reverse proxy fronts the service: its
176
416
  host is trusted, and previews and outputs are linked under it; with a path, the
177
417
  proxy forwards that path unchanged and everything the service serves is below it
418
+ --allow <kinds> approvals given without asking: operate, spend, write, agent (by default
419
+ they are asked in an open Presmium window)
420
+ mcp MCP on stdio for AI tools such as Claude Code and Codex: relays to the running Presmium
421
+ Studio or presmium serve of the directory, where the AI can edit documents; otherwise it
422
+ compiles the document for reading, checking and exporting. See presmium mcp --help
178
423
  studio Presmium Studio (experimental): the editing app in the browser and the workspace service
179
- of the directory (the workspace root, or a deck); prints the one address to open. It is
180
- the package @lincyaw/studio (about 865 MB), installed beside this one
424
+ of the directory (the workspace root, or a deck); prints the one address to open.
425
+ Included with Presmium
181
426
  --port <n> Presmium Studio’s port (default: 4320, or a free one when that is in use)
182
427
  --host <addr> listen on this address of the machine on the local network instead of
183
428
  127.0.0.1, with no login: whoever reaches the port works as you
@@ -202,10 +447,10 @@ Exit Codes: 0 no errors, 1 error findings, 2 usage or internal error.`,
202
447
  compiled: (sections, summary) => `compiled ${sections} sections; ${summary}`,
203
448
  token: file => ` (its token is in ${file})`,
204
449
  watching: ir => `watching; runtime snapshot in ${ir}`,
205
- noFfmpeg: command => `presmium serve: FFmpeg was not found, so lecture videos export from the browser as WebM, at a lower quality. Install it for sharp MP4 videos: ${command}`,
206
450
  serveOpen: (address, port) => `presmium serve: listening on ${address}, on the local network, with no login: anyone who reaches port ${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.`,
207
451
  newMissing: 'presmium new: create-presmium is not installed. It comes with the presmium package: run pnpm add -g @lincyaw/presmium.',
208
- studioMissing: 'presmium studio: Presmium Studio is not installed here (experimental, about 865 MB). Run pnpm add -g @lincyaw/studio, then presmium-studio; or run pnpm add -D @lincyaw/studio in this project.',
452
+ studioMissing: 'presmium studio: Presmium Studio is not installed. It comes with Presmium: run pnpm add -g @lincyaw/presmium.',
453
+ mcpMissing: 'presmium mcp: @lincyaw/mcp is not installed. It comes with Presmium: run pnpm add -g @lincyaw/presmium.',
209
454
  noProblems: 'no problems',
210
455
  counts: (errors, warnings, infos) => `${errors} errors, ${warnings} warnings, ${infos} infos`,
211
456
  severity: { error: 'error', warning: 'warning', info: 'info' },
@@ -214,6 +459,102 @@ Exit Codes: 0 no errors, 1 error findings, 2 usage or internal error.`,
214
459
  documentRuns: (executed, cached) => ` (code runs: ${executed} executed, ${cached} from cache)`,
215
460
  notRendered: blocks => ` (${blocks} blocks not rendered)`,
216
461
  codeRuns: (executed, cached, sandbox) => `code runs: ${executed} executed, ${cached} from cache${sandbox ? `, isolated by ${sandbox}` : ''}`,
462
+ badGroup: value => `--group needs a whole number of 1 or more, not “${value}”.`,
463
+ importMissing: 'No notes to import. Give a .md file or a folder, for example presmium import notes --out site.',
464
+ imported: (documents, files, out) => `imported ${documents} documents and copied ${files} files into ${out}`,
465
+ importUnresolved: (note, link) => `${note}: the link ${link} leads to no note or file; it is plain text now`,
466
+ importPatterns: patterns => `the documents of presmium.workspace.yaml need:\n${patterns.map(pattern => ` - '${pattern}'`).join('\n')}`,
467
+ badVoice: value => `--voice takes “<service>:<voice>”, such as volcengine:zh_female_tianmeitaozi_uranus_bigtts, not “${value}”.`,
468
+ documentChanged: 'The document changed after it was read, so nothing was written. Run the command again.',
469
+ documentInvalid: detail => `The changed document is not valid, so nothing was written: ${detail}`,
470
+ voiceoverUnavailable: 'This document can’t generate voiceover: its plugins need @lincyaw/addon-lecture and @lincyaw/addon-speech (enabling video production in Presmium Studio adds them).',
471
+ voiceoverLabels: { document: 'document', voice: 'voice', service: 'voice service', sentences: 'sentences', missing: 'to generate', blocked: 'unavailable', prune: 'unused audio' },
472
+ voiceoverPlace: (page, step) => `page ${page}, step ${step}`,
473
+ voiceoverReasons: {
474
+ 'voice-unset': 'no voice is set',
475
+ 'cue-step': 'the script moves to the next step while this page sets voices per step',
476
+ 'voice-step-binding-unavailable': 'the steps of the script changed; check the voice settings again',
477
+ 'step-binding-stale': 'the steps of the script changed; check the voice settings again',
478
+ 'speech-unavailable': 'the document has no voice service plugin',
479
+ 'voice-not-configured': 'no voice service is configured',
480
+ 'voice-engine-unknown': 'this voice service is not configured',
481
+ 'voice-engine-unsupported': 'this voice service can’t generate voiceover',
482
+ 'voice-catalog-unavailable': 'couldn’t read the voice service’s list of voices',
483
+ 'voice-unavailable': 'the voice service has no such voice for the document’s language',
484
+ 'voice-revision-changed': 'the document changed',
485
+ 'voice-source-changed': 'the document changed',
486
+ 'speech-authentication': 'the voice service rejected the key; update it with presmium speech key set',
487
+ 'speech-permission': 'the voice service denied access: check that speech synthesis 2.0 is enabled and the key’s service and voice permissions',
488
+ 'speech-quota': 'the voice service has insufficient credit or quota',
489
+ 'speech-busy': 'the voice service is at its concurrency limit; try again shortly',
490
+ 'speech-network': 'couldn’t connect to the voice service',
491
+ 'speech-empty-audio': 'the voice service returned no audio',
492
+ 'speech-invalid-request': 'the voice service rejected this script or the voice parameters',
493
+ 'speech-provider': 'the voice service can’t generate voiceover right now',
494
+ 'speech-cache-failed': 'couldn’t write the voiceover cache; check disk space and directory permissions',
495
+ },
496
+ voiceoverReasonOther: code => `another reason (${code})`,
497
+ voiceoverNoVoice: 'no voiceover',
498
+ voiceoverUnset: 'not set',
499
+ voiceoverVoiceChange: (next, previous) => `${next} (to become the document’s default voice instead of ${previous})`,
500
+ voiceoverVoiceDefault: voice => `${voice} (the document’s default voice)`,
501
+ voiceoverService: (id, provider, local) => `${id} (${provider}, ${local ? 'on this machine' : 'cloud'})`,
502
+ voiceoverServiceMissing: id => `${id} (not configured)`,
503
+ voiceoverCounts: (total, cached, missing, skipped, blocked) => `${total}: ${cached} with voiceover, ${missing} to generate${skipped ? `, ${skipped} silent or recorded` : ''}${blocked ? `, ${blocked} unavailable` : ''}`,
504
+ voiceoverMissing: (count, characters, voices) => `${sentences(count)}, about ${characters} characters, voice ${list(voices, ', ')}`,
505
+ voiceoverCharges: providers => `A cloud voice service charges by the character (${list(providers, ', ')}); the voiceover is AI-generated.`,
506
+ voiceoverLocal: 'Generated on this machine; the voiceover is AI-generated.',
507
+ voiceoverBlocked: (count, reason, places, more) => `${count}: ${reason} (${list(places, '; ')}${more ? '; …' : ''})`,
508
+ voiceoverPruneErrors: 'The document has errors, so the voiceover cache was not cleaned: some of the script may not have been read. Check and fix it with presmium check first.',
509
+ voiceoverPruneUnavailable: 'The document’s voice service plugin can’t clean the voiceover cache. Update Presmium.',
510
+ voiceoverPruneEngineUnknown: 'Some sentences name no voice service and no default one is configured, so the audio in use can’t be told apart; nothing was cleaned.',
511
+ voiceoverPruneWould: (count, megabytes, kept) => `${entries(count)} no sentence uses (${megabytes} MB); ${kept} kept`,
512
+ voiceoverDryRun: 'This is a preview: no voiceover was generated and no file changed. Add --yes to go ahead.',
513
+ voiceoverNothing: 'Every sentence has its voiceover; there is nothing to do.',
514
+ voiceoverNothingElse: 'The other sentences have their voiceover.',
515
+ voiceoverVoiceRefused: (voice, reason) => `The default voice was not set to ${voice}: ${reason}.`,
516
+ voiceoverVoiceSaved: voice => `the document’s default voice is now ${voice}`,
517
+ voiceoverGenerating: (done, total) => `Generating voiceover ${done} of ${total}`,
518
+ voiceoverCancelled: generated => `Canceled; the ${sentences(generated)} generated so far are kept.`,
519
+ voiceoverStale: generated => `The document changed while generating, so it stopped; the ${sentences(generated)} generated so far are kept.`,
520
+ voiceoverGenerated: generated => `Completed: ${sentences(generated)} generated`,
521
+ voiceoverRunError: reason => `Generation failed: ${reason}`,
522
+ voiceoverPruned: (count, megabytes) => `deleted ${entries(count)} no sentence uses (${megabytes} MB)`,
523
+ voiceoverLeft: (missing, blocked) => `${missing + blocked === 1 ? '1 sentence still has' : `${missing + blocked} sentences still have`} no voiceover.`,
524
+ speechUsage: 'The commands of presmium speech are key set, key clear, and key status, for example presmium speech key status.',
525
+ speechKeyLabels: { workspace: 'workspace', key: 'speech key', file: 'file' },
526
+ speechKeySaved: appId => `configured, saved on this machine${appId ? ' with an App ID' : ''}; service permissions are verified when voiceover is generated`,
527
+ speechKeyEnvironment: variable => `configured, from the environment variable ${variable}`,
528
+ speechKeyNone: variable => `not configured; save one with presmium speech key set, or set the environment variable ${variable}`,
529
+ speechKeyPrompt: 'Volcengine speech API key (not shown as you type): ',
530
+ speechKeyCancelled: 'Canceled; no key was saved.',
531
+ speechKeyEmpty: 'No key was read. Type it at the prompt, or pass it on standard input, for example presmium speech key set < key.txt.',
532
+ speechKeyStored: file => `saved the Volcengine speech key in ${file}. A running Presmium Studio or presmium serve uses it without a restart.`,
533
+ speechKeyCleared: 'cleared the key saved on this machine',
534
+ speechKeyClearedEnvironment: variable => `cleared the key saved on this machine; the key in the environment variable ${variable} is used now`,
535
+ speechKeyErrors: {
536
+ 'speech-settings-conflict': () => 'The voice service settings changed elsewhere. Run the command again.',
537
+ 'speech-settings-invalid': () => 'The key is not valid: it takes 8 to 8192 visible characters without spaces.',
538
+ 'speech-settings-busy': () => 'The voice service settings are being updated. Try again shortly.',
539
+ 'speech-settings-unavailable': file => `Couldn’t read or write the voice service settings: ${file}`,
540
+ },
541
+ scriptUsage: 'Usage: presmium script export <document> [--out <file>], or presmium script import <document> [<file>].',
542
+ scriptInstructions: 'Script: the captions and the voiceover are made from it. Edit only the paragraphs; keep the n: line above each. A paragraph runs to the next n: line or heading, and its line breaks and blank lines are kept. A word shown one way and said another is written {shown|spoken}; ⟦cue:…⟧ marks a cue and stays in its paragraph. Put \\ before a \\, {, }, ⟦ or ⟧ meant as text (and before a | inside {shown|spoken}). Then run presmium script import <document>.',
543
+ scriptExported: (file, narrations, steps) => `wrote the script of ${steps} steps (${narrations} paragraphs) to ${file}`,
544
+ scriptUnchanged: 'The script has no changes; the document is unchanged.',
545
+ scriptImported: changed => `updated ${[changed].flat().length} ${[changed].flat().length === 1 ? 'paragraph' : 'paragraphs'} of the script: ${list(changed, ', ')}`,
546
+ scriptNext: document => `regenerate the voiceover for the new script: presmium voiceover ${document}`,
547
+ scriptErrors: {
548
+ 'script-duplicate': (detail, line) => `line ${line}: the marker n: ${list(detail, '')} appears twice. Each paragraph has one marker.`,
549
+ 'script-stray': (detail, line) => `line ${line}: “${list(detail, '')}” is under no n: marker. Write the script below its marker line.`,
550
+ 'script-unknown': (detail, line) => `line ${line}: the document has no script for the markers n: ${list(detail, ', ')}. Start from the file presmium script export writes.`,
551
+ 'script-missing': detail => `The file lacks the markers n: ${list(detail, ', ')}. Keep every marker line; delete script in Presmium Studio.`,
552
+ 'script-empty': (detail, line) => `line ${line}: the script ${list(detail, '')} is empty; a paragraph can’t be removed here.`,
553
+ 'script-cue-unknown': detail => `The script ${[detail].flat()[0]} has no cue ⟦cue:${[detail].flat()[1]}⟧. A cue can move only within its paragraph; it can’t be added or moved to another one.`,
554
+ 'script-cue-repeated': detail => `The cue ⟦cue:${[detail].flat()[1]}⟧ appears twice in the script ${[detail].flat()[0]}.`,
555
+ 'script-cue-removed': detail => `The script ${[detail].flat()[0]} lost the cues ${[detail].flat().slice(1).map(cue => `⟦cue:${cue}⟧`).join(', ')}. Keep them in the text.`,
556
+ 'script-node': detail => `The script holds content that can’t be written to the file (${list(detail, '')}).`,
557
+ },
217
558
  },
218
559
  }
219
560
 
package/src/script.ts ADDED
@@ -0,0 +1,152 @@
1
+ import type { NarrationNode, TeachingDocument } from '@lincyaw/kernel'
2
+
3
+ // The narration of a document as one Markdown file to polish, and back; lecture.json stays the only source. Each step
4
+ // is a heading; under it each narration follows its marker line `<!-- n: <narration> -->` up to the next marker or
5
+ // heading. Each line break of a narration starts a new line of the file, and a blank line stands for a blank line
6
+ // (`\n\n`; several read back as one).
7
+ // A word shown one way and spoken another is `{shown|spoken}`, a cue `⟦cue:<id>⟧`; a backslash before `\`, `{`, `}`,
8
+ // `|`, `⟦` or `⟧` keeps that character as text, and a line that would read as a heading or a comment starts with one.
9
+
10
+ export class ScriptError extends Error {
11
+ readonly code: 'script-duplicate' | 'script-stray' | 'script-unknown' | 'script-missing' | 'script-empty' | 'script-cue-unknown' | 'script-cue-repeated' | 'script-cue-removed' | 'script-node'
12
+ readonly detail: string[]
13
+ readonly line?: number
14
+ constructor(code: ScriptError['code'], detail: string[], line?: number) {
15
+ super(code)
16
+ this.code = code
17
+ this.detail = detail
18
+ if (line !== undefined) this.line = line
19
+ }
20
+ }
21
+
22
+ const MARKER = /^<!-- n: (\S+) -->$/
23
+ const HEADING = /^#{1,6}(?:\s|$)/
24
+ const COMMENT = /^<!--[\s\S]*-->$/
25
+ // An escaped character, a pronunciation (its parts may hold escaped characters) or a cue; anything else is text.
26
+ const TOKEN = /\\([\\{}|⟦⟧#<])|\{((?:\\[\s\S]|[^\\{}|])+)\|((?:\\[\s\S]|[^\\{}])+)\}|⟦cue:([^⟧]+)⟧/g
27
+
28
+ const escaped = (text: string, special: RegExp) => text.replace(special, '\\$&')
29
+ const unescaped = (text: string) => text.replace(/\\([\\{}|⟦⟧#<])/g, '$1')
30
+
31
+ /** A narration's content as the lines of the file: escaped, trimmed, a line that reads as a heading or comment marked. */
32
+ export function scriptLines(content: NarrationNode[]): string[] {
33
+ return content.map((node) => {
34
+ if (node.type === 'text') return escaped(node.text, /[\\{}⟦⟧]/g)
35
+ if (node.type === 'pronunciation') return `{${escaped(node.display, /[\\{}|⟦⟧]/g)}|${escaped(node.spoken, /[\\{}|⟦⟧]/g)}}`
36
+ if (node.type === 'cue') return `⟦cue:${node.id}⟧`
37
+ throw new ScriptError('script-node', [(node as { type: string }).type])
38
+ }).join('').split('\n').map(line => line.trim()).map(line => /^(?:#|<!--)/.test(line) ? `\\${line}` : line)
39
+ }
40
+
41
+ /** A narration's lines read back: joined by line breaks, a run of blank lines one blank line, none at either end. */
42
+ function linesToText(lines: readonly string[]): string {
43
+ return lines.join('\n').replace(/\n{3,}/g, '\n\n').replace(/^\n+|\n+$/g, '')
44
+ }
45
+
46
+ /** The narrated steps in reading order, each with the narrations it is the first to say (a shared one is listed once). */
47
+ export function narratedSteps(document: TeachingDocument): { section: string, title: string, step: string, stepTitle: string, narrations: string[] }[] {
48
+ const seen = new Set<string>()
49
+ return document.sectionOrder.flatMap(sectionId => {
50
+ const section = document.sections[sectionId]!
51
+ return section.stepOrder.flatMap(stepId => {
52
+ const step = document.steps[stepId]!
53
+ const narrations = step.narrationIds.filter(id => document.narrations[id] && !seen.has(id))
54
+ for (const id of narrations) seen.add(id)
55
+ return narrations.length ? [{ section: sectionId, title: section.title || sectionId, step: stepId, stepTitle: step.title || stepId, narrations }] : []
56
+ })
57
+ })
58
+ }
59
+
60
+ export function exportScript(document: TeachingDocument, instructions: string): { text: string, steps: number, narrations: number } {
61
+ const steps = narratedSteps(document)
62
+ const parts = [`# ${document.metadata.title}`, '', `<!-- ${instructions} -->`, '']
63
+ let page: string | undefined
64
+ for (const step of steps) {
65
+ if (step.section !== page) { parts.push(`## ${step.title}`, ''); page = step.section }
66
+ parts.push(`### ${step.stepTitle}`, '')
67
+ for (const id of step.narrations) {
68
+ parts.push(`<!-- n: ${id} -->`, ...scriptLines(document.narrations[id]!.content), '')
69
+ }
70
+ }
71
+ return { text: parts.join('\n'), steps: steps.length, narrations: steps.reduce((n, step) => n + step.narrations.length, 0) }
72
+ }
73
+
74
+ /** The narration below each marker; text outside a narration (under a heading, before the first marker) is refused. */
75
+ export function readScript(text: string): Map<string, { body: string, line: number }> {
76
+ const found = new Map<string, { body: string, line: number }>()
77
+ let current: { id: string, line: number, lines: string[] } | undefined
78
+ const close = () => { if (current) found.set(current.id, { body: linesToText(current.lines), line: current.line }); current = undefined }
79
+ const lines = text.replace(/\r\n/g, '\n').split('\n')
80
+ lines.forEach((raw, index) => {
81
+ const line = raw.trim()
82
+ const marker = MARKER.exec(line)
83
+ if (marker) {
84
+ close()
85
+ if (found.has(marker[1]!)) throw new ScriptError('script-duplicate', [marker[1]!], index + 1)
86
+ current = { id: marker[1]!, line: index + 1, lines: [] }
87
+ } else if (HEADING.test(line)) close()
88
+ else if (COMMENT.test(line)) return
89
+ else if (!line) current?.lines.push(line)
90
+ else if (!current) throw new ScriptError('script-stray', [line.slice(0, 40)], index + 1)
91
+ else current.lines.push(line)
92
+ })
93
+ close()
94
+ return found
95
+ }
96
+
97
+ /** One edited narration back to its content; cues are taken from the narration it came from. */
98
+ function contentOf(id: string, text: string, before: NarrationNode[]): NarrationNode[] {
99
+ const cues = new Map(before.flatMap(node => node.type === 'cue' ? [[node.id, node] as const] : []))
100
+ const used = new Set<string>()
101
+ const nodes: NarrationNode[] = []
102
+ const plain = (value: string) => {
103
+ if (!value) return
104
+ const last = nodes.at(-1)
105
+ if (last?.type === 'text') last.text += value
106
+ else nodes.push({ type: 'text', text: value })
107
+ }
108
+ let from = 0
109
+ for (const match of text.matchAll(TOKEN)) {
110
+ plain(text.slice(from, match.index))
111
+ from = match.index + match[0].length
112
+ const [, character, display, spoken, cue] = match
113
+ if (character) plain(character)
114
+ else if (display !== undefined && spoken !== undefined) nodes.push({ type: 'pronunciation', display: unescaped(display), spoken: unescaped(spoken) })
115
+ else if (cue) {
116
+ if (used.has(cue)) throw new ScriptError('script-cue-repeated', [id, cue])
117
+ const known = cues.get(cue)
118
+ if (!known) throw new ScriptError('script-cue-unknown', [id, cue])
119
+ nodes.push(structuredClone(known))
120
+ used.add(cue)
121
+ }
122
+ }
123
+ plain(text.slice(from))
124
+ const removed = [...cues.keys()].filter(cue => !used.has(cue))
125
+ if (removed.length) throw new ScriptError('script-cue-removed', [id, ...removed])
126
+ return nodes
127
+ }
128
+
129
+ /**
130
+ * Applies the file to the document: every narrated step's markers must be there exactly once; only the narrations whose
131
+ * text differs from what an untouched export reads back as are changed. Returns the same document when nothing changed.
132
+ */
133
+ export function importScript(document: TeachingDocument, text: string): { document: TeachingDocument, changed: string[] } {
134
+ const found = readScript(text)
135
+ const expected = narratedSteps(document).flatMap(step => step.narrations)
136
+ const unknown = [...found.keys()].filter(id => !expected.includes(id))
137
+ if (unknown.length) throw new ScriptError('script-unknown', unknown, found.get(unknown[0]!)!.line)
138
+ const missing = expected.filter(id => !found.has(id))
139
+ if (missing.length) throw new ScriptError('script-missing', missing)
140
+ const changed: string[] = []
141
+ let narrations = document.narrations
142
+ for (const id of expected) {
143
+ const { body, line } = found.get(id)!
144
+ const before = document.narrations[id]!
145
+ if (linesToText(scriptLines(before.content)) === body) continue
146
+ if (!body) throw new ScriptError('script-empty', [id], line)
147
+ if (narrations === document.narrations) narrations = { ...narrations }
148
+ narrations[id] = { ...before, content: contentOf(id, body, before.content) }
149
+ changed.push(id)
150
+ }
151
+ return { document: changed.length ? { ...document, narrations } : document, changed }
152
+ }