@lincyaw/workspace 1.0.0-rc.15 → 1.0.0-rc.18

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workspace",
3
- "version": "1.0.0-rc.15",
3
+ "version": "1.0.0-rc.18",
4
4
  "description": "Presmium's workspace service (presmium serve): documents, their history, reviews and the workspace site",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -32,13 +32,14 @@
32
32
  "dependencies": {
33
33
  "image-size": "2.0.4",
34
34
  "mime-types": "3.0.2",
35
+ "playwright-chromium": "1.64.1",
35
36
  "yaml": "^2.9.1",
36
- "@lincyaw/compiler": "1.0.0-rc.15",
37
- "@lincyaw/kernel": "1.0.0-rc.15",
38
- "@lincyaw/server": "1.0.0-rc.15"
37
+ "@lincyaw/compiler": "1.0.0-rc.18",
38
+ "@lincyaw/kernel": "1.0.0-rc.18",
39
+ "@lincyaw/server": "1.0.0-rc.18"
39
40
  },
40
41
  "devDependencies": {
41
42
  "@types/mime-types": "^3.0.1",
42
- "@lincyaw/mcp": "1.0.0-rc.15"
43
+ "@lincyaw/mcp": "1.0.0-rc.18"
43
44
  }
44
45
  }
@@ -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
+ }
package/src/node/serve.ts CHANGED
@@ -1,16 +1,17 @@
1
1
  import { createProjectAuthoring } from './projects.ts'
2
2
  import { createDocumentHistory } from './document-history.ts'
3
3
  import { createAuthoringClients } from './authoring-clients.ts'
4
- import { createHash } from 'node:crypto'
5
- import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'
6
- import { homedir, tmpdir } from 'node:os'
4
+ import { createDocumentCapture } from './capture.ts'
5
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
6
+ import { stripVTControlCharacters } from 'node:util'
7
+ import { tmpdir } from 'node:os'
7
8
  import { join, relative } from 'node:path'
8
9
  import { Compiler, operatorDir as resolveOperatorDir, pluginLogger, runBlock, workspacePlugins } from '@lincyaw/compiler'
9
10
  import type { Compilation, CompilerOptions } from '@lincyaw/compiler'
10
- import { CHANGE_REVIEW, DOCUMENT_FILES, DOCUMENT_LOCKS, DOCUMENT_VOICE_TASKS, errorMessage, PRODUCTION_AUDIO_AUTHORING, REVISIONS, SPEECH, VOICEOVER, VOICEOVER_EXECUTION } from '@lincyaw/kernel'
11
- import { irRevision, operatorSpeechSecrets } from '@lincyaw/kernel/node'
11
+ import { CHANGE_REVIEW, DOCUMENT_FILES, DOCUMENT_LOCKS, DOCUMENT_VOICE_TASKS, errorMessage, PreviewPreparing, PRODUCTION_AUDIO_AUTHORING, REVISIONS, SPEECH, VOICEOVER, VOICEOVER_EXECUTION } from '@lincyaw/kernel'
12
+ import { irRevision, operatorSpeechSecrets, serveStateDir } from '@lincyaw/kernel/node'
12
13
  import { speechSettingsRoute } from './speech-settings.ts'
13
- import type { CanonicalSource, ChangeReviewService, Finding, IRDocument, Logger, ProductionAudioAuthoring, ServiceToken, SiteSpec, SpeechService } from '@lincyaw/kernel'
14
+ import type { ApprovalKind, CanonicalSource, ChangeReviewService, Finding, IRDocument, Logger, ProductionAudioAuthoring, ServiceToken, SiteSpec, SpeechService } from '@lincyaw/kernel'
14
15
  import { serverConfigKey, servedDocument, startServer } from '@lincyaw/server'
15
16
  import type { DiagnosticStore, PresmiumServer, ServedDocument, ServedPlugin, ServerHost } from '@lincyaw/server'
16
17
  import { CompileSession } from './compile-session.ts'
@@ -26,7 +27,7 @@ import { createTaskReviewService } from './review/task-reviews.ts'
26
27
  import { Revisions } from './revisions.ts'
27
28
  import { WORKSPACE_ID, authorizeWorkspaceRoutes, workspaceRoutes, workspaceRoutesPlugin } from './routes.ts'
28
29
  import { refreshDocumentVitePlugins, siteContext, siteDocument, siteDocumentIR, siteSpec, untranslatedFindings, webRenderer } from './site.ts'
29
- import { SourceEditor } from './source-editor.ts'
30
+ import { SourceEditor, versionOf } from './source-editor.ts'
30
31
  import { createDocumentEditor } from './document-editor.ts'
31
32
  import type { DocumentEditor } from './document-editor.ts'
32
33
  import { createDocumentTranscriptions } from './document-transcription.ts'
@@ -50,6 +51,8 @@ export interface ServeOptions {
50
51
  /** The address browsers use when a reverse proxy fronts the service (see `ServerOptions.publicUrl`). */
51
52
  publicUrl?: string
52
53
  env?: NodeJS.ProcessEnv
54
+ /** Approvals given without asking, over the workspace's `approvals` (`presmium serve --allow`). */
55
+ allow?: ApprovalKind[]
53
56
  approvalTimeoutMs?: number
54
57
  log?: Logger
55
58
  }
@@ -76,8 +79,7 @@ interface NodeServiceLoad { key: string, promise: Promise<AuthoringServices>, co
76
79
  const DISK_LOOK_MS = 1000
77
80
 
78
81
  function makeStateDir(root: string, env: NodeJS.ProcessEnv): string {
79
- const base = env.XDG_CACHE_HOME || join(homedir(), '.cache')
80
- const dir = join(base, 'presmium', 'serve', createHash('sha256').update(root).digest('hex').slice(0, 16))
82
+ const dir = serveStateDir(root, env)
81
83
  mkdirSync(dir, { recursive: true })
82
84
  return dir
83
85
  }
@@ -118,6 +120,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
118
120
  let transcriptionAdoption: ReturnType<typeof createTranscriptionAdoption> | undefined
119
121
  let audioAuthoring: ReturnType<typeof createDocumentAudioAuthoring> | undefined
120
122
  let imageAuthoring: ReturnType<typeof createDocumentImageAuthoring> | undefined
123
+ let capture: ReturnType<typeof createDocumentCapture> | undefined
121
124
  let voiceAuthoring: ReturnType<typeof createDocumentVoiceAuthoring> | undefined
122
125
  let workspaceRoutesOwner: ReturnType<typeof workspaceRoutes> | undefined
123
126
  let routesPlugin: ServedPlugin | undefined
@@ -268,6 +271,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
268
271
  get voiceAuthoring() { return voiceAuthoring?.service },
269
272
  get transcriptions() { return transcriptions },
270
273
  get transcriptionAdoption() { return transcriptionAdoption?.service },
274
+ get capture() { return capture?.service },
271
275
  get routes() { return workspaceRoutesOwner?.routes ? { [WORKSPACE_ID]: workspaceRoutesOwner.routes, ...voiceAuthoring ? { 'presmium.lecture': authorizeWorkspaceRoutes(voiceAuthoring.routes, launcherToken) } : {} } : undefined },
272
276
  agentTools(document) {
273
277
  const compiled = (document === undefined ? [...compileSessions.values()] : [compileSessions.get(document)]).flatMap(session => session?.latest ? [session.latest] : [])
@@ -355,7 +359,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
355
359
  }
356
360
  },
357
361
  settings: config.settings,
358
- approvals: config.approvals,
362
+ approvals: { ...config.approvals, ...Object.fromEntries((options.allow ?? []).map(kind => [kind, 'allow' as const])) },
359
363
  operatorDir: operatorDirectory,
360
364
  serverHost,
361
365
  env,
@@ -422,6 +426,15 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
422
426
  throw error
423
427
  }
424
428
 
429
+ // A picture right after a save shows what was saved: the document is compiled first when its file is newer.
430
+ const savedCompilation = async (dir: string): Promise<Compilation> => {
431
+ const session = compileSessionOf(dir)
432
+ const compilation = await session.ready()
433
+ const entry = docs().find(doc => doc.dir === dir)?.entry
434
+ const saved = entry ? versionOf(readFileSync(join(root, entry))) : undefined
435
+ return saved && compilation.doc.source?.version !== saved ? await session.recompile() : compilation
436
+ }
437
+ capture = createDocumentCapture({ root, url: () => running.url, viewerPage: dir => site?.app(dir, true) ?? Promise.resolve(undefined), compiled: async dir => (await savedCompilation(dir)).doc, dir: join(stateDir, 'captures') })
425
438
  started()
426
439
 
427
440
  const compileForSite = async (dir: string): Promise<IRDocument> => {
@@ -433,6 +446,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
433
446
  site = await startWorkspaceSite({ root, spec, basePath, bundled: options.bundled, stateDir, compile: compileForSite, stampPreviewRevision: (compilation, doc) => workbench!.stampPreviewRevision(compilation, doc), diagnostics: running.diagnostics, preview, log })
434
447
  } catch (error) {
435
448
  await closeAuthoring()
449
+ await capture.close()
436
450
  await workbench.close()
437
451
  await running.close()
438
452
  if (home) rmSync(home, { recursive: true, force: true })
@@ -448,6 +462,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
448
462
  await closeAuthoring()
449
463
  for (const session of compileSessions.values()) session.close()
450
464
  await jobs.close()
465
+ await capture?.close()
451
466
  await workbench?.close()
452
467
  await site?.close()
453
468
  await running.close()
@@ -471,6 +486,23 @@ interface WorkspaceSiteOptions {
471
486
 
472
487
  type WorkspaceSite = Awaited<ReturnType<typeof startWorkspaceSite>>
473
488
 
489
+ /** The bundler's failure as a diagnostic: the file and the module it could not find, when that is the failure. */
490
+ function codeFailure(error: unknown): Finding {
491
+ const text = stripVTControlCharacters(errorMessage(error))
492
+ const unresolved = /failed to resolve import "([^"]+)" from "([^"]+)"/.exec(text)
493
+ if (unresolved) {
494
+ return {
495
+ checkId: 'presmium.preview.code',
496
+ severity: 'error',
497
+ message: `the document's code could not be bundled: ${unresolved[1]} cannot be found from this file`,
498
+ hint: 'Name the plugin that provides it in metadata.plugins, or add its package to the project’s dependencies.',
499
+ source: { file: unresolved[2]! },
500
+ }
501
+ }
502
+ const reason = text.split('\n').map(line => line.replace(/^Error:\s*/, '').trim()).find(line => line && !/^Build failed/.test(line)) ?? text
503
+ return { checkId: 'presmium.preview.code', severity: 'error', message: `the document's code could not be bundled: ${reason}` }
504
+ }
505
+
474
506
  /** The workspace site's dev router in this process, which serve forwards the site's paths to. */
475
507
  async function startWorkspaceSite(options: WorkspaceSiteOptions) {
476
508
  const { root, spec, log } = options
@@ -497,7 +529,20 @@ async function startWorkspaceSite(options: WorkspaceSiteOptions) {
497
529
  })
498
530
  },
499
531
  warm: (dir: string): Promise<void> => dev.warm?.(dir) ?? Promise.resolve(),
500
- app: (dir: string, wait: boolean): Promise<string | undefined> => dev.app?.(dir, wait) ?? Promise.resolve(undefined),
532
+ app: async (dir: string, wait: boolean): Promise<string | undefined> => {
533
+ // A file of the document's own code (a scene, a component) that does not bundle fails alone: what imports it
534
+ // shows its failure. Each such file is a diagnostic, where the author, the workbench's AI and MCP clients find
535
+ // it, until a preview bundles it; when none of the code bundles, the preview fails, and the reason is one.
536
+ const source = { document: dir, origin: 'preview', renderer: 'web', instance: 'code' } as const
537
+ try {
538
+ const page = await (dev.app?.(dir, wait) ?? Promise.resolve(undefined))
539
+ if (wait && page) options.diagnostics.replace(source, dev.codeFindings?.(dir) ?? [], { root, irRevision: options.diagnostics.irRevision(dir) })
540
+ return page
541
+ } catch (error) {
542
+ if (wait && !(error instanceof PreviewPreparing)) options.diagnostics.replace(source, [codeFailure(error)], { root, irRevision: options.diagnostics.irRevision(dir) })
543
+ throw error
544
+ }
545
+ },
501
546
  close: (): Promise<void> => dev.close(),
502
547
  }
503
548
  }