@lincyaw/workspace 1.0.0-rc.4 → 1.0.0-rc.41

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.4",
3
+ "version": "1.0.0-rc.41",
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.4",
37
- "@lincyaw/kernel": "1.0.0-rc.4",
38
- "@lincyaw/server": "1.0.0-rc.4"
37
+ "@lincyaw/compiler": "1.0.0-rc.41",
38
+ "@lincyaw/kernel": "1.0.0-rc.41",
39
+ "@lincyaw/server": "1.0.0-rc.41"
39
40
  },
40
41
  "devDependencies": {
41
42
  "@types/mime-types": "^3.0.1",
42
- "@lincyaw/mcp": "1.0.0-rc.4"
43
+ "@lincyaw/mcp": "1.0.0-rc.41"
43
44
  }
44
45
  }
@@ -7,7 +7,7 @@ import { catchRequestErrors, RequestError } from './errors.ts'
7
7
  import type { SourceEditor } from './source-editor.ts'
8
8
 
9
9
  type Client = { member: string, credential: string, value: AuthoringClientDescriptor, sequence: number, lastSignature?: string, send?(value: AuthoringClientEvent): void, close?(): void }
10
- type Pending = { member: string, signature: string, request: AuthoringClientRequest, value: AuthoringClientRequestResult, timer?: ReturnType<typeof setTimeout> }
10
+ type Pending = { member: string, signature: string, request: AuthoringClientRequest, value: AuthoringClientRequestResult, timer?: ReturnType<typeof setTimeout>, done: Promise<void>, resolve(): void }
11
11
  const sameSource = (a: CanonicalSource, b: CanonicalSource) => a.documentId === b.documentId && a.version === b.version && a.fingerprint === b.fingerprint
12
12
  const size = (value: unknown) => JSON.stringify(value, null, 2).length
13
13
  const budget = (value: unknown, maximum = AUTHORING_CLIENT_MAX_REQUEST_CHARS) => { const text = JSON.stringify(value); if (text === undefined) throw new RequestError(400, 'client-request-invalid'); if (text.length > maximum) throw new RequestError(413, 'client-request-too-large') }
@@ -41,6 +41,7 @@ export function createAuthoringClients(editor: SourceEditor) {
41
41
  if (terminal(pending)) return
42
42
  clearTimeout(pending.timer); pending.timer = undefined
43
43
  pending.value = { ...pending.value, state, ...code ? { error: { code } } : {} }
44
+ pending.resolve()
44
45
  if (state === 'expired') clients.get(clientKey(pending.member, pending.request.clientId))?.send?.({ type: 'cancel', requestId: pending.request.requestId, connectionId: pending.request.expectedClientState.connectionId })
45
46
  }
46
47
  const disconnect = (client: Client, connectionId: string) => {
@@ -95,7 +96,9 @@ export function createAuthoringClients(editor: SourceEditor) {
95
96
  }
96
97
  const now = Date.now(), value: AuthoringClientRequestResult = { document, clientId: state.clientId, epoch: state.epoch, connectionId: state.connectionId, requestId: request.requestId, action: request.action.type, source: request.source,
97
98
  state: 'sent', admittedAt: new Date(now).toISOString(), expiresAt: new Date(now + AUTHORING_CLIENT_REQUEST_TIMEOUT_MS).toISOString(), verification: 'not-acknowledged', current: false }
98
- const pending: Pending = { member: member.id, signature, request: structuredClone(request), value }
99
+ let resolve!: () => void
100
+ const done = new Promise<void>(finish => resolve = finish)
101
+ const pending: Pending = { member: member.id, signature, request: structuredClone(request), value, done, resolve }
99
102
  pending.timer = setTimeout(() => finish(pending, 'expired', 'client-request-timeout'), AUTHORING_CLIENT_REQUEST_TIMEOUT_MS)
100
103
  requests.set(key, pending)
101
104
  client.send?.({ type: 'request', request: pending.request, expiresAt: value.expiresAt })
@@ -194,7 +197,23 @@ export function createAuthoringClients(editor: SourceEditor) {
194
197
  if (!validateAuthoringClientReport(value.report)) throw new RequestError(400, 'client-report-invalid')
195
198
  report(connection(ctx.document, value.connection, ctx.member), value.report, digest(value.report)); return jsonResponse({ accepted: true })
196
199
  }) })
197
- return { service, routes: {
200
+ return { service,
201
+ async flush(documents: string[], member: Member): Promise<void> {
202
+ const active = [...clients.values()].filter(client => client.member === member.id && client.value.connected && documents.includes(client.value.document))
203
+ await Promise.all(active.map(async client => {
204
+ const state = client.value
205
+ if (!state.snapshot.actions.includes('source.flush')) {
206
+ if (state.snapshot.editing.dirty || state.snapshot.editing.saving || state.snapshot.editing.composing || state.snapshot.editing.conflicted) throw new RequestError(409, 'agent-author-editing', { next: 'The author has unconfirmed input. Read the current author files and retry after that input is saved. Nothing was published.' })
207
+ return
208
+ }
209
+ const request: AuthoringClientRequest = { clientId: state.clientId, epoch: state.epoch, requestId: randomUUID(), source: state.snapshot.source,
210
+ expectedClientState: { connectionId: state.connectionId, revision: state.snapshot.revision }, action: { type: 'source.flush' } }
211
+ await service.request(state.document, request, member)
212
+ const pending = requests.get(requestKey(member.id, state.document, request))!
213
+ await pending.done
214
+ if (pending.value.state !== 'done') throw new RequestError(409, 'agent-author-editing', { next: 'The author client could not confirm its saved input. Read the current author files and retry. Nothing was published.' })
215
+ }))
216
+ }, routes: {
198
217
  'authoring-clients/register': post('register'), 'authoring-clients/report': post('report'), 'authoring-clients/ack': post('ack'),
199
218
  'authoring-clients/events': { role: 'editor', handle: (request, ctx) => catchRequestErrors(async () => {
200
219
  if (request.method !== 'GET') return problemResponse(405, 'GET')
@@ -202,5 +221,5 @@ export function createAuthoringClients(editor: SourceEditor) {
202
221
  if (!validateAuthoringClientLease(lease)) throw new RequestError(400, 'client-connection-invalid')
203
222
  return sseResponse(open(ctx.document, lease, ctx.member, request.signal), request.signal)
204
223
  }) } satisfies Route,
205
- }, async close() { closed = true; for (const client of clients.values()) client.close?.(); for (const pending of requests.values()) clearTimeout(pending.timer); requests.clear(); clients.clear() } }
224
+ }, async close() { closed = true; for (const client of clients.values()) client.close?.(); for (const pending of requests.values()) finish(pending, 'expired', 'client-owner-closed'); requests.clear(); clients.clear() } }
206
225
  }
package/src/node/build.ts CHANGED
@@ -1,9 +1,10 @@
1
- import { cpSync, existsSync, rmSync } from 'node:fs'
2
- import { join, resolve } from 'node:path'
3
- import { build, Compiler } from '@lincyaw/compiler'
1
+ import { cpSync, existsSync, readdirSync, rmSync } from 'node:fs'
2
+ import { isAbsolute, join, resolve } from 'node:path'
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'
6
- import type { Finding } from '@lincyaw/kernel'
5
+ import { APP_DIR, errorMessage, isRecord, SLIDES_DIR } from '@lincyaw/kernel'
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
 
@@ -21,9 +22,11 @@ export async function buildWorkspace(root: string, options: { outDir?: string, b
21
22
  const site = siteSpec(config, [])
22
23
  const base = siteBase(config.site.base)
23
24
  const forms: { dir: string, compilation: Compilation, to: string[] }[] = []
25
+ const compilations: Compilation[] = []
24
26
  for (const document of found) {
25
27
  const compilation = await new Compiler(join(config.root, document.entry), { bundled: options.bundled, settings: config.settings }).compile({ pruneCache: true })
26
- const to = presentations(compilation, `${base}${document.dir.split('/').map(encodeURIComponent).join('/')}/`)
28
+ compilations.push(compilation)
29
+ const to = presentations(compilation, base, `${base}${urlPath(document.dir)}/`, siteLook(config.site, config.root, document.dir))
27
30
  if (to.length > 0) forms.push({ dir: document.dir, compilation, to })
28
31
  const translated = await siteTranslations(compilation)
29
32
  findings.push(...compilation.doc.diagnostics, ...translated.findings)
@@ -33,6 +36,7 @@ export async function buildWorkspace(root: string, options: { outDir?: string, b
33
36
  const outDir = join(resolve(options.outDir ?? join(config.root, 'dist')), 'web')
34
37
  const renderer = await webRenderer(config.root, options.bundled)
35
38
  const ctx = siteContext({ root: config.root, outDir, workDir: join(config.root, '.presmium', 'site'), base, findings })
39
+ ctx.pluginDirs = pluginsByName(site, compilations)
36
40
  try {
37
41
  await renderer.buildSite!(site, ctx)
38
42
  } catch (error) {
@@ -47,6 +51,7 @@ export async function buildWorkspace(root: string, options: { outDir?: string, b
47
51
  const report = await build(compilation, { outDir: work, to })
48
52
  findings.push(...report.findings)
49
53
  for (const form of to) if (existsSync(join(work, form))) cpSync(join(work, form), join(outDir, dir, form), { recursive: true })
54
+ if (to.includes('slides')) moveApps(join(outDir, dir, SLIDES_DIR), outDir)
50
55
  } catch (error) {
51
56
  findings.push({ checkId: 'presmium.render', severity: 'error', message: `document ${dir}: its ${to.join(' and ')} failed: ${errorMessage(error)}` })
52
57
  }
@@ -54,20 +59,72 @@ export async function buildWorkspace(root: string, options: { outDir?: string, b
54
59
  return { outDir, documents, findings }
55
60
  }
56
61
 
62
+ /**
63
+ * The site's documents name their plugins by package, as a presentation built alone does, so the pages and the
64
+ * presentations share one viewer app (its key follows the plugin names); the site resolves each name to the directory
65
+ * it was loaded from. A name that two documents load from different directories stays a directory, to tell them apart.
66
+ */
67
+ function pluginsByName(site: SiteSpec, compilations: readonly Compilation[]): Record<string, string> {
68
+ const dirs = new Map<string, Set<string>>(), names = new Map<string, string>()
69
+ for (const { plugins } of compilations) for (const { name, dir } of plugins) {
70
+ let own = dirs.get(name)
71
+ if (!own) dirs.set(name, own = new Set())
72
+ own.add(dir)
73
+ names.set(dir, name)
74
+ }
75
+ const unique = new Map([...dirs].filter(([, own]) => own.size === 1).map(([name, own]) => [name, [...own][0]!]))
76
+ const byName = (doc: IRDocument): IRDocument => ({ ...doc, config: { ...doc.config, plugins: doc.config.plugins.map(dir => names.has(dir) && unique.has(names.get(dir)!) ? names.get(dir)! : dir) } })
77
+ for (const entry of site.documents) {
78
+ if (entry.doc) entry.doc = byName(entry.doc)
79
+ for (const translation of entry.translations ?? []) translation.doc = byName(translation.doc)
80
+ }
81
+ return Object.fromEntries(unique)
82
+ }
83
+
57
84
  const PRESENTATIONS = ['slides', 'lecture']
58
85
 
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> {
92
+ const theme = typeof site.theme === 'string' && (site.theme.startsWith('.') || isAbsolute(site.theme)) ? resolve(root, site.theme) : site.theme
93
+ return { ...theme !== undefined ? { theme } : {}, ...isRecord(site.params) ? { params: site.params, siteFile: relativePath(dir, WORKSPACE_CONFIG) } : {} }
94
+ }
95
+
96
+ const urlPath = (dir: string) => dir.split('/').map(encodeURIComponent).join('/')
97
+
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
+ }
105
+
59
106
  /**
60
107
  * The presentation forms a document asks for (`metadata.renderers.slides` or `lecture`), set to be served below its
61
- * 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.
62
109
  */
63
- function presentations(compilation: Compilation, prefix: string): string[] {
110
+ function presentations(compilation: Compilation, base: string, prefix: string, look: Record<string, unknown>): string[] {
64
111
  const { renderers } = compilation.doc.config
65
112
  const to = PRESENTATIONS.filter(form => renderers[form] !== undefined)
66
113
  if (to.length === 0) return to
67
- if (to.includes('slides')) renderers.slides = { ...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 lecture.json, 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
+ }
68
120
  const settings = compilation.doc.config.presmium ??= {}
69
121
  const web = isRecord(settings['presmium.web']) ? settings['presmium.web'] : {}
70
- 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}/` } : {} }
123
+ // The slides find the lecture where it is built, without probing `slides/lecture/` first.
124
+ if (to.includes('lecture')) {
125
+ const lecture = isRecord(settings['presmium.lecture']) ? settings['presmium.lecture'] : {}
126
+ settings['presmium.lecture'] = { url: `${prefix}lecture/`, ...lecture }
127
+ }
71
128
  return to
72
129
  }
73
130
 
@@ -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
 
@@ -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)
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