@lincyaw/workspace 1.0.0-rc.59 → 1.0.0-rc.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workspace",
3
- "version": "1.0.0-rc.59",
3
+ "version": "1.0.0-rc.60",
4
4
  "description": "Presmium's workspace service (presmium serve): documents, their history, reviews and the workspace site",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -34,12 +34,13 @@
34
34
  "mime-types": "3.0.2",
35
35
  "playwright-chromium": "1.64.1",
36
36
  "yaml": "^2.9.1",
37
- "@lincyaw/compiler": "1.0.0-rc.59",
38
- "@lincyaw/server": "1.0.0-rc.59",
39
- "@lincyaw/kernel": "1.0.0-rc.59"
37
+ "@lincyaw/compiler": "1.0.0-rc.60",
38
+ "@lincyaw/server": "1.0.0-rc.60",
39
+ "@lincyaw/design": "1.0.0-rc.60",
40
+ "@lincyaw/kernel": "1.0.0-rc.60"
40
41
  },
41
42
  "devDependencies": {
42
43
  "@types/mime-types": "^3.0.1",
43
- "@lincyaw/mcp": "1.0.0-rc.59"
44
+ "@lincyaw/mcp": "1.0.0-rc.60"
44
45
  }
45
46
  }
@@ -8,6 +8,7 @@ import { productionAssetFile, validateDocumentRecordingAdoption, validateDocumen
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
  }
@@ -57,7 +59,7 @@ export async function readDocumentAudioBytes(editor: SourceEditor, ctx: RequestC
57
59
  }
58
60
 
59
61
  /** Owns the canonical transaction and receipts; plugin services only inspect actual media. */
60
- 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>, close(): Promise<void> } {
61
63
  const receipts = new Map<string, Receipt>(), imports = new Map<string, { signature: string, source: CanonicalSource, promise: Promise<VerifiedDocumentAudioImport> }>(), operations = new Set<Operation>()
62
64
  const clipChanges = new Map<string, { signature: string, promise: Promise<VerifiedDocumentMediaClipChange> }>()
63
65
  const recordingChanges = new Map<string, { signature: string, promise: Promise<VerifiedDocumentRecordingAdoption> }>()
@@ -131,7 +133,7 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
131
133
  }
132
134
  }
133
135
  const importKey = (ctx: RequestContext, id: string) => JSON.stringify(['audio', ctx.document, ctx.member.id, id])
134
- 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] : []]))
135
137
  /** A known intent replays (receipt still current) or joins its flight; a different payload under the same ID is refused. */
136
138
  const known = (ctx: RequestContext, signature: string, previous: Receipt | undefined, pending: { signature: string } | undefined) => {
137
139
  if (!previous && !pending) return false
@@ -139,10 +141,10 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
139
141
  if (previous) opened(ctx, previous.version)
140
142
  return true
141
143
  }
142
- 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) => {
143
145
  authorize(ctx.member); available()
144
146
  if (origin === 'agent' && reviewRequired) throw new RequestError(409, 'authoring-review-required')
145
- 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)
146
148
  const previous = receipts.get(key)
147
149
  if (previous) {
148
150
  if (previous.signature !== signature) throw new RequestError(409, 'document-change-id-reused')
@@ -155,7 +157,7 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
155
157
  imports.set(key, { signature, source, promise })
156
158
  return promise
157
159
  }
158
- 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) => {
159
161
  check(signal)
160
162
  if (!found.audio) throw new RequestError(503, 'production-audio-unavailable')
161
163
  const current = opened(ctx, change.baseDocumentVersion, source), assetId = `audio_${randomUUID().replaceAll('-', '')}`, probed = await found.audio.inspectBytes(assetId, bytes, signal)
@@ -166,7 +168,7 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
166
168
  check(signal); opened(ctx, change.baseDocumentVersion, source)
167
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) }))
168
170
  const version = saved.versions.find(file => file.path === current.source.path)!.version
169
- 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 } : {} }
170
172
  remember(importKey(ctx, change.id), receipt)
171
173
  // A committed write is verified even when its request disconnected or shutdown began meanwhile.
172
174
  return readback(ctx, change.id, receipt)
@@ -318,12 +320,25 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
318
320
  recordingChanges.set(key, { signature, promise })
319
321
  return promise
320
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
+ }
321
332
  const workspaceImport = (document: string, request: DocumentWorkspaceAudioImport, member: Member) => {
322
333
  authorize(member); available()
323
334
  if (!validateDocumentWorkspaceAudioImport(request)) throw new RequestError(400, 'document-audio-import-invalid')
324
335
  if (Buffer.byteLength(JSON.stringify(request)) > DOCUMENT_AUDIO_REQUEST_MAX_BYTES) throw new RequestError(413, 'document-audio-request-size')
325
- workspacePath(document, request.file.path, member)
326
- 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 } }
327
342
  }
328
343
  const service: DocumentAudioAuthoring = {
329
344
  capabilities: (document, member) => work(member, undefined, async signal => {
@@ -341,16 +356,15 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
341
356
  }),
342
357
  inspectWorkspace: (document, request, member, signal) => work(member, signal, async signal => {
343
358
  if (!validateDocumentWorkspaceAudioInspect(request)) throw new RequestError(400, 'document-audio-query-invalid')
344
- workspacePath(document, request.path, member)
345
359
  const ctx = ctxOf(document, member)
346
360
  opened(ctx, request.source.version, request.source)
347
- 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)])
348
362
  if (!found.audio) throw new RequestError(503, 'production-audio-unavailable')
349
363
  const probed = await found.audio.inspectBytes('workspace-audio-probe', bytes, signal)
350
364
  const { assetId: _assetId, mediaId: _mediaId, ...inspection } = probed.inspection
351
365
  if (inspection.sha256 !== hash(bytes) || inspection.byteLength !== bytes.length) throw new RequestError(409, 'audio-inspection-changed')
352
366
  check(signal); opened(ctx, request.source.version, request.source)
353
- 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
354
368
  }),
355
369
  readProductionPlan: (document, request, member, signal) => work(member, signal, async signal => {
356
370
  if (!validateDocumentProductionPlanQuery(request)) throw new RequestError(400, 'production-query-invalid')
@@ -368,9 +382,10 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
368
382
  return work(member, signal, async signal => {
369
383
  if (reviewRequired) throw new RequestError(409, 'authoring-review-required')
370
384
  const key = importKey(ctx, request.id)
371
- 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
372
386
  opened(ctx, request.source.version, request.source)
373
- 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')
374
389
  if (bytes.length !== request.file.byteLength || hash(bytes) !== request.file.sha256) throw new RequestError(409, 'audio-file-changed')
375
390
  if (!found.audio) throw new RequestError(503, 'production-audio-unavailable')
376
391
  await found.audio.inspectBytes('workspace-audio-probe', bytes, signal)
@@ -381,10 +396,11 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
381
396
  const { ctx, title, change } = workspaceImport(document, request, member)
382
397
  return work(member, signal, signal => once(ctx, change, request.source, title, request.file.sha256, request.file.byteLength, 'agent', async () => {
383
398
  opened(ctx, request.source.version, request.source)
384
- 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')
385
401
  if (bytes.length !== request.file.byteLength || hash(bytes) !== request.file.sha256) throw new RequestError(409, 'audio-file-changed')
386
- return importBytes(ctx, change, title, bytes, request.source, found, 'agent', signal)
387
- }))
402
+ return importBytes(ctx, change, title, bytes, request.source, found, 'agent', signal, request.file.upload)
403
+ }, request.file.upload))
388
404
  },
389
405
  validateClipChange: (document, request, member, signal) => work(member, signal, async signal => {
390
406
  if (!validateDocumentMediaClipValidation(request)) throw new RequestError(400, 'document-media-clip-invalid')
@@ -8,10 +8,11 @@ import type { Asset, CanonicalSource, DocumentImageAuthoring, DocumentImageImpor
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> } {
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) => {
@@ -89,9 +90,9 @@ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRe
89
90
  return revisions.commitWhileLocked({ paths, summary: 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')
@@ -0,0 +1,4 @@
1
+ export const MEDIA_UPLOAD_MESSAGES = {
2
+ 'zh-CN': { image: '上传图片', audio: '上传音频', choose: '选择文件', sending: '正在上传…', ready: '上传完成。请返回助手继续导入。', pending: '选择文件后自动上传,再由助手导入讲义。', failed: '上传未完成。请重新选择文件后重试。', unavailable: '此上传链接已失效,请返回助手重新发起上传。', limit: (size: number) => `文件大小上限:${size} MiB` },
3
+ en: { image: 'Upload Image', audio: 'Upload Audio', choose: 'Choose File', sending: 'Uploading…', ready: 'Upload complete. Return to the assistant to import it.', pending: 'Choose a file to upload it, then return to the assistant to import it.', failed: 'Upload did not finish. Choose the file and try again.', unavailable: 'This upload link expired. Return to the assistant to request another.', limit: (size: number) => `Maximum file size: ${size} MiB` },
4
+ }
@@ -0,0 +1,57 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { readFileSync } from 'node:fs'
3
+ import type { MediaUpload } from '@lincyaw/kernel'
4
+ import { MEDIA_UPLOAD_MESSAGES } from './media-upload-messages.ts'
5
+
6
+ const escape = (value: string) => value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;')
7
+ let styles: string | undefined
8
+ const css = () => styles ??= [readFileSync(new URL(import.meta.resolve('@lincyaw/design/tokens.css')), 'utf8'), readFileSync(new URL(import.meta.resolve('@lincyaw/design/components.css')), 'utf8'), readFileSync(new URL('./media-upload.css', import.meta.url), 'utf8')].join('\n')
9
+ export function mediaUploadPage(value: MediaUpload | undefined, locale: 'zh-CN' | 'en', documentTitle?: string): Response {
10
+ const t = MEDIA_UPLOAD_MESSAGES[locale], nonce = randomBytes(18).toString('base64'), title = value ? t[value.kind] : t.unavailable
11
+ const ready = value?.state === 'ready', uploading = value?.state === 'uploading'
12
+ const script = value ? `
13
+ const form = document.querySelector('form');
14
+ const status = document.querySelector('[role="status"]');
15
+ const input = document.querySelector('input');
16
+ const choose = document.querySelector('button');
17
+ choose?.addEventListener('click', () => input.click());
18
+ form?.addEventListener('submit', async event => {
19
+ event.preventDefault();
20
+ const file = input.files[0];
21
+ if (!file || input.disabled) return;
22
+ if (file.size > ${value.maxBytes}) { status.textContent = ${JSON.stringify(t.limit(value.maxBytes / (1 << 20)))}; input.value = ''; return; }
23
+ input.disabled = true; choose.disabled = true;
24
+ status.textContent = ${JSON.stringify(t.sending)};
25
+ try {
26
+ const answer = await fetch(location.href, { method: 'POST', credentials: 'same-origin', redirect: 'error',
27
+ headers: { 'Content-Type': 'application/octet-stream', 'X-Presmium-Upload-Name': encodeURIComponent(file.name) }, body: file });
28
+ if (!answer.ok) throw Error();
29
+ form.remove();
30
+ status.textContent = ${JSON.stringify(t.ready)};
31
+ } catch {
32
+ status.textContent = ${JSON.stringify(t.failed)};
33
+ input.disabled = false; choose.disabled = false;
34
+ input.value = '';
35
+ }
36
+ });
37
+ input?.addEventListener('change', () => form.requestSubmit());
38
+ ` : ''
39
+ const html = `<!doctype html>
40
+ <html lang="${locale}">
41
+ <head>
42
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
43
+ <title>${escape(title)}</title><style nonce="${nonce}">${css()}</style>
44
+ <script nonce="${nonce}">
45
+ const theme = matchMedia('(prefers-color-scheme: dark)');
46
+ const update = () => document.documentElement.classList.toggle('dark', theme.matches);
47
+ update(); theme.addEventListener('change', update);
48
+ </script>
49
+ </head>
50
+ <body class="pm-ui pm-media-upload-body"><main class="pm-media-upload">
51
+ <h1>${escape(title)}</h1>${documentTitle ? `<p>${escape(documentTitle)}</p>` : ''}
52
+ ${value ? `<p>${escape(t.limit(value.maxBytes / (1 << 20)))}</p><p>${escape(t.pending)}</p>
53
+ ${ready || uploading ? '' : `<form><button class="pm-ui-button" type="button">${escape(t.choose)}</button><input hidden type="file" name="file" aria-label="${escape(t.choose)}" accept="${value.kind}/*" required></form>`}` : ''}
54
+ <p role="status">${ready ? escape(t.ready) : uploading ? escape(t.sending) : ''}</p>
55
+ </main><script nonce="${nonce}">${script}</script></body></html>`
56
+ return new Response(html, { status: value ? 200 : 410, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff', 'content-security-policy': `default-src 'none'; style-src 'nonce-${nonce}'; script-src 'nonce-${nonce}'; connect-src 'self'; form-action 'none'; base-uri 'none'; frame-ancestors 'none'` } })
57
+ }
@@ -0,0 +1,4 @@
1
+ .pm-media-upload-body { margin: 0; padding: var(--pm-space-6); color: var(--pm-color-ink); background: var(--pm-color-bg); font-family: var(--pm-font-sans); }
2
+ .pm-media-upload { max-inline-size: var(--pm-dialog-width); margin-inline: auto; }
3
+ .pm-media-upload form { display: grid; justify-items: start; gap: var(--pm-space-4); }
4
+ .pm-media-upload h1 { font-size: var(--pm-text-lg); }
@@ -0,0 +1,116 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { ASSET_TITLE_MAX_LENGTH, DOCUMENT_AUDIO_MAX_BYTES, DOCUMENT_IMAGE_MAX_BYTES, MEDIA_UPLOAD_KINDS, MEDIA_UPLOAD_PATH, hasRole } from '@lincyaw/kernel'
3
+ import type { DocumentMediaUploads, MediaUpload, MediaUploadKind, Member } from '@lincyaw/kernel'
4
+ import { readAuthoringDocument } from './document-editor.ts'
5
+ import type { SourceEditor } from './source-editor.ts'
6
+ import { RequestError } from './errors.ts'
7
+ import { mediaUploadPage } from './media-upload-page.ts'
8
+
9
+ interface Entry { value: MediaUpload, document: string, documentId: string, member: string, locale?: 'zh-CN' | 'en', title: string, bytes?: Uint8Array, reserved: number, controller: AbortController, timer: ReturnType<typeof setTimeout> }
10
+ export interface MediaUploadsOwner extends DocumentMediaUploads {
11
+ read(document: string, documentId: string, member: Member, upload: string, kind: MediaUploadKind): { bytes: Uint8Array, name: string }
12
+ handle(request: Request): Promise<Response>
13
+ close(): void
14
+ }
15
+ const MAX_SLOTS = 64, MAX_BYTES = 64 << 20, LIFETIME_MS = 10 * 60_000
16
+
17
+ /** Bounded temporary input. Only the original media owners may commit these bytes to a document. */
18
+ export function createMediaUploads({ editor, url, lifetimeMs = LIFETIME_MS }: { editor: SourceEditor, url(): string, lifetimeMs?: number }): MediaUploadsOwner {
19
+ if (!Number.isSafeInteger(lifetimeMs) || lifetimeMs < 1 || lifetimeMs > LIFETIME_MS) throw new Error('media-upload-invalid')
20
+ const entries = new Map<string, Entry>()
21
+ let reserved = 0, closed = false
22
+ const fail = (status: number, code: string): never => { throw new RequestError(status, code) }
23
+ const current = (document: string, member: Member) => {
24
+ if (closed) return fail(503, 'media-upload-unavailable')
25
+ if (!hasRole(member, 'editor')) return fail(403, 'media-upload-permission-denied')
26
+ return readAuthoringDocument(editor, { document, member }).content
27
+ }
28
+ const release = (entry: Entry) => { reserved -= entry.reserved; entry.reserved = 0; delete entry.bytes }
29
+ const retire = (upload: string, entry: Entry) => {
30
+ if (entries.get(upload) !== entry) return
31
+ entries.delete(upload); clearTimeout(entry.timer); entry.controller.abort(); release(entry)
32
+ }
33
+ const lookup = (upload: string): Entry => {
34
+ const entry = entries.get(upload)
35
+ if (!entry || closed || Date.now() >= Date.parse(entry.value.expiresAt)) { if (entry) retire(upload, entry); return fail(410, 'media-upload-unavailable') }
36
+ return entry
37
+ }
38
+ const authorized = (document: string, member: Member, upload: string, documentId = current(document, member).id) => {
39
+ const entry = lookup(upload)
40
+ if (entry.document !== document || entry.documentId !== documentId || entry.member !== member.id) return fail(403, 'media-upload-permission-denied')
41
+ return entry
42
+ }
43
+ return {
44
+ async prepare(document, kind, member) {
45
+ const content = current(document, member)
46
+ if (!MEDIA_UPLOAD_KINDS.includes(kind)) return fail(400, 'media-upload-invalid')
47
+ if (entries.size >= MAX_SLOTS) return fail(503, 'media-upload-busy')
48
+ const upload = randomBytes(32).toString('hex'), expiresAt = new Date(Date.now() + lifetimeMs).toISOString()
49
+ const value: MediaUpload = { upload, kind, url: `${url().replace(/\/$/, '')}${MEDIA_UPLOAD_PATH}/${upload}`, expiresAt, maxBytes: kind === 'audio' ? DOCUMENT_AUDIO_MAX_BYTES : DOCUMENT_IMAGE_MAX_BYTES, state: 'empty' }
50
+ const entry: Entry = { value, document, documentId: content.id, member: member.id, locale: content.metadata.lang?.startsWith('en') ? 'en' : !content.metadata.lang || content.metadata.lang.startsWith('zh') ? 'zh-CN' : undefined, title: content.metadata.title, reserved: 0, controller: new AbortController(), timer: setTimeout(() => retire(upload, entry), lifetimeMs) }
51
+ entry.timer.unref(); entries.set(upload, entry)
52
+ return { ...value }
53
+ },
54
+ async status(document, upload, member) { return { ...authorized(document, member, upload).value } },
55
+ read(document, documentId, member, upload, kind) {
56
+ if (!hasRole(member, 'editor')) return fail(403, 'media-upload-permission-denied')
57
+ if (current(document, member).id !== documentId) return fail(403, 'media-upload-permission-denied')
58
+ const entry = authorized(document, member, upload, documentId)
59
+ if (entry.value.kind !== kind) return fail(400, 'media-upload-kind')
60
+ if (!entry.bytes || entry.value.state !== 'ready' || !entry.value.name) return fail(409, 'media-upload-not-ready')
61
+ return { bytes: new Uint8Array(entry.bytes), name: entry.value.name }
62
+ },
63
+ async handle(request) {
64
+ const headers = { 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', 'access-control-allow-origin': '*', 'access-control-allow-methods': 'POST, OPTIONS', 'access-control-allow-headers': 'Content-Type, X-Presmium-Upload-Name', 'x-content-type-options': 'nosniff' }
65
+ let entry: Entry | undefined
66
+ try {
67
+ const upload = new URL(request.url).pathname.split('/').at(-1) ?? ''
68
+ if (!/^[a-f0-9]{64}$/.test(upload)) return fail(410, 'media-upload-unavailable')
69
+ entry = lookup(upload)
70
+ if (request.method === 'GET') return mediaUploadPage(entry.value, entry.locale ?? (request.headers.get('accept-language')?.startsWith('en') ? 'en' : 'zh-CN'), entry.title)
71
+ if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers })
72
+ if (request.method !== 'POST') return new Response(null, { status: 405, headers })
73
+ if (entry.value.state !== 'empty') return fail(409, 'media-upload-already-written')
74
+ const declared = request.headers.get('content-length')
75
+ if (declared !== null && !/^\d+$/.test(declared)) return fail(400, 'media-upload-invalid')
76
+ const allocation = declared === null ? entry.value.maxBytes : Number(declared)
77
+ if (!Number.isSafeInteger(allocation) || allocation < 1 || allocation > entry.value.maxBytes) return fail(413, 'media-upload-size')
78
+ if (reserved + allocation > MAX_BYTES) return fail(503, 'media-upload-busy')
79
+ const encoded = request.headers.get('x-presmium-upload-name') ?? entry.value.kind
80
+ if (encoded.length > 4096) return fail(400, 'media-upload-invalid')
81
+ let name: string
82
+ try { name = decodeURIComponent(encoded).replaceAll('\\', '/').split('/').at(-1)!.replace(/[\u0000-\u001f\u007f-\u009f]/g, '').trim() } catch { return fail(400, 'media-upload-invalid') }
83
+ name = [...name].slice(0, ASSET_TITLE_MAX_LENGTH).join('') || entry.value.kind
84
+ const reader = request.body?.getReader()
85
+ if (!reader) return fail(400, 'media-upload-invalid')
86
+ const signal = AbortSignal.any([request.signal, entry.controller.signal]), bytes = new Uint8Array(allocation)
87
+ entry.reserved = allocation; reserved += allocation; entry.value.state = 'uploading'
88
+ const abort = () => { void reader.cancel().catch(() => {}) }
89
+ signal.addEventListener('abort', abort, { once: true })
90
+ let length = 0
91
+ try {
92
+ signal.throwIfAborted()
93
+ for (;;) {
94
+ const next = await reader.read(); signal.throwIfAborted()
95
+ if (next.done) break
96
+ if (length + next.value.byteLength > allocation) return fail(413, 'media-upload-size')
97
+ bytes.set(next.value, length); length += next.value.byteLength
98
+ }
99
+ if (!length || declared !== null && length !== allocation) return fail(400, 'media-upload-invalid')
100
+ lookup(upload); signal.throwIfAborted()
101
+ entry.bytes = bytes.subarray(0, length); entry.value = { ...entry.value, state: 'ready', name, byteLength: length }
102
+ return new Response(JSON.stringify({ uploaded: true }), { headers: { ...headers, 'content-type': 'application/json' } })
103
+ } finally {
104
+ signal.removeEventListener('abort', abort)
105
+ if (entry.value.state !== 'ready') { release(entry); if (entries.get(upload) === entry) entry.value.state = 'empty'; await reader.cancel().catch(() => {}) }
106
+ reader.releaseLock()
107
+ }
108
+ } catch (error) {
109
+ if (request.method === 'GET') return mediaUploadPage(undefined, entry?.locale ?? (request.headers.get('accept-language')?.startsWith('en') ? 'en' : 'zh-CN'))
110
+ const status = error instanceof RequestError ? error.status : 400
111
+ return new Response(JSON.stringify({ error: { code: error instanceof RequestError ? error.message : 'media-upload-invalid' } }), { status, headers: { ...headers, 'content-type': 'application/json' } })
112
+ }
113
+ },
114
+ close() { closed = true; for (const [upload, entry] of entries) retire(upload, entry) },
115
+ }
116
+ }
package/src/node/serve.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { createMediaUploads } from './media-uploads.ts'
1
2
  import { createProjectAuthoring } from './projects.ts'
2
3
  import { createDocumentHistory } from './document-history.ts'
3
4
  import { createAuthoringClients } from './authoring-clients.ts'
@@ -129,6 +130,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
129
130
  let authoringWindows: ReturnType<typeof createAuthoringWindows> | undefined
130
131
  let transcriptions: ReturnType<typeof createDocumentTranscriptions> | undefined
131
132
  let transcriptionAdoption: ReturnType<typeof createTranscriptionAdoption> | undefined
133
+ let mediaUploads: ReturnType<typeof createMediaUploads> | undefined
132
134
  let audioAuthoring: ReturnType<typeof createDocumentAudioAuthoring> | undefined
133
135
  let imageAuthoring: ReturnType<typeof createDocumentImageAuthoring> | undefined
134
136
  let capture: ReturnType<typeof createDocumentCapture> | undefined
@@ -208,7 +210,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
208
210
  authoringServicesClosed = true
209
211
  transcriptionAdoption?.close()
210
212
  for (const load of nodeServicePending) load.controller.abort()
211
- await Promise.all([projectAuthoring?.close(), transcriptions?.close(), audioAuthoring?.close(), voiceAuthoring?.close(), documentHistory?.close(), authoringClients?.close(), authoringWindows?.close(), workspaceRoutesOwner?.close?.()])
213
+ await Promise.all([mediaUploads?.close(), projectAuthoring?.close(), transcriptions?.close(), audioAuthoring?.close(), voiceAuthoring?.close(), documentHistory?.close(), authoringClients?.close(), authoringWindows?.close(), workspaceRoutesOwner?.close?.()])
212
214
  await Promise.allSettled([...nodeServicePending].map(load => load.promise))
213
215
  nodeServiceLoads.clear()
214
216
  }
@@ -278,6 +280,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
278
280
  get projectAuthoring() { return projectAuthoring?.service },
279
281
  get authoringClients() { return authoringClients?.service },
280
282
  get authoringWindows() { return authoringWindows?.service },
283
+ get mediaUploads() { return mediaUploads },
281
284
  get audioAuthoring() { return audioAuthoring?.service },
282
285
  get imageAuthoring() { return imageAuthoring?.service },
283
286
  get voiceAuthoring() { return voiceAuthoring?.service },
@@ -410,8 +413,9 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
410
413
  documentHistory = createDocumentHistory({ config, editor, locks, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required', changed: (before, after) => documentsChanged(documentsDiff(before, after)), reverted: (target, revision) => history?.agentSessionReviews.reverted(target, revision) })
411
414
  transcriptions = createDocumentTranscriptions({ root, editor, services: authoringServices })
412
415
  transcriptionAdoption = createTranscriptionAdoption({ documentEditor, transcriptions })
413
- audioAuthoring = createDocumentAudioAuthoring({ root, editor, revisions: history?.revisions, services: authoringServices, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
414
- imageAuthoring = createDocumentImageAuthoring({ root, editor, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
416
+ mediaUploads = createMediaUploads({ editor, url: () => `${publicOrigin()}${basePath.replace(/\/$/, '')}` })
417
+ audioAuthoring = createDocumentAudioAuthoring({ root, editor, uploads: mediaUploads, revisions: history?.revisions, services: authoringServices, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
418
+ imageAuthoring = createDocumentImageAuthoring({ root, editor, uploads: mediaUploads, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
415
419
  const routeOptions = {
416
420
  speechSettings: speechSettingsRoute(speechSettings),
417
421
  changesRoutes: workspaceChanges.routes,