@lincyaw/workspace 1.0.0-rc.16 → 1.0.0-rc.160

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 (60) hide show
  1. package/README.md +6 -4
  2. package/package.json +11 -6
  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 +16 -6
  9. package/src/node/capture.ts +40 -13
  10. package/src/node/config.ts +135 -50
  11. package/src/node/document-assets.ts +2 -2
  12. package/src/node/document-audio.ts +66 -47
  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 +34 -6
  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 +654 -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 +85 -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 +211 -68
  39. package/src/node/review/agent-workspace.ts +151 -0
  40. package/src/node/review/git-review.ts +72 -29
  41. package/src/node/review/record.ts +41 -9
  42. package/src/node/review/routes.ts +9 -1
  43. package/src/node/review/windows-dependencies.ts +163 -0
  44. package/src/node/review/workspace-review.ts +87 -0
  45. package/src/node/revision-files.ts +54 -0
  46. package/src/node/revisions.ts +318 -80
  47. package/src/node/routes.ts +52 -59
  48. package/src/node/serve.ts +216 -46
  49. package/src/node/site.ts +5 -5
  50. package/src/node/source-editor.ts +66 -26
  51. package/src/node/speech-settings.ts +6 -8
  52. package/src/node/templates.ts +2 -2
  53. package/src/node/tree-operations.ts +425 -0
  54. package/src/node/tree-routes.ts +107 -0
  55. package/src/node/workbench-api.ts +14 -3
  56. package/src/node/workspace-changes.ts +130 -0
  57. package/src/node/workspace-migrate.ts +54 -0
  58. package/src/node/workspace-source.ts +133 -0
  59. package/src/node/writer.ts +21 -8
  60. package/templates/document/default/{lecture.json → index.pmd} +5 -1
package/src/node/build.ts CHANGED
@@ -1,9 +1,10 @@
1
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
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, `${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)
@@ -82,10 +83,14 @@ 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('/')
@@ -106,7 +111,12 @@ function presentations(compilation: Compilation, base: string, prefix: string, l
106
111
  const { renderers } = compilation.doc.config
107
112
  const to = PRESENTATIONS.filter(form => renderers[form] !== undefined)
108
113
  if (to.length === 0) return to
109
- if (to.includes('slides')) renderers.slides = { ...look, ...isRecord(renderers.slides) ? renderers.slides : {}, base: `${prefix}${SLIDES_DIR}/`, appBase: base }
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
+ }
110
120
  const settings = compilation.doc.config.presmium ??= {}
111
121
  const web = isRecord(settings['presmium.web']) ? settings['presmium.web'] : {}
112
122
  settings['presmium.web'] = { ...web, webUrl: prefix, ...to.includes('slides') ? { slidesUrl: `${prefix}${SLIDES_DIR}/` } : {} }
@@ -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. */
@@ -282,7 +309,7 @@ const escapeHtml = (text: string) => text.replace(/[&<>"]/g, char => `&#${char.c
282
309
 
283
310
  /** A sheet of thumbnails with their labels: plain HTML for the capturing browser, not a page of the product. */
284
311
  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']
312
+ const [paper, ink, line] = appearance === 'dark' ? ['#16171a', '#e8eaed', '#2e3136'] : ['#ffffff', '#1f2329', '#e3e5e9']
286
313
  return `<!doctype html><meta charset="utf-8"><style>
287
314
  body { margin: 0; padding: ${SHEET_GAP}px; background: ${paper}; color: ${ink}; font: 13px/1.4 system-ui, sans-serif; }
288
315
  main { display: grid; grid-template-columns: repeat(${columns}, ${THUMB_WIDTH}px); gap: ${SHEET_GAP}px; }
@@ -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
  }
@@ -1,28 +1,29 @@
1
- import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs'
1
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
2
2
  import { join, resolve } from 'node:path'
3
- import { WORKSPACE_CONFIG } from '@lincyaw/compiler'
4
- import type { OperatorSettings } from '@lincyaw/compiler'
3
+ import { effectiveDocumentIn, providedDocuments, inheritedSettingsIn, settingOriginsIn, WORKSPACE_CONFIG, workspaceDefaults, workspaceDocuments, workspaceSettings } from '@lincyaw/compiler'
4
+ import type { OperatorSettings, WorkspaceDocuments } from '@lincyaw/compiler'
5
5
  import { APPROVAL_KINDS, DOCUMENT_ENTRY, errorMessage, isRecord } from '@lincyaw/kernel'
6
- import type { ApprovalKind, DocumentSummary } from '@lincyaw/kernel'
6
+ import type { ApprovalKind, DocumentDefaults, DocumentSummary, EffectiveDocument, PresmiumDocument, SettingOrigins } from '@lincyaw/kernel'
7
7
  import type { ApprovalPolicy } from '@lincyaw/server'
8
8
  import { parse as parseYaml } from 'yaml'
9
- import { matchesPattern, patternSegments } from '../domain/paths.ts'
10
9
 
11
- export const DEFAULT_DOCUMENTS = [`*/${DOCUMENT_ENTRY}`]
12
-
13
- const SKIPPED = new Set(['node_modules', '.git', '.presmium', 'dist'])
10
+ const SKIPPED = new Set(['node_modules', '.git', '.presmium', 'dist', '.trash'])
14
11
 
15
12
  const POLICIES = new Set<ApprovalPolicy>(['off', 'ask', 'allow'])
16
13
 
17
14
  export interface WorkspaceConfig {
18
15
  root: string
19
16
  title: string
20
- documents: string[]
17
+ /** A folder whose own entry file is the only document. */
21
18
  singleDeck: boolean
22
19
  site: Record<string, unknown>
23
20
  approvals: Partial<Record<ApprovalKind, ApprovalPolicy>>
24
21
  templates?: string
25
22
  settings: OperatorSettings
23
+ /** The root of the documents' inherited settings. */
24
+ defaults: DocumentDefaults
25
+ /** The workspace file still lists `documents:`; `presmium migrate` or Studio's Upgrade removes it. */
26
+ needsMigration: boolean
26
27
  }
27
28
 
28
29
  function strings(value: unknown): string[] {
@@ -41,23 +42,23 @@ export function readWorkspaceConfig(root: string): WorkspaceConfig {
41
42
  throw new Error(`${file}: ${errorMessage(error)}`)
42
43
  }
43
44
  }
44
- const declared = strings(data.documents)
45
- const singleDeck = declared.length === 0 && existsSync(join(dir, DOCUMENT_ENTRY))
45
+ const singleDeck = existsSync(join(dir, DOCUMENT_ENTRY))
46
46
  const approvals = isRecord(data.approvals) ? data.approvals : {}
47
47
  const settings = isRecord(data.settings) ? data.settings : {}
48
48
  const renderers = isRecord(data.renderers) ? data.renderers : {}
49
49
  for (const [path, value] of [['renderers.lecture', renderers.lecture], ['settings.presmium.lecture', settings['presmium.lecture']]] as const) {
50
- if (isRecord(value) && Object.hasOwn(value, 'script')) throw new Error(`${file}: ${path}.script: External lecture scripts are not supported. Author narration in each document's lecture.json narrations.`)
50
+ if (isRecord(value) && Object.hasOwn(value, 'script')) throw new Error(`${file}: ${path}.script: External lecture scripts are not supported. Author narration in each document's narrations.`)
51
51
  }
52
52
  return {
53
53
  root: dir,
54
54
  title: typeof data.title === 'string' && data.title.trim() ? data.title.trim() : dir.split('/').at(-1) ?? 'Presmium',
55
- documents: singleDeck ? [DOCUMENT_ENTRY] : declared.length > 0 ? declared : DEFAULT_DOCUMENTS,
56
55
  singleDeck,
57
56
  site: isRecord(data.site) ? data.site : {},
58
57
  approvals: Object.fromEntries(APPROVAL_KINDS.flatMap(kind => (POLICIES.has(approvals[kind] as ApprovalPolicy) ? [[kind, approvals[kind] as ApprovalPolicy]] : []))),
59
58
  ...typeof data.templates === 'string' && data.templates.trim() ? { templates: resolve(dir, data.templates.trim()) } : {},
60
59
  settings: Object.fromEntries(Object.entries(settings).map(([id, value]) => [id, isRecord(value) ? value : {}])),
60
+ defaults: workspaceDefaults(data.defaults),
61
+ needsMigration: data.documents !== undefined,
61
62
  }
62
63
  }
63
64
 
@@ -70,51 +71,67 @@ export function isWorkspaceRoot(dir: string): boolean {
70
71
  }
71
72
  }
72
73
 
73
- function entries(config: WorkspaceConfig): string[] {
74
- const found: string[] = []
75
- for (const pattern of config.documents) {
76
- const parts = patternSegments(pattern)
77
- const walk = (dir: string, rel: string, i: number): string[] => {
78
- const part = parts[i]!
79
- const last = i === parts.length - 1
80
- const names = typeof part === 'string'
81
- ? [part]
82
- : (() => {
83
- try {
84
- return readdirSync(dir).filter(name => !SKIPPED.has(name) && !name.startsWith('.') && part.test(name)).sort()
85
- } catch {
86
- return []
87
- }
88
- })()
89
- return names.flatMap((name) => {
90
- const path = join(dir, name)
91
- const next = rel ? `${rel}/${name}` : name
92
- if (last) return name === DOCUMENT_ENTRY && existsSync(path) && statSync(path).isFile() ? [next] : []
93
- return existsSync(path) && statSync(path).isDirectory() ? walk(path, next, i + 1) : []
94
- })
95
- }
96
- for (const entry of walk(config.root, '', 0)) if (!found.includes(entry)) found.push(entry)
97
- }
98
- return found
99
- }
100
-
101
74
  export interface DocumentEntry {
102
75
  dir: string
103
76
  entry: string
104
77
  }
105
78
 
106
- export interface FoundDocument extends DocumentSummary, DocumentEntry {}
79
+ export interface FoundDocument extends DocumentSummary, DocumentEntry {
80
+ /** The folder of the document it is under in the tree; absent at the top level. */
81
+ parentDir?: string
82
+ }
83
+
84
+ const entryOf = (path: string): DocumentEntry => ({ dir: path.split('/').slice(0, -1).join('/'), entry: path })
107
85
 
108
- /** The configured documents that exist on disk, without reading their content. */
86
+ /**
87
+ * The documents on disk, without validating them: in a workspace every entry file found by the scan, in tree order
88
+ * (depth first, siblings by rank); entries the tree leaves out (a second document with a taken ID) follow by path.
89
+ */
109
90
  export function listDocumentEntries(config: WorkspaceConfig): DocumentEntry[] {
110
- return entries(config).map(entry => ({ dir: entry.split('/').slice(0, -1).join('/'), entry }))
91
+ if (config.singleDeck) return [{ dir: '', entry: DOCUMENT_ENTRY }]
92
+ const { documents, tree } = workspaceDocuments(config.root)
93
+ const ordered = tree.order.map(node => node.path)
94
+ const listed = new Set(ordered)
95
+ return [...ordered, ...documents.map(document => document.path).filter(path => !listed.has(path))].map(entryOf)
111
96
  }
112
97
 
113
- export function readDocumentSummary(config: WorkspaceConfig, { dir, entry }: DocumentEntry): FoundDocument {
98
+ /** The tree position of every listed document, by folder. */
99
+ export function documentPlaces(config: WorkspaceConfig): Map<string, { id: string, parent: string | null, depth: number, schemaVersion: unknown }> {
100
+ if (config.singleDeck) return new Map()
101
+ const { documents, tree } = workspaceDocuments(config.root)
102
+ const versions = new Map(documents.map(document => [document.path, document.schemaVersion]))
103
+ return new Map(tree.order.map(node => [entryOf(node.path).dir, { id: node.id, parent: node.parent, depth: node.depth, schemaVersion: versions.get(node.path) }]))
104
+ }
105
+
106
+ /** The metadata a document decides with (its language, plugins, renderers), inherited settings filled in. */
107
+ function effectiveMetadata(config: WorkspaceConfig, entry: string, parsed: unknown, scanned?: WorkspaceDocuments): Record<string, unknown> {
108
+ if (!isRecord(parsed) || !isRecord(parsed.metadata)) return {}
109
+ if (!isRecord(parsed.production) || !isRecord(parsed.placement)) return parsed.metadata
110
+ return effectiveDocumentIn(config.root, join(config.root, entry), parsed as unknown as PresmiumDocument, scanned).metadata as unknown as Record<string, unknown>
111
+ }
112
+
113
+ /** What a summary needs of a document file (not its pages or blocks), kept until the file changes. */
114
+ const heads = new Map<string, { mtimeMs: number, size: number, value: unknown }>()
115
+ const headOf = (parsed: unknown) => isRecord(parsed) ? { id: parsed.id, schemaVersion: parsed.schemaVersion, placement: parsed.placement, metadata: parsed.metadata, production: parsed.production } : parsed
116
+ function documentHead(file: string): unknown {
117
+ const stat = statSync(file)
118
+ const known = heads.get(file)
119
+ if (known && known.mtimeMs === stat.mtimeMs && known.size === stat.size) return known.value
120
+ const value = headOf(JSON.parse(readFileSync(file, 'utf8')))
121
+ heads.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, value })
122
+ return value
123
+ }
124
+
125
+ /** A document file another reader (the document index, reading asynchronously) has just parsed: listing it needs no second read. */
126
+ export function primeDocumentHead(file: string, mtimeMs: number, size: number, parsed: unknown): void {
127
+ heads.set(file, { mtimeMs, size, value: headOf(parsed) })
128
+ }
129
+
130
+ /** `scanned`: the workspace scan the caller already has (listing every document must not scan once per document). */
131
+ export function readDocumentSummary(config: WorkspaceConfig, { dir, entry }: DocumentEntry, scanned?: WorkspaceDocuments): FoundDocument {
114
132
  let headmatter: Record<string, unknown> = {}
115
133
  try {
116
- const parsed: unknown = JSON.parse(readFileSync(join(config.root, entry), 'utf8'))
117
- headmatter = isRecord(parsed) && isRecord(parsed.metadata) ? parsed.metadata : {}
134
+ headmatter = effectiveMetadata(config, entry, documentHead(join(config.root, entry)), scanned)
118
135
  } catch {
119
136
  }
120
137
  const tags = strings(headmatter.tags)
@@ -129,14 +146,82 @@ export function readDocumentSummary(config: WorkspaceConfig, { dir, entry }: Doc
129
146
  }
130
147
  }
131
148
 
149
+ const listed = new WeakMap<WorkspaceConfig, { generation: number, settings: unknown, documents: FoundDocument[] }>()
150
+
151
+ /**
152
+ * The documents with their summaries, in tree order. Where the workspace service's index keeps the documents, the list
153
+ * is reused until one of them changes; otherwise each document file is looked at (and read only when it changed).
154
+ */
132
155
  export function listDocuments(config: WorkspaceConfig): FoundDocument[] {
133
- return listDocumentEntries(config).map(entry => readDocumentSummary(config, entry))
156
+ const generation = config.singleDeck ? undefined : providedDocuments(config.root)?.generation
157
+ const settings = workspaceSettings(config.root)
158
+ const known = listed.get(config)
159
+ if (generation !== undefined && known?.generation === generation && known.settings === settings) return known.documents.map(document => ({ ...document }))
160
+ const documents = summarize(config)
161
+ if (generation !== undefined) listed.set(config, { generation, settings, documents })
162
+ return documents.map(document => ({ ...document }))
163
+ }
164
+
165
+ /** Each document's summary with the stamps of its file and its ancestors' files it was made from. */
166
+ const summaries = new WeakMap<WorkspaceConfig, { settings: unknown, entries: Map<string, { key: string, summary: FoundDocument }> }>()
167
+
168
+ function summarize(config: WorkspaceConfig): FoundDocument[] {
169
+ const places = documentPlaces(config)
170
+ const dirs = new Map([...places].map(([dir, place]) => [place.id, dir]))
171
+ // With an index in this process, a summary is made again only when its file or an ancestor's file changed.
172
+ const provided = config.singleDeck ? undefined : providedDocuments(config.root)
173
+ const settings = workspaceSettings(config.root)
174
+ const cache = summaries.get(config)
175
+ const known = cache?.settings === settings ? cache.entries : new Map<string, { key: string, summary: FoundDocument }>()
176
+ summaries.set(config, { settings, entries: known })
177
+ const keyOf = (entry: DocumentEntry): string | undefined => {
178
+ if (!provided) return undefined
179
+ const stamps: string[] = [String(provided.stamps.get(entry.entry))]
180
+ for (let at = places.get(entry.dir)?.parent ?? null, hops = 0; at !== null && hops < 64; hops++) {
181
+ const dir = dirs.get(at)
182
+ if (dir === undefined) break
183
+ stamps.push(String(provided.stamps.get(dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY)))
184
+ at = places.get(dir)?.parent ?? null
185
+ }
186
+ return stamps.join('|')
187
+ }
188
+ let scanned: WorkspaceDocuments | undefined
189
+ return listDocumentEntries(config).map((entry) => {
190
+ const key = keyOf(entry), cached = known.get(entry.entry)
191
+ const found = key !== undefined && cached?.key === key ? cached.summary : readDocumentSummary(config, entry, scanned ??= config.singleDeck ? undefined : workspaceDocuments(config.root))
192
+ if (key !== undefined) known.set(entry.entry, { key, summary: found })
193
+ const parent = places.get(entry.dir)?.parent
194
+ const parentDir = parent === null || parent === undefined ? undefined : dirs.get(parent)
195
+ return parentDir === undefined ? found : { ...found, parentDir }
196
+ })
134
197
  }
135
198
 
136
199
  export function documentSummaries(config: WorkspaceConfig): DocumentSummary[] {
137
- return listDocuments(config).map(({ entry: _entry, ...document }) => document)
200
+ const places = documentPlaces(config)
201
+ return listDocuments(config).map(({ entry: _entry, ...document }) => {
202
+ const place = places.get(document.dir)
203
+ return place ? { ...document, id: place.id, parent: place.parent, depth: place.depth } : document
204
+ })
138
205
  }
139
206
 
207
+ /** Whether a document may live in this folder: in a workspace any folder outside the skipped ones and translations. */
140
208
  export function isDocumentDir(config: WorkspaceConfig, dir: string): boolean {
141
- return config.documents.some(pattern => matchesPattern(pattern, dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY))
209
+ if (config.singleDeck) return dir === ''
210
+ const parts = dir.split('/')
211
+ return dir !== '' && !parts.some(part => part === '' || part.startsWith('.') || SKIPPED.has(part)) && !parts.some((part, index) => part === 'locales' && index === parts.length - 2)
212
+ }
213
+
214
+ /** The document in `dir` with the settings it inherits from its ancestors and the workspace defaults; never saved. */
215
+ export function effectiveContent(config: WorkspaceConfig, dir: string, content: PresmiumDocument): EffectiveDocument {
216
+ return effectiveDocumentIn(config.root, join(config.root, dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY), content)
217
+ }
218
+
219
+ /** What the document in `dir` inherits from its ancestors and the workspace defaults, without its own settings. */
220
+ export function inheritedContent(config: WorkspaceConfig, dir: string, content: PresmiumDocument): DocumentDefaults {
221
+ return inheritedSettingsIn(config.root, join(config.root, dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY), content)
222
+ }
223
+
224
+ /** Which ancestor (or the workspace defaults, null) each setting the document in `dir` inherits comes from. */
225
+ export function inheritedOrigins(config: WorkspaceConfig, dir: string, content: PresmiumDocument): SettingOrigins {
226
+ return settingOriginsIn(config.root, join(config.root, dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY), content)
142
227
  }
@@ -2,11 +2,11 @@ import { createReadStream, realpathSync } from 'node:fs'
2
2
  import { basename, isAbsolute, relative, resolve, sep } from 'node:path'
3
3
  import { Readable } from 'node:stream'
4
4
  import { lookup } from 'mime-types'
5
- import type { TeachingDocument } from '@lincyaw/kernel'
5
+ import type { PresmiumDocument } from '@lincyaw/kernel'
6
6
  import { RequestError } from './errors.ts'
7
7
 
8
8
  /** Read only a file registered by the current canonical document, without compiling it. */
9
- export function documentAssetResponse(root: string, directory: string, document: TeachingDocument, id: string, readableFile: (path: string) => string, signal?: AbortSignal): Response {
9
+ export function documentAssetResponse(root: string, directory: string, document: PresmiumDocument, id: string, readableFile: (path: string) => string, signal?: AbortSignal): Response {
10
10
  const asset = document.assets[id]
11
11
  if (!asset) throw new RequestError(404, 'document-asset-missing')
12
12
  if (!asset.location || /^(?:[a-z][a-z\d+.-]*:|\/)/i.test(asset.location)) throw new RequestError(400, 'document-asset-not-local')