@lincyaw/workspace 1.0.0-rc.6 → 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.
@@ -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')
@@ -1,6 +1,8 @@
1
- import { DOCUMENT_ENTRY, fnv1a64, hasRole, speechEngineId } from '@lincyaw/kernel'
2
- import type { CanonicalSource, DocumentVoiceAuthoring, Finding, Member, SpeechService, VoiceoverExecution, VoiceoverJob } from '@lincyaw/kernel'
3
- import { createVoiceoverOwner, createVoiceoverRoutes, validateDocumentVoiceCatalogQuery, validateVoicePreviewStart } from '@lincyaw/kernel/node'
1
+ import { DOCUMENT_ENTRY, VOICE_CLONE_MAX_AUDIO_BYTES, fnv1a64, hasRole, speechEngineId } from '@lincyaw/kernel'
2
+ import type { CanonicalSource, DocumentVoiceAuthoring, Finding, Member, PreparedVoiceClone, SpeechService, VoiceoverExecution, VoiceoverJob } from '@lincyaw/kernel'
3
+ import { createVoiceoverOwner, createVoiceoverRoutes, validateDocumentVoiceCatalogQuery, validateDocumentVoiceClone, validateDocumentVoiceCloneQuery, validateVoicePreviewStart } from '@lincyaw/kernel/node'
4
+ import { extname } from 'node:path'
5
+ import { readDocumentAudioBytes } from './document-audio.ts'
4
6
  import { readAuthoringDocument } from './document-editor.ts'
5
7
  import { RequestError } from './errors.ts'
6
8
  import type { SourceEditor } from './source-editor.ts'
@@ -16,6 +18,7 @@ const same = (a: CanonicalSource, b: CanonicalSource) => a.documentId === b.docu
16
18
  export function createDocumentVoiceAuthoring({ editor, services, revision }: DocumentVoiceAuthoringOptions) {
17
19
  const pending = new Set<{ controller: AbortController, finished: Promise<unknown> }>()
18
20
  const owners = new Map<string, ReturnType<typeof createVoiceoverOwner>>()
21
+ const clones = new Set<PreparedVoiceClone>()
19
22
  let closed = false
20
23
  const authorize = (document: string, member: Member) => {
21
24
  if (!hasRole(member, 'editor')) throw new RequestError(403, 'voice-authoring-permission-denied')
@@ -61,13 +64,67 @@ export function createDocumentVoiceAuthoring({ editor, services, revision }: Doc
61
64
  catch { return 'unknown' }
62
65
  }
63
66
  const service: DocumentVoiceAuthoring = {
67
+ prepareClone: (document, value, member, signal) => work(signal, async signal => {
68
+ if (!hasRole(member, 'owner')) throw new RequestError(403, 'voice-clone-permission-denied')
69
+ if (!validateDocumentVoiceClone(value)) throw new RequestError(400, 'voice-clone-invalid')
70
+ if (clones.size >= 4) throw new RequestError(503, 'voice-authoring-busy')
71
+ const request = structuredClone(value), loaded = await load(document, member, signal, request.source)
72
+ const speech = loaded.speech, engine = request.engine ?? await speech?.defaultSynthesisEngine?.()
73
+ const mime = (path: string) => {
74
+ if (path.split(/[\\/]/).some(part => part.startsWith('.'))) throw new RequestError(403, 'audio-file-path')
75
+ const types: Record<string, string> = { '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.webm': 'audio/webm', '.ogg': 'audio/ogg', '.m4a': 'audio/mp4', '.mp4': 'audio/mp4', '.flac': 'audio/flac', '.aac': 'audio/aac' }
76
+ const type = types[extname(path).toLowerCase()]
77
+ if (!type) throw new RequestError(422, 'voice-clone-audio-type')
78
+ editor.assertEditable({ document, home: false }, path, member)
79
+ return type
80
+ }
81
+ const sampleType = mime(request.sample), statementType = mime(request.consent.statement)
82
+ const [sampleBytes, statementBytes] = await Promise.all([request.sample, request.consent.statement].map(path => readDocumentAudioBytes(editor, { document, member, rest: '' }, path, signal, VOICE_CLONE_MAX_AUDIO_BYTES)))
83
+ current(document, member, loaded.source); signal.throwIfAborted()
84
+ if (!speech?.cloneVoice || !engine || !(await speech.engines()).some(info => info.id === speechEngineId(engine) && info.clone)) throw new RequestError(409, 'voice-clone-unavailable')
85
+ current(document, member, loaded.source); signal.throwIfAborted()
86
+ // Several readers may finish concurrently; the retained byte budget is checked again before retaining blobs.
87
+ if (clones.size >= 4) throw new RequestError(503, 'voice-authoring-busy')
88
+ let sample: Blob | undefined = new Blob([sampleBytes! as Uint8Array<ArrayBuffer>], { type: sampleType })
89
+ let statement: Blob | undefined = new Blob([statementBytes! as Uint8Array<ArrayBuffer>], { type: statementType })
90
+ let started: ReturnType<NonNullable<SpeechService['cloneVoice']>> | undefined
91
+ let expired = false
92
+ const prepared: PreparedVoiceClone = { engine: speechEngineId(engine), voice: request.voice,
93
+ start: startSignal => {
94
+ if (started) return started
95
+ if (expired || !sample || !statement) return Promise.reject(new RequestError(409, 'voice-clone-expired'))
96
+ clearTimeout(timer)
97
+ const exactSample = sample, exactStatement = statement
98
+ started = work(startSignal, async ownedSignal => {
99
+ current(document, member, loaded.source); ownedSignal.throwIfAborted()
100
+ return speech.cloneVoice!({ engine, voice: request.voice, sample: exactSample,
101
+ ...request.lang ? { lang: request.lang } : {}, ...request.text ? { text: request.text } : {},
102
+ consent: { speaker: request.consent.speaker, scope: request.consent.scope, statement: exactStatement } }, ownedSignal)
103
+ }).finally(() => prepared.close())
104
+ return started
105
+ },
106
+ close: () => { expired = true; clearTimeout(timer); sample = undefined; statement = undefined; clones.delete(prepared) },
107
+ }
108
+ const timer = setTimeout(() => prepared.close(), 90000)
109
+ timer.unref()
110
+ clones.add(prepared)
111
+ return prepared
112
+ }),
113
+ cloneStatus: (document, query, member, signal) => work(signal, async signal => {
114
+ if (!hasRole(member, 'owner')) throw new RequestError(403, 'voice-clone-permission-denied')
115
+ if (!validateDocumentVoiceCloneQuery(query)) throw new RequestError(400, 'voice-clone-invalid')
116
+ const loaded = await load(document, member, signal), speech = loaded.speech, engine = query.engine ?? await speech?.defaultSynthesisEngine?.()
117
+ if (!speech?.cloneStatus || !engine || !(await speech.engines()).some(info => info.id === speechEngineId(engine) && info.clone)) throw new RequestError(409, 'voice-clone-unavailable')
118
+ current(document, member, loaded.source); signal.throwIfAborted()
119
+ return speech.cloneStatus(engine, query.voice, signal)
120
+ }),
64
121
  capabilities: (document, member, signal) => work(signal, async signal => {
65
122
  const loaded = await load(document, member, signal)
66
123
  const [engines, defaultEngine] = await Promise.all([loaded.speech?.engines() ?? [], loaded.speech?.defaultSynthesisEngine?.()])
67
124
  signal.throwIfAborted(); current(document, member, loaded.source)
68
125
  const configured = engines.some(engine => engine.tts), unknown = !loaded.speech && loaded.findings?.some(finding => finding.severity === 'error')
69
126
  const implemented = Boolean(loaded.voiceoverExecution)
70
- return { document, source: loaded.source, verification: 'configuration-only', status: configured ? 'configured' : unknown ? 'unknown' : 'unavailable', ...!configured ? { reason: unknown ? 'services-unavailable' : 'not-configured' } as const : {}, voiceover: implemented, preview: implemented, engines, ...defaultEngine ? { defaultEngine } : {}, ...loaded.findings?.length ? { findings: loaded.findings } : {}, actions: { status: implemented, list: true, get: true, start: implemented && configured, cancel: true, quotePreview: implemented, preview: implemented && configured, readPreview: true }, tasks: { idempotency: 'process', limits: ownerOf(document, member).limits } }
127
+ return { document, source: loaded.source, verification: 'configuration-only', status: configured ? 'configured' : unknown ? 'unknown' : 'unavailable', ...!configured ? { reason: unknown ? 'services-unavailable' : 'not-configured' } as const : {}, voiceover: implemented, preview: implemented, engines, ...defaultEngine ? { defaultEngine } : {}, ...loaded.findings?.length ? { findings: loaded.findings } : {}, actions: { status: implemented, list: true, get: true, start: implemented && configured, cancel: true, quotePreview: implemented, preview: implemented && configured, readPreview: true, clone: hasRole(member, 'owner') && Boolean(loaded.speech?.cloneVoice) && engines.some(engine => engine.clone), cloneStatus: hasRole(member, 'owner') && Boolean(loaded.speech?.cloneStatus) && engines.some(engine => engine.clone) }, tasks: { idempotency: 'process', limits: ownerOf(document, member).limits } }
71
128
  }),
72
129
  catalog: (document, query, member, signal) => work(signal, async signal => {
73
130
  if (!validateDocumentVoiceCatalogQuery(query)) throw new RequestError(400, 'voice-catalog-query-invalid')
@@ -111,5 +168,5 @@ export function createDocumentVoiceAuthoring({ editor, services, revision }: Doc
111
168
  },
112
169
  readPreview: async (document, id, member) => ownerOf(document, member).readPreview(id),
113
170
  }
114
- return { service, routes: createVoiceoverRoutes(service), async close() { closed = true; for (const operation of pending) operation.controller.abort(); await Promise.allSettled([...owners.values()].map(owner => owner.close())); await Promise.allSettled([...pending].map(operation => operation.finished)); owners.clear() } }
171
+ return { service, routes: createVoiceoverRoutes(service), async close() { closed = true; for (const prepared of clones) prepared.close(); for (const operation of pending) operation.controller.abort(); await Promise.allSettled([...owners.values()].map(owner => owner.close())); await Promise.allSettled([...pending].map(operation => operation.finished)); owners.clear() } }
115
172
  }
package/src/node/locks.ts CHANGED
@@ -4,6 +4,15 @@ import { RequestError } from './errors.ts'
4
4
 
5
5
  export class DocumentLocks implements DocumentLockService {
6
6
  readonly #held = new Map<string, string>()
7
+ readonly #waiters = new Set<() => void>()
8
+
9
+ async acquire(document: string, holder: string): Promise<() => void> {
10
+ for (;;) {
11
+ const release = this.claim(document, holder)
12
+ if (release) return release
13
+ await new Promise<void>(done => this.#waiters.add(done))
14
+ }
15
+ }
7
16
 
8
17
  claim(document: string, holder: string): (() => void) | undefined {
9
18
  if (this.holder(document) !== undefined) return undefined
@@ -13,6 +22,9 @@ export class DocumentLocks implements DocumentLockService {
13
22
  if (released) return
14
23
  released = true
15
24
  this.#held.delete(document)
25
+ const waiting = [...this.#waiters]
26
+ this.#waiters.clear()
27
+ for (const ready of waiting) ready()
16
28
  }
17
29
  }
18
30
 
@@ -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
+ }
@@ -13,6 +13,7 @@ import type { Revisions } from './revisions.ts'
13
13
  import { DOCUMENT_OPERATION_MAX_BACKUP_BYTES, DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES, documentDirOf } from './writer.ts'
14
14
  import { catchRequestErrors, RequestError } from './errors.ts'
15
15
  import { projectConfiguration, projectDigest, projectMaterial } from './project-files.ts'
16
+ import { listTemplates } from './templates.ts'
16
17
 
17
18
  type Admission = { signature: string, admission: Promise<ProjectPlan> }
18
19
  type Stored = { member: string, origin: ProjectCaller['origin'], signature: string, plan: ProjectPlan, material?: ReturnType<typeof projectMaterial>, canonical?: { change: DocumentChange, planId: string, source: CanonicalSource }, receipt?: ProjectApplied, work?: Promise<ProjectApplied> }
@@ -59,14 +60,28 @@ export function createProjectAuthoring(options: { config: WorkspaceConfig, opera
59
60
  }
60
61
  const key = (request: ProjectPlanRequest, caller: ProjectCaller) => JSON.stringify([caller.member.id, caller.origin, request.id])
61
62
  const service: ProjectAuthoring = {
62
- async capabilities(caller) {
63
+ async capabilities(caller, query = {}) {
63
64
  if (closed) throw new RequestError(503, 'project-owner-closed')
65
+ const offset = query.templatesOffset ?? 0
66
+ if (!Number.isSafeInteger(offset) || offset < 0 || Object.keys(query).some(key => key !== 'templatesOffset')) throw new RequestError(400, 'project-request-invalid')
64
67
  const observed = await observation(), directory = reasons(caller), metadata = reasons(caller, { op: 'retitle', dir: caller.boundDocument ?? '', title: 'capability' })
65
68
  if (!observed.snapshot && !directory.includes('project-git-unavailable')) directory.push('project-head-unavailable')
66
69
  const actions = Object.fromEntries(['create', 'copy', 'rename', 'delete', 'retitle'].map(op => { const unavailable = op === 'retitle' ? metadata : directory; return [op, { available: unavailable.length === 0, reasons: unavailable }] })) as import('@lincyaw/kernel').ProjectCapabilities['actions']
67
70
  const available = Object.values(actions).some(action => action.available)
68
- return bounded({ available, actions, reasons: available ? [] : [...new Set([...directory, ...metadata])], observation: observed, verification: 'configuration-only', rootDirectoryOperations: false,
69
- limits: { requestChars: PROJECT_MAX_REQUEST_CHARS, responseChars: PROJECT_MAX_RESPONSE_CHARS, backupEntries: DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES, backupBytes: DOCUMENT_OPERATION_MAX_BACKUP_BYTES, plans: PROJECT_MAX_PLANS, ttlMs: PROJECT_PLAN_TTL_MS } })
71
+ const answer: import('@lincyaw/kernel').ProjectCapabilities = { available, actions, reasons: available ? [] : [...new Set([...directory, ...metadata])], observation: observed, verification: 'configuration-only', rootDirectoryOperations: false,
72
+ limits: { requestChars: PROJECT_MAX_REQUEST_CHARS, responseChars: PROJECT_MAX_RESPONSE_CHARS, backupEntries: DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES, backupBytes: DOCUMENT_OPERATION_MAX_BACKUP_BYTES, plans: PROJECT_MAX_PLANS, ttlMs: PROJECT_PLAN_TTL_MS } }
73
+ if (caller.boundDocument === undefined) {
74
+ const templates = listTemplates(config)
75
+ if (offset > templates.length) throw new RequestError(400, 'project-request-invalid')
76
+ answer.templates = []
77
+ for (const template of templates.slice(offset, offset + 20)) {
78
+ if (JSON.stringify({ ...answer, templates: [...answer.templates, template], nextTemplatesOffset: offset + answer.templates.length + 1 }).length > PROJECT_MAX_RESPONSE_CHARS) break
79
+ answer.templates.push(template)
80
+ }
81
+ if (!answer.templates.length && offset < templates.length) throw new RequestError(413, 'project-response-too-large')
82
+ if (offset + answer.templates.length < templates.length) answer.nextTemplatesOffset = offset + answer.templates.length
83
+ } else if (offset) throw new RequestError(403, 'project-workspace-scope-required')
84
+ return bounded(answer)
70
85
  },
71
86
  async plan(request, caller) {
72
87
  budget(request)