@lincyaw/workspace 1.0.0-rc.110 → 1.0.0-rc.112
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/document-import.ts +120 -0
- package/src/node/revisions.ts +8 -0
- package/src/node/routes.ts +2 -0
- package/src/node/serve.ts +2 -0
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.112",
|
|
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/
|
|
38
|
-
"@lincyaw/design": "1.0.0-rc.
|
|
39
|
-
"@lincyaw/
|
|
40
|
-
"@lincyaw/
|
|
37
|
+
"@lincyaw/kernel": "1.0.0-rc.112",
|
|
38
|
+
"@lincyaw/design": "1.0.0-rc.112",
|
|
39
|
+
"@lincyaw/compiler": "1.0.0-rc.112",
|
|
40
|
+
"@lincyaw/server": "1.0.0-rc.112"
|
|
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.112"
|
|
45
45
|
}
|
|
46
46
|
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { tmpdir } from 'node:os'
|
|
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'
|
|
7
|
+
import type { DocumentImportAnswer, Route } from '@lincyaw/kernel'
|
|
8
|
+
import { parse, stringify } from 'yaml'
|
|
9
|
+
import { readWorkspaceConfig } from './config.ts'
|
|
10
|
+
import type { WorkspaceConfig } from './config.ts'
|
|
11
|
+
import { catchRequestErrors, RequestError } from './errors.ts'
|
|
12
|
+
import type { DocumentLocks } from './locks.ts'
|
|
13
|
+
import type { Revisions } from './revisions.ts'
|
|
14
|
+
import { writeChanges } from './writer.ts'
|
|
15
|
+
import type { DocumentWriter } from './writer.ts'
|
|
16
|
+
import type { DocumentsChange } from './document-operations.ts'
|
|
17
|
+
|
|
18
|
+
const bad = (status: number, code: string): never => { throw new RequestError(status, `document-import-${code}`) }
|
|
19
|
+
const plainPath = (path: unknown): path is string => typeof path === 'string' && path.length > 0 && path.length <= 500
|
|
20
|
+
&& !path.startsWith('/') && !/[\\\0:]/.test(path) && !path.split('/').some(part => !part || part === '.' || part === '..' || ['.git', '.presmium', 'node_modules', 'dist'].includes(part))
|
|
21
|
+
|
|
22
|
+
/** Uploaded sources are converted before a single locked, rollback-capable workspace publication. */
|
|
23
|
+
export function documentImportRoute(options: { config: WorkspaceConfig, writer: DocumentWriter, locks: DocumentLocks, revisions?: Revisions, changed(change: DocumentsChange): Promise<void> }): Route {
|
|
24
|
+
const { config, writer, locks, revisions } = options
|
|
25
|
+
return {
|
|
26
|
+
role: 'owner', maxBody: DOCUMENT_IMPORT_MAX_BYTES + (1 << 20),
|
|
27
|
+
handle: (request, ctx) => catchRequestErrors(async () => {
|
|
28
|
+
if (request.method !== 'POST') return bad(405, 'method')
|
|
29
|
+
if (!hasRole(ctx.member, 'owner') || ctx.document !== '') return bad(403, 'forbidden')
|
|
30
|
+
if (config.singleDeck || !revisions) return bad(409, 'unavailable')
|
|
31
|
+
const form = await request.formData().catch(() => bad(400, 'invalid'))
|
|
32
|
+
const raw = form.get('paths')
|
|
33
|
+
if (typeof raw !== 'string' || raw.length > 512_000) return bad(400, 'invalid')
|
|
34
|
+
let paths: unknown
|
|
35
|
+
try { paths = JSON.parse(raw) } catch { return bad(400, 'invalid') }
|
|
36
|
+
const uploads = form.getAll('files')
|
|
37
|
+
if (!Array.isArray(paths) || paths.length === 0 || paths.length > DOCUMENT_IMPORT_MAX_FILES || paths.length !== uploads.length || !paths.every(plainPath)) return bad(400, 'invalid')
|
|
38
|
+
if (new Set(paths.map(path => path.toLowerCase())).size !== paths.length) return bad(400, 'invalid')
|
|
39
|
+
if (uploads.some(file => typeof file === 'string') || uploads.reduce((sum, file) => sum + (typeof file === 'string' ? 0 : file.size), 0) > DOCUMENT_IMPORT_MAX_BYTES) return bad(413, 'limit')
|
|
40
|
+
const temporary = mkdtempSync(join(tmpdir(), 'presmium-import-'))
|
|
41
|
+
try {
|
|
42
|
+
const source = join(temporary, 'source'), output = join(temporary, 'output')
|
|
43
|
+
mkdirSync(source)
|
|
44
|
+
for (const [index, path] of paths.entries()) {
|
|
45
|
+
const file = uploads[index] as File
|
|
46
|
+
request.signal.throwIfAborted()
|
|
47
|
+
mkdirSync(dirname(join(source, path)), { recursive: true })
|
|
48
|
+
writeFileSync(join(source, path), Buffer.from(await file.arrayBuffer()), { flag: 'wx' })
|
|
49
|
+
}
|
|
50
|
+
const report = await importDocuments(source, { out: output, preserveOriginal: true }).catch(() => bad(422, 'conversion'))
|
|
51
|
+
if (report.documents.length === 0) return bad(422, 'empty')
|
|
52
|
+
const files: { path: string, content: Buffer }[] = []
|
|
53
|
+
let bytes = 0
|
|
54
|
+
const walk = (dir: string, path = '') => {
|
|
55
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
56
|
+
const rel = path ? `${path}/${entry.name}` : entry.name
|
|
57
|
+
if (entry.isDirectory()) walk(join(dir, entry.name), rel)
|
|
58
|
+
else {
|
|
59
|
+
const content = readFileSync(join(dir, entry.name))
|
|
60
|
+
if (files.length >= DOCUMENT_IMPORT_MAX_FILES || (bytes += content.byteLength) > DOCUMENT_IMPORT_MAX_BYTES) bad(413, 'limit')
|
|
61
|
+
files.push({ path: rel, content })
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
walk(output)
|
|
66
|
+
const documents = report.documents.map(dir => {
|
|
67
|
+
const checked = validateDocument(JSON.parse(readFileSync(join(output, dir, DOCUMENT_ENTRY), 'utf8')))
|
|
68
|
+
if (!checked.document || checked.issues.some(issue => issue.severity === 'error')) return bad(422, 'conversion')
|
|
69
|
+
checked.document.id = randomUUID()
|
|
70
|
+
files.find(file => file.path === `${dir}/${DOCUMENT_ENTRY}`)!.content = Buffer.from(`${JSON.stringify(checked.document, null, 2)}\n`)
|
|
71
|
+
return { dir, title: checked.document.metadata.title }
|
|
72
|
+
})
|
|
73
|
+
const release = await locks.acquire('', 'document:import')
|
|
74
|
+
try {
|
|
75
|
+
const answer = await revisions.transaction(async (): Promise<DocumentImportAnswer> => {
|
|
76
|
+
request.signal.throwIfAborted()
|
|
77
|
+
const directory = `imported-${randomUUID().slice(0, 8)}`
|
|
78
|
+
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])
|
|
94
|
+
const before = await revisions.head()
|
|
95
|
+
let committed = false
|
|
96
|
+
try {
|
|
97
|
+
for (const item of files) { request.signal.throwIfAborted(); await writer.create(`${directory}/${item.path}`, item.content, true) }
|
|
98
|
+
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 } } })
|
|
103
|
+
if (!revision) return bad(409, 'changed')
|
|
104
|
+
committed = true
|
|
105
|
+
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
|
+
} catch (error) {
|
|
107
|
+
if (await revisions.head() !== before) { committed = true; throw new RequestError(409, 'document-import-changed', { committed: true }) }
|
|
108
|
+
await checkpoint.restore()
|
|
109
|
+
config.documents.splice(0, config.documents.length, ...previous)
|
|
110
|
+
throw error
|
|
111
|
+
} finally { if (committed || await revisions.head() === before) checkpoint.dispose() }
|
|
112
|
+
})
|
|
113
|
+
try { await options.changed({ removed: [], added: answer.documents.map(doc => doc.dir) }) }
|
|
114
|
+
catch { throw new RequestError(409, 'document-import-changed', { committed: true }) }
|
|
115
|
+
return jsonResponse(answer, 201)
|
|
116
|
+
} finally { release() }
|
|
117
|
+
} finally { rmSync(temporary, { recursive: true, force: true }) }
|
|
118
|
+
}),
|
|
119
|
+
}
|
|
120
|
+
}
|
package/src/node/revisions.ts
CHANGED
|
@@ -574,6 +574,14 @@ export class Revisions implements RevisionService {
|
|
|
574
574
|
})
|
|
575
575
|
}
|
|
576
576
|
|
|
577
|
+
/** Checks a whole import before writing; one Git process regardless of file count. */
|
|
578
|
+
async ignoresAny(paths: string[]): Promise<boolean> {
|
|
579
|
+
if (!paths.length) return false
|
|
580
|
+
const answer = await this.#git.run(['check-ignore', '-z', '--stdin'], {}, Buffer.from(paths.map(path => `${path}\0`).join('')))
|
|
581
|
+
if (answer.code > 1) throw new Error('history-ignore-check-failed')
|
|
582
|
+
return answer.code === 0
|
|
583
|
+
}
|
|
584
|
+
|
|
577
585
|
/** Whether git ignores the path, which a commit then leaves out. */
|
|
578
586
|
async ignores(path: string): Promise<boolean> {
|
|
579
587
|
return (await this.#git.run(['check-ignore', '-q', '--', path])).code === 0
|
package/src/node/routes.ts
CHANGED
|
@@ -61,6 +61,7 @@ export interface WorkspaceRoutesOptions {
|
|
|
61
61
|
historyRoutes?: Record<string, Route>
|
|
62
62
|
authoringClientRoutes?: Record<string, Route>
|
|
63
63
|
projectRoutes?: Record<string, Route>
|
|
64
|
+
documentImport?: Route
|
|
64
65
|
mcpSettings?: Route
|
|
65
66
|
speechSettings?: Route
|
|
66
67
|
changesRoutes?: Record<string, Route>
|
|
@@ -130,6 +131,7 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
|
|
|
130
131
|
...(options.historyRoutes ?? ownedHistory!.routes),
|
|
131
132
|
...options.authoringClientRoutes,
|
|
132
133
|
...options.projectRoutes,
|
|
134
|
+
...options.documentImport ? { 'documents/import': options.documentImport } : {},
|
|
133
135
|
'files': {
|
|
134
136
|
role: 'editor',
|
|
135
137
|
handle: (request, ctx) => catchRequestErrors(async () => {
|
package/src/node/serve.ts
CHANGED
|
@@ -50,6 +50,7 @@ import type { DocumentVoiceServices } from './document-voice.ts'
|
|
|
50
50
|
import { createWorkbenchBackend } from './workbench-api.ts'
|
|
51
51
|
import type { WorkbenchBackend } from './workbench-api.ts'
|
|
52
52
|
import { localWriter } from './writer.ts'
|
|
53
|
+
import { documentImportRoute } from './document-import.ts'
|
|
53
54
|
|
|
54
55
|
export interface ServeOptions {
|
|
55
56
|
dir: string
|
|
@@ -494,6 +495,7 @@ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
|
|
|
494
495
|
historyRoutes: documentHistory.routes,
|
|
495
496
|
authoringClientRoutes: { ...authoringClients.routes, ...authoringWindows.routes, ...agentActivity.routes },
|
|
496
497
|
projectRoutes: projectAuthoring.routes,
|
|
498
|
+
documentImport: documentImportRoute({ config, writer, locks, revisions: history?.revisions, changed: documentsChanged }),
|
|
497
499
|
locks,
|
|
498
500
|
...history ? { revisions: history.revisions, operations: history.operations, reviews: history.agentSessionReviews } : {},
|
|
499
501
|
documentsChanged,
|