@ultimat3/core 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 (67) hide show
  1. package/CLAUDE.md +54 -58
  2. package/README.md +70 -27
  3. package/package.json +3 -2
  4. package/src/adapter-slot.ts +42 -0
  5. package/src/adapter.ts +24 -0
  6. package/src/audit.ts +31 -14
  7. package/src/aws-sigv4.ts +9 -3
  8. package/src/cache-vocabulary.ts +1 -1
  9. package/src/client-problem.ts +10 -3
  10. package/src/clock.ts +68 -14
  11. package/src/config-defaults.ts +4 -4
  12. package/src/config-keys.ts +1 -1
  13. package/src/config-removed.ts +11 -1
  14. package/src/config.ts +16 -20
  15. package/src/context.ts +2 -2
  16. package/src/cursor.ts +3 -11
  17. package/src/der.ts +65 -0
  18. package/src/error-render.ts +27 -1
  19. package/src/error-reporter-chain.ts +1 -1
  20. package/src/error-reporter-sentry-hooks.ts +85 -0
  21. package/src/error-reporter-sentry.ts +99 -7
  22. package/src/error-reporter.ts +39 -11
  23. package/src/errors.ts +3 -1
  24. package/src/exports/error-contract.ts +4 -14
  25. package/src/exports/observability.ts +57 -17
  26. package/src/exports/secrets.ts +4 -18
  27. package/src/failure-capture.ts +22 -13
  28. package/src/gate-shapes.ts +88 -0
  29. package/src/host-rules.ts +13 -1
  30. package/src/html-escape.ts +7 -1
  31. package/src/ids.ts +59 -10
  32. package/src/image/png-pixels.ts +14 -8
  33. package/src/index.ts +123 -136
  34. package/src/instrument-events.ts +272 -0
  35. package/src/instrument-semconv.ts +65 -0
  36. package/src/instrument-stacks.ts +38 -0
  37. package/src/instrument.ts +194 -0
  38. package/src/keyed-fingerprint.ts +7 -11
  39. package/src/lifecycle-signals.ts +5 -3
  40. package/src/lifecycle.ts +27 -0
  41. package/src/logger-record.ts +35 -0
  42. package/src/logger.ts +24 -16
  43. package/src/mcp-exposure.ts +17 -0
  44. package/src/metrics-semconv.ts +124 -0
  45. package/src/metrics.ts +19 -16
  46. package/src/otlp-batch.ts +78 -0
  47. package/src/otlp-log-exporter.ts +180 -0
  48. package/src/otlp-metric-exporter.ts +2 -1
  49. package/src/otlp-post.ts +22 -2
  50. package/src/otlp-span-exporter.ts +10 -59
  51. package/src/otlp.ts +27 -9
  52. package/src/outbound-instrument.ts +82 -0
  53. package/src/outbound.ts +5 -4
  54. package/src/page-meta.ts +6 -0
  55. package/src/page.ts +23 -5
  56. package/src/registrar.ts +269 -0
  57. package/src/route-vocabulary.ts +11 -2
  58. package/src/safe-url.ts +10 -8
  59. package/src/seal-errors.ts +14 -4
  60. package/src/seal-keys.ts +11 -7
  61. package/src/secret-source.ts +125 -0
  62. package/src/secrets-errors.ts +32 -12
  63. package/src/secrets-store.ts +30 -26
  64. package/src/sleep-clock.ts +70 -0
  65. package/src/telemetry.ts +90 -31
  66. package/src/type-pins.ts +19 -16
  67. package/src/log-tee.ts +0 -73
package/src/adapter.ts ADDED
@@ -0,0 +1,24 @@
1
+ // `@ultimat3/core/adapter`: what an adapter author implements for core's ports (`ADAPTER_PORTS`
2
+ // rows owned by `@ultimat3/core`), the built-ins to copy or compose, and the INSTALLERS. Installers
3
+ // live here and never on the barrel: the boot (`apps/<app>/runtime.ts`) and `@ultimat3/testing`
4
+ // are their only callers, so an app module cannot swap a backend behind the boot's back.
5
+
6
+ export type { AdapterSlot } from './adapter-slot';
7
+ export { adapterSlot } from './adapter-slot';
8
+ export type { AuditRecord, AuditSink } from './audit';
9
+ export { installAuditSink, resetAuditSink } from './audit';
10
+ export type { Clock, FrozenClock, SleepClock } from './clock';
11
+
12
+ export type { ErrorReport, ErrorReporter } from './error-reporter';
13
+ export { installErrorReporter } from './error-reporter';
14
+ export type { FailureBundle, FailureCaptureLimits, FailureStore } from './failure-capture';
15
+ export { installFailureStore } from './failure-capture';
16
+ export type { MasterKeyRef, SecretSource, SecretSourceContext } from './secret-source';
17
+ export {
18
+ defaultSecretSource,
19
+ envSecretSource,
20
+ fileSecretSource,
21
+ installSecretSource,
22
+ } from './secret-source';
23
+ export { SecretsKeyMissingError } from './secrets-errors';
24
+ export { installClock, noWaitClock, systemClock } from './sleep-clock';
package/src/audit.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  * (retention, hash chain, subject index, "who" under impersonation) is the app's; none of it is here.
6
6
  */
7
7
 
8
+ import { adapterSlot } from './adapter-slot';
8
9
  import type { Ctx } from './context';
9
10
 
10
11
  /**
@@ -15,8 +16,12 @@ import type { Ctx } from './context';
15
16
  */
16
17
  export type AuditOutcome = 'allowed' | 'denied' | 'failed';
17
18
 
18
- /** Which primitive acted — the value of the `ultimate.primitive` span attribute, too. */
19
- export type AuditPrimitive = 'action' | 'query';
19
+ /**
20
+ * Which primitive acted — the value of the `ultimate.primitive` span attribute, too. `'job'` is a
21
+ * job's OWN write (`@ultimat3/jobs`' `subjectErase`); an action a job enqueued is still `'action'`
22
+ * on surface `'job'`, because the action is what ran.
23
+ */
24
+ export type AuditPrimitive = 'action' | 'query' | 'job';
20
25
 
21
26
  /**
22
27
  * Which projection ran the attempt: a price change over `http` and one over `mcp` are not the same
@@ -56,9 +61,12 @@ export interface AuditRecord {
56
61
  * `x_audit.action` column — a column rename is a data migration, and the value is the same.
57
62
  */
58
63
  readonly name: string;
59
- /** `'action'` (a mutator included — see `mutator`) or `'query'`. A read and a write are not one event. */
64
+ /**
65
+ * `'action'` (a mutator included — see `mutator`), `'query'`, or `'job'` for a job's own write.
66
+ * A read and a write are not one event.
67
+ */
60
68
  readonly primitive: AuditPrimitive;
61
- /** True when `mutator()` built it. Always false for a query. */
69
+ /** True when `mutator()` built it. Always false for a query or a job. */
62
70
  readonly mutator: boolean;
63
71
  readonly surface: AuditSurface;
64
72
  /**
@@ -116,29 +124,38 @@ export const AUDIT_RECORD_FIELDS: readonly (keyof AuditRecord)[] = Object.freeze
116
124
 
117
125
  /**
118
126
  * Where a record goes: a table, an append-only hash chain, an OTel log, a queue — the app's.
119
- * `@ultimat3/admin`'s `AuditSink` is the same noun one tier up over its own fixed entry type.
120
- * A sink that throws is never swallowed; each primitive's audit gate says which failure wins.
127
+ * The framework's ONE audit-sink interface: generic over the record so `@ultimat3/admin` writes
128
+ * its own `AuditEntry` through `AuditSink<AuditEntry>` instead of declaring a second noun (there
129
+ * were two until 31.0.0). The default record is the primitive attempt `action` and `query` write.
130
+ * A sink that throws is never swallowed; each caller's audit gate says which failure wins.
121
131
  */
122
- export interface AuditSink {
123
- write(record: AuditRecord): Promise<void> | void;
132
+ export interface AuditSink<TRecord = AuditRecord> {
133
+ write(record: TRecord): Promise<void> | void;
124
134
  }
125
135
 
126
136
  /**
127
137
  * No default. A logger-backed default would satisfy `audit: true` with a line nobody stores, which
128
138
  * is the silent pass this seam exists to remove: an audited primitive with no sink installed is
129
139
  * refused before it reads its input (`X_AUDIT_SINK_MISSING`, `X_QUERY_AUDIT_SINK_MISSING`).
140
+ * Core's one slot shape (`adapter-slot.ts`), so two boots in one process release in any order.
130
141
  */
131
- let installed: AuditSink | null = null;
142
+ const installed = /* @__PURE__ */ adapterSlot<AuditSink | null>(() => null);
132
143
 
133
- export function setAuditSink(sink: AuditSink): void {
134
- installed = sink;
144
+ /**
145
+ * The `auditSink` port's installer — on `@ultimat3/core/adapter` only: the boot calls it with
146
+ * `runtime.ts`'s `auditSink`, a test through `@ultimat3/testing`'s `swapAdapter('auditSink', …)`.
147
+ * Answers the release that removes THIS install and no other.
148
+ */
149
+ export function installAuditSink(sink: AuditSink): () => void {
150
+ return installed.install(sink);
135
151
  }
136
152
 
153
+ /** The sink `action` and `query` write to, or `null` when the boot installed none. */
137
154
  export function getAuditSink(): AuditSink | null {
138
- return installed;
155
+ return installed.current();
139
156
  }
140
157
 
141
- /** Test seam: back to "nothing installed", which restoring a literal cannot express. */
158
+ /** Test seam: back to "nothing installed", whatever is stacked. On `./adapter`, beside the installer. */
142
159
  export function resetAuditSink(): void {
143
- installed = null;
160
+ installed.reset();
144
161
  }
package/src/aws-sigv4.ts CHANGED
@@ -165,7 +165,12 @@ function canonicalPath(pathname: string, doubleEncode: boolean): string {
165
165
  .join('/');
166
166
  }
167
167
 
168
- /** Pairs decoded then strictly re-encoded, sorted by key then value; a bare `key` is `key=`. */
168
+ /**
169
+ * Pairs decoded then strictly re-encoded, sorted by key then value; a bare `key` is `key=`. A `+`
170
+ * is a space — the form encoding `URLSearchParams` writes — so `url.searchParams.set('prefix',
171
+ * 'a b')` is signed and sent as `a%20b`, never `a%2Bb` (a different key to S3). A literal plus is
172
+ * `%2B`, which `URLSearchParams` already writes.
173
+ */
169
174
  function canonicalQuery(search: string): string {
170
175
  const pairs: [string, string][] = [];
171
176
  for (const part of search.replace(/^\?/, '').split('&')) {
@@ -173,7 +178,8 @@ function canonicalQuery(search: string): string {
173
178
  const at = part.indexOf('=');
174
179
  const key = at === -1 ? part : part.slice(0, at);
175
180
  const value = at === -1 ? '' : part.slice(at + 1);
176
- pairs.push([uriEncode(uriDecode(key, 'query')), uriEncode(uriDecode(value, 'query'))]);
181
+ const decode = (raw: string): string => uriDecode(raw.replaceAll('+', ' '), 'query');
182
+ pairs.push([uriEncode(decode(key)), uriEncode(decode(value))]);
177
183
  }
178
184
  pairs.sort(([ak, av], [bk, bv]) => (ak === bk ? (av < bv ? -1 : 1) : ak < bk ? -1 : 1));
179
185
  return pairs.map(([key, value]) => `${key}=${value}`).join('&');
@@ -350,7 +356,7 @@ export async function presignAwsUrl(input: PresignAwsUrlInput): Promise<Presigne
350
356
  params.set('X-Amz-Expires', String(expires));
351
357
  params.set('X-Amz-SignedHeaders', signedHeaders);
352
358
  if (token !== undefined && token !== '') params.set('X-Amz-Security-Token', token);
353
- const query = canonicalQuery(params.toString().replaceAll('+', '%20'));
359
+ const query = canonicalQuery(params.toString());
354
360
  const doubleEncode = input.doubleEncodePath ?? input.service !== 's3';
355
361
  const canonicalRequest = [
356
362
  input.method,
@@ -12,7 +12,7 @@
12
12
  * accepted `memo | lru | shared | isr | cdn` while the stack ordered `request-memo | lru | redis |
13
13
  * cdn`, so `cache: { tiers: ['isr'] }` typechecked and selected nothing. `memo`/`request-memo` and
14
14
  * `shared`/`redis` were one rung spelled twice; the ladder's spelling wins, because it is the one
15
- * a `TierInvalidation`, a `TierFailure` and the `/_x` panel already report.
15
+ * a `TierInvalidation`, a `cache.tier_failure` event and the `/_x` panel already report.
16
16
  *
17
17
  * **`isr` is not here and is not a cache tier.** It is a `RenderMode` (`route-vocabulary.ts`) — a
18
18
  * per-route rendering decision, revalidated by a tag bust — and `@ultimat3/cache` has no ISR store
@@ -77,7 +77,12 @@ export function problemError(
77
77
  // The server's declared keys FIRST, so the ones this decoder owns win a collision.
78
78
  meta: withStatedDelay(
79
79
  withRequestId(
80
- { ...serverMeta(body['meta'], body['issues']), origin: 'remote', status, url },
80
+ {
81
+ ...serverMeta(body['meta'], body['issues'], body['issuesTruncated']),
82
+ origin: 'remote',
83
+ status,
84
+ url,
85
+ },
81
86
  body['requestId'],
82
87
  ),
83
88
  retryAfterSeconds,
@@ -155,9 +160,10 @@ export function transportFailed(
155
160
  /**
156
161
  * The document's `meta`, copied own key by own key: `JSON.parse` mints `__proto__` as a real own
157
162
  * key, and assigned onto a plain object it would replace the prototype. `issues` rides along
158
- * unparsed for the caller whose schema can read it.
163
+ * unparsed for the caller whose schema can read it, and `issuesTruncated` — only ever the literal
164
+ * `true` — says that list is a prefix the server cut at its cap.
159
165
  */
160
- function serverMeta(meta: unknown, issues: unknown): Record<string, unknown> {
166
+ function serverMeta(meta: unknown, issues: unknown, truncated: unknown): Record<string, unknown> {
161
167
  const out: Record<string, unknown> = {};
162
168
  if (isJsonObject(meta)) {
163
169
  for (const [key, member] of Object.entries(meta)) {
@@ -166,6 +172,7 @@ function serverMeta(meta: unknown, issues: unknown): Record<string, unknown> {
166
172
  }
167
173
  }
168
174
  if (Array.isArray(issues)) out['issues'] = issues;
175
+ if (truncated === true) out['issuesTruncated'] = true;
169
176
  return out;
170
177
  }
171
178
 
package/src/clock.ts CHANGED
@@ -1,5 +1,9 @@
1
- // Single responsibility: the only source of "now" in the framework. Everything time-related
2
- // takes a `Clock` so tests freeze time instead of sleeping. Nothing else may call `Date.now()`.
1
+ // Single responsibility: the only source of "now" in the framework, and the clock types. Everything
2
+ // time-related takes a `Clock` (or a `SleepClock` when it waits) so tests freeze time instead of
3
+ // sleeping. Nothing else may call `Date.now()`. Page-safe: what waits is `sleep-clock.ts`, server-only.
4
+
5
+ import { adapterSlot } from './adapter-slot';
6
+ import { finiteOption } from './finite-option';
3
7
 
4
8
  export interface Clock {
5
9
  /** Wall-clock instant. Always UTC-backed; format at the edge with an explicit IANA tz. */
@@ -8,12 +12,31 @@ export interface Clock {
8
12
  monotonic(): number;
9
13
  }
10
14
 
11
- export interface FrozenClock extends Clock {
15
+ /**
16
+ * A clock that can also wait. ONE type for every wait in the framework — it replaced
17
+ * `@ultimat3/scraping`'s `ScrapeClock` and `@ultimat3/cli`'s `ShotClock`, which were this
18
+ * interface twice under two names.
19
+ */
20
+ export interface SleepClock extends Clock {
21
+ /**
22
+ * Resolve after `ms` of this clock's time, or reject with the signal's reason — VERBATIM, never
23
+ * wrapped: whoever aborted put an `UltimateError` with a fix there — the moment it aborts.
24
+ */
25
+ sleep(ms: number, signal?: AbortSignal): Promise<void>;
26
+ }
27
+
28
+ export interface FrozenClock extends SleepClock {
12
29
  /** Move wall-clock and monotonic time forward by `ms`. */
13
30
  advance(ms: number): void;
14
31
  set(at: Date | number | string): void;
15
32
  }
16
33
 
34
+ /**
35
+ * Now and monotonic, nothing else. This is the object `./page` ships to the browser, so it carries
36
+ * no `sleep`: no client caller waits on a clock, and the bytes would ride every route (axiom 6).
37
+ * Waiting code reads `ambientClock()` (`sleep-clock.ts`), whose default is the system `SleepClock`
38
+ * with these same `now`/`monotonic`, exported as `systemClock` from `./adapter` only.
39
+ */
17
40
  export const systemClock: Clock = Object.freeze({
18
41
  now(): Date {
19
42
  return new Date();
@@ -23,29 +46,60 @@ export const systemClock: Clock = Object.freeze({
23
46
  },
24
47
  });
25
48
 
49
+ /**
50
+ * The `clock` adapter port's frames. Here, not in `sleep-clock.ts`, so a NOW reader (`liveClock`)
51
+ * follows `installClock` without a browser bundle paying for `sleep`. Pure, so a bundle that never
52
+ * reads `liveClock` keeps none of it.
53
+ */
54
+ export const installedClocks = /* @__PURE__ */ adapterSlot<SleepClock | undefined>(() => undefined);
55
+
56
+ /**
57
+ * "Now", as the `clock` port says: the installed clock's `now`/`monotonic`, read at EACH call, or the
58
+ * system's. The default of the server's readers of the present — `ctxOf` (so every action, query,
59
+ * job and `uuidV7(ctx.clock)`) and the logger — so `runtime.ts`'s `clock` and a test's
60
+ * `installClock` reach them. `systemClock` stays the default where that is the point: deadlines and
61
+ * backoff that race REAL timers (`retry-loop`, `breaker`, `outbound`, the drain; a frozen clock under
62
+ * a real `setTimeout` is a budget that never spends), AWS signing, and a bare `uuidV7()` — it ships
63
+ * on `./page`, where nothing installs a clock and the slot would be bytes that buy nothing.
64
+ */
65
+ export const liveClock: Clock = /* @__PURE__ */ Object.freeze({
66
+ now: (): Date => (installedClocks.current() ?? systemClock).now(),
67
+ monotonic: (): number => (installedClocks.current() ?? systemClock).monotonic(),
68
+ });
69
+
26
70
  function toEpochMs(at: Date | number | string): number {
27
71
  if (at instanceof Date) return at.getTime();
28
72
  if (typeof at === 'number') return at;
29
73
  return new Date(at).getTime();
30
74
  }
31
75
 
32
- /** A clock stuck at `at` until `advance()` is called. Monotonic starts at 0. */
76
+ /**
77
+ * A clock stuck at `at` until `advance()` is called. Monotonic starts at 0. Sleeping IS advancing:
78
+ * `await clock.sleep(30_000)` returns on the next microtask with thirty seconds elapsed, so a
79
+ * poll-until-deadline test is instant without knowing how many polls the loop makes.
80
+ */
33
81
  export function frozenClock(at: Date | number | string = 0): FrozenClock {
34
82
  let epochMs = toEpochMs(at);
35
83
  let mono = 0;
84
+ const advance = (ms: number): void => {
85
+ epochMs += ms;
86
+ mono += ms;
87
+ };
36
88
  return {
37
- now(): Date {
38
- return new Date(epochMs);
39
- },
40
- monotonic(): number {
41
- return mono;
42
- },
43
- advance(ms: number): void {
44
- epochMs += ms;
45
- mono += ms;
46
- },
89
+ now: () => new Date(epochMs),
90
+ monotonic: () => mono,
91
+ advance,
47
92
  set(next: Date | number | string): void {
48
93
  epochMs = toEpochMs(next);
49
94
  },
95
+ async sleep(ms: number, signal?: AbortSignal): Promise<void> {
96
+ // Screened: `epochMs += NaN` is a clock no later `set` can trust again.
97
+ const wait = finiteOption('frozenClock.sleep', 'ms', ms);
98
+ signal?.throwIfAborted();
99
+ advance(Math.max(0, wait));
100
+ // Yield anyway: a loop that never awaits anything real starves whatever armed its abort.
101
+ await Promise.resolve();
102
+ signal?.throwIfAborted();
103
+ },
50
104
  };
51
105
  }
@@ -28,7 +28,7 @@ type Sectioned =
28
28
  | 'time'
29
29
  | 'assets';
30
30
 
31
- export function configDefaults(name: string): Omit<AppConfig, Sectioned> {
31
+ export function configDefaults(): Omit<AppConfig, Sectioned> {
32
32
  return {
33
33
  theme: { defaultMode: 'system' },
34
34
  auth: { signInPath: null },
@@ -44,7 +44,7 @@ export function configDefaults(name: string): Omit<AppConfig, Sectioned> {
44
44
  database: { driver: 'postgres', ssl: false, rowSecurity: false },
45
45
  cache: { defaultTtlMs: 60_000, tiers: ['request-memo', 'lru'] },
46
46
  jobs: {
47
- queues: [`${name}-default`],
47
+ queues: ['default'],
48
48
  concurrency: JOBS_CONCURRENCY_DEFAULT,
49
49
  maxAttempts: 5,
50
50
  backoff: 'exponential',
@@ -59,11 +59,11 @@ export function configDefaults(name: string): Omit<AppConfig, Sectioned> {
59
59
  // (1,000) in `@ultimat3/realtime` — a tenth of its 10,000 windows, so no one actor fills it.
60
60
  realtime: {
61
61
  enabled: true,
62
- transport: 'memory',
63
- urlEnv: undefined,
64
62
  maxSubscriptionsPerActor: undefined,
65
63
  // Unset: the sync node's `DEFAULT_MAX_SOCKETS_PER_ACTOR` (16).
66
64
  maxSocketsPerActor: undefined,
65
+ // Unset: the page outbox queues without a ceiling (`pageOutbox`'s own default).
66
+ maxQueued: undefined,
67
67
  },
68
68
  notify: { inboxReadRetentionMs: undefined, inboxUnreadRetentionMs: undefined },
69
69
  ai: { mcp: { expose: true } },
@@ -106,7 +106,7 @@ const join = (path: string, key: string): string => (path === '' ? key : `${path
106
106
 
107
107
  /**
108
108
  * CLOSED BY DEFAULT: an object is walked wherever it is written, its known keys the reference's
109
- * plus `SECTION_KEYS`' — so an object at a key whose default is `undefined` (`realtime.urlEnv`)
109
+ * plus `SECTION_KEYS`' — so an object at a key whose default is `undefined` (`realtime.maxSocketsPerActor`)
110
110
  * knows no keys and every one is refused. Two exceptions: `OPEN_CONFIG_PATHS`, and a position the
111
111
  * defaults hold a VALUE at (`site.origin: null`), whose own rule names the wrong value in better
112
112
  * words than "unknown key".
@@ -43,7 +43,7 @@ export const REMOVED_CONFIG_KEYS: Readonly<Record<string, RemovedConfigKey>> = O
43
43
  'jobs.driver': {
44
44
  removedIn: '5.0.0',
45
45
  instead:
46
- 'nothing read it and boot always built Postgres; the driver is code — setJobDriver(postgresJobDriver({ executor })) from @ultimat3/jobs, or setJobDriver(memoryJobDriver()) in a test',
46
+ "nothing read it and boot always built Postgres; the driver is the jobs adapter port — export const runtime = { jobs: postgresJobDriver({ executor }) } in apps/<app>/runtime.ts (postgresJobDriver from @ultimat3/jobs), or @ultimat3/testing's per-test override in a test",
47
47
  },
48
48
  'realtime.heartbeatMs': {
49
49
  removedIn: '4.0.0',
@@ -100,6 +100,16 @@ export const REMOVED_CONFIG_KEYS: Readonly<Record<string, RemovedConfigKey>> = O
100
100
  instead:
101
101
  "nothing read it; the app's theme is declared once with export const brand = defineTheme({ … }) from @ultimat3/ui, in apps/web/shared/theme.ts",
102
102
  },
103
+ 'realtime.transport': {
104
+ removedIn: '31.0.0',
105
+ instead:
106
+ 'the bus is the transport adapter port: NATS_URL set builds NATS, unset builds the in-process bus — any other Transport is export const runtime = { transport } in apps/<app>/runtime.ts',
107
+ },
108
+ 'realtime.urlEnv': {
109
+ removedIn: '31.0.0',
110
+ instead:
111
+ 'the bus url is the NATS_URL environment variable, read by the boot — rename the variable urlEnv named (BUS_URL, …) to NATS_URL for every realtime role (web, sync, replicator), or hand a NatsTransport as transport in apps/<app>/runtime.ts',
112
+ },
103
113
  'ai.mcp.path': {
104
114
  removedIn: '25.0.0',
105
115
  instead:
package/src/config.ts CHANGED
@@ -42,13 +42,6 @@ import { ROLES, type Role } from './roles';
42
42
 
43
43
  export const THEME_MODES = ['light', 'dark', 'system'] as const;
44
44
  export type ThemeMode = (typeof THEME_MODES)[number];
45
- /**
46
- * The buses `@ultimat3/realtime`'s `selectTransport` builds, and nothing else. `'redis'` was in
47
- * this union until 22.0.0 with no Redis transport anywhere: it booted whatever `NATS_URL` chose.
48
- */
49
- export const REALTIME_TRANSPORTS = ['memory', 'nats'] as const;
50
- export type RealtimeTransport = (typeof REALTIME_TRANSPORTS)[number];
51
-
52
45
  /**
53
46
  * No `tokens` (deleted in 25.0.0): read by nothing once the theme seam landed — the app's theme is
54
47
  * `export const brand = defineTheme(…)` from `@ultimat3/ui`. A second theming path nothing read.
@@ -152,10 +145,11 @@ export interface JobsConfig {
152
145
  * silently gave you Postgres. Deleted 2026-08-20 (5.0.0); since 25.0.0 a config still writing it
153
146
  * is REFUSED by name (`config-removed.ts`) rather than carried through the spread.
154
147
  *
155
- * The seam that works is `setJobDriver(driver)` —
156
- * `setJobDriver(postgresJobDriver({ executor }))`, or `setJobDriver(memoryJobDriver())` in a
157
- * test. Swap the driver, zero job-code change, which is the whole of what the `JobDriver`
158
- * interface buys. There is no config line, and one that cannot be honoured is worse than none.
148
+ * The seam that works is the `jobs` adapter port (`ADAPTER_PORTS`): `export const runtime = {
149
+ * jobs: postgresJobDriver({ executor }) }` in `apps/<app>/runtime.ts`, or `@ultimat3/testing`'s
150
+ * per-test override. Swap the driver, zero job-code change, which is the whole of what the
151
+ * `JobDriver` interface buys. There is no config line, and one that cannot be honoured is worse
152
+ * than none.
159
153
  */
160
154
  readonly queues: readonly string[];
161
155
  /**
@@ -188,16 +182,22 @@ export interface JobsConfig {
188
182
  * No `heartbeatMs` (deleted 2026-08-19) and no `tier` (deleted 2026-08-23): read by nothing. The
189
183
  * socket beat is `new LiveClient({ heartbeatMs })`, the presence beat is derived, and an app's
190
184
  * realtime tier is what it DECLARES (a `channel()`, a `live: true` query) — never a config key.
191
- * `transport`, `urlEnv` and the two per-actor caps are the fields code reads.
185
+ * No `transport` and no `urlEnv` either (deleted in 31.0.0): the bus is the `transport` adapter
186
+ * port — `NATS_URL` set builds NATS, unset builds the in-process bus, and any other `Transport` is
187
+ * `runtime.ts`'s `transport` — so a closed two-member union here could only refuse a third bus.
192
188
  */
193
189
  export interface RealtimeConfig {
194
190
  readonly enabled: boolean;
195
- readonly transport: RealtimeTransport;
196
- readonly urlEnv: string | undefined;
197
191
  /** Live subscriptions one actor (or anonymous network) may hold per sync node. Unset: 1,000. */
198
192
  readonly maxSubscriptionsPerActor?: number | undefined;
199
193
  /** Sockets one actor (or anonymous network) may hold per sync node. Unset: 16. */
200
194
  readonly maxSocketsPerActor?: number | undefined;
195
+ /**
196
+ * Unsent writes the page's offline outbox holds before it refuses the next
197
+ * (`X_OFFLINE_QUEUE_FULL`). Rendered on every document as `ultimate-outbox-max` and read by
198
+ * realtime's page boot. Unset: no ceiling.
199
+ */
200
+ readonly maxQueued?: number | undefined;
201
201
  }
202
202
 
203
203
  /**
@@ -313,8 +313,7 @@ function validate(config: AppConfig): void {
313
313
  : routePathIssue('auth.signInPath', config.auth.signInPath),
314
314
  booleanIssue('ai.mcp.expose', config.ai.mcp.expose),
315
315
  booleanIssue('realtime.enabled', config.realtime.enabled),
316
- oneOfIssue('realtime.transport', config.realtime.transport, REALTIME_TRANSPORTS),
317
- ...(['maxSubscriptionsPerActor', 'maxSocketsPerActor'] as const).map((key) =>
316
+ ...(['maxSubscriptionsPerActor', 'maxSocketsPerActor', 'maxQueued'] as const).map((key) =>
318
317
  config.realtime[key] === undefined
319
318
  ? undefined
320
319
  : countIssue(`realtime.${key}`, config.realtime[key], 1),
@@ -324,9 +323,6 @@ function validate(config: AppConfig): void {
324
323
  ];
325
324
  for (const issue of perKey) if (issue !== undefined) issues.push(issue);
326
325
  nameListIssues('jobs.queues', config.jobs.queues, 'queue', issues);
327
- if (config.realtime.transport === 'nats' && config.realtime.urlEnv === undefined) {
328
- issues.push(`realtime.transport "nats" requires realtime.urlEnv`);
329
- }
330
326
  // `undefined` (never swept) or a positive, finite count of ms. Zero is refused, never read as
331
327
  // "immediately": a sweep at age 0 is an inbox that silently receives nothing. `describeValue`:
332
328
  // this is the boundary a JS app's untyped config crosses, so the value is `unknown` in practice.
@@ -382,7 +378,7 @@ function validate(config: AppConfig): void {
382
378
  * defaults, which is the reference `shapeIssues` compares each layer against.
383
379
  */
384
380
  function merge(name: string, layers: readonly AppConfigOverlay[]): AppConfig {
385
- const base = configDefaults(name);
381
+ const base = configDefaults();
386
382
  return {
387
383
  name,
388
384
  theme: layered(
package/src/context.ts CHANGED
@@ -32,7 +32,7 @@
32
32
 
33
33
  import { type Actor, anonymousActor } from './actor';
34
34
  import { asyncContext } from './async-context';
35
- import { type Clock, systemClock } from './clock';
35
+ import { type Clock, liveClock } from './clock';
36
36
  import { DEFAULT_LOCALE, DEFAULT_TIME_ZONE } from './default-locale';
37
37
  import { isUltimateError, UltimateError } from './errors';
38
38
  import { finiteOption } from './finite-option';
@@ -163,7 +163,7 @@ function buildId(): string {
163
163
  }
164
164
 
165
165
  export function ctxOf(init: CtxInit = {}): Ctx {
166
- const clock = init.clock ?? systemClock;
166
+ const clock = init.clock ?? liveClock;
167
167
  const requestId = init.requestId ?? uuidV7(clock);
168
168
  const trace = init.traceId ?? newTraceId();
169
169
  const base = init.logger ?? rootLogger;
package/src/cursor.ts CHANGED
@@ -9,6 +9,7 @@
9
9
 
10
10
  import { UltimateError } from './errors';
11
11
  import { hmac } from './hmac';
12
+ import { timingSafeEqual } from './timing-safe-equal';
12
13
 
13
14
  export interface CursorPayload {
14
15
  /** What this cursor belongs to: one read plus its arguments. A cursor is not portable. */
@@ -118,7 +119,8 @@ export function decodeCursor(cursor: string, scope: string): CursorPayload {
118
119
  const dot = cursor.lastIndexOf('.');
119
120
  if (dot <= 0) throw new CursorInvalidError('not a signed cursor');
120
121
  const body = cursor.slice(0, dot);
121
- if (!sameSignature(sign(body), cursor.slice(dot + 1))) {
122
+ // Constant time: the comparison must not leak how much of a forged signature was right.
123
+ if (!timingSafeEqual(sign(body), cursor.slice(dot + 1))) {
122
124
  throw new CursorInvalidError('signature does not match — tampered with, or the secret rotated');
123
125
  }
124
126
 
@@ -139,16 +141,6 @@ function sign(body: string): string {
139
141
  return hmac('sha256', currentSecret(), body, 'hex').slice(0, 32);
140
142
  }
141
143
 
142
- /** Constant time: the comparison must not leak how much of a forged signature was right. */
143
- function sameSignature(expected: string, actual: string): boolean {
144
- if (expected.length !== actual.length) return false;
145
- let difference = 0;
146
- for (let index = 0; index < expected.length; index += 1) {
147
- difference |= expected.charCodeAt(index) ^ actual.charCodeAt(index);
148
- }
149
- return difference === 0;
150
- }
151
-
152
144
  // A cursor travels in a query string and carries row values, so the encoding has to survive
153
145
  // both: base64url (no `+`, `/` or `=` for a caller to re-encode) over UTF-8 bytes — `btoa`
154
146
  // alone throws above code point 0xFF, and one accented title would break pagination.
package/src/der.ts ADDED
@@ -0,0 +1,65 @@
1
+ // Single responsibility: the one DER walk the framework owns — an X.509 certificate's
2
+ // `subjectPublicKeyInfo` (RFC 5280 §4.1), the bytes Web Crypto's `importKey('spki', …)` takes,
3
+ // because Web Crypto takes no certificate. SAML's IdP key and SNS's signing key both read it here.
4
+ // Malformed input is `undefined`, never a throw: the bytes came off a network.
5
+
6
+ /** One DER tag-length-value. Offsets index the buffer it was read from. */
7
+ export interface DerTlv {
8
+ readonly tag: number;
9
+ /** Offset of the tag byte. */
10
+ readonly start: number;
11
+ /** Offset of the first content byte. */
12
+ readonly body: number;
13
+ /** Offset one past the last content byte. */
14
+ readonly end: number;
15
+ }
16
+
17
+ const SEQUENCE = 0x30;
18
+ const VERSION = 0xa0;
19
+ /** `serialNumber`, `signature`, `issuer`, `validity`, `subject` — skipped to reach the key. */
20
+ const FIELDS_BEFORE_KEY = 5;
21
+ /** Four length octets reach 4 GiB; no certificate is longer, and more would overflow nothing useful. */
22
+ const MAX_LENGTH_OCTETS = 4;
23
+
24
+ /**
25
+ * The TLV at `at`, its content bounded by `limit`. Definite lengths only, as DER requires: the
26
+ * indefinite form (`0x80`) and a length running past `limit` are `undefined`.
27
+ */
28
+ export function readDerTlv(bytes: Uint8Array, at: number, limit: number): DerTlv | undefined {
29
+ if (at + 2 > limit) return undefined;
30
+ const tag = bytes[at] ?? 0;
31
+ const first = bytes[at + 1] ?? 0;
32
+ let body = at + 2;
33
+ let length = first;
34
+ if (first & 0x80) {
35
+ const count = first & 0x7f;
36
+ if (count === 0 || count > MAX_LENGTH_OCTETS || body + count > limit) return undefined;
37
+ length = 0;
38
+ for (let index = 0; index < count; index += 1)
39
+ length = length * 256 + (bytes[body + index] ?? 0);
40
+ body += count;
41
+ }
42
+ const end = body + length;
43
+ return end > limit ? undefined : { tag, start: at, body, end };
44
+ }
45
+
46
+ /**
47
+ * `Certificate → tbsCertificate → subjectPublicKeyInfo`, the whole element, tag included — or
48
+ * `undefined` when `der` is not exactly one certificate (trailing bytes included: DER is exact).
49
+ * Only the key is read; dates, issuer and signature are the caller's business.
50
+ */
51
+ export function x509Spki(der: Uint8Array): Uint8Array<ArrayBuffer> | undefined {
52
+ const certificate = readDerTlv(der, 0, der.byteLength);
53
+ if (certificate?.tag !== SEQUENCE || certificate.end !== der.byteLength) return undefined;
54
+ const tbs = readDerTlv(der, certificate.body, certificate.end);
55
+ if (tbs?.tag !== SEQUENCE) return undefined;
56
+ let field = readDerTlv(der, tbs.body, tbs.end);
57
+ // `[0] EXPLICIT version` is absent on a v1 certificate and present on every v3 one.
58
+ if (field?.tag === VERSION) field = readDerTlv(der, field.end, tbs.end);
59
+ for (let skipped = 0; skipped < FIELDS_BEFORE_KEY; skipped += 1) {
60
+ if (field === undefined) return undefined;
61
+ field = readDerTlv(der, field.end, tbs.end);
62
+ }
63
+ if (field?.tag !== SEQUENCE) return undefined;
64
+ return der.slice(field.start, field.end);
65
+ }
@@ -37,6 +37,32 @@ const boundedJson = (value: unknown): string | undefined => {
37
37
  });
38
38
  };
39
39
 
40
+ /**
41
+ * The cap on a WHOLE cause, in UTF-16 units — 4 KiB of ASCII. `MAX_RENDERED_LENGTH` bounds one
42
+ * value inside a cause; this bounds the sentence a call site assembles from many, which no value
43
+ * cap can: a 10k-issue validation joined into one cause was 3.6 MiB, copied into the error's
44
+ * `message`, its log line, the span's `error.message` and the problem document's `detail`.
45
+ */
46
+ export const MAX_CAUSE_LENGTH = 4096;
47
+
48
+ /**
49
+ * A cause cut to `MAX_CAUSE_LENGTH`, saying how much was dropped. Applied once, by the error
50
+ * CONSTRUCTOR (`UltimateError`, and `@ultimat3/schema`'s `SchemaError` copy, pinned by
51
+ * `single-line-pin.test.ts`), so every reader of `cause` and `message` gets the same bounded text.
52
+ * The cut never lands inside a surrogate pair: a lone surrogate is text Postgres refuses to store.
53
+ * The marker is ASCII so a cut ASCII cause is exactly 4 KiB of UTF-8, not three bytes over.
54
+ */
55
+ export function boundedCause(text: string): string {
56
+ if (text.length <= MAX_CAUSE_LENGTH) return text;
57
+ // The marker's width is decided off the total, which has at least as many digits as the
58
+ // dropped count, so `keep` never leaves the result above the cap.
59
+ const reserve = `... (${text.length} more characters)`.length;
60
+ let keep = MAX_CAUSE_LENGTH - reserve;
61
+ const last = text.charCodeAt(keep - 1);
62
+ if (last >= 0xd800 && last <= 0xdbff) keep -= 1;
63
+ return `${text.slice(0, keep)}... (${text.length - keep} more characters)`;
64
+ }
65
+
40
66
  /**
41
67
  * A value from an app, rendered for a `cause`. `JSON.stringify` raises a `TypeError` on a bigint
42
68
  * and on a cyclic structure, RUNS any `toJSON` the value carries and reads every enumerable
@@ -96,7 +122,7 @@ export function renderCauseValue(value: unknown): string {
96
122
  export function singleLine(text: string): string {
97
123
  // biome-ignore lint/suspicious/noControlCharactersInRegex: escaping them is the point.
98
124
  return text.replace(/[\u0000-\u001f\u007f\u2028\u2029]/g, (char) => {
99
- const known = CONTROL_ESCAPES[char];
125
+ const known = Object.hasOwn(CONTROL_ESCAPES, char) ? CONTROL_ESCAPES[char] : undefined;
100
126
  if (known !== undefined) return known;
101
127
  return `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`;
102
128
  });
@@ -1,6 +1,6 @@
1
1
  // Single responsibility: several `ErrorReporter`s behind the ONE seam — a vendor transport beside
2
2
  // an app's own sink (`@ultimat3/admin`'s `errorGroupsSink`). Not a second seam: the chain IS a
3
- // reporter, installed through `configureErrorReporting` like any other.
3
+ // reporter, installed through `installErrorReporter` (`./adapter`) like any other.
4
4
 
5
5
  import { renderThrowable } from './error-render';
6
6
  import { type ErrorReport, type ErrorReporter, noopErrorReporter } from './error-reporter';