@crombolo/cli 0.0.0-stage → 0.10.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 (97) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +69 -0
  3. package/bin/crombolo.ts +2183 -0
  4. package/package.json +42 -4
  5. package/src/index.ts +7 -0
  6. package/src/operations/commands.ts +645 -0
  7. package/src/templates.ts +309 -0
  8. package/templates/basic/bundle/content/bundle.json +45 -0
  9. package/templates/basic/bundle/content/nodes/36955f6e-d110-469e-b280-72096eccd148.json +38 -0
  10. package/templates/basic/bundle/package.json +16 -0
  11. package/templates/basic/files/components/homePage.tsx +22 -0
  12. package/templates/basic/files/schema/content-types/home-page.toml +28 -0
  13. package/templates/basic/files/schema/schema.toml +2 -0
  14. package/templates/basic/template.json +4 -0
  15. package/templates/demo/harbourstone/CREDITS.md +42 -0
  16. package/templates/demo/harbourstone/bundle/content/blobs/180cc8ef/distillery-from-the-cliff-path.jpg +0 -0
  17. package/templates/demo/harbourstone/bundle/content/blobs/68c9cfdf/bottle-brine-and-kiln.jpg +0 -0
  18. package/templates/demo/harbourstone/bundle/content/blobs/6be45535/bottle-oloroso-pier.jpg +0 -0
  19. package/templates/demo/harbourstone/bundle/content/blobs/6d8d6398/bottle-the-cove.jpg +0 -0
  20. package/templates/demo/harbourstone/bundle/content/blobs/7b4713f8/copper-pot-stills.jpg +0 -0
  21. package/templates/demo/harbourstone/bundle/content/blobs/c114b7d8/bottle-neap-tide.jpg +0 -0
  22. package/templates/demo/harbourstone/bundle/content/blobs/fd337567/casks-in-the-sea-facing-warehouse.jpg +0 -0
  23. package/templates/demo/harbourstone/bundle/content/bundle.json +197 -0
  24. package/templates/demo/harbourstone/bundle/content/nodes/069cc3c5-c9f5-4792-90c9-e2bfcc4855b6.json +35 -0
  25. package/templates/demo/harbourstone/bundle/content/nodes/13788fe7-1a45-4b48-8ae4-f4227e154e1e.json +35 -0
  26. package/templates/demo/harbourstone/bundle/content/nodes/180cc8ef-caf1-4316-b6a7-e3b5aee41ffd.json +60 -0
  27. package/templates/demo/harbourstone/bundle/content/nodes/22144db2-e214-4006-a0bb-53b5bd121fd6.json +35 -0
  28. package/templates/demo/harbourstone/bundle/content/nodes/26e87610-e2d6-4b47-bf92-3967f7186907.json +35 -0
  29. package/templates/demo/harbourstone/bundle/content/nodes/2caa099b-3884-472d-9cea-797a0f0c376f.json +35 -0
  30. package/templates/demo/harbourstone/bundle/content/nodes/2efbdb5b-7888-4a49-bca5-c0f85b76e472.json +42 -0
  31. package/templates/demo/harbourstone/bundle/content/nodes/2fe03891-1294-4344-8e24-47e8b212e5b0.json +35 -0
  32. package/templates/demo/harbourstone/bundle/content/nodes/38b009f7-03c0-4fda-b5c7-843ad6044e9c.json +35 -0
  33. package/templates/demo/harbourstone/bundle/content/nodes/3d312cc8-2937-40e1-ba14-fd781c9a862d.json +95 -0
  34. package/templates/demo/harbourstone/bundle/content/nodes/3dc30fc1-973a-4217-b26f-24902210be17.json +35 -0
  35. package/templates/demo/harbourstone/bundle/content/nodes/40107d59-f3e9-4592-aee8-5b03d4586cbd.json +101 -0
  36. package/templates/demo/harbourstone/bundle/content/nodes/483a0d3b-a10c-4c9d-8c81-d9607d37e968.json +35 -0
  37. package/templates/demo/harbourstone/bundle/content/nodes/4b760c0b-b83a-4eee-aa29-c225cfabf19b.json +35 -0
  38. package/templates/demo/harbourstone/bundle/content/nodes/4e5c7f3f-54cb-4328-ad61-bc4c2736b890.json +35 -0
  39. package/templates/demo/harbourstone/bundle/content/nodes/62f479ff-0875-453e-99ae-3bf1bec5e3c8.json +35 -0
  40. package/templates/demo/harbourstone/bundle/content/nodes/68c9cfdf-6b40-47da-a1d2-17256a6cc6db.json +60 -0
  41. package/templates/demo/harbourstone/bundle/content/nodes/6ad8f0f3-9334-47f1-b805-80c4b4b4fa88.json +101 -0
  42. package/templates/demo/harbourstone/bundle/content/nodes/6be45535-83e5-4469-acf0-4127016721ae.json +60 -0
  43. package/templates/demo/harbourstone/bundle/content/nodes/6d8d6398-738f-4f38-ad3c-e5d6e9a971fe.json +60 -0
  44. package/templates/demo/harbourstone/bundle/content/nodes/7b4713f8-d917-457d-a9d8-7dd01a3617b4.json +60 -0
  45. package/templates/demo/harbourstone/bundle/content/nodes/88ec1185-53b5-439a-a2ce-3f56603be4ff.json +35 -0
  46. package/templates/demo/harbourstone/bundle/content/nodes/97469df2-107c-4010-8c14-4de88f735529.json +35 -0
  47. package/templates/demo/harbourstone/bundle/content/nodes/a2eb439f-71d9-4ea6-89d7-c5bc72618281.json +35 -0
  48. package/templates/demo/harbourstone/bundle/content/nodes/a562f0a2-cb6e-4ead-a1ce-4d180632419f.json +101 -0
  49. package/templates/demo/harbourstone/bundle/content/nodes/a5e36a18-a2ef-4eb5-85b4-7e12b21cca06.json +35 -0
  50. package/templates/demo/harbourstone/bundle/content/nodes/b1876d3a-50a7-4358-84bf-a0899932ffa9.json +35 -0
  51. package/templates/demo/harbourstone/bundle/content/nodes/b4e38bbd-c1a3-431a-b7a9-5868aa32993a.json +35 -0
  52. package/templates/demo/harbourstone/bundle/content/nodes/c114b7d8-0138-404b-9d8f-a39d992577a2.json +60 -0
  53. package/templates/demo/harbourstone/bundle/content/nodes/cb4c569e-c28a-43b6-a4d7-d33bb544e973.json +136 -0
  54. package/templates/demo/harbourstone/bundle/content/nodes/cd681b4b-9c4e-4624-9c13-450aa6a9c135.json +101 -0
  55. package/templates/demo/harbourstone/bundle/content/nodes/d60ef12b-0f0a-4db5-9763-21fa52b8d4da.json +150 -0
  56. package/templates/demo/harbourstone/bundle/content/nodes/d7f13222-d060-4496-b86d-bef21da963c1.json +35 -0
  57. package/templates/demo/harbourstone/bundle/content/nodes/f36dd4a9-927c-4ca3-a790-c9c859ac7302.json +35 -0
  58. package/templates/demo/harbourstone/bundle/content/nodes/fd337567-df67-41ca-ae94-9d84d8d6042f.json +60 -0
  59. package/templates/demo/harbourstone/bundle/package.json +16 -0
  60. package/templates/demo/harbourstone/files/components/pages/contactPage.tsx +36 -0
  61. package/templates/demo/harbourstone/files/components/pages/contentPage.tsx +54 -0
  62. package/templates/demo/harbourstone/files/components/pages/expression.tsx +33 -0
  63. package/templates/demo/harbourstone/files/components/pages/homePage.tsx +71 -0
  64. package/templates/demo/harbourstone/files/components/pages/whiskyList.tsx +19 -0
  65. package/templates/demo/harbourstone/files/components/shared/bottling.tsx +59 -0
  66. package/templates/demo/harbourstone/files/components/shared/highlights.tsx +39 -0
  67. package/templates/demo/harbourstone/files/components/shared/layout.tsx +49 -0
  68. package/templates/demo/harbourstone/files/components/shared/section-intro.tsx +40 -0
  69. package/templates/demo/harbourstone/files/components/shared/site-footer.tsx +14 -0
  70. package/templates/demo/harbourstone/files/components/shared/site-header.tsx +57 -0
  71. package/templates/demo/harbourstone/files/css/site.css +720 -0
  72. package/templates/demo/harbourstone/files/schema/content-types/contact-page.toml +75 -0
  73. package/templates/demo/harbourstone/files/schema/content-types/content-page.toml +89 -0
  74. package/templates/demo/harbourstone/files/schema/content-types/expression.toml +78 -0
  75. package/templates/demo/harbourstone/files/schema/content-types/highlight.toml +27 -0
  76. package/templates/demo/harbourstone/files/schema/content-types/home-page.toml +104 -0
  77. package/templates/demo/harbourstone/files/schema/content-types/tasting-note.toml +26 -0
  78. package/templates/demo/harbourstone/files/schema/content-types/whisky-list.toml +35 -0
  79. package/templates/demo/harbourstone/files/schema/data-types/highlight-picker.toml +10 -0
  80. package/templates/demo/harbourstone/files/schema/data-types/tasting-note-picker.toml +11 -0
  81. package/templates/demo/harbourstone/files/schema/forms/contact.toml +119 -0
  82. package/templates/demo/harbourstone/files/schema/schema.toml +2 -0
  83. package/templates/demo/harbourstone/template.json +10 -0
  84. package/templates/starter/bundle/content/bundle.json +49 -0
  85. package/templates/starter/bundle/content/nodes/634dd948-cf83-4cad-9b7b-7c938b33da76.json +62 -0
  86. package/templates/starter/bundle/content/nodes/64d95359-d91a-4050-b440-3e5124a74999.json +62 -0
  87. package/templates/starter/bundle/content/nodes/d2997ebb-36ca-47cb-bbc8-31fefca787c0.json +45 -0
  88. package/templates/starter/bundle/package.json +16 -0
  89. package/templates/starter/files/components/pages/contentPage.tsx +25 -0
  90. package/templates/starter/files/components/shared/layout.tsx +24 -0
  91. package/templates/starter/files/components/shared/site-footer.tsx +9 -0
  92. package/templates/starter/files/components/shared/site-header.tsx +40 -0
  93. package/templates/starter/files/css/site.css +117 -0
  94. package/templates/starter/files/schema/content-types/content-page.toml +51 -0
  95. package/templates/starter/files/schema/schema.toml +2 -0
  96. package/templates/starter/template.json +4 -0
  97. package/README.md +0 -3
@@ -0,0 +1,2183 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * The crombolo CLI. Runs from a site directory and reads `crombolo.config.ts`
4
+ * there when present.
5
+ *
6
+ * crombolo start boot the site; resets and prints the admin password
7
+ * crombolo start --keep-admin boot without touching the admin password
8
+ * crombolo start --bundle <pkg> apply a bundle's content, once, then serve
9
+ * crombolo init scaffold a site in the current directory
10
+ * crombolo init --template <id> …from a starter template, content included
11
+ * crombolo status what this environment is, without starting it
12
+ * crombolo admin reset-password reset the administrator's password and print it
13
+ * crombolo schema check validate schema/ and report what a sync would do
14
+ * crombolo schema check --static validate the files only, no database
15
+ * crombolo schema sync apply schema/ to the database
16
+ * crombolo schema export write the database's definitions as schema/ files
17
+ * crombolo schema new scaffold a type file, and the view it points at
18
+ * crombolo schema add-property append a property to a type, and apply it
19
+ * crombolo generate TypeScript for the content types in schema/
20
+ * crombolo components check compile every component before a visitor does
21
+ * crombolo assets list the stylesheets and scripts beside them
22
+ *
23
+ * crombolo content export write a subtree as a private bundle package, to move to another environment
24
+ * crombolo content check read-only: what installing a bundle's content here would do
25
+ * crombolo content import apply a bundle's content, in one transaction, and record the run
26
+ * crombolo content runs the imports applied here
27
+ * crombolo content revert put an import back, restoring what the site served
28
+ *
29
+ * crombolo domains the hostnames this site answers on
30
+ * crombolo domains set write domains.toml and apply it
31
+ *
32
+ * crombolo import umbraco report read-only: what importing an Umbraco backup would and would not bring
33
+ * crombolo import umbraco apply write a crombolo site from an Umbraco backup
34
+ *
35
+ * crombolo upgrade --plan print the DDL each pending framework migration would run
36
+ * crombolo upgrade back up, apply pending framework migrations, record them
37
+ * crombolo upgrade ledger print migration_history
38
+ * crombolo bundle purge <id> back up, drop a bundle's tables and clear its state
39
+ *
40
+ * crombolo maintenance pause refuse editors' saves cluster-wide; readers unaffected
41
+ * crombolo maintenance resume let editors save again
42
+ */
43
+ import { existsSync } from 'node:fs'
44
+ import { mkdir, writeFile } from 'node:fs/promises'
45
+ import { basename, join, relative, resolve } from 'node:path'
46
+ import { AuthStore, resetAdminPassword } from '@crombolo/auth'
47
+ import { ObjectTypes } from '@crombolo/core'
48
+ import {
49
+ ContentTypeRepository,
50
+ connect,
51
+ currentSchemaState,
52
+ DictionaryRepository,
53
+ DocumentRepository,
54
+ DomainRepository,
55
+ describeRefFailure,
56
+ type Finding,
57
+ NodeRepository,
58
+ readLedger,
59
+ recordInLedger,
60
+ resolveNodeRef,
61
+ TransferRunRepository,
62
+ writeReport,
63
+ } from '@crombolo/data'
64
+ import {
65
+ addProperty,
66
+ allProperties,
67
+ BUILTIN_DATA_TYPES,
68
+ exportSchemaSet,
69
+ fileNameFor,
70
+ generateTypes,
71
+ loadSchemaDirectory,
72
+ loadValueMigrations,
73
+ newType,
74
+ type SchemaContentType,
75
+ type SchemaTypeKind,
76
+ type SyncReport,
77
+ TYPE_KIND_FILES,
78
+ type ValueMigration,
79
+ validateSchemaSet,
80
+ viewScaffold,
81
+ writeContentType,
82
+ writeSchemaFiles,
83
+ } from '@crombolo/schema'
84
+ import {
85
+ assertPortAvailable,
86
+ assetDirs,
87
+ assetScaffold,
88
+ backupBefore,
89
+ bootstrapDatabase,
90
+ type CromboloConfig,
91
+ checkComponents,
92
+ componentAliasesIn,
93
+ componentFileFor,
94
+ componentScaffold,
95
+ createServer,
96
+ DOMAINS_FILE,
97
+ type DomainDeclaration,
98
+ describeDatabase,
99
+ dictionaryToUdt,
100
+ domainsFilePath,
101
+ importDictionaryUdt,
102
+ isSafeAlias,
103
+ listAssets,
104
+ listComponents,
105
+ loadConfig,
106
+ mediaStoreFor,
107
+ placeBlobs,
108
+ readDomainsFile,
109
+ resolveDomainNode,
110
+ resolvePlaceholders,
111
+ type ServerHandle,
112
+ siteStatus,
113
+ syncDomainsFile,
114
+ syncSchemaDirectory,
115
+ undoDomainsFile,
116
+ VERSION,
117
+ withoutNode,
118
+ writeDictionaryUdt,
119
+ writeDomains,
120
+ writeDomainsFile,
121
+ writeUdtAll,
122
+ } from '@crombolo/server'
123
+ import {
124
+ importBundle,
125
+ isResolution,
126
+ isRevertResolution,
127
+ packageNameFor,
128
+ RESOLUTIONS,
129
+ RESOLUTIONS_FILE,
130
+ REVERT_RESOLUTIONS,
131
+ type Resolution,
132
+ type RevertResolution,
133
+ resolutionsFor,
134
+ revertResolutionsFor,
135
+ revertRun,
136
+ type TransferCheck,
137
+ writeResolutions,
138
+ } from '@crombolo/transfer'
139
+ import * as ops from '../src/operations/commands.ts'
140
+ import { findTemplate, listTemplates, scaffoldFiles } from '../src/templates.ts'
141
+
142
+ const cwd = process.cwd()
143
+ const [command = 'help', ...rest] = Bun.argv.slice(2)
144
+ const flags = new Set(rest.filter((arg) => arg.startsWith('--')))
145
+ const positional = rest.filter((arg) => !arg.startsWith('--'))
146
+
147
+ async function siteConfig(): Promise<CromboloConfig> {
148
+ const file = join(cwd, 'crombolo.config.ts')
149
+ const overrides = existsSync(file)
150
+ ? ((await import(file)).default as Partial<CromboloConfig>)
151
+ : {}
152
+ return loadConfig(overrides, cwd)
153
+ }
154
+
155
+ function banner(lines: string[]): void {
156
+ const width = Math.max(...lines.map((line) => line.length))
157
+ console.log(`┌─${'─'.repeat(width)}─┐`)
158
+ for (const line of lines) console.log(`│ ${line.padEnd(width)} │`)
159
+ console.log(`└─${'─'.repeat(width)}─┘`)
160
+ }
161
+
162
+ /** How long a shutdown gets before it is abandoned and the process leaves anyway. */
163
+ const SHUTDOWN_MS = 10_000
164
+
165
+ /**
166
+ * Stops the site on SIGINT and SIGTERM.
167
+ *
168
+ * Without a handler neither signal does anything at all in a container: `bun` is
169
+ * PID 1 there, and the kernel drops a signal PID 1 has registered no handler
170
+ * for. That is why Ctrl-C did nothing under `docker compose run` — the keystroke
171
+ * reaches the container's own terminal, which raises a SIGINT nothing was
172
+ * listening for — and why `docker stop` sat out its ten-second grace and then
173
+ * resorted to SIGKILL. Outside a container the default would at least have
174
+ * killed the process, so this was invisible there.
175
+ *
176
+ * `server.close()` is the point of it either way: the job runner, the event
177
+ * hubs, the component watcher, the poller and the database all get to stop,
178
+ * rather than being taken away mid-write. Connections are closed with the
179
+ * listener because the live-update sockets are long-lived, and waiting for a
180
+ * socket that is meant to stay open would be waiting for ever.
181
+ *
182
+ * A second signal, or a close that will not finish, leaves immediately.
183
+ */
184
+ function stopOnSignal(
185
+ listening: { stop: (closeActiveConnections?: boolean) => void },
186
+ server: ServerHandle,
187
+ ): void {
188
+ let stopping = false
189
+ const stop = (signal: string) => {
190
+ // 130 is what a shell reports for a SIGINT death, and what this was.
191
+ if (stopping) process.exit(130)
192
+ stopping = true
193
+ console.log(`\nStopping (${signal})…`)
194
+ setTimeout(() => process.exit(130), SHUTDOWN_MS).unref()
195
+ void (async () => {
196
+ listening.stop(true)
197
+ await server.close()
198
+ process.exit(0)
199
+ })()
200
+ }
201
+ for (const signal of ['SIGINT', 'SIGTERM'] as const) process.on(signal, () => stop(signal))
202
+ }
203
+
204
+ async function start(): Promise<void> {
205
+ const config = await siteConfig()
206
+ // Before the migration and the seed, so a clash with the container stack is
207
+ // reported in a second rather than after the database work.
208
+ await assertPortAvailable(config.port)
209
+ const server = await createServer(config)
210
+ // After the schema sync inside `createServer`, which is what gives the bundle
211
+ // content types to land on, and before anything is served.
212
+ const bundles = await importStartupBundles(server, config)
213
+ const seededAdminPassword = server.seededAdminPassword
214
+
215
+ const lines = ['Crombolo is running', '']
216
+ const listening = Bun.serve(server.serveOptions)
217
+ // Registered the moment it is listening, so there is no window in which the
218
+ // site answers requests and cannot be asked to stop.
219
+ stopOnSignal(listening, server)
220
+ // What this node actually answers, so a split deployment's banner does not
221
+ // advertise an address that 404s here.
222
+ if (config.role !== 'web')
223
+ lines.push(` backoffice ${listening.url}${config.backOfficePath.slice(1)}`)
224
+ if (config.role !== 'api') lines.push(` site ${listening.url}`)
225
+ if (config.role !== 'all') lines.push(` role ${config.role}`)
226
+ lines.push('')
227
+
228
+ // A `web` node owns nothing and writes nothing at boot: resetting the password
229
+ // here would be a write from the node whose whole point is not to make them,
230
+ // and would end the sessions of editors signed in to the api node.
231
+ if (config.role === 'web') {
232
+ // Nothing to print: this node has no sign-in.
233
+ } else if (flags.has('--keep-admin')) {
234
+ if (seededAdminPassword)
235
+ lines.push(
236
+ ' Sign in with',
237
+ ` username ${config.adminLogin}`,
238
+ ` password ${seededAdminPassword}`,
239
+ '',
240
+ )
241
+ } else {
242
+ const admin = await resetAdminPassword(
243
+ new AuthStore(server.db),
244
+ config.adminLogin,
245
+ config.adminPassword,
246
+ )
247
+ if (admin) {
248
+ lines.push(
249
+ ' Sign in with',
250
+ ` username ${admin.login}`,
251
+ ` password ${admin.password}`,
252
+ '',
253
+ )
254
+ lines.push(
255
+ config.adminPassword
256
+ ? ' (from CROMBOLO_ADMIN_PASSWORD)'
257
+ : ' A fresh password is generated on every start; set',
258
+ )
259
+ if (!config.adminPassword)
260
+ lines.push(' CROMBOLO_ADMIN_PASSWORD to keep one, or pass --keep-admin.')
261
+ if (admin.sessionsEnded > 0)
262
+ lines.push(` Ended ${admin.sessionsEnded} session(s): the password changed.`)
263
+ }
264
+ }
265
+ const components = server.health().components
266
+ lines.push(
267
+ ` database ${describeDatabase(config)}`,
268
+ ` components ${config.componentsDir}${components.hash ? ` generation ${components.hash.slice(0, 8)}` : ''}`,
269
+ )
270
+ for (const line of bundles) lines.push(line)
271
+ const report = server.schema.report
272
+ if (report) lines.push(` schema ${describeSync(report)}`)
273
+ if (server.schema.compatibilityMode)
274
+ lines.push(' ⚠ database is ahead of schema/: reads only, writes refused with 409')
275
+ banner(lines)
276
+ if (seededAdminPassword) console.log('Database created and seeded.')
277
+ }
278
+
279
+ /**
280
+ * `start --bundle <dir>`, repeatable: apply a bundle before the site serves
281
+ * anything, taking the flags `content import` takes.
282
+ *
283
+ * Imported once per bundle — a run still standing here means this site already
284
+ * has that content — so a restart costs a query and a line in the banner. It
285
+ * runs after the schema sync, which is what gives the bundle its content types,
286
+ * and before anything is served. A refusal stops the boot: a site missing the
287
+ * content the command line asked for is worse than a site that did not come up.
288
+ */
289
+ async function importStartupBundles(
290
+ server: ServerHandle,
291
+ config: CromboloConfig,
292
+ ): Promise<string[]> {
293
+ const targets = flagValues('--bundle')
294
+ if (targets.length === 0) return []
295
+
296
+ const lines: string[] = []
297
+ const db = server.db
298
+ let imported = false
299
+ for (const target of targets) {
300
+ let resolved: ops.ResolvedBundle
301
+ try {
302
+ resolved = ops.readBundle(target, config.siteDir)
303
+ } catch (error) {
304
+ if (!(error instanceof ops.CommandError)) throw error
305
+ console.error(` ${error.message}`)
306
+ for (const problem of error.problems) console.error(` ${problem}`)
307
+ console.error(`\n${target} cannot be read. The site has not started.`)
308
+ process.exit(1)
309
+ }
310
+ const set = resolved.set
311
+ const standing = await new TransferRunRepository(db).appliedFor(set.manifest.id)
312
+ if (standing) {
313
+ lines.push(` bundle ${set.manifest.id} already imported (run ${standing.id})`)
314
+ continue
315
+ }
316
+
317
+ // Nothing to roll back to on a database this boot created, so the backup
318
+ // rule — which on Postgres means refusing without one — applies only to a
319
+ // site that already had content.
320
+ if (!server.seededAdminPassword) {
321
+ const backup = await backupBefore(config, {
322
+ reason: 'content-import',
323
+ backupTaken: flags.has('--backup-taken'),
324
+ })
325
+ if (backup.path) console.log(` backup ${backup.path}`)
326
+ }
327
+
328
+ const prepared = await ops.transferOptions(db, config, resolved, transferInput(target))
329
+ for (const problem of prepared.problems) console.error(` ${problem}`)
330
+ const started = performance.now()
331
+ const result = await importBundle(db, set, {
332
+ ...prepared.options,
333
+ publish: flags.has('--publish'),
334
+ nodeId: config.nodeId,
335
+ label: flagValue('--label'),
336
+ package: { name: resolved.package.packageName, version: resolved.package.version },
337
+ })
338
+ await writeReport(db, result.check.findings, { source: 'transfer', scope: set.manifest.id })
339
+ if (!result.runId) {
340
+ printTransferFindings(result.check)
341
+ console.error(
342
+ `\n${target} was refused: ${result.check.outstanding.length} finding(s) outstanding. ` +
343
+ 'Nothing was written, and the site has not started.',
344
+ )
345
+ process.exit(1)
346
+ }
347
+ const c = result.check.counts
348
+ const placed = describePlaced(
349
+ resolved.blobs.size > 0
350
+ ? await placeBlobs(await mediaStoreFor(config), resolved.blobs)
351
+ : null,
352
+ )
353
+ lines.push(
354
+ ` bundle ${set.manifest.id}: ${c.create} created, ${c.update} updated` +
355
+ `${result.published.length > 0 ? `, ${result.published.length} published` : ''} (run ${result.runId})`,
356
+ )
357
+ if (placed) lines.push(` blobs ${placed}`)
358
+ for (const failure of result.publishFailures)
359
+ console.error(` not published ${failure.key}: ${failure.reason}`)
360
+ await recordInLedger(db, {
361
+ name: `content import ${set.manifest.id}`,
362
+ kind: 'transfer',
363
+ durationMs: Math.round(performance.now() - started),
364
+ appliedBy: config.nodeId,
365
+ note: `run ${result.runId}, ${resolved.package.packageName}@${resolved.package.version} (start --bundle)`,
366
+ })
367
+ imported = true
368
+ }
369
+ // The content landed under a cache this process had already constructed.
370
+ if (imported) server.cache.invalidate()
371
+ return lines
372
+ }
373
+
374
+ async function init(): Promise<void> {
375
+ const requested = flagValue('--template')
376
+ if (requested === 'list') {
377
+ for (const t of listTemplates()) console.log(` ${t.id.padEnd(20)} ${t.description}`)
378
+ console.log('\n (no --template scaffolds the files and no content)')
379
+ return
380
+ }
381
+ const template = requested ? findTemplate(requested) : undefined
382
+ if (requested && !template) {
383
+ console.error(`No template "${requested}". \`crombolo init --template list\` prints them.`)
384
+ process.exit(1)
385
+ }
386
+
387
+ const files = scaffoldFiles({
388
+ siteName: flagValue('--name'),
389
+ postgres: flags.has('--postgres'),
390
+ template,
391
+ })
392
+
393
+ for (const file of files) {
394
+ const target = join(cwd, file.path)
395
+ if (existsSync(target) && !flags.has('--force')) {
396
+ console.log(` exists ${file.path}`)
397
+ continue
398
+ }
399
+ await mkdir(join(target, '..'), { recursive: true })
400
+ if (file.copyFrom === undefined) await writeFile(target, file.text ?? '')
401
+ else await Bun.write(target, Bun.file(file.copyFrom))
402
+ console.log(` created ${file.path}`)
403
+ }
404
+
405
+ console.log(`\nNext:\n bun install\n bun start`)
406
+ if (template?.bundle)
407
+ console.log(
408
+ `\n\`bun start\` imports ${template.bundle} on the first boot of an empty database,\n` +
409
+ 'and says so. Nothing happens on later boots; it is one line in package.json.',
410
+ )
411
+ }
412
+
413
+ /**
414
+ * `crombolo status`: what this environment resolved to, and what is wrong with
415
+ * it, without starting it.
416
+ *
417
+ * Read-only by construction — it opens the database rather than bootstrapping
418
+ * it, so asking a production node how it is never migrates it.
419
+ */
420
+ async function status(): Promise<void> {
421
+ const config = await siteConfig()
422
+ const report = await siteStatus(config)
423
+
424
+ if (flags.has('--json')) {
425
+ console.log(JSON.stringify(report, null, 2))
426
+ if (report.problems.length > 0) process.exit(1)
427
+ return
428
+ }
429
+
430
+ const line = (label: string, value: string) => console.log(` ${label.padEnd(10)} ${value}`)
431
+ line('site', `${report.site.name}${report.site.dir ? ` ${report.site.dir}` : ''}`)
432
+ line('components', `${report.site.components} snapshots in ${report.site.componentsCache}`)
433
+ line(
434
+ 'database',
435
+ `${report.database.description} ${
436
+ report.database.reachable
437
+ ? report.database.installed
438
+ ? 'reachable'
439
+ : 'reachable, not installed'
440
+ : 'unreachable'
441
+ }`,
442
+ )
443
+ const files = report.schema.files ?? 'none'
444
+ const database = report.schema.database
445
+ ? `${report.schema.database.version}+${report.schema.database.revision}`
446
+ : 'not installed'
447
+ line(
448
+ 'schema',
449
+ `files ${files} database ${database} ${
450
+ !report.database.installed
451
+ ? 'nothing applied yet'
452
+ : report.schema.compatibilityMode
453
+ ? 'compatibility mode'
454
+ : report.schema.pending
455
+ ? 'a deploy is pending'
456
+ : 'up to date'
457
+ }`,
458
+ )
459
+ const pending = report.framework.pending
460
+ line(
461
+ 'framework',
462
+ pending.length === 0
463
+ ? 'no migration pending'
464
+ : // The whole list is a wall of names on a fresh database; `upgrade --plan`
465
+ // is where somebody goes when they want them.
466
+ pending.length > 3
467
+ ? `${pending.length} pending (\`crombolo upgrade --plan\` lists them)`
468
+ : `${pending.length} pending: ${pending.join(', ')}`,
469
+ )
470
+ line(
471
+ 'content',
472
+ `${report.content.documents} document(s), ${report.content.media} media, ${report.content.elements} element(s)` +
473
+ `${report.content.lastImport ? `; last import ${report.content.lastImport}` : ''}`,
474
+ )
475
+ line(
476
+ 'email',
477
+ report.email.available
478
+ ? (report.email.description ?? 'configured')
479
+ : report.email.provider === 'log'
480
+ ? 'console only, nothing is sent'
481
+ : `none — ${report.email.affects.join(', ')} unavailable`,
482
+ )
483
+ line(
484
+ 'findings',
485
+ `${report.findings.blocking} blocking, ${report.findings.person} need a person, ` +
486
+ `${report.findings.auto} automatic, ${report.findings.resolved} resolved`,
487
+ )
488
+ line(
489
+ 'versions',
490
+ `crombolo ${report.versions.crombolo}${report.versions.backoffice ? `, backoffice ${report.versions.backoffice}` : ''}, bun ${report.versions.bun}`,
491
+ )
492
+
493
+ for (const problem of report.problems) console.error(`\n ⚠ ${problem}`)
494
+ if (report.problems.length > 0) process.exit(1)
495
+ }
496
+
497
+ async function admin(): Promise<void> {
498
+ if (positional[0] !== 'reset-password') return help()
499
+ const config = await siteConfig()
500
+ // The database, not the server: resetting a password has nothing to do with
501
+ // the schema sync, the caches or the port, and should not need them to be
502
+ // healthy to work.
503
+ const { db } = await bootstrapDatabase(config)
504
+ const result = await resetAdminPassword(new AuthStore(db), config.adminLogin, positional[1])
505
+ await db.close()
506
+ if (!result) {
507
+ console.error(`No account '${config.adminLogin}'.`)
508
+ process.exit(1)
509
+ }
510
+ console.log(`${result.login}\n${result.password}`)
511
+ }
512
+
513
+ function describeSync(report: SyncReport): string {
514
+ switch (report.action) {
515
+ case 'applied':
516
+ case 'would-apply': {
517
+ const verb = report.action === 'applied' ? 'applied' : 'would apply'
518
+ const c = report.created
519
+ const parts = [
520
+ `${c.types} type(s)`,
521
+ `${c.properties} propert${c.properties === 1 ? 'y' : 'ies'}`,
522
+ `${c.dataTypes} data type(s)`,
523
+ `${c.languages} language(s)`,
524
+ ]
525
+ const extra = [
526
+ report.retired.length > 0 ? `retired ${report.retired.join(', ')}` : '',
527
+ report.retiredTypes.length > 0 ? `retired types ${report.retiredTypes.join(', ')}` : '',
528
+ report.revived.length > 0 ? `revived ${report.revived.join(', ')}` : '',
529
+ report.assignedKeys.length > 0 ? `${report.assignedKeys.length} key(s) assigned` : '',
530
+ ].filter(Boolean)
531
+ return `${verb} ${report.state?.version ?? ''}: created ${parts.join(', ')}${extra.length > 0 ? `; ${extra.join('; ')}` : ''}`
532
+ }
533
+ case 'skipped-same':
534
+ return 'up to date'
535
+ case 'skipped-older':
536
+ return `compatibility mode: ${report.reason ?? ''}`
537
+ case 'refused':
538
+ return `refused: ${report.reason ?? `${report.problems.length} problem(s)`}`
539
+ }
540
+ }
541
+
542
+ function printProblems(problems: SyncReport['problems']): void {
543
+ for (const p of problems)
544
+ console.error(` ${p.file}${p.path ? ` (${p.path})` : ''}: ${p.message}`)
545
+ }
546
+
547
+ async function schema(): Promise<void> {
548
+ const config = await siteConfig()
549
+ const sub = positional[0]
550
+ if (!existsSync(config.schemaDir) && sub !== 'export') {
551
+ console.error(`No schema directory at ${relative(cwd, config.schemaDir) || '.'}.`)
552
+ process.exit(1)
553
+ }
554
+ switch (sub) {
555
+ case 'check': {
556
+ const loaded = loadSchemaDirectory(config.schemaDir)
557
+ const problems = [
558
+ ...loaded.problems,
559
+ ...validateSchemaSet(loaded.set, {
560
+ componentAliases: componentAliasesIn(config.componentsDir),
561
+ }),
562
+ ]
563
+ if (problems.length > 0) {
564
+ console.error(`${problems.length} problem(s):`)
565
+ printProblems(problems)
566
+ process.exit(1)
567
+ }
568
+ console.log(
569
+ `schema ${loaded.set.version}: ${loaded.set.contentTypes.length} content type(s), ${(loaded.set.mediaTypes ?? []).length} media type(s), ${loaded.set.dataTypes.length} data type(s), ${loaded.set.languages.length} language(s) — valid`,
570
+ )
571
+ if (flags.has('--static')) {
572
+ const issues = staticProblems(loaded, await loadValueMigrations(config.schemaDir))
573
+ for (const issue of issues) console.error(` ${issue}`)
574
+ if (issues.length > 0) process.exit(1)
575
+ return
576
+ }
577
+ // The same check an upgrade runs, over the site's own diff.
578
+ positional[0] = 'check'
579
+ await upgrade()
580
+ return
581
+ }
582
+ case 'sync': {
583
+ const { db } = await bootstrapDatabase(config)
584
+ try {
585
+ const report = await syncSchemaDirectory(
586
+ db,
587
+ config,
588
+ { nodeId: config.nodeId, revision: config.schemaRevision },
589
+ { forceRetireTypes: flags.has('--force-retire-types') },
590
+ )
591
+ if (report.problems.length > 0) printProblems(report.problems)
592
+ console.log(describeSync(report))
593
+ if (report.action === 'refused') process.exit(1)
594
+ } finally {
595
+ await db.close()
596
+ }
597
+ return
598
+ }
599
+ case 'purge':
600
+ return schemaPurge(config)
601
+ case 'new':
602
+ return schemaNew(config)
603
+ case 'add-property':
604
+ return schemaAddProperty(config)
605
+ case 'rewrite': {
606
+ // Every file in the canonical layout: a reviewable commit when the vocabulary changes.
607
+ const loaded = loadSchemaDirectory(config.schemaDir)
608
+ if (loaded.problems.length > 0) {
609
+ printProblems(loaded.problems)
610
+ process.exit(1)
611
+ }
612
+ for (const file of writeSchemaFiles(config.schemaDir, loaded.set))
613
+ console.log(` wrote ${relative(cwd, file)}`)
614
+ return
615
+ }
616
+ case 'export': {
617
+ const { db } = await bootstrapDatabase(config)
618
+ try {
619
+ const version = existsSync(config.schemaDir)
620
+ ? loadSchemaDirectory(config.schemaDir).set.version
621
+ : '1.0.0'
622
+ const set = await exportSchemaSet(db, version)
623
+ for (const file of writeSchemaFiles(config.schemaDir, set))
624
+ console.log(` wrote ${relative(cwd, file)}`)
625
+ } finally {
626
+ await db.close()
627
+ }
628
+ return
629
+ }
630
+ default:
631
+ return help()
632
+ }
633
+ }
634
+
635
+ const TYPE_KINDS: Record<string, SchemaTypeKind> = {
636
+ 'content-type': 'document',
637
+ 'media-type': 'media',
638
+ 'member-type': 'member',
639
+ }
640
+
641
+ /**
642
+ * `schema new <kind> <alias>`: the file a site would otherwise write from
643
+ * memory, keys and all, and the view it points at.
644
+ */
645
+ async function schemaNew(config: CromboloConfig): Promise<void> {
646
+ const kindArg = positional[1] ?? ''
647
+ const alias = positional[2]
648
+ const kind = TYPE_KINDS[kindArg]
649
+ if (!kind || !alias) {
650
+ console.error(
651
+ `schema new needs a kind and an alias: ${Object.keys(TYPE_KINDS).join(', ')}.\n` +
652
+ ' crombolo schema new content-type article --at-root',
653
+ )
654
+ process.exit(1)
655
+ }
656
+
657
+ const loaded = loadSchemaDirectory(config.schemaDir)
658
+ const existing = [
659
+ ...loaded.set.contentTypes,
660
+ ...(loaded.set.mediaTypes ?? []),
661
+ ...(loaded.set.memberTypes ?? []),
662
+ ]
663
+ if (existing.some((type) => type.alias === alias)) {
664
+ console.error(`There is already a type with the alias "${alias}".`)
665
+ process.exit(1)
666
+ }
667
+
668
+ const element = flags.has('--element')
669
+ const type = newType({
670
+ alias,
671
+ kind,
672
+ name: flagValue('--name'),
673
+ description: flagValue('--description'),
674
+ icon: flagValue('--icon'),
675
+ allowAtRoot: flags.has('--at-root'),
676
+ element,
677
+ template: !flags.has('--no-view'),
678
+ // A content type with nothing in it cannot be published, so it starts with
679
+ // the one property every page has; the other kinds get what they are given.
680
+ tab: kind === 'document' ? (flagValue('--tab') ?? 'Content') : undefined,
681
+ })
682
+
683
+ const file = join(config.schemaDir, TYPE_KIND_FILES[kind].dir, fileNameFor(alias))
684
+ await mkdir(join(file, '..'), { recursive: true })
685
+ await writeFile(file, writeContentType(type, kind))
686
+ console.log(` created ${relative(cwd, file)}`)
687
+
688
+ // A type nothing allows cannot be created anywhere, which is a confusing
689
+ // first five minutes: the editor simply never offers it.
690
+ if (kind === 'document' && !element && !type.allowAtRoot) {
691
+ const parents = loaded.set.contentTypes.filter((t) => t.allowChildren.includes(alias))
692
+ if (parents.length === 0)
693
+ console.log(
694
+ ` note nothing allows a "${alias}" yet — add it to a parent's allow-children, or pass --at-root`,
695
+ )
696
+ }
697
+
698
+ if (type.components.length > 0) {
699
+ const view = join(config.componentsDir, `${alias}.tsx`)
700
+ if (existsSync(view)) console.log(` exists ${relative(cwd, view)}`)
701
+ else {
702
+ await mkdir(join(view, '..'), { recursive: true })
703
+ await writeFile(view, viewScaffold(type))
704
+ console.log(` created ${relative(cwd, view)}`)
705
+ }
706
+ }
707
+ return applySchema(config)
708
+ }
709
+
710
+ /** `schema add-property <type> <alias> --type <data type>`: the repetitive edit. */
711
+ async function schemaAddProperty(config: CromboloConfig): Promise<void> {
712
+ const typeAlias = positional[1]
713
+ const alias = positional[2]
714
+ const dataType = flagValue('--type')
715
+ if (!typeAlias || !alias || !dataType) {
716
+ console.error(
717
+ 'schema add-property needs the type, the property alias and --type <data type>:\n' +
718
+ ' crombolo schema add-property article summary --type textarea --mandatory',
719
+ )
720
+ process.exit(1)
721
+ }
722
+
723
+ const loaded = loadSchemaDirectory(config.schemaDir)
724
+ if (loaded.problems.length > 0) {
725
+ printProblems(loaded.problems)
726
+ process.exit(1)
727
+ }
728
+ const kinds: Array<[SchemaTypeKind, SchemaContentType[]]> = [
729
+ ['document', loaded.set.contentTypes],
730
+ ['media', loaded.set.mediaTypes ?? []],
731
+ ['member', loaded.set.memberTypes ?? []],
732
+ ]
733
+ const found = kinds
734
+ .map(([kind, types]) => ({ kind, type: types.find((t) => t.alias === typeAlias) }))
735
+ .find((candidate) => candidate.type)
736
+ if (!found?.type) {
737
+ console.error(`No type "${typeAlias}" in ${relative(cwd, config.schemaDir)}.`)
738
+ process.exit(1)
739
+ }
740
+
741
+ const known = new Set([
742
+ ...BUILTIN_DATA_TYPES.map((d) => d.alias),
743
+ ...loaded.set.dataTypes.map((d) => d.alias),
744
+ ])
745
+ if (!known.has(dataType)) {
746
+ console.error(`No data type "${dataType}". Built in: ${[...known].sort().join(', ')}`)
747
+ process.exit(1)
748
+ }
749
+
750
+ const result = addProperty(found.type, {
751
+ alias,
752
+ type: dataType,
753
+ name: flagValue('--name'),
754
+ description: flagValue('--description'),
755
+ mandatory: flags.has('--mandatory'),
756
+ tab: flagValue('--tab'),
757
+ })
758
+ if (!result.ok) {
759
+ console.error(` ${result.reason}`)
760
+ process.exit(1)
761
+ }
762
+
763
+ const file = join(config.schemaDir, TYPE_KIND_FILES[found.kind].dir, fileNameFor(typeAlias))
764
+ // The whole file is re-emitted from the model, as `schema rewrite` does, so a
765
+ // comment in it does not survive. Said out loud rather than discovered in a
766
+ // diff; `--dry-run` prints the file instead of writing it.
767
+ const text = writeContentType(result.type, found.kind)
768
+ if (flags.has('--dry-run')) {
769
+ console.log(text)
770
+ return
771
+ }
772
+ const before = existsSync(file) ? await Bun.file(file).text() : ''
773
+ await writeFile(file, text)
774
+ console.log(` wrote ${relative(cwd, file)}`)
775
+ console.log(
776
+ ` ${result.property.alias} ${result.property.name} (${dataType}${result.property.mandatory ? ', mandatory' : ''}) in tab "${result.tab}"`,
777
+ )
778
+ if (/^\s*#/m.test(before))
779
+ console.log(' note the file is rewritten canonically, so its comments are not kept')
780
+ return applySchema(config)
781
+ }
782
+
783
+ /** Applies `schema/` as a boot or a deploy step would, and reports what it did. */
784
+ async function applySchema(config: CromboloConfig): Promise<void> {
785
+ const { db } = await bootstrapDatabase(config)
786
+ try {
787
+ const report = await syncSchemaDirectory(db, config, {
788
+ nodeId: config.nodeId,
789
+ revision: config.schemaRevision,
790
+ })
791
+ if (report.problems.length > 0) printProblems(report.problems)
792
+ console.log(` schema ${describeSync(report)}`)
793
+ if (report.action === 'refused') process.exit(1)
794
+ } finally {
795
+ await db.close()
796
+ }
797
+ }
798
+
799
+ /** The pull-request rules: keys present, migrations well-formed, nothing the database needs. */
800
+ function staticProblems(
801
+ loaded: ReturnType<typeof loadSchemaDirectory>,
802
+ migrations: ValueMigration[],
803
+ ): string[] {
804
+ const problems: string[] = []
805
+ for (const t of loaded.set.contentTypes) {
806
+ if (!t.key)
807
+ problems.push(
808
+ `${t.alias}: no key — run \`crombolo schema sync\` in development to assign one`,
809
+ )
810
+ for (const p of allProperties(t)) if (!p.key) problems.push(`${t.alias}.${p.alias}: no key`)
811
+ }
812
+ for (const d of loaded.set.dataTypes) if (!d.key) problems.push(`data type ${d.alias}: no key`)
813
+ for (const m of migrations) {
814
+ const type = loaded.set.contentTypes.find((t) => t.alias === m.from.type)
815
+ if (!type) {
816
+ problems.push(`migration ${m.id}: no content type "${m.from.type}"`)
817
+ continue
818
+ }
819
+ for (const target of m.to)
820
+ if (!allProperties(type).some((p) => p.alias === target.property))
821
+ problems.push(
822
+ `migration ${m.id}: "${m.from.type}" has no property "${target.property}" to write to`,
823
+ )
824
+ }
825
+ return problems
826
+ }
827
+
828
+ async function schemaPurge(config: CromboloConfig): Promise<void> {
829
+ const index = rest.indexOf('--older-than')
830
+ const days = index >= 0 ? Number(rest[index + 1]) : Number.NaN
831
+ if (!Number.isFinite(days) || days < 0) {
832
+ console.error(
833
+ 'schema purge needs --older-than <days>: how long a property must have been retired.',
834
+ )
835
+ process.exit(1)
836
+ }
837
+ const backup = await backupBefore(config, {
838
+ reason: 'purge',
839
+ backupTaken: flags.has('--backup-taken'),
840
+ })
841
+ if (backup.path) console.log(` backup ${backup.path}`)
842
+ const { db } = await bootstrapDatabase(config)
843
+ try {
844
+ const before = new Date(Date.now() - days * 86_400_000)
845
+ const started = performance.now()
846
+ const purged = await new ContentTypeRepository(db).purgeRetired(before)
847
+ for (const p of purged) console.log(` purged ${p.type}.${p.alias}`)
848
+ if (purged.length === 0) console.log(`Nothing retired more than ${days} day(s) ago.`)
849
+ else
850
+ await recordInLedger(db, {
851
+ name: `purge ${purged.map((p) => `${p.type}.${p.alias}`).join(', ')}`,
852
+ kind: 'contract',
853
+ durationMs: Math.round(performance.now() - started),
854
+ appliedBy: config.nodeId,
855
+ note: `--older-than ${days}`,
856
+ })
857
+ } finally {
858
+ await db.close()
859
+ }
860
+ }
861
+
862
+ async function generate(): Promise<void> {
863
+ const config = await siteConfig()
864
+ const loaded = loadSchemaDirectory(config.schemaDir)
865
+ const problems = [...loaded.problems, ...validateSchemaSet(loaded.set)]
866
+ if (problems.length > 0) {
867
+ printProblems(problems)
868
+ process.exit(1)
869
+ }
870
+ const target = join(config.schemaDir, 'content-types.d.ts')
871
+ await writeFile(target, generateTypes(loaded.set))
872
+ console.log(` wrote ${relative(cwd, target)}`)
873
+ }
874
+
875
+ /** Every value given for a repeatable flag, in the order they appeared. */
876
+ function flagValues(name: string): string[] {
877
+ const out: string[] = []
878
+ for (let i = 0; i < rest.length; i++) {
879
+ if (rest[i] !== name) continue
880
+ const value = rest[i + 1]
881
+ if (value !== undefined && !value.startsWith('--')) out.push(value)
882
+ }
883
+ return out
884
+ }
885
+
886
+ function flagValue(name: string): string | undefined {
887
+ return flagValues(name)[0]
888
+ }
889
+
890
+ async function content(): Promise<void> {
891
+ const config = await siteConfig()
892
+ switch (positional[0]) {
893
+ case 'export':
894
+ return contentExport(config)
895
+ case 'check':
896
+ return contentCheck(config)
897
+ case 'import':
898
+ return contentImport(config)
899
+ case 'runs':
900
+ return contentRuns(config)
901
+ case 'publish':
902
+ return contentPublish(config, true)
903
+ case 'unpublish':
904
+ return contentPublish(config, false)
905
+ case 'revert':
906
+ return contentRevert(config)
907
+ default:
908
+ return help()
909
+ }
910
+ }
911
+
912
+ async function contentRevert(config: CromboloConfig): Promise<void> {
913
+ const runId = positional[1]
914
+ if (!runId) {
915
+ console.error('content revert needs the run id. `crombolo content runs` lists them.')
916
+ process.exit(1)
917
+ }
918
+ const resolutions: Record<string, RevertResolution> = {}
919
+ for (const pair of flagValues('--resolve')) {
920
+ const eq = pair.indexOf('=')
921
+ const choice = eq >= 0 ? pair.slice(eq + 1) : ''
922
+ if (eq < 0 || !isRevertResolution(choice)) {
923
+ console.error(` --resolve wants <key>=${REVERT_RESOLUTIONS.join('|')}, not "${pair}"`)
924
+ process.exit(1)
925
+ }
926
+ resolutions[pair.slice(0, eq)] = choice
927
+ }
928
+ const allFlag = flagValue('--resolve-all')
929
+ if (allFlag !== undefined && !isRevertResolution(allFlag)) {
930
+ console.error(` "${allFlag}" is not one of ${REVERT_RESOLUTIONS.join(', ')}`)
931
+ process.exit(1)
932
+ }
933
+
934
+ const backup = await backupBefore(config, {
935
+ reason: 'content-revert',
936
+ backupTaken: flags.has('--backup-taken'),
937
+ })
938
+ if (backup.path) console.log(` backup ${backup.path}`)
939
+
940
+ const { db } = await bootstrapDatabase(config)
941
+ try {
942
+ const started = performance.now()
943
+ const forceIndex = rest.indexOf('--force')
944
+ const result = await revertRun(db, runId, {
945
+ resolutions,
946
+ resolveAll: allFlag as RevertResolution | undefined,
947
+ force: forceIndex >= 0,
948
+ nodeId: config.nodeId,
949
+ backOfficePath: config.backOfficePath,
950
+ })
951
+
952
+ if (!result.runId) {
953
+ for (const f of result.check.findings) {
954
+ console.error(` [${f.kind.padEnd(8)}] ${f.message}`)
955
+ for (const suggestion of revertResolutionsFor(f.code))
956
+ console.error(` → ${suggestion}`)
957
+ }
958
+ console.error('\nrevert refused. Nothing was changed.')
959
+ process.exit(1)
960
+ }
961
+
962
+ // The files an install replaced come back from the run's own copies, not
963
+ // from git: these files are editable in the backoffice, so a site need not
964
+ // be a checkout at all.
965
+ const files = ops.restoreSectionFiles(config, runId)
966
+ for (const file of files.restored) console.log(` restored ${relative(cwd, file)}`)
967
+ for (const file of files.removed)
968
+ console.log(` removed ${relative(cwd, file)} (created by that run)`)
969
+
970
+ for (const key of result.restored) console.log(` restored ${key}`)
971
+ for (const key of result.recycled) console.log(` recycled ${key} (created by that run)`)
972
+ for (const entry of result.check.plan.filter((p) => p.action === 'skip'))
973
+ console.log(` left ${entry.name}`)
974
+ await recordInLedger(db, {
975
+ name: `content revert ${runId}`,
976
+ kind: 'revert',
977
+ durationMs: Math.round(performance.now() - started),
978
+ appliedBy: config.nodeId,
979
+ note: `run ${result.runId}`,
980
+ })
981
+ console.log(
982
+ `\nReverted ${runId} as run ${result.runId}. ` +
983
+ `\`crombolo content revert ${result.runId}\` would put it back again.`,
984
+ )
985
+ } finally {
986
+ await db.close()
987
+ }
988
+ }
989
+
990
+ /**
991
+ * Puts the media files a bundle carries into this environment's store.
992
+ *
993
+ * After the content, because the run is what decides whether any of this
994
+ * happened: a refused import leaves the store alone. The keys are the ones the
995
+ * values already name, so a picked image finds its file wherever media lives
996
+ * here — a disk, a bucket, a container.
997
+ */
998
+ function describePlaced(placed: { placed: number; bytes: number } | null): string | undefined {
999
+ if (!placed) return undefined
1000
+ return `${placed.placed} media file(s) placed, ${describeBytes(placed.bytes)}`
1001
+ }
1002
+
1003
+ /** The flags `check` and `import` share: resolutions, placement, blobs. */
1004
+ function transferInput(bundle: string): ops.TransferInput {
1005
+ const allFlag = flagValue('--resolve-all')
1006
+ if (allFlag !== undefined && !isResolution(allFlag)) {
1007
+ console.error(` "${allFlag}" is not one of ${RESOLUTIONS.join(', ')}`)
1008
+ process.exit(1)
1009
+ }
1010
+ return {
1011
+ bundle,
1012
+ under: flagValue('--under'),
1013
+ resolutions: parseResolutions(),
1014
+ resolveAll: allFlag as Resolution | undefined,
1015
+ allowMissingBlobs: flags.has('--allow-missing-blobs'),
1016
+ // What a bundle carries is applied by default — that is the point of it
1017
+ // carrying anything — so these decline a half, for someone who wants the
1018
+ // content without the structure that came with it.
1019
+ withoutSchema: flags.has('--no-schema'),
1020
+ withoutFiles: flags.has('--no-files'),
1021
+ replaceFiles: flags.has('--replace-files'),
1022
+ }
1023
+ }
1024
+
1025
+ /** What the carried sections would do, or did. */
1026
+ function printSections(plan: ops.SectionPlan | undefined): void {
1027
+ if (!plan) return
1028
+ console.log(` carries ${plan.sections.join(', ')}`)
1029
+ const counts = new Map<string, number>()
1030
+ for (const file of plan.files) counts.set(file.action, (counts.get(file.action) ?? 0) + 1)
1031
+ const summary = [...counts].map(([action, n]) => `${n} ${action}`).join(', ')
1032
+ if (summary) console.log(` files ${summary}`)
1033
+ for (const file of plan.files)
1034
+ if (file.action === 'overwrite') console.log(` overwrites ${relative(cwd, file.target)}`)
1035
+ if (plan.dictionaryItems > 0) console.log(` dict ${plan.dictionaryItems} file(s)`)
1036
+ if (plan.schema) {
1037
+ console.log(` schema ${plan.schema.classification}`)
1038
+ for (const finding of plan.schema.findings) console.log(` ${finding}`)
1039
+ }
1040
+ }
1041
+
1042
+ /** Bytes as somebody reads them, since a bundle of media is measured in them. */
1043
+ function describeBytes(bytes: number): string {
1044
+ if (bytes < 1024) return `${bytes} B`
1045
+ const units = ['KB', 'MB', 'GB']
1046
+ let value = bytes / 1024
1047
+ let unit = 0
1048
+ while (value >= 1024 && unit < units.length - 1) {
1049
+ value /= 1024
1050
+ unit += 1
1051
+ }
1052
+ return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`
1053
+ }
1054
+
1055
+ function describeBundle(bundle: ops.BundleSummary): void {
1056
+ console.log(
1057
+ ` bundle ${bundle.id} from ${bundle.from || 'elsewhere'} ` +
1058
+ `(schema ${bundle.schemaVersion}+${bundle.schemaRevision}, ` +
1059
+ `${bundle.snapshot} snapshot, ${bundle.nodes} node(s))`,
1060
+ )
1061
+ if (bundle.blobsCarried > 0)
1062
+ console.log(
1063
+ ` blobs ${bundle.blobsCarried} media file(s) carried, ${describeBytes(bundle.blobBytes)}`,
1064
+ )
1065
+ }
1066
+
1067
+ async function contentImport(config: CromboloConfig): Promise<void> {
1068
+ const dir = positional[1]
1069
+ if (!dir) {
1070
+ console.error(
1071
+ 'content import needs a bundle: a package directory, or the name of a bundle this site depends on.',
1072
+ )
1073
+ process.exit(1)
1074
+ }
1075
+ const result = await ops.contentImport(config, {
1076
+ ...transferInput(dir),
1077
+ publish: flags.has('--publish'),
1078
+ label: flagValue('--label'),
1079
+ backupTaken: flags.has('--backup-taken'),
1080
+ })
1081
+ for (const problem of result.problems) console.error(` ${problem}`)
1082
+ if (result.backup.path) console.log(` backup ${result.backup.path}`)
1083
+ describeBundle(result.bundle)
1084
+
1085
+ if (!result.runId) {
1086
+ printTransferFindings(result.check)
1087
+ // Sections are applied before the content is checked, because content
1088
+ // naming a type the bundle brings cannot pass a check until that type
1089
+ // exists. So a refusal here may still have written files, and saying
1090
+ // otherwise would send somebody looking in the wrong place.
1091
+ if (result.sections) {
1092
+ console.error(
1093
+ `\nimport refused, but this bundle's structure was already applied: ` +
1094
+ `${result.sections.written.length} file(s) written${
1095
+ result.sections.schema ? `, schema ${result.sections.schema.action}` : ''
1096
+ }.`,
1097
+ )
1098
+ for (const file of result.sections.written) console.error(` ${relative(cwd, file)}`)
1099
+ if (result.sections.replaced.length > 0)
1100
+ console.error(
1101
+ ` the originals are under ${relative(cwd, join(config.siteDir, ops.RUN_BACKUP_DIR))}`,
1102
+ )
1103
+ } else {
1104
+ console.error(
1105
+ `\nimport refused: ${result.check.outstanding.length} finding(s) outstanding. Nothing was written.`,
1106
+ )
1107
+ }
1108
+ process.exit(1)
1109
+ }
1110
+
1111
+ const c = result.check.counts
1112
+ console.log(` run ${result.runId}`)
1113
+ console.log(
1114
+ ` applied ${c.create} created, ${c.update} updated, ${c.unchanged} unchanged, ${c.skip} skipped`,
1115
+ )
1116
+ const placed = describePlaced(result.blobs)
1117
+ if (placed) console.log(` blobs ${placed}`)
1118
+ if (result.sections) {
1119
+ console.log(
1120
+ ` files ${result.sections.written.length} written` +
1121
+ (result.sections.replaced.length > 0
1122
+ ? `, ${result.sections.replaced.length} replaced`
1123
+ : ''),
1124
+ )
1125
+ if (result.sections.schema) console.log(` schema ${result.sections.schema.action}`)
1126
+ if (result.sections.dictionary)
1127
+ console.log(` dict ${result.sections.dictionary.imported} imported`)
1128
+ // Named, because this is what makes reverting the install possible.
1129
+ if (result.replacedFilesKept)
1130
+ console.log(` kept ${relative(cwd, result.replacedFilesKept)} (the files it replaced)`)
1131
+ }
1132
+ if (result.published > 0) console.log(` published ${result.published} node(s)`)
1133
+ for (const failure of result.publishFailures)
1134
+ console.error(` not published ${failure.key}: ${failure.reason}`)
1135
+ for (const finding of result.check.findings.filter((f) => f.kind === 'auto'))
1136
+ console.log(` [auto ] ${finding.message}`)
1137
+ console.log(`\nDone. \`crombolo content revert ${result.runId}\` puts it back.`)
1138
+ }
1139
+
1140
+ /**
1141
+ * `content publish` / `content unpublish`: taking a page or a branch live, and
1142
+ * back off again, without the backoffice.
1143
+ *
1144
+ * A publish can be refused per node — an unpublished ancestor, an unpublished
1145
+ * mandatory language, an empty mandatory property — so the whole selection is
1146
+ * checked before any of it is written. Half a published branch is a state
1147
+ * nobody asked for and nobody can reason about.
1148
+ */
1149
+ async function contentPublish(config: CromboloConfig, publishing: boolean): Promise<void> {
1150
+ const ref = positional[1]
1151
+ const verb = publishing ? 'publish' : 'unpublish'
1152
+ if (!ref) {
1153
+ console.error(`content ${verb} needs the page: a path or a uuid.`)
1154
+ process.exit(1)
1155
+ }
1156
+ const cultures = flagValues('--culture')
1157
+ const at = flagValue('--at')
1158
+ const until = flagValue('--until')
1159
+ const when = (value: string | undefined, what: string): Date | null => {
1160
+ if (value === undefined) return null
1161
+ const date = new Date(value)
1162
+ if (Number.isNaN(date.getTime())) {
1163
+ console.error(` ${what} "${value}" is not a date I can read; try 2026-10-01T09:00`)
1164
+ process.exit(1)
1165
+ }
1166
+ return date
1167
+ }
1168
+ const publishTime = when(at, '--at')
1169
+ const unpublishTime = when(until, '--until')
1170
+
1171
+ const { db } = await bootstrapDatabase(config)
1172
+ try {
1173
+ const resolved = await resolveNodeRef(db, [ObjectTypes.Document], ref)
1174
+ if (!resolved.ok) {
1175
+ console.error(` ${describeRefFailure(ref, resolved)}`)
1176
+ process.exit(1)
1177
+ }
1178
+ const state = await currentSchemaState(db)
1179
+ const docs = new DocumentRepository(db, {
1180
+ nodeState: { version: state.version, revision: state.revision },
1181
+ nodeId: config.nodeId,
1182
+ })
1183
+ // Parents before children, which is the order publishing has to happen in.
1184
+ const targets = [
1185
+ resolved.node,
1186
+ ...(flags.has('--descendants')
1187
+ ? await docs.nodes.descendants(resolved.node, [ObjectTypes.Document])
1188
+ : []),
1189
+ ]
1190
+
1191
+ if (publishTime || unpublishTime) {
1192
+ // A schedule is a statement about the future, so today's blockers are not
1193
+ // the question: the background job checks them when the time comes.
1194
+ for (const node of targets) {
1195
+ await docs.setSchedule(node.key, [
1196
+ { culture: cultures[0] ?? null, publishTime, unpublishTime },
1197
+ ])
1198
+ console.log(
1199
+ ` scheduled ${node.text ?? node.key}${publishTime ? ` from ${publishTime.toISOString()}` : ''}${unpublishTime ? ` until ${unpublishTime.toISOString()}` : ''}`,
1200
+ )
1201
+ }
1202
+ return
1203
+ }
1204
+
1205
+ if (publishing) {
1206
+ const blocked: Array<{ name: string; reasons: string[] }> = []
1207
+ // Everything in the selection counts as published for the check: the run
1208
+ // publishes parents first, so a child is not blocked by an ancestor this
1209
+ // very command is about to take live.
1210
+ const selection = new Set(targets.map((node) => node.id))
1211
+ for (const node of targets) {
1212
+ const reasons = await docs.publishBlockers(node.key, cultures, selection)
1213
+ if (reasons.length > 0) blocked.push({ name: node.text ?? node.key, reasons })
1214
+ }
1215
+ if (blocked.length > 0) {
1216
+ console.error(
1217
+ ` refused ${blocked.length} of ${targets.length} page(s) cannot be published:`,
1218
+ )
1219
+ for (const entry of blocked) console.error(` ${entry.name} ${entry.reasons.join('; ')}`)
1220
+ console.error(' nothing was published')
1221
+ process.exit(1)
1222
+ }
1223
+ }
1224
+
1225
+ for (const node of targets) {
1226
+ const result = publishing
1227
+ ? await docs.publish(node.key, cultures.length > 0 ? cultures : null)
1228
+ : await docs.unpublish(node.key, cultures.length > 0 ? cultures : null)
1229
+ if (!result) continue
1230
+ console.log(` ${publishing ? 'published' : 'unpublished'} ${node.text ?? node.key}`)
1231
+ }
1232
+ console.log(
1233
+ `\n${targets.length} page(s) ${publishing ? 'published' : 'unpublished'}${cultures.length > 0 ? ` in ${cultures.join(', ')}` : ''}.`,
1234
+ )
1235
+ } finally {
1236
+ await db.close()
1237
+ }
1238
+ }
1239
+
1240
+ async function contentRuns(config: CromboloConfig): Promise<void> {
1241
+ const limitIndex = rest.indexOf('--limit')
1242
+ const limit = limitIndex >= 0 ? Number(rest[limitIndex + 1]) : 20
1243
+ const { db } = await bootstrapDatabase(config)
1244
+ try {
1245
+ const runs = await new TransferRunRepository(db).recent(
1246
+ Number.isFinite(limit) && limit > 0 ? limit : 20,
1247
+ )
1248
+ if (runs.length === 0) return console.log('No content has been imported here.')
1249
+ for (const run of runs)
1250
+ console.log(
1251
+ ` ${run.startedAt.toISOString()} ${run.direction.padEnd(6)} ${run.status.padEnd(8)} ` +
1252
+ `${run.id} ${run.nodeCount} node(s) bundle ${run.bundleId}` +
1253
+ `${run.appliedBy ? ` by ${run.appliedBy}` : ''}${run.bundleLabel ? ` (${run.bundleLabel})` : ''}`,
1254
+ )
1255
+ } finally {
1256
+ await db.close()
1257
+ }
1258
+ }
1259
+
1260
+ /** `--resolve <key>=take-bundle`, repeatable; the same shape as `--set`. */
1261
+ function parseResolutions(): Record<string, Resolution> {
1262
+ const out: Record<string, Resolution> = {}
1263
+ for (const pair of flagValues('--resolve')) {
1264
+ const eq = pair.indexOf('=')
1265
+ if (eq < 0) {
1266
+ console.error(` --resolve wants <key>=<choice>, not "${pair}"`)
1267
+ process.exit(1)
1268
+ }
1269
+ const choice = pair.slice(eq + 1)
1270
+ if (!isResolution(choice)) {
1271
+ console.error(` "${choice}" is not one of ${RESOLUTIONS.join(', ')}`)
1272
+ process.exit(1)
1273
+ }
1274
+ out[pair.slice(0, eq)] = choice
1275
+ }
1276
+ return out
1277
+ }
1278
+
1279
+ function printTransferFindings(check: TransferCheck): void {
1280
+ const byKind = { blocking: 0, person: 0, auto: 0 }
1281
+ for (const f of check.findings) byKind[f.kind] += 1
1282
+ const c = check.counts
1283
+ console.log(
1284
+ ` plan ${c.create} new, ${c.update} updated, ${c.unchanged} unchanged, ${c.skip} skipped`,
1285
+ )
1286
+ console.log(
1287
+ ` findings ${byKind.blocking} blocking, ${byKind.person} need a person, ${byKind.auto} automatic`,
1288
+ )
1289
+ for (const f of check.findings) {
1290
+ console.log(` [${f.kind.padEnd(8)}] ${f.message}`)
1291
+ for (const suggestion of resolutionsFor(f.code)) console.log(` → ${suggestion}`)
1292
+ if (f.link) console.log(` ${f.link}`)
1293
+ }
1294
+ }
1295
+
1296
+ async function contentCheck(config: CromboloConfig): Promise<void> {
1297
+ const dir = positional[1]
1298
+ if (!dir) {
1299
+ console.error(
1300
+ 'content check needs a bundle: a package directory, or the name of a bundle this site depends on.',
1301
+ )
1302
+ process.exit(1)
1303
+ }
1304
+ const result = await ops.contentCheck(config, transferInput(dir))
1305
+ for (const problem of result.problems) console.error(` ${problem}`)
1306
+ describeBundle(result.bundle)
1307
+ if (result.under) console.log(` under ${result.under}`)
1308
+ printSections(result.sections)
1309
+ printTransferFindings(result.check)
1310
+
1311
+ if (flags.has('--save')) {
1312
+ const target = join(result.payloadDir, RESOLUTIONS_FILE)
1313
+ await writeFile(
1314
+ target,
1315
+ writeResolutions({
1316
+ bundleId: result.bundle.id,
1317
+ under: flagValue('--under') ?? null,
1318
+ all: result.decisions.all,
1319
+ byNode: result.decisions.byNode,
1320
+ }),
1321
+ )
1322
+ console.log(` wrote ${relative(cwd, target)}`)
1323
+ }
1324
+
1325
+ if (!result.clean) {
1326
+ console.log(
1327
+ `\n${result.check.outstanding.length} finding(s) would stop an import. Resolve them, or pass --resolve.`,
1328
+ )
1329
+ process.exit(1)
1330
+ }
1331
+ console.log('\nNothing outstanding: this bundle would import cleanly.')
1332
+ }
1333
+
1334
+ async function contentExport(config: CromboloConfig): Promise<void> {
1335
+ const out = flagValue('--out')
1336
+ const refs = flagValues('--root')
1337
+ if (!out || refs.length === 0) {
1338
+ console.error('content export needs --root <path|uuid> (repeatable) and --out <dir>.')
1339
+ process.exit(1)
1340
+ }
1341
+ const result = await ops.contentExport(config, {
1342
+ roots: refs,
1343
+ only: flags.has('--only'),
1344
+ drafts: flags.has('--drafts'),
1345
+ withBlobs: flags.has('--with-blobs'),
1346
+ withBlueprints: flags.has('--with-blueprints'),
1347
+ // An export is a private package; without --name it is named for its directory.
1348
+ package: {
1349
+ name: flagValue('--name') ?? packageNameFor(basename(resolve(out))),
1350
+ version: flagValue('--package-version'),
1351
+ },
1352
+ })
1353
+ for (const key of result.blobs.missing)
1354
+ console.error(` missing ${key} is not in this environment's media store`)
1355
+ for (const file of result.files) {
1356
+ const target = join(out, file.path)
1357
+ await mkdir(join(target, '..'), { recursive: true })
1358
+ await writeFile(target, file.bytes ?? (file.text as string))
1359
+ }
1360
+ const counts = Object.entries(result.counts)
1361
+ console.log(` wrote ${relative(cwd, out) || '.'}`)
1362
+ console.log(` package ${result.package.name}@${result.package.version} (private)`)
1363
+ console.log(
1364
+ ` bundle ${result.bundleId} (${result.snapshot}): ${
1365
+ counts.length > 0 ? counts.map(([kind, n]) => `${n} ${kind}`).join(', ') : 'nothing selected'
1366
+ }`,
1367
+ )
1368
+ if (result.expected.length > 0) {
1369
+ console.log(` expects ${result.expected.length} node(s) to exist at the destination:`)
1370
+ for (const e of result.expected) console.log(` ${e.key} ${e.name} (${e.why})`)
1371
+ }
1372
+ if (result.blobs.carried > 0)
1373
+ console.log(
1374
+ ` blobs ${result.blobs.carried} media file(s), ${describeBytes(result.blobs.bytes)}`,
1375
+ )
1376
+ else if (result.blobs.notCarried > 0)
1377
+ console.log(
1378
+ ` blobs ${result.blobs.notCarried} media file(s) are not carried — pass --with-blobs to include them`,
1379
+ )
1380
+ if (counts.length === 0) process.exit(1)
1381
+ }
1382
+
1383
+ /**
1384
+ * `schema-as-code.md` leaves the dictionary in the database, because
1385
+ * translators work in production where `schema/` is read-only — so this is how
1386
+ * a lower environment gets the translations.
1387
+ */
1388
+ async function dictionary(): Promise<void> {
1389
+ const config = await siteConfig()
1390
+ const sub = positional[0]
1391
+ if (sub !== 'export' && sub !== 'import') return help()
1392
+ const { db } = await bootstrapDatabase(config)
1393
+ try {
1394
+ if (sub === 'export') {
1395
+ const out = flagValue('--out')
1396
+ if (!out) {
1397
+ console.error('dictionary export needs --out <file.udt>.')
1398
+ process.exit(1)
1399
+ }
1400
+ const items = await dictionaryToUdt(new DictionaryRepository(db), flagValue('--key'))
1401
+ if (items.length === 0) {
1402
+ console.error('Nothing to export: this site has no dictionary items.')
1403
+ process.exit(1)
1404
+ }
1405
+ await mkdir(join(out, '..'), { recursive: true })
1406
+ await writeFile(out, writeDictionaryUdt(items))
1407
+ const count = (list: typeof items): number =>
1408
+ list.reduce((total, item) => total + 1 + count(item.children), 0)
1409
+ console.log(` wrote ${relative(cwd, out)}`)
1410
+ console.log(` items ${count(items)}`)
1411
+ return
1412
+ }
1413
+
1414
+ const file = positional[1]
1415
+ if (!file) {
1416
+ console.error('dictionary import needs the .udt file.')
1417
+ process.exit(1)
1418
+ }
1419
+ if (!existsSync(file)) {
1420
+ console.error(`No file at ${file}.`)
1421
+ process.exit(1)
1422
+ }
1423
+ const outcome = await importDictionaryUdt(db, await Bun.file(file).text(), null)
1424
+ if (!outcome.ok) {
1425
+ console.error(` refused: ${outcome.reason}`)
1426
+ process.exit(1)
1427
+ }
1428
+ console.log(` imported ${outcome.imported} item(s)`)
1429
+ // Umbraco's own behaviour, and worth saying out loud rather than dropping
1430
+ // translations silently: a language this site has not got is skipped.
1431
+ if (outcome.skipped.length > 0)
1432
+ console.log(
1433
+ ` skipped translations for ${outcome.skipped.join(', ')} — no such language here`,
1434
+ )
1435
+ } finally {
1436
+ await db.close()
1437
+ }
1438
+ }
1439
+
1440
+ /**
1441
+ * `crombolo domains`: which hostnames reach which page.
1442
+ *
1443
+ * `domains.toml` is the truth and the database follows it, so `set` and `clear`
1444
+ * write the file and then apply it — one command, rather than an edit here and
1445
+ * a deploy to make it real. The file is committed; `${VAR}` in a host is read
1446
+ * from the environment when it is applied, so one file serves every
1447
+ * environment.
1448
+ */
1449
+ async function domains(): Promise<void> {
1450
+ const config = await siteConfig()
1451
+ const sub = positional[0] ?? 'list'
1452
+ if (sub !== 'list' && sub !== 'apply' && sub !== 'set' && sub !== 'clear' && sub !== 'undo')
1453
+ return help()
1454
+
1455
+ const file = domainsFilePath(config.siteDir)
1456
+ const read = readDomainsFile(config.siteDir)
1457
+ const declarations = read?.declarations ?? []
1458
+ for (const problem of read?.problems ?? []) console.error(` ${file}: ${problem}`)
1459
+
1460
+ if (sub === 'list') {
1461
+ const { db } = await bootstrapDatabase(config)
1462
+ try {
1463
+ if (!read) console.log(`No ${DOMAINS_FILE}; nothing is deployed from a file here.`)
1464
+ for (const declaration of declarations) {
1465
+ const resolved = resolvePlaceholders(declaration.host)
1466
+ const culture = declaration.culture ? ` ${declaration.culture}` : ''
1467
+ // What the file says, and what it comes to here, which is the whole
1468
+ // point of a placeholder and the first thing to check when one is wrong.
1469
+ const here =
1470
+ resolved.missing.length > 0
1471
+ ? ` (${resolved.missing.join(', ')} not set here)`
1472
+ : resolved.value !== declaration.host
1473
+ ? ` → ${resolved.value}`
1474
+ : ''
1475
+ console.log(
1476
+ ` file ${declaration.node.padEnd(24)} ${declaration.host}${here}${culture}`,
1477
+ )
1478
+ }
1479
+ // What the database actually answers on, which is the thing a person is
1480
+ // usually asking about when a hostname is not working.
1481
+ const nodes = new NodeRepository(db)
1482
+ for (const row of await new DomainRepository(db).all()) {
1483
+ const node = await nodes.byId(row.nodeId)
1484
+ console.log(
1485
+ ` bound ${(node?.text ?? String(row.nodeId)).padEnd(24)} ${row.domainName}${row.isoCode ? ` ${row.isoCode}` : ''}`,
1486
+ )
1487
+ }
1488
+ } finally {
1489
+ await db.close()
1490
+ }
1491
+ return
1492
+ }
1493
+
1494
+ if (sub === 'apply') return applyDomains(config)
1495
+
1496
+ if (sub === 'undo') {
1497
+ const undone = await undoDomainsFile(config.siteDir)
1498
+ if (!undone.ok) {
1499
+ console.error(` ${undone.message}`)
1500
+ process.exit(1)
1501
+ }
1502
+ console.log(` restored ${relative(cwd, undone.file)}`)
1503
+ return applyDomains(config)
1504
+ }
1505
+
1506
+ const ref = positional[1]
1507
+ if (!ref) {
1508
+ console.error(`domains ${sub} needs the page: a path, a uuid, or / for the root page.`)
1509
+ process.exit(1)
1510
+ }
1511
+
1512
+ // Stating a node's hostnames says what they are, as the backoffice's dialog
1513
+ // does: whatever that page had is replaced, so running this twice is the same
1514
+ // as running it once. Which entries belong to that page is decided by
1515
+ // resolving them, not by matching the text — `/` and `/Home` can be the same
1516
+ // page, and clearing one while the other stayed would do nothing at all.
1517
+ const { db: resolving } = await bootstrapDatabase(config)
1518
+ let kept: DomainDeclaration[] = []
1519
+ try {
1520
+ const target = await resolveDomainNode(resolving, ref)
1521
+ if (!target.ok) {
1522
+ console.error(` ${target.message}`)
1523
+ process.exit(1)
1524
+ }
1525
+ kept = await withoutNode(resolving, declarations, target.node)
1526
+ } finally {
1527
+ await resolving.close()
1528
+ }
1529
+ const defaultCulture = flagValue('--default-culture')
1530
+ const next: DomainDeclaration[] = [...kept]
1531
+ if (sub === 'set') {
1532
+ const hosts = flagValues('--host')
1533
+ if (hosts.length === 0 && !defaultCulture) {
1534
+ console.error('domains set needs --host <host>[=<culture>], or --default-culture <iso>.')
1535
+ process.exit(1)
1536
+ }
1537
+ if (hosts.length === 0 && defaultCulture) next.push({ node: ref, host: '', defaultCulture })
1538
+ for (const [index, entry] of hosts.entries()) {
1539
+ const [host = '', culture] = entry.split('=')
1540
+ next.push({
1541
+ node: ref,
1542
+ host,
1543
+ culture,
1544
+ // The node's own fallback culture belongs to the node, so it is written
1545
+ // once rather than repeated on every hostname.
1546
+ defaultCulture: index === 0 ? defaultCulture : undefined,
1547
+ })
1548
+ }
1549
+ }
1550
+
1551
+ const written = await writeDomains(config.siteDir, next)
1552
+ console.log(
1553
+ ` wrote ${relative(cwd, written.file)}${written.backup ? ' (previous kept; `crombolo domains undo` puts it back)' : ''}`,
1554
+ )
1555
+ return applyDomains(config)
1556
+ }
1557
+
1558
+ /** Applies the file as a boot would, and reports what it did. */
1559
+ async function applyDomains(config: CromboloConfig): Promise<void> {
1560
+ const { db } = await bootstrapDatabase(config)
1561
+ try {
1562
+ const report = await syncDomainsFile(db, config.siteDir)
1563
+ for (const problem of report.problems) console.error(` ${problem}`)
1564
+ for (const applied of report.applied)
1565
+ console.log(
1566
+ ` applied ${applied.node.padEnd(24)} ${applied.host}${applied.culture ? ` ${applied.culture}` : ''}`,
1567
+ )
1568
+ if (report.removed > 0) console.log(` removed ${report.removed} binding(s)`)
1569
+ if (report.problems.length > 0) process.exit(1)
1570
+ } finally {
1571
+ await db.close()
1572
+ }
1573
+ }
1574
+
1575
+ /**
1576
+ * `crombolo import umbraco`: a compatibility report for an Umbraco backup, and
1577
+ * then a crombolo site written from it.
1578
+ *
1579
+ * Neither subcommand touches a database. `report` reads the backup and prints
1580
+ * what will and will not come across; `apply` writes a site directory — schema
1581
+ * files, view stubs, a content bundle — whose `start` script does the import
1582
+ * through `start --bundle`, the path every other bundle takes.
1583
+ *
1584
+ * The importer is a package of its own, loaded here on demand, so a site that
1585
+ * never imports anything does not carry it or the `.bacpac` reader it needs.
1586
+ */
1587
+ async function importSite(): Promise<void> {
1588
+ const VALUE_FLAGS = new Set(['--out', '--site', '--media', '--name', '--staging'])
1589
+ const args: string[] = []
1590
+ for (let i = 0; i < rest.length; i++) {
1591
+ const arg = rest[i] as string
1592
+ if (VALUE_FLAGS.has(arg)) i++
1593
+ else if (!arg.startsWith('--')) args.push(arg)
1594
+ }
1595
+ const [kind, sub, backup] = args
1596
+ if (kind !== 'umbraco' || (sub !== 'report' && sub !== 'apply')) return help()
1597
+ if (!backup) {
1598
+ console.error(`import umbraco ${sub} needs the backup: a .bacpac, or Umbraco's SQLite file.`)
1599
+ process.exit(1)
1600
+ }
1601
+ const out = flagValue('--out')
1602
+ if (sub === 'apply' && !out) {
1603
+ console.error('import umbraco apply needs --out <dir>: the site directory to write.')
1604
+ process.exit(1)
1605
+ }
1606
+
1607
+ let importer: typeof import('@crombolo/import-umbraco')
1608
+ try {
1609
+ importer = await import('@crombolo/import-umbraco')
1610
+ } catch {
1611
+ console.error(
1612
+ 'The importer is a separate package. Add it, then run this again:\n\n bun add -d @crombolo/import-umbraco',
1613
+ )
1614
+ process.exit(1)
1615
+ }
1616
+
1617
+ let plan: Awaited<ReturnType<typeof importer.planImport>>
1618
+ try {
1619
+ plan = await importer.planImport({
1620
+ source: backup,
1621
+ site: flagValue('--site'),
1622
+ media: flagValue('--media'),
1623
+ siteName: flagValue('--name'),
1624
+ drafts: flags.has('--drafts'),
1625
+ staging: flagValue('--staging'),
1626
+ coreVersion: VERSION,
1627
+ })
1628
+ } catch (error) {
1629
+ console.error(` ${error instanceof Error ? error.message : error}`)
1630
+ process.exit(1)
1631
+ }
1632
+ const { report } = plan
1633
+
1634
+ if (sub === 'report') {
1635
+ if (flags.has('--json')) console.log(importer.reportJson(report).trimEnd())
1636
+ else for (const line of importer.reportSummary(report)) console.log(` ${line}`)
1637
+ if (out) {
1638
+ await mkdir(out, { recursive: true })
1639
+ await writeFile(join(out, 'report.md'), importer.reportMarkdown(report))
1640
+ await writeFile(join(out, 'report.json'), importer.reportJson(report))
1641
+ if (!flags.has('--json')) console.log(`\n wrote ${relative(cwd, join(out, 'report.md'))}`)
1642
+ }
1643
+ if (!report.ready) process.exit(1)
1644
+ return
1645
+ }
1646
+
1647
+ const target = out as string
1648
+ if (!report.ready) {
1649
+ for (const finding of report.findings.filter((f) => f.class === 'blocking'))
1650
+ console.error(
1651
+ ` blocked ${finding.title}${finding.detail ? `\n ${finding.detail}` : ''}`,
1652
+ )
1653
+ console.error('\nNothing was written.')
1654
+ process.exit(1)
1655
+ }
1656
+ if (
1657
+ existsSync(target) &&
1658
+ (await Array.fromAsync(new Bun.Glob('*').scan({ cwd: target, onlyFiles: false, dot: true })))
1659
+ .length > 0 &&
1660
+ !flags.has('--force')
1661
+ ) {
1662
+ console.error(
1663
+ `${target} is not empty. Choose a new directory, or pass --force to write into it.`,
1664
+ )
1665
+ process.exit(1)
1666
+ }
1667
+
1668
+ const files = new Map<string, { text?: string; bytes?: Uint8Array; copyFrom?: string }>()
1669
+ const scaffold = scaffoldFiles({
1670
+ siteName: plan.siteName,
1671
+ postgres: flags.has('--postgres'),
1672
+ bundle: {
1673
+ path: importer.IMPORT_BUNDLE,
1674
+ // A media item whose file was not in the backup is reported, not refused.
1675
+ flags: plan.missingMedia > 0 ? ['--allow-missing-blobs'] : [],
1676
+ },
1677
+ })
1678
+ for (const file of scaffold) files.set(file.path, file)
1679
+ // The importer's files win: the source site's media types replace the defaults.
1680
+ for (const file of plan.files) files.set(file.path, file)
1681
+ if (plan.dictionary.length > 0)
1682
+ files.set(`${importer.IMPORT_DIR}/dictionary.udt`, { text: writeUdtAll(plan.dictionary) })
1683
+ if (plan.domains.length > 0)
1684
+ files.set(`${importer.IMPORT_DIR}/domains.toml`, { text: writeDomainsFile(plan.domains) })
1685
+
1686
+ for (const [path, file] of files) {
1687
+ const destination = join(target, path)
1688
+ await mkdir(join(destination, '..'), { recursive: true })
1689
+ if (file.copyFrom !== undefined) await Bun.write(destination, Bun.file(file.copyFrom))
1690
+ else await Bun.write(destination, file.bytes ?? file.text ?? '')
1691
+ }
1692
+
1693
+ for (const line of importer.reportSummary(report)) console.log(` ${line}`)
1694
+ console.log(`\n wrote ${files.size} files to ${relative(cwd, target) || '.'}`)
1695
+ console.log(` report ${relative(cwd, join(target, importer.IMPORT_DIR, 'report.md'))}`)
1696
+ console.log(`\nNext:\n cd ${relative(cwd, target) || '.'}\n bun install\n bun start`)
1697
+ console.log(
1698
+ `\n\`bun start\` imports ${importer.IMPORT_BUNDLE} on the first boot of an empty database.`,
1699
+ )
1700
+ if (plan.dictionary.length > 0)
1701
+ console.log(`Then: crombolo dictionary import ${importer.IMPORT_DIR}/dictionary.udt`)
1702
+ }
1703
+
1704
+ /**
1705
+ * `crombolo views`: what is on disk, whether it compiles, and a new one.
1706
+ *
1707
+ * A view is loaded when a request renders it, so one that does not compile is a
1708
+ * 500 waiting for a visitor. `components check` is that failure brought forward.
1709
+ */
1710
+ async function components(): Promise<void> {
1711
+ const config = await siteConfig()
1712
+ const sub = positional[0] ?? 'check'
1713
+ if (sub !== 'check' && sub !== 'list' && sub !== 'new') return help()
1714
+
1715
+ const loaded = existsSync(config.schemaDir) ? loadSchemaDirectory(config.schemaDir) : undefined
1716
+ const types = loaded?.set.contentTypes ?? []
1717
+
1718
+ if (sub === 'list') {
1719
+ const found = listComponents(config.componentsDir)
1720
+ if (found.length === 0) console.log(`Nothing in ${relative(cwd, config.componentsDir) || '.'}.`)
1721
+ for (const component of found) {
1722
+ // A component is a template because a content type names it, not
1723
+ // because of where it sits — so the label is read off the schema.
1724
+ const declaredBy = types
1725
+ .filter((type) => type.components.includes(component.alias))
1726
+ .map((type) => type.alias)
1727
+ const kind = declaredBy.length > 0 ? 'template' : 'component'
1728
+ const note = declaredBy.length > 0 ? ` ← ${declaredBy.join(', ')}` : ''
1729
+ console.log(` ${kind.padEnd(9)} ${relative(cwd, component.path)}${note}`)
1730
+ }
1731
+ return
1732
+ }
1733
+
1734
+ if (sub === 'new') {
1735
+ const alias = positional[1]
1736
+ if (!alias) {
1737
+ console.error('components new needs a name: `crombolo components new pages/article`.')
1738
+ process.exit(1)
1739
+ }
1740
+ if (!isSafeAlias(alias)) {
1741
+ console.error(`"${alias}" is not a path inside ${relative(cwd, config.componentsDir)}.`)
1742
+ process.exit(1)
1743
+ }
1744
+ const file = componentFileFor(config.componentsDir, alias)
1745
+ if (existsSync(file)) {
1746
+ console.error(`${relative(cwd, file)} already exists.`)
1747
+ process.exit(1)
1748
+ }
1749
+ // A content type that names this alias gets the page scaffold, which takes
1750
+ // PageProps; anything else gets the plain one. Nothing turns on the folder.
1751
+ const type = types.find((candidate) => candidate.components.includes(alias))
1752
+ if (!type)
1753
+ console.log(
1754
+ ` note no content type declares the template "${alias}" — add it to one's templates, or \`crombolo schema new\``,
1755
+ )
1756
+ await mkdir(join(file, '..'), { recursive: true })
1757
+ await writeFile(file, type ? viewScaffold(type) : componentScaffold(alias))
1758
+ console.log(` created ${relative(cwd, file)}`)
1759
+ return
1760
+ }
1761
+
1762
+ const report = await checkComponents({
1763
+ componentsDir: config.componentsDir,
1764
+ siteDir: config.siteDir,
1765
+ declaredComponents: types.flatMap((type) => type.components),
1766
+ })
1767
+ const templates = report.declared.length
1768
+ console.log(
1769
+ ` checked ${report.components.length} file(s): ${templates} template(s), ` +
1770
+ `${report.components.length - templates} component(s)`,
1771
+ )
1772
+ for (const problem of report.problems)
1773
+ console.error(` [error] ${problem.file}: ${problem.message}`)
1774
+ if (report.types.note) console.log(` types ${report.types.note}`)
1775
+ else {
1776
+ console.log(` types tsc --noEmit over ${relative(cwd, config.siteDir) || '.'}`)
1777
+ for (const problem of report.types.problems) console.error(` [types] ${problem}`)
1778
+ }
1779
+ if (report.problems.length > 0 || report.types.problems.length > 0) process.exit(1)
1780
+ }
1781
+
1782
+ /** `crombolo assets`: the stylesheets and scripts the backoffice also edits. */
1783
+ async function assets(): Promise<void> {
1784
+ const config = await siteConfig()
1785
+ const sub = positional[0] ?? 'list'
1786
+ if (sub !== 'list' && sub !== 'new') return help()
1787
+
1788
+ if (sub === 'list') {
1789
+ const found = listAssets(config)
1790
+ if (found.length === 0) console.log('No stylesheets or scripts here.')
1791
+ for (const asset of found)
1792
+ console.log(` ${asset.kind.padEnd(10)} ${relative(cwd, asset.path)}`)
1793
+ return
1794
+ }
1795
+
1796
+ const kind = positional[1]
1797
+ const name = positional[2]
1798
+ if ((kind !== 'stylesheet' && kind !== 'script') || !name) {
1799
+ console.error('assets new needs a kind and a name: `crombolo assets new stylesheet site.css`.')
1800
+ process.exit(1)
1801
+ }
1802
+ const where = assetDirs(config)[kind]
1803
+ const file = join(where.dir, name.endsWith(where.extension) ? name : `${name}${where.extension}`)
1804
+ if (existsSync(file)) {
1805
+ console.error(`${relative(cwd, file)} already exists.`)
1806
+ process.exit(1)
1807
+ }
1808
+ await mkdir(join(file, '..'), { recursive: true })
1809
+ await writeFile(file, assetScaffold(kind, relative(where.dir, file)))
1810
+ console.log(` created ${relative(cwd, file)}`)
1811
+ }
1812
+
1813
+ function parseSet(): Record<string, unknown> {
1814
+ const out: Record<string, unknown> = {}
1815
+ for (let i = 0; i < rest.length; i++) {
1816
+ if (rest[i] !== '--set') continue
1817
+ const pair = rest[i + 1] ?? ''
1818
+ const eq = pair.indexOf('=')
1819
+ if (eq < 0) continue
1820
+ const raw = pair.slice(eq + 1)
1821
+ let value: unknown = raw
1822
+ try {
1823
+ value = JSON.parse(raw)
1824
+ } catch {}
1825
+ out[pair.slice(0, eq)] = value
1826
+ }
1827
+ return out
1828
+ }
1829
+
1830
+ function printFindings(report: { classification: string; findings: Finding[] }): void {
1831
+ const byKind = { blocking: 0, person: 0, auto: 0 }
1832
+ for (const f of report.findings) byKind[f.kind] += 1
1833
+ console.log(
1834
+ `change: ${report.classification}; findings: ${byKind.blocking} blocking, ${byKind.person} need a person, ${byKind.auto} automatic`,
1835
+ )
1836
+ for (const f of report.findings) {
1837
+ const where = f.link ? ` ${f.link}` : ''
1838
+ console.log(` [${f.kind.padEnd(8)}] ${f.message}${where}`)
1839
+ }
1840
+ }
1841
+
1842
+ async function upgrade(): Promise<void> {
1843
+ const config = await siteConfig()
1844
+ switch (positional[0]) {
1845
+ case 'ledger': {
1846
+ const db = await connect({ file: config.sqliteFile })
1847
+ try {
1848
+ for (const row of await readLedger(db))
1849
+ console.log(
1850
+ ` ${row.appliedAt} ${row.kind.padEnd(8)} ${row.bundle ? `[${row.bundle}] ` : ''}${row.name} ${row.durationMs}ms${row.appliedBy ? ` by ${row.appliedBy}` : ''}${row.note ? ` (${row.note})` : ''}`,
1851
+ )
1852
+ } finally {
1853
+ await db.close()
1854
+ }
1855
+ return
1856
+ }
1857
+ case 'check': {
1858
+ if (!flags.has('--fix')) {
1859
+ const report = await ops.upgradeCheck(config, { set: parseSet() })
1860
+ for (const bundle of report.bundles)
1861
+ if (bundle.pending.length > 0)
1862
+ console.log(
1863
+ ` bundle ${bundle.id}: ${bundle.pending.map((step) => `${step.name} (${step.kind})`).join(', ')}`,
1864
+ )
1865
+ printFindings(report)
1866
+ if (!report.siteChecked)
1867
+ console.log(
1868
+ 'The site schema is checked once the framework migrations have run (`crombolo upgrade`).',
1869
+ )
1870
+ if (report.blocking) process.exit(1)
1871
+ return
1872
+ }
1873
+ const fix = await ops.upgradeFix(config, {
1874
+ set: parseSet(),
1875
+ backupTaken: flags.has('--backup-taken'),
1876
+ })
1877
+ if (fix.backup.path) console.log(` backup ${fix.backup.path}`)
1878
+ console.log(
1879
+ ` sync ${fix.sync.action}${fix.sync.deferred.length > 0 ? ` (deferred to the cut-over: ${fix.sync.deferred.join(', ')})` : ''}`,
1880
+ )
1881
+ for (const name of fix.applied) console.log(` applied ${name}`)
1882
+ if (fix.skipped > 0)
1883
+ console.log(` skipped ${fix.skipped} value(s) a converter refused; see the findings`)
1884
+ printFindings(fix)
1885
+ return
1886
+ }
1887
+ case 'schema': {
1888
+ positional[0] = 'rewrite'
1889
+ return schema()
1890
+ }
1891
+ case undefined: {
1892
+ if (flags.has('--plan')) {
1893
+ const plan = await ops.upgradePlan(config)
1894
+ if (plan.steps.length === 0) console.log('No framework migration is pending.')
1895
+ const printStep = (step: ops.PlannedStepResult, indent = '') => {
1896
+ console.log(
1897
+ `\n${indent}== ${step.name} (${step.kind}${step.release ? `, release ${step.release}` : ''})`,
1898
+ )
1899
+ if (step.unplannable) console.log(`${indent} unplannable: ${step.unplannable}`)
1900
+ for (const sql of step.statements) console.log(`${indent} ${sql};`)
1901
+ }
1902
+ for (const step of plan.steps) printStep(step)
1903
+ // After core's, in the order `bundles` lists them, because that is the order they run.
1904
+ for (const bundle of plan.bundles) {
1905
+ console.log(
1906
+ `\nbundle ${bundle.id} (${bundle.name}): ${bundle.steps.length === 0 ? 'nothing pending' : `${bundle.steps.length} step(s)`}`,
1907
+ )
1908
+ for (const step of bundle.steps) printStep(step, ' ')
1909
+ }
1910
+ console.log(
1911
+ plan.site.checked
1912
+ ? `\nsite schema: ${plan.site.action} (${plan.site.classification})`
1913
+ : '\nsite schema: checked once the framework migrations have run',
1914
+ )
1915
+ return
1916
+ }
1917
+ const forceIndex = rest.indexOf('--force')
1918
+ const result = await ops.upgradeRun(config, {
1919
+ force: forceIndex >= 0 ? rest[forceIndex + 1] : undefined,
1920
+ set: parseSet(),
1921
+ backupTaken: flags.has('--backup-taken'),
1922
+ })
1923
+ if (result.backup.path) console.log(` backup ${result.backup.path}`)
1924
+ if (result.action === 'refused') {
1925
+ console.error(`upgrade refused: ${result.reasons.length} outstanding finding(s)`)
1926
+ for (const f of result.reasons)
1927
+ console.error(` [${f.kind.padEnd(8)}] ${f.message}${f.link ? ` ${f.link}` : ''}`)
1928
+ console.error(
1929
+ 'Run `crombolo upgrade check --fix`, resolve what needs a person, and try again.',
1930
+ )
1931
+ process.exit(1)
1932
+ }
1933
+ if (result.action === 'nothing')
1934
+ return console.log('Nothing to upgrade: the database is at this version.')
1935
+ for (const name of result.frameworkApplied) console.log(` applied ${name}`)
1936
+ for (const bundle of result.bundlesApplied)
1937
+ for (const name of bundle.applied) console.log(` applied [${bundle.id}] ${name}`)
1938
+ console.log(
1939
+ ` schema ${result.schema?.action} ${result.schema?.version ?? ''}+${result.schema?.revision ?? ''}`,
1940
+ )
1941
+ return
1942
+ }
1943
+ default:
1944
+ return help()
1945
+ }
1946
+ }
1947
+
1948
+ /**
1949
+ * `bundle purge <id>`: drops a bundle's tables and forgets its state. Taking a
1950
+ * bundle out of `bundles` leaves them in place, so re-adding it resumes; this is
1951
+ * the deliberate act that does not.
1952
+ */
1953
+ async function bundlePurge(): Promise<void> {
1954
+ const config = await siteConfig()
1955
+ const id = positional[1]
1956
+ if (!id) {
1957
+ console.error('bundle purge needs the bundle id.')
1958
+ process.exit(1)
1959
+ }
1960
+ const plan = await ops.bundlePurgePlan(config, id)
1961
+ if (plan.tables.length === 0) console.log(` The bundle "${id}" has no tables in this database.`)
1962
+ else {
1963
+ console.log(` This drops ${plan.tables.length} table(s), and every row in them:`)
1964
+ for (const table of plan.tables) console.log(` ${table}`)
1965
+ }
1966
+ if (!flags.has('--yes')) {
1967
+ const answer = prompt(` Purge the bundle "${id}"? Type its id to confirm:`)
1968
+ if (answer?.trim() !== id) {
1969
+ console.log(' Nothing was dropped.')
1970
+ process.exit(1)
1971
+ }
1972
+ }
1973
+ const result = await ops.bundlePurge(config, id, { backupTaken: flags.has('--backup-taken') })
1974
+ if (result.backup.path) console.log(` backup ${result.backup.path}`)
1975
+ for (const table of result.dropped) console.log(` dropped ${table}`)
1976
+ console.log(` The bundle "${id}"'s state is cleared; adding it again starts its tables afresh.`)
1977
+ }
1978
+
1979
+ /**
1980
+ * `maintenance`: the cluster-wide pause on editing that a restore or a swap
1981
+ * needs. It is a database flag, so it reaches every node on its next write.
1982
+ */
1983
+ async function maintenance(): Promise<void> {
1984
+ const config = await siteConfig()
1985
+ switch (positional[0]) {
1986
+ case 'pause': {
1987
+ const paused = await ops.pauseEditing(config, { reason: flagValue('--reason') })
1988
+ console.log(`Editing paused${paused.reason ? `: ${paused.reason}` : ''}.`)
1989
+ return
1990
+ }
1991
+ case 'resume':
1992
+ await ops.resumeEditing(config)
1993
+ console.log('Editing resumed.')
1994
+ return
1995
+ case 'status': {
1996
+ const paused = await ops.editingPaused(config)
1997
+ if (flags.has('--json')) {
1998
+ console.log(JSON.stringify({ paused: paused ?? null }, null, 2))
1999
+ return
2000
+ }
2001
+ console.log(
2002
+ paused
2003
+ ? `Editing paused since ${paused.at}${paused.by ? ` by ${paused.by}` : ''}${paused.reason ? `: ${paused.reason}` : ''}.`
2004
+ : 'Editing is not paused.',
2005
+ )
2006
+ return
2007
+ }
2008
+ default:
2009
+ return help()
2010
+ }
2011
+ }
2012
+
2013
+ function help(): void {
2014
+ console.log(`crombolo <command>
2015
+
2016
+ start [--keep-admin] boot the site in the current directory
2017
+ [--bundle <pkg>] apply a bundle's content first, once per bundle, then serve;
2018
+ takes the \`content import\` flags (--publish, --under, …)
2019
+ init [--force] [--name <site name>] [--postgres] [--template <id>]
2020
+ scaffold a site here; --template list prints the
2021
+ starter templates, which bring schema, views and content
2022
+ status [--json] what this environment resolved to, and what is wrong with
2023
+ it; non-zero when something would stop the site working
2024
+ admin reset-password [pw] reset the administrator's password
2025
+ schema check [--static] validate schema/ and report what a sync would do
2026
+ schema sync [--force-retire-types]
2027
+ apply schema/ to the database
2028
+ schema export write the database's definitions as schema/ files
2029
+ schema rewrite rewrite every schema/ file canonically
2030
+ schema new <content-type|media-type|member-type> <alias>
2031
+ write the type file, with keys, and the view it points at
2032
+ [--name <name>] [--description <text>] [--icon <icon>]
2033
+ [--at-root] [--element] [--tab <tab>] [--no-view]
2034
+ schema add-property <type> <alias> --type <data type>
2035
+ append a property to that type and apply it
2036
+ [--name <name>] [--mandatory] [--tab <tab>] [--dry-run]
2037
+ schema purge --older-than N delete properties retired more than N days ago, with their values
2038
+ generate schema/content-types.d.ts from schema/
2039
+ components check compile every component, and report one a type declares with no file
2040
+ components list what is in components/, and which type declares each
2041
+ components new <alias> components/<alias>.tsx; the alias may carry folders
2042
+ assets list the stylesheets and scripts this site has
2043
+ assets new <stylesheet|script> <name>
2044
+ write an empty one in the place the backoffice edits
2045
+ content export --root <path|uuid> --out <dir>
2046
+ write a private bundle package: the subtree, its
2047
+ dependencies and what the destination must already have
2048
+ [--only] [--drafts] [--with-blobs] [--with-blueprints]
2049
+ [--name <npm name>] [--package-version <version>]
2050
+ A bundle is an npm package. <pkg> is its directory, or the name of one this
2051
+ site depends on.
2052
+ content check <pkg> what installing its content here would do, and what it
2053
+ needs from a person first; writes to the Changes dashboard
2054
+ [--under <path|uuid>] [--resolve <key>=take-bundle|keep-local|skip]
2055
+ [--resolve-all <choice>] [--allow-missing-blobs] [--save]
2056
+ content import <pkg> re-check, back up, then apply: documents and elements
2057
+ arrive as drafts, media is live. One transaction, so a
2058
+ failure leaves nothing behind
2059
+ [--publish] [--label <text>] [--backup-taken] + the check flags
2060
+ [--no-schema] [--no-files] decline a section it carries
2061
+ [--replace-files] allow replacing files this site has;
2062
+ refused without it, and the originals are kept for a revert
2063
+ bundle check <pkg> the same as content check
2064
+ bundle install <pkg> the same as content import; a bundle carrying its own
2065
+ schema and views installs into a site that has neither
2066
+ content runs [--limit N] the imports applied here, newest first
2067
+ content publish <path|uuid> take it live; --descendants for the branch below it,
2068
+ --culture <iso> per culture, --at/--until to schedule
2069
+ content unpublish <path|uuid>
2070
+ take it down; the same flags
2071
+ content revert <run-id> put an import back: values and published state restored,
2072
+ nodes it created unpublished and recycled. Itself a run,
2073
+ so it can be reverted in turn
2074
+ [--resolve <key>=discard|skip] [--resolve-all <choice>]
2075
+ [--force] [--backup-taken]
2076
+ dictionary export --out <file.udt> [--key <uuid>]
2077
+ the dictionary as Umbraco's .udt, to seed another environment
2078
+ dictionary import <file.udt>
2079
+ apply one: items upsert by key, and a translation for a
2080
+ language this site has not got is skipped
2081
+ domains the hostnames domains.toml declares and what is bound here
2082
+ domains set <path|uuid|/> --host <host>[=<culture>] [--host ...] [--default-culture <iso>]
2083
+ write domains.toml and apply it; the page's hostnames are
2084
+ replaced, and \${VAR} in a host is read from the environment
2085
+ domains clear <path|uuid|/> unbind that page, in the file and in the database
2086
+ domains apply apply domains.toml here, as a boot does
2087
+ domains undo put back the file the last write replaced, and apply it
2088
+ import umbraco report <backup> [--site <dir>] [--media <dir>] [--out <dir>] [--json]
2089
+ read-only: what importing an Umbraco backup would bring,
2090
+ and what it would not — packages, Razor, custom code.
2091
+ <backup> is a .bacpac or Umbraco's SQLite file; --site is
2092
+ the site's files, for its views, media and plugins.
2093
+ Non-zero when something blocks the import
2094
+ import umbraco apply <backup> --out <dir> [--site <dir>] [--media <dir>]
2095
+ write a crombolo site: schema, view stubs, media and a
2096
+ content bundle that \`bun start\` imports on first boot
2097
+ [--name <site name>] [--drafts] [--postgres] [--force]
2098
+ upgrade check [--set t.p=v] what the deployed schema/ would do to this database's data
2099
+ upgrade check --fix back up; apply the additive part and every conversion early
2100
+ upgrade [--force <reason>] re-check, back up, apply framework steps, cut over, ledger
2101
+ upgrade --plan the DDL pending framework migrations would run
2102
+ upgrade ledger print migration_history
2103
+ bundle purge <id> [--yes] back up, then drop a bundle's tables and clear its state;
2104
+ refused while crombolo.config.ts still wires it
2105
+ maintenance pause [--reason <text>]
2106
+ refuse every editor's save, on every node, until resumed;
2107
+ readers are unaffected and no node drains
2108
+ maintenance resume let editors save again
2109
+ maintenance status [--json] whether editing is paused, by whom and why
2110
+ (Postgres: --backup-taken or CROMBOLO_PG_DUMP before anything that writes)`)
2111
+ }
2112
+
2113
+ try {
2114
+ await dispatch()
2115
+ } catch (error) {
2116
+ if (!(error instanceof ops.CommandError)) throw error
2117
+ for (const problem of error.problems) console.error(` ${problem}`)
2118
+ console.error(error.message)
2119
+ process.exit(1)
2120
+ }
2121
+
2122
+ async function dispatch(): Promise<void> {
2123
+ switch (command) {
2124
+ case 'start':
2125
+ await start()
2126
+ break
2127
+ case 'init':
2128
+ await init()
2129
+ break
2130
+ case 'status':
2131
+ await status()
2132
+ break
2133
+ case 'admin':
2134
+ await admin()
2135
+ break
2136
+ case 'schema':
2137
+ await schema()
2138
+ break
2139
+ case 'generate':
2140
+ await generate()
2141
+ break
2142
+ case 'content':
2143
+ await content()
2144
+ break
2145
+ /**
2146
+ * The artifact's own name. A bundle that carries its own structure is what
2147
+ * the Packages section builds (`docs/bundles.md`), and `install` reads
2148
+ * better than `import` for one — but it is the same operation on the same
2149
+ * artifact, so this is the same code path, not a second one.
2150
+ */
2151
+ case 'bundle':
2152
+ if (positional[0] === 'purge') {
2153
+ await bundlePurge()
2154
+ break
2155
+ }
2156
+ if (positional[0] === 'install') positional[0] = 'import'
2157
+ await content()
2158
+ break
2159
+ case 'dictionary':
2160
+ await dictionary()
2161
+ break
2162
+ case 'domains':
2163
+ await domains()
2164
+ break
2165
+ case 'components':
2166
+ await components()
2167
+ break
2168
+ case 'assets':
2169
+ await assets()
2170
+ break
2171
+ case 'import':
2172
+ await importSite()
2173
+ break
2174
+ case 'upgrade':
2175
+ await upgrade()
2176
+ break
2177
+ case 'maintenance':
2178
+ await maintenance()
2179
+ break
2180
+ default:
2181
+ help()
2182
+ }
2183
+ }