@crombolo/server 0.69.1 → 0.71.0

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.
Files changed (51) hide show
  1. package/package.json +15 -14
  2. package/src/adapters/blueprints.ts +51 -5
  3. package/src/adapters/change-recording.ts +140 -0
  4. package/src/adapters/content.ts +132 -21
  5. package/src/adapters/documents.ts +26 -5
  6. package/src/adapters/elements.ts +3 -0
  7. package/src/adapters/media.ts +7 -1
  8. package/src/adapters/schema-files.ts +89 -1
  9. package/src/adapters/users.ts +17 -12
  10. package/src/adapters/workspace-dictionary.ts +287 -0
  11. package/src/adapters/workspace-file-port.ts +160 -0
  12. package/src/adapters/workspace-languages.ts +94 -0
  13. package/src/approvals-api.ts +16 -7
  14. package/src/bundle-api.ts +19 -16
  15. package/src/bundle-install.ts +4 -0
  16. package/src/change-transfer.ts +676 -0
  17. package/src/changes-api.ts +258 -0
  18. package/src/component-templates-api.ts +2 -2
  19. package/src/config.ts +195 -21
  20. package/src/content-events.ts +65 -1
  21. package/src/content-operations.ts +22 -3
  22. package/src/core.ts +2 -0
  23. package/src/environment-values-api.ts +161 -0
  24. package/src/external-sign-in.ts +9 -2
  25. package/src/index.ts +1 -0
  26. package/src/managed-users.ts +122 -0
  27. package/src/node-operations.ts +150 -2
  28. package/src/ports.ts +174 -52
  29. package/src/principal.ts +1 -0
  30. package/src/remote-changes.ts +279 -0
  31. package/src/remote-schema.ts +126 -0
  32. package/src/remote-workspaces.ts +82 -0
  33. package/src/remote.ts +289 -192
  34. package/src/schema-transfer.ts +240 -41
  35. package/src/schema.ts +7 -2
  36. package/src/seed/compile.ts +13 -1
  37. package/src/seed/values.ts +3 -0
  38. package/src/server.ts +965 -364
  39. package/src/settings.ts +137 -5
  40. package/src/site-sections.ts +1 -1
  41. package/src/user-admin.ts +2 -0
  42. package/src/workspace-access.ts +152 -0
  43. package/src/workspace-checks.ts +299 -0
  44. package/src/workspace-losses.ts +95 -0
  45. package/src/workspace-processes.ts +306 -0
  46. package/src/workspace-render-child.ts +168 -0
  47. package/src/workspace-schema-dir.ts +100 -0
  48. package/src/workspace-schema.ts +598 -0
  49. package/src/workspace-sites.ts +179 -0
  50. package/src/workspace-views.ts +121 -0
  51. package/src/workspaces.ts +1031 -0
@@ -0,0 +1,598 @@
1
+ /**
2
+ * A workspace's files in the server (stories 376, 377). When a workspace opens,
3
+ * it takes a copy of Shared's schema files, components, stylesheets and scripts,
4
+ * kept by hash; its type rows are built from its schema copy at its first schema
5
+ * save. At merge each file it changed is merged three ways (its copy at open, its
6
+ * own, Shared's now): the schema files synced into Shared on the merge's own
7
+ * transaction, every file then written where it lives, and put back if the merge
8
+ * is undone. A file the site reads only as it starts (`site/`: its package, its
9
+ * config, routes, jobs) is carried to the merge and takes effect there. "Update
10
+ * from Shared" is the same merge the other way. docs/workspaces.md.
11
+ */
12
+ import {
13
+ cpSync,
14
+ existsSync,
15
+ mkdirSync,
16
+ mkdtempSync,
17
+ readdirSync,
18
+ readFileSync,
19
+ rmSync,
20
+ statSync,
21
+ writeFileSync,
22
+ } from 'node:fs'
23
+ import { tmpdir } from 'node:os'
24
+ import { dirname, join, relative, sep } from 'node:path'
25
+ import { costlier } from '@crombolo/core'
26
+ import {
27
+ appendCacheInstruction,
28
+ type ChangeItemInput,
29
+ type Db,
30
+ ensureFormLibraryTypes,
31
+ type NodeSchemaState,
32
+ WorkspaceFileRepository,
33
+ WorkspaceRepository,
34
+ type WorkspaceScope,
35
+ } from '@crombolo/data'
36
+ import {
37
+ type ChangeClass,
38
+ type ChangeItem,
39
+ describeFileChange,
40
+ exportSchemaSet,
41
+ type LoadedSchema,
42
+ loadSchemaDirectory,
43
+ nextSchemaVersion,
44
+ schemaSetFiles,
45
+ syncSchema,
46
+ writeSchemaVersion,
47
+ } from '@crombolo/schema'
48
+ import { merge as mergeLines } from 'node-diff3'
49
+ import { WORKSPACE_SCHEMA_PREFIX } from './adapters/schema-files.ts'
50
+ import {
51
+ applyDictionaryLines,
52
+ mergeDictionaryLines,
53
+ sharedDictionaryLines,
54
+ WORKSPACE_DICTIONARY,
55
+ } from './adapters/workspace-dictionary.ts'
56
+ import { WORKSPACE_FILE_LIMIT } from './adapters/workspace-file-port.ts'
57
+ import { checkComponents } from './components.ts'
58
+ import type { CromboloConfig } from './config.ts'
59
+ import { formTypesFor } from './form-types.ts'
60
+ import { componentAliasesIn, syncOptionsFor } from './schema.ts'
61
+ import { publishSchema, type SchemaStore } from './schema-store.ts'
62
+ import { schemaFilesIn } from './schema-transfer.ts'
63
+ import { withLosses } from './workspace-losses.ts'
64
+
65
+ /** A file both the workspace and Shared changed, where the lines overlap. */
66
+ export interface FileConflict {
67
+ /** A definition by its path in the schema folder; any other file by its full path. */
68
+ path: string
69
+ definition: boolean
70
+ base: string | null
71
+ mine: string | null
72
+ theirs: string | null
73
+ }
74
+
75
+ /** What merging a workspace's files into Shared would write, and what it cannot. */
76
+ export interface FileMergePlan {
77
+ /** By full path in the workspace's list: the merged text, or null to remove it. */
78
+ writes: Record<string, string | null>
79
+ conflicts: FileConflict[]
80
+ /** What the merged components would break (story 377), each saying where. */
81
+ problems: string[]
82
+ /** The greatest class of the workspace's changes to definitions, which the version moves by. */
83
+ change: ChangeClass
84
+ /** Each item of the change against Shared now, with how many pages a lossy one touches (story 382). */
85
+ items: Array<ChangeItem & { pages?: number }>
86
+ /** Shared's text of each written file before the merge, for the change it records (story 381). */
87
+ befores: Record<string, string | null>
88
+ }
89
+
90
+ /** An area of files a workspace holds, besides its definitions (story 377). */
91
+ export interface FileArea {
92
+ prefix: string
93
+ dir: string
94
+ extensions: readonly string[]
95
+ /** Copied as the workspace opens; `site/` is only carried to the merge. */
96
+ copied: boolean
97
+ }
98
+
99
+ /** The areas, as this site has them. */
100
+ export function fileAreasOf(config: CromboloConfig): FileArea[] {
101
+ return [
102
+ {
103
+ prefix: 'components/',
104
+ dir: config.componentsDir,
105
+ extensions: ['.tsx', '.ts'],
106
+ copied: true,
107
+ },
108
+ { prefix: 'stylesheets/', dir: config.stylesheetsDir, extensions: ['.css'], copied: true },
109
+ { prefix: 'scripts/', dir: config.scriptsDir, extensions: ['.js'], copied: true },
110
+ { prefix: 'site/', dir: config.siteDir, extensions: [], copied: false },
111
+ ]
112
+ }
113
+
114
+ /** Files the site reads only as it starts, which a workspace carries to its merge (story 377). */
115
+ export const SITE_FILES =
116
+ /^(package\.json|bun\.lockb?|crombolo\.config\.ts|(routes|jobs|middleware)\/.+\.(ts|tsx|js))$/
117
+
118
+ const RANK: Record<ChangeClass, number> = {
119
+ none: 0,
120
+ additive: 1,
121
+ 'data-requiring': 2,
122
+ breaking: 3,
123
+ }
124
+
125
+ /** Three ways, by line: the merged text, or undefined where the two overlap. */
126
+ export function mergeText(base: string, mine: string, theirs: string): string | undefined {
127
+ const merged = mergeLines(mine.split('\n'), base.split('\n'), theirs.split('\n'), {
128
+ excludeFalseConflicts: true,
129
+ })
130
+ return merged.conflict ? undefined : merged.result.join('\n')
131
+ }
132
+
133
+ /** Three ways for one file, any side possibly absent (null). */
134
+ function mergeFile(
135
+ base: string | null,
136
+ mine: string | null,
137
+ theirs: string | null,
138
+ ): { text: string | null } | undefined {
139
+ if (mine === theirs) return { text: mine }
140
+ if (theirs === base) return { text: mine }
141
+ if (mine === base) return { text: theirs }
142
+ if (base === null || mine === null || theirs === null) return undefined
143
+ const text = mergeText(base, mine, theirs)
144
+ return text === undefined ? undefined : { text }
145
+ }
146
+
147
+ /** Every file of an area on disk, by its `/`-separated path in it; dot folders and packages left out. */
148
+ function filesOfArea(area: FileArea): Map<string, string> {
149
+ const out = new Map<string, string>()
150
+ const walk = (at: string) => {
151
+ if (!existsSync(at)) return
152
+ for (const entry of readdirSync(at, { withFileTypes: true })) {
153
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue
154
+ const path = join(at, entry.name)
155
+ if (entry.isDirectory()) walk(path)
156
+ else if (
157
+ area.extensions.some((e) => entry.name.toLowerCase().endsWith(e)) &&
158
+ statSync(path).size <= WORKSPACE_FILE_LIMIT
159
+ )
160
+ out.set(relative(area.dir, path).split(sep).join('/'), readFileSync(path, 'utf8'))
161
+ }
162
+ }
163
+ walk(area.dir)
164
+ return out
165
+ }
166
+
167
+ export function createWorkspaceSchema(
168
+ db: Db,
169
+ config: CromboloConfig,
170
+ boot: { nodeId: string; nodeState: NodeSchemaState },
171
+ ) {
172
+ const formTypes = formTypesFor(config)
173
+ const areas = fileAreasOf(config)
174
+ const unprefixed = (files: ReadonlyMap<string, string>) =>
175
+ new Map([...files].map(([path, text]) => [path.slice(WORKSPACE_SCHEMA_PREFIX.length), text]))
176
+ const areaOf = (key: string) => areas.find((a) => key.startsWith(a.prefix))
177
+ /** A path as people read it: a definition by its place in the schema folder. */
178
+ const shown = (key: string) =>
179
+ key.startsWith(WORKSPACE_SCHEMA_PREFIX) ? key.slice(WORKSPACE_SCHEMA_PREFIX.length) : key
180
+ /** A path as a person names it, back to its key in the workspace's list. */
181
+ const keyFor = (path: string) =>
182
+ areaOf(path) || path.startsWith(WORKSPACE_SCHEMA_PREFIX) || path === WORKSPACE_DICTIONARY
183
+ ? path
184
+ : `${WORKSPACE_SCHEMA_PREFIX}${path}`
185
+
186
+ /** Shared's schema files now: the folder's, or, where there is none, the database's. */
187
+ async function sharedFiles(handle: Db = db): Promise<Map<string, string>> {
188
+ if (existsSync(config.schemaDir)) return schemaFilesIn(config.schemaDir)
189
+ return schemaSetFiles(await exportSchemaSet(handle, boot.nodeState.version))
190
+ }
191
+
192
+ /** The dictionary merges by item (story 392); every other file by line. */
193
+ const mergeOf = (key: string, base: string | null, mine: string | null, now: string | null) =>
194
+ key === WORKSPACE_DICTIONARY
195
+ ? mergeDictionaryLines(base, mine, now)
196
+ : mergeFile(base, mine, now)
197
+
198
+ /** Every file a workspace copies, as Shared has it now, by its key. */
199
+ async function sharedCopied(handle: Db = db): Promise<Map<string, string>> {
200
+ const out = new Map<string, string>()
201
+ for (const [path, text] of await sharedFiles(handle))
202
+ out.set(`${WORKSPACE_SCHEMA_PREFIX}${path}`, text)
203
+ for (const area of areas.filter((a) => a.copied))
204
+ for (const [path, text] of filesOfArea(area)) out.set(`${area.prefix}${path}`, text)
205
+ return out
206
+ }
207
+
208
+ /** One file as Shared has it now, by its key; null where there is none. */
209
+ const sharedText = (key: string, schema: ReadonlyMap<string, string>): string | null => {
210
+ if (key.startsWith(WORKSPACE_SCHEMA_PREFIX))
211
+ return schema.get(key.slice(WORKSPACE_SCHEMA_PREFIX.length)) ?? null
212
+ const area = areaOf(key)
213
+ if (!area) return null
214
+ const file = join(area.dir, ...key.slice(area.prefix.length).split('/'))
215
+ return existsSync(file) ? readFileSync(file, 'utf8') : null
216
+ }
217
+
218
+ /** Files loaded as a sync reads them, from a folder made for them and then removed. */
219
+ function loaded(files: ReadonlyMap<string, string>): LoadedSchema {
220
+ const dir = mkdtempSync(join(tmpdir(), 'crombolo-workspace-schema-'))
221
+ try {
222
+ for (const [path, text] of files) {
223
+ mkdirSync(dirname(join(dir, path)), { recursive: true })
224
+ writeFileSync(join(dir, path), text)
225
+ }
226
+ return loadSchemaDirectory(dir, { formTypes })
227
+ } finally {
228
+ rmSync(dir, { recursive: true, force: true })
229
+ }
230
+ }
231
+
232
+ /**
233
+ * What Shared's components would be with the merge's laid over them: compiled
234
+ * and imported, as a render does, so a component that no longer works with
235
+ * Shared's is found before anything is written (story 377).
236
+ */
237
+ async function componentProblems(writes: Record<string, string | null>): Promise<string[]> {
238
+ const area = areas.find((a) => a.prefix === 'components/') as FileArea
239
+ const own = Object.entries(writes).filter(([key]) => key.startsWith(area.prefix))
240
+ if (own.length === 0) return []
241
+ mkdirSync(join(process.cwd(), 'output'), { recursive: true })
242
+ const dir = mkdtempSync(join(process.cwd(), 'output', 'workspace-merge-views-'))
243
+ try {
244
+ const components = join(dir, 'components')
245
+ if (existsSync(area.dir)) cpSync(area.dir, components, { recursive: true })
246
+ else mkdirSync(components, { recursive: true })
247
+ for (const [key, text] of own) {
248
+ const target = join(components, ...key.slice(area.prefix.length).split('/'))
249
+ if (text === null) rmSync(target, { force: true })
250
+ else {
251
+ mkdirSync(dirname(target), { recursive: true })
252
+ writeFileSync(target, text)
253
+ }
254
+ }
255
+ const report = await checkComponents({ componentsDir: components, siteDir: dir })
256
+ return report.problems.map((p) => `${p.file}: ${p.message}`)
257
+ } finally {
258
+ rmSync(dir, { recursive: true, force: true })
259
+ }
260
+ }
261
+
262
+ /** How many of Shared's pages hold a value for a type's property: what a lossy change costs. */
263
+ async function pagesHolding(handle: Db, type: string, property: string): Promise<number> {
264
+ const rows = await handle.q
265
+ .selectFrom('property_value as pv')
266
+ .innerJoin('property_type as p', 'p.id', 'pv.property_type_id')
267
+ .innerJoin('content_type as ct', 'ct.node_id', 'p.content_type_id')
268
+ .select((eb) => eb.fn.count<number>('pv.node_id').distinct().as('n'))
269
+ .where('ct.alias', '=', type)
270
+ .where('ct.workspace_id', 'is', null)
271
+ .where('p.alias', '=', property)
272
+ .where('pv.workspace_id', 'is', null)
273
+ .where('pv.is_current', '=', handle.dialect.boolValue(true) as boolean)
274
+ .execute()
275
+ return Number(rows[0]?.n ?? 0)
276
+ }
277
+
278
+ /** Writes the workspace's rows from its files, as a sync of its own. */
279
+ async function build(workspace: WorkspaceScope, handle: Db = db): Promise<void> {
280
+ const files = unprefixed(
281
+ await new WorkspaceFileRepository(handle).files(workspace.id, WORKSPACE_SCHEMA_PREFIX),
282
+ )
283
+ const report = await syncSchema(
284
+ handle,
285
+ loaded(files),
286
+ { nodeId: boot.nodeId, version: boot.nodeState.version, revision: boot.nodeState.revision },
287
+ {
288
+ ...syncOptionsFor(config),
289
+ componentAliases: componentAliasesIn(config.componentsDir),
290
+ workspace,
291
+ },
292
+ )
293
+ if (report.action === 'refused')
294
+ throw new Error(`The workspace's definitions cannot be used: ${report.reason ?? ''}`)
295
+ await new WorkspaceRepository(handle).setSchemaBuilt(workspace.id, true)
296
+ }
297
+
298
+ /** Writes files where they live, returning how to put them back. */
299
+ function writeOut(entries: ReadonlyArray<[string, string | null]>): () => void {
300
+ const before = new Map<string, string | undefined>()
301
+ for (const [target, text] of entries) {
302
+ before.set(target, existsSync(target) ? readFileSync(target, 'utf8') : undefined)
303
+ if (text === null) rmSync(target, { force: true })
304
+ else {
305
+ mkdirSync(dirname(target), { recursive: true })
306
+ writeFileSync(target, text)
307
+ }
308
+ }
309
+ return () => {
310
+ for (const [target, text] of before)
311
+ if (text === undefined) rmSync(target, { force: true })
312
+ else writeFileSync(target, text)
313
+ }
314
+ }
315
+
316
+ return {
317
+ sharedFiles,
318
+ shown,
319
+
320
+ /** A file as Shared has it now, by its full path: a definition's, or any other's. */
321
+ async textNow(key: string): Promise<string | null> {
322
+ return sharedText(key, await sharedFiles())
323
+ },
324
+
325
+ /** Takes Shared's files as the workspace's copy, as it opens. */
326
+ async snapshot(workspaceId: number): Promise<void> {
327
+ await new WorkspaceFileRepository(db).snapshot(workspaceId, await sharedCopied())
328
+ },
329
+
330
+ /** Builds the workspace's rows the first time it changes its schema. */
331
+ async ensureBuilt(workspace: WorkspaceScope): Promise<void> {
332
+ if (await new WorkspaceRepository(db).schemaBuilt(workspace.id)) return
333
+ await build(workspace)
334
+ },
335
+
336
+ build,
337
+
338
+ /** Carries a file the site reads only as it starts to the merge (story 377). */
339
+ async carry(workspaceId: number, path: string, text: string | null): Promise<boolean> {
340
+ if (!SITE_FILES.test(path)) return false
341
+ const store = new WorkspaceFileRepository(db)
342
+ const key = `site/${path}`
343
+ const known = (await store.changes(workspaceId, key)).find((c) => c.path === key)
344
+ const base = known ? known.base : sharedText(key, new Map())
345
+ await store.rebase(workspaceId, key, base, text)
346
+ return true
347
+ },
348
+
349
+ /** Each changed file merged with Shared's now: what would be written, and what conflicts. */
350
+ async plan(workspaceId: number, handle: Db = db): Promise<FileMergePlan> {
351
+ const changes = await new WorkspaceFileRepository(handle).changes(workspaceId)
352
+ const schema = await sharedFiles(handle)
353
+ // Story 392: Shared's dictionary is rows, read as the workspace's file holds it.
354
+ const dictionary = changes.some((c) => c.path === WORKSPACE_DICTIONARY)
355
+ ? await sharedDictionaryLines(handle)
356
+ : null
357
+ const nowOf = (key: string) =>
358
+ key === WORKSPACE_DICTIONARY ? dictionary : sharedText(key, schema)
359
+ const writes: Record<string, string | null> = {}
360
+ const conflicts: FileConflict[] = []
361
+ let change: ChangeClass = 'none'
362
+ for (const c of changes) {
363
+ const now = nowOf(c.path)
364
+ const merged = mergeOf(c.path, c.base, c.now, now)
365
+ const definition = c.path.startsWith(WORKSPACE_SCHEMA_PREFIX)
366
+ if (!merged) {
367
+ conflicts.push({
368
+ path: shown(c.path),
369
+ definition,
370
+ base: c.base,
371
+ mine: c.now,
372
+ theirs: now,
373
+ })
374
+ continue
375
+ }
376
+ if (merged.text !== now) writes[c.path] = merged.text
377
+ if (!definition) continue
378
+ const own = (c.class ?? 'additive') as ChangeClass
379
+ if (RANK[own] > RANK[change]) change = own
380
+ }
381
+ // What each written file's change is, against Shared now, and what a lossy one costs.
382
+ const items: FileMergePlan['items'] = []
383
+ for (const [key, text] of Object.entries(writes))
384
+ for (const found of describeFileChange(shown(key), nowOf(key), text, {
385
+ definition: key.startsWith(WORKSPACE_SCHEMA_PREFIX),
386
+ }))
387
+ items.push(
388
+ found.class === 'breaking' && found.type && found.property
389
+ ? { ...found, pages: await pagesHolding(handle, found.type, found.property) }
390
+ : found,
391
+ )
392
+ const befores: Record<string, string | null> = {}
393
+ for (const key of Object.keys(writes)) befores[key] = nowOf(key)
394
+ const costed = await withLosses(handle, items)
395
+ for (const found of costed)
396
+ if (RANK[found.class as ChangeClass] > RANK[change]) change = found.class as ChangeClass
397
+ return {
398
+ writes,
399
+ conflicts,
400
+ problems: await componentProblems(writes),
401
+ change,
402
+ items: costed,
403
+ befores,
404
+ }
405
+ },
406
+
407
+ /**
408
+ * Syncs the merged definitions into Shared on `tx`, the merge's transaction,
409
+ * then writes every merged file where it lives; what it returns puts them back,
410
+ * for when the merge is undone after.
411
+ */
412
+ async apply(
413
+ tx: Db,
414
+ plan: FileMergePlan,
415
+ ): Promise<{ restore(): void; after(): Promise<void>; items: ChangeItemInput[] }> {
416
+ const restores: Array<() => void> = []
417
+ // Each file as the change records it (story 381): its text before and after.
418
+ const items: ChangeItemInput[] = Object.entries(plan.writes).map(([key, text]) => {
419
+ const before = plan.befores[key] ?? null
420
+ const own = describeFileChange(shown(key), before, text, {
421
+ definition: key.startsWith(WORKSPACE_SCHEMA_PREFIX),
422
+ })
423
+ return {
424
+ path: key,
425
+ kind: before === null ? 'file-added' : text === null ? 'file-removed' : 'file-changed',
426
+ class: own.reduce<ChangeClass>((worst, i) => costlier(worst, i.class), 'none'),
427
+ before,
428
+ after: text,
429
+ }
430
+ })
431
+ const definitions = Object.entries(plan.writes).filter(([key]) =>
432
+ key.startsWith(WORKSPACE_SCHEMA_PREFIX),
433
+ )
434
+ let publish = false
435
+ if (definitions.length > 0) {
436
+ const files = await sharedFiles(tx)
437
+ for (const [key, text] of definitions) {
438
+ const path = key.slice(WORKSPACE_SCHEMA_PREFIX.length)
439
+ if (text === null) files.delete(path)
440
+ else files.set(path, text)
441
+ }
442
+ const version = loaded(files).set.version
443
+ const next = nextSchemaVersion(version, plan.change === 'none' ? 'additive' : plan.change)
444
+ files.set(
445
+ 'schema.toml',
446
+ writeSchemaVersion(next, loaded(files).set.urls, loaded(files).set.environments),
447
+ )
448
+ // Story 392: the Library's types made from forms follow them, as a sync's do.
449
+ if (definitions.some(([key]) => key.startsWith(`${WORKSPACE_SCHEMA_PREFIX}forms/`)))
450
+ await ensureFormLibraryTypes(tx, loaded(files).set.forms ?? [])
451
+ const report = await syncSchema(
452
+ tx,
453
+ loaded(files),
454
+ { nodeId: boot.nodeId, version: next, revision: config.schemaRevision },
455
+ { ...syncOptionsFor(config), componentAliases: componentAliasesIn(config.componentsDir) },
456
+ )
457
+ if (report.action !== 'applied')
458
+ throw new FileMergeRefused(
459
+ `Shared's definitions would not take the workspace's: ${report.reason ?? report.action}`,
460
+ )
461
+ // This node runs the new state from here, or its own page writes are refused;
462
+ // an undone merge puts it back.
463
+ const was = { version: boot.nodeState.version, revision: boot.nodeState.revision }
464
+ boot.nodeState.version = next
465
+ boot.nodeState.revision = config.schemaRevision
466
+ restores.push(() => {
467
+ boot.nodeState.version = was.version
468
+ boot.nodeState.revision = was.revision
469
+ })
470
+ if (existsSync(config.schemaDir) && config.schemaWritable) {
471
+ restores.push(
472
+ writeOut([
473
+ ...definitions.map(
474
+ ([key, text]) =>
475
+ [join(config.schemaDir, ...shown(key).split('/')), text] as [
476
+ string,
477
+ string | null,
478
+ ],
479
+ ),
480
+ [join(config.schemaDir, 'schema.toml'), files.get('schema.toml') ?? null],
481
+ ]),
482
+ )
483
+ publish = true
484
+ }
485
+ }
486
+ const others = Object.entries(plan.writes).flatMap(([key, text]) => {
487
+ const area = areaOf(key)
488
+ return area
489
+ ? [
490
+ [join(area.dir, ...key.slice(area.prefix.length).split('/')), text] as [
491
+ string,
492
+ string | null,
493
+ ],
494
+ ]
495
+ : []
496
+ })
497
+ if (others.length > 0) restores.push(writeOut(others))
498
+ // Story 392: the dictionary goes into Shared's rows, with the merge.
499
+ const dictionary = plan.writes[WORKSPACE_DICTIONARY]
500
+ if (typeof dictionary === 'string') await applyDictionaryLines(tx, dictionary)
501
+ const views = Object.keys(plan.writes).some((key) => key.startsWith('components/'))
502
+ return {
503
+ items,
504
+ restore() {
505
+ for (const undo of restores.reverse()) undo()
506
+ },
507
+ async after() {
508
+ if (publish && config.schemaStore)
509
+ await publishSchema(config.schemaStore as SchemaStore, config.schemaDir)
510
+ // Every node, this one included, takes a new generation of the views.
511
+ if (views)
512
+ await appendCacheInstruction(db, {
513
+ kind: 'components',
514
+ payload: { from: 'workspace-merge' },
515
+ by: `${boot.nodeId}:merge`,
516
+ })
517
+ },
518
+ }
519
+ },
520
+
521
+ /**
522
+ * Shared's changes since the copy brought into the workspace (story 380's
523
+ * "update from Shared"): each file Shared changed is merged with the
524
+ * workspace's; where the two overlap the workspace keeps its own and the file
525
+ * stays a conflict for its merge to answer. Its rows are built again.
526
+ */
527
+ async updateFromShared(workspace: WorkspaceScope): Promise<{
528
+ updated: string[]
529
+ conflicts: FileConflict[]
530
+ }> {
531
+ const store = new WorkspaceFileRepository(db)
532
+ const theirs = await sharedCopied()
533
+ const all = await store.files(workspace.id)
534
+ if (all.has(WORKSPACE_DICTIONARY))
535
+ theirs.set(WORKSPACE_DICTIONARY, await sharedDictionaryLines(db))
536
+ const own = new Map([...all].filter(([key]) => !key.startsWith('site/')))
537
+ const bases = new Map<string, string | null>()
538
+ for (const c of await store.changes(workspace.id)) bases.set(c.path, c.base)
539
+ const updated: string[] = []
540
+ const conflicts: FileConflict[] = []
541
+ for (const key of new Set([...theirs.keys(), ...own.keys(), ...bases.keys()])) {
542
+ if (key.startsWith('site/')) continue
543
+ const mine = own.get(key) ?? null
544
+ const base = bases.has(key) ? (bases.get(key) ?? null) : mine
545
+ const now = theirs.get(key) ?? null
546
+ if (now === base) continue
547
+ const merged = mergeOf(key, base, mine, now)
548
+ if (!merged) {
549
+ conflicts.push({
550
+ path: shown(key),
551
+ definition: key.startsWith(WORKSPACE_SCHEMA_PREFIX),
552
+ base,
553
+ mine,
554
+ theirs: now,
555
+ })
556
+ continue
557
+ }
558
+ await store.rebase(workspace.id, key, now, merged.text)
559
+ updated.push(shown(key))
560
+ }
561
+ if (
562
+ updated.some((path) => keyFor(path).startsWith(WORKSPACE_SCHEMA_PREFIX)) &&
563
+ (await new WorkspaceRepository(db).schemaBuilt(workspace.id))
564
+ )
565
+ await build(workspace)
566
+ return { updated, conflicts }
567
+ },
568
+
569
+ /** Answers a file's conflict: the workspace's, Shared's, or a text written for it. */
570
+ async resolve(
571
+ workspace: WorkspaceScope,
572
+ path: string,
573
+ answer: { side: 'mine' | 'theirs' } | { text: string },
574
+ ): Promise<boolean> {
575
+ const key = keyFor(path)
576
+ const store = new WorkspaceFileRepository(db)
577
+ const theirs =
578
+ key === WORKSPACE_DICTIONARY
579
+ ? await sharedDictionaryLines(db)
580
+ : sharedText(key, await sharedFiles())
581
+ const mine = (await store.files(workspace.id)).get(key) ?? null
582
+ const text = 'text' in answer ? answer.text : answer.side === 'mine' ? mine : theirs
583
+ if ('text' in answer && /^(<{7}|={7}|>{7})/m.test(answer.text)) return false
584
+ await store.rebase(workspace.id, key, theirs, text)
585
+ if (
586
+ key.startsWith(WORKSPACE_SCHEMA_PREFIX) &&
587
+ (await new WorkspaceRepository(db).schemaBuilt(workspace.id))
588
+ )
589
+ await build(workspace)
590
+ return true
591
+ },
592
+ }
593
+ }
594
+
595
+ export type WorkspaceSchema = ReturnType<typeof createWorkspaceSchema>
596
+
597
+ /** Shared's definitions refused the workspace's: the merge is undone. */
598
+ export class FileMergeRefused extends Error {}