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

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
@@ -0,0 +1,425 @@
1
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
2
+ import { randomBytes } from 'node:crypto'
3
+ import { dirname, join, relative, resolve, sep } from 'node:path'
4
+ import { copyEmbeddedBlock, DOCUMENT_ENTRY, documentFolderName, withReferenceFallbacks, freshDocumentId, hasRole, isRecord, ranksBetween, validateDocument } from '@lincyaw/kernel'
5
+ import type { BlockId, DocumentId, Member, PresmiumDocument, TreeOperation, TreeOperationResult } from '@lincyaw/kernel'
6
+ import { isWithin } from '../domain/paths.ts'
7
+ import { effectiveContent, isDocumentDir } from './config.ts'
8
+ import type { WorkspaceConfig } from './config.ts'
9
+ import { TRASH_DIR, TRASH_RECORD } from './document-index.ts'
10
+ import type { DocumentIndex, TrashRecord } from './document-index.ts'
11
+ import { documentsDiff } from './document-operations.ts'
12
+ import type { DocumentsChange } from './document-operations.ts'
13
+ import { RequestError } from './errors.ts'
14
+ import { lockedError } from './locks.ts'
15
+ import type { DocumentLocks } from './locks.ts'
16
+ import type { Revisions } from './revisions.ts'
17
+ import { DEFAULT_TEMPLATE, listTemplates } from './templates.ts'
18
+ import { makeDocumentDir } from './writer.ts'
19
+ import type { DocumentWriter } from './writer.ts'
20
+
21
+ /** Where new documents are created, one folder each. */
22
+ export const NEW_DOCUMENTS_DIR = 'docs'
23
+ const TITLE_MAX = 200
24
+ /** Settings a document created under a parent leaves to it (see the inherited settings in docs/ir.md). */
25
+ const INHERITED_METADATA = ['lang', 'plugins', 'presmium', 'renderers', 'execute', 'checks'] as const
26
+ const AUTOMATIC_TRAILER = 'Presmium-Automatic'
27
+ /** How long titles must stay the same before references to them are updated. */
28
+ const TITLES_SETTLE_MS = 2000
29
+ /** The author of the revisions Presmium records on its own (reference titles brought up to date). */
30
+ const AUTOMATIC_MEMBER: Member = { id: 'presmium', name: 'Presmium', roles: ['owner'] }
31
+
32
+ export interface TreeOperationsOptions {
33
+ config: WorkspaceConfig
34
+ index: DocumentIndex
35
+ writer: DocumentWriter
36
+ locks: DocumentLocks
37
+ revisions?: Revisions
38
+ /** Documents were added or removed. */
39
+ changed(change: DocumentsChange): Promise<void> | void
40
+ /** Documents (by folder) changed title or place without any being added or removed. */
41
+ placed?(dirs: string[]): Promise<void> | void
42
+ warn?(message: string): void
43
+ }
44
+
45
+ /** The undo log of one operation: what it moved, wrote and created, undone in reverse when it fails. */
46
+ class Journal {
47
+ readonly #root: string
48
+ readonly #before: (paths: string[]) => Promise<void>
49
+ readonly #undo: (() => void)[] = []
50
+ readonly #after: (() => void)[] = []
51
+ readonly paths = new Set<string>()
52
+ /** `before` records the files' state before they change, so the revision shows the change (the local history's baseline). */
53
+ constructor(root: string, before: (paths: string[]) => Promise<void>) { this.#root = root; this.#before = before }
54
+ #abs(path: string) { return join(this.#root, path) }
55
+ async #touch(...paths: string[]) {
56
+ const fresh = paths.filter(path => !this.paths.has(path))
57
+ if (fresh.length) await this.#before(fresh)
58
+ for (const path of fresh) this.paths.add(path)
59
+ }
60
+ async write(path: string, content: string) {
61
+ await this.#touch(path)
62
+ const file = this.#abs(path), before = existsSync(file) ? readFileSync(file) : undefined
63
+ mkdirSync(dirname(file), { recursive: true })
64
+ writeFileSync(file, content)
65
+ this.#undo.push(() => { if (before) writeFileSync(file, before); else rmSync(file, { force: true }) })
66
+ }
67
+ async move(from: string, to: string) {
68
+ await this.#touch(from, to)
69
+ const target = this.#abs(to)
70
+ if (existsSync(target)) await this.discard(to)
71
+ mkdirSync(dirname(target), { recursive: true })
72
+ renameSync(this.#abs(from), target)
73
+ this.#undo.push(() => renameSync(target, this.#abs(from)))
74
+ }
75
+ async created(path: string) {
76
+ await this.#touch(path)
77
+ this.#undo.push(() => rmSync(this.#abs(path), { recursive: true, force: true }))
78
+ }
79
+ async copyFile(from: string, to: string) {
80
+ const target = this.#abs(to)
81
+ if (existsSync(target)) return
82
+ await this.created(to)
83
+ mkdirSync(dirname(target), { recursive: true })
84
+ copyFileSync(this.#abs(from), target)
85
+ }
86
+ /** Removed for good only once the operation is recorded; until then it waits beside the workspace's state. */
87
+ async discard(path: string) {
88
+ await this.#touch(path)
89
+ const parked = join(this.#root, '.presmium', `discarded-${randomBytes(6).toString('hex')}`)
90
+ mkdirSync(dirname(parked), { recursive: true })
91
+ renameSync(this.#abs(path), parked)
92
+ this.#undo.push(() => renameSync(parked, this.#abs(path)))
93
+ this.#after.push(() => rmSync(parked, { recursive: true, force: true }))
94
+ }
95
+ rollback() { for (const undo of this.#undo.reverse()) { try { undo() } catch { /* Every other step is still undone. */ } } }
96
+ finish() { for (const done of this.#after) { try { done() } catch { /* A leftover in .presmium is harmless. */ } } }
97
+ }
98
+
99
+ /**
100
+ * The workspace's tree operations (docs/authoring-actions.md): each is atomic, the documents it changes are written
101
+ * together and recorded as one revision, under the documents' locks. Folders are never moved by a move or rename;
102
+ * only trash and restore move a document's folder, to `.trash/<id>/` and back.
103
+ */
104
+ export class TreeOperations {
105
+ readonly #options: TreeOperationsOptions
106
+ /** Documents whose titles changed, waiting for them to settle before the references to them are updated. */
107
+ readonly #titled = new Set<DocumentId>()
108
+ #titleTimer?: ReturnType<typeof setTimeout>
109
+ #refreshing = false
110
+ #stop: () => void
111
+
112
+ constructor(options: TreeOperationsOptions) {
113
+ this.#options = options
114
+ this.#stop = options.index.onTitles((changed) => {
115
+ for (const id of changed) this.#titled.add(id)
116
+ clearTimeout(this.#titleTimer)
117
+ this.#titleTimer = setTimeout(() => { void this.refreshFallbacks() }, TITLES_SETTLE_MS)
118
+ this.#titleTimer.unref?.()
119
+ })
120
+ }
121
+
122
+ close(): void {
123
+ this.#stop()
124
+ clearTimeout(this.#titleTimer)
125
+ }
126
+
127
+ /** The document folders of the workspace, from the index. */
128
+ #dirs(): string[] {
129
+ return [...this.#options.index.scan().documents.values()].map(entry => entry.dir)
130
+ }
131
+
132
+ get #root() { return this.#options.config.root }
133
+
134
+ #read(dir: string): PresmiumDocument {
135
+ try { return JSON.parse(readFileSync(join(this.#root, dir, DOCUMENT_ENTRY), 'utf8').replace(/^/, '')) as PresmiumDocument }
136
+ catch { throw new RequestError(422, 'document-invalid') }
137
+ }
138
+
139
+ async #write(journal: Journal, dir: string, document: PresmiumDocument) {
140
+ const checked = validateDocument(document)
141
+ if (!checked.document || checked.issues.some(issue => issue.severity === 'error')) throw new RequestError(422, 'document-invalid', { issues: checked.issues.filter(issue => issue.severity === 'error').slice(0, 3) })
142
+ await journal.write(`${dir}/${DOCUMENT_ENTRY}`, `${JSON.stringify(document, null, 2)}\n`)
143
+ }
144
+
145
+ #live(id: DocumentId) {
146
+ const found = this.#options.index.scan().documents.get(id)
147
+ if (!found) throw new RequestError(404, 'tree.not-found', { id })
148
+ return found
149
+ }
150
+
151
+ /** The rank between `after` (or the start) and the sibling following it, among `parent`'s children other than `moving`. */
152
+ #rankAfter(parent: DocumentId | null, after: DocumentId | null | undefined, moving?: DocumentId): string {
153
+ const { tree, documents } = this.#options.index.scan()
154
+ const siblings = (tree?.children.get(parent) ?? []).filter(id => id !== moving)
155
+ const rank = (id: DocumentId | undefined) => id === undefined ? null : documents.get(id)?.placement.rank || null
156
+ if (after === null || after === undefined) return ranksBetween(null, rank(siblings[0]), 1)[0]!
157
+ const at = siblings.indexOf(after)
158
+ if (at < 0) throw new RequestError(400, 'tree.not-found', { after })
159
+ return ranksBetween(rank(after), rank(siblings[at + 1]), 1)[0]!
160
+ }
161
+
162
+ #freshDir(title: string): string {
163
+ const taken = this.#dirs()
164
+ const base = `${NEW_DOCUMENTS_DIR}/${documentFolderName(title)}`
165
+ for (let n = 1; ; n++) {
166
+ const dir = n === 1 ? base : `${base}-${n}`
167
+ if (!existsSync(join(this.#root, dir)) && isDocumentDir(this.#options.config, dir) && !taken.some(other => other !== '' && (isWithin(dir, other) || isWithin(other, dir)))) return dir
168
+ }
169
+ }
170
+
171
+ #title(value: string): string {
172
+ const title = value.replace(/\s+/g, ' ').trim()
173
+ if (!title) throw new RequestError(400, 'tree.title-empty')
174
+ return [...title].slice(0, TITLE_MAX).join('')
175
+ }
176
+
177
+ /** The documents below `id` in tree order, deepest last. */
178
+ #descendants(id: DocumentId): DocumentId[] {
179
+ const { tree } = this.#options.index.scan()
180
+ const out: DocumentId[] = []
181
+ const walk = (at: DocumentId) => { for (const child of tree?.children.get(at) ?? []) { out.push(child); walk(child) } }
182
+ walk(id)
183
+ return out
184
+ }
185
+
186
+ /**
187
+ * Runs the operation's changes under the documents' locks and the history's lock, then records them as one revision;
188
+ * on any failure every change is undone and nothing is recorded.
189
+ */
190
+ async #run(kind: TreeOperation['type'], locked: string[], member: Member, origin: 'editor' | 'agent', work: (journal: Journal) => Promise<{ summary: string, body?: string, documents: DocumentId[], created?: DocumentId, converted?: TreeOperationResult['converted'], toTopLevel?: TreeOperationResult['toTopLevel'] }>, automatic = false): Promise<TreeOperationResult> {
191
+ const { locks, revisions, index } = this.#options
192
+ await index.ready()
193
+ const before = this.#dirs()
194
+ const execute = async () => {
195
+ const claim = locks.claimAll(locked, `document:tree-${kind}`)
196
+ if ('holder' in claim) throw lockedError(claim.document, claim.holder)
197
+ const journal = new Journal(this.#root, async paths => { await revisions?.checkpoint(paths) })
198
+ try {
199
+ const done = await work(journal)
200
+ const paths = [...journal.paths]
201
+ const revision = revisions ? await revisions.commitWhileLocked({ paths, summary: done.summary, body: done.body ?? '', origin: { kind: origin, member }, ...automatic ? { trailers: [[AUTOMATIC_TRAILER, 'reference-titles']] } : {} }) : undefined
202
+ journal.finish()
203
+ return { ...done, revision: revision?.id, paths: [...journal.paths], dirs: [...locked, ...[...journal.paths].map(path => path.endsWith(`/${DOCUMENT_ENTRY}`) ? path.slice(0, -DOCUMENT_ENTRY.length - 1) : path)] }
204
+ } catch (error) {
205
+ journal.rollback()
206
+ throw error
207
+ } finally { claim.release() }
208
+ }
209
+ const done = revisions ? await revisions.transaction(execute) : await execute()
210
+ // Only the files and folders this operation changed are read again; no walk of the workspace.
211
+ await index.changed(done.paths)
212
+ const change = documentsDiff(before, this.#dirs())
213
+ if (change.added.length || change.removed.length) await this.#options.changed(change)
214
+ else await this.#options.placed?.(done.dirs)
215
+ return {
216
+ tree: this.#options.index.tree(),
217
+ ...done.created ? { created: done.created } : {},
218
+ revisions: done.revision ? done.documents.map(document => ({ document, revision: done.revision! })) : [],
219
+ ...done.converted?.length ? { converted: done.converted } : {},
220
+ ...done.toTopLevel?.length ? { toTopLevel: done.toTopLevel } : {},
221
+ }
222
+ }
223
+
224
+ async apply(operation: TreeOperation, member: Member, origin: 'editor' | 'agent' = 'editor'): Promise<TreeOperationResult> {
225
+ if (!hasRole(member, 'editor')) throw new RequestError(403, 'authoring-permission-denied')
226
+ if (this.#options.config.singleDeck) throw new RequestError(409, 'tree.single-document')
227
+ const { index } = this.#options
228
+ switch (operation.type) {
229
+ case 'create': {
230
+ const title = this.#title(operation.title)
231
+ if (operation.parent !== null) this.#live(operation.parent)
232
+ const dir = this.#freshDir(title)
233
+ return this.#run('create', [dir], member, origin, async (journal) => {
234
+ const templates = listTemplates(this.#options.config)
235
+ const template = templates.includes(DEFAULT_TEMPLATE) ? DEFAULT_TEMPLATE : templates[0]
236
+ if (!template) throw new RequestError(409, 'tree.template-missing')
237
+ const id = freshDocumentId(new Set(index.scan().documents.keys()))
238
+ makeDocumentDir(this.#root, dir)
239
+ await journal.created(dir)
240
+ await this.#options.writer.template(dir, template, title, id)
241
+ const document = this.#read(dir)
242
+ document.placement = { parent: operation.parent, rank: this.#rankAfter(operation.parent, operation.after) }
243
+ if (operation.parent !== null) for (const field of INHERITED_METADATA) delete document.metadata[field]
244
+ await this.#write(journal, dir, document)
245
+ return { summary: `Create document ${title}`, body: `Folder: ${dir}`, documents: [id], created: id }
246
+ })
247
+ }
248
+ case 'move': {
249
+ const moved = this.#live(operation.id)
250
+ if (operation.parent !== null) {
251
+ this.#live(operation.parent)
252
+ if (operation.parent === operation.id || this.#descendants(operation.id).includes(operation.parent)) throw new RequestError(409, 'tree.cycle')
253
+ }
254
+ return this.#run('move', [moved.dir], member, origin, async (journal) => {
255
+ const document = this.#read(moved.dir)
256
+ document.placement = { parent: operation.parent, rank: this.#rankAfter(operation.parent, operation.after, operation.id) }
257
+ await this.#write(journal, moved.dir, document)
258
+ const under = operation.parent === null ? 'to the top level' : `under ${index.scan().documents.get(operation.parent)?.title ?? operation.parent}`
259
+ return { summary: `Move document ${document.metadata.title} ${under}`, documents: [operation.id] }
260
+ })
261
+ }
262
+ case 'rename': {
263
+ const title = this.#title(operation.title)
264
+ const renamed = this.#live(operation.id)
265
+ return this.#run('rename', [renamed.dir], member, origin, async (journal) => {
266
+ const document = this.#read(renamed.dir)
267
+ const was = document.metadata.title
268
+ document.metadata.title = title
269
+ await this.#write(journal, renamed.dir, document)
270
+ return { summary: `Rename document ${was} to ${title}`, documents: [operation.id] }
271
+ })
272
+ }
273
+ case 'duplicate': {
274
+ const original = this.#live(operation.id)
275
+ const english = (effectiveContent(this.#options.config, original.dir, this.#read(original.dir)).metadata.lang ?? '').startsWith('en')
276
+ const title = [...`${original.title}${english ? ' (copy)' : ' 副本'}`].slice(0, TITLE_MAX).join('')
277
+ const dir = this.#freshDir(title)
278
+ return this.#run('duplicate', [dir], member, origin, async (journal) => {
279
+ const id = freshDocumentId(new Set(index.scan().documents.keys()))
280
+ makeDocumentDir(this.#root, dir)
281
+ await journal.created(dir)
282
+ await this.#options.writer.copy(original.dir, dir, id, title)
283
+ return { summary: `Duplicate document ${original.title}`, body: `Folder: ${dir}`, documents: [id], created: id }
284
+ })
285
+ }
286
+ case 'trash': {
287
+ const root = this.#live(operation.id)
288
+ const ids = [operation.id, ...this.#descendants(operation.id)]
289
+ const found = ids.map(id => this.#live(id))
290
+ return this.#run('trash', found.map(item => item.dir), member, origin, async (journal) => {
291
+ const deletedAt = new Date().toISOString()
292
+ for (const item of found) {
293
+ const record: TrashRecord = { deletedAt, from: item.dir, parent: item.placement.parent, rank: item.placement.rank, children: item.id === operation.id ? ids.slice(1) : [], ...item.id === operation.id ? {} : { with: operation.id } }
294
+ const target = `${TRASH_DIR}/${item.id}`
295
+ await journal.move(item.dir, target)
296
+ await journal.write(`${target}/${TRASH_RECORD}`, `${JSON.stringify(record, null, 2)}\n`)
297
+ }
298
+ return { summary: `Move document ${root.title} to the trash`, body: ids.length > 1 ? `With: ${found.slice(1).map(item => item.title).join(', ')}` : '', documents: ids }
299
+ })
300
+ }
301
+ case 'restore': {
302
+ const trashed = index.trashed()
303
+ const entry = trashed.get(operation.id)
304
+ if (!entry) throw new RequestError(404, 'tree.trash-not-found', { id: operation.id })
305
+ const ids = [operation.id, ...entry.record.children.filter(id => trashed.get(id)?.record.with === operation.id)]
306
+ return this.#run('restore', [], member, origin, async (journal) => {
307
+ const live = index.scan().documents
308
+ const taken = this.#dirs()
309
+ const restored = new Set(ids)
310
+ const toTopLevel: NonNullable<TreeOperationResult['toTopLevel']> = []
311
+ for (const id of ids) {
312
+ const item = trashed.get(id)!
313
+ const free = (dir: string) => isDocumentDir(this.#options.config, dir) && !existsSync(join(this.#root, dir)) && !taken.some(other => other !== '' && (isWithin(dir, other) || isWithin(other, dir)))
314
+ const dir = free(item.record.from) ? item.record.from : this.#freshDir(item.title)
315
+ await journal.move(item.dir, dir)
316
+ taken.push(dir)
317
+ const record = `${dir}/${TRASH_RECORD}`
318
+ await journal.discard(record)
319
+ const parent = item.record.parent
320
+ if (parent !== null && !live.has(parent) && !restored.has(parent)) {
321
+ const document = this.#read(dir)
322
+ document.placement = { parent: null, rank: this.#rankAfter(null, (index.scan().tree?.children.get(null) ?? []).at(-1)) }
323
+ await this.#write(journal, dir, document)
324
+ toTopLevel.push({ document: id, parent: trashed.has(parent) ? 'trashed' : 'missing' })
325
+ }
326
+ }
327
+ return { summary: `Restore document ${entry.title}`, documents: ids, toTopLevel }
328
+ })
329
+ }
330
+ case 'purge': {
331
+ const trashed = index.trashed()
332
+ const entry = trashed.get(operation.id)
333
+ if (!entry) throw new RequestError(404, 'tree.trash-not-found', { id: operation.id })
334
+ const ids = [operation.id, ...entry.record.children.filter(id => trashed.get(id)?.record.with === operation.id)]
335
+ const purged = new Set(ids)
336
+ const hosts = [...index.scan().documents.values()].filter(host => host.sites.some(site => site.kind === 'embed' && purged.has(site.target.document)))
337
+ return this.#run('purge', hosts.map(host => host.dir), member, origin, async (journal) => {
338
+ const converted: { document: DocumentId, block: BlockId }[] = []
339
+ for (const host of hosts) {
340
+ let document = this.#read(host.dir)
341
+ for (const site of host.sites) {
342
+ if (site.kind !== 'embed' || !purged.has(site.target.document)) continue
343
+ const source = await index.read(site.target.document)
344
+ if (!source) throw new RequestError(409, 'embed.missing')
345
+ document = await this.#copyEmbed(journal, host.dir, document, site.block, source.dir, source.document)
346
+ converted.push({ document: host.id, block: site.block })
347
+ }
348
+ await this.#write(journal, host.dir, document)
349
+ }
350
+ for (const id of ids) await journal.discard(trashed.get(id)!.dir)
351
+ return { summary: `Delete document ${entry.title} for good`, body: converted.length ? `Synced blocks converted to copies in: ${[...new Set(hosts.map(host => host.title))].join(', ')}` : '', documents: [...ids, ...new Set(converted.map(item => item.document))], converted }
352
+ })
353
+ }
354
+ case 'embed-to-copy': {
355
+ const host = this.#live(operation.document)
356
+ const block = this.#read(host.dir).blocks[operation.block]
357
+ if (block?.type !== 'embed') throw new RequestError(404, 'tree.not-found', { block: operation.block })
358
+ const located = await index.read(block.source.document)
359
+ if (!located || !Object.hasOwn(located.document.blocks, block.source.block)) throw new RequestError(409, 'embed.missing')
360
+ return this.#run('embed-to-copy', [host.dir], member, origin, async (journal) => {
361
+ const document = await this.#copyEmbed(journal, host.dir, this.#read(host.dir), operation.block, located.dir, located.document)
362
+ await this.#write(journal, host.dir, document)
363
+ return { summary: `Convert a synced block from ${located.document.metadata.title} to a copy`, documents: [operation.document] }
364
+ })
365
+ }
366
+ }
367
+ }
368
+
369
+ /** The host with the synced block replaced by a copy; the files it needs are copied into the host's folder. */
370
+ async #copyEmbed(journal: Journal, hostDir: string, host: PresmiumDocument, block: BlockId, sourceDir: string, source: PresmiumDocument): Promise<PresmiumDocument> {
371
+ const hostRoot = join(this.#root, hostDir), sourceRoot = join(this.#root, sourceDir)
372
+ const located = (location: string): string => {
373
+ if (/^[a-z][a-z0-9+.-]*:/i.test(location) || location.startsWith('/')) return location
374
+ const file = resolve(sourceRoot, location)
375
+ const inside = relative(sourceRoot, file)
376
+ // A file outside the source's folder stays where it is; the copy points at it from the host.
377
+ if (inside.startsWith('..') || inside.startsWith(sep)) return relative(hostRoot, file).split(sep).join('/')
378
+ const plain = inside.split(sep).join('/')
379
+ const same = join(hostRoot, plain)
380
+ if (!existsSync(same) || (existsSync(file) && readFileSync(same).equals(readFileSync(file)))) return plain
381
+ return `synced/${source.id.slice(0, 8)}/${plain}`
382
+ }
383
+ const copied = copyEmbeddedBlock(host, block, source, located)
384
+ for (const file of copied.files) {
385
+ const from = resolve(sourceRoot, file.from), to = resolve(hostRoot, file.to)
386
+ if (from === to || !existsSync(from) || !isWithin(relative(this.#root, to).split(sep).join('/'), hostDir)) continue
387
+ await journal.copyFile(relative(this.#root, from).split(sep).join('/'), relative(this.#root, to).split(sep).join('/'))
388
+ }
389
+ return copied.document
390
+ }
391
+
392
+ /**
393
+ * Brings reference fallbacks up to date in the documents that cite a title which changed (and in the documents whose
394
+ * titles changed, for their own new references), one automatic revision per document that needs it; a busy (locked)
395
+ * document is tried again with the next change. Runs once titles have not changed for a moment, so typing a title
396
+ * does not record a revision per keystroke, and reads only those documents.
397
+ */
398
+ async refreshFallbacks(): Promise<void> {
399
+ if (this.#refreshing || this.#options.config.singleDeck || !this.#titled.size) return
400
+ this.#refreshing = true
401
+ const { index } = this.#options
402
+ try {
403
+ await index.ready()
404
+ const candidates = index.citing([...this.#titled])
405
+ this.#titled.clear()
406
+ for (const item of candidates) {
407
+ if (this.#options.locks.holder(item.dir) !== undefined) continue
408
+ let current: PresmiumDocument
409
+ try { current = this.#read(item.dir) } catch { continue }
410
+ if (current.id !== item.id || withReferenceFallbacks(current, target => index.titleOf(target)) === current) continue
411
+ try {
412
+ await this.#run('rename', [item.dir], AUTOMATIC_MEMBER, 'editor', async (journal) => {
413
+ const latest = this.#read(item.dir)
414
+ if (!isRecord(latest) || latest.id !== item.id) throw new RequestError(409, 'document-version-changed')
415
+ const document = withReferenceFallbacks(latest, target => index.titleOf(target))
416
+ if (document !== latest) await this.#write(journal, item.dir, document)
417
+ return { summary: (latest.metadata.lang ?? '').startsWith('en') ? 'Update the titles of references' : '更新引用的标题', documents: [item.id] }
418
+ }, true)
419
+ } catch (error) {
420
+ this.#options.warn?.(`the reference titles in ${item.dir} were not updated: ${error instanceof Error ? error.message : String(error)}`)
421
+ }
422
+ }
423
+ } finally { this.#refreshing = false }
424
+ }
425
+ }
@@ -0,0 +1,94 @@
1
+ import { isRecord, jsonResponse, pushStream, sseResponse } from '@lincyaw/kernel'
2
+ import type { Route, TreeOperation } from '@lincyaw/kernel'
3
+ import type { DocumentIndex } from './document-index.ts'
4
+ import { catchRequestErrors, RequestError } from './errors.ts'
5
+ import type { TreeOperations } from './tree-operations.ts'
6
+
7
+ const ID_MAX = 200
8
+ const QUERY_MAX = 200
9
+ const SEARCH_LIMIT = 20
10
+ const SEARCH_LIMIT_MAX = 100
11
+
12
+ const isId = (value: unknown): value is string => typeof value === 'string' && value.length > 0 && value.length <= ID_MAX
13
+ const isPlace = (value: unknown): value is string | null => value === null || isId(value)
14
+
15
+ /** The request body as a tree operation, or undefined when it is not one. */
16
+ export function treeOperationOf(body: unknown): TreeOperation | undefined {
17
+ if (!isRecord(body) || typeof body.type !== 'string') return undefined
18
+ const only = (...keys: string[]) => Object.keys(body).every(key => key === 'type' || keys.includes(key))
19
+ const after = body.after === undefined || isPlace(body.after)
20
+ switch (body.type) {
21
+ case 'create': return only('title', 'parent', 'after') && typeof body.title === 'string' && body.title.length <= 1000 && isPlace(body.parent) && after ? { type: 'create', title: body.title, parent: body.parent, ...body.after !== undefined ? { after: body.after as string | null } : {} } : undefined
22
+ case 'move': return only('id', 'parent', 'after') && isId(body.id) && isPlace(body.parent) && after ? { type: 'move', id: body.id, parent: body.parent, ...body.after !== undefined ? { after: body.after as string | null } : {} } : undefined
23
+ case 'rename': return only('id', 'title') && isId(body.id) && typeof body.title === 'string' && body.title.length <= 1000 ? { type: 'rename', id: body.id, title: body.title } : undefined
24
+ case 'duplicate': case 'trash': case 'restore': case 'purge': return only('id') && isId(body.id) ? { type: body.type, id: body.id } : undefined
25
+ case 'embed-to-copy': return only('document', 'block') && isId(body.document) && isId(body.block) ? { type: 'embed-to-copy', document: body.document, block: body.block } : undefined
26
+ default: return undefined
27
+ }
28
+ }
29
+
30
+ /**
31
+ * The document tree's routes (`docs/authoring-actions.md`): the tree with its trash, tree operations, a document's
32
+ * references in both directions, search, a reference's preview card, a synced block's source, what needs attention
33
+ * across the workspace, and `tree/events`, which sends `{ type: 'tree' }` (event `tree`) whenever the tree or the trash
34
+ * changes and `{ type: 'attention' }` whenever what `tree/attention` answers changes.
35
+ */
36
+ export function treeRoutes(index: DocumentIndex, operations: TreeOperations | undefined): Record<string, Route> {
37
+ const params = (request: Request) => new URL(request.url).searchParams
38
+ const required = (request: Request, name: string) => {
39
+ const value = params(request).get(name)
40
+ if (!isId(value)) throw new RequestError(400, `${name}-required`)
41
+ return value
42
+ }
43
+ const optional = (request: Request, name: string) => {
44
+ const value = params(request).get(name)
45
+ if (value === null || value === '') return undefined
46
+ if (!isId(value)) throw new RequestError(400, `${name}-invalid`)
47
+ return value
48
+ }
49
+ const get = (handle: (request: Request) => unknown): Route => ({
50
+ role: 'reader',
51
+ handle: request => catchRequestErrors(async () => {
52
+ if (request.method !== 'GET') throw new RequestError(405, 'GET')
53
+ // What file events reported is read first; everything else is answered from memory.
54
+ await index.ready()
55
+ return jsonResponse(await handle(request))
56
+ }),
57
+ })
58
+ return {
59
+ 'tree': get(() => index.tree()),
60
+ 'tree/operation': {
61
+ role: 'editor',
62
+ maxBody: 8192,
63
+ handle: (request, ctx) => catchRequestErrors(async () => {
64
+ if (request.method !== 'POST') throw new RequestError(405, 'POST')
65
+ if (!operations) throw new RequestError(409, 'tree.unavailable')
66
+ const operation = treeOperationOf(await request.json().catch(() => undefined))
67
+ if (!operation) throw new RequestError(400, 'tree.operation-invalid')
68
+ return jsonResponse(await operations.apply(operation, ctx.member))
69
+ }),
70
+ },
71
+ 'document/links': get(request => index.links(required(request, 'id'))),
72
+ 'documents/search': get((request) => {
73
+ const query = params(request).get('q') ?? ''
74
+ if (query.length > QUERY_MAX) throw new RequestError(400, 'q-too-long')
75
+ const limit = Number(params(request).get('limit') ?? SEARCH_LIMIT)
76
+ return index.search(query, Number.isInteger(limit) && limit > 0 ? Math.min(limit, SEARCH_LIMIT_MAX) : SEARCH_LIMIT)
77
+ }),
78
+ 'document/preview': get(request => index.preview(required(request, 'id'), { ...optional(request, 'section') !== undefined ? { section: optional(request, 'section') } : {}, ...optional(request, 'block') !== undefined ? { block: optional(request, 'block') } : {} })),
79
+ 'embed/source': get(request => index.embedSource(required(request, 'document'), required(request, 'block'))),
80
+ 'tree/attention': get(() => index.attention()),
81
+ 'tree/events': {
82
+ role: 'reader',
83
+ handle: async (request) => {
84
+ if (request.method !== 'GET') return jsonResponse({ error: 'GET' }, 405)
85
+ const stream = pushStream<{ event: string, data: { type: 'tree' | 'attention' } }>((push) => {
86
+ const offTree = index.subscribe(() => push({ event: 'tree', data: { type: 'tree' } }))
87
+ const offAttention = index.onAttention(() => push({ event: 'tree', data: { type: 'attention' } }))
88
+ return () => { offTree(); offAttention() }
89
+ }, { signal: request.signal })
90
+ return sseResponse(stream, request.signal)
91
+ },
92
+ },
93
+ }
94
+ }
@@ -33,7 +33,7 @@ export interface WorkbenchApi {
33
33
  * `prefetch`: the workbench prepares the document ahead of the author's click, answered at once. A build still running
34
34
  * after the wait is answered with 503 `preview-preparing` and `Retry-After`.
35
35
  */
36
- preview(document: string, renderer?: PreviewRenderer, prefetch?: boolean): Promise<PreviewAnswer>
36
+ preview(document: string, renderer?: PreviewRenderer, prefetch?: boolean, browserOrigin?: string): Promise<PreviewAnswer>
37
37
  build(document: string, to?: string[]): Promise<BuildAnswer>
38
38
  check(document: string): Promise<CheckAnswer>
39
39
  }
@@ -80,6 +80,17 @@ export function createWorkbenchBackend(options: WorkbenchBackendOptions): Workbe
80
80
  const { root, log } = options
81
81
  const irRevisions = new WeakMap<Compilation, string>()
82
82
  const relativeDocs = new WeakMap<Compilation, IRDocument>()
83
+ const previewBase = (base: string, browserOrigin: string | undefined): string => {
84
+ if (!browserOrigin) return base
85
+ try {
86
+ const preview = new URL(base), browser = new URL(browserOrigin)
87
+ if (preview.protocol !== browser.protocol || !['localhost', '127.0.0.1', '[::1]'].includes(preview.hostname)) return base
88
+ preview.hostname = browser.hostname
89
+ return base.endsWith('/') ? preview.href : preview.href.replace(/\/$/, '')
90
+ } catch {
91
+ return base
92
+ }
93
+ }
83
94
  const irRevisionOf = (compilation: Compilation) => {
84
95
  let known = irRevisions.get(compilation)
85
96
  if (!known) irRevisions.set(compilation, known = irRevision(compilation.doc))
@@ -119,7 +130,7 @@ export function createWorkbenchBackend(options: WorkbenchBackendOptions): Workbe
119
130
  return () => own.delete(listener)
120
131
  }, { signal })
121
132
  },
122
- async preview(document, renderer, prefetch = false) {
133
+ async preview(document, renderer, prefetch = false, browserOrigin) {
123
134
  const request = ++previewRequest
124
135
  const started = Date.now()
125
136
  const label = `[preview ${request}] document=${JSON.stringify(document || '.')} renderer=${renderer ?? 'all'} prefetch=${prefetch}`
@@ -127,7 +138,7 @@ export function createWorkbenchBackend(options: WorkbenchBackendOptions): Workbe
127
138
  let outcome = 'failed'
128
139
  log.info(`${label} state=started`)
129
140
  try {
130
- const base = options.url()
141
+ const base = previewBase(options.url(), browserOrigin)
131
142
  // The viewer app's page once it has what the document needs (an opened document waits for it a while), else the
132
143
  // document's page on the site.
133
144
  const page = await options.viewerPage?.(document, !prefetch).catch((error: unknown) => {