@crombolo/server 0.37.0 → 0.39.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 (80) hide show
  1. package/package.json +15 -14
  2. package/src/access.ts +29 -27
  3. package/src/adapters/audit.ts +1 -1
  4. package/src/adapters/blueprints.ts +22 -13
  5. package/src/adapters/content.ts +1 -1
  6. package/src/adapters/dictionary.ts +1 -1
  7. package/src/adapters/documents.ts +17 -10
  8. package/src/adapters/elements.ts +47 -37
  9. package/src/adapters/file-system.ts +1 -1
  10. package/src/adapters/health.ts +10 -5
  11. package/src/adapters/media.ts +12 -8
  12. package/src/adapters/member-groups.ts +8 -6
  13. package/src/adapters/members.ts +6 -4
  14. package/src/adapters/public-access.ts +7 -5
  15. package/src/adapters/redirects.ts +1 -1
  16. package/src/adapters/references.ts +1 -1
  17. package/src/adapters/relations.ts +1 -1
  18. package/src/adapters/schema-files.ts +33 -1
  19. package/src/adapters/search-index.ts +1 -1
  20. package/src/adapters/template-query.ts +1 -1
  21. package/src/adapters/users.ts +13 -13
  22. package/src/adapters/webhooks.ts +1 -1
  23. package/src/anonymise-rules.ts +83 -0
  24. package/src/approvals-api.ts +1 -1
  25. package/src/approvals.ts +75 -38
  26. package/src/back-office-url.ts +20 -0
  27. package/src/backup.ts +26 -2
  28. package/src/bundle-code.ts +1 -1
  29. package/src/bundle-grants.ts +250 -0
  30. package/src/bundle-install.ts +13 -2
  31. package/src/bundle-media.ts +12 -11
  32. package/src/bundles.ts +131 -43
  33. package/src/component-snippets.ts +1 -1
  34. package/src/components.ts +6 -1
  35. package/src/config.ts +61 -3
  36. package/src/content-notifications.ts +13 -9
  37. package/src/content-operations.ts +23 -65
  38. package/src/content-query.ts +1 -1
  39. package/src/core.ts +675 -0
  40. package/src/cron.ts +139 -0
  41. package/src/custom-tables.ts +274 -0
  42. package/src/database.ts +22 -14
  43. package/src/dictionary-transfer.ts +1 -1
  44. package/src/git-routes.ts +1 -1
  45. package/src/identity-provider-overrides.ts +18 -16
  46. package/src/imaging.ts +65 -15
  47. package/src/index.ts +10 -1
  48. package/src/job-wake.ts +23 -0
  49. package/src/live-reload.ts +195 -0
  50. package/src/log-viewer.ts +6 -1
  51. package/src/marketplace.ts +82 -10
  52. package/src/media-access.ts +12 -9
  53. package/src/member-auth.ts +6 -4
  54. package/src/models-builder.ts +1 -1
  55. package/src/node-operations.ts +122 -0
  56. package/src/owner-jobs.ts +428 -0
  57. package/src/ports.ts +36 -154
  58. package/src/preview-tokens.ts +6 -12
  59. package/src/remote.ts +3 -1
  60. package/src/routes.ts +18 -1
  61. package/src/schema.ts +8 -3
  62. package/src/seed/compile.ts +7 -5
  63. package/src/seed/export.ts +6 -4
  64. package/src/seo.ts +2 -2
  65. package/src/server.ts +328 -452
  66. package/src/settings.ts +18 -2
  67. package/src/site-data.ts +195 -0
  68. package/src/site-file.ts +30 -4
  69. package/src/site-queries.ts +140 -0
  70. package/src/site-replace.ts +25 -19
  71. package/src/site-sections.ts +1 -1
  72. package/src/site-services.ts +23 -6
  73. package/src/status-pages.ts +19 -5
  74. package/src/status.ts +11 -9
  75. package/src/url-settings.ts +1 -2
  76. package/src/webhook-files.ts +1 -1
  77. package/src/webhooks.ts +31 -23
  78. package/src/worker-watch.ts +73 -0
  79. package/src/worker.ts +138 -0
  80. package/src/bundle-tables.ts +0 -161
package/src/server.ts CHANGED
@@ -46,8 +46,7 @@ import {
46
46
  } from '@crombolo/auth'
47
47
  import {
48
48
  collectManifests,
49
- createBackOfficePaths,
50
- createExtensionRegistry,
49
+ type createBackOfficePaths,
51
50
  isSpaRoute,
52
51
  renderBackOfficeShell,
53
52
  renderDeviceShell,
@@ -58,7 +57,6 @@ import {
58
57
  resolveStaticFile,
59
58
  serveStaticFile,
60
59
  } from '@crombolo/backoffice-host'
61
- import type { DocumentOperations, MediaOperations } from '@crombolo/content'
62
60
  import { servedContract } from '@crombolo/contracts'
63
61
  import {
64
62
  CACHE_KEEP_FOR_ALIAS,
@@ -78,11 +76,12 @@ import {
78
76
  } from '@crombolo/core'
79
77
  import {
80
78
  appendCacheInstruction,
81
- createTablesCapability,
82
79
  type Db,
83
80
  ensureKeyValue,
84
81
  FormEntryRepository,
85
82
  FormWorkflowRepository,
83
+ JobRepository,
84
+ type JobState,
86
85
  latestContentVersionId,
87
86
  MediaAccessRepository,
88
87
  MemberRepository,
@@ -93,7 +92,6 @@ import {
93
92
  readUrlOptions,
94
93
  SiteSearch,
95
94
  TransferRunRepository,
96
- UserGroupRepository,
97
95
  type WritesPaused,
98
96
  } from '@crombolo/data'
99
97
  import {
@@ -103,8 +101,6 @@ import {
103
101
  cacheControl,
104
102
  chosenLifetime,
105
103
  contentForNode,
106
- DEFAULT_MEDIA_CACHE_MEGABYTES,
107
- DEVELOPMENT_LIMITS,
108
104
  FORM_SCRIPT,
109
105
  FORM_SCRIPT_PATH,
110
106
  FORM_SUBMIT_PATH,
@@ -112,22 +108,21 @@ import {
112
108
  ISLAND_LOADER_PATH,
113
109
  ISLAND_LOADER_SCRIPT,
114
110
  ISLANDS_PATH,
115
- islandTransform,
111
+ LIVE_EVENTS_PATH,
112
+ LIVE_RELOAD_SCRIPT,
113
+ LIVE_RELOAD_SCRIPT_PATH,
116
114
  type Lifetime,
117
115
  lifetimeFor,
118
- MEMBER_EXTERNAL_SIGN_IN_PATH,
119
- MediaCache,
120
116
  type PageOutcome,
121
117
  PRIVATE_NO_STORE,
122
118
  PublishedCache,
123
119
  type PublishedContent,
124
- Renderer,
120
+ type Renderer,
125
121
  type RequestMember,
126
122
  resolveCacheSettings,
127
123
  type SnapshotStatus,
128
- setFormFieldTypes,
129
- setFormTokenSigner,
130
- ViewSnapshots,
124
+ type ViewSnapshots,
125
+ withLiveReload,
131
126
  } from '@crombolo/render'
132
127
  import type { SyncReport } from '@crombolo/schema'
133
128
  import { choicesFor } from '@crombolo/transfer'
@@ -135,30 +130,15 @@ import type { Server } from 'bun'
135
130
  import { createNodeLookup, loadAccess } from './access.ts'
136
131
  import { createAuditHost, createAuditSink, pluginAuditPlan, recordAudit } from './adapters/audit.ts'
137
132
  import { readCreatedBundlePackage, writeCreatedBundlePackage } from './adapters/bundles.ts'
138
- import {
139
- createMediaSource,
140
- createPublishedContentSource,
141
- loadDraftNode,
142
- } from './adapters/documents.ts'
133
+ import { createPublishedContentSource, loadDraftNode } from './adapters/documents.ts'
143
134
  import type { Approvals } from './approvals.ts'
144
135
  import { handleApprovalsApi } from './approvals-api.ts'
136
+ import type { BundleGrants } from './bundle-grants.ts'
145
137
  import { CommandError, installBundleContent } from './bundle-install.ts'
146
- import {
147
- type BundleMediaFactory,
148
- createBundleMedia,
149
- type ResolvedMediaFolder,
150
- resolveBundleMediaFolders,
151
- } from './bundle-media.ts'
152
138
  import { BUNDLES_CHANGED_EVENT, type BundleReload, createBundleReloader } from './bundle-reload.ts'
153
- import { bundleChains, bundleTablesReport } from './bundle-tables.ts'
154
- import {
155
- bundleRouteGroups,
156
- createBundleRedirects,
157
- createServerBundles,
158
- validateServerBundles,
159
- } from './bundles.ts'
139
+ import { bundleRouteGroups } from './bundles.ts'
160
140
  import { busyResponse } from './busy.ts'
161
- import { listEmailTemplates } from './components.ts'
141
+ import { checkTypes, listEmailTemplates } from './components.ts'
162
142
  import {
163
143
  type CromboloConfig,
164
144
  listeningBodyLimit,
@@ -166,32 +146,26 @@ import {
166
146
  type ServerRole,
167
147
  VERSION,
168
148
  } from './config.ts'
169
- import { createContentDispatcher } from './content-dispatch.ts'
170
- import { createContentEventSink } from './content-events.ts'
171
- import { createContentNotificationRunner, createContentNotifier } from './content-notifications.ts'
172
149
  import { answerContentQuery, contentQueryScope } from './content-query.ts'
173
- import { attachDatabase, bootstrapDatabase } from './database.ts'
150
+ import { createCore } from './core.ts'
151
+ import { closeTables, tablesReport } from './custom-tables.ts'
174
152
  import { createDeliveryMediaPort } from './delivery-media.ts'
175
153
  import { createDeliveryMemberSecurity } from './delivery-members.ts'
176
- import { createDiagnostics } from './diagnostics.ts'
177
154
  import { syncDomainsFile } from './domains.ts'
178
155
  import { editorTypeLibs, siteJsxImportSource } from './editor-types.ts'
179
- import { emailAvailability, resolveEmailPort } from './email.ts'
156
+ import { emailAvailability } from './email.ts'
180
157
  import { noticeAboutEmail } from './email-notice.ts'
181
158
  import { warnAboutAppPlugins } from './extensions-notice.ts'
182
159
  import { coerceForm, deleteForm, saveForm } from './form-files.ts'
183
160
  import {
184
- createFormRegistry,
185
161
  FORM_FLASH_COOKIE,
186
- formSigningSecret,
187
162
  readFlash,
188
163
  signFormToken,
189
164
  submitForm,
190
165
  wantsJson,
191
166
  writeFlash,
192
167
  } from './form-submit.ts'
193
- import { describeFormTypes, formTypesFor, formTypesOf } from './form-types.ts'
194
- import { createWorkflowRunner } from './form-workflows.ts'
168
+ import { describeFormTypes, formTypesFor } from './form-types.ts'
195
169
  import {
196
170
  entriesCsv,
197
171
  formDetail,
@@ -201,46 +175,35 @@ import {
201
175
  redactSensitive,
202
176
  } from './forms.ts'
203
177
  import { HOST_TOKEN_SECONDS, issueHostToken } from './host-token.ts'
204
- import { ImageProcessor, parseImagingQuery } from './imaging.ts'
205
- import { type BackgroundJobs, createBackgroundJobs } from './jobs.ts'
178
+ import { canEncodeAvif, ImageProcessor, parseImagingQuery } from './imaging.ts'
179
+ import type { BackgroundJobs } from './jobs.ts'
180
+ import { createLiveReload, createTypeWatch, watchDirectory } from './live-reload.ts'
206
181
  import { configureLogging, logger } from './logging.ts'
207
182
  import { createMarketplace } from './marketplace.ts'
208
183
  import { createMediaAccess } from './media-access.ts'
209
- import { MediaFileStore } from './media-files.ts'
210
- import { mediaStoreFromEnvironment } from './media-store.ts'
211
184
  import { createMemberAuth, MEMBER_ROUTE_PREFIX } from './member-auth.ts'
212
185
  import { noNodesPage } from './no-nodes.ts'
213
186
  import { NotImplementedLog } from './not-implemented.ts'
214
- import { createDeps, documentEditUrl, PREVIEW_COOKIE, resolveUserLinkSender } from './ports.ts'
187
+ import { createDeps, PREVIEW_COOKIE, resolveUserLinkSender } from './ports.ts'
215
188
  import {
216
189
  previewSigningSecret,
217
190
  previewUser,
218
191
  readPreviewToken,
219
192
  signPreviewToken,
220
193
  } from './preview-tokens.ts'
221
- import { createRedirectTracker } from './redirects.ts'
222
194
  import { createRemote } from './remote.ts'
223
- import { withRemoteMedia } from './remote-media.ts'
224
195
  import { unknownHostProvided } from './site-file.ts'
225
196
  import { handleTransferAction, pendingTransfers } from './transfer-dashboard.ts'
226
- import {
227
- changeUrlOptions,
228
- redirectAfterUrlChange,
229
- type UrlChangeContext,
230
- urlSettingEditable,
231
- } from './url-settings.ts'
197
+ import { changeUrlOptions, urlSettingEditable } from './url-settings.ts'
198
+ import type { JobsStatus } from './worker-watch.ts'
232
199
 
233
200
  export { PREVIEW_COOKIE }
234
201
 
235
202
  import type { SiteRoute } from '@crombolo/common'
236
- import { BACKOFFICE_EXTERNAL_PATH, backofficeAudience } from './backoffice-external.ts'
203
+ import { backofficeAudience } from './backoffice-external.ts'
237
204
  import { createExternalSignIn } from './external-sign-in.ts'
205
+ import { IdentityProviderOverrides } from './identity-provider-overrides.ts'
238
206
  import {
239
- createBundleIdentityProviders,
240
- IdentityProviderOverrides,
241
- } from './identity-provider-overrides.ts'
242
- import {
243
- buildIslands,
244
207
  builtIslandFile,
245
208
  devServerIslandManifest,
246
209
  viteIslandManifest,
@@ -254,18 +217,12 @@ import {
254
217
  requestCookies,
255
218
  runStage,
256
219
  } from './middleware.ts'
220
+ import type { JobRunner } from './owner-jobs.ts'
257
221
  import { callerAddress } from './rate-limit.ts'
258
222
  import { syncConfiguredRedirects } from './redirects.ts'
259
223
  import { createRoutes, type DeclaredRoute, siteRouteProblems } from './routes.ts'
260
- import {
261
- bootSchema,
262
- CacheInstructionPoller,
263
- componentAliasesIn,
264
- importSchema,
265
- type SchemaBoot,
266
- watchSchema,
267
- } from './schema.ts'
268
- import { publishSchema, type SchemaStore, useSchemaStore } from './schema-store.ts'
224
+ import { componentAliasesIn, importSchema, type SchemaBoot, watchSchema } from './schema.ts'
225
+ import { publishSchema, type SchemaStore } from './schema-store.ts'
269
226
  import { createSeoHost, originOf, publicOrigin } from './seo.ts'
270
227
  import {
271
228
  combineHubs,
@@ -275,7 +232,6 @@ import {
275
232
  } from './server-events.ts'
276
233
  import { AttemptLimiter, createSetupRoutes } from './setup.ts'
277
234
  import { siteSearchFor } from './site-search.ts'
278
- import { createSiteServices } from './site-services.ts'
279
235
  import {
280
236
  genericStatusPage,
281
237
  previewRedirectNotice,
@@ -285,8 +241,7 @@ import {
285
241
  } from './status-pages.ts'
286
242
  import { TwoFactorService, USER_TWO_FACTOR_PROVIDER } from './two-factor.ts'
287
243
  import { summariseUpgrades } from './upgrade-summary.ts'
288
- import { assertViewRuntime } from './view-runtime.ts'
289
- import { bundleEventProblems, createWebhookService, webhookStoreView } from './webhooks.ts'
244
+ import { webhookStoreView } from './webhooks.ts'
290
245
 
291
246
  export interface ServerHandle {
292
247
  config: CromboloConfig
@@ -308,6 +263,12 @@ export interface ServerHandle {
308
263
  /** The views generations this node has taken; `status()` is what /health reports. */
309
264
  snapshots: ViewSnapshots
310
265
  seededAdminPassword: string | undefined
266
+ /** What each bundle may do, and whether it is on (story 222). */
267
+ bundleGrants: BundleGrants
268
+ /** The site's and bundles' background jobs (story 187); started on a node that owns writes. */
269
+ backgroundJobs: JobRunner
270
+ /** The wired bundles an administrator has disabled, and who did. */
271
+ disabledBundles(): { id: string; by: string | null }[]
311
272
  schema: SchemaBoot
312
273
  /** Applies cache instructions other nodes appended; the interval calls this too. */
313
274
  poll(): Promise<number>
@@ -329,6 +290,8 @@ export interface ServerHandle {
329
290
  role: ServerRole
330
291
  /** The views generation in use, and whether newer ones are being refused. */
331
292
  components: SnapshotStatus
293
+ /** Where jobs run, and whether a worker is running them; not on a `web` node. */
294
+ jobs?: JobsStatus
332
295
  }
333
296
  /** Scheduled publishing and version cleanup; each run can be called directly. */
334
297
  jobs: BackgroundJobs
@@ -343,32 +306,82 @@ export interface ServerHandle {
343
306
  }
344
307
 
345
308
  export async function createServer(config: CromboloConfig = loadConfig()): Promise<ServerHandle> {
309
+ if (config.role === 'worker')
310
+ throw new Error('A worker serves no site: start it with createWorker (story 223).')
346
311
  configureLogging({
347
312
  logsDir: config.logsDir,
348
313
  level: config.logLevel,
349
314
  console: config.logToConsole,
350
315
  })
351
- const diagnostics = createDiagnostics(config.diagnostics)
352
316
  const log = logger('server')
353
317
  const schemaLog = logger('schema')
354
318
  const renderLog = logger('render')
355
319
  const redirectLog = logger('redirects')
356
- const bundleLog = (id: string) => {
357
- const named = logger('bundle', id)
358
- return {
359
- info: (message: string, properties?: Record<string, unknown>) =>
360
- named.info(message, properties),
361
- warn: (message: string, properties?: Record<string, unknown>) =>
362
- named.warn(message, properties),
363
- error: (message: string, properties?: Record<string, unknown>) =>
364
- named.error(message, properties),
365
- }
366
- }
367
320
  const domainLog = logger('domains')
368
321
  const apiLog = logger('management-api')
369
- // Extensions are the site's own npm dependencies (`docs/bundles.md`).
370
- // Uncached in development so an author editing one sees a reload pick it up.
371
- const extensions = createExtensionRegistry(config.siteDir, { cache: !config.development })
322
+ // Story 214: in development, open pages reload when what they show changes,
323
+ // and a template error says which components were rendering.
324
+ const live = config.liveReload ? createLiveReload() : undefined
325
+ let drafts: { cache: PublishedCache; version: number } | undefined
326
+ const core = await createCore(config, {
327
+ onCacheInvalidate: () => {
328
+ drafts = undefined
329
+ live?.changed('content')
330
+ },
331
+ onViewsSwap: () => {
332
+ live?.changed('views')
333
+ void typeWatch
334
+ ?.schedule()
335
+ .catch((error: unknown) =>
336
+ renderLog.error('The type check failed to run: {error}', { error: String(error) }),
337
+ )
338
+ },
339
+ buildIslands: true,
340
+ announce: (event) => announce(event),
341
+ onDocumentChanged: (key) =>
342
+ events.broadcast('notify', [
343
+ { eventSource: 'Umbraco:CMS:Document', eventType: 'Updated', key },
344
+ ]),
345
+ streamMemberFile: (src, search) => streamMemberFile(src, search),
346
+ siteName: async () => (await seo.siteDefaults()).siteName,
347
+ })
348
+ const {
349
+ diagnostics,
350
+ extensions,
351
+ paths,
352
+ owns,
353
+ bundlePackages,
354
+ formTypes,
355
+ chains,
356
+ db,
357
+ seededAdminPassword,
358
+ bundleGrants,
359
+ jobRunner,
360
+ schema,
361
+ forms,
362
+ formSecret,
363
+ cacheOptions,
364
+ mediaCache,
365
+ cache,
366
+ afterSync,
367
+ snapshots,
368
+ renderer,
369
+ mediaStore,
370
+ email,
371
+ notifier,
372
+ mediaFiles,
373
+ webhooks,
374
+ dispatcher,
375
+ contentEvents,
376
+ bundles,
377
+ poller,
378
+ siteServicesFor,
379
+ jobs,
380
+ wake,
381
+ urlChange,
382
+ } = core
383
+ // What this process answers: only `web` serves no back office.
384
+ const servesBackOffice = config.role !== 'web'
372
385
  // A host that installs packages itself calls `reloadBundles()` (story 181); the
373
386
  // Marketplace's own install goes through it too, so either way open back
374
387
  // offices hear about it. `events` is created further down, before any reload.
@@ -384,6 +397,10 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
384
397
  extensions: { ...extensions, invalidate: () => void bundleReloader.reload() },
385
398
  siteDir: config.siteDir,
386
399
  wired: () => bundles?.mounted.map((bundle) => bundle.id) ?? [],
400
+ grants: {
401
+ state: (pkg) => bundleGrants.state(pkg),
402
+ grant: (pkg, by) => bundleGrants.grant(pkg, by),
403
+ },
387
404
  contentApplied: async (packageName) =>
388
405
  (await new TransferRunRepository(db).appliedForPackage(packageName))?.packageVersion ?? null,
389
406
  applyContentOnInstall: config.applyBundleContentOnInstall,
@@ -416,46 +433,6 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
416
433
  return { applied: true, runId: result.runId, message: 'Its content was applied.' }
417
434
  },
418
435
  })
419
- const paths = createBackOfficePaths({ backOfficePath: config.backOfficePath })
420
- // Two questions, not one: what this process answers, and what it is
421
- // responsible for converging at boot. `all` and `api` are both owners; only
422
- // `all` and `web` serve the public site.
423
- const servesBackOffice = config.role !== 'web'
424
- const owns = config.role !== 'web'
425
- // Bundles are checked before the database is touched, because a bundle that
426
- // owns tables is migrated at boot, and a bad declaration must not get that far.
427
- // On every role: a bundle's form types are needed wherever forms render and
428
- // submit, and its member and public routes wherever the site is served. Its
429
- // tables are migrated only by the nodes that own the database.
430
- const bundlePackages = extensions.bundles().bundles
431
- const formTypes = formTypesOf(config)
432
- {
433
- const problems = [
434
- ...validateServerBundles(config.bundles, bundlePackages, VERSION),
435
- ...formTypes.problems,
436
- ...bundleEventProblems(config.bundles),
437
- ]
438
- if (problems.length > 0)
439
- throw new Error(`The configured bundles cannot be mounted:\n- ${problems.join('\n- ')}`)
440
- }
441
- setFormFieldTypes(formTypes.types, formTypes.renderers)
442
- const chains = bundleChains(config.bundles, bundlePackages)
443
- const { db, seededAdminPassword } = owns
444
- ? await bootstrapDatabase(config, chains)
445
- : await attachDatabase(config)
446
- // A configured schema store is copied down before anything reads `schema/`, and
447
- // becomes the schema directory for this boot. Everything after here — loading,
448
- // validation, hashing, sync, the writer — works on files exactly as it always has.
449
- const copied = await useSchemaStore(config)
450
- if (config.schemaStore)
451
- schemaLog.info('Schema read from {store}: {count} files in {dir}', {
452
- store: config.schemaStore.description,
453
- count: copied,
454
- dir: config.schemaCacheDir,
455
- })
456
- // A node that does not own the schema still loads it — the renderer needs the
457
- // property definitions — but writes none of it.
458
- const schema = await bootSchema(db, owns ? config : { ...config, syncSchemaAtBoot: false })
459
436
 
460
437
  const auth = new AuthService(new AuthStore(db))
461
438
  const cookies = { siteName: config.siteName, securePrefix: config.secureCookies }
@@ -607,24 +584,6 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
607
584
  }
608
585
  }
609
586
 
610
- // Form definitions are files, so they are re-read rather than cached with the
611
- // content: nothing about a publish tells this node that a form changed.
612
- const forms = createFormRegistry(config.schemaDir, { formTypes: formTypes.types })
613
- // Every form this node renders carries a token signed with the site's key, so
614
- // the timing guard cannot be bypassed by posting a made-up render time.
615
- const formSecret = await formSigningSecret(db)
616
- setFormTokenSigner((formKey, renderedAt) => signFormToken(formSecret, formKey, renderedAt))
617
- const publishedSource = createPublishedContentSource(db, {
618
- nodeState: schema.nodeState,
619
- nodeId: schema.nodeId,
620
- })
621
- // Media is cached apart from the pages (story 197), item by item within a
622
- // budget, and shared by the published and draft caches: media has no drafts.
623
- const mediaCache = new MediaCache(
624
- createMediaSource(db, { nodeState: schema.nodeState, nodeId: schema.nodeId }),
625
- { budgetBytes: (config.mediaCacheMegabytes ?? DEFAULT_MEDIA_CACHE_MEGABYTES) * 1024 * 1024 },
626
- )
627
- const cacheOptions = { form: (key: string) => forms.byKey(key), media: mediaCache }
628
587
  // Every page as last saved, for previewing in an app (story 053). Built on the
629
588
  // first preview after a change and dropped with the published cache, so a site
630
589
  // nobody previews never holds it. A save on another node announces nothing,
@@ -634,99 +593,40 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
634
593
  nodeId: schema.nodeId,
635
594
  drafts: true,
636
595
  })
637
- let drafts: { cache: PublishedCache; version: number } | undefined
638
596
  const draftCache = async (): Promise<PublishedCache> => {
639
597
  const version = await latestContentVersionId(db)
640
598
  if (drafts?.version !== version)
641
599
  drafts = { cache: new PublishedCache(draftSource, cacheOptions), version }
642
600
  return drafts.cache
643
601
  }
644
- const cache = new PublishedCache(publishedSource, {
645
- ...cacheOptions,
646
- onInvalidate: () => {
647
- drafts = undefined
648
- },
649
- })
650
- // A sync or a Settings change that alters how URLs are built moves every URL:
651
- // the old ones redirect, as a rename's do.
652
- const urlChange: UrlChangeContext = {
653
- db,
654
- config,
655
- source: publishedSource,
656
- cacheOptions,
657
- cache,
658
- tracker: createRedirectTracker({
659
- cache,
660
- redirects: new RedirectRepository(db),
661
- enabled: config.trackRedirects,
662
- instruct: () =>
663
- appendCacheInstruction(db, {
664
- kind: 'content',
665
- payload: { redirects: true },
666
- by: schema.nodeId,
667
- }),
668
- }),
669
- }
670
- const afterSync = async (report: SyncReport | undefined) => {
671
- if (!report?.urls) return
672
- await redirectAfterUrlChange(urlChange, report.urls.before)
673
- log.info('Page addresses now {mode} the top-level page; old addresses redirect', {
674
- mode: report.urls.after.hideTopLevel ? 'leave out' : 'include',
675
- })
676
- }
677
- await afterSync(schema.report)
678
- // A snapshot of the views, so a template edited anywhere — the backoffice, a
679
- // deploy, a bucket synced underneath — is picked up without restarting this
680
- // node. `assertViewRuntime` first, because a cache directory the JSX runtime
681
- // cannot be resolved from fails every render rather than the boot.
682
- assertViewRuntime(config.componentsCacheDir)
683
- const snapshots = new ViewSnapshots({
684
- sourceDir: config.componentsDir,
685
- cacheDir: config.componentsCacheDir,
686
- limits: { ...(config.development ? DEVELOPMENT_LIMITS : {}), ...config.componentsSnapshot },
687
- onProblem: (message) => renderLog.error('{message}', { message }),
688
- // Only a change: every boot takes a generation, and saying so each time is
689
- // noise. The start banner names the one a node came up on.
690
- onSwap: (hash, previous) => {
691
- if (previous)
692
- renderLog.info('Views changed: generation {previous} to {hash}', {
693
- previous: previous.slice(0, 8),
694
- hash: hash.slice(0, 8),
602
+ // Story 214: a save under components/ swaps the views now rather than at the
603
+ // next render, and each swap checks the types again in the background.
604
+ const viewWatcher =
605
+ live && existsSync(config.componentsDir)
606
+ ? watchDirectory(config.componentsDir, () => {
607
+ void snapshots
608
+ .refresh()
609
+ .catch((error: unknown) =>
610
+ renderLog.error('Could not refresh the views: {error}', { error: String(error) }),
611
+ )
695
612
  })
696
- },
697
- // Story 209: a `'use client'` view is a stub on the server, and its browser
698
- // code is built with the generation, unless a site's Vite build supplies it.
699
- transform: islandTransform,
700
- beforeSwap: async (generation) => {
701
- if (config.islands?.manifest || (config.development && config.islands?.devServer)) return
702
- try {
703
- await buildIslands({ ...generation, development: config.development })
704
- } catch (error) {
705
- renderLog.error(
706
- "The views' islands did not build; their pages show each island's fallback: {problems}",
707
- {
708
- problems: error instanceof Error ? error.message : String(error),
709
- },
710
- )
711
- }
712
- },
713
- })
714
- await snapshots.prepare()
715
- // Before the poller, which tells it to look again on a `views` instruction
716
- // from another node: a closure over a `const` declared later would be a
717
- // temporal dead zone waiting for the first instruction to land.
718
- const renderer = new Renderer({
719
- cache,
720
- componentsDir: config.componentsDir,
721
- snapshots,
722
- renderTimeoutMs: config.renderTimeoutMs,
723
- islandsManifest: (generation) =>
724
- config.development && config.islands?.devServer
725
- ? `${ISLANDS_PATH}/dev/manifest.json`
726
- : config.islands?.manifest
727
- ? `${ISLANDS_PATH}/vite/manifest.json`
728
- : generation && `${ISLANDS_PATH}/${generation}/manifest.json`,
729
- })
613
+ : undefined
614
+ const typesLog = logger('types')
615
+ const typeWatch = live
616
+ ? createTypeWatch({
617
+ check: (signal) => checkTypes(config.siteDir, { signal }),
618
+ onFindings: ({ problems, types }) => {
619
+ if (types.count === 0) typesLog.info('The components type-check cleanly')
620
+ else for (const problem of problems) typesLog.warning('{problem}', { problem })
621
+ live?.types(types)
622
+ },
623
+ })
624
+ : undefined
625
+ void typeWatch
626
+ ?.schedule()
627
+ .catch((error: unknown) =>
628
+ typesLog.error('The type check failed to run: {error}', { error: String(error) }),
629
+ )
730
630
  // The site's own redirects are code, so the database follows the file: rules it
731
631
  // no longer declares are removed, which is what makes deleting one from config
732
632
  // actually take effect.
@@ -757,91 +657,6 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
757
657
  }
758
658
  const deliverySettings = resolveDeliveryApiSettings(config.deliveryApi)
759
659
  const formCors = corsPolicy(deliverySettings)
760
- /**
761
- * The server halves of the site's bundles. Back-office routes answer only
762
- * where the backoffice is; site routes (story 211) wherever the site is
763
- * served, through the site's route table.
764
- *
765
- * Capabilities are built here, from what this node already holds, so a bundle
766
- * is handed a narrow interface rather than the database. A bad bundle fails the
767
- * boot — see `createServerBundles`.
768
- */
769
- // Story 198: media as the member, built at the first request, when the media
770
- // operations and the store it writes through exist.
771
- let bundleMedia: BundleMediaFactory | undefined
772
- let bundleMediaFolders = new Map<string, ResolvedMediaFolder[]>()
773
- const bundles =
774
- config.bundles.length > 0
775
- ? createServerBundles({
776
- bundles: config.bundles,
777
- packages: bundlePackages,
778
- coreVersion: VERSION,
779
- tables: (bundle) => {
780
- const chain = chains.find((candidate) => candidate.id === bundle.id)
781
- return chain ? createTablesCapability(db, chain.compiled.schema) : undefined
782
- },
783
- pluginApiPath: `${paths.pluginPath}/api`,
784
- host: {
785
- redirects: createBundleRedirects({ db, cache }),
786
- documents: {
787
- url: async (key, culture) => {
788
- const content = await cache.byKey(key, culture ?? null)
789
- return content && content.url !== '#' ? content.url : undefined
790
- },
791
- },
792
- log: bundleLog('bundle'),
793
- identityProviders: createBundleIdentityProviders({
794
- overrides: new IdentityProviderOverrides(db, config.secretKey),
795
- members: config.memberIdentityProviders,
796
- backoffice: config.backofficeIdentityProviders,
797
- memberCallbackPath: MEMBER_EXTERNAL_SIGN_IN_PATH,
798
- backofficeCallbackPath: BACKOFFICE_EXTERNAL_PATH,
799
- groups: async (audience) =>
800
- audience === 'user'
801
- ? (await new UserGroupRepository(db).all()).map((g) => ({
802
- value: g.alias,
803
- name: g.name,
804
- }))
805
- : (
806
- await db.query<{ text: string }>(
807
- 'SELECT text FROM node WHERE node_object_type = ? ORDER BY text',
808
- [ObjectTypes.MemberGroup],
809
- )
810
- ).map((g) => ({ value: String(g.text), name: String(g.text) })),
811
- }),
812
- },
813
- log: (id) => bundleLog(id),
814
- callerHost: {
815
- media: (caller, bundle) => {
816
- bundleMedia ??= createBundleMedia({
817
- db,
818
- operations: managementDeps.mediaOperations as MediaOperations,
819
- files: mediaFiles,
820
- cache: mediaCache,
821
- folders: (id) => bundleMediaFolders.get(id) ?? [],
822
- bundleName: (id) => bundles?.mounted.find((b) => b.id === id)?.name ?? id,
823
- stream: (src, search) => streamMemberFile(src, search),
824
- })
825
- return bundleMedia(caller, bundle)
826
- },
827
- },
828
- })
829
- : undefined
830
- if (bundles) {
831
- // A declared folder that is not there would fail on the first upload; the
832
- // boot says so instead, naming the bundle and the path.
833
- const names = new Map(bundles.mounted.map((bundle) => [bundle.id, bundle.name]))
834
- const resolved = await resolveBundleMediaFolders(
835
- db,
836
- config.bundles,
837
- (id) => names.get(id) ?? id,
838
- )
839
- if (resolved.problems.length > 0)
840
- throw new Error(
841
- `The configured bundles cannot be mounted:\n- ${resolved.problems.join('\n- ')}`,
842
- )
843
- bundleMediaFolders = resolved.folders
844
- }
845
660
  for (const bundle of bundles?.mounted ?? []) {
846
661
  if (servesBackOffice)
847
662
  log.info('Bundle {name} answering below {prefix} for the {section} section', {
@@ -868,9 +683,11 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
868
683
  if (named.length > 0) {
869
684
  const existing = new Set(
870
685
  (
871
- await db.query<{ text: string }>('SELECT text FROM node WHERE node_object_type = ?', [
872
- ObjectTypes.MemberGroup,
873
- ])
686
+ await db.q
687
+ .selectFrom('node')
688
+ .select('text')
689
+ .where('node_object_type', '=', ObjectTypes.MemberGroup)
690
+ .execute()
874
691
  ).map((row) => String(row.text).toLowerCase()),
875
692
  )
876
693
  for (const group of named.filter((name) => !existing.has(name.toLowerCase())))
@@ -886,40 +703,6 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
886
703
  { name },
887
704
  )
888
705
 
889
- const poller = new CacheInstructionPoller({
890
- db,
891
- nodeId: schema.nodeId,
892
- nodeState: schema.nodeState,
893
- role: config.role,
894
- // `schema` and `content` change what renders: schema alters property
895
- // definitions. `views` changes the code that renders it, which is a new
896
- // snapshot rather than anything in the published cache.
897
- onInstruction: (kind, payload) => {
898
- if (kind !== 'components') return cache.invalidate()
899
- // The hash only says when to stop looking eagerly; the snapshot is always
900
- // of the bytes this node reads, so a superseded one is harmless.
901
- snapshots.announce(typeof payload.hash === 'string' ? payload.hash : undefined)
902
- },
903
- // Behind the latest committed checkpoint: rebuilt now rather than on the next
904
- // read, so an idle node catches up and says so (story 174).
905
- content: {
906
- served: () => cache.served(),
907
- covered: (checkpoint) => cache.covered(checkpoint),
908
- behind: () => {
909
- cache.invalidate()
910
- void cache
911
- .snapshot()
912
- .catch((error: unknown) =>
913
- renderLog.error('Could not rebuild the published cache: {error}', { error }),
914
- )
915
- },
916
- },
917
- media: {
918
- apply: (change) => mediaCache.apply(change),
919
- clear: () => mediaCache.clear(),
920
- },
921
- })
922
- await poller.start(config.development ? 2_000 : 5_000)
923
706
  for (const { kind, path } of await unresolvedStatusPages(cache, config.pages).catch(() => []))
924
707
  renderLog.warning(
925
708
  "pages.{kind} is '{path}', which no published page answers; that status shows a plain page until one does.",
@@ -955,6 +738,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
955
738
  // the path it owns.
956
739
  if (report.state?.version) schema.nodeState.version = report.state.version
957
740
  schemaLog.info('Schema {version} applied', { version: report.state?.version ?? '' })
741
+ live?.changed('schema')
958
742
  }
959
743
  },
960
744
  )
@@ -1000,7 +784,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1000
784
  onChange: (key) => mediaCache.drop([key]),
1001
785
  nodeId: schema.nodeId,
1002
786
  bundleFolders: () =>
1003
- [...bundleMediaFolders].flatMap(([id, folders]) =>
787
+ [...core.bundleMediaFolders()].flatMap(([id, folders]) =>
1004
788
  folders.map((folder) => ({
1005
789
  bundle: bundles?.mounted.find((b) => b.id === id)?.name ?? id,
1006
790
  nodePath: folder.nodePath,
@@ -1147,7 +931,6 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1147
931
  draft: draftModel,
1148
932
  })
1149
933
  const seoPath = `${paths.pluginPath}/api/seo`
1150
- const siteServicesFor = createSiteServices({ db, cache })
1151
934
 
1152
935
  // Story 211: the site's routes and its bundles' site routes, at their own
1153
936
  // paths, ahead of content finding; one pipeline answers bundles' back-office
@@ -1195,44 +978,20 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1195
978
  ...entry,
1196
979
  })
1197
980
  })
1198
- // The site's config may name a store; without one the environment decides,
1199
- // and that falls back to the media directory on this disk.
1200
- // A site pulled with `--lazy-media` reads files through from its remote (story 108).
1201
- const mediaStore = withRemoteMedia(
1202
- config.mediaStore ?? (await mediaStoreFromEnvironment(config.mediaDir)),
1203
- config.siteDir,
1204
- )
1205
- // Resolved once: constructing it twice would warn twice about a provider that
1206
- // is half-configured, and the adapters are cheap but not free of side effects.
1207
- const email = resolveEmailPort(config)
1208
981
  const emailStatus = emailAvailability(email)
1209
982
  // Whether an invitation or a reset link can reach anyone at all, which is what
1210
983
  // gates the options rather than `emailStatus.available`: development delivers
1211
984
  // to the console, and that is a working flow for the person using it.
1212
985
  const canSendUserLinks = Boolean(resolveUserLinkSender(config, email))
1213
- // Story 045: a change queues the e-mails its subscribers asked for. Nothing is
1214
- // queued on a site that cannot send; development sends to the console.
1215
- const notifier = createContentNotifier(db, { canSend: Boolean(email) })
1216
- const mediaFiles = new MediaFileStore(mediaStore)
1217
986
  const images = new ImageProcessor(mediaStore)
987
+ // Asked at boot, so the first AVIF request does not wait on it.
988
+ void canEncodeAvif()
1218
989
  const publicMedia = mediaStore.publicUrl?.('media/file')
1219
990
  if (publicMedia)
1220
991
  log.warning(
1221
992
  'Media files are also served from {where}. Protected files are always sent by this site and never from there, but anyone with a file’s address there can open it: keep protected files in a store nothing public serves.',
1222
993
  { where: publicMedia.replace(/media\/file$/, '') },
1223
994
  )
1224
- const webhooks = createWebhookService({
1225
- db,
1226
- schemaDir: config.schemaDir,
1227
- filesWritable: config.schemaWritable,
1228
- secretKey: config.secretKey,
1229
- bundles: config.bundles,
1230
- onFilesChanged: config.schemaStore
1231
- ? async () => {
1232
- await publishSchema(config.schemaStore as SchemaStore, config.schemaDir)
1233
- }
1234
- : undefined,
1235
- })
1236
995
  /**
1237
996
  * What an open backoffice hears of a change: the event hub drops its cached
1238
997
  * copy, whatever was queued gets indexed now, and an open preview reloads.
@@ -1240,19 +999,9 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1240
999
  */
1241
1000
  function announce(event: ServerEvent): void {
1242
1001
  events.broadcast('notify', [event])
1243
- jobs.kickSearchIndexing()
1244
1002
  if (event.eventSource === 'Umbraco:CMS:Document' && event.eventType !== 'Deleted')
1245
1003
  previewHub.broadcast('refreshed', [event.key])
1246
1004
  }
1247
- // Recorded content events become deliveries and notifications here (story 171).
1248
- const dispatcher = createContentDispatcher({ db, webhooks, notifier })
1249
- // Document writes record and announce themselves through this, from every entry point.
1250
- const contentEvents = createContentEventSink({
1251
- webhooks,
1252
- notifier,
1253
- live: announce,
1254
- nudge: () => dispatcher.nudge(),
1255
- })
1256
1005
 
1257
1006
  const managementDeps = createDeps({
1258
1007
  config,
@@ -1272,18 +1021,29 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1272
1021
  }
1273
1022
  return hidden
1274
1023
  },
1275
- extensions,
1024
+ // A server bundle's screens show only while it is on (story 222).
1025
+ extensions: {
1026
+ ...extensions,
1027
+ list: () =>
1028
+ extensions
1029
+ .list()
1030
+ .filter(
1031
+ (extension) =>
1032
+ !extension.bundle.carries.server || bundleGrants.isOn(extension.bundle.id),
1033
+ ),
1034
+ },
1276
1035
  db,
1277
1036
  webhooks,
1278
1037
  contentEvents,
1279
- nudgeEvents: () => dispatcher.nudge(),
1038
+ nudgeEvents: () => wake('events'),
1039
+ operations: core.operations,
1280
1040
  cache,
1281
1041
  previewInApp: appPreview,
1282
1042
  schema,
1283
1043
  mediaFiles,
1284
1044
  email,
1285
1045
  notifier,
1286
- onSearchQueued: () => jobs.kickSearchIndexing(),
1046
+ onSearchQueued: () => wake('search'),
1287
1047
  // This node looks again at once; the others are told to. The write has
1288
1048
  // already landed wherever `componentsDir` points, so there is nothing to
1289
1049
  // distribute — only the fact that it happened.
@@ -1368,59 +1128,17 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1368
1128
  role: config.role,
1369
1129
  content: contentFreshness(),
1370
1130
  components: snapshots.status(),
1131
+ // Where jobs run, and on a node that leaves them to a worker whether one
1132
+ // is running them; reported, never drained on (story 223).
1133
+ ...(config.role === 'web' ? {} : { jobs: core.workerWatch.status() }),
1371
1134
  }
1372
1135
  }
1373
1136
 
1374
1137
  const events = createServerEventHub()
1375
1138
  const previewHub = createServerEventHub({ name: 'PreviewHub' })
1376
- const jobs = createBackgroundJobs({
1377
- db,
1378
- cache,
1379
- approvals: managementDeps.approvals as Approvals | undefined,
1380
- operations: managementDeps.documentOperations as DocumentOperations,
1381
- dispatcher,
1382
- eventRetentionDays: config.eventRetentionDays,
1383
- nodeState: schema.nodeState,
1384
- nodeId: schema.nodeId,
1385
- versionCleanup: config.versionCleanup,
1386
- auditRetentionDays: config.auditRetentionDays,
1387
- mediaFiles,
1388
- // The workflow queue drains here rather than in the request: a submission is
1389
- // stored first, and an e-mail that cannot be sent yet must not cost it.
1390
- webhooks,
1391
- formWorkflows: createWorkflowRunner({
1392
- db,
1393
- forms,
1394
- email,
1395
- mediaFiles,
1396
- nodeState: schema.nodeState,
1397
- nodeId: schema.nodeId,
1398
- onContentChanged: () => cache.invalidate(),
1399
- operations: managementDeps.documentOperations,
1400
- bundleWorkflows: formTypes.workflows,
1401
- renderEmail: (alias, props) => renderer.renderEmail(alias, props),
1402
- site: async () => ({
1403
- name: (await seo.siteDefaults()).siteName || config.siteName,
1404
- url: config.applicationUrl,
1405
- }),
1406
- }),
1407
- contentNotifications: email
1408
- ? createContentNotificationRunner({
1409
- db,
1410
- email,
1411
- siteName: config.siteName,
1412
- editUrl: (key) => documentEditUrl(config, key),
1413
- })
1414
- : undefined,
1415
- onDocumentChanged: (key) =>
1416
- events.broadcast('notify', [
1417
- { eventSource: 'Umbraco:CMS:Document', eventType: 'Updated', key },
1418
- ]),
1419
- })
1420
- // Scheduled publishing and version cleanup are writes on a timer. Running them
1421
- // on every node would have two processes publishing the same document in the
1422
- // same second, so only an owner starts them.
1423
- if (owns) jobs.start()
1139
+ // Jobs are writes on a timer, claimed so each runs once, and started where
1140
+ // this node runs them: an owner unless told to leave them to a worker.
1141
+ await core.startJobs()
1424
1142
  log.info('Crombolo {version} started on node {nodeId} as {role}', {
1425
1143
  version: VERSION,
1426
1144
  nodeId: schema.nodeId,
@@ -1439,10 +1157,13 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1439
1157
  // Imported only when configured: an unconfigured site has no git route and no
1440
1158
  // credentials anywhere near it.
1441
1159
  const auditPath = `${paths.pluginPath}/api/audit`
1160
+ const jobsPath = `${paths.pluginPath}/api/jobs`
1442
1161
  const hostTokenPath = `${paths.pluginPath}/api/host-token`
1443
1162
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1444
1163
  const bundleInstallPaths = new Set(
1445
- ['install', 'uninstall'].map((action) => `${paths.pluginPath}/api/bundles/${action}`),
1164
+ ['install', 'uninstall', 'disable', 'enable'].map(
1165
+ (action) => `${paths.pluginPath}/api/bundles/${action}`,
1166
+ ),
1446
1167
  )
1447
1168
  /** Per node: ten a minute for each person, three hundred in all. */
1448
1169
  const hostTokens = new AttemptLimiter({ max: 10, maxAll: 300, windowMs: 60_000 })
@@ -1472,6 +1193,15 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1472
1193
  * address it is answered with points back at the new paths.
1473
1194
  */
1474
1195
  async function fetch(request: Request): Promise<Response> {
1196
+ const response = await answer(request)
1197
+ // Readers are answered from the previous cache while it rebuilds (story
1198
+ // 175), so a change is in it before the request that made it is answered.
1199
+ if (request.method !== 'GET' && request.method !== 'HEAD' && cache.stale)
1200
+ await cache.fresh().catch(() => {})
1201
+ return response
1202
+ }
1203
+
1204
+ async function answer(request: Request): Promise<Response> {
1475
1205
  const url = new URL(request.url)
1476
1206
  const contract = contractPathFor(paths.backOfficePath, url.pathname)
1477
1207
  if (!contract) return route(request)
@@ -1568,7 +1298,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1568
1298
  : new Response('Method Not Allowed', { status: 405, headers: { allow: 'POST' } })
1569
1299
  }
1570
1300
 
1571
- // A bundle's member and public routes (story 186), wherever the site is served.
1301
+ // The script that calls the site's routes as a member, wherever the site is served.
1572
1302
  if (config.role !== 'api') {
1573
1303
  if (pathname === BUNDLE_SCRIPT_PATH)
1574
1304
  return new Response(BUNDLE_SCRIPT, {
@@ -1584,9 +1314,33 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1584
1314
  return pathname === '/sitemap.xml' ? seo.sitemap(request, url.host) : seo.robots(request)
1585
1315
 
1586
1316
  if (pathname.startsWith('/media/')) return serveMedia(request, pathname, url.searchParams)
1317
+ if (live && config.role !== 'api') {
1318
+ if (pathname === LIVE_EVENTS_PATH) return live.stream(request)
1319
+ if (pathname === LIVE_RELOAD_SCRIPT_PATH)
1320
+ return new Response(LIVE_RELOAD_SCRIPT, {
1321
+ headers: {
1322
+ 'content-type': 'text/javascript; charset=utf-8',
1323
+ 'cache-control': 'no-cache',
1324
+ },
1325
+ })
1326
+ return withLiveReloadScript(await siteRequest(request, url))
1327
+ }
1587
1328
  return siteRequest(request, url)
1588
1329
  }
1589
1330
 
1331
+ /** A site page in development, carrying the live-reload script (story 214). */
1332
+ async function withLiveReloadScript(response: Response): Promise<Response> {
1333
+ if (!response.body || !response.headers.get('content-type')?.startsWith('text/html'))
1334
+ return response
1335
+ const headers = new Headers(response.headers)
1336
+ headers.delete('content-length')
1337
+ return new Response(withLiveReload(await response.text()), {
1338
+ status: response.status,
1339
+ statusText: response.statusText,
1340
+ headers,
1341
+ })
1342
+ }
1343
+
1590
1344
  /** What a chain is carrying through one request (story 210). */
1591
1345
  interface ChainRun {
1592
1346
  original: URL
@@ -1758,7 +1512,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1758
1512
  // A content query is a POST that reads.
1759
1513
  if (pathname === contentQueryPath) return
1760
1514
  // Installs and removals write their own entry, with the package (story 194).
1761
- if (bundleInstallPaths.has(pathname)) return
1515
+ if (bundleInstallPaths.has(pathname) || pathname.startsWith(`${jobsPath}/`)) return
1762
1516
  const principal = await authenticate(request)
1763
1517
  if (!principal) return
1764
1518
  const plan = pluginAuditPlan(request.method, pathname.slice(prefix.length))
@@ -1973,15 +1727,21 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1973
1727
  version?: unknown
1974
1728
  applyContent?: unknown
1975
1729
  acceptServerCode?: unknown
1730
+ grant?: unknown
1976
1731
  }
1977
1732
  const name = typeof body.name === 'string' ? body.name : ''
1978
1733
  const version = typeof body.version === 'string' ? body.version : undefined
1979
1734
  const acceptServerCode = body.acceptServerCode === true
1735
+ const grant = Array.isArray(body.grant)
1736
+ ? body.grant.filter((p): p is string => typeof p === 'string')
1737
+ : []
1980
1738
  const outcome =
1981
1739
  action === 'install'
1982
1740
  ? await marketplace.install(name, version, {
1983
1741
  applyContent: body.applyContent !== false,
1984
1742
  acceptServerCode,
1743
+ grant,
1744
+ by: principal.email,
1985
1745
  })
1986
1746
  : await marketplace.uninstall(name)
1987
1747
  log.info('{user} {action} the package {name}: {outcome}', {
@@ -1998,7 +1758,10 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1998
1758
  action: action === 'install' ? 'Install' : 'Uninstall',
1999
1759
  entityType: 'Bundle',
2000
1760
  entityName: outcome.dependency ? `${name}@${outcome.dependency.version}` : name,
2001
- detail: action === 'install' && acceptServerCode ? 'accepted server code' : null,
1761
+ detail:
1762
+ action === 'install' && acceptServerCode
1763
+ ? `accepted server code; granted ${grant.length > 0 ? grant.join(', ') : 'nothing'}`
1764
+ : null,
2002
1765
  source: 'request',
2003
1766
  userKey: principal.id,
2004
1767
  userName: principal.name,
@@ -2007,6 +1770,42 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2007
1770
  return Response.json(outcome, { status: outcome.ok ? 200 : 400 })
2008
1771
  }
2009
1772
 
1773
+ // Story 225: a bundle wired in the config is approved by it; an
1774
+ // administrator can disable one, and enable it again.
1775
+ if ((action === 'disable' || action === 'enable') && request.method === 'POST') {
1776
+ const body = (await request.json().catch(() => ({}))) as { id?: unknown }
1777
+ const id = typeof body.id === 'string' ? body.id : ''
1778
+ const pkg = extensions.bundles().bundles.find((candidate) => candidate.id === id)
1779
+ if (!pkg?.carries.server)
1780
+ return Response.json(
1781
+ { ok: false, message: `No installed bundle with a server half is called "${id}".` },
1782
+ { status: 404 },
1783
+ )
1784
+ const state =
1785
+ action === 'disable'
1786
+ ? await bundleGrants.disable(pkg, principal.email)
1787
+ : await bundleGrants.enable(pkg)
1788
+ await recordAudit(db, {
1789
+ category: 'system',
1790
+ action: action === 'disable' ? 'Disable' : 'Enable',
1791
+ entityType: 'Bundle',
1792
+ entityName: `${pkg.packageName}@${pkg.version}`,
1793
+ detail: action === 'disable' ? 'disabled; it is off' : 'enabled; it runs again',
1794
+ source: 'request',
1795
+ userKey: principal.id,
1796
+ userName: principal.name,
1797
+ ...clientAddress(request),
1798
+ })
1799
+ return Response.json({
1800
+ ok: true,
1801
+ on: state.on,
1802
+ message:
1803
+ action === 'disable'
1804
+ ? `${pkg.name} is turned off until it is enabled again.`
1805
+ : `${pkg.name} is turned on.`,
1806
+ })
1807
+ }
1808
+
2010
1809
  return new Response('Not Found', { status: 404 })
2011
1810
  }
2012
1811
 
@@ -2350,6 +2149,69 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2350
2149
  if (response) return response
2351
2150
  }
2352
2151
 
2152
+ // Non-contract, Settings: every owner's background jobs, and retrying a
2153
+ // failed one by hand (story 187).
2154
+ if (pathname === jobsPath || pathname.startsWith(`${jobsPath}/`)) {
2155
+ const principal = await authenticate(request)
2156
+ if (!principal) return new Response('Unauthorized', { status: 401 })
2157
+ if (!hasSection(principal, 'settings')) return new Response('Forbidden', { status: 403 })
2158
+ const queue = new JobRepository(db)
2159
+ if (pathname === jobsPath && request.method === 'GET') {
2160
+ const url = new URL(request.url)
2161
+ const state = url.searchParams.get('state')
2162
+ const listed = await queue.list({
2163
+ owner: url.searchParams.get('owner') || undefined,
2164
+ state: ['queued', 'running', 'succeeded', 'failed'].includes(state ?? '')
2165
+ ? (state as JobState)
2166
+ : undefined,
2167
+ skip: Math.max(0, Number(url.searchParams.get('skip')) || 0),
2168
+ take: Math.min(200, Math.max(1, Number(url.searchParams.get('take')) || 50)),
2169
+ })
2170
+ return Response.json({
2171
+ total: listed.total,
2172
+ // Set while this node leaves its jobs to a worker and none is running.
2173
+ waitingSince: core.workerWatch.status().waitingSince,
2174
+ items: listed.items.map((job) => ({
2175
+ id: job.id,
2176
+ owner: job.owner,
2177
+ name: job.name,
2178
+ state: job.state,
2179
+ attempts: job.attempts,
2180
+ maxAttempts: job.maxAttempts,
2181
+ nextAttemptAt: job.nextAttemptAt.toISOString(),
2182
+ progress: job.progress,
2183
+ error: job.lastError,
2184
+ queuedBy: job.queuedBy,
2185
+ createdAt: job.createdAt.toISOString(),
2186
+ finishedAt: job.finishedAt?.toISOString() ?? null,
2187
+ })),
2188
+ })
2189
+ }
2190
+ const retry = /^\/([0-9a-f-]{36})\/retry$/i.exec(pathname.slice(jobsPath.length))
2191
+ if (retry && request.method === 'POST') {
2192
+ const id = retry[1] as string
2193
+ const job = await queue.get(id)
2194
+ if (!job || !(await queue.retry(id)))
2195
+ return Response.json(
2196
+ { ok: false, message: 'Only a job that has failed can be run again.' },
2197
+ { status: 409 },
2198
+ )
2199
+ await recordAudit(db, {
2200
+ category: 'system',
2201
+ action: 'Retry',
2202
+ entityType: 'Job',
2203
+ entityName: `${job.owner}/${job.name}`,
2204
+ detail: job.lastError ? `after: ${job.lastError.slice(0, 200)}` : null,
2205
+ source: 'request',
2206
+ userKey: principal.id,
2207
+ userName: principal.name,
2208
+ ...clientAddress(request),
2209
+ })
2210
+ return Response.json({ ok: true, message: `${job.name} is queued to run again.` })
2211
+ }
2212
+ return new Response('Not Found', { status: 404 })
2213
+ }
2214
+
2353
2215
  // Non-contract, Settings: how page addresses are built (story 110).
2354
2216
  // Non-contract: finding pages by their facts (story 183), as the signed-in user.
2355
2217
  if (pathname === contentQueryPath) {
@@ -2472,7 +2334,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2472
2334
  }
2473
2335
  // A bundle's tables are part of what an upgrade changes, so the dashboard
2474
2336
  // that shows an upgrade's findings shows their steps too.
2475
- const bundles = await bundleTablesReport(db, chains)
2337
+ const bundles = await tablesReport(db, chains)
2476
2338
  const upgrades = summariseUpgrades(await readLedger(db), VERSION)
2477
2339
  // The answers a finding can be given, offered only to those who may import.
2478
2340
  const mayImport = hasSection(principal, 'packages')
@@ -3305,6 +3167,14 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
3305
3167
  renderer,
3306
3168
  snapshots,
3307
3169
  seededAdminPassword,
3170
+ bundleGrants,
3171
+ backgroundJobs: jobRunner,
3172
+ disabledBundles: () =>
3173
+ config.bundles.flatMap((bundle) => {
3174
+ const pkg = bundlePackages.find((candidate) => candidate.id === bundle.id)
3175
+ if (!pkg || bundleGrants.isOn(bundle.id)) return []
3176
+ return [{ id: bundle.id, by: bundleGrants.state(pkg).disabledBy }]
3177
+ }),
3308
3178
  schema,
3309
3179
  poll: () => poller.poll(),
3310
3180
  notImplemented,
@@ -3335,6 +3205,8 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
3335
3205
  if (!request.headers.has('content-length') && request.headers.has('transfer-encoding'))
3336
3206
  return new Response('Length Required', { status: 411 })
3337
3207
  }
3208
+ // An open event stream outlives Bun's idle timeout.
3209
+ if (live && pathname === LIVE_EVENTS_PATH) bunServer.timeout(request, 0)
3338
3210
  const hubAt = contractPathFor(paths.backOfficePath, pathname) ?? pathname
3339
3211
  if (hubAt === hubPath || hubAt === previewHubPath) {
3340
3212
  const principal = await authenticate(request)
@@ -3347,15 +3219,19 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
3347
3219
  },
3348
3220
  async close() {
3349
3221
  diagnostics.stop()
3350
- // A run already going finishes first: closing the database under a job
3351
- // left its locks behind for whatever used the database next.
3352
- await jobs.stop()
3222
+ // A run already going finishes first, or goes back in the queue: closing
3223
+ // the database under a job left its locks behind for whatever used it next.
3224
+ await core.stopJobs()
3353
3225
  // A dispatch a commit started finishes before the connection goes.
3354
3226
  await dispatcher.settled().catch(() => {})
3355
3227
  events.stop()
3356
3228
  previewHub.stop()
3357
3229
  watcher?.close()
3230
+ viewWatcher?.close()
3231
+ typeWatch?.stop()
3232
+ live?.close()
3358
3233
  poller.stop()
3234
+ await closeTables(chains)
3359
3235
  await db.close()
3360
3236
  },
3361
3237
  }