@lincyaw/workspace 1.0.0-rc.90 → 1.0.0-rc.91

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 (2) hide show
  1. package/package.json +6 -6
  2. package/src/node/capture.ts +39 -12
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workspace",
3
- "version": "1.0.0-rc.90",
3
+ "version": "1.0.0-rc.91",
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": {
@@ -34,13 +34,13 @@
34
34
  "mime-types": "3.0.2",
35
35
  "playwright-chromium": "1.64.1",
36
36
  "yaml": "^2.9.1",
37
- "@lincyaw/compiler": "1.0.0-rc.90",
38
- "@lincyaw/server": "1.0.0-rc.90",
39
- "@lincyaw/kernel": "1.0.0-rc.90",
40
- "@lincyaw/design": "1.0.0-rc.90"
37
+ "@lincyaw/compiler": "1.0.0-rc.91",
38
+ "@lincyaw/server": "1.0.0-rc.91",
39
+ "@lincyaw/kernel": "1.0.0-rc.91",
40
+ "@lincyaw/design": "1.0.0-rc.91"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@types/mime-types": "^3.0.1",
44
- "@lincyaw/mcp": "1.0.0-rc.90"
44
+ "@lincyaw/mcp": "1.0.0-rc.91"
45
45
  }
46
46
  }
@@ -1,7 +1,8 @@
1
1
  import { mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
2
+ import { randomUUID } from 'node:crypto'
2
3
  import { basename, join } from 'node:path'
3
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'
4
- import type { CapturedBox, CapturedSlide, CaptureHook, DocumentCapture, IRDocument, IRSection } from '@lincyaw/kernel'
5
+ import type { CanonicalSource, CaptureEvidence, CapturedBox, CapturedSlide, CaptureHook, DocumentCapture, IRDocument, IRSection, OverviewCaptureRequest, ReadingCaptureRequest, SlideCaptureRequest } from '@lincyaw/kernel'
5
6
  import { playwrightChromium } from '@lincyaw/kernel/node'
6
7
 
7
8
  /** What capturing uses of Playwright's Chromium. */
@@ -38,6 +39,13 @@ export interface CaptureOptions {
38
39
  }
39
40
 
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
41
49
 
42
50
  const PAGE_MS = 120_000
43
51
  const IDLE_MS = 120_000
@@ -98,7 +106,7 @@ export function createDocumentCapture(options: CaptureOptions): { service: Docum
98
106
  }
99
107
 
100
108
  /** 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> => {
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 }> => {
102
110
  const page = await options.viewerPage(document).catch((error: unknown) => {
103
111
  throw new CaptureError('capture-preview-failed', 409, { reason: errorMessage(error) })
104
112
  })
@@ -106,6 +114,8 @@ export function createDocumentCapture(options: CaptureOptions): { service: Docum
106
114
  signal?.throwIfAborted()
107
115
  const context = await (await launch()).newContext({ viewport: { width: view.width, height: view.height }, deviceScaleFactor: view.scale, reducedMotion: 'reduce', colorScheme: view.appearance, serviceWorkers: 'block' })
108
116
  const problems = new Set<string>()
117
+ let directory: string | undefined
118
+ let complete = false
109
119
  try {
110
120
  const tab = await context.newPage()
111
121
  tab.on('pageerror', error => problems.add(error.message))
@@ -117,9 +127,23 @@ export function createDocumentCapture(options: CaptureOptions): { service: Docum
117
127
  address.searchParams.set(PREVIEW_APPEARANCE_PARAM, view.appearance)
118
128
  await tab.goto(address.href, { waitUntil: 'load', timeout: PAGE_MS })
119
129
  await tab.waitForFunction(`Boolean(window.${CAPTURE_HOOK})`, undefined, { timeout: PAGE_MS })
120
- const out = join(options.dir, `${new Date().toISOString().replace(/[:.]/g, '-')}-${process.pid}`)
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
121
137
  mkdirSync(out, { recursive: true })
122
- return await run(tab, problems, out)
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 }
123
147
  } catch (error) {
124
148
  if (error instanceof CaptureError || signal?.aborted) throw error
125
149
  // A page that loads again while it is driven loses its hook: going back reloaded it.
@@ -127,11 +151,13 @@ export function createDocumentCapture(options: CaptureOptions): { service: Docum
127
151
  throw new CaptureError('capture-failed', 500, { reason: errorMessage(error), problems: [...problems] })
128
152
  } finally {
129
153
  await context.close().catch(() => undefined)
154
+ if (!complete && directory) rmSync(directory, { recursive: true, force: true })
130
155
  prune(options.dir)
131
156
  }
132
157
  }
133
158
 
134
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)
135
161
  const doc = await options.compiled(document)
136
162
  const section = sectionOf(doc, request.section)
137
163
  const steps = request.steps ?? Array.from({ length: section.steps + 1 }, (_, step) => step)
@@ -167,7 +193,7 @@ export function createDocumentCapture(options: CaptureOptions): { service: Docum
167
193
  }
168
194
  }
169
195
  return { document, shape: { width: shape.width, height: shape.height }, frames, problems: [...problems], images }
170
- })
196
+ }, { kind: 'slides', request, source: doc.source })
171
197
  }
172
198
 
173
199
  const reading: DocumentCapture['reading'] = async (document, request, signal) => {
@@ -187,7 +213,7 @@ export function createDocumentCapture(options: CaptureOptions): { service: Docum
187
213
  writeFileSync(file, png)
188
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 } : {} }
189
215
  return { document, width, frames: [frame], problems: [...problems], images: [png] }
190
- })
216
+ }, { kind: 'reading', request, source: doc.source })
191
217
  }
192
218
 
193
219
  const overview: DocumentCapture['overview'] = async (document, request, signal) => {
@@ -198,7 +224,7 @@ export function createDocumentCapture(options: CaptureOptions): { service: Docum
198
224
  const shape = slideShape(doc)
199
225
  const appearance = request.appearance ?? 'light'
200
226
  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) => {
227
+ return await open(document, 'slides', { width: shape.width, height: shape.height, scale: 1, appearance, captions: request.captions }, signal, async (tab, problems, out, newPage) => {
202
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)
203
229
  const first = positions[0]!
204
230
  await fit(tab, shape, first.section.id, first.step, () => show(first.section.id, first.step))
@@ -219,12 +245,13 @@ export function createDocumentCapture(options: CaptureOptions): { service: Docum
219
245
  }
220
246
  // Sheets of thumbnails, each labelled with its page, step and title, for reading the whole piece at a glance.
221
247
  const sheets: string[] = [], images: Uint8Array[] = []
222
- await tab.setViewportSize({ width: columns * (THUMB_WIDTH + SHEET_GAP) + SHEET_GAP, height: READING_HEIGHT })
248
+ const sheet = await newPage()
249
+ await sheet.setViewportSize({ width: columns * (THUMB_WIDTH + SHEET_GAP) + SHEET_GAP, height: READING_HEIGHT })
223
250
  for (let start = 0; start < frames.length; start += CAPTURE_SHEET_SIZE) {
224
251
  signal?.throwIfAborted()
225
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]! }))
226
- await tab.setContent(sheetHtml(cells, columns, appearance), { waitUntil: 'load', timeout: PAGE_MS })
227
- const png = await tab.screenshot({ type: 'png', fullPage: true })
253
+ await sheet.setContent(sheetHtml(cells, columns, appearance), { waitUntil: 'load', timeout: PAGE_MS })
254
+ const png = await sheet.screenshot({ type: 'png', fullPage: true })
228
255
  const file = join(out, `sheet-${String(sheets.length + 1).padStart(2, '0')}.png`)
229
256
  writeFileSync(file, png)
230
257
  sheets.push(file)
@@ -234,7 +261,7 @@ export function createDocumentCapture(options: CaptureOptions): { service: Docum
234
261
  const narrationFile = join(out, 'narration.md')
235
262
  writeFileSync(narrationFile, frames.map(frame => `## ${basename(frame.file)}\n\n${frame.narration || '—'}\n`).join('\n'))
236
263
  return { document, dir: out, frames, narrationFile, sheets, problems: [...problems], images }
237
- })
264
+ }, { kind: 'overview', request, source: doc.source })
238
265
  }
239
266
 
240
267
  /** One capture at a time; the browser closes when none came for a while. */
@@ -350,7 +377,7 @@ function measureSection({ section, selector, max }: { section: string, selector:
350
377
  /** Keeps the pictures of the last few requests. */
351
378
  function prune(dir: string): void {
352
379
  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)
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)
354
381
  for (const run of runs.slice(KEEP)) rmSync(run.path, { recursive: true, force: true })
355
382
  } catch {}
356
383
  }