@ultimat3/cli 31.1.0 → 31.3.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 (42) hide show
  1. package/CLAUDE.md +3 -3
  2. package/package.json +29 -29
  3. package/src/app-load.ts +3 -2
  4. package/src/binding-names.ts +124 -0
  5. package/src/browser-transport.ts +28 -0
  6. package/src/cmd-doctor.ts +8 -0
  7. package/src/cmd-exercise.ts +13 -1
  8. package/src/cmd-upgrade.ts +28 -4
  9. package/src/dev-boot.ts +4 -5
  10. package/src/dev-rebuild.ts +38 -5
  11. package/src/doctor-typescript.ts +31 -0
  12. package/src/error-codes.ts +2 -0
  13. package/src/island-build-pool.ts +35 -0
  14. package/src/island-bundle.ts +137 -176
  15. package/src/island-cache-inputs.ts +141 -0
  16. package/src/island-duplicates.ts +36 -0
  17. package/src/island-group-cache.ts +289 -0
  18. package/src/island-groups.ts +117 -0
  19. package/src/island-outputs.ts +153 -0
  20. package/src/island-runtime.ts +5 -0
  21. package/src/island-styles.ts +68 -19
  22. package/src/mcp-errors-shot.ts +49 -0
  23. package/src/mcp-errors.ts +5 -41
  24. package/src/measure-scope.ts +17 -4
  25. package/src/messages-upgrade.ts +2 -0
  26. package/src/offline-ports.ts +106 -0
  27. package/src/prerender.ts +2 -2
  28. package/src/runtime-storage-boot.ts +41 -7
  29. package/src/templates/scaffold-repo.ts +2 -1
  30. package/src/templates/sign-in-oidc.ts +24 -9
  31. package/src/transport-calls.ts +7 -3
  32. package/src/transport-values.ts +59 -0
  33. package/src/typescript-floor.ts +83 -0
  34. package/src/upgrade-report.ts +8 -1
  35. package/src/verify-e2e.ts +17 -5
  36. package/wiki/Client-Data.md +14 -8
  37. package/wiki/Configuration.md +1 -1
  38. package/wiki/Deployment.md +1 -1
  39. package/wiki/Entities-And-Migrations.md +15 -10
  40. package/wiki/Storage-And-Uploads.md +1 -1
  41. package/wiki/Testing.md +1 -0
  42. package/wiki/Upgrading.md +17 -4
@@ -0,0 +1,289 @@
1
+ // One island group's built output, kept under `.x/cache/islands/` and reused while everything the
2
+ // build read still says the same: each file's bytes (the bundler's inputs and every Sass partial a
3
+ // sheet `@use`s), each directory listing an import was resolved in, and the shared environment in
4
+ // the key (`island-cache-inputs.ts`). It reuses BYTES, never a layout.
5
+ //
6
+ // The prebuilt store's rule (`island-store.ts`: record what went in, rehash it before serving) at
7
+ // the grain a build runs at — one group — so a restart rebuilds only the groups an edit reached.
8
+ // Measured on the 5,124-file bench app (159 islands, 157 groups), As of 2026-11-10: islands
9
+ // 14.6–21 s built (load-dependent), 0.42 s reused, 0.8 s with one island edited — 10,241,659 B
10
+ // either way.
11
+
12
+ // why: Bun ships no rename, mkdir, unlink, directory listing or utimes. An entry is written beside
13
+ // itself and renamed into place, so a reader in another process never parses half a file.
14
+ import { mkdir, readdir, rename, unlink, utimes } from 'node:fs/promises';
15
+ // why: Bun ships no path API.
16
+ import { dirname, join } from 'node:path';
17
+ import { frameworkVersion } from '@ultimat3/core';
18
+ import { contentHash } from '@ultimat3/render/server';
19
+ import type { IslandChunk, SharedChunk } from './island-bundle';
20
+ import type { InputDigester } from './island-cache-inputs';
21
+ import { listingDigester, resolutionDirs } from './island-cache-inputs';
22
+ import { stableChunk } from './island-identity';
23
+ import { isStylesheet, registerIslandStylesheet } from './island-styles';
24
+ import { hasPathSegment } from './path-segments';
25
+
26
+ /** App-root-relative: `.x/` is the app's own scratch tree, kept across `x dev` restarts. */
27
+ export const ISLAND_CACHE_DIR = '.x/cache/islands';
28
+
29
+ /** Bumped when an entry's shape or meaning changes: an older entry is a miss, never a misread. */
30
+ const FORMAT = 2;
31
+
32
+ /** An entry or a partial nobody read or wrote for this long is swept. */
33
+ const SWEEP_AFTER_MS = 14 * 86_400_000;
34
+
35
+ /**
36
+ * Coarse mtimes (1–2 s on some filesystems) and a clock stepped back read an edit made during the
37
+ * build as one made before it: anything modified this close to the start is treated as raced.
38
+ */
39
+ const MTIME_SLACK_MS = 2_000;
40
+
41
+ /** What one `buildAll` answers, plus what it read — the half a cache entry is verified by. */
42
+ export interface GroupOutput {
43
+ readonly chunks: readonly IslandChunk[];
44
+ readonly shared: readonly SharedChunk[];
45
+ /** Every file the build read, absolute: the bundler's inputs and each sheet's Sass partials. */
46
+ readonly inputs: readonly string[];
47
+ /** Every stylesheet the build registered, absolute — registered again on a hit. */
48
+ readonly stylesheets: readonly string[];
49
+ }
50
+
51
+ interface Stamp {
52
+ readonly path: string;
53
+ readonly digest: string;
54
+ }
55
+
56
+ type Stored<T> = T & { readonly codeHash: string };
57
+
58
+ interface Entry {
59
+ readonly format: number;
60
+ readonly key: string;
61
+ readonly chunks: readonly Stored<IslandChunk>[];
62
+ readonly shared: readonly Stored<SharedChunk>[];
63
+ readonly inputs: readonly Stamp[];
64
+ /** Directory listings, digested: a file added where a resolver looks is a miss. */
65
+ readonly dirs: readonly Stamp[];
66
+ readonly stylesheets: readonly string[];
67
+ }
68
+
69
+ /**
70
+ * Everything a group's output depends on besides what it read: the group, how it is split, the
71
+ * framework and Bun that build it, the shared environment (`environmentDigest`), and the realtime
72
+ * answer the app gives (`null` for a group no island of which reaches realtime).
73
+ */
74
+ export function groupKey(parts: {
75
+ readonly group: readonly string[];
76
+ readonly splitting: boolean;
77
+ readonly environment: string;
78
+ readonly persists: boolean | undefined;
79
+ }): string {
80
+ return contentHash(
81
+ JSON.stringify([
82
+ FORMAT,
83
+ frameworkVersion(),
84
+ Bun.version,
85
+ parts.environment,
86
+ parts.group,
87
+ parts.splitting,
88
+ parts.persists ?? null,
89
+ ]),
90
+ );
91
+ }
92
+
93
+ const entryPath = (root: string, key: string): string =>
94
+ join(root, ISLAND_CACHE_DIR, `${key}.json`);
95
+
96
+ const isStamp = (value: unknown): value is Stamp => {
97
+ const one = value as Record<string, unknown> | null;
98
+ return typeof one?.['path'] === 'string' && typeof one['digest'] === 'string';
99
+ };
100
+
101
+ const hashed = (value: unknown): boolean => {
102
+ const one = value as Record<string, unknown> | null;
103
+ return typeof one?.['code'] === 'string' && one['codeHash'] === contentHash(one['code']);
104
+ };
105
+
106
+ const strings = (value: unknown): boolean =>
107
+ Array.isArray(value) && value.every((one) => typeof one === 'string');
108
+
109
+ const count = (value: unknown): boolean => Number.isSafeInteger(value) && (value as number) >= 0;
110
+
111
+ /** Every field a served chunk is read by: a hit hands it to the resolver, the store and the route. */
112
+ const isChunk = (value: unknown): boolean => {
113
+ const one = value as Record<string, unknown>;
114
+ const kind = one['realtime'];
115
+ return (
116
+ hashed(value) &&
117
+ typeof one['file'] === 'string' &&
118
+ typeof one['moduleId'] === 'string' &&
119
+ typeof one['url'] === 'string' &&
120
+ count(one['bytes']) &&
121
+ strings(one['imports']) &&
122
+ (one['sources'] === undefined || strings(one['sources'])) &&
123
+ (kind === undefined || kind === 'restores' || kind === 'follows')
124
+ );
125
+ };
126
+
127
+ const isShared = (value: unknown): boolean => {
128
+ const one = value as Record<string, unknown>;
129
+ return (
130
+ hashed(value) &&
131
+ typeof one['url'] === 'string' &&
132
+ count(one['bytes']) &&
133
+ strings(one['importers']) &&
134
+ (one['sources'] === undefined || strings(one['sources']))
135
+ );
136
+ };
137
+
138
+ /**
139
+ * A file on disk is input, so the entry proves what it serves before any of it is: inputs to
140
+ * rehash (none is a refusal — it would verify trivially), every chunk whole (each field a hit
141
+ * reads, its code matching its recorded hash), and every stylesheet one of the recorded inputs or an installed package's (`node_modules`,
142
+ * versioned by the lockfile in the key) — a sheet is compiled into served CSS.
143
+ */
144
+ function parseEntry(value: unknown, key: string): Entry | undefined {
145
+ if (typeof value !== 'object' || value === null) return undefined;
146
+ const entry = value as Record<string, unknown>;
147
+ const { format, chunks, shared, inputs, dirs, stylesheets } = entry;
148
+ if (format !== FORMAT || entry['key'] !== key) return undefined;
149
+ if (![chunks, shared, inputs, dirs, stylesheets].every(Array.isArray)) return undefined;
150
+ const stamps = inputs as readonly unknown[];
151
+ if (stamps.length === 0 || !stamps.every(isStamp)) return undefined;
152
+ if (!(dirs as readonly unknown[]).every(isStamp)) return undefined;
153
+ if (!(chunks as unknown[]).every(isChunk) || !(shared as unknown[]).every(isShared)) {
154
+ return undefined;
155
+ }
156
+ const recorded = new Set((stamps as readonly Stamp[]).map((stamp) => stamp.path));
157
+ const sheetOk = (sheet: unknown): boolean =>
158
+ typeof sheet === 'string' &&
159
+ isStylesheet(sheet) &&
160
+ (recorded.has(sheet) || hasPathSegment(sheet, 'node_modules'));
161
+ return (stylesheets as readonly unknown[]).every(sheetOk) ? (value as Entry) : undefined;
162
+ }
163
+
164
+ /** `/islands/<id>-<identity>.js`, `chunk-<identity>.js`, `page-runtime.<identity>.js`. */
165
+ const identityOf = (url: string): string => /[-.]([0-9a-z]+)\.js$/.exec(url)?.[1] ?? url;
166
+
167
+ const unchanged = async (stamps: readonly Stamp[], digestOf: InputDigester): Promise<boolean> => {
168
+ const digests = await Promise.all(stamps.map((stamp) => digestOf(stamp.path)));
169
+ return stamps.every((stamp, index) => digests[index] === stamp.digest);
170
+ };
171
+
172
+ /**
173
+ * The group's output as it was built, when every input and listing still hashes the same;
174
+ * `undefined` otherwise. A hit touches the entry (the sweep keeps what is read) and seeds
175
+ * `stableChunk`, so a later in-process build of the same graph serves these bytes at this URL.
176
+ */
177
+ export async function readGroup(
178
+ root: string,
179
+ key: string,
180
+ digestOf: InputDigester,
181
+ listingOf: InputDigester = listingDigester(),
182
+ ): Promise<
183
+ { readonly chunks: readonly IslandChunk[]; readonly shared: readonly SharedChunk[] } | undefined
184
+ > {
185
+ const path = entryPath(root, key);
186
+ const file = Bun.file(path);
187
+ if (!(await file.exists())) return undefined;
188
+ const entry = parseEntry(await file.json().catch(() => undefined), key);
189
+ if (entry === undefined) return undefined;
190
+ if (!(await unchanged(entry.inputs, digestOf))) return undefined;
191
+ if (!(await unchanged(entry.dirs, listingOf))) return undefined;
192
+ for (const sheet of entry.stylesheets) {
193
+ const source = Bun.file(sheet);
194
+ if (!(await source.exists())) return undefined;
195
+ registerIslandStylesheet(sheet, await source.text());
196
+ }
197
+ const now = new Date();
198
+ await utimes(path, now, now).catch(() => undefined);
199
+ const strip = <T>({ codeHash: _, ...rest }: Stored<T>): T => rest as T;
200
+ const chunks = entry.chunks.map(strip<IslandChunk>).map((chunk) => ({
201
+ ...chunk,
202
+ ...stableChunk(chunk.file, identityOf(chunk.url), chunk.code),
203
+ }));
204
+ const shared = entry.shared.map(strip<SharedChunk>).map((one) => ({
205
+ ...one,
206
+ ...stableChunk(one.url, identityOf(one.url), one.code),
207
+ }));
208
+ return { chunks, shared };
209
+ }
210
+
211
+ /**
212
+ * Records the group's output and what it read. The digests are `digestOf`'s and `listingOf`'s —
213
+ * memoised, so a file or directory the pre-build `readGroup` already hashed is stamped as it was
214
+ * BEFORE the build, and an edit during it is a miss next time whatever its mtime says. One hashed
215
+ * only now is guarded by its mtime, with `MTIME_SLACK_MS` for coarse clocks: modified near or
216
+ * after the start — a directory included, which an added or removed name moves — no entry.
217
+ */
218
+ export async function writeGroup(
219
+ root: string,
220
+ key: string,
221
+ output: GroupOutput,
222
+ startedAt: number,
223
+ digestOf: InputDigester,
224
+ listingOf: InputDigester = listingDigester(),
225
+ ): Promise<void> {
226
+ // A directory's mtime moves when a name is added or removed in it: `util.ts` landing beside
227
+ // `util/` mid-build changes no input's bytes, only what `./util` would now resolve to.
228
+ const listed = resolutionDirs(output.inputs);
229
+ const raced = [...output.inputs, ...listed].some(
230
+ (path) => Bun.file(path).lastModified > startedAt - MTIME_SLACK_MS,
231
+ );
232
+ if (raced || output.inputs.length === 0) return;
233
+ const stamp = async (paths: readonly string[], of: InputDigester) => {
234
+ const digests = await Promise.all(paths.map((path) => of(path)));
235
+ const stamps = paths.map((path, index) => ({ path, digest: digests[index] }));
236
+ return stamps.every((one): one is Stamp => one.digest !== undefined) ? stamps : undefined;
237
+ };
238
+ const inputs = await stamp(output.inputs, digestOf);
239
+ const dirs = await stamp(listed, listingOf);
240
+ if (inputs === undefined || dirs === undefined) return;
241
+ const withHash = <T extends { readonly code: string }>(one: T): Stored<T> => ({
242
+ ...one,
243
+ codeHash: contentHash(one.code),
244
+ });
245
+ const entry: Entry = {
246
+ format: FORMAT,
247
+ key,
248
+ chunks: output.chunks.map(withHash),
249
+ shared: output.shared.map(withHash),
250
+ inputs,
251
+ dirs,
252
+ stylesheets: output.stylesheets,
253
+ };
254
+ const path = entryPath(root, key);
255
+ await mkdir(dirname(path), { recursive: true });
256
+ const partial = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}`;
257
+ try {
258
+ await Bun.write(partial, JSON.stringify(entry));
259
+ await rename(partial, path);
260
+ } catch (error) {
261
+ // A failed rename (EPERM on Windows while a reader holds the entry) left the partial: remove it
262
+ // before the caller hears the failure, or every such write leaves a file the size of a group.
263
+ await unlink(partial).catch(() => undefined);
264
+ throw error;
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Removes every entry and partial in the cache not touched for `SWEEP_AFTER_MS` before `now`: a
270
+ * group whose key moved (a renamed island, a new framework version) is never read again. A hit
271
+ * touches its entry, so only the abandoned go.
272
+ */
273
+ export async function sweepGroupCache(root: string, now: number): Promise<void> {
274
+ const dir = join(root, ISLAND_CACHE_DIR);
275
+ const names = await readdir(dir).catch(() => [] as string[]);
276
+ for (const name of names) {
277
+ const file = Bun.file(join(dir, name));
278
+ if (file.lastModified < now - SWEEP_AFTER_MS) await unlink(join(dir, name)).catch(() => {});
279
+ }
280
+ }
281
+
282
+ const swept = new Set<string>();
283
+
284
+ /** `sweepGroupCache` at most once per root per process: a sweep is a listing, not per build. */
285
+ export function sweepOnce(root: string): Promise<void> {
286
+ if (swept.has(root)) return Promise.resolve();
287
+ swept.add(root);
288
+ return sweepGroupCache(root, performance.timeOrigin + performance.now());
289
+ }
@@ -0,0 +1,117 @@
1
+ // Which islands one `Bun.build` bundles together: the islands every route renders TOGETHER, and no
2
+ // other. Two islands named by exactly the same route files are one split build, so the code they
3
+ // share is one chunk a page fetches once; every other island is built alone, byte for byte what it
4
+ // always was.
5
+ //
6
+ // Read from the route files' sources, so `x dev`, the container, the image's store and the static
7
+ // export all derive one grouping from one tree — none of them needs a render pass.
8
+ //
9
+ // Measured on examples/dummy, As of 2026-11-10 (Bun 1.4.4): `/posts/:id` renders like, likes-badge
10
+ // and summary on that route only — its islands' bytes 95,754 → 65,676 B (runtime chunk aside);
11
+ // every other route of the three tracked apps byte-identical. One global split build
12
+ // (`islands.sharedChunks`) got that route to 70,462 B and charged six others +910…+9,154 B.
13
+
14
+ // why: Bun ships no path API; an island's file is its route file's directory joined to its `src`.
15
+ import { posix } from 'node:path';
16
+ import { ISLAND_EXTENSION, ROUTE_FILENAME } from '@ultimat3/render';
17
+ import { hasPathSegment } from './path-segments';
18
+ import { posixRelative } from './posix-path';
19
+
20
+ /** Every route file that can declare an island: `page.tsx` on the surfaces that render documents. */
21
+ const ROUTE_GLOB = `apps/*/{site,app}/**/${ROUTE_FILENAME.site}`;
22
+
23
+ /** A string literal naming an island file — quoted, double-quoted or a template with no holes. */
24
+ const ISLAND_LITERAL = /(["'`])([^"'`\s$]+\.island\.tsx)\1/g;
25
+
26
+ /**
27
+ * Comments are dropped by transpiling first, so a page whose prose names another page's island
28
+ * does not join that island's group. Unused declarations are KEPT: `island()` at module scope is
29
+ * the declaration, rendered or not, and a dynamic route renders a different subset per params.
30
+ */
31
+ const transpiler = new Bun.Transpiler({
32
+ loader: 'tsx',
33
+ deadCodeElimination: false,
34
+ trimUnusedImports: false,
35
+ });
36
+
37
+ /** The page's code without its comments — or as written, when it does not parse. */
38
+ function codeOf(source: string): string {
39
+ try {
40
+ return transpiler.transformSync(source);
41
+ } catch {
42
+ // A page that does not parse fails its own load with its own code (`X_APP_MODULE_LOAD_FAILED`);
43
+ // grouping is a byte saving, never a verdict, so it reads the literals as written.
44
+ return source;
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Each route file (app-root-relative, POSIX) → the islands it names, resolved from its directory
50
+ * the way `resolverFor` resolves a `src`. Only files in `islands` count: a literal naming nothing
51
+ * built cannot be grouped, and the render refuses it by name (`X_ISLAND_INVALID`).
52
+ */
53
+ export async function routeIslandReferences(
54
+ root: string,
55
+ islands: ReadonlySet<string>,
56
+ ): Promise<ReadonlyMap<string, ReadonlySet<string>>> {
57
+ const references = new Map<string, ReadonlySet<string>>();
58
+ for await (const absolute of new Bun.Glob(ROUTE_GLOB).scan({ cwd: root, absolute: true })) {
59
+ // The ROOT-RELATIVE path, as `isScannedModule` tests it: an app checked out under
60
+ // `<anything>/node_modules/<app>` holds the segment in every absolute path it has.
61
+ const file = posixRelative(root, absolute);
62
+ if (hasPathSegment(file, 'node_modules')) continue;
63
+ const source = await Bun.file(absolute).text();
64
+ if (!source.includes(ISLAND_EXTENSION)) continue;
65
+ const dir = posix.dirname(file);
66
+ const named = new Set<string>();
67
+ for (const match of codeOf(source).matchAll(ISLAND_LITERAL)) {
68
+ const target = posix.normalize(posix.join(dir, match[2] ?? ''));
69
+ if (islands.has(target)) named.add(target);
70
+ }
71
+ if (named.size > 0) references.set(file, named);
72
+ }
73
+ return references;
74
+ }
75
+
76
+ const byFirst = (a: readonly string[], b: readonly string[]): number => {
77
+ const [x = '', y = ''] = [a[0], b[0]];
78
+ return x < y ? -1 : x > y ? 1 : 0;
79
+ };
80
+
81
+ /**
82
+ * The partition: islands keyed by the set of routes naming them. Same key, same group —
83
+ * so every route loading one member loads all of them, and no route pays for a member it does not
84
+ * render. An island on many routes (a layout-wide banner) has a key of its own and stays alone,
85
+ * with no rule naming it. Groups of more than one first, each sorted, then the solos — so the
86
+ * partition is a function of the sources, never of the order a glob answered in.
87
+ */
88
+ export function groupIslands(
89
+ islands: readonly string[],
90
+ references: ReadonlyMap<string, ReadonlySet<string>>,
91
+ ): readonly (readonly string[])[] {
92
+ const routesOf = new Map<string, string[]>();
93
+ for (const [route, named] of references) {
94
+ for (const island of named) routesOf.set(island, [...(routesOf.get(island) ?? []), route]);
95
+ }
96
+ const byKey = new Map<string, string[]>();
97
+ for (const island of [...islands].sort()) {
98
+ const routes = routesOf.get(island);
99
+ // One walk of `references` built every list, so equal sets are equal strings unsorted. No route
100
+ // names it: alone, under a key no route set can spell.
101
+ const key = routes === undefined ? `\0${island}` : routes.join('\n');
102
+ byKey.set(key, [...(byKey.get(key) ?? []), island]);
103
+ }
104
+ const groups = [...byKey.values()];
105
+ return [
106
+ ...groups.filter((group) => group.length > 1).sort(byFirst),
107
+ ...groups.filter((group) => group.length === 1).sort(byFirst),
108
+ ];
109
+ }
110
+
111
+ /** `islands`, partitioned by the routes of the app at `root` that render them together. */
112
+ export async function islandGroups(
113
+ root: string,
114
+ islands: readonly string[],
115
+ ): Promise<readonly (readonly string[])[]> {
116
+ return groupIslands(islands, await routeIslandReferences(root, new Set(islands)));
117
+ }
@@ -0,0 +1,153 @@
1
+ // One island build's outputs, turned into the chunk table: which output is which island's entry,
2
+ // the shared chunks each entry loads, and the files on disk each was built from. Split from
3
+ // `island-bundle.ts`, which runs the build; this only reads what the bundler emitted.
4
+
5
+ // why: Bun ships no path API; `posix` for Bun's output paths, `basename` for a module id.
6
+ import { basename, posix } from 'node:path';
7
+ import { islandModuleId } from '@ultimat3/render';
8
+ import { IslandBuildFailedError } from './errors';
9
+ import type { IslandChunk, SharedChunk } from './island-bundle';
10
+ import { sourcesContentOf, stableChunk, stripDebugId } from './island-identity';
11
+ import type { BuiltOutput, LinkedFile } from './island-link';
12
+ import { sharedChunkName } from './island-link';
13
+ import { REALTIME_ISLAND_ENTRY } from './island-realtime';
14
+ import type { SourcePaths } from './island-sources';
15
+ import { sourcesOnDisk } from './island-sources';
16
+
17
+ /**
18
+ * Where a chunk is served from, in `x dev`, in the container and in a static export — one base
19
+ * path, because the URL is minted by one resolver and baked into the document. Sits beside
20
+ * `ICON_BASE_PATH` and `MEDIA_BASE_PATH`, deliberately outside the dev-only `/_x` namespace.
21
+ */
22
+ export const ISLAND_BASE_PATH = '/islands';
23
+
24
+ /**
25
+ * Bun's `./a/b.island.js` → `a/b.island.js`. A realtime wrapper's output is named after its
26
+ * VIRTUAL entry, which Bun places relative to the cwd behind `_.._/` segments — so everything up to
27
+ * and including the prefix goes, leaving the island's own spelling.
28
+ */
29
+ const outputKey = (path: string): string => {
30
+ const bare = path.startsWith('./') ? path.slice(2) : path;
31
+ const at = bare.indexOf(REALTIME_ISLAND_ENTRY);
32
+ return at === -1 ? bare : bare.slice(at + REALTIME_ISLAND_ENTRY.length);
33
+ };
34
+
35
+ const withoutExtension = (file: string): string =>
36
+ file.slice(0, file.length - posix.extname(file).length);
37
+
38
+ /** Every code output paired with its source map's inputs and, for an entry, its island. */
39
+ export async function builtOutputs(
40
+ root: string,
41
+ files: readonly string[],
42
+ artifacts: readonly Bun.BuildArtifact[],
43
+ sourcePaths: Map<string, SourcePaths>,
44
+ ): Promise<readonly BuiltOutput[]> {
45
+ const byStem = new Map(files.map((file) => [withoutExtension(file), file]));
46
+ const maps = new Map<string, string>();
47
+ for (const artifact of artifacts) {
48
+ if (artifact.kind === 'sourcemap') maps.set(artifact.path, await artifact.text());
49
+ }
50
+ const outputs: BuiltOutput[] = [];
51
+ for (const artifact of artifacts) {
52
+ if (artifact.kind !== 'entry-point' && artifact.kind !== 'chunk') continue;
53
+ const key = outputKey(artifact.path);
54
+ const file = artifact.kind === 'entry-point' ? byStem.get(withoutExtension(key)) : undefined;
55
+ const map = maps.get(`${artifact.path}.map`);
56
+ const parsed: unknown = map === undefined ? undefined : JSON.parse(map);
57
+ const sources = parsed === undefined ? undefined : sourcesContentOf(parsed, true);
58
+ sourcePaths.set(key, await sourcesOnDisk(root, parsed));
59
+ if (sources === undefined || (artifact.kind === 'entry-point' && file === undefined)) {
60
+ throw new IslandBuildFailedError({
61
+ file: file ?? key,
62
+ logs: `the bundler emitted ${key} with no source map or no island behind it, so the output has no stable identity`,
63
+ });
64
+ }
65
+ outputs.push({
66
+ path: key,
67
+ ...(file === undefined ? {} : { file }),
68
+ code: stripDebugId(await artifact.text()),
69
+ sources,
70
+ });
71
+ }
72
+ return outputs;
73
+ }
74
+
75
+ /**
76
+ * The entry's own file, added to sources the map resolved into the root. A pure re-export island
77
+ * (`export { mountMenu as mount } from '../shared/menu'`) emits no code of its own, so its source
78
+ * map names only what it re-exports: the store then recorded nothing that changes when the entry
79
+ * is edited, and `writeIslandStore` refused it as a map whose paths left the root. A map that
80
+ * resolved NOTHING into the root stays empty — that is the cwd failure, and it is still refused.
81
+ */
82
+ function withOwnFile(file: string, sources: SourcePaths): SourcePaths {
83
+ return sources.length === 0 || sources.includes(file) ? sources : [...sources, file].sort();
84
+ }
85
+
86
+ /** The linked outputs, as the chunk table: the entries in `files` order, their chunks attached. */
87
+ export function entryChunks(
88
+ files: readonly string[],
89
+ linked: readonly LinkedFile[],
90
+ sources: ReadonlyMap<string, SourcePaths>,
91
+ ): readonly IslandChunk[] {
92
+ const shared = new Map(
93
+ linked
94
+ .filter((one) => one.file === undefined)
95
+ .map((one) => [sharedChunkName(one.identity), one]),
96
+ );
97
+ const closure = (start: readonly string[]): readonly string[] => {
98
+ const seen = new Set<string>();
99
+ const walk = (names: readonly string[]): void => {
100
+ for (const name of names) {
101
+ if (seen.has(name)) continue;
102
+ seen.add(name);
103
+ walk(shared.get(name)?.imports ?? []);
104
+ }
105
+ };
106
+ walk(start);
107
+ return [...seen].sort().map((name) => `${ISLAND_BASE_PATH}/${name}`);
108
+ };
109
+ const chunks: IslandChunk[] = [];
110
+ for (const file of files) {
111
+ const entry = linked.find((one) => one.file === file);
112
+ if (entry === undefined) {
113
+ throw new IslandBuildFailedError({ file, logs: 'the bundler emitted no entry point for it' });
114
+ }
115
+ const moduleId = islandModuleId(basename(file));
116
+ chunks.push({
117
+ file,
118
+ moduleId,
119
+ url: `${ISLAND_BASE_PATH}/${moduleId}-${entry.identity}.js`,
120
+ // The FIRST bytes this process emitted for these inputs, so a URL served `immutable` answers
121
+ // one byte string for as long as the process lives. Without it `x dev` re-mints the chunk on
122
+ // every watcher tick and a browser holding the previous one under `max-age=31536000` has two
123
+ // different files at one address. `bytes` is measured on THAT code, never on this build's.
124
+ ...stableChunk(file, entry.identity, entry.code),
125
+ imports: closure(entry.imports),
126
+ sources: withOwnFile(file, sources.get(entry.path) ?? []),
127
+ });
128
+ }
129
+ return chunks;
130
+ }
131
+
132
+ /** Every shared chunk the entries load, pinned the same way, with the islands that load it. */
133
+ export function sharedChunks(
134
+ chunks: readonly IslandChunk[],
135
+ linked: readonly LinkedFile[],
136
+ sources: ReadonlyMap<string, SourcePaths>,
137
+ ): readonly SharedChunk[] {
138
+ const out: SharedChunk[] = [];
139
+ for (const one of linked) {
140
+ if (one.file !== undefined) continue;
141
+ const url = `${ISLAND_BASE_PATH}/${sharedChunkName(one.identity)}`;
142
+ out.push({
143
+ url,
144
+ ...stableChunk(url, one.identity, one.code),
145
+ importers: chunks
146
+ .filter((chunk) => chunk.imports.includes(url))
147
+ .map((chunk) => chunk.file)
148
+ .sort(),
149
+ sources: sources.get(one.path) ?? [],
150
+ });
151
+ }
152
+ return out.sort((a, b) => (a.url < b.url ? -1 : a.url > b.url ? 1 : 0));
153
+ }
@@ -8,6 +8,7 @@ import { dirname, join } from 'node:path';
8
8
  import type { BunPlugin } from 'bun';
9
9
  import { IslandBuildFailedError } from './errors';
10
10
  import type { IslandChunk, SharedChunk } from './island-bundle';
11
+ import { inputFiles } from './island-cache-inputs';
11
12
  import { realSpelling } from './island-duplicates';
12
13
  import { describeBuildError, graphHash, stableChunk, stripDebugId } from './island-identity';
13
14
  import { frameworkDedupePlugins } from './island-package-dedupe';
@@ -57,6 +58,8 @@ export interface RuntimeChunk {
57
58
  readonly code: string;
58
59
  readonly bytes: number;
59
60
  readonly sources: SourcePaths;
61
+ /** Every file the runtime's build read, absolute (`inputFiles`): what a cached group rehashes. */
62
+ readonly inputs: readonly string[];
60
63
  }
61
64
 
62
65
  /**
@@ -147,6 +150,7 @@ async function buildRuntime(
147
150
  // `sourcesContent` is the one stable identity a minified bundle has.
148
151
  define: { 'process.env.NODE_ENV': '"production"' },
149
152
  sourcemap: 'external',
153
+ metafile: true,
150
154
  });
151
155
  } catch (error) {
152
156
  throw new IslandBuildFailedError({ file: island, logs: describeBuildError(error) });
@@ -168,6 +172,7 @@ async function buildRuntime(
168
172
  url,
169
173
  ...stableChunk(url, identity, stripDebugId(await output.text())),
170
174
  sources: await sourcesOnDisk(root, JSON.parse(text)),
175
+ inputs: await inputFiles(Object.keys(built.metafile?.inputs ?? {})),
171
176
  };
172
177
  }
173
178