@ultimat3/cli 31.13.1 → 31.15.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 (49) hide show
  1. package/CLAUDE.md +1 -1
  2. package/README.md +2 -1
  3. package/package.json +29 -29
  4. package/src/budgets-requests.ts +37 -0
  5. package/src/budgets.ts +20 -1
  6. package/src/dev-boot.ts +2 -2
  7. package/src/dev-route-table.ts +5 -9
  8. package/src/document-options.ts +0 -7
  9. package/src/island-bundle.ts +52 -12
  10. package/src/island-disposer.ts +1 -1
  11. package/src/island-group-cache.ts +4 -0
  12. package/src/island-link-check.ts +73 -0
  13. package/src/island-realtime.ts +9 -3
  14. package/src/island-vendor.ts +183 -0
  15. package/src/job-registration.ts +10 -14
  16. package/src/mcp-errors.ts +1 -1
  17. package/src/prerender.ts +7 -7
  18. package/src/route-islands-preload.ts +54 -11
  19. package/src/runtime-admin.ts +2 -4
  20. package/src/runtime-render-document.ts +34 -13
  21. package/src/runtime-render.ts +58 -30
  22. package/src/serve-web.ts +8 -11
  23. package/src/static-images.ts +25 -4
  24. package/src/static-precompress.ts +57 -0
  25. package/src/style-bundle.ts +28 -6
  26. package/src/templates/guard-island-mount-clears.ts +151 -0
  27. package/src/templates/guard-raw-interval.ts +3 -2
  28. package/src/templates/island.ts +8 -7
  29. package/src/templates/resource-form-island.ts +12 -9
  30. package/src/templates/scaffold-docs.ts +2 -1
  31. package/src/templates/scaffold-guards.ts +4 -1
  32. package/src/templates/scaffold-shell.ts +12 -9
  33. package/src/theme-brand.ts +18 -20
  34. package/wiki/Client-Data.md +54 -2
  35. package/wiki/Configuration.md +1 -0
  36. package/wiki/Home.md +3 -3
  37. package/wiki/Jobs-And-Workflows.md +48 -6
  38. package/wiki/Known-Gaps.md +4 -3
  39. package/wiki/MCP-And-AI.md +42 -1
  40. package/wiki/Notify.md +6 -0
  41. package/wiki/PWA-And-Offline.md +11 -0
  42. package/wiki/Queries-And-Live-Queries.md +1 -1
  43. package/wiki/Realtime.md +28 -7
  44. package/wiki/SEO.md +1 -1
  45. package/wiki/Scheduled-Tasks.md +36 -0
  46. package/wiki/Scraping.md +3 -1
  47. package/wiki/Static-Assets.md +30 -3
  48. package/wiki/Theming.md +6 -6
  49. package/wiki/Upgrading.md +16 -0
@@ -0,0 +1,183 @@
1
+ // Solid as ONE output beside the islands: `vendor-solid.<contentHash>.js`, re-exporting `solid-js`,
2
+ // `solid-js/web` and `solid-js/store` whole, once per `buildIslands` call. Every island resolves
3
+ // them to it as an external, so three islands built apart download one Solid. Its bytes move with
4
+ // a Solid install, never an island edit, so no island's change re-names the file the rest import.
5
+
6
+ // why: Bun ships no path API; the vendor's URL is basePath joined to its file name.
7
+ import { posix } from 'node:path';
8
+ import { contentHash } from '@ultimat3/render/server';
9
+ import type { BunPlugin } from 'bun';
10
+ import { IslandBuildFailedError } from './errors';
11
+ import type { IslandChunk, SharedChunk } from './island-bundle';
12
+ import { inputFiles } from './island-cache-inputs';
13
+ import { describeBuildError, stableChunk, stripDebugId } from './island-identity';
14
+ import { frameworkDedupePlugins } from './island-package-dedupe';
15
+ import { solidDedupePlugin } from './island-solid-dedupe';
16
+
17
+ /**
18
+ * The specifiers the vendor answers. `solid-js/h`, `/html` and `/universal` stay bundled into the
19
+ * island that asks: rare, and each imports `solid-js/web`, which then resolves here.
20
+ */
21
+ export const VENDOR_SPECIFIER = /^solid-js(?:\/web|\/store)?$/;
22
+
23
+ /**
24
+ * The vendor entry. `DEV` is exported by both `solid-js` and `solid-js/store`, and two star
25
+ * exports of one name export NEITHER (measured on 1.9.17: 121 names, `DEV` missing) — an island
26
+ * importing it would fail to link in the browser. The explicit export wins over both stars; under
27
+ * the production condition both are `undefined`.
28
+ */
29
+ const VENDOR_SOURCE = [
30
+ `export * from 'solid-js';`,
31
+ `export * from 'solid-js/web';`,
32
+ `export * from 'solid-js/store';`,
33
+ `export { DEV } from 'solid-js';`,
34
+ '',
35
+ ].join('\n');
36
+
37
+ const ENTRY = 'ultimate:vendor-solid';
38
+ const NAMESPACE = 'ultimate-vendor-solid';
39
+
40
+ /**
41
+ * `vendor-solid.<identity>.js` — the dot, as `page-runtime.<identity>.js` has it: a module id is
42
+ * `[a-z0-9-]` only, so no island entry (`<moduleId>-<identity>.js`) can be served at this name.
43
+ */
44
+ const VENDOR_FILE = /^vendor-solid\.[0-9a-z]+\.js$/;
45
+
46
+ /** Whether `url` (any base path) is the Solid vendor chunk — the one predicate, never a prefix. */
47
+ export function isVendorChunk(url: string): boolean {
48
+ return VENDOR_FILE.test(posix.basename(url));
49
+ }
50
+
51
+ export interface VendorChunk {
52
+ readonly url: string;
53
+ /** `./vendor-solid.<identity>.js`: what an island's code imports, resolved beside it. */
54
+ readonly specifier: string;
55
+ readonly code: string;
56
+ readonly bytes: number;
57
+ /** Every file the vendor's build read, absolute (`inputFiles`): what a cached group rehashes. */
58
+ readonly inputs: readonly string[];
59
+ }
60
+
61
+ /** The vendor a build's islands import — built at most once per `buildIslands` call. */
62
+ export type Vendors = () => Promise<VendorChunk>;
63
+
64
+ export function vendorBuilder(root: string, basePath: string): Vendors {
65
+ let built: Promise<VendorChunk> | undefined;
66
+ return () => {
67
+ built ??= buildVendor(root, basePath);
68
+ return built;
69
+ };
70
+ }
71
+
72
+ async function buildVendor(root: string, basePath: string): Promise<VendorChunk> {
73
+ let built: Awaited<ReturnType<typeof Bun.build>>;
74
+ try {
75
+ built = await Bun.build({
76
+ entrypoints: [ENTRY],
77
+ root,
78
+ target: 'browser',
79
+ format: 'esm',
80
+ minify: true,
81
+ // The app's one Solid copy (`island-solid-dedupe.ts`) — the copy every island was built
82
+ // against before this file existed — under `island-bundle.ts`'s production `define`.
83
+ plugins: [vendorEntryPlugin(), solidDedupePlugin(root), ...frameworkDedupePlugins(root)],
84
+ define: { 'process.env.NODE_ENV': '"production"' },
85
+ metafile: true,
86
+ });
87
+ } catch (error) {
88
+ throw new IslandBuildFailedError({ file: 'solid-js', logs: describeBuildError(error) });
89
+ }
90
+ const output = built.outputs.find((artifact) => artifact.kind === 'entry-point');
91
+ if (!built.success || output === undefined) {
92
+ throw new IslandBuildFailedError({
93
+ file: 'solid-js',
94
+ logs: built.logs.map((log) => String(log)).join('; '),
95
+ });
96
+ }
97
+ // Named by its bytes (#1075), as every island output is: `immutable` is a promise about them.
98
+ const code = stripDebugId(await output.text());
99
+ const identity = contentHash(code);
100
+ const name = `vendor-solid.${identity}.js`;
101
+ const url = `${basePath}/${name}`;
102
+ return {
103
+ url,
104
+ specifier: `./${name}`,
105
+ ...stableChunk(url, identity, code),
106
+ inputs: await inputFiles(Object.keys(built.metafile?.inputs ?? {})),
107
+ };
108
+ }
109
+
110
+ function vendorEntryPlugin(): BunPlugin {
111
+ return {
112
+ name: 'ultimate-vendor-solid-entry',
113
+ setup(build) {
114
+ build.onResolve({ filter: /^ultimate:vendor-solid$/ }, () => ({
115
+ path: 'entry',
116
+ namespace: NAMESPACE,
117
+ }));
118
+ build.onLoad({ filter: /.*/, namespace: NAMESPACE }, () => ({
119
+ contents: VENDOR_SOURCE,
120
+ loader: 'js',
121
+ }));
122
+ },
123
+ };
124
+ }
125
+
126
+ /**
127
+ * The island-side half: every vendored specifier, from any file of the island's graph, is the
128
+ * vendor's relative URL, left external. Installed FIRST, ahead of the Solid dedupe, so no Solid
129
+ * file is ever read into an island chunk.
130
+ */
131
+ export function vendorExternalPlugin(vendor: VendorChunk): BunPlugin {
132
+ return {
133
+ name: 'ultimate-vendor-solid-external',
134
+ setup(build) {
135
+ build.onResolve({ filter: VENDOR_SPECIFIER }, () => ({
136
+ path: vendor.specifier,
137
+ external: true,
138
+ }));
139
+ },
140
+ };
141
+ }
142
+
143
+ /** Whether `code` imports the vendor — statically or by `import()`. */
144
+ function importsVendor(code: string, vendor: VendorChunk): boolean {
145
+ return new Bun.Transpiler({ loader: 'js' })
146
+ .scan(code)
147
+ .imports.some((one) => one.path === vendor.specifier);
148
+ }
149
+
150
+ /**
151
+ * Every entry whose own code or a shared chunk it loads imports the vendor names it among its
152
+ * `imports`, so a precache, a preload and a budget count it — once, by URL.
153
+ */
154
+ export function loadingVendor(
155
+ chunks: readonly IslandChunk[],
156
+ shared: readonly SharedChunk[],
157
+ vendor: VendorChunk | undefined,
158
+ ): readonly IslandChunk[] {
159
+ if (vendor === undefined) return chunks;
160
+ const sharedLoads = new Set(
161
+ shared.filter((one) => importsVendor(one.code, vendor)).map((one) => one.url),
162
+ );
163
+ return chunks.map((chunk) =>
164
+ importsVendor(chunk.code, vendor) || chunk.imports.some((url) => sharedLoads.has(url))
165
+ ? { ...chunk, imports: [...new Set([...chunk.imports, vendor.url])].sort() }
166
+ : chunk,
167
+ );
168
+ }
169
+
170
+ /** The vendor as the bundle's shared asset, with the islands that load it; none, no asset. */
171
+ export function vendorShared(
172
+ vendor: VendorChunk | undefined,
173
+ chunks: readonly IslandChunk[],
174
+ ): readonly SharedChunk[] {
175
+ if (vendor === undefined) return [];
176
+ const importers = chunks
177
+ .filter((chunk) => chunk.imports.includes(vendor.url))
178
+ .map((chunk) => chunk.file)
179
+ .sort();
180
+ if (importers.length === 0) return [];
181
+ const { url, code, bytes } = vendor;
182
+ return [{ url, code, bytes, importers, sources: [] }];
183
+ }
@@ -4,7 +4,12 @@
4
4
  // declaring `partitionBy` with no `partitions()` job registered (`X_PARTITIONS_UNMAINTAINED`).
5
5
 
6
6
  import { ERROR_DOCS_URL } from '@ultimat3/core';
7
- import { partitionedEntities, registeredJobs, registeredTasks } from '@ultimat3/jobs';
7
+ import {
8
+ isPartitionsJob,
9
+ partitionedEntities,
10
+ registeredJobs,
11
+ registeredTasks,
12
+ } from '@ultimat3/jobs';
8
13
  import { loadApp } from './app-load';
9
14
  import type { AppLoader } from './app-permissions';
10
15
  import type { Finding } from './output';
@@ -48,23 +53,14 @@ export async function unregisteredJobFindings(
48
53
  ];
49
54
  }
50
55
 
51
- /** What a registered job has to look like for this rule: a name, and maybe a `.schedule` task. */
52
- interface JobShape {
53
- readonly name: string;
54
- readonly schedule?: { readonly name: string };
55
- }
56
-
57
56
  /**
58
- * Recognised by SHAPE, so a renamed `partitions({ name })` counts: the handle carries the
59
- * `.schedule` task the factory minted, named `<job>.schedule`. Nothing else does — `consumer()`
60
- * carries `.supervisor`.
57
+ * Pure: the partitioned tables and the registered jobs in, one finding when none maintains them.
58
+ * A maintainer is recognised by IDENTITY (`isPartitionsJob`), so a renamed `partitions({ name })`
59
+ * counts and a `cronJob()` — the same `<job>.schedule` shape — does not.
61
60
  */
62
- const isPartitionsJob = (job: JobShape): boolean => job.schedule?.name === `${job.name}.schedule`;
63
-
64
- /** Pure: the partitioned tables and the registered jobs in, one finding when none maintains them. */
65
61
  export function unmaintainedPartitionFindings(
66
62
  tables: readonly string[],
67
- jobs: readonly JobShape[],
63
+ jobs: readonly unknown[],
68
64
  ): readonly Finding[] {
69
65
  if (tables.length === 0 || jobs.some(isPartitionsJob)) return [];
70
66
  return [
package/src/mcp-errors.ts CHANGED
@@ -357,7 +357,7 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
357
357
  X_NEW_SHAPE_GENERATE_FAILED:
358
358
  'bunx x g sign-in --password --json # in the app x new wrote, reproduces it; then bun test ./packages/cli/src/templates/shapes',
359
359
  X_ISLAND_DISPOSER_MISSING:
360
- 'x verify --only boundaries --json # names the file; end its mount() with return render(() => <Island {...props} />, el)',
360
+ 'x verify --only boundaries --json # names the file; end its mount() with return mountOver(el, (root) => render(() => <Island {...props} />, root))',
361
361
  X_SOCKET_HAND_ROLLED:
362
362
  'x verify --only boundaries --json — names the file and line; delete the upgrade and declare the socket with deviceSocket({ path, resolveToken, onFrame }) from @ultimat3/realtime/server',
363
363
  X_EXERCISE_FILE_UNEDITABLE:
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
  }