@lunora/runtime 1.0.0-alpha.37 → 1.0.0-alpha.39

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 (51) hide show
  1. package/dist/index.d.mts +359 -8
  2. package/dist/index.d.ts +359 -8
  3. package/dist/index.mjs +1 -22
  4. package/dist/packem_shared/DEFAULT_LOG_COLUMNS-CpZ9kd-q.mjs +1 -0
  5. package/dist/packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-BBf3mNrD.mjs +1 -0
  6. package/dist/packem_shared/GET_AUTH_AUDIT_LOG_OP-DmxHQbZT.mjs +1 -0
  7. package/dist/packem_shared/HEALTH_PATH-DiZqjEGp.mjs +1 -0
  8. package/dist/packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs +1 -0
  9. package/dist/packem_shared/LOG_ARCHIVE_PATH-e8U3ftfM.mjs +1 -0
  10. package/dist/packem_shared/LunoraError-C08OP5Uq.mjs +1 -0
  11. package/dist/packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs +1 -0
  12. package/dist/packem_shared/analyticsEngineSink-DOoyBx4o.mjs +1 -0
  13. package/dist/packem_shared/applyJurisdiction-uRQLx282.mjs +1 -0
  14. package/dist/packem_shared/argsFromQuery-0KrWTkNx.mjs +1 -0
  15. package/dist/packem_shared/composeIdentityResolvers-DlBbYmBJ.mjs +1 -0
  16. package/dist/packem_shared/composeWorker-D7Zi6kZR.mjs +6 -0
  17. package/dist/packem_shared/createCrossShardRelationCapabilities-B2EKbSEs.mjs +1 -0
  18. package/dist/packem_shared/createKvCursorStore-C24tEuYk.mjs +3 -0
  19. package/dist/packem_shared/createQueryCoordinator-DLsrcOkB.mjs +1 -0
  20. package/dist/packem_shared/createShardClient-62qcYKGl.mjs +1 -0
  21. package/dist/packem_shared/decorateResponse-C6TZSzID.mjs +1 -0
  22. package/dist/packem_shared/emitLogEvent-CEbCh6FQ.mjs +1 -0
  23. package/dist/packem_shared/memoizeIdentity-DRYIK1yT.mjs +1 -0
  24. package/dist/packem_shared/method-guard-BbuR0VfS.mjs +1 -0
  25. package/dist/packem_shared/observability-B0MYwNDB.mjs +1 -0
  26. package/dist/packem_shared/otlp-resource-cAjGEywx.mjs +1 -0
  27. package/dist/packem_shared/pipeline-log-reader-tDuvc_Ty.mjs +1 -0
  28. package/dist/packem_shared/toAirbyteMessages-DBTuFjb5.mjs +1 -0
  29. package/package.json +1 -1
  30. package/dist/packem_shared/DEFAULT_LOG_COLUMNS-B7H3YdJ3.mjs +0 -2
  31. package/dist/packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-B3pA7aXp.mjs +0 -79
  32. package/dist/packem_shared/HEALTH_PATH-e5J_NHBx.mjs +0 -150
  33. package/dist/packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-acNcguqc.mjs +0 -3
  34. package/dist/packem_shared/LOG_ARCHIVE_PATH-CNs0bznX.mjs +0 -125
  35. package/dist/packem_shared/LunoraError-Bpb9EFJ3.mjs +0 -22
  36. package/dist/packem_shared/NOOP_EXECUTION_CONTEXT-CCTu0Bf1.mjs +0 -8
  37. package/dist/packem_shared/analyticsEngineSink-yLFNjHDt.mjs +0 -429
  38. package/dist/packem_shared/applyJurisdiction-BkZtTkct.mjs +0 -20
  39. package/dist/packem_shared/argsFromQuery-c-U1WRy-.mjs +0 -121
  40. package/dist/packem_shared/composeIdentityResolvers-XGjO7V1J.mjs +0 -55
  41. package/dist/packem_shared/composeWorker-DiWwOXXt.mjs +0 -3738
  42. package/dist/packem_shared/createCrossShardRelationCapabilities-CbcWjkAn.mjs +0 -63
  43. package/dist/packem_shared/createKvCursorStore-g8aA6B4L.mjs +0 -165
  44. package/dist/packem_shared/createQueryCoordinator-DNCJzOZE.mjs +0 -847
  45. package/dist/packem_shared/decorateResponse-DRWQFNhF.mjs +0 -273
  46. package/dist/packem_shared/emitLogEvent-BlGMnKZK.mjs +0 -1
  47. package/dist/packem_shared/method-guard-Qzw99aCj.mjs +0 -3
  48. package/dist/packem_shared/observability--NOFYBFc.mjs +0 -47
  49. package/dist/packem_shared/otlp-resource-Dow6-F_u.mjs +0 -163
  50. package/dist/packem_shared/pipeline-log-reader-BXULGNC3.mjs +0 -135
  51. package/dist/packem_shared/toAirbyteMessages-DrHdplb4.mjs +0 -39
package/dist/index.d.mts CHANGED
@@ -1560,6 +1560,20 @@ interface LogSinkContext {
1560
1560
  interface LogEvent {
1561
1561
  /** Raw arguments passed to the `ctx.log.*` call, in order. */
1562
1562
  args: unknown[];
1563
+ /**
1564
+ * OTel `LogRecord.eventName` — set when the line was emitted as a **structured
1565
+ * event** via `ctx.log.event(name, fields)` rather than as a human-readable
1566
+ * log line.
1567
+ *
1568
+ * The distinction is the whole point of the Events API: a log line's payload
1569
+ * is its `message` (prose, for a human, unstable), while an event's payload is
1570
+ * its `fields` (a named schema, for a query, stable). A collector that knows
1571
+ * `eventName` can index and aggregate the latter; without it, "how many
1572
+ * checkouts failed" degrades into a substring search over prose.
1573
+ *
1574
+ * Absent for ordinary `ctx.log.*` calls.
1575
+ */
1576
+ eventName?: string;
1563
1577
  /**
1564
1578
  * Structured fields the caller attached (`ctx.log.info(message, fields)` or a
1565
1579
  * bound `ctx.log.with(fields)` child), already normalized to a fresh bag of
@@ -1817,6 +1831,58 @@ interface MetricEvent {
1817
1831
  */
1818
1832
  value: number;
1819
1833
  }
1834
+ /** A JS attribute value the encoder maps onto an OTLP `AnyValue`. */
1835
+ type OtlpAttributeValue = boolean | number | string;
1836
+ /**
1837
+ * A `Resource.attributes` bag — the process-level identity (`service.name`,
1838
+ * `service.version`, `cloud.region`, …) attached to every exported signal.
1839
+ * Lives here rather than in either exporter because both packages build one and
1840
+ * `wrapResource*` consumes it.
1841
+ */
1842
+ type OtlpResourceAttributes = Record<string, OtlpAttributeValue>;
1843
+ /**
1844
+ * The OTel `SpanKind` union, in the spec's own words rather than its wire
1845
+ * numbers, so a call site reads `{ kind: "client" }` instead of `{ kind: 3 }`.
1846
+ *
1847
+ * Kind is not cosmetic: a service map is built from it. A CLIENT span with no
1848
+ * matching SERVER span on the other side is a dropped hop; PRODUCER/CONSUMER is
1849
+ * what makes a queue render as an async edge rather than a synchronous call.
1850
+ * Getting it wrong is why "everything is INTERNAL" traces produce no topology.
1851
+ */
1852
+ type OtlpSpanKind = "client" | "consumer" | "internal" | "producer" | "server";
1853
+ /**
1854
+ * One timestamped occurrence inside a span — OTel's `Span.events`.
1855
+ *
1856
+ * The right shape for something that has a moment but no duration: a retry, a
1857
+ * cache miss, a validation failure, a thrown exception. Modelling those as
1858
+ * near-zero-width child spans clutters the waterfall, and modelling them as
1859
+ * separate log lines loses the "which span was I in" correlation that makes them
1860
+ * useful in the first place.
1861
+ */
1862
+ interface SpanEventPoint {
1863
+ /** Structured attributes, normalized like a span's own. */
1864
+ attributes?: LogFields;
1865
+ /** Event name, e.g. `"exception"` or `"cache.miss"`. */
1866
+ name: string;
1867
+ /** Wall-clock millis when it happened. */
1868
+ ts: number;
1869
+ }
1870
+ /**
1871
+ * A causal reference to a span in ANOTHER trace — OTel's `Span.links`.
1872
+ *
1873
+ * The standard answer to fan-in: a queue consumer processing a batch of 100
1874
+ * messages links to the 100 producing spans rather than parenting to one of them
1875
+ * (arbitrary) or all of them (impossible). The traces stay separately navigable
1876
+ * and the causal edge survives.
1877
+ */
1878
+ interface SpanLink {
1879
+ /** Attributes describing the relationship, e.g. `{ "link.kind": "enqueued_by" }`. */
1880
+ attributes?: LogFields;
1881
+ /** Linked span id (16-hex). */
1882
+ spanId: string;
1883
+ /** Linked trace id (32-hex). */
1884
+ traceId: string;
1885
+ }
1820
1886
  interface SpanEvent {
1821
1887
  /**
1822
1888
  * Structured attributes the caller attached, already normalized to a fresh
@@ -1826,6 +1892,12 @@ interface SpanEvent {
1826
1892
  attributes?: LogFields;
1827
1893
  /** Wall-clock duration of the span body, in milliseconds. */
1828
1894
  durationMs: number;
1895
+ /**
1896
+ * Timestamped occurrences inside the span (see {@link SpanEventPoint}) —
1897
+ * `ctx.trace`'s `span.addEvent(...)` / `span.recordException(...)`. Absent
1898
+ * when the body recorded none.
1899
+ */
1900
+ events?: SpanEventPoint[];
1829
1901
  /**
1830
1902
  * Populated when the span body threw. `type` is the error's constructor name
1831
1903
  * (or its `LunoraError` code); `message` is the human-readable string and may
@@ -1842,6 +1914,14 @@ interface SpanEvent {
1842
1914
  * reuses its context — the same attribution rule `ctx.log` follows.
1843
1915
  */
1844
1916
  functionPath: string;
1917
+ /**
1918
+ * OTel `SpanKind`. Absent means `"internal"` — the overwhelming majority of
1919
+ * `ctx.trace` spans — so the common case costs no bytes on the wire and every
1920
+ * pre-existing recorded span stays valid.
1921
+ */
1922
+ kind?: OtlpSpanKind;
1923
+ /** Causal references to spans in other traces (see {@link SpanLink}). Absent when none. */
1924
+ links?: SpanLink[];
1845
1925
  /** Caller-supplied span name, e.g. `"stripe.charge"`. */
1846
1926
  name: string;
1847
1927
  /** True when the span body returned without throwing. */
@@ -1963,6 +2043,21 @@ type ObservabilitySinkContext = LogSinkContext;
1963
2043
  * events it cares about; the runtime no-ops the others.
1964
2044
  */
1965
2045
  interface ObservabilitySink {
2046
+ /**
2047
+ * Ship anything the sink is holding, now.
2048
+ *
2049
+ * A batching sink (`otlpSink` by default) buffers events and exports them as
2050
+ * one request instead of one request per event. That is only safe because a
2051
+ * Workers isolate can be frozen the instant a response is returned: the
2052
+ * runtime calls this at every invocation boundary — end of `fetch`, `queue`,
2053
+ * `scheduled`, and each Durable Object dispatch — passing the request's
2054
+ * `waitUntil` so the export outlives the response.
2055
+ *
2056
+ * Optional and idempotent: a non-buffering sink simply omits it, and calling
2057
+ * it with an empty buffer is a no-op. A sink must never throw from here; like
2058
+ * every other hook, a telemetry failure must not surface to the caller.
2059
+ */
2060
+ flush?: (context?: ObservabilitySinkContext) => void;
1966
2061
  /**
1967
2062
  * **Opt-in, EXPERIMENTAL, default `false`.** When `true`, each `ctx.trace`
1968
2063
  * span the Durable Object records is ALSO emitted as a Cloudflare **custom
@@ -1993,6 +2088,23 @@ interface ObservabilitySink {
1993
2088
  * `createShardDO` — the DO reads the flag when building `ctx.trace`.
1994
2089
  */
1995
2090
  fuseCloudflareTraces?: boolean;
2091
+ /**
2092
+ * How much detail automatic `ctx.db` instrumentation produces.
2093
+ *
2094
+ * `"summary"` (**default**) — aggregate counters (`db.calls`, `db.duration_ms`,
2095
+ * per-operation counts) folded onto the dispatch's wide event. No extra spans
2096
+ * and no extra log records, so the cost is flat no matter how many queries a
2097
+ * handler makes.
2098
+ *
2099
+ * `"spans"` — one span per database call: the full waterfall, for when you are
2100
+ * chasing a specific slow query. Capped per dispatch so a query loop cannot
2101
+ * bury the trace; truncation is reported as `db.spans_truncated`.
2102
+ *
2103
+ * `"off"` — no database telemetry.
2104
+ *
2105
+ * Applies only when a sink is configured; with none, `ctx.db` is untouched.
2106
+ */
2107
+ instrumentDatabase?: "off" | "spans" | "summary";
1996
2108
  /** Invoked once per `ctx.log.*` call from a function handler. */
1997
2109
  onLog?: (event: LogEvent, context?: ObservabilitySinkContext) => void;
1998
2110
  /**
@@ -2008,6 +2120,20 @@ interface ObservabilitySink {
2008
2120
  * INTERNAL spans a handler creates beneath it.
2009
2121
  */
2010
2122
  onSpan?: (event: SpanEvent, context?: ObservabilitySinkContext) => void;
2123
+ /**
2124
+ * Whether `ctx.fetch` is instrumented: each outbound call becomes a **CLIENT
2125
+ * span**, and a W3C `traceparent` naming that span is injected so the callee's
2126
+ * spans join this trace instead of starting a disconnected one. Default `true`
2127
+ * whenever a sink is configured.
2128
+ *
2129
+ * Set `false` for the bare platform `fetch` (no span, no header). Pass
2130
+ * `{ propagate }` to keep the spans but control who receives trace context, e.g.
2131
+ * `propagate: (url) => url.host.endsWith(".internal")` to send it to your own
2132
+ * services and not to third parties.
2133
+ */
2134
+ traceFetch?: boolean | {
2135
+ propagate?: ((url: URL) => boolean) | boolean;
2136
+ };
2011
2137
  }
2012
2138
  /**
2013
2139
  * Invoke `sink.onRpc` with the given event, swallowing any error the sink
@@ -2187,6 +2313,23 @@ interface CorsOptions {
2187
2313
  }
2188
2314
  /** Origin/CSRF guard configuration. */
2189
2315
  interface CsrfOptions {
2316
+ /**
2317
+ * Whether a loopback `Origin` is trusted **when the worker itself is serving on
2318
+ * loopback**. Defaults to `true`.
2319
+ *
2320
+ * This is the local-development shape: the browser loads the app from the dev
2321
+ * server on `localhost:3000` which proxies `/_lunora` to wrangler on
2322
+ * `localhost:8787`. With `changeOrigin`, the worker sees its own URL as
2323
+ * `:8787` while the browser's `Origin` stays `:3000`, so the two don't match and
2324
+ * the cookie-bearing WS upgrade is rejected — the app then hangs on its loading
2325
+ * state with no clue why. Both ends are loopback, so nothing cross-site can
2326
+ * reach them.
2327
+ *
2328
+ * It cannot loosen production: the exemption requires the worker's OWN origin to
2329
+ * be loopback, which a deployed worker's never is. Set `false` for a hardened
2330
+ * local setup that wants the strict same-origin rule.
2331
+ */
2332
+ allowLoopback?: boolean;
2190
2333
  /** Extra origins (beyond same-origin and the CORS allowlist) accepted on unsafe cookie requests. */
2191
2334
  trustedOrigins?: string[];
2192
2335
  }
@@ -2232,6 +2375,7 @@ interface ResolvedCors {
2232
2375
  maxAge: number;
2233
2376
  }
2234
2377
  interface ResolvedCsrf {
2378
+ allowLoopback: boolean;
2235
2379
  enabled: boolean;
2236
2380
  trustedOrigins: string[];
2237
2381
  }
@@ -3754,15 +3898,53 @@ declare class LunoraError extends LunoraError$1 {
3754
3898
  });
3755
3899
  toResponse(): Response;
3756
3900
  }
3757
- /** A JS attribute value the encoder maps onto an OTLP `AnyValue`. */
3758
- type OtlpAttributeValue = boolean | number | string;
3759
3901
  /**
3760
- * A `Resource.attributes` bag the process-level identity (`service.name`,
3761
- * `service.version`, `cloud.region`, …) attached to every exported signal.
3762
- * Lives here rather than in either exporter because both packages build one and
3763
- * `wrapResource*` consumes it.
3902
+ * Memoize a resolver **within a single request**.
3903
+ *
3904
+ * The safe default: keyed on the `Request` object itself, so the result is reused by
3905
+ * every code path handling that request (the RPC dispatch, each fan-out leg, an
3906
+ * admin gate) and discarded the moment the request is collected. It cannot serve a
3907
+ * stale identity, because it never outlives the request that produced it — a revoked
3908
+ * session is re-verified on the very next request.
3909
+ *
3910
+ * ```ts
3911
+ * createWorker({ resolveIdentity: memoizeIdentityPerRequest(myResolver), … });
3912
+ * ```
3764
3913
  */
3765
- type OtlpResourceAttributes = Record<string, OtlpAttributeValue>;
3914
+ declare const memoizeIdentityPerRequest: (resolver: IdentityResolver) => IdentityResolver;
3915
+ /** Tuning for {@link memoizeIdentity}. */
3916
+ interface MemoizeIdentityOptions {
3917
+ /**
3918
+ * Cache size before the oldest entry is evicted. Defaults to 500 — an isolate
3919
+ * serves a bounded set of concurrent users, and an unbounded map in a
3920
+ * long-lived isolate is a leak.
3921
+ */
3922
+ maxEntries?: number;
3923
+ /**
3924
+ * How long a verified identity is reused for the same credential, in ms.
3925
+ * Defaults to 5000.
3926
+ *
3927
+ * **This is the revocation delay.** A signed-out or revoked session keeps
3928
+ * resolving for up to this long, so keep it in the seconds — long enough to
3929
+ * collapse a burst (a page load's parallel queries, one query's fan-out across
3930
+ * shards), short enough that a sign-out is effectively immediate. Do not raise it
3931
+ * into the minutes to save verifications.
3932
+ */
3933
+ ttlMs?: number;
3934
+ }
3935
+ /**
3936
+ * Memoize a resolver **across requests**, keyed on the presented credential, for
3937
+ * `ttlMs`.
3938
+ *
3939
+ * Use it when session verification is genuinely expensive (a JWKS fetch, a D1 read)
3940
+ * and a few seconds of revocation delay is acceptable — see
3941
+ * {@link MemoizeIdentityOptions.ttlMs}, which is the whole trade-off. Composes with
3942
+ * (and subsumes) {@link memoizeIdentityPerRequest}: within one request the same entry
3943
+ * is reused regardless of TTL.
3944
+ *
3945
+ * An anonymous request (no cookie, no bearer) is never cached.
3946
+ */
3947
+ declare const memoizeIdentity: (resolver: IdentityResolver, options?: MemoizeIdentityOptions) => IdentityResolver;
3766
3948
  /** Shared shape for sinks that can be limited to error events only. */
3767
3949
  interface OnlyErrorsOption {
3768
3950
  /** When true, only events with `ok === false` are forwarded. */
@@ -3961,8 +4143,76 @@ interface PipelineLogSinkOptions {
3961
4143
  * `serializeFields` stores `fields` as a queryable JSON string.
3962
4144
  */
3963
4145
  declare const pipelineLogSink: (options: PipelineLogSinkOptions) => ObservabilitySink;
4146
+ /**
4147
+ * Everything the exporter buffered for one flush window, grouped so a
4148
+ * {@link TailSampler} can judge a trace as a whole.
4149
+ *
4150
+ * This is what makes it *tail* sampling rather than another head decision: by
4151
+ * flush time the trace's spans have all settled, so "keep it if anything in it
4152
+ * was slow or failed" is answerable — which it is not at the moment the first
4153
+ * span starts.
4154
+ */
4155
+ interface TailSamplerInput {
4156
+ /** Log records emitted under this trace. */
4157
+ logs: LogEvent[];
4158
+ /** RPC (SERVER) dispatch events belonging to this trace. */
4159
+ rpc: ObservabilityEvent[];
4160
+ /** `ctx.trace` spans belonging to this trace. */
4161
+ spans: SpanEvent[];
4162
+ /** The trace's id, or `undefined` for events that carried no trace context. */
4163
+ traceId: string | undefined;
4164
+ }
4165
+ /**
4166
+ * Decide whether a whole trace is exported. Return `false` to drop it — spans,
4167
+ * logs, and all.
4168
+ *
4169
+ * Composes with head sampling rather than replacing it: head sampling cheaply
4170
+ * discards most traces before they cost anything, and this makes the final call
4171
+ * on what survived. The canonical policy — "keep errors and slow requests, drop
4172
+ * the rest" — needs both.
4173
+ */
4174
+ type TailSampler = (input: TailSamplerInput) => boolean;
4175
+ /**
4176
+ * Last-chance transforms applied to each event immediately before encoding.
4177
+ *
4178
+ * Return `undefined` from any hook to drop that event entirely. This is the
4179
+ * redaction seam: attributes, log messages, and error strings can all carry user
4180
+ * input, and once a payload leaves for a third-party collector it is out of your
4181
+ * control. Doing it here rather than at each call site means one auditable place
4182
+ * to prove PII cannot escape.
4183
+ *
4184
+ * A hook that THROWS also drops the event. Redaction is a privacy control, so it
4185
+ * fails closed — losing a span beats exporting the thing the hook existed to
4186
+ * remove.
4187
+ */
4188
+ interface OtlpPostProcessor {
4189
+ log?: (event: LogEvent) => LogEvent | undefined;
4190
+ metric?: (event: MetricEvent) => MetricEvent | undefined;
4191
+ rpc?: (event: ObservabilityEvent) => ObservabilityEvent | undefined;
4192
+ span?: (event: SpanEvent) => SpanEvent | undefined;
4193
+ }
4194
+ /** Batching knobs for {@link otlpSink}; pass `batch: false` to export each event immediately. */
4195
+ interface OtlpBatchOptions {
4196
+ /**
4197
+ * Flush this long after the first buffered event, as a backstop for contexts
4198
+ * with no invocation boundary. Default 200ms.
4199
+ */
4200
+ maxDelayMs?: number;
4201
+ /** Flush as soon as this many events are buffered. Default 512. */
4202
+ maxItems?: number;
4203
+ }
3964
4204
  /** Options for {@link otlpSink}. */
3965
4205
  interface OtlpSinkOptions extends OnlyErrorsOption {
4206
+ /**
4207
+ * Buffer events and export them as one request per signal instead of one
4208
+ * request per event (the default). Pass `false` to restore per-event POSTs.
4209
+ *
4210
+ * Batching is on by default because the alternative is a correctness problem,
4211
+ * not just an efficiency one: a Worker is capped at 50 (free) / 1000 (paid)
4212
+ * subrequests per invocation, so a well-instrumented handler exporting one
4213
+ * `fetch` per span can exhaust the budget its own business logic needs.
4214
+ */
4215
+ batch?: OtlpBatchOptions | false;
3966
4216
  /**
3967
4217
  * Value of the `deployment.environment` resource attribute (e.g.
3968
4218
  * `"production"`, `"staging"`, `"development"`).
@@ -3999,6 +4249,12 @@ interface OtlpSinkOptions extends OnlyErrorsOption {
3999
4249
  * default and may be overridden here.
4000
4250
  */
4001
4251
  headers?: Record<string, string>;
4252
+ /**
4253
+ * Redact or drop events just before they are encoded — see
4254
+ * {@link OtlpPostProcessor}. A hook that throws drops the event (fail-closed);
4255
+ * see {@link postProcess}.
4256
+ */
4257
+ postProcessor?: OtlpPostProcessor;
4002
4258
  /**
4003
4259
  * Additional resource attributes to attach to every exported signal. These
4004
4260
  * ride alongside the built-in `service.name` and any convenience fields
@@ -4022,6 +4278,18 @@ interface OtlpSinkOptions extends OnlyErrorsOption {
4022
4278
  * release tag).
4023
4279
  */
4024
4280
  serviceVersion?: string;
4281
+ /**
4282
+ * Decide per trace, at flush time, whether it is exported — see
4283
+ * {@link TailSampler}. Requires batching (the default); ignored when
4284
+ * `batch: false`, because an unbuffered exporter has no trace to judge.
4285
+ *
4286
+ * A sampler that throws **keeps** the trace (fail-open) and the failure is
4287
+ * reported to `console.error`, rate-limited per sink. Treat this hook as a
4288
+ * cost control, not a guarantee: if a bounded export volume is a hard
4289
+ * requirement, enforce it at the collector, which cannot be bypassed by a bug
4290
+ * in this predicate.
4291
+ */
4292
+ tailSampler?: TailSampler;
4025
4293
  /**
4026
4294
  * Convenience bearer token: when set, an `Authorization: Bearer` header
4027
4295
  * carrying it is added to every POST (overriding any authorization in
@@ -4065,5 +4333,88 @@ declare const otlpSink: (options: OtlpSinkOptions) => ObservabilitySink;
4065
4333
  * @param sinks The sinks to fan out to.
4066
4334
  */
4067
4335
  declare const combineSinks: (...sinks: ObservabilitySink[]) => ObservabilitySink;
4336
+ /**
4337
+ * Structural mirror of `@lunora/client`'s `FunctionReference`, re-declared so this
4338
+ * module carries no `runtime → client` (browser SDK) dependency. The phantom
4339
+ * marker's shape matches, so a generated `api.*` / `internal.*` reference infers
4340
+ * its args and return type through {@link ShardClient.call} unchanged.
4341
+ */
4342
+ interface ShardFunctionReference<Args = unknown, Return = unknown> {
4343
+ readonly __lunoraPhantom?: {
4344
+ args: Args;
4345
+ kind: string;
4346
+ returns: Return;
4347
+ };
4348
+ readonly __lunoraRef: string;
4349
+ }
4350
+ /** Args type of a {@link ShardFunctionReference} (`Record&lt;string, unknown>` for an untyped ref). */
4351
+ type ShardCallArgs<F> = F extends ShardFunctionReference<infer A, infer _R> ? A : Record<string, unknown>;
4352
+ /** Return type of a {@link ShardFunctionReference} (`unknown` for an untyped ref). */
4353
+ type ShardCallReturn<F> = F extends ShardFunctionReference<infer _A, infer R> ? R : unknown;
4354
+ /** A verified end-user identity a shard call runs as. */
4355
+ interface ShardCallerIdentity {
4356
+ /**
4357
+ * Full identity claims, forwarded so `ctx.auth.getIdentity()` and any
4358
+ * claim-reading RLS policy see the same object the HTTP path would build. Omit
4359
+ * to forward only `userId`.
4360
+ */
4361
+ claims?: Record<string, unknown>;
4362
+ /** The verified user id — becomes `ctx.auth.userId` on the shard. */
4363
+ userId: string;
4364
+ }
4365
+ /** Options for {@link createShardClient}. */
4366
+ interface ShardClientOptions {
4367
+ /** Run every call as this verified end-user identity. See {@link ShardClient.as}. */
4368
+ as?: ShardCallerIdentity;
4369
+ /** Pin the DO namespace to a data-residency jurisdiction, exactly as the worker does. */
4370
+ jurisdiction?: DurableObjectJurisdiction;
4371
+ /** Default shard key for calls that don't pass one. See {@link ShardClient.forShard}. */
4372
+ shardKey?: string;
4373
+ /**
4374
+ * Whether calls carry system privilege (may invoke `internalQuery` /
4375
+ * `internalMutation` / `internalAction`). Defaults to `true` — a caller holding
4376
+ * the DO binding is already inside the trust boundary. Set `false` to make calls
4377
+ * behave exactly like an end-user RPC, so an accidental `internal.*` call is
4378
+ * rejected by the shard instead of succeeding.
4379
+ */
4380
+ system?: boolean;
4381
+ }
4382
+ /** Per-call overrides. */
4383
+ interface ShardCallOptions {
4384
+ /**
4385
+ * Idempotency key. The DO dedupes on `(identity, mutationId)` and replays the
4386
+ * cached result, so an at-least-once retry (a queue redelivery, a webhook resend)
4387
+ * applies the mutation once. Use a key derived from the upstream event, not a
4388
+ * fresh uuid per attempt.
4389
+ */
4390
+ mutationId?: string;
4391
+ /** Override the client's default shard key for this call. */
4392
+ shardKey?: string;
4393
+ }
4394
+ /** A typed caller bound to a namespace + privilege + (optionally) a shard. */
4395
+ interface ShardClient {
4396
+ /** Derive a client that runs as `identity`. Keeps system privilege unless `system: false` was set. */
4397
+ as: (identity: ShardCallerIdentity) => ShardClient;
4398
+ /** Derive a client with no end-user identity — a pure system caller. */
4399
+ asSystem: () => ShardClient;
4400
+ /**
4401
+ * Call a Lunora function on the shard. Pass a generated reference
4402
+ * (`internal.mcp.listNodes`) for typed args and return; a bare
4403
+ * `"namespace:fn"` string works as the escape hatch and returns `unknown`.
4404
+ *
4405
+ * Throws a {@link LunoraError} carrying the server's `code` when the function
4406
+ * fails — the same error shape the browser client surfaces, so a caller branches
4407
+ * on `FORBIDDEN` / `CONFLICT` / … identically on both sides.
4408
+ */
4409
+ call: <F extends ShardFunctionReference | string>(reference: F, args: F extends string ? Record<string, unknown> : ShardCallArgs<F>, options?: ShardCallOptions) => Promise<ShardCallReturn<F>>;
4410
+ /** Derive a client whose calls default to `shardKey`. */
4411
+ forShard: (shardKey: string) => ShardClient;
4412
+ }
4413
+ /**
4414
+ * Create a typed server-side caller over a `ShardDO` namespace binding.
4415
+ *
4416
+ * See the module docs for the privilege model and the authorization caveat.
4417
+ */
4418
+ declare const createShardClient: (namespace: ShardNamespaceLike, options?: ShardClientOptions) => ShardClient;
4068
4419
  declare const VERSION: string;
4069
- export { type AdminTableResolver, type AirbyteMessage, type AnalyticsEngineDataPointLike, type AnalyticsEngineDatasetLike, type AnalyticsEngineSinkOptions, type AuthAdmin, type AuthCapabilities, type AuthConfigInfo, type AuthImpersonation, type AuthPage, type AuthSession, type AuthUser, type AuthUserFieldSpec, type BackupManifest, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS, DEFAULT_LOG_LIMIT, DEFAULT_REGISTRY_CACHE_TTL_MS, type DurableObjectJurisdiction, type DynamicShardRegistry, type DynamicShardRegistryOptions, type ExecutionContextLike, type ExportBatch, type ExportChange, type ExportCursorStore, type ExportFanOutRequest, type ExportFanOutResult, type ExportSink, type ExportTapFailure, type ExportTapResult, type FanOutRequest, type FanOutResult, type FanOutSpec, type FivetranResponse, type FrameworkHostHandler, type FrameworkWorkerOptions, type FrameworkWorkerOptionsInput, type FunctionDescriptor, type FunctionRegistryEntry, type FunctionRegistryLike, type GlobalExportFunction as GlobalExportFn, type GlobalImportFunction as GlobalImportFn, type GlobalIntrospector, type GlobalTableInfo as GlobalTableInfoMeta, type GlobalTablePage as GlobalTablePageMeta, HEALTH_PATH, HEALTH_READY_PATH, type HealthAuthPosture, type HealthBody, type HealthCheckReport, type HealthProbe, type HealthProbeKind, type HealthProbeResult, type HealthRouteDeps, type HttpActionContext, type HttpActionLike, type HttpRouterLike, type IdentityContractLike, type IdentityResolver, type IdentityValidation, type ImportFanOutRequest, type ImportFanOutResult, type KvIntrospector, type KvKeyEntry, type KvKeyListResult, type KvNamespaceSummary, type KvValueResult, LOG_ARCHIVE_NOT_CONFIGURED, LOG_ARCHIVE_PATH, type ListAuthUsersOptions, type LogArchiveConfig, type LogEvent, type LogFields, type LogLevel, LunoraError, type LunoraErrorBody, type LunoraHandlerOptions, type LunoraWorker, type MergeStrategy, type MetricEvent, type MetricKind, type MigrationFanOutRequest, type MigrationFanOutResult, NOOP_EXECUTION_CONTEXT, type NotifySubscriptionDevice, type NotifySubscriptionStoreLike, type ObservabilityEvent, type ObservabilitySink, type ObservabilitySinkContext, type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardError, type ShardExportOutcome, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, argsFromQuery, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, mergeStrategyForAggregate, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
4420
+ export { type AdminTableResolver, type AirbyteMessage, type AnalyticsEngineDataPointLike, type AnalyticsEngineDatasetLike, type AnalyticsEngineSinkOptions, type AuthAdmin, type AuthCapabilities, type AuthConfigInfo, type AuthImpersonation, type AuthPage, type AuthSession, type AuthUser, type AuthUserFieldSpec, type BackupManifest, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS, DEFAULT_LOG_LIMIT, DEFAULT_REGISTRY_CACHE_TTL_MS, type DurableObjectJurisdiction, type DynamicShardRegistry, type DynamicShardRegistryOptions, type ExecutionContextLike, type ExportBatch, type ExportChange, type ExportCursorStore, type ExportFanOutRequest, type ExportFanOutResult, type ExportSink, type ExportTapFailure, type ExportTapResult, type FanOutRequest, type FanOutResult, type FanOutSpec, type FivetranResponse, type FrameworkHostHandler, type FrameworkWorkerOptions, type FrameworkWorkerOptionsInput, type FunctionDescriptor, type FunctionRegistryEntry, type FunctionRegistryLike, type GlobalExportFunction as GlobalExportFn, type GlobalImportFunction as GlobalImportFn, type GlobalIntrospector, type GlobalTableInfo as GlobalTableInfoMeta, type GlobalTablePage as GlobalTablePageMeta, HEALTH_PATH, HEALTH_READY_PATH, type HealthAuthPosture, type HealthBody, type HealthCheckReport, type HealthProbe, type HealthProbeKind, type HealthProbeResult, type HealthRouteDeps, type HttpActionContext, type HttpActionLike, type HttpRouterLike, type IdentityContractLike, type IdentityResolver, type IdentityValidation, type ImportFanOutRequest, type ImportFanOutResult, type KvIntrospector, type KvKeyEntry, type KvKeyListResult, type KvNamespaceSummary, type KvValueResult, LOG_ARCHIVE_NOT_CONFIGURED, LOG_ARCHIVE_PATH, type ListAuthUsersOptions, type LogArchiveConfig, type LogEvent, type LogFields, type LogLevel, LunoraError, type LunoraErrorBody, type LunoraHandlerOptions, type LunoraWorker, type MemoizeIdentityOptions, type MergeStrategy, type MetricEvent, type MetricKind, type MigrationFanOutRequest, type MigrationFanOutResult, NOOP_EXECUTION_CONTEXT, type NotifySubscriptionDevice, type NotifySubscriptionStoreLike, type ObservabilityEvent, type ObservabilitySink, type ObservabilitySinkContext, type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, argsFromQuery, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };