@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
package/src/serve-env.ts CHANGED
@@ -7,10 +7,15 @@ import {
7
7
  configureErrorReporting,
8
8
  errorReportersOf,
9
9
  installedErrorReporter,
10
+ isLocalErrorSink,
10
11
  isRole,
12
+ isSentryErrorReporter,
13
+ logger,
11
14
  ROLES,
12
15
  sentryErrorReporter,
16
+ UltimateError,
13
17
  } from '@ultimat3/core';
18
+ import { installErrorReporter } from '@ultimat3/core/adapter';
14
19
  import { PortInvalidError, RoleUnknownError } from './errors';
15
20
  import { DEFAULT_METRICS_PORT } from './metrics-endpoint';
16
21
  import type { WebBinding } from './role-start';
@@ -111,27 +116,55 @@ export const metricsPortFor = (env: Env, port: number, override?: number): numbe
111
116
  */
112
117
  export const ERROR_DSN_KEY = 'SENTRY_DSN';
113
118
 
114
- /** The transport the LAST `configureReporting` installed, so a second boot swaps it, never adds. */
119
+ /** The transport the LAST `configureReporting` chained, so a second boot swaps it, never adds. */
115
120
  let vendor: ErrorReporter | undefined;
116
121
 
117
122
  /**
118
- * Switch reporting on for this process. Unset DSN leaves whatever the app installed (or core's
119
- * no-op) in place, so a laptop and a CI run pay nothing and page nobody — and the release every
123
+ * Logged, never thrown: `SENTRY_DSN` is set and the app installed reporters that are neither its
124
+ * marked Sentry transport nor local sinks — so the boot adds none, and says how to mark them.
125
+ */
126
+ export class ErrorReporterDsnUnclaimedError extends UltimateError {
127
+ constructor(reporters: number) {
128
+ super({
129
+ code: 'X_ERROR_REPORTER_DSN_UNCLAIMED',
130
+ cause: `${ERROR_DSN_KEY} is set and the app installed ${String(reporters)} error reporter(s) marked neither as its Sentry transport nor as a local sink — one may already send to a monitor, so the boot adds no second transport and nothing is sent to that DSN`,
131
+ fix: 'errorReporter: sentryTransport(yourWrapper) // in apps/web/runtime.ts, around the reporter that wraps sentryErrorReporter — or localErrorSink(yourSink) when it keeps reports on the box, and the boot adds the DSN transport beside it',
132
+ meta: { key: ERROR_DSN_KEY, reporters },
133
+ });
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Switch reporting on for this process, and answer the release of what it installed. Unset DSN
139
+ * leaves the app's reporter — `runtime.ts`'s `errorReporter`, installed before `loadApp` — (or
140
+ * core's no-op) in place, so a laptop and a CI run pay nothing and page nobody — and the release every
120
141
  * event carries is the build id this boot already computed, never a second identity for the deploy.
121
142
  *
122
- * The transport is CHAINED beside the app's reporter, never over it: the app's modules import —
123
- * and install an `errorGroupsSink`, say — before this line runs, and replacing it here would
124
- * leave `/admin/errors` empty in exactly the deploys that set `SENTRY_DSN`.
143
+ * The rule (v31): the boot adds its `SENTRY_DSN` transport beside the app's reporters when every
144
+ * one of them is a LOCAL sink (`localErrorSink`: `errorGroupsSink`, `memoryErrorReporter`) — or
145
+ * there are none. An app whose reporters include its own Sentry transport (`sentryErrorReporter`,
146
+ * or a wrapper marked `sentryTransport`) keeps it as the only one: a boot that chained a second
147
+ * beside it sent every error twice, once unscrubbed. Any other reporter is `{ report }` and might
148
+ * be a transport, so the boot adds nothing beside it and logs `X_ERROR_REPORTER_DSN_UNCLAIMED`.
125
149
  */
126
- export function configureReporting(env: Env, buildId: string): void {
150
+ export function configureReporting(env: Env, buildId: string): () => void {
127
151
  const dsn = env[ERROR_DSN_KEY]?.trim();
128
- // A malformed DSN throws here, at boot, rather than at the first outage: a monitor that was
129
- // never connected looks exactly like an app that never failed.
130
- const next = dsn === undefined || dsn.length === 0 ? undefined : sentryErrorReporter({ dsn });
131
152
  const app = errorReportersOf(installedErrorReporter()).filter((member) => member !== vendor);
153
+ // A malformed DSN throws here, at boot, rather than at the first outage: a monitor that was
154
+ // never connected looks exactly like an app that never failed — checked even when the app's
155
+ // reporters keep the boot from adding it, so a DSN that could never have connected is never silent.
156
+ const built = dsn === undefined || dsn.length === 0 ? undefined : sentryErrorReporter({ dsn });
157
+ const owned = app.some(isSentryErrorReporter);
158
+ const unmarked = app.filter(
159
+ (member) => !isSentryErrorReporter(member) && !isLocalErrorSink(member),
160
+ );
161
+ const next = owned || unmarked.length > 0 ? undefined : built;
162
+ if (built !== undefined && !owned && unmarked.length > 0) {
163
+ const unclaimed = new ErrorReporterDsnUnclaimedError(unmarked.length);
164
+ logger.warn(unclaimed.format(), { code: unclaimed.code, ...unclaimed.meta });
165
+ }
132
166
  vendor = next;
133
- configureErrorReporting({
134
- release: buildId,
135
- reporter: chainErrorReporters(...app, ...(next === undefined ? [] : [next])),
136
- });
167
+ configureErrorReporting({ release: buildId });
168
+ // A frame ABOVE the app's: its release restores exactly the app's reporter, whatever stopped first.
169
+ return installErrorReporter(chainErrorReporters(...app, ...(next === undefined ? [] : [next])));
137
170
  }
@@ -15,5 +15,8 @@ export const PREBUILT_ISLANDS_DIR = `${PREBUILT_DIR}/islands`;
15
15
 
16
16
  export const PREBUILT_SASS_DIR = `${PREBUILT_DIR}/sass`;
17
17
 
18
+ /** The app's module registry: what a serving role imports instead of scanning (`build-registry.ts`). */
19
+ export const PREBUILT_REGISTRY_DIR = `${PREBUILT_DIR}/registry`;
20
+
18
21
  /** The Dockerfile line that writes the store — one spelling, for the template and every `fix:`. */
19
22
  export const PREBUILT_COMMAND = 'bun node_modules/@ultimat3/cli/src/bin.ts build --target prebuilt';
@@ -9,8 +9,9 @@ import { existsSync } from 'node:fs';
9
9
  // why: Bun ships no path-join primitive.
10
10
  import { join } from 'node:path';
11
11
  import type { Role } from '@ultimat3/core';
12
- import { logger, UltimateError } from '@ultimat3/core';
12
+ import { logger, tryResolveEnvironment, UltimateError } from '@ultimat3/core';
13
13
  import { sassCompilations, setSassCacheDir } from '@ultimat3/render/server';
14
+ import type { Env } from './runtime-bindings';
14
15
  import { PREBUILT_COMMAND, PREBUILT_SASS_DIR } from './serve-prebuilt-paths';
15
16
 
16
17
  /**
@@ -75,10 +76,20 @@ export function watchBootBuilds(): (islands?: BootBuilds['islands']) => BootBuil
75
76
  });
76
77
  }
77
78
 
78
- /** One `error` line when the boot built anything, and nothing when it built nothing. */
79
- export function reportBootBuilds(role: Role, builds: BootBuilds): boolean {
79
+ /**
80
+ * One line when the boot built anything, and nothing when it built nothing. `warn` only where the
81
+ * environment is DECLARED local (`ULTIMATE_ENV` or `NODE_ENV` = `development`/`test`): no image
82
+ * exists to fix, and an `error` in every test boot buries the real ones. `error` everywhere else —
83
+ * `staging` fails the way production does, and a container that declares nothing, or names no
84
+ * environment, is read as production: the direction that still pages.
85
+ */
86
+ export function reportBootBuilds(role: Role, builds: BootBuilds, env: Env): boolean {
80
87
  if (builds.islands === undefined && builds.stylesheets === 0) return false;
81
88
  const error = new ImageNotPrebuiltError({ role, ...builds });
82
- logger.error(error.format(), { code: error.code, ...error.meta });
89
+ const environment = tryResolveEnvironment({ env, fallback: 'production' });
90
+ const local = environment === 'development' || environment === 'test';
91
+ const fields = { code: error.code, ...error.meta };
92
+ if (local) logger.warn(error.format(), fields);
93
+ else logger.error(error.format(), fields);
83
94
  return true;
84
95
  }
package/src/serve.ts CHANGED
@@ -12,7 +12,7 @@ import { type BootedHold, holdWhileBooting } from './hold';
12
12
  import { rolePorts, startMetricsEndpoint } from './metrics-endpoint';
13
13
  import { readMigrations } from './migrations';
14
14
  import { resolveServices } from './runtime-bindings';
15
- import { startQueue } from './runtime-queue';
15
+ import { startQueueWithBoot } from './runtime-boot-ports';
16
16
  import { containerBinding, metricsPortFor, portFromEnv, roleFromEnv } from './serve-env';
17
17
  import type { MigratedApp, ServedApp, ServeOptions, StartedApp } from './serve-types';
18
18
 
@@ -51,7 +51,7 @@ export async function runMigrations(options: ServeOptions): Promise<MigratedApp>
51
51
  // `'apply'`, never the stamp-first default: this IS the step that applies, and an operator
52
52
  // re-running it is how a dropped framework table comes back.
53
53
  const services = resolveServices(options.root, options.env);
54
- const queue = await startQueue(services, options.runtime, options.env, 'apply');
54
+ const queue = await startQueueWithBoot(services, options.runtime, options.env, 'apply');
55
55
  try {
56
56
  const migrations = await readMigrations(options.root);
57
57
  // PGlite with `database.rowSecurity`: the app's migrations run as `x_migrator` for their scope.
@@ -0,0 +1,61 @@
1
+ // The GPU backend the photographed page could reach, read from `navigator.gpu` inside the page.
2
+ // A WebGPU canvas that came out blank on a headless machine with no adapter is a fact about the
3
+ // machine, not the app — and a picture alone cannot tell the two apart. Recorded, never gating.
4
+
5
+ import type { StandardSchemaV1 } from '@ultimat3/schema';
6
+ import { t, validate } from '@ultimat3/schema';
7
+ import type { JsonValue } from './output';
8
+
9
+ export interface ShotGpu {
10
+ /** `navigator.gpu` exists — the browser exposes WebGPU at all. */
11
+ readonly api: boolean;
12
+ /** `requestAdapter()` answered an adapter: WebGPU is usable on this page, on this machine. */
13
+ readonly available: boolean;
14
+ /** The adapter's `info` (vendor, architecture, device, description), or `null` with none. */
15
+ readonly adapter: string | null;
16
+ /** A software adapter (SwiftShader and kin): it renders, at a speed no user sees. */
17
+ readonly fallback: boolean;
18
+ }
19
+
20
+ /**
21
+ * An expression, never a closure: `CdpPageLike.evaluate` takes the string form and awaits the
22
+ * promise. `requestAdapter()` is raced against a bound so a browser that never answers cannot
23
+ * hold a capture whose picture is already taken. `adapter.info` is current Chrome; older ones
24
+ * spell the flag `isFallbackAdapter` on the adapter, which is why both are read.
25
+ */
26
+ export const GPU_PROBE =
27
+ '(async function(){var g=navigator.gpu;' +
28
+ 'if(!g)return{api:false,available:false,adapter:null,fallback:false};var a=null;' +
29
+ 'try{a=await Promise.race([g.requestAdapter(),' +
30
+ 'new Promise(function(r){setTimeout(function(){r(null);},2000);})]);}catch(e){a=null;}' +
31
+ 'if(!a)return{api:true,available:false,adapter:null,fallback:false};var i=a.info||{};' +
32
+ 'var n=[i.vendor,i.architecture,i.device,i.description].filter(function(s){return !!s;})' +
33
+ '.join(" ");return{api:true,available:true,adapter:n===""?null:n,' +
34
+ 'fallback:!!(a.isFallbackAdapter||i.isFallbackAdapter)};})()';
35
+
36
+ const gpuProbeSchema: StandardSchemaV1<unknown, ShotGpu> = t.object({
37
+ api: t.boolean,
38
+ available: t.boolean,
39
+ adapter: t.nullable(t.string),
40
+ fallback: t.boolean,
41
+ }) as unknown as StandardSchemaV1<unknown, ShotGpu>;
42
+
43
+ /** Parsed, never cast: a page can answer anything. `null` for a shape that does not fit. */
44
+ export function parseGpuProbe(value: unknown): ShotGpu | null {
45
+ const result = validate(gpuProbeSchema, value);
46
+ return result.issues === undefined ? result.value : null;
47
+ }
48
+
49
+ /** `null` when the page refused the probe — "not read" is never reported as "no GPU". */
50
+ export const readShotGpu = (page: {
51
+ evaluate(expression: string): Promise<unknown>;
52
+ }): Promise<ShotGpu | null> =>
53
+ page
54
+ .evaluate(GPU_PROBE)
55
+ .then(parseGpuProbe)
56
+ .catch(() => null);
57
+
58
+ export const gpuJson = (gpu: ShotGpu | null | undefined): JsonValue =>
59
+ gpu === null || gpu === undefined
60
+ ? null
61
+ : { api: gpu.api, available: gpu.available, adapter: gpu.adapter, fallback: gpu.fallback };
@@ -0,0 +1,95 @@
1
+ // `x shot`'s subject: the one route argument read and refused before anything boots, and the
2
+ // directory name a route photographs into. A path on the app, never a URL — the SSRF shape
3
+ // `allowHosts` exists to refuse is refused here, at the argument, where the reader can see why.
4
+
5
+ import { BadFlagError, MissingPositionalError } from './errors';
6
+
7
+ /** A directory name a route can never escape: everything that is not a letter or digit is a dash. */
8
+ export function shotSlug(route: string): string {
9
+ const slug = route.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '');
10
+ return slug === '' ? 'root' : slug.toLowerCase();
11
+ }
12
+
13
+ const pathOf = (url: string): string => {
14
+ try {
15
+ return new URL(url).pathname;
16
+ } catch {
17
+ return '/';
18
+ }
19
+ };
20
+
21
+ /**
22
+ * A reserved name (RFC 2606) that resolves nowhere, so the origin check below can never be
23
+ * satisfied by an accident of what the app's own host happens to be.
24
+ */
25
+ const ROUTE_BASE = 'http://route.invalid';
26
+
27
+ /**
28
+ * Where a browser would actually go. The refusal above reads `scheme:` and nothing else, and this
29
+ * is the question it was standing in for: a path is a path only if resolving it lands back on the
30
+ * origin it was resolved against.
31
+ */
32
+ const resolvedOrigin = (path: string): string => {
33
+ try {
34
+ return new URL(path, ROUTE_BASE).origin;
35
+ } catch {
36
+ // A path `new URL` will not parse is one no browser will fetch either, and reporting it as the
37
+ // origin it is not is the honest answer here.
38
+ return '';
39
+ }
40
+ };
41
+
42
+ const refuseRoute = (reason: string): never => {
43
+ throw new BadFlagError({
44
+ flag: 'route',
45
+ command: 'shot',
46
+ reason,
47
+ // A placeholder, because there is nothing safe to substitute: unlike an absolute URL, an
48
+ // origin-escaping route carries no path the caller can be assumed to have meant.
49
+ fix: 'x shot /<path> --json',
50
+ });
51
+ };
52
+
53
+ /**
54
+ * A path on the app, never a URL. `x shot https://example.com` would photograph somebody else's
55
+ * site through a headless browser inside your network, which is the SSRF shape `allowHosts` exists
56
+ * to refuse — so it is refused here, at the argument, where the reader can still see why.
57
+ *
58
+ * `scheme:` was the ONLY spelling refused until 2026-08-22, and it is one of four: `//evil/x` is a
59
+ * protocol-relative URL, `\evil\x` is the same thing to every URL parser (a backslash IS a slash
60
+ * for a special scheme), and a TAB inside the path is deleted by the parser before the host is
61
+ * read, so `/⇥/evil/x` becomes `//evil/x`. Each one reached `new URL(route, server.url)` and came
62
+ * back pointed at another host. `allowHostsFrom` one layer down could not catch any of them: it
63
+ * allows a HOSTNAME, and the hostname it is given is the one the page has already left — which is
64
+ * how `x shot //localhost:9200/_cat/indices` photographed whatever else was on the dev box.
65
+ */
66
+ export function readRoute(raw: string | undefined): string {
67
+ if (raw === undefined || raw.trim() === '') {
68
+ throw new MissingPositionalError({ command: 'shot', positional: 'route', example: 'x shot /' });
69
+ }
70
+ const route = raw.trim();
71
+ if (/^[a-z][a-z0-9+.-]*:/i.test(route)) {
72
+ throw new BadFlagError({
73
+ flag: 'route',
74
+ command: 'shot',
75
+ reason: `"${route}" is an absolute URL; x shot photographs a route of the app under test`,
76
+ // The path out of the URL when it parses — the refusal's own fix line has to be runnable,
77
+ // and `new URL('http://')` throws, so the fallback is the route every app has.
78
+ fix: `x shot ${pathOf(route)} --json`,
79
+ });
80
+ }
81
+ const path = route.startsWith('/') ? route : `/${route}`;
82
+ // Its own refusal rather than folded into the origin check: `/a\b` stays on this origin and is
83
+ // still not the route that was typed — the verdict would record `/a\b` beside a picture of
84
+ // `/a/b`, which is the artifact lying about its own subject.
85
+ if (path.includes('\\')) {
86
+ return refuseRoute(`"${route}" contains a backslash, which a URL parser reads as "/"`);
87
+ }
88
+ const origin = resolvedOrigin(path);
89
+ if (origin !== ROUTE_BASE) {
90
+ return refuseRoute(
91
+ `"${route}" is not a path on the app: a browser resolves it to ${origin === '' ? 'no URL at all' : origin}`,
92
+ );
93
+ }
94
+ return path;
95
+ }
@@ -0,0 +1,189 @@
1
+ // One route photographed: boot (or find) the server, drive the page, settle the islands, take the
2
+ // picture and write `shot.png` beside the `verdict.json` that gates. The driver and the boot are
3
+ // arguments, so `bun test` proves the whole capture with no Chrome.
4
+
5
+ import { mkdirSync } from 'node:fs'; // why: Bun has no recursive directory create.
6
+ import { join } from 'node:path'; // why: Bun exposes no path-join primitive.
7
+ import { systemClock } from '@ultimat3/core/adapter';
8
+ import type { ShotColorScheme, ShotDriver, ShotPage, ShotSession } from './browser-launcher-port';
9
+ import { type ShotCookiePair, shotCookies } from './shot-cookie';
10
+ import { readShotGpu } from './shot-gpu';
11
+ import { acceptLanguageHeaders } from './shot-locale';
12
+ import type { ShotServer } from './shot-server';
13
+ import { allowHostsFrom } from './shot-server';
14
+ import { SETTLE_POLL_MS, settleIslands } from './shot-settle';
15
+ import { themeChoiceExpression } from './shot-theme';
16
+ import type { IslandCount, ShotArtifacts } from './shot-verdict';
17
+ import {
18
+ buildVerdict,
19
+ documentStatus,
20
+ ISLAND_PROBE,
21
+ parseIslandProbe,
22
+ verdictJson,
23
+ } from './shot-verdict';
24
+
25
+ export const SHOT_IMAGE = 'shot.png';
26
+ export const SHOT_VERDICT = 'verdict.json';
27
+
28
+ export interface ShotRun {
29
+ readonly route: string;
30
+ readonly outDir: string;
31
+ readonly driver: ShotDriver;
32
+ readonly boot: () => Promise<ShotServer>;
33
+ readonly settleMs: number;
34
+ readonly timeoutMs: number;
35
+ readonly fullPage: boolean;
36
+ /**
37
+ * `--allow-hosts`, verbatim. The app's own host is added once the server is up and never here:
38
+ * with `--port 0` the port — and therefore the origin — does not exist until after the boot.
39
+ */
40
+ readonly extraHosts?: string | undefined;
41
+ /**
42
+ * The theme the picture is of. Two things happen BEFORE navigation, because the boot script runs
43
+ * inline and nothing after `goto` can reach it: `prefers-color-scheme` is emulated so the boot's
44
+ * "system" branch answers the same on every box, AND the scheme is stored as the visitor's
45
+ * choice under `THEME_STORAGE_KEY` (`shot-theme.ts`), because an app with `theme.defaultMode`
46
+ * set answers that before the OS and only a stored choice beats it (issue #489). Absent means
47
+ * neither: the box's own preference and the app's own default — what `x shot` has always done,
48
+ * and the point of `defaultMode` — and `ui.shot` names one explicitly for exactly that reason.
49
+ */
50
+ readonly colorScheme?: ShotColorScheme | undefined;
51
+ /** CSS pixels the page is laid out in; absent is the driver's default. */
52
+ readonly viewport?: { readonly width: number; readonly height: number } | undefined;
53
+ /**
54
+ * Sent as `Accept-Language` on every request. The command always sets it — `--locale`, or the
55
+ * app's default locale — so a picture never depends on the language of the machine's Chrome.
56
+ */
57
+ readonly acceptLanguage?: string | undefined;
58
+ /**
59
+ * `--cookie`: set before the first navigation, each for the server's own URL once it is up —
60
+ * so a consent banner (or any cookie-held choice) is decided in the picture.
61
+ */
62
+ readonly cookies?: readonly ShotCookiePair[] | undefined;
63
+ readonly now?: (() => Date) | undefined;
64
+ /**
65
+ * `--expect-status`: the document status this shot is ok with — `404` to photograph the not-found
66
+ * page on purpose. Absent means any 2xx, and anything else fails the verdict with the status.
67
+ */
68
+ readonly expectStatus?: number | undefined;
69
+ /**
70
+ * Something to do with the page AFTER the islands settled and BEFORE the picture — `ui.inspect`
71
+ * reads the DOM here, on the one navigation the picture already paid for. `settle` re-runs the
72
+ * island poll (an action that mounts something changes the count the verdict reports); the
73
+ * caller who never calls it gets the count from the first settle.
74
+ */
75
+ readonly act?:
76
+ | ((page: ShotPage, settle: () => Promise<IslandCount | null>) => Promise<void>)
77
+ | undefined;
78
+ /**
79
+ * The clock the settle window runs on — the same seam `SettleOptions.sleep` and
80
+ * `InteractDeps.sleep` take, and the reason they had none on this path: `settleMs` was a
81
+ * `Bun.sleep` here, so a caller that injected a sleep everywhere else still paid the real
82
+ * 2000 ms window in wall time once per `runShot`, and a test doing it twice raced its own
83
+ * per-test timeout on a slower box. Absent is `Bun.sleep`: production waits for real.
84
+ */
85
+ readonly sleep?: ((ms: number) => Promise<void>) | undefined;
86
+ }
87
+
88
+ /** Nothing here may replace the failure that caused it, so a teardown throw is swallowed. */
89
+ const quietly = async (stop: () => Promise<void>): Promise<void> => {
90
+ await stop().catch(() => undefined);
91
+ };
92
+
93
+ /**
94
+ * Boot (or find) the server, photograph one route, write both artifacts. The driver and the boot
95
+ * are ARGUMENTS: `bun test` drives this with `fakeBrowser()` and a stub server, so the whole
96
+ * command is proved on a machine with no Chrome — which this command is explicitly excluded from
97
+ * the gate for needing.
98
+ */
99
+ export async function runShot(options: ShotRun): Promise<ShotArtifacts> {
100
+ const server = await options.boot();
101
+ const sleep = options.sleep ?? ((ms: number): Promise<void> => Bun.sleep(ms));
102
+ let session: ShotSession | undefined;
103
+ try {
104
+ const requestedUrl = new URL(options.route, server.url).toString();
105
+ session = await options.driver.open({
106
+ name: 'x shot',
107
+ // The host the picture is of, plus whatever the caller named. Never `*`: a headless browser
108
+ // inside your network is the widest SSRF surface an app can own, and a screenshot command is
109
+ // not the place to open it by default. Every refusal lands in the verdict's `refused` count.
110
+ rules: { allowHosts: allowHostsFrom(server.url, options.extraHosts) },
111
+ clock: systemClock,
112
+ timeoutMs: options.timeoutMs,
113
+ ...(options.viewport === undefined ? {} : { viewport: options.viewport }),
114
+ ...(options.acceptLanguage === undefined
115
+ ? {}
116
+ : { headers: acceptLanguageHeaders(options.acceptLanguage) }),
117
+ ...(options.cookies === undefined || options.cookies.length === 0
118
+ ? {}
119
+ : { cookies: shotCookies(options.cookies, new URL(server.url).toString()) }),
120
+ });
121
+ const page = session.page;
122
+ if (options.colorScheme !== undefined) {
123
+ await page.colorScheme(options.colorScheme);
124
+ const choice = themeChoiceExpression(options.colorScheme);
125
+ if (choice !== undefined) await page.prepare(choice);
126
+ }
127
+ await page.goto(requestedUrl, { timeout: options.timeoutMs });
128
+ // Read NOW as well as at capture: the network ring is bounded, and a page that fires a few
129
+ // hundred requests while it settles evicts the document entry the verdict needs.
130
+ const landedStatus = documentStatus(page.network(), page.url());
131
+ if (options.settleMs > 0) await sleep(options.settleMs);
132
+ // A probe may answer nothing (a page refusing evaluation, a driver with no JS engine): `null`
133
+ // says so, where a `0` would claim "no islands". `gpu` is read the same way, after the picture.
134
+ const probe = (): Promise<IslandCount | null> =>
135
+ page
136
+ .evaluate(ISLAND_PROBE)
137
+ .then(parseIslandProbe)
138
+ .catch(() => null);
139
+ // The same budget again, no new flag: `settleMs` is when the runtime CALLS `import()`, so a
140
+ // mount gets as long to settle as the runtime got to start it; `--settle 0` still gets none.
141
+ const settle = (): Promise<IslandCount | null> =>
142
+ settleIslands(probe, { windowMs: options.settleMs, pollMs: SETTLE_POLL_MS, sleep });
143
+ let islands = await settle();
144
+ if (options.act !== undefined) {
145
+ await options.act(page, async () => {
146
+ islands = await settle();
147
+ return islands;
148
+ });
149
+ }
150
+ const bytes = await page.screenshot({ fullPage: options.fullPage });
151
+ // Read AFTER the capture, so an error logged while the page settled ships with its picture —
152
+ // and copied BEFORE the gpu probe: `requestAdapter()` may take seconds, and a page that
153
+ // redirects meanwhile must not have its new URL or its new logs reported beside the old picture.
154
+ const captured = {
155
+ finalUrl: page.url(),
156
+ capturedAt: (options.now ?? (() => new Date()))().toISOString(),
157
+ console: [...page.console()],
158
+ pageErrors: [...page.pageErrors()],
159
+ pageErrorsDropped: page.pageErrorsDropped(),
160
+ network: [...page.network()],
161
+ networkDropped: page.networkDropped(),
162
+ };
163
+ const gpu = await readShotGpu(page);
164
+ const verdict = buildVerdict({
165
+ route: options.route,
166
+ requestedUrl,
167
+ server: server.origin,
168
+ screenshot: SHOT_IMAGE,
169
+ bytes,
170
+ ...captured,
171
+ islands,
172
+ gpu,
173
+ landedStatus,
174
+ ...(options.expectStatus === undefined ? {} : { expectStatus: options.expectStatus }),
175
+ });
176
+ mkdirSync(options.outDir, { recursive: true });
177
+ const image = join(options.outDir, SHOT_IMAGE);
178
+ const verdictFile = join(options.outDir, SHOT_VERDICT);
179
+ await Bun.write(image, bytes);
180
+ await Bun.write(verdictFile, `${JSON.stringify(verdictJson(verdict), null, 2)}\n`);
181
+ return { verdict, image, verdictFile };
182
+ } finally {
183
+ // Bound to a const: narrowing a `let` does not survive into the closure below, and the session
184
+ // has to be closed from inside one so a teardown throw cannot replace the real failure.
185
+ const open = session;
186
+ if (open !== undefined) await quietly(() => open.close());
187
+ await quietly(() => server.stop());
188
+ }
189
+ }
@@ -9,6 +9,8 @@ import { t, validate } from '@ultimat3/schema';
9
9
  import type { ConsoleLine, NetworkEntry, PageError } from './browser-launcher-port';
10
10
  import { msg } from './messages';
11
11
  import type { JsonValue } from './output';
12
+ import type { ShotGpu } from './shot-gpu';
13
+ import { gpuJson } from './shot-gpu';
12
14
 
13
15
  /**
14
16
  * The one expression that counts islands, and it counts TWO different facts because they are two
@@ -156,6 +158,8 @@ export interface ShotInput {
156
158
  readonly landedStatus?: number | null | undefined;
157
159
  /** `--expect-status`: the one status this shot is ok with. Absent means any 2xx. */
158
160
  readonly expectStatus?: number | undefined;
161
+ /** The GPU backend the page could reach (`shot-gpu.ts`); absent or `null` when not read. */
162
+ readonly gpu?: ShotGpu | null | undefined;
159
163
  }
160
164
 
161
165
  export interface ShotVerdict extends ShotInput {
@@ -324,6 +328,7 @@ export function verdictJson(verdict: ShotVerdict): JsonValue {
324
328
  })),
325
329
  },
326
330
  islands: islandJson(verdict.islands),
331
+ gpu: gpuJson(verdict.gpu),
327
332
  network: {
328
333
  requests: verdict.network.length,
329
334
  refused: verdict.refused,
@@ -6,9 +6,10 @@
6
6
  // why: Bun exposes no path-join primitive, and every card path is relative to the export root.
7
7
  import { join } from 'node:path';
8
8
  import { probeImage, transformImageBytes } from '@ultimat3/core';
9
+ import { systemClock } from '@ultimat3/core/adapter';
9
10
  import type { OpenGraphImage } from '@ultimat3/seo';
10
11
  import type { ShotDriver } from './browser-launcher-port';
11
- import { DEFAULT_PAGE_TIMEOUT_MS, systemShotClock } from './cdp-shot-clock';
12
+ import { DEFAULT_PAGE_TIMEOUT_MS } from './cdp-shot-clock';
12
13
  import { CardBrowserMissingError, CardRouteUnknownError } from './static-capture-errors';
13
14
  import { serveExport } from './static-cards-serve';
14
15
 
@@ -72,7 +73,7 @@ export function staticCards(): StaticCards {
72
73
  const session = await driver.open({
73
74
  name: 'x build cards',
74
75
  rules: { allowHosts: ['127.0.0.1'] },
75
- clock: systemShotClock,
76
+ clock: systemClock,
76
77
  timeoutMs: DEFAULT_PAGE_TIMEOUT_MS,
77
78
  viewport: CARD_SIZE,
78
79
  });
@@ -9,9 +9,9 @@
9
9
  import { rm } from 'node:fs/promises';
10
10
  import { join } from 'node:path';
11
11
  import type { RenderMode } from '@ultimat3/core';
12
- import { RENDER_MODES } from '@ultimat3/core';
12
+ import { RENDER_MODES, SURFACES } from '@ultimat3/core';
13
13
  import type { Surface } from '@ultimat3/render';
14
- import { SURFACE_SPECS, SURFACES, surfaceAllows } from '@ultimat3/render';
14
+ import { SURFACE_SPECS, surfaceAllows } from '@ultimat3/render';
15
15
  import type { JsonValue } from './output';
16
16
  import { SERVICE_WORKER_PATH } from './sw-artifacts';
17
17
 
@@ -12,8 +12,8 @@
12
12
  // Bun ships no path API; `join` is the filesystem side of writing a chunk into a static export.
13
13
  // why: Bun exposes no path API — nothing native joins a directory to a URL-shaped path.
14
14
  import { join } from 'node:path';
15
+ import { SURFACES } from '@ultimat3/core';
15
16
  import type { Surface } from '@ultimat3/render';
16
- import { SURFACES } from '@ultimat3/render';
17
17
  import { contentHash, stylesFor, stylesheetsRevision } from '@ultimat3/render/server';
18
18
 
19
19
  /**
@@ -9,27 +9,19 @@ import { finiteCount, systemClock } from '@ultimat3/core';
9
9
  import type { HttpConfig } from '@ultimat3/http';
10
10
  import {
11
11
  configuredAuthenticator,
12
+ configuredCredentialTtlMs,
12
13
  defineHttpConfig,
14
+ MAX_CREDENTIAL_TTL_MS,
13
15
  requestContext,
14
16
  UltimateRequest,
15
17
  } from '@ultimat3/http';
16
18
  import type { SyncAuthenticator, SyncGrant } from '@ultimat3/realtime/server';
17
19
 
18
- /**
19
- * How long one grant stands before the node re-decides it.
20
- *
21
- * A grant with no expiry never appears in `GrantBook.expired()`, so `sweepGrants` — the only path
22
- * to `hub.onActorChange` and `registry.reauthorize` — never fired for a socket this adapter opened.
23
- * `logout`, `revokeSession`, `disableUser` and `updatePrivileges` closed the HTTP session and never
24
- * the websocket, and the client's 15s heartbeat beats the 120s idle sweep, so the socket stayed up
25
- * with the revoked actor's authority for as long as the tab was open.
26
- *
27
- * Five minutes, against `DEFAULT_REAUTH_INTERVAL_MS` (30s): the window a revoked actor keeps its
28
- * socket is this plus one sweep, and the cost is one resolver call per socket per window — 167/s
29
- * on the 50,000-socket node this repo has measured, against 1,667/s at a 30s TTL. A deployment
30
- * whose credential has a shorter real lifetime passes `runtime.syncAuthenticate` and states it.
31
- */
32
- export const SYNC_GRANT_TTL_MS = 5 * 60_000;
20
+ // How long one grant stands before the node re-decides it is `@ultimat3/http`'s
21
+ // `MAX_CREDENTIAL_TTL_MS` (five minutes) — one constant, the ceiling an app's `credentialTtlMs` is
22
+ // held to. A grant with no expiry never reaches `sweepGrants`, so `logout` closed the HTTP session
23
+ // and never the socket; five minutes is one resolver call per socket per window (167/s at 50,000
24
+ // sockets, against 1,667/s at 30 s).
33
25
 
34
26
  /**
35
27
  * The credential this adapter retains per socket, and nothing else.
@@ -41,7 +33,7 @@ export const SYNC_GRANT_TTL_MS = 5 * 60_000;
41
33
  * Dropping the rest can only make a refresh MORE restrictive, never more permissive: an app that
42
34
  * resolves identity from some other header sees its refresh answer `null`, which closes the socket
43
35
  * with `1008` and the client re-dials carrying that header again. One reconnect per window, not an
44
- * escalation — and `runtime.syncAuthenticate` is the declared seam for stating something else.
36
+ * escalation.
45
37
  */
46
38
  const CREDENTIAL_HEADERS = ['cookie', 'authorization'] as const;
47
39
 
@@ -77,7 +69,7 @@ function credentialOf(request: Request): Credential {
77
69
  export interface SyncAuthenticatorOptions {
78
70
  /** The clock a grant's window is measured on. Injected so a re-auth is provable without sleeping. */
79
71
  readonly clock?: Clock;
80
- /** Overrides `SYNC_GRANT_TTL_MS`. A test names its own window; nothing in the boot passes one. */
72
+ /** Overrides `MAX_CREDENTIAL_TTL_MS`. A test names its own window; nothing in the boot passes one. */
81
73
  readonly ttlMs?: number;
82
74
  }
83
75
 
@@ -108,7 +100,14 @@ export function syncAuthenticator(
108
100
  // long as the tab is open. That is the hole this whole file was written to close, and a `??`
109
101
  // does not close it: `NaN` is not nullish. At least 1ms — a window that has already shut when
110
102
  // the grant is minted is not a window.
111
- const ttlMs = finiteCount('syncAuthenticator', 'ttlMs', options.ttlMs ?? SYNC_GRANT_TTL_MS, 1);
103
+ const ttlMs = finiteCount(
104
+ 'syncAuthenticator',
105
+ 'ttlMs',
106
+ // The app's own credential lifetime, declared beside its resolver (`configureAuthenticator(fn,
107
+ // { credentialTtlMs })`) — what `runtime.syncAuthenticate` was the second way to state.
108
+ options.ttlMs ?? configuredCredentialTtlMs() ?? MAX_CREDENTIAL_TTL_MS,
109
+ 1,
110
+ );
112
111
 
113
112
  const resolve = async (credential: Credential): Promise<SyncGrant | null> => {
114
113
  const request = new Request(credential.url, {