@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
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
 
@@ -0,0 +1,151 @@
1
+ // The `island-mount-clears` guard `x new` ships: an island's `mount` never empties its wrapper
2
+ // outside `mountOver` (`@ultimat3/render/client`). An island that clears and then throws in render
3
+ // shows a blank box; `mountOver` puts the server's markup back. The guard is how an app scaffolded
4
+ // before it adopts the helper: `x g guard island-mount-clears`, then each finding's fix.
5
+
6
+ import { guardCode } from './guard';
7
+ import type { GeneratedFile } from './naming';
8
+
9
+ /** Derived from the guard's name, never a literal: an `X_*` literal here is a FRAMEWORK code. */
10
+ const NAME = 'island-mount-clears';
11
+ const CODE = guardCode(NAME);
12
+
13
+ const source =
14
+ (): string => `// island-mount-clears: an island never empties its server markup with no way back.
15
+ // \`x verify\` discovers every file in \`guards/\` and runs its \`guard\` inside the \`boundaries\`
16
+ // step — nothing registers this file, so nothing can forget to. Delete it to drop the rule.
17
+ //
18
+ // Why: a \`mount\` that empties its wrapper and then renders leaves a BLANK box when the render
19
+ // throws. \`mountOver\` from \`@ultimat3/render/client\` clears the same way, puts the server's markup
20
+ // back on a throw, and rethrows — the runtime still marks the root \`data-x-failed\` for the reporter.
21
+ // Read: \`.textContent = ''\`, \`.innerHTML = ''\` and \`.replaceChildren()\` on \`mount\`'s own wrapper (its
22
+ // first parameter) in a \`*.island.tsx\` that calls no \`mountOver(\`. Not read: a clear of an element
23
+ // inside the wrapper, a comment, a string, a test, a file that is not an island.
24
+
25
+ import type { Finding, Guard } from '@ultimat3/cli';
26
+
27
+ /** The app owns the codes its own conventions raise — this one is named for the guard. */
28
+ const CODE = '${CODE}';
29
+
30
+ export interface SourceFile {
31
+ /** App-root-relative POSIX path, so the finding names the file an author opens. */
32
+ readonly path: string;
33
+ readonly source: string;
34
+ }
35
+
36
+ /** Found on the BLANKED text, so a comment or a string never matches; the value is read below. */
37
+ const WRITE = /([\\w$]+)\\.(?:textContent|innerHTML)\\s*=(?!=)/g;
38
+ /** On the original text at a write's offset: an EMPTY literal is the clear; any other is content. */
39
+ const EMPTIES = /^[\\w$]+\\.(?:textContent|innerHTML)\\s*=\\s*(?:''|""|\`\`)/;
40
+ const REPLACE_ALL = /([\\w$]+)\\.replaceChildren\\s*\\(\\s*\\)/g;
41
+ /** \`function mount(el\` or \`mount = (el\`: the wrapper's name. None found reads \`el\`, the convention. */
42
+ const MOUNT_PARAM = /\\bmount\\s*(?:=\\s*(?:async\\s*)?)?\\(\\s*([\\w$]+)/;
43
+ const MOUNT_OVER = /(?<![\\w$.])mountOver\\s*\\(/;
44
+
45
+ /** Comments and string bodies blanked IN PLACE, so a line number still points at the source. */
46
+ const blank = (text: string): string =>
47
+ text
48
+ .replaceAll(/\\/\\*[\\s\\S]*?\\*\\//g, (match) => match.replaceAll(/[^\\n]/g, ' '))
49
+ .replaceAll(/(?<![:\\w])\\/\\/[^\\n]*/g, (match) => ' '.repeat(match.length))
50
+ .replaceAll(/'(?:[^'\\\\\\n]|\\\\.)*'|"(?:[^"\\\\\\n]|\\\\.)*"|\`(?:[^\`\\\\]|\\\\.)*\`/g, (match) =>
51
+ match.replaceAll(/[^\\n]/g, ' '),
52
+ );
53
+
54
+ /** Every offset in \`source\` that empties the WRAPPER: an empty-literal write or a bare replace. */
55
+ const clears = (source: string, text: string): readonly number[] => {
56
+ const wrapper = MOUNT_PARAM.exec(text)?.[1] ?? 'el';
57
+ return [
58
+ ...[...text.matchAll(WRITE)]
59
+ .filter((match) => match[1] === wrapper && EMPTIES.test(source.slice(match.index)))
60
+ .map((match) => match.index),
61
+ ...[...text.matchAll(REPLACE_ALL)]
62
+ .filter((match) => match[1] === wrapper)
63
+ .map((match) => match.index),
64
+ ];
65
+ };
66
+
67
+ /** Pure — the caller does the I/O — so the rule is testable without a filesystem. */
68
+ export function islandMountClears(files: readonly SourceFile[]): readonly Finding[] {
69
+ const findings: Finding[] = [];
70
+ for (const file of files) {
71
+ const text = blank(file.source);
72
+ if (MOUNT_OVER.test(text)) continue;
73
+ for (const index of [...clears(file.source, text)].sort((a, b) => a - b)) {
74
+ const at = \`\${file.path}:\${text.slice(0, index).split('\\n').length}\`;
75
+ findings.push({
76
+ code: CODE,
77
+ cause: \`\${at} empties the island's server markup outside mountOver, so a render that throws leaves a blank box where the server's HTML was, and the visitor sees nothing to retry\`,
78
+ fix: \`edit \${at} — delete the clear and end mount() with return mountOver(el, (root) => render(() => <Island {...props} />, root)), adding mountOver to the island's imports from '@ultimat3/render/client' — then: x verify\`,
79
+ at,
80
+ });
81
+ }
82
+ }
83
+ return findings;
84
+ }
85
+
86
+ /** The files the rule reads: islands, never a test. */
87
+ export const readsFile = (path: string): boolean =>
88
+ path.endsWith('.island.tsx') && !/\\.test\\.tsx?$/.test(path);
89
+
90
+ export const guard: Guard = {
91
+ summary: 'an island mounts over its server markup, never clears it with no way back',
92
+ async check(_root, sources) {
93
+ // The run's ONE read of the source: every guard asking for this glob shares the walk.
94
+ const code = await sources.files('{apps,packages}/**/*.{ts,tsx}');
95
+ return islandMountClears(
96
+ code
97
+ .filter((file) => readsFile(file.path))
98
+ .map((file) => ({ path: file.path, source: file.text })),
99
+ );
100
+ },
101
+ };
102
+ `;
103
+
104
+ const test =
105
+ (): string => `// The rule, driven directly. Failure case first: a guard whose rule silently stopped matching is
106
+ // a green gate over the convention it was written to enforce.
107
+
108
+ import { expect, unitTest } from '@ultimat3/testing';
109
+ import { islandMountClears, readsFile } from './island-mount-clears';
110
+
111
+ const file = (source: string) => [{ path: 'apps/web/app/posts/like.island.tsx', source }];
112
+
113
+ unitTest('a mount that clears its shell is refused, and the finding names the line', () => {
114
+ const findings = islandMountClears(
115
+ file("export function mount(el) {\\n el.textContent = '';\\n}"),
116
+ );
117
+ expect(findings).toHaveLength(1);
118
+ expect(findings[0]?.code).toBe('${CODE}');
119
+ expect(findings[0]?.at).toBe('apps/web/app/posts/like.island.tsx:2');
120
+ // Not an import line: an app's import audit would read a pasteable one as this file's own.
121
+ expect(findings[0]?.fix).toContain("imports from '@ultimat3/render/client'");
122
+ });
123
+
124
+ unitTest('innerHTML and a bare replaceChildren() are the same clear', () => {
125
+ expect(islandMountClears(file('el.innerHTML = "";'))).toHaveLength(1);
126
+ expect(islandMountClears(file('el.replaceChildren();'))).toHaveLength(1);
127
+ });
128
+
129
+ unitTest('mountOver, a comment, a string and a non-empty write are not refused', () => {
130
+ expect(
131
+ islandMountClears(file('return mountOver(el, (root) => render(() => <A />, root));')),
132
+ ).toEqual([]);
133
+ expect(islandMountClears(file("// el.textContent = '';"))).toEqual([]);
134
+ expect(islandMountClears(file('const s = "el.textContent = \\'\\'";'))).toEqual([]);
135
+ expect(islandMountClears(file("el.textContent = 'ready';"))).toEqual([]);
136
+ expect(islandMountClears(file('if (el.textContent === "") go();'))).toEqual([]);
137
+ });
138
+
139
+ unitTest('islands are read; their tests and other files are not', () => {
140
+ expect(readsFile('apps/web/app/posts/like.island.tsx')).toBe(true);
141
+ expect(readsFile('packages/ui/src/menu.island.tsx')).toBe(true);
142
+ expect(readsFile('apps/web/app/posts/like.island.test.tsx')).toBe(false);
143
+ expect(readsFile('apps/web/app/posts/page.tsx')).toBe(false);
144
+ });
145
+ `;
146
+
147
+ /** `guards/island-mount-clears.ts` and its test. No index, no registry — the directory registers it. */
148
+ export const islandMountClearsGuardFiles = (): readonly GeneratedFile[] => [
149
+ { path: `guards/${NAME}.ts`, contents: source() },
150
+ { path: `guards/${NAME}.test.ts`, contents: test() },
151
+ ];
@@ -18,7 +18,8 @@ const source =
18
18
  //
19
19
  // Why: a raw interval keeps asking from a background tab, and from a tab past its session it asks
20
20
  // for a 401 forever. \`visibleInterval(run, ms)\` from \`@ultimat3/core/page\` makes no call while the
21
- // tab is hidden, one when it is shown, and stops at the first lost session. Read: a bare,
21
+ // tab is hidden, one when it is shown, and stops at the first lost session; a query's re-read is
22
+ // \`useQuery(ref, input, { poll: pollEvery(ms) })\`, the same timer, built. Read: a bare,
22
23
  // \`window.\`, \`self.\` or \`globalThis.\` \`setInterval(\` in a \`*.island.tsx\`. Admitted: a \`// why:\` on
23
24
  // the call's line or the line above it — an animation tick is not a read. Not read: a bare
24
25
  // \`setInterval(\` in a file that binds its own (declared, imported, a parameter, destructured).
@@ -64,7 +65,7 @@ export function rawIntervals(files: readonly SourceFile[]): readonly Finding[] {
64
65
  findings.push({
65
66
  code: CODE,
66
67
  cause: \`\${at} polls with setInterval, which keeps asking from a hidden tab and asks for a 401 forever once the session is gone\`,
67
- fix: \`import { visibleInterval } from '@ultimat3/core/page' and call visibleInterval(run, ms) at \${at}, disposing it on cleanup — or add a // why: comment on that line naming why this interval is not a read — then: x verify\`,
68
+ fix: \`re-read a query with useQuery(ref, input, { poll: pollEvery(ms) }) (pollEvery is exported by @ultimat3/realtime) at \${at}; any other read: import { visibleInterval } from '@ultimat3/core/page' and call visibleInterval(run, ms) there, disposing it on cleanup — or add a // why: comment on that line naming why this interval is not a read — then: x verify\`,
68
69
  at,
69
70
  });
70
71
  }
@@ -34,6 +34,7 @@ const islandSource = (name: string): string => {
34
34
  // A string has no import edge, so nothing follows one into this file and the page's bundle graph
35
35
  // stays the page's (axiom 6). WHEN it wakes is the route's \`hydrate\`, never a declaration here.
36
36
 
37
+ import { mountOver } from '@ultimat3/render/client';
37
38
  import type { JSX } from 'solid-js';
38
39
  import { createSignal } from 'solid-js';
39
40
  import { render } from 'solid-js/web';
@@ -67,15 +68,15 @@ function ${Name}(props: ${Name}Props): JSX.Element {
67
68
  * The one export the hydration runtime calls — \`import(entry).then((m) => m.mount(el, props))\`.
68
69
  * \`el\` is the wrapper the page rendered, with the server's own markup already inside it.
69
70
  *
70
- * The shell is cleared first, and that line is load-bearing: Solid's \`render\` APPENDS when the
71
- * container already has children, so without it the server's markup stays on screen above a
72
- * second, live copy of the same thing.
71
+ * \`mountOver\` clears that markup for the live render (Solid's \`render\` APPENDS, so it would
72
+ * otherwise stay on screen above a second copy) and puts it BACK if the render throws: a broken
73
+ * island shows what the server sent, not a blank box, and the throw still reaches the runtime,
74
+ * which marks the root \`data-x-failed\` for the error reporter.
73
75
  */
74
76
  export function mount(el: HTMLElement, props: ${Name}Props): () => void {
75
- el.textContent = '';
76
- // Solid's \`render\` answers its disposer; returning it is what lets \`@ultimat3/testing\`
77
- // stop this island — its timers included — when a test is done with it.
78
- return render(() => <${Name} {...props} />, el);
77
+ // Solid's \`render\` answers its disposer; returning it is what lets the client router and
78
+ // \`@ultimat3/testing\` stop this island — its timers included — when they are done with it.
79
+ return mountOver(el, (root) => render(() => <${Name} {...props} />, root));
79
80
  }
80
81
  `;
81
82
  };
@@ -40,6 +40,7 @@ const formIslandSource = (
40
40
 
41
41
  import { clientTransport } from '@ultimat3/core';
42
42
  import { fromDecimal } from '@ultimat3/money';
43
+ import { mountOver } from '@ultimat3/render/client';
43
44
  import { Button, Form, Input, setSolidRuntime, UiProvider } from '@ultimat3/ui';
44
45
  import type { JSX } from 'solid-js';
45
46
  import {
@@ -151,8 +152,9 @@ function ${feature.pascal}FormBody(props: ${feature.pascal}FormProps): JSX.Eleme
151
152
  * keeps every export of solid-js alive, and the bundler cannot shake what it cannot see unused —
152
153
  * measured at 14.8 kB minified per island chunk (5.6 kB gzipped) for the namespace form.
153
154
  *
154
- * The shell is cleared first: Solid's \`render\` APPENDS when the container already has children,
155
- * so without it the server's markup stays on screen above a second, live copy of the same thing.
155
+ * \`mountOver\` clears the shell (Solid's \`render\` APPENDS, so the server's markup would stay above
156
+ * a second, live copy) and puts it back if the render throws — a broken form shows what the server
157
+ * sent, not a blank box, and the throw still reaches the runtime's \`data-x-failed\` marker.
156
158
  */
157
159
  export function mount(el: HTMLElement, props: ${feature.pascal}FormProps): () => void {
158
160
  setSolidRuntime({
@@ -164,16 +166,17 @@ export function mount(el: HTMLElement, props: ${feature.pascal}FormProps): () =>
164
166
  onCleanup,
165
167
  createRoot,
166
168
  });
167
- el.textContent = '';
168
169
  // Solid's disposer, returned: the client router calls it when it navigates away, and a mount
169
170
  // that returns nothing is X_ISLAND_DISPOSER_MISSING.
170
- return render(
171
- () => (
172
- <UiProvider locale={props.locale}>
173
- <${feature.pascal}FormBody {...props} />
174
- </UiProvider>
171
+ return mountOver(el, (root) =>
172
+ render(
173
+ () => (
174
+ <UiProvider locale={props.locale}>
175
+ <${feature.pascal}FormBody {...props} />
176
+ </UiProvider>
177
+ ),
178
+ root,
175
179
  ),
176
- el,
177
180
  );
178
181
  }
179
182
  `;
@@ -45,7 +45,7 @@ queries, jobs, MCP tools, published operations and tests it touches, each with p
45
45
  | Data | routes call actions and queries; only \`repo.ts\` touches the database | \`X_BOUNDARY_ROUTE_TO_DB\` |
46
46
  | Repos | a \`repo.ts\` reads through the typed handle, never a \`sql\` literal the handle can express | \`guards/repo-raw-sql.ts\` |
47
47
  | Vendors | a server \`fetch(\` carries a \`signal\` in its own options — better, it is \`outbound()\` from \`@ultimat3/core/outbound\`: a deadline, the caller's signal, safe-only retry | \`guards/raw-fetch.ts\` |
48
- | Polling | an island re-reads on a timer with \`visibleInterval(run, ms)\` from \`@ultimat3/core/page\` — no call while the tab is hidden, none after a lost session — never a bare \`setInterval(\`; a \`// why:\` on the line admits a tick that is not a read | \`guards/raw-interval.ts\` |
48
+ | Polling | an island re-reads a query on a timer with \`useQuery(ref, input, { poll: pollEvery(ms) })\` (\`@ultimat3/realtime\`), anything else with \`visibleInterval(run, ms)\` from \`@ultimat3/core/page\` — no call while the tab is hidden, none after a lost session — never a bare \`setInterval(\`; a \`// why:\` on the line admits a tick that is not a read | \`guards/raw-interval.ts\` |
49
49
  | Confirmation | a destructive act asks through \`ConfirmDialog\` from \`@ultimat3/ui\` — Cancel focused, a native post, stays open on a refusal — never \`confirm(\`; a \`// why:\` on the line admits a call that is not that question | \`guards/native-confirm.ts\` |
50
50
  | Errors | never \`throw new Error\` — declare each code once, \`defineError({ code, title, status, cause, fix })\` from \`@ultimat3/core/page\`, and throw its class; never a handwritten \`UltimateError\` subclass | \`guards/bare-error.ts\`, \`guards/error-declared.ts\` |
51
51
  | Money | \`{ minor, currency }\`, never a float — \`money()\` on the column | the type: \`price: 19.99\` is TS2322, \`number\` is not \`MoneyInput\` |
@@ -64,6 +64,7 @@ queries, jobs, MCP tools, published operations and tests it touches, each with p
64
64
  | Images | every image carries width + height or an aspect-ratio, and the priority one is never \`loading="lazy"\` | \`guards/image-dimensions.ts\` |
65
65
  | Motion | animate \`transform\` and \`opacity\` — never a layout property, never \`transition: all\` | \`guards/animated-layout-property.ts\` |
66
66
  | Islands | every \`*.island.tsx\` has a sibling \`*.island.states.ts\`, so \`bunx x shot --island\` can photograph its failures | \`guards/island-without-states.ts\` |
67
+ | Island mounts | a \`mount\` replaces its server markup through \`mountOver\`, so a render that throws shows the server's HTML, not a blank box | \`guards/island-mount-clears.ts\` |
67
68
  | Size | one file, one job — ${LINE_CEILING} lines of reviewable logic, and split past it | \`X_FILE_TOO_LONG\` |
68
69
 
69
70
  \`guards/\` is yours: each file is one rule, discovered by \`bunx x verify\` and run inside its
@@ -9,7 +9,8 @@
9
9
  //
10
10
  // The other five are about what the app is like to USE, which no row of `AGENTS.md` had ever been
11
11
  // about: a control a keyboard cannot reach, a focus ring taken away and not replaced, an image with
12
- // no box, an animation the compositor cannot run, and an island nobody has seen fail. Each is
12
+ // no box, an animation the compositor cannot run, an island nobody has seen fail, and one that
13
+ // fails BLANK — its server markup cleared outside `mountOver`. Each is
13
14
  // statically decidable from the file alone — the reason those five and not the many that are not.
14
15
  //
15
16
  // The seven after those are about the STYLESHEET, which Biome does not read at all: a length, a
@@ -29,6 +30,7 @@ import { bareErrorGuardFiles } from './guard-bare-error';
29
30
  import { errorDeclaredGuardFiles } from './guard-error-declared';
30
31
  import { focusVisibleGuardFiles } from './guard-focus-visible';
31
32
  import { imageDimensionsGuardFiles } from './guard-image-dimensions';
33
+ import { islandMountClearsGuardFiles } from './guard-island-mount-clears';
32
34
  import { islandWithoutStatesGuardFiles } from './guard-island-without-states';
33
35
  import { nativeConfirmGuardFiles } from './guard-native-confirm';
34
36
  import { rawBreakpointGuardFiles } from './guard-raw-breakpoint';
@@ -59,6 +61,7 @@ const SHIPPED: readonly (readonly [string, () => readonly GeneratedFile[]])[] =
59
61
  ['error-declared', errorDeclaredGuardFiles],
60
62
  ['focus-visible', focusVisibleGuardFiles],
61
63
  ['image-dimensions', imageDimensionsGuardFiles],
64
+ ['island-mount-clears', islandMountClearsGuardFiles],
62
65
  ['island-without-states', islandWithoutStatesGuardFiles],
63
66
  ['native-confirm', nativeConfirmGuardFiles],
64
67
  ['raw-breakpoint', rawBreakpointGuardFiles],
@@ -245,6 +245,7 @@ const toggleIsland =
245
245
  // reads the browser on its own: the theme the boot stamped on \`<html>\`, then \`theme.defaultMode\`
246
246
  // (stamped beside it), then the OS.
247
247
 
248
+ import { mountOver } from '@ultimat3/render/client';
248
249
  import { setSolidRuntime, ThemeToggle, UiProvider } from '@ultimat3/ui';
249
250
  import {
250
251
  createContext,
@@ -266,8 +267,9 @@ export interface ThemeToggleIslandProps {
266
267
  * The one export the hydration runtime calls. \`setSolidRuntime\` comes FIRST and is not optional:
267
268
  * \`@ultimat3/ui\` imports types from solid-js and never a runtime, so the reactive graph a
268
269
  * component reaches is the one an entry registers. Seven NAMED imports, never a namespace: a
269
- * namespace object keeps every export of solid-js alive in the chunk. The shell is cleared before
270
- * \`render\`, which APPENDS — the server's copy would otherwise stay on screen beside the live one.
270
+ * namespace object keeps every export of solid-js alive in the chunk. \`mountOver\` clears the shell
271
+ * before \`render\`, which APPENDS, and puts it back if the render throws: a broken toggle shows the
272
+ * server's copy, not a blank box, and the throw still reaches the runtime's \`data-x-failed\`.
271
273
  */
272
274
  export function mount(el: HTMLElement, props: ThemeToggleIslandProps): () => void {
273
275
  setSolidRuntime({
@@ -279,16 +281,17 @@ export function mount(el: HTMLElement, props: ThemeToggleIslandProps): () => voi
279
281
  onCleanup,
280
282
  createRoot,
281
283
  });
282
- el.textContent = '';
283
284
  // Solid's disposer, returned: the client router calls it when it navigates away, and a mount
284
285
  // that returns nothing is X_ISLAND_DISPOSER_MISSING.
285
- return render(
286
- () => (
287
- <UiProvider locale={props.locale}>
288
- <ThemeToggle mode="toggle" />
289
- </UiProvider>
286
+ return mountOver(el, (root) =>
287
+ render(
288
+ () => (
289
+ <UiProvider locale={props.locale}>
290
+ <ThemeToggle mode="toggle" />
291
+ </UiProvider>
292
+ ),
293
+ root,
290
294
  ),
291
- el,
292
295
  );
293
296
  }
294
297
  `;
@@ -1,12 +1,12 @@
1
1
  // The app's brand, declared once as `export const brand = defineTheme(…)` in
2
- // `apps/web/shared/theme.ts`, read here and nowhere else: the `<style>` every document the boot
3
- // renders carries after its stylesheet, and the body `style-src` admits. No module, no brand: an
4
- // unthemed app emits no tag and extends no policy.
2
+ // `apps/web/shared/theme.ts`, read here and nowhere else: its CSS is appended to every surface
3
+ // stylesheet (`style-bundle.ts`), so it rides the hashed, immutable file — no inline `<style>`, no
4
+ // `style-src` hash. No module, no brand: an unthemed app's sheets are unchanged.
5
5
 
6
6
  // why: Bun exposes no path-join primitive, and the module path is app-root-relative.
7
7
  import { join } from 'node:path';
8
8
  import { ConfigInvalidError, describeValue } from '@ultimat3/core';
9
- import { renderHead } from '@ultimat3/render';
9
+ import { setBrandStyles } from './style-bundle';
10
10
 
11
11
  /** The conventional module, beside `shared/global.ts` — one fixed path, as `API_INDEX` is. */
12
12
  export const APP_THEME_MODULE = 'apps/web/shared/theme.ts';
@@ -14,36 +14,34 @@ export const APP_THEME_MODULE = 'apps/web/shared/theme.ts';
14
14
  export const APP_THEME_EXPORT = 'brand';
15
15
 
16
16
  export interface ThemeBrand {
17
- /** The rendered `<style>`, for `DocumentOptions.brandHead`. */
18
- readonly head: string;
19
- /** Exactly the text between the tags — the body a boot hands `inlineStyleSources`. */
20
- readonly style: string;
17
+ /** The brand's CSS, exactly as `defineTheme()` rendered it — now the tail of every sheet. */
18
+ readonly css: string;
21
19
  }
22
20
 
23
21
  /** Code to paste, as `loadAppConfig`'s is: the module path is already in the cause. */
24
22
  const FIX = `export const ${APP_THEME_EXPORT} = defineTheme({ preset: 'scifi' });`;
25
23
 
26
24
  /**
27
- * `undefined` when the app has no theme module or its brand renders no CSS. A module that will not
28
- * import throws as it did, so a palette `defineTheme()` refuses fails the boot with
29
- * `X_UI_CONTRAST_INSUFFICIENT` (or its token code) and not a rewording of it.
25
+ * `undefined` when the app has no theme module or its brand renders no CSS. Either way the answer
26
+ * is REGISTERED with the stylesheet table, so the next `styleBundle()` carries it (or drops a
27
+ * previous app's). A module that will not import throws as it did, so a palette `defineTheme()`
28
+ * refuses fails the boot with `X_UI_CONTRAST_INSUFFICIENT` (or its token code), not a rewording.
30
29
  */
31
30
  export async function loadThemeBrand(root: string): Promise<ThemeBrand | undefined> {
32
31
  const path = join(root, APP_THEME_MODULE);
33
- if (!(await Bun.file(path).exists())) return undefined;
34
- const module = (await import(path)) as Record<string, unknown>;
35
- const css = brandCss(path, module);
36
- if (css.length === 0) return undefined;
37
- // `renderHead` escapes `</` in a style body, which would make the tag's text differ from the
38
- // hashed one — so a body that needs escaping is refused above rather than escaped here.
39
- return { head: renderHead([{ kind: 'style', key: 'style:brand', content: css }]), style: css };
32
+ const css = (await Bun.file(path).exists())
33
+ ? brandCss(path, (await import(path)) as Record<string, unknown>)
34
+ : '';
35
+ setBrandStyles(css);
36
+ return css.length === 0 ? undefined : { css };
40
37
  }
41
38
 
42
39
  /**
43
40
  * The brand's stylesheet, read structurally: `@ultimat3/ui` is a tier below and this package does
44
41
  * not import it, so a `Brand` is `{ css: string }`. `defineTheme()` never emits `<` — its values
45
42
  * are validated against grammars that exclude it — so one here came from a hand-built object, and
46
- * it is the one character that could end the element and start markup.
43
+ * a sheet every document links is not where an unvalidated one goes. Kept from the inline era,
44
+ * when `<` could also close the element and start markup.
47
45
  */
48
46
  function brandCss(path: string, module: Record<string, unknown>): string {
49
47
  const brand = Object.hasOwn(module, APP_THEME_EXPORT) ? module[APP_THEME_EXPORT] : undefined;
@@ -57,7 +55,7 @@ function brandCss(path: string, module: Record<string, unknown>): string {
57
55
  }
58
56
  if (css.includes('<')) {
59
57
  throw new ConfigInvalidError({
60
- cause: `${path}'s ${APP_THEME_EXPORT}.css contains "<", which defineTheme() never emits and which could close the <style> element it is inlined in`,
58
+ cause: `${path}'s ${APP_THEME_EXPORT}.css contains "<", which defineTheme() never emits, so the brand was hand-built and is not appended to every stylesheet the documents link`,
61
59
  fix: FIX,
62
60
  meta: { key: APP_THEME_EXPORT },
63
61
  });