@ultimat3/cli 31.14.0 → 31.16.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 (69) hide show
  1. package/CLAUDE.md +1 -1
  2. package/README.md +3 -2
  3. package/package.json +29 -29
  4. package/src/budgets-requests.ts +37 -0
  5. package/src/budgets.ts +20 -1
  6. package/src/cmd-doctor.ts +47 -37
  7. package/src/cmd-exercise.ts +14 -1
  8. package/src/cmd-upgrade.ts +19 -2
  9. package/src/coverage-floor.ts +2 -2
  10. package/src/dev-boot.ts +2 -2
  11. package/src/dev-route-table.ts +5 -9
  12. package/src/doctor-env-reserved.ts +111 -0
  13. package/src/doctor-floor.ts +62 -0
  14. package/src/doctor-pins.ts +101 -0
  15. package/src/doctor-probe.ts +21 -1
  16. package/src/doctor-row-security.ts +119 -4
  17. package/src/doctor-warnings.ts +55 -0
  18. package/src/document-options.ts +0 -7
  19. package/src/error-codes-doctor.ts +24 -0
  20. package/src/error-codes.ts +5 -0
  21. package/src/exercise-floor-report.ts +138 -0
  22. package/src/exercise-floor-verdict.ts +98 -0
  23. package/src/exercise-floor.ts +158 -0
  24. package/src/island-bundle.ts +52 -12
  25. package/src/island-disposer.ts +1 -1
  26. package/src/island-group-cache.ts +4 -0
  27. package/src/island-link-check.ts +73 -0
  28. package/src/island-vendor.ts +183 -0
  29. package/src/mcp-errors.ts +11 -1
  30. package/src/messages-upgrade.ts +13 -0
  31. package/src/messages.ts +3 -0
  32. package/src/prerender.ts +7 -7
  33. package/src/route-islands-preload.ts +54 -11
  34. package/src/runtime-admin.ts +2 -4
  35. package/src/runtime-render-document.ts +34 -13
  36. package/src/runtime-render.ts +58 -30
  37. package/src/serve-web.ts +8 -11
  38. package/src/static-images.ts +25 -4
  39. package/src/static-precompress.ts +57 -0
  40. package/src/style-bundle.ts +28 -6
  41. package/src/templates/guard-island-mount-clears.ts +151 -0
  42. package/src/templates/island.ts +8 -7
  43. package/src/templates/resource-form-island.ts +12 -9
  44. package/src/templates/scaffold-docs.ts +1 -0
  45. package/src/templates/scaffold-guards.ts +4 -1
  46. package/src/templates/scaffold-shell.ts +12 -9
  47. package/src/templates/scaffold-verify-floor.ts +4 -0
  48. package/src/test-dotenv.ts +15 -2
  49. package/src/theme-brand.ts +18 -20
  50. package/src/upgrade-coverage.ts +109 -0
  51. package/src/upgrade-document.ts +18 -0
  52. package/src/upgrade-exercise-floor.ts +53 -0
  53. package/src/upgrade-gate.ts +68 -25
  54. package/src/upgrade-guards.ts +159 -0
  55. package/src/upgrade-report.ts +29 -1
  56. package/src/verify-checks.ts +3 -1
  57. package/src/verify-floor.ts +13 -0
  58. package/wiki/CLI-Reference.md +26 -3
  59. package/wiki/Client-Data.md +52 -0
  60. package/wiki/Configuration.md +17 -0
  61. package/wiki/MCP-And-AI.md +42 -1
  62. package/wiki/Notify.md +6 -0
  63. package/wiki/PWA-And-Offline.md +11 -0
  64. package/wiki/Realtime.md +4 -3
  65. package/wiki/SEO.md +1 -1
  66. package/wiki/Static-Assets.md +30 -3
  67. package/wiki/Testing.md +64 -2
  68. package/wiki/Theming.md +6 -6
  69. package/wiki/Upgrading.md +11 -0
package/src/prerender.ts CHANGED
@@ -47,6 +47,7 @@ import { loadSiteSettings, originWarning, publicOrigin } from './site-config';
47
47
  import type { LlmsPages } from './site-llms-pages';
48
48
  import { newestSourceMtime } from './source-mtime';
49
49
  import { staticCapture } from './static-capture';
50
+ import { immutableUrls, writePrecompressed } from './static-precompress';
50
51
  import type { SkippedRoute, UnmeasuredRoute } from './static-report';
51
52
  import { skippedRoute, skipReasonFor, writeStaticReport } from './static-report';
52
53
  import { styleBundle, writeStyles } from './style-bundle';
@@ -159,12 +160,14 @@ export async function prerenderSite(options: PrerenderOptions): Promise<Prerende
159
160
  // behind it, so the artifact carries every byte the browser will ask for.
160
161
  const islands = await buildIslands(options.root);
161
162
  await writeIslands(islands, options.out);
162
- // And the stylesheet every document below LINKS. Derived after the island build on purpose:
163
- // `islandStylesPlugin` registers an island's own `.module.scss` during `Bun.build`, so a bundle
164
- // minted before it would hash CSS the documents do not carry — and the export would publish
165
- // pages whose `<link>` names a file the artifact does not have.
163
+ // And the stylesheet every document below LINKS, after the island build: `islandStylesPlugin`
164
+ // registers an island's `.module.scss` during `Bun.build`, so a sheet minted before it is CSS the
165
+ // documents do not carry. The brand first: it is every sheet's tail, as in the served process.
166
+ await loadThemeBrand(options.root);
166
167
  const styles = styleBundle();
167
168
  await writeStyles(styles, options.out);
169
+ // Every immutable URL above, coded beside itself: a static host serves `.br`/`.gz` unread.
170
+ await writePrecompressed(options.out, immutableUrls(islands, styles));
168
171
  // The hashed `site/assets/**` copies every document's `asset()` URL names — once, never per
169
172
  // locale: an asset is the same bytes in every language, so `/en/` pages link the root's copy.
170
173
  writeSiteAssets(options.root, options.out);
@@ -190,8 +193,6 @@ export async function prerenderSite(options: PrerenderOptions): Promise<Prerende
190
193
  // names it either.
191
194
  const pwa = await loadPwaArtifacts(options.root);
192
195
  const theme = themeBoot(await loadThemeMode(options.root));
193
- // The brand the served process carries, so an exported page and a served one paint alike.
194
- const brand = await loadThemeBrand(options.root);
195
196
  // The app's own favicon is resolved by the DOCUMENT, per render, from the app root below — the
196
197
  // link the served surfaces emit, so an exported document and a served one carry the same icon.
197
198
  // The client router, for the surfaces that opted in: written BEFORE any document names it, for
@@ -276,7 +277,6 @@ export async function prerenderSite(options: PrerenderOptions): Promise<Prerende
276
277
  resolveIsland: (file: string) => islands.resolverFor(file),
277
278
  realtimeIslands: () => islands.realtime,
278
279
  themeHead: theme.head,
279
- ...(brand === undefined ? {} : { brandHead: brand.head }),
280
280
  ...(speculation === undefined ? {} : { speculationHead: speculation.head }),
281
281
  origin,
282
282
  ...(navigation.head === undefined ? {} : { navigation: navigation.head }),
@@ -1,6 +1,7 @@
1
1
  // The `<link rel="modulepreload">` tags for the islands ONE render recorded: every shared chunk an
2
2
  // eagerly booted island imports, each once, so the browser fetches them beside the entry instead of
3
- // discovering them only after the entry is parsed. A page that rendered no island gets none.
3
+ // discovering them only after the entry is parsed. A page that rendered no island gets none. The
4
+ // same set, with the stylesheet, as a `Link` response header: what a CDN turns into a 103.
4
5
 
5
6
  import { escapeHtml } from '@ultimat3/core';
6
7
  import type { IslandCollector, IslandDirective, RouteEntry } from '@ultimat3/render';
@@ -16,22 +17,21 @@ const eager = (directive: IslandDirective): boolean =>
16
17
  directive.strategy === 'idle' || directive.hold === true;
17
18
 
18
19
  /**
19
- * The tags, sorted, after the body beside the boot — `<link rel="modulepreload">` is body-ok, and
20
- * which islands rendered is known only once the walk ran. `booted`: the document carries the page
21
- * boot, which supplies the realtime runtime, so an island there never fetches the runtime chunk
22
- * (`awaitPageRuntime`) and a preload of it would download 64 kB for nothing — the same rule the
23
- * `budgets` step charges by (`MeasureOptions.boot`). `linked` is what an earlier flush of the same
24
- * document already emitted; it is extended with what this call emits.
20
+ * The URLs, sorted, that one call's tags preload — `preloadTags`' set, and the `Link` header's.
21
+ * `booted`: the document carries the page boot, which supplies the realtime runtime, so an island
22
+ * there never fetches the runtime chunk (`awaitPageRuntime`) and a preload of it would download
23
+ * 64 kB for nothing — the same rule the `budgets` step charges by (`MeasureOptions.boot`). `linked`
24
+ * is what an earlier flush of the same document already emitted; it is extended with these.
25
25
  */
26
- export function preloadTags(
26
+ export function preloadUrls(
27
27
  entry: RouteEntry,
28
28
  islands: IslandCollector,
29
29
  options: DocumentOptions,
30
30
  booted: boolean,
31
31
  linked: Set<string> = new Set(),
32
- ): string {
32
+ ): readonly string[] {
33
33
  const importsOf = options.resolveIsland?.(entry.file).importsOf;
34
- if (importsOf === undefined) return '';
34
+ if (importsOf === undefined) return [];
35
35
  const fresh = new Set<string>();
36
36
  for (const directive of islands.directives) {
37
37
  if (!eager(directive)) continue;
@@ -42,5 +42,48 @@ export function preloadTags(
42
42
  }
43
43
  const urls = [...fresh].sort();
44
44
  for (const url of urls) linked.add(url);
45
- return urls.map((url) => `<link rel="modulepreload" href="${escapeHtml(url)}">`).join('');
45
+ return urls;
46
+ }
47
+
48
+ /** The tags, after the body beside the boot: body-ok, and known only once the walk ran. */
49
+ export const preloadTagsOf = (urls: readonly string[]): string =>
50
+ urls.map((url) => `<link rel="modulepreload" href="${escapeHtml(url)}">`).join('');
51
+
52
+ /** `preloadUrls`, as the tags a document carries. */
53
+ export function preloadTags(
54
+ entry: RouteEntry,
55
+ islands: IslandCollector,
56
+ options: DocumentOptions,
57
+ booted: boolean,
58
+ linked: Set<string> = new Set(),
59
+ ): string {
60
+ return preloadTagsOf(preloadUrls(entry, islands, options, booted, linked));
61
+ }
62
+
63
+ /**
64
+ * Only what RFC 8288's `<URI-Reference>` carries bare. Every URL here is one the framework minted
65
+ * (`/styles/<hash>.css`, `/islands/chunk-<hash>.js`), so a URL outside this is not escaped into
66
+ * the header: it is left to its tag, which `escapeHtml` already made safe.
67
+ */
68
+ const HEADER_SAFE_URL = /^[A-Za-z0-9\-._~:/?#@!$&'()*+=%]+$/;
69
+
70
+ /**
71
+ * The `Link` header for a document: its stylesheet as `rel=preload; as=style`, then each chunk its
72
+ * tags preload as `rel=modulepreload` — the same URLs, so a CDN's 103 Early Hint starts exactly the
73
+ * fetches the document would. `undefined` when there is nothing to hint.
74
+ */
75
+ export function linkHeader(
76
+ stylesheet: string | undefined,
77
+ modules: readonly string[],
78
+ ): string | undefined {
79
+ // Each URL screened BEFORE it is wrapped: read back out of the link, a URL holding its own `>;`
80
+ // passed on its first half and carried a second link to another origin in the rest.
81
+ const sheet = stylesheet !== undefined && HEADER_SAFE_URL.test(stylesheet) ? [stylesheet] : [];
82
+ const links = [
83
+ ...sheet.map((url) => `<${url}>; rel=preload; as=style`),
84
+ ...modules
85
+ .filter((url) => HEADER_SAFE_URL.test(url))
86
+ .map((url) => `<${url}>; rel=modulepreload`),
87
+ ];
88
+ return links.length === 0 ? undefined : links.join(', ');
46
89
  }
@@ -28,8 +28,8 @@ const declared = (): ReadonlyMap<string, AdminApp> => {
28
28
  return held instanceof Map ? (held as ReadonlyMap<string, AdminApp>) : new Map();
29
29
  };
30
30
 
31
- export interface AdminMountOptions
32
- extends Pick<DocumentOptions, 'themeHead' | 'brandHead' | 'origin'> {
31
+ // The brand restyles the admin through the `app/` stylesheet a screen links (`style-bundle.ts`).
32
+ export interface AdminMountOptions extends Pick<DocumentOptions, 'themeHead' | 'origin'> {
33
33
  readonly buildId: string;
34
34
  }
35
35
 
@@ -107,8 +107,6 @@ async function answer(
107
107
  () =>
108
108
  routeDocument(entry, data, {
109
109
  ...(options.themeHead === undefined ? {} : { themeHead: options.themeHead }),
110
- // The app's brand restyles its admin too: a screen is a document of the `app/` surface.
111
- ...(options.brandHead === undefined ? {} : { brandHead: options.brandHead }),
112
110
  ...(options.origin === undefined ? {} : { origin: options.origin }),
113
111
  }),
114
112
  { buildId: options.buildId, status: response.status },
@@ -27,7 +27,7 @@ import { routeQuery } from './isr-query-guard';
27
27
  import { navigationTagsOf } from './page-navigation';
28
28
  import { servedPins } from './page-pins';
29
29
  import { bootScript, collectorFor } from './route-islands';
30
- import { preloadTags } from './route-islands-preload';
30
+ import { linkHeader, preloadTagsOf, preloadUrls } from './route-islands-preload';
31
31
  import { siteAssetTable } from './site-assets';
32
32
  import { styleBundle } from './style-bundle';
33
33
 
@@ -137,13 +137,16 @@ export const headFor = async (
137
137
  * `styleRoutes` serves from.
138
138
  */
139
139
  const styleTag = (entry: RouteEntry): string => {
140
- const href = styleBundle().hrefFor(entry.surface);
140
+ const href = stylesheetOf(entry);
141
141
  return href === undefined ? '' : `<link rel="stylesheet" href="${href}">`;
142
142
  };
143
143
 
144
- /** The surface stylesheet, then the app's brand — the order that lets the brand win the cascade. */
145
- export const stylesFor = (entry: RouteEntry, options: DocumentOptions): string =>
146
- styleTag(entry) + (options.brandHead ?? '');
144
+ /** The surface stylesheet's URL: what `styleTag` links and what the `Link` header preloads. */
145
+ export const stylesheetOf = (entry: RouteEntry): string | undefined =>
146
+ styleBundle().hrefFor(entry.surface);
147
+
148
+ /** The surface stylesheet — whose tail is the app's brand (`style-bundle.ts`), so it wins ties. */
149
+ export const stylesFor = (entry: RouteEntry): string => styleTag(entry);
147
150
 
148
151
  /**
149
152
  * The route's rendered body, inside the hydration root. Every mode goes through here — an empty
@@ -177,6 +180,12 @@ export async function routeBody(
177
180
  return `<div id="${ROOT_ELEMENT_ID}">${html}</div>`;
178
181
  }
179
182
 
183
+ /** A buffered document, and the `Link` header naming what its tags fetch early. */
184
+ export interface RenderedDocument {
185
+ readonly html: string;
186
+ readonly link: string | undefined;
187
+ }
188
+
180
189
  /**
181
190
  * The document from data ALREADY resolved. Split from `routeDocument` so one request resolves
182
191
  * `load` exactly once: `stream` renders head and body separately, and resolving in each would let
@@ -184,24 +193,36 @@ export async function routeBody(
184
193
  *
185
194
  * The hydration runtime is appended after the body and only after it: what strategies a page needs
186
195
  * is a fact about the islands the walk just recorded, so emitting it earlier would guess or ship
187
- * the whole runtime to a page with no island.
196
+ * the whole runtime to a page with no island. The `Link` header is read off the same two values
197
+ * the tags are written from — the stylesheet's href and the preload set — never off the markup.
188
198
  */
189
- export async function documentFrom(
199
+ export async function renderedDocument(
190
200
  entry: RouteEntry,
191
201
  ctx: DevRouteData,
192
202
  data: RouteData,
193
203
  options: RenderOptions,
194
204
  scope?: string,
195
- ): Promise<string> {
205
+ ): Promise<RenderedDocument> {
196
206
  const islands = collectorFor(entry, options, scope);
197
207
  const [head, body] = await Promise.all([
198
208
  headFor(entry, ctx, data, options, scope),
199
209
  routeBody(entry, ctx, data, islands),
200
210
  ]);
201
211
  const boot = bootScript(entry, islands, options, scope);
202
- const preloads = preloadTags(entry, islands, options, boot !== '');
203
- return (
204
- `<!doctype html><html lang="${lang()}"><head>${head}${stylesFor(entry, options)}</head>` +
205
- `<body>${body}${boot}${preloads}${hydrateRuntime(islands.directives)}</body></html>`
206
- );
212
+ const preloads = preloadUrls(entry, islands, options, boot !== '');
213
+ const html =
214
+ `<!doctype html><html lang="${lang()}"><head>${head}${stylesFor(entry)}</head>` +
215
+ `<body>${body}${boot}${preloadTagsOf(preloads)}${hydrateRuntime(islands.directives)}</body></html>`;
216
+ return { html, link: linkHeader(stylesheetOf(entry), preloads) };
217
+ }
218
+
219
+ /** `renderedDocument`'s markup alone: the prerender and the budgets weigh this. */
220
+ export async function documentFrom(
221
+ entry: RouteEntry,
222
+ ctx: DevRouteData,
223
+ data: RouteData,
224
+ options: RenderOptions,
225
+ scope?: string,
226
+ ): Promise<string> {
227
+ return (await renderedDocument(entry, ctx, data, options, scope)).html;
207
228
  }
@@ -15,7 +15,6 @@ import type {
15
15
  } from '@ultimat3/http';
16
16
  import {
17
17
  asCtx,
18
- html,
19
18
  NO_STORE,
20
19
  redirect,
21
20
  stream,
@@ -44,12 +43,21 @@ import {
44
43
  navigationMetaOf,
45
44
  principalRelocation,
46
45
  } from './page-navigation';
47
- import { collectorFor, streamScripts } from './route-islands';
46
+ import { bootScript, collectorFor, streamScripts } from './route-islands';
47
+ import { linkHeader, preloadUrls } from './route-islands-preload';
48
48
  import { addressedUrl } from './runtime-address';
49
49
  import { attachedIsr } from './runtime-isr';
50
50
  import { isrOutcome } from './runtime-isr-outcome';
51
51
  import type { DevRouteData, RenderOptions } from './runtime-render-document';
52
- import { documentFrom, headFor, lang, routeBody, stylesFor } from './runtime-render-document';
52
+ import {
53
+ documentFrom,
54
+ headFor,
55
+ lang,
56
+ renderedDocument,
57
+ routeBody,
58
+ stylesFor,
59
+ stylesheetOf,
60
+ } from './runtime-render-document';
53
61
  import type { StaticResult } from './static-document';
54
62
  import { createStaticMemo, staticMemoKey, staticResponse } from './static-document';
55
63
  import { enterHole } from './stream-hole-scope';
@@ -132,8 +140,11 @@ async function resultFor(
132
140
  case 'static': {
133
141
  // Not `renderStatic`: that enumerates every prerendered path for the build. A request
134
142
  // names exactly one, and it earns the same content-hashed headers.
135
- const body = await documentFrom(entry, request, data, options);
136
- return { status, headers: staticHeaders(contentHash(body), options.buildId), body };
143
+ const { html: body, link } = await renderedDocument(entry, request, data, options);
144
+ return withLink(
145
+ { status, headers: staticHeaders(contentHash(body), options.buildId), body },
146
+ link,
147
+ );
137
148
  }
138
149
  case 'stream': {
139
150
  // Everything outside a `<Hole>` is the first flush; every hole fills after it, in the
@@ -148,18 +159,24 @@ async function resultFor(
148
159
  routeBody(entry, request, data, islands, sink),
149
160
  ]);
150
161
  const scripts = streamScripts(entry, islands, options, scope, sink.holes.length > 0);
162
+ // The first flush's tags, recomputed from the same recorded islands: the headers leave first.
163
+ const booted = bootScript(entry, islands, options, scope) !== '';
164
+ const link = linkHeader(stylesheetOf(entry), preloadUrls(entry, islands, options, booted));
151
165
  return withScope(
152
- streamResult(
153
- {
154
- head: `<!doctype html><html lang="${lang()}"><head>${head}${stylesFor(entry, options)}</head><body>`,
155
- // The runtime rides the first flush, with the shell it boots. A later chunk would leave
156
- // the window between flush one and the close with inert islands and no listeners on
157
- // them — the first-click-lost failure `interaction` replay exists for.
158
- shell: `${shell}${scripts.first}`,
159
- holes: sink.holes.map((hole) => ({ ...hole, after: scripts.after })),
160
- },
161
- { buildId: options.buildId },
162
- status,
166
+ withLink(
167
+ streamResult(
168
+ {
169
+ head: `<!doctype html><html lang="${lang()}"><head>${head}${stylesFor(entry)}</head><body>`,
170
+ // The runtime rides the first flush, with the shell it boots. A later chunk would leave
171
+ // the window between flush one and the close with inert islands and no listeners on
172
+ // them — the first-click-lost failure `interaction` replay exists for.
173
+ shell: `${shell}${scripts.first}`,
174
+ holes: sink.holes.map((hole) => ({ ...hole, after: scripts.after })),
175
+ },
176
+ { buildId: options.buildId },
177
+ status,
178
+ ),
179
+ link,
163
180
  ),
164
181
  scope,
165
182
  );
@@ -169,18 +186,25 @@ async function resultFor(
169
186
  // scope; an ungated one is `public, s-maxage` and a CDN may hand it to anyone, so it carries
170
187
  // none — absent, which core reads as "not rendered for anyone", never as anonymous.
171
188
  const scope = documentScope(entry, options.buildId, ctx.actor);
172
- return withScope(
173
- await renderSsr(
174
- { entry, params: request.params, url, ctx },
175
- () => documentFrom(entry, request, data, options, scope),
176
- { buildId: options.buildId, status },
177
- ),
178
- scope,
189
+ let link: string | undefined;
190
+ const result = await renderSsr(
191
+ { entry, params: request.params, url, ctx },
192
+ async () => {
193
+ const rendered = await renderedDocument(entry, request, data, options, scope);
194
+ link = rendered.link;
195
+ return rendered.html;
196
+ },
197
+ { buildId: options.buildId, status },
179
198
  );
199
+ return withScope(withLink(result, link), scope);
180
200
  }
181
201
  }
182
202
  }
183
203
 
204
+ /** The document's early fetches as a `Link` header (`route-islands-preload.ts`), when it has any. */
205
+ const withLink = (result: RenderResult, link: string | undefined): RenderResult =>
206
+ link === undefined ? result : { ...result, headers: { ...result.headers, link } };
207
+
184
208
  /**
185
209
  * A private document's scope, as a RESPONSE header too: the service worker partitions its offline
186
210
  * pages by principal and never parses HTML, so the meta alone cannot reach it.
@@ -200,9 +224,13 @@ function loadRedirect(entry: RouteEntry, to: RedirectIntent): Response {
200
224
  if (entry.config.cache === undefined) response.headers.set('cache-control', 'private, no-store');
201
225
  return response;
202
226
  }
203
- const responseOf = (result: RenderResult): Response =>
227
+ /**
228
+ * A buffered document answers through `staticResponse`, so a 200 carrying a validator (`ssr`'s
229
+ * cacheable pages, `isr`'s) is a 304 to a request that names it, as a `static` page always was.
230
+ */
231
+ const responseOf = (request: UltimateRequest, result: RenderResult): Response =>
204
232
  typeof result.body === 'string'
205
- ? html(result.body, { status: result.status, headers: result.headers })
233
+ ? staticResponse(request, { ...result, body: result.body })
206
234
  : stream(result.body, { status: result.status, headers: result.headers });
207
235
 
208
236
  /** `auth` follows the route's own guard: a gated page is gated in dev by the production stage. */
@@ -273,7 +301,7 @@ export function appRoutes(options: DevRenderOptions): readonly Route[] {
273
301
  const rendered = shared.document !== undefined || led ? shared : await render();
274
302
  // The ETag was only ever a header: a matching `If-None-Match` is a 304, not the page again.
275
303
  return rendered.document === undefined
276
- ? rendered.respond()
304
+ ? rendered.respond(request)
277
305
  : staticResponse(request, rendered.document);
278
306
  },
279
307
  }));
@@ -282,7 +310,7 @@ export function appRoutes(options: DevRenderOptions): readonly Route[] {
282
310
  /** A static document a joined request can share, or how to answer when there is none. */
283
311
  interface Rendered {
284
312
  readonly document?: StaticResult;
285
- readonly respond: () => Response;
313
+ readonly respond: (request: UltimateRequest) => Response;
286
314
  }
287
315
 
288
316
  async function renderEntry(
@@ -321,10 +349,10 @@ async function loadAndRender(
321
349
  if (to !== undefined) return { respond: () => loadRedirect(entry, to) };
322
350
  const result = await resultFor(entry, data, loaded, options, asCtx(ctx));
323
351
  if (entry.config.render !== 'static' || typeof result.body !== 'string') {
324
- return { respond: () => responseOf(result) };
352
+ return { respond: (request) => responseOf(request, result) };
325
353
  }
326
354
  const document: StaticResult = { ...result, body: result.body };
327
- return { document, respond: () => responseOf(document) };
355
+ return { document, respond: (request) => responseOf(request, document) };
328
356
  }
329
357
 
330
358
  /** `isr`'s outcome (`runtime-isr-outcome.ts`) as this file's answer: a page, or the redirect. */
@@ -346,5 +374,5 @@ async function renderIsr(
346
374
  origin: options.origin,
347
375
  });
348
376
  if (outcome.kind === 'redirect') return { respond: () => loadRedirect(entry, outcome.to) };
349
- return { respond: () => responseOf(outcome.result) };
377
+ return { respond: (request) => responseOf(request, outcome.result) };
350
378
  }
package/src/serve-web.ts CHANGED
@@ -47,7 +47,7 @@ export interface WebSurface {
47
47
  readonly routes: readonly Route[];
48
48
  /** The theme boot and the speculation rules: the two inline bodies every document may carry. */
49
49
  readonly inlineScripts: readonly string[];
50
- /** The app's error pages' and its brand's `<style>` bodies, which the enforced policy admits. */
50
+ /** The app's error pages' `<style>` bodies, which the enforced policy admits. */
51
51
  readonly inlineStyles: readonly string[];
52
52
  /** Where a browser that opened a guarded page is sent — the declaration `x dev` reads. */
53
53
  readonly signInPath: string | null;
@@ -71,8 +71,9 @@ export async function webSurface(
71
71
  // prevent, and it is the one an operator cannot see without installing the app.
72
72
  const pwa = await loadPwaArtifacts(options.root);
73
73
  const theme = themeBoot(await loadThemeMode(options.root));
74
- // The app's brand (`apps/web/shared/theme.ts`), or nothing: the same reader `x dev` calls.
75
- const brand = await loadThemeBrand(options.root);
74
+ // The app's brand (`apps/web/shared/theme.ts`) onto every surface stylesheet, before the first
75
+ // `styleBundle()` below: the same reader `x dev` calls, so both link one sheet.
76
+ await loadThemeBrand(options.root);
76
77
  // `site.origin` and `seo.robots.disallow`: the absolute URLs every document and the sitemap carry.
77
78
  const site = await loadSiteSettings(options.root);
78
79
  const origin = publicOrigin(options.env, site);
@@ -180,7 +181,6 @@ export async function webSurface(
180
181
  ...adminMountRoutes({
181
182
  buildId: buildId,
182
183
  themeHead: theme.head,
183
- ...(brand === undefined ? {} : { brandHead: brand.head }),
184
184
  ...(origin === undefined ? {} : { origin }),
185
185
  }),
186
186
  ...appRoutes({
@@ -193,7 +193,6 @@ export async function webSurface(
193
193
  persisted: sync.persisted,
194
194
  ...(navigation.head === undefined ? {} : { navigation: navigation.head }),
195
195
  themeHead: theme.head,
196
- ...(brand === undefined ? {} : { brandHead: brand.head }),
197
196
  ...(speculation === undefined ? {} : { speculationHead: speculation.head }),
198
197
  // A `static` page is the same bytes for every request of this process: rendered once.
199
198
  memoStatic: true,
@@ -213,12 +212,10 @@ export async function webSurface(
213
212
  ...(speculation === undefined ? [] : [speculation.cspSource]),
214
213
  ...(zone === undefined ? [] : [zone.cspSource]),
215
214
  ],
216
- // The enforced policy this process sends must admit the app's own error pages' `<style>` and
217
- // the brand's; `x dev` is report-only, so only here was a missing hash an unstyled page.
218
- inlineStyles: [
219
- ...(await errorPageStyleBodies(options.root)),
220
- ...(brand === undefined ? [] : [brand.style]),
221
- ],
215
+ // The enforced policy this process sends must admit the app's own error pages' `<style>`;
216
+ // `x dev` is report-only, so only here was a missing hash an unstyled page. The brand is in
217
+ // the surface stylesheet, which `'self'` admits: no hash.
218
+ inlineStyles: await errorPageStyleBodies(options.root),
222
219
  // Same declaration `x dev` reads. Without it a container answers a browser that opened a
223
220
  // guarded page with the problem document, rendered as raw JSON in the viewport.
224
221
  signInPath: await loadSignInPath(options.root),
@@ -1,11 +1,17 @@
1
1
  // Single responsibility: the image variants a static export's documents promise, as FILES. While
2
- // the export renders, `responsiveImage` asks this module for each variant's URL — `/_img/<source
2
+ // the export renders, `responsiveImage` asks this module for each variant's URL — `/_img/<variant
3
3
  // hash>-<width>.<ext>` — and after it, every URL an exported document names is decoded, resized
4
4
  // and written through core's pipeline. A dumb file server then answers `image/webp` for a webp.
5
5
 
6
6
  // why: Bun exposes no path-join primitive, and every variant path is relative to the export root.
7
7
  import { join } from 'node:path';
8
- import { canEncode, imageUnsupported, sniffImageFormat, transformImageBytes } from '@ultimat3/core';
8
+ import {
9
+ canEncode,
10
+ frameworkVersion,
11
+ imageUnsupported,
12
+ sniffImageFormat,
13
+ transformImageBytes,
14
+ } from '@ultimat3/core';
9
15
  import { contentHash } from '@ultimat3/render/server';
10
16
  import type { StaticImageRequest } from '@ultimat3/seo';
11
17
  import { ImageSourceUnreadableError } from './static-capture-errors';
@@ -72,7 +78,19 @@ async function indexSources(out: string): Promise<ReadonlyMap<string, Source>> {
72
78
  return sources;
73
79
  }
74
80
 
75
- export async function staticImages(out: string): Promise<StaticImages> {
81
+ /**
82
+ * What re-encodes a variant: core's raster pipeline over Bun's image codecs. The URL is minted
83
+ * during the render and the bytes are encoded after it — the documents are hashed by then, so
84
+ * the name cannot be the output's own hash (#1075's rule for islands). It is the hash of
85
+ * everything those bytes are a function of instead: one URL is one byte string, and an upgrade
86
+ * that may re-encode costs one cache miss, never an `immutable` file holding other bytes.
87
+ */
88
+ export const imageEncoderIdentity = (): string => `${frameworkVersion()}+bun${Bun.version}`;
89
+
90
+ export async function staticImages(
91
+ out: string,
92
+ encoder: string = imageEncoderIdentity(),
93
+ ): Promise<StaticImages> {
76
94
  const sources = await indexSources(out);
77
95
  const variants = new Map<string, Variant>();
78
96
  return {
@@ -80,7 +98,10 @@ export async function staticImages(out: string): Promise<StaticImages> {
80
98
  const source = sources.get(pathOf(src));
81
99
  const resolved = format ?? source?.ownFormat ?? 'png';
82
100
  // A src the export lacks still gets a stable URL, so `write` can tell which document named it.
83
- const stem = source === undefined ? `missing-${contentHash(src)}` : source.hash;
101
+ const stem =
102
+ source === undefined
103
+ ? `missing-${contentHash(src)}`
104
+ : contentHash(JSON.stringify([source.hash, width, resolved, encoder]));
84
105
  const url = `/${STATIC_IMAGE_DIR}/${stem}-${String(width)}.${EXTENSION.get(resolved) ?? resolved}`;
85
106
  variants.set(url, { src, width, source, format: resolved });
86
107
  return url;
@@ -0,0 +1,57 @@
1
+ // The `.br` and `.gz` siblings a static export writes beside each immutable asset — every island
2
+ // chunk and surface stylesheet — so a static host serves them coded with no CPU per hit. The coders
3
+ // are `@ultimat3/http`'s `PRECODERS` (brotli 11, gzip 9): the bytes the served process precodes.
4
+
5
+ // why: Bun exposes no path-join primitive; the URL is joined onto the export directory.
6
+ import { join } from 'node:path';
7
+ import { PRECODERS } from '@ultimat3/http';
8
+
9
+ /** The codings a static host reads siblings for, with the suffix each is written under. */
10
+ export const STATIC_PRECODINGS = [
11
+ { coding: 'br', suffix: '.br' },
12
+ { coding: 'gzip', suffix: '.gz' },
13
+ ] as const;
14
+
15
+ /**
16
+ * Below this a coding's framing eats what it saves — `COMPRESS_MIN_BYTES`' reason, and its value:
17
+ * the served process codes nothing under 1 KiB either, so the export does not pretend to.
18
+ */
19
+ export const STATIC_PRECOMPRESS_MIN_BYTES = 1_024;
20
+
21
+ /** The URLs a static export writes that are named by their bytes: every chunk, every sheet. */
22
+ export const immutableUrls = (
23
+ islands: { readonly chunks: readonly HasUrl[]; readonly shared: readonly HasUrl[] },
24
+ styles: { readonly chunks: readonly HasUrl[] },
25
+ ): readonly string[] => [...islands.chunks, ...islands.shared, ...styles.chunks].map((c) => c.url);
26
+
27
+ interface HasUrl {
28
+ readonly url: string;
29
+ }
30
+
31
+ const plain = (bytes: Uint8Array): Uint8Array<ArrayBuffer> =>
32
+ bytes.buffer instanceof ArrayBuffer ? (bytes as Uint8Array<ArrayBuffer>) : new Uint8Array(bytes);
33
+
34
+ /**
35
+ * Each URL's file under `out`, coded into its siblings — the file itself is already there. All at
36
+ * once: the coders run on the thread pool, so a build with 40 chunks waits for the slowest. A
37
+ * sibling no smaller than its source is not written: a host would serve more bytes, not fewer.
38
+ */
39
+ export async function writePrecompressed(out: string, urls: readonly string[]): Promise<number> {
40
+ const counts = await Promise.all(
41
+ urls.map(async (url) => {
42
+ const path = join(out, url.slice(1));
43
+ const bytes = plain(await Bun.file(path).bytes());
44
+ if (bytes.byteLength < STATIC_PRECOMPRESS_MIN_BYTES) return 0;
45
+ const coded = await Promise.all(
46
+ STATIC_PRECODINGS.map(async ({ coding, suffix }) => {
47
+ const body = await PRECODERS[coding](bytes);
48
+ if (body.byteLength >= bytes.byteLength) return 0;
49
+ await Bun.write(`${path}${suffix}`, body);
50
+ return 1;
51
+ }),
52
+ );
53
+ return coded.reduce<number>((sum, one) => sum + one, 0);
54
+ }),
55
+ );
56
+ return counts.reduce<number>((sum, one) => sum + one, 0);
57
+ }
@@ -67,15 +67,37 @@ const surfaceKey = (surface: Surface | null): Surface => surface ?? 'shared';
67
67
  * Memoised on that revision rather than recomputed per request, because the derivation is a filter
68
68
  * over every registered sheet plus a hash of the ~150 kB it joins.
69
69
  */
70
- let memo: { readonly revision: number; readonly bundle: StyleBundle } | undefined;
70
+ let memo:
71
+ | { readonly revision: number; readonly brand: string; readonly bundle: StyleBundle }
72
+ | undefined;
73
+
74
+ /**
75
+ * The app's brand (`theme-brand.ts`), LAST in every surface sheet. It was an inline `<style>` right
76
+ * after the `<link>`, so the cascade saw the sheet's rules then the brand's; appended to the same
77
+ * file, it sees exactly that sequence — and the 6,130 bytes are fetched once and cached
78
+ * `immutable`, not re-sent in every document (the demo's exported `/`, 2026-11-12: 18,389 →
79
+ * 12,244 B; each sheet +6,131 B). Process-global for the registry's reason: loading the theme
80
+ * module is what fills it.
81
+ */
82
+ let brand = '';
83
+
84
+ /** Called by `loadThemeBrand` alone; `''` clears it, so a second app in one process has none. */
85
+ export function setBrandStyles(css: string): void {
86
+ brand = css;
87
+ }
88
+
89
+ /** A surface's sheets, then the brand. The newline keeps a sheet's last token off the brand's. */
90
+ export const withBrand = (css: string, brandCss: string): string =>
91
+ brandCss.length === 0 ? css : css.length === 0 ? brandCss : `${css}\n${brandCss}`;
71
92
 
72
93
  export function styleBundle(): StyleBundle {
73
94
  const revision = stylesheetsRevision();
74
- if (memo !== undefined && memo.revision === revision) return memo.bundle;
95
+ if (memo !== undefined && memo.revision === revision && memo.brand === brand) return memo.bundle;
75
96
  const current = styleBundleOf(
76
- STYLED_SURFACES.map((surface) => ({ surface, css: stylesFor(surface) })).filter(
77
- (sheet) => sheet.css.length > 0,
78
- ),
97
+ STYLED_SURFACES.map((surface) => ({
98
+ surface,
99
+ css: withBrand(stylesFor(surface), brand),
100
+ })).filter((sheet) => sheet.css.length > 0),
79
101
  );
80
102
  for (const chunk of current.chunks) {
81
103
  minted.delete(chunk.url);
@@ -90,7 +112,7 @@ export function styleBundle(): StyleBundle {
90
112
  ...current,
91
113
  chunkAt: (url: string): StyleChunk | undefined => current.chunkAt(url) ?? minted.get(url),
92
114
  };
93
- memo = { revision, bundle };
115
+ memo = { revision, brand, bundle };
94
116
  return bundle;
95
117
  }
96
118