@lincyaw/workspace 1.0.0-rc.120 → 1.0.0-rc.122
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 +6 -6
- package/src/node/config.ts +7 -2
- package/src/node/document-authoring.ts +1 -1
- package/src/node/document-history.ts +24 -4
- package/src/node/document-index.ts +44 -2
- package/src/node/document-materials.ts +80 -0
- package/src/node/revisions.ts +7 -0
- package/src/node/routes.ts +2 -0
- package/src/node/serve.ts +2 -0
- package/src/node/source-editor.ts +7 -2
- package/src/node/tree-operations.ts +5 -2
- package/src/node/tree-routes.ts +9 -3
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lincyaw/workspace",
|
|
3
|
-
"version": "1.0.0-rc.
|
|
3
|
+
"version": "1.0.0-rc.122",
|
|
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/compiler": "1.0.0-rc.
|
|
38
|
-
"@lincyaw/kernel": "1.0.0-rc.
|
|
39
|
-
"@lincyaw/server": "1.0.0-rc.
|
|
40
|
-
"@lincyaw/design": "1.0.0-rc.
|
|
37
|
+
"@lincyaw/compiler": "1.0.0-rc.122",
|
|
38
|
+
"@lincyaw/kernel": "1.0.0-rc.122",
|
|
39
|
+
"@lincyaw/server": "1.0.0-rc.122",
|
|
40
|
+
"@lincyaw/design": "1.0.0-rc.122"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
43
|
"@types/mime-types": "^3.0.1",
|
|
44
|
-
"@lincyaw/mcp": "1.0.0-rc.
|
|
44
|
+
"@lincyaw/mcp": "1.0.0-rc.122"
|
|
45
45
|
}
|
|
46
46
|
}
|
package/src/node/config.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
|
|
2
2
|
import { join, resolve } from 'node:path'
|
|
3
|
-
import { effectiveDocumentIn, providedDocuments, inheritedSettingsIn, WORKSPACE_CONFIG, workspaceDefaults, workspaceDocuments, workspaceSettings } from '@lincyaw/compiler'
|
|
3
|
+
import { effectiveDocumentIn, providedDocuments, inheritedSettingsIn, settingOriginsIn, WORKSPACE_CONFIG, workspaceDefaults, workspaceDocuments, workspaceSettings } from '@lincyaw/compiler'
|
|
4
4
|
import type { OperatorSettings, WorkspaceDocuments } from '@lincyaw/compiler'
|
|
5
5
|
import { APPROVAL_KINDS, DOCUMENT_ENTRY, errorMessage, isRecord } from '@lincyaw/kernel'
|
|
6
|
-
import type { ApprovalKind, DocumentDefaults, DocumentSummary, EffectiveDocument, PresmiumDocument } from '@lincyaw/kernel'
|
|
6
|
+
import type { ApprovalKind, DocumentDefaults, DocumentSummary, EffectiveDocument, PresmiumDocument, SettingOrigins } from '@lincyaw/kernel'
|
|
7
7
|
import type { ApprovalPolicy } from '@lincyaw/server'
|
|
8
8
|
import { parse as parseYaml } from 'yaml'
|
|
9
9
|
|
|
@@ -220,3 +220,8 @@ export function effectiveContent(config: WorkspaceConfig, dir: string, content:
|
|
|
220
220
|
export function inheritedContent(config: WorkspaceConfig, dir: string, content: PresmiumDocument): DocumentDefaults {
|
|
221
221
|
return inheritedSettingsIn(config.root, join(config.root, dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY), content)
|
|
222
222
|
}
|
|
223
|
+
|
|
224
|
+
/** Which ancestor (or the workspace defaults, null) each setting the document in `dir` inherits comes from. */
|
|
225
|
+
export function inheritedOrigins(config: WorkspaceConfig, dir: string, content: PresmiumDocument): SettingOrigins {
|
|
226
|
+
return settingOriginsIn(config.root, join(config.root, dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY), content)
|
|
227
|
+
}
|
|
@@ -61,7 +61,7 @@ export function createDocumentEditor({ editor, revisions, reviewRequired = false
|
|
|
61
61
|
}
|
|
62
62
|
const read = async (document: string, member: Member): Promise<DocumentAnswer> => {
|
|
63
63
|
const { source, content, effective, issues } = readAuthoringDocument(editor, { document, member })
|
|
64
|
-
return { document, version: source.version, fingerprint: fnv1a64(source.content), content, settings: documentSettings(effective), inherited: editor.inherited(document, content), issues }
|
|
64
|
+
return { document, version: source.version, fingerprint: fnv1a64(source.content), content, settings: documentSettings(effective), inherited: editor.inherited(document, content), inheritedFrom: editor.inheritedFrom(document, content), issues }
|
|
65
65
|
}
|
|
66
66
|
const readSelection = <T>(document: string, expected: CanonicalSource | undefined, member: Member, select: (content: PresmiumDocument, source: CanonicalSource) => T): T => {
|
|
67
67
|
if (!hasRole(member, 'editor')) throw new RequestError(403, 'authoring-permission-denied')
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto'
|
|
2
|
-
import { DOCUMENT_ENTRY, DOCUMENT_HISTORY_MAX_FILE_BYTES, DOCUMENT_HISTORY_MAX_REQUEST_CHARS, DOCUMENT_HISTORY_MAX_RESPONSE_CHARS, DOCUMENT_HISTORY_PAGE_SIZE, fnv1a64, hasRole, jsonResponse, problemResponse } from '@lincyaw/kernel'
|
|
2
|
+
import { DOCUMENT_ENTRY, DOCUMENT_HISTORY_MAX_FILE_BYTES, DOCUMENT_SCHEMA_VERSION, DOCUMENT_HISTORY_MAX_REQUEST_CHARS, DOCUMENT_HISTORY_MAX_RESPONSE_CHARS, DOCUMENT_HISTORY_PAGE_SIZE, fnv1a64, hasRole, jsonResponse, problemResponse } from '@lincyaw/kernel'
|
|
3
3
|
import type { DocumentHistory, DocumentHistoryAnswer, DocumentHistoryBinding, DocumentHistoryChange, DocumentHistoryChanged, DocumentHistoryFile, DocumentHistorySource, HistoryRevision, Member, Route } from '@lincyaw/kernel'
|
|
4
4
|
import { validateDocumentHistoryChange, validateDocumentHistoryQuery, validateDocumentHistoryRead } from '@lincyaw/kernel/node'
|
|
5
5
|
import { listDocuments } from './config.ts'
|
|
@@ -74,9 +74,25 @@ export function createDocumentHistory(options: DocumentHistoryOptions): { servic
|
|
|
74
74
|
if (origin === 'agent' && options.reviewRequired) throw new RequestError(409, 'authoring-review-required')
|
|
75
75
|
return { key: JSON.stringify([document, member.id, request.id]), signature: digest(JSON.stringify([which, request.id, request.snapshot, request.source.version, request.source.fingerprint, request.expect])) }
|
|
76
76
|
}
|
|
77
|
-
|
|
77
|
+
// A format upgrade (and a document's creation) is a boundary of its history: taking it back would leave the document
|
|
78
|
+
// without its entry file, or in a format this version no longer opens.
|
|
79
|
+
const supportedAt = async (revision: string, document: string): Promise<boolean> => {
|
|
80
|
+
try {
|
|
81
|
+
const bytes = await history().readFile(revision, entryOf(document), DOCUMENT_HISTORY_MAX_FILE_BYTES)
|
|
82
|
+
const value = JSON.parse(new TextDecoder().decode(bytes)) as { schemaVersion?: unknown }
|
|
83
|
+
return value.schemaVersion === DOCUMENT_SCHEMA_VERSION
|
|
84
|
+
} catch { return false }
|
|
85
|
+
}
|
|
86
|
+
const crossesBoundary = async (document: string, revision: string, paths?: string[]): Promise<boolean> => {
|
|
87
|
+
const files = paths ?? await history().filesOf(revision)
|
|
88
|
+
if (!files.includes(entryOf(document))) return false
|
|
89
|
+
const parent = await history().parentOf(revision)
|
|
90
|
+
return !parent || !await supportedAt(parent, document)
|
|
91
|
+
}
|
|
92
|
+
const targetPaths = async (document: string, request: DocumentHistoryChange, member: Member, which: 'undo' | 'redo' | 'revert') => {
|
|
78
93
|
const paths = await history().filesOf(request.expect)
|
|
79
94
|
if (!paths.length) throw new RequestError(404, 'history-revision-not-found')
|
|
95
|
+
if (which !== 'redo' && await crossesBoundary(document, request.expect, paths)) throw new RequestError(409, 'history-format-boundary')
|
|
80
96
|
for (const path of paths) {
|
|
81
97
|
pathAllowed(document, path, member)
|
|
82
98
|
const owners = await Promise.all([history().ownerAt(request.expect, path), history().ownerAt(`${request.expect}^1`, path)])
|
|
@@ -100,6 +116,10 @@ export function createDocumentHistory(options: DocumentHistoryOptions): { servic
|
|
|
100
116
|
if ((query.offset ?? 0) > 0 && !query.snapshot) throw new RequestError(400, 'history-snapshot-required')
|
|
101
117
|
if (query.snapshot !== undefined && query.snapshot !== before.snapshot) throw new RequestError(409, 'history-snapshot-changed')
|
|
102
118
|
const full = await revisions.historyWithUndo({ document }), changes = full.revisions.filter(entry => !entry.reverts), offset = query.offset ?? 0
|
|
119
|
+
// The upgrade from the earlier format is not offered as a step to undo or revert.
|
|
120
|
+
if (full.undo && await crossesBoundary(document, full.undo)) delete full.undo
|
|
121
|
+
const legacy = `${document ? `${document}/` : ''}lecture.json`
|
|
122
|
+
for (const entry of changes) if (entry.files.includes(legacy) && entry.files.includes(entryOf(document))) entry.revertible = false
|
|
103
123
|
if (offset > changes.length) throw new RequestError(400, 'history-offset-invalid')
|
|
104
124
|
const answer: DocumentHistoryAnswer = { document, available: true, historyBinding: before, revisions: [], ...full.undo ? { undo: full.undo } : {}, ...full.redo ? { redo: full.redo } : {} }
|
|
105
125
|
let index = offset
|
|
@@ -141,7 +161,7 @@ export function createDocumentHistory(options: DocumentHistoryOptions): { servic
|
|
|
141
161
|
if (known && !flight && !sameBinding(await binding(document, member), { source: known.answer.source, snapshot: known.answer.snapshot })) throw new RequestError(409, 'history-result-no-longer-current')
|
|
142
162
|
return
|
|
143
163
|
}
|
|
144
|
-
const paths = await targetPaths(document, request, member)
|
|
164
|
+
const paths = await targetPaths(document, request, member, which)
|
|
145
165
|
if (!sameBinding(await binding(document, member), { source: request.source, snapshot: request.snapshot })) throw new RequestError(409, 'history-source-changed')
|
|
146
166
|
const claimed = locks.claimAll(paths.map(path => documentDirOf(config, path)!), 'revision:revert')
|
|
147
167
|
if ('holder' in claimed) throw lockedError(claimed.document, claimed.holder)
|
|
@@ -161,7 +181,7 @@ export function createDocumentHistory(options: DocumentHistoryOptions): { servic
|
|
|
161
181
|
}
|
|
162
182
|
if (pending.size >= MAX_RECEIPTS) throw new RequestError(429, 'history-busy')
|
|
163
183
|
const work = Promise.resolve().then(async () => {
|
|
164
|
-
const paths = await targetPaths(document, request, member)
|
|
184
|
+
const paths = await targetPaths(document, request, member, which)
|
|
165
185
|
const claimed = locks.claimAll(paths.map(path => documentDirOf(config, path)!), 'revision:revert')
|
|
166
186
|
if ('holder' in claimed) throw lockedError(claimed.document, claimed.holder)
|
|
167
187
|
try {
|
|
@@ -6,7 +6,7 @@ import { setImmediate as yieldToEvents } from 'node:timers/promises'
|
|
|
6
6
|
import { provideDocumentEntries } from '@lincyaw/compiler'
|
|
7
7
|
import type { ScannedDocument } from '@lincyaw/compiler'
|
|
8
8
|
import { blockFirstText, blockSubtree, DOCUMENT_ENTRY, documentCitationSites, documentSearchText, documentTree, isRecord, targetExcerpt } from '@lincyaw/kernel'
|
|
9
|
-
import type { BlockId, DocumentCitation, DocumentId, DocumentLinks, DocumentPlacement, DocumentPreview, DocumentSearchHit, DocumentTree, EmbedSource, OutgoingLink, PlacementTree, PresmiumDocument, ReferenceTarget, SectionId, TrashEntry, TreeIssue, TreeNode } from '@lincyaw/kernel'
|
|
9
|
+
import type { AttentionCount, BlockId, DocumentCitation, DocumentId, DocumentLinks, DocumentPlacement, DocumentPreview, DocumentSearchHit, DocumentTree, EmbedSource, OutgoingLink, PlacementTree, PresmiumDocument, ReferenceTarget, SectionId, TrashEntry, TreeIssue, TreeNode, WorkspaceAttention } from '@lincyaw/kernel'
|
|
10
10
|
import { primeDocumentHead } from './config.ts'
|
|
11
11
|
import type { WorkspaceConfig } from './config.ts'
|
|
12
12
|
|
|
@@ -128,6 +128,9 @@ export class DocumentIndex {
|
|
|
128
128
|
readonly #watchers = new Map<string, FSWatcher>()
|
|
129
129
|
readonly #listeners = new Set<() => void>()
|
|
130
130
|
readonly #titleListeners = new Set<(changed: DocumentId[]) => void>()
|
|
131
|
+
readonly #attentionListeners = new Set<() => void>()
|
|
132
|
+
/** The attention summary of one generation of the index, with its text to tell a change. */
|
|
133
|
+
#attention?: { generation: number, value: WorkspaceAttention, text: string }
|
|
131
134
|
#derived?: Derived
|
|
132
135
|
#dirty = new Set<string>()
|
|
133
136
|
readonly #folders = new Set<string>()
|
|
@@ -166,6 +169,7 @@ export class DocumentIndex {
|
|
|
166
169
|
this.#watchers.clear()
|
|
167
170
|
this.#listeners.clear()
|
|
168
171
|
this.#titleListeners.clear()
|
|
172
|
+
this.#attentionListeners.clear()
|
|
169
173
|
}
|
|
170
174
|
|
|
171
175
|
/** Resolves once everything known to have changed has been read. */
|
|
@@ -355,6 +359,11 @@ export class DocumentIndex {
|
|
|
355
359
|
const titleChanged = changes.flatMap(change => change.after && change.before?.titleKey !== change.after.titleKey ? [change.after.id] : [])
|
|
356
360
|
if (before && treeChanged) for (const listener of [...this.#listeners]) listener()
|
|
357
361
|
if (before && titleChanged.length) for (const listener of [...this.#titleListeners]) listener(titleChanged)
|
|
362
|
+
if (before && this.#attentionListeners.size) {
|
|
363
|
+
const was = this.#attention?.text
|
|
364
|
+
this.attention()
|
|
365
|
+
if (this.#attention!.text !== was) for (const listener of [...this.#attentionListeners]) listener()
|
|
366
|
+
}
|
|
358
367
|
}
|
|
359
368
|
|
|
360
369
|
/** One document changed without changing the tree: only its own entries are replaced. */
|
|
@@ -473,7 +482,10 @@ export class DocumentIndex {
|
|
|
473
482
|
for (const node of tree.order) {
|
|
474
483
|
nodes[node.id] = { id: node.id, title: node.title, path: dirOf(node.path), parent: node.parent, rank: node.placement.rank, depth: node.depth, children: [...tree.children.get(node.id) ?? []], ...issues.has(node.id) ? { issues: issues.get(node.id) } : {} }
|
|
475
484
|
}
|
|
476
|
-
const trash: TrashEntry[] = [...this.#trash.values()].filter(entry => !entry.record.with).map(entry =>
|
|
485
|
+
const trash: TrashEntry[] = [...this.#trash.values()].filter(entry => !entry.record.with).map((entry) => {
|
|
486
|
+
const parent = entry.record.parent
|
|
487
|
+
return { id: entry.id, title: entry.title, deletedAt: entry.record.deletedAt, from: entry.record.from, parent, children: entry.record.children, ...parent !== null && !documents.has(parent) && this.#trash.has(parent) ? { parentTrashed: true } : {} }
|
|
488
|
+
})
|
|
477
489
|
trash.sort((a, b) => a.deletedAt < b.deletedAt ? 1 : a.deletedAt > b.deletedAt ? -1 : 0)
|
|
478
490
|
return derived.clientTree = { roots: [...tree.children.get(null) ?? []], nodes, trash }
|
|
479
491
|
}
|
|
@@ -566,6 +578,36 @@ export class DocumentIndex {
|
|
|
566
578
|
return { document: id, title: document.metadata.title, block, blocks, ...Object.keys(assets).length ? { assets } : {}, ...states ? { states } : {}, ...located.trashed ? { trashed: true } : {} }
|
|
567
579
|
}
|
|
568
580
|
|
|
581
|
+
/**
|
|
582
|
+
* References and synced blocks whose target is gone or in the trash, counted across the workspace. One pass over the
|
|
583
|
+
* references the index keeps, at most once per change of the index.
|
|
584
|
+
*/
|
|
585
|
+
attention(): WorkspaceAttention {
|
|
586
|
+
const { documents, order } = this.#now()
|
|
587
|
+
if (this.#attention?.generation === this.#generation) return this.#attention.value
|
|
588
|
+
const counts = { reference: undefined as AttentionCount | undefined, embed: undefined as AttentionCount | undefined }
|
|
589
|
+
for (const id of order) {
|
|
590
|
+
const entry = documents.get(id)
|
|
591
|
+
if (!entry) continue
|
|
592
|
+
const counted = new Set<'reference' | 'embed'>()
|
|
593
|
+
for (const site of entry.sites) {
|
|
594
|
+
if (this.titleOf(site.target, true) !== undefined) continue
|
|
595
|
+
const count = counts[site.kind] ??= { places: 0, documents: 0, first: { document: id, ...site.section !== undefined ? { section: site.section } : {}, block: site.block } }
|
|
596
|
+
count.places++
|
|
597
|
+
if (!counted.has(site.kind)) { counted.add(site.kind); count.documents++ }
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
const value: WorkspaceAttention = { ...counts.reference ? { references: counts.reference } : {}, ...counts.embed ? { embeds: counts.embed } : {} }
|
|
601
|
+
this.#attention = { generation: this.#generation, value, text: JSON.stringify(value) }
|
|
602
|
+
return value
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/** Called whenever what `attention` answers has changed. */
|
|
606
|
+
onAttention(listener: () => void): () => void {
|
|
607
|
+
this.#attentionListeners.add(listener)
|
|
608
|
+
return () => { this.#attentionListeners.delete(listener) }
|
|
609
|
+
}
|
|
610
|
+
|
|
569
611
|
/** The documents whose references may show an outdated fallback after the titles of `changed` changed: those citing them, and themselves. */
|
|
570
612
|
citing(changed: DocumentId[]): IndexEntry[] {
|
|
571
613
|
const { documents, incoming } = this.#now()
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { existsSync, rmSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { DOCUMENT_ENTRY, DOCUMENT_MATERIALS_DIR, DOCUMENT_MATERIALS_MAX_BYTES, DOCUMENT_MATERIALS_MAX_FILES, hasRole, jsonResponse } from '@lincyaw/kernel'
|
|
4
|
+
import type { DocumentMaterialsAnswer, Route } from '@lincyaw/kernel'
|
|
5
|
+
import type { WorkspaceConfig } from './config.ts'
|
|
6
|
+
import { catchRequestErrors, RequestError } from './errors.ts'
|
|
7
|
+
import type { DocumentLocks } from './locks.ts'
|
|
8
|
+
import type { Revisions } from './revisions.ts'
|
|
9
|
+
import type { DocumentWriter } from './writer.ts'
|
|
10
|
+
|
|
11
|
+
const NAME_MAX = 120
|
|
12
|
+
const bad = (status: number, code: string): never => { throw new RequestError(status, `document-materials-${code}`) }
|
|
13
|
+
|
|
14
|
+
/** A file name that stays one plain name in the materials folder: no folders, control characters or leading dots. */
|
|
15
|
+
function plainName(name: string): string {
|
|
16
|
+
const base = (name.split(/[\\/]/).at(-1) ?? '').replace(/[\u0000-\u001f\u007f:*?"<>|]/g, '').replace(/^[.\s]+/, '').trim()
|
|
17
|
+
if (!base) return 'material'
|
|
18
|
+
if ([...base].length <= NAME_MAX) return base
|
|
19
|
+
const dot = base.lastIndexOf('.'), extension = dot > 0 && base.length - dot <= 12 ? base.slice(dot) : ''
|
|
20
|
+
return [...base.slice(0, base.length - extension.length)].slice(0, NAME_MAX - extension.length).join('') + extension
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** `name`, or `name (2)`, `name (3)`… before its extension, whichever is not taken yet. */
|
|
24
|
+
function freeName(name: string, taken: (name: string) => boolean): string {
|
|
25
|
+
if (!taken(name)) return name
|
|
26
|
+
const dot = name.lastIndexOf('.'), stem = dot > 0 ? name.slice(0, dot) : name, extension = dot > 0 ? name.slice(dot) : ''
|
|
27
|
+
for (let n = 2; ; n++) {
|
|
28
|
+
const next = `${stem} (${n})${extension}`
|
|
29
|
+
if (!taken(next)) return next
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Adds the author's source material (PDF, Word, slides, pictures, text…) to a document: the files are kept as they
|
|
35
|
+
* are in the document's `materials/` folder, under its lock and recorded as one revision, for the AI to write the
|
|
36
|
+
* document from. Nothing in the document refers to them.
|
|
37
|
+
*/
|
|
38
|
+
export function documentMaterialsRoute(options: { config: WorkspaceConfig, writer: DocumentWriter, locks: DocumentLocks, revisions?: Revisions }): Route {
|
|
39
|
+
const { config, writer, locks, revisions } = options
|
|
40
|
+
return {
|
|
41
|
+
role: 'editor',
|
|
42
|
+
maxBody: DOCUMENT_MATERIALS_MAX_BYTES + (1 << 20),
|
|
43
|
+
handle: (request, ctx) => catchRequestErrors(async () => {
|
|
44
|
+
if (request.method !== 'POST') return bad(405, 'method')
|
|
45
|
+
if (!hasRole(ctx.member, 'editor')) return bad(403, 'forbidden')
|
|
46
|
+
const dir = ctx.document
|
|
47
|
+
if (!existsSync(join(config.root, dir, DOCUMENT_ENTRY))) return bad(404, 'document')
|
|
48
|
+
const form = await request.formData().catch(() => bad(400, 'invalid'))
|
|
49
|
+
const uploads = form.getAll('files')
|
|
50
|
+
if (uploads.length === 0 || uploads.some(file => typeof file === 'string')) return bad(400, 'invalid')
|
|
51
|
+
const files = uploads as File[]
|
|
52
|
+
if (files.length > DOCUMENT_MATERIALS_MAX_FILES || files.reduce((sum, file) => sum + file.size, 0) > DOCUMENT_MATERIALS_MAX_BYTES) return bad(413, 'limit')
|
|
53
|
+
const folder = dir ? `${dir}/${DOCUMENT_MATERIALS_DIR}` : DOCUMENT_MATERIALS_DIR
|
|
54
|
+
const release = await locks.acquire(dir, 'document:materials')
|
|
55
|
+
try {
|
|
56
|
+
const write = async (): Promise<DocumentMaterialsAnswer> => {
|
|
57
|
+
const names: string[] = []
|
|
58
|
+
for (const file of files) names.push(freeName(plainName(file.name), name => names.includes(name) || existsSync(join(config.root, folder, name))))
|
|
59
|
+
const paths = names.map(name => `${folder}/${name}`)
|
|
60
|
+
if (revisions && await revisions.ignoresAny(paths)) return bad(403, 'forbidden')
|
|
61
|
+
await revisions?.checkpoint(paths)
|
|
62
|
+
const written: string[] = []
|
|
63
|
+
try {
|
|
64
|
+
for (const [index, file] of files.entries()) {
|
|
65
|
+
request.signal.throwIfAborted()
|
|
66
|
+
await writer.create(paths[index]!, new Uint8Array(await file.arrayBuffer()))
|
|
67
|
+
written.push(paths[index]!)
|
|
68
|
+
}
|
|
69
|
+
const revision = revisions ? await revisions.commitWhileLocked({ paths, summary: `Add source material to ${dir || 'the document'}`, body: names.join('\n'), origin: { kind: 'editor', member: ctx.member } }) : undefined
|
|
70
|
+
return { files: names.map(name => `${DOCUMENT_MATERIALS_DIR}/${name}`), ...revision ? { revision } : {} }
|
|
71
|
+
} catch (error) {
|
|
72
|
+
for (const path of written) rmSync(join(config.root, path), { force: true })
|
|
73
|
+
throw error
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return jsonResponse(await (revisions ? revisions.transaction(write) : write()), 201)
|
|
77
|
+
} finally { release() }
|
|
78
|
+
}),
|
|
79
|
+
}
|
|
80
|
+
}
|
package/src/node/revisions.ts
CHANGED
|
@@ -438,6 +438,13 @@ export class Revisions implements RevisionService {
|
|
|
438
438
|
return this.#git.exclusive(async () => undoTargets(await this.#entries(document))[which])
|
|
439
439
|
}
|
|
440
440
|
|
|
441
|
+
/** The first parent of a revision in the current history; none for the root. */
|
|
442
|
+
async parentOf(id: string): Promise<string | undefined> {
|
|
443
|
+
if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(id)) throw new RequestError(400, 'history-file-invalid')
|
|
444
|
+
const result = await this.#git.tryOutput(['rev-parse', '--verify', '--quiet', `${id}^1`])
|
|
445
|
+
return result.ok ? result.output.trim() || undefined : undefined
|
|
446
|
+
}
|
|
447
|
+
|
|
441
448
|
async head(): Promise<string | undefined> {
|
|
442
449
|
const result = await this.#git.tryOutput(['rev-parse', '--verify', 'HEAD'])
|
|
443
450
|
return result.ok ? result.output.trim() : undefined
|
package/src/node/routes.ts
CHANGED
|
@@ -66,6 +66,7 @@ export interface WorkspaceRoutesOptions {
|
|
|
66
66
|
authoringClientRoutes?: Record<string, Route>
|
|
67
67
|
projectRoutes?: Record<string, Route>
|
|
68
68
|
documentImport?: Route
|
|
69
|
+
documentMaterials?: Route
|
|
69
70
|
workspaceMigrate?: Route
|
|
70
71
|
mcpSettings?: Route
|
|
71
72
|
speechSettings?: Route
|
|
@@ -144,6 +145,7 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
|
|
|
144
145
|
...options.authoringClientRoutes,
|
|
145
146
|
...options.projectRoutes,
|
|
146
147
|
...options.documentImport ? { 'documents/import': options.documentImport } : {},
|
|
148
|
+
...options.documentMaterials ? { 'document/materials': options.documentMaterials } : {},
|
|
147
149
|
...options.workspaceMigrate ? { 'workspace/migrate': options.workspaceMigrate } : {},
|
|
148
150
|
'files': {
|
|
149
151
|
role: 'editor',
|
package/src/node/serve.ts
CHANGED
|
@@ -53,6 +53,7 @@ import { localWriter } from './writer.ts'
|
|
|
53
53
|
import { DocumentIndex } from './document-index.ts'
|
|
54
54
|
import { TreeOperations } from './tree-operations.ts'
|
|
55
55
|
import { documentImportRoute } from './document-import.ts'
|
|
56
|
+
import { documentMaterialsRoute } from './document-materials.ts'
|
|
56
57
|
import { workspaceMigrateRoute } from './workspace-migrate.ts'
|
|
57
58
|
import { hostUpgradeRoute } from './host-upgrade.ts'
|
|
58
59
|
import { createHostActivity } from './host-activity.ts'
|
|
@@ -527,6 +528,7 @@ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
|
|
|
527
528
|
authoringClientRoutes: { ...authoringClients.routes, ...authoringWindows.routes, ...agentActivity.routes },
|
|
528
529
|
projectRoutes: projectAuthoring.routes,
|
|
529
530
|
documentImport: documentImportRoute({ config, writer, locks, revisions: history?.revisions, changed: documentsChanged }),
|
|
531
|
+
documentMaterials: documentMaterialsRoute({ config, writer, locks, revisions: history?.revisions }),
|
|
530
532
|
workspaceMigrate: workspaceMigrateRoute({ config, locks, revisions: history?.revisions, changed: documentsChanged }),
|
|
531
533
|
locks,
|
|
532
534
|
...history ? { revisions: history.revisions, operations: history.operations, reviews: history.agentSessionReviews } : {},
|
|
@@ -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 } from '@lincyaw/kernel'
|
|
6
|
-
import type { ConflictAnswer, DocumentFileChange, FilesAnswer, Member, Revision, SavedAnswer, SourceAnswer, SourceFile, SourceTransactionAnswer, SourceTransactionChange, DocumentDefaults, EffectiveDocument, PresmiumDocument } from '@lincyaw/kernel'
|
|
6
|
+
import type { ConflictAnswer, DocumentFileChange, FilesAnswer, Member, Revision, SavedAnswer, SourceAnswer, SourceFile, SourceTransactionAnswer, SourceTransactionChange, DocumentDefaults, EffectiveDocument, PresmiumDocument, SettingOrigins } from '@lincyaw/kernel'
|
|
7
7
|
import { isWithin } from '../domain/paths.ts'
|
|
8
|
-
import { effectiveContent, inheritedContent, listDocumentEntries, readDocumentSummary } from './config.ts'
|
|
8
|
+
import { effectiveContent, inheritedContent, inheritedOrigins, listDocumentEntries, readDocumentSummary } from './config.ts'
|
|
9
9
|
import type { DocumentEntry, WorkspaceConfig } from './config.ts'
|
|
10
10
|
import { RequestError } from './errors.ts'
|
|
11
11
|
import { checkDocumentText } from './document-check.ts'
|
|
@@ -83,6 +83,11 @@ export class SourceEditor {
|
|
|
83
83
|
return inheritedContent(this.#config, document, content)
|
|
84
84
|
}
|
|
85
85
|
|
|
86
|
+
/** Which ancestor (or the workspace defaults, null) each setting the document in `document` inherits comes from. */
|
|
87
|
+
inheritedFrom(document: string, content: PresmiumDocument): SettingOrigins {
|
|
88
|
+
return inheritedOrigins(this.#config, document, content)
|
|
89
|
+
}
|
|
90
|
+
|
|
86
91
|
scope(document: string): Scope {
|
|
87
92
|
return { document, home: document === '' && !this.#config.singleDeck }
|
|
88
93
|
}
|
|
@@ -189,7 +189,7 @@ export class TreeOperations {
|
|
|
189
189
|
* Runs the operation's changes under the documents' locks and the history's lock, then records them as one revision;
|
|
190
190
|
* on any failure every change is undone and nothing is recorded.
|
|
191
191
|
*/
|
|
192
|
-
async #run(kind: TreeOperation['type'], locked: string[], member: Member, origin: 'editor' | 'agent', work: (journal: Journal) => Promise<{ summary: string, body?: string, documents: DocumentId[], created?: DocumentId, converted?: TreeOperationResult['converted'] }>, automatic = false): Promise<TreeOperationResult> {
|
|
192
|
+
async #run(kind: TreeOperation['type'], locked: string[], member: Member, origin: 'editor' | 'agent', work: (journal: Journal) => Promise<{ summary: string, body?: string, documents: DocumentId[], created?: DocumentId, converted?: TreeOperationResult['converted'], toTopLevel?: TreeOperationResult['toTopLevel'] }>, automatic = false): Promise<TreeOperationResult> {
|
|
193
193
|
const { locks, revisions, index } = this.#options
|
|
194
194
|
await index.ready()
|
|
195
195
|
const before = this.#dirs()
|
|
@@ -219,6 +219,7 @@ export class TreeOperations {
|
|
|
219
219
|
...done.created ? { created: done.created } : {},
|
|
220
220
|
revisions: done.revision ? done.documents.map(document => ({ document, revision: done.revision! })) : [],
|
|
221
221
|
...done.converted?.length ? { converted: done.converted } : {},
|
|
222
|
+
...done.toTopLevel?.length ? { toTopLevel: done.toTopLevel } : {},
|
|
222
223
|
}
|
|
223
224
|
}
|
|
224
225
|
|
|
@@ -308,6 +309,7 @@ export class TreeOperations {
|
|
|
308
309
|
const live = index.scan().documents
|
|
309
310
|
const taken = this.#dirs()
|
|
310
311
|
const restored = new Set(ids)
|
|
312
|
+
const toTopLevel: NonNullable<TreeOperationResult['toTopLevel']> = []
|
|
311
313
|
for (const id of ids) {
|
|
312
314
|
const item = trashed.get(id)!
|
|
313
315
|
const free = (dir: string) => isDocumentDir(this.#options.config, dir) && !existsSync(join(this.#root, dir)) && !taken.some(other => other !== '' && (isWithin(dir, other) || isWithin(other, dir)))
|
|
@@ -321,9 +323,10 @@ export class TreeOperations {
|
|
|
321
323
|
const document = this.#read(dir)
|
|
322
324
|
document.placement = { parent: null, rank: this.#rankAfter(null, (index.scan().tree?.children.get(null) ?? []).at(-1)) }
|
|
323
325
|
await this.#write(journal, dir, document)
|
|
326
|
+
toTopLevel.push({ document: id, parent: trashed.has(parent) ? 'trashed' : 'missing' })
|
|
324
327
|
}
|
|
325
328
|
}
|
|
326
|
-
return { summary: `Restore document ${entry.title}`, documents: ids }
|
|
329
|
+
return { summary: `Restore document ${entry.title}`, documents: ids, toTopLevel }
|
|
327
330
|
})
|
|
328
331
|
}
|
|
329
332
|
case 'purge': {
|
package/src/node/tree-routes.ts
CHANGED
|
@@ -29,8 +29,9 @@ export function treeOperationOf(body: unknown): TreeOperation | undefined {
|
|
|
29
29
|
|
|
30
30
|
/**
|
|
31
31
|
* The document tree's routes (`docs/authoring-actions.md`): the tree with its trash, tree operations, a document's
|
|
32
|
-
* references in both directions, search, a reference's preview card, a synced block's source,
|
|
33
|
-
* sends `{ type: 'tree' }` (event `tree`) whenever the tree or the trash
|
|
32
|
+
* references in both directions, search, a reference's preview card, a synced block's source, what needs attention
|
|
33
|
+
* across the workspace, and `tree/events`, which sends `{ type: 'tree' }` (event `tree`) whenever the tree or the trash
|
|
34
|
+
* changes and `{ type: 'attention' }` whenever what `tree/attention` answers changes.
|
|
34
35
|
*/
|
|
35
36
|
export function treeRoutes(index: DocumentIndex, operations: TreeOperations | undefined): Record<string, Route> {
|
|
36
37
|
const params = (request: Request) => new URL(request.url).searchParams
|
|
@@ -76,11 +77,16 @@ export function treeRoutes(index: DocumentIndex, operations: TreeOperations | un
|
|
|
76
77
|
}),
|
|
77
78
|
'document/preview': get(request => index.preview(required(request, 'id'), { ...optional(request, 'section') !== undefined ? { section: optional(request, 'section') } : {}, ...optional(request, 'block') !== undefined ? { block: optional(request, 'block') } : {} })),
|
|
78
79
|
'embed/source': get(request => index.embedSource(required(request, 'document'), required(request, 'block'))),
|
|
80
|
+
'tree/attention': get(() => index.attention()),
|
|
79
81
|
'tree/events': {
|
|
80
82
|
role: 'reader',
|
|
81
83
|
handle: async (request) => {
|
|
82
84
|
if (request.method !== 'GET') return jsonResponse({ error: 'GET' }, 405)
|
|
83
|
-
const stream = pushStream<{ event: string, data: { type: 'tree' } }>(push
|
|
85
|
+
const stream = pushStream<{ event: string, data: { type: 'tree' | 'attention' } }>((push) => {
|
|
86
|
+
const offTree = index.subscribe(() => push({ event: 'tree', data: { type: 'tree' } }))
|
|
87
|
+
const offAttention = index.onAttention(() => push({ event: 'tree', data: { type: 'attention' } }))
|
|
88
|
+
return () => { offTree(); offAttention() }
|
|
89
|
+
}, { signal: request.signal })
|
|
84
90
|
return sseResponse(stream, request.signal)
|
|
85
91
|
},
|
|
86
92
|
},
|