@crombolo/server 0.24.1 → 0.26.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.
package/src/schema.ts CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  type Finding,
20
20
  Locks,
21
21
  latestCacheInstructionId,
22
+ latestCheckpoint,
22
23
  latestLedgerId,
23
24
  type NodeSchemaState,
24
25
  readWritesPaused,
@@ -247,14 +248,27 @@ export interface CachePollerOptions {
247
248
  role?: string
248
249
  /** Called for instructions other nodes appended. */
249
250
  onInstruction(kind: CacheInstructionKind, payload: Record<string, unknown>): void
251
+ /**
252
+ * The published cache's freshness (story 174). With it, content and schema
253
+ * instructions only wake the poll: the node compares the latest committed
254
+ * checkpoint with the one it serves, and is told it is behind. Being ordered
255
+ * by commit, the checkpoint cannot skip a change that committed late.
256
+ */
257
+ content?: {
258
+ served(): { checkpoint: number | undefined; builtAt: Date } | undefined
259
+ behind(latest: number): void
260
+ }
250
261
  }
251
262
 
263
+ /** A rebuild asked for and not yet served is asked for again after this long. */
264
+ const REASK_AFTER_MS = 30_000
265
+
252
266
  /**
253
267
  * Polls `cache_instruction` from where this node came in; own instructions are
254
268
  * skipped. Where the database can notify, a write wakes it at once and the
255
269
  * timer is only the fallback.
256
270
  */
257
- /** How far behind its cursor the poller looks for a row that committed late. */
271
+ /** How far behind its cursor the poller looks for a views instruction that committed late. */
258
272
  const CURSOR_WINDOW = 100
259
273
 
260
274
  export class CacheInstructionPoller {
@@ -272,6 +286,14 @@ export class CacheInstructionPoller {
272
286
  #bootLedgerId = 0
273
287
  #readsUnsafe = false
274
288
  #paused: WritesPaused | undefined
289
+ /** The checkpoint this node last asked its cache to catch up to, and when. */
290
+ #asked: { checkpoint: number; at: number } | undefined
291
+ #latest: number | undefined
292
+
293
+ /** The latest committed content checkpoint, as of the last poll. */
294
+ get latestCheckpoint(): number | undefined {
295
+ return this.#latest
296
+ }
275
297
 
276
298
  /** True once an upgrade has moved the database past this node: reads only. */
277
299
  get behind(): boolean {
@@ -349,15 +371,22 @@ export class CacheInstructionPoller {
349
371
  this.#seen.add(instruction.id)
350
372
  this.#cursor = Math.max(this.#cursor, instruction.id)
351
373
  if (instruction.createdBy === nodeId) continue
352
- onInstruction(instruction.kind, instruction.payload)
353
374
  applied += 1
375
+ // The checkpoint below decides; an instruction about content only woke us.
376
+ if (this.#options.content && instruction.checkpoint !== null) continue
377
+ onInstruction(instruction.kind, instruction.payload)
354
378
  }
355
379
  for (const id of this.#seen) if (id <= this.#cursor - CURSOR_WINDOW) this.#seen.delete(id)
380
+ const served = await this.#catchUp()
356
381
  await touchServer(db, {
357
382
  nodeId,
358
383
  ...nodeState,
359
384
  role: this.#options.role,
360
385
  cromboloVersion: VERSION,
386
+ served:
387
+ served?.checkpoint === undefined
388
+ ? undefined
389
+ : { checkpoint: served.checkpoint, at: served.builtAt },
361
390
  })
362
391
  const current = await currentSchemaState(db)
363
392
  const behind = compareStates(nodeState, current) < 0
@@ -371,6 +400,27 @@ export class CacheInstructionPoller {
371
400
  return applied
372
401
  }
373
402
 
403
+ /**
404
+ * Tells the cache it is behind when the latest committed checkpoint is past
405
+ * the one it serves. A cache that has not been built yet is left to build on
406
+ * its first read. A request not served within a while is made again, so a
407
+ * failed rebuild is retried.
408
+ */
409
+ async #catchUp() {
410
+ const content = this.#options.content
411
+ if (!content) return undefined
412
+ const latest = await latestCheckpoint(this.#options.db)
413
+ this.#latest = latest
414
+ const served = content.served()
415
+ if (served?.checkpoint === undefined || served.checkpoint >= latest) return served
416
+ const asked = this.#asked
417
+ if (!asked || asked.checkpoint < latest || Date.now() - asked.at > REASK_AFTER_MS) {
418
+ this.#asked = { checkpoint: latest, at: Date.now() }
419
+ content.behind(latest)
420
+ }
421
+ return served
422
+ }
423
+
374
424
  stop(): void {
375
425
  if (this.#timer) clearInterval(this.#timer)
376
426
  this.#timer = undefined
@@ -398,7 +448,7 @@ export interface SchemaImportResult {
398
448
  * by the backoffice arrives here and is imported the same way, through one path.
399
449
  *
400
450
  * Deliberately never automatic. It runs when someone asks, or when an operation
401
- * needs it — committing an assistant changeset, publishing type changes — because
451
+ * needs it — publishing type changes, say — because
402
452
  * importing a half-finished schema underneath an editor mid-save is worse than
403
453
  * importing a minute later.
404
454
  *
package/src/server.ts CHANGED
@@ -62,12 +62,14 @@ import { servedContract } from '@crombolo/contracts'
62
62
  import {
63
63
  CHOICE_SOURCE_KINDS,
64
64
  type ChoiceSourceKind,
65
+ contractPathFor,
65
66
  DEFAULT_UPLOAD_SETTINGS,
66
67
  DELIVERY_API_PREFIX,
67
68
  FormPermissions,
68
69
  hasAccessToSensitiveData,
69
70
  localReturnUrl,
70
71
  MANAGEMENT_API_PREFIX,
72
+ managementApiPrefix,
71
73
  ObjectTypes,
72
74
  PREVIEW_HUB_PATH,
73
75
  SERVER_EVENT_HUB_PATH,
@@ -117,7 +119,6 @@ import { createNodeLookup, loadAccess } from './access.ts'
117
119
  import { createAuditHost, createAuditSink, pluginAuditPlan, recordAudit } from './adapters/audit.ts'
118
120
  import { readCreatedBundlePackage, writeCreatedBundlePackage } from './adapters/bundles.ts'
119
121
  import { createPublishedContentSource, loadDraftNode } from './adapters/documents.ts'
120
- import { createSchemaProposals } from './adapters/schema-proposals.ts'
121
122
  import type { Approvals } from './approvals.ts'
122
123
  import { handleApprovalsApi } from './approvals-api.ts'
123
124
  import { CommandError, installBundleContent } from './bundle-install.ts'
@@ -164,6 +165,7 @@ import {
164
165
  parseEntryState,
165
166
  redactSensitive,
166
167
  } from './forms.ts'
168
+ import { HOST_TOKEN_SECONDS, issueHostToken } from './host-token.ts'
167
169
  import { ImageProcessor, parseImagingQuery } from './imaging.ts'
168
170
  import { type BackgroundJobs, createBackgroundJobs } from './jobs.ts'
169
171
  import { configureLogging, logger } from './logging.ts'
@@ -183,6 +185,7 @@ import {
183
185
  import { createRedirectTracker } from './redirects.ts'
184
186
  import { createRemote } from './remote.ts'
185
187
  import { withRemoteMedia } from './remote-media.ts'
188
+ import { unknownHostProvided } from './site-file.ts'
186
189
  import { handleTransferAction, pendingTransfers } from './transfer-dashboard.ts'
187
190
  import {
188
191
  changeUrlOptions,
@@ -216,7 +219,7 @@ import {
216
219
  type HubSocketData,
217
220
  type ServerEventHub,
218
221
  } from './server-events.ts'
219
- import { createSetupRoutes } from './setup.ts'
222
+ import { AttemptLimiter, createSetupRoutes } from './setup.ts'
220
223
  import { siteSearchFor } from './site-search.ts'
221
224
  import { TwoFactorService, USER_TWO_FACTOR_PROVIDER } from './two-factor.ts'
222
225
  import { summariseUpgrades } from './upgrade-summary.ts'
@@ -379,7 +382,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
379
382
  const cookies = { siteName: config.siteName, securePrefix: config.secureCookies }
380
383
  const names = cookieNames(cookies)
381
384
  // The socket's peer for each request in flight, which only `Bun.serve` knows;
382
- // a request that came some other way (a test, the assistant) has none.
385
+ // a request that came some other way (a test) has none.
383
386
  const peers = new WeakMap<Request, string>()
384
387
  const clientAddress = (request: Request): ClientAddress => ({
385
388
  ipAddress: peers.get(request) ?? null,
@@ -571,6 +574,12 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
571
574
  cache,
572
575
  redirects: new RedirectRepository(db),
573
576
  enabled: config.trackRedirects,
577
+ instruct: () =>
578
+ appendCacheInstruction(db, {
579
+ kind: 'content',
580
+ payload: { redirects: true },
581
+ by: schema.nodeId,
582
+ }),
574
583
  }),
575
584
  }
576
585
  const afterSync = async (report: SyncReport | undefined) => {
@@ -695,6 +704,11 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
695
704
  prefix: bundle.prefix,
696
705
  section: bundle.section,
697
706
  })
707
+ for (const name of unknownHostProvided(config))
708
+ log.warning(
709
+ '{name} is listed as host-provided but is not installed here; exports leave it out regardless',
710
+ { name },
711
+ )
698
712
 
699
713
  const poller = new CacheInstructionPoller({
700
714
  db,
@@ -710,6 +724,19 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
710
724
  // of the bytes this node reads, so a superseded one is harmless.
711
725
  snapshots.announce(typeof payload.hash === 'string' ? payload.hash : undefined)
712
726
  },
727
+ // Behind the latest committed checkpoint: rebuilt now rather than on the next
728
+ // read, so an idle node catches up and says so (story 174).
729
+ content: {
730
+ served: () => cache.served(),
731
+ behind: () => {
732
+ cache.invalidate()
733
+ void cache
734
+ .snapshot()
735
+ .catch((error: unknown) =>
736
+ renderLog.error('Could not rebuild the published cache: {error}', { error }),
737
+ )
738
+ },
739
+ },
713
740
  })
714
741
  await poller.start(config.development ? 2_000 : 5_000)
715
742
  const watcher =
@@ -1014,6 +1041,23 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1014
1041
  // Fixed by the contract and the client's SDK, wherever the editor is mounted.
1015
1042
  const apiPrefix = MANAGEMENT_API_PREFIX
1016
1043
 
1044
+ /**
1045
+ * Which committed changes this node's published cache holds (story 174):
1046
+ * numbers and times only. `latest` is as of the last poll; `behind` is null
1047
+ * until both are known.
1048
+ */
1049
+ const contentFreshness = () => {
1050
+ const served = cache.served()
1051
+ const latest = poller.latestCheckpoint
1052
+ const checkpoint = served?.checkpoint
1053
+ return {
1054
+ checkpoint: checkpoint ?? null,
1055
+ latest: latest ?? null,
1056
+ behind: checkpoint === undefined || latest === undefined ? null : checkpoint < latest,
1057
+ builtAt: served?.builtAt.toISOString() ?? null,
1058
+ }
1059
+ }
1060
+
1017
1061
  const health = () => {
1018
1062
  const paused = poller.paused
1019
1063
  const readOnly = schema.compatibilityMode || poller.behind || paused !== undefined
@@ -1037,6 +1081,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1037
1081
  revision: schema.nodeState.revision,
1038
1082
  nodeId: schema.nodeId,
1039
1083
  role: config.role,
1084
+ content: contentFreshness(),
1040
1085
  components: snapshots.status(),
1041
1086
  }
1042
1087
  }
@@ -1106,48 +1151,12 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1106
1151
  const hubPath = SERVER_EVENT_HUB_PATH
1107
1152
  const previewHubPath = PREVIEW_HUB_PATH
1108
1153
 
1109
- // Imported only when the feature is configured, so an unconfigured site never
1110
- // loads the assistant, its provider or its tool definitions.
1111
- const assistantPath = `${paths.pluginPath}/api/assistant`
1112
- const assistant =
1113
- config.assistant && servesBackOffice
1114
- ? await import('./assistant.ts').then((module) =>
1115
- module.createAssistantHost({
1116
- config: config.assistant as NonNullable<typeof config.assistant>,
1117
- db,
1118
- schema: createSchemaProposals({ db, config, boot: schema, afterSync }),
1119
- siteName: config.siteName,
1120
- version: VERSION,
1121
- dispatch: (inner) => api.dispatch(inner),
1122
- }),
1123
- )
1124
- : undefined
1125
- if (assistant) {
1126
- log.info('Assistant enabled with {provider}{mcp}', {
1127
- provider: config.assistant?.provider.name,
1128
- mcp: config.assistant?.mcp === true ? ', MCP endpoint served' : '',
1129
- })
1130
- // Checked once at boot so an expired SSO session is reported here rather than
1131
- // as a failed message later. Never awaited into the boot path: the assistant
1132
- // is optional and the site must come up either way.
1133
- void assistant.status(true).then((status) => {
1134
- if (status.ok) {
1135
- log.info('Assistant credentials resolved: {detail}{expires}', {
1136
- detail: status.detail,
1137
- expires: status.expires ? `, expiring ${status.expires}` : '',
1138
- })
1139
- } else {
1140
- log.warning('Assistant cannot reach its model: {detail} {remedy}', {
1141
- detail: status.detail,
1142
- remedy: status.remedy ?? '',
1143
- })
1144
- }
1145
- })
1146
- }
1147
-
1148
- // Imported only when configured, like the assistant: an unconfigured site has no
1149
- // git route and no credentials anywhere near it.
1154
+ // Imported only when configured: an unconfigured site has no git route and no
1155
+ // credentials anywhere near it.
1150
1156
  const auditPath = `${paths.pluginPath}/api/audit`
1157
+ const hostTokenPath = `${paths.pluginPath}/api/host-token`
1158
+ /** Per node: ten a minute for each person, three hundred in all. */
1159
+ const hostTokens = new AttemptLimiter({ max: 10, maxAll: 300, windowMs: 60_000 })
1151
1160
  const auditHost = createAuditHost(db, config.auditRetentionDays)
1152
1161
 
1153
1162
  const gitPath = `${paths.pluginPath}/api/git`
@@ -1168,7 +1177,37 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1168
1177
  })
1169
1178
  }
1170
1179
 
1180
+ /**
1181
+ * Answers on the back office's API paths as on Umbraco's (`contractPathFor`):
1182
+ * a request on the new paths is routed as the contract names it, and an
1183
+ * address it is answered with points back at the new paths.
1184
+ */
1171
1185
  async function fetch(request: Request): Promise<Response> {
1186
+ const url = new URL(request.url)
1187
+ const contract = contractPathFor(paths.backOfficePath, url.pathname)
1188
+ if (!contract) return route(request)
1189
+ url.pathname = contract
1190
+ const moved = new Request(url, request)
1191
+ const peer = peers.get(request)
1192
+ if (peer) peers.set(moved, peer)
1193
+ const response = await route(moved)
1194
+ const location = response.headers.get('location')
1195
+ if (location?.includes(MANAGEMENT_API_PREFIX)) {
1196
+ const headers = new Headers(response.headers)
1197
+ headers.set(
1198
+ 'location',
1199
+ location.replace(MANAGEMENT_API_PREFIX, managementApiPrefix(paths.backOfficePath)),
1200
+ )
1201
+ return new Response(response.body, {
1202
+ status: response.status,
1203
+ statusText: response.statusText,
1204
+ headers,
1205
+ })
1206
+ }
1207
+ return response
1208
+ }
1209
+
1210
+ async function route(request: Request): Promise<Response> {
1172
1211
  const url = new URL(request.url)
1173
1212
  const { pathname } = url
1174
1213
 
@@ -1241,13 +1280,14 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1241
1280
 
1242
1281
  /**
1243
1282
  * The audit entry for a successful write to one of Crombolo's own endpoints,
1244
- * which the contract router does not see. The assistant's are left out: what it
1245
- * changes goes through the router, and is recorded there. docs/audit-log.md.
1283
+ * which the contract router does not see. docs/audit-log.md.
1246
1284
  */
1247
1285
  async function auditPluginWrite(request: Request, pathname: string): Promise<void> {
1248
1286
  const prefix = `${paths.pluginPath}/api/`
1249
1287
  if (request.method === 'GET' || request.method === 'HEAD') return
1250
- if (!pathname.startsWith(prefix) || pathname.startsWith(`${assistantPath}/`)) return
1288
+ if (!pathname.startsWith(prefix)) return
1289
+ // A host token changes nothing here: each one is a log line, not an entry.
1290
+ if (pathname === hostTokenPath) return
1251
1291
  const principal = await authenticate(request)
1252
1292
  if (!principal) return
1253
1293
  const plan = pluginAuditPlan(request.method, pathname.slice(prefix.length))
@@ -1281,20 +1321,6 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1281
1321
  )
1282
1322
  return new Response(null, { status: 303, headers: { location: setup.path } })
1283
1323
 
1284
- // Non-contract, signed-in: the assistant's chat, review and MCP endpoints.
1285
- // Absent configuration there is no `assistant`, so these paths 404 like any
1286
- // other unknown route.
1287
- if (assistant && pathname.startsWith(`${assistantPath}/`)) {
1288
- const principal = await authenticate(request)
1289
- if (!principal) return new Response('Unauthorized', { status: 401 })
1290
- const response = await assistant.handle(
1291
- request,
1292
- pathname.slice(assistantPath.length),
1293
- principal,
1294
- )
1295
- if (response) return response
1296
- }
1297
-
1298
1324
  // Non-contract, Settings: what the repository has against what this site has.
1299
1325
  // Settings and not merely signed in, because the diff is the schema's full
1300
1326
  // text and a commit pushes it under this site's credentials — the same
@@ -1322,8 +1348,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1322
1348
  const principal = await authenticate(request)
1323
1349
  if (!principal) return new Response('Unauthorized', { status: 401 })
1324
1350
  // Settings: this applies type changes to the database, which is what every
1325
- // `document-type` write requires, and what the assistant asks of a schema
1326
- // proposal before it writes one.
1351
+ // `document-type` write requires.
1327
1352
  if (!hasSection(principal, 'settings')) return new Response('Forbidden', { status: 403 })
1328
1353
  if (request.method !== 'GET' && request.method !== 'POST') {
1329
1354
  return new Response('Method Not Allowed', { status: 405 })
@@ -1355,8 +1380,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1355
1380
  //
1356
1381
  // Signed in and not Settings, although only Settings can open a template:
1357
1382
  // this is the same vocabulary of type and property aliases that the content
1358
- // editor in front of every backoffice user already shows them, and the
1359
- // assistant's review pane loads a template for anyone who may use it.
1383
+ // editor in front of every backoffice user already shows them.
1360
1384
  if (pathname === `${paths.pluginPath}/api/editor-types`) {
1361
1385
  const principal = await authenticate(request)
1362
1386
  if (!principal) return new Response('Unauthorized', { status: 401 })
@@ -1476,6 +1500,39 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1476
1500
  * wherever someone finds the option missing. The provider's `description`
1477
1501
  * is deliberately left out: for a custom adapter it is an internal URL.
1478
1502
  */
1503
+ // Story 178: the back office vouches for its user to the host's own service.
1504
+ if (pathname === hostTokenPath) {
1505
+ if (!config.host) return new Response('Not Found', { status: 404 })
1506
+ if (request.method !== 'POST') return new Response('Method Not Allowed', { status: 405 })
1507
+ if (!isSameOrigin(request, config.applicationUrl || undefined))
1508
+ return new Response('Forbidden', { status: 403 })
1509
+ // The person as they stand now: an ended session, a lock-out or a
1510
+ // disabled account resolves to nobody.
1511
+ const principal = await authenticate(request)
1512
+ if (!principal) return new Response('Unauthorized', { status: 401 })
1513
+ if (hostTokens.blocked(principal.id))
1514
+ return new Response('Too Many Requests', { status: 429, headers: { 'retry-after': '60' } })
1515
+ hostTokens.fail(principal.id)
1516
+ const token = await issueHostToken(config.host, {
1517
+ user: { key: principal.id, name: principal.name },
1518
+ groups: principal.groups.map((group) => group.alias),
1519
+ sections: principal.allowedSections,
1520
+ site: {
1521
+ name: config.siteName,
1522
+ nodeId: schema.nodeId,
1523
+ url: config.applicationUrl || undefined,
1524
+ },
1525
+ })
1526
+ log.info('Issued a host token to {user} for {host}', {
1527
+ user: principal.email,
1528
+ host: config.host.origin,
1529
+ })
1530
+ return Response.json(
1531
+ { token, expiresIn: HOST_TOKEN_SECONDS },
1532
+ { headers: { 'cache-control': 'no-store' } },
1533
+ )
1534
+ }
1535
+
1479
1536
  if (pathname === `${paths.pluginPath}/api/email` && request.method === 'GET') {
1480
1537
  if (!(await authenticate(request))) return new Response('Unauthorized', { status: 401 })
1481
1538
  return Response.json({
@@ -1937,7 +1994,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1937
1994
  if (pathname.startsWith(apiPrefix)) {
1938
1995
  if (pathname === `${apiPrefix}openapi.json`) {
1939
1996
  // Umbraco's contract with crombolo's deliberate differences (contracts/src/overrides.ts).
1940
- return new Response(servedContract(), {
1997
+ return new Response(servedContract(managementApiPrefix(paths.backOfficePath)), {
1941
1998
  headers: { 'content-type': 'application/json' },
1942
1999
  })
1943
2000
  }
@@ -2455,9 +2512,10 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2455
2512
  if (!request.headers.has('content-length') && request.headers.has('transfer-encoding'))
2456
2513
  return new Response('Length Required', { status: 411 })
2457
2514
  }
2458
- if (pathname === hubPath || pathname === previewHubPath) {
2515
+ const hubAt = contractPathFor(paths.backOfficePath, pathname) ?? pathname
2516
+ if (hubAt === hubPath || hubAt === previewHubPath) {
2459
2517
  const principal = await authenticate(request)
2460
- const hub = pathname === hubPath ? events : previewHub
2518
+ const hub = hubAt === hubPath ? events : previewHub
2461
2519
  return hub.upgrade(request, bunServer, principal?.id)
2462
2520
  }
2463
2521
  return fetch(request)
@@ -2467,6 +2525,8 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2467
2525
  async close() {
2468
2526
  diagnostics.stop()
2469
2527
  jobs.stop()
2528
+ // A dispatch a commit started finishes before the connection goes.
2529
+ await dispatcher.settled().catch(() => {})
2470
2530
  events.stop()
2471
2531
  previewHub.stop()
2472
2532
  watcher?.close()
package/src/settings.ts CHANGED
@@ -893,19 +893,13 @@ const DECLARED = [
893
893
  env: 'AWS_REGION',
894
894
  kind: 'string',
895
895
  section: 'AWS credentials',
896
- description: 'The AWS region, for SES e-mail and the Bedrock assistant when they set none.',
897
- },
898
- {
899
- env: 'AWS_PROFILE',
900
- kind: 'string',
901
- section: 'AWS credentials',
902
- description: 'The AWS profile the Bedrock assistant signs in with.',
896
+ description: 'The AWS region, for SES e-mail when it sets none.',
903
897
  },
904
898
  {
905
899
  env: 'AWS_ACCESS_KEY_ID',
906
900
  kind: 'string',
907
901
  section: 'AWS credentials',
908
- description: 'A static AWS access key, for SES e-mail and the Bedrock assistant.',
902
+ description: 'A static AWS access key, for SES e-mail.',
909
903
  },
910
904
  {
911
905
  env: 'AWS_SECRET_ACCESS_KEY',
package/src/site-file.ts CHANGED
@@ -98,12 +98,28 @@ async function topLevelNodes(db: Db): Promise<NodeRow[]> {
98
98
  }
99
99
 
100
100
  /** The server bundles the site wires, by package name and version. */
101
+ /**
102
+ * The names in `hostProvided` this installation has not got: neither a wired
103
+ * bundle's package nor an extension discovered in the site. Said once at start
104
+ * rather than refused, so a host can list a bundle it is still rolling out.
105
+ */
106
+ export function unknownHostProvided(
107
+ config: Pick<CromboloConfig, 'hostProvided' | 'siteDir'>,
108
+ ): string[] {
109
+ if (config.hostProvided.length === 0) return []
110
+ const installed = new Set(discoverBundles(config.siteDir).bundles.map((b) => b.packageName))
111
+ return config.hostProvided.filter((name) => !installed.has(name))
112
+ }
113
+
101
114
  function requiredPackages(config: CromboloConfig): Record<string, string> {
102
115
  if (config.bundles.length === 0) return {}
103
116
  const wired = new Set(config.bundles.map((bundle) => bundle.id))
117
+ // The installation's own packages are not the site's to need (story 177).
118
+ const hosts = new Set(config.hostProvided)
104
119
  const required: Record<string, string> = {}
105
120
  for (const found of discoverBundles(config.siteDir).bundles)
106
- if (wired.has(found.id)) required[found.packageName] = found.version
121
+ if (wired.has(found.id) && !hosts.has(found.packageName))
122
+ required[found.packageName] = found.version
107
123
  return required
108
124
  }
109
125
 
@@ -43,8 +43,19 @@ export async function redirectAfterUrlChange(
43
43
  ctx: UrlChangeContext,
44
44
  before: UrlOptions,
45
45
  ): Promise<void> {
46
+ const withBefore = (source: PublishedContentSource): PublishedContentSource => ({
47
+ ...source,
48
+ loadUrlOptions: async () => before,
49
+ })
50
+ // The snapshot hands the build a source of its own, so the old setting goes on that too.
51
+ const snapshot = ctx.source.withSnapshot?.bind(ctx.source)
46
52
  const old = new PublishedCache(
47
- { ...ctx.source, loadUrlOptions: async () => before },
53
+ {
54
+ ...withBefore(ctx.source),
55
+ withSnapshot: snapshot
56
+ ? (fn) => snapshot((scoped, checkpoint) => fn(withBefore(scoped), checkpoint))
57
+ : undefined,
58
+ },
48
59
  ctx.cacheOptions,
49
60
  )
50
61
  const captured: DocumentRoute[] = []