@lincyaw/workspace 1.0.0-rc.13 → 1.0.0-rc.131

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.
Files changed (59) hide show
  1. package/README.md +4 -4
  2. package/package.json +8 -5
  3. package/src/domain/paths.ts +0 -15
  4. package/src/node/agent-activity.ts +46 -0
  5. package/src/node/archive.ts +33 -0
  6. package/src/node/authoring-clients.ts +73 -20
  7. package/src/node/authoring-windows.ts +165 -0
  8. package/src/node/build.ts +28 -23
  9. package/src/node/capture.ts +383 -0
  10. package/src/node/config.ts +136 -50
  11. package/src/node/document-assets.ts +2 -2
  12. package/src/node/document-audio.ts +65 -46
  13. package/src/node/document-authoring.ts +30 -15
  14. package/src/node/document-check.ts +36 -0
  15. package/src/node/document-history.ts +32 -5
  16. package/src/node/document-images.ts +24 -14
  17. package/src/node/document-import.ts +123 -0
  18. package/src/node/document-index.ts +644 -0
  19. package/src/node/document-materials.ts +80 -0
  20. package/src/node/document-operations.ts +4 -2
  21. package/src/node/document-transcription.ts +2 -1
  22. package/src/node/document-voice.ts +121 -13
  23. package/src/node/git-runner.mjs +19 -0
  24. package/src/node/git.ts +141 -22
  25. package/src/node/host-activity.ts +17 -0
  26. package/src/node/host-upgrade.ts +28 -0
  27. package/src/node/jobs.ts +40 -8
  28. package/src/node/local-history.ts +84 -0
  29. package/src/node/locks.ts +12 -0
  30. package/src/node/mcp-settings.ts +68 -0
  31. package/src/node/media-upload-messages.ts +4 -0
  32. package/src/node/media-upload-page.ts +57 -0
  33. package/src/node/media-upload.css +4 -0
  34. package/src/node/media-uploads.ts +116 -0
  35. package/src/node/page-delete.ts +0 -1
  36. package/src/node/project-files.ts +2 -2
  37. package/src/node/projects.ts +20 -5
  38. package/src/node/review/agent-session-reviews.ts +194 -63
  39. package/src/node/review/agent-workspace.ts +124 -0
  40. package/src/node/review/git-review.ts +47 -15
  41. package/src/node/review/record.ts +5 -1
  42. package/src/node/review/routes.ts +9 -1
  43. package/src/node/review/workspace-review.ts +87 -0
  44. package/src/node/revision-files.ts +54 -0
  45. package/src/node/revisions.ts +244 -59
  46. package/src/node/routes.ts +52 -59
  47. package/src/node/serve.ts +267 -52
  48. package/src/node/site.ts +5 -5
  49. package/src/node/source-editor.ts +66 -26
  50. package/src/node/speech-settings.ts +6 -8
  51. package/src/node/templates.ts +2 -2
  52. package/src/node/tree-operations.ts +425 -0
  53. package/src/node/tree-routes.ts +94 -0
  54. package/src/node/workbench-api.ts +14 -3
  55. package/src/node/workspace-changes.ts +130 -0
  56. package/src/node/workspace-migrate.ts +54 -0
  57. package/src/node/workspace-source.ts +133 -0
  58. package/src/node/writer.ts +21 -8
  59. package/templates/document/default/{lecture.json → index.pmd} +5 -1
package/src/node/build.ts CHANGED
@@ -1,9 +1,10 @@
1
- import { cpSync, existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
1
+ import { cpSync, existsSync, readdirSync, rmSync } from 'node:fs'
2
2
  import { isAbsolute, join, resolve } from 'node:path'
3
- import { build, Compiler } from '@lincyaw/compiler'
3
+ import { build, Compiler, WORKSPACE_CONFIG } from '@lincyaw/compiler'
4
4
  import type { Compilation, RunStats } from '@lincyaw/compiler'
5
- import { errorMessage, isRecord } from '@lincyaw/kernel'
5
+ import { APP_DIR, errorMessage, isRecord, SLIDES_DIR } from '@lincyaw/kernel'
6
6
  import type { Finding, IRDocument, SiteSpec } from '@lincyaw/kernel'
7
+ import { relativePath } from '../domain/paths.ts'
7
8
  import { listDocuments, readWorkspaceConfig } from './config.ts'
8
9
  import { siteContext, siteDocument, siteIR, siteSpec, siteTranslations, webRenderer } from './site.ts'
9
10
 
@@ -25,7 +26,7 @@ export async function buildWorkspace(root: string, options: { outDir?: string, b
25
26
  for (const document of found) {
26
27
  const compilation = await new Compiler(join(config.root, document.entry), { bundled: options.bundled, settings: config.settings }).compile({ pruneCache: true })
27
28
  compilations.push(compilation)
28
- const to = presentations(compilation, `${base}${urlPath(document.dir)}/`, siteLook(config.site, config.root))
29
+ const to = presentations(compilation, base, `${base}${urlPath(document.dir)}/`, siteLook(config.site, config.root, document.dir))
29
30
  if (to.length > 0) forms.push({ dir: document.dir, compilation, to })
30
31
  const translated = await siteTranslations(compilation)
31
32
  findings.push(...compilation.doc.diagnostics, ...translated.findings)
@@ -50,7 +51,7 @@ export async function buildWorkspace(root: string, options: { outDir?: string, b
50
51
  const report = await build(compilation, { outDir: work, to })
51
52
  findings.push(...report.findings)
52
53
  for (const form of to) if (existsSync(join(work, form))) cpSync(join(work, form), join(outDir, dir, form), { recursive: true })
53
- if (to.includes('slides')) shareSlidesApp(join(outDir, dir, 'slides'), `${base}${urlPath(dir)}/slides/`, outDir, base)
54
+ if (to.includes('slides')) moveApps(join(outDir, dir, SLIDES_DIR), outDir)
54
55
  } catch (error) {
55
56
  findings.push({ checkId: 'presmium.render', severity: 'error', message: `document ${dir}: its ${to.join(' and ')} failed: ${errorMessage(error)}` })
56
57
  }
@@ -82,39 +83,43 @@ function pluginsByName(site: SiteSpec, compilations: readonly Compilation[]): Re
82
83
 
83
84
  const PRESENTATIONS = ['slides', 'lecture']
84
85
 
85
- /** The site's theme and its parameters, for its presentations to look like its pages; a theme directory made absolute. */
86
- function siteLook(site: Record<string, unknown>, root: string): Record<string, unknown> {
86
+ /**
87
+ * The site's theme and its parameters, for the presentations of the document in `dir` to look like its pages: a theme
88
+ * directory made absolute, and the parameters with the file they are written in (`siteFile`, relative to the document),
89
+ * for their paths (`logo`) to resolve against it.
90
+ */
91
+ function siteLook(site: Record<string, unknown>, root: string, dir: string): Record<string, unknown> {
87
92
  const theme = typeof site.theme === 'string' && (site.theme.startsWith('.') || isAbsolute(site.theme)) ? resolve(root, site.theme) : site.theme
88
- return { ...theme !== undefined ? { theme } : {}, ...isRecord(site.params) ? { params: site.params } : {} }
93
+ return { ...theme !== undefined ? { theme } : {}, ...isRecord(site.params) ? { params: site.params, siteFile: relativePath(dir, WORKSPACE_CONFIG) } : {} }
89
94
  }
90
95
 
91
96
  const urlPath = (dir: string) => dir.split('/').map(encodeURIComponent).join('/')
92
97
 
93
- /**
94
- * Every document's slides run the same viewer app: it moves to the site's `_app/<key>/`, beside the web pages' own,
95
- * so a reader downloads it once for all the presentations of the site, and the slides' page points there.
96
- */
97
- function shareSlidesApp(slides: string, slidesBase: string, outDir: string, base: string): void {
98
- const app = join(slides, '_app')
99
- if (!existsSync(app)) return
100
- for (const key of readdirSync(app)) if (!existsSync(join(outDir, '_app', key))) cpSync(join(app, key), join(outDir, '_app', key), { recursive: true })
101
- rmSync(app, { recursive: true, force: true })
102
- const page = join(slides, 'index.html')
103
- writeFileSync(page, readFileSync(page, 'utf8').replaceAll(`${slidesBase}_app/`, `${base}_app/`))
98
+ /** The presentation's viewer app goes where its page names it (`appBase`): with the site's own, downloaded once for all. */
99
+ function moveApps(presentation: string, outDir: string): void {
100
+ const apps = join(presentation, APP_DIR)
101
+ if (!existsSync(apps)) return
102
+ for (const key of readdirSync(apps)) if (!existsSync(join(outDir, APP_DIR, key))) cpSync(join(apps, key), join(outDir, APP_DIR, key), { recursive: true })
103
+ rmSync(apps, { recursive: true, force: true })
104
104
  }
105
105
 
106
106
  /**
107
107
  * The presentation forms a document asks for (`metadata.renderers.slides` or `lecture`), set to be served below its
108
- * pages at `prefix`: the slides at `slides/`, and the web pages and the slides linked to each other.
108
+ * pages at `prefix`, with its viewer app below the site's `base`: the slides at `slides/`, and the web pages and the slides linked to each other.
109
109
  */
110
- function presentations(compilation: Compilation, prefix: string, look: Record<string, unknown>): string[] {
110
+ function presentations(compilation: Compilation, base: string, prefix: string, look: Record<string, unknown>): string[] {
111
111
  const { renderers } = compilation.doc.config
112
112
  const to = PRESENTATIONS.filter(form => renderers[form] !== undefined)
113
113
  if (to.length === 0) return to
114
- if (to.includes('slides')) renderers.slides = { ...look, ...isRecord(renderers.slides) ? renderers.slides : {}, base: `${prefix}slides/` }
114
+ if (to.includes('slides')) {
115
+ const own = isRecord(renderers.slides) ? renderers.slides : {}
116
+ // Parameters the document sets for its slides are written in its index.pmd, not in the workspace's file.
117
+ const { siteFile, ...shared } = look
118
+ renderers.slides = { ...shared, ...own.params === undefined && siteFile !== undefined ? { siteFile } : {}, ...own, base: `${prefix}${SLIDES_DIR}/`, appBase: base }
119
+ }
115
120
  const settings = compilation.doc.config.presmium ??= {}
116
121
  const web = isRecord(settings['presmium.web']) ? settings['presmium.web'] : {}
117
- settings['presmium.web'] = { ...web, webUrl: prefix, ...to.includes('slides') ? { slidesUrl: `${prefix}slides/` } : {} }
122
+ settings['presmium.web'] = { ...web, webUrl: prefix, ...to.includes('slides') ? { slidesUrl: `${prefix}${SLIDES_DIR}/` } : {} }
118
123
  // The slides find the lecture where it is built, without probing `slides/lecture/` first.
119
124
  if (to.includes('lecture')) {
120
125
  const lecture = isRecord(settings['presmium.lecture']) ? settings['presmium.lecture'] : {}
@@ -0,0 +1,383 @@
1
+ import { mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { basename, join } from 'node:path'
4
+ 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'
5
+ import type { CanonicalSource, CaptureEvidence, CapturedBox, CapturedSlide, CaptureHook, DocumentCapture, IRDocument, IRSection, OverviewCaptureRequest, ReadingCaptureRequest, SlideCaptureRequest } from '@lincyaw/kernel'
6
+ import { playwrightChromium } from '@lincyaw/kernel/node'
7
+
8
+ /** What capturing uses of Playwright's Chromium. */
9
+ interface Page {
10
+ goto(url: string, options: { waitUntil: 'load', timeout: number }): Promise<unknown>
11
+ waitForFunction(script: string, arg: undefined, options: { timeout: number }): Promise<unknown>
12
+ evaluate<R, A>(run: (arg: A) => R | Promise<R>, arg: A): Promise<R>
13
+ screenshot(options: { type: 'png', fullPage?: boolean, clip?: { x: number, y: number, width: number, height: number } }): Promise<Buffer>
14
+ setViewportSize(size: { width: number, height: number }): Promise<void>
15
+ setContent(html: string, options: { waitUntil: 'load', timeout: number }): Promise<void>
16
+ on(event: 'pageerror', listener: (error: Error) => void): void
17
+ on(event: 'console', listener: (message: { type(): string, text(): string }) => void): void
18
+ }
19
+ interface Context {
20
+ newPage(): Promise<Page>
21
+ close(): Promise<void>
22
+ }
23
+ interface Browser {
24
+ newContext(options: { viewport: { width: number, height: number }, deviceScaleFactor: number, reducedMotion: 'reduce', colorScheme: 'light' | 'dark', serviceWorkers: 'block' }): Promise<Context>
25
+ close(): Promise<void>
26
+ }
27
+ interface Chromium { launch(): Promise<Browser> }
28
+
29
+ export interface CaptureOptions {
30
+ root: string
31
+ /** The service's own address. */
32
+ url(): string
33
+ /** The viewer page of a document once the page can show it (its path below the address), as previews open it. */
34
+ viewerPage(document: string): Promise<string | undefined>
35
+ /** The document's current runtime snapshot. */
36
+ compiled(document: string): Promise<IRDocument>
37
+ /** Where the pictures are written. */
38
+ dir: string
39
+ }
40
+
41
+ interface View { width: number, height: number, scale: number, appearance: 'light' | 'dark' }
42
+ interface CaptureInput {
43
+ kind: 'slides' | 'reading' | 'overview'
44
+ request: SlideCaptureRequest | ReadingCaptureRequest | OverviewCaptureRequest
45
+ source?: CanonicalSource
46
+ }
47
+ const sameSource = (a: CanonicalSource | undefined, b: CanonicalSource | undefined): boolean =>
48
+ a?.documentId === b?.documentId && a?.version === b?.version && a?.fingerprint === b?.fingerprint
49
+
50
+ const PAGE_MS = 120_000
51
+ const IDLE_MS = 120_000
52
+ const KEEP = 20
53
+ const FIT_ROUNDS = 3
54
+ const READING_WIDTH = 1280
55
+ const READING_HEIGHT = 900
56
+ const MIN_WIDTH = 320
57
+ const MAX_WIDTH = 2560
58
+ const THUMB_WIDTH = 320
59
+ const SHEET_GAP = 16
60
+
61
+ class CaptureError extends Error {
62
+ readonly status: number
63
+ readonly detail?: Record<string, unknown>
64
+ constructor(code: string, status: number, detail?: Record<string, unknown>) {
65
+ super(code)
66
+ this.status = status
67
+ if (detail) this.detail = detail
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Pictures of documents as readers see them, in a headless Chromium kept while it is used: the viewer page of a
73
+ * document, opened with `?capture`, is driven by its capture hook (a slide step by step and moment by moment, so that a
74
+ * picture is the same however often it is taken; a section of the reading page scrolled through and at rest). One request
75
+ * at a time; the pictures stay in `dir`, the last few requests.
76
+ */
77
+ export function createDocumentCapture(options: CaptureOptions): { service: DocumentCapture, close(): Promise<void> } {
78
+ let browser: Promise<Browser> | undefined
79
+ let idle: ReturnType<typeof setTimeout> | undefined
80
+ let queue: Promise<unknown> = Promise.resolve()
81
+ const launch = (): Promise<Browser> => {
82
+ clearTimeout(idle)
83
+ browser ??= playwrightChromium<Chromium>(options.root, import.meta.url).then(chromium => chromium.launch()).catch((error: unknown) => {
84
+ browser = undefined
85
+ throw new CaptureError('capture-browser-unavailable', 503, { reason: errorMessage(error) })
86
+ })
87
+ return browser
88
+ }
89
+ const release = () => {
90
+ clearTimeout(idle)
91
+ idle = setTimeout(() => void close(), IDLE_MS)
92
+ idle.unref?.()
93
+ }
94
+ const close = async () => {
95
+ clearTimeout(idle)
96
+ const open = browser
97
+ browser = undefined
98
+ await (await open?.catch(() => undefined))?.close().catch(() => undefined)
99
+ }
100
+
101
+ /** The section asked for, by id or by its number from 1. */
102
+ const sectionOf = (doc: IRDocument, asked: string) => {
103
+ const section = doc.sections.find(s => s.id === asked) ?? doc.sections[Number(asked) - 1]
104
+ if (!section) throw new CaptureError('capture-section-unknown', 404, { section: asked, sections: doc.sections.map(s => s.id) })
105
+ return section
106
+ }
107
+
108
+ /** The document's viewer page in a form, opened with its capture hook in a new context; `run` uses it, then it closes. */
109
+ const open = async <T extends { images: Uint8Array[] }>(document: string, form: 'web' | 'slides', view: View & { captions?: boolean }, signal: AbortSignal | undefined, run: (tab: Page, problems: Set<string>, out: string, newPage: () => Promise<Page>) => Promise<T>, input: CaptureInput): Promise<T & { capture: CaptureEvidence }> => {
110
+ const page = await options.viewerPage(document).catch((error: unknown) => {
111
+ throw new CaptureError('capture-preview-failed', 409, { reason: errorMessage(error) })
112
+ })
113
+ if (!page) throw new CaptureError('capture-preview-failed', 409)
114
+ signal?.throwIfAborted()
115
+ const context = await (await launch()).newContext({ viewport: { width: view.width, height: view.height }, deviceScaleFactor: view.scale, reducedMotion: 'reduce', colorScheme: view.appearance, serviceWorkers: 'block' })
116
+ const problems = new Set<string>()
117
+ let directory: string | undefined
118
+ let complete = false
119
+ try {
120
+ const tab = await context.newPage()
121
+ tab.on('pageerror', error => problems.add(error.message))
122
+ tab.on('console', message => { if (message.type() === 'error') problems.add(message.text().slice(0, 500)) })
123
+ const address = new URL(page, options.url())
124
+ if (form === 'slides') address.searchParams.set('form', 'slides')
125
+ if (view.captions === false) address.searchParams.set(CAPTIONS_PARAM, 'off')
126
+ address.searchParams.set(CAPTURE_PARAM, '')
127
+ address.searchParams.set(PREVIEW_APPEARANCE_PARAM, view.appearance)
128
+ await tab.goto(address.href, { waitUntil: 'load', timeout: PAGE_MS })
129
+ await tab.waitForFunction(`Boolean(window.${CAPTURE_HOOK})`, undefined, { timeout: PAGE_MS })
130
+ const snapshot = () => tab.evaluate(hook => (window as unknown as Record<string, CaptureHook>)[hook]!.snapshot?.(), CAPTURE_HOOK)
131
+ const before = await snapshot()
132
+ if (before?.source && input.source && !sameSource(before.source, input.source)) throw new CaptureError('capture-source-changed', 409)
133
+ const createdAt = new Date().toISOString()
134
+ const id = `${createdAt.replace(/[:.]/g, '-')}-${randomUUID()}`
135
+ const out = join(options.dir, ...(input.request.retain ? ['retained', id] : [id]))
136
+ directory = out
137
+ mkdirSync(out, { recursive: true })
138
+ const result = await run(tab, problems, out, () => context.newPage())
139
+ signal?.throwIfAborted()
140
+ const after = await snapshot()
141
+ if (!sameSource(before?.source, after?.source) || before?.codeBundle !== after?.codeBundle) throw new CaptureError('capture-source-changed', 409)
142
+ const capture: CaptureEvidence = { id, createdAt, directory: out, manifestFile: join(out, 'capture.json'), retained: input.request.retain === true, ...before }
143
+ const { images: _images, ...details } = result
144
+ writeFileSync(capture.manifestFile, `${JSON.stringify({ capture, kind: input.kind, request: input.request, ...details }, null, 2)}\n`)
145
+ complete = true
146
+ return { ...result, capture }
147
+ } catch (error) {
148
+ if (error instanceof CaptureError || signal?.aborted) throw error
149
+ // A page that loads again while it is driven loses its hook: going back reloaded it.
150
+ if (/context was destroyed|because of a navigation/i.test(errorMessage(error))) throw new CaptureError('capture-page-reloaded', 409, { problems: [...problems] })
151
+ throw new CaptureError('capture-failed', 500, { reason: errorMessage(error), problems: [...problems] })
152
+ } finally {
153
+ await context.close().catch(() => undefined)
154
+ if (!complete && directory) rmSync(directory, { recursive: true, force: true })
155
+ prune(options.dir)
156
+ }
157
+ }
158
+
159
+ const slides: DocumentCapture['slides'] = async (document, request, signal) => {
160
+ if (request.arrive === 'backward' && request.at !== undefined) throw new CaptureError('capture-arrive-moment-conflict', 400)
161
+ const doc = await options.compiled(document)
162
+ const section = sectionOf(doc, request.section)
163
+ const steps = request.steps ?? Array.from({ length: section.steps + 1 }, (_, step) => step)
164
+ const wrong = steps.find(step => !Number.isInteger(step) || step < 0 || step > section.steps)
165
+ if (wrong !== undefined) throw new CaptureError('capture-step-invalid', 400, { step: wrong, last: section.steps })
166
+ const arrive = request.arrive ?? 'direct'
167
+ // Reached backward, a step is at rest: moments apply to steps drawn directly.
168
+ const moments: (number | null)[] = request.at?.length && arrive === 'direct' ? request.at : [null]
169
+ if (moments.some(at => at !== null && (!Number.isFinite(at) || at < 0))) throw new CaptureError('capture-moment-invalid', 400)
170
+ const count = steps.length * moments.length
171
+ if (count === 0 || count > CAPTURE_MAX_FRAMES) throw new CaptureError('capture-too-many-frames', 400, { requested: count, max: CAPTURE_MAX_FRAMES })
172
+ const shape = slideShape(doc)
173
+ const scale = request.scale ?? 1
174
+ return await open(document, 'slides', { width: shape.width, height: shape.height, scale, appearance: request.appearance ?? 'light', captions: request.captions }, signal, async (tab, problems, out) => {
175
+ 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)
176
+ await fit(tab, shape, section.id, steps[0]!, () => show(steps[0]!, moments[0]!))
177
+ const frames: CapturedSlide[] = [], images: Uint8Array[] = []
178
+ for (const step of steps) {
179
+ for (const at of moments) {
180
+ signal?.throwIfAborted()
181
+ const shown = await show(step, at, arrive)
182
+ for (const problem of shown.problems) problems.add(problem)
183
+ const measured = await tab.evaluate(measure, { section: section.id, step, selector: request.measure ?? '', width: shape.width, max: CAPTURE_MAX_BOXES })
184
+ if (!measured) throw new CaptureError('capture-slide-missing', 500, { section: section.id, step })
185
+ const clip = request.clip
186
+ ? { 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 }
187
+ : { x: measured.slide.x, y: measured.slide.y, width: measured.slide.width, height: measured.slide.height }
188
+ const png = await tab.screenshot({ type: 'png', clip })
189
+ const file = join(out, `${section.id}-${step}${at === null ? '' : `-${at}ms`}${arrive === 'backward' ? '-backward' : ''}.png`)
190
+ writeFileSync(file, png)
191
+ images.push(png)
192
+ 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 } : {} })
193
+ }
194
+ }
195
+ return { document, shape: { width: shape.width, height: shape.height }, frames, problems: [...problems], images }
196
+ }, { kind: 'slides', request, source: doc.source })
197
+ }
198
+
199
+ const reading: DocumentCapture['reading'] = async (document, request, signal) => {
200
+ const doc = await options.compiled(document)
201
+ const section = sectionOf(doc, request.section)
202
+ const width = Math.round(request.width ?? READING_WIDTH)
203
+ if (!Number.isFinite(width) || width < MIN_WIDTH || width > MAX_WIDTH) throw new CaptureError('capture-width-invalid', 400, { min: MIN_WIDTH, max: MAX_WIDTH })
204
+ const scale = request.scale ?? 1
205
+ return await open(document, 'web', { width, height: READING_HEIGHT, scale, appearance: request.appearance ?? 'light' }, signal, async (tab, problems, out) => {
206
+ 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)
207
+ for (const problem of shown.problems) problems.add(problem)
208
+ const measured = await tab.evaluate(measureSection, { section: section.id, selector: request.measure ?? '', max: CAPTURE_MAX_BOXES })
209
+ if (!measured) throw new CaptureError('capture-slide-missing', 500, { section: section.id })
210
+ const height = Math.min(measured.height, CAPTURE_MAX_HEIGHT)
211
+ const png = await tab.screenshot({ type: 'png', fullPage: true, clip: { x: measured.x, y: measured.y, width: measured.width, height } })
212
+ const file = join(out, `${section.id}-reading-${width}.png`)
213
+ writeFileSync(file, png)
214
+ 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 } : {} }
215
+ return { document, width, frames: [frame], problems: [...problems], images: [png] }
216
+ }, { kind: 'reading', request, source: doc.source })
217
+ }
218
+
219
+ const overview: DocumentCapture['overview'] = async (document, request, signal) => {
220
+ const doc = await options.compiled(document)
221
+ const every = request.steps === 'all'
222
+ const positions = doc.sections.flatMap(section => (every ? Array.from({ length: section.steps + 1 }, (_, step) => step) : [section.steps]).map(step => ({ section, step })))
223
+ if (positions.length === 0 || positions.length > CAPTURE_MAX_OVERVIEW) throw new CaptureError('capture-too-many-frames', 400, { requested: positions.length, max: CAPTURE_MAX_OVERVIEW })
224
+ const shape = slideShape(doc)
225
+ const appearance = request.appearance ?? 'light'
226
+ const columns = Math.max(1, Math.min(8, Math.round(request.columns ?? 4)))
227
+ return await open(document, 'slides', { width: shape.width, height: shape.height, scale: 1, appearance, captions: request.captions }, signal, async (tab, problems, out, newPage) => {
228
+ 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)
229
+ const first = positions[0]!
230
+ await fit(tab, shape, first.section.id, first.step, () => show(first.section.id, first.step))
231
+ // Names that sort in reading order: the page number (from 1) and the step (from 0, as the tools count it) padded.
232
+ const pageWidth = String(doc.sections.length).length
233
+ const stepWidth = String(Math.max(...doc.sections.map(section => section.steps))).length
234
+ const frames: { section: string, slide: number, step: number, file: string, narration: string }[] = [], pictures: Buffer[] = []
235
+ for (const { section, step } of positions) {
236
+ signal?.throwIfAborted()
237
+ for (const problem of (await show(section.id, step)).problems) problems.add(problem)
238
+ const measured = await tab.evaluate(measure, { section: section.id, step, selector: '', width: shape.width, max: 0 })
239
+ if (!measured) throw new CaptureError('capture-slide-missing', 500, { section: section.id, step })
240
+ const png = await tab.screenshot({ type: 'png', clip: { x: measured.slide.x, y: measured.slide.y, width: measured.slide.width, height: measured.slide.height } })
241
+ const file = join(out, `${String(section.index).padStart(pageWidth, '0')}-${String(step).padStart(stepWidth, '0')}-${section.id}.png`)
242
+ writeFileSync(file, png)
243
+ frames.push({ section: section.id, slide: section.index, step, file, narration: narrationOf(section, step) })
244
+ pictures.push(png)
245
+ }
246
+ // Sheets of thumbnails, each labelled with its page, step and title, for reading the whole piece at a glance.
247
+ const sheets: string[] = [], images: Uint8Array[] = []
248
+ const sheet = await newPage()
249
+ await sheet.setViewportSize({ width: columns * (THUMB_WIDTH + SHEET_GAP) + SHEET_GAP, height: READING_HEIGHT })
250
+ for (let start = 0; start < frames.length; start += CAPTURE_SHEET_SIZE) {
251
+ signal?.throwIfAborted()
252
+ 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]! }))
253
+ await sheet.setContent(sheetHtml(cells, columns, appearance), { waitUntil: 'load', timeout: PAGE_MS })
254
+ const png = await sheet.screenshot({ type: 'png', fullPage: true })
255
+ const file = join(out, `sheet-${String(sheets.length + 1).padStart(2, '0')}.png`)
256
+ writeFileSync(file, png)
257
+ sheets.push(file)
258
+ images.push(png)
259
+ }
260
+ // The narration beside the pictures, for a reader who looks at whole slides and reads the script as text.
261
+ const narrationFile = join(out, 'narration.md')
262
+ writeFileSync(narrationFile, frames.map(frame => `## ${basename(frame.file)}\n\n${frame.narration || '—'}\n`).join('\n'))
263
+ return { document, dir: out, frames, narrationFile, sheets, problems: [...problems], images }
264
+ }, { kind: 'overview', request, source: doc.source })
265
+ }
266
+
267
+ /** One capture at a time; the browser closes when none came for a while. */
268
+ const queued = <A extends unknown[], R>(run: (...args: A) => Promise<R>) => (...args: A): Promise<R> => {
269
+ const next = queue.then(async () => {
270
+ try {
271
+ return await run(...args)
272
+ } finally {
273
+ release()
274
+ }
275
+ })
276
+ queue = next.catch(() => undefined)
277
+ return next
278
+ }
279
+
280
+ return {
281
+ service: { slides: queued(slides), reading: queued(reading), overview: queued(overview) },
282
+ close,
283
+ }
284
+ }
285
+
286
+ /**
287
+ * The page fits the slide in its window with a margin: the window is made that much larger, a few times, until the slide
288
+ * shows at its own size.
289
+ */
290
+ async function fit(tab: Page, shape: { width: number, height: number }, section: string, step: number, show: () => Promise<unknown>): Promise<void> {
291
+ let viewport = { width: shape.width, height: shape.height }
292
+ await show()
293
+ for (let round = 0; round < FIT_ROUNDS; round++) {
294
+ const fitted = await tab.evaluate(measure, { section, step, selector: '', width: shape.width, max: 0 })
295
+ if (!fitted || Math.abs(fitted.slide.scale - 1) < 0.005) return
296
+ viewport = { width: Math.round(viewport.width / fitted.slide.scale), height: Math.round(viewport.height / fitted.slide.scale) }
297
+ await tab.setViewportSize(viewport)
298
+ await show()
299
+ }
300
+ }
301
+
302
+ /** A step's narration as text: the script written for it, line by line. */
303
+ function narrationOf(section: IRSection, step: number): string {
304
+ const id = section.stepIds?.[step]
305
+ return (id ? section.stepNarrations?.[id] ?? [] : []).map(line => line.text).join('\n')
306
+ }
307
+
308
+ const escapeHtml = (text: string) => text.replace(/[&<>"]/g, char => `&#${char.charCodeAt(0)};`)
309
+
310
+ /** A sheet of thumbnails with their labels: plain HTML for the capturing browser, not a page of the product. */
311
+ function sheetHtml(cells: { label: string, png: Buffer }[], columns: number, appearance: 'light' | 'dark'): string {
312
+ const [paper, ink, line] = appearance === 'dark' ? ['#16171a', '#e8eaed', '#2e3136'] : ['#ffffff', '#1f2329', '#e3e5e9']
313
+ return `<!doctype html><meta charset="utf-8"><style>
314
+ body { margin: 0; padding: ${SHEET_GAP}px; background: ${paper}; color: ${ink}; font: 13px/1.4 system-ui, sans-serif; }
315
+ main { display: grid; grid-template-columns: repeat(${columns}, ${THUMB_WIDTH}px); gap: ${SHEET_GAP}px; }
316
+ figure { margin: 0; } img { display: block; width: ${THUMB_WIDTH}px; border: 1px solid ${line}; }
317
+ figcaption { margin-top: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
318
+ </style><main>${cells.map(cell => `<figure><img src="data:image/png;base64,${cell.png.toString('base64')}"><figcaption>${escapeHtml(cell.label)}</figcaption></figure>`).join('')}</main>`
319
+ }
320
+
321
+ /** In the page: the slide shown at the step, in viewport pixels, and the boxes of `selector` in it, in slide pixels. */
322
+ 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 {
323
+ const slides = [...document.querySelectorAll<HTMLElement>(`.pm-slide[data-section="${CSS.escape(section)}"]`)]
324
+ const slide = slides.find(element => element.dataset.step === String(step) && element.getBoundingClientRect().width > 0) ?? slides.find(element => element.getBoundingClientRect().width > 0)
325
+ if (!slide) return undefined
326
+ const frame = slide.getBoundingClientRect()
327
+ const scale = frame.width / width
328
+ const round = (value: number) => Math.round(value * 10) / 10
329
+ const boxes: CapturedBox[] = []
330
+ if (selector) {
331
+ for (const element of [...slide.querySelectorAll<HTMLElement>(selector)].slice(0, max)) {
332
+ const box = element.getBoundingClientRect()
333
+ const style = getComputedStyle(element)
334
+ const attributes: Record<string, string> = {}
335
+ 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)
336
+ boxes.push({
337
+ x: round((box.left - frame.left) / scale),
338
+ y: round((box.top - frame.top) / scale),
339
+ width: round(box.width / scale),
340
+ height: round(box.height / scale),
341
+ visible: box.width > 0 && box.height > 0 && style.visibility !== 'hidden' && style.display !== 'none' && Number(style.opacity) > 0,
342
+ text: (element.textContent ?? '').replace(/\s+/g, ' ').trim().slice(0, 80),
343
+ attributes,
344
+ })
345
+ }
346
+ }
347
+ return { slide: { x: frame.left, y: frame.top, width: frame.width, height: frame.height, scale }, boxes }
348
+ }
349
+
350
+ /** In the page: the section of the reading page, in page pixels, and the boxes of `selector` in it, relative to it. */
351
+ function measureSection({ section, selector, max }: { section: string, selector: string, max: number }): { x: number, y: number, width: number, height: number, boxes: CapturedBox[] } | undefined {
352
+ const element = document.querySelector<HTMLElement>(`section.pm-section[data-section="${CSS.escape(section)}"]`)
353
+ if (!element) return undefined
354
+ const frame = element.getBoundingClientRect()
355
+ const round = (value: number) => Math.round(value * 10) / 10
356
+ const boxes: CapturedBox[] = []
357
+ if (selector) {
358
+ for (const node of [...element.querySelectorAll<HTMLElement>(selector)].slice(0, max)) {
359
+ const box = node.getBoundingClientRect()
360
+ const style = getComputedStyle(node)
361
+ const attributes: Record<string, string> = {}
362
+ 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)
363
+ boxes.push({
364
+ x: round(box.left - frame.left),
365
+ y: round(box.top - frame.top),
366
+ width: round(box.width),
367
+ height: round(box.height),
368
+ visible: box.width > 0 && box.height > 0 && style.visibility !== 'hidden' && style.display !== 'none' && Number(style.opacity) > 0,
369
+ text: (node.textContent ?? '').replace(/\s+/g, ' ').trim().slice(0, 80),
370
+ attributes,
371
+ })
372
+ }
373
+ }
374
+ return { x: frame.left + window.scrollX, y: frame.top + window.scrollY, width: frame.width, height: frame.height, boxes }
375
+ }
376
+
377
+ /** Keeps the pictures of the last few requests. */
378
+ function prune(dir: string): void {
379
+ try {
380
+ const runs = readdirSync(dir, { withFileTypes: true }).filter(entry => entry.isDirectory() && entry.name !== 'retained').map(entry => ({ path: join(dir, entry.name), time: statSync(join(dir, entry.name)).mtimeMs })).sort((a, b) => b.time - a.time)
381
+ for (const run of runs.slice(KEEP)) rmSync(run.path, { recursive: true, force: true })
382
+ } catch {}
383
+ }