@lincyaw/workspace 1.0.0-rc.117 → 1.0.0-rc.119

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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Presmium's workspace: the site of several documents (`presmium build` at a workspace root) and the local workbench `presmium serve`, with the document templates.
4
4
 
5
- Part of [Presmium](https://github.com/Lincyaw/presmium), which compiles canonical lecture.json teaching documents into web pages, slides, Jupyter notebooks and narrated playback.
5
+ Part of [Presmium](https://github.com/Lincyaw/presmium), which compiles canonical index.pmd teaching documents into web pages, slides, Jupyter notebooks and narrated playback.
6
6
 
7
7
  ## Install
8
8
 
@@ -10,11 +10,11 @@ It comes with `@lincyaw/cli`.
10
10
 
11
11
  ## Workspaces
12
12
 
13
- A workspace has `presmium.workspace.yaml` at its root and each document in a subdirectory with its own `lecture.json`:
13
+ A workspace has `presmium.workspace.yaml` at its root; every `index.pmd` below it is a document, placed in the document tree by its own `placement` (the file lists no documents):
14
14
 
15
15
  ```yaml
16
16
  title: Introduction to machine learning
17
- documents: [week1/lecture.json, week2/lecture.json]
17
+ defaults: { lang: en } # settings every document inherits unless it sets its own
18
18
  site:
19
19
  nav:
20
20
  - { text: Week 1, link: /week1/ }
@@ -28,7 +28,7 @@ site:
28
28
 
29
29
  ## Documentation
30
30
 
31
- - [Author guide](https://github.com/Lincyaw/presmium/blob/main/site/guide/locales/en/lecture.json): workspaces
31
+ - [Author guide](https://github.com/Lincyaw/presmium/blob/main/site/guide/locales/en/index.pmd): workspaces
32
32
  - [Security and the trust model](https://github.com/Lincyaw/presmium/blob/main/SECURITY.md)
33
33
 
34
34
  ## License
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workspace",
3
- "version": "1.0.0-rc.117",
3
+ "version": "1.0.0-rc.119",
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,13 +34,13 @@
34
34
  "mime-types": "3.0.2",
35
35
  "playwright-chromium": "1.64.1",
36
36
  "yaml": "^2.9.1",
37
- "@lincyaw/server": "1.0.0-rc.117",
38
- "@lincyaw/kernel": "1.0.0-rc.117",
39
- "@lincyaw/design": "1.0.0-rc.117",
40
- "@lincyaw/compiler": "1.0.0-rc.117"
37
+ "@lincyaw/kernel": "1.0.0-rc.119",
38
+ "@lincyaw/compiler": "1.0.0-rc.119",
39
+ "@lincyaw/design": "1.0.0-rc.119",
40
+ "@lincyaw/server": "1.0.0-rc.119"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@types/mime-types": "^3.0.1",
44
- "@lincyaw/mcp": "1.0.0-rc.117"
44
+ "@lincyaw/mcp": "1.0.0-rc.119"
45
45
  }
46
46
  }
@@ -46,21 +46,6 @@ export function invalidDocumentDir(dir: string): string | undefined {
46
46
  return undefined
47
47
  }
48
48
 
49
- function segmentPattern(segment: string): RegExp {
50
- const escaped = segment.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*').replace(/\?/g, '[^/]')
51
- return new RegExp(`^${escaped}$`)
52
- }
53
-
54
- export function matchesPattern(pattern: string, path: string): boolean {
55
- const want = pattern.replace(/^\.\//, '').split('/')
56
- const have = path.split('/')
57
- return want.length === have.length && want.every((segment, i) => segmentPattern(segment).test(have[i]!))
58
- }
59
-
60
- export function patternSegments(pattern: string): (string | RegExp)[] {
61
- return pattern.replace(/^\.\//, '').split('/').map(segment => (/[*?]/.test(segment) ? segmentPattern(segment) : segment))
62
- }
63
-
64
49
  const NOT_RELATIVE = /^(?:[a-z][a-z\d+.-]*:|\/|#|\?)/i
65
50
 
66
51
  export function movedUrl(url: string, file: string, was: string, from: string, to: string): string | undefined {
package/src/node/build.ts CHANGED
@@ -113,7 +113,7 @@ function presentations(compilation: Compilation, base: string, prefix: string, l
113
113
  if (to.length === 0) return to
114
114
  if (to.includes('slides')) {
115
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.
116
+ // Parameters the document sets for its slides are written in its index.pmd, not in the workspace's file.
117
117
  const { siteFile, ...shared } = look
118
118
  renderers.slides = { ...shared, ...own.params === undefined && siteFile !== undefined ? { siteFile } : {}, ...own, base: `${prefix}${SLIDES_DIR}/`, appBase: base }
119
119
  }
@@ -309,7 +309,7 @@ const escapeHtml = (text: string) => text.replace(/[&<>"]/g, char => `&#${char.c
309
309
 
310
310
  /** A sheet of thumbnails with their labels: plain HTML for the capturing browser, not a page of the product. */
311
311
  function sheetHtml(cells: { label: string, png: Buffer }[], columns: number, appearance: 'light' | 'dark'): string {
312
- const [paper, ink, line] = appearance === 'dark' ? ['#161614', '#ece9e2', '#3a3833'] : ['#f7f5f0', '#1c1b19', '#e3ded3']
312
+ const [paper, ink, line] = appearance === 'dark' ? ['#16171a', '#e8eaed', '#2e3136'] : ['#ffffff', '#1f2329', '#e3e5e9']
313
313
  return `<!doctype html><meta charset="utf-8"><style>
314
314
  body { margin: 0; padding: ${SHEET_GAP}px; background: ${paper}; color: ${ink}; font: 13px/1.4 system-ui, sans-serif; }
315
315
  main { display: grid; grid-template-columns: repeat(${columns}, ${THUMB_WIDTH}px); gap: ${SHEET_GAP}px; }
@@ -1,28 +1,29 @@
1
- import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs'
1
+ import { existsSync, readFileSync, realpathSync } from 'node:fs'
2
2
  import { join, resolve } from 'node:path'
3
- import { WORKSPACE_CONFIG } from '@lincyaw/compiler'
3
+ import { effectiveDocumentIn, inheritedSettingsIn, WORKSPACE_CONFIG, workspaceDefaults, workspaceDocuments } from '@lincyaw/compiler'
4
4
  import type { OperatorSettings } from '@lincyaw/compiler'
5
5
  import { APPROVAL_KINDS, DOCUMENT_ENTRY, errorMessage, isRecord } from '@lincyaw/kernel'
6
- import type { ApprovalKind, DocumentSummary } from '@lincyaw/kernel'
6
+ import type { ApprovalKind, DocumentDefaults, DocumentSummary, EffectiveDocument, PresmiumDocument } from '@lincyaw/kernel'
7
7
  import type { ApprovalPolicy } from '@lincyaw/server'
8
8
  import { parse as parseYaml } from 'yaml'
9
- import { matchesPattern, patternSegments } from '../domain/paths.ts'
10
9
 
11
- export const DEFAULT_DOCUMENTS = [`*/${DOCUMENT_ENTRY}`]
12
-
13
- const SKIPPED = new Set(['node_modules', '.git', '.presmium', 'dist'])
10
+ const SKIPPED = new Set(['node_modules', '.git', '.presmium', 'dist', '.trash'])
14
11
 
15
12
  const POLICIES = new Set<ApprovalPolicy>(['off', 'ask', 'allow'])
16
13
 
17
14
  export interface WorkspaceConfig {
18
15
  root: string
19
16
  title: string
20
- documents: string[]
17
+ /** A folder whose own entry file is the only document. */
21
18
  singleDeck: boolean
22
19
  site: Record<string, unknown>
23
20
  approvals: Partial<Record<ApprovalKind, ApprovalPolicy>>
24
21
  templates?: string
25
22
  settings: OperatorSettings
23
+ /** The root of the documents' inherited settings. */
24
+ defaults: DocumentDefaults
25
+ /** The workspace file still lists `documents:`; `presmium migrate` or Studio's Upgrade removes it. */
26
+ needsMigration: boolean
26
27
  }
27
28
 
28
29
  function strings(value: unknown): string[] {
@@ -41,23 +42,23 @@ export function readWorkspaceConfig(root: string): WorkspaceConfig {
41
42
  throw new Error(`${file}: ${errorMessage(error)}`)
42
43
  }
43
44
  }
44
- const declared = strings(data.documents)
45
- const singleDeck = declared.length === 0 && existsSync(join(dir, DOCUMENT_ENTRY))
45
+ const singleDeck = existsSync(join(dir, DOCUMENT_ENTRY))
46
46
  const approvals = isRecord(data.approvals) ? data.approvals : {}
47
47
  const settings = isRecord(data.settings) ? data.settings : {}
48
48
  const renderers = isRecord(data.renderers) ? data.renderers : {}
49
49
  for (const [path, value] of [['renderers.lecture', renderers.lecture], ['settings.presmium.lecture', settings['presmium.lecture']]] as const) {
50
- if (isRecord(value) && Object.hasOwn(value, 'script')) throw new Error(`${file}: ${path}.script: External lecture scripts are not supported. Author narration in each document's lecture.json narrations.`)
50
+ if (isRecord(value) && Object.hasOwn(value, 'script')) throw new Error(`${file}: ${path}.script: External lecture scripts are not supported. Author narration in each document's narrations.`)
51
51
  }
52
52
  return {
53
53
  root: dir,
54
54
  title: typeof data.title === 'string' && data.title.trim() ? data.title.trim() : dir.split('/').at(-1) ?? 'Presmium',
55
- documents: singleDeck ? [DOCUMENT_ENTRY] : declared.length > 0 ? declared : DEFAULT_DOCUMENTS,
56
55
  singleDeck,
57
56
  site: isRecord(data.site) ? data.site : {},
58
57
  approvals: Object.fromEntries(APPROVAL_KINDS.flatMap(kind => (POLICIES.has(approvals[kind] as ApprovalPolicy) ? [[kind, approvals[kind] as ApprovalPolicy]] : []))),
59
58
  ...typeof data.templates === 'string' && data.templates.trim() ? { templates: resolve(dir, data.templates.trim()) } : {},
60
59
  settings: Object.fromEntries(Object.entries(settings).map(([id, value]) => [id, isRecord(value) ? value : {}])),
60
+ defaults: workspaceDefaults(data.defaults),
61
+ needsMigration: data.documents !== undefined,
61
62
  }
62
63
  }
63
64
 
@@ -70,34 +71,6 @@ export function isWorkspaceRoot(dir: string): boolean {
70
71
  }
71
72
  }
72
73
 
73
- function entries(config: WorkspaceConfig): string[] {
74
- const found: string[] = []
75
- for (const pattern of config.documents) {
76
- const parts = patternSegments(pattern)
77
- const walk = (dir: string, rel: string, i: number): string[] => {
78
- const part = parts[i]!
79
- const last = i === parts.length - 1
80
- const names = typeof part === 'string'
81
- ? [part]
82
- : (() => {
83
- try {
84
- return readdirSync(dir).filter(name => !SKIPPED.has(name) && !name.startsWith('.') && part.test(name)).sort()
85
- } catch {
86
- return []
87
- }
88
- })()
89
- return names.flatMap((name) => {
90
- const path = join(dir, name)
91
- const next = rel ? `${rel}/${name}` : name
92
- if (last) return name === DOCUMENT_ENTRY && existsSync(path) && statSync(path).isFile() ? [next] : []
93
- return existsSync(path) && statSync(path).isDirectory() ? walk(path, next, i + 1) : []
94
- })
95
- }
96
- for (const entry of walk(config.root, '', 0)) if (!found.includes(entry)) found.push(entry)
97
- }
98
- return found
99
- }
100
-
101
74
  export interface DocumentEntry {
102
75
  dir: string
103
76
  entry: string
@@ -105,16 +78,39 @@ export interface DocumentEntry {
105
78
 
106
79
  export interface FoundDocument extends DocumentSummary, DocumentEntry {}
107
80
 
108
- /** The configured documents that exist on disk, without reading their content. */
81
+ const entryOf = (path: string): DocumentEntry => ({ dir: path.split('/').slice(0, -1).join('/'), entry: path })
82
+
83
+ /**
84
+ * The documents on disk, without validating them: in a workspace every entry file found by the scan, in tree order
85
+ * (depth first, siblings by rank); entries the tree leaves out (a second document with a taken ID) follow by path.
86
+ */
109
87
  export function listDocumentEntries(config: WorkspaceConfig): DocumentEntry[] {
110
- return entries(config).map(entry => ({ dir: entry.split('/').slice(0, -1).join('/'), entry }))
88
+ if (config.singleDeck) return [{ dir: '', entry: DOCUMENT_ENTRY }]
89
+ const { documents, tree } = workspaceDocuments(config.root)
90
+ const ordered = tree.order.map(node => node.path)
91
+ const listed = new Set(ordered)
92
+ return [...ordered, ...documents.map(document => document.path).filter(path => !listed.has(path))].map(entryOf)
93
+ }
94
+
95
+ /** The tree position of every listed document, by folder. */
96
+ export function documentPlaces(config: WorkspaceConfig): Map<string, { id: string, parent: string | null, depth: number, schemaVersion: unknown }> {
97
+ if (config.singleDeck) return new Map()
98
+ const { documents, tree } = workspaceDocuments(config.root)
99
+ const versions = new Map(documents.map(document => [document.path, document.schemaVersion]))
100
+ return new Map(tree.order.map(node => [entryOf(node.path).dir, { id: node.id, parent: node.parent, depth: node.depth, schemaVersion: versions.get(node.path) }]))
101
+ }
102
+
103
+ /** The metadata a document decides with (its language, plugins, renderers), inherited settings filled in. */
104
+ function effectiveMetadata(config: WorkspaceConfig, entry: string, parsed: unknown): Record<string, unknown> {
105
+ if (!isRecord(parsed) || !isRecord(parsed.metadata)) return {}
106
+ if (!isRecord(parsed.production) || !isRecord(parsed.placement)) return parsed.metadata
107
+ return effectiveDocumentIn(config.root, join(config.root, entry), parsed as unknown as PresmiumDocument).metadata as unknown as Record<string, unknown>
111
108
  }
112
109
 
113
110
  export function readDocumentSummary(config: WorkspaceConfig, { dir, entry }: DocumentEntry): FoundDocument {
114
111
  let headmatter: Record<string, unknown> = {}
115
112
  try {
116
- const parsed: unknown = JSON.parse(readFileSync(join(config.root, entry), 'utf8'))
117
- headmatter = isRecord(parsed) && isRecord(parsed.metadata) ? parsed.metadata : {}
113
+ headmatter = effectiveMetadata(config, entry, JSON.parse(readFileSync(join(config.root, entry), 'utf8')))
118
114
  } catch {
119
115
  }
120
116
  const tags = strings(headmatter.tags)
@@ -134,9 +130,26 @@ export function listDocuments(config: WorkspaceConfig): FoundDocument[] {
134
130
  }
135
131
 
136
132
  export function documentSummaries(config: WorkspaceConfig): DocumentSummary[] {
137
- return listDocuments(config).map(({ entry: _entry, ...document }) => document)
133
+ const places = documentPlaces(config)
134
+ return listDocuments(config).map(({ entry: _entry, ...document }) => {
135
+ const place = places.get(document.dir)
136
+ return place ? { ...document, id: place.id, parent: place.parent, depth: place.depth } : document
137
+ })
138
138
  }
139
139
 
140
+ /** Whether a document may live in this folder: in a workspace any folder outside the skipped ones and translations. */
140
141
  export function isDocumentDir(config: WorkspaceConfig, dir: string): boolean {
141
- return config.documents.some(pattern => matchesPattern(pattern, dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY))
142
+ if (config.singleDeck) return dir === ''
143
+ const parts = dir.split('/')
144
+ return dir !== '' && !parts.some(part => part === '' || part.startsWith('.') || SKIPPED.has(part)) && !parts.some((part, index) => part === 'locales' && index === parts.length - 2)
145
+ }
146
+
147
+ /** The document in `dir` with the settings it inherits from its ancestors and the workspace defaults; never saved. */
148
+ export function effectiveContent(config: WorkspaceConfig, dir: string, content: PresmiumDocument): EffectiveDocument {
149
+ return effectiveDocumentIn(config.root, join(config.root, dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY), content)
150
+ }
151
+
152
+ /** What the document in `dir` inherits from its ancestors and the workspace defaults, without its own settings. */
153
+ export function inheritedContent(config: WorkspaceConfig, dir: string, content: PresmiumDocument): DocumentDefaults {
154
+ return inheritedSettingsIn(config.root, join(config.root, dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY), content)
142
155
  }
@@ -2,11 +2,11 @@ import { createReadStream, realpathSync } from 'node:fs'
2
2
  import { basename, isAbsolute, relative, resolve, sep } from 'node:path'
3
3
  import { Readable } from 'node:stream'
4
4
  import { lookup } from 'mime-types'
5
- import type { TeachingDocument } from '@lincyaw/kernel'
5
+ import type { PresmiumDocument } from '@lincyaw/kernel'
6
6
  import { RequestError } from './errors.ts'
7
7
 
8
8
  /** Read only a file registered by the current canonical document, without compiling it. */
9
- export function documentAssetResponse(root: string, directory: string, document: TeachingDocument, id: string, readableFile: (path: string) => string, signal?: AbortSignal): Response {
9
+ export function documentAssetResponse(root: string, directory: string, document: PresmiumDocument, id: string, readableFile: (path: string) => string, signal?: AbortSignal): Response {
10
10
  const asset = document.assets[id]
11
11
  if (!asset) throw new RequestError(404, 'document-asset-missing')
12
12
  if (!asset.location || /^(?:[a-z][a-z\d+.-]*:|\/)/i.test(asset.location)) throw new RequestError(400, 'document-asset-not-local')
@@ -3,7 +3,7 @@ import { constants } from 'node:fs'
3
3
  import { lstat, open } from 'node:fs/promises'
4
4
  import { basename, join, relative } from 'node:path'
5
5
  import { ASSET_TITLE_MAX_LENGTH, DOCUMENT_AUDIO_MAX_BYTES, DOCUMENT_AUDIO_REQUEST_MAX_BYTES, fnv1a64, hasRole, isRecord, jsonResponse, ProductionAudioRefusal, recordingSourceRange, recordingStepIssue, validateDocument } from '@lincyaw/kernel'
6
- import type { Asset, CanonicalSource, DocumentRecordingAdoption, VerifiedDocumentRecordingAdoption, DocumentAudioAuthoring, DocumentAudioCapabilities, DocumentAudioImport, DocumentAudioInspectionAnswer, DocumentChangeAnswer, DocumentMediaClipEdit, DocumentMediaClipValidation, DocumentMediaClipValidationAnswer, DocumentWorkspaceAudioImport, Finding, Member, ProductionAudioAuthoring, RequestContext, Route, TeachingDocument, VerifiedDocumentAudioImport, VerifiedDocumentMediaClipChange, WorkspaceAudioInspectionAnswer } from '@lincyaw/kernel'
6
+ import type { Asset, CanonicalSource, DocumentRecordingAdoption, VerifiedDocumentRecordingAdoption, DocumentAudioAuthoring, DocumentAudioCapabilities, DocumentAudioImport, DocumentAudioInspectionAnswer, DocumentChangeAnswer, DocumentMediaClipEdit, DocumentMediaClipValidation, DocumentMediaClipValidationAnswer, DocumentWorkspaceAudioImport, Finding, Member, ProductionAudioAuthoring, RequestContext, Route, PresmiumDocument, VerifiedDocumentAudioImport, VerifiedDocumentMediaClipChange, WorkspaceAudioInspectionAnswer } from '@lincyaw/kernel'
7
7
  import { productionAssetFile, validateDocumentRecordingAdoption, validateDocumentAudioInspect, validateDocumentWorkspaceAudioImport, validateDocumentWorkspaceAudioInspect, validateDocumentMediaClipValidation, validateDocumentMediaClipEdit, validateDocumentProductionPlanQuery } from '@lincyaw/kernel/node'
8
8
  import { readAuthoringDocument } from './document-editor.ts'
9
9
  import { catchRequestErrors, RequestError } from './errors.ts'
@@ -108,13 +108,13 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
108
108
  check(signal); opened(ctx, source.version, source)
109
109
  return inspection
110
110
  }
111
- const history = (ctx: RequestContext, content: TeachingDocument, origin: 'editor' | 'agent', validate?: () => Promise<void>): SourceTransactionHistory => ({
111
+ const history = (ctx: RequestContext, content: PresmiumDocument, origin: 'editor' | 'agent', validate?: () => Promise<void>): SourceTransactionHistory => ({
112
112
  run: work => { const guarded = async () => { await validate?.(); return work() }; return revisions ? revisions.transaction(guarded) : guarded() },
113
113
  commit: async paths => {
114
114
  if (!revisions) return undefined
115
115
  const ignored = (await Promise.all(paths.map(async path => await revisions.ignores(path) ? path : undefined))).filter((path): path is string => Boolean(path))
116
116
  if (ignored.length) throw new RequestError(409, 'document-files-ignored', { ignored })
117
- return revisions.commitWhileLocked({ paths, summary: content.metadata.lang?.startsWith('en') ? 'Edit audio media' : '编辑音频素材', body: '', origin: { kind: origin, member: ctx.member } })
117
+ return revisions.commitWhileLocked({ paths, summary: editor.effective(ctx.document, content).metadata.lang.startsWith('en') ? 'Edit audio media' : '编辑音频素材', body: '', origin: { kind: origin, member: ctx.member } })
118
118
  },
119
119
  })
120
120
  const remember = (key: string, receipt: Receipt) => { receipts.set(key, receipt); while (receipts.size > MAX_RECEIPTS) receipts.delete(receipts.keys().next().value!) }
@@ -278,7 +278,7 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
278
278
  const current = opened(ctx, request.source.version, request.source), step = current.content.steps[request.stepId], asset = current.content.assets[request.assetId]
279
279
  if (!step) throw new RequestError(404, 'document-step-missing')
280
280
  if (!asset) throw new RequestError(404, 'production.asset-missing')
281
- const original = current.content.production.stepOverrides[step.id]?.voiceSource ?? current.content.production.sectionOverrides?.[step.sectionId]?.voiceSource ?? current.content.production.defaults.voiceSource
281
+ const original = current.content.production.stepOverrides[step.id]?.voiceSource ?? current.content.production.sectionOverrides?.[step.sectionId]?.voiceSource ?? current.effective.production.defaults.voiceSource
282
282
  if (request.sourceRange && (original?.type !== 'recording' || original.assetId !== asset.id)) throw new RequestError(409, 'recording-source-changed')
283
283
  const issue = recordingStepIssue(current.content, request.stepId)
284
284
  if (issue) throw new RequestError(422, issue)
@@ -1,8 +1,8 @@
1
1
  import { createHash, randomUUID } from 'node:crypto'
2
2
  import { isRecord } from '@lincyaw/kernel'
3
- import { applyDocumentOperations, AUTHORING_API_VERSION, createDocumentPage, DOCUMENT_ENTRY, DOCUMENT_OPERATION_TYPES, DOCUMENT_READ_MAX_REQUEST_CHARS, DOCUMENT_READ_MAX_RESPONSE_CHARS, DOCUMENT_SCHEMA_VERSION, documentOutline, documentPart, DocumentReadError, duplicateDocumentPage, fnv1a64, hasRole, moveDocumentPage, pageDeletionImpact, removeDocumentPage, renameDocumentPage, validateDocument } from '@lincyaw/kernel'
3
+ import { applyDocumentOperations, AUTHORING_API_VERSION, documentSettings, createDocumentPage, DOCUMENT_ENTRY, DOCUMENT_OPERATION_TYPES, DOCUMENT_READ_MAX_REQUEST_CHARS, DOCUMENT_READ_MAX_RESPONSE_CHARS, DOCUMENT_SCHEMA_VERSION, documentOutline, documentPart, DocumentReadError, duplicateDocumentPage, fnv1a64, hasRole, moveDocumentPage, pageDeletionImpact, removeDocumentPage, renameDocumentPage, validateDocument } from '@lincyaw/kernel'
4
4
  import { validateDocumentChange, validateDocumentPageChange, validateDocumentPageChangeApply, validateDocumentPageDuplication, validateDocumentPageDuplicationApply, validateDocumentOutlineQuery, validateDocumentPartQuery } from '@lincyaw/kernel/node'
5
- import type { AppliedDocumentChange, ApplyDocumentChange, CanonicalSource, DocumentAnswer, DocumentAuthoring, DocumentChange, DocumentChangeAnswer, DocumentChangePlan, DocumentIssue, DocumentPageAction, DocumentPageChangePlan, DocumentPageDuplicationPlan, Member, RequestContext, SourceTransactionChange, TeachingDocument } from '@lincyaw/kernel'
5
+ import type { AppliedDocumentChange, ApplyDocumentChange, CanonicalSource, DocumentAnswer, DocumentAuthoring, DocumentChange, DocumentChangeAnswer, DocumentChangePlan, DocumentIssue, DocumentPageAction, DocumentPageChangePlan, DocumentPageDuplicationPlan, Member, RequestContext, SourceTransactionChange, PresmiumDocument } from '@lincyaw/kernel'
6
6
  import { RequestError } from './errors.ts'
7
7
  import { applyDocumentAuthoringAction, DOCUMENT_ACTION_MAX_REQUEST_CHARS, DOCUMENT_ACTION_MAX_RESPONSE_CHARS, DOCUMENT_AUTHORING_ACTION_TYPES, DOCUMENT_PARAMETER_MAX_CHANGES, DOCUMENT_PARAMETER_MAX_PATH_DEPTH, DocumentCommentError, DocumentComponentError, DocumentCaptionTimingError, ProductionAudioRefusal } from '@lincyaw/kernel'
8
8
  import { validateDocumentAuthoringAction, validateDocumentAuthoringActionReference, validateDocumentAuthoringActionImpact } from '@lincyaw/kernel/node'
@@ -18,7 +18,7 @@ const signatureOf = (change: DocumentChange) => createHash('sha256').update(JSON
18
18
  const keyOf = (document: string, member: Member, id: string) => JSON.stringify([document, member.id, id])
19
19
  const sourceOf = (answer: DocumentAnswer) => ({ documentId: answer.content.id, version: answer.version, fingerprint: answer.fingerprint })
20
20
 
21
- export function decodeAuthoringDocument(content: string): { document?: TeachingDocument, issues: DocumentIssue[] } {
21
+ export function decodeAuthoringDocument(content: string): { document?: PresmiumDocument, issues: DocumentIssue[] } {
22
22
  let value: unknown
23
23
  try { value = JSON.parse(content.replace(/^\uFEFF/, '')) }
24
24
  catch { return { issues: [{ path: '', code: 'json-syntax', message: 'The document is not valid JSON.', severity: 'error' }] } }
@@ -30,7 +30,7 @@ export function readAuthoringDocument(editor: SourceEditor, ctx: Pick<RequestCon
30
30
  const source = editor.read(editor.scope(ctx.document), entryOf(ctx.document), ctx.member)
31
31
  const checked = decodeAuthoringDocument(source.content)
32
32
  if (!checked.document || checked.issues.some(issue => issue.severity === 'error')) throw new RequestError(422, 'document-invalid', { issues: checked.issues })
33
- return { source, content: checked.document, issues: checked.issues }
33
+ return { source, content: checked.document, effective: editor.effective(ctx.document, checked.document), issues: checked.issues }
34
34
  }
35
35
 
36
36
  export interface DocumentEditor extends DocumentAuthoring {
@@ -59,10 +59,10 @@ export function createDocumentEditor({ editor, revisions, reviewRequired = false
59
59
  while (table.size > MAX_RECEIPTS) table.delete(table.keys().next().value!)
60
60
  }
61
61
  const read = async (document: string, member: Member): Promise<DocumentAnswer> => {
62
- const { source, content, issues } = readAuthoringDocument(editor, { document, member })
63
- return { document, version: source.version, fingerprint: fnv1a64(source.content), content, issues }
62
+ const { source, content, effective, issues } = readAuthoringDocument(editor, { document, member })
63
+ return { document, version: source.version, fingerprint: fnv1a64(source.content), content, settings: documentSettings(effective), inherited: editor.inherited(document, content), issues }
64
64
  }
65
- const readSelection = <T>(document: string, expected: CanonicalSource | undefined, member: Member, select: (content: TeachingDocument, source: CanonicalSource) => T): T => {
65
+ const readSelection = <T>(document: string, expected: CanonicalSource | undefined, member: Member, select: (content: PresmiumDocument, source: CanonicalSource) => T): T => {
66
66
  if (!hasRole(member, 'editor')) throw new RequestError(403, 'authoring-permission-denied')
67
67
  const scope = editor.scope(document), path = entryOf(document)
68
68
  const readSource = () => {
@@ -94,7 +94,7 @@ export function createDocumentEditor({ editor, revisions, reviewRequired = false
94
94
  if (!checked.change) throw new RequestError(400, 'document-change-invalid', { issues: checked.issues })
95
95
  return checked.change
96
96
  }
97
- const filesOf = async (document: string, current: DocumentAnswer, change: DocumentChange): Promise<{ content: TeachingDocument, issues: DocumentIssue[], changes: SourceTransactionChange[] }> => {
97
+ const filesOf = async (document: string, current: DocumentAnswer, change: DocumentChange): Promise<{ content: PresmiumDocument, issues: DocumentIssue[], changes: SourceTransactionChange[] }> => {
98
98
  if (current.version !== change.baseDocumentVersion) throw new RequestError(409, 'document-version-changed', { version: current.version })
99
99
  let candidate: unknown = change.replacement
100
100
  if (change.operations) {
@@ -326,7 +326,7 @@ export function createDocumentEditor({ editor, revisions, reviewRequired = false
326
326
  })
327
327
  const planId = randomUUID(), record: Plan = { key, signature: '', expires: Date.now() + PLAN_LIFETIME_MS, ready: false }
328
328
  const result = (async (): Promise<DocumentPageChangePlan> => {
329
- let candidate: TeachingDocument, sectionId: string, created
329
+ let candidate: PresmiumDocument, sectionId: string, created
330
330
  try {
331
331
  if (action.type === 'create') { const next = createDocumentPage(current, action.after ?? null, action.title, randomUUID); candidate = next.document; created = next.ids; sectionId = next.ids.sectionId }
332
332
  else {
@@ -4,7 +4,7 @@ import { lstat, open, stat } from 'node:fs/promises'
4
4
  import { basename, extname, join, relative } from 'node:path'
5
5
  import { imageSize } from 'image-size'
6
6
  import { ASSET_TITLE_MAX_LENGTH, DOCUMENT_IMAGE_MAX_BYTES, fnv1a64, hasRole, isRecord, jsonResponse } from '@lincyaw/kernel'
7
- import type { Asset, CanonicalSource, DocumentImageAuthoring, DocumentImageImport, DocumentImageImportAnswer, DocumentWorkspaceImageImport, Member, RequestContext, Route, TeachingDocument, VerifiedDocumentImageImport } from '@lincyaw/kernel'
7
+ import type { Asset, CanonicalSource, DocumentImageAuthoring, DocumentImageImport, DocumentImageImportAnswer, DocumentWorkspaceImageImport, Member, RequestContext, Route, PresmiumDocument, VerifiedDocumentImageImport } from '@lincyaw/kernel'
8
8
  import { productionAssetFile, validateDocumentWorkspaceImageImport, validateDocumentWorkspaceImageInspect } from '@lincyaw/kernel/node'
9
9
  import { readAuthoringDocument } from './document-editor.ts'
10
10
  import { catchRequestErrors, RequestError } from './errors.ts'
@@ -78,7 +78,7 @@ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRe
78
78
  receipts.set(key, receipt)
79
79
  while (receipts.size > 64) receipts.delete(receipts.keys().next().value!)
80
80
  }
81
- const history = (ctx: RequestContext, document: TeachingDocument, signal: AbortSignal, origin: 'editor' | 'agent'): SourceTransactionHistory => ({
81
+ const history = (ctx: RequestContext, document: PresmiumDocument, signal: AbortSignal, origin: 'editor' | 'agent'): SourceTransactionHistory => ({
82
82
  run: work => {
83
83
  const guarded = () => { signal.throwIfAborted(); return work() }
84
84
  return revisions ? revisions.transaction(guarded) : guarded()
@@ -87,7 +87,7 @@ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRe
87
87
  if (!revisions) return undefined
88
88
  const ignored = (await Promise.all(paths.map(async path => await revisions.ignores(path) ? path : undefined))).filter((path): path is string => Boolean(path))
89
89
  if (ignored.length) throw new RequestError(409, 'document-files-ignored', { ignored })
90
- return revisions.commitWhileLocked({ paths, summary: document.metadata.lang.startsWith('en') ? 'Import image' : '导入图片', body: '', origin: { kind: origin, member: ctx.member } })
90
+ return revisions.commitWhileLocked({ paths, summary: editor.effective(ctx.document, document).metadata.lang.startsWith('en') ? 'Import image' : '导入图片', body: '', origin: { kind: origin, member: ctx.member } })
91
91
  },
92
92
  })
93
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')
@@ -1,17 +1,15 @@
1
1
  import { randomUUID } from 'node:crypto'
2
- import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
2
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
3
3
  import { tmpdir } from 'node:os'
4
4
  import { dirname, join } from 'node:path'
5
- import { importDocuments, WORKSPACE_CONFIG } from '@lincyaw/compiler'
6
- import { DOCUMENT_ENTRY, DOCUMENT_IMPORT_MAX_BYTES, DOCUMENT_IMPORT_MAX_FILES, hasRole, isRecord, jsonResponse, validateDocument } from '@lincyaw/kernel'
5
+ import { importDocuments } from '@lincyaw/compiler'
6
+ import { DOCUMENT_ENTRY, DOCUMENT_IMPORT_MAX_BYTES, DOCUMENT_IMPORT_MAX_FILES, hasRole, jsonResponse, validateDocument } from '@lincyaw/kernel'
7
7
  import type { DocumentImportAnswer, Route } from '@lincyaw/kernel'
8
- import { parse, stringify } from 'yaml'
9
8
  import { readWorkspaceConfig } from './config.ts'
10
9
  import type { WorkspaceConfig } from './config.ts'
11
10
  import { catchRequestErrors, RequestError } from './errors.ts'
12
11
  import type { DocumentLocks } from './locks.ts'
13
12
  import type { Revisions } from './revisions.ts'
14
- import { writeChanges } from './writer.ts'
15
13
  import type { DocumentWriter } from './writer.ts'
16
14
  import type { DocumentsChange } from './document-operations.ts'
17
15
 
@@ -47,7 +45,7 @@ export function documentImportRoute(options: { config: WorkspaceConfig, writer:
47
45
  mkdirSync(dirname(join(source, path)), { recursive: true })
48
46
  writeFileSync(join(source, path), Buffer.from(await file.arrayBuffer()), { flag: 'wx' })
49
47
  }
50
- const report = await importDocuments(source, { out: output, preserveOriginal: true }).catch(() => bad(422, 'conversion'))
48
+ const report = await importDocuments(source, { out: output, preserveOriginal: true, workspaceRoot: config.root }).catch(() => bad(422, 'conversion'))
51
49
  if (report.documents.length === 0) return bad(422, 'empty')
52
50
  const files: { path: string, content: Buffer }[] = []
53
51
  let bytes = 0
@@ -76,37 +74,22 @@ export function documentImportRoute(options: { config: WorkspaceConfig, writer:
76
74
  request.signal.throwIfAborted()
77
75
  const directory = `imported-${randomUUID().slice(0, 8)}`
78
76
  if (existsSync(join(config.root, directory))) return bad(409, 'changed')
79
- const file = join(config.root, WORKSPACE_CONFIG)
80
- const stat = lstatSync(file, { throwIfNoEntry: false })
81
- if (stat && !stat.isFile()) return bad(403, 'forbidden')
82
- let settings: unknown
83
- try { settings = stat ? parse(readFileSync(file, 'utf8')) : {} } catch { return bad(422, 'configuration') }
84
- if (!isRecord(settings)) return bad(422, 'configuration')
85
- const entries = documents.map(doc => `${directory}/${doc.dir}/${DOCUMENT_ENTRY}`)
86
- const previous = [...config.documents]
87
- const current = readWorkspaceConfig(config.root)
88
- if (current.singleDeck) return bad(409, 'unavailable')
89
- const patterns = [...new Set([...current.documents, ...entries])]
90
- const next = Buffer.from(stringify({ ...settings, documents: patterns }))
91
- if (await revisions.ignoresAny([WORKSPACE_CONFIG, ...files.map(item => `${directory}/${item.path}`)])) return bad(403, 'forbidden')
92
- await revisions.checkpoint([directory, WORKSPACE_CONFIG])
93
- const checkpoint = await writer.checkpoint([directory], undefined, [WORKSPACE_CONFIG])
77
+ if (readWorkspaceConfig(config.root).singleDeck) return bad(409, 'unavailable')
78
+ if (await revisions.ignoresAny(files.map(item => `${directory}/${item.path}`))) return bad(403, 'forbidden')
79
+ await revisions.checkpoint([directory])
80
+ const checkpoint = await writer.checkpoint([directory])
94
81
  const before = await revisions.head()
95
82
  let committed = false
96
83
  try {
97
84
  for (const item of files) { request.signal.throwIfAborted(); await writer.create(`${directory}/${item.path}`, item.content, true) }
98
85
  request.signal.throwIfAborted()
99
- writeChanges(config, [{ path: WORKSPACE_CONFIG, content: next }], true)
100
- config.documents.splice(0, config.documents.length, ...patterns)
101
- request.signal.throwIfAborted()
102
- const revision = await revisions.commitWhileLocked({ paths: [directory, WORKSPACE_CONFIG], summary: `Import ${documents.length} documents`, body: '', origin: { kind: 'document', member: ctx.member, operation: { op: 'create', dir: directory } } })
86
+ const revision = await revisions.commitWhileLocked({ paths: [directory], summary: `Import ${documents.length} documents`, body: '', origin: { kind: 'document', member: ctx.member, operation: { op: 'create', dir: directory } } })
103
87
  if (!revision) return bad(409, 'changed')
104
88
  committed = true
105
89
  return { directory, documents: documents.map(doc => ({ ...doc, dir: `${directory}/${doc.dir}` })), files: files.length, unresolved: report.unresolved.length, warnings: report.warnings ?? 0, ...revision ? { revision } : {} }
106
90
  } catch (error) {
107
91
  if (await revisions.head() !== before) { committed = true; throw new RequestError(409, 'document-import-changed', { committed: true }) }
108
92
  await checkpoint.restore()
109
- config.documents.splice(0, config.documents.length, ...previous)
110
93
  throw error
111
94
  } finally { if (committed || await revisions.head() === before) checkpoint.dispose() }
112
95
  })
@@ -143,7 +143,7 @@ export class DocumentOperations {
143
143
  const fresh = (dir: string) => {
144
144
  const invalid = invalidDocumentDir(dir)
145
145
  if (invalid) throw new RequestError(400, invalid)
146
- if (!isDocumentDir(config, dir)) throw new RequestError(400, `"${dir}" is not where the workspace configuration's documents are (${config.documents.join(', ')})`)
146
+ if (!isDocumentDir(config, dir)) throw new RequestError(400, `"${dir}" cannot hold a document`)
147
147
  const holder = known.find(doc => doc !== '' && (isWithin(dir, doc) || isWithin(doc, dir)))
148
148
  if (holder !== undefined) throw new RequestError(409, `${dir} would hold or be inside the document ${holder}`)
149
149
  if (existsSync(join(config.root, dir))) throw new RequestError(409, `${dir} exists already`)
@@ -47,7 +47,7 @@ export function createDocumentVoiceAuthoring({ editor, services, prepareExecutio
47
47
  const opened = readAuthoringDocument(editor, { document, member })
48
48
  const source = { documentId: opened.content.id, version: opened.source.version, fingerprint: fnv1a64(opened.source.content) }
49
49
  if (expected && !same(source, expected)) throw new RequestError(409, 'document-version-changed', { currentSource: source })
50
- return { source, lang: opened.content.metadata.lang }
50
+ return { source, lang: opened.effective.metadata.lang }
51
51
  }
52
52
  const work = <T>(signal: AbortSignal | undefined, run: (signal: AbortSignal) => Promise<T>): Promise<T> => {
53
53
  if (closed) throw new RequestError(503, 'voice-authoring-closed')
@@ -1,4 +1,4 @@
1
1
  export const MEDIA_UPLOAD_MESSAGES = {
2
- 'zh-CN': { image: '上传图片', audio: '上传音频', choose: '选择文件', sending: '正在上传…', ready: '上传完成。请返回助手继续导入。', pending: '选择文件后自动上传,再由助手导入讲义。', failed: '上传未完成。请重新选择文件后重试。', unavailable: '此上传链接已失效,请返回助手重新发起上传。', limit: (size: number) => `文件大小上限:${size} MiB` },
2
+ 'zh-CN': { image: '上传图片', audio: '上传音频', choose: '选择文件', sending: '正在上传…', ready: '上传完成。请返回助手继续导入。', pending: '选择文件后自动上传,再由助手导入文稿。', failed: '上传未完成。请重新选择文件后重试。', unavailable: '此上传链接已失效,请返回助手重新发起上传。', limit: (size: number) => `文件大小上限:${size} MiB` },
3
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
4
  }
@@ -23,7 +23,7 @@ export function createMediaUploads({ editor, url, lifetimeMs = LIFETIME_MS }: {
23
23
  const current = (document: string, member: Member) => {
24
24
  if (closed) return fail(503, 'media-upload-unavailable')
25
25
  if (!hasRole(member, 'editor')) return fail(403, 'media-upload-permission-denied')
26
- return readAuthoringDocument(editor, { document, member }).content
26
+ return readAuthoringDocument(editor, { document, member }).effective
27
27
  }
28
28
  const release = (entry: Entry) => { reserved -= entry.reserved; entry.reserved = 0; delete entry.bytes }
29
29
  const retire = (upload: string, entry: Entry) => {
@@ -41,7 +41,6 @@ export function pageDeleteRoute({ config, editor, workbench, locks, revisions }:
41
41
  if (!config.singleDeck) {
42
42
  const workspaceSource = editor.read(editor.scope(''), WORKSPACE_CONFIG, ctx.member)
43
43
  const currentConfig = readWorkspaceConfig(config.root)
44
- if (JSON.stringify(currentConfig.documents) !== JSON.stringify(config.documents)) throw new RequestError(409, 'page-references-unavailable')
45
44
  dependencies.set(workspaceSource.path, workspaceSource.version)
46
45
  const workspaceView = { ...answer.doc, meta: { ...answer.doc.meta, entry: WORKSPACE_CONFIG }, config: { ...answer.doc.config, presmium: { site: currentConfig.site } }, sections: [] }
47
46
  if (pageIncomingReferences(workspaceView, answer.doc.meta.entry, targets).length) references.push({ document: '', section })
@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto'
2
2
  import { existsSync, lstatSync, readFileSync, readdirSync, readlinkSync } from 'node:fs'
3
3
  import { join, posix } from 'node:path'
4
4
  import { DOCUMENT_ENTRY, parseAnchor, validateDocument } from '@lincyaw/kernel'
5
- import type { ProjectOperation, TeachingDocument, DocumentFileChange } from '@lincyaw/kernel'
5
+ import type { ProjectOperation, PresmiumDocument, DocumentFileChange } from '@lincyaw/kernel'
6
6
  import { invalidDocumentDir, isWithin, movedUrl, rewriteLinks } from '../domain/paths.ts'
7
7
  import { isDocumentDir, listDocuments, readWorkspaceConfig } from './config.ts'
8
8
  import type { WorkspaceConfig } from './config.ts'
@@ -62,7 +62,7 @@ export function projectMaterial(config: WorkspaceConfig, operation: ProjectOpera
62
62
  const dirs = operation.op === 'copy' || operation.op === 'rename' ? [operation.dir, operation.to] : [operation.dir]
63
63
  if (operation.op === 'retitle') walk(join(config.root, entry(operation.dir)), entry(operation.dir), operation.dir)
64
64
  else for (const dir of dirs) { safeParents(dir); walk(join(config.root, dir), dir, dir) }
65
- const canonical = new Map<string, TeachingDocument>()
65
+ const canonical = new Map<string, PresmiumDocument>()
66
66
  for (const doc of known) {
67
67
  safeParents(doc.dir)
68
68
  const path = join(config.root, doc.entry), stat = lstatSync(path)
@@ -3,7 +3,7 @@ import { listDocuments } from './config.ts'
3
3
  import { randomUUID } from 'node:crypto'
4
4
  import { existsSync, readFileSync } from 'node:fs'
5
5
  import { join } from 'node:path'
6
- import { PROJECT_MAX_PLANS, PROJECT_PLAN_TTL_MS, PROJECT_MAX_REQUEST_CHARS, PROJECT_MAX_RESPONSE_CHARS, hasRole, jsonResponse, problemResponse, validateDocument } from '@lincyaw/kernel'
6
+ import { PROJECT_MAX_PLANS, PROJECT_PLAN_TTL_MS, PROJECT_MAX_REQUEST_CHARS, PROJECT_MAX_RESPONSE_CHARS, hasRole, jsonResponse, problemResponse, validateDocument, DOCUMENT_ENTRY } from '@lincyaw/kernel'
7
7
  import type { CanonicalSource, DocumentChange, ProjectApplied, ProjectApply, ProjectAuthoring, ProjectCaller, ProjectOperation, ProjectPlan, ProjectPlanRequest, Route } from '@lincyaw/kernel'
8
8
  import { validateProjectApply, validateProjectPlan } from '@lincyaw/kernel/node'
9
9
  import type { WorkspaceConfig } from './config.ts'
@@ -183,7 +183,7 @@ export function createProjectAuthoring(options: { config: WorkspaceConfig, opera
183
183
  if (op.op === 'rename' || op.op === 'delete') if (existsSync(join(config.root, op.dir))) throw new RequestError(409, 'project-readback-changed', { committed: true })
184
184
  for (const change of stored.material!.changes) if ('content' in change && projectDigest(readFileSync(join(config.root, change.path))) !== projectDigest(change.content)) throw new RequestError(409, 'project-readback-changed', { committed: true })
185
185
  if (stored.plan.documentId && answer.dir) {
186
- const checked = validateDocument(JSON.parse(readFileSync(join(config.root, answer.dir, 'lecture.json'), 'utf8')))
186
+ const checked = validateDocument(JSON.parse(readFileSync(join(config.root, answer.dir, DOCUMENT_ENTRY), 'utf8')))
187
187
  if (checked.document?.id !== stored.plan.documentId) throw new RequestError(409, 'project-readback-changed', { committed: true })
188
188
  }
189
189
  stored.receipt = bounded(receipt)
@@ -3,7 +3,7 @@ import { closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, mkdt
3
3
  import { tmpdir } from 'node:os'
4
4
  import { basename, dirname, join, relative, resolve, sep } from 'node:path'
5
5
  import type { DocumentFileChange, HistoryRevision, Member, RevertResult, Revision, RevisionsAnswer, RevisionService, UncommittedFile } from '@lincyaw/kernel'
6
- import { CHANGES_MAX_BYTES, LOCAL_AUTHOR, SOURCE_MAX_BYTES } from '@lincyaw/kernel'
6
+ import { CHANGES_MAX_BYTES, LOCAL_AUTHOR, SOURCE_MAX_BYTES, DOCUMENT_ENTRY } from '@lincyaw/kernel'
7
7
  import { leavesRoot } from '../domain/paths.ts'
8
8
  import { commitMessage, memberAddress, originOf } from '../domain/commit-message.ts'
9
9
  import type { CommitOrigin } from '../domain/commit-message.ts'
@@ -509,7 +509,7 @@ export class Revisions implements RevisionService {
509
509
  while (at < tree.length) {
510
510
  const space = tree.indexOf(32, at), zero = tree.indexOf(0, space + 1)
511
511
  if (space < at || zero < space || zero + 1 + oidBytes > tree.length) throw new RequestError(500, 'history-tree-read-failed')
512
- if (tree.subarray(space + 1, zero).toString('utf8') === 'lecture.json') found = ['100644', '100755'].includes(tree.subarray(at, space).toString('ascii'))
512
+ if (tree.subarray(space + 1, zero).toString('utf8') === DOCUMENT_ENTRY) found = ['100644', '100755'].includes(tree.subarray(at, space).toString('ascii'))
513
513
  at = zero + 1 + oidBytes
514
514
  }
515
515
  regular.set(oid, found); cursor = end + 1
@@ -3,6 +3,7 @@ import { createRequire } from 'node:module'
3
3
  import { DOCUMENT_ENTRY, fnv1a64, hasRole, isRecord, jsonResponse, problemResponse, PRODUCTION_AUDIO_AUTHORING, pushStream, SPEECH, sseResponse } from '@lincyaw/kernel'
4
4
  import type { CompileJob, DocumentsAnswer, JobsAnswer, PresmiumNodePlugin, RequestContext, Route, SavedAnswer, ServerContribution, SourceTransactionAnswer, SourceTransactionChange } from '@lincyaw/kernel'
5
5
  import { hasBearerToken } from '@lincyaw/server'
6
+ import { migrationNeed } from '@lincyaw/compiler/migrate'
6
7
  import { saveSummary } from '../domain/commit-message.ts'
7
8
  import { documentSummaries, listDocuments } from './config.ts'
8
9
  import type { WorkspaceConfig } from './config.ts'
@@ -62,6 +63,7 @@ export interface WorkspaceRoutesOptions {
62
63
  authoringClientRoutes?: Record<string, Route>
63
64
  projectRoutes?: Record<string, Route>
64
65
  documentImport?: Route
66
+ workspaceMigrate?: Route
65
67
  mcpSettings?: Route
66
68
  speechSettings?: Route
67
69
  changesRoutes?: Record<string, Route>
@@ -124,7 +126,8 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
124
126
  handle: (request, ctx) => catchRequestErrors(async () => {
125
127
  if (request.method === 'GET') {
126
128
  const status = options.projectRevisions ? await options.projectRevisions.status(editor.roots(scopeOf(ctx))) : {}
127
- return jsonResponse({ title: config.title, documents: documentSummaries(config), templates: listTemplates(config), git: Boolean(revisions), ...status, single: config.singleDeck } satisfies DocumentsAnswer)
129
+ const migration = migrationNeed(config.root)
130
+ return jsonResponse({ title: config.title, documents: documentSummaries(config), templates: listTemplates(config), git: Boolean(revisions), ...status, single: config.singleDeck, ...migration ? { migration } : {} } satisfies DocumentsAnswer)
128
131
  }
129
132
  if (request.method !== 'POST') return problemResponse(405, 'GET or POST')
130
133
  return problemResponse(409, 'project-plan-required')
@@ -134,6 +137,7 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
134
137
  ...options.authoringClientRoutes,
135
138
  ...options.projectRoutes,
136
139
  ...options.documentImport ? { 'documents/import': options.documentImport } : {},
140
+ ...options.workspaceMigrate ? { 'workspace/migrate': options.workspaceMigrate } : {},
137
141
  'files': {
138
142
  role: 'editor',
139
143
  handle: (request, ctx) => catchRequestErrors(async () => {
package/src/node/serve.ts CHANGED
@@ -51,6 +51,7 @@ import { createWorkbenchBackend } from './workbench-api.ts'
51
51
  import type { WorkbenchBackend } from './workbench-api.ts'
52
52
  import { localWriter } from './writer.ts'
53
53
  import { documentImportRoute } from './document-import.ts'
54
+ import { workspaceMigrateRoute } from './workspace-migrate.ts'
54
55
  import { hostUpgradeRoute } from './host-upgrade.ts'
55
56
  import { createHostActivity } from './host-activity.ts'
56
57
 
@@ -509,6 +510,7 @@ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
509
510
  authoringClientRoutes: { ...authoringClients.routes, ...authoringWindows.routes, ...agentActivity.routes },
510
511
  projectRoutes: projectAuthoring.routes,
511
512
  documentImport: documentImportRoute({ config, writer, locks, revisions: history?.revisions, changed: documentsChanged }),
513
+ workspaceMigrate: workspaceMigrateRoute({ config, locks, revisions: history?.revisions, changed: documentsChanged }),
512
514
  locks,
513
515
  ...history ? { revisions: history.revisions, operations: history.operations, reviews: history.agentSessionReviews } : {},
514
516
  documentsChanged,
package/src/node/site.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
2
2
  import { basename, dirname, join, relative, resolve, sep } from 'node:path'
3
- import { compileTranslations, directoryAsset, fileHash, lineContaining, loadPlugins, nodeVitePlugins, portable, publishesDirectory, viewFor } from '@lincyaw/compiler'
3
+ import { compileTranslations, directoryAsset, effectiveDocumentIn, fileHash, lineContaining, loadPlugins, nodeVitePlugins, portable, publishesDirectory, viewFor } from '@lincyaw/compiler'
4
4
  import type { Compilation } from '@lincyaw/compiler'
5
5
  import { DOCUMENT_ENTRY, isRecord, NON_FILE_URL, WEB_RENDERER_PACKAGE } from '@lincyaw/kernel'
6
- import type { DocumentSummary, Finding, IRDocument, RenderContext, Renderer, SiteDocument, SiteSpec, SourcePos } from '@lincyaw/kernel'
6
+ import type { DocumentSummary, Finding, IRDocument, PresmiumDocument, RenderContext, Renderer, SiteDocument, SiteSpec, SourcePos } from '@lincyaw/kernel'
7
7
  import { isInside } from '@lincyaw/kernel/node'
8
8
  import type { WorkspaceConfig } from './config.ts'
9
9
 
@@ -116,7 +116,7 @@ function publishedAsset(options: SiteContextOptions, source: SourcePos, url: str
116
116
  const deck = deckOf(source.file, options.root)
117
117
  if (!deck || !publishesDirectory(target, deck)) return undefined
118
118
  const document: unknown = JSON.parse(readFileSync(join(deck, DOCUMENT_ENTRY), 'utf8'))
119
- const lang = isRecord(document) && isRecord(document.metadata) ? document.metadata.lang : undefined
119
+ const lang = isRecord(document) && isRecord(document.metadata) && isRecord(document.production) && isRecord(document.placement) ? effectiveDocumentIn(options.root, join(deck, DOCUMENT_ENTRY), document as unknown as PresmiumDocument).metadata.lang : undefined
120
120
  return directoryAsset(target, deck, join(options.workDir, 'files'), typeof lang === 'string' ? lang : undefined, message => warn(`${url} is not published: ${message}`))
121
121
  }
122
122
 
@@ -3,9 +3,9 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, readdir
3
3
  import { join } from 'node:path'
4
4
  import { WORKSPACE_CONFIG } from '@lincyaw/compiler'
5
5
  import { DOCUMENT_ENTRY, SOURCE_MAX_BYTES, SOURCE_MAX_FILES, validateDocument } from '@lincyaw/kernel'
6
- import type { ConflictAnswer, DocumentFileChange, FilesAnswer, Member, Revision, SavedAnswer, SourceAnswer, SourceFile, SourceTransactionAnswer, SourceTransactionChange } from '@lincyaw/kernel'
6
+ import type { ConflictAnswer, DocumentFileChange, FilesAnswer, Member, Revision, SavedAnswer, SourceAnswer, SourceFile, SourceTransactionAnswer, SourceTransactionChange, DocumentDefaults, EffectiveDocument, PresmiumDocument } from '@lincyaw/kernel'
7
7
  import { isWithin } from '../domain/paths.ts'
8
- import { listDocumentEntries, readDocumentSummary } from './config.ts'
8
+ import { effectiveContent, inheritedContent, listDocumentEntries, readDocumentSummary } from './config.ts'
9
9
  import type { DocumentEntry, WorkspaceConfig } from './config.ts'
10
10
  import { RequestError } from './errors.ts'
11
11
  import type { DocumentLocks } from './locks.ts'
@@ -74,6 +74,16 @@ export class SourceEditor {
74
74
  this.#beforeWrite = options.beforeWrite
75
75
  }
76
76
 
77
+ /** The document in `document` with its inherited settings filled in, for decisions; never saved. */
78
+ effective(document: string, content: PresmiumDocument): EffectiveDocument {
79
+ return effectiveContent(this.#config, document, content)
80
+ }
81
+
82
+ /** What the document in `document` inherits from its ancestors and the workspace defaults. */
83
+ inherited(document: string, content: PresmiumDocument): DocumentDefaults {
84
+ return inheritedContent(this.#config, document, content)
85
+ }
86
+
77
87
  scope(document: string): Scope {
78
88
  return { document, home: document === '' && !this.#config.singleDeck }
79
89
  }
@@ -0,0 +1,54 @@
1
+ import { WORKSPACE_CONFIG } from '@lincyaw/compiler'
2
+ import { applyMigration, planMigration } from '@lincyaw/compiler/migrate'
3
+ import type { MigrationPlan } from '@lincyaw/compiler/migrate'
4
+ import { DOCUMENT_ENTRY, hasRole, jsonResponse } from '@lincyaw/kernel'
5
+ import type { Route, WorkspaceMigrationAnswer } from '@lincyaw/kernel'
6
+ import type { WorkspaceConfig } from './config.ts'
7
+ import type { DocumentsChange } from './document-operations.ts'
8
+ import { catchRequestErrors, RequestError } from './errors.ts'
9
+ import type { DocumentLocks } from './locks.ts'
10
+ import type { Revisions } from './revisions.ts'
11
+
12
+ const dirOf = (path: string) => path.split('/').slice(0, -1).join('/')
13
+ /** The document folder a migrated file belongs to: a translation belongs to its original. */
14
+ const ownerOf = (path: string) => dirOf(path).replace(/(^|\/)locales\/[^/]+$/, '').replace(/\/\.presmium\/freeze$|^\.presmium\/freeze$/, '')
15
+
16
+ /**
17
+ * `POST workspace/migrate`, Studio's Upgrade: the migration of `presmium migrate`, recorded as one revision per
18
+ * document (its rename, translations and content) and one for the workspace file.
19
+ */
20
+ export function workspaceMigrateRoute(options: { config: WorkspaceConfig, locks: DocumentLocks, revisions?: Revisions, changed(change: DocumentsChange): Promise<void> | void }): Route {
21
+ const { config, locks, revisions } = options
22
+ return {
23
+ role: 'owner', maxBody: 1024,
24
+ handle: (request, ctx) => catchRequestErrors(async () => {
25
+ if (request.method !== 'POST') throw new RequestError(405, 'POST')
26
+ if (!hasRole(ctx.member, 'owner') || ctx.document !== '') throw new RequestError(403, 'workspace-migrate-forbidden')
27
+ const release = await locks.acquire('', 'workspace:migrate')
28
+ try {
29
+ const run = async (): Promise<WorkspaceMigrationAnswer> => {
30
+ const plan: MigrationPlan = planMigration(config.root)
31
+ const groups = new Map<string, string[]>()
32
+ const add = (path: string) => {
33
+ const owner = path === WORKSPACE_CONFIG ? WORKSPACE_CONFIG : ownerOf(path)
34
+ groups.set(owner, [...groups.get(owner) ?? [], path])
35
+ }
36
+ for (const { from, to } of plan.renames) { add(from); add(to) }
37
+ for (const { path } of plan.writes) add(path)
38
+ if (revisions) await revisions.checkpoint([...groups.values()].flat())
39
+ applyMigration(plan)
40
+ const revisionIds: string[] = []
41
+ if (revisions) for (const [owner, paths] of groups) {
42
+ const summary = owner === WORKSPACE_CONFIG ? `Upgrade ${WORKSPACE_CONFIG}` : `Upgrade ${owner ? `${owner}/` : ''}${DOCUMENT_ENTRY}`
43
+ const revision = await revisions.commitWhileLocked({ paths, summary, body: 'Convert to the current document format (presmium migrate).', origin: { kind: 'document', member: ctx.member } })
44
+ if (revision) revisionIds.push(revision.id)
45
+ }
46
+ return { documents: plan.documents.map(dirOf), workspaceFile: plan.workspaceFile, problems: plan.problems, revisions: revisionIds }
47
+ }
48
+ const answer = revisions ? await revisions.transaction(run) : await run()
49
+ if (answer.documents.length) await options.changed({ removed: [], added: answer.documents })
50
+ return jsonResponse(answer)
51
+ } finally { release() }
52
+ }),
53
+ }
54
+ }
@@ -3,8 +3,9 @@ import { closeSync, constants, cpSync, fstatSync, lstatSync, mkdirSync, mkdtempS
3
3
  import type { Stats } from 'node:fs'
4
4
  import { tmpdir } from 'node:os'
5
5
  import { dirname, join } from 'node:path'
6
- import { CHANGES_MAX_BYTES, CHANGES_MAX_FILES, DOCUMENT_ENTRY, validateDocument } from '@lincyaw/kernel'
7
- import type { DocumentFileChange, DocumentFiles } from '@lincyaw/kernel'
6
+ import { topLevelRanks, workspaceDocuments } from '@lincyaw/compiler'
7
+ import { CHANGES_MAX_BYTES, CHANGES_MAX_FILES, DOCUMENT_ENTRY, ranksBetween, validateDocument } from '@lincyaw/kernel'
8
+ import type { DocumentFileChange, DocumentFiles, DocumentPlacement } from '@lincyaw/kernel'
8
9
  import { isWithin, rewriteLinks } from '../domain/paths.ts'
9
10
  import { isDocumentDir, listDocuments } from './config.ts'
10
11
  import type { WorkspaceConfig } from './config.ts'
@@ -238,19 +239,30 @@ function writeTemplate(config: WorkspaceConfig, dir: string, template: string, t
238
239
  if (!entries.some(entry => entry.path === DOCUMENT_ENTRY)) throw new FilesError(`The document template must contain ${DOCUMENT_ENTRY}.`)
239
240
  writeChanges(config, entries.map(({ path, executable }) => {
240
241
  const content = readFileSync(join(source, path))
241
- return { path: `${dir}/${path}`, content: path === DOCUMENT_ENTRY ? freshDocument(content, title, documentId) : content, ...executable ? { executable } : {} }
242
+ return { path: `${dir}/${path}`, content: path === DOCUMENT_ENTRY ? freshDocument(content, { parent: null, rank: topLevelRanks(config.root, 1)[0]! }, title, documentId) : content, ...executable ? { executable } : {} }
242
243
  }))
243
244
  }
244
245
 
246
+ /** Where a copy of the document in `dir` goes: beside it, right after it. */
247
+ function placementAfter(config: WorkspaceConfig, dir: string): DocumentPlacement {
248
+ const { tree } = workspaceDocuments(config.root)
249
+ const node = tree.order.find(node => node.path === `${dir}/${DOCUMENT_ENTRY}`)
250
+ if (!node) return { parent: null, rank: topLevelRanks(config.root, 1)[0]! }
251
+ const siblings = tree.children.get(node.parent) ?? []
252
+ const next = siblings[siblings.indexOf(node.id) + 1]
253
+ return { parent: node.parent, rank: ranksBetween(node.placement.rank || null, next === undefined ? null : tree.byId.get(next)!.placement.rank || null, 1)[0]! }
254
+ }
255
+
245
256
  /** A copy is a new document; block/section identities remain inside its new namespace. */
246
- function freshDocument(content: Uint8Array, title?: string, documentId?: string): Buffer {
257
+ function freshDocument(content: Uint8Array, placement: DocumentPlacement, title?: string, documentId?: string): Buffer {
247
258
  let value: unknown
248
259
  try { value = JSON.parse(Buffer.from(content).toString('utf8')) }
249
- catch { throw new FilesError(`Invalid ${DOCUMENT_ENTRY}: expected a JSON teaching document.`) }
260
+ catch { throw new FilesError(`Invalid ${DOCUMENT_ENTRY}: expected a JSON Presmium document.`) }
250
261
  const validated = validateDocument(value)
251
262
  if (!validated.document) throw new FilesError(`Invalid ${DOCUMENT_ENTRY}: ${validated.issues[0]?.message ?? 'document validation failed'}`)
252
263
  const document = validated.document
253
264
  document.id = documentId ?? randomUUID()
265
+ document.placement = placement
254
266
  if (title !== undefined) {
255
267
  document.metadata.title = title
256
268
  for (const section of Object.values(document.sections)) if (section.title === '{{title}}') section.title = title
@@ -263,13 +275,14 @@ function copyDocument(config: WorkspaceConfig, from: string, to: string, documen
263
275
  assertDocumentDir(config, to)
264
276
  const entries = documentSourceEntries(join(config.root, from))
265
277
  if (!entries.some(entry => entry.path === DOCUMENT_ENTRY)) throw new FilesError(`The copied document must contain ${DOCUMENT_ENTRY}.`)
278
+ const placement = placementAfter(config, from)
266
279
  writeChanges(config, entries.map(({ path, link, executable }): DocumentFileChange => {
267
280
  if (link !== undefined) {
268
281
  if (path === DOCUMENT_ENTRY) throw new FilesError('The canonical document entry cannot be a symbolic link when copied.')
269
282
  return { path: `${to}/${path}`, link }
270
283
  }
271
284
  const content = readFileSync(join(config.root, from, path))
272
- if (path === DOCUMENT_ENTRY) return { path: `${to}/${path}`, content: freshDocument(content, title, documentId) }
285
+ if (path === DOCUMENT_ENTRY) return { path: `${to}/${path}`, content: freshDocument(content, placement, title, documentId) }
273
286
  if (path.endsWith('.md')) return { path: `${to}/${path}`, content: Buffer.from(rewriteLinks(content.toString('utf8'), `${to}/${path}`, `${from}/${path}`, from, to)) }
274
287
  return { path: `${to}/${path}`, content, ...executable ? { executable } : {} }
275
288
  }))
@@ -1,6 +1,10 @@
1
1
  {
2
- "schemaVersion": 1,
2
+ "schemaVersion": 2,
3
3
  "id": "document-template",
4
+ "placement": {
5
+ "parent": null,
6
+ "rank": "a0"
7
+ },
4
8
  "metadata": {
5
9
  "title": "{{title}}",
6
10
  "lang": "zh-CN",