@lincyaw/workspace 1.0.0-rc.5 → 1.0.0-rc.50

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.5",
3
+ "version": "1.0.0-rc.50",
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": {
@@ -32,13 +32,14 @@
32
32
  "dependencies": {
33
33
  "image-size": "2.0.4",
34
34
  "mime-types": "3.0.2",
35
+ "playwright-chromium": "1.64.1",
35
36
  "yaml": "^2.9.1",
36
- "@lincyaw/compiler": "1.0.0-rc.5",
37
- "@lincyaw/server": "1.0.0-rc.5",
38
- "@lincyaw/kernel": "1.0.0-rc.5"
37
+ "@lincyaw/compiler": "1.0.0-rc.50",
38
+ "@lincyaw/kernel": "1.0.0-rc.50",
39
+ "@lincyaw/server": "1.0.0-rc.50"
39
40
  },
40
41
  "devDependencies": {
41
42
  "@types/mime-types": "^3.0.1",
42
- "@lincyaw/mcp": "1.0.0-rc.5"
43
+ "@lincyaw/mcp": "1.0.0-rc.50"
43
44
  }
44
45
  }
@@ -1,5 +1,5 @@
1
1
  import { randomBytes, randomUUID, createHash } from 'node:crypto'
2
- import { AUTHORING_CLIENT_ACK_MAX_BYTES, AUTHORING_CLIENT_MAX_CLIENTS, AUTHORING_CLIENT_MAX_REQUESTS, AUTHORING_CLIENT_MAX_REQUEST_CHARS, AUTHORING_CLIENT_MAX_RESPONSE_CHARS, AUTHORING_CLIENT_REQUEST_TIMEOUT_MS, authoringClientResultFits, DOCUMENT_ENTRY, fnv1a64, hasRole, isRecord, jsonResponse, problemResponse, pushStream, sseResponse } from '@lincyaw/kernel'
2
+ import { AUTHORING_CLIENT_ACK_MAX_BYTES, AUTHORING_CLIENT_MAX_CLIENTS, AUTHORING_CLIENT_MAX_REQUESTS, AUTHORING_CLIENT_MAX_REQUEST_CHARS, AUTHORING_CLIENT_MAX_RESPONSE_CHARS, AUTHORING_CLIENT_REQUEST_TIMEOUT_MS, authoringClientActionChangesSource, authoringClientActionMutatesDraft, authoringClientActionUsesLocalDraft, authoringClientResultFits, DOCUMENT_ENTRY, fnv1a64, hasRole, isRecord, jsonResponse, problemResponse, pushStream, sseResponse } from '@lincyaw/kernel'
3
3
  import type { AuthoringClientAcknowledgement, AuthoringClientConnection, AuthoringClientDescriptor, AuthoringClientEvent, AuthoringClientLease, AuthoringClientOpen, AuthoringClientReport, AuthoringClientRequest, AuthoringClientRequestResult, AuthoringClients, CanonicalSource, Member, PushStream, Route } from '@lincyaw/kernel'
4
4
  import { validateAuthoringClientAcknowledgement, validateAuthoringClientLease, validateAuthoringClientOpen, validateAuthoringClientQuery, validateAuthoringClientReport, validateAuthoringClientRequest, validateAuthoringClientRequestQuery } from '@lincyaw/kernel/node'
5
5
  import { readAuthoringDocument } from './document-editor.ts'
@@ -7,7 +7,7 @@ import { catchRequestErrors, RequestError } from './errors.ts'
7
7
  import type { SourceEditor } from './source-editor.ts'
8
8
 
9
9
  type Client = { member: string, credential: string, value: AuthoringClientDescriptor, sequence: number, lastSignature?: string, send?(value: AuthoringClientEvent): void, close?(): void }
10
- type Pending = { member: string, signature: string, request: AuthoringClientRequest, value: AuthoringClientRequestResult, timer?: ReturnType<typeof setTimeout> }
10
+ type Pending = { member: string, signature: string, request: AuthoringClientRequest, value: AuthoringClientRequestResult, timer?: ReturnType<typeof setTimeout>, done: Promise<void>, resolve(): void }
11
11
  const sameSource = (a: CanonicalSource, b: CanonicalSource) => a.documentId === b.documentId && a.version === b.version && a.fingerprint === b.fingerprint
12
12
  const size = (value: unknown) => JSON.stringify(value, null, 2).length
13
13
  const budget = (value: unknown, maximum = AUTHORING_CLIENT_MAX_REQUEST_CHARS) => { const text = JSON.stringify(value); if (text === undefined) throw new RequestError(400, 'client-request-invalid'); if (text.length > maximum) throw new RequestError(413, 'client-request-too-large') }
@@ -15,7 +15,8 @@ const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(va
15
15
  const terminal = (pending: Pending) => !['sent', 'executing'].includes(pending.value.state)
16
16
 
17
17
  /** Ephemeral live-client control. It owns no document writer, compilation or durable task ledger. */
18
- export function createAuthoringClients(editor: SourceEditor) {
18
+ export function createAuthoringClients(editor: SourceEditor, options: { reviewRequired?: boolean } = {}) {
19
+ const requiresReview = (type: import('@lincyaw/kernel').AuthoringClientActionType) => options.reviewRequired && authoringClientActionChangesSource(type) && type !== 'source.flush'
19
20
  const clients = new Map<string, Client>(), requests = new Map<string, Pending>()
20
21
  let closed = false
21
22
  const clientKey = (member: string, clientId: string) => JSON.stringify([member, clientId])
@@ -41,6 +42,7 @@ export function createAuthoringClients(editor: SourceEditor) {
41
42
  if (terminal(pending)) return
42
43
  clearTimeout(pending.timer); pending.timer = undefined
43
44
  pending.value = { ...pending.value, state, ...code ? { error: { code } } : {} }
45
+ pending.resolve()
44
46
  if (state === 'expired') clients.get(clientKey(pending.member, pending.request.clientId))?.send?.({ type: 'cancel', requestId: pending.request.requestId, connectionId: pending.request.expectedClientState.connectionId })
45
47
  }
46
48
  const disconnect = (client: Client, connectionId: string) => {
@@ -68,9 +70,15 @@ export function createAuthoringClients(editor: SourceEditor) {
68
70
  if (!validateAuthoringClientQuery(query)) throw new RequestError(400, 'client-query-invalid')
69
71
  const all = [...clients.values()].filter(client => client.member === member.id && client.value.document === document && (!query.clientId || client.value.clientId === query.clientId)
70
72
  && (!query.after || client.value.clientId > query.after)).sort((a, b) => a.value.clientId.localeCompare(b.value.clientId))
71
- const answer = { document, clients: [] as AuthoringClientDescriptor[], unavailable: ['recording', 'new-comment-restore', 'active-comment-discard', 'timing-drafts', 'recording-drafts', 'review', 'open-document'] }
73
+ const answer = { document, clients: [] as AuthoringClientDescriptor[], unavailable: ['new-comment-restore', 'active-comment-discard', 'timing-drafts', 'recording-range-drafts', 'review', 'open-document', ...options.reviewRequired ? ['source-writes-require-review'] : []] }
72
74
  for (const client of all) {
73
75
  const row = structuredClone(client.value)
76
+ row.snapshot.actions = row.snapshot.actions.filter(type => !requiresReview(type))
77
+ const pending = [...requests.values()].find(pending => pending.member === member.id && pending.value.document === document && pending.value.clientId === row.clientId && pending.value.epoch === row.epoch && !terminal(pending))
78
+ if (pending) {
79
+ row.pendingRequest = { requestId: pending.value.requestId, action: pending.value.action, ...pending.value.cancellationRequested ? { cancellationRequested: true } : {} }
80
+ row.snapshot.actions = []
81
+ }
74
82
  if (size({ ...answer, clients: [...answer.clients, row], nextAfter: row.clientId }) > AUTHORING_CLIENT_MAX_RESPONSE_CHARS) break
75
83
  answer.clients.push(row)
76
84
  }
@@ -78,14 +86,15 @@ export function createAuthoringClients(editor: SourceEditor) {
78
86
  return { ...answer, ...answer.clients.length < all.length ? { nextAfter: answer.clients.at(-1)!.clientId } : {} }
79
87
  },
80
88
  async request(document, request, member) {
81
- const actual = current(document, member); budget(request)
89
+ authorize(document, member); budget(request)
82
90
  if (!validateAuthoringClientRequest(request)) throw new RequestError(400, 'client-request-invalid')
91
+ if (requiresReview(request.action.type)) throw new RequestError(409, 'authoring-review-required')
83
92
  const key = requestKey(member.id, document, request), signature = digest(request), known = requests.get(key)
84
- if (known) { if (known.signature !== signature) throw new RequestError(409, 'client-request-id-reused'); return readResult(known, actual) }
93
+ if (known) { if (known.signature !== signature) throw new RequestError(409, 'client-request-id-reused'); return readResult(known, authoringClientActionUsesLocalDraft(request.action.type) ? undefined : current(document, member)) }
85
94
  const client = clients.get(clientKey(member.id, request.clientId)), state = client?.value
86
95
  if (!client || !state?.connected || state.document !== document || state.epoch !== request.epoch) throw new RequestError(409, 'client-unavailable')
87
96
  if (state.connectionId !== request.expectedClientState.connectionId || state.snapshot.revision !== request.expectedClientState.revision) throw new RequestError(409, 'client-state-changed')
88
- if (!sameSource(actual, request.source) || !sameSource(state.snapshot.source, request.source)) throw new RequestError(409, 'client-source-changed')
97
+ if (!authoringClientActionUsesLocalDraft(request.action.type) && !sameSource(current(document, member), request.source) || (request.action.type === 'body-drafts.retry' ? state.snapshot.source.documentId !== request.source.documentId : !sameSource(state.snapshot.source, request.source))) throw new RequestError(409, 'client-source-changed')
89
98
  if (!state.snapshot.actions.includes(request.action.type)) throw new RequestError(409, 'client-action-unavailable')
90
99
  if ([...requests.values()].some(value => !terminal(value) && value.member === member.id && value.request.clientId === request.clientId)) throw new RequestError(409, 'client-busy')
91
100
  while (requests.size >= AUTHORING_CLIENT_MAX_REQUESTS) {
@@ -95,11 +104,13 @@ export function createAuthoringClients(editor: SourceEditor) {
95
104
  }
96
105
  const now = Date.now(), value: AuthoringClientRequestResult = { document, clientId: state.clientId, epoch: state.epoch, connectionId: state.connectionId, requestId: request.requestId, action: request.action.type, source: request.source,
97
106
  state: 'sent', admittedAt: new Date(now).toISOString(), expiresAt: new Date(now + AUTHORING_CLIENT_REQUEST_TIMEOUT_MS).toISOString(), verification: 'not-acknowledged', current: false }
98
- const pending: Pending = { member: member.id, signature, request: structuredClone(request), value }
107
+ let resolve!: () => void
108
+ const done = new Promise<void>(finish => resolve = finish)
109
+ const pending: Pending = { member: member.id, signature, request: structuredClone(request), value, done, resolve }
99
110
  pending.timer = setTimeout(() => finish(pending, 'expired', 'client-request-timeout'), AUTHORING_CLIENT_REQUEST_TIMEOUT_MS)
100
111
  requests.set(key, pending)
101
112
  client.send?.({ type: 'request', request: pending.request, expiresAt: value.expiresAt })
102
- return readResult(pending, actual)
113
+ return readResult(pending, authoringClientActionUsesLocalDraft(request.action.type) ? undefined : current(document, member))
103
114
  },
104
115
  async get(document, query, member) {
105
116
  authorize(document, member); budget(query)
@@ -110,6 +121,21 @@ export function createAuthoringClients(editor: SourceEditor) {
110
121
  try { actual = current(document, member) } catch { /* An old receipt stays readable if the current source is invalid. */ }
111
122
  return readResult(pending, actual)
112
123
  },
124
+ async cancel(document, query, member) {
125
+ if (closed) throw new RequestError(503, 'client-owner-closed')
126
+ if (!hasRole(member, 'editor')) throw new RequestError(403, 'client-permission-denied')
127
+ budget(query)
128
+ if (!validateAuthoringClientRequestQuery(query)) throw new RequestError(400, 'client-request-query-invalid')
129
+ const pending = requests.get(requestKey(member.id, document, query))
130
+ if (!pending) throw new RequestError(404, 'client-request-not-found')
131
+ if (!terminal(pending) && !pending.value.cancellationRequested) {
132
+ pending.value.cancellationRequested = true
133
+ clients.get(clientKey(member.id, query.clientId))?.send?.({ type: 'cancel', requestId: query.requestId, connectionId: pending.value.connectionId })
134
+ }
135
+ let actual: CanonicalSource | undefined
136
+ try { actual = current(document, member) } catch { /* Cancelling the caller's original request does not require a valid new source. */ }
137
+ return readResult(pending, actual)
138
+ },
113
139
  }
114
140
  const register = (document: string, value: AuthoringClientOpen, member: Member): AuthoringClientLease => {
115
141
  const source = current(document, member)
@@ -147,24 +173,33 @@ export function createAuthoringClients(editor: SourceEditor) {
147
173
  if (pending && Date.now() >= Date.parse(pending.value.expiresAt)) finish(pending, 'expired', 'client-request-timeout')
148
174
  if (!pending || terminal(pending) || pending.request.expectedClientState.connectionId !== lease.connectionId) throw new RequestError(409, 'client-request-expired')
149
175
  if (ack.state === 'executing' && pending.value.state !== 'sent' || ack.state === 'done' && pending.value.state !== 'executing') throw new RequestError(409, 'client-ack-state-invalid')
150
- if ((ack.state === 'executing' || ack.state === 'done') && !sameSource(ack.snapshot.source, pending.request.source) && !(ack.state === 'done' && pending.request.action.type === 'source.flush' && ack.snapshot.source.documentId === pending.request.source.documentId)) throw new RequestError(409, 'client-source-changed')
151
- const actual = ack.state === 'executing' || ack.state === 'done' ? current(document, member) : undefined
152
- if (ack.state === 'executing' && (ack.snapshot.revision !== pending.request.expectedClientState.revision || !actual || !sameSource(actual, pending.request.source))) throw new RequestError(409, 'client-state-changed')
153
- if (ack.state === 'done' && (!actual || !sameSource(actual, ack.snapshot.source))) throw new RequestError(409, 'client-source-changed')
176
+ if ((ack.state === 'executing' || ack.state === 'done') && !sameSource(ack.snapshot.source, pending.request.source) && !(ack.state === 'executing' && pending.request.action.type === 'body-drafts.retry' && ack.snapshot.source.documentId === pending.request.source.documentId) && !(ack.state === 'done' && (authoringClientActionChangesSource(pending.request.action.type) || authoringClientActionUsesLocalDraft(pending.request.action.type)) && ack.snapshot.source.documentId === pending.request.source.documentId)) throw new RequestError(409, 'client-source-changed')
177
+ const localDraft = authoringClientActionUsesLocalDraft(pending.request.action.type)
178
+ const actual = !localDraft && (ack.state === 'executing' || ack.state === 'done') ? current(document, member) : undefined
179
+ if (ack.state === 'executing' && (ack.snapshot.revision !== pending.request.expectedClientState.revision || !localDraft && (!actual || !sameSource(actual, pending.request.source)))) throw new RequestError(409, 'client-state-changed')
180
+ if (ack.state === 'done' && !localDraft && (!actual || !sameSource(actual, ack.snapshot.source))) throw new RequestError(409, 'client-source-changed')
154
181
  const action = pending.request.action
155
- const family = action.type.startsWith('comment-drafts.') ? 'comment' : action.type.startsWith('component-drafts.') ? 'component' : undefined
182
+ const family = action.type.startsWith('body-drafts.') ? 'body' : action.type.startsWith('comment-drafts.') ? 'comment' : action.type.startsWith('component-drafts.') ? 'component' : undefined
156
183
  if (ack.result && (!family || ack.state !== 'done' || ack.result.type !== action.type || ack.result.family !== family)) throw new RequestError(400, 'client-result-invalid')
157
184
  if (family && ack.state === 'done') {
158
185
  const result = ack.result
159
- const mutation = action.type === 'component-drafts.restore' || action.type === 'component-drafts.discard' || action.type === 'comment-drafts.restore' || action.type === 'comment-drafts.discard'
186
+ const mutation = authoringClientActionMutatesDraft(action.type)
160
187
  if (!result || (mutation ? ack.snapshot.revision <= pending.request.expectedClientState.revision : ack.snapshot.revision !== pending.request.expectedClientState.revision)) throw new RequestError(409, `client-${family}-drafts-changed`)
161
188
  if (!authoringClientResultFits({ request: pending.request, connection: client.value, document, snapshot: ack.snapshot }, result)) throw new RequestError(413, `client-${family}-result-too-large`)
189
+ if (action.type === 'body-drafts.read' && (result.type !== action.type || result.draft !== action.draft
190
+ || result.offset !== action.offset || result.endOffset !== result.offset + result.jsonText.length || result.endOffset > result.totalUtf16
191
+ || result.jsonText.length > (action.maxChars ?? 2048))) throw new RequestError(400, 'client-result-invalid')
162
192
  if ((action.type === 'comment-drafts.read' || action.type === 'component-drafts.read') && (result.type !== action.type || result.draft.id !== action.draft.id || result.draft.revision !== action.draft.revision || result.draft.token !== action.draft.token
163
193
  || action.type === 'component-drafts.read' && (result.type !== action.type || result.draft.blockId !== action.draft.blockId || result.draft.stepId !== action.draft.stepId)
164
194
  || result.offset !== action.offset || result.endOffset !== result.offset + result.jsonText.length || result.endOffset > result.totalUtf16
165
195
  || result.jsonText.length > (action.maxChars ?? 2048))) throw new RequestError(400, 'client-result-invalid')
166
- if ((action.type === 'comment-drafts.inspect' || action.type === 'component-drafts.inspect') && (result.type !== action.type || result.drafts.length > (action.limit ?? 10)
196
+ if ((action.type === 'comment-drafts.inspect' || action.type === 'component-drafts.inspect' || action.type === 'body-drafts.inspect') && (result.type !== action.type || result.drafts.length > (action.limit ?? 10)
167
197
  || action.cursor && action.cursor.token !== result.token || result.next && result.next.token !== result.token)) throw new RequestError(400, 'client-result-invalid')
198
+ if (action.type === 'body-drafts.restore' || action.type === 'body-drafts.discard' || action.type === 'body-drafts.retry') {
199
+ if (result.type !== action.type || !('outcome' in result) || result.draft !== action.draft
200
+ || (action.type === 'body-drafts.restore' ? !['restored', 'already-saved'].includes(result.outcome)
201
+ : action.type === 'body-drafts.discard' ? !['source-restored', 'backup-discarded'].includes(result.outcome) : result.outcome !== 'saved')) throw new RequestError(400, 'client-result-invalid')
202
+ }
168
203
  const sameComment = (a: import('@lincyaw/kernel').ClientCommentDraftReference | null, b: import('@lincyaw/kernel').ClientCommentDraftReference | null) => a === null || b === null ? a === b
169
204
  : a.id === b.id && a.revision === b.revision && a.token === b.token
170
205
  if (action.type === 'comment-drafts.restore' && (result.type !== action.type || !sameComment(result.draft, action.draft) || result.composerId !== action.composerId
@@ -194,7 +229,23 @@ export function createAuthoringClients(editor: SourceEditor) {
194
229
  if (!validateAuthoringClientReport(value.report)) throw new RequestError(400, 'client-report-invalid')
195
230
  report(connection(ctx.document, value.connection, ctx.member), value.report, digest(value.report)); return jsonResponse({ accepted: true })
196
231
  }) })
197
- return { service, routes: {
232
+ return { service,
233
+ async flush(documents: string[], member: Member): Promise<void> {
234
+ const active = [...clients.values()].filter(client => client.member === member.id && client.value.connected && documents.includes(client.value.document))
235
+ await Promise.all(active.map(async client => {
236
+ const state = client.value
237
+ if (!state.snapshot.actions.includes('source.flush')) {
238
+ if (state.snapshot.editing.dirty || state.snapshot.editing.saving || state.snapshot.editing.composing || state.snapshot.editing.conflicted) throw new RequestError(409, 'agent-author-editing', { next: 'The author has unconfirmed input. Read the current author files and retry after that input is saved. Nothing was published.' })
239
+ return
240
+ }
241
+ const request: AuthoringClientRequest = { clientId: state.clientId, epoch: state.epoch, requestId: randomUUID(), source: state.snapshot.source,
242
+ expectedClientState: { connectionId: state.connectionId, revision: state.snapshot.revision }, action: { type: 'source.flush' } }
243
+ await service.request(state.document, request, member)
244
+ const pending = requests.get(requestKey(member.id, state.document, request))!
245
+ await pending.done
246
+ if (pending.value.state !== 'done') throw new RequestError(409, 'agent-author-editing', { next: 'The author client could not confirm its saved input. Read the current author files and retry. Nothing was published.' })
247
+ }))
248
+ }, routes: {
198
249
  'authoring-clients/register': post('register'), 'authoring-clients/report': post('report'), 'authoring-clients/ack': post('ack'),
199
250
  'authoring-clients/events': { role: 'editor', handle: (request, ctx) => catchRequestErrors(async () => {
200
251
  if (request.method !== 'GET') return problemResponse(405, 'GET')
@@ -202,5 +253,5 @@ export function createAuthoringClients(editor: SourceEditor) {
202
253
  if (!validateAuthoringClientLease(lease)) throw new RequestError(400, 'client-connection-invalid')
203
254
  return sseResponse(open(ctx.document, lease, ctx.member, request.signal), request.signal)
204
255
  }) } satisfies Route,
205
- }, async close() { closed = true; for (const client of clients.values()) client.close?.(); for (const pending of requests.values()) clearTimeout(pending.timer); requests.clear(); clients.clear() } }
256
+ }, async close() { closed = true; for (const client of clients.values()) client.close?.(); for (const pending of requests.values()) finish(pending, 'expired', 'client-owner-closed'); requests.clear(); clients.clear() } }
206
257
  }
package/src/node/build.ts CHANGED
@@ -1,9 +1,10 @@
1
- import { cpSync, existsSync, rmSync } from 'node:fs'
2
- import { join, resolve } from 'node:path'
3
- import { build, Compiler } from '@lincyaw/compiler'
1
+ import { cpSync, existsSync, readdirSync, rmSync } from 'node:fs'
2
+ import { isAbsolute, join, resolve } from 'node:path'
3
+ import { build, Compiler, WORKSPACE_CONFIG } from '@lincyaw/compiler'
4
4
  import type { Compilation, RunStats } from '@lincyaw/compiler'
5
- import { errorMessage, isRecord } from '@lincyaw/kernel'
6
- import type { Finding } from '@lincyaw/kernel'
5
+ import { APP_DIR, errorMessage, isRecord, SLIDES_DIR } from '@lincyaw/kernel'
6
+ import type { Finding, IRDocument, SiteSpec } from '@lincyaw/kernel'
7
+ import { relativePath } from '../domain/paths.ts'
7
8
  import { listDocuments, readWorkspaceConfig } from './config.ts'
8
9
  import { siteContext, siteDocument, siteIR, siteSpec, siteTranslations, webRenderer } from './site.ts'
9
10
 
@@ -21,9 +22,11 @@ export async function buildWorkspace(root: string, options: { outDir?: string, b
21
22
  const site = siteSpec(config, [])
22
23
  const base = siteBase(config.site.base)
23
24
  const forms: { dir: string, compilation: Compilation, to: string[] }[] = []
25
+ const compilations: Compilation[] = []
24
26
  for (const document of found) {
25
27
  const compilation = await new Compiler(join(config.root, document.entry), { bundled: options.bundled, settings: config.settings }).compile({ pruneCache: true })
26
- const to = presentations(compilation, `${base}${document.dir.split('/').map(encodeURIComponent).join('/')}/`)
28
+ compilations.push(compilation)
29
+ const to = presentations(compilation, base, `${base}${urlPath(document.dir)}/`, siteLook(config.site, config.root, document.dir))
27
30
  if (to.length > 0) forms.push({ dir: document.dir, compilation, to })
28
31
  const translated = await siteTranslations(compilation)
29
32
  findings.push(...compilation.doc.diagnostics, ...translated.findings)
@@ -33,6 +36,7 @@ export async function buildWorkspace(root: string, options: { outDir?: string, b
33
36
  const outDir = join(resolve(options.outDir ?? join(config.root, 'dist')), 'web')
34
37
  const renderer = await webRenderer(config.root, options.bundled)
35
38
  const ctx = siteContext({ root: config.root, outDir, workDir: join(config.root, '.presmium', 'site'), base, findings })
39
+ ctx.pluginDirs = pluginsByName(site, compilations)
36
40
  try {
37
41
  await renderer.buildSite!(site, ctx)
38
42
  } catch (error) {
@@ -47,6 +51,7 @@ export async function buildWorkspace(root: string, options: { outDir?: string, b
47
51
  const report = await build(compilation, { outDir: work, to })
48
52
  findings.push(...report.findings)
49
53
  for (const form of to) if (existsSync(join(work, form))) cpSync(join(work, form), join(outDir, dir, form), { recursive: true })
54
+ if (to.includes('slides')) moveApps(join(outDir, dir, SLIDES_DIR), outDir)
50
55
  } catch (error) {
51
56
  findings.push({ checkId: 'presmium.render', severity: 'error', message: `document ${dir}: its ${to.join(' and ')} failed: ${errorMessage(error)}` })
52
57
  }
@@ -54,20 +59,67 @@ export async function buildWorkspace(root: string, options: { outDir?: string, b
54
59
  return { outDir, documents, findings }
55
60
  }
56
61
 
62
+ /**
63
+ * The site's documents name their plugins by package, as a presentation built alone does, so the pages and the
64
+ * presentations share one viewer app (its key follows the plugin names); the site resolves each name to the directory
65
+ * it was loaded from. A name that two documents load from different directories stays a directory, to tell them apart.
66
+ */
67
+ function pluginsByName(site: SiteSpec, compilations: readonly Compilation[]): Record<string, string> {
68
+ const dirs = new Map<string, Set<string>>(), names = new Map<string, string>()
69
+ for (const { plugins } of compilations) for (const { name, dir } of plugins) {
70
+ let own = dirs.get(name)
71
+ if (!own) dirs.set(name, own = new Set())
72
+ own.add(dir)
73
+ names.set(dir, name)
74
+ }
75
+ const unique = new Map([...dirs].filter(([, own]) => own.size === 1).map(([name, own]) => [name, [...own][0]!]))
76
+ const byName = (doc: IRDocument): IRDocument => ({ ...doc, config: { ...doc.config, plugins: doc.config.plugins.map(dir => names.has(dir) && unique.has(names.get(dir)!) ? names.get(dir)! : dir) } })
77
+ for (const entry of site.documents) {
78
+ if (entry.doc) entry.doc = byName(entry.doc)
79
+ for (const translation of entry.translations ?? []) translation.doc = byName(translation.doc)
80
+ }
81
+ return Object.fromEntries(unique)
82
+ }
83
+
57
84
  const PRESENTATIONS = ['slides', 'lecture']
58
85
 
86
+ /**
87
+ * The site's theme and its parameters, for the presentations of the document in `dir` to look like its pages: a theme
88
+ * directory made absolute, and the parameters with the file they are written in (`siteFile`, relative to the document),
89
+ * for their paths (`logo`) to resolve against it.
90
+ */
91
+ function siteLook(site: Record<string, unknown>, root: string, dir: string): Record<string, unknown> {
92
+ const theme = typeof site.theme === 'string' && (site.theme.startsWith('.') || isAbsolute(site.theme)) ? resolve(root, site.theme) : site.theme
93
+ return { ...theme !== undefined ? { theme } : {}, ...isRecord(site.params) ? { params: site.params, siteFile: relativePath(dir, WORKSPACE_CONFIG) } : {} }
94
+ }
95
+
96
+ const urlPath = (dir: string) => dir.split('/').map(encodeURIComponent).join('/')
97
+
98
+ /** The presentation's viewer app goes where its page names it (`appBase`): with the site's own, downloaded once for all. */
99
+ function moveApps(presentation: string, outDir: string): void {
100
+ const apps = join(presentation, APP_DIR)
101
+ if (!existsSync(apps)) return
102
+ for (const key of readdirSync(apps)) if (!existsSync(join(outDir, APP_DIR, key))) cpSync(join(apps, key), join(outDir, APP_DIR, key), { recursive: true })
103
+ rmSync(apps, { recursive: true, force: true })
104
+ }
105
+
59
106
  /**
60
107
  * The presentation forms a document asks for (`metadata.renderers.slides` or `lecture`), set to be served below its
61
- * pages at `prefix`: the slides at `slides/`, and the web pages and the slides linked to each other.
108
+ * pages at `prefix`, with its viewer app below the site's `base`: the slides at `slides/`, and the web pages and the slides linked to each other.
62
109
  */
63
- function presentations(compilation: Compilation, prefix: string): string[] {
110
+ function presentations(compilation: Compilation, base: string, prefix: string, look: Record<string, unknown>): string[] {
64
111
  const { renderers } = compilation.doc.config
65
112
  const to = PRESENTATIONS.filter(form => renderers[form] !== undefined)
66
113
  if (to.length === 0) return to
67
- if (to.includes('slides')) renderers.slides = { ...isRecord(renderers.slides) ? renderers.slides : {}, base: `${prefix}slides/` }
114
+ if (to.includes('slides')) {
115
+ const own = isRecord(renderers.slides) ? renderers.slides : {}
116
+ // Parameters the document sets for its slides are written in its lecture.json, not in the workspace's file.
117
+ const { siteFile, ...shared } = look
118
+ renderers.slides = { ...shared, ...own.params === undefined && siteFile !== undefined ? { siteFile } : {}, ...own, base: `${prefix}${SLIDES_DIR}/`, appBase: base }
119
+ }
68
120
  const settings = compilation.doc.config.presmium ??= {}
69
121
  const web = isRecord(settings['presmium.web']) ? settings['presmium.web'] : {}
70
- settings['presmium.web'] = { ...web, webUrl: prefix, ...to.includes('slides') ? { slidesUrl: `${prefix}slides/` } : {} }
122
+ settings['presmium.web'] = { ...web, webUrl: prefix, ...to.includes('slides') ? { slidesUrl: `${prefix}${SLIDES_DIR}/` } : {} }
71
123
  // The slides find the lecture where it is built, without probing `slides/lecture/` first.
72
124
  if (to.includes('lecture')) {
73
125
  const lecture = isRecord(settings['presmium.lecture']) ? settings['presmium.lecture'] : {}