@crombolo/content 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/content",
3
- "version": "0.69.1",
3
+ "version": "0.71.0",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The rules every page, media and Library write follows, whoever starts it: who may, where it may go, approvals, and what it announces. No transport.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -29,7 +29,7 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@crombolo/core": "0.69.1",
33
- "@crombolo/data": "0.69.1"
32
+ "@crombolo/core": "0.71.0",
33
+ "@crombolo/data": "0.71.0"
34
34
  }
35
35
  }
package/src/index.ts CHANGED
@@ -2,3 +2,5 @@ export * from './element-operations.ts'
2
2
  export * from './media-operations.ts'
3
3
  export * from './operations.ts'
4
4
  export * from './rules.ts'
5
+ export * from './workspace-merge.ts'
6
+ export * from './workspace-merge-run.ts'
package/src/operations.ts CHANGED
@@ -12,6 +12,7 @@
12
12
  import type { DocumentValidationError, DocumentValue } from '@crombolo/core'
13
13
  import { normaliseUuid, SystemNodes } from '@crombolo/core'
14
14
  import {
15
+ AuditLog,
15
16
  appendCacheInstruction,
16
17
  ContentTypeRepository,
17
18
  type Db,
@@ -26,11 +27,12 @@ import {
26
27
  type SetDomainsResult,
27
28
  StaleRevisionError,
28
29
  sql,
30
+ WorkspaceRefusedError,
29
31
  WriteRejectedError,
30
32
  } from '@crombolo/data'
31
33
  import type { Actor, ContentPrincipal } from './actor.ts'
32
34
  import { duplicateBlockAlias } from './block-aliases.ts'
33
- import type { DocumentEvent, EventSink } from './events.ts'
35
+ import { auditEntryFor, type DocumentEvent, type EventSink } from './events.ts'
34
36
  import {
35
37
  deniedPropertyWrite,
36
38
  mayAt,
@@ -194,6 +196,7 @@ function refusalFrom(error: unknown, extra?: (error: unknown) => string | undefi
194
196
  ...(error.errors.length > 0 ? { errors: error.errors } : {}),
195
197
  }
196
198
  if (error instanceof StaleRevisionError) return refuse('stale', 412, STALE)
199
+ if (error instanceof WorkspaceRefusedError) return refuse('conflict', 409, error.message)
197
200
  const reason = extra?.(error)
198
201
  if (reason) return refuse('invalid', 400, reason)
199
202
  throw error
@@ -204,6 +207,8 @@ export type DocumentOperations = ReturnType<typeof createDocumentOperations>
204
207
  export function createDocumentOperations(options: DocumentOperationsOptions) {
205
208
  const { db, events } = options
206
209
  const repo = new DocumentRepository(db, options.repository)
210
+ /** Set for a workspace's operations (story 375): nothing they write reaches Shared. */
211
+ const workspace = options.repository?.workspace
207
212
  const nodes = new NodeRepository(db)
208
213
  const types = new ContentTypeRepository(db, {
209
214
  kind: repo.kind === 'media' ? 'media' : 'document',
@@ -249,7 +254,7 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
249
254
  key: string,
250
255
  ): Promise<{ node: NodeRow; chain: string[]; trashed: boolean } | undefined> => {
251
256
  const node = await nodes.byKey(key)
252
- if (!node || node.objectType !== repo.objectType) return undefined
257
+ if (!node || !repo.sees(node)) return undefined
253
258
  const ids = node.path
254
259
  .split(',')
255
260
  .map(Number)
@@ -257,7 +262,7 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
257
262
  const byId = new Map((await nodes.byIds(ids)).map((row) => [row.id, row]))
258
263
  const chain = ids.flatMap((id) => {
259
264
  const row = byId.get(id)
260
- return row && row.objectType === repo.objectType ? [row.key] : []
265
+ return row && repo.sees(row) ? [row.key] : []
261
266
  })
262
267
  return { node, chain, trashed: node.trashed }
263
268
  }
@@ -380,7 +385,7 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
380
385
  const out: NodeRow[] = []
381
386
  for (const key of keys) {
382
387
  const node = await nodes.byKey(key)
383
- if (!node || node.objectType !== repo.objectType) return refuse('notFound', 404, NOT_FOUND)
388
+ if (!node || !repo.sees(node)) return refuse('notFound', 404, NOT_FOUND)
384
389
  if (!out.some((seen) => seen.id === node.id)) out.push(node)
385
390
  }
386
391
  return out
@@ -422,7 +427,7 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
422
427
  const found = await pagesFor(keys)
423
428
  if (!Array.isArray(found)) return found
424
429
  const target = targetKey ? await nodes.byKey(targetKey) : undefined
425
- if (targetKey && (!target || target.objectType !== repo.objectType))
430
+ if (targetKey && (!target || !repo.sees(target)))
426
431
  return refuse('notFound', 404, 'The document or target could not be found.')
427
432
  const denied = await deniedOf(actor, 'move', found)
428
433
  if (denied) return denied
@@ -985,6 +990,8 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
985
990
  },
986
991
 
987
992
  async emptyBin(actor: Actor): Promise<Result<{ deleted: number }>> {
993
+ if (workspace !== undefined)
994
+ return refuse('conflict', 409, 'The recycle bin is Shared’s: empty it there.')
988
995
  if (!(await permits(actor, 'emptyBin', 'bin'))) return forbidden()
989
996
  // One change: each page deleted is announced as a delete from the bin is,
990
997
  // and the emptying itself is recorded once.
@@ -1179,6 +1186,8 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
1179
1186
  > {
1180
1187
  const node = await nodes.byKey(key)
1181
1188
  if (!node || node.objectType !== repo.objectType) return { status: 'notFound' }
1189
+ // A page's hostnames are the site's, as its users are: never a workspace's.
1190
+ if (workspace !== undefined) return { status: 'forbidden' }
1182
1191
  if (!(await permits(actor, 'domains', key))) return { status: 'forbidden' }
1183
1192
  const result = await commit(
1184
1193
  actor,
@@ -1203,6 +1212,7 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
1203
1212
  change: 'added' | 'set',
1204
1213
  ): Promise<PublicAccessStatus> {
1205
1214
  if (!(await isDocument(key))) return 'content-not-found'
1215
+ if (workspace !== undefined) return 'forbidden'
1206
1216
  if (!(await permits(actor, 'publicAccess', key))) return 'forbidden'
1207
1217
  if (!(await isDocument(input.loginDocumentKey))) return 'login-node-not-found'
1208
1218
  if (!(await isDocument(input.errorDocumentKey))) return 'error-node-not-found'
@@ -1228,6 +1238,7 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
1228
1238
 
1229
1239
  async removePublicAccess(actor: Actor, key: string): Promise<PublicAccessStatus> {
1230
1240
  if (!(await isDocument(key))) return 'content-not-found'
1241
+ if (workspace !== undefined) return 'forbidden'
1231
1242
  if (!(await permits(actor, 'publicAccess', key))) return 'forbidden'
1232
1243
  const removed = await commit(
1233
1244
  actor,
@@ -1266,6 +1277,7 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
1266
1277
 
1267
1278
  /** The content cache instruction other nodes rebuild on. */
1268
1279
  async function repoInstruction(key: string, on: Db = db): Promise<void> {
1280
+ if (workspace !== undefined) return
1269
1281
  await appendCacheInstruction(on, {
1270
1282
  kind: 'content',
1271
1283
  payload: { key },
@@ -1273,3 +1285,45 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
1273
1285
  })
1274
1286
  }
1275
1287
  }
1288
+
1289
+ /**
1290
+ * A workspace's operations (story 375): the same rules over the workspace's
1291
+ * pages, audited naming the workspace, and announced nowhere else. No
1292
+ * webhook, notification, live event, redirect or approval: a workspace's work
1293
+ * reaches anyone else only by its merge (story 380).
1294
+ */
1295
+ export function createWorkspaceOperations(
1296
+ options: Pick<DocumentOperationsOptions, 'db' | 'repository' | 'refusalReason'>,
1297
+ workspace: { id: number; name: string },
1298
+ ): DocumentOperations {
1299
+ return createDocumentOperations({
1300
+ db: options.db,
1301
+ repository: { ...options.repository, workspace: workspace.id },
1302
+ events: workspaceAuditSink(workspace.name),
1303
+ refusalReason: options.refusalReason,
1304
+ })
1305
+ }
1306
+
1307
+ /** Each write's audit entry, saying which workspace it was made in. */
1308
+ export function workspaceAuditSink(name: string): EventSink {
1309
+ return {
1310
+ async record(tx, event, actor) {
1311
+ const entry = auditEntryFor(event, actor)
1312
+ const audit = new AuditLog(tx)
1313
+ const subject =
1314
+ event.type === 'deleted'
1315
+ ? { entityType: entry.entityType, entityKey: event.key, entityName: event.name }
1316
+ : entry.entityKey
1317
+ ? await audit.describe(entry.entityType, entry.entityKey)
1318
+ : undefined
1319
+ const where = `In the workspace "${name}"`
1320
+ await audit.record({
1321
+ ...entry,
1322
+ entityType: subject?.entityType ?? entry.entityType,
1323
+ entityKey: subject?.entityKey ?? entry.entityKey,
1324
+ entityName: subject?.entityName ?? null,
1325
+ detail: entry.detail ? `${where}. ${entry.detail}` : where,
1326
+ })
1327
+ },
1328
+ }
1329
+ }
@@ -0,0 +1,529 @@
1
+ /**
2
+ * Running a workspace's merge into Shared (story 380): in one transaction under
3
+ * the content tree's lock, each page the workspace changed is saved in Shared
4
+ * with the fields it takes, published as the workspace left it, and each move,
5
+ * reorder and delete is done; then the workspace is closed. Anything refused
6
+ * undoes all of it. A rehearsal runs the same and undoes it on purpose.
7
+ */
8
+ import { type DocumentValue, ObjectTypes } from '@crombolo/core'
9
+ import {
10
+ type ChangeItemInput,
11
+ ChangeRepository,
12
+ type ContentKind,
13
+ type Db,
14
+ DocumentRepository,
15
+ type DocumentRepositoryOptions,
16
+ Locks,
17
+ SystemNodes,
18
+ TransferRunRepository,
19
+ type Workspace,
20
+ WorkspaceRepository,
21
+ } from '@crombolo/data'
22
+ import type { Actor } from './actor.ts'
23
+ import type { DocumentEvent, EventSink } from './events.ts'
24
+ import {
25
+ fieldWords,
26
+ type MergePlan,
27
+ mergeBlockers,
28
+ type PageMergePlan,
29
+ planWorkspaceMerge,
30
+ } from './workspace-merge.ts'
31
+
32
+ export interface WorkspaceMergeOptions {
33
+ db: Db
34
+ repository?: DocumentRepositoryOptions
35
+ events: EventSink
36
+ actor: Actor
37
+ /** The user's id, for the events a merge writes; the user's key, for the workspace's record. */
38
+ userId?: number
39
+ userKey: string
40
+ /** The findings the person accepted, by id. */
41
+ accepted?: readonly string[]
42
+ /**
43
+ * Why the merge may not publish a page itself: a workflow covers it. Such a
44
+ * page is saved in Shared and sent for approval once the merge commits.
45
+ */
46
+ publishRefusal?(key: string, action: 'publish' | 'unpublish'): Promise<string | undefined>
47
+ /** Run it all and undo it: what a merge would do, with every refusal it would meet. */
48
+ rehearse?: boolean
49
+ /**
50
+ * A workspace's files (story 376): what merging them would write and what
51
+ * conflicts, then writing them on the merge's transaction, before its pages.
52
+ */
53
+ files?: WorkspaceFileMerging
54
+ /**
55
+ * The identity the change it records takes (story 383): a change brought from
56
+ * another site keeps its own. By default a whole workspace's own key, so one
57
+ * exported before it merged is known as the same change.
58
+ */
59
+ changeKey?: string
60
+ /** The changes from other sites this merge applies, recorded so each is applied once (story 383). */
61
+ appliedChanges?: ReadonlyArray<{ key: string; name: string | null }>
62
+ }
63
+
64
+ /** How a merge plans and writes a workspace's files, which the server knows. */
65
+ export interface WorkspaceFileMerging {
66
+ /**
67
+ * `conflicts` refuse the merge outright; `findings` until each is accepted by
68
+ * its id or its kind (story 382).
69
+ */
70
+ plan(
71
+ workspaceId: number,
72
+ tx: Db,
73
+ ): Promise<{
74
+ conflicts: string[]
75
+ findings: Array<{ id: string; kind: string; says: string }>
76
+ ready: unknown
77
+ }>
78
+ /** Writes them; `items` are each file's text before and after, for the change it records. */
79
+ apply(
80
+ tx: Db,
81
+ ready: unknown,
82
+ ): Promise<{ restore(): void; after(): Promise<void>; items?: ChangeItemInput[] }>
83
+ }
84
+
85
+ export type WorkspaceMergeOutcome =
86
+ | {
87
+ ok: true
88
+ merged: Array<{ key: string; name: string; published: boolean; unpublished: boolean }>
89
+ /** Pages a workflow covers: saved in Shared, to be sent for approval. */
90
+ forApproval: Array<{
91
+ key: string
92
+ name: string
93
+ action: 'publish' | 'unpublish'
94
+ cultures: string[] | null
95
+ }>
96
+ done: Array<{ key: string | null; name: string; kind: string }>
97
+ rehearsed: boolean
98
+ /** The change it was recorded as (story 381). */
99
+ changeId?: string
100
+ }
101
+ | { ok: false; blockers: string[]; plan: MergePlan }
102
+
103
+ /** Where a deleted page's state is kept among its change's items (story 383). */
104
+ export const REMOVED_PAGE_PREFIX = 'pages/'
105
+
106
+ /** Records a merge as a change (story 381): its name, who made and merged it, its files and pages. */
107
+ async function recordChange(
108
+ tx: Db,
109
+ list: readonly Workspace[],
110
+ options: WorkspaceMergeOptions & { only?: string },
111
+ items: readonly ChangeItemInput[],
112
+ pages: readonly PageChange[],
113
+ merged: Done['merged'],
114
+ ): Promise<string> {
115
+ const changes = new ChangeRepository(tx)
116
+ const first = list[0] as Workspace
117
+ const name =
118
+ options.only !== undefined
119
+ ? `Published "${merged[0]?.name ?? 'a page'}"`
120
+ : list.map((w) => w.name).join(', ')
121
+ const id = await changes.begin({
122
+ kind: 'merge',
123
+ name,
124
+ madeBy: first.ownerKey,
125
+ appliedBy: options.userKey,
126
+ workspaceKey: first.key,
127
+ key:
128
+ options.changeKey ??
129
+ (list.length === 1 && options.only === undefined ? first.key : undefined),
130
+ })
131
+ for (const applied of options.appliedChanges ?? []) await changes.applied(applied, id)
132
+ for (const item of items) await changes.item(id, item)
133
+ const runs = new TransferRunRepository(tx)
134
+ for (const page of pages)
135
+ await runs.record({
136
+ runId: id,
137
+ nodeKey: page.key,
138
+ kind: page.kind,
139
+ action: page.action,
140
+ beforeEventId: page.beforeEventId,
141
+ beforePublishedEventId: page.beforePublishedEventId,
142
+ eventId: page.eventId,
143
+ })
144
+ await runs.finish(id, pages.length)
145
+ return id
146
+ }
147
+
148
+ /** A page's events before and after a merge, which its change records (story 381). */
149
+ interface PageChange {
150
+ key: string
151
+ kind: ContentKind
152
+ action: 'create' | 'update' | 'recycle'
153
+ beforeEventId: number | null
154
+ beforePublishedEventId: number | null
155
+ eventId: number | null
156
+ }
157
+
158
+ class Rehearsed extends Error {}
159
+
160
+ /** The plan for a workspace's merge as things stand, without writing anything. */
161
+ export async function previewWorkspaceMerge(
162
+ db: Db,
163
+ repository: DocumentRepositoryOptions | undefined,
164
+ workspace: Workspace,
165
+ ): Promise<MergePlan> {
166
+ return planFor(new DocumentRepository(db, repository), new WorkspaceRepository(db), workspace)
167
+ }
168
+
169
+ /** The kinds a workspace holds, in the order a merge writes them: what pages use, first (story 390). */
170
+ const KINDS = ['element', 'media', 'blueprint', 'document'] as const
171
+
172
+ /** What each pending change's node is, by its object type. */
173
+ const KIND_OF: Record<string, (typeof KINDS)[number]> = {
174
+ [ObjectTypes.Document]: 'document',
175
+ [ObjectTypes.WorkspaceDocument]: 'document',
176
+ [ObjectTypes.Media]: 'media',
177
+ [ObjectTypes.WorkspaceMedia]: 'media',
178
+ [ObjectTypes.Element]: 'element',
179
+ [ObjectTypes.WorkspaceElement]: 'element',
180
+ [ObjectTypes.DocumentBlueprint]: 'blueprint',
181
+ [ObjectTypes.WorkspaceDocumentBlueprint]: 'blueprint',
182
+ }
183
+
184
+ async function planFor(
185
+ shared: DocumentRepository,
186
+ workspaces: WorkspaceRepository,
187
+ workspace: Workspace,
188
+ ): Promise<MergePlan> {
189
+ const pages = []
190
+ for (const kind of KINDS)
191
+ pages.push(...(await shared.ofKind(kind).inWorkspace(workspace.id).workspaceMergePages()))
192
+ const pending = await workspaces.pending(workspace.id)
193
+ const where = new Map<number, { parentId: number; head: number | null }>()
194
+ for (const p of pending) {
195
+ if (p.key === null) continue
196
+ const node = await shared.nodes.byId(p.nodeId)
197
+ if (!node) continue
198
+ const kind = KIND_OF[node.objectType ?? ''] ?? 'document'
199
+ p.objectKind = kind
200
+ if (!node.trashed)
201
+ where.set(p.nodeId, {
202
+ parentId: node.parentId,
203
+ head: await shared.ofKind(kind).sharedHeadEvent(node.id),
204
+ })
205
+ }
206
+ return planWorkspaceMerge(pages, pending, where)
207
+ }
208
+
209
+ /** The save a page's plan makes in Shared: the fields it takes, the rest as Shared has them. */
210
+ function saveOf(plan: PageMergePlan, userId: number | undefined) {
211
+ const { page } = plan
212
+ const taken = new Set(plan.take.map((f) => f.field))
213
+ const pick = (field: string) => {
214
+ const f = page.fields.find((x) => x.field === field)
215
+ if (!f) return undefined
216
+ return taken.has(field) ? f.mine : f.theirs
217
+ }
218
+ // A save sends every value: one it leaves out is cleared.
219
+ const values: DocumentValue[] = page.fields.flatMap((f) =>
220
+ f.value ? [{ ...f.value, value: (taken.has(f.field) ? f.mine : f.theirs) ?? null }] : [],
221
+ )
222
+ const name = String(pick('@name') ?? plan.name)
223
+ const variants =
224
+ page.cultures.length > 0
225
+ ? page.cultures.map((c) => ({
226
+ culture: c.iso,
227
+ segment: null,
228
+ name: String(pick(`@name:${c.iso}`) ?? name),
229
+ }))
230
+ : [{ culture: null, segment: null, name }]
231
+ const template = pick('@template')
232
+ return {
233
+ key: page.key,
234
+ contentTypeKey: page.contentTypeKey,
235
+ componentKey: typeof template === 'string' ? template : null,
236
+ parentKey: page.parentKey,
237
+ values,
238
+ variants,
239
+ ...(userId === undefined ? {} : { userId }),
240
+ }
241
+ }
242
+
243
+ type Done = Extract<WorkspaceMergeOutcome, { ok: true }>
244
+
245
+ /** Fields two workspaces both take for one page, with different values: named before anything merges. */
246
+ function betweenThem(plans: ReadonlyArray<{ workspace: Workspace; plan: MergePlan }>): string[] {
247
+ const taken = new Map<string, { workspace: string; value: unknown; name: string }>()
248
+ const out: string[] = []
249
+ for (const { workspace, plan } of plans)
250
+ for (const page of plan.pages)
251
+ for (const field of page.take) {
252
+ const id = `${page.page.key}|${field.field}`
253
+ const before = taken.get(id)
254
+ if (!before)
255
+ taken.set(id, { workspace: workspace.name, value: field.mine, name: page.name })
256
+ else if (JSON.stringify(before.value ?? null) !== JSON.stringify(field.mine ?? null))
257
+ out.push(
258
+ `"${page.name}": ${fieldWords(field.field)} is changed differently in "${before.workspace}" and "${workspace.name}"; settle it in one of them.`,
259
+ )
260
+ }
261
+ return out
262
+ }
263
+
264
+ /**
265
+ * Merges workspaces into Shared, all of them or none: each is planned against
266
+ * Shared as the ones before it left it. With `only`, one page of one workspace
267
+ * goes (a person's own, story 380), and the workspace stays open.
268
+ */
269
+ export async function runWorkspaceMerge(
270
+ chosen: Workspace | readonly Workspace[],
271
+ options: WorkspaceMergeOptions & { only?: string },
272
+ ): Promise<WorkspaceMergeOutcome> {
273
+ const list = Array.isArray(chosen) ? chosen : [chosen as Workspace]
274
+ const documents = new DocumentRepository(options.db, options.repository)
275
+ const events: DocumentEvent[] = []
276
+ let outcome: WorkspaceMergeOutcome | undefined
277
+ const written: Array<{ restore(): void; after(): Promise<void> }> = []
278
+ // Files sync Shared's schema, which takes the schema lock: taken first, as every
279
+ // schema write takes it before the content tree's.
280
+ const files = options.only === undefined ? options.files : undefined
281
+ // Media is written too (story 390), under its own tree's lock.
282
+ const locked = <T>(fn: () => Promise<T>) => {
283
+ const media = () => options.db.locks.withLock(Locks.MediaTree, fn)
284
+ return files ? options.db.locks.withLock(Locks.Schema, media) : media()
285
+ }
286
+ try {
287
+ await locked(() =>
288
+ documents.atomically(async (shared, tx) => {
289
+ const workspaces = new WorkspaceRepository(tx)
290
+ const narrowed = (plan: MergePlan): MergePlan =>
291
+ options.only === undefined
292
+ ? plan
293
+ : {
294
+ pages: plan.pages.filter((p) => p.page.key === options.only),
295
+ pending: [],
296
+ conflicts: plan.conflicts.filter((c) => c.key === options.only),
297
+ findings: plan.findings.filter((f) => f.key === options.only),
298
+ }
299
+ const first: Array<{ workspace: Workspace; plan: MergePlan }> = []
300
+ for (const workspace of list)
301
+ first.push({ workspace, plan: narrowed(await planFor(shared, workspaces, workspace)) })
302
+ const filePlans: unknown[] = []
303
+ const fileBlockers: string[] = []
304
+ for (const workspace of list) {
305
+ const planned = files
306
+ ? await files.plan(workspace.id, tx)
307
+ : { conflicts: [], findings: [], ready: null }
308
+ filePlans.push(planned.ready)
309
+ const accepted = options.accepted ?? []
310
+ for (const c of [
311
+ ...planned.conflicts,
312
+ ...planned.findings
313
+ .filter((f) => !accepted.includes(f.id) && !accepted.includes(f.kind))
314
+ .map((f) => f.says),
315
+ ])
316
+ fileBlockers.push(list.length > 1 ? `In "${workspace.name}": ${c}` : c)
317
+ }
318
+ // A page alone cannot go without the media or Library items it uses that only
319
+ // the workspace has (story 390): they come with the whole workspace.
320
+ if (options.only !== undefined)
321
+ for (const workspace of list) {
322
+ const own = await tx.q
323
+ .selectFrom('node')
324
+ .select(['unique_id', 'text'])
325
+ .where('workspace_id', '=', workspace.id)
326
+ .where('node_object_type', 'in', [
327
+ ObjectTypes.WorkspaceMedia,
328
+ ObjectTypes.WorkspaceElement,
329
+ ])
330
+ .execute()
331
+ for (const { plan } of first)
332
+ for (const page of plan.pages) {
333
+ const text = JSON.stringify(page.page.fields.map((f) => f.mine)).toLowerCase()
334
+ for (const item of own) {
335
+ const key = String(item.unique_id).toLowerCase()
336
+ if (text.includes(key) || text.includes(key.replaceAll('-', '')))
337
+ fileBlockers.push(
338
+ `"${page.name}" uses "${item.text ?? key}", which is only in the workspace: merge the workspace to bring both.`,
339
+ )
340
+ }
341
+ }
342
+ }
343
+ // A page alone cannot go before the type it is made of (story 376).
344
+ if (options.only !== undefined)
345
+ for (const { plan } of first)
346
+ for (const page of plan.pages)
347
+ if (page.page.made && (await shared.madeOfWorkspaceType(page.page.nodeId)))
348
+ fileBlockers.push(
349
+ `"${page.name}" is of a type made in the workspace: merge the workspace to bring both.`,
350
+ )
351
+ const blockers = [
352
+ ...fileBlockers,
353
+ ...betweenThem(first),
354
+ ...first.flatMap(({ workspace, plan }) =>
355
+ mergeBlockers(plan, options.accepted ?? []).map((b) =>
356
+ list.length > 1 ? `In "${workspace.name}": ${b}` : b,
357
+ ),
358
+ ),
359
+ ]
360
+ if (blockers.length > 0) {
361
+ outcome = { ok: false, blockers, plan: first[0]?.plan as MergePlan }
362
+ return
363
+ }
364
+ const record = async (event: DocumentEvent) => {
365
+ events.push(event)
366
+ await options.events.record(tx, event, options.actor)
367
+ }
368
+ const merged: Done['merged'] = []
369
+ const forApproval: Done['forApproval'] = []
370
+ const done: Done['done'] = []
371
+ const pages: PageChange[] = []
372
+ const items: ChangeItemInput[] = []
373
+ for (const [n, workspace] of list.entries()) {
374
+ // Its files first, so its pages are written against the types they need.
375
+ if (files) {
376
+ const applied = await files.apply(tx, filePlans[n])
377
+ written.push(applied)
378
+ items.push(...(applied.items ?? []))
379
+ }
380
+ // Each after the first is planned again against Shared as the ones before left it.
381
+ const plan =
382
+ n === 0
383
+ ? (first[0] as { plan: MergePlan }).plan
384
+ : narrowed(await planFor(shared, workspaces, workspace))
385
+ await apply(shared, plan, record, options, {
386
+ merged,
387
+ forApproval,
388
+ done,
389
+ pages,
390
+ removed: items,
391
+ })
392
+ if (options.only === undefined)
393
+ await workspaces.closeMerged(workspace.id, options.userKey)
394
+ else
395
+ for (const page of plan.pages)
396
+ if (!page.page.made) await workspaces.dropPage(workspace.id, page.page.nodeId)
397
+ }
398
+ // Story 381: the merge is a change, its files and pages each with before and after.
399
+ const changeId = await recordChange(tx, list, options, items, pages, merged)
400
+ outcome = {
401
+ ok: true,
402
+ merged,
403
+ forApproval,
404
+ done,
405
+ rehearsed: options.rehearse === true,
406
+ changeId,
407
+ }
408
+ if (options.rehearse) throw new Rehearsed()
409
+ }),
410
+ )
411
+ } catch (error) {
412
+ // The database is as it was: so are the files.
413
+ for (const w of written.reverse()) w.restore()
414
+ if (!(error instanceof Rehearsed)) throw error
415
+ return outcome as WorkspaceMergeOutcome
416
+ }
417
+ for (const w of written) await w.after()
418
+ if (outcome?.ok) for (const event of events) options.events.afterCommit?.(event, options.actor)
419
+ return outcome as WorkspaceMergeOutcome
420
+ }
421
+
422
+ /** One workspace's plan, written into Shared through its own save, publish, move and delete. */
423
+ async function apply(
424
+ sharedAll: DocumentRepository,
425
+ plan: MergePlan,
426
+ record: (event: DocumentEvent) => Promise<void>,
427
+ options: WorkspaceMergeOptions,
428
+ out: Pick<Done, 'merged' | 'forApproval' | 'done'> & {
429
+ pages: PageChange[]
430
+ removed: ChangeItemInput[]
431
+ },
432
+ ): Promise<void> {
433
+ for (const pagePlan of plan.pages) {
434
+ const { page } = pagePlan
435
+ // Each kind through its own repository: pages, media, Library items (story 390).
436
+ const shared = sharedAll.ofKind(page.kind)
437
+ const before = page.made ? undefined : await shared.eventMarkers(page.key)
438
+ if (page.made) await shared.adoptWorkspacePage(page.nodeId)
439
+ if (page.made || pagePlan.take.length > 0) {
440
+ await shared.update(saveOf(pagePlan, options.userId))
441
+ await record({ type: page.made ? 'created' : 'saved', key: page.key })
442
+ }
443
+ let published = false
444
+ let unpublished = false
445
+ if (pagePlan.publish) {
446
+ const cultures = pagePlan.publish.cultures
447
+ if (await options.publishRefusal?.(page.key, 'publish'))
448
+ out.forApproval.push({ key: page.key, name: pagePlan.name, action: 'publish', cultures })
449
+ else {
450
+ await shared.publish(page.key, cultures)
451
+ await record({ type: 'published', key: page.key, cultures })
452
+ published = true
453
+ }
454
+ }
455
+ if (pagePlan.unpublish) {
456
+ const cultures = pagePlan.unpublish.cultures
457
+ if (await options.publishRefusal?.(page.key, 'unpublish'))
458
+ out.forApproval.push({ key: page.key, name: pagePlan.name, action: 'unpublish', cultures })
459
+ else {
460
+ await shared.unpublish(page.key, cultures)
461
+ await record({ type: 'unpublished', key: page.key, cultures })
462
+ unpublished = true
463
+ }
464
+ }
465
+ out.merged.push({ key: page.key, name: pagePlan.name, published, unpublished })
466
+ const after = await shared.eventMarkers(page.key)
467
+ out.pages.push({
468
+ key: page.key,
469
+ kind: page.kind,
470
+ action: page.made ? 'create' : 'update',
471
+ beforeEventId: before?.head ?? null,
472
+ beforePublishedEventId: before?.published ?? null,
473
+ eventId: after?.head ?? null,
474
+ })
475
+ }
476
+
477
+ const keyOf = async (id: number | null) =>
478
+ id === null || id === SystemNodes.Root ? null : ((await sharedAll.nodes.byId(id))?.key ?? null)
479
+ for (const { pending } of plan.pending) {
480
+ const key = pending.key
481
+ if (pending.kind === 'gone' || key === null) continue
482
+ const shared = sharedAll.ofKind(pending.objectKind ?? 'document')
483
+ const before = await shared.eventMarkers(key)
484
+ // A delete takes the page's history with it: its change keeps the page as it stood (story 383).
485
+ if (pending.kind === 'delete') {
486
+ const doc = await shared.byKey(key)
487
+ if (doc)
488
+ out.removed.push({
489
+ path: `${REMOVED_PAGE_PREFIX}${key}`,
490
+ kind: 'page',
491
+ class: 'none',
492
+ before: JSON.stringify(doc),
493
+ after: null,
494
+ })
495
+ }
496
+ if (pending.kind === 'move') {
497
+ await shared.move(key, await keyOf(pending.targetParentId))
498
+ await record({ type: 'moved', key })
499
+ } else if (pending.kind === 'sort' && pending.sortOrder !== null) {
500
+ const node = await shared.nodes.byId(pending.nodeId)
501
+ const parentKey = await keyOf(node?.parentId ?? null)
502
+ await shared.sort(parentKey, [{ key, sortOrder: pending.sortOrder }])
503
+ await record({ type: 'sorted', parentKey })
504
+ } else if (pending.kind === 'trash') {
505
+ await shared.moveToRecycleBin(key)
506
+ await record({ type: 'trashed', key })
507
+ } else if (pending.kind === 'delete') {
508
+ await shared.delete(key)
509
+ await record({ type: 'deleted', key, name: pending.name })
510
+ }
511
+ out.done.push({ key, name: pending.name, kind: pending.kind })
512
+ // Story 383: what it moved or deleted is in its change too, once per page.
513
+ const gone = pending.kind === 'trash' || pending.kind === 'delete'
514
+ const after = gone ? undefined : await shared.eventMarkers(key)
515
+ const recorded = out.pages.find((p) => p.key === key)
516
+ if (recorded) {
517
+ if (gone) Object.assign(recorded, { action: 'recycle', eventId: null })
518
+ else recorded.eventId = after?.head ?? recorded.eventId
519
+ } else
520
+ out.pages.push({
521
+ key,
522
+ kind: pending.objectKind ?? 'document',
523
+ action: gone ? 'recycle' : 'update',
524
+ beforeEventId: before?.head ?? null,
525
+ beforePublishedEventId: before?.published ?? null,
526
+ eventId: after?.head ?? null,
527
+ })
528
+ }
529
+ }
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Planning a workspace's merge into Shared (story 380). Pure: from each page as
3
+ * it began, as the workspace has it and as Shared has it now, and from what
4
+ * waits for the merge, it says what the merge takes, publishes and does, what
5
+ * conflicts, and what must be accepted by name before it goes ahead.
6
+ */
7
+ import { threeWay } from '@crombolo/core'
8
+ import type { MergeField, WorkspacePageMerge, WorkspacePending } from '@crombolo/data'
9
+
10
+ /** A field both the workspace and Shared changed, differently. */
11
+ export interface MergeConflict {
12
+ key: string
13
+ name: string
14
+ field: string
15
+ base: unknown
16
+ mine: unknown
17
+ theirs: unknown
18
+ }
19
+
20
+ /** Something the merge will do that Shared did not expect, named so it can be accepted. */
21
+ export interface MergeFinding {
22
+ id: string
23
+ key: string | null
24
+ name: string
25
+ says: string
26
+ }
27
+
28
+ /** One page's part of the merge. */
29
+ export interface PageMergePlan {
30
+ page: WorkspacePageMerge
31
+ name: string
32
+ /** The fields the workspace's version is taken for. */
33
+ take: MergeField[]
34
+ /** Publish or unpublish in Shared, with the languages; null for an invariant page. */
35
+ publish: { cultures: string[] | null } | null
36
+ unpublish: { cultures: string[] | null } | null
37
+ }
38
+
39
+ /** What waits for the merge, and whether it can go. */
40
+ export interface PendingMergePlan {
41
+ pending: WorkspacePending
42
+ /** Why it cannot go as it is; it is answered by moving it again or dropping it. */
43
+ conflict?: string
44
+ }
45
+
46
+ export interface MergePlan {
47
+ pages: PageMergePlan[]
48
+ pending: PendingMergePlan[]
49
+ conflicts: MergeConflict[]
50
+ findings: MergeFinding[]
51
+ }
52
+
53
+ const nameOf = (page: WorkspacePageMerge): string => {
54
+ const name = page.fields.find((f) => f.field === '@name')
55
+ return String(name?.mine ?? name?.theirs ?? page.key)
56
+ }
57
+
58
+ /** A page made in the workspace takes every field; a changed one, field by field, three ways. */
59
+ function planPage(page: WorkspacePageMerge, conflicts: MergeConflict[]): PageMergePlan {
60
+ const name = nameOf(page)
61
+ const take: MergeField[] = []
62
+ for (const field of page.fields) {
63
+ if (page.made) {
64
+ take.push(field)
65
+ continue
66
+ }
67
+ // Shared is the site the change comes into; the workspace is what comes in.
68
+ const outcome = threeWay(field.theirs, field.mine, { value: field.base })
69
+ if (outcome === 'take') take.push(field)
70
+ else if (outcome === 'ask')
71
+ conflicts.push({
72
+ key: page.key,
73
+ name,
74
+ field: field.field,
75
+ base: field.base,
76
+ mine: field.mine,
77
+ theirs: field.theirs,
78
+ })
79
+ }
80
+
81
+ // Published state: what the workspace did to it is what the merge does.
82
+ const varies = page.cultures.length > 0
83
+ let publish: PageMergePlan['publish'] = null
84
+ let unpublish: PageMergePlan['unpublish'] = null
85
+ if (varies) {
86
+ const on = page.published.here ? page.cultures.filter((c) => c.mine).map((c) => c.iso) : []
87
+ const off = page.cultures.filter((c) => !c.mine && c.base === true).map((c) => c.iso)
88
+ if (on.length > 0) publish = { cultures: on }
89
+ if (off.length > 0) unpublish = { cultures: off }
90
+ } else if (page.published.here) publish = { cultures: null }
91
+ else if (!page.published.mine && page.published.base === true && page.published.theirs)
92
+ unpublish = { cultures: null }
93
+ return { page, name, take, publish, unpublish }
94
+ }
95
+
96
+ /** A pending move, reorder or delete, against where Shared has the page now. */
97
+ function planPending(
98
+ pending: WorkspacePending,
99
+ shared: ReadonlyMap<number, { parentId: number; head: number | null }>,
100
+ ): PendingMergePlan {
101
+ if (pending.kind === 'gone') return { pending }
102
+ if (pending.kind === 'orphaned')
103
+ return {
104
+ pending,
105
+ conflict: `Its parent was deleted in Shared: move "${pending.name}" somewhere in the workspace first.`,
106
+ }
107
+ const now = shared.get(pending.nodeId)
108
+ if (!now) return { pending, conflict: `"${pending.name}" is no longer in Shared.` }
109
+ if (
110
+ pending.kind === 'move' &&
111
+ pending.baseParentId !== null &&
112
+ now.parentId !== pending.baseParentId
113
+ )
114
+ return { pending, conflict: `"${pending.name}" was moved in Shared since.` }
115
+ if (
116
+ (pending.kind === 'trash' || pending.kind === 'delete') &&
117
+ pending.baseEventId !== null &&
118
+ now.head !== pending.baseEventId
119
+ )
120
+ return { pending, conflict: `"${pending.name}" was changed in Shared since.` }
121
+ return { pending }
122
+ }
123
+
124
+ /**
125
+ * The merge's plan. `shared` is where each pending page is in Shared now: its
126
+ * parent and its latest event.
127
+ */
128
+ export function planWorkspaceMerge(
129
+ pages: readonly WorkspacePageMerge[],
130
+ pending: readonly WorkspacePending[],
131
+ shared: ReadonlyMap<number, { parentId: number; head: number | null }>,
132
+ ): MergePlan {
133
+ const conflicts: MergeConflict[] = []
134
+ const findings: MergeFinding[] = []
135
+ // Pages a workspace made go in before the pages beneath them.
136
+ const ordered = [...pages].sort((a, b) => a.level - b.level)
137
+ const planned = ordered.map((page) => planPage(page, conflicts))
138
+ for (const plan of planned) {
139
+ const { page } = plan
140
+ if (plan.publish && page.published.sharedEdited)
141
+ findings.push({
142
+ id: `publishes-shared-draft:${page.key}`,
143
+ key: page.key,
144
+ name: plan.name,
145
+ says: `Publishing "${plan.name}" also publishes changes made to it in Shared that were not published.`,
146
+ })
147
+ if (plan.publish && page.published.base === true && !page.published.theirs)
148
+ findings.push({
149
+ id: `unpublished-since:${page.key}`,
150
+ key: page.key,
151
+ name: plan.name,
152
+ says: `"${plan.name}" was unpublished in Shared since; the merge publishes it again.`,
153
+ })
154
+ }
155
+ const pendingPlans = pending.map((p) => planPending(p, shared))
156
+ // Story 382: a page deleted is accepted by name, or every one at once by kind.
157
+ for (const p of pendingPlans)
158
+ if ((p.pending.kind === 'delete' || p.pending.kind === 'trash') && !p.conflict)
159
+ findings.push({
160
+ id: `page-deleted:${p.pending.key ?? p.pending.nodeId}`,
161
+ key: p.pending.key,
162
+ name: p.pending.name,
163
+ says: `"${p.pending.name}" is ${p.pending.kind === 'trash' ? 'moved to the recycle bin' : 'deleted'}. Accept "page-deleted" to go ahead.`,
164
+ })
165
+ for (const p of pendingPlans)
166
+ if (p.pending.kind === 'gone')
167
+ findings.push({
168
+ id: `gone:${p.pending.nodeId}`,
169
+ key: null,
170
+ name: p.pending.name,
171
+ says: `"${p.pending.name}" was deleted in Shared; the workspace's changes to it are not merged.`,
172
+ })
173
+ return { pages: planned, pending: pendingPlans, conflicts, findings }
174
+ }
175
+
176
+ /** A field as a person reads it: `its name`, `its template`, or the property, with its language. */
177
+ export function fieldWords(field: string): string {
178
+ if (field === '@name') return 'its name'
179
+ if (field === '@template') return 'its template'
180
+ if (field.startsWith('@name:')) return `its name in ${field.slice(6)}`
181
+ const [alias, culture, segment] = field.split('|')
182
+ const where = [culture, segment].filter(Boolean).join(', ')
183
+ return where ? `${alias} (${where})` : String(alias)
184
+ }
185
+
186
+ /** Whether a plan can go: no conflict, nothing pending that cannot, and every finding accepted. */
187
+ export function mergeBlockers(plan: MergePlan, accepted: readonly string[]): string[] {
188
+ const reasons = [
189
+ ...plan.conflicts.map(
190
+ (c) => `"${c.name}": ${fieldWords(c.field)} was changed in both the workspace and Shared.`,
191
+ ),
192
+ ...plan.pending.flatMap((p) => (p.conflict ? [p.conflict] : [])),
193
+ ...plan.findings
194
+ .filter((f) => !accepted.includes(f.id) && !accepted.includes(f.id.split(':')[0] as string))
195
+ .map((f) => f.says),
196
+ ]
197
+ return reasons
198
+ }