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

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
@@ -3,11 +3,12 @@ import { constants } from 'node:fs'
3
3
  import { lstat, open } from 'node:fs/promises'
4
4
  import { basename, join, relative } from 'node:path'
5
5
  import { ASSET_TITLE_MAX_LENGTH, DOCUMENT_AUDIO_MAX_BYTES, DOCUMENT_AUDIO_REQUEST_MAX_BYTES, fnv1a64, hasRole, isRecord, jsonResponse, ProductionAudioRefusal, recordingSourceRange, recordingStepIssue, validateDocument } from '@lincyaw/kernel'
6
- import type { Asset, CanonicalSource, DocumentRecordingAdoption, VerifiedDocumentRecordingAdoption, DocumentAudioAuthoring, DocumentAudioCapabilities, DocumentAudioImport, DocumentAudioInspectionAnswer, DocumentChangeAnswer, DocumentMediaClipEdit, DocumentMediaClipValidation, DocumentMediaClipValidationAnswer, DocumentWorkspaceAudioImport, Finding, Member, ProductionAudioAuthoring, RequestContext, Route, TeachingDocument, VerifiedDocumentAudioImport, VerifiedDocumentMediaClipChange, WorkspaceAudioInspectionAnswer } from '@lincyaw/kernel'
6
+ import type { Asset, CanonicalSource, DocumentRecordingAdoption, VerifiedDocumentRecordingAdoption, DocumentAudioAuthoring, DocumentAudioCapabilities, DocumentAudioImport, DocumentAudioInspectionAnswer, DocumentChangeAnswer, DocumentMediaClipEdit, DocumentMediaClipValidation, DocumentMediaClipValidationAnswer, DocumentWorkspaceAudioImport, Finding, Member, ProductionAudioAuthoring, RequestContext, Route, PresmiumDocument, VerifiedDocumentAudioImport, VerifiedDocumentMediaClipChange, WorkspaceAudioInspectionAnswer } from '@lincyaw/kernel'
7
7
  import { productionAssetFile, validateDocumentRecordingAdoption, validateDocumentAudioInspect, validateDocumentWorkspaceAudioImport, validateDocumentWorkspaceAudioInspect, validateDocumentMediaClipValidation, validateDocumentMediaClipEdit, validateDocumentProductionPlanQuery } from '@lincyaw/kernel/node'
8
8
  import { readAuthoringDocument } from './document-editor.ts'
9
9
  import { catchRequestErrors, RequestError } from './errors.ts'
10
10
  import type { Revisions } from './revisions.ts'
11
+ import type { MediaUploadsOwner } from './media-uploads.ts'
11
12
  import type { SourceEditor, SourceTransactionHistory } from './source-editor.ts'
12
13
 
13
14
  export interface DocumentAudioServices { audio?: ProductionAudioAuthoring, findings?: Finding[] }
@@ -15,6 +16,7 @@ export interface DocumentAudioAuthoringOptions extends DocumentAudioServices {
15
16
  root: string
16
17
  editor: SourceEditor
17
18
  revisions?: Revisions
19
+ uploads?: MediaUploadsOwner
18
20
  reviewRequired?: boolean
19
21
  services?(document: string, source: CanonicalSource): Promise<DocumentAudioServices>
20
22
  }
@@ -27,10 +29,37 @@ const sameSource = (a: CanonicalSource, b: CanonicalSource) => a.documentId ===
27
29
  const scopeOf = (document: string) => ({ document, home: false })
28
30
  const binding = (current: ReturnType<typeof readAuthoringDocument>): CanonicalSource => ({ documentId: current.content.id, version: current.source.version, fingerprint: fnv1a64(current.source.content) })
29
31
  const titleOf = (name: string) => [...(name.replaceAll('\\', '/').split('/').at(-1) ?? '').replace(/[\u0000-\u001f\u007f-\u009f]/g, '').trim()].slice(0, ASSET_TITLE_MAX_LENGTH).join('')
30
- const stamp = (stat: Awaited<ReturnType<Awaited<ReturnType<typeof open>>['stat']>>) => [stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs].join(':')
32
+ const stamp = (stat: import('node:fs').Stats) => [stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs].join(':')
33
+
34
+ /** Scoped bounded audio reads are shared by import, inspection and voice cloning. */
35
+ export async function readDocumentAudioBytes(editor: SourceEditor, ctx: RequestContext, path: string, signal?: AbortSignal, maxBytes = DOCUMENT_AUDIO_MAX_BYTES): Promise<Uint8Array> {
36
+ signal?.throwIfAborted()
37
+ const file = editor.readableFile({ document: ctx.document, home: false }, path, ctx.member)
38
+ const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK).catch(error => {
39
+ if (error.code === 'ELOOP') throw new RequestError(403, 'audio-file-path')
40
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') throw new RequestError(404, 'audio-file-missing')
41
+ throw error
42
+ })
43
+ try {
44
+ const before = await handle.stat(), named = await lstat(editor.readableFile({ document: ctx.document, home: false }, path, ctx.member))
45
+ if (!before.isFile() || before.dev !== named.dev || before.ino !== named.ino) throw new RequestError(403, 'audio-file-path')
46
+ if (!before.size || before.size > maxBytes) throw new RequestError(413, 'production.asset-size')
47
+ const bytes = new Uint8Array(before.size + 1); let length = 0
48
+ while (length < bytes.length) {
49
+ signal?.throwIfAborted()
50
+ const read = await handle.read(bytes, length, bytes.length - length, length)
51
+ if (!read.bytesRead) break
52
+ length += read.bytesRead
53
+ }
54
+ const after = await handle.stat(), current = await lstat(editor.readableFile({ document: ctx.document, home: false }, path, ctx.member))
55
+ if (length !== before.size || stamp(before) !== stamp(after) || after.dev !== current.dev || after.ino !== current.ino) throw new RequestError(409, 'audio-file-changed')
56
+ signal?.throwIfAborted()
57
+ return bytes.slice(0, length)
58
+ } finally { await handle.close() }
59
+ }
31
60
 
32
61
  /** Owns the canonical transaction and receipts; plugin services only inspect actual media. */
33
- export function createDocumentAudioAuthoring({ root, editor, revisions, audio, services, reviewRequired = false }: DocumentAudioAuthoringOptions): { service: DocumentAudioAuthoring, routes: Record<string, Route>, close(): Promise<void> } {
62
+ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, services, reviewRequired = false, uploads }: DocumentAudioAuthoringOptions): { service: DocumentAudioAuthoring, routes: Record<string, Route>, busy(): boolean, close(): Promise<void> } {
34
63
  const receipts = new Map<string, Receipt>(), imports = new Map<string, { signature: string, source: CanonicalSource, promise: Promise<VerifiedDocumentAudioImport> }>(), operations = new Set<Operation>()
35
64
  const clipChanges = new Map<string, { signature: string, promise: Promise<VerifiedDocumentMediaClipChange> }>()
36
65
  const recordingChanges = new Map<string, { signature: string, promise: Promise<VerifiedDocumentRecordingAdoption> }>()
@@ -64,31 +93,7 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
64
93
  editor.assertEditable(scopeOf(document), path, member)
65
94
  if (path.split('/').some(part => part.startsWith('.'))) throw new RequestError(403, 'audio-file-path')
66
95
  }
67
- const reader = async (ctx: RequestContext, path: string, signal?: AbortSignal): Promise<Uint8Array> => {
68
- signal?.throwIfAborted()
69
- const file = editor.readableFile(scopeOf(ctx.document), path, ctx.member)
70
- const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK).catch(error => {
71
- if (error.code === 'ELOOP') throw new RequestError(403, 'audio-file-path')
72
- if (error.code === 'ENOENT' || error.code === 'ENOTDIR') throw new RequestError(404, 'audio-file-missing')
73
- throw error
74
- })
75
- try {
76
- const before = await handle.stat(), named = await lstat(editor.readableFile(scopeOf(ctx.document), path, ctx.member))
77
- if (!before.isFile() || before.dev !== named.dev || before.ino !== named.ino) throw new RequestError(403, 'audio-file-path')
78
- if (!before.size || before.size > DOCUMENT_AUDIO_MAX_BYTES) throw new RequestError(413, 'production.asset-size')
79
- const bytes = new Uint8Array(before.size + 1); let length = 0
80
- while (length < bytes.length) {
81
- signal?.throwIfAborted()
82
- const read = await handle.read(bytes, length, bytes.length - length, length)
83
- if (!read.bytesRead) break
84
- length += read.bytesRead
85
- }
86
- const after = await handle.stat(), current = await lstat(editor.readableFile(scopeOf(ctx.document), path, ctx.member))
87
- if (length !== before.size || stamp(before) !== stamp(after) || after.dev !== current.dev || after.ino !== current.ino) throw new RequestError(409, 'audio-file-changed')
88
- signal?.throwIfAborted()
89
- return bytes.slice(0, length)
90
- } finally { await handle.close() }
91
- }
96
+ const reader = (ctx: RequestContext, path: string, signal?: AbortSignal) => readDocumentAudioBytes(editor, ctx, path, signal)
92
97
  const pathOf = (ctx: RequestContext, asset: Asset) => {
93
98
  const file = productionAssetFile(join(root, ctx.document), asset.location)
94
99
  if (!file) throw new RequestError(422, 'production.asset-path')
@@ -103,13 +108,13 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
103
108
  check(signal); opened(ctx, source.version, source)
104
109
  return inspection
105
110
  }
106
- const history = (ctx: RequestContext, content: TeachingDocument, origin: 'editor' | 'agent', validate?: () => Promise<void>): SourceTransactionHistory => ({
111
+ const history = (ctx: RequestContext, content: PresmiumDocument, origin: 'editor' | 'agent', validate?: () => Promise<void>): SourceTransactionHistory => ({
107
112
  run: work => { const guarded = async () => { await validate?.(); return work() }; return revisions ? revisions.transaction(guarded) : guarded() },
108
113
  commit: async paths => {
109
114
  if (!revisions) return undefined
110
115
  const ignored = (await Promise.all(paths.map(async path => await revisions.ignores(path) ? path : undefined))).filter((path): path is string => Boolean(path))
111
116
  if (ignored.length) throw new RequestError(409, 'document-files-ignored', { ignored })
112
- return revisions.commitWhileLocked({ paths, summary: content.metadata.lang?.startsWith('en') ? 'Edit audio media' : '编辑音频素材', body: '', origin: { kind: origin, member: ctx.member } })
117
+ return revisions.commitWhileLocked({ paths, summary: editor.effective(ctx.document, content).metadata.lang.startsWith('en') ? 'Edit audio media' : '编辑音频素材', body: '', origin: { kind: origin, member: ctx.member } })
113
118
  },
114
119
  })
115
120
  const remember = (key: string, receipt: Receipt) => { receipts.set(key, receipt); while (receipts.size > MAX_RECEIPTS) receipts.delete(receipts.keys().next().value!) }
@@ -128,7 +133,7 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
128
133
  }
129
134
  }
130
135
  const importKey = (ctx: RequestContext, id: string) => JSON.stringify(['audio', ctx.document, ctx.member.id, id])
131
- const importSignature = (change: DocumentAudioImport, source: CanonicalSource, title: string, sha256: string, byteLength: number) => hash(JSON.stringify([change.id, source.documentId, change.baseDocumentVersion, source.fingerprint, title, sha256, byteLength]))
136
+ const importSignature = (change: DocumentAudioImport, source: CanonicalSource, title: string, sha256: string, byteLength: number, upload?: string) => hash(JSON.stringify([change.id, source.documentId, change.baseDocumentVersion, source.fingerprint, title, sha256, byteLength, ...upload ? [upload] : []]))
132
137
  /** A known intent replays (receipt still current) or joins its flight; a different payload under the same ID is refused. */
133
138
  const known = (ctx: RequestContext, signature: string, previous: Receipt | undefined, pending: { signature: string } | undefined) => {
134
139
  if (!previous && !pending) return false
@@ -136,10 +141,10 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
136
141
  if (previous) opened(ctx, previous.version)
137
142
  return true
138
143
  }
139
- const once = (ctx: RequestContext, change: DocumentAudioImport, source: CanonicalSource, title: string, sha256: string, byteLength: number, origin: 'editor' | 'agent', run: () => Promise<VerifiedDocumentAudioImport>) => {
144
+ const once = (ctx: RequestContext, change: DocumentAudioImport, source: CanonicalSource, title: string, sha256: string, byteLength: number, origin: 'editor' | 'agent', run: () => Promise<VerifiedDocumentAudioImport>, upload?: string) => {
140
145
  authorize(ctx.member); available()
141
146
  if (origin === 'agent' && reviewRequired) throw new RequestError(409, 'authoring-review-required')
142
- const key = importKey(ctx, change.id), signature = importSignature(change, source, title, sha256, byteLength)
147
+ const key = importKey(ctx, change.id), signature = importSignature(change, source, title, sha256, byteLength, upload)
143
148
  const previous = receipts.get(key)
144
149
  if (previous) {
145
150
  if (previous.signature !== signature) throw new RequestError(409, 'document-change-id-reused')
@@ -152,7 +157,7 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
152
157
  imports.set(key, { signature, source, promise })
153
158
  return promise
154
159
  }
155
- const importBytes = async (ctx: RequestContext, change: DocumentAudioImport, title: string, bytes: Uint8Array, source: CanonicalSource, found: DocumentAudioServices, origin: 'editor' | 'agent', signal: AbortSignal) => {
160
+ const importBytes = async (ctx: RequestContext, change: DocumentAudioImport, title: string, bytes: Uint8Array, source: CanonicalSource, found: DocumentAudioServices, origin: 'editor' | 'agent', signal: AbortSignal, upload?: string) => {
156
161
  check(signal)
157
162
  if (!found.audio) throw new RequestError(503, 'production-audio-unavailable')
158
163
  const current = opened(ctx, change.baseDocumentVersion, source), assetId = `audio_${randomUUID().replaceAll('-', '')}`, probed = await found.audio.inspectBytes(assetId, bytes, signal)
@@ -163,7 +168,7 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
163
168
  check(signal); opened(ctx, change.baseDocumentVersion, source)
164
169
  const saved = await editor.transactionWithBinary(scopeOf(ctx.document), { path: current.source.path, content, base: current.source.version }, { path, content: bytes }, ctx.member, history(ctx, candidate, origin, async () => { check(signal) }))
165
170
  const version = saved.versions.find(file => file.path === current.source.path)!.version
166
- const receipt: Receipt = { signature: importSignature(change, source, title, hash(bytes), bytes.length), source, version, files: saved.versions, assetId, inspection: probed.inspection, ...saved.revision ? { commit: saved.revision } : {} }
171
+ const receipt: Receipt = { signature: importSignature(change, source, title, hash(bytes), bytes.length, upload), source, version, files: saved.versions, assetId, inspection: probed.inspection, ...saved.revision ? { commit: saved.revision } : {} }
167
172
  remember(importKey(ctx, change.id), receipt)
168
173
  // A committed write is verified even when its request disconnected or shutdown began meanwhile.
169
174
  return readback(ctx, change.id, receipt)
@@ -273,7 +278,7 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
273
278
  const current = opened(ctx, request.source.version, request.source), step = current.content.steps[request.stepId], asset = current.content.assets[request.assetId]
274
279
  if (!step) throw new RequestError(404, 'document-step-missing')
275
280
  if (!asset) throw new RequestError(404, 'production.asset-missing')
276
- const original = current.content.production.stepOverrides[step.id]?.voiceSource ?? current.content.production.sectionOverrides?.[step.sectionId]?.voiceSource ?? current.content.production.defaults.voiceSource
281
+ const original = current.content.production.stepOverrides[step.id]?.voiceSource ?? current.content.production.sectionOverrides?.[step.sectionId]?.voiceSource ?? current.effective.production.defaults.voiceSource
277
282
  if (request.sourceRange && (original?.type !== 'recording' || original.assetId !== asset.id)) throw new RequestError(409, 'recording-source-changed')
278
283
  const issue = recordingStepIssue(current.content, request.stepId)
279
284
  if (issue) throw new RequestError(422, issue)
@@ -315,12 +320,25 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
315
320
  recordingChanges.set(key, { signature, promise })
316
321
  return promise
317
322
  }
323
+ const mediaInput = async (ctx: RequestContext, source: CanonicalSource, location: { path?: string, upload?: string }, signal?: AbortSignal) => {
324
+ if (location.upload !== undefined) {
325
+ signal?.throwIfAborted()
326
+ if (!uploads) throw new RequestError(503, 'media-upload-unavailable')
327
+ return uploads.read(ctx.document, source.documentId, ctx.member, location.upload, 'audio')
328
+ }
329
+ workspacePath(ctx.document, location.path!, ctx.member)
330
+ return { bytes: await reader(ctx, location.path!, signal), name: titleOf(basename(location.path!)) }
331
+ }
318
332
  const workspaceImport = (document: string, request: DocumentWorkspaceAudioImport, member: Member) => {
319
333
  authorize(member); available()
320
334
  if (!validateDocumentWorkspaceAudioImport(request)) throw new RequestError(400, 'document-audio-import-invalid')
321
335
  if (Buffer.byteLength(JSON.stringify(request)) > DOCUMENT_AUDIO_REQUEST_MAX_BYTES) throw new RequestError(413, 'document-audio-request-size')
322
- workspacePath(document, request.file.path, member)
323
- return { ctx: ctxOf(document, member), title: titleOf(basename(request.file.path)), change: { id: request.id, baseDocumentVersion: request.source.version } }
336
+ if (request.file.path !== undefined) workspacePath(document, request.file.path, member)
337
+ else {
338
+ if (!uploads) throw new RequestError(503, 'media-upload-unavailable')
339
+ if (uploads.read(document, request.source.documentId, member, request.file.upload, 'audio').name !== request.file.name) throw new RequestError(409, 'audio-file-changed')
340
+ }
341
+ return { ctx: ctxOf(document, member), title: request.file.path !== undefined ? titleOf(basename(request.file.path)) : request.file.name, change: { id: request.id, baseDocumentVersion: request.source.version } }
324
342
  }
325
343
  const service: DocumentAudioAuthoring = {
326
344
  capabilities: (document, member) => work(member, undefined, async signal => {
@@ -338,16 +356,15 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
338
356
  }),
339
357
  inspectWorkspace: (document, request, member, signal) => work(member, signal, async signal => {
340
358
  if (!validateDocumentWorkspaceAudioInspect(request)) throw new RequestError(400, 'document-audio-query-invalid')
341
- workspacePath(document, request.path, member)
342
359
  const ctx = ctxOf(document, member)
343
360
  opened(ctx, request.source.version, request.source)
344
- const [bytes, found] = await Promise.all([reader(ctx, request.path, signal), resolved(document, request.source, signal)])
361
+ const [{ bytes, name }, found] = await Promise.all([mediaInput(ctx, request.source, request, signal), resolved(document, request.source, signal)])
345
362
  if (!found.audio) throw new RequestError(503, 'production-audio-unavailable')
346
363
  const probed = await found.audio.inspectBytes('workspace-audio-probe', bytes, signal)
347
364
  const { assetId: _assetId, mediaId: _mediaId, ...inspection } = probed.inspection
348
365
  if (inspection.sha256 !== hash(bytes) || inspection.byteLength !== bytes.length) throw new RequestError(409, 'audio-inspection-changed')
349
366
  check(signal); opened(ctx, request.source.version, request.source)
350
- return { document, source: request.source, file: { path: request.path, sha256: inspection.sha256, byteLength: inspection.byteLength }, inspection } satisfies WorkspaceAudioInspectionAnswer
367
+ return { document, source: request.source, file: { ...request.upload ? { upload: request.upload, name } : { path: request.path! }, sha256: inspection.sha256, byteLength: inspection.byteLength }, inspection } satisfies WorkspaceAudioInspectionAnswer
351
368
  }),
352
369
  readProductionPlan: (document, request, member, signal) => work(member, signal, async signal => {
353
370
  if (!validateDocumentProductionPlanQuery(request)) throw new RequestError(400, 'production-query-invalid')
@@ -365,9 +382,10 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
365
382
  return work(member, signal, async signal => {
366
383
  if (reviewRequired) throw new RequestError(409, 'authoring-review-required')
367
384
  const key = importKey(ctx, request.id)
368
- if (known(ctx, importSignature(change, request.source, title, request.file.sha256, request.file.byteLength), receipts.get(key), imports.get(key))) return
385
+ if (known(ctx, importSignature(change, request.source, title, request.file.sha256, request.file.byteLength, request.file.upload), receipts.get(key), imports.get(key))) return
369
386
  opened(ctx, request.source.version, request.source)
370
- const [bytes, found] = await Promise.all([reader(ctx, request.file.path, signal), resolved(document, request.source, signal)])
387
+ const [{ bytes, name }, found] = await Promise.all([mediaInput(ctx, request.source, request.file, signal), resolved(document, request.source, signal)])
388
+ if (request.file.upload && name !== request.file.name) throw new RequestError(409, 'audio-file-changed')
371
389
  if (bytes.length !== request.file.byteLength || hash(bytes) !== request.file.sha256) throw new RequestError(409, 'audio-file-changed')
372
390
  if (!found.audio) throw new RequestError(503, 'production-audio-unavailable')
373
391
  await found.audio.inspectBytes('workspace-audio-probe', bytes, signal)
@@ -378,10 +396,11 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
378
396
  const { ctx, title, change } = workspaceImport(document, request, member)
379
397
  return work(member, signal, signal => once(ctx, change, request.source, title, request.file.sha256, request.file.byteLength, 'agent', async () => {
380
398
  opened(ctx, request.source.version, request.source)
381
- const [bytes, found] = await Promise.all([reader(ctx, request.file.path, signal), resolved(document, request.source, signal)])
399
+ const [{ bytes, name }, found] = await Promise.all([mediaInput(ctx, request.source, request.file, signal), resolved(document, request.source, signal)])
400
+ if (request.file.upload && name !== request.file.name) throw new RequestError(409, 'audio-file-changed')
382
401
  if (bytes.length !== request.file.byteLength || hash(bytes) !== request.file.sha256) throw new RequestError(409, 'audio-file-changed')
383
- return importBytes(ctx, change, title, bytes, request.source, found, 'agent', signal)
384
- }))
402
+ return importBytes(ctx, change, title, bytes, request.source, found, 'agent', signal, request.file.upload)
403
+ }, request.file.upload))
385
404
  },
386
405
  validateClipChange: (document, request, member, signal) => work(member, signal, async signal => {
387
406
  if (!validateDocumentMediaClipValidation(request)) throw new RequestError(400, 'document-media-clip-invalid')
@@ -469,5 +488,5 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
469
488
  }),
470
489
  },
471
490
  }
472
- return { service, routes, async close() { closed = true; for (const operation of operations) operation.controller.abort(); await Promise.allSettled([...operations].map(operation => operation.finished)); receipts.clear() } }
491
+ return { service, routes, busy: () => operations.size > 0, async close() { closed = true; for (const operation of operations) operation.controller.abort(); await Promise.allSettled([...operations].map(operation => operation.finished)); receipts.clear() } }
473
492
  }
@@ -1,8 +1,11 @@
1
1
  import { createHash, randomUUID } from 'node:crypto'
2
- 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'
2
+ import { setImmediate as nextTurn } from 'node:timers/promises'
3
+ import { isRecord } from '@lincyaw/kernel'
4
+ import { applyDocumentOperations, AUTHORING_API_VERSION, documentSettings, 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
5
  import { validateDocumentChange, validateDocumentPageChange, validateDocumentPageChangeApply, validateDocumentPageDuplication, validateDocumentPageDuplicationApply, validateDocumentOutlineQuery, validateDocumentPartQuery } from '@lincyaw/kernel/node'
4
- import type { AppliedDocumentChange, ApplyDocumentChange, CanonicalSource, DocumentAnswer, DocumentAuthoring, DocumentChange, DocumentChangeAnswer, DocumentChangePlan, DocumentIssue, DocumentPageAction, DocumentPageChangePlan, DocumentPageDuplicationPlan, Member, RequestContext, SourceTransactionChange, TeachingDocument } from '@lincyaw/kernel'
6
+ import type { AppliedDocumentChange, ApplyDocumentChange, CanonicalSource, DocumentAnswer, DocumentAuthoring, DocumentChange, DocumentChangeAnswer, DocumentChangePlan, DocumentIssue, DocumentPageAction, DocumentPageChangePlan, DocumentPageDuplicationPlan, Member, RequestContext, SourceTransactionChange, PresmiumDocument } from '@lincyaw/kernel'
5
7
  import { RequestError } from './errors.ts'
8
+ import { checkDocumentText, rememberCheckedText } from './document-check.ts'
6
9
  import { applyDocumentAuthoringAction, DOCUMENT_ACTION_MAX_REQUEST_CHARS, DOCUMENT_ACTION_MAX_RESPONSE_CHARS, DOCUMENT_AUTHORING_ACTION_TYPES, DOCUMENT_PARAMETER_MAX_CHANGES, DOCUMENT_PARAMETER_MAX_PATH_DEPTH, DocumentCommentError, DocumentComponentError, DocumentCaptionTimingError, ProductionAudioRefusal } from '@lincyaw/kernel'
7
10
  import { validateDocumentAuthoringAction, validateDocumentAuthoringActionReference, validateDocumentAuthoringActionImpact } from '@lincyaw/kernel/node'
8
11
  import type { AppliedDocumentAuthoringAction, DocumentAuthoringActionReference, DocumentPageChangeReference, DocumentPageDuplicationReference, DocumentAuthoringActionPlan, DocumentComponentImpactAnswer, DocumentAuthoringAction, ProductionPlan } from '@lincyaw/kernel'
@@ -17,11 +20,10 @@ const signatureOf = (change: DocumentChange) => createHash('sha256').update(JSON
17
20
  const keyOf = (document: string, member: Member, id: string) => JSON.stringify([document, member.id, id])
18
21
  const sourceOf = (answer: DocumentAnswer) => ({ documentId: answer.content.id, version: answer.version, fingerprint: answer.fingerprint })
19
22
 
20
- export function decodeAuthoringDocument(content: string): { document?: TeachingDocument, issues: DocumentIssue[] } {
21
- let value: unknown
22
- try { value = JSON.parse(content.replace(/^\uFEFF/, '')) }
23
- catch { return { issues: [{ path: '', code: 'json-syntax', message: 'The document is not valid JSON.', severity: 'error' }] } }
24
- return validateDocument(value)
23
+ export function decodeAuthoringDocument(content: string): { document?: PresmiumDocument, issues: DocumentIssue[] } {
24
+ const checked = checkDocumentText(content)
25
+ if (checked.syntax) return { issues: [{ path: '', code: 'json-syntax', message: 'The document is not valid JSON.', severity: 'error' }] }
26
+ return checked.document ? { document: checked.document, issues: checked.issues } : { issues: checked.issues }
25
27
  }
26
28
 
27
29
  export function readAuthoringDocument(editor: SourceEditor, ctx: Pick<RequestContext, 'document' | 'member'>) {
@@ -29,7 +31,7 @@ export function readAuthoringDocument(editor: SourceEditor, ctx: Pick<RequestCon
29
31
  const source = editor.read(editor.scope(ctx.document), entryOf(ctx.document), ctx.member)
30
32
  const checked = decodeAuthoringDocument(source.content)
31
33
  if (!checked.document || checked.issues.some(issue => issue.severity === 'error')) throw new RequestError(422, 'document-invalid', { issues: checked.issues })
32
- return { source, content: checked.document, issues: checked.issues }
34
+ return { source, content: checked.document, effective: editor.effective(ctx.document, checked.document), issues: checked.issues }
33
35
  }
34
36
 
35
37
  export interface DocumentEditor extends DocumentAuthoring {
@@ -58,10 +60,10 @@ export function createDocumentEditor({ editor, revisions, reviewRequired = false
58
60
  while (table.size > MAX_RECEIPTS) table.delete(table.keys().next().value!)
59
61
  }
60
62
  const read = async (document: string, member: Member): Promise<DocumentAnswer> => {
61
- const { source, content, issues } = readAuthoringDocument(editor, { document, member })
62
- return { document, version: source.version, fingerprint: fnv1a64(source.content), content, issues }
63
+ const { source, content, effective, issues } = readAuthoringDocument(editor, { document, member })
64
+ return { document, version: source.version, fingerprint: fnv1a64(source.content), content, settings: documentSettings(effective), inherited: editor.inherited(document, content), inheritedFrom: editor.inheritedFrom(document, content), issues }
63
65
  }
64
- const readSelection = <T>(document: string, expected: CanonicalSource | undefined, member: Member, select: (content: TeachingDocument, source: CanonicalSource) => T): T => {
66
+ const readSelection = <T>(document: string, expected: CanonicalSource | undefined, member: Member, select: (content: PresmiumDocument, source: CanonicalSource) => T): T => {
65
67
  if (!hasRole(member, 'editor')) throw new RequestError(403, 'authoring-permission-denied')
66
68
  const scope = editor.scope(document), path = entryOf(document)
67
69
  const readSource = () => {
@@ -93,7 +95,8 @@ export function createDocumentEditor({ editor, revisions, reviewRequired = false
93
95
  if (!checked.change) throw new RequestError(400, 'document-change-invalid', { issues: checked.issues })
94
96
  return checked.change
95
97
  }
96
- const filesOf = async (document: string, current: DocumentAnswer, change: DocumentChange): Promise<{ content: TeachingDocument, issues: DocumentIssue[], changes: SourceTransactionChange[] }> => {
98
+ const filesOf = async (document: string, current: DocumentAnswer, change: DocumentChange): Promise<{ content: PresmiumDocument, issues: DocumentIssue[], changes: SourceTransactionChange[] }> => {
99
+ await nextTurn()
97
100
  if (current.version !== change.baseDocumentVersion) throw new RequestError(409, 'document-version-changed', { version: current.version })
98
101
  let candidate: unknown = change.replacement
99
102
  if (change.operations) {
@@ -106,6 +109,8 @@ export function createDocumentEditor({ editor, revisions, reviewRequired = false
106
109
  const path = entryOf(document), fileChanges = change.fileChanges ?? []
107
110
  if (fileChanges.some(file => file.path === path)) throw new RequestError(422, 'document-file-repeated')
108
111
  const changes = [{ path, content: `${JSON.stringify(checked.document, null, 2)}\n`, base: current.version }, ...fileChanges]
112
+ // The text written is the document just validated: its checks are not repeated when it is read back.
113
+ rememberCheckedText(changes[0]!.content, true, checked.issues)
109
114
  if (revisions) {
110
115
  const ignored = (await Promise.all(changes.map(async file => await revisions.ignores(file.path) ? file.path : undefined))).filter((path): path is string => Boolean(path))
111
116
  if (ignored.length) throw new RequestError(409, 'document-files-ignored', { ignored })
@@ -128,14 +133,24 @@ export function createDocumentEditor({ editor, revisions, reviewRequired = false
128
133
  await editor.planTransaction(editor.scope(document), candidate.changes, member)
129
134
  }
130
135
  const saveChange = async (document: string, raw: DocumentChange, member: Member, origin: 'editor' | 'agent' = 'editor'): Promise<DocumentChangeAnswer> => {
131
- const change = checkedChange(raw), current = await read(document, member)
136
+ // Validating a large document takes milliseconds; each check gets its own turn of the event loop.
137
+ const change = checkedChange(raw)
138
+ await nextTurn()
139
+ const current = await read(document, member)
140
+ await nextTurn()
132
141
  const signature = signatureOf(change), key = keyOf(document, member, change.id), receipt = replayOf(document, change, member, current)
133
142
  if (receipt) return { ...current, changeId: change.id, files: receipt.files, ...receipt.commit ? { commit: receipt.commit } : {} }
134
143
  const candidate = await filesOf(document, current, change)
135
144
  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)
145
+ const saved = await editor.transaction(editor.scope(document), candidate.changes, member, ownHistory).catch((error: unknown) => {
146
+ if (error instanceof RequestError && error.status === 409 && isRecord(error.detail?.conflict) && error.detail.conflict.path === entryOf(document)) {
147
+ throw new RequestError(409, 'document-version-changed', { version: error.detail.conflict.version })
148
+ }
149
+ throw error
150
+ })
137
151
  const version = saved.versions.find(file => file.path === entryOf(document))!.version
138
152
  remember(receipts, key, { signature, version, files: saved.versions, ...saved.revision ? { commit: saved.revision } : {} })
153
+ await nextTurn()
139
154
  const verified = await read(document, member)
140
155
  if (verified.version !== version || saved.versions.some(file => editor.read(editor.scope(document), file.path, member).version !== file.version)) throw new RequestError(409, 'document-readback-changed', { changeId: change.id, committed: true, version, currentVersion: verified.version })
141
156
  return { ...verified, changeId: change.id, files: saved.versions, ...saved.revision ? { commit: saved.revision } : {} }
@@ -320,7 +335,7 @@ export function createDocumentEditor({ editor, revisions, reviewRequired = false
320
335
  })
321
336
  const planId = randomUUID(), record: Plan = { key, signature: '', expires: Date.now() + PLAN_LIFETIME_MS, ready: false }
322
337
  const result = (async (): Promise<DocumentPageChangePlan> => {
323
- let candidate: TeachingDocument, sectionId: string, created
338
+ let candidate: PresmiumDocument, sectionId: string, created
324
339
  try {
325
340
  if (action.type === 'create') { const next = createDocumentPage(current, action.after ?? null, action.title, randomUUID); candidate = next.document; created = next.ids; sectionId = next.ids.sectionId }
326
341
  else {
@@ -0,0 +1,36 @@
1
+ import { validateDocument } from '@lincyaw/kernel'
2
+ import type { DocumentIssue, PresmiumDocument } from '@lincyaw/kernel'
3
+
4
+ /** How many recently checked document texts are remembered. */
5
+ const REMEMBERED = 16
6
+ const remembered = new Map<string, { valid: boolean, issues: DocumentIssue[] }>()
7
+
8
+ function remember(text: string, valid: boolean, issues: DocumentIssue[]): void {
9
+ remembered.delete(text)
10
+ remembered.set(text, { valid, issues })
11
+ while (remembered.size > REMEMBERED) remembered.delete(remembered.keys().next().value!)
12
+ }
13
+
14
+ /**
15
+ * A document file's text parsed and validated. Checking a large document holds the event loop for milliseconds, and a
16
+ * save checks the same text several times (the current file, the candidate, the readback), so the outcome for a
17
+ * recent text is remembered: the text is parsed again (a fresh document every time) and its checks are not repeated.
18
+ */
19
+ export function checkDocumentText(content: string): { document?: PresmiumDocument, issues: DocumentIssue[], syntax?: true } {
20
+ const text = content.replace(/^/, '')
21
+ let value: unknown
22
+ try { value = JSON.parse(text) } catch { return { issues: [], syntax: true } }
23
+ const known = remembered.get(text)
24
+ if (known) {
25
+ remember(text, known.valid, known.issues)
26
+ return { ...known.valid ? { document: value as PresmiumDocument } : {}, issues: known.issues.map(issue => ({ ...issue })) }
27
+ }
28
+ const checked = validateDocument(value)
29
+ remember(text, Boolean(checked.document), checked.issues.map(issue => ({ ...issue })))
30
+ return checked
31
+ }
32
+
33
+ /** A text about to be written whose document was just validated: reading it back does not check it again. */
34
+ export function rememberCheckedText(content: string, valid: boolean, issues: DocumentIssue[]): void {
35
+ remember(content.replace(/^/, ''), valid, issues.map(issue => ({ ...issue })))
36
+ }
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'node:crypto'
2
- import { DOCUMENT_ENTRY, DOCUMENT_HISTORY_MAX_FILE_BYTES, DOCUMENT_HISTORY_MAX_REQUEST_CHARS, DOCUMENT_HISTORY_MAX_RESPONSE_CHARS, DOCUMENT_HISTORY_PAGE_SIZE, fnv1a64, hasRole, jsonResponse, problemResponse } from '@lincyaw/kernel'
2
+ import { DOCUMENT_ENTRY, DOCUMENT_HISTORY_MAX_FILE_BYTES, DOCUMENT_SCHEMA_VERSION, DOCUMENT_HISTORY_MAX_REQUEST_CHARS, DOCUMENT_HISTORY_MAX_RESPONSE_CHARS, DOCUMENT_HISTORY_PAGE_SIZE, fnv1a64, hasRole, jsonResponse, problemResponse } from '@lincyaw/kernel'
3
3
  import type { DocumentHistory, DocumentHistoryAnswer, DocumentHistoryBinding, DocumentHistoryChange, DocumentHistoryChanged, DocumentHistoryFile, DocumentHistorySource, HistoryRevision, Member, Route } from '@lincyaw/kernel'
4
4
  import { validateDocumentHistoryChange, validateDocumentHistoryQuery, validateDocumentHistoryRead } from '@lincyaw/kernel/node'
5
5
  import { listDocuments } from './config.ts'
@@ -53,7 +53,14 @@ export function createDocumentHistory(options: DocumentHistoryOptions): { servic
53
53
  if ((/[\x00-\x1f\x7f]/.test(path) || path.split('/').some(part => part.startsWith('.'))) || documentDirOf(config, path) !== document) throw new RequestError(403, 'history-file-outside-document')
54
54
  }
55
55
  const compact = (document: string, entry: HistoryRevision, member: Member): HistoryRevision => {
56
- const files = entry.files.filter(path => { try { pathAllowed(document, path, member); return path.length <= 500 } catch { return false } })
56
+ // A revision can name every file of the workspace (the baseline does): only this document's files are checked in
57
+ // full, and only until the six shown are found.
58
+ const files: string[] = []
59
+ for (const path of entry.files) {
60
+ if (files.length >= 6) break
61
+ if (path.length > 500 || (document && !path.startsWith(`${document}/`))) continue
62
+ try { pathAllowed(document, path, member); files.push(path) } catch { /* Not shown. */ }
63
+ }
57
64
  const message = (entry.message.split('\n')[0] ?? '').slice(0, 240)
58
65
  return { id: entry.id, message, author: entry.author.slice(0, 120), date: entry.date, origin: { kind: entry.origin.kind }, files: files.slice(0, 6),
59
66
  ...entry.revertedBy ? { revertedBy: entry.revertedBy } : {}, ...entry.reverts ? { reverts: entry.reverts } : {}, ...entry.redo ? { redo: true } : {},
@@ -67,9 +74,25 @@ export function createDocumentHistory(options: DocumentHistoryOptions): { servic
67
74
  if (origin === 'agent' && options.reviewRequired) throw new RequestError(409, 'authoring-review-required')
68
75
  return { key: JSON.stringify([document, member.id, request.id]), signature: digest(JSON.stringify([which, request.id, request.snapshot, request.source.version, request.source.fingerprint, request.expect])) }
69
76
  }
70
- const targetPaths = async (document: string, request: DocumentHistoryChange, member: Member) => {
77
+ // A format upgrade (and a document's creation) is a boundary of its history: taking it back would leave the document
78
+ // without its entry file, or in a format this version no longer opens.
79
+ const supportedAt = async (revision: string, document: string): Promise<boolean> => {
80
+ try {
81
+ const bytes = await history().readFile(revision, entryOf(document), DOCUMENT_HISTORY_MAX_FILE_BYTES)
82
+ const value = JSON.parse(new TextDecoder().decode(bytes)) as { schemaVersion?: unknown }
83
+ return value.schemaVersion === DOCUMENT_SCHEMA_VERSION
84
+ } catch { return false }
85
+ }
86
+ const crossesBoundary = async (document: string, revision: string, paths?: string[]): Promise<boolean> => {
87
+ const files = paths ?? await history().filesOf(revision)
88
+ if (!files.includes(entryOf(document))) return false
89
+ const parent = await history().parentOf(revision)
90
+ return !parent || !await supportedAt(parent, document)
91
+ }
92
+ const targetPaths = async (document: string, request: DocumentHistoryChange, member: Member, which: 'undo' | 'redo' | 'revert') => {
71
93
  const paths = await history().filesOf(request.expect)
72
94
  if (!paths.length) throw new RequestError(404, 'history-revision-not-found')
95
+ if (which !== 'redo' && await crossesBoundary(document, request.expect, paths)) throw new RequestError(409, 'history-format-boundary')
73
96
  for (const path of paths) {
74
97
  pathAllowed(document, path, member)
75
98
  const owners = await Promise.all([history().ownerAt(request.expect, path), history().ownerAt(`${request.expect}^1`, path)])
@@ -93,6 +116,10 @@ export function createDocumentHistory(options: DocumentHistoryOptions): { servic
93
116
  if ((query.offset ?? 0) > 0 && !query.snapshot) throw new RequestError(400, 'history-snapshot-required')
94
117
  if (query.snapshot !== undefined && query.snapshot !== before.snapshot) throw new RequestError(409, 'history-snapshot-changed')
95
118
  const full = await revisions.historyWithUndo({ document }), changes = full.revisions.filter(entry => !entry.reverts), offset = query.offset ?? 0
119
+ // The upgrade from the earlier format is not offered as a step to undo or revert.
120
+ if (full.undo && await crossesBoundary(document, full.undo)) delete full.undo
121
+ const legacy = `${document ? `${document}/` : ''}lecture.json`
122
+ for (const entry of changes) if (entry.files.includes(legacy) && entry.files.includes(entryOf(document))) entry.revertible = false
96
123
  if (offset > changes.length) throw new RequestError(400, 'history-offset-invalid')
97
124
  const answer: DocumentHistoryAnswer = { document, available: true, historyBinding: before, revisions: [], ...full.undo ? { undo: full.undo } : {}, ...full.redo ? { redo: full.redo } : {} }
98
125
  let index = offset
@@ -119,7 +146,8 @@ export function createDocumentHistory(options: DocumentHistoryOptions): { servic
119
146
  if (content.includes('\0')) throw new RequestError(422, 'history-file-not-utf8-text')
120
147
  const offset = query.offset ?? 0
121
148
  if (offset > content.length || offset > 0 && /[\uD800-\uDBFF]/.test(content[offset - 1]!) && /[\uDC00-\uDFFF]/.test(content[offset] ?? '')) throw new RequestError(400, 'history-offset-invalid')
122
- const reply = (end: number): DocumentHistoryFile => ({ document, revision: query.revision, path, encoding: 'utf8-text-fragment', text: content.slice(offset, end), offset, ...end < content.length ? { nextOffset: end } : {}, totalChars: content.length, complete: end === content.length, sha256: digest(bytes), verification: 'historical-file-only' })
149
+ const sha256 = digest(bytes)
150
+ const reply = (end: number): DocumentHistoryFile => ({ document, revision: query.revision, path, encoding: 'utf8-text-fragment', text: content.slice(offset, end), offset, ...end < content.length ? { nextOffset: end } : {}, totalChars: content.length, complete: end === content.length, sha256, verification: 'historical-file-only' })
123
151
  let low = offset, high = Math.min(content.length, offset + DOCUMENT_HISTORY_MAX_RESPONSE_CHARS)
124
152
  while (low < high) { const middle = Math.ceil((low + high) / 2); if (size(reply(middle)) <= DOCUMENT_HISTORY_MAX_RESPONSE_CHARS) low = middle; else high = middle - 1 }
125
153
  if (low < content.length && low > offset && /[\uD800-\uDBFF]/.test(content[low - 1]!) && /[\uDC00-\uDFFF]/.test(content[low]!)) low--
@@ -134,7 +162,7 @@ export function createDocumentHistory(options: DocumentHistoryOptions): { servic
134
162
  if (known && !flight && !sameBinding(await binding(document, member), { source: known.answer.source, snapshot: known.answer.snapshot })) throw new RequestError(409, 'history-result-no-longer-current')
135
163
  return
136
164
  }
137
- const paths = await targetPaths(document, request, member)
165
+ const paths = await targetPaths(document, request, member, which)
138
166
  if (!sameBinding(await binding(document, member), { source: request.source, snapshot: request.snapshot })) throw new RequestError(409, 'history-source-changed')
139
167
  const claimed = locks.claimAll(paths.map(path => documentDirOf(config, path)!), 'revision:revert')
140
168
  if ('holder' in claimed) throw lockedError(claimed.document, claimed.holder)
@@ -154,7 +182,7 @@ export function createDocumentHistory(options: DocumentHistoryOptions): { servic
154
182
  }
155
183
  if (pending.size >= MAX_RECEIPTS) throw new RequestError(429, 'history-busy')
156
184
  const work = Promise.resolve().then(async () => {
157
- const paths = await targetPaths(document, request, member)
185
+ const paths = await targetPaths(document, request, member, which)
158
186
  const claimed = locks.claimAll(paths.map(path => documentDirOf(config, path)!), 'revision:revert')
159
187
  if ('holder' in claimed) throw lockedError(claimed.document, claimed.holder)
160
188
  try {
@@ -4,14 +4,15 @@ import { lstat, open, stat } from 'node:fs/promises'
4
4
  import { basename, extname, join, relative } from 'node:path'
5
5
  import { imageSize } from 'image-size'
6
6
  import { ASSET_TITLE_MAX_LENGTH, DOCUMENT_IMAGE_MAX_BYTES, fnv1a64, hasRole, isRecord, jsonResponse } from '@lincyaw/kernel'
7
- import type { Asset, CanonicalSource, DocumentImageAuthoring, DocumentImageImport, DocumentImageImportAnswer, DocumentWorkspaceImageImport, Member, RequestContext, Route, TeachingDocument, VerifiedDocumentImageImport } from '@lincyaw/kernel'
7
+ import type { Asset, CanonicalSource, DocumentImageAuthoring, DocumentImageImport, DocumentImageImportAnswer, DocumentWorkspaceImageImport, Member, RequestContext, Route, PresmiumDocument, VerifiedDocumentImageImport } from '@lincyaw/kernel'
8
8
  import { productionAssetFile, validateDocumentWorkspaceImageImport, validateDocumentWorkspaceImageInspect } from '@lincyaw/kernel/node'
9
9
  import { readAuthoringDocument } from './document-editor.ts'
10
10
  import { catchRequestErrors, RequestError } from './errors.ts'
11
+ import type { MediaUploadsOwner } from './media-uploads.ts'
11
12
  import type { Revisions } from './revisions.ts'
12
13
  import type { SourceEditor, SourceTransactionHistory } from './source-editor.ts'
13
14
 
14
- interface Options { root: string, editor: SourceEditor, revisions?: Revisions, reviewRequired?: boolean }
15
+ interface Options { root: string, editor: SourceEditor, revisions?: Revisions, reviewRequired?: boolean, uploads?: MediaUploadsOwner }
15
16
  interface ImageFormat { extension: string, mediaType: string }
16
17
  interface Receipt { signature: string, assetId: string, version: string, files?: DocumentImageImportAnswer['files'], commit?: DocumentImageImportAnswer['commit'] }
17
18
  const FORMATS: Record<string, ImageFormat> = {
@@ -34,7 +35,7 @@ function inspect(bytes: Uint8Array) {
34
35
  }
35
36
 
36
37
  /** Original bytes and the canonical asset bank are committed or rolled back together. */
37
- export function createDocumentImageAuthoring({ root, editor, revisions, reviewRequired = false }: Options): { service: DocumentImageAuthoring, routes: Record<string, Route> } {
38
+ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRequired = false, uploads }: Options): { service: DocumentImageAuthoring, routes: Record<string, Route>, busy(): boolean } {
38
39
  const receipts = new Map<string, Receipt>(), pending = new Map<string, { signature: string, done: Promise<DocumentImageImportAnswer> }>()
39
40
  const binding = (current: ReturnType<typeof readAuthoringDocument>): CanonicalSource => ({ documentId: current.content.id, version: current.source.version, fingerprint: fnv1a64(current.source.content) })
40
41
  const opened = (ctx: RequestContext, version?: string, source?: CanonicalSource) => {
@@ -77,7 +78,7 @@ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRe
77
78
  receipts.set(key, receipt)
78
79
  while (receipts.size > 64) receipts.delete(receipts.keys().next().value!)
79
80
  }
80
- const history = (ctx: RequestContext, document: TeachingDocument, signal: AbortSignal, origin: 'editor' | 'agent'): SourceTransactionHistory => ({
81
+ const history = (ctx: RequestContext, document: PresmiumDocument, signal: AbortSignal, origin: 'editor' | 'agent'): SourceTransactionHistory => ({
81
82
  run: work => {
82
83
  const guarded = () => { signal.throwIfAborted(); return work() }
83
84
  return revisions ? revisions.transaction(guarded) : guarded()
@@ -86,12 +87,12 @@ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRe
86
87
  if (!revisions) return undefined
87
88
  const ignored = (await Promise.all(paths.map(async path => await revisions.ignores(path) ? path : undefined))).filter((path): path is string => Boolean(path))
88
89
  if (ignored.length) throw new RequestError(409, 'document-files-ignored', { ignored })
89
- return revisions.commitWhileLocked({ paths, summary: document.metadata.lang.startsWith('en') ? 'Import image' : '导入图片', body: '', origin: { kind: origin, member: ctx.member } })
90
+ return revisions.commitWhileLocked({ paths, summary: editor.effective(ctx.document, document).metadata.lang.startsWith('en') ? 'Import image' : '导入图片', body: '', origin: { kind: origin, member: ctx.member } })
90
91
  },
91
92
  })
92
- const signatureOf = (change: DocumentImageImport, title: string, hash: string, origin: 'editor' | 'agent', source?: CanonicalSource, inputPath?: string) => createHash('sha256').update(JSON.stringify([change.id, change.baseDocumentVersion, source?.documentId ?? null, source?.fingerprint ?? null, origin, inputPath ?? null, title, hash])).digest('hex')
93
+ const signatureOf = (change: DocumentImageImport, title: string, hash: string, origin: 'editor' | 'agent', source?: CanonicalSource, inputPath?: string | { upload: string }) => createHash('sha256').update(JSON.stringify([change.id, change.baseDocumentVersion, source?.documentId ?? null, source?.fingerprint ?? null, origin, inputPath ?? null, title, hash])).digest('hex')
93
94
  const keyOf = (ctx: RequestContext, change: DocumentImageImport) => JSON.stringify([ctx.document, ctx.member.id, change.id])
94
- const apply = async (ctx: RequestContext, change: DocumentImageImport, title: string, bytes: Uint8Array, image: ReturnType<typeof inspect>, hash: string, signal: AbortSignal, origin: 'editor' | 'agent', source?: CanonicalSource, inputPath?: string): Promise<DocumentImageImportAnswer> => {
95
+ const apply = async (ctx: RequestContext, change: DocumentImageImport, title: string, bytes: Uint8Array, image: ReturnType<typeof inspect>, hash: string, signal: AbortSignal, origin: 'editor' | 'agent', source?: CanonicalSource, inputPath?: string | { upload: string }): Promise<DocumentImageImportAnswer> => {
95
96
  const signature = signatureOf(change, title, hash, origin, source, inputPath), key = keyOf(ctx, change)
96
97
  const replay = async () => {
97
98
  const previous = receipts.get(key)
@@ -160,10 +161,19 @@ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRe
160
161
  signal?.throwIfAborted(); return bytes.slice(0, length)
161
162
  } finally { await handle.close() }
162
163
  }
164
+ const input = async (ctx: RequestContext, source: CanonicalSource, location: { path?: string, upload?: string }, signal?: AbortSignal) => {
165
+ if (location.upload !== undefined) {
166
+ signal?.throwIfAborted()
167
+ if (!uploads) throw new RequestError(503, 'media-upload-unavailable')
168
+ return uploads.read(ctx.document, source.documentId, ctx.member, location.upload, 'image')
169
+ }
170
+ return { bytes: await reader(ctx, location.path!, signal), name: basename(location.path!) }
171
+ }
163
172
  const workspaceImport = async (ctx: RequestContext, request: DocumentWorkspaceImageImport, signal?: AbortSignal) => {
164
- const bytes = await reader(ctx, request.file.path, signal), sha256 = createHash('sha256').update(bytes).digest('hex')
173
+ const { bytes, name } = await input(ctx, request.source, request.file, signal), sha256 = createHash('sha256').update(bytes).digest('hex')
165
174
  if (bytes.length !== request.file.byteLength || sha256 !== request.file.sha256) throw new RequestError(409, 'image-file-changed')
166
- const image = inspect(bytes), title = [...basename(request.file.path).replace(/[\u0000-\u001f\u007f-\u009f]/g, '').trim()].slice(0, ASSET_TITLE_MAX_LENGTH).join('')
175
+ if (request.file.upload && request.file.name !== name) throw new RequestError(409, 'image-file-changed')
176
+ const image = inspect(bytes), title = [...name.replace(/[\u0000-\u001f\u007f-\u009f]/g, '').trim()].slice(0, ASSET_TITLE_MAX_LENGTH).join('')
167
177
  return { bytes, image, sha256, title }
168
178
  }
169
179
  let active = 0
@@ -183,9 +193,9 @@ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRe
183
193
  if (!validateDocumentWorkspaceImageInspect(request)) throw new RequestError(400, 'document-image-query-invalid')
184
194
  return limited(async () => {
185
195
  const ctx = ctxOf(document, member); opened(ctx, request.source.version, request.source)
186
- const bytes = await reader(ctx, request.path, signal), image = inspect(bytes), sha256 = createHash('sha256').update(bytes).digest('hex')
196
+ const { bytes, name } = await input(ctx, request.source, request, signal), image = inspect(bytes), sha256 = createHash('sha256').update(bytes).digest('hex')
187
197
  signal?.throwIfAborted(); opened(ctx, request.source.version, request.source)
188
- return { document, source: request.source, file: { path: request.path, sha256, byteLength: bytes.length }, image: { mediaType: image.mediaType, dimensions: image.dimensions } }
198
+ return { document, source: request.source, file: { ...request.upload ? { upload: request.upload, name } : { path: request.path! }, sha256, byteLength: bytes.length }, image: { mediaType: image.mediaType, dimensions: image.dimensions } }
189
199
  })
190
200
  },
191
201
  async checkWorkspaceImport(document, request, member, signal) {
@@ -195,7 +205,7 @@ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRe
195
205
  return limited(async () => {
196
206
  const ctx = ctxOf(document, member), change = { id: request.id, baseDocumentVersion: request.source.version }, key = keyOf(ctx, change)
197
207
  if (!receipts.has(key) && !pending.has(key)) opened(ctx, request.source.version, request.source)
198
- const { sha256, title } = await workspaceImport(ctx, request, signal), signature = signatureOf(change, title, sha256, 'agent', request.source, request.file.path)
208
+ const { sha256, title } = await workspaceImport(ctx, request, signal), signature = signatureOf(change, title, sha256, 'agent', request.source, request.file.path ?? { upload: request.file.upload! })
199
209
  const receipt = receipts.get(key), known = receipt ?? pending.get(key)
200
210
  if (known && known.signature !== signature) throw new RequestError(409, 'document-change-id-reused')
201
211
  // A receipt of this exact import replays while the source is still the one it saved; an import in flight decides itself.
@@ -209,7 +219,7 @@ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRe
209
219
  if (!validateDocumentWorkspaceImageImport(request)) throw new RequestError(400, 'document-image-import-invalid')
210
220
  return limited(async () => {
211
221
  const ctx = ctxOf(document, member), { bytes, image, sha256, title } = await workspaceImport(ctx, request, signal)
212
- const result = await apply(ctx, { id: request.id, baseDocumentVersion: request.source.version }, title, bytes, image, sha256, signal ?? new AbortController().signal, 'agent', request.source, request.file.path)
222
+ const result = await apply(ctx, { id: request.id, baseDocumentVersion: request.source.version }, title, bytes, image, sha256, signal ?? new AbortController().signal, 'agent', request.source, request.file.path ?? { upload: request.file.upload! })
213
223
  try {
214
224
  const current = opened(ctx, result.version), asset = current.content.assets[result.assetId], file = asset && productionAssetFile(join(root, document), asset.location)
215
225
  if (!asset || !file || !await matches(ctx, asset, bytes, image, new AbortController().signal)) throw new Error('asset-changed')
@@ -237,5 +247,5 @@ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRe
237
247
  return jsonResponse(await apply(ctx, change, title, bytes, image, hash, request.signal, 'editor'))
238
248
  }) },
239
249
  }
240
- return { service, routes }
250
+ return { service, routes, busy: () => active > 0 || pending.size > 0 }
241
251
  }