@crombolo/server 0.69.1 → 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.
Files changed (45) 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/workspace-dictionary.ts +287 -0
  10. package/src/adapters/workspace-file-port.ts +160 -0
  11. package/src/adapters/workspace-languages.ts +94 -0
  12. package/src/approvals-api.ts +16 -7
  13. package/src/bundle-api.ts +19 -16
  14. package/src/bundle-install.ts +4 -0
  15. package/src/change-transfer.ts +676 -0
  16. package/src/changes-api.ts +258 -0
  17. package/src/component-templates-api.ts +2 -2
  18. package/src/config.ts +161 -21
  19. package/src/content-events.ts +65 -1
  20. package/src/content-operations.ts +22 -3
  21. package/src/core.ts +2 -0
  22. package/src/environment-values-api.ts +161 -0
  23. package/src/node-operations.ts +150 -2
  24. package/src/ports.ts +174 -52
  25. package/src/remote-changes.ts +279 -0
  26. package/src/remote-schema.ts +126 -0
  27. package/src/remote-workspaces.ts +82 -0
  28. package/src/remote.ts +289 -192
  29. package/src/schema-transfer.ts +240 -41
  30. package/src/schema.ts +7 -2
  31. package/src/seed/compile.ts +13 -1
  32. package/src/seed/values.ts +3 -0
  33. package/src/server.ts +948 -364
  34. package/src/settings.ts +123 -5
  35. package/src/site-sections.ts +1 -1
  36. package/src/workspace-access.ts +152 -0
  37. package/src/workspace-checks.ts +299 -0
  38. package/src/workspace-losses.ts +95 -0
  39. package/src/workspace-processes.ts +306 -0
  40. package/src/workspace-render-child.ts +168 -0
  41. package/src/workspace-schema-dir.ts +100 -0
  42. package/src/workspace-schema.ts +598 -0
  43. package/src/workspace-sites.ts +179 -0
  44. package/src/workspace-views.ts +121 -0
  45. package/src/workspaces.ts +1031 -0
@@ -12,7 +12,7 @@ import type {
12
12
  EventSink,
13
13
  MediaOperations,
14
14
  } from '@crombolo/content'
15
- import { currentSchemaState, type Db } from '@crombolo/data'
15
+ import { currentSchemaState, type Db, WorkspaceRepository } from '@crombolo/data'
16
16
  import { PublishedCache } from '@crombolo/render'
17
17
  import { createPublishedContentSource } from './adapters/documents.ts'
18
18
  import { backOfficeUrl } from './back-office-url.ts'
@@ -34,6 +34,13 @@ export interface SiteOperations {
34
34
  export async function siteDocumentOperations(
35
35
  db: Db,
36
36
  config: CromboloConfig,
37
+ options: {
38
+ /**
39
+ * Story 386: where workspaces are on, a command's change goes into this person's
40
+ * own workspace, opened for them and named when it is pushed or merged.
41
+ */
42
+ ownWorkspaceOf?: { key: string; name: string }
43
+ } = {},
37
44
  ): Promise<SiteOperations> {
38
45
  const state = await currentSchemaState(db)
39
46
  const nodeState = { version: state.version, revision: state.revision }
@@ -51,7 +58,7 @@ export async function siteDocumentOperations(
51
58
  const cache = new PublishedCache(createPublishedContentSource(db, { nodeState }))
52
59
  // The routes a redirect is tracked from are read from this cache once a change
53
60
  // has committed, so the change drops it first.
54
- const { documents: operations } = createNodeOperations({
61
+ const nodeOperations = createNodeOperations({
55
62
  db,
56
63
  config,
57
64
  cache,
@@ -65,7 +72,19 @@ export async function siteDocumentOperations(
65
72
  webhooks,
66
73
  backOfficeUrl: backOfficeUrl(config),
67
74
  })
68
- return { operations, events }
75
+ const owner = options.ownWorkspaceOf
76
+ if (owner && config.workspaces) {
77
+ const workspaces = new WorkspaceRepository(db)
78
+ const own =
79
+ (await workspaces.ownOf(owner.key)) ??
80
+ (await workspaces.open({
81
+ name: `Changes by ${owner.name}`,
82
+ ownerKey: owner.key,
83
+ personal: true,
84
+ }))
85
+ return { operations: nodeOperations.documentsIn(own), events }
86
+ }
87
+ return { operations: nodeOperations.documents, events }
69
88
  }
70
89
 
71
90
  /**
package/src/core.ts CHANGED
@@ -411,6 +411,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
411
411
  const publishedSource = createPublishedContentSource(db, {
412
412
  nodeState: schema.nodeState,
413
413
  nodeId: schema.nodeId,
414
+ environment: config.environment,
414
415
  })
415
416
  // Media is cached apart from the pages (story 197), item by item within a
416
417
  // budget, and shared by the published and draft caches: media has no drafts.
@@ -594,6 +595,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
594
595
  wake('search')
595
596
  },
596
597
  nudge: () => wake('events'),
598
+ changes: true,
597
599
  })
598
600
  const operations = createNodeOperations({
599
601
  db,
@@ -0,0 +1,161 @@
1
+ /**
2
+ * A property's value per environment, edited beside its field (story 387), at
3
+ * `<plugin>/api/environment-values`: which environment this copy of the site is and
4
+ * which the schema names; a page's properties that vary by environment, each with
5
+ * its shared value and every environment's own; and one environment's value set or
6
+ * cleared, saved as any edit of the page is. docs/environments.md.
7
+ */
8
+ import type { Principal } from '@crombolo/api-management/domain'
9
+ import { type DocumentOperations, userActor } from '@crombolo/content'
10
+ import { type DocumentValue, normaliseUuid } from '@crombolo/core'
11
+ import {
12
+ ContentTypeRepository,
13
+ type Db,
14
+ DocumentRepository,
15
+ type DocumentRepositoryOptions,
16
+ readEnvironments,
17
+ } from '@crombolo/data'
18
+
19
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
20
+ const json = (body: unknown, status = 200) => Response.json(body, { status })
21
+ const refused = (message: string, status: number) => json({ message }, status)
22
+
23
+ /** One property's values: the shared one, and each environment's that overrides it. */
24
+ export interface EnvironmentValues {
25
+ alias: string
26
+ name: string
27
+ culture: string | null
28
+ segment: string | null
29
+ shared: unknown
30
+ overrides: Array<{ environment: string; value: unknown; known: boolean }>
31
+ }
32
+
33
+ export function createEnvironmentValuesApi(
34
+ db: Db,
35
+ options: {
36
+ environment: () => string
37
+ repository: DocumentRepositoryOptions
38
+ documents: () => DocumentOperations
39
+ /** The values can only arrive by a change here (`environmentValues.readOnly`, or locked content). */
40
+ readOnly: () => boolean
41
+ },
42
+ ) {
43
+ /** The properties of a page that vary by environment, with each of their values. */
44
+ async function valuesOf(key: string): Promise<EnvironmentValues[] | undefined> {
45
+ const page = await new DocumentRepository(db, options.repository).byKey(key)
46
+ if (!page) return undefined
47
+ const type = await new ContentTypeRepository(db).byKey(page.contentTypeKey)
48
+ const names = new Set(await readEnvironments(db))
49
+ const varying = (type?.properties ?? []).filter((p) => p.variesByEnvironment)
50
+ const out: EnvironmentValues[] = []
51
+ for (const property of varying) {
52
+ const mine = page.values.filter((v) => v.alias === property.alias)
53
+ const slots = new Map<string, EnvironmentValues>()
54
+ const slotOf = (v: DocumentValue) => {
55
+ const id = `${v.culture ?? ''}|${v.segment ?? ''}`
56
+ let slot = slots.get(id)
57
+ if (!slot) {
58
+ slot = {
59
+ alias: property.alias,
60
+ name: property.name,
61
+ culture: v.culture,
62
+ segment: v.segment,
63
+ shared: null,
64
+ overrides: [],
65
+ }
66
+ slots.set(id, slot)
67
+ }
68
+ return slot
69
+ }
70
+ for (const v of mine) {
71
+ const slot = slotOf(v)
72
+ if (v.environment)
73
+ slot.overrides.push({
74
+ environment: v.environment,
75
+ value: v.value,
76
+ known: names.has(v.environment),
77
+ })
78
+ else slot.shared = v.value
79
+ }
80
+ if (slots.size === 0)
81
+ slots.set('|', {
82
+ alias: property.alias,
83
+ name: property.name,
84
+ culture: null,
85
+ segment: null,
86
+ shared: null,
87
+ overrides: [],
88
+ })
89
+ out.push(...slots.values())
90
+ }
91
+ return out
92
+ }
93
+
94
+ return {
95
+ valuesOf,
96
+
97
+ async handle(request: Request, principal: Principal, rest: string): Promise<Response> {
98
+ const parts = rest.split('/').filter(Boolean)
99
+ if (parts.length === 0 && request.method === 'GET')
100
+ return json({
101
+ current: options.environment(),
102
+ names: await readEnvironments(db),
103
+ readOnly: options.readOnly(),
104
+ })
105
+ const key = parts[0]
106
+ if (parts.length !== 1 || !key || !UUID.test(key))
107
+ return refused('There is no such page.', 404)
108
+ if (request.method === 'GET') {
109
+ // A page not saved yet has none: the editor asks as it opens one.
110
+ return json({ items: (await valuesOf(normaliseUuid(key))) ?? [] })
111
+ }
112
+ if (request.method !== 'PUT') return new Response(null, { status: 405 })
113
+ if (options.readOnly())
114
+ return refused(
115
+ "This environment's values arrive only by a change applied from where they are made.",
116
+ 409,
117
+ )
118
+ const asked = ((await request.json().catch(() => ({}))) ?? {}) as Record<string, unknown>
119
+ const alias = typeof asked.alias === 'string' ? asked.alias : ''
120
+ const environment = typeof asked.environment === 'string' ? asked.environment : ''
121
+ const culture = typeof asked.culture === 'string' ? asked.culture : null
122
+ const segment = typeof asked.segment === 'string' ? asked.segment : null
123
+ if (!alias || !/^[a-z][a-z0-9-]{0,63}$/.test(environment))
124
+ return refused('Name the property and the environment.', 400)
125
+ const page = await new DocumentRepository(db, options.repository).byKey(normaliseUuid(key))
126
+ if (!page) return refused('There is no such page.', 404)
127
+ const type = await new ContentTypeRepository(db).byKey(page.contentTypeKey)
128
+ if (!type?.properties.some((p) => p.alias === alias && p.variesByEnvironment))
129
+ return refused(`"${alias}" does not vary by environment.`, 400)
130
+ const same = (v: DocumentValue) =>
131
+ v.alias === alias &&
132
+ (v.culture ?? null) === culture &&
133
+ (v.segment ?? null) === segment &&
134
+ v.environment === environment
135
+ // Every value is sent: one it leaves out of the property's environments is cleared.
136
+ const values: DocumentValue[] = page.values.filter((v) => !same(v))
137
+ if (asked.value !== null && asked.value !== undefined && asked.value !== '')
138
+ values.push({ alias, culture, segment, environment, value: asked.value })
139
+ const saved = await options.documents().save(
140
+ userActor(principal),
141
+ page.key,
142
+ {
143
+ key: page.key,
144
+ contentTypeKey: page.contentTypeKey,
145
+ componentKey: page.componentKey,
146
+ parentKey: page.parentKey,
147
+ values,
148
+ variants: page.variants.map((v) => ({
149
+ culture: v.culture,
150
+ segment: v.segment,
151
+ name: v.name,
152
+ })),
153
+ },
154
+ // Saved on the copy it was just read at, as an editor's save names its revision.
155
+ page.revision ? { expectedRevision: page.revision } : {},
156
+ )
157
+ if (!saved.ok) return refused(saved.reason, saved.status)
158
+ return json({ items: (await valuesOf(page.key)) ?? [] })
159
+ },
160
+ }
161
+ }
@@ -4,27 +4,41 @@
4
4
  * and shared by the Management API, the jobs and the command line, so a worker
5
5
  * (story 223) publishes a schedule exactly as an editor's node does.
6
6
  */
7
+ import type { Principal } from '@crombolo/api-management/domain'
7
8
  import {
8
9
  createDocumentOperations,
9
10
  createElementOperations,
10
11
  createMediaOperations,
12
+ createWorkspaceOperations,
11
13
  type DocumentOperations,
12
14
  type ElementOperations,
13
15
  type EventSink,
14
16
  type MediaOperations,
17
+ type MergePlan,
18
+ previewWorkspaceMerge,
19
+ runWorkspaceMerge,
15
20
  SILENT,
21
+ userActor,
22
+ type WorkspaceFileMerging,
23
+ type WorkspaceMergeOutcome,
24
+ workspaceAuditSink,
16
25
  } from '@crombolo/content'
17
26
  import {
18
27
  appendCacheInstruction,
19
28
  type Db,
20
29
  type NodeSchemaState,
21
30
  RedirectRepository,
31
+ type Workspace,
22
32
  } from '@crombolo/data'
23
33
  import type { PublishedCache } from '@crombolo/render'
24
34
  import { createElementPort } from './adapters/elements.ts'
25
35
  import { type Approvals, approvalsGate, createApprovals } from './approvals.ts'
26
36
  import type { CromboloConfig } from './config.ts'
27
- import { createElementEventSink, createMediaEventSink } from './content-events.ts'
37
+ import {
38
+ createElementEventSink,
39
+ createMediaEventSink,
40
+ workspaceElementEventSink,
41
+ } from './content-events.ts'
28
42
  import type { ContentNotifier } from './content-notifications.ts'
29
43
  import { writeDomainsFor } from './domains.ts'
30
44
  import type { EmailPort } from './email.ts'
@@ -32,15 +46,42 @@ import { createFileIntake, TemporaryFileMissingError } from './file-intake.ts'
32
46
  import type { MediaFileStore } from './media-files.ts'
33
47
  import { createRedirectTracker, NO_REDIRECT_TRACKING, type RedirectTracker } from './redirects.ts'
34
48
  import type { WebhookService } from './webhooks.ts'
49
+ import { createWorkspaceSchema, type FileMergePlan } from './workspace-schema.ts'
35
50
 
36
51
  export interface NodeOperations {
37
52
  valueIntake: ReturnType<typeof createFileIntake>
38
53
  tracker: RedirectTracker
39
54
  approvals: Approvals
40
55
  documents: DocumentOperations
56
+ /** The document operations in a workspace (story 375). */
57
+ documentsIn(workspace: Workspace): DocumentOperations
58
+ /** Its media and Library operations (story 390). */
59
+ mediaIn(workspace: Workspace): MediaOperations
60
+ elementsIn(workspace: Workspace): ElementOperations
41
61
  media: MediaOperations
42
62
  /** Every Library write (story 361). */
43
63
  elements: ElementOperations
64
+ /** Merging a workspace into Shared (story 380). */
65
+ merge: WorkspaceMerging
66
+ }
67
+
68
+ /** A workspace's merge: what it would do, and doing it, as the person merging. */
69
+ export interface WorkspaceMerging {
70
+ preview(workspace: Workspace): Promise<MergePlan>
71
+ /** One workspace, several as one, or `only` one page of a person's own. */
72
+ run(
73
+ workspaces: Workspace | readonly Workspace[],
74
+ principal: Principal,
75
+ options: {
76
+ userId?: number
77
+ accepted?: readonly string[]
78
+ rehearse?: boolean
79
+ only?: string
80
+ /** Story 383: the identity its change takes, and the changes from other sites it applies. */
81
+ changeKey?: string
82
+ appliedChanges?: ReadonlyArray<{ key: string; name: string | null }>
83
+ },
84
+ ): Promise<WorkspaceMergeOutcome>
44
85
  }
45
86
 
46
87
  export interface NodeOperationsOptions {
@@ -138,5 +179,112 @@ export function createNodeOperations(options: NodeOperationsOptions): NodeOperat
138
179
  events: createElementEventSink(),
139
180
  onChange: () => cache?.invalidate(),
140
181
  })
141
- return { valueIntake: repository.valueIntake, tracker, approvals, documents, media, elements }
182
+ /** A workspace's media and Library (story 390): audited, announced nowhere else. */
183
+ const mediaIn = (workspace: Workspace): MediaOperations =>
184
+ createMediaOperations({
185
+ db,
186
+ repository: { ...repository, workspace: workspace.id },
187
+ events: workspaceAuditSink(workspace.name),
188
+ files: options.mediaFiles,
189
+ refusalReason,
190
+ })
191
+ const elementsIn = (workspace: Workspace): ElementOperations =>
192
+ createElementOperations({
193
+ db,
194
+ store: (tx) =>
195
+ createElementPort(tx, {
196
+ nodeState: options.nodeState,
197
+ nodeId: options.nodeId,
198
+ valueIntake: repository.valueIntake,
199
+ workspace: workspace.id,
200
+ }),
201
+ events: workspaceElementEventSink(workspace.name),
202
+ })
203
+ /** The document operations in a workspace (story 375): its pages, audited, announced nowhere else. */
204
+ const documentsIn = (workspace: Workspace): DocumentOperations =>
205
+ createWorkspaceOperations(
206
+ { db, repository, refusalReason },
207
+ { id: workspace.id, name: workspace.name },
208
+ )
209
+ const gate = approvalsGate(approvals)
210
+ // Story 376: a workspace's files merge before its pages, on the same transaction.
211
+ const workspaceSchema = options.nodeState
212
+ ? createWorkspaceSchema(db, options.config, {
213
+ nodeId: options.nodeId ?? 'node',
214
+ nodeState: options.nodeState,
215
+ })
216
+ : undefined
217
+ const files: WorkspaceFileMerging | undefined = workspaceSchema && {
218
+ async plan(workspaceId, tx) {
219
+ const planned = await workspaceSchema.plan(workspaceId, tx)
220
+ return {
221
+ conflicts: [
222
+ ...planned.conflicts.map(
223
+ (c) =>
224
+ `The ${c.definition ? 'definition' : 'file'} ${c.path} was changed in both the workspace and Shared.`,
225
+ ),
226
+ // Story 377: a component that would not work with Shared's, saying where.
227
+ ...planned.problems.map((p) => `A component would break: ${p}`),
228
+ ],
229
+ // Story 382: what loses data, removes or renames, each accepted by name or kind.
230
+ findings: planned.items
231
+ .filter((i) => i.accept)
232
+ .map((i) => ({
233
+ id: i.id,
234
+ kind: i.kind,
235
+ says: `${i.says}${i.pages ? ` ${i.pages} page(s) hold a value for it.` : ''} Accept "${i.id}" or "${i.kind}" to go ahead.`,
236
+ })),
237
+ ready: planned,
238
+ }
239
+ },
240
+ apply: (tx, ready) => workspaceSchema.apply(tx, ready as FileMergePlan),
241
+ }
242
+ const merge: WorkspaceMerging = {
243
+ preview: (workspace) => previewWorkspaceMerge(db, repository, workspace),
244
+ async run(chosen, principal, run) {
245
+ const list: readonly Workspace[] = Array.isArray(chosen) ? chosen : [chosen as Workspace]
246
+ const names = list.map((w) => `"${w.name}"`).join(', ')
247
+ const outcome = await runWorkspaceMerge(list, {
248
+ db,
249
+ repository,
250
+ events: options.contentEvents ?? SILENT,
251
+ actor: userActor(principal, {
252
+ via: `a merge of ${list.length > 1 ? 'the workspaces' : 'the workspace'} ${names}`,
253
+ }),
254
+ userId: run.userId,
255
+ userKey: principal.id,
256
+ accepted: run.accepted,
257
+ rehearse: run.rehearse,
258
+ ...(run.only === undefined ? {} : { only: run.only }),
259
+ ...(run.changeKey ? { changeKey: run.changeKey } : {}),
260
+ ...(run.appliedChanges ? { appliedChanges: run.appliedChanges } : {}),
261
+ ...(files ? { files } : {}),
262
+ publishRefusal: (key, action) => gate.publishRefusal(principal, key, action),
263
+ })
264
+ if (!outcome.ok || outcome.rehearsed) return outcome
265
+ cache?.invalidate()
266
+ // A page a workflow covers arrives as a draft, and its publish waits for approval.
267
+ for (const page of outcome.forApproval)
268
+ await approvals.send(
269
+ principal,
270
+ page.key,
271
+ page.action,
272
+ page.cultures,
273
+ `Merged from ${list.length > 1 ? 'the workspaces' : 'the workspace'} ${names}`,
274
+ )
275
+ return outcome
276
+ },
277
+ }
278
+ return {
279
+ valueIntake: repository.valueIntake,
280
+ tracker,
281
+ approvals,
282
+ merge,
283
+ documents,
284
+ documentsIn,
285
+ mediaIn,
286
+ elementsIn,
287
+ media,
288
+ elements,
289
+ }
142
290
  }