@crombolo/server 0.69.0 → 0.70.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 +15 -14
- package/src/adapters/blueprints.ts +51 -5
- package/src/adapters/change-recording.ts +140 -0
- package/src/adapters/content.ts +132 -21
- package/src/adapters/documents.ts +26 -5
- package/src/adapters/elements.ts +3 -0
- package/src/adapters/media.ts +7 -1
- package/src/adapters/schema-files.ts +89 -1
- package/src/adapters/workspace-dictionary.ts +287 -0
- package/src/adapters/workspace-file-port.ts +160 -0
- package/src/adapters/workspace-languages.ts +94 -0
- package/src/approvals-api.ts +16 -7
- package/src/bundle-api.ts +19 -16
- package/src/bundle-install.ts +4 -0
- package/src/change-transfer.ts +676 -0
- package/src/changes-api.ts +258 -0
- package/src/component-templates-api.ts +2 -2
- package/src/config.ts +162 -22
- package/src/content-events.ts +65 -1
- package/src/content-operations.ts +22 -3
- package/src/core.ts +2 -0
- package/src/environment-values-api.ts +161 -0
- package/src/host-token.ts +30 -1
- package/src/node-operations.ts +150 -2
- package/src/ports.ts +174 -52
- package/src/remote-changes.ts +279 -0
- package/src/remote-schema.ts +126 -0
- package/src/remote-workspaces.ts +82 -0
- package/src/remote.ts +289 -192
- package/src/schema-transfer.ts +240 -41
- package/src/schema.ts +7 -2
- package/src/seed/compile.ts +13 -1
- package/src/seed/values.ts +3 -0
- package/src/server.ts +971 -364
- package/src/settings.ts +123 -5
- package/src/site-sections.ts +1 -1
- package/src/workspace-access.ts +152 -0
- package/src/workspace-checks.ts +299 -0
- package/src/workspace-losses.ts +95 -0
- package/src/workspace-processes.ts +306 -0
- package/src/workspace-render-child.ts +168 -0
- package/src/workspace-schema-dir.ts +100 -0
- package/src/workspace-schema.ts +598 -0
- package/src/workspace-sites.ts +179 -0
- package/src/workspace-views.ts +121 -0
- package/src/workspaces.ts +1031 -0
|
@@ -0,0 +1,676 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A change moved from one site to another (story 383). Exported, it is a change
|
|
3
|
+
* bundle: its identity, the changes it needs, each file and page it touched as
|
|
4
|
+
* they stood before and after, and the media files it added or replaced.
|
|
5
|
+
* Staged, it is a workspace on the target holding it, made for it and edited by
|
|
6
|
+
* nobody, served at the workspace's address. Applied, it is that workspace's
|
|
7
|
+
* merge (story 380): only what the change altered is written, a field the target
|
|
8
|
+
* changed since is a conflict, and a refused apply changes nothing and leaves
|
|
9
|
+
* the workspace for the conflict to be settled in. docs/changes.md.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { Principal } from '@crombolo/api-management/domain'
|
|
13
|
+
import { REMOVED_PAGE_PREFIX } from '@crombolo/content'
|
|
14
|
+
import type { DocumentAggregate } from '@crombolo/core'
|
|
15
|
+
import { normaliseUuid } from '@crombolo/core'
|
|
16
|
+
import {
|
|
17
|
+
ChangeRepository,
|
|
18
|
+
type ContentKind,
|
|
19
|
+
type Db,
|
|
20
|
+
DbDate,
|
|
21
|
+
DocumentRepository,
|
|
22
|
+
type DocumentRepositoryOptions,
|
|
23
|
+
TransferRunRepository,
|
|
24
|
+
type Workspace,
|
|
25
|
+
WorkspaceFileRepository,
|
|
26
|
+
WorkspaceRepository,
|
|
27
|
+
type WorkspaceScope,
|
|
28
|
+
} from '@crombolo/data'
|
|
29
|
+
import type {
|
|
30
|
+
ChangeBundle,
|
|
31
|
+
ChangeBundleFile,
|
|
32
|
+
ChangeBundlePage,
|
|
33
|
+
ChangePageState,
|
|
34
|
+
ChangeValue,
|
|
35
|
+
} from '@crombolo/transfer'
|
|
36
|
+
import type { MediaFileStore } from './media-files.ts'
|
|
37
|
+
import type { WorkspaceMerging } from './node-operations.ts'
|
|
38
|
+
|
|
39
|
+
type PageKind = ChangeBundlePage['kind']
|
|
40
|
+
const PAGE_KINDS: readonly PageKind[] = ['document', 'media', 'element', 'blueprint']
|
|
41
|
+
const isPageKind = (kind: string): kind is PageKind => (PAGE_KINDS as string[]).includes(kind)
|
|
42
|
+
|
|
43
|
+
/** One thing a change could not do on this site, in the words it is shown in. */
|
|
44
|
+
export interface ChangeConflict {
|
|
45
|
+
change: string
|
|
46
|
+
item: string
|
|
47
|
+
says: string
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface StageOutcome {
|
|
51
|
+
workspace: Workspace | undefined
|
|
52
|
+
/** Changes this site already holds, which were skipped. */
|
|
53
|
+
skipped: string[]
|
|
54
|
+
conflicts: ChangeConflict[]
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export type ApplyOutcome =
|
|
58
|
+
| { ok: true; skipped: string[]; changeId: string | null }
|
|
59
|
+
| {
|
|
60
|
+
ok: false
|
|
61
|
+
skipped: string[]
|
|
62
|
+
conflicts: ChangeConflict[]
|
|
63
|
+
/** Where the change waits, for the conflict to be settled and merged. */
|
|
64
|
+
workspace: string | null
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface ChangeTransferOptions {
|
|
68
|
+
db: Db
|
|
69
|
+
repository: DocumentRepositoryOptions
|
|
70
|
+
/** What this site calls itself, written into what it exports. */
|
|
71
|
+
siteName: () => string
|
|
72
|
+
media: MediaFileStore
|
|
73
|
+
schema: () =>
|
|
74
|
+
| {
|
|
75
|
+
snapshot(workspaceId: number): Promise<void>
|
|
76
|
+
build(workspace: WorkspaceScope): Promise<void>
|
|
77
|
+
}
|
|
78
|
+
| undefined
|
|
79
|
+
merge: () => WorkspaceMerging | undefined
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const fieldOf = (v: {
|
|
83
|
+
alias: string
|
|
84
|
+
culture: string | null
|
|
85
|
+
segment: string | null
|
|
86
|
+
environment?: string | null
|
|
87
|
+
}) => `${v.alias}|${v.culture ?? ''}|${v.segment ?? ''}|${v.environment ?? ''}`
|
|
88
|
+
const same = (a: unknown, b: unknown) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null)
|
|
89
|
+
const MEDIA_URL = /\/media\/[^"'\s?#\\]+/g
|
|
90
|
+
const UUID = /[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}/gi
|
|
91
|
+
|
|
92
|
+
function stateOf(doc: DocumentAggregate): ChangePageState {
|
|
93
|
+
const invariant = doc.variants.find((v) => v.culture === null) ?? doc.variants[0]
|
|
94
|
+
const names: Record<string, string> = {}
|
|
95
|
+
for (const v of doc.variants) if (v.culture) names[v.culture] = v.name
|
|
96
|
+
return {
|
|
97
|
+
name: invariant?.name ?? '',
|
|
98
|
+
values: doc.values.map((v) => ({
|
|
99
|
+
alias: v.alias,
|
|
100
|
+
culture: v.culture,
|
|
101
|
+
segment: v.segment,
|
|
102
|
+
...(v.environment ? { environment: v.environment } : {}),
|
|
103
|
+
value: v.value,
|
|
104
|
+
})),
|
|
105
|
+
...(Object.keys(names).length > 0 ? { names } : {}),
|
|
106
|
+
published: doc.published,
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Every field of a page's state, values and names alike, by one key. */
|
|
111
|
+
function fieldsOf(state: ChangePageState | null): Map<string, unknown> {
|
|
112
|
+
const out = new Map<string, unknown>()
|
|
113
|
+
if (!state) return out
|
|
114
|
+
out.set('@name', state.name)
|
|
115
|
+
for (const [culture, name] of Object.entries(state.names ?? {})) out.set(`@name:${culture}`, name)
|
|
116
|
+
for (const v of state.values) out.set(fieldOf(v), v.value)
|
|
117
|
+
return out
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const mediaIn = (state: ChangePageState | null) =>
|
|
121
|
+
new Set(JSON.stringify(state?.values ?? []).match(MEDIA_URL) ?? [])
|
|
122
|
+
|
|
123
|
+
export function createChangeTransfer(options: ChangeTransferOptions) {
|
|
124
|
+
const { db } = options
|
|
125
|
+
const repo = (kind: PageKind, workspace?: number) =>
|
|
126
|
+
new DocumentRepository(db, {
|
|
127
|
+
...options.repository,
|
|
128
|
+
...(workspace === undefined ? {} : { workspace }),
|
|
129
|
+
}).ofKind(kind as ContentKind)
|
|
130
|
+
|
|
131
|
+
async function stateAt(kind: PageKind, eventId: number | null) {
|
|
132
|
+
if (eventId === null) return null
|
|
133
|
+
const found = await repo(kind).atVersion(String(eventId))
|
|
134
|
+
return found ? found.document : null
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The change that left a page as this one found it: the one whose event it started from. */
|
|
138
|
+
async function lastChangeOfNode(
|
|
139
|
+
nodeKey: string,
|
|
140
|
+
from: number | null,
|
|
141
|
+
self: string,
|
|
142
|
+
): Promise<string | null> {
|
|
143
|
+
if (from === null) return null
|
|
144
|
+
const rows = await db.q
|
|
145
|
+
.selectFrom('content_transfer_change as c')
|
|
146
|
+
.innerJoin('content_transfer_run as r', 'r.id', 'c.run_id')
|
|
147
|
+
.select(['r.change_key', 'c.event_id'])
|
|
148
|
+
.where('c.node_key', '=', nodeKey)
|
|
149
|
+
.where('r.status', '=', 'applied')
|
|
150
|
+
.where('c.event_id', '<=', from)
|
|
151
|
+
.orderBy('c.event_id', 'desc')
|
|
152
|
+
.execute()
|
|
153
|
+
const earlier = rows.find((r) => String(r.change_key) !== self)
|
|
154
|
+
return earlier?.change_key ? String(earlier.change_key) : null
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** The changes that made the pages and media a state refers to. */
|
|
158
|
+
async function madeBy(states: ReadonlyArray<ChangePageState | null>, self: string) {
|
|
159
|
+
const keys = new Set<string>()
|
|
160
|
+
for (const state of states)
|
|
161
|
+
for (const m of JSON.stringify(state?.values ?? []).match(UUID) ?? [])
|
|
162
|
+
keys.add(normaliseUuid(m))
|
|
163
|
+
if (keys.size === 0) return []
|
|
164
|
+
const rows = await db.q
|
|
165
|
+
.selectFrom('content_transfer_change as c')
|
|
166
|
+
.innerJoin('content_transfer_run as r', 'r.id', 'c.run_id')
|
|
167
|
+
.select('r.change_key')
|
|
168
|
+
.where('c.node_key', 'in', [...keys])
|
|
169
|
+
.where('c.action', '=', 'create')
|
|
170
|
+
.where('r.status', '=', 'applied')
|
|
171
|
+
.execute()
|
|
172
|
+
return rows.map((r) => String(r.change_key ?? '')).filter((k) => k && k !== self)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async function mediaBytes(urls: Iterable<string>): Promise<Map<string, Uint8Array>> {
|
|
176
|
+
const out = new Map<string, Uint8Array>()
|
|
177
|
+
for (const url of urls) {
|
|
178
|
+
const file = await options.media.open(url)
|
|
179
|
+
if (file) out.set(url, new Uint8Array(await file.bytes()))
|
|
180
|
+
}
|
|
181
|
+
return out
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function bundleOf(input: {
|
|
185
|
+
key: string
|
|
186
|
+
name: string | null
|
|
187
|
+
kind: string
|
|
188
|
+
madeBy: string | null
|
|
189
|
+
createdAt: Date
|
|
190
|
+
depends: Iterable<string>
|
|
191
|
+
files: ChangeBundleFile[]
|
|
192
|
+
pages: ChangeBundlePage[]
|
|
193
|
+
}): ChangeBundle {
|
|
194
|
+
const added = new Set<string>()
|
|
195
|
+
for (const page of input.pages) {
|
|
196
|
+
const before = mediaIn(page.before)
|
|
197
|
+
for (const url of mediaIn(page.after)) if (!before.has(url)) added.add(url)
|
|
198
|
+
}
|
|
199
|
+
return {
|
|
200
|
+
key: normaliseUuid(input.key),
|
|
201
|
+
name: input.name,
|
|
202
|
+
kind: input.kind,
|
|
203
|
+
madeBy: input.madeBy,
|
|
204
|
+
createdAt: input.createdAt.toISOString(),
|
|
205
|
+
source: options.siteName(),
|
|
206
|
+
depends: [...new Set(input.depends)].filter((k) => k !== input.key).sort(),
|
|
207
|
+
files: input.files,
|
|
208
|
+
pages: input.pages,
|
|
209
|
+
media: [...added].sort(),
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const pageOf = (
|
|
214
|
+
key: string,
|
|
215
|
+
kind: PageKind,
|
|
216
|
+
action: ChangeBundlePage['action'],
|
|
217
|
+
shape: DocumentAggregate,
|
|
218
|
+
before: DocumentAggregate | null,
|
|
219
|
+
after: DocumentAggregate | null,
|
|
220
|
+
lastChange: string | null,
|
|
221
|
+
): ChangeBundlePage => ({
|
|
222
|
+
key: normaliseUuid(key),
|
|
223
|
+
kind,
|
|
224
|
+
action,
|
|
225
|
+
parentKey: shape.parentKey,
|
|
226
|
+
...(before && after && before.parentKey !== after.parentKey
|
|
227
|
+
? { beforeParentKey: before.parentKey }
|
|
228
|
+
: {}),
|
|
229
|
+
contentTypeKey: shape.contentTypeKey,
|
|
230
|
+
contentTypeAlias: shape.contentTypeAlias,
|
|
231
|
+
componentKey: shape.componentKey,
|
|
232
|
+
before: before ? stateOf(before) : null,
|
|
233
|
+
after: after ? stateOf(after) : null,
|
|
234
|
+
lastChange,
|
|
235
|
+
})
|
|
236
|
+
|
|
237
|
+
/** A change made here, as a bundle with the media it carries. */
|
|
238
|
+
async function exportChange(id: string) {
|
|
239
|
+
const changes = new ChangeRepository(db)
|
|
240
|
+
const change = await changes.byId(id)
|
|
241
|
+
if (!change) return undefined
|
|
242
|
+
const files: ChangeBundleFile[] = []
|
|
243
|
+
const items = await changes.itemsOf(change.id, { pages: true })
|
|
244
|
+
const removed = new Map(
|
|
245
|
+
items
|
|
246
|
+
.filter((i) => i.path.startsWith(REMOVED_PAGE_PREFIX) && i.before)
|
|
247
|
+
.map((i) => [
|
|
248
|
+
normaliseUuid(i.path.slice(REMOVED_PAGE_PREFIX.length)),
|
|
249
|
+
JSON.parse(i.before as string),
|
|
250
|
+
]),
|
|
251
|
+
) as Map<string, DocumentAggregate>
|
|
252
|
+
for (const item of items) {
|
|
253
|
+
if (item.path.startsWith(REMOVED_PAGE_PREFIX)) continue
|
|
254
|
+
const versions = await changes.versions(item.path)
|
|
255
|
+
const at = versions.findIndex((v) => v.changeId === change.id)
|
|
256
|
+
const earlier = at > 0 ? versions[at - 1] : undefined
|
|
257
|
+
const earlierChange = earlier ? await changes.byId(earlier.changeId) : undefined
|
|
258
|
+
files.push({
|
|
259
|
+
path: item.path,
|
|
260
|
+
kind: item.kind,
|
|
261
|
+
class: item.class,
|
|
262
|
+
before: item.before,
|
|
263
|
+
after: item.after,
|
|
264
|
+
lastChange: earlierChange?.key ?? null,
|
|
265
|
+
})
|
|
266
|
+
}
|
|
267
|
+
const pages: ChangeBundlePage[] = []
|
|
268
|
+
const depends: string[] = []
|
|
269
|
+
for (const row of await new TransferRunRepository(db).changes(change.id)) {
|
|
270
|
+
if (!isPageKind(row.kind)) continue
|
|
271
|
+
const before =
|
|
272
|
+
(await stateAt(row.kind, row.beforeEventId)) ??
|
|
273
|
+
removed.get(normaliseUuid(row.nodeKey)) ??
|
|
274
|
+
null
|
|
275
|
+
const after = row.action === 'recycle' ? null : await stateAt(row.kind, row.eventId)
|
|
276
|
+
const shape = after ?? before
|
|
277
|
+
if (!shape) continue
|
|
278
|
+
const action =
|
|
279
|
+
row.action === 'create' ? 'create' : row.action === 'recycle' ? 'delete' : 'update'
|
|
280
|
+
const page = pageOf(
|
|
281
|
+
row.nodeKey,
|
|
282
|
+
row.kind,
|
|
283
|
+
action,
|
|
284
|
+
shape,
|
|
285
|
+
before,
|
|
286
|
+
after,
|
|
287
|
+
await lastChangeOfNode(row.nodeKey, row.beforeEventId, change.key),
|
|
288
|
+
)
|
|
289
|
+
pages.push(page)
|
|
290
|
+
depends.push(...(await madeBy([page.after], change.key)))
|
|
291
|
+
if (page.lastChange && page.action !== 'create') depends.push(page.lastChange)
|
|
292
|
+
}
|
|
293
|
+
for (const f of files) if (f.lastChange) depends.push(f.lastChange)
|
|
294
|
+
const bundle = bundleOf({
|
|
295
|
+
key: change.key,
|
|
296
|
+
name: change.name,
|
|
297
|
+
kind: change.kind,
|
|
298
|
+
madeBy: change.madeBy,
|
|
299
|
+
createdAt: change.startedAt,
|
|
300
|
+
depends,
|
|
301
|
+
files,
|
|
302
|
+
pages,
|
|
303
|
+
})
|
|
304
|
+
return { change: bundle, media: await mediaBytes(bundle.media) }
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** An open workspace, as the change its merge will be: it keeps the workspace's key. */
|
|
308
|
+
async function exportWorkspace(workspace: Workspace) {
|
|
309
|
+
const files: ChangeBundleFile[] = (
|
|
310
|
+
await new WorkspaceFileRepository(db).changes(workspace.id)
|
|
311
|
+
).map((c) => ({
|
|
312
|
+
path: c.path,
|
|
313
|
+
kind: c.path.startsWith('schema/') ? 'definition' : 'file',
|
|
314
|
+
class: c.class ?? 'none',
|
|
315
|
+
before: c.base,
|
|
316
|
+
after: c.now,
|
|
317
|
+
lastChange: null,
|
|
318
|
+
}))
|
|
319
|
+
const pages: ChangeBundlePage[] = []
|
|
320
|
+
const made = (
|
|
321
|
+
await Promise.all(PAGE_KINDS.map((kind) => repo(kind, workspace.id).workspaceMergePages()))
|
|
322
|
+
).flat()
|
|
323
|
+
for (const page of made) {
|
|
324
|
+
if (!isPageKind(page.kind)) continue
|
|
325
|
+
const after = await repo(page.kind, workspace.id).byKey(page.key)
|
|
326
|
+
const before = page.made ? null : await stateAt(page.kind, page.baseEvent)
|
|
327
|
+
const shape = after ?? before
|
|
328
|
+
if (!shape) continue
|
|
329
|
+
pages.push(
|
|
330
|
+
pageOf(
|
|
331
|
+
page.key,
|
|
332
|
+
page.kind,
|
|
333
|
+
page.made ? 'create' : 'update',
|
|
334
|
+
shape,
|
|
335
|
+
before,
|
|
336
|
+
after ?? null,
|
|
337
|
+
null,
|
|
338
|
+
),
|
|
339
|
+
)
|
|
340
|
+
}
|
|
341
|
+
for (const pending of await new WorkspaceRepository(db).pending(workspace.id)) {
|
|
342
|
+
if (pending.kind !== 'delete' && pending.kind !== 'trash') continue
|
|
343
|
+
if (!pending.key) continue
|
|
344
|
+
const kind = (pending.objectKind ?? 'document') as PageKind
|
|
345
|
+
if (!isPageKind(kind)) continue
|
|
346
|
+
const before = (await repo(kind).byKey(pending.key)) ?? null
|
|
347
|
+
if (before) pages.push(pageOf(pending.key, kind, 'delete', before, before, null, null))
|
|
348
|
+
}
|
|
349
|
+
const bundle = bundleOf({
|
|
350
|
+
key: workspace.key,
|
|
351
|
+
name: workspace.name,
|
|
352
|
+
kind: 'workspace',
|
|
353
|
+
madeBy: workspace.ownerKey,
|
|
354
|
+
createdAt: new Date(),
|
|
355
|
+
depends: [],
|
|
356
|
+
files,
|
|
357
|
+
pages,
|
|
358
|
+
})
|
|
359
|
+
return { change: bundle, media: await mediaBytes(bundle.media) }
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** Every page edited since a point, as one change: each as it stood then, and now. */
|
|
363
|
+
async function exportSince(at: Date) {
|
|
364
|
+
const rows = await db.q
|
|
365
|
+
.selectFrom('content_version as v')
|
|
366
|
+
.innerJoin('node as n', 'n.id', 'v.node_id')
|
|
367
|
+
.select(['n.unique_id as key', 'n.node_object_type as type'])
|
|
368
|
+
.where('v.workspace_id', 'is', null)
|
|
369
|
+
.where('n.workspace_id', 'is', null)
|
|
370
|
+
.where('v.version_date', '>', DbDate.toDb(at) as never)
|
|
371
|
+
.groupBy(['n.unique_id', 'n.node_object_type'])
|
|
372
|
+
.execute()
|
|
373
|
+
const pages: ChangeBundlePage[] = []
|
|
374
|
+
for (const row of rows) {
|
|
375
|
+
const key = normaliseUuid(String(row.key))
|
|
376
|
+
for (const kind of PAGE_KINDS) {
|
|
377
|
+
const r = repo(kind)
|
|
378
|
+
const now = await r.byKey(key)
|
|
379
|
+
if (!now) continue
|
|
380
|
+
const versions = await r.versions(key)
|
|
381
|
+
const then = versions
|
|
382
|
+
.filter((v) => new Date(v.versionDate) <= at)
|
|
383
|
+
.sort((a, b) => new Date(b.versionDate).getTime() - new Date(a.versionDate).getTime())[0]
|
|
384
|
+
const before = then ? await stateAt(kind, Number(then.id)) : null
|
|
385
|
+
pages.push(pageOf(key, kind, before ? 'update' : 'create', now, before, now, null))
|
|
386
|
+
break
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
const bundle = bundleOf({
|
|
390
|
+
key: crypto.randomUUID(),
|
|
391
|
+
name: `Page edits since ${at.toISOString()}`,
|
|
392
|
+
kind: 'edits',
|
|
393
|
+
madeBy: null,
|
|
394
|
+
createdAt: new Date(),
|
|
395
|
+
depends: [],
|
|
396
|
+
files: [],
|
|
397
|
+
pages,
|
|
398
|
+
})
|
|
399
|
+
return { change: bundle, media: await mediaBytes(bundle.media) }
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Puts changes into a workspace on this site: each file with the change's
|
|
404
|
+
* before as its base, so the merge goes three ways against this site's now;
|
|
405
|
+
* each page with only the fields the change altered, a field this site
|
|
406
|
+
* changed since being a conflict.
|
|
407
|
+
*/
|
|
408
|
+
async function stage(
|
|
409
|
+
bundles: ReadonlyArray<{ change: ChangeBundle; media: Map<string, Uint8Array> }>,
|
|
410
|
+
principal: Principal,
|
|
411
|
+
into?: Workspace,
|
|
412
|
+
): Promise<StageOutcome> {
|
|
413
|
+
const changes = new ChangeRepository(db)
|
|
414
|
+
const keys = bundles.map((b) => b.change.key)
|
|
415
|
+
const held = await changes.held(keys)
|
|
416
|
+
const skipped = keys.filter((k) => held.has(normaliseUuid(k)))
|
|
417
|
+
const todo = bundles.filter((b) => !held.has(normaliseUuid(b.change.key)))
|
|
418
|
+
const conflicts: ChangeConflict[] = []
|
|
419
|
+
if (todo.length === 0) return { workspace: into, skipped, conflicts }
|
|
420
|
+
|
|
421
|
+
const coming = new Set(todo.map((b) => normaliseUuid(b.change.key)))
|
|
422
|
+
const known = await changes.held(todo.flatMap((b) => b.change.depends))
|
|
423
|
+
const workspaces = new WorkspaceRepository(db)
|
|
424
|
+
let workspace = into
|
|
425
|
+
if (!workspace) {
|
|
426
|
+
const name =
|
|
427
|
+
todo.length === 1
|
|
428
|
+
? `Change: ${todo[0]?.change.name ?? todo[0]?.change.key}`
|
|
429
|
+
: `${todo.length} changes`
|
|
430
|
+
workspace = await workspaces.open({ name, ownerKey: principal.id })
|
|
431
|
+
await options.schema()?.snapshot(workspace.id)
|
|
432
|
+
}
|
|
433
|
+
const store = new WorkspaceFileRepository(db)
|
|
434
|
+
let schemaTouched = false
|
|
435
|
+
for (const { change, media } of todo) {
|
|
436
|
+
const missing = change.depends.filter(
|
|
437
|
+
(d) => !known.has(normaliseUuid(d)) && !coming.has(normaliseUuid(d)),
|
|
438
|
+
)
|
|
439
|
+
const named = change.name ?? change.key
|
|
440
|
+
const conflict = (item: string, says: string) =>
|
|
441
|
+
conflicts.push({ change: change.key, item, says: `"${named}": ${says}` })
|
|
442
|
+
/** Says so, and answers true, when an item is not as the change found it for want of another change. */
|
|
443
|
+
const moved = (item: string): boolean => {
|
|
444
|
+
if (missing.length === 0) return false
|
|
445
|
+
conflict(
|
|
446
|
+
item,
|
|
447
|
+
`${item} is not as the change found it, and it needs ${missing.map((m) => `"${m}"`).join(', ')}, which this site does not have.`,
|
|
448
|
+
)
|
|
449
|
+
return true
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
for (const file of change.files) {
|
|
453
|
+
const now = (await store.files(workspace.id, file.path)).get(file.path) ?? null
|
|
454
|
+
if (now !== file.before && missing.length > 0) moved(file.path)
|
|
455
|
+
await store.rebase(workspace.id, file.path, file.before, file.after)
|
|
456
|
+
if (file.path.startsWith('schema/')) schemaTouched = true
|
|
457
|
+
}
|
|
458
|
+
for (const [url, bytes] of media) {
|
|
459
|
+
const key = options.media.key(url)
|
|
460
|
+
if (key) await options.media.store.put(key, bytes)
|
|
461
|
+
}
|
|
462
|
+
for (const page of change.pages) await stagePage(workspace, page, conflict, moved)
|
|
463
|
+
}
|
|
464
|
+
if (schemaTouched) await options.schema()?.build({ id: workspace.id, key: workspace.key })
|
|
465
|
+
const staged = [...(workspace.stagedChanges ?? [])]
|
|
466
|
+
for (const { change } of todo)
|
|
467
|
+
if (!staged.some((s) => s.key === change.key))
|
|
468
|
+
staged.push({ key: change.key, name: change.name })
|
|
469
|
+
await workspaces.setStaged(workspace.id, staged)
|
|
470
|
+
return { workspace: (await workspaces.byKey(workspace.key)) ?? workspace, skipped, conflicts }
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
async function stagePage(
|
|
474
|
+
workspace: Workspace,
|
|
475
|
+
page: ChangeBundlePage,
|
|
476
|
+
conflict: (item: string, says: string) => void,
|
|
477
|
+
moved: (item: string) => boolean,
|
|
478
|
+
) {
|
|
479
|
+
const shared = repo(page.kind)
|
|
480
|
+
const here = repo(page.kind, workspace.id)
|
|
481
|
+
const target = await shared.byKey(page.key)
|
|
482
|
+
const label = `"${page.after?.name ?? page.before?.name ?? page.key}"`
|
|
483
|
+
|
|
484
|
+
if (page.action === 'delete') {
|
|
485
|
+
if (!target) return
|
|
486
|
+
const now = stateOf(target)
|
|
487
|
+
if (!same([...fieldsOf(now)].sort(), [...fieldsOf(page.before)].sort())) {
|
|
488
|
+
moved(label)
|
|
489
|
+
conflict(label, `${label} was changed here since, so it is not deleted.`)
|
|
490
|
+
return
|
|
491
|
+
}
|
|
492
|
+
if (await stillUsed(page.key)) {
|
|
493
|
+
conflict(label, `${label} is still used here, so it is not deleted.`)
|
|
494
|
+
return
|
|
495
|
+
}
|
|
496
|
+
await here.delete(page.key)
|
|
497
|
+
return
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
const after = page.after as ChangePageState
|
|
501
|
+
if (!target) {
|
|
502
|
+
// Changed by the change, and never made here: the change that made it is missing.
|
|
503
|
+
if (page.action === 'update' && page.before && moved(label)) return
|
|
504
|
+
const clash = await sameAddress(page, after.name)
|
|
505
|
+
if (clash) {
|
|
506
|
+
conflict(label, `${label} was made here too, as "${clash}", at the same address.`)
|
|
507
|
+
return
|
|
508
|
+
}
|
|
509
|
+
await here.create({
|
|
510
|
+
key: page.key,
|
|
511
|
+
contentTypeKey: page.contentTypeKey,
|
|
512
|
+
componentKey: page.componentKey,
|
|
513
|
+
parentKey: page.parentKey,
|
|
514
|
+
values: after.values,
|
|
515
|
+
variants: variantsOf(after),
|
|
516
|
+
})
|
|
517
|
+
if (after.published) await here.publish(page.key, null)
|
|
518
|
+
return
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
const now = (await here.byKey(page.key)) ?? target
|
|
522
|
+
const nowFields = fieldsOf(stateOf(now))
|
|
523
|
+
const beforeFields = fieldsOf(page.before)
|
|
524
|
+
const afterFields = fieldsOf(after)
|
|
525
|
+
const taken = new Map<string, unknown>()
|
|
526
|
+
for (const field of new Set([...beforeFields.keys(), ...afterFields.keys()])) {
|
|
527
|
+
const b = beforeFields.get(field)
|
|
528
|
+
const a = afterFields.get(field)
|
|
529
|
+
if (same(a, b)) continue
|
|
530
|
+
const n = nowFields.get(field)
|
|
531
|
+
if (same(n, a)) continue
|
|
532
|
+
if (same(n, b)) taken.set(field, a)
|
|
533
|
+
else {
|
|
534
|
+
moved(label)
|
|
535
|
+
conflict(label, `${label}: ${field.split('|')[0]} was changed here since.`)
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
if (taken.size > 0) {
|
|
539
|
+
const values: ChangeValue[] = now.values.map((v) =>
|
|
540
|
+
taken.has(fieldOf(v)) ? { ...v, value: taken.get(fieldOf(v)) } : v,
|
|
541
|
+
)
|
|
542
|
+
for (const v of after.values)
|
|
543
|
+
if (taken.has(fieldOf(v)) && !values.some((x) => fieldOf(x) === fieldOf(v))) values.push(v)
|
|
544
|
+
const variants = now.variants.map((v) => ({
|
|
545
|
+
culture: v.culture,
|
|
546
|
+
segment: v.segment,
|
|
547
|
+
name: String(
|
|
548
|
+
taken.get(v.culture ? `@name:${v.culture}` : '@name') ??
|
|
549
|
+
(v.culture === null ? taken.get('@name') : undefined) ??
|
|
550
|
+
v.name,
|
|
551
|
+
),
|
|
552
|
+
}))
|
|
553
|
+
await here.update({
|
|
554
|
+
key: page.key,
|
|
555
|
+
contentTypeKey: now.contentTypeKey,
|
|
556
|
+
componentKey: now.componentKey,
|
|
557
|
+
parentKey: now.parentKey,
|
|
558
|
+
values: values as never,
|
|
559
|
+
variants,
|
|
560
|
+
})
|
|
561
|
+
}
|
|
562
|
+
if (page.beforeParentKey !== undefined && now.parentKey !== page.parentKey) {
|
|
563
|
+
if (now.parentKey === page.beforeParentKey) await here.move(page.key, page.parentKey)
|
|
564
|
+
else {
|
|
565
|
+
moved(label)
|
|
566
|
+
conflict(label, `${label} was moved here since.`)
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
if (taken.size > 0 && after.published) await here.publish(page.key, null)
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
const variantsOf = (state: ChangePageState) =>
|
|
573
|
+
state.names && Object.keys(state.names).length > 0
|
|
574
|
+
? Object.entries(state.names).map(([culture, name]) => ({ culture, segment: null, name }))
|
|
575
|
+
: [{ culture: null, segment: null, name: state.name }]
|
|
576
|
+
|
|
577
|
+
/** Whether anything else on this site names the page. */
|
|
578
|
+
async function stillUsed(key: string): Promise<boolean> {
|
|
579
|
+
const plain = normaliseUuid(key)
|
|
580
|
+
const rows = await db.q
|
|
581
|
+
.selectFrom('property_value')
|
|
582
|
+
.select('id')
|
|
583
|
+
.where('workspace_id', 'is', null)
|
|
584
|
+
.where((eb) =>
|
|
585
|
+
eb.or([
|
|
586
|
+
eb('varchar_value', 'like', `%${plain}%`),
|
|
587
|
+
eb('text_value', 'like', `%${plain}%`),
|
|
588
|
+
eb('text_value', 'like', `%${plain.replaceAll('-', '')}%`),
|
|
589
|
+
]),
|
|
590
|
+
)
|
|
591
|
+
.limit(1)
|
|
592
|
+
.execute()
|
|
593
|
+
return rows.length > 0
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** The name of another page already at the address a new one would take. */
|
|
597
|
+
async function sameAddress(page: ChangeBundlePage, name: string): Promise<string | undefined> {
|
|
598
|
+
const parent = page.parentKey ? await repo(page.kind).byKey(page.parentKey) : undefined
|
|
599
|
+
const siblings = await db.q
|
|
600
|
+
.selectFrom('node')
|
|
601
|
+
.select(['unique_id', 'text', 'parent_id'])
|
|
602
|
+
.where('workspace_id', 'is', null)
|
|
603
|
+
.where('text', '=', name)
|
|
604
|
+
.execute()
|
|
605
|
+
const parentId = parent
|
|
606
|
+
? (
|
|
607
|
+
await db.q
|
|
608
|
+
.selectFrom('node')
|
|
609
|
+
.select('id')
|
|
610
|
+
.where('unique_id', '=', page.parentKey as string)
|
|
611
|
+
.executeTakeFirst()
|
|
612
|
+
)?.id
|
|
613
|
+
: -1
|
|
614
|
+
const clash = siblings.find(
|
|
615
|
+
(s) =>
|
|
616
|
+
Number(s.parent_id) === Number(parentId) && normaliseUuid(String(s.unique_id)) !== page.key,
|
|
617
|
+
)
|
|
618
|
+
return clash ? String(clash.text) : undefined
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/**
|
|
622
|
+
* Applies changes: staged, then merged. Anything refused leaves the workspace
|
|
623
|
+
* holding them, open to edit, and changes nothing here.
|
|
624
|
+
*/
|
|
625
|
+
async function apply(
|
|
626
|
+
bundles: ReadonlyArray<{ change: ChangeBundle; media: Map<string, Uint8Array> }>,
|
|
627
|
+
principal: Principal,
|
|
628
|
+
run: { userId?: number; accepted?: readonly string[] },
|
|
629
|
+
): Promise<ApplyOutcome> {
|
|
630
|
+
const staged = await stage(bundles, principal)
|
|
631
|
+
const workspace = staged.workspace
|
|
632
|
+
if (!workspace) return { ok: true, skipped: staged.skipped, changeId: null }
|
|
633
|
+
const workspaces = new WorkspaceRepository(db)
|
|
634
|
+
if (staged.conflicts.length > 0) {
|
|
635
|
+
// Left to be settled: someone edits it, then merges it.
|
|
636
|
+
await workspaces.setStaged(workspace.id, workspace.stagedChanges, false)
|
|
637
|
+
return {
|
|
638
|
+
ok: false,
|
|
639
|
+
skipped: staged.skipped,
|
|
640
|
+
conflicts: staged.conflicts,
|
|
641
|
+
workspace: workspace.key,
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
return mergeStaged(workspace, principal, run, staged.skipped)
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/** A staged workspace's merge, recording each change it applies. */
|
|
648
|
+
async function mergeStaged(
|
|
649
|
+
workspace: Workspace,
|
|
650
|
+
principal: Principal,
|
|
651
|
+
run: { userId?: number; accepted?: readonly string[] },
|
|
652
|
+
skipped: string[] = [],
|
|
653
|
+
): Promise<ApplyOutcome> {
|
|
654
|
+
const merging = options.merge()
|
|
655
|
+
if (!merging) throw new Error('Workspaces are not turned on for this site.')
|
|
656
|
+
const applied = workspace.stagedChanges ?? []
|
|
657
|
+
const outcome = await merging.run(workspace, principal, {
|
|
658
|
+
...(run.userId === undefined ? {} : { userId: run.userId }),
|
|
659
|
+
...(run.accepted ? { accepted: run.accepted } : {}),
|
|
660
|
+
...(applied.length === 1 ? { changeKey: applied[0]?.key } : {}),
|
|
661
|
+
appliedChanges: applied,
|
|
662
|
+
})
|
|
663
|
+
if (!outcome.ok)
|
|
664
|
+
return {
|
|
665
|
+
ok: false,
|
|
666
|
+
skipped,
|
|
667
|
+
conflicts: outcome.blockers.map((says) => ({ change: workspace.key, item: '', says })),
|
|
668
|
+
workspace: workspace.key,
|
|
669
|
+
}
|
|
670
|
+
return { ok: true, skipped, changeId: outcome.changeId ?? null }
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
return { exportChange, exportWorkspace, exportSince, stage, apply, mergeStaged }
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
export type ChangeTransfer = ReturnType<typeof createChangeTransfer>
|