@lincyaw/workspace 1.0.0-rc.5 → 1.0.0-rc.51

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.
@@ -0,0 +1,356 @@
1
+ import { mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
2
+ import { basename, join } from 'node:path'
3
+ import { CAPTIONS_PARAM, CAPTURE_HOOK, CAPTURE_MAX_BOXES, CAPTURE_MAX_FRAMES, CAPTURE_MAX_HEIGHT, CAPTURE_MAX_OVERVIEW, CAPTURE_PARAM, CAPTURE_SHEET_SIZE, errorMessage, PREVIEW_APPEARANCE_PARAM, slideShape } from '@lincyaw/kernel'
4
+ import type { CapturedBox, CapturedSlide, CaptureHook, DocumentCapture, IRDocument, IRSection } from '@lincyaw/kernel'
5
+ import { playwrightChromium } from '@lincyaw/kernel/node'
6
+
7
+ /** What capturing uses of Playwright's Chromium. */
8
+ interface Page {
9
+ goto(url: string, options: { waitUntil: 'load', timeout: number }): Promise<unknown>
10
+ waitForFunction(script: string, arg: undefined, options: { timeout: number }): Promise<unknown>
11
+ evaluate<R, A>(run: (arg: A) => R | Promise<R>, arg: A): Promise<R>
12
+ screenshot(options: { type: 'png', fullPage?: boolean, clip?: { x: number, y: number, width: number, height: number } }): Promise<Buffer>
13
+ setViewportSize(size: { width: number, height: number }): Promise<void>
14
+ setContent(html: string, options: { waitUntil: 'load', timeout: number }): Promise<void>
15
+ on(event: 'pageerror', listener: (error: Error) => void): void
16
+ on(event: 'console', listener: (message: { type(): string, text(): string }) => void): void
17
+ }
18
+ interface Context {
19
+ newPage(): Promise<Page>
20
+ close(): Promise<void>
21
+ }
22
+ interface Browser {
23
+ newContext(options: { viewport: { width: number, height: number }, deviceScaleFactor: number, reducedMotion: 'reduce', colorScheme: 'light' | 'dark', serviceWorkers: 'block' }): Promise<Context>
24
+ close(): Promise<void>
25
+ }
26
+ interface Chromium { launch(): Promise<Browser> }
27
+
28
+ export interface CaptureOptions {
29
+ root: string
30
+ /** The service's own address. */
31
+ url(): string
32
+ /** The viewer page of a document once the page can show it (its path below the address), as previews open it. */
33
+ viewerPage(document: string): Promise<string | undefined>
34
+ /** The document's current runtime snapshot. */
35
+ compiled(document: string): Promise<IRDocument>
36
+ /** Where the pictures are written. */
37
+ dir: string
38
+ }
39
+
40
+ interface View { width: number, height: number, scale: number, appearance: 'light' | 'dark' }
41
+
42
+ const PAGE_MS = 120_000
43
+ const IDLE_MS = 120_000
44
+ const KEEP = 20
45
+ const FIT_ROUNDS = 3
46
+ const READING_WIDTH = 1280
47
+ const READING_HEIGHT = 900
48
+ const MIN_WIDTH = 320
49
+ const MAX_WIDTH = 2560
50
+ const THUMB_WIDTH = 320
51
+ const SHEET_GAP = 16
52
+
53
+ class CaptureError extends Error {
54
+ readonly status: number
55
+ readonly detail?: Record<string, unknown>
56
+ constructor(code: string, status: number, detail?: Record<string, unknown>) {
57
+ super(code)
58
+ this.status = status
59
+ if (detail) this.detail = detail
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Pictures of documents as readers see them, in a headless Chromium kept while it is used: the viewer page of a
65
+ * document, opened with `?capture`, is driven by its capture hook (a slide step by step and moment by moment, so that a
66
+ * picture is the same however often it is taken; a section of the reading page scrolled through and at rest). One request
67
+ * at a time; the pictures stay in `dir`, the last few requests.
68
+ */
69
+ export function createDocumentCapture(options: CaptureOptions): { service: DocumentCapture, close(): Promise<void> } {
70
+ let browser: Promise<Browser> | undefined
71
+ let idle: ReturnType<typeof setTimeout> | undefined
72
+ let queue: Promise<unknown> = Promise.resolve()
73
+ const launch = (): Promise<Browser> => {
74
+ clearTimeout(idle)
75
+ browser ??= playwrightChromium<Chromium>(options.root, import.meta.url).then(chromium => chromium.launch()).catch((error: unknown) => {
76
+ browser = undefined
77
+ throw new CaptureError('capture-browser-unavailable', 503, { reason: errorMessage(error) })
78
+ })
79
+ return browser
80
+ }
81
+ const release = () => {
82
+ clearTimeout(idle)
83
+ idle = setTimeout(() => void close(), IDLE_MS)
84
+ idle.unref?.()
85
+ }
86
+ const close = async () => {
87
+ clearTimeout(idle)
88
+ const open = browser
89
+ browser = undefined
90
+ await (await open?.catch(() => undefined))?.close().catch(() => undefined)
91
+ }
92
+
93
+ /** The section asked for, by id or by its number from 1. */
94
+ const sectionOf = (doc: IRDocument, asked: string) => {
95
+ const section = doc.sections.find(s => s.id === asked) ?? doc.sections[Number(asked) - 1]
96
+ if (!section) throw new CaptureError('capture-section-unknown', 404, { section: asked, sections: doc.sections.map(s => s.id) })
97
+ return section
98
+ }
99
+
100
+ /** The document's viewer page in a form, opened with its capture hook in a new context; `run` uses it, then it closes. */
101
+ const open = async <T>(document: string, form: 'web' | 'slides', view: View & { captions?: boolean }, signal: AbortSignal | undefined, run: (tab: Page, problems: Set<string>, out: string) => Promise<T>): Promise<T> => {
102
+ const page = await options.viewerPage(document).catch((error: unknown) => {
103
+ throw new CaptureError('capture-preview-failed', 409, { reason: errorMessage(error) })
104
+ })
105
+ if (!page) throw new CaptureError('capture-preview-failed', 409)
106
+ signal?.throwIfAborted()
107
+ const context = await (await launch()).newContext({ viewport: { width: view.width, height: view.height }, deviceScaleFactor: view.scale, reducedMotion: 'reduce', colorScheme: view.appearance, serviceWorkers: 'block' })
108
+ const problems = new Set<string>()
109
+ try {
110
+ const tab = await context.newPage()
111
+ tab.on('pageerror', error => problems.add(error.message))
112
+ tab.on('console', message => { if (message.type() === 'error') problems.add(message.text().slice(0, 500)) })
113
+ const address = new URL(page, options.url())
114
+ if (form === 'slides') address.searchParams.set('form', 'slides')
115
+ if (view.captions === false) address.searchParams.set(CAPTIONS_PARAM, 'off')
116
+ address.searchParams.set(CAPTURE_PARAM, '')
117
+ address.searchParams.set(PREVIEW_APPEARANCE_PARAM, view.appearance)
118
+ await tab.goto(address.href, { waitUntil: 'load', timeout: PAGE_MS })
119
+ await tab.waitForFunction(`Boolean(window.${CAPTURE_HOOK})`, undefined, { timeout: PAGE_MS })
120
+ const out = join(options.dir, `${new Date().toISOString().replace(/[:.]/g, '-')}-${process.pid}`)
121
+ mkdirSync(out, { recursive: true })
122
+ return await run(tab, problems, out)
123
+ } catch (error) {
124
+ if (error instanceof CaptureError || signal?.aborted) throw error
125
+ // A page that loads again while it is driven loses its hook: going back reloaded it.
126
+ if (/context was destroyed|because of a navigation/i.test(errorMessage(error))) throw new CaptureError('capture-page-reloaded', 409, { problems: [...problems] })
127
+ throw new CaptureError('capture-failed', 500, { reason: errorMessage(error), problems: [...problems] })
128
+ } finally {
129
+ await context.close().catch(() => undefined)
130
+ prune(options.dir)
131
+ }
132
+ }
133
+
134
+ const slides: DocumentCapture['slides'] = async (document, request, signal) => {
135
+ const doc = await options.compiled(document)
136
+ const section = sectionOf(doc, request.section)
137
+ const steps = request.steps ?? Array.from({ length: section.steps + 1 }, (_, step) => step)
138
+ const wrong = steps.find(step => !Number.isInteger(step) || step < 0 || step > section.steps)
139
+ if (wrong !== undefined) throw new CaptureError('capture-step-invalid', 400, { step: wrong, last: section.steps })
140
+ const arrive = request.arrive ?? 'direct'
141
+ // Reached backward, a step is at rest: moments apply to steps drawn directly.
142
+ const moments: (number | null)[] = request.at?.length && arrive === 'direct' ? request.at : [null]
143
+ if (moments.some(at => at !== null && (!Number.isFinite(at) || at < 0))) throw new CaptureError('capture-moment-invalid', 400)
144
+ const count = steps.length * moments.length
145
+ if (count === 0 || count > CAPTURE_MAX_FRAMES) throw new CaptureError('capture-too-many-frames', 400, { requested: count, max: CAPTURE_MAX_FRAMES })
146
+ const shape = slideShape(doc)
147
+ const scale = request.scale ?? 1
148
+ return await open(document, 'slides', { width: shape.width, height: shape.height, scale, appearance: request.appearance ?? 'light', captions: request.captions }, signal, async (tab, problems, out) => {
149
+ const show = (step: number, at: number | null, how: 'direct' | 'backward' = 'direct') => tab.evaluate(async ([hook, position]) => await (window as unknown as Record<string, CaptureHook>)[hook]!.show(position), [CAPTURE_HOOK, { section: section.id, step, arrive: how, ...at === null ? {} : { at } }] as const)
150
+ await fit(tab, shape, section.id, steps[0]!, () => show(steps[0]!, moments[0]!))
151
+ const frames: CapturedSlide[] = [], images: Uint8Array[] = []
152
+ for (const step of steps) {
153
+ for (const at of moments) {
154
+ signal?.throwIfAborted()
155
+ const shown = await show(step, at, arrive)
156
+ for (const problem of shown.problems) problems.add(problem)
157
+ const measured = await tab.evaluate(measure, { section: section.id, step, selector: request.measure ?? '', width: shape.width, max: CAPTURE_MAX_BOXES })
158
+ if (!measured) throw new CaptureError('capture-slide-missing', 500, { section: section.id, step })
159
+ const clip = request.clip
160
+ ? { x: measured.slide.x + request.clip.x * measured.slide.scale, y: measured.slide.y + request.clip.y * measured.slide.scale, width: request.clip.width * measured.slide.scale, height: request.clip.height * measured.slide.scale }
161
+ : { x: measured.slide.x, y: measured.slide.y, width: measured.slide.width, height: measured.slide.height }
162
+ const png = await tab.screenshot({ type: 'png', clip })
163
+ const file = join(out, `${section.id}-${step}${at === null ? '' : `-${at}ms`}${arrive === 'backward' ? '-backward' : ''}.png`)
164
+ writeFileSync(file, png)
165
+ images.push(png)
166
+ frames.push({ section: section.id, slide: section.index, step, at, file, narration: narrationOf(section, step), width: Math.round(clip.width * scale), height: Math.round(clip.height * scale), ...request.measure ? { boxes: measured.boxes } : {} })
167
+ }
168
+ }
169
+ return { document, shape: { width: shape.width, height: shape.height }, frames, problems: [...problems], images }
170
+ })
171
+ }
172
+
173
+ const reading: DocumentCapture['reading'] = async (document, request, signal) => {
174
+ const doc = await options.compiled(document)
175
+ const section = sectionOf(doc, request.section)
176
+ const width = Math.round(request.width ?? READING_WIDTH)
177
+ if (!Number.isFinite(width) || width < MIN_WIDTH || width > MAX_WIDTH) throw new CaptureError('capture-width-invalid', 400, { min: MIN_WIDTH, max: MAX_WIDTH })
178
+ const scale = request.scale ?? 1
179
+ return await open(document, 'web', { width, height: READING_HEIGHT, scale, appearance: request.appearance ?? 'light' }, signal, async (tab, problems, out) => {
180
+ const shown = await tab.evaluate(async ([hook, id]) => await (window as unknown as Record<string, CaptureHook>)[hook]!.read(id), [CAPTURE_HOOK, section.id] as const)
181
+ for (const problem of shown.problems) problems.add(problem)
182
+ const measured = await tab.evaluate(measureSection, { section: section.id, selector: request.measure ?? '', max: CAPTURE_MAX_BOXES })
183
+ if (!measured) throw new CaptureError('capture-slide-missing', 500, { section: section.id })
184
+ const height = Math.min(measured.height, CAPTURE_MAX_HEIGHT)
185
+ const png = await tab.screenshot({ type: 'png', fullPage: true, clip: { x: measured.x, y: measured.y, width: measured.width, height } })
186
+ const file = join(out, `${section.id}-reading-${width}.png`)
187
+ writeFileSync(file, png)
188
+ const frame = { section: section.id, file, width: Math.round(measured.width), height: Math.round(height), cut: measured.height > CAPTURE_MAX_HEIGHT, ...request.measure ? { boxes: measured.boxes } : {} }
189
+ return { document, width, frames: [frame], problems: [...problems], images: [png] }
190
+ })
191
+ }
192
+
193
+ const overview: DocumentCapture['overview'] = async (document, request, signal) => {
194
+ const doc = await options.compiled(document)
195
+ const every = request.steps === 'all'
196
+ const positions = doc.sections.flatMap(section => (every ? Array.from({ length: section.steps + 1 }, (_, step) => step) : [section.steps]).map(step => ({ section, step })))
197
+ if (positions.length === 0 || positions.length > CAPTURE_MAX_OVERVIEW) throw new CaptureError('capture-too-many-frames', 400, { requested: positions.length, max: CAPTURE_MAX_OVERVIEW })
198
+ const shape = slideShape(doc)
199
+ const appearance = request.appearance ?? 'light'
200
+ const columns = Math.max(1, Math.min(8, Math.round(request.columns ?? 4)))
201
+ return await open(document, 'slides', { width: shape.width, height: shape.height, scale: 1, appearance, captions: request.captions }, signal, async (tab, problems, out) => {
202
+ const show = (section: string, step: number) => tab.evaluate(async ([hook, position]) => await (window as unknown as Record<string, CaptureHook>)[hook]!.show(position), [CAPTURE_HOOK, { section, step }] as const)
203
+ const first = positions[0]!
204
+ await fit(tab, shape, first.section.id, first.step, () => show(first.section.id, first.step))
205
+ // Names that sort in reading order: the page number (from 1) and the step (from 0, as the tools count it) padded.
206
+ const pageWidth = String(doc.sections.length).length
207
+ const stepWidth = String(Math.max(...doc.sections.map(section => section.steps))).length
208
+ const frames: { section: string, slide: number, step: number, file: string, narration: string }[] = [], pictures: Buffer[] = []
209
+ for (const { section, step } of positions) {
210
+ signal?.throwIfAborted()
211
+ for (const problem of (await show(section.id, step)).problems) problems.add(problem)
212
+ const measured = await tab.evaluate(measure, { section: section.id, step, selector: '', width: shape.width, max: 0 })
213
+ if (!measured) throw new CaptureError('capture-slide-missing', 500, { section: section.id, step })
214
+ const png = await tab.screenshot({ type: 'png', clip: { x: measured.slide.x, y: measured.slide.y, width: measured.slide.width, height: measured.slide.height } })
215
+ const file = join(out, `${String(section.index).padStart(pageWidth, '0')}-${String(step).padStart(stepWidth, '0')}-${section.id}.png`)
216
+ writeFileSync(file, png)
217
+ frames.push({ section: section.id, slide: section.index, step, file, narration: narrationOf(section, step) })
218
+ pictures.push(png)
219
+ }
220
+ // Sheets of thumbnails, each labelled with its page, step and title, for reading the whole piece at a glance.
221
+ const sheets: string[] = [], images: Uint8Array[] = []
222
+ await tab.setViewportSize({ width: columns * (THUMB_WIDTH + SHEET_GAP) + SHEET_GAP, height: READING_HEIGHT })
223
+ for (let start = 0; start < frames.length; start += CAPTURE_SHEET_SIZE) {
224
+ signal?.throwIfAborted()
225
+ const cells = frames.slice(start, start + CAPTURE_SHEET_SIZE).map((frame, i) => ({ label: `${frame.slide} · ${frame.step} ${doc.sections[frame.slide - 1]?.title ?? ''}`, png: pictures[start + i]! }))
226
+ await tab.setContent(sheetHtml(cells, columns, appearance), { waitUntil: 'load', timeout: PAGE_MS })
227
+ const png = await tab.screenshot({ type: 'png', fullPage: true })
228
+ const file = join(out, `sheet-${String(sheets.length + 1).padStart(2, '0')}.png`)
229
+ writeFileSync(file, png)
230
+ sheets.push(file)
231
+ images.push(png)
232
+ }
233
+ // The narration beside the pictures, for a reader who looks at whole slides and reads the script as text.
234
+ const narrationFile = join(out, 'narration.md')
235
+ writeFileSync(narrationFile, frames.map(frame => `## ${basename(frame.file)}\n\n${frame.narration || '—'}\n`).join('\n'))
236
+ return { document, dir: out, frames, narrationFile, sheets, problems: [...problems], images }
237
+ })
238
+ }
239
+
240
+ /** One capture at a time; the browser closes when none came for a while. */
241
+ const queued = <A extends unknown[], R>(run: (...args: A) => Promise<R>) => (...args: A): Promise<R> => {
242
+ const next = queue.then(async () => {
243
+ try {
244
+ return await run(...args)
245
+ } finally {
246
+ release()
247
+ }
248
+ })
249
+ queue = next.catch(() => undefined)
250
+ return next
251
+ }
252
+
253
+ return {
254
+ service: { slides: queued(slides), reading: queued(reading), overview: queued(overview) },
255
+ close,
256
+ }
257
+ }
258
+
259
+ /**
260
+ * The page fits the slide in its window with a margin: the window is made that much larger, a few times, until the slide
261
+ * shows at its own size.
262
+ */
263
+ async function fit(tab: Page, shape: { width: number, height: number }, section: string, step: number, show: () => Promise<unknown>): Promise<void> {
264
+ let viewport = { width: shape.width, height: shape.height }
265
+ await show()
266
+ for (let round = 0; round < FIT_ROUNDS; round++) {
267
+ const fitted = await tab.evaluate(measure, { section, step, selector: '', width: shape.width, max: 0 })
268
+ if (!fitted || Math.abs(fitted.slide.scale - 1) < 0.005) return
269
+ viewport = { width: Math.round(viewport.width / fitted.slide.scale), height: Math.round(viewport.height / fitted.slide.scale) }
270
+ await tab.setViewportSize(viewport)
271
+ await show()
272
+ }
273
+ }
274
+
275
+ /** A step's narration as text: the script written for it, line by line. */
276
+ function narrationOf(section: IRSection, step: number): string {
277
+ const id = section.stepIds?.[step]
278
+ return (id ? section.stepNarrations?.[id] ?? [] : []).map(line => line.text).join('\n')
279
+ }
280
+
281
+ const escapeHtml = (text: string) => text.replace(/[&<>"]/g, char => `&#${char.charCodeAt(0)};`)
282
+
283
+ /** A sheet of thumbnails with their labels: plain HTML for the capturing browser, not a page of the product. */
284
+ function sheetHtml(cells: { label: string, png: Buffer }[], columns: number, appearance: 'light' | 'dark'): string {
285
+ const [paper, ink, line] = appearance === 'dark' ? ['#161614', '#ece9e2', '#3a3833'] : ['#f7f5f0', '#1c1b19', '#e3ded3']
286
+ return `<!doctype html><meta charset="utf-8"><style>
287
+ body { margin: 0; padding: ${SHEET_GAP}px; background: ${paper}; color: ${ink}; font: 13px/1.4 system-ui, sans-serif; }
288
+ main { display: grid; grid-template-columns: repeat(${columns}, ${THUMB_WIDTH}px); gap: ${SHEET_GAP}px; }
289
+ figure { margin: 0; } img { display: block; width: ${THUMB_WIDTH}px; border: 1px solid ${line}; }
290
+ figcaption { margin-top: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
291
+ </style><main>${cells.map(cell => `<figure><img src="data:image/png;base64,${cell.png.toString('base64')}"><figcaption>${escapeHtml(cell.label)}</figcaption></figure>`).join('')}</main>`
292
+ }
293
+
294
+ /** In the page: the slide shown at the step, in viewport pixels, and the boxes of `selector` in it, in slide pixels. */
295
+ function measure({ section, step, selector, width, max }: { section: string, step: number, selector: string, width: number, max: number }): { slide: { x: number, y: number, width: number, height: number, scale: number }, boxes: CapturedBox[] } | undefined {
296
+ const slides = [...document.querySelectorAll<HTMLElement>(`.pm-slide[data-section="${CSS.escape(section)}"]`)]
297
+ const slide = slides.find(element => element.dataset.step === String(step) && element.getBoundingClientRect().width > 0) ?? slides.find(element => element.getBoundingClientRect().width > 0)
298
+ if (!slide) return undefined
299
+ const frame = slide.getBoundingClientRect()
300
+ const scale = frame.width / width
301
+ const round = (value: number) => Math.round(value * 10) / 10
302
+ const boxes: CapturedBox[] = []
303
+ if (selector) {
304
+ for (const element of [...slide.querySelectorAll<HTMLElement>(selector)].slice(0, max)) {
305
+ const box = element.getBoundingClientRect()
306
+ const style = getComputedStyle(element)
307
+ const attributes: Record<string, string> = {}
308
+ for (const attribute of element.attributes) if (attribute.name === 'id' || attribute.name === 'class' || attribute.name.startsWith('data-')) attributes[attribute.name] = attribute.value.slice(0, 200)
309
+ boxes.push({
310
+ x: round((box.left - frame.left) / scale),
311
+ y: round((box.top - frame.top) / scale),
312
+ width: round(box.width / scale),
313
+ height: round(box.height / scale),
314
+ visible: box.width > 0 && box.height > 0 && style.visibility !== 'hidden' && style.display !== 'none' && Number(style.opacity) > 0,
315
+ text: (element.textContent ?? '').replace(/\s+/g, ' ').trim().slice(0, 80),
316
+ attributes,
317
+ })
318
+ }
319
+ }
320
+ return { slide: { x: frame.left, y: frame.top, width: frame.width, height: frame.height, scale }, boxes }
321
+ }
322
+
323
+ /** In the page: the section of the reading page, in page pixels, and the boxes of `selector` in it, relative to it. */
324
+ function measureSection({ section, selector, max }: { section: string, selector: string, max: number }): { x: number, y: number, width: number, height: number, boxes: CapturedBox[] } | undefined {
325
+ const element = document.querySelector<HTMLElement>(`section.pm-section[data-section="${CSS.escape(section)}"]`)
326
+ if (!element) return undefined
327
+ const frame = element.getBoundingClientRect()
328
+ const round = (value: number) => Math.round(value * 10) / 10
329
+ const boxes: CapturedBox[] = []
330
+ if (selector) {
331
+ for (const node of [...element.querySelectorAll<HTMLElement>(selector)].slice(0, max)) {
332
+ const box = node.getBoundingClientRect()
333
+ const style = getComputedStyle(node)
334
+ const attributes: Record<string, string> = {}
335
+ for (const attribute of node.attributes) if (attribute.name === 'id' || attribute.name === 'class' || attribute.name.startsWith('data-')) attributes[attribute.name] = attribute.value.slice(0, 200)
336
+ boxes.push({
337
+ x: round(box.left - frame.left),
338
+ y: round(box.top - frame.top),
339
+ width: round(box.width),
340
+ height: round(box.height),
341
+ visible: box.width > 0 && box.height > 0 && style.visibility !== 'hidden' && style.display !== 'none' && Number(style.opacity) > 0,
342
+ text: (node.textContent ?? '').replace(/\s+/g, ' ').trim().slice(0, 80),
343
+ attributes,
344
+ })
345
+ }
346
+ }
347
+ return { x: frame.left + window.scrollX, y: frame.top + window.scrollY, width: frame.width, height: frame.height, boxes }
348
+ }
349
+
350
+ /** Keeps the pictures of the last few requests. */
351
+ function prune(dir: string): void {
352
+ try {
353
+ const runs = readdirSync(dir).map(name => ({ path: join(dir, name), time: statSync(join(dir, name)).mtimeMs })).sort((a, b) => b.time - a.time)
354
+ for (const run of runs.slice(KEEP)) rmSync(run.path, { recursive: true, force: true })
355
+ } catch {}
356
+ }
@@ -125,6 +125,7 @@ export function readDocumentSummary(config: WorkspaceConfig, { dir, entry }: Doc
125
125
  ...typeof headmatter.description === 'string' && headmatter.description.trim() ? { description: headmatter.description.trim() } : {},
126
126
  ...typeof headmatter.lang === 'string' && headmatter.lang.trim() ? { lang: headmatter.lang.trim() } : {},
127
127
  ...tags.length > 0 ? { tags } : {},
128
+ ...isRecord(headmatter.renderers) && headmatter.renderers.slides !== undefined ? { slides: true } : {},
128
129
  }
129
130
  }
130
131
 
@@ -29,6 +29,33 @@ const binding = (current: ReturnType<typeof readAuthoringDocument>): CanonicalSo
29
29
  const titleOf = (name: string) => [...(name.replaceAll('\\', '/').split('/').at(-1) ?? '').replace(/[\u0000-\u001f\u007f-\u009f]/g, '').trim()].slice(0, ASSET_TITLE_MAX_LENGTH).join('')
30
30
  const stamp = (stat: Awaited<ReturnType<Awaited<ReturnType<typeof open>>['stat']>>) => [stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs].join(':')
31
31
 
32
+ /** Scoped bounded audio reads are shared by import, inspection and voice cloning. */
33
+ export async function readDocumentAudioBytes(editor: SourceEditor, ctx: RequestContext, path: string, signal?: AbortSignal, maxBytes = DOCUMENT_AUDIO_MAX_BYTES): Promise<Uint8Array> {
34
+ signal?.throwIfAborted()
35
+ const file = editor.readableFile({ document: ctx.document, home: false }, path, ctx.member)
36
+ const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK).catch(error => {
37
+ if (error.code === 'ELOOP') throw new RequestError(403, 'audio-file-path')
38
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') throw new RequestError(404, 'audio-file-missing')
39
+ throw error
40
+ })
41
+ try {
42
+ const before = await handle.stat(), named = await lstat(editor.readableFile({ document: ctx.document, home: false }, path, ctx.member))
43
+ if (!before.isFile() || before.dev !== named.dev || before.ino !== named.ino) throw new RequestError(403, 'audio-file-path')
44
+ if (!before.size || before.size > maxBytes) throw new RequestError(413, 'production.asset-size')
45
+ const bytes = new Uint8Array(before.size + 1); let length = 0
46
+ while (length < bytes.length) {
47
+ signal?.throwIfAborted()
48
+ const read = await handle.read(bytes, length, bytes.length - length, length)
49
+ if (!read.bytesRead) break
50
+ length += read.bytesRead
51
+ }
52
+ const after = await handle.stat(), current = await lstat(editor.readableFile({ document: ctx.document, home: false }, path, ctx.member))
53
+ if (length !== before.size || stamp(before) !== stamp(after) || after.dev !== current.dev || after.ino !== current.ino) throw new RequestError(409, 'audio-file-changed')
54
+ signal?.throwIfAborted()
55
+ return bytes.slice(0, length)
56
+ } finally { await handle.close() }
57
+ }
58
+
32
59
  /** Owns the canonical transaction and receipts; plugin services only inspect actual media. */
33
60
  export function createDocumentAudioAuthoring({ root, editor, revisions, audio, services, reviewRequired = false }: DocumentAudioAuthoringOptions): { service: DocumentAudioAuthoring, routes: Record<string, Route>, close(): Promise<void> } {
34
61
  const receipts = new Map<string, Receipt>(), imports = new Map<string, { signature: string, source: CanonicalSource, promise: Promise<VerifiedDocumentAudioImport> }>(), operations = new Set<Operation>()
@@ -64,31 +91,7 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
64
91
  editor.assertEditable(scopeOf(document), path, member)
65
92
  if (path.split('/').some(part => part.startsWith('.'))) throw new RequestError(403, 'audio-file-path')
66
93
  }
67
- const reader = async (ctx: RequestContext, path: string, signal?: AbortSignal): Promise<Uint8Array> => {
68
- signal?.throwIfAborted()
69
- const file = editor.readableFile(scopeOf(ctx.document), path, ctx.member)
70
- const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK).catch(error => {
71
- if (error.code === 'ELOOP') throw new RequestError(403, 'audio-file-path')
72
- if (error.code === 'ENOENT' || error.code === 'ENOTDIR') throw new RequestError(404, 'audio-file-missing')
73
- throw error
74
- })
75
- try {
76
- const before = await handle.stat(), named = await lstat(editor.readableFile(scopeOf(ctx.document), path, ctx.member))
77
- if (!before.isFile() || before.dev !== named.dev || before.ino !== named.ino) throw new RequestError(403, 'audio-file-path')
78
- if (!before.size || before.size > DOCUMENT_AUDIO_MAX_BYTES) throw new RequestError(413, 'production.asset-size')
79
- const bytes = new Uint8Array(before.size + 1); let length = 0
80
- while (length < bytes.length) {
81
- signal?.throwIfAborted()
82
- const read = await handle.read(bytes, length, bytes.length - length, length)
83
- if (!read.bytesRead) break
84
- length += read.bytesRead
85
- }
86
- const after = await handle.stat(), current = await lstat(editor.readableFile(scopeOf(ctx.document), path, ctx.member))
87
- if (length !== before.size || stamp(before) !== stamp(after) || after.dev !== current.dev || after.ino !== current.ino) throw new RequestError(409, 'audio-file-changed')
88
- signal?.throwIfAborted()
89
- return bytes.slice(0, length)
90
- } finally { await handle.close() }
91
- }
94
+ const reader = (ctx: RequestContext, path: string, signal?: AbortSignal) => readDocumentAudioBytes(editor, ctx, path, signal)
92
95
  const pathOf = (ctx: RequestContext, asset: Asset) => {
93
96
  const file = productionAssetFile(join(root, ctx.document), asset.location)
94
97
  if (!file) throw new RequestError(422, 'production.asset-path')
@@ -1,4 +1,5 @@
1
1
  import { createHash, randomUUID } from 'node:crypto'
2
+ import { isRecord } from '@lincyaw/kernel'
2
3
  import { applyDocumentOperations, AUTHORING_API_VERSION, createDocumentPage, DOCUMENT_ENTRY, DOCUMENT_OPERATION_TYPES, DOCUMENT_READ_MAX_REQUEST_CHARS, DOCUMENT_READ_MAX_RESPONSE_CHARS, DOCUMENT_SCHEMA_VERSION, documentOutline, documentPart, DocumentReadError, duplicateDocumentPage, fnv1a64, hasRole, moveDocumentPage, pageDeletionImpact, removeDocumentPage, renameDocumentPage, validateDocument } from '@lincyaw/kernel'
3
4
  import { validateDocumentChange, validateDocumentPageChange, validateDocumentPageChangeApply, validateDocumentPageDuplication, validateDocumentPageDuplicationApply, validateDocumentOutlineQuery, validateDocumentPartQuery } from '@lincyaw/kernel/node'
4
5
  import type { AppliedDocumentChange, ApplyDocumentChange, CanonicalSource, DocumentAnswer, DocumentAuthoring, DocumentChange, DocumentChangeAnswer, DocumentChangePlan, DocumentIssue, DocumentPageAction, DocumentPageChangePlan, DocumentPageDuplicationPlan, Member, RequestContext, SourceTransactionChange, TeachingDocument } from '@lincyaw/kernel'
@@ -133,7 +134,12 @@ export function createDocumentEditor({ editor, revisions, reviewRequired = false
133
134
  if (receipt) return { ...current, changeId: change.id, files: receipt.files, ...receipt.commit ? { commit: receipt.commit } : {} }
134
135
  const candidate = await filesOf(document, current, change)
135
136
  const ownHistory: SourceTransactionHistory | undefined = revisions ? { run: work => revisions.transaction(work), commit: (paths, lang) => revisions.commitWhileLocked({ paths, summary: lang?.startsWith('en') ? 'Edit document' : '编辑文稿', body: '', origin: { kind: origin, member } }) } : undefined
136
- const saved = await editor.transaction(editor.scope(document), candidate.changes, member, ownHistory)
137
+ const saved = await editor.transaction(editor.scope(document), candidate.changes, member, ownHistory).catch((error: unknown) => {
138
+ if (error instanceof RequestError && error.status === 409 && isRecord(error.detail?.conflict) && error.detail.conflict.path === entryOf(document)) {
139
+ throw new RequestError(409, 'document-version-changed', { version: error.detail.conflict.version })
140
+ }
141
+ throw error
142
+ })
137
143
  const version = saved.versions.find(file => file.path === entryOf(document))!.version
138
144
  remember(receipts, key, { signature, version, files: saved.versions, ...saved.revision ? { commit: saved.revision } : {} })
139
145
  const verified = await read(document, member)
@@ -1,6 +1,8 @@
1
- import { DOCUMENT_ENTRY, fnv1a64, hasRole, speechEngineId } from '@lincyaw/kernel'
2
- import type { CanonicalSource, DocumentVoiceAuthoring, Finding, Member, SpeechService, VoiceoverExecution, VoiceoverJob } from '@lincyaw/kernel'
3
- import { createVoiceoverOwner, createVoiceoverRoutes, validateDocumentVoiceCatalogQuery, validateVoicePreviewStart } from '@lincyaw/kernel/node'
1
+ import { DOCUMENT_ENTRY, VOICE_CLONE_MAX_AUDIO_BYTES, fnv1a64, hasRole, speechEngineId } from '@lincyaw/kernel'
2
+ import type { CanonicalSource, DocumentVoiceAuthoring, Finding, Member, PreparedVoiceClone, SpeechService, VoiceoverExecution, VoiceoverJob } from '@lincyaw/kernel'
3
+ import { createVoiceoverOwner, createVoiceoverRoutes, validateDocumentVoiceCatalogQuery, validateDocumentVoiceClone, validateDocumentVoiceCloneQuery, validateVoicePreviewStart } from '@lincyaw/kernel/node'
4
+ import { extname } from 'node:path'
5
+ import { readDocumentAudioBytes } from './document-audio.ts'
4
6
  import { readAuthoringDocument } from './document-editor.ts'
5
7
  import { RequestError } from './errors.ts'
6
8
  import type { SourceEditor } from './source-editor.ts'
@@ -16,6 +18,7 @@ const same = (a: CanonicalSource, b: CanonicalSource) => a.documentId === b.docu
16
18
  export function createDocumentVoiceAuthoring({ editor, services, revision }: DocumentVoiceAuthoringOptions) {
17
19
  const pending = new Set<{ controller: AbortController, finished: Promise<unknown> }>()
18
20
  const owners = new Map<string, ReturnType<typeof createVoiceoverOwner>>()
21
+ const clones = new Set<PreparedVoiceClone>()
19
22
  let closed = false
20
23
  const authorize = (document: string, member: Member) => {
21
24
  if (!hasRole(member, 'editor')) throw new RequestError(403, 'voice-authoring-permission-denied')
@@ -61,13 +64,67 @@ export function createDocumentVoiceAuthoring({ editor, services, revision }: Doc
61
64
  catch { return 'unknown' }
62
65
  }
63
66
  const service: DocumentVoiceAuthoring = {
67
+ prepareClone: (document, value, member, signal) => work(signal, async signal => {
68
+ if (!hasRole(member, 'owner')) throw new RequestError(403, 'voice-clone-permission-denied')
69
+ if (!validateDocumentVoiceClone(value)) throw new RequestError(400, 'voice-clone-invalid')
70
+ if (clones.size >= 4) throw new RequestError(503, 'voice-authoring-busy')
71
+ const request = structuredClone(value), loaded = await load(document, member, signal, request.source)
72
+ const speech = loaded.speech, engine = request.engine ?? await speech?.defaultSynthesisEngine?.()
73
+ const mime = (path: string) => {
74
+ if (path.split(/[\\/]/).some(part => part.startsWith('.'))) throw new RequestError(403, 'audio-file-path')
75
+ const types: Record<string, string> = { '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.webm': 'audio/webm', '.ogg': 'audio/ogg', '.m4a': 'audio/mp4', '.mp4': 'audio/mp4', '.flac': 'audio/flac', '.aac': 'audio/aac' }
76
+ const type = types[extname(path).toLowerCase()]
77
+ if (!type) throw new RequestError(422, 'voice-clone-audio-type')
78
+ editor.assertEditable({ document, home: false }, path, member)
79
+ return type
80
+ }
81
+ const sampleType = mime(request.sample), statementType = mime(request.consent.statement)
82
+ const [sampleBytes, statementBytes] = await Promise.all([request.sample, request.consent.statement].map(path => readDocumentAudioBytes(editor, { document, member, rest: '' }, path, signal, VOICE_CLONE_MAX_AUDIO_BYTES)))
83
+ current(document, member, loaded.source); signal.throwIfAborted()
84
+ if (!speech?.cloneVoice || !engine || !(await speech.engines()).some(info => info.id === speechEngineId(engine) && info.clone)) throw new RequestError(409, 'voice-clone-unavailable')
85
+ current(document, member, loaded.source); signal.throwIfAborted()
86
+ // Several readers may finish concurrently; the retained byte budget is checked again before retaining blobs.
87
+ if (clones.size >= 4) throw new RequestError(503, 'voice-authoring-busy')
88
+ let sample: Blob | undefined = new Blob([sampleBytes! as Uint8Array<ArrayBuffer>], { type: sampleType })
89
+ let statement: Blob | undefined = new Blob([statementBytes! as Uint8Array<ArrayBuffer>], { type: statementType })
90
+ let started: ReturnType<NonNullable<SpeechService['cloneVoice']>> | undefined
91
+ let expired = false
92
+ const prepared: PreparedVoiceClone = { engine: speechEngineId(engine), voice: request.voice,
93
+ start: startSignal => {
94
+ if (started) return started
95
+ if (expired || !sample || !statement) return Promise.reject(new RequestError(409, 'voice-clone-expired'))
96
+ clearTimeout(timer)
97
+ const exactSample = sample, exactStatement = statement
98
+ started = work(startSignal, async ownedSignal => {
99
+ current(document, member, loaded.source); ownedSignal.throwIfAborted()
100
+ return speech.cloneVoice!({ engine, voice: request.voice, sample: exactSample,
101
+ ...request.lang ? { lang: request.lang } : {}, ...request.text ? { text: request.text } : {},
102
+ consent: { speaker: request.consent.speaker, scope: request.consent.scope, statement: exactStatement } }, ownedSignal)
103
+ }).finally(() => prepared.close())
104
+ return started
105
+ },
106
+ close: () => { expired = true; clearTimeout(timer); sample = undefined; statement = undefined; clones.delete(prepared) },
107
+ }
108
+ const timer = setTimeout(() => prepared.close(), 90000)
109
+ timer.unref()
110
+ clones.add(prepared)
111
+ return prepared
112
+ }),
113
+ cloneStatus: (document, query, member, signal) => work(signal, async signal => {
114
+ if (!hasRole(member, 'owner')) throw new RequestError(403, 'voice-clone-permission-denied')
115
+ if (!validateDocumentVoiceCloneQuery(query)) throw new RequestError(400, 'voice-clone-invalid')
116
+ const loaded = await load(document, member, signal), speech = loaded.speech, engine = query.engine ?? await speech?.defaultSynthesisEngine?.()
117
+ if (!speech?.cloneStatus || !engine || !(await speech.engines()).some(info => info.id === speechEngineId(engine) && info.clone)) throw new RequestError(409, 'voice-clone-unavailable')
118
+ current(document, member, loaded.source); signal.throwIfAborted()
119
+ return speech.cloneStatus(engine, query.voice, signal)
120
+ }),
64
121
  capabilities: (document, member, signal) => work(signal, async signal => {
65
122
  const loaded = await load(document, member, signal)
66
123
  const [engines, defaultEngine] = await Promise.all([loaded.speech?.engines() ?? [], loaded.speech?.defaultSynthesisEngine?.()])
67
124
  signal.throwIfAborted(); current(document, member, loaded.source)
68
125
  const configured = engines.some(engine => engine.tts), unknown = !loaded.speech && loaded.findings?.some(finding => finding.severity === 'error')
69
126
  const implemented = Boolean(loaded.voiceoverExecution)
70
- return { document, source: loaded.source, verification: 'configuration-only', status: configured ? 'configured' : unknown ? 'unknown' : 'unavailable', ...!configured ? { reason: unknown ? 'services-unavailable' : 'not-configured' } as const : {}, voiceover: implemented, preview: implemented, engines, ...defaultEngine ? { defaultEngine } : {}, ...loaded.findings?.length ? { findings: loaded.findings } : {}, actions: { status: implemented, list: true, get: true, start: implemented && configured, cancel: true, quotePreview: implemented, preview: implemented && configured, readPreview: true }, tasks: { idempotency: 'process', limits: ownerOf(document, member).limits } }
127
+ return { document, source: loaded.source, verification: 'configuration-only', status: configured ? 'configured' : unknown ? 'unknown' : 'unavailable', ...!configured ? { reason: unknown ? 'services-unavailable' : 'not-configured' } as const : {}, voiceover: implemented, preview: implemented, engines, ...defaultEngine ? { defaultEngine } : {}, ...loaded.findings?.length ? { findings: loaded.findings } : {}, actions: { status: implemented, list: true, get: true, start: implemented && configured, cancel: true, quotePreview: implemented, preview: implemented && configured, readPreview: true, clone: hasRole(member, 'owner') && Boolean(loaded.speech?.cloneVoice) && engines.some(engine => engine.clone), cloneStatus: hasRole(member, 'owner') && Boolean(loaded.speech?.cloneStatus) && engines.some(engine => engine.clone) }, tasks: { idempotency: 'process', limits: ownerOf(document, member).limits } }
71
128
  }),
72
129
  catalog: (document, query, member, signal) => work(signal, async signal => {
73
130
  if (!validateDocumentVoiceCatalogQuery(query)) throw new RequestError(400, 'voice-catalog-query-invalid')
@@ -111,5 +168,5 @@ export function createDocumentVoiceAuthoring({ editor, services, revision }: Doc
111
168
  },
112
169
  readPreview: async (document, id, member) => ownerOf(document, member).readPreview(id),
113
170
  }
114
- return { service, routes: createVoiceoverRoutes(service), async close() { closed = true; for (const operation of pending) operation.controller.abort(); await Promise.allSettled([...owners.values()].map(owner => owner.close())); await Promise.allSettled([...pending].map(operation => operation.finished)); owners.clear() } }
171
+ return { service, routes: createVoiceoverRoutes(service), async close() { closed = true; for (const prepared of clones) prepared.close(); for (const operation of pending) operation.controller.abort(); await Promise.allSettled([...owners.values()].map(owner => owner.close())); await Promise.allSettled([...pending].map(operation => operation.finished)); owners.clear() } }
115
172
  }
package/src/node/locks.ts CHANGED
@@ -4,6 +4,15 @@ import { RequestError } from './errors.ts'
4
4
 
5
5
  export class DocumentLocks implements DocumentLockService {
6
6
  readonly #held = new Map<string, string>()
7
+ readonly #waiters = new Set<() => void>()
8
+
9
+ async acquire(document: string, holder: string): Promise<() => void> {
10
+ for (;;) {
11
+ const release = this.claim(document, holder)
12
+ if (release) return release
13
+ await new Promise<void>(done => this.#waiters.add(done))
14
+ }
15
+ }
7
16
 
8
17
  claim(document: string, holder: string): (() => void) | undefined {
9
18
  if (this.holder(document) !== undefined) return undefined
@@ -13,6 +22,9 @@ export class DocumentLocks implements DocumentLockService {
13
22
  if (released) return
14
23
  released = true
15
24
  this.#held.delete(document)
25
+ const waiting = [...this.#waiters]
26
+ this.#waiters.clear()
27
+ for (const ready of waiting) ready()
16
28
  }
17
29
  }
18
30
 
@@ -13,6 +13,7 @@ import type { Revisions } from './revisions.ts'
13
13
  import { DOCUMENT_OPERATION_MAX_BACKUP_BYTES, DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES, documentDirOf } from './writer.ts'
14
14
  import { catchRequestErrors, RequestError } from './errors.ts'
15
15
  import { projectConfiguration, projectDigest, projectMaterial } from './project-files.ts'
16
+ import { listTemplates } from './templates.ts'
16
17
 
17
18
  type Admission = { signature: string, admission: Promise<ProjectPlan> }
18
19
  type Stored = { member: string, origin: ProjectCaller['origin'], signature: string, plan: ProjectPlan, material?: ReturnType<typeof projectMaterial>, canonical?: { change: DocumentChange, planId: string, source: CanonicalSource }, receipt?: ProjectApplied, work?: Promise<ProjectApplied> }
@@ -59,14 +60,28 @@ export function createProjectAuthoring(options: { config: WorkspaceConfig, opera
59
60
  }
60
61
  const key = (request: ProjectPlanRequest, caller: ProjectCaller) => JSON.stringify([caller.member.id, caller.origin, request.id])
61
62
  const service: ProjectAuthoring = {
62
- async capabilities(caller) {
63
+ async capabilities(caller, query = {}) {
63
64
  if (closed) throw new RequestError(503, 'project-owner-closed')
65
+ const offset = query.templatesOffset ?? 0
66
+ if (!Number.isSafeInteger(offset) || offset < 0 || Object.keys(query).some(key => key !== 'templatesOffset')) throw new RequestError(400, 'project-request-invalid')
64
67
  const observed = await observation(), directory = reasons(caller), metadata = reasons(caller, { op: 'retitle', dir: caller.boundDocument ?? '', title: 'capability' })
65
68
  if (!observed.snapshot && !directory.includes('project-git-unavailable')) directory.push('project-head-unavailable')
66
69
  const actions = Object.fromEntries(['create', 'copy', 'rename', 'delete', 'retitle'].map(op => { const unavailable = op === 'retitle' ? metadata : directory; return [op, { available: unavailable.length === 0, reasons: unavailable }] })) as import('@lincyaw/kernel').ProjectCapabilities['actions']
67
70
  const available = Object.values(actions).some(action => action.available)
68
- return bounded({ available, actions, reasons: available ? [] : [...new Set([...directory, ...metadata])], observation: observed, verification: 'configuration-only', rootDirectoryOperations: false,
69
- limits: { requestChars: PROJECT_MAX_REQUEST_CHARS, responseChars: PROJECT_MAX_RESPONSE_CHARS, backupEntries: DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES, backupBytes: DOCUMENT_OPERATION_MAX_BACKUP_BYTES, plans: PROJECT_MAX_PLANS, ttlMs: PROJECT_PLAN_TTL_MS } })
71
+ const answer: import('@lincyaw/kernel').ProjectCapabilities = { available, actions, reasons: available ? [] : [...new Set([...directory, ...metadata])], observation: observed, verification: 'configuration-only', rootDirectoryOperations: false,
72
+ limits: { requestChars: PROJECT_MAX_REQUEST_CHARS, responseChars: PROJECT_MAX_RESPONSE_CHARS, backupEntries: DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES, backupBytes: DOCUMENT_OPERATION_MAX_BACKUP_BYTES, plans: PROJECT_MAX_PLANS, ttlMs: PROJECT_PLAN_TTL_MS } }
73
+ if (caller.boundDocument === undefined) {
74
+ const templates = listTemplates(config)
75
+ if (offset > templates.length) throw new RequestError(400, 'project-request-invalid')
76
+ answer.templates = []
77
+ for (const template of templates.slice(offset, offset + 20)) {
78
+ if (JSON.stringify({ ...answer, templates: [...answer.templates, template], nextTemplatesOffset: offset + answer.templates.length + 1 }).length > PROJECT_MAX_RESPONSE_CHARS) break
79
+ answer.templates.push(template)
80
+ }
81
+ if (!answer.templates.length && offset < templates.length) throw new RequestError(413, 'project-response-too-large')
82
+ if (offset + answer.templates.length < templates.length) answer.nextTemplatesOffset = offset + answer.templates.length
83
+ } else if (offset) throw new RequestError(403, 'project-workspace-scope-required')
84
+ return bounded(answer)
70
85
  },
71
86
  async plan(request, caller) {
72
87
  budget(request)