@ultimat3/cli 30.9.0 → 31.1.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 (215) hide show
  1. package/CLAUDE.md +80 -64
  2. package/README.md +4 -1
  3. package/package.json +30 -29
  4. package/src/admin-registration.ts +1 -1
  5. package/src/affected-base.ts +51 -0
  6. package/src/affected.ts +34 -11
  7. package/src/app-boundaries.ts +88 -9
  8. package/src/app-load-async.ts +133 -0
  9. package/src/app-load-batch.ts +203 -0
  10. package/src/app-load-prebuilt.ts +147 -0
  11. package/src/app-load-register.ts +175 -0
  12. package/src/app-load.ts +143 -175
  13. package/src/app-loader-imports.ts +31 -0
  14. package/src/app-root.ts +13 -0
  15. package/src/app-runtime.ts +5 -1
  16. package/src/boundary-findings.ts +12 -0
  17. package/src/browser-launcher-port.ts +3 -7
  18. package/src/browser-launcher.ts +1 -1
  19. package/src/budgets-scan.ts +8 -0
  20. package/src/budgets.ts +10 -1
  21. package/src/build-registry-background.ts +59 -0
  22. package/src/build-registry.ts +207 -0
  23. package/src/cdp-shot-clock.ts +3 -11
  24. package/src/cdp-shot-driver.ts +3 -2
  25. package/src/cdp-shot-element.ts +3 -2
  26. package/src/cdp-shot-page.ts +2 -2
  27. package/src/cdp-shot-watch.ts +4 -3
  28. package/src/ci-log.ts +76 -13
  29. package/src/cmd-affected-spec.ts +7 -3
  30. package/src/cmd-affected.ts +91 -77
  31. package/src/cmd-auth.ts +3 -3
  32. package/src/cmd-ci.ts +6 -3
  33. package/src/cmd-db-recount.ts +15 -0
  34. package/src/cmd-drill.ts +10 -6
  35. package/src/cmd-exercise.ts +2 -1
  36. package/src/cmd-generate-spec.ts +6 -0
  37. package/src/cmd-generate.ts +22 -4
  38. package/src/cmd-mail.ts +1 -1
  39. package/src/cmd-pr-spec.ts +1 -1
  40. package/src/cmd-pr.ts +72 -1
  41. package/src/cmd-routes.ts +2 -2
  42. package/src/cmd-secrets-spec.ts +4 -1
  43. package/src/cmd-shot.ts +14 -262
  44. package/src/cmd-test-spec.ts +2 -2
  45. package/src/cmd-verify-spec.ts +21 -1
  46. package/src/cmd-verify.ts +16 -4
  47. package/src/coverage-source.ts +4 -1
  48. package/src/db-diagnostics.ts +8 -1
  49. package/src/dev-boot.ts +29 -15
  50. package/src/dev-dashboard-invalidations.ts +43 -0
  51. package/src/dev-dashboard.ts +13 -16
  52. package/src/dev-n-plus-one.ts +7 -3
  53. package/src/dev-rebuild.ts +2 -1
  54. package/src/dev-route-table.ts +1 -1
  55. package/src/dev-traces.ts +16 -15
  56. package/src/document-options.ts +12 -1
  57. package/src/drift-store.ts +55 -0
  58. package/src/error-catalog.ts +8 -3
  59. package/src/error-codes-boundary.ts +32 -0
  60. package/src/error-codes-package.ts +38 -0
  61. package/src/error-codes.ts +28 -40
  62. package/src/errors.ts +17 -7
  63. package/src/exercise-database.ts +13 -1
  64. package/src/exercise-findings.ts +36 -18
  65. package/src/exercise-services.ts +84 -0
  66. package/src/exercise-subject.ts +38 -13
  67. package/src/failure-capture-boot.ts +9 -5
  68. package/src/framework-schema.ts +5 -5
  69. package/src/generate-exercise.ts +1 -1
  70. package/src/generate-files.ts +27 -7
  71. package/src/generate-kinds.ts +5 -0
  72. package/src/generate-refresh.ts +53 -0
  73. package/src/generate-workspace.ts +169 -0
  74. package/src/generate-write.ts +8 -2
  75. package/src/hold.ts +19 -8
  76. package/src/image-prepare.ts +6 -2
  77. package/src/index.ts +5 -20
  78. package/src/island-bundle.ts +7 -3
  79. package/src/island-capture.ts +2 -2
  80. package/src/island-harness.ts +1 -1
  81. package/src/job-registration.ts +43 -6
  82. package/src/jobs-driver.ts +4 -5
  83. package/src/mcp-errors.ts +20 -4
  84. package/src/mcp-host.ts +5 -1
  85. package/src/mcp-ui-interact.ts +3 -0
  86. package/src/messages-gate.ts +10 -0
  87. package/src/new-shapes-generate.ts +1 -1
  88. package/src/otlp-export.ts +94 -29
  89. package/src/output.ts +24 -10
  90. package/src/page-sync.ts +3 -1
  91. package/src/pr-activity.ts +150 -0
  92. package/src/pr-bots.ts +109 -0
  93. package/src/pr-threads.ts +7 -2
  94. package/src/role-load.ts +17 -11
  95. package/src/role-start.ts +5 -4
  96. package/src/role-sync.ts +7 -8
  97. package/src/route-islands-preload.ts +46 -0
  98. package/src/route-islands.ts +6 -2
  99. package/src/runtime-admin.ts +5 -1
  100. package/src/runtime-bindings.ts +25 -19
  101. package/src/runtime-boot-ports.ts +66 -0
  102. package/src/runtime-bus.ts +29 -5
  103. package/src/runtime-cache-bus.ts +53 -0
  104. package/src/runtime-cache.ts +43 -13
  105. package/src/runtime-isr-outcome.ts +5 -4
  106. package/src/runtime-jobs.ts +2 -2
  107. package/src/runtime-keys.ts +37 -0
  108. package/src/runtime-overrides.ts +148 -42
  109. package/src/runtime-port-bindings-queue.ts +36 -0
  110. package/src/runtime-port-bindings.ts +117 -0
  111. package/src/runtime-ports.ts +164 -0
  112. package/src/runtime-purge.ts +41 -28
  113. package/src/runtime-push.ts +7 -3
  114. package/src/runtime-queue.ts +70 -55
  115. package/src/runtime-realtime.ts +5 -5
  116. package/src/runtime-render-document.ts +4 -1
  117. package/src/runtime-services.ts +110 -158
  118. package/src/runtime-storage-boot.ts +111 -0
  119. package/src/runtime-storage-upload.ts +9 -7
  120. package/src/runtime-storage.ts +7 -1
  121. package/src/serve-boot.ts +8 -4
  122. package/src/serve-entry.ts +3 -0
  123. package/src/serve-env.ts +47 -14
  124. package/src/serve-prebuilt-paths.ts +3 -0
  125. package/src/serve-prebuilt.ts +15 -4
  126. package/src/serve.ts +2 -2
  127. package/src/shot-gpu.ts +61 -0
  128. package/src/shot-route.ts +95 -0
  129. package/src/shot-run.ts +189 -0
  130. package/src/shot-verdict.ts +5 -0
  131. package/src/static-cards.ts +3 -2
  132. package/src/static-report.ts +2 -2
  133. package/src/style-bundle.ts +1 -1
  134. package/src/sync-authenticator.ts +17 -18
  135. package/src/templates/action-tests.ts +4 -4
  136. package/src/templates/backfill.ts +5 -8
  137. package/src/templates/entity.ts +3 -0
  138. package/src/templates/github/ci.yml.ts +3 -1
  139. package/src/templates/github/dependabot.yml.ts +73 -0
  140. package/src/templates/job.ts +13 -22
  141. package/src/templates/naming.ts +20 -1
  142. package/src/templates/pinned/docker-compose.yml +1 -1
  143. package/src/templates/query.ts +7 -8
  144. package/src/templates/route.ts +5 -3
  145. package/src/templates/scaffold-api.ts +1 -1
  146. package/src/templates/scaffold-auth.ts +5 -3
  147. package/src/templates/scaffold-claude-commands.ts +6 -3
  148. package/src/templates/scaffold-claude.ts +4 -4
  149. package/src/templates/scaffold-container-compose.ts +2 -4
  150. package/src/templates/scaffold-domain-package.ts +1 -1
  151. package/src/templates/scaffold-entries.ts +6 -1
  152. package/src/templates/scaffold-helm-fences.ts +3 -2
  153. package/src/templates/scaffold-helm.ts +35 -6
  154. package/src/templates/scaffold-repo.ts +47 -135
  155. package/src/templates/scaffold-runtime-ports.ts +62 -0
  156. package/src/templates/scaffold-verify-floor.ts +97 -0
  157. package/src/templates/shapes/overlay.ts +1 -1
  158. package/src/templates/sign-in-oidc.ts +5 -3
  159. package/src/templates/sign-in-shared.ts +28 -10
  160. package/src/templates/workspace.ts +75 -0
  161. package/src/test-ignores.ts +5 -2
  162. package/src/test-select.ts +4 -1
  163. package/src/tsconfig-aliases.ts +85 -0
  164. package/src/upgrade-gate.ts +30 -5
  165. package/src/upgrade-report.ts +7 -1
  166. package/src/verify-changed-facts.ts +53 -0
  167. package/src/verify-changed-scope.ts +162 -0
  168. package/src/verify-changed.ts +174 -0
  169. package/src/verify-checks.ts +33 -19
  170. package/src/verify-drift-owner.ts +30 -0
  171. package/src/verify-e2e.ts +2 -1
  172. package/src/verify-factories.ts +86 -0
  173. package/src/verify-run.ts +13 -11
  174. package/src/verify-step.ts +13 -0
  175. package/src/verify-tests.ts +58 -6
  176. package/src/workspace-external-deps.ts +164 -0
  177. package/src/write-line.ts +21 -6
  178. package/wiki/Actions.md +2 -2
  179. package/wiki/Adapters.md +400 -0
  180. package/wiki/Admin-Dashboard.md +1 -1
  181. package/wiki/Agents.md +9 -9
  182. package/wiki/Auth.md +78 -2
  183. package/wiki/Building-Your-Own-Base.md +1 -1
  184. package/wiki/CLI-Reference.md +45 -14
  185. package/wiki/Caching-And-Invalidation.md +17 -5
  186. package/wiki/Compared.md +8 -2
  187. package/wiki/Configuration.md +14 -14
  188. package/wiki/Deployment.md +28 -1
  189. package/wiki/Entities-And-Migrations.md +47 -1
  190. package/wiki/FAQ.md +8 -2
  191. package/wiki/Feature-Flags.md +1 -1
  192. package/wiki/Home.md +3 -2
  193. package/wiki/Jobs-And-Workflows.md +107 -6
  194. package/wiki/Known-Gaps.md +4 -3
  195. package/wiki/MCP-And-AI.md +18 -4
  196. package/wiki/Mail.md +14 -5
  197. package/wiki/Migrations-And-Backfills.md +29 -4
  198. package/wiki/Money.md +2 -0
  199. package/wiki/N-Plus-One-Detection.md +24 -22
  200. package/wiki/Notify.md +28 -4
  201. package/wiki/Observability.md +121 -15
  202. package/wiki/Queries-And-Live-Queries.md +2 -2
  203. package/wiki/Realtime.md +9 -4
  204. package/wiki/Routes-And-Render-Modes.md +5 -0
  205. package/wiki/Scraping.md +57 -11
  206. package/wiki/Shapes.md +2 -2
  207. package/wiki/Stability.md +7 -5
  208. package/wiki/Storage-And-Uploads.md +56 -4
  209. package/wiki/Testing.md +65 -52
  210. package/wiki/Troubleshooting.md +1 -1
  211. package/wiki/Tutorial-01-First-App.md +1 -1
  212. package/wiki/Tutorial-04-Jobs-And-Realtime.md +1 -1
  213. package/wiki/Tutorial-05-Deploy-Free.md +1 -1
  214. package/wiki/Tutorial-06-Growing-Up.md +8 -8
  215. package/wiki/Upgrading.md +136 -5
@@ -18,9 +18,10 @@
18
18
  import { join as joinPath } from 'node:path';
19
19
  // The POSIX variants resolve specifiers against import-graph keys, which are POSIX on every host.
20
20
  import { dirname, join, normalize, relative } from 'node:path/posix';
21
- import { ERROR_DOCS_URL } from '@ultimat3/core';
22
- import type { BoundaryRule, ImportGraph } from '@ultimat3/render';
23
- import { checkSurfaceBoundary, importGraph, SURFACES } from '@ultimat3/render';
21
+ import { ADAPTER_PORTS, ERROR_DOCS_URL, SURFACES } from '@ultimat3/core';
22
+ import type { BoundaryRule, ImportGraph, ImportRef } from '@ultimat3/render';
23
+ import { checkSurfaceBoundary, importGraph, surfaceOf } from '@ultimat3/render';
24
+ import { loaderImportFindings } from './app-loader-imports';
24
25
  import { commentSafe } from './comment-safe';
25
26
  import { scanRuntimeImports, stripShebang } from './import-scan';
26
27
  import type { Finding } from './output';
@@ -35,6 +36,8 @@ export const BOUNDARY_CODES = [
35
36
  'X_BOUNDARY_ROUTE_TO_DB',
36
37
  'X_BOUNDARY_SERVICE_TO_HTTP',
37
38
  'X_BOUNDARY_SURFACE_IMPORT',
39
+ 'X_BOUNDARY_ADAPTER_IMPORT',
40
+ 'X_BOUNDARY_LOADER_IMPORT',
38
41
  // `package-boundaries.ts`'s: it reads `packages/`, which this module's surface graph never holds.
39
42
  'X_BOUNDARY_PACKAGE_TO_APP',
40
43
  ] as const;
@@ -103,7 +106,7 @@ export function resolveSpecifier(
103
106
  specifier: string,
104
107
  keys: ReadonlySet<string>,
105
108
  ): string {
106
- if (!specifier.startsWith('.')) return specifier;
109
+ if (!specifier.startsWith('.')) return workspaceKey(specifier, keys) ?? specifier;
107
110
  const base = normalize(join(dirname(fromFile), specifier));
108
111
  for (const suffix of CANDIDATE_SUFFIXES) {
109
112
  if (keys.has(`${base}${suffix}`)) return `${base}${suffix}`;
@@ -111,6 +114,21 @@ export function resolveSpecifier(
111
114
  return base;
112
115
  }
113
116
 
117
+ /**
118
+ * `@<scope>/<app>/<rest>` → `apps/<app>/<rest>` when that lands on an app source: the spelling one
119
+ * app workspace reaches another by (`x new`'s root alias `@<app>/*` → `packages/*\/src`, then
120
+ * `apps/*`). Left unresolved, `apps/api/site/` importing `@acme/web/app/…` was an edge to nowhere
121
+ * and `X_BOUNDARY_SITE_TO_APP` never fired. Matched against the graph's own keys — a framework or
122
+ * package specifier lands on none — so a workspace whose package name differs from its directory
123
+ * is the one spelling this cannot see.
124
+ */
125
+ const workspaceKey = (specifier: string, keys: ReadonlySet<string>): string | undefined => {
126
+ const [, app, rest] = /^@[^/]+\/([^/]+)\/(.+)$/.exec(specifier) ?? [];
127
+ if (app === undefined || rest === undefined) return undefined;
128
+ const base = `apps/${app}/${rest}`;
129
+ return CANDIDATE_SUFFIXES.map((suffix) => `${base}${suffix}`).find((key) => keys.has(key));
130
+ };
131
+
114
132
  /**
115
133
  * The specifier `fromFile` must write to reach `target` — `resolveSpecifier` run backwards, and
116
134
  * what every import of a file has to become once that file moves. Extensionless, because that is
@@ -138,9 +156,36 @@ function scan(files: readonly SourceFile[]): readonly ScannedFile[] {
138
156
  }));
139
157
  }
140
158
 
159
+ /** `apps/<ws>/…` → `<ws>`, or `undefined` outside an app workspace. */
160
+ const workspaceOf = (path: string): string | undefined => /^apps\/([^/]+)\//.exec(path)?.[1];
161
+
162
+ /**
163
+ * An `app/` module reaching a SIBLING app's `api/` registry. `app/ → api/` is types-only inside
164
+ * one app because that app's `api/index.ts` imports its own `app/` slices — a value edge back is a
165
+ * cycle. Across workspaces there is none: `apps/admin` projecting `apps/web`'s actions through its
166
+ * `api` is the documented pattern. Such an edge enters the graph as declaration-only, which the
167
+ * table admits for `app` and still refuses for `site` (`SURFACE_SPECS`).
168
+ */
169
+ const isSiblingRegistry = (from: string, to: string): boolean => {
170
+ const own = workspaceOf(from);
171
+ const other = workspaceOf(to);
172
+ return (
173
+ own !== undefined &&
174
+ other !== undefined &&
175
+ own !== other &&
176
+ surfaceOf(from) === 'app' &&
177
+ surfaceOf(to) === 'api'
178
+ );
179
+ };
180
+
141
181
  function graphOf(scanned: readonly ScannedFile[]): ImportGraph {
142
- const record: Record<string, readonly string[]> = {};
143
- for (const file of scanned) record[file.path] = file.imports;
182
+ const record: Record<string, readonly ImportRef[]> = {};
183
+ for (const file of scanned) {
184
+ record[file.path] = file.imports.map((to) => ({
185
+ file: to,
186
+ type: isSiblingRegistry(file.path, to),
187
+ }));
188
+ }
144
189
  return importGraph(record);
145
190
  }
146
191
 
@@ -220,6 +265,21 @@ const routeToDbFix = (path: string, specifier: string): string => {
220
265
  return `x g query ${query} --feature ${quoteArg(slice)} # ${then}`;
221
266
  };
222
267
 
268
+ /** A package's `./adapter` subpath: the installers `runtime.ts` and the boot own, never an app module. */
269
+ const ADAPTER_SUBPATH = /^@ultimat3\/[a-z-]+\/adapter$/;
270
+
271
+ /**
272
+ * The `runtime.ts` field an import of `specifier` stands in for: the port named after its package
273
+ * (`@ultimat3/jobs/adapter` → `jobs`), else that package's first row. A real field, never a
274
+ * placeholder — the fix's runnable half is pasted as it stands.
275
+ */
276
+ const portOf = (specifier: string): string => {
277
+ const pkg = specifier.slice(0, -'/adapter'.length);
278
+ const rows = ADAPTER_PORTS.filter((row) => row.pkg === pkg);
279
+ const named = rows.find((row) => `@ultimat3/${row.port}` === pkg);
280
+ return (named ?? rows[0])?.port ?? 'jobs';
281
+ };
282
+
223
283
  /**
224
284
  * Both fixes are one runnable line, with the rest of the instruction behind a `#` — a fix a
225
285
  * caller has to edit before it runs is prose, and prose is what "errors are instructions" bans.
@@ -228,6 +288,16 @@ function layerFindings(scanned: readonly ScannedFile[]): readonly Finding[] {
228
288
  const findings: Finding[] = [];
229
289
  for (const file of scanned) {
230
290
  for (const specifier of file.imports) {
291
+ // `file.imports` is runtime imports only: `import type { Gateway }` from an adapter is fine.
292
+ if (ADAPTER_SUBPATH.test(specifier)) {
293
+ findings.push({
294
+ code: 'X_BOUNDARY_ADAPTER_IMPORT',
295
+ cause: `an app module imports "${specifier}" at runtime — its installers are the boot's, and one called from here races it (X_RUNTIME_DRIVER_SPLIT)`,
296
+ fix: `export const runtime = { ${quoteArg(portOf(specifier))}: yourDriver } satisfies RuntimeOverrides; # in apps/web/runtime.ts, then delete the import from ${commentSafe(file.path)}`,
297
+ docs: ERROR_DOCS_URL,
298
+ at: file.path,
299
+ });
300
+ }
231
301
  if (isRoute(file.path) && isDbSpecifier(specifier)) {
232
302
  findings.push({
233
303
  code: 'X_BOUNDARY_ROUTE_TO_DB',
@@ -257,7 +327,11 @@ function layerFindings(scanned: readonly ScannedFile[]): readonly Finding[] {
257
327
  */
258
328
  export function checkImportRules(files: readonly SourceFile[]): readonly Finding[] {
259
329
  const scanned = scan(files);
260
- return [...surfaceFindings(graphOf(scanned)), ...layerFindings(scanned)];
330
+ return [
331
+ ...surfaceFindings(graphOf(scanned)),
332
+ ...layerFindings(scanned),
333
+ ...loaderImportFindings(files),
334
+ ];
261
335
  }
262
336
 
263
337
  const APP_GLOBS = ['apps/*/{site,app,api,shared}/**/*.{ts,tsx}'];
@@ -267,12 +341,17 @@ const APP_GLOBS = ['apps/*/{site,app,api,shared}/**/*.{ts,tsx}'];
267
341
  * only I/O in this module, and the one definition of "which files are the app's sources" —
268
342
  * `appBoundaryFindings` reads through this, and so does `x fix boundary`, never a second glob.
269
343
  */
270
- export async function readAppSources(root: string): Promise<readonly SourceFile[]> {
344
+ export async function readAppSources(
345
+ root: string,
346
+ /** `tests`: the same surfaces' `.test.` files instead — read by the loader rule alone. */
347
+ which: 'sources' | 'tests' = 'sources',
348
+ ): Promise<readonly SourceFile[]> {
271
349
  const files: SourceFile[] = [];
272
350
  for (const pattern of APP_GLOBS) {
273
351
  const glob = new Bun.Glob(pattern);
274
352
  for await (const path of glob.scan({ cwd: root, absolute: false })) {
275
- if (hasPathSegment(path, 'node_modules') || path.includes('.test.')) continue;
353
+ if (hasPathSegment(path, 'node_modules')) continue;
354
+ if (path.includes('.test.') !== (which === 'tests')) continue;
276
355
  const posix = toPosix(path);
277
356
  files.push({ path: posix, source: await Bun.file(joinPath(root, posix)).text() });
278
357
  }
@@ -0,0 +1,133 @@
1
+ // Which app modules evaluate ASYNCHRONOUSLY — a top-level `await` in the module or in anything of
2
+ // the app's it imports. In one entry module such a module suspends and its later siblings run
3
+ // meanwhile, so the batched import (`app-load-batch.ts`) imports each on its own: the serial
4
+ // scan's evaluation order is the guarantee, and these are the modules that would break it.
5
+
6
+ // why: Bun ships no path API; the walk resolves imports to absolute paths and names them back.
7
+ import { basename, resolve } from 'node:path';
8
+ import { resolvedImports } from './module-imports';
9
+ import { hasPathSegment, isPathUnder } from './path-segments';
10
+ import { isTest } from './source-files';
11
+
12
+ /** Every source the app could import: the scan's globs are not the whole of what modules import. */
13
+ const APP_SOURCE = '**/*.{ts,tsx,mts,js,jsx,mjs}';
14
+
15
+ const transpilers = {
16
+ ts: new Bun.Transpiler({ loader: 'ts' }),
17
+ tsx: new Bun.Transpiler({ loader: 'tsx' }),
18
+ js: new Bun.Transpiler({ loader: 'js' }),
19
+ };
20
+
21
+ /**
22
+ * The module statements, removed or turned into the declarations they export, so what remains
23
+ * is a statement list a class static block can hold. Read off Bun's own printed output, whose
24
+ * shape is fixed: one statement per `import`/`export`, double-quoted specifiers.
25
+ */
26
+ function withoutModuleSyntax(printed: string): string {
27
+ return printed
28
+ .replace(/^import\s[\s\S]*?\sfrom\s*"[^"]*";/gm, '')
29
+ .replace(/^import\s*"[^"]*";/gm, '')
30
+ .replace(/^export\s*\*[^;]*;/gm, '')
31
+ .replace(/^export\s*\{[\s\S]*?\}(?:\s*from\s*"[^"]*")?;/gm, '')
32
+ .replace(/^export\s+default\s+/gm, 'void ')
33
+ .replace(/^export\s+/gm, '')
34
+ .replace(/\bimport\.meta\b/g, '({})');
35
+ }
36
+
37
+ /**
38
+ * Whether `source` awaits at its top level. Parsed, never pattern-matched: the statements go into a
39
+ * class static block, where `await` is reserved — `await x`, `await (x)` and `for await` refuse
40
+ * there exactly as they run at a module's top level, while every `await` inside an async function
41
+ * still parses. A source the parser refuses for any other reason is answered `true`: importing it
42
+ * alone costs a little speed, importing it in a batch could cost the order.
43
+ */
44
+ export function hasTopLevelAwait(path: string, source: string): boolean {
45
+ if (!source.includes('await')) return false;
46
+ const loader = /x$/.test(path) ? transpilers.tsx : transpilers.ts;
47
+ try {
48
+ const statements = withoutModuleSyntax(loader.transformSync(source));
49
+ transpilers.js.transformSync(`class __XTopLevel { static {\n${statements}\n} }`);
50
+ return false;
51
+ } catch {
52
+ return true;
53
+ }
54
+ }
55
+
56
+ const inApp = (root: string, path: string): boolean =>
57
+ isPathUnder(root, path) && !hasPathSegment(path, 'node_modules');
58
+
59
+ /** Every app source, read, and the ones that await at their top level. */
60
+ async function readSources(root: string): Promise<{
61
+ readonly sources: ReadonlyMap<string, string>;
62
+ readonly awaiting: readonly string[];
63
+ }> {
64
+ const sources = new Map<string, string>();
65
+ const awaiting: string[] = [];
66
+ const paths: string[] = [];
67
+ for await (const path of new Bun.Glob(APP_SOURCE).scan({ cwd: root, absolute: true })) {
68
+ // A test is imported by no module: `bun test` loads it, never the scan.
69
+ if (!hasPathSegment(path, 'node_modules') && !isTest(path)) paths.push(path);
70
+ }
71
+ // Bounded: an app of 12k files opened 12k descriptors at once otherwise.
72
+ for (let start = 0; start < paths.length; start += 64) {
73
+ const batch = paths.slice(start, start + 64);
74
+ const texts = await Promise.all(batch.map((path) => Bun.file(path).text()));
75
+ for (const [index, path] of batch.entries()) {
76
+ const text = texts[index] as string;
77
+ sources.set(path, text);
78
+ if (hasTopLevelAwait(path, text)) awaiting.push(path);
79
+ }
80
+ }
81
+ return { sources, awaiting };
82
+ }
83
+
84
+ /**
85
+ * Whether any source could import `path`: a specifier ending in its file name, with or without the
86
+ * extension. A filter, never the answer — it only spares the import walk for the awaiting modules
87
+ * nothing names, which are most of them: `server.ts`, `prerender.ts`, `bin/` scripts.
88
+ */
89
+ function named(path: string, sources: ReadonlyMap<string, string>): boolean {
90
+ const file = basename(path);
91
+ const stem = file.replace(/\.[cm]?[jt]sx?$/, '');
92
+ const escaped = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
93
+ const specifier = new RegExp(`[/'"](?:${escaped(stem)}|${escaped(file)})['"]`);
94
+ for (const [other, text] of sources) {
95
+ if (other !== path && specifier.test(text)) return true;
96
+ }
97
+ return false;
98
+ }
99
+
100
+ /**
101
+ * The modules of `modules` (absolute) whose evaluation can suspend: one that awaits at its top
102
+ * level, or reaches one through the app's own imports. The framework and `node_modules` are not
103
+ * walked — the CLI has evaluated the framework before any scan, so it is no longer async. The
104
+ * common answer, no importable top-level await in the app, costs one read of each source.
105
+ */
106
+ export async function asyncModules(
107
+ root: string,
108
+ modules: readonly string[],
109
+ ): Promise<ReadonlySet<string>> {
110
+ const base = resolve(root);
111
+ const { sources, awaiting } = await readSources(base);
112
+ // The common answer: nothing the app could import awaits at its top level, and no walk runs.
113
+ if (!awaiting.some((path) => modules.includes(path) || named(path, sources))) return new Set();
114
+ const answered = new Map<string, boolean>();
115
+ const reaches = (path: string, visiting: Set<string>): boolean => {
116
+ const known = answered.get(path);
117
+ if (known !== undefined) return known;
118
+ // A cycle is answered by the rest of the walk: the module on the stack is still deciding.
119
+ if (visiting.has(path)) return false;
120
+ visiting.add(path);
121
+ const source = sources.get(path);
122
+ const awaits =
123
+ source !== undefined &&
124
+ (hasTopLevelAwait(path, source) ||
125
+ resolvedImports(path, source, 'evaluated')
126
+ .filter((target) => inApp(base, target))
127
+ .some((target) => reaches(target, visiting)));
128
+ visiting.delete(path);
129
+ answered.set(path, awaits);
130
+ return awaits;
131
+ };
132
+ return new Set(modules.filter((path) => reaches(path, new Set())));
133
+ }
@@ -0,0 +1,203 @@
1
+ // Importing many app modules at once, with the serial loop's guarantee: each module is evaluated,
2
+ // then handed to `onEvaluated`, before the next one starts — so a module reads every earlier one
3
+ // REGISTERED. A batch is an entry that imports one hook module per app module (`batchSources`);
4
+ // a module that can suspend (top-level await) is a batch of its own (`app-load-async.ts`).
5
+
6
+ // why: Bun ships no temp directory, no path API and no recursive delete of its own.
7
+ import { mkdir, rm } from 'node:fs/promises';
8
+ // why: as above — the batch lives in the platform temp root, which only node:os names.
9
+ import { tmpdir } from 'node:os';
10
+ // why: Bun exposes no path-join primitive.
11
+ import { join } from 'node:path';
12
+
13
+ /**
14
+ * Modules per entry. A bound, not a tuning knob: the loader holds a batch's whole graph — every
15
+ * source, every transpiled module — before it evaluates the first, so an unbounded entry over a
16
+ * 12k-module app held all of it at once. Measured on a 5,000-module fixture (2026-11-09): 64 →
17
+ * 1.04 s, 256 → 0.87 s, 1,000 → 0.84 s, serial → 1.36 s. The hooks cost their own module each:
18
+ * re-measured 2026-11-10 (median of 5 cold boots), serial 2.19 s, hooked batches 1.39 s, and the
19
+ * order-breaking hookless entry 0.90 s.
20
+ */
21
+ export const BATCH_SIZE = 256;
22
+
23
+ /** One module's import: the namespace it evaluated to, or what it threw. */
24
+ export type Imported =
25
+ | { readonly ok: true; readonly module: Record<string, unknown> }
26
+ | { readonly ok: false; readonly error: unknown };
27
+
28
+ /**
29
+ * Called once per module that evaluated, by its index in scan order, before the next module in
30
+ * that order is evaluated. The scan registers here: what a later module reads at its top level —
31
+ * `defineAppMcp({ include: 'exposed' })` reads the action registry — is what the serial scan left.
32
+ */
33
+ export type OnEvaluated = (index: number, module: Record<string, unknown>) => void;
34
+
35
+ /** The global a hook module reports through: one well-known symbol, owned by `receiving`. */
36
+ const HOOK = 'ultimate.scan.evaluated';
37
+
38
+ /** The file one hook module is written to, beside its entry: named by the module's scan index. */
39
+ export const hookFile = (index: number): string => `m${String(index)}.ts`;
40
+
41
+ /**
42
+ * One batch's sources: a hook per module — it imports the module and reports it — and an entry
43
+ * that imports the hooks in order. ES evaluation walks the entry's imports depth-first, so hook N
44
+ * runs after module N and before module N+1: a static graph the loader fetches concurrently, with
45
+ * the serial loop's interleaving of evaluate and register. Never the modules themselves in one
46
+ * entry: static imports evaluate every one before the entry's first statement runs.
47
+ */
48
+ export function batchSources(
49
+ specifiers: readonly string[],
50
+ first: number,
51
+ ): { readonly entry: string; readonly hooks: readonly (readonly [string, string])[] } {
52
+ const hooks = specifiers.map((specifier, offset): readonly [string, string] => [
53
+ hookFile(first + offset),
54
+ `import * as m from ${JSON.stringify(specifier)};\n` +
55
+ `globalThis[Symbol.for(${JSON.stringify(HOOK)})]?.(${String(first + offset)}, m);\n`,
56
+ ]);
57
+ const entry = hooks.map(([name]) => `import ${JSON.stringify(`./${name}`)};`).join('\n');
58
+ return { entry: `${entry}\n`, hooks };
59
+ }
60
+
61
+ /**
62
+ * Runs `load` with `receive` installed as the hooks' target, or answers `undefined` without
63
+ * running it when another load holds the slot: two at once would hand one's modules to the other.
64
+ * A receiver that throws is contained — a throw would fail the hook, and the batch with it.
65
+ */
66
+ export async function receiving<T>(
67
+ receive: OnEvaluated,
68
+ load: () => Promise<T>,
69
+ ): Promise<T | undefined> {
70
+ const slot = Symbol.for(HOOK);
71
+ if (Reflect.get(globalThis, slot) !== undefined) return undefined;
72
+ const contained: OnEvaluated = (index, module) => {
73
+ try {
74
+ receive(index, module);
75
+ } catch {
76
+ // `registerModule` answers a finding, never a throw; anything else is not the batch's.
77
+ }
78
+ };
79
+ Reflect.set(globalThis, slot, contained);
80
+ try {
81
+ return await load();
82
+ } finally {
83
+ Reflect.deleteProperty(globalThis, slot);
84
+ }
85
+ }
86
+
87
+ /**
88
+ * A directory no other batch has used — in this process or any copy of this module in it. Bun's
89
+ * module cache is keyed by path and outlives a module instance: `bun test --parallel` evaluates
90
+ * this file afresh per test file in one worker, and a per-instance counter named the same
91
+ * directory twice, so the second load imported the first one's cached hooks and was handed the
92
+ * first app's modules (2026-11-10, `app-load-batch.test.ts`).
93
+ */
94
+ export const uniqueBatchName = (): string => `x-scan-${crypto.randomUUID()}`;
95
+
96
+ /** The serial import, for one module: what the batch falls back to. */
97
+ async function importOne(absolute: string): Promise<Imported> {
98
+ try {
99
+ return { ok: true, module: (await import(absolute)) as Record<string, unknown> };
100
+ } catch (error) {
101
+ return { ok: false, error };
102
+ }
103
+ }
104
+
105
+ /** A batch's answers, filled by the hooks as they run and by the serial fallback after. */
106
+ type Slots = (Imported | undefined)[];
107
+
108
+ /** Imports `absolute` serially unless a hook already answered it, and reports a first evaluation. */
109
+ async function fillSerially(
110
+ batch: readonly string[],
111
+ first: number,
112
+ slots: Slots,
113
+ onEvaluated: OnEvaluated,
114
+ ): Promise<void> {
115
+ for (const [offset, absolute] of batch.entries()) {
116
+ if (slots[offset] !== undefined) continue;
117
+ const one = await importOne(absolute);
118
+ slots[offset] = one;
119
+ if (one.ok) onEvaluated(first + offset, one.module);
120
+ }
121
+ }
122
+
123
+ /**
124
+ * One batch. Any failure in it — a module that throws, one that cannot link — fails the entry:
125
+ * every module before the failing one has evaluated and been reported, and the rest are imported
126
+ * module by module — the failing one throws its own error again, every one after it evaluates in
127
+ * its serial turn. A temp root that cannot be written (a read-only container) is the serial loop
128
+ * too: slower, never wrong.
129
+ */
130
+ async function importBatch(
131
+ batch: readonly string[],
132
+ first: number,
133
+ onEvaluated: OnEvaluated,
134
+ ): Promise<readonly Imported[]> {
135
+ const slots: Slots = batch.map(() => undefined);
136
+ if (batch.length > 1) {
137
+ const dir = join(tmpdir(), uniqueBatchName());
138
+ const { entry, hooks } = batchSources(
139
+ batch.map((absolute) => Bun.pathToFileURL(absolute).href),
140
+ first,
141
+ );
142
+ const receive: OnEvaluated = (index, module) => {
143
+ slots[index - first] = { ok: true, module };
144
+ onEvaluated(index, module);
145
+ };
146
+ try {
147
+ await mkdir(dir, { recursive: true });
148
+ await Promise.all(hooks.map(([name, source]) => Bun.write(join(dir, name), source)));
149
+ await Bun.write(join(dir, 'entry.ts'), entry);
150
+ await receiving(receive, () => import(join(dir, 'entry.ts')));
151
+ } catch {
152
+ // Answered below, module by module, with each module's own error.
153
+ } finally {
154
+ await rm(dir, { recursive: true, force: true });
155
+ }
156
+ }
157
+ await fillSerially(batch, first, slots, onEvaluated);
158
+ return slots as Imported[];
159
+ }
160
+
161
+ /**
162
+ * `absolutes` cut into entry-sized batches, in order. A module in `alone` — one whose evaluation can
163
+ * suspend — ends the batch before it and is a batch by itself: an entry module waits for it before
164
+ * anything after it starts. The scan and the prebuilt registry both cut here, so both keep order.
165
+ */
166
+ export function planBatches(
167
+ absolutes: readonly string[],
168
+ alone: ReadonlySet<string> = new Set(),
169
+ ): readonly (readonly string[])[] {
170
+ const batches: string[][] = [];
171
+ let current: string[] = [];
172
+ const flush = (): void => {
173
+ if (current.length > 0) batches.push(current);
174
+ current = [];
175
+ };
176
+ for (const absolute of absolutes) {
177
+ if (alone.has(absolute)) {
178
+ flush();
179
+ batches.push([absolute]);
180
+ continue;
181
+ }
182
+ current.push(absolute);
183
+ if (current.length === BATCH_SIZE) flush();
184
+ }
185
+ flush();
186
+ return batches;
187
+ }
188
+
189
+ /**
190
+ * Every module of `absolutes`, imported in `planBatches`' batches and answered in the same order;
191
+ * `onEvaluated` hears each module that evaluated, in that order, before the next one evaluates.
192
+ */
193
+ export async function importInOrder(
194
+ absolutes: readonly string[],
195
+ alone: ReadonlySet<string> = new Set(),
196
+ onEvaluated: OnEvaluated = () => undefined,
197
+ ): Promise<readonly Imported[]> {
198
+ const imported: Imported[] = [];
199
+ for (const batch of planBatches(absolutes, alone)) {
200
+ imported.push(...(await importBatch(batch, imported.length, onEvaluated)));
201
+ }
202
+ return imported;
203
+ }
@@ -0,0 +1,147 @@
1
+ // A serving role's import of the app from the image's prebuilt registry (`build-registry.ts`):
2
+ // the chunks `x build --target prebuilt` wrote — every module's, or the background roles' subset —
3
+ // imported in order and registered, with no import scan and no document-graph walk. `undefined`
4
+ // whenever the registry cannot be trusted to be the app, so the caller scans instead.
5
+
6
+ // why: Bun ships no path-join primitive.
7
+ import { join } from 'node:path';
8
+ import { logger, UltimateError } from '@ultimat3/core';
9
+ import type { AppScan } from './app-load';
10
+ import { prepareAppImport, scannedModulePaths } from './app-load';
11
+ import type { OnEvaluated } from './app-load-batch';
12
+ import { receiving } from './app-load-batch';
13
+ import { registerModule } from './app-load-register';
14
+ import type { RegistryChunks } from './build-registry';
15
+ import { moduleStamp, readPrebuiltRegistry, registryDir } from './build-registry';
16
+ import type { Finding } from './output';
17
+ import { posixRelative } from './posix-path';
18
+ import type { RoleLoad } from './role-load';
19
+ import { PREBUILT_COMMAND } from './serve-prebuilt-paths';
20
+
21
+ /**
22
+ * Logged, never thrown: a stale registry is answered by the scan, which imports what is on disk.
23
+ * In an image it cannot happen — the registry is written after the source is copied in — so it
24
+ * says the Dockerfile copies something after the prebuilt step.
25
+ */
26
+ export class PrebuiltRegistryStaleError extends UltimateError {
27
+ constructor(input: {
28
+ readonly added: readonly string[];
29
+ readonly removed: readonly string[];
30
+ /** The same modules, and one at least was rewritten since the build (a background boot's check). */
31
+ readonly changed?: boolean;
32
+ }) {
33
+ const first = [...input.added, ...input.removed].slice(0, 3).join(', ');
34
+ const what = input.changed
35
+ ? 'lists the modules on disk, and one or more of them changed content since it was written (which of them reach a component decides what a worker imports)'
36
+ : `lists ${String(input.removed.length)} module(s) not on disk and misses ${String(input.added.length)} that are (${first})`;
37
+ super({
38
+ code: 'X_PREBUILT_REGISTRY_STALE',
39
+ cause: `the prebuilt module registry ${what}, so this boot scanned the app instead of importing the registry`,
40
+ fix: `edit docker/Dockerfile: move RUN ${PREBUILT_COMMAND} after the last COPY in the runtime stage, then rebuild the image`,
41
+ meta: { added: input.added, removed: input.removed, changed: input.changed === true },
42
+ });
43
+ }
44
+ }
45
+
46
+ /** The module list `files` against the one on disk, as what each lacks. */
47
+ function difference(
48
+ listed: readonly string[],
49
+ onDisk: readonly string[],
50
+ ): { readonly added: readonly string[]; readonly removed: readonly string[] } {
51
+ const held = new Set(listed);
52
+ const present = new Set(onDisk);
53
+ return {
54
+ added: onDisk.filter((file) => !held.has(file)),
55
+ removed: listed.filter((file) => !present.has(file)),
56
+ };
57
+ }
58
+
59
+ /**
60
+ * Every chunk imported in order, each module reported to `receive` as it evaluates — or `false`
61
+ * when one would not import, or another load held the hooks' slot.
62
+ */
63
+ async function importChunks(
64
+ dir: string,
65
+ chunks: readonly string[],
66
+ receive: OnEvaluated,
67
+ ): Promise<boolean> {
68
+ const imported = await receiving(receive, async () => {
69
+ for (const chunk of chunks) {
70
+ try {
71
+ await import(join(dir, chunk));
72
+ } catch {
73
+ // The scan imports module by module and reports the one that fails, with its own cause.
74
+ return false;
75
+ }
76
+ }
77
+ return true;
78
+ });
79
+ return imported === true;
80
+ }
81
+
82
+ /** Logs the registry stale and answers `undefined`: the caller scans. */
83
+ function stale(input: ConstructorParameters<typeof PrebuiltRegistryStaleError>[0]): undefined {
84
+ const error = new PrebuiltRegistryStaleError(input);
85
+ logger.warn(error.format(), { code: error.code, ...error.meta });
86
+ return undefined;
87
+ }
88
+
89
+ /**
90
+ * The app, imported from the prebuilt registry and registered in its order — every module for a
91
+ * role that imports `everything`, the background subset for `worker` and `scheduler` — or
92
+ * `undefined`: no registry, one this Bun did not write, one whose module list is not the disk's
93
+ * (logged, `X_PREBUILT_REGISTRY_STALE`), or a chunk that would not import. The list is checked
94
+ * against the scan's own glob, which reads directory entries and imports nothing: a module added
95
+ * after the build is a route or an action the registry would silently not serve. A background
96
+ * boot also checks every module's stamp: its subset is decided by what the modules import.
97
+ */
98
+ export async function loadPrebuiltApp(
99
+ root: string,
100
+ load: RoleLoad = 'everything',
101
+ ): Promise<AppScan | undefined> {
102
+ const registry = await readPrebuiltRegistry(root);
103
+ if (registry === undefined) return undefined;
104
+ const scanned = await scannedModulePaths(root);
105
+ const onDisk = scanned.map((absolute) => posixRelative(root, absolute));
106
+ if (onDisk.join('\n') !== registry.files.join('\n')) {
107
+ return stale(difference(registry.files, onDisk));
108
+ }
109
+ if (load === 'background') {
110
+ const stamp = await moduleStamp(root, registry.files);
111
+ if (stamp !== registry.background.stamp)
112
+ return stale({ added: [], removed: [], changed: true });
113
+ }
114
+ // The glob's own spelling of each path: registration is keyed by it, and a later full load (the
115
+ // background boot's fallback) must find these modules registered under the same key.
116
+ const absoluteOf = new Map(onDisk.map((file, index) => [file, scanned[index] as string]));
117
+ const set = load === 'background' ? registry.background : registry;
118
+ const absolutes = set.files.map((file) => absoluteOf.get(file));
119
+ if (absolutes.some((absolute) => absolute === undefined)) return undefined;
120
+ return importRegistered(root, set, absolutes as string[]);
121
+ }
122
+
123
+ /** `set`'s chunks imported and each module registered as it evaluates, in the set's order. */
124
+ async function importRegistered(
125
+ root: string,
126
+ set: RegistryChunks,
127
+ absolutes: readonly string[],
128
+ ): Promise<AppScan | undefined> {
129
+ prepareAppImport(root);
130
+ // Registered as each module evaluates, by its hook: a later module reads every earlier one
131
+ // registered, as the scan leaves them (`app-load-batch.ts`).
132
+ const findings: (Finding | undefined)[] = [];
133
+ let evaluated = 0;
134
+ const register: OnEvaluated = (index, module) => {
135
+ const absolute = absolutes[index];
136
+ if (absolute === undefined) return;
137
+ evaluated += 1;
138
+ const at = { absolute, file: set.files[index] as string, track: false };
139
+ findings[index] = registerModule(module, at);
140
+ };
141
+ const imported = await importChunks(registryDir(root), set.chunks, register);
142
+ if (!imported || evaluated !== absolutes.length) return undefined;
143
+ return {
144
+ files: [...set.files].sort(),
145
+ findings: findings.filter((finding): finding is Finding => finding !== undefined),
146
+ };
147
+ }