@crombolo/server 0.36.2 → 0.37.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/server.ts CHANGED
@@ -61,6 +61,7 @@ import {
61
61
  import type { DocumentOperations, MediaOperations } from '@crombolo/content'
62
62
  import { servedContract } from '@crombolo/contracts'
63
63
  import {
64
+ CACHE_KEEP_FOR_ALIAS,
64
65
  CHOICE_SOURCE_KINDS,
65
66
  type ChoiceSourceKind,
66
67
  contractPathFor,
@@ -98,9 +99,9 @@ import {
98
99
  import {
99
100
  BUNDLE_SCRIPT,
100
101
  BUNDLE_SCRIPT_PATH,
101
- BUNDLE_SITE_PATH,
102
102
  cacheable,
103
103
  cacheControl,
104
+ chosenLifetime,
104
105
  contentForNode,
105
106
  DEFAULT_MEDIA_CACHE_MEGABYTES,
106
107
  DEVELOPMENT_LIMITS,
@@ -108,12 +109,20 @@ import {
108
109
  FORM_SCRIPT_PATH,
109
110
  FORM_SUBMIT_PATH,
110
111
  formAction,
112
+ ISLAND_LOADER_PATH,
113
+ ISLAND_LOADER_SCRIPT,
114
+ ISLANDS_PATH,
115
+ islandTransform,
116
+ type Lifetime,
111
117
  lifetimeFor,
112
118
  MEMBER_EXTERNAL_SIGN_IN_PATH,
113
119
  MediaCache,
120
+ type PageOutcome,
114
121
  PRIVATE_NO_STORE,
115
122
  PublishedCache,
123
+ type PublishedContent,
116
124
  Renderer,
125
+ type RequestMember,
117
126
  resolveCacheSettings,
118
127
  type SnapshotStatus,
119
128
  setFormFieldTypes,
@@ -143,7 +152,6 @@ import {
143
152
  import { BUNDLES_CHANGED_EVENT, type BundleReload, createBundleReloader } from './bundle-reload.ts'
144
153
  import { bundleChains, bundleTablesReport } from './bundle-tables.ts'
145
154
  import {
146
- type BundleMember,
147
155
  bundleRouteGroups,
148
156
  createBundleRedirects,
149
157
  createServerBundles,
@@ -224,14 +232,31 @@ import {
224
232
 
225
233
  export { PREVIEW_COOKIE }
226
234
 
235
+ import type { SiteRoute } from '@crombolo/common'
227
236
  import { BACKOFFICE_EXTERNAL_PATH, backofficeAudience } from './backoffice-external.ts'
228
237
  import { createExternalSignIn } from './external-sign-in.ts'
229
238
  import {
230
239
  createBundleIdentityProviders,
231
240
  IdentityProviderOverrides,
232
241
  } from './identity-provider-overrides.ts'
242
+ import {
243
+ buildIslands,
244
+ builtIslandFile,
245
+ devServerIslandManifest,
246
+ viteIslandManifest,
247
+ viteOutDir,
248
+ } from './islands.ts'
249
+ import {
250
+ hasMiddleware,
251
+ isSitePath,
252
+ type MiddlewareBudget,
253
+ MiddlewareError,
254
+ requestCookies,
255
+ runStage,
256
+ } from './middleware.ts'
233
257
  import { callerAddress } from './rate-limit.ts'
234
258
  import { syncConfiguredRedirects } from './redirects.ts'
259
+ import { createRoutes, type DeclaredRoute, siteRouteProblems } from './routes.ts'
235
260
  import {
236
261
  bootSchema,
237
262
  CacheInstructionPoller,
@@ -250,6 +275,14 @@ import {
250
275
  } from './server-events.ts'
251
276
  import { AttemptLimiter, createSetupRoutes } from './setup.ts'
252
277
  import { siteSearchFor } from './site-search.ts'
278
+ import { createSiteServices } from './site-services.ts'
279
+ import {
280
+ genericStatusPage,
281
+ previewRedirectNotice,
282
+ resolveStatusPage,
283
+ statusPageKind,
284
+ unresolvedStatusPages,
285
+ } from './status-pages.ts'
253
286
  import { TwoFactorService, USER_TWO_FACTOR_PROVIDER } from './two-factor.ts'
254
287
  import { summariseUpgrades } from './upgrade-summary.ts'
255
288
  import { assertViewRuntime } from './view-runtime.ts'
@@ -661,6 +694,22 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
661
694
  hash: hash.slice(0, 8),
662
695
  })
663
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
+ },
664
713
  })
665
714
  await snapshots.prepare()
666
715
  // Before the poller, which tells it to look again on a `views` instruction
@@ -671,6 +720,12 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
671
720
  componentsDir: config.componentsDir,
672
721
  snapshots,
673
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`,
674
729
  })
675
730
  // The site's own redirects are code, so the database follows the file: rules it
676
731
  // no longer declares are removed, which is what makes deleting one from config
@@ -704,26 +759,13 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
704
759
  const formCors = corsPolicy(deliverySettings)
705
760
  /**
706
761
  * The server halves of the site's bundles. Back-office routes answer only
707
- * where the backoffice is; member and public routes (story 186) wherever the
708
- * site is served.
762
+ * where the backoffice is; site routes (story 211) wherever the site is
763
+ * served, through the site's route table.
709
764
  *
710
765
  * Capabilities are built here, from what this node already holds, so a bundle
711
766
  * is handed a narrow interface rather than the database. A bad bundle fails the
712
767
  * boot — see `createServerBundles`.
713
768
  */
714
- const asBundleMember = (member: {
715
- key: string
716
- name: string
717
- username: string
718
- email: string
719
- roles: string[]
720
- }): BundleMember => ({
721
- key: member.key,
722
- name: member.name,
723
- username: member.username,
724
- email: member.email,
725
- groups: member.roles,
726
- })
727
769
  // Story 198: media as the member, built at the first request, when the media
728
770
  // operations and the store it writes through exist.
729
771
  let bundleMedia: BundleMediaFactory | undefined
@@ -783,23 +825,6 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
783
825
  return bundleMedia(caller, bundle)
784
826
  },
785
827
  },
786
- site: {
787
- session: async (request) => {
788
- const session = await members.session(request)
789
- return session && { member: asBundleMember(session.member), verify: session.verify }
790
- },
791
- memberByToken: memberAuthorizationEnabled(deliverySettings)
792
- ? async (token) => {
793
- const named = await deliveryMembers.member(token)
794
- if (!named?.approved || named.lockedOut) return undefined
795
- const member = await new MemberRepository(db).byKey(named.key)
796
- return member && asBundleMember(member)
797
- }
798
- : undefined,
799
- cors: formCors,
800
- callerAddress: (request) =>
801
- callerAddress(peers.get(request), request.headers.get('x-forwarded-for')),
802
- },
803
828
  })
804
829
  : undefined
805
830
  if (bundles) {
@@ -824,14 +849,22 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
824
849
  prefix: bundle.prefix,
825
850
  section: bundle.section,
826
851
  })
827
- if (config.role !== 'api' && bundle.routes.some((route) => route.audience !== 'backoffice'))
828
- log.info('Bundle {name} answering members and visitors below {prefix}', {
852
+ const paths = bundle.routes
853
+ .filter((route) => route.audience === 'site')
854
+ .map((route) => route.path)
855
+ if (config.role !== 'api' && paths.length > 0)
856
+ log.info('Bundle {name} answering on the site at {paths}', {
829
857
  name: bundle.name,
830
- prefix: bundle.sitePrefix,
858
+ paths: paths.join(', '),
831
859
  })
832
860
  }
833
861
  {
834
- const named = bundleRouteGroups(config.bundles)
862
+ const named = [
863
+ ...bundleRouteGroups(config.bundles),
864
+ ...(config.routes ?? []).flatMap((route) =>
865
+ typeof route.options.members === 'object' ? route.options.members.groups : [],
866
+ ),
867
+ ]
835
868
  if (named.length > 0) {
836
869
  const existing = new Set(
837
870
  (
@@ -887,6 +920,11 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
887
920
  },
888
921
  })
889
922
  await poller.start(config.development ? 2_000 : 5_000)
923
+ for (const { kind, path } of await unresolvedStatusPages(cache, config.pages).catch(() => []))
924
+ renderLog.warning(
925
+ "pages.{kind} is '{path}', which no published page answers; that status shows a plain page until one does.",
926
+ { kind, path },
927
+ )
890
928
  const watcher =
891
929
  config.development && owns
892
930
  ? watchSchema(
@@ -1042,7 +1080,10 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1042
1080
  },
1043
1081
  sitemap: (request, host) => seo.sitemapItems(request, host),
1044
1082
  notFound: async (host, path) => {
1045
- const found = await seo.notFound(host, path)
1083
+ // The page a rendered site answers with, so an app shows the same one (story 208).
1084
+ const found =
1085
+ (await resolveStatusPage(cache, config.pages, 'notFound', host, path)) ??
1086
+ (await seo.notFound(host, path))
1046
1087
  return found && { key: found.content.key, culture: found.culture }
1047
1088
  },
1048
1089
  preview: async (request, keyed) => {
@@ -1106,6 +1147,45 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1106
1147
  draft: draftModel,
1107
1148
  })
1108
1149
  const seoPath = `${paths.pluginPath}/api/seo`
1150
+ const siteServicesFor = createSiteServices({ db, cache })
1151
+
1152
+ // Story 211: the site's routes and its bundles' site routes, at their own
1153
+ // paths, ahead of content finding; one pipeline answers bundles' back-office
1154
+ // routes too.
1155
+ const declaredRoutes: DeclaredRoute[] = [
1156
+ ...(config.routes ?? []).map(
1157
+ (route): DeclaredRoute => ({ route: route as SiteRoute, owner: 'the site' }),
1158
+ ),
1159
+ ...(bundles?.siteRoutes() ?? []),
1160
+ ]
1161
+ {
1162
+ const problems = siteRouteProblems(declaredRoutes, config.backOfficePath)
1163
+ if (problems.length > 0)
1164
+ throw new Error(`The site's routes cannot be mounted:\n- ${problems.join('\n- ')}`)
1165
+ }
1166
+ const siteRoutes = createRoutes<RequestMember>(declaredRoutes, {
1167
+ backOfficePath: config.backOfficePath,
1168
+ timeoutMs: config.routeTimeoutMs,
1169
+ defaultPerMinute: config.routeRateLimitPerMinute,
1170
+ siteFor: (member) => siteServicesFor(member),
1171
+ session: (request) => members.session(request),
1172
+ memberByToken: memberAuthorizationEnabled(deliverySettings)
1173
+ ? async (token) => {
1174
+ const named = await deliveryMembers.member(token)
1175
+ if (!named?.approved || named.lockedOut) return undefined
1176
+ return (await new MemberRepository(db).byKey(named.key)) ?? undefined
1177
+ }
1178
+ : undefined,
1179
+ callerAddress: (request) =>
1180
+ callerAddress(peers.get(request), request.headers.get('x-forwarded-for')) ?? 'unknown',
1181
+ statusPage: (request, outcome) => {
1182
+ const url = new URL(request.url)
1183
+ return statusResponse(request, url.pathname, url.host, undefined, outcome)
1184
+ },
1185
+ logError: (message, properties) => renderLog.error(message, properties),
1186
+ showDetails: config.errors.showDetails,
1187
+ cors: formCors,
1188
+ })
1109
1189
 
1110
1190
  const notImplementedLog = logger('not-implemented')
1111
1191
  const notImplemented = new NotImplementedLog((line, entry) => {
@@ -1177,6 +1257,21 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1177
1257
  const managementDeps = createDeps({
1178
1258
  config,
1179
1259
  paths,
1260
+ hiddenByRoutes: async () => {
1261
+ const snapshot = await cache.snapshot()
1262
+ const hidden: Array<{ route: string; owner: string; page: string; url: string }> = []
1263
+ for (const [url, content] of snapshot.byRoute) {
1264
+ const found = siteRoutes.match(url)
1265
+ if (found)
1266
+ hidden.push({
1267
+ route: found.entry.route.path,
1268
+ owner: found.entry.owner,
1269
+ page: content.name,
1270
+ url,
1271
+ })
1272
+ }
1273
+ return hidden
1274
+ },
1180
1275
  extensions,
1181
1276
  db,
1182
1277
  webhooks,
@@ -1441,6 +1536,17 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1441
1536
  if (response) return response
1442
1537
  }
1443
1538
 
1539
+ // Islands (story 209): the loader, and each generation's browser code.
1540
+ if (pathname === ISLAND_LOADER_PATH)
1541
+ return new Response(ISLAND_LOADER_SCRIPT, {
1542
+ headers: {
1543
+ 'content-type': 'text/javascript; charset=utf-8',
1544
+ 'cache-control': config.development ? 'no-cache' : 'public, max-age=3600',
1545
+ },
1546
+ })
1547
+ if (pathname.startsWith(`${ISLANDS_PATH}/`))
1548
+ return islandFile(pathname.slice(ISLANDS_PATH.length + 1))
1549
+
1444
1550
  // The progressive-enhancement script. A site adds it to a layout; a form
1445
1551
  // works without it, so nothing emits it automatically.
1446
1552
  if (pathname === FORM_SCRIPT_PATH)
@@ -1471,8 +1577,6 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1471
1577
  'cache-control': config.development ? 'no-cache' : 'public, max-age=3600',
1472
1578
  },
1473
1579
  })
1474
- if (pathname.startsWith(`${BUNDLE_SITE_PATH}/`))
1475
- return (await bundles?.site(request, url)) ?? new Response('Not Found', { status: 404 })
1476
1580
  }
1477
1581
 
1478
1582
  // Not on an `api` node, which serves no public site to describe.
@@ -1480,9 +1584,165 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1480
1584
  return pathname === '/sitemap.xml' ? seo.sitemap(request, url.host) : seo.robots(request)
1481
1585
 
1482
1586
  if (pathname.startsWith('/media/')) return serveMedia(request, pathname, url.searchParams)
1587
+ return siteRequest(request, url)
1588
+ }
1589
+
1590
+ /** What a chain is carrying through one request (story 210). */
1591
+ interface ChainRun {
1592
+ original: URL
1593
+ budget: MiddlewareBudget
1594
+ preview: boolean
1595
+ /** Something read in the chain depends on who is asking. */
1596
+ personal: boolean
1597
+ /** The route stage has run; a rewrite it made is not routed through it again. */
1598
+ routed: boolean
1599
+ }
1600
+
1601
+ const chainOf = () => config.middleware
1602
+ const anyMiddleware = () => {
1603
+ const chain = chainOf()
1604
+ return Boolean(
1605
+ chain &&
1606
+ (hasMiddleware(chain.request) || hasMiddleware(chain.route) || hasMiddleware(chain.page)),
1607
+ )
1608
+ }
1609
+
1610
+ /** A site request: the middleware chain around crombolo's own handling, when the site has one. */
1611
+ async function siteRequest(request: Request, url: URL): Promise<Response> {
1612
+ if (!anyMiddleware()) return siteFiles(request)
1613
+ const run: ChainRun = {
1614
+ original: url,
1615
+ budget: {
1616
+ remainingMs:
1617
+ config.middlewareTimeoutMs > 0 ? config.middlewareTimeoutMs : Number.POSITIVE_INFINITY,
1618
+ },
1619
+ preview: Boolean(readCookie(request, PREVIEW_COOKIE) && (await authenticate(request))),
1620
+ personal: false,
1621
+ routed: false,
1622
+ }
1623
+ try {
1624
+ const response = await runStage({
1625
+ stage: 'request',
1626
+ chain: chainOf()?.request,
1627
+ request,
1628
+ budget: run.budget,
1629
+ context: (current) => chainContext(current, run, {}),
1630
+ inner: (current) => {
1631
+ assertSiteTarget(new URL(current.url), run)
1632
+ return siteFiles(current, run)
1633
+ },
1634
+ })
1635
+ return finishChain(response, run)
1636
+ } catch (error) {
1637
+ return middlewareFailure(request, url, error)
1638
+ }
1639
+ }
1640
+
1641
+ /** The site's stylesheets and scripts, or its pages. */
1642
+ async function siteFiles(request: Request, run?: ChainRun): Promise<Response> {
1643
+ const url = new URL(request.url)
1644
+ const pathname = url.pathname
1645
+ // A route wins at its path (story 211); an `api` node serves no site.
1646
+ if (config.role !== 'api') {
1647
+ const routed = await siteRoutes.handle(request, url)
1648
+ if (routed) return routed
1649
+ }
1483
1650
  if (pathname.startsWith('/css/')) return serveSiteFile(config.stylesheetsDir, pathname, '.css')
1484
1651
  if (pathname.startsWith('/scripts/')) return serveSiteFile(config.scriptsDir, pathname, '.js')
1485
- return renderSite(request, pathname, url.host)
1652
+ return renderSite(request, pathname, url.host, run)
1653
+ }
1654
+
1655
+ /** A rewrite stays on this site, among its own pages. */
1656
+ function assertSiteTarget(target: URL, run: ChainRun): void {
1657
+ if (target.origin !== run.original.origin)
1658
+ throw new MiddlewareError(
1659
+ 'the middleware chain',
1660
+ `A rewrite goes to a path on this site, not to ${target.origin}.`,
1661
+ )
1662
+ if (
1663
+ target.pathname !== run.original.pathname &&
1664
+ !isSitePath(target.pathname, config.backOfficePath)
1665
+ )
1666
+ throw new MiddlewareError(
1667
+ 'the middleware chain',
1668
+ `A rewrite cannot go to ${target.pathname}, which is not one of this site's pages.`,
1669
+ )
1670
+ }
1671
+
1672
+ /** What a middleware is given: its cookies mark the answer personal when read. */
1673
+ function chainContext(
1674
+ request: Request,
1675
+ run: ChainRun,
1676
+ extra: { page?: PublishedContent; member?: Awaited<ReturnType<typeof members.resolve>> },
1677
+ ) {
1678
+ return {
1679
+ url: new URL(request.url),
1680
+ get cookies() {
1681
+ run.personal = true
1682
+ return requestCookies(request)
1683
+ },
1684
+ site: () =>
1685
+ siteServicesFor(
1686
+ run.preview ? undefined : async () => (await members.session(request))?.member,
1687
+ )(),
1688
+ preview: run.preview,
1689
+ signal: request.signal,
1690
+ ...extra,
1691
+ }
1692
+ }
1693
+
1694
+ /** The chain's answer, kept private when it depended on who asked, and shown to an editor in preview. */
1695
+ function finishChain(response: Response, run: ChainRun): Response {
1696
+ const location = response.headers.get('location')
1697
+ if (run.preview && response.status >= 300 && response.status < 400 && location)
1698
+ return new Response(previewRedirectNotice(response.status, location), {
1699
+ headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': PRIVATE_NO_STORE },
1700
+ })
1701
+ if (!run.personal && !response.headers.has('set-cookie')) return response
1702
+ const headers = new Headers(response.headers)
1703
+ headers.set('cache-control', PRIVATE_NO_STORE)
1704
+ headers.delete('etag')
1705
+ return new Response(response.body, {
1706
+ status: response.status,
1707
+ statusText: response.statusText,
1708
+ headers,
1709
+ })
1710
+ }
1711
+
1712
+ /** A middleware that failed: logged by name with a reference, and answered with the error page. */
1713
+ async function middlewareFailure(request: Request, url: URL, error: unknown): Promise<Response> {
1714
+ if (request.signal.aborted) return new Response(null, { status: 499 })
1715
+ const name = error instanceof MiddlewareError ? error.middleware : 'the middleware chain'
1716
+ const message = error instanceof Error ? error.message : String(error)
1717
+ const cause = error instanceof MiddlewareError ? error.cause : error
1718
+ const reference = errorReference()
1719
+ renderLog.error('Middleware {name} failed on {path}, reference {reference}: {detail}', {
1720
+ name,
1721
+ path: url.pathname,
1722
+ reference,
1723
+ detail: cause instanceof Error ? (cause.stack ?? message) : message,
1724
+ })
1725
+ return statusResponse(
1726
+ request,
1727
+ url.pathname,
1728
+ url.host,
1729
+ undefined,
1730
+ {
1731
+ status: 500,
1732
+ name: 'serverError',
1733
+ errors: [],
1734
+ reference,
1735
+ ...(config.errors.showDetails
1736
+ ? {
1737
+ details: {
1738
+ message,
1739
+ ...(cause instanceof Error && cause.stack ? { stack: cause.stack } : {}),
1740
+ },
1741
+ }
1742
+ : {}),
1743
+ },
1744
+ { 'cache-control': PRIVATE_NO_STORE },
1745
+ )
1486
1746
  }
1487
1747
 
1488
1748
  /**
@@ -1639,7 +1899,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1639
1899
  if (bundles && pathname.startsWith(bundles.basePath)) {
1640
1900
  const principal = await authenticate(request)
1641
1901
  if (!principal) return new Response('Unauthorized', { status: 401 })
1642
- const answered = await bundles.handle(request, url, principal)
1902
+ const answered = await bundles.handle(request, url, principal, siteRoutes.invoke)
1643
1903
  if (answered) return answered
1644
1904
  }
1645
1905
 
@@ -2523,6 +2783,8 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2523
2783
  return renderer.renderModel(draft.content, draft.culture, {
2524
2784
  ...(await pageRequest(request)),
2525
2785
  search: siteSearchFor(db, cache, undefined),
2786
+ // The previewing editor is the visitor, with no member.
2787
+ site: siteServicesFor(undefined),
2526
2788
  // Blocks with no component say so here, and only here (story 184).
2527
2789
  preview: true,
2528
2790
  })
@@ -2533,6 +2795,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2533
2795
  return {
2534
2796
  origin: publicOrigin(request, config),
2535
2797
  url: request.url,
2798
+ headers: request.headers,
2536
2799
  seo: await seo.siteDefaults(),
2537
2800
  signal: request.signal,
2538
2801
  }
@@ -2655,7 +2918,90 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2655
2918
  }
2656
2919
  }
2657
2920
 
2658
- async function renderSite(request: Request, pathname: string, host: string): Promise<Response> {
2921
+ /**
2922
+ * A page, through the route and page stages of the chain when it has them:
2923
+ * the route stage once the page is found (a redirect the tables answer comes
2924
+ * first), the page stage once its access is decided. Access is always checked
2925
+ * on the page that finally renders.
2926
+ */
2927
+ async function renderSite(
2928
+ request: Request,
2929
+ pathname: string,
2930
+ host: string,
2931
+ run?: ChainRun,
2932
+ ): Promise<Response> {
2933
+ const chain = chainOf()
2934
+ if (!run || !chain) return renderPage(request, pathname, host)
2935
+ if (hasMiddleware(chain.route) && !run.routed) {
2936
+ const resolved = run.preview ? undefined : await cache.resolve(host, pathname)
2937
+ const redirected =
2938
+ resolved?.redirect !== undefined ||
2939
+ (!resolved && !run.preview && (await cache.redirect(host, pathname)) !== undefined)
2940
+ // The redirect tables answer first, and there is no page for the later stages.
2941
+ if (redirected) return renderPage(request, pathname, host)
2942
+ run.routed = true
2943
+ return runStage({
2944
+ stage: 'route',
2945
+ chain: chain.route,
2946
+ request,
2947
+ budget: run.budget,
2948
+ context: (current) => chainContext(current, run, { page: resolved?.content }),
2949
+ inner: (current) => {
2950
+ const to = new URL(current.url)
2951
+ if (to.pathname === pathname)
2952
+ return pageStage(current, pathname, host, run, resolved?.content)
2953
+ // Resolved again from the start: redirects, access, the page found there.
2954
+ assertSiteTarget(to, run)
2955
+ return renderSite(current, to.pathname, host, run)
2956
+ },
2957
+ })
2958
+ }
2959
+ return pageStage(request, pathname, host, run)
2960
+ }
2961
+
2962
+ /** The page stage: after access is decided, so it sees the page that renders and may not change it. */
2963
+ async function pageStage(
2964
+ request: Request,
2965
+ pathname: string,
2966
+ host: string,
2967
+ run: ChainRun,
2968
+ found?: PublishedContent,
2969
+ ): Promise<Response> {
2970
+ const chain = chainOf()
2971
+ if (!hasMiddleware(chain?.page)) return renderPage(request, pathname, host)
2972
+ const resolved = found || run.preview ? undefined : await cache.resolve(host, pathname)
2973
+ const content = found ?? resolved?.content
2974
+ // A redirect has no page to see, so the redirect tables and `umbracoRedirect` answer first.
2975
+ if (
2976
+ resolved?.redirect !== undefined ||
2977
+ (!content && !run.preview && (await cache.redirect(host, pathname)) !== undefined)
2978
+ )
2979
+ return renderPage(request, pathname, host)
2980
+ const member = run.preview ? undefined : (await members.session(request))?.member
2981
+ let shown = content
2982
+ if (content) {
2983
+ const decision = await members.decide(content, member)
2984
+ if (decision.status === 'substitute')
2985
+ shown = (await cache.byKey(decision.contentKey, content.culture)) ?? content
2986
+ }
2987
+ return runStage({
2988
+ stage: 'page',
2989
+ chain: chain?.page,
2990
+ request,
2991
+ budget: run.budget,
2992
+ context: (current) => chainContext(current, run, { page: shown, member }),
2993
+ inner: (current) => {
2994
+ if (new URL(current.url).pathname !== pathname)
2995
+ throw new MiddlewareError(
2996
+ 'the page stage',
2997
+ 'A rewrite is refused in the page stage: which page renders, and who may see it, is already decided.',
2998
+ )
2999
+ return renderPage(current, pathname, host)
3000
+ },
3001
+ })
3002
+ }
3003
+
3004
+ async function renderPage(request: Request, pathname: string, host: string): Promise<Response> {
2659
3005
  const preview = await renderPreview(request, pathname, host)
2660
3006
  // An `api` node renders for preview and nothing else. The backoffice opens a
2661
3007
  // site URL to preview a draft, so the renderer has to be here; serving the
@@ -2675,7 +3021,9 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2675
3021
  // A page that is not the same for everyone is never kept: a member's, a
2676
3022
  // preview, a form's answer, or anything in a members-only branch — which a
2677
3023
  // visitor sees as the login page, at the same address.
2678
- let personal = Boolean(preview || member || submission || cookie)
3024
+ // Whether the page itself read anything personal, the member included, it
3025
+ // says in its result (story 206).
3026
+ let personal = Boolean(preview || submission || cookie)
2679
3027
  const result =
2680
3028
  preview ??
2681
3029
  (await renderer.render(pathname, host, {
@@ -2687,6 +3035,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2687
3035
  return members.decide(content, member)
2688
3036
  },
2689
3037
  search: siteSearchFor(db, cache, member),
3038
+ site: siteServicesFor(member),
2690
3039
  ...(await pageRequest(request)),
2691
3040
  }))
2692
3041
  const cleared: Record<string, string> = cookie
@@ -2697,16 +3046,23 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2697
3046
  const response = new Response(result.html, {
2698
3047
  headers: { 'content-type': 'text/html; charset=utf-8', ...cleared },
2699
3048
  })
2700
- if (personal) {
3049
+ if (personal || result.personal) {
2701
3050
  response.headers.set('cache-control', PRIVATE_NO_STORE)
2702
3051
  return response
2703
3052
  }
2704
3053
  const ancestors = (await cache.navigation(result.content.culture)).ancestors(result.content)
3054
+ const item = {
3055
+ typeAlias: result.content.contentType.alias,
3056
+ value: (alias: string) => result.content.value(alias),
3057
+ }
2705
3058
  return cacheable(request, response, result.html, {
2706
- lifetime: lifetimeFor(caching, {
2707
- typeAlias: result.content.contentType.alias,
2708
- value: (alias) => result.content.value(alias),
2709
- }),
3059
+ // A page's own "Keep copies for" still wins over its template's `revalidate`.
3060
+ lifetime:
3061
+ (result.revalidate === undefined
3062
+ ? undefined
3063
+ : chosenLifetime(result.content.value(CACHE_KEEP_FOR_ALIAS))) ??
3064
+ revalidateLifetime(result.revalidate) ??
3065
+ lifetimeFor(caching, item),
2710
3066
  tags: [result.content.key, ...ancestors.map((a) => a.key)],
2711
3067
  tagHeader: caching.tagHeader,
2712
3068
  })
@@ -2723,6 +3079,36 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2723
3079
  status: 404,
2724
3080
  headers: { 'content-type': 'text/plain; charset=utf-8' },
2725
3081
  })
3082
+ case 'outcome': {
3083
+ const { outcome } = result
3084
+ const shared = !(personal || result.personal)
3085
+ const headers: Record<string, string> = {
3086
+ ...cleared,
3087
+ ...(shared ? {} : { 'cache-control': PRIVATE_NO_STORE }),
3088
+ }
3089
+ if (outcome.isRedirect) {
3090
+ const location = outcome.location as string
3091
+ // The preview frame stays put, and the editor is told where visitors go.
3092
+ if (preview)
3093
+ return new Response(previewRedirectNotice(outcome.status, location), {
3094
+ headers: { 'content-type': 'text/html; charset=utf-8', ...headers },
3095
+ })
3096
+ return new Response(null, { status: outcome.status, headers: { location, ...headers } })
3097
+ }
3098
+ return statusResponse(
3099
+ request,
3100
+ pathname,
3101
+ host,
3102
+ member,
3103
+ {
3104
+ status: outcome.status,
3105
+ name: outcome.name,
3106
+ message: outcome.message,
3107
+ errors: outcome.errors,
3108
+ },
3109
+ headers,
3110
+ )
3111
+ }
2726
3112
  case 'error': {
2727
3113
  // The visitor left and the render was stopped for it: nobody reads this
2728
3114
  // response, and it says nothing about the template.
@@ -2730,16 +3116,30 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2730
3116
  // Through `inSource`, so the file named is the one somebody can open
2731
3117
  // rather than the snapshot generation it was imported from.
2732
3118
  const detail = renderer.inSource(result.error.stack ?? result.error.message)
2733
- renderLog.error('Template error while rendering {name} ({key}): {detail}', {
2734
- name: result.content.name,
2735
- key: result.content.key,
2736
- detail,
2737
- })
2738
- return new Response(
2739
- config.development
2740
- ? `Template error while rendering '${result.content.name}':\n\n${detail}`
2741
- : 'Server Error',
2742
- { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } },
3119
+ const reference = errorReference()
3120
+ renderLog.error(
3121
+ 'Template error while rendering {name} ({key}), reference {reference}: {detail}',
3122
+ {
3123
+ name: result.content.name,
3124
+ key: result.content.key,
3125
+ reference,
3126
+ detail,
3127
+ },
3128
+ )
3129
+ const described = renderer.describeError(result.error)
3130
+ return statusResponse(
3131
+ request,
3132
+ pathname,
3133
+ host,
3134
+ member,
3135
+ {
3136
+ status: 500,
3137
+ name: 'serverError',
3138
+ errors: [],
3139
+ reference,
3140
+ ...(config.errors.showDetails ? { details: described } : {}),
3141
+ },
3142
+ { ...cleared, 'cache-control': PRIVATE_NO_STORE },
2743
3143
  )
2744
3144
  }
2745
3145
  default: {
@@ -2766,6 +3166,13 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2766
3166
  noNodesPage({ siteName: config.siteName, backOfficePath: config.backOfficePath }),
2767
3167
  { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } },
2768
3168
  )
3169
+ const configured = config.pages?.notFound !== undefined
3170
+ if (configured)
3171
+ return statusResponse(request, pathname, host, member, {
3172
+ status: 404,
3173
+ name: 'notFound',
3174
+ errors: [],
3175
+ })
2769
3176
  const page = await renderNotFoundPage(request, pathname, host, member)
2770
3177
  if (page) return page
2771
3178
  return new Response('Not Found', {
@@ -2776,6 +3183,88 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2776
3183
  }
2777
3184
  }
2778
3185
 
3186
+ /** A file of the islands' browser code, or their manifest, by the mode the site is in. */
3187
+ async function islandFile(path: string): Promise<Response> {
3188
+ const missing = () => new Response('Not Found', { status: 404 })
3189
+ const typed = (file: string, cache: string) =>
3190
+ new Response(Bun.file(file), {
3191
+ headers: {
3192
+ 'content-type': file.endsWith('.json')
3193
+ ? 'application/json; charset=utf-8'
3194
+ : file.endsWith('.css')
3195
+ ? 'text/css; charset=utf-8'
3196
+ : 'text/javascript; charset=utf-8',
3197
+ 'cache-control': cache,
3198
+ },
3199
+ })
3200
+ const [mode, ...rest] = path.split('/')
3201
+ if (mode === 'dev') {
3202
+ if (!config.development || !config.islands?.devServer || rest.join('/') !== 'manifest.json')
3203
+ return missing()
3204
+ return Response.json(
3205
+ devServerIslandManifest(config.islands.devServer, config.componentsDir),
3206
+ {
3207
+ headers: { 'cache-control': 'no-cache' },
3208
+ },
3209
+ )
3210
+ }
3211
+ if (mode === 'vite') {
3212
+ const manifestPath = config.islands?.manifest
3213
+ if (!manifestPath) return missing()
3214
+ const file = rest.join('/')
3215
+ if (file === 'manifest.json')
3216
+ return Response.json(viteIslandManifest(config.siteDir, manifestPath), {
3217
+ headers: { 'cache-control': config.development ? 'no-cache' : 'public, max-age=60' },
3218
+ })
3219
+ if (!file || rest.some((part) => part === '' || part === '.' || part === '..'))
3220
+ return missing()
3221
+ const built = join(viteOutDir(config.siteDir, manifestPath), ...rest)
3222
+ return existsSync(built) ? typed(built, 'public, max-age=31536000, immutable') : missing()
3223
+ }
3224
+ const built = builtIslandFile(config.componentsCacheDir, mode ?? '', rest.join('/'))
3225
+ return built ? typed(built, 'public, max-age=31536000, immutable') : missing()
3226
+ }
3227
+
3228
+ /**
3229
+ * A status answered by the site's own page for it, rendered at the address
3230
+ * asked for (story 206); else, for a 404, the page `seo.notFoundPage` names;
3231
+ * else a generic page. A status page that fails or throws an outcome falls to
3232
+ * the generic page, so it never loops.
3233
+ */
3234
+ async function statusResponse(
3235
+ request: Request,
3236
+ pathname: string,
3237
+ host: string,
3238
+ member: Awaited<ReturnType<typeof members.resolve>>,
3239
+ outcome: PageOutcome,
3240
+ headers: Record<string, string> = {},
3241
+ ): Promise<Response> {
3242
+ const html = { 'content-type': 'text/html; charset=utf-8', ...headers }
3243
+ const kind = statusPageKind(outcome.status)
3244
+ const found = await resolveStatusPage(cache, config.pages, kind, host, pathname)
3245
+ if (found) {
3246
+ const result = await renderer.renderModel(found.content, found.culture, {
3247
+ member,
3248
+ outcome,
3249
+ search: siteSearchFor(db, cache, member),
3250
+ site: siteServicesFor(member),
3251
+ ...(await pageRequest(request)),
3252
+ })
3253
+ if (result.status === 'ok')
3254
+ return new Response(result.html, { status: outcome.status, headers: html })
3255
+ if (result.status === 'error' && !request.signal.aborted)
3256
+ renderLog.error('Template error while rendering the {kind} page {name}: {detail}', {
3257
+ kind,
3258
+ name: found.content.name,
3259
+ detail: renderer.inSource(result.error.stack ?? result.error.message),
3260
+ })
3261
+ } else if (outcome.status === 404) {
3262
+ const page = await renderNotFoundPage(request, pathname, host, member)
3263
+ if (page) return page
3264
+ }
3265
+ return new Response(genericStatusPage(outcome), { status: outcome.status, headers: html })
3266
+ }
3267
+
2779
3268
  /**
2780
3269
  * The page chosen to answer an address nothing else does, with status 404. A
2781
3270
  * page that fails to render leaves the plain answer rather than a second error.
@@ -2885,3 +3374,16 @@ function withQuery(location: string, requestUrl: string): string {
2885
3374
  const query = new URL(requestUrl).search
2886
3375
  return query && !location.includes('?') ? `${location}${query}` : location
2887
3376
  }
3377
+
3378
+ /** A short code a visitor can quote, which the log line carries too. */
3379
+ function errorReference(): string {
3380
+ return crypto.randomUUID().replaceAll('-', '').slice(0, 10).toUpperCase()
3381
+ }
3382
+
3383
+ /** A template's `revalidate` as a lifetime: seconds, or false for as long as it is unchanged. */
3384
+ function revalidateLifetime(revalidate: number | false | undefined): Lifetime {
3385
+ if (revalidate === undefined) return undefined
3386
+ if (revalidate === false) return { maxAge: 31_536_000 }
3387
+ if (!Number.isFinite(revalidate) || revalidate < 0) return undefined
3388
+ return revalidate === 0 ? 'none' : { maxAge: Math.floor(revalidate) }
3389
+ }