@crombolo/server 0.69.1 → 0.71.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/package.json +15 -14
  2. package/src/adapters/blueprints.ts +51 -5
  3. package/src/adapters/change-recording.ts +140 -0
  4. package/src/adapters/content.ts +132 -21
  5. package/src/adapters/documents.ts +26 -5
  6. package/src/adapters/elements.ts +3 -0
  7. package/src/adapters/media.ts +7 -1
  8. package/src/adapters/schema-files.ts +89 -1
  9. package/src/adapters/users.ts +17 -12
  10. package/src/adapters/workspace-dictionary.ts +287 -0
  11. package/src/adapters/workspace-file-port.ts +160 -0
  12. package/src/adapters/workspace-languages.ts +94 -0
  13. package/src/approvals-api.ts +16 -7
  14. package/src/bundle-api.ts +19 -16
  15. package/src/bundle-install.ts +4 -0
  16. package/src/change-transfer.ts +676 -0
  17. package/src/changes-api.ts +258 -0
  18. package/src/component-templates-api.ts +2 -2
  19. package/src/config.ts +195 -21
  20. package/src/content-events.ts +65 -1
  21. package/src/content-operations.ts +22 -3
  22. package/src/core.ts +2 -0
  23. package/src/environment-values-api.ts +161 -0
  24. package/src/external-sign-in.ts +9 -2
  25. package/src/index.ts +1 -0
  26. package/src/managed-users.ts +122 -0
  27. package/src/node-operations.ts +150 -2
  28. package/src/ports.ts +174 -52
  29. package/src/principal.ts +1 -0
  30. package/src/remote-changes.ts +279 -0
  31. package/src/remote-schema.ts +126 -0
  32. package/src/remote-workspaces.ts +82 -0
  33. package/src/remote.ts +289 -192
  34. package/src/schema-transfer.ts +240 -41
  35. package/src/schema.ts +7 -2
  36. package/src/seed/compile.ts +13 -1
  37. package/src/seed/values.ts +3 -0
  38. package/src/server.ts +965 -364
  39. package/src/settings.ts +137 -5
  40. package/src/site-sections.ts +1 -1
  41. package/src/user-admin.ts +2 -0
  42. package/src/workspace-access.ts +152 -0
  43. package/src/workspace-checks.ts +299 -0
  44. package/src/workspace-losses.ts +95 -0
  45. package/src/workspace-processes.ts +306 -0
  46. package/src/workspace-render-child.ts +168 -0
  47. package/src/workspace-schema-dir.ts +100 -0
  48. package/src/workspace-schema.ts +598 -0
  49. package/src/workspace-sites.ts +179 -0
  50. package/src/workspace-views.ts +121 -0
  51. package/src/workspaces.ts +1031 -0
package/src/ports.ts CHANGED
@@ -5,6 +5,7 @@ import { join } from 'node:path'
5
5
  import { resolveDeliveryApiSettings } from '@crombolo/api-delivery'
6
6
  import type {
7
7
  CurrentUserPort,
8
+ FileSystemPort,
8
9
  LocalizationPort,
9
10
  ManagementApiDeps,
10
11
  ManifestPort,
@@ -41,6 +42,7 @@ import {
41
42
  LanguageRepository,
42
43
  TagRepository,
43
44
  UserRepository,
45
+ type Workspace,
44
46
  } from '@crombolo/data'
45
47
  import type { PublishedCache } from '@crombolo/render'
46
48
  import { fileNameFor, parseUserGroup, type SchemaUserGroup, writeUserGroup } from '@crombolo/schema'
@@ -48,6 +50,7 @@ import { createNodeLookup } from './access.ts'
48
50
  import { createAuditHistory } from './adapters/audit.ts'
49
51
  import { createBlueprintPort } from './adapters/blueprints.ts'
50
52
  import { createPackagePort } from './adapters/bundles.ts'
53
+ import { recordEdit, recordingFilePort } from './adapters/change-recording.ts'
51
54
  import {
52
55
  createContentTypePort,
53
56
  createDataTypePort,
@@ -76,6 +79,16 @@ import { createTemplateFileStore } from './adapters/template-files.ts'
76
79
  import { createTemplateQueryPort } from './adapters/template-query.ts'
77
80
  import { avatarUrls, createUserPorts, type DeclaredGroups } from './adapters/users.ts'
78
81
  import { createWebhookPort } from './adapters/webhooks.ts'
82
+ import {
83
+ recordingDictionaryPort,
84
+ WORKSPACE_DICTIONARY,
85
+ workspaceDictionaryPort,
86
+ } from './adapters/workspace-dictionary.ts'
87
+ import {
88
+ createWorkspaceFilePort,
89
+ type WorkspaceFileAreaOptions,
90
+ } from './adapters/workspace-file-port.ts'
91
+ import { workspaceLocalizationPort, writeLanguagesFile } from './adapters/workspace-languages.ts'
79
92
  import { backOfficeUrl } from './back-office-url.ts'
80
93
  import { COMPONENT_SNIPPETS } from './component-snippets.ts'
81
94
  import { type CromboloConfig, contentFilesLocked, type UserLinkSender, VERSION } from './config.ts'
@@ -88,9 +101,12 @@ import { MediaFileStore } from './media-files.ts'
88
101
  import { createModelsBuilderPort } from './models-builder.ts'
89
102
  import { createNodeOperations, type NodeOperations } from './node-operations.ts'
90
103
  import { createOEmbedService } from './oembed.ts'
104
+ import { NO_REDIRECT_TRACKING } from './redirects.ts'
91
105
  import type { SchemaBoot } from './schema.ts'
92
106
  import { TwoFactorService, USER_TWO_FACTOR_PROVIDER } from './two-factor.ts'
93
107
  import { createWebhookService, type WebhookService } from './webhooks.ts'
108
+ import { createWorkspaceSchema } from './workspace-schema.ts'
109
+ import { inWorkspaces } from './workspaces.ts'
94
110
 
95
111
  /** Re-exported for tests; the canonical list lives in @crombolo/core. */
96
112
  export const CORE_SECTIONS = CORE_SECTION_ALIASES
@@ -122,7 +138,7 @@ function createServerPort(config: CromboloConfig, canSendUserLinks: () => boolea
122
138
  version: VERSION,
123
139
  assemblyVersion: VERSION,
124
140
  baseUtcOffset: '00:00:00',
125
- // Stories 337, 343: the back office keeps templates read-only in its Production mode, so it follows the content mode.
141
+ // Stories 337, 343, 391: the back office keeps templates read-only in its Production mode, so it follows the code setting.
126
142
  runtimeMode: contentFilesLocked(config) ? 'Production' : 'BackofficeDevelopment',
127
143
  }),
128
144
  }
@@ -211,6 +227,31 @@ function createLocalizationPort(db: Db | undefined, files?: SchemaFileWriter): L
211
227
  return db ? underSchemaLock(db, port, ['saveLanguage', 'deleteLanguage']) : port
212
228
  }
213
229
 
230
+ /**
231
+ * Story 392: in a workspace, the languages it holds; in Shared, each write by someone
232
+ * recorded as their change to `schema/languages.toml`.
233
+ */
234
+ function localizationIn(db: Db | undefined, shared: LocalizationPort): LocalizationPort {
235
+ if (!db) return shared
236
+ const text = async () => writeLanguagesFile(await shared.allLanguages())
237
+ const recorded: LocalizationPort = {
238
+ ...shared,
239
+ async saveLanguage(language, by) {
240
+ const before = by ? await text() : ''
241
+ await shared.saveLanguage(language)
242
+ if (by) await recordEdit(db, by, 'schema/languages.toml', before, await text())
243
+ },
244
+ async deleteLanguage(isoCode, by) {
245
+ const before = by ? await text() : ''
246
+ const result = await shared.deleteLanguage(isoCode)
247
+ if (by && result === 'deleted')
248
+ await recordEdit(db, by, 'schema/languages.toml', before, await text())
249
+ return result
250
+ },
251
+ }
252
+ return inWorkspaces(recorded, (w) => workspaceLocalizationPort(db, shared, w.id))
253
+ }
254
+
214
255
  function createCurrentUserPort(
215
256
  config: CromboloConfig,
216
257
  db: Db | undefined,
@@ -441,9 +482,12 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
441
482
  options.readyExtensions ?? (async () => options.extensions.list()),
442
483
  options.previewInApp ? [] : [APP_PREVIEW_MANIFEST_ID],
443
484
  ),
444
- localization: createLocalizationPort(
485
+ localization: localizationIn(
445
486
  options.db,
446
- options.db ? createSchemaFileWriter(options.db, schemaFiles(options.config)) : undefined,
487
+ createLocalizationPort(
488
+ options.db,
489
+ options.db ? createSchemaFileWriter(options.db, schemaFiles(options.config)) : undefined,
490
+ ),
447
491
  ),
448
492
  currentUser: createCurrentUserPort(
449
493
  options.config,
@@ -480,13 +524,33 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
480
524
  // already understands folders; the template API is id-addressed and cannot
481
525
  // express a folder at all.
482
526
  const readOnly = contentFilesLocked(options.config)
483
- deps.components = createComponentsPort(options.config.componentsDir, readOnly)
484
- deps.componentSnippets = COMPONENT_SNIPPETS
485
- deps.stylesheets = createFileSystemPort(options.config.stylesheetsDir, {
486
- extension: '.css',
487
- readOnly,
527
+ // Story 377: with the header, a workspace's own copy, kept in its file list.
528
+ // Story 381: Shared's own, each direct write recorded as its author's change.
529
+ const workspaceFiles = (
530
+ shared: FileSystemPort,
531
+ area: Omit<WorkspaceFileAreaOptions, 'readOnly'>,
532
+ ) =>
533
+ options.db
534
+ ? inWorkspaces(recordingFilePort(options.db, area.prefix, shared), (w) =>
535
+ createWorkspaceFilePort(options.db as Db, w.id, { ...area, readOnly }),
536
+ )
537
+ : shared
538
+ deps.components = workspaceFiles(createComponentsPort(options.config.componentsDir, readOnly), {
539
+ prefix: 'components/',
540
+ extension: '.tsx',
541
+ also: ['.ts'],
542
+ rewrites: ['.cshtml'],
543
+ compiles: true,
488
544
  })
489
- deps.scripts = createFileSystemPort(options.config.scriptsDir, { extension: '.js', readOnly })
545
+ deps.componentSnippets = COMPONENT_SNIPPETS
546
+ deps.stylesheets = workspaceFiles(
547
+ createFileSystemPort(options.config.stylesheetsDir, { extension: '.css', readOnly }),
548
+ { prefix: 'stylesheets/', extension: '.css' },
549
+ )
550
+ deps.scripts = workspaceFiles(
551
+ createFileSystemPort(options.config.scriptsDir, { extension: '.js', readOnly }),
552
+ { prefix: 'scripts/', extension: '.js' },
553
+ )
490
554
  if (options.db) {
491
555
  const dynamicRoots = new DynamicRootRepository(options.db)
492
556
  deps.dynamicRoots = { resolve: (query) => dynamicRoots.resolve(query) }
@@ -561,34 +625,59 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
561
625
  }
562
626
  deps.userGroups = userPorts.groups
563
627
  deps.userData = userPorts.userData
564
- deps.media = createMediaPort(options.db, {
628
+ // Story 390: with the header, a workspace's media.
629
+ const mediaOptions = {
565
630
  nodeState: options.schema?.nodeState,
566
631
  nodeId: options.schema?.nodeId,
567
632
  valueIntake,
568
- })
633
+ }
634
+ deps.media = inWorkspaces(createMediaPort(options.db, mediaOptions), (w) =>
635
+ createMediaPort(options.db as Db, { ...mediaOptions, workspace: w.id }),
636
+ )
569
637
  // Every media write, whoever starts it (story 165).
570
- deps.mediaOperations = operations?.media
571
- deps.blueprints = createBlueprintPort(options.db, {
572
- nodeState: options.schema?.nodeState,
573
- valueIntake,
574
- })
575
- deps.contentTypes = createContentTypePort(options.db, schemaFiles(options.config), {
576
- nodeState: options.schema?.nodeState,
577
- componentFiles: createTemplateFileStore(
578
- options.config.componentsDir,
579
- options.onViewsChange,
580
- contentFilesLocked(options.config),
581
- ),
582
- })
583
- deps.mediaTypes = createContentTypePort(options.db, schemaFiles(options.config), {
584
- nodeState: options.schema?.nodeState,
585
- kind: 'media',
586
- })
587
- deps.memberTypes = createContentTypePort(options.db, schemaFiles(options.config), {
588
- nodeState: options.schema?.nodeState,
589
- kind: 'member',
638
+ deps.mediaOperations = operations
639
+ ? inWorkspaces(operations.media, operations.mediaIn)
640
+ : undefined
641
+ // Story 392: with the header, a workspace's blueprints.
642
+ const blueprintsIn = (workspace?: number) =>
643
+ createBlueprintPort(options.db as Db, {
644
+ nodeState: options.schema?.nodeState,
645
+ valueIntake,
646
+ workspace,
647
+ })
648
+ deps.blueprints = inWorkspaces(blueprintsIn(), (w) => blueprintsIn(w.id))
649
+ // Story 376: a request in a workspace reads and writes its own copy of the types,
650
+ // built from its copy of the files at its first schema save.
651
+ const db = options.db
652
+ const workspaceSchema = options.schema
653
+ ? createWorkspaceSchema(db, options.config, options.schema)
654
+ : undefined
655
+ const inWorkspace = (workspace: Workspace) => ({
656
+ workspace: { id: workspace.id, key: workspace.key },
657
+ beforeWrite: () =>
658
+ workspaceSchema?.ensureBuilt({ id: workspace.id, key: workspace.key }) ?? Promise.resolve(),
590
659
  })
591
- deps.dataTypes = createDataTypePort(options.db, schemaFiles(options.config))
660
+ const typePort = (kind: 'document' | 'media' | 'member', workspace?: Workspace) =>
661
+ createContentTypePort(db, schemaFiles(options.config), {
662
+ nodeState: options.schema?.nodeState,
663
+ kind,
664
+ ...(kind === 'document'
665
+ ? {
666
+ componentFiles: createTemplateFileStore(
667
+ options.config.componentsDir,
668
+ options.onViewsChange,
669
+ contentFilesLocked(options.config),
670
+ ),
671
+ }
672
+ : {}),
673
+ ...(workspace ? inWorkspace(workspace) : {}),
674
+ })
675
+ deps.contentTypes = inWorkspaces(typePort('document'), (w) => typePort('document', w))
676
+ deps.mediaTypes = inWorkspaces(typePort('media'), (w) => typePort('media', w))
677
+ deps.memberTypes = inWorkspaces(typePort('member'), (w) => typePort('member', w))
678
+ deps.dataTypes = inWorkspaces(createDataTypePort(db, schemaFiles(options.config)), (w) =>
679
+ createDataTypePort(db, schemaFiles(options.config), inWorkspace(w)),
680
+ )
592
681
  deps.templates = createTemplatePort(
593
682
  options.db,
594
683
  createTemplateFileStore(
@@ -612,14 +701,22 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
612
701
  nodeId: options.schema?.nodeId,
613
702
  onChange: () => options.cache?.invalidate(),
614
703
  })
615
- deps.elements = createElementPort(options.db, {
704
+ const elementOptions = {
616
705
  nodeState: options.schema?.nodeState,
617
706
  nodeId: options.schema?.nodeId,
618
707
  valueIntake,
619
- onChange: () => options.cache?.invalidate(),
620
- })
708
+ }
709
+ deps.elements = inWorkspaces(
710
+ createElementPort(options.db, {
711
+ ...elementOptions,
712
+ onChange: () => options.cache?.invalidate(),
713
+ }),
714
+ (w) => createElementPort(options.db as Db, { ...elementOptions, workspace: w.id }),
715
+ )
621
716
  // Every Library write, whoever starts it (story 361).
622
- deps.elementOperations = operations?.elements
717
+ deps.elementOperations = operations
718
+ ? inWorkspaces(operations.elements, operations.elementsIn)
719
+ : undefined
623
720
  deps.references = createReferencePort(options.db)
624
721
  deps.relations = createRelationPort(options.db)
625
722
  deps.webhooks = createWebhookPort(
@@ -674,26 +771,51 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
674
771
  isRebuilding: () => false,
675
772
  }
676
773
  }
677
- deps.dictionary = createDictionaryPort(options.db, mediaFiles, {
678
- onChange: () => options.cache?.invalidate(),
679
- nodeId: options.schema?.nodeId,
680
- })
681
- if (operations && options.cache)
682
- deps.documents = createDocumentPort(
683
- options.db,
684
- options.cache,
685
- {
686
- nodeState: options.schema?.nodeState,
774
+ // Story 392: in a workspace, the dictionary it holds.
775
+ deps.dictionary = inWorkspaces(
776
+ recordingDictionaryPort(
777
+ options.db as Db,
778
+ createDictionaryPort(options.db, mediaFiles, {
779
+ onChange: () => options.cache?.invalidate(),
687
780
  nodeId: options.schema?.nodeId,
688
- valueIntake,
689
- },
690
- operations.tracker,
691
- options.config.siteDir,
692
- () => emailReady(email),
781
+ }),
782
+ (by, before, after) =>
783
+ recordEdit(options.db as Db, by, WORKSPACE_DICTIONARY, before, after).then(() => {}),
784
+ ),
785
+ (w) => workspaceDictionaryPort(options.db as Db, w.id),
786
+ )
787
+ if (operations && options.cache) {
788
+ const cache = options.cache
789
+ const db = options.db
790
+ const documentOptions = {
791
+ nodeState: options.schema?.nodeState,
792
+ nodeId: options.schema?.nodeId,
793
+ valueIntake,
794
+ }
795
+ // Story 375: a request in a workspace reads and writes the workspace's pages.
796
+ deps.documents = inWorkspaces(
797
+ createDocumentPort(
798
+ db,
799
+ cache,
800
+ documentOptions,
801
+ operations.tracker,
802
+ options.config.siteDir,
803
+ () => emailReady(email),
804
+ ),
805
+ (workspace) =>
806
+ createDocumentPort(
807
+ db,
808
+ cache,
809
+ { ...documentOptions, workspace: workspace.id },
810
+ NO_REDIRECT_TRACKING,
811
+ options.config.siteDir,
812
+ () => emailReady(email),
813
+ ),
693
814
  )
815
+ }
694
816
  if (deps.documents && operations) {
695
817
  deps.approvals = operations.approvals
696
- deps.documentOperations = operations.documents
818
+ deps.documentOperations = inWorkspaces(operations.documents, operations.documentsIn)
697
819
  }
698
820
  }
699
821
  return deps
package/src/principal.ts CHANGED
@@ -32,5 +32,6 @@ export async function principalOf(
32
32
  ...(identity.viewingAs ? { viewingAs: identity.viewingAs } : {}),
33
33
  ...(viaToken ? { viaToken } : {}),
34
34
  ...(identity.exchangedThrough ? { viaExchange: { provider: identity.exchangedThrough } } : {}),
35
+ ...(identity.viaClient ? { viaClient: identity.viaClient } : {}),
35
36
  }
36
37
  }
@@ -0,0 +1,279 @@
1
+ /**
2
+ * The remote protocol's routes for changes (story 383): the site's changes, which
3
+ * of some it already holds, one exported as a change bundle (or an open
4
+ * workspace, or the page edits since a point), and one sent here to be staged or
5
+ * applied. Exporting is a pull; staging and applying need Apply changes, and
6
+ * Install code too when the change carries templates or the site's own code.
7
+ * docs/changes.md.
8
+ */
9
+ import { mkdtempSync, rmSync } from 'node:fs'
10
+ import { tmpdir } from 'node:os'
11
+ import { join } from 'node:path'
12
+ import type { Principal } from '@crombolo/api-management/domain'
13
+ import { normaliseUuid, RemotePermissions, type RemoteVerb } from '@crombolo/core'
14
+ import { ChangeRepository, type Db, WorkspaceRepository } from '@crombolo/data'
15
+ import {
16
+ type ChangeBundle,
17
+ ChangeBundleError,
18
+ readChangeBundle,
19
+ writeChangeBundle,
20
+ } from '@crombolo/transfer'
21
+ import type { ChangeTransfer } from './change-transfer.ts'
22
+ import { extractTarball, writeNpmTarball } from './tar.ts'
23
+
24
+ interface Problem {
25
+ code: string
26
+ title: string
27
+ detail?: string
28
+ items?: string[]
29
+ }
30
+
31
+ export interface ChangeRouteOptions {
32
+ db: Db
33
+ changes: () => ChangeTransfer | undefined
34
+ problem(status: number, body: Problem): Response
35
+ atLeast(level: 'read' | 'content'): boolean
36
+ notAtLevel(level: 'read' | 'content', what: string): Response
37
+ may(principal: Principal, verb: RemoteVerb): boolean
38
+ /** A change's detail and its revert, as the back office's change routes answer them (story 386). */
39
+ changeRoutes?: () =>
40
+ | { handle(request: Request, principal: Principal, rest: string): Promise<Response> }
41
+ | undefined
42
+ /** The request's body, written to `path`, with its hash; undefined when it carried none. */
43
+ receive(request: Request, path: string): Promise<{ sha256: string; size: number } | undefined>
44
+ }
45
+
46
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
47
+ const ONE = /^changes\/([0-9a-f-]{36})\/bundle$/i
48
+ const WORKSPACE = /^workspaces\/([0-9a-f-]{36})\/change$/i
49
+
50
+ /** A change bundle packed as a tarball, as it travels. */
51
+ export function packChange(change: ChangeBundle, media: ReadonlyMap<string, Uint8Array>) {
52
+ const encoder = new TextEncoder()
53
+ return writeNpmTarball(
54
+ writeChangeBundle(change, media).map((file) => ({
55
+ path: file.path,
56
+ bytes: file.bytes ?? encoder.encode(file.text ?? ''),
57
+ })),
58
+ )
59
+ }
60
+
61
+ /** A packed change, unpacked and checked whole. */
62
+ export async function unpackChange(file: string) {
63
+ const dir = mkdtempSync(join(tmpdir(), 'crombolo-change-'))
64
+ try {
65
+ await extractTarball(file, dir)
66
+ return readChangeBundle(dir)
67
+ } finally {
68
+ rmSync(dir, { recursive: true, force: true })
69
+ }
70
+ }
71
+
72
+ /** Whether a change carries code: templates, or the site's own files read as it starts. */
73
+ export const carriesCode = (change: ChangeBundle) =>
74
+ change.files.some((f) => f.path.startsWith('components/') || f.path.startsWith('site/'))
75
+
76
+ export function createChangeRoutes(options: ChangeRouteOptions) {
77
+ const { problem } = options
78
+ const packed = (change: ChangeBundle, media: ReadonlyMap<string, Uint8Array>) => {
79
+ const bytes = packChange(change, media)
80
+ return new Response(bytes, {
81
+ headers: {
82
+ 'content-type': 'application/gzip',
83
+ 'crombolo-sha256': new Bun.CryptoHasher('sha256').update(bytes).digest('hex'),
84
+ 'content-disposition': `attachment; filename="change-${change.key}.tgz"`,
85
+ },
86
+ })
87
+ }
88
+ const forbidden = (title: string, detail: string) =>
89
+ problem(403, { code: 'forbidden', title, detail })
90
+
91
+ async function receiveChange(request: Request) {
92
+ const declared = request.headers.get('crombolo-sha256')?.toLowerCase()
93
+ if (!declared || !/^[0-9a-f]{64}$/.test(declared))
94
+ return problem(400, { code: 'hash-required', title: 'Crombolo-Sha256 is required' })
95
+ const dir = mkdtempSync(join(tmpdir(), 'crombolo-change-in-'))
96
+ const file = join(dir, 'change.tgz')
97
+ try {
98
+ let received: { sha256: string } | undefined
99
+ try {
100
+ received = await options.receive(request, file)
101
+ } catch {
102
+ return problem(413, {
103
+ code: 'too-large',
104
+ title: 'The change is larger than this site takes',
105
+ })
106
+ }
107
+ if (!received)
108
+ return problem(400, { code: 'body-required', title: 'The request carried no change' })
109
+ if (received.sha256 !== declared)
110
+ return problem(400, {
111
+ code: 'hash-mismatch',
112
+ title: 'The change is not the one described',
113
+ detail:
114
+ 'Its SHA-256 does not match Crombolo-Sha256: it was changed or cut short on the way.',
115
+ })
116
+ try {
117
+ return await unpackChange(file)
118
+ } catch (error) {
119
+ return problem(400, {
120
+ code: 'not-a-change',
121
+ title: 'It is not a change this site can read',
122
+ detail: error instanceof ChangeBundleError ? error.message : String(error),
123
+ })
124
+ }
125
+ } finally {
126
+ rmSync(dir, { recursive: true, force: true })
127
+ }
128
+ }
129
+
130
+ return {
131
+ capabilities(): string[] {
132
+ return options.changes() && options.atLeast('read') ? ['changes'] : []
133
+ },
134
+
135
+ /** Answers the route, or undefined when `what` is not one of these. */
136
+ async handle(
137
+ request: Request,
138
+ url: URL,
139
+ principal: Principal,
140
+ what: string,
141
+ ): Promise<Response | undefined> {
142
+ const transfer = options.changes()
143
+ const isOurs =
144
+ what === 'changes' ||
145
+ what.startsWith('changes/') ||
146
+ (WORKSPACE.test(what) && request.method === 'GET')
147
+ if (!isOurs) return undefined
148
+ if (!transfer)
149
+ return problem(404, {
150
+ code: 'not-enabled',
151
+ title: 'Workspaces are not turned on for this site',
152
+ })
153
+
154
+ if (request.method === 'GET') {
155
+ if (!options.atLeast('read')) return options.notAtLevel('read', 'pulls')
156
+ if (!options.may(principal, RemotePermissions.Pull))
157
+ return forbidden(
158
+ 'You may not take changes from this site',
159
+ 'It needs Crombolo.Remote.Pull.',
160
+ )
161
+ const changes = new ChangeRepository(options.db)
162
+ if (what === 'changes') {
163
+ const skip = Number(url.searchParams.get('skip') ?? 0) || 0
164
+ const take = Math.min(Number(url.searchParams.get('take') ?? 50) || 50, 500)
165
+ return Response.json(await changes.list(skip, take))
166
+ }
167
+ if (what === 'changes/held') {
168
+ const keys = (url.searchParams.get('keys') ?? '').split(',').filter((k) => UUID.test(k))
169
+ return Response.json({ held: [...(await changes.held(keys))] })
170
+ }
171
+ if (what === 'changes/since') {
172
+ const at = new Date(url.searchParams.get('at') ?? '')
173
+ if (Number.isNaN(at.getTime()))
174
+ return problem(400, {
175
+ code: 'bad-time',
176
+ title: 'Say since when, as an ISO time in `at`',
177
+ })
178
+ const out = await transfer.exportSince(at)
179
+ return packed(out.change, out.media)
180
+ }
181
+ const detail = /^changes\/([0-9a-f-]{36})$/i.exec(what)?.[1]
182
+ const routes = options.changeRoutes?.()
183
+ if (detail && routes) return routes.handle(request, principal, `/${detail}`)
184
+ const one = ONE.exec(what)?.[1]
185
+ if (one) {
186
+ const out = await transfer.exportChange(normaliseUuid(one))
187
+ if (!out)
188
+ return problem(404, { code: 'not-found', title: 'There is no such change here' })
189
+ return packed(out.change, out.media)
190
+ }
191
+ const open = WORKSPACE.exec(what)?.[1]
192
+ if (open) {
193
+ const workspace = await new WorkspaceRepository(options.db).byKey(normaliseUuid(open))
194
+ if (workspace?.state !== 'open')
195
+ return problem(404, {
196
+ code: 'not-found',
197
+ title: 'There is no such open workspace here',
198
+ })
199
+ const out = await transfer.exportWorkspace(workspace)
200
+ return packed(out.change, out.media)
201
+ }
202
+ return problem(404, { code: 'not-found', title: 'There is no such route' })
203
+ }
204
+
205
+ const reverting = /^changes\/([0-9a-f-]{36})\/revert$/i.exec(what)?.[1]
206
+ if (reverting && request.method === 'POST') {
207
+ if (!options.atLeast('content')) return options.notAtLevel('content', 'changes')
208
+ const routes = options.changeRoutes?.()
209
+ if (!routes) return problem(404, { code: 'not-found', title: 'There is no such route' })
210
+ const answered = await routes.handle(request, principal, `/${reverting}/revert`)
211
+ if (answered.ok) return answered
212
+ const body = (await answered.json().catch(() => ({}))) as {
213
+ message?: string
214
+ blockers?: string[]
215
+ }
216
+ return problem(answered.status, {
217
+ code: answered.status === 409 ? 'conflict' : 'refused',
218
+ title: body.message ?? 'It cannot be reverted',
219
+ ...(body.blockers ? { items: body.blockers } : {}),
220
+ })
221
+ }
222
+ if (what === 'changes' && request.method === 'PUT') {
223
+ if (!options.atLeast('content')) return options.notAtLevel('content', 'changes')
224
+ if (!options.may(principal, RemotePermissions.ApplyChanges))
225
+ return forbidden(
226
+ 'You may not apply changes here',
227
+ 'Staging or applying a change needs "Apply changes" (Crombolo.Remote.ApplyChanges).',
228
+ )
229
+ const received = await receiveChange(request)
230
+ if (received instanceof Response) return received
231
+ if (carriesCode(received.change) && !options.may(principal, RemotePermissions.InstallCode))
232
+ return forbidden(
233
+ 'You may not apply this change here',
234
+ 'It carries templates or the site\'s own code, which needs "Install code on this site" (Crombolo.Remote.InstallCode).',
235
+ )
236
+ // Story 386: what applying it here would do, staged and set aside again.
237
+ if (url.searchParams.get('check') === 'true') {
238
+ const outcome = await transfer.stage([received], principal)
239
+ const workspaces = new WorkspaceRepository(options.db)
240
+ if (outcome.workspace) await workspaces.discard(outcome.workspace.id)
241
+ return Response.json({
242
+ skipped: outcome.skipped,
243
+ conflicts: outcome.conflicts,
244
+ pages: received.change.pages.map((p) => ({
245
+ key: p.key,
246
+ name: p.after?.name ?? p.before?.name ?? p.key,
247
+ action: p.action,
248
+ })),
249
+ files: received.change.files.map((f) => ({ path: f.path, class: f.class })),
250
+ })
251
+ }
252
+ const stage = url.searchParams.get('stage') === 'true'
253
+ const intoKey = url.searchParams.get('into')
254
+ const accepted = (url.searchParams.get('accept') ?? '').split(',').filter(Boolean)
255
+ if (stage) {
256
+ const workspaces = new WorkspaceRepository(options.db)
257
+ const into = intoKey && UUID.test(intoKey) ? await workspaces.byKey(intoKey) : undefined
258
+ if (intoKey && (!into?.stagedReadOnly || into.state !== 'open'))
259
+ return problem(404, { code: 'not-found', title: 'There is no such staged change here' })
260
+ const outcome = await transfer.stage([received], principal, into)
261
+ // Story 386: a workspace pulled to work on, rather than a change to look at.
262
+ if (url.searchParams.get('editable') === 'true' && outcome.workspace)
263
+ await workspaces.setStaged(outcome.workspace.id, outcome.workspace.stagedChanges, false)
264
+ return Response.json(
265
+ {
266
+ workspace: outcome.workspace?.key ?? null,
267
+ skipped: outcome.skipped,
268
+ conflicts: outcome.conflicts,
269
+ },
270
+ { status: outcome.conflicts.length > 0 ? 409 : 200 },
271
+ )
272
+ }
273
+ const outcome = await transfer.apply([received], principal, { accepted })
274
+ return Response.json(outcome, { status: outcome.ok ? 200 : 409 })
275
+ }
276
+ return new Response(null, { status: 405 })
277
+ },
278
+ }
279
+ }