@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.
Files changed (46) 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 +162 -22
  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/host-token.ts +30 -1
  24. package/src/node-operations.ts +150 -2
  25. package/src/ports.ts +174 -52
  26. package/src/remote-changes.ts +279 -0
  27. package/src/remote-schema.ts +126 -0
  28. package/src/remote-workspaces.ts +82 -0
  29. package/src/remote.ts +289 -192
  30. package/src/schema-transfer.ts +240 -41
  31. package/src/schema.ts +7 -2
  32. package/src/seed/compile.ts +13 -1
  33. package/src/seed/values.ts +3 -0
  34. package/src/server.ts +971 -364
  35. package/src/settings.ts +123 -5
  36. package/src/site-sections.ts +1 -1
  37. package/src/workspace-access.ts +152 -0
  38. package/src/workspace-checks.ts +299 -0
  39. package/src/workspace-losses.ts +95 -0
  40. package/src/workspace-processes.ts +306 -0
  41. package/src/workspace-render-child.ts +168 -0
  42. package/src/workspace-schema-dir.ts +100 -0
  43. package/src/workspace-schema.ts +598 -0
  44. package/src/workspace-sites.ts +179 -0
  45. package/src/workspace-views.ts +121 -0
  46. package/src/workspaces.ts +1031 -0
@@ -9,7 +9,12 @@
9
9
  * and runs the sync a deploy runs, putting the files back if the sync refuses.
10
10
  * Only TOML in the folder's own layout is taken: `migrations/` is code, and an
11
11
  * upload never brings code.
12
+ *
13
+ * The command line reads the files and changes them by the definition (story
14
+ * 374): an edit names each file it writes or removes, with a hash of what it
15
+ * expects there, and is applied at once, as a type saved in the back office is.
12
16
  */
17
+ import { createHash } from 'node:crypto'
13
18
  import {
14
19
  cpSync,
15
20
  existsSync,
@@ -114,8 +119,8 @@ function placeLoose(
114
119
 
115
120
  const aliasOf = (text: string) => /^\s*alias\s*=\s*"([^"]+)"/m.exec(text)?.[1]
116
121
 
117
- /** Every TOML file under `dir`, by its `/`-separated path in it. */
118
- function schemaFiles(dir: string): Map<string, string> {
122
+ /** Every TOML file under `dir` in the schema folder's layout, by its `/`-separated path in it. */
123
+ export function schemaFilesIn(dir: string): Map<string, string> {
119
124
  const out = new Map<string, string>()
120
125
  const walk = (at: string) => {
121
126
  if (!existsSync(at)) return
@@ -161,10 +166,43 @@ export interface PendingSchemaImportView {
161
166
 
162
167
  export type SchemaOutcome<T = object> =
163
168
  | ({ ok: true } & T)
164
- | { ok: false; status: number; message: string; problems?: string[] }
169
+ | { ok: false; status: number; message: string; problems?: string[]; code?: string }
170
+
171
+ const refused = (status: number, message: string, problems?: string[], code?: string) =>
172
+ ({
173
+ ok: false,
174
+ status,
175
+ message,
176
+ ...(problems ? { problems } : {}),
177
+ ...(code ? { code } : {}),
178
+ }) as const
179
+
180
+ /** The hash an edit's `base` names a file by; null for no file. */
181
+ export const schemaFileHash = (text: string | undefined): string | null =>
182
+ text === undefined ? null : createHash('sha256').update(text).digest('hex')
165
183
 
166
- const refused = (status: number, message: string, problems?: string[]) =>
167
- ({ ok: false, status, message, ...(problems ? { problems } : {}) }) as const
184
+ /** Files written (text) or removed (null), by their path in `schema/`. */
185
+ export type SchemaWrites = Record<string, string | null>
186
+
187
+ /** A change to `schema/` by the definition, from the command line (story 374). */
188
+ export interface SchemaEdit {
189
+ edits: SchemaWrites
190
+ /** What each file is expected to hold now, by `schemaFileHash`; absent, it is not checked. */
191
+ base?: Record<string, string | null>
192
+ /** Retire a type the edit removes though items of it exist. */
193
+ retire?: boolean
194
+ dryRun?: boolean
195
+ }
196
+
197
+ export interface SchemaEditResult {
198
+ changed: boolean
199
+ /** What the sync did; absent for a dry run or no change. */
200
+ action?: string
201
+ /** The schema's version after it, or as it would be. */
202
+ version: string
203
+ /** What the check said the change does to the site's content. */
204
+ findings: string[]
205
+ }
168
206
 
169
207
  export function createSchemaTransfer(
170
208
  db: Db,
@@ -216,7 +254,12 @@ export function createSchemaTransfer(
216
254
  const file = join(config.schemaDir, 'schema.toml')
217
255
  const text = existsSync(file) ? readFileSync(file, 'utf8') : undefined
218
256
  const parsed = text ? parseSchemaSettings('schema.toml', text).value : undefined
219
- return { text, version: parsed?.version ?? '1.0.0', urls: parsed?.urls }
257
+ return {
258
+ text,
259
+ version: parsed?.version ?? '1.0.0',
260
+ urls: parsed?.urls,
261
+ environments: parsed?.environments,
262
+ }
220
263
  }
221
264
 
222
265
  /**
@@ -227,8 +270,14 @@ export function createSchemaTransfer(
227
270
  const current = currentSettings()
228
271
  const parsed = parseSchemaSettings('schema.toml', text)
229
272
  if (!parsed.value) return text
230
- const written = writeSchemaVersion(current.version, parsed.value.urls)
231
- return written === writeSchemaVersion(current.version, current.urls) ? undefined : written
273
+ const written = writeSchemaVersion(
274
+ current.version,
275
+ parsed.value.urls,
276
+ parsed.value.environments,
277
+ )
278
+ return written === writeSchemaVersion(current.version, current.urls, current.environments)
279
+ ? undefined
280
+ : written
232
281
  }
233
282
 
234
283
  /**
@@ -237,11 +286,15 @@ export function createSchemaTransfer(
237
286
  * the change needs, as the back office raises it for a type it saves, and
238
287
  * `schemaToml` is the file to write with it.
239
288
  */
240
- async function check(files: Record<string, string>) {
289
+ async function check(files: SchemaWrites) {
241
290
  const dir = mkdtempSync(join(tmpdir(), 'crombolo-import-'))
242
291
  try {
243
292
  if (existsSync(config.schemaDir)) cpSync(config.schemaDir, dir, { recursive: true })
244
293
  for (const [path, text] of Object.entries(files)) {
294
+ if (text === null) {
295
+ rmSync(join(dir, path), { force: true })
296
+ continue
297
+ }
245
298
  mkdirSync(dirname(join(dir, path)), { recursive: true })
246
299
  writeFileSync(join(dir, path), text)
247
300
  }
@@ -251,7 +304,7 @@ export function createSchemaTransfer(
251
304
  .map((p) => `${p.file}${p.path ? ` (${p.path})` : ''}: ${p.message}`)
252
305
  .map((line) => line.replaceAll(dir, 'schema'))
253
306
  for (const [path, text] of Object.entries(files))
254
- if (path.startsWith('webhooks/'))
307
+ if (path.startsWith('webhooks/') && text !== null)
255
308
  problems.push(...parseWebhookFile(path, text).problems.map((p) => `${path}: ${p}`))
256
309
  if (problems.length > 0) return { problems, findings: [] as Finding[], schemaToml: undefined }
257
310
  const run = () =>
@@ -289,12 +342,75 @@ export function createSchemaTransfer(
289
342
 
290
343
  const blocking = (findings: readonly Finding[]) => findings.some((f) => f.kind === 'blocking')
291
344
 
345
+ /** The paths among `base` whose file no longer holds what it names. */
346
+ const movedOn = (base: Record<string, string | null>) => {
347
+ const current = schemaFilesIn(config.schemaDir)
348
+ return Object.entries(base)
349
+ .filter(([path, hash]) => schemaFileHash(current.get(path)) !== hash)
350
+ .map(([path]) => path)
351
+ .sort()
352
+ }
353
+
354
+ /**
355
+ * Writes the files into `schema/` and syncs them, putting them back when the
356
+ * sync refuses; `base`, when given, is checked again under the lock.
357
+ */
358
+ async function commit(
359
+ writes: SchemaWrites,
360
+ how: { retire?: boolean; base?: Record<string, string | null>; what?: string } = {},
361
+ ): Promise<SchemaOutcome<{ action?: string }>> {
362
+ const before = new Map<string, string | undefined>()
363
+ const moved = await db.locks.withLock(Locks.Schema, async () => {
364
+ const moved = how.base ? movedOn(how.base) : []
365
+ if (moved.length > 0) return moved
366
+ for (const [path, text] of Object.entries(writes)) {
367
+ const target = join(config.schemaDir, path)
368
+ before.set(path, existsSync(target) ? readFileSync(target, 'utf8') : undefined)
369
+ if (text === null) rmSync(target, { force: true })
370
+ else {
371
+ mkdirSync(dirname(target), { recursive: true })
372
+ writeFileSync(target, text)
373
+ }
374
+ }
375
+ return []
376
+ })
377
+ if (moved.length > 0) return changedHere(moved)
378
+ const result = await importSchema(db, config, options.boot, {
379
+ materialise: false,
380
+ forceRetireTypes: how.retire === true,
381
+ })
382
+ if (result.report?.action === 'refused') {
383
+ await db.locks.withLock(Locks.Schema, async () => {
384
+ for (const [path, text] of before) {
385
+ const target = join(config.schemaDir, path)
386
+ if (text === undefined) rmSync(target, { force: true })
387
+ else writeFileSync(target, text)
388
+ }
389
+ })
390
+ return refused(
391
+ 409,
392
+ `The ${how.what ?? 'change'} was refused, and the schema is as it was: ${result.report.reason ?? 'see the server log'}.`,
393
+ )
394
+ }
395
+ if (config.schemaStore) await publishSchema(config.schemaStore as SchemaStore, config.schemaDir)
396
+ await options.afterApply?.(result.report)
397
+ return { ok: true, action: result.report?.action }
398
+ }
399
+
400
+ const changedHere = (paths: string[]) =>
401
+ refused(
402
+ 409,
403
+ 'The schema here has changed since those files were read.',
404
+ paths.map((path) => `${path}: changed here`),
405
+ 'changed-here',
406
+ )
407
+
292
408
  return {
293
409
  /** Every TOML file in `schema/`, as a zip that unpacks to a `schema` folder. */
294
410
  exportZip(): Uint8Array<ArrayBuffer> {
295
411
  const encoder = new TextEncoder()
296
412
  return writeZip(
297
- [...schemaFiles(config.schemaDir)]
413
+ [...schemaFilesIn(config.schemaDir)]
298
414
  .sort(([a], [b]) => a.localeCompare(b))
299
415
  .map(([path, text]) => ({ path: `schema/${path}`, bytes: encoder.encode(text) })),
300
416
  )
@@ -333,7 +449,7 @@ export function createSchemaTransfer(
333
449
  try {
334
450
  if (/\.toml$/i.test(fileName)) {
335
451
  const text = decoder.decode(bytes)
336
- const path = placeLoose(fileName, text, schemaFiles(config.schemaDir))
452
+ const path = placeLoose(fileName, text, schemaFilesIn(config.schemaDir))
337
453
  if (!path) outside.push(fileName)
338
454
  else files[path] = text
339
455
  } else {
@@ -359,7 +475,7 @@ export function createSchemaTransfer(
359
475
  if (settings === undefined) delete files['schema.toml']
360
476
  else files['schema.toml'] = settings
361
477
  }
362
- const current = schemaFiles(config.schemaDir)
478
+ const current = schemaFilesIn(config.schemaDir)
363
479
  const added = Object.keys(files).filter((path) => !current.has(path))
364
480
  const changed = Object.keys(files).filter(
365
481
  (path) => current.has(path) && current.get(path) !== files[path],
@@ -411,33 +527,9 @@ export function createSchemaTransfer(
411
527
  'Something on the Changes dashboard stops this import. Discard it, or fix the files and upload them again.',
412
528
  )
413
529
 
414
- const before = new Map<string, string | undefined>()
415
- await db.locks.withLock(Locks.Schema, async () => {
416
- const writes = { ...pending.files, ...(schemaToml ? { 'schema.toml': schemaToml } : {}) }
417
- for (const [path, text] of Object.entries(writes)) {
418
- const target = join(config.schemaDir, path)
419
- before.set(path, existsSync(target) ? readFileSync(target, 'utf8') : undefined)
420
- mkdirSync(dirname(target), { recursive: true })
421
- writeFileSync(target, text)
422
- }
423
- })
424
- const result = await importSchema(db, config, options.boot, { materialise: false })
425
- if (result.report?.action === 'refused') {
426
- await db.locks.withLock(Locks.Schema, async () => {
427
- for (const [path, text] of before) {
428
- const target = join(config.schemaDir, path)
429
- if (text === undefined) rmSync(target, { force: true })
430
- else writeFileSync(target, text)
431
- }
432
- })
433
- return refused(
434
- 409,
435
- `The import was refused, and the schema is as it was: ${result.report.reason ?? 'see the server log'}.`,
436
- )
437
- }
438
- if (config.schemaStore)
439
- await publishSchema(config.schemaStore as SchemaStore, config.schemaDir)
440
- await options.afterApply?.(result.report)
530
+ const writes = { ...pending.files, ...(schemaToml ? { 'schema.toml': schemaToml } : {}) }
531
+ const committed = await commit(writes, { what: 'import' })
532
+ if (!committed.ok) return committed
441
533
  await write(undefined)
442
534
  await writeReport(db, [], { source: 'import', scope: SCOPE })
443
535
  await audit(
@@ -445,7 +537,114 @@ export function createSchemaTransfer(
445
537
  'Apply',
446
538
  `${pending.fileName}: ${describe(pending.added, pending.changed)} (${[...pending.added, ...pending.changed].join(', ')})`,
447
539
  )
448
- return { ok: true, action: result.report?.action }
540
+ return { ok: true, action: committed.action }
541
+ },
542
+
543
+ /** Every TOML file in `schema/` by its path, with the version (story 374). */
544
+ files(): { version: string; files: Record<string, string> } {
545
+ const files = schemaFilesIn(config.schemaDir)
546
+ return {
547
+ version: currentSettings().version,
548
+ files: Object.fromEntries([...files].sort(([a], [b]) => a.localeCompare(b))),
549
+ }
550
+ },
551
+
552
+ /**
553
+ * Writes and removes the files an edit names, checked as an upload is, and
554
+ * syncs them at once (story 374). Refused, changing nothing, when a file no
555
+ * longer holds what `base` says, when the check finds problems, or when
556
+ * something would block it.
557
+ */
558
+ async edit(actor: SchemaActor, asked: SchemaEdit): Promise<SchemaOutcome<SchemaEditResult>> {
559
+ if (!config.schemaWritable)
560
+ return refused(
561
+ 409,
562
+ "This site's schema changes only with a deploy, so it can't be changed here.",
563
+ undefined,
564
+ 'not-writable',
565
+ )
566
+ const paths = Object.keys(asked.edits)
567
+ const wrong = paths.filter((path) => schemaPathOf(path) !== path)
568
+ if (wrong.length > 0)
569
+ return refused(
570
+ 400,
571
+ 'Only schema files can be changed: TOML, in the folders a schema folder has.',
572
+ wrong.slice(0, 20).map((path) => `${path}: not a schema file`),
573
+ )
574
+ const texts = Object.values(asked.edits).filter((text): text is string => text !== null)
575
+ if (
576
+ paths.length > UPLOAD_LIMITS.maxEntries ||
577
+ texts.some((text) => text.length > UPLOAD_LIMITS.maxEntryBytes) ||
578
+ texts.reduce((sum, text) => sum + text.length, 0) > UPLOAD_LIMITS.maxTotalBytes
579
+ )
580
+ return refused(413, 'That is too large to be a schema.')
581
+ if (asked.edits['schema.toml'] === null)
582
+ return refused(400, 'schema.toml is kept: it can be changed, not removed.')
583
+ if (asked.base) {
584
+ const moved = movedOn(asked.base)
585
+ if (moved.length > 0) return changedHere(moved)
586
+ }
587
+
588
+ const current = schemaFilesIn(config.schemaDir)
589
+ const edits: SchemaWrites = {}
590
+ for (const [path, text] of Object.entries(asked.edits)) {
591
+ if (path === 'schema.toml') {
592
+ const settings = settingsFrom(text as string)
593
+ if (settings !== undefined) edits[path] = settings
594
+ } else if (text === null ? current.has(path) : current.get(path) !== text)
595
+ edits[path] = text
596
+ }
597
+ const version = currentSettings().version
598
+ if (Object.keys(edits).length === 0)
599
+ return { ok: true, changed: false, version, findings: [] }
600
+
601
+ const { problems, findings, schemaToml } = await check(edits)
602
+ if (problems.length > 0)
603
+ return refused(400, 'The site would not accept it.', problems.slice(0, 50), 'problems')
604
+ const stopping = findings.filter(
605
+ (f) => f.kind === 'blocking' && !(asked.retire && f.code === 'type-removed-with-content'),
606
+ )
607
+ if (stopping.length > 0)
608
+ return refused(
609
+ 409,
610
+ "It would change the site's content.",
611
+ stopping.map((f) => f.message),
612
+ stopping.some((f) => f.code === 'type-removed-with-content')
613
+ ? 'removed-with-content'
614
+ : 'blocked',
615
+ )
616
+ const notes = findings
617
+ .filter((f) => f.kind === 'auto' || f.kind === 'person')
618
+ .map((f) => f.message)
619
+ const next = schemaToml
620
+ ? (parseSchemaSettings('schema.toml', schemaToml).value?.version ?? version)
621
+ : version
622
+ if (asked.dryRun) return { ok: true, changed: false, version: next, findings: notes }
623
+
624
+ const committed = await commit(
625
+ { ...edits, ...(schemaToml ? { 'schema.toml': schemaToml } : {}) },
626
+ { retire: asked.retire, base: asked.base },
627
+ )
628
+ if (!committed.ok) return committed
629
+ const written = Object.keys(edits).filter((path) => edits[path] !== null)
630
+ const removed = Object.keys(edits).filter((path) => edits[path] === null)
631
+ await audit(
632
+ actor,
633
+ 'Save',
634
+ `from the command line: ${[
635
+ written.length > 0 ? `wrote ${written.sort().join(', ')}` : '',
636
+ removed.length > 0 ? `removed ${removed.sort().join(', ')}` : '',
637
+ ]
638
+ .filter(Boolean)
639
+ .join('; ')}`,
640
+ )
641
+ return {
642
+ ok: true,
643
+ changed: true,
644
+ action: committed.action,
645
+ version: next,
646
+ findings: notes,
647
+ }
449
648
  },
450
649
 
451
650
  async discard(actor: SchemaActor): Promise<SchemaOutcome> {
package/src/schema.ts CHANGED
@@ -578,7 +578,7 @@ export async function importSchema(
578
578
  db: Db,
579
579
  config: CromboloConfig,
580
580
  boot: { nodeId: string; nodeState: NodeSchemaState },
581
- options: { dryRun?: boolean; materialise?: boolean } = {},
581
+ options: { dryRun?: boolean; materialise?: boolean; forceRetireTypes?: boolean } = {},
582
582
  ): Promise<SchemaImportResult> {
583
583
  // A caller that has just written into the directory says not to, or the store's
584
584
  // older copy would be laid over its write.
@@ -598,7 +598,12 @@ export async function importSchema(
598
598
  }
599
599
  }
600
600
 
601
- const report = await syncSchemaDirectory(db, config, node)
601
+ const report = await syncSchemaDirectory(
602
+ db,
603
+ config,
604
+ node,
605
+ options.forceRetireTypes ? { forceRetireTypes: true } : {},
606
+ )
602
607
  if (report.action === 'applied') {
603
608
  boot.nodeState.version = loadSchemaDirectory(config.schemaDir, {
604
609
  formTypes: formTypesFor(config),
@@ -411,8 +411,19 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
411
411
  culture: string | null,
412
412
  path: string[],
413
413
  ) => {
414
- for (const [alias, raw] of Object.entries(table)) {
414
+ for (const [named, raw] of Object.entries(table)) {
415
+ // Story 387: `title@production` is the value for one environment.
416
+ const [alias, environment] = named.split('@') as [string, string | undefined]
415
417
  const property = editors.get(alias)
418
+ if (property && environment !== undefined && !property.variesByEnvironment) {
419
+ find(
420
+ item,
421
+ [...path, named],
422
+ 'not-by-environment',
423
+ `"${alias}" is the same in every environment, so it takes no @${environment}`,
424
+ )
425
+ continue
426
+ }
416
427
  if (!property) {
417
428
  const iso =
418
429
  culture === null && isRecord(raw) ? languages.get(alias.toLowerCase()) : undefined
@@ -443,6 +454,7 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
443
454
  property: alias,
444
455
  culture,
445
456
  segment: null,
457
+ ...(environment ? { environment } : {}),
446
458
  editor: property.editor,
447
459
  value: converted.value,
448
460
  ...(references.length > 0 ? { references } : {}),
@@ -36,6 +36,8 @@ const fail = (message: string): Converted => ({ ok: false, message })
36
36
  export interface PropertyEditor {
37
37
  editor: string
38
38
  variesByCulture: boolean
39
+ /** A value per environment as well as a shared one (story 387). */
40
+ variesByEnvironment?: boolean
39
41
  /** The data type's settings, by alias: a block list's `blocks`, say. */
40
42
  config: Record<string, unknown>
41
43
  }
@@ -79,6 +81,7 @@ export function schemaLookup(db: Db) {
79
81
  out.set(property.alias, {
80
82
  editor: dataType.editorAlias,
81
83
  variesByCulture: property.variesByCulture,
84
+ ...(property.variesByEnvironment ? { variesByEnvironment: true } : {}),
82
85
  config: Object.fromEntries(dataType.values.map((v) => [v.alias, v.value])),
83
86
  })
84
87
  }