@lunora/runtime 1.0.0-alpha.177 → 1.0.0-alpha.179
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.
- package/dist/index.d.mts +82 -45
- package/dist/index.d.ts +82 -45
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{DEFAULT_REGISTRY_CACHE_TTL_MS-BSKqUsWS.mjs → DEFAULT_REGISTRY_CACHE_TTL_MS-CdACWUQW.mjs} +1 -1
- package/dist/packem_shared/{HEALTH_PATH-D0i8LhwT.mjs → HEALTH_PATH-CAX2UeFy.mjs} +1 -1
- package/dist/packem_shared/analyticsEngineSink-CDfEAQHU.mjs +4 -0
- package/dist/packem_shared/applyJurisdiction-D4vryLhj.mjs +1 -0
- package/dist/packem_shared/composeWorker-PP4n0KPn.mjs +6 -0
- package/dist/packem_shared/{createQueryCoordinator-BkZPoV26.mjs → createQueryCoordinator-CXdh_RxT.mjs} +1 -1
- package/dist/packem_shared/{createShardClient-BrzRLSs9.mjs → createShardClient-BLW9uJZN.mjs} +1 -1
- package/dist/packem_shared/parseStackFrames-CZddjveh.mjs +2 -0
- package/package.json +4 -4
- package/dist/packem_shared/analyticsEngineSink-DQyRIP6N.mjs +0 -1
- package/dist/packem_shared/applyJurisdiction-C0ddU7Tg.mjs +0 -1
- package/dist/packem_shared/composeWorker-D4DrmOnY.mjs +0 -6
package/dist/index.d.mts
CHANGED
|
@@ -895,6 +895,11 @@ declare const applyJurisdiction: (namespace: ShardNamespaceLike, jurisdiction?:
|
|
|
895
895
|
* advisory and only the *creating* resolution can honour it, so it is safe to
|
|
896
896
|
* pass on every call and never safe to depend on: callers must behave
|
|
897
897
|
* identically when the shard turns out to live somewhere else entirely.
|
|
898
|
+
*
|
|
899
|
+
* A key carrying {@link LUNORA_ROLE_PREFIX} is refused with a 400 (the platform
|
|
900
|
+
* contract refuses it too): in an app that merges its Durable Object classes,
|
|
901
|
+
* those names belong to the scheduler and the shard registry. Every caller's key
|
|
902
|
+
* is checked — the framework's own role names reach here unprefixed.
|
|
898
903
|
*/
|
|
899
904
|
declare const resolveShard: (namespace: ShardNamespaceInput, shardKey: string, locationHint?: RegionHint) => ResolvedShard;
|
|
900
905
|
/**
|
|
@@ -1902,6 +1907,14 @@ interface KvIntrospector {
|
|
|
1902
1907
|
value: string;
|
|
1903
1908
|
}) => Promise<void>;
|
|
1904
1909
|
}
|
|
1910
|
+
/** The unredacted facts about a thrown value, for observability sinks only. */
|
|
1911
|
+
interface ErrorDetail {
|
|
1912
|
+
/** The `LunoraError` taxonomy code, when the thrown value carries one. */
|
|
1913
|
+
code?: string;
|
|
1914
|
+
message: string;
|
|
1915
|
+
name: string;
|
|
1916
|
+
stack?: string;
|
|
1917
|
+
}
|
|
1905
1918
|
/**
|
|
1906
1919
|
* Shared, bundler-inlined helpers for the structured `fields` a
|
|
1907
1920
|
* `ctx.log.<level>(message, fields)` / `ctx.log.with(fields)` call carries.
|
|
@@ -1952,6 +1965,14 @@ interface LogSinkContext {
|
|
|
1952
1965
|
interface LogEvent {
|
|
1953
1966
|
/** Raw arguments passed to the `ctx.log.*` call, in order. */
|
|
1954
1967
|
args: unknown[];
|
|
1968
|
+
/**
|
|
1969
|
+
* The first `Error` the call was handed, as an argument
|
|
1970
|
+
* (`ctx.log.error("failed", err)`) or a fields value (`{ err }`): its `name`,
|
|
1971
|
+
* unredacted `message`, `stack`, and `code` when it carries one. Absent when
|
|
1972
|
+
* the line logged no `Error`. An error tracker reads this rather than parsing
|
|
1973
|
+
* the rendered `message`.
|
|
1974
|
+
*/
|
|
1975
|
+
error?: ErrorDetail;
|
|
1955
1976
|
/**
|
|
1956
1977
|
* OTel `LogRecord.eventName` — set when the line was emitted as a **structured
|
|
1957
1978
|
* event** via `ctx.log.event(name, fields)` rather than as a human-readable
|
|
@@ -2398,11 +2419,15 @@ interface ObservabilityEvent {
|
|
|
2398
2419
|
/**
|
|
2399
2420
|
* Populated on `ok === false`. `code`/`status` mirror the LunoraError
|
|
2400
2421
|
* taxonomy; `message` is the human-readable string (may include user
|
|
2401
|
-
* input — sinks that ship to third parties should scrub it).
|
|
2422
|
+
* input — sinks that ship to third parties should scrub it). `name` and
|
|
2423
|
+
* `stack` are the thrown `Error`'s, captured where it was thrown — inside
|
|
2424
|
+
* the shard for a handler error — and are never sent to the client.
|
|
2402
2425
|
*/
|
|
2403
2426
|
error?: {
|
|
2404
2427
|
code: string;
|
|
2405
2428
|
message: string;
|
|
2429
|
+
name?: string;
|
|
2430
|
+
stack?: string;
|
|
2406
2431
|
status: number;
|
|
2407
2432
|
};
|
|
2408
2433
|
/**
|
|
@@ -4844,6 +4869,43 @@ interface DynamicShardRegistry extends ShardRegistry {
|
|
|
4844
4869
|
unregister: (table: string, shardKey: string) => Promise<void>;
|
|
4845
4870
|
}
|
|
4846
4871
|
declare const createDynamicShardRegistry: (options: DynamicShardRegistryOptions) => DynamicShardRegistry;
|
|
4872
|
+
/**
|
|
4873
|
+
* Helpers for handing a Lunora error to an error tracker from a sink.
|
|
4874
|
+
*
|
|
4875
|
+
* A failed RPC's `event.error` and a `ctx.log` line's `event.error` both carry
|
|
4876
|
+
* the thrown error as plain data (`name`, `message`, `stack`, `code`) — data,
|
|
4877
|
+
* because it crosses from the Durable Object to the worker. These turn that
|
|
4878
|
+
* data back into what trackers consume: a throwable for an SDK
|
|
4879
|
+
* (`Sentry.captureException(toError(event.error))`), or stack frames for an
|
|
4880
|
+
* HTTP ingestion API that wants them parsed (PostHog's `$exception_list`).
|
|
4881
|
+
*/
|
|
4882
|
+
/** The error half of an RPC event or a log event — what both helpers accept. */
|
|
4883
|
+
interface ReportedError {
|
|
4884
|
+
code?: string;
|
|
4885
|
+
message: string;
|
|
4886
|
+
name?: string;
|
|
4887
|
+
stack?: string;
|
|
4888
|
+
}
|
|
4889
|
+
/** One parsed stack frame. */
|
|
4890
|
+
interface StackFrame {
|
|
4891
|
+
colno: number;
|
|
4892
|
+
filename: string;
|
|
4893
|
+
/** The function name, or `"<anonymous>"` for a frame V8 printed without one. */
|
|
4894
|
+
function: string;
|
|
4895
|
+
lineno: number;
|
|
4896
|
+
}
|
|
4897
|
+
/**
|
|
4898
|
+
* Rebuild a throwable from an event's `error`, carrying the original `name`,
|
|
4899
|
+
* `message`, `stack`, and `code`, so an SDK groups it by the handler's real
|
|
4900
|
+
* stack rather than by the line that called the SDK.
|
|
4901
|
+
*/
|
|
4902
|
+
declare const toError: (error: ReportedError) => Error;
|
|
4903
|
+
/**
|
|
4904
|
+
* Parse a V8 stack trace into frames, **oldest call first** — the order Sentry
|
|
4905
|
+
* and PostHog expect. Lines that carry no location (`at Array.map (<anonymous>)`,
|
|
4906
|
+
* the leading `TypeError: …` line) are skipped; an absent stack yields `[]`.
|
|
4907
|
+
*/
|
|
4908
|
+
declare const parseStackFrames: (stack: string | undefined) => StackFrame[];
|
|
4847
4909
|
interface LunoraErrorBody {
|
|
4848
4910
|
error: ErrorBody;
|
|
4849
4911
|
}
|
|
@@ -4974,30 +5036,33 @@ interface WebhookSinkOptions extends OnlyErrorsOption {
|
|
|
4974
5036
|
*/
|
|
4975
5037
|
headers?: Record<string, string>;
|
|
4976
5038
|
/**
|
|
4977
|
-
* Optional
|
|
4978
|
-
*
|
|
4979
|
-
* `error.message`)
|
|
4980
|
-
*
|
|
4981
|
-
*
|
|
4982
|
-
*
|
|
5039
|
+
* Optional hook applied to each event immediately before it is serialized
|
|
5040
|
+
* and shipped. Its return value IS the request body, so it can scrub PII
|
|
5041
|
+
* (return the event minus `error.message`), filter (return `null`/`undefined`
|
|
5042
|
+
* to drop the event), or map the event onto a vendor's ingestion shape — e.g.
|
|
5043
|
+
* a PostHog `$exception` capture — without a dedicated sink. A throwing
|
|
5044
|
+
* `transform` drops the event (fail-closed) so a buggy redactor can never
|
|
5045
|
+
* leak the un-scrubbed payload.
|
|
4983
5046
|
*/
|
|
4984
|
-
transform?: (event: ObservabilityEvent) =>
|
|
5047
|
+
transform?: (event: ObservabilityEvent) => unknown;
|
|
4985
5048
|
/**
|
|
4986
|
-
* Optional
|
|
4987
|
-
*
|
|
4988
|
-
*
|
|
4989
|
-
*
|
|
4990
|
-
*
|
|
5049
|
+
* Optional hook for `ctx.log` events (the `transform` counterpart for log
|
|
5050
|
+
* lines). Same contract: the return value is the body, `null`/`undefined`
|
|
5051
|
+
* drops the line, and a throw drops it. When unset, log events are shipped
|
|
5052
|
+
* as-is (message + structured fields — which may carry user input; see the
|
|
5053
|
+
* privacy note).
|
|
4991
5054
|
*/
|
|
4992
|
-
transformLog?: (event: LogEvent) =>
|
|
5055
|
+
transformLog?: (event: LogEvent) => unknown;
|
|
4993
5056
|
/** The ingestion endpoint to POST each event to. */
|
|
4994
5057
|
url: string;
|
|
4995
5058
|
}
|
|
4996
5059
|
/**
|
|
4997
5060
|
* A fire-and-forget sink that POSTs each event as JSON to an HTTP endpoint.
|
|
4998
5061
|
*
|
|
4999
|
-
* This covers Axiom, Datadog, and any generic webhook/log-ingestion
|
|
5000
|
-
* point `url` at the ingestion endpoint
|
|
5062
|
+
* This covers Axiom, Datadog, PostHog, and any generic webhook/log-ingestion
|
|
5063
|
+
* service — point `url` at the ingestion endpoint, supply auth via `headers`,
|
|
5064
|
+
* and reshape the body with `transform` / `transformLog` when the vendor
|
|
5065
|
+
* expects its own format. Each
|
|
5001
5066
|
* event is sent as its own `fetch`. When the runtime supplies a per-event
|
|
5002
5067
|
* `context.waitUntil` (the request's `ctx.waitUntil`), the send is registered
|
|
5003
5068
|
* with it so it survives isolate teardown after the response returns; otherwise
|
|
@@ -5012,34 +5077,6 @@ interface WebhookSinkOptions extends OnlyErrorsOption {
|
|
|
5012
5077
|
* `transform` redacts/drops each event before send.
|
|
5013
5078
|
*/
|
|
5014
5079
|
declare const webhookSink: (options: WebhookSinkOptions) => ObservabilitySink;
|
|
5015
|
-
/** Options for {@link sentrySink}. */
|
|
5016
|
-
interface SentrySinkOptions extends OnlyErrorsOption {
|
|
5017
|
-
/**
|
|
5018
|
-
* User-supplied capture callback. Wire this to your Sentry client, e.g.
|
|
5019
|
-
* `(event) => Sentry.captureMessage(...)` or `captureException`. Kept as an
|
|
5020
|
-
* injected callback so the runtime takes no dependency on `@sentry/*`.
|
|
5021
|
-
*/
|
|
5022
|
-
capture: (event: ObservabilityEvent) => void;
|
|
5023
|
-
/**
|
|
5024
|
-
* Optional callback for `ctx.log` events. Wire it to Sentry's structured
|
|
5025
|
-
* logging or a breadcrumb, e.g. `(e) => Sentry.logger[e.level]?.(e.message,
|
|
5026
|
-
* e.fields)`. Omit it to leave `ctx.log` lines out of Sentry entirely
|
|
5027
|
-
* (capturing every log line would usually flood the project). Invoked inside
|
|
5028
|
-
* a try/catch so a throwing client can't break the handler.
|
|
5029
|
-
*/
|
|
5030
|
-
captureLog?: (event: LogEvent) => void;
|
|
5031
|
-
}
|
|
5032
|
-
/**
|
|
5033
|
-
* A thin adapter that forwards events to an injected `capture` callback.
|
|
5034
|
-
*
|
|
5035
|
-
* Intentionally does NOT bundle `@sentry/*`: the user wires their own Sentry
|
|
5036
|
-
* client (`captureException` / `captureMessage`) into `capture`, giving Sentry
|
|
5037
|
-
* parity without a hard dependency. The callback is invoked inside a try/catch
|
|
5038
|
-
* so a throwing client can't break dispatch.
|
|
5039
|
-
* @param options Sink options: `capture` is invoked per forwarded event;
|
|
5040
|
-
* `onlyErrors` defaults to true (error events only) — pass `false` for all.
|
|
5041
|
-
*/
|
|
5042
|
-
declare const sentrySink: (options: SentrySinkOptions) => ObservabilitySink;
|
|
5043
5080
|
/** One Analytics Engine data point — the structural subset {@link analyticsEngineSink} writes. */
|
|
5044
5081
|
interface AnalyticsEngineDataPointLike {
|
|
5045
5082
|
/** Free-form string dimensions (≤20, ≤5120 bytes total). */
|
|
@@ -5510,4 +5547,4 @@ export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolve
|
|
|
5510
5547
|
* surface — without a name for it, a caller cannot hoist a shared attribute bag
|
|
5511
5548
|
* into a typed constant.
|
|
5512
5549
|
*/
|
|
5513
|
-
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 PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type QueueForwardBatch, type QueueForwardHandler, type QueueForwardMessage, type QueueForwardResult, 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, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type
|
|
5550
|
+
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 PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type QueueForwardBatch, type QueueForwardHandler, type QueueForwardMessage, type QueueForwardResult, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ReportedError, 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, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StackFrame, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TriggerTrace, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, declareAppJurisdiction, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, normalizeBackupPrefix, otlpSink, parseStackFrames, pipelineLogSink, presenceProbe, r2Sink, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, toAirbyteMessages, toError, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
|
package/dist/index.d.ts
CHANGED
|
@@ -895,6 +895,11 @@ declare const applyJurisdiction: (namespace: ShardNamespaceLike, jurisdiction?:
|
|
|
895
895
|
* advisory and only the *creating* resolution can honour it, so it is safe to
|
|
896
896
|
* pass on every call and never safe to depend on: callers must behave
|
|
897
897
|
* identically when the shard turns out to live somewhere else entirely.
|
|
898
|
+
*
|
|
899
|
+
* A key carrying {@link LUNORA_ROLE_PREFIX} is refused with a 400 (the platform
|
|
900
|
+
* contract refuses it too): in an app that merges its Durable Object classes,
|
|
901
|
+
* those names belong to the scheduler and the shard registry. Every caller's key
|
|
902
|
+
* is checked — the framework's own role names reach here unprefixed.
|
|
898
903
|
*/
|
|
899
904
|
declare const resolveShard: (namespace: ShardNamespaceInput, shardKey: string, locationHint?: RegionHint) => ResolvedShard;
|
|
900
905
|
/**
|
|
@@ -1902,6 +1907,14 @@ interface KvIntrospector {
|
|
|
1902
1907
|
value: string;
|
|
1903
1908
|
}) => Promise<void>;
|
|
1904
1909
|
}
|
|
1910
|
+
/** The unredacted facts about a thrown value, for observability sinks only. */
|
|
1911
|
+
interface ErrorDetail {
|
|
1912
|
+
/** The `LunoraError` taxonomy code, when the thrown value carries one. */
|
|
1913
|
+
code?: string;
|
|
1914
|
+
message: string;
|
|
1915
|
+
name: string;
|
|
1916
|
+
stack?: string;
|
|
1917
|
+
}
|
|
1905
1918
|
/**
|
|
1906
1919
|
* Shared, bundler-inlined helpers for the structured `fields` a
|
|
1907
1920
|
* `ctx.log.<level>(message, fields)` / `ctx.log.with(fields)` call carries.
|
|
@@ -1952,6 +1965,14 @@ interface LogSinkContext {
|
|
|
1952
1965
|
interface LogEvent {
|
|
1953
1966
|
/** Raw arguments passed to the `ctx.log.*` call, in order. */
|
|
1954
1967
|
args: unknown[];
|
|
1968
|
+
/**
|
|
1969
|
+
* The first `Error` the call was handed, as an argument
|
|
1970
|
+
* (`ctx.log.error("failed", err)`) or a fields value (`{ err }`): its `name`,
|
|
1971
|
+
* unredacted `message`, `stack`, and `code` when it carries one. Absent when
|
|
1972
|
+
* the line logged no `Error`. An error tracker reads this rather than parsing
|
|
1973
|
+
* the rendered `message`.
|
|
1974
|
+
*/
|
|
1975
|
+
error?: ErrorDetail;
|
|
1955
1976
|
/**
|
|
1956
1977
|
* OTel `LogRecord.eventName` — set when the line was emitted as a **structured
|
|
1957
1978
|
* event** via `ctx.log.event(name, fields)` rather than as a human-readable
|
|
@@ -2398,11 +2419,15 @@ interface ObservabilityEvent {
|
|
|
2398
2419
|
/**
|
|
2399
2420
|
* Populated on `ok === false`. `code`/`status` mirror the LunoraError
|
|
2400
2421
|
* taxonomy; `message` is the human-readable string (may include user
|
|
2401
|
-
* input — sinks that ship to third parties should scrub it).
|
|
2422
|
+
* input — sinks that ship to third parties should scrub it). `name` and
|
|
2423
|
+
* `stack` are the thrown `Error`'s, captured where it was thrown — inside
|
|
2424
|
+
* the shard for a handler error — and are never sent to the client.
|
|
2402
2425
|
*/
|
|
2403
2426
|
error?: {
|
|
2404
2427
|
code: string;
|
|
2405
2428
|
message: string;
|
|
2429
|
+
name?: string;
|
|
2430
|
+
stack?: string;
|
|
2406
2431
|
status: number;
|
|
2407
2432
|
};
|
|
2408
2433
|
/**
|
|
@@ -4844,6 +4869,43 @@ interface DynamicShardRegistry extends ShardRegistry {
|
|
|
4844
4869
|
unregister: (table: string, shardKey: string) => Promise<void>;
|
|
4845
4870
|
}
|
|
4846
4871
|
declare const createDynamicShardRegistry: (options: DynamicShardRegistryOptions) => DynamicShardRegistry;
|
|
4872
|
+
/**
|
|
4873
|
+
* Helpers for handing a Lunora error to an error tracker from a sink.
|
|
4874
|
+
*
|
|
4875
|
+
* A failed RPC's `event.error` and a `ctx.log` line's `event.error` both carry
|
|
4876
|
+
* the thrown error as plain data (`name`, `message`, `stack`, `code`) — data,
|
|
4877
|
+
* because it crosses from the Durable Object to the worker. These turn that
|
|
4878
|
+
* data back into what trackers consume: a throwable for an SDK
|
|
4879
|
+
* (`Sentry.captureException(toError(event.error))`), or stack frames for an
|
|
4880
|
+
* HTTP ingestion API that wants them parsed (PostHog's `$exception_list`).
|
|
4881
|
+
*/
|
|
4882
|
+
/** The error half of an RPC event or a log event — what both helpers accept. */
|
|
4883
|
+
interface ReportedError {
|
|
4884
|
+
code?: string;
|
|
4885
|
+
message: string;
|
|
4886
|
+
name?: string;
|
|
4887
|
+
stack?: string;
|
|
4888
|
+
}
|
|
4889
|
+
/** One parsed stack frame. */
|
|
4890
|
+
interface StackFrame {
|
|
4891
|
+
colno: number;
|
|
4892
|
+
filename: string;
|
|
4893
|
+
/** The function name, or `"<anonymous>"` for a frame V8 printed without one. */
|
|
4894
|
+
function: string;
|
|
4895
|
+
lineno: number;
|
|
4896
|
+
}
|
|
4897
|
+
/**
|
|
4898
|
+
* Rebuild a throwable from an event's `error`, carrying the original `name`,
|
|
4899
|
+
* `message`, `stack`, and `code`, so an SDK groups it by the handler's real
|
|
4900
|
+
* stack rather than by the line that called the SDK.
|
|
4901
|
+
*/
|
|
4902
|
+
declare const toError: (error: ReportedError) => Error;
|
|
4903
|
+
/**
|
|
4904
|
+
* Parse a V8 stack trace into frames, **oldest call first** — the order Sentry
|
|
4905
|
+
* and PostHog expect. Lines that carry no location (`at Array.map (<anonymous>)`,
|
|
4906
|
+
* the leading `TypeError: …` line) are skipped; an absent stack yields `[]`.
|
|
4907
|
+
*/
|
|
4908
|
+
declare const parseStackFrames: (stack: string | undefined) => StackFrame[];
|
|
4847
4909
|
interface LunoraErrorBody {
|
|
4848
4910
|
error: ErrorBody;
|
|
4849
4911
|
}
|
|
@@ -4974,30 +5036,33 @@ interface WebhookSinkOptions extends OnlyErrorsOption {
|
|
|
4974
5036
|
*/
|
|
4975
5037
|
headers?: Record<string, string>;
|
|
4976
5038
|
/**
|
|
4977
|
-
* Optional
|
|
4978
|
-
*
|
|
4979
|
-
* `error.message`)
|
|
4980
|
-
*
|
|
4981
|
-
*
|
|
4982
|
-
*
|
|
5039
|
+
* Optional hook applied to each event immediately before it is serialized
|
|
5040
|
+
* and shipped. Its return value IS the request body, so it can scrub PII
|
|
5041
|
+
* (return the event minus `error.message`), filter (return `null`/`undefined`
|
|
5042
|
+
* to drop the event), or map the event onto a vendor's ingestion shape — e.g.
|
|
5043
|
+
* a PostHog `$exception` capture — without a dedicated sink. A throwing
|
|
5044
|
+
* `transform` drops the event (fail-closed) so a buggy redactor can never
|
|
5045
|
+
* leak the un-scrubbed payload.
|
|
4983
5046
|
*/
|
|
4984
|
-
transform?: (event: ObservabilityEvent) =>
|
|
5047
|
+
transform?: (event: ObservabilityEvent) => unknown;
|
|
4985
5048
|
/**
|
|
4986
|
-
* Optional
|
|
4987
|
-
*
|
|
4988
|
-
*
|
|
4989
|
-
*
|
|
4990
|
-
*
|
|
5049
|
+
* Optional hook for `ctx.log` events (the `transform` counterpart for log
|
|
5050
|
+
* lines). Same contract: the return value is the body, `null`/`undefined`
|
|
5051
|
+
* drops the line, and a throw drops it. When unset, log events are shipped
|
|
5052
|
+
* as-is (message + structured fields — which may carry user input; see the
|
|
5053
|
+
* privacy note).
|
|
4991
5054
|
*/
|
|
4992
|
-
transformLog?: (event: LogEvent) =>
|
|
5055
|
+
transformLog?: (event: LogEvent) => unknown;
|
|
4993
5056
|
/** The ingestion endpoint to POST each event to. */
|
|
4994
5057
|
url: string;
|
|
4995
5058
|
}
|
|
4996
5059
|
/**
|
|
4997
5060
|
* A fire-and-forget sink that POSTs each event as JSON to an HTTP endpoint.
|
|
4998
5061
|
*
|
|
4999
|
-
* This covers Axiom, Datadog, and any generic webhook/log-ingestion
|
|
5000
|
-
* point `url` at the ingestion endpoint
|
|
5062
|
+
* This covers Axiom, Datadog, PostHog, and any generic webhook/log-ingestion
|
|
5063
|
+
* service — point `url` at the ingestion endpoint, supply auth via `headers`,
|
|
5064
|
+
* and reshape the body with `transform` / `transformLog` when the vendor
|
|
5065
|
+
* expects its own format. Each
|
|
5001
5066
|
* event is sent as its own `fetch`. When the runtime supplies a per-event
|
|
5002
5067
|
* `context.waitUntil` (the request's `ctx.waitUntil`), the send is registered
|
|
5003
5068
|
* with it so it survives isolate teardown after the response returns; otherwise
|
|
@@ -5012,34 +5077,6 @@ interface WebhookSinkOptions extends OnlyErrorsOption {
|
|
|
5012
5077
|
* `transform` redacts/drops each event before send.
|
|
5013
5078
|
*/
|
|
5014
5079
|
declare const webhookSink: (options: WebhookSinkOptions) => ObservabilitySink;
|
|
5015
|
-
/** Options for {@link sentrySink}. */
|
|
5016
|
-
interface SentrySinkOptions extends OnlyErrorsOption {
|
|
5017
|
-
/**
|
|
5018
|
-
* User-supplied capture callback. Wire this to your Sentry client, e.g.
|
|
5019
|
-
* `(event) => Sentry.captureMessage(...)` or `captureException`. Kept as an
|
|
5020
|
-
* injected callback so the runtime takes no dependency on `@sentry/*`.
|
|
5021
|
-
*/
|
|
5022
|
-
capture: (event: ObservabilityEvent) => void;
|
|
5023
|
-
/**
|
|
5024
|
-
* Optional callback for `ctx.log` events. Wire it to Sentry's structured
|
|
5025
|
-
* logging or a breadcrumb, e.g. `(e) => Sentry.logger[e.level]?.(e.message,
|
|
5026
|
-
* e.fields)`. Omit it to leave `ctx.log` lines out of Sentry entirely
|
|
5027
|
-
* (capturing every log line would usually flood the project). Invoked inside
|
|
5028
|
-
* a try/catch so a throwing client can't break the handler.
|
|
5029
|
-
*/
|
|
5030
|
-
captureLog?: (event: LogEvent) => void;
|
|
5031
|
-
}
|
|
5032
|
-
/**
|
|
5033
|
-
* A thin adapter that forwards events to an injected `capture` callback.
|
|
5034
|
-
*
|
|
5035
|
-
* Intentionally does NOT bundle `@sentry/*`: the user wires their own Sentry
|
|
5036
|
-
* client (`captureException` / `captureMessage`) into `capture`, giving Sentry
|
|
5037
|
-
* parity without a hard dependency. The callback is invoked inside a try/catch
|
|
5038
|
-
* so a throwing client can't break dispatch.
|
|
5039
|
-
* @param options Sink options: `capture` is invoked per forwarded event;
|
|
5040
|
-
* `onlyErrors` defaults to true (error events only) — pass `false` for all.
|
|
5041
|
-
*/
|
|
5042
|
-
declare const sentrySink: (options: SentrySinkOptions) => ObservabilitySink;
|
|
5043
5080
|
/** One Analytics Engine data point — the structural subset {@link analyticsEngineSink} writes. */
|
|
5044
5081
|
interface AnalyticsEngineDataPointLike {
|
|
5045
5082
|
/** Free-form string dimensions (≤20, ≤5120 bytes total). */
|
|
@@ -5510,4 +5547,4 @@ export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolve
|
|
|
5510
5547
|
* surface — without a name for it, a caller cannot hoist a shared attribute bag
|
|
5511
5548
|
* into a typed constant.
|
|
5512
5549
|
*/
|
|
5513
|
-
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 PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type QueueForwardBatch, type QueueForwardHandler, type QueueForwardMessage, type QueueForwardResult, 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, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type
|
|
5550
|
+
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 PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type QueueForwardBatch, type QueueForwardHandler, type QueueForwardMessage, type QueueForwardResult, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ReportedError, 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, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StackFrame, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TriggerTrace, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, declareAppJurisdiction, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, normalizeBackupPrefix, otlpSink, parseStackFrames, pipelineLogSink, presenceProbe, r2Sink, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, toAirbyteMessages, toError, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as
|
|
1
|
+
import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as R,toFivetranResponse as x}from"./packem_shared/toAirbyteMessages-2d_iJXPf.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as y}from"./packem_shared/composeWorker-PP4n0KPn.mjs";import{createCrossShardRelationCapabilities as O}from"./packem_shared/createCrossShardRelationCapabilities-BiXSW10v.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-CdACWUQW.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w as B}from"./packem_shared/export-tap-CAyZ2TWC.mjs";import{HEALTH_PATH as w,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-CAX2UeFy.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as $,memoizeIdentityPerRequest as ee}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as oe,a as te}from"./packem_shared/observability-DgurIZIR.mjs";import{analyticsEngineSink as se,combineSinks as ie,consoleSink as pe,otlpSink as ne,pipelineLogSink as ce,webhookSink as me}from"./packem_shared/analyticsEngineSink-CDfEAQHU.mjs";import{D as Ee,c as Re}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as Se,createStaticShardRegistry as le}from"./packem_shared/createQueryCoordinator-CXdh_RxT.mjs";import{applyJurisdiction as ue,resolveShard as _e}from"./packem_shared/applyJurisdiction-D4vryLhj.mjs";import{a as ye,r as Ce,b as Oe}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as Ae,b as Le,c as Te,r as he}from"./packem_shared/rest-routes-D3ShCTHh.mjs";import{decorateResponse as Pe,enforceOrigin as ge,handleCorsPreflight as ve,resolveSecurity as Ie}from"./packem_shared/decorateResponse-CRrFNW1v.mjs";import{createShardClient as Fe}from"./packem_shared/createShardClient-BLW9uJZN.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ne}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ke}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Be}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as we,routeIdentityResolvers as ze}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Ee as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,w as HEALTH_PATH,z as HEALTH_READY_PATH,Ke as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,Be as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ne as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,se as analyticsEngineSink,ue as applyJurisdiction,ye as applyRestCache,Ae as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,Le as buildRestRoutes,ie as combineSinks,we as composeIdentityResolvers,l as composeWorker,pe as consoleSink,O as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,d as createLunoraHandler,M as createMemoryCursorStore,Re as createPipelineLogReader,Se as createQueryCoordinator,Te as createRestRateLimit,Fe as createShardClient,le as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Pe as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,ge as enforceOrigin,ve as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,ne as otlpSink,H as parseStackFrames,ce as pipelineLogSink,W as presenceProbe,G as r2Sink,Ce as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Ie as resolveSecurity,_e as resolveShard,Oe as restCacheHeaders,he as restSurfaceFromRegistry,ze as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,R as toAirbyteMessages,P as toError,I as toErrorResponse,x as toFivetranResponse,B as webhookExportSink,me as webhookSink,y as withFrameworkWorker};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as a}from"./LunoraError-DksAgIpa.mjs";import{applyJurisdiction as S,resolveShard as _}from"./applyJurisdiction-
|
|
1
|
+
import{LunoraError as a}from"./LunoraError-DksAgIpa.mjs";import{applyJurisdiction as S,resolveShard as _}from"./applyJurisdiction-D4vryLhj.mjs";const l="__lunora_shard_registry__",f=3e4,y="https://shard-registry.internal",g=async r=>await r.json(),T=r=>{const p=r.instanceName??l,i=r.cacheTtlMs??f,n=new Map,w=S(r.namespace,r.jurisdiction),c=()=>_(w,p),d=async(e,t)=>c().fetch(new Request(`${y}${e}`,{body:JSON.stringify(t),headers:{"content-type":"application/json"},method:"POST"})),h=async e=>c().fetch(new Request(`${y}${e}`,{method:"GET"}));return{invalidate(e){e===void 0?n.clear():n.delete(e)},async listShardKeys(e){const t=Date.now(),s=n.get(e);if(s&&s.expiresAt>t)return s.shardKeys;const o=await h(`/list?table=${encodeURIComponent(e)}`);if(!o.ok)throw new a(`shard registry /list returned ${String(o.status)}`);const{shardKeys:u}=await g(o);return i>0&&n.set(e,{expiresAt:t+i,shardKeys:u}),u},async register(e,t){const s=await d("/register",{shardKey:t,table:e});if(!s.ok)throw new a(`shard registry /register returned ${String(s.status)}`);n.delete(e)},async snapshot(){const e=await h("/snapshot");if(!e.ok)throw new a(`shard registry /snapshot returned ${String(e.status)}`);const{tables:t}=await g(e);return t},async unregister(e,t){const s=await d("/unregister",{shardKey:t,table:e});if(!s.ok)throw new a(`shard registry /unregister returned ${String(s.status)}`);n.delete(e)}}};export{f as DEFAULT_REGISTRY_CACHE_TTL_MS,l as SHARD_REGISTRY_DO_NAME,T as createDynamicShardRegistry};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as T}from"./LunoraError-DksAgIpa.mjs";import{m as A}from"./method-guard-BG_vJNTl.mjs";import{resolveShard as R}from"./applyJurisdiction-
|
|
1
|
+
import{LunoraError as T}from"./LunoraError-DksAgIpa.mjs";import{m as A}from"./method-guard-BG_vJNTl.mjs";import{resolveShard as R}from"./applyJurisdiction-D4vryLhj.mjs";const H="/_lunora/health",C="/_lunora/health/ready",N=t=>t==="liveness"?["liveness"]:t==="readiness"?["readiness"]:["liveness","readiness"];class P{#e=new Map;addChecker(e,s,r){this.#e.set(e,{run:s,types:r.type})}async getReport(e){const s=[...this.#e].filter(([,a])=>e===void 0||a.types.includes(e)),r=await Promise.all(s.map(async([a,o])=>[a,await o.run()]));return{healthy:r.every(([,a])=>a.health.healthy),report:Object.fromEntries(r)}}}const S=t=>{const e=new P,s=new Set;for(const r of t)r.critical&&s.add(r.name),e.addChecker(r.name,async()=>{let a;try{a=await r.check()}catch(o){a={healthy:!1,message:o instanceof Error?o.message:"probe failed"}}return{health:{healthy:a.healthy,...a.message===void 0?{}:{message:a.message}}}},{type:N(r.kind)});return{criticalNames:s,registry:e}},_=(t,e)=>{const s=t.includes(":")?t.slice(0,t.indexOf(":")):"probe",r=(e.get(s)??0)+1;return e.set(s,r),r===1?s:`${s}#${String(r)}`},j=(t,e)=>t?"unhealthy":e?"degraded":"healthy",M=(t,e,s,r,a)=>{const o=[];let u=!1,d=!1;const y=new Map;for(const[h,c]of Object.entries(t)){const n=e.has(h),i=c.health.healthy;d=d||!i,u=u||!i&&n;const l=s==="admin"?h:_(h,y);o.push({critical:n,...s==="admin"&&c.health.message!==void 0?{message:c.health.message}:{},name:l,status:i?"up":"down"})}return o.sort((h,c)=>h.name<c.name?-1:+(h.name>c.name)),{anyCriticalDown:u,body:{appName:r,appVersion:a,checks:o,status:j(u,d),timestamp:new Date().toISOString()}}},G=t=>{const{appName:e="lunora",appVersion:s="0.0.0",auth:r="public",cacheTtlMs:a,isAdmin:o,resolveProbes:u}=t,d=n=>a!==void 0?a:n==="readiness"?0:r==="public"?5e3:0,y={},h=n=>{if(r==="admin"&&!o(n))throw new T("health endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},c=async(n,i,l)=>{const p=A(n,["GET","HEAD"]);if(p)return p;h(n);const f=d(l);if(f>0){const m=y[l];if(m!==void 0&&Date.now()<m.expiresAt)return Response.json(m.body,{headers:{"cache-control":"no-store"},status:m.down?503:200})}const{criticalNames:b,registry:v}=S(u(i)),{healthy:E,report:k}=await v.getReport(l==="readiness"?"readiness":void 0),{anyCriticalDown:D,body:g}=M(k,b,r,e,s),w=l==="readiness"?!E:D;return f>0&&(y[l]={body:g,down:w,expiresAt:Date.now()+f}),Response.json(g,{headers:{"cache-control":"no-store"},status:w?503:200})};return{[H]:(n,i)=>c(n,i,"aggregate"),[C]:(n,i)=>c(n,i,"readiness")}},I=(t,e,s)=>({check:async()=>{try{return await R(e,s).fetch(new Request("https://shard.internal/_lunora/status",{method:"GET"})),{healthy:!0}}catch{return{healthy:!1,message:"durable object unreachable"}}},critical:!0,name:t}),q=(t,e)=>({check:async()=>{try{return await e.prepare("SELECT 1").first(),{healthy:!0}}catch{return{healthy:!1,message:"d1 query failed"}}},critical:!0,name:t}),B=(t,e)=>({check:()=>e?{healthy:!0}:{healthy:!1,message:"binding not configured"},critical:!1,name:t});export{H as HEALTH_PATH,C as HEALTH_READY_PATH,G as buildHealthRoutes,q as d1Probe,I as durableObjectProbe,B as presenceProbe};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{LunoraError as Q}from"@lunora/errors";import{redactArgs as R}from"@lunora/observability";import{e as d,L as h,o as j,c as I,O as V,f as v,g as tt,h as z,w as rt,i as ot,j as st,m as et}from"./otlp-resource-BwFJnvwB.mjs";const it=t=>{if(typeof t=="string")return t;if(t instanceof Error)return String(t);try{return JSON.stringify(t)??String(t)}catch{return String(t)}},W=t=>typeof t=="boolean"||typeof t=="number"||typeof t=="string"?t:it(t),nt=512,at=200,ct=t=>{const s=t.maxItems??nt,r=t.maxDelayMs??at;let o=[],e,c,i;const a=()=>{e!==void 0&&(clearTimeout(e),e=void 0)},y=async()=>{a();const p=o;o=[];const u=i;c=void 0,i=void 0;try{p.length>0&&await t.export(p)}catch{}finally{u?.()}},m=p=>{c===void 0&&(c=new Promise(u=>{i=u}),e=setTimeout(()=>{y()},r)),p?.(c)};return{add:(p,u)=>{for(o.push(p);o.length>s;)o.shift();m(u),o.length>=s&&y()},flush:async p=>{if(o.length===0){a();return}const u=y();return p?.(u),u},get size(){return o.length}}},dt=/["\\\u0000-\u001F\uD800-\uDFFF]/,B=t=>dt.test(t)?JSON.stringify(t):`"${t}"`,M=t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return B(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let i="[";for(let a=0;a<t.length;a++)a>0&&(i+=","),i+=M(t[a]);return i+"]"}const s=Object.getPrototypeOf(t);if(s!==null&&s!==Object.prototype){const i=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${i} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const r=t,o=Object.keys(r).sort();let e="{",c=!0;for(const i of o){const a=r[i];a!==void 0&&(c?c=!1:e+=",",e+=B(i),e+=":",e+=M(a))}return e+"}"},ut=1,lt=0,G=(t,s,r)=>[d("exception.type",t),d("exception.message",s),...r===void 0?[]:[d("exception.stacktrace",r)]],pt=(t,s)=>{const r=[d(h.functionPath,t.functionPath),d(h.ok,t.ok)];t.method!==void 0&&r.push(d("http.request.method",t.method)),t.path!==void 0&&r.push(d("url.path",t.path)),r.push(d("http.route",t.functionPath)),t.scheme!==void 0&&r.push(d("url.scheme",t.scheme)),t.host!==void 0&&r.push(d("server.address",t.host)),t.port!==void 0&&r.push(d("server.port",t.port)),t.userAgent!==void 0&&r.push(d("user_agent.original",t.userAgent)),t.shardKey!==void 0&&r.push(d(h.shardKey,t.shardKey)),t.rayId!==void 0&&r.push(d(h.rayId,t.rayId)),r.push(d("http.response.status_code",t.error?.status??200)),t.error&&r.push(d(h.errorType,t.error.code),d("lunora.error_status",t.error.status)),t.fanOut&&r.push(d("lunora.fanout.table",t.fanOut.table),d("lunora.fanout.shards",t.fanOut.shards),d("lunora.fanout.failed",t.fanOut.failed));const o={attributes:r,endTimeUnixNano:I(s),kind:V.server,name:t.functionPath,...t.parentSpanId===void 0?{}:{parentSpanId:t.parentSpanId},spanId:t.spanId??j(8),startTimeUnixNano:I(s-t.durationMs),status:t.ok?{code:1}:{code:2,message:t.error?.message??""},traceId:t.traceId??j(16)};return t.traceFlags!==void 0&&(o.flags=t.traceFlags),t.error&&(o.events=[{attributes:G(t.error.code,t.error.message,t.error.stack),name:"exception",timeUnixNano:I(s)}]),o},x=(t,s)=>{const r=new Map([[h.functionPath,d(h.functionPath,t.functionPath)]]);t.shardKey!==void 0&&r.set(h.shardKey,d(h.shardKey,t.shardKey)),t.userId!==void 0&&r.set(h.userId,d(h.userId,t.userId)),t.rayId!==void 0&&r.set(h.rayId,d(h.rayId,t.rayId)),t.errorType!==void 0&&r.set(h.errorType,d(h.errorType,t.errorType));for(const[o,e]of Object.entries(s??{}))r.set(o,d(o,W(e)));return[...r.values()]},ft=t=>{const s={attributes:x({errorType:t.error?.type,functionPath:t.functionPath,rayId:t.rayId,shardKey:t.shardKey,userId:t.userId},t.attributes),endTimeUnixNano:I(t.startTs+t.durationMs),flags:t.sampled===!1?lt:ut,kind:V[t.kind??"internal"],name:t.name,parentSpanId:t.parentSpanId,spanId:t.spanId,startTimeUnixNano:I(t.startTs),status:t.ok?{code:1}:{code:2,message:t.error?.message??""},traceId:t.traceId},r=o=>tt(Object.fromEntries(Object.entries(o??{}).map(([e,c])=>[e,W(c)])));return t.events!==void 0&&t.events.length>0&&(s.events=t.events.map(o=>({attributes:r(o.attributes),name:o.name,timeUnixNano:I(o.ts)}))),t.links!==void 0&&t.links.length>0&&(s.links=t.links.map(o=>({attributes:r(o.attributes),spanId:o.spanId,traceId:o.traceId}))),s},mt=t=>{const s=I(t.ts),r=x({functionPath:t.functionPath,shardKey:t.shardKey},t.attributes),o=t.traceId===void 0?void 0:[{asDouble:t.value,timeUnixNano:s,traceId:t.traceId}],e={asDouble:t.value,attributes:r,...o===void 0?{}:{exemplars:o},timeUnixNano:s};return t.kind==="gauge"?{gauge:{dataPoints:[e]},name:t.name}:t.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:r,bucketCounts:["1"],count:"1",...o===void 0?{}:{exemplars:o},explicitBounds:[],max:t.value,min:t.value,sum:t.value,timeUnixNano:s}]},name:t.name}:{name:t.name,sum:{aggregationTemporality:1,dataPoints:[e],isMonotonic:!0}}},ht=t=>{const s={attributes:x({functionPath:t.functionPath,rayId:t.rayId,shardKey:t.shardKey,userId:t.userId},t.fields),body:{stringValue:t.message},severityNumber:v[t.level],severityText:t.level.toUpperCase(),timeUnixNano:I(t.ts)};if(t.traceId!==void 0&&(s.traceId=t.traceId),t.spanId!==void 0&&(s.spanId=t.spanId),t.error!==void 0){const r=G(t.error.name,t.error.message,t.error.stack),o=new Set(r.map(e=>e.key));s.attributes=[...s.attributes.filter(e=>!o.has(e.key)),...r]}return t.eventName!==void 0&&(s.eventName=t.eventName,s.attributes.push(d("event.name",t.eventName))),s},yt=1024,C=5;let A=0;const gt=(t,s)=>{if(A>=C)return;A+=1;let r;try{r=new URL(t).host}catch{r="<unparseable endpoint>"}const o=A===C?" Further OTLP rejections are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] collector ${r} rejected the export with HTTP ${String(s)}; the batch is DROPPED (there is no retry).${o}`)},bt=async t=>{const s=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(s).arrayBuffer()},X=async(t,s,r,o)=>{try{const e=JSON.stringify(s),{byteLength:c}=new TextEncoder().encode(e),i=(c<yt?fetch(t,{body:e,headers:r,method:"POST"}):bt(e).then(a=>fetch(t,{body:a,headers:{...r,"content-encoding":"gzip"},method:"POST"}))).then(a=>{a.ok||gt(t,a.status)},()=>{});o?.(i),await i}catch{}},kt=(t,s,r,o)=>{X(t,s,r,o?.waitUntil).catch(()=>{})},N=(t,s)=>s===!0&&t.ok,It=t=>t.kind==="metric"?void 0:t.event.traceId,St=t=>{const s=Map.groupBy(t,o=>It(o)),r=s.get(void 0)??[];return s.delete(void 0),{byTrace:s,untraced:r}},J=5,Tt=(t,s,r)=>{if(s===void 0)return t;const{byTrace:o,untraced:e}=St(t),c=[...e];let i=0,a;for(const[y,m]of o){let p;try{p=s({logs:m.filter(u=>u.kind==="log").map(u=>u.event),rpc:m.filter(u=>u.kind==="rpc").map(u=>u.event),spans:m.filter(u=>u.kind==="span").map(u=>u.event),traceId:y})}catch(u){i+=1,i===1&&(a=u),p=!0}p&&c.push(...m)}return i>0&&r(a,i),c},P=(t,s)=>{let r;try{r=s===void 0?t:s(t)}catch{r=void 0}return r??void 0},wt=t=>{const s=R(t.message);if(t.stack===void 0)return{...t,message:s};const r=`: ${t.message}`,o=t.stack.indexOf(r),c=t.message!==""&&o!==-1&&!t.stack.slice(0,o).includes(`
|
|
2
|
+
`)?t.stack.slice(o+r.length):t.stack.split(`
|
|
3
|
+
`).filter(i=>i.trimStart().startsWith("at ")).map(i=>`
|
|
4
|
+
${i}`).join("");return{...t,message:s,stack:`${t.name}: ${s}${c}`}},Pt=t=>({...t,...t.error===void 0?{}:{error:wt(t.error)},...t.fields===void 0?{}:{fields:R(t.fields)},message:R(t.message)}),H=(t,s,r)=>{if(t.kind==="rpc"){const e=P(t.event,s?.rpc);return e===void 0?void 0:{bucket:"spans",encoded:pt(e,t.endMs)}}if(t.kind==="span"){const e=P(t.event,s?.span);return e===void 0?void 0:{bucket:"spans",encoded:ft(e)}}if(t.kind==="log"){const e=P(r?Pt(t.event):t.event,s?.log);return e===void 0?void 0:{bucket:"logs",encoded:ht(e)}}const o=P(t.event,s?.metric);return o===void 0?void 0:{bucket:"metrics",encoded:mt(o)}},Ot=["fuseCloudflareTraces","instrumentDatabase","metricHistory","traceFetch"],At=(t={})=>{const{onlyErrors:s}=t;return{onLog:r=>{r.level==="error"||r.level==="fatal"?console.error("[lunora:log]",r.functionPath,r.message):console.log("[lunora:log]",r.functionPath,r.message)},onMetric:r=>{console.log("[lunora:metric]",`${r.name}=${String(r.value)}`,r.kind,r.functionPath)},onRpc:r=>{N(r,s)||(r.ok?console.log("[lunora:rpc]",r):console.error("[lunora:rpc]",r))},onSpan:r=>{const o=r.ok?"ok":`error ${r.error?.type??""}`.trim();console.log("[lunora:span]",r.name,`${String(r.durationMs)}ms`,o,r.functionPath)}}},Rt=t=>{const{headers:s,onlyErrors:r,transform:o,transformLog:e,url:c}=t,i=z({"content-type":"application/json"},s),a=(y,m)=>{try{const p=fetch(c,{body:JSON.stringify(y),headers:i,method:"POST"}).catch(()=>{});m?.waitUntil&&m.waitUntil(p)}catch{}};return{onLog:(y,m)=>{const p=P(y,e);p!==void 0&&a(p,m)},onRpc:(y,m)=>{if(N(y,r))return;const p=P(y,o);p!==void 0&&a(p,m)}}},Mt=t=>{const{dataset:s,onlyErrors:r}=t;return{onRpc:o=>{if(!N(o,r))try{s.writeDataPoint({blobs:[o.functionPath,o.ok?"ok":"error",o.shardKey??"",o.error?.code??"",o.fanOut?.table??""],doubles:[o.durationMs,o.ok?0:1,o.fanOut?.shards??0,o.fanOut?.failed??0],indexes:[o.functionPath]})}catch{}}}},xt=t=>{const{pipeline:s,serializeFields:r}=t;return{onLog:(o,e)=>{try{const c={functionPath:o.functionPath,level:o.level,message:o.message,ts:o.ts};o.fields&&(c.fields=r===!0?JSON.stringify(o.fields):o.fields);for(const a of["shardKey","userId","traceId","spanId"])o[a]!==void 0&&(c[a]=o[a]);const i=s.send([c]).catch(()=>{});e?.waitUntil&&e.waitUntil(i)}catch{}}}},_t=t=>{const{batch:s,deploymentEnvironment:r,detectResources:o,endpoint:e,headers:c,onlyErrors:i,postProcessor:a,resourceAttributes:y,serviceNamespace:m,serviceVersion:p,tailSampler:u,token:q}=t,_=t.serviceName??"lunora",U=t.redactLogs??!0;if(s!==!1&&s?.maxItems!==void 0&&(!Number.isInteger(s.maxItems)||s.maxItems<1))throw new Q("ENV_INVALID",`otlpSink: \`batch.maxItems\` must be a positive integer, received ${String(s.maxItems)}.`);const D={...p===void 0?{}:{"service.version":p},...m===void 0?{}:{"service.namespace":m},...r===void 0?{}:{"deployment.environment":r},...y},F=new WeakMap,k=l=>{if(o!==!0||l?.resourceAttributes===void 0)return D;const n=F.get(l);if(n!==void 0)return n;const f=et(l.resourceAttributes(),D);return F.set(l,f),f};let S=e;for(;S.endsWith("/");)S=S.slice(0,-1);const $={logs:{url:`${S}/v1/logs`,wrap:st},metrics:{url:`${S}/v1/metrics`,wrap:ot},spans:{url:`${S}/v1/traces`,wrap:rt}},K=z({"content-type":"application/json"},c,q);let L=0;const Y=(l,n)=>{if(L>=J)return;L+=1;const f=L===J?" Further tailSampler failures from this sink are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] tailSampler threw for ${String(n)} trace(s) in this flush window; keeping them (fail-open), so the sampling policy did NOT apply.${f}`,l)},Z=async l=>{const n=Tt(l,u,Y),f=new Map;for(const g of n){const b=H(g,a,U);if(b===void 0)continue;const E=M(g.resource);let w=f.get(E);w===void 0&&(w={logs:[],metrics:[],resource:g.resource,spans:[]},f.set(E,w)),w[b.bucket].push(b.encoded)}const T=[];for(const[,g]of f)for(const b of["spans","logs","metrics"])if(g[b].length>0){const{url:E,wrap:w}=$[b];T.push(X(E,w(g[b],"@lunora/runtime",_,g.resource),K))}await Promise.all(T)};if(s===!1){const l=(n,f)=>{const T=H(n,a,U);if(T!==void 0){const{url:g,wrap:b}=$[T.bucket];kt(g,b(T.encoded,"@lunora/runtime",_,n.resource),K,f)}};return{onLog:(n,f)=>{l({event:n,kind:"log",resource:k(f)},f)},onMetric:(n,f)=>{l({event:n,kind:"metric",resource:k(f)},f)},onRpc:(n,f)=>{N(n,i)||l({endMs:Date.now(),event:n,kind:"rpc",resource:k(f)},f)},onSpan:(n,f)=>{l({event:n,kind:"span",resource:k(f)},f)}}}const O=ct({export:Z,...s?.maxDelayMs===void 0?{}:{maxDelayMs:s.maxDelayMs},...s?.maxItems===void 0?{}:{maxItems:s.maxItems}});return{flush:l=>{O.flush(l?.waitUntil).catch(()=>{})},onLog:(l,n)=>{O.add({event:l,kind:"log",resource:k(n)},n?.waitUntil)},onMetric:(l,n)=>{O.add({event:l,kind:"metric",resource:k(n)},n?.waitUntil)},onRpc:(l,n)=>{N(l,i)||O.add({endMs:Date.now(),event:l,kind:"rpc",resource:k(n)},n?.waitUntil)},onSpan:(l,n)=>{O.add({event:l,kind:"span",resource:k(n)},n?.waitUntil)}}},Ut=(...t)=>{const s=(o,e)=>{for(const c of t){const i=c[o];if(i)try{i.apply(c,e)}catch{}}},r={};for(const o of t)for(const e of Ot)r[e]===void 0&&o[e]!==void 0&&(r[e]=o[e]);return{...r,flush:o=>{s("flush",[o])},onLog:(o,e)=>{s("onLog",[o,e])},onMetric:(o,e)=>{s("onMetric",[o,e])},onRpc:(o,e)=>{s("onRpc",[o,e])},onSpan:(o,e)=>{s("onSpan",[o,e])}}};export{Mt as analyticsEngineSink,Ut as combineSinks,At as consoleSink,_t as otlpSink,xt as pipelineLogSink,Rt as webhookSink};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LUNORA_ROLE_PREFIX as d,resolveShard as f}from"@lunora/platform";import{LunoraError as m}from"./LunoraError-DksAgIpa.mjs";const a=new WeakMap,n=e=>e===void 0?void 0:{locationHint:e},p=e=>typeof e.idFromName=="function",u=e=>{if(!p(e))return e;const o=e,i=a.get(e);if(i!==void 0)return i;const s=typeof o.jurisdiction=="function"?r=>u(o.jurisdiction(r)):void 0,c=typeof o.getByName=="function"?{get:(r,t)=>o.get(r,n(t)),getByName:(r,t)=>o.getByName(r,n(t)),idForName:r=>o.idFromName(r),jurisdiction:s}:{get:(r,t)=>o.get(r,n(t)),idForName:r=>o.idFromName(r),jurisdiction:s};return a.set(e,c),c},g=(e,o)=>{if(o===void 0)return e;if(typeof e.jurisdiction!="function")throw new TypeError(`@lunora/runtime: Durable Object namespace does not support jurisdiction("${o}") — update @cloudflare/workers-types or remove the jurisdiction option`);return e.jurisdiction(o)},h=(e,o,i)=>{if(o.startsWith(d))throw new m(`shard key "${o}" uses the reserved "${d}" prefix`,{code:"BAD_REQUEST",status:400});return f(u(e),o,i)};export{g as applyJurisdiction,h as resolveShard};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{isLunoraError as wr,toErrorBody as gr}from"@lunora/errors";import{e as sn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as yr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as br,f as _r}from"./base64-Bl1_r2k1.mjs";import{i as Rr,e as Er,a as Ar,E as bt,d as Tr}from"./identity-header-pR617HTs.mjs";import{O as _t,a as Rt}from"./origin-paywall-B6eOO67m.mjs";import{o as ge,b as cn,p as Sr,m as Or,d as vr,a as Ir,r as kr}from"./otlp-resource-BwFJnvwB.mjs";import{r as Pr,f as Et,a as de,S as At}from"./observability-DgurIZIR.mjs";import{e as Oe,d as Xe,a as Dr}from"./wire-codec-BLvSm5Mn.mjs";import{d as ee,e as ne,M as dn,b as Nr,f as Ur,g as un,w as Cr,h as ln,t as Br}from"./rest-routes-D3ShCTHh.mjs";import{LunoraError as c,toErrorResponse as Tt}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as we}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as ot,BACKUP_KEY_PREFIX as at,isBackupManifestKey as xr,backupObjectKeyOfManifest as hn,backupObjectKey as Hr,backupManifestKey as Lr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as jr,buildStorageAdminRoutes as Mr,STORAGE_UPLOAD_MAX_BODY_BYTES as $r,STORAGE_PATH as Kr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as Fr,e as Gr,f as St,g as Qr,h as Wr}from"./export-tap-CAyZ2TWC.mjs";import{buildHealthRoutes as zr,durableObjectProbe as Vr,d1Probe as Jr,presenceProbe as $e}from"./HEALTH_PATH-CAX2UeFy.mjs";import{wrapResolverWithContract as Yr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Mi,routeIdentityResolvers as $i}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as qr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{pruneShardRegistry as Xr,createQueryCoordinator as Zr,createDefaultShardRegistry as eo}from"./createQueryCoordinator-CXdh_RxT.mjs";import{resolveShard as ye,applyJurisdiction as Ke}from"./applyJurisdiction-D4vryLhj.mjs";import{resolveSecurity as Ot,handleCorsPreflight as to,enforceOrigin as no,decorateResponse as Fe,enforceWebSocketOrigin as vt}from"./decorateResponse-CRrFNW1v.mjs";const ro=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},fn="__lunoraBranch",oo=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,fn),ao=`may not contain the reserved workflow branch-marker key ("${fn}")`,so=async e=>{const t=[];let n;for(;;){const o=await e(n);if(t.push(...Array.isArray(o.records)?o.records:[]),o.truncated!==!0||typeof o.cursor!="string"||o.cursor.length===0)return t;if(o.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=o.cursor}},st=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,d=a<t.length?t.charCodeAt(a):0;o|=i^d}return o===0},io=/already[\s_-]?exists/iu,co=e=>io.test(e instanceof Error?e.message:String(e)),It="x-lunora-want-error-detail",kt="x-lunora-error-detail",uo=8192,lo=e=>{if(!(e instanceof Error))return{message:String(e),name:typeof e};const{code:t}=e;return{...typeof t=="string"?{code:t}:{},message:e.message,name:e.name,...e.stack===void 0?{}:{stack:e.stack.slice(0,uo)}}},Pt=e=>{if(e!=null)try{const t=JSON.parse(decodeURIComponent(e));return typeof t?.message=="string"&&typeof t.name=="string"?t:void 0}catch{return}},ho=(e,t,n,o)=>{const a=e.get(t);if(a!==void 0)return a;sn(e,o);const i=n().catch(d=>{throw e.get(t)===i&&e.delete(t),d});return e.set(t,i),i},it=new TextEncoder,fo=Array.from({length:32},(e,t)=>t);new RegExp(`[${fo.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const po=64,mo=new Map,pn=async e=>ho(mo,e,async()=>crypto.subtle.importKey("raw",it.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),po),mn=async(e,t)=>{const n=await pn(e),o=await crypto.subtle.sign("HMAC",n,it.encode(t));return br(new Uint8Array(o))},wo=async(e,t,n)=>{const o=await pn(e);return crypto.subtle.verify("HMAC",o,n,it.encode(t))},go="cf-ray",yo="x-lunora-ray-id",bo=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,_o=e=>e==null?void 0:bo.exec(e.trim())?.[1]?.toLowerCase(),Ro=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Ro);const Eo=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Ao=-100,To=15,So=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Eo.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>To?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Ao?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},Dt=e=>{const t=e.cf;return t===void 0?void 0:So(t)},Ze="::relay::",Oo=(e,t)=>`${e}${Ze}${String(t)}`,et="::replica::",vo=(e,t)=>`${e}${et}${t}`,Io=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},ko=(e,t,n)=>e?.[n]??t?.[n],Po=(e,t,n,o)=>{const a=ko(e,t,n);if(!(typeof a!="object"||a===null))return o.every(i=>typeof a[i]=="function")?a:void 0},Do=new Set(["1","enabled","on","true","yes"]),No=new Set(["0","disabled","false","no","off"]),Uo=(e,t)=>{const n=(e??"").trim().toLowerCase();return Do.has(n)?!0:No.has(n)?!1:t},wn="v1",Co=6e4,Bo=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Co),o=`${wn}.${String(n)}`,a=await mn(e,o);return{expiresAtMs:n,token:`${o}.${a}`}},xo=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[a,i,d]=o;if(a!==wn||d.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let h;try{h=_r(d)}catch{return!1}return wo(e,`${a}.${i}`,h)},N="/_lunora/admin/auth",Ho={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},C=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},pe=(e,t)=>{const n=e(t);if(n===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},gn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ge=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},Nt=e=>{const t=gn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},Ut=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[o,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[o]=a);return n},Lo={[`${N}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${N}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${N}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${N}/accounts`]:{build:({query:e})=>({userId:pe(e,"userId")}),http:"GET",method:"listAccounts"},[`${N}/passkeys`]:{build:({query:e})=>({userId:pe(e,"userId")}),http:"GET",method:"listPasskeys"},[`${N}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${N}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:pe(t,"organizationId")}),http:"GET",method:"listMembers"},[`${N}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:pe(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${N}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${N}/sign-up-invitations/create`]:{build:({body:e})=>({email:C(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:te(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${N}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:C(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${N}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${N}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:pe(t,"organizationId")}),http:"GET",method:"listTeams"},[`${N}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:pe(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${N}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:pe(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${N}/users/create`]:{build:({body:e})=>({data:Ge(e,"data"),email:C(e,"email"),name:C(e,"name"),password:te(e,"password"),role:gn(e.role)}),http:"POST",method:"createUser"},[`${N}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:C(e,"userId")}},http:"POST",method:"updateUser"},[`${N}/users/role`]:{build:({body:e})=>({role:Nt(e),userId:C(e,"userId")}),http:"POST",method:"setRole"},[`${N}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:C(e,"userId")}),http:"POST",method:"banUser"},[`${N}/users/unban`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"unbanUser"},[`${N}/users/password`]:{build:({body:e})=>({newPassword:C(e,"newPassword"),userId:C(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${N}/users/remove`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${N}/users/impersonate`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"impersonateUser"},[`${N}/sessions/revoke`]:{build:({body:e})=>({sessionId:C(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${N}/sessions/revoke-all`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${N}/accounts/unlink`]:{build:({body:e})=>({accountId:C(e,"accountId"),userId:C(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${N}/two-factor/disable`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${N}/passkeys/delete`]:{build:({body:e})=>({passkeyId:C(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${N}/organizations/members/remove`]:{build:({body:e})=>({memberId:C(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${N}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:C(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${N}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ge(e,"metadata"),name:C(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${N}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ge(e,"metadata"),name:te(e,"name"),organizationId:C(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${N}/organizations/remove`]:{build:({body:e})=>({organizationId:C(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${N}/organizations/members/add`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),role:te(e,"role"),userId:C(e,"userId")}),http:"POST",method:"addMember"},[`${N}/organizations/members/invite`]:{build:({body:e})=>({email:C(e,"email"),inviterId:te(e,"inviterId"),organizationId:C(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${N}/organizations/members/role`]:{build:({body:e})=>({memberId:C(e,"memberId"),role:Nt(e)}),http:"POST",method:"updateMemberRole"},[`${N}/organizations/teams/create`]:{build:({body:e})=>({name:C(e,"name"),organizationId:C(e,"organizationId")}),http:"POST",method:"createTeam"},[`${N}/organizations/teams/update`]:{build:({body:e})=>({name:C(e,"name"),teamId:C(e,"teamId")}),http:"POST",method:"updateTeam"},[`${N}/organizations/teams/remove`]:{build:({body:e})=>({teamId:C(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${N}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:C(e,"teamId"),userId:C(e,"userId")}),http:"POST",method:"addTeamMember"},[`${N}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:C(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${N}/organizations/roles/create`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),permission:Ut(e),role:C(e,"role")}),http:"POST",method:"createOrgRole"},[`${N}/organizations/roles/update`]:{build:({body:e})=>({permission:Ut(e),roleId:C(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${N}/organizations/roles/remove`]:{build:({body:e})=>({roleId:C(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},jo=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof c)throw i;const d=i,f=typeof d.code=="string"?d.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:f,status:Ho[f]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const d=e.getAuthAdmin();if(d===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=d[i.method];if(f===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const h=new URL(a.url),m={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:S=>e.queryParameter(h,S)},b=i.build(m),T=await t(()=>f(b));return Response.json(i.returns==="void"?{ok:!0}:T,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[a,i]of Object.entries(Lo))o[a]=d=>n(d,i);return o},Ct="__lunora_admin__:getAuthAuditLog",Bt=e=>typeof e=="string"&&e!==""?e:void 0,xt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Mo=e=>async(n,o)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=Bt(o.actorId),d=Bt(o.event),f=xt(o.sinceSeq),h=xt(o.limit),m={...i===void 0?{}:{actorId:i},...d===void 0?{}:{event:d},...f===void 0?{}:{sinceSeq:f},...h===void 0?{}:{limit:h}};let b;try{b=await a.read(m)}catch(S){throw S instanceof c?S:(console.error("[lunora] auth audit read failed:",S),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const T={entries:b};return Response.json({result:Oe(T)},{headers:{"content-type":"application/json"},status:200})},tt="__lunora_admin__:copyAuthToJurisdiction",yn="__lunora_admin__:purgeUnpinnedAuth",$o=e=>async(t,n,o)=>{if(n!==tt&&n!==yn)return;e.assertAdmin(t);const a=e.getMove();if(a===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===tt?await a.copy({force:o.force===!0}):await a.purge();return Response.json({result:Oe(i)},{headers:{"content-type":"application/json"},status:200})},Ko=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?o.push(a):n.push(a);return{globalTables:o,shardLocalTables:n}},Fo=async(e,t,n,o,a,i)=>{if(n!==void 0&&o.length===0)return[];const d=await e.orchestrateExport(a,{args:{tables:o},defaultShardKey:i,headers:t,tables:o}),f=d.shards.filter(h=>h.error);if(f.length>0){const h=f.map(m=>`${m.shardKey}: ${m.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(f.length)} of ${String(d.shards.length)} shard(s) — ${h}`,{code:"EXPORT_SHARD_FAILED",status:502})}return d.shards.flatMap(h=>h.rows??[])},bn=async(e,t,n,o,a)=>{const i=o??e.listSchemaTables?.();o===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:d,shardLocalTables:f}=Ko(e,i),h=await Fo(t,n,i,f,a,e.defaultShardKey??"__root__"),m=e.exportGlobals,b=o===void 0||d.length>0;return(async function*(){yield*h,b&&m&&(yield*m({tables:d}))})()},Go=async(e,t,n,o,a,i)=>{for await(const d of await bn(e,t,n,o,i))a(d)},Qo=new TextEncoder,Wo=1e3,_n=10,zo=200,Ht=8,Rn="lunoraBackupCron",Lt=24*1048576,jt=e=>{const t=e.slice(0,_n).map(o=>hn(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Vo=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const a of e)n.set(a,o),o+=a.byteLength;return n},ct=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let d=0;d<Wo;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)xr(h.key)&&h.customMetadata?.[Rn]===o&&a.push(h.key);if(!f.truncated||f.cursor===void 0)break;i=f.cursor}return{eligible:a.length,stale:a.toSorted((d,f)=>f.localeCompare(d)).slice(n)}},Jo=async(e,t,n,o,a)=>{const{stale:i}=await ct(e,t,n,o),d=new Set(a),f=i.filter(k=>d.has(k)),h=f.slice(0,zo),m=i.length-h.length,b=a.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:b,remaining:m};const T=[],S=[];for(let k=0;k<h.length;k+=Ht){const w=await Promise.allSettled(h.slice(k,k+Ht).map(async g=>(await e.delete(hn(g)),await e.delete(g),g)));for(const[g,y]of w.entries())y.status==="fulfilled"?T.push(y.value):S.push(h[k+g])}return T.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(T.length)}: ${jt(T)}`),S.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(S.length)}: ${jt(S)}`),{deleted:T,failed:S,ignored:b,remaining:m}},Yo=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=ot(e.backupPrefix??at),o=e.backupCron,{eligible:a,stale:i}=o===void 0?{eligible:0,stale:[]}:await ct(t,n,e.backupRetain,o);return{cron:o,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},qo=async(e,t,n,o,a)=>{const i=e.backupStore;if(!i)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!o||o.length===0)throw new c("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const d={authorization:`Bearer ${o}`,"content-type":"application/json"},f=e.backupTables;let h=0,m=0,b=[];await Go(e,t,d,f,I=>{const E=Qo.encode(`${JSON.stringify(I)}
|
|
2
|
+
`);if(h+=1,m+=E.byteLength,m>Lt)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Lt)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});b.push(E)},n);const S=ot(e.backupPrefix??at),k=new Date(a.scheduledTime).toISOString(),w=Hr(S,k),g=Vo(b,m);b=[];const y=jr(await crypto.subtle.digest("SHA-256",g));await i.put(w,g,{httpMetadata:{contentType:"application/x-ndjson"},sha256:y});const v={bytes:m,createdAt:k,cron:a.cron,file:w,id:k,rows:h,scheduledTime:a.scheduledTime,sha256:y,...f?{tables:f.join(",")}:{}};await i.put(Lr(w),`${JSON.stringify(v,void 0,2)}
|
|
3
|
+
`,{customMetadata:{[Rn]:a.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:I}=await ct(i,S,e.backupRetain,a.cron);if(I.length>0){const E=I.slice(0,_n),j=I.length-E.length;console.info(`[lunora] backup retention: ${String(I.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${E.join(", ")}${j>0?` (+${String(j)} more)`:""}`)}}catch(I){console.warn(`[lunora] backup ${w} was written, but the retention report failed:`,I)}},Xo=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const o=e.backupCron,a=e.backupRetain;if(o===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return Jo(n,ot(e.backupPrefix??at),a,o,t)},Zo="/_lunora/admin/backup/retention",ea="/_lunora/admin/backup/prune",ta=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,a=(f,h)=>{o(f,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${h} requires a \`backupStore\` on the worker`})},i=async f=>(M(f,"GET","Backup-retention"),a(f,"retention preview"),Response.json(await Yo(t),{headers:{"cache-control":"no-store"}})),d=async f=>{M(f,"POST","Backup-prune"),a(f,"prune");const{confirm:h}=await n(f);if(!Array.isArray(h)||h.some(m=>typeof m!="string"))throw new c("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await Xo(t,h),{headers:{"cache-control":"no-store"}})};return{[ea]:d,[Zo]:i}},Mt=500,na=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const o=e;if(typeof o.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(o.functionPath.startsWith("__lunora_relation__:")||o.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(o.args!==void 0&&(typeof o.args!="object"||o.args===null||Array.isArray(o.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(o.id!==void 0&&typeof o.id!="number")throw new c("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:o.args===void 0?{}:o.args,baselineSeq:typeof o.baselineSeq=="number"?o.baselineSeq:void 0,clientId:typeof o.clientId=="string"?o.clientId:void 0,clientSeq:typeof o.clientSeq=="number"?o.clientSeq:void 0,functionPath:o.functionPath,id:typeof o.id=="number"?o.id:t,mutationId:typeof o.mutationId=="string"?o.mutationId:void 0},shardKey:typeof o.shardKey=="string"?o.shardKey:n}},ra=(e,t)=>{if(e.length>Mt)throw new c(`RPC batch exceeds the ${String(Mt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,o=new Set;for(const[a,i]of e.entries()){const{entry:d,shardKey:f}=na(i,a,t);if(o.has(d.id))throw new c(`batch call id ${String(d.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});o.add(d.id);const h=n.get(f)??[];h.push(d),n.set(f,h)}return n},oa="/_lunora/admin/export",aa="/_lunora/admin/import",sa="/_lunora/admin/sync",ia="/_lunora/admin/connector/sync",ca="/_lunora/admin/apply",da="/_lunora/admin/export-tap/run",ua=new TextEncoder,la=async e=>{const n=await ne(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const o=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});o.push(a)}return{tables:o}},Qe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,ha=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:a,knownTables:i,queryCoordinator:d,assertAdmin:f,resolveForwardContext:h,shardDO:m,prepareExportRows:b,streamingImport:T,syncGlobals:S}=e,k=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const U=await la(E),{headers:K}=await h(E,j),W=await b(K,U.tables),Y=new ReadableStream({async pull(q){try{for await(const G of W)q.enqueue(ua.encode(`${JSON.stringify(G)}
|
|
4
|
+
`));q.close()}catch(G){q.error(G)}}});return new Response(Y,{headers:{"content-type":"application/x-ndjson"},status:200})},w=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const U=await ee(E),K=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},W=typeof U.epochs=="object"&&U.epochs!==null?U.epochs:{},Y=typeof U.limit=="number"?U.limit:void 0,q=typeof U.globalCursor=="number"?U.globalCursor:0,G=Qe(U.tables),{headers:re}=await h(E,j),Q=G??i(),ue=await d.orchestrateCdcSync(m,{cursors:K,defaultShardKey:n,epochs:W,headers:re,limit:Y,tables:Q}),oe=S?await S({limit:Y,sinceSeq:q}):void 0;return Response.json({global:oe,shards:ue.shards},{status:200})},g=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const U=await ee(E),K=Gr(U.cursor),W=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,Y=Qe(U.tables),{headers:q}=await h(E,j),G=Y??i(),re=await d.orchestrateCdcSync(m,{cursors:K.s,defaultShardKey:n,headers:q,limit:W,tables:G}),Q=[],ue={...K.s};let oe=!1;for(const se of re.shards)oe=St(Q,se.changes??[],Wr(W))||oe,ue[se.shardKey]=se.cursor;let be=K.g;if(S){const se=await S({limit:W,sinceSeq:K.g});oe=St(Q,se.changes,W)||oe,be=se.cursor}const z=Qr({g:be,s:ue,v:1}),ae={changes:Q,hasMore:oe,nextCursor:z};return Response.json(ae,{status:200})},y=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const U=await ee(E),W=(Array.isArray(U.batches)?U.batches:[]).map(Q=>Q).filter(Q=>Q!==null&&typeof Q=="object"&&typeof Q.shardKey=="string"&&Array.isArray(Q.changes)),Y=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:q}=await h(E,j),G=await d.orchestrateApplyCdc(m,{batches:W,headers:q}),re=Y.length>0&&t?await t({changes:Y}):0;return Response.json({applied:G.applied+re,failed:G.failed,ok:G.ok},{status:200})},v=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const{headers:U}=await h(E,j),K=await T(E,U);return Response.json(K,{headers:{"content-type":"application/json"},status:K.failed.length>0?207:200})},I=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;if(f(E),a===void 0||Object.keys(a).length===0||o===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const U=await ee(E),K=typeof U.sink=="string"?U.sink:void 0,W=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,Y=Qe(U.tables);if(K===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const q=a[K];if(q===void 0)throw new c(`Export-tap sink "${K}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:G}=await h(E,j),re=Y??i(),Q=await Fr({coordinator:d,cursorStore:o,defaultShardKey:n,headers:G,limit:W,shardDO:m,sink:q,tables:re});return Response.json(Q,{headers:{"content-type":"application/json"},status:200})};return{[ca]:y,[ia]:g,[oa]:k,[da]:I,[aa]:v,[sa]:w}},fa=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const o=n;return typeof o.table!="string"||o.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!o.doc||typeof o.doc!="object"||Array.isArray(o.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:o.table},ok:!1}:{doc:o.doc,ok:!0,table:o.table}},pa=(e,t,n,o,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:o}},ma=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const o=[],a=[],i=new Map;let d=0,f=0;const h=e.body.getReader(),m=new TextDecoder;let b="",T=0;const S=k=>{f+=1;const w=k.trim();if(w.length===0)return;d+=1;const g=fa(w,f);if(!g.ok){o.push(g.error);return}const{doc:y,table:v}=g,I=t.resolveTableSharding?.(v);if(I?.mode.kind==="global"){a.push({doc:y,line:f,table:v});return}const E=pa(y,v,I,n,f);if(!E.ok){o.push(E.error);return}const j=i.get(E.shardKey);j?j.rows.push({doc:y,table:v}):i.set(E.shardKey,{rows:[{doc:y,table:v}],shardKey:E.shardKey,startLine:f})};for(;;){const{done:k,value:w}=await h.read();if(k)break;if(w&&(T+=w.byteLength,T>dn))throw await h.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});b+=m.decode(w,{stream:!0});let g=b.indexOf(`
|
|
5
|
+
`);for(;g!==-1;){const y=b.slice(0,g);b=b.slice(g+1),S(y),g=b.indexOf(`
|
|
6
|
+
`)}}return b.length>0&&S(b),{errors:o,globalRows:a,perShard:i,received:d}},wa=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),$t=(e,t)=>{for(const[n,o]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+o;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},ga=async(e,t,n,o,a)=>{const i=t.defaultShardKey??"__root__",{errors:d,globalRows:f,perShard:h,received:m}=await ma(e,t,i),b={conflicts:0,errors:d,failed:[],inserted:{}},T=[];if(t.resolveTableSharding===void 0&&h.size>0&&T.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const S=await n.orchestrateImport(a,{batches:[...h.values()],headers:o});$t(b,S),b.failed.push(...wa(S.shards))}if(f.length>0)if(t.importGlobals){const S=f[0]?.line??1,k=await t.importGlobals({rows:f,startLine:S});$t(b,k)}else for(const S of f)b.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:S.line,message:`row targets global table "${S.table}" but no \`importGlobals\` is configured`,table:S.table});return{conflicts:b.conflicts,errors:b.errors,failed:b.failed,inserted:b.inserted,received:m,...T.length>0?{warnings:T}:{}}},ya=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),We=e=>typeof e=="object"&&e!==null?e:{},ze=e=>typeof e.kind=="string"?e.kind:"unknown",ba=(e,t)=>{let n=We(t),o=!1;ze(n)==="optional"&&(o=!0,n=We(n._meta?.inner));const a=ze(n),i=n._meta??{},d={kind:a,name:e,optional:o};if(a==="id"&&typeof i.tableName=="string"&&(d.table=i.tableName),a==="array"){const f=ze(We(i.inner));f!=="unknown"&&(d.element=f)}return d},_a=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>ba(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),Ra="/_lunora/admin/functions",Ea="/_lunora/admin/cron-jobs",Aa="/_lunora/admin/architecture",Ta="/_lunora/admin/openapi",Sa="/_lunora/admin/openrpc",Oa="/_lunora/admin/global/tables",va="/_lunora/admin/global/table",Ia="/_lunora/admin/global/facet",Kt=e=>{if(e===void 0||e==="")return;let t;try{t=Xe(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(o=>{if(typeof o!="object"||o===null||typeof o.column!="string")return[];const{column:a,value:i}=o;return[{column:a,value:i}]});return n.length===0?void 0:n},ka=Object.freeze({info:{description:'No OpenAPI spec is configured on this worker. Run `lunora codegen`, then wire the generated module to `createWorker`: `import { openApiSpec } from "./lunora/_generated/openapi"`.',title:"Lunora API",version:"0.0.0"},openapi:"3.1.0",paths:{}}),Pa=Object.freeze({info:{description:'No OpenRPC spec is configured on this worker. Run `lunora codegen --api-spec openrpc` (or `both`), then wire the generated module to `createWorker`: `import { openRpcSpec } from "./lunora/_generated/openrpc"`.',title:"Lunora RPC",version:"0.0.0"},methods:[],openrpc:"1.3.2"}),Da=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:a,requireAdminOption:i}=e,d=w=>{M(w,"GET","Functions");const g=i(w,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),y=Object.entries(g).flatMap(([v,I])=>I.visibility==="internal"||I.kind==="stream"?[]:[{args:_a(I.args),kind:I.kind,path:v}]).toSorted((v,I)=>v.path.localeCompare(I.path));return Response.json({functions:y},{headers:{"content-type":"application/json"},status:200})},f=w=>{M(w,"GET","Cron-jobs");const g=i(w,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),y=Object.entries(g).flatMap(([v,I])=>I.map(E=>({args:E.args,cron:v,functionPath:E.functionPath,name:E.name,shardKey:E.shardKey,workflow:E.workflow}))).toSorted((v,I)=>v.name.localeCompare(I.name));return Response.json({jobs:y},{headers:{"content-type":"application/json"},status:200})},h=w=>(M(w,"GET","Architecture"),t(w),Response.json(n.architecture??ya,{headers:{"content-type":"application/json"},status:200})),m=w=>(M(w,"GET","OpenAPI"),t(w),Response.json(n.openApiSpec??ka,{headers:{"content-type":"application/json"},status:200})),b=w=>(M(w,"GET","OpenRPC"),t(w),Response.json(n.openRpcSpec??Pa,{headers:{"content-type":"application/json"},status:200})),T=async w=>{M(w,"GET","Global-tables");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await g.listTables(),{headers:{"content-type":"application/json"},status:200})},S=async w=>{M(w,"GET","Global-table");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),y=new URL(w.url),v=a(y,"table");if(v===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const I=await g.readTablePage({...o(w),filters:Kt(a(y,"filters")),table:v});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},k=async w=>{M(w,"GET","Global-facet");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),y=new URL(w.url),v=a(y,"table"),I=a(y,"column");if(v===void 0||I===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const E=a(y,"limit"),j=E===void 0?void 0:Number(E),H=await g.facetColumn({column:I,filters:Kt(a(y,"filters")),limit:j!==void 0&&Number.isFinite(j)?j:void 0,table:v});return Response.json(H,{headers:{"content-type":"application/json"},status:200})};return{[Ea]:f,[Ra]:d,[Ia]:k,[va]:S,[Oa]:T,[Aa]:h,[Ta]:m,[Sa]:b}},Na="/_lunora/admin/kv/namespaces",Ua="/_lunora/admin/kv/keys",En="/_lunora/admin/kv/value",An=32*1048576,Ft=60,Ca=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=w=>n(w,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=w=>Response.json(w,{headers:{"content-type":"application/json"},status:200}),i=(w,g)=>{const y=new URL(w.url),v=y.searchParams.get("namespace")??"",I=y.searchParams.get("key")??"";if(v==="")throw new c(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(I==="")throw new c(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:I,namespace:v}},d=async(w,g)=>{if(!(await w.listNamespaces()).some(v=>v.binding===g))throw new c(`Unknown KV namespace binding \`${g}\``,{code:"NOT_FOUND",status:404})},f=async w=>(M(w,"GET","KV-namespaces"),a({namespaces:await o(w).listNamespaces()})),h=async w=>{M(w,"GET","KV-keys");const g=o(w),y=new URL(w.url),v=y.searchParams.get("namespace")??"";if(v==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const I=y.searchParams.get("prefix")??void 0,E=y.searchParams.get("cursor")??void 0,j=y.searchParams.get("limit"),H=j===null?void 0:Number.parseInt(j,10);if(H!==void 0&&(!Number.isInteger(H)||H<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const U=H===void 0?void 0:Math.min(H,1e3);return await d(g,v),a(await g.listKeys({cursor:E,limit:U,namespace:v,prefix:I}))},S={DELETE:async w=>{const g=o(w),y=i(w,"DELETE");return await d(g,y.namespace),await g.deleteKey(y),a({deleted:!0})},GET:async w=>{const g=o(w),y=i(w,"GET");return await d(g,y.namespace),a(await g.getValue(y))},PUT:async w=>{const g=o(w),y=await t(w,An);if(typeof y.namespace!="string"||y.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof y.key!="string"||y.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof y.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(y.expirationTtl!==void 0&&(typeof y.expirationTtl!="number"||!Number.isInteger(y.expirationTtl)||y.expirationTtl<Ft))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const v=Math.floor(Date.now()/1e3)+Ft;if(y.expiration!==void 0&&(typeof y.expiration!="number"||!Number.isInteger(y.expiration)||y.expiration<v))throw new c("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await d(g,y.namespace),await g.putValue({expiration:y.expiration,expirationTtl:y.expirationTtl,key:y.key,metadata:y.metadata,namespace:y.namespace,value:y.value}),a({ok:!0})}},k=w=>{const g=S[w.method];if(!g)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(w)};return{[Na]:f,[Ua]:h,[En]:k}},Ba="/_lunora/migrate",xa="/_lunora/admin/pitr",Ha="/_lunora/admin/rank",La="/_lunora/admin/rankpage",ja="/_lunora/admin/shard-registry/prune",Ma="/_lunora/admin/shard-traffic",$a=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Ka=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Fa=async e=>{const n=await ne(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!$a.has(n.functionPath))throw new c("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},Ga=async e=>{const n=await ne(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new c("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new c("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new c("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new c("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},Qa=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new c('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Wa=e=>{if(typeof e.table!="string"||e.table.length===0)throw new c("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new c("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new c("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new c("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new c("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},za=async e=>{const n=await ne(e,"Rank page")??{};Wa(n);const o=Qa(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:o,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},Va=async e=>{const n=await ne(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},Ja=async e=>{const n=await ne(e,"Shard-registry prune")??{};if(n.tables!==void 0&&!(Array.isArray(n.tables)&&n.tables.every(o=>typeof o=="string")))throw new c("Shard-registry prune `tables` must be an array of table names",{code:"BAD_REQUEST",status:400});return{dryRun:n.dryRun===!0,tables:n.tables}},Ya=async e=>{const n=await ee(e);if(typeof n.functionPath!="string"||!Ka.has(n.functionPath))throw new c("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new c("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},qa=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:a,resolveForwardContext:i,shardDO:d,shardedTables:f}=e,h=(g,y)=>{if(g.method!=="POST")throw new c(`${y} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(g))throw new c("Admin auth required",{code:"FORBIDDEN",status:403})},m=async(g,y)=>{h(g,"Migration");const v=await Fa(g),{headers:I}=await i(g,y),E=await a.orchestrateMigration(d,{args:v.args,defaultShardKey:t,functionPath:v.functionPath,headers:I,table:v.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},b=async(g,y)=>{h(g,"Rank");const v=await Ga(g),{headers:I}=await i(g,y),E=await a.orchestrateRank(d,{headers:I,index:v.index,partitionKey:v.partitionKey,rowId:v.rowId,sortValues:v.sortValues,table:v.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},T=async(g,y)=>{h(g,"Rank page");const v=await za(g),{headers:I}=await i(g,y),E=await a.orchestrateRankPage(d,{...v,headers:I});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},S=async(g,y)=>{h(g,"Shard-traffic");const v=await Va(g),{headers:I}=await i(g,y),E=await a.orchestrateShardTraffic(d,{headers:I,table:v.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},k=async(g,y)=>{h(g,"Shard-registry prune");const v=await Ja(g),I=f(),E=(v.tables??[]).filter(U=>!I.includes(U));if(E.length>0)throw new c(`Shard-registry prune names tables that are not \`.shardBy()\`: ${E.join(", ")}`,{code:"BAD_REQUEST",status:400});const{headers:j}=await i(g,y),H=await Xr(a.registry,d,{dryRun:v.dryRun,headers:j,tables:v.tables??I});return Response.json(H,{status:H.failed.length>0?207:200})},w=async(g,y)=>{if(M(g,"POST","PITR"),!o(g))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const v=await Ya(g),{headers:I}=await i(g,y),E=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:v.args,functionPath:v.functionPath}),headers:I,method:"POST"});return n(d,v.shardKey??t,E)};return{[Ba]:m,[xa]:w,[Ha]:b,[La]:T,[ja]:k,[Ma]:S}},Xa=1,Za=0,es=32,ts=512,ns=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,rs=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>ts)return;const n=t.split(",");if(!(n.length>es)){for(const o of n)if(!ns.test(o.trim()))return;return t}},os=e=>{const t=Sr(e.headers.get("traceparent"));if(t===void 0)return;const n=rs(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},Gt=(e,t={})=>{const n=os(e),o=t.trustInbound===!0?n:void 0,a=ge(8),i=o?.traceId??ge(16),d=Pr(t.sampling,o===void 0?a:i),{rayId:f}=t,h=d.isTraced&&(o===void 0||o.sampled);return{decision:d,ignoredUpstream:n!==void 0&&o===void 0,trace:{sampled:h,spanId:a,traceFlags:h?Xa:Za,traceId:i,...o?.parentSpanId===void 0?{}:{parentSpanId:o.parentSpanId},...o?.traceState===void 0?{}:{traceState:o.traceState},...f===void 0?{}:{rayId:f}}}},Qt=(e,t)=>{t.traceparent=cn(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState),e.rayId!==void 0&&(t[yo]=e.rayId)},as=(e,t)=>{let n;return()=>{if(n===void 0){const o=kr(e),a=t===void 0?void 0:t.cf;n=Or(Ir(o),vr(o,a))}return n}},ss="/_lunora/admin/scheduled",is="/_lunora/admin/scheduled/status",cs="/_lunora/admin/scheduled/ws",ds="/_lunora/admin/scheduled/cancel",us="/_lunora/admin/scheduled/dead",ls="/_lunora/admin/scheduled/dead/retry",hs="/_lunora/admin/scheduled/dead/cancel",fs="/_lunora/admin/scheduled/pool/release",ps=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:a}=e,i=(m,b)=>T=>{if(T.method!=="GET")throw new c(`${b} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const S=new URL(T.url).searchParams.get("cursor"),k=S===null||S===""?"":`?cursor=${encodeURIComponent(S)}`;return o(T).fetch(new Request(`https://scheduler.internal${m}${k}`,{method:"GET"}))},d=(m,b,T=b)=>async S=>{if(S.method!=="POST")throw new c(`${T} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const k=o(S),w=await ne(S,b);if(typeof w?.id!="string"||w.id==="")throw new c(`${b} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return k.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))},f=async m=>{if(m.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const b=o(m),T=await ne(m,"Scheduled pool-release");if(typeof T?.pool!="string"||T.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const S=typeof T.id=="string"&&T.id!==""?T.id:void 0;return b.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(S===void 0?{pool:T.pool}:{id:S,pool:T.pool}),headers:{"content-type":"application/json"},method:"POST"}))},h=async m=>{if(m.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(m))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const b=n();return ye(b,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ds]:d("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[hs]:d("/dead/cancel","Scheduled dead-letter action"),[us]:i("/dead","Scheduled dead-letter"),[ls]:d("/dead/retry","Scheduled dead-letter action"),[ss]:i("/list","Scheduled-list"),[fs]:f,[is]:i("/status","Scheduler-status"),[cs]:h}},ms="/_lunora/scheduled",Tn="/_lunora/queue",Sn=16*1048576,ws=e=>{const{assertAdmin:t,dispatchScheduled:n,queueHandler:o}=e,a=async(d,f,h)=>{if(t(d),d.method!=="POST")throw new c("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const m=await ne(d,"Scheduled tick"),b=typeof m?.cron=="string"?m.cron:"";if(b==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:b,noRetry:()=>{},scheduledTime:Date.now()},f,h),Response.json({cron:b,ok:!0})},i=async(d,f,h)=>{if(t(d),d.method!=="POST")throw new c("queue dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!o)throw new c("no queueHandler configured",{code:"BAD_REQUEST",status:400});const m=await ne(d,"Queue dispatch",Sn);if(!Array.isArray(m?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const b=typeof m.queue=="string"?m.queue:"",T=m.messages.filter(k=>typeof k=="object"&&k!==null&&typeof k.id=="string").map(k=>({body:k.body,id:k.id})),S=await o({messages:T,queue:b},f,h);return Response.json({retry:S?.retry??[]})};return{[Tn]:i,[ms]:a}},gs=(e,...t)=>{let n=e.cf;for(const o of t){if(typeof n!="object"||n===null)return;n=n[o]}return typeof n=="string"?n:void 0},nt={mtls:e=>gs(e,"tlsClientAuth","certVerified")==="SUCCESS"},ys=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(nt,e)?nt[e]:void 0)??(()=>!1),bs=e=>typeof e=="string"&&Object.hasOwn(nt,e),_s=e=>{const t=bs(e)?e:void 0;if(e!==void 0&&t===void 0)return()=>{};let n=!1;return o=>{n||t!==void 0&&o.cf!==void 0||(n=!0,console.warn(t===void 0?'[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.':`[lunora] \`trustInboundTraceContext: "${t}"\` cannot be satisfied on this host: the request carries no platform-injected \`cf\` metadata, which is what that signal reads, so every inbound \`traceparent\` is ignored and this request starts a new trace. Off Cloudflare, trust the upstream some other way — \`trustInboundTraceContext: true\` when nothing untrusted can reach this worker, or a predicate that verifies whatever your own front door sets. Set it to \`false\` to keep this behaviour and silence this message.`))}},Rs="/_lunora/admin/vector/indexes",Es="/_lunora/admin/vector/query",As=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=async i=>{M(i,"GET","Vector-indexes");const d=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await d.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async i=>{M(i,"POST","Vector-query");const d=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(d.queryIndex===void 0)throw new c("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const h=await t(i);if(typeof h.name!="string"||h.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof h.text!="string"||h.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(h.topK!==void 0&&(typeof h.topK!="number"||!Number.isInteger(h.topK)||h.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const m=await d.queryIndex({name:h.name,text:h.text,topK:h.topK});return Response.json(m,{headers:{"content-type":"application/json"},status:200})};return{[Rs]:o,[Es]:a}},Ts="/_lunora/admin/workflows/instances",Ss="/_lunora/admin/workflows/instance",Os="/_lunora/admin/workflows/status",vs={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Is=e=>e!==null&&Object.hasOwn(vs,e)?e:void 0,Wt=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const o=Number(n);return Number.isInteger(o)&&o>0?o:void 0},Ve=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new c(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},zt=()=>{throw new c("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},ks=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,o=async(d,f,h)=>{M(d,"GET","Workflows instances"),t(d);const m=n(f);if(!m)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const b=Ve(h,"name"),T=Is(h.searchParams.get("status"));return Response.json(await m.listInstances({page:Wt(h,"page"),perPage:Wt(h,"perPage"),status:T,workflowName:b}))},a=async(d,f,h)=>{M(d,"GET","Workflows instance"),t(d);const m=n(f);return m?Response.json(await m.getInstance({instanceId:Ve(h,"id"),workflowName:Ve(h,"name")})):zt()},i=async(d,f)=>{M(d,"POST","Workflows status"),t(d);const h=n(f);if(!h)return zt();const m=await ne(d,"Workflows status");if(typeof m?.name!="string"||m.name===""||typeof m.id!="string"||m.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:b}=m;if(b!=="pause"&&b!=="resume"&&b!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await h.setInstanceStatus({action:b,instanceId:m.id,workflowName:m.name}))};return{[Ss]:a,[Ts]:o,[Os]:i}},Ps={[En]:An,[Tn]:Sn,[Kr]:$r},Vt="/_lunora/rpc",Ds="/_lunora/rpc-batch",Ns="/_lunora/ws",Se=(e,t,n)=>({resourceAttributes:as(e,t),...n===void 0?{}:{waitUntil:n}}),Je=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Jt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ye=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0,o=_o(e.headers.get(go)),a=o===void 0?{}:{rayId:o};let i;try{i=new URL(e.url)}catch{return{method:t,...a,userAgent:n}}const d=i.port===""?void 0:Number(i.port);return{host:i.hostname,method:t,path:i.pathname,port:Number.isNaN(d)?void 0:d,...a,scheme:i.protocol.replace(":",""),userAgent:n}},Yt="/_lunora/voice/",Us="/_lunora/scheduler/dispatch",Cs="/_lunora/admin/cron-jobs/run",Bs="/_lunora/admin/ws-token",xs="/_lunora/admin/",xe="/_lunora/",Hs="/_lunora/migrate",Ls="/_lunora/status",js=e=>e.startsWith(xs)||e===Hs,Ms="__lunora_relation__:",De=e=>{if(e.startsWith(Ms))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Ne=async e=>await e===!0,qt=(e,t)=>{const n=e.headers.get(bt);if(n===null)return;const o=Tr(n);if(o===void 0)throw new c(`malformed ${bt} header`,{code:"BAD_REQUEST",status:400});if(o.subject!==(t?.userId??null))throw new c("the session changed since this write was queued",{code:"IDENTITY_MISMATCH",status:409})},$s=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},Xt="/api/auth",Ks="__lunora_admin__:recordAuthEvent",Zt="__lunora_admin__:listPushSubscriptions",Fs=["/sign-in","/sign-up","/callback"],Gs=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return Fs.some(a=>o===a||o.startsWith(`${a}/`))},en=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},Ue=(e,t,n,o)=>{const a=wr(n),i=a?n.code:"INTERNAL_SERVER_ERROR",d=a?n.status:500,{message:f,name:h,stack:m}=lo(n);return{durationMs:t,error:{code:i,message:f,name:h,status:d,...m===void 0?{}:{stack:m}},functionPath:e,ok:!1,...o.fanOut?{fanOut:{failed:0,shards:0,table:o.fanOut.table}}:{},...o.shardKey?{shardKey:o.shardKey}:{}}},On=e=>{const{exp:t,expiresAtMs:n}=e;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},vn=({identity:e})=>e!==null&&Rr(On(e)),Qs=e=>{if(vn(e))throw new c("authentication token expired",{code:"TOKEN_EXPIRED",status:401});return e},Ws=e=>{if(!vn(e))return e;const t={...e.headers};return delete t["x-lunora-identity"],delete t["x-lunora-identity-exp"],delete t["x-lunora-userid"],{claims:null,headers:t,identity:null,userId:null}},tn=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,zs=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},rt=new WeakMap,Vs=async(e,t,n,o,a=rt.get(e))=>{const i={"content-type":"application/json"},d=e.headers.get("authorization"),f=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),m=e.headers.get("x-lunora-mutation-id"),b=e.headers.get("x-lunora-client-id"),T=e.headers.get("x-lunora-client-seq"),S=e.headers.get("x-lunora-base-seq");d&&(i.authorization=d),f&&(i.cookie=f),h&&(i["x-d1-bookmark"]=h),m&&(i["x-lunora-mutation-id"]=m),b&&(i["x-lunora-client-id"]=b),T&&(i["x-lunora-client-seq"]=T),S&&(i["x-lunora-base-seq"]=S);const k=Br(e.headers,o);if(k&&(i["x-lunora-client-ip"]=k),i["x-lunora-origin"]=new URL(e.url).origin,!n)return{claims:null,headers:i,identity:null,userId:null};const w=await n(e,t,a);if(!w||typeof w.userId!="string"||w.userId.length===0)return{claims:null,headers:i,identity:null,userId:null};i["x-lunora-userid"]=Er(w.userId);const g=On(w);g!==void 0&&(i["x-lunora-identity-exp"]=String(g));const{userId:y,...v}=w,I=Object.keys(v).length>0?v:null;return I&&(i["x-lunora-identity"]=Ar(I)),{claims:I,headers:i,identity:w,userId:y}},Js=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Ys=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new c("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new c("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new c("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!Js.has(n.kind))throw new c("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new c("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new c("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},qs=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},qe=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new c("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new c(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},Xs=async e=>{const t=await ln(e);let n;try{n=JSON.parse(t)}catch{throw new c("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new c("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const o=n;if(o.args!==void 0&&un(o.args,"RPC"),o.shardKey!==void 0&&typeof o.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,i=Ys(a.fanOut),d=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const f=d.table;if(typeof f=="string"&&f!==i.table)throw new c("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});d.table=i.table}return{args:d,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},Ce=new Map,Zs=5e3,ei=4096,ti=async(e,t)=>{const n=Date.now(),o=Ce.get(t);if(o!==void 0&&o.expiresMs>n)return o.relayCount;o!==void 0&&Ce.delete(t);let a=0;try{const i=await ye(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const f=(await i.json()).relayCount;typeof f=="number"&&f>0&&(a=Math.floor(f))}}catch{a=0}return sn(Ce,ei),Ce.set(t,{expiresMs:n+Zs,relayCount:a}),a},nn=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},Be=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),ni=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],ri=(e,t)=>{for(const n of ni){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},rn=(e,t)=>{const n=new Headers(e.headers),o=[...n.keys()];for(const a of o)a.startsWith("x-lunora-")&&n.delete(a);return ri(n,t),n},oi=async(e,t,n)=>e.length===0||n.length===0?!1:st(await mn(e,t),n),on=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[o,...a]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:st(t,a.join(" ").trim())},an=async(e,t,n)=>{if(!t||t.length===0)return!1;const o=new URL(e.url).searchParams.get("token");return o===null?!1:await xo(t,o)?!0:n?!1:st(t,o)},ai=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return Jr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return $e(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return $e(`queue:${e}`,!0);if(typeof n.connectionString=="string")return $e(`hyperdrive:${e}`,!0)},si=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(xe))throw new c(`route "${t}" is under the reserved ${xe} prefix, which the framework owns. App routes registered there shadow the internal endpoint AND its admin gate — pick a path outside the prefix.`,{code:"MISCONFIGURED",status:500})},ii=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new c("`x402Charge` requires `functions`: paid (.x402) procedures are read from the function registry, so without it every paid procedure would dispatch FREE. Build the worker with `defineApp()` (which supplies the registry) or pass `functions` explicitly.",{code:"MISCONFIGURED",status:500})},In=e=>{ii(e);const t=ys(e.trustInboundTraceContext),n=_s(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",a=e.queryCoordinator??Zr({registry:eo(e.resolveTableSharding,o)}),i=Yr(e.resolveIdentity,e.identity),d=Ke(e.shardDO,e.jurisdiction),f=e.schedulerDO===void 0?void 0:Ke(e.schedulerDO,e.jurisdiction),h=e.voiceAgents===void 0?void 0:Object.fromEntries(Object.entries(e.voiceAgents).map(([r,s])=>[r,Ke(s,e.jurisdiction)]));let m=!1;const b=r=>{if(r===void 0||e.jurisdiction===void 0)return r;m||(m=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},T=async(r,s,l,u=e.shardRegion?.(s))=>ye(r,s,b(u)).fetch(l);let S;const k=()=>e.adminToken??S;let w;const g=()=>e.requireEphemeralWsToken??w??!0;let y;const v=r=>{const s=r??{};if(y??=nn(r,e.shardDO),w===void 0&&e.requireEphemeralWsToken===void 0){const u=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof u=="string"&&u.length>0&&(w=Uo(u,!0))}if(S!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(S=l)},I=new WeakSet,E=r=>on(r,k())||I.has(r),j=async r=>{if(!(e.adminGate===void 0||I.has(r)))try{await Ne(e.adminGate(r,rt.get(r)))&&I.add(r)}catch{}},H=async(r,s,l,u)=>{const p=await Vs(r,s,l,e.trustedClientIpHeader,u);return e.functions!==void 0&&(p.headers[Rt]=_t),p},U=async(r,s,l,u)=>Qs(await H(r,s,l,u)),K=async(r,s)=>{const l=await H(r,s,e.resolveIdentity);if(I.has(r)&&l.headers.authorization===void 0){const u=k();u!==void 0&&(l.headers.authorization=`Bearer ${u}`)}return l};let W=!1,Y=!1;const q=()=>{Y||(Y=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},G=r=>{if(!e.allowUnauthenticatedShardAccess){const s=r==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${r} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${r} access (relying solely on per-row RLS).`,{code:r==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}W||(W=!0,console.warn([`[lunora] SECURITY: serving ${r} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},re=async(r,s,l=!1)=>{if(s.includes(Ze)||s.includes(et))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(!l)if(e.authorizeShard){if(!await Ne(e.authorizeShard({identity:r,shardKey:s})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==o&&G("shard")},Q=qa({defaultShard:o,forwardToShard:T,isAdmin:E,queryCoordinator:a,resolveForwardContext:K,shardDO:d,shardedTables:()=>(e.listSchemaTables?.()??[]).filter(r=>e.resolveTableSharding?.(r)?.mode.kind==="shardBy")}),ue=async(r,s,l,u,p,R)=>{De(r);const O={"content-type":"application/json",[Rt]:_t,"x-lunora-system":"1"};return p?.userId!==void 0&&p.userId.length>0&&(O["x-lunora-userid"]=p.userId),p?.identity!==void 0&&p.identity.length>0&&(O["x-lunora-identity"]=p.identity),u!==void 0&&u.length>0&&(O["x-lunora-mutation-id"]=u),R!==void 0&&R.length>0&&(O.traceparent=R),T(d,l,Be(r,s,O))},oe=async(r,s,l,u,p)=>{const R=Po(l.env,l.context?.exports,r,["create"]);if(R===void 0)throw new c(`${u} targets workflow "${r}", which is on neither ctx.exports nor env`,{code:"CRON_JOB_FAILED",status:500});if(oo(s))throw new c(`${u} params ${ao}`,{code:"BAD_REQUEST",status:400});try{await R.create(p===void 0?{params:s}:{id:p,params:s})}catch(O){if(!co(O))throw O}},be=async(r,s,l,u)=>{if(r.workflow){await oe(r.workflow,r.args??{},{context:l,env:s},`cron job "${r.name}"`);return}if(r.functionPath===void 0)throw new c(`cron job "${r.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const p=await ue(r.functionPath,r.args??{},r.shardKey??o,void 0,void 0,u);if(!p.ok)throw new c(`cron job "${r.name}" (${r.functionPath}) failed with shard status ${String(p.status)}`,{code:"CRON_JOB_FAILED",status:500})},z=r=>{if(!E(r))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},ae=(r,s,l)=>{if(z(r),s===void 0)throw new c(l.message,{code:l.code,status:400});return s},se=async(r,s,l,u,p,R)=>{const O=e.cronJobs?.[r];if(!O)return 0;for(const P of O)try{await be(P,s,l,R)}catch(D){u.push(p(D))}return O.length},kn=async(r,s,l)=>{if(z(r),M(r,"POST","cron-jobs run"),!e.cronJobs)throw new c("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const u=await ee(r),p=typeof u.name=="string"?u.name:"";if(p==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const R=Object.values(e.cronJobs).flat().find(O=>O.name===p);if(!R)throw new c(`no cron job named "${p}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await be(R,s,l),Response.json({name:p,ran:!0},{status:200})},dt=async r=>{const s=typeof r.pool=="string"&&r.pool.length>0?r.pool:void 0;if(!s||!f||typeof r.id!="string")return;const l=typeof r.instanceName=="string"&&r.instanceName.length>0?r.instanceName:"default";try{await ye(f,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:r.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Pn=async(r,s,l)=>{M(r,"POST","Scheduler dispatch");const u=await ln(r),p=s??{},R=typeof p.LUNORA_SCHEDULER_SECRET=="string"?p.LUNORA_SCHEDULER_SECRET:void 0,O=e.adminToken??(typeof p.LUNORA_ADMIN_TOKEN=="string"?p.LUNORA_ADMIN_TOKEN:void 0),P=r.headers.get("x-lunora-scheduler-signature");let D=!1;if(P&&R?D=await oi(R,u,P):O&&(D=on(r,O)),!D)throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let A;try{A=JSON.parse(u)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const _=A??{},B=_.args??{},L=typeof _.id=="string"&&_.id.length>0?_.id:void 0;if(typeof _.workflow=="string"&&_.workflow.length>0)return await oe(_.workflow,B,{context:l,env:s},"scheduled workflow",L),await dt(_),Response.json({ok:!0},{status:200});if(typeof _.functionPath!="string"||_.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const V=typeof _.shardKey=="string"&&_.shardKey.length>0?_.shardKey:o,x=$s(r),ce=await ue(_.functionPath,B,V,L,x,r.headers.get("traceparent")??void 0);return await dt(_),ce},Dn=Mo({assertAdmin:z,getReader:()=>e.authAuditReader}),Nn=$o({assertAdmin:z,getMove:()=>e.authJurisdictionMove}),Un=async(r,s)=>{z(r);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:Oe({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const u=s?.kind,p=s?.userId,R=s?.limit,O=u==="fcm"||u==="web-push"?u:void 0,P=typeof p=="string"&&p!==""?p:void 0,D=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,A=D>0?Math.min(D,1e3):1e3,B=(await l.list({kind:O,limit:A,userId:P})).filter(L=>O!==void 0&&L.kind!==O?!1:P===void 0||(L.userId??null)===P).map(({keys:L,token:V,...x})=>x);return Response.json({result:Oe({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},Cn=async(r,s)=>{if(!s.fanOut&&!(s.functionPath!==Ct&&s.functionPath!==Zt&&s.functionPath!==tt&&s.functionPath!==yn))return await j(r),s.functionPath===Ct?Dn(r,s.args??{}):s.functionPath===Zt?Un(r,s.args):Nn(r,s.functionPath,s.args??{})},Bn=ha({applyGlobals:e.applyGlobals,assertAdmin:z,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:o,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:a,resolveForwardContext:K,shardDO:d,prepareExportRows:async(r,s)=>bn(e,a,r,s,d),streamingImport:(r,s)=>ga(r,e,a,s,d),syncGlobals:e.syncGlobals}),He=(r,s)=>{const l=r.searchParams.get(s);return l===null||l===""?void 0:l},Le=r=>{const s=new URL(r.url),l=s.searchParams.get("limit"),u=s.searchParams.get("offset"),p=l===null?void 0:Number.parseInt(l,10),R=u===null?void 0:Number.parseInt(u,10);return{limit:p!==void 0&&Number.isFinite(p)&&p>=0?p:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},ut=()=>{if(f===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return f},xn=ps({checkWsAdmin:async r=>E(r)||an(r,k(),g()),requireSchedulerNamespace:ut,resolveSchedulerStub:r=>(z(r),ye(ut(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Hn=ks({assertAdmin:z,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Ln=Mr({assertAdmin:z,parsePaging:Le,queryParameter:He,readBodyBytes:Ur,requireAdminOption:ae,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),jn=ta({options:e,readJsonBody:ee,requireAdminOption:ae}),Mn=As({readJsonBody:ee,requireAdminOption:ae,vectorIntrospector:e.vectorIntrospector}),$n=Ca({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:ae}),Kn=qr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:ae}),Fn=Da({assertAdmin:z,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,architecture:e.architecture,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Le,queryParameter:He,requireAdminOption:ae}),Gn=r=>{const s=[],l=d??r?.SHARD;if(l!==void 0&&s.push(Vr("durable-object:default",l,o)),e.health?.disableBindingProbes!==!0)for(const[u,p]of Object.entries(r??{})){const R=ai(u,p);R!==void 0&&s.push(R)}for(const u of e.health?.probes??[])s.push(u);return s},Qn=zr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:E,resolveProbes:Gn}),Wn=r=>{const s=A=>"args"in A?{...A,args:Xe(A.args)}:A,l=e.schedulerInstanceName??"default",u=()=>ye(r,l),p=async(A,_)=>{const B=await u().fetch(new Request(`https://scheduler.internal${A}`,_));if(!B.ok)throw new c(`ctx.scheduler: SchedulerDO ${A} failed (${String(B.status)}): ${await B.text()}`,{code:"INTERNAL",status:500});return await B.json()},R=async(A,_)=>await p(A,{body:JSON.stringify(_),headers:{"content-type":"application/json"},method:"POST"}),O=A=>{const _=A;if(_==null)throw new c("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof _.binding=="string"&&_.binding.length>0)return{workflow:_.binding};if(typeof _.__lunoraRef=="string")return{functionPath:_.__lunoraRef};throw new c("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},P=async()=>(await so(async _=>p(_===void 0?"/list":`/list?cursor=${encodeURIComponent(_)}`,{method:"GET"}))).map(_=>s(_)),D=async(A,_,B={})=>{const L=O(_),{id:V}=await R("/schedule",{args:Dr("ctx.scheduler",String(L.functionPath??L.workflow),B),scheduledFor:Math.ceil(A),...L});return V};return{cancel:async A=>await R("/cancel",{id:A}),get:async A=>{const _=await p(`/get?id=${encodeURIComponent(A)}`,{method:"GET"});return _.record===void 0?null:s(_.record)},list:P,runAfter:async(A,_,B)=>{if(!Number.isFinite(A)||A<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await D(Date.now()+A,_,B)},runAt:async(A,_,B)=>{if(!Number.isFinite(A))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await D(A,_,B)}}},zn=async(r,s,l)=>{const{claims:u,headers:p,userId:R}=Ws(await H(r,s,i)),O=Se(s,r,A=>l.waitUntil?.(A)),P=A=>async(_,B={})=>{const L=_.__lunoraRef;if(typeof L!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});De(L);const V=await Ie(r,L,Oe(B),A,{...p,"x-lunora-system":"1"},O),x=await V.json();if(x.error)throw new c(x.error.message??"shard RPC failed",{code:x.error.code??"INTERNAL",status:V.status});return Xe(x.result)},D=P(o);return{auth:{getIdentity:()=>Promise.resolve(u),userId:R},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),forShard:A=>{const _=P(A);return{runAction:_,runMutation:_,runQuery:_}},runAction:D,runMutation:D,runQuery:D,...f===void 0?{}:{scheduler:Wn(f)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:ro(e.storage(s,new URL(r.url).origin))}}},Vn=async(r,s,l)=>{if(!e.httpRouter)return;const u=await zn(r,s,l);try{return await e.httpRouter.fetch(r,{...s,__lunoraCtx:u},l)}catch(p){return console.error("[lunora] httpRouter (SSR) handler threw:",p),new Response("Internal Server Error",{status:500})}},Jn=async(r,s,l)=>{if(r.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const u=vt(r,ie);if(u)return u;const p=l.searchParams.get("shard")??o,{headers:R,identity:O}=await H(r,s,i),P=E(r)||await an(r,k(),g());await re(O,p,P);const D=rn(r,R),A=nn(s,e.shardDO);if(A!==void 0){D.set("x-lunora-shard-binding",A);const _=await ti(d,p);if(_>0){const B=Oo(p,Math.floor(Math.random()*_));return T(d,B,new Request(r,{headers:D}),Dt(r))}}return T(d,p,new Request(r,{headers:D}))},Yn=async(r,s,l)=>{if(h===void 0)return new Response("Not found",{status:404});if(r.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const u=vt(r,ie);if(u)return u;let p;try{p=decodeURIComponent(l.pathname.slice(Yt.length))}catch{return new Response("Unknown voice agent",{status:404})}const R=Object.hasOwn(h,p)?h[p]:void 0;if(R===void 0)return new Response("Unknown voice agent",{status:404});const O=l.searchParams.get("threadKey");if(O===null||O.length===0)return new Response("Missing threadKey",{status:400});const{headers:P,identity:D}=await H(r,s,i);if(e.authorizeShard){if(!await Ne(e.authorizeShard({identity:D,shardKey:O})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else G("shard");const A=rn(r,P);return T(R,O,new Request(r,{headers:A}))},qn=async(r,s,l)=>{if(e.authorizeFanOut){if(!await Ne(e.authorizeFanOut(l,r.table,s)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new c("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});G("fan-out")},ve=async(r,s)=>{if(!(!r.fanOut&&r.functionPath.startsWith("__lunora_admin__:"))){if(r.fanOut){await qn(r.fanOut,r.functionPath,s);return}await re(s,r.shardKey??o)}},Xn=(r,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){q();return}if(e.functions[s]?.kind!=="query"||l.includes(et)||l.includes(Ze))return;const u=Dt(r);return u===void 0?void 0:{name:vo(l,u),region:u}},Zn=async(r,s,l,u,p)=>{const R=Xn(r,s,u);if(R!==void 0){const O={...p,"x-lunora-replica-read":"1",...y===void 0?{}:{"x-lunora-shard-binding":y}},P=Io(r.headers.get("x-lunora-min-seq"));P!==void 0&&(O["x-lunora-min-seq"]=String(P));const D=await T(d,R.name,Be(s,l,O),R.region);if(D.status!==421)return D}return T(d,u,Be(s,l,p))},Ie=async(r,s,l,u,p,R)=>{const O=Date.now(),{observability:P,sampling:D}=e,A=Ye(r),{decision:_,ignoredUpstream:B,trace:L}=Gt(r,{...A.rayId===void 0?{}:{rayId:A.rayId},...D===void 0?{}:{sampling:D},trustInbound:t(r)});B&&n(r);const V={...p,[At]:_.keepErrors?"1":"0",[It]:"1"};Qt(L,V);try{const x=await Zn(r,s,l,u,V),ce=Pt(x.headers.get(kt));de(P,{...A,...Jt(L),durationMs:Date.now()-O,functionPath:s,ok:x.ok,shardKey:u,...x.ok?{}:{error:{...ce,code:ce?.code??"SHARD_ERROR",message:ce?.message??`shard returned ${String(x.status)}`,status:x.status}}},R,void 0,{isTraced:L.sampled,keepErrors:_.keepErrors});const _e=new Response(x.body,{headers:x.headers,status:x.status,statusText:x.statusText});return _e.headers.set("x-lunora-shard-key",u),_e.headers.delete(kt),_e}catch(x){throw de(P,{...A,...Jt(L),...Ue(s,Date.now()-O,x,{shardKey:u})},R,void 0,{isTraced:L.sampled,keepErrors:_.keepErrors}),x}},er=r=>{if(r.fanOut&&r.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});r.fanOut||De(r.functionPath)},tr=async(r,s,l)=>{M(r,"POST","RPC");const u=await Xs(r);qs(s,u),er(u);const p=await Cn(r,u);if(p!==void 0)return p;const{headers:R,identity:O}=await U(r,s,i);qt(r,O),await ve(u,O);const P=qe(u,e);{const D=Date.now(),{observability:A}=e,_=Ye(r),B=Se(s,r,l&&(x=>l.waitUntil?.(x)));if(u.fanOut)try{const x=await a.fanOut(d,{args:u.args??{},fanOut:u.fanOut,functionPath:u.functionPath,headers:R});return de(A,{durationMs:Date.now()-D,fanOut:{failed:x.failed,shards:x.ok+x.failed,table:u.fanOut.table},functionPath:u.functionPath,..._,ok:!0},B),Response.json(x,{headers:{"content-type":"application/json"},status:200})}catch(x){throw de(A,{...Ue(u.functionPath,Date.now()-D,x,{fanOut:{table:u.fanOut.table}}),..._},B),x}const L=u.shardKey??o,V=()=>Ie(r,u.functionPath,u.args??{},L,R,B);return P&&e.x402Charge?e.x402Charge(r,{functionPath:u.functionPath,price:P.price},V,Je(l)):V()}},nr=async(r,s,l)=>{M(r,"POST","RPC batch");const u=await ee(r),{calls:p}=u;if(!Array.isArray(p))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:O}=await U(r,s,i);qt(r,O);const P=ra(p,o);for(const $ of P.values())for(const F of $)if(e.functions?.[F.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${F.functionPath}" cannot be called in a batch; dispatch it individually over ${Vt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...P.entries()].flatMap(([$,F])=>F.map(X=>ve({args:X.args,functionPath:X.functionPath,shardKey:$},O))));const{observability:D,sampling:A}=e,_=Se(s,r,l&&($=>l.waitUntil?.($))),B=Ye(r),{decision:L,ignoredUpstream:V,trace:x}=Gt(r,{...B.rayId===void 0?{}:{rayId:B.rayId},...A===void 0?{}:{sampling:A},trustInbound:t(r)});V&&n(r);const ce={isTraced:x.sampled,keepErrors:L.keepErrors},_e=$=>{const F={...R,"content-type":"application/json",[At]:L.keepErrors?"1":"0",[It]:"1"};return Qt({...x,spanId:$},F),F},je=$=>({parentSpanId:$,spanId:ge(8),traceFlags:x.traceFlags,traceId:x.traceId}),Pe=[],Me=[],pt=($,F,X,le)=>({body:{error:{code:X,message:le}},id:$.id,status:F}),mt=($,F,X,le,me)=>{for(const Z of $)de(D,me(Z),_,void 0,ce),Pe.push(pt(Z,F,X,le))},pr=($,F,X,le,me,Z)=>{for(const Re of $){const Ee=me.get(Re.id),he=Ee?.status??Z,fe=he<400,Ae=fe?void 0:Pt(Ee?.errorDetail);de(D,{durationMs:le,functionPath:Re.functionPath,...B,...je(X),ok:fe,shardKey:F,...fe?{}:{error:{...Ae,code:Ae?.code??"SHARD_ERROR",message:Ae?.message??`batched call returned ${String(he)}`,status:he}}},_,void 0,ce)}};await Promise.all([...P.entries()].map(async([$,F])=>{const X=ge(8),le=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:F}),headers:new Headers(_e(X)),method:"POST"}),me=Date.now();let Z;try{Z=await T(d,$,le)}catch(J){const Te=Date.now()-me,{body:yt}=gr(J,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});mt(F,502,yt.code,yt.message,mr=>({...Ue(mr.functionPath,Te,J,{shardKey:$}),...B,...je(X)}));return}const Re=Date.now()-me,Ee=Z.headers.get("x-d1-bookmark");Ee&&Me.push(Ee);let he;try{he=await Z.json()}catch{const J=`shard batch returned a non-JSON response (${String(Z.status)})`;mt(F,Z.status,"SHARD_ERROR",J,Te=>({durationMs:Re,error:{code:"SHARD_ERROR",message:J,status:Z.status},functionPath:Te.functionPath,...B,...je(X),ok:!1,shardKey:$}));return}const fe=Array.isArray(he.results)?he.results:[],Ae=new Set(fe.map(J=>J.id));pr(F,$,X,Re,new Map(fe.map(J=>[J.id,J])),Z.status),Pe.push(...fe.map(({errorDetail:J,...Te})=>Te));for(const J of F)Ae.has(J.id)||Pe.push(pt(J,Z.status,"SHARD_ERROR",`shard batch omitted result for call ${String(J.id)}`))}));const wt={"content-type":"application/json"},[gt]=Me;return Me.length===1&>!==void 0&&(wt["x-d1-bookmark"]=gt),Response.json({results:Pe},{headers:wt,status:200})},rr=async(r,s,l,u={},p={})=>{try{const R=l.__lunoraRef;if(typeof R!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});De(R);const{headers:O,identity:P}=await U(r,s,i,p.context),D={args:u,functionPath:R,shardKey:p.shardKey};await ve(D,P);const A=p.shardKey??o,_=Se(s,r,p.waitUntil),B=()=>Ie(r,R,u,A,O,_),L=qe(D,e);return L&&e.x402Charge?await e.x402Charge(r,{functionPath:R,price:L.price},B,Je(p.waitUntil?{waitUntil:p.waitUntil}:p.context)):await B()}catch(R){return Tt(R)}},lt=async(r,s,l)=>{const{observability:u}=e,p=Date.now(),R=ge(16),O=ge(8),P=tn(s),D=cn(R,O,!0);try{const A=await l(D);return de(u,{durationMs:Date.now()-p,functionPath:r,ok:!0,spanId:O,traceId:R},P),A}catch(A){throw de(u,{...Ue(r,Date.now()-p,A,{}),spanId:O,traceId:R},P),A}finally{Et(u,P)}},ht=async(r,s,l,u)=>{v(s);const p=[],R=_=>_ instanceof Error?_:new Error(String(_)),O=e.crons?.[r.cron];if(O)try{await O(r,s,l)}catch(_){p.push(R(_))}const P=await se(r.cron,s,l,p,R,u),D=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===r.cron;if(D)try{await qo(e,a,d,k(),r)}catch(_){p.push(R(_))}if(!O&&P===0&&!D){const _=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${r.cron}") fired but no cron handler is registered for that expression. Registered: ${_.length===0?"(none)":_.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[A]=p;if(p.length===1&&A)throw A;if(p.length>1)throw new AggregateError(p,`scheduled("${r.cron}") had ${String(p.length)} failure(s)`)},or=ws({assertAdmin:z,dispatchScheduled:ht,queueHandler:e.queueHandler}),ar=async(r,s)=>{try{const l=r??{},u=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!u||u.length===0)return;await T(d,o,Be(Ks,{outcome:s},{authorization:`Bearer ${u}`,"content-type":"application/json"}))}catch{}},sr=async(r,s,l,u)=>{if(!e.authHandler)return;const p=e.authBasePath??Xt,R=en(l.pathname,p)?Cr(r):void 0;let O;try{O=await e.authHandler(R?.request??r)}catch(P){throw R?.overflowed()?new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413}):P}if(R?.overflowed())throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});if(O)return Gs(l.pathname,p)&&u.waitUntil?.(ar(s,O.status>=400?"fail":"ok")),O},ir=async({args:r,env:s,functionPath:l,request:u,shardKey:p,waitUntil:R})=>{un(r,"REST");const O={functionPath:l,...p===void 0?{}:{shardKey:p}},{headers:P,identity:D}=await U(u,s,i);await ve(O,D);const A=p??o,_=Se(s,u,R),B=()=>Ie(u,l,r,A,P,_),L=qe(O,e);return L&&e.x402Charge?e.x402Charge(u,{functionPath:l,price:L.price},B,Je({waitUntil:R})):B()},cr=Nr({functions:e.functions??{},invoke:ir,readJsonBody:ee,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),ke=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0;si(ke);const dr={[Ls]:r=>r.method!=="GET"&&r.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Ns]:(r,s,l)=>Jn(r,s,l),[Vt]:(r,s,l,u)=>tr(r,s,u),[Ds]:(r,s,l,u)=>nr(r,s,u),[Us]:(r,s,l,u)=>Pn(r,s,u),[Cs]:(r,s,l,u)=>kn(r,s,u),[Bs]:async r=>{M(r,"POST","ws-token"),z(r);const s=k();if(s===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Bo(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...Q,...Bn,...xn,...Hn,...Ln,...jn,...Mn,...$n,...Kn,...Fn,...Qn,...cr,...jo({assertAdmin:z,getAuthAdmin:()=>e.authAdmin,parsePaging:Le,queryParameter:He,readJsonBody:ee})};let ie=Ot(e.security),ft=!1;const ur=r=>{ft||(ft=!0,ie=Ot(e.security,r??{}))},lr=async(r,s)=>{js(s)&&await j(r)},hr=(r,s)=>{if(!(s.pathname.startsWith(xe)||e.authHandler!==void 0&&en(s.pathname,e.authBasePath??Xt))||r.method!=="POST"&&r.method!=="PUT")return;const u=Number(r.headers.get("content-length")??""),p=Ps[s.pathname]??dn;if(Number.isFinite(u)&&u>p)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},fr=async(r,s,l)=>{rt.set(r,l);const u=new URL(r.url);hr(r,u);const p=await sr(r,s,u,l);if(p)return p;if(ke){const A=`${r.method} ${u.pathname}`,_=ke[A]??ke[u.pathname];if(_)return _(r,s,l)}const R=or[u.pathname];if(R)return R(r,s,l);const O=dr[u.pathname];if(O)return await lr(r,u.pathname),O(r,s,u,l);if(e.voiceAgents!==void 0&&u.pathname.startsWith(Yt))return Yn(r,s,u);if(u.pathname.startsWith(xe))return new Response("Not found",{status:404});const P=await Vn(r,s,l);if(P&&P.status!==404)return P;const D=await e.authDiscoveryHandler?.(r);return D?(await P?.body?.cancel(),D):P??new Response("Not found",{status:404})};return{async fetch(r,s,l){e.passThroughOnException&&l.passThroughOnException?.(),ur(s),v(s);const u=to(r,ie);if(u)return u;const p=no(r,ie);if(p)return Fe(p,r,ie);try{const R=await fr(r,s,l);return Fe(R,r,ie)}catch(R){return Fe(Tt(R),r,ie)}finally{Et(e.observability,tn(l))}},async queue(r,s,l){await lt(`queue:${zs(r)}`,l,async u=>{await e.queue?.(r,s,l,{traceparent:u})})},async scheduled(r,s,l){await lt(`cron:${r.cron}`,l,async u=>{await ht(r,s,l,u)})},serverQuery:rr}},ci=e=>In(e),di=e=>typeof e=="function"?{fetch:e}:e,ui=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,li=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},Bi=(e,t)=>{const n=di(e),{email:o,queue:a,scheduled:i}=li(e),d=h=>{const b={...ci({...h,httpRouter:n})};return i!==void 0&&!ui(h)&&(b.scheduled=async(T,S,k)=>{await i(T,S,k)}),a!==void 0&&h.queue===void 0&&(b.queue=async(T,S,k)=>{await a(T,S,k)}),o!==void 0&&(b.email=async(T,S,k)=>{await o(T,S,k)}),b};if(typeof t!="function")return d(t);const f=t;return{fetch:(h,m,b)=>d(f(m)).fetch(h,m,b),queue:(h,m,b)=>d(f(m)).queue?.(h,m,b)??Promise.resolve(),scheduled:(h,m,b)=>d(f(m)).scheduled(h,m,b),serverQuery:(h,m,b,T,S)=>d(f(m)).serverQuery(h,m,b,T,S),...o===void 0?{}:{email:(h,m,b)=>d(f(m)).email?.(h,m,b)??Promise.resolve()}}},hi=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new c("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},xi=(e={})=>(t,n,o)=>In(hi(e,n)).fetch(t,n,o??yr),Hi=e=>e;export{tt as COPY_AUTH_TO_JURISDICTION_OP,Ct as GET_AUTH_AUDIT_LOG_OP,yr as NOOP_EXECUTION_CONTEXT,yn as PURGE_UNPINNED_AUTH_OP,Mi as composeIdentityResolvers,ci as composeWorker,xi as createLunoraHandler,In as createWorker,Hi as defineRpcEnvelope,ti as probeRelayCount,hi as resolveLunoraOptions,$i as routeIdentityResolvers,Bi as withFrameworkWorker};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorBody as I}from"@lunora/errors";import{b as U,a as F}from"./base64-Bl1_r2k1.mjs";import{LunoraError as v}from"./LunoraError-DksAgIpa.mjs";import{resolveShard as V}from"./applyJurisdiction-C0ddU7Tg.mjs";const ke=r=>({listShardKeys(e){return r[e]??[]}}),be=(r,e)=>({listShardKeys(s){if(r===void 0)throw new v(`cannot discover the shards of "${s}": the worker has no \`resolveTableSharding\` to tell a sharded table from a root one, and no shard registry is configured`,{code:"BAD_REQUEST",status:400});const o=r(s)?.mode.kind;if(o==="shardBy")throw new v(`cannot discover the shards of "${s}": it is \`.shardBy()\` and the worker has no shard registry — declare \`.shardRegistry((env) => env.SHARD_REGISTRY)\` on the app builder and bind \`SHARD_REGISTRY\` to \`ShardRegistryDO\` (or pass \`queryCoordinator\` to \`createWorker\`)`,{code:"BAD_REQUEST",status:400});return o==="global"?[]:[e]}}),P=16,x=5e3,y=r=>r!==null&&typeof r=="object"&&"result"in r?r.result:r,L=r=>{const e=r??{};return{changed:typeof e.changed=="number"?e.changed:0,processed:typeof e.processed=="number"?e.processed:0,status:typeof e.status=="string"?e.status:void 0}},$=(r,e)=>r?"failed":e?"in_progress":"completed",j=r=>{const e=[];let s=0,o=0,t=0,n=0,a=!1,c=!1;for(const d of r){if(d.kind==="err"){o+=1,e.push({error:{message:d.message,timedOut:d.timedOut},shardKey:d.shardKey});continue}s+=1;const i=y(d.value),u=L(i);t+=u.changed,n+=u.processed,a||=u.status==="in_progress",c||=u.status==="failed",e.push({result:i,shardKey:d.shardKey})}return{changed:t,failed:o,ok:s,processed:n,shards:e,status:$(c,a||o>0)}},G=r=>{const e=r??{};return{before:typeof e.before=="number"&&Number.isFinite(e.before)?e.before:0,total:typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0}},H=r=>{const e=[];let s=0,o=0,t=0,n=0;for(const a of r){if(a.kind==="err"){o+=1,e.push({error:{message:a.message,timedOut:a.timedOut},shardKey:a.shardKey});continue}s+=1;const c=G(y(a.value));t+=c.before,n+=c.total,e.push({result:c,shardKey:a.shardKey})}return{failed:o,ok:s,partial:o>0,position:t+1,shards:e,total:n}},B=0,D=1,J=2,k=(r,e)=>r<e?-1:r>e?1:0,E=r=>r==null?B:typeof r=="number"?D:J,O=(r,e)=>{const s=E(r),o=E(e);return s!==o?s<o?-1:1:s===B?0:s===D?k(r,e):k(String(r),String(e))},Q=(r,e,s)=>{const o=O(r.partitionKey,e.partitionKey);if(o!==0)return o;const t=Math.max(r.sortValues.length,e.sortValues.length);for(let n=0;n<t;n+=1){const a=O(r.sortValues[n],e.sortValues[n]);if(a!==0)return s[n]==="desc"?-a:a}return O(r.rowId,e.rowId)},Y=r=>F(new TextEncoder().encode(JSON.stringify(r))),W=r=>{try{const e=JSON.parse(new TextDecoder().decode(U(r)));if(e!==null&&typeof e=="object"&&"perShard"in e){const{perShard:s}=e;if(s!==null&&typeof s=="object")return{perShard:s}}}catch{}return{perShard:{}}},X=r=>{const e=r??{},s=Array.isArray(e.rows)?e.rows:[];return{directions:Array.isArray(e.directions)?e.directions:[],hasMore:e.hasMore===!0,rows:s}},z=(r,e)=>{let s;for(const o of r){const t=o.rows[o.head];t!==void 0&&(s===void 0||Q(t.key,s.row.key,e)<0)&&(s={row:t,slice:o})}return s},Z=(r,e)=>{let s=!1;const o=new Set;for(const n of r)o.add(n.shardKey),(n.head<n.rows.length||n.hasMore)&&(s=!0);const t={...e};for(const n of Object.keys(e))o.has(n)||(s=!0);return s?Y({perShard:t}):null},q=(r,e,s,o)=>{const t=[],n={...o};for(;t.length<e;){const c=z(r,s);if(c===void 0)break;t.push(c.row.doc),n[c.slice.shardKey]=c.row.key,c.slice.head+=1}const a=Z(r,n);return{isDone:a===null,nextCursor:a,page:t}},ee=r=>{const e=[];let s=0,o=0;for(const t of r){if(t.kind==="err"){o+=1,e.push({error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const n=y(t.value),a=Array.isArray(n?.rows)?n.rows:[];e.push({rows:a,shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},re=r=>{const e=[];let s=0,o=0;for(const{outcome:t,sinceEpoch:n,sinceSeq:a}of r){if(t.kind==="err"){o+=1,e.push({cursor:a,error:{code:t.code,message:t.message,timedOut:t.timedOut},shardKey:t.shardKey,...n===void 0?{}:{epoch:n}});continue}s+=1;const c=y(t.value),d=Array.isArray(c?.changes)?c.changes:[],i=typeof c?.cursor=="number"?c.cursor:a,u=typeof c?.epoch=="string"&&c.epoch.length>0?c.epoch:n;e.push({changes:d,cursor:i,shardKey:t.shardKey,...u===void 0?{}:{epoch:u}})}return{failed:o,ok:s,shards:e}},te=r=>{let e=0,s=0,o=0;for(const t of r){if(t.kind==="err"){s+=1;continue}e+=1;const n=y(t.value);o+=typeof n?.applied=="number"?n.applied:0}return{applied:o,failed:s,ok:e}},se=r=>{const e=r??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},oe=r=>{const e=[];let s=0,o=0;for(const t of r){if(t.kind==="err"){o+=1,e.push({requests:0,shardKey:t.shardKey});continue}s+=1,e.push({requests:se(y(t.value)),shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},ne=r=>{const e=[],s={},o=[];let t=0,n=0,a=0;for(const c of r){if(c.kind==="err"){a+=1,e.push({error:{message:c.message,timedOut:c.timedOut},shardKey:c.shardKey});continue}n+=1;const d=y(c.value),i=d?.inserted??{};for(const[l,f]of Object.entries(i))s[l]=(s[l]??0)+f;const u=d?.errors;Array.isArray(u)&&o.push(...u),t+=d?.conflicts??0,e.push({result:{conflicts:d?.conflicts??0,errors:d?.errors??[],inserted:i},shardKey:c.shardKey})}return{conflicts:t,errors:o,failed:a,inserted:s,ok:n,shards:e}},m=r=>({body:JSON.stringify({args:r.args??{},functionPath:r.functionPath}),headers:{"content-type":"application/json",...r.headers}}),ae=async r=>{try{const s=(await r.json())?.error;return typeof s?.code!="string"||s.code.length===0?void 0:{code:s.code,message:typeof s.message=="string"?s.message:""}}catch{return}},g=async(r,e,s,o)=>{const t=V(r,e),n=new AbortController,a=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:n.signal});let c;const d=new Promise(u=>{c=setTimeout(()=>{try{n.abort()}catch{}u({code:"SHARD_TIMEOUT",kind:"err",message:`shard "${e}" timed out after ${String(o)}ms`,shardKey:e,timedOut:!0})},o)}),i=(async()=>{try{const u=await t.fetch(a);if(!u.ok){const f=await ae(u),p=`shard "${e}" returned ${String(u.status)}`;return{code:f?.code??"SHARD_HTTP_ERROR",kind:"err",message:f===void 0||f.message.length===0?p:`${p}: ${f.message}`,shardKey:e,timedOut:!1}}const l=await u.json();return{kind:"ok",shardKey:e,value:l}}catch(u){const{body:l}=I(u,{fallbackCode:"INTERNAL",redactedMessage:"shard call failed"});return{code:l.code,kind:"err",message:`shard "${e}" failed: ${l.message}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([i,d])}finally{c!==void 0&&clearTimeout(c)}},w=async(r,e,s)=>{if(r.length===0)return[];const o=Array.from({length:r.length});let t=0;const n=async()=>{for(;;){const c=t;t+=1;const d=r[c];if(c>=r.length||d===void 0)return;o[c]=await s(d,c)}},a=Math.min(e,r.length);return await Promise.all(Array.from({length:a},()=>n())),o},K=(r,e)=>r.length>0||e===null?r:[e],T=async(r,e,s)=>{const o=await Promise.all(e.map(async t=>K(await r.listShardKeys(t),s)));return[...new Set(o.flat())]},S=async(r,e,s,o,t)=>{const n=m(s);return w(e,o,async a=>g(r,a,n,t))},ce=r=>{const e={};for(const s of Object.keys(r).toSorted(k))e[s]=r[s]??null;return JSON.stringify(e)},ie=r=>r.flatMap(e=>Array.isArray(e)?e:[]),de=(r,e,s)=>{switch(s){case"max":return Math.max(r,e);case"min":return Math.min(r,e);case"sum":return r+e;default:return r}},ue=(r,e,s)=>{if(e===null||typeof e!="object")return;const o=e.key??{},t=e.value??null,n=ce(o),a=r.get(n);if(!a){r.set(n,{key:o,value:t});return}if(a.value===null){a.value=t;return}t!==null&&(a.value=de(a.value,t,s))},le=(r,e)=>{const s=new Map;for(const o of r)if(Array.isArray(o))for(const t of o)ue(s,t,e);return[...s.values()]},M=(r,e)=>{let s=null;for(const o of r)typeof o=="number"&&Number.isFinite(o)&&(s=s===null?o:e(s,o));return s},he=r=>{let e=0;for(const s of r)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},fe=r=>{let e=0,s=0;for(const o of r){if(o===null||typeof o!="object")continue;const t=o;typeof t.before=="number"&&Number.isFinite(t.before)&&(e+=t.before),typeof t.total=="number"&&Number.isFinite(t.total)&&(s+=t.total)}return{position:e+1,total:s}},ye=(r,e)=>{const s=[];for(const t of r)if(Array.isArray(t))for(const n of t){if(n===null||typeof n!="object")continue;const a=n[e.by],c=typeof a=="number"&&Number.isFinite(a)?a:Number.NEGATIVE_INFINITY;s.push({row:n,score:c})}const o=e.direction??"desc";return s.sort((t,n)=>o==="asc"?k(t.score,n.score):k(n.score,t.score)),s.slice(0,e.k).map(t=>t.row)},pe=(r,e)=>{switch(e.kind){case"concat":return ie(r);case"first":return r[0];case"groupBy":return le(r,e.op??"sum");case"max":return M(r,Math.max);case"min":return M(r,Math.min);case"rank":return fe(r);case"sum":return he(r);case"topK":return ye(r,e);default:return r}},N=(r,e)=>(Array.isArray(e)?e:[]).filter(s=>typeof s=="string").map(s=>({shardKey:r,table:s})),Ke=async(r,e,s)=>{const o=new Map,t=await Promise.all(s.tables.map(async i=>({keys:await r.listShardKeys(i),table:i})));for(const{keys:i,table:u}of t)for(const l of i)o.set(l,[...o.get(l)??[],u]);const n=await w([...o],P,async([i,u])=>({outcome:await g(e,i,m({args:{dryRun:s.dryRun===!0,tables:u},functionPath:"__lunora_admin__:releaseShardRegistration",headers:s.headers}),x),tables:u})),a=[],c=[],d=[];for(const{outcome:i,tables:u}of n){if(i.kind==="err"){a.push({message:i.message,shardKey:i.shardKey,tables:u});continue}const l=y(i.value)??{};c.push(...N(i.shardKey,l.kept)),d.push(...N(i.shardKey,l.released))}if(s.dryRun!==!0)for(const i of new Set(d.map(u=>u.table)))r.invalidate?.(i);return{failed:a,kept:c,released:d}},_e=r=>{const e=r.maxConcurrency??P,s=r.perShardTimeoutMs??x;if(e<1)throw new v("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(o,t){const n=await r.registry.listShardKeys(t.fanOut.table),a=await S(o,n,t,e,s),c=[],d=[];for(const i of a)i.kind==="ok"?c.push(i.value):d.push({code:i.code,message:i.message,shardKey:i.shardKey,timedOut:i.timedOut});return{data:pe(c,t.fanOut.merge),errors:d,failed:d.length,ok:c.length}},async orchestrateExport(o,t){const n=await T(r.registry,t.tables,t.defaultShardKey),a=K(n,t.defaultShardKey),c={args:{...t.args,tables:[...t.tables]},functionPath:"__lunora_admin__:exportShard",headers:t.headers},d=await S(o,a,c,e,s);return ee(d)},async orchestrateCdcSync(o,t){const n=K(await T(r.registry,t.tables,t.defaultShardKey),t.defaultShardKey),a=t.cursors??{},c=t.epochs??{},d=await w(n,e,async i=>{const u=a[i]??0,l=c[i];return{outcome:await g(o,i,m({args:{limit:t.limit,sinceEpoch:l,sinceSeq:u},functionPath:"__lunora_admin__:cdcSync",headers:t.headers}),s),sinceEpoch:l,sinceSeq:u}});return re(d)},async orchestrateImport(o,t){const{batches:n}=t,a=await w(n,e,async c=>g(o,c.shardKey,m({args:{rows:[...c.rows],startLine:c.startLine??1},functionPath:"__lunora_admin__:importShard",headers:t.headers}),s));return ne(a)},async orchestrateApplyCdc(o,t){const{batches:n}=t,a=await w(n,e,async c=>g(o,c.shardKey,m({args:{changes:[...c.changes]},functionPath:"__lunora_admin__:applyCdc",headers:t.headers}),s));return te(a)},async orchestrateMigration(o,t){const n=K(await r.registry.listShardKeys(t.table),t.defaultShardKey),a=await S(o,n,t,e,s);return j(a)},async orchestrateRank(o,t){const n=await r.registry.listShardKeys(t.table),a={args:{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:[...t.sortValues],table:t.table},functionPath:"__lunora_admin__:rankBefore",headers:t.headers},c=await S(o,n,a,e,s);return H(c)},async orchestrateRankPage(o,t){const n=await r.registry.listShardKeys(t.table),a=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),c=t.directions??[],d=t.cursor?W(t.cursor):{perShard:{}},i=await w(n,e,async h=>{const C=d.perShard[h],R={index:t.index,table:t.table,take:a};t.partitionKey!==void 0&&(R.partitionKey=t.partitionKey),C!==void 0&&(R.after=C);const b=await g(o,h,m({args:R,functionPath:"__lunora_admin__:rankPage",headers:t.headers}),s);if(b.kind==="err")return{error:{message:b.message,timedOut:b.timedOut},shardKey:h};const A=X(y(b.value));return{directions:A.directions,hasMore:A.hasMore,rows:A.rows,shardKey:h}}),u=[];let l=0,f=0,p;for(const h of i){if(h.error){f+=1;continue}l+=1,p===void 0&&h.directions&&h.directions.length>0&&(p=h.directions),u.push({hasMore:h.hasMore??!1,head:0,rows:h.rows??[],shardKey:h.shardKey})}const _=q(u,a,p??c,d.perShard);return{continueCursor:_.nextCursor,failed:f,isDone:_.isDone,ok:l,page:_.page,partial:f>0,shards:i}},async orchestrateShardTraffic(o,t){const n=await r.registry.listShardKeys(t.table),a={functionPath:"__lunora_admin__:getMetrics",headers:t.headers},c=await S(o,n,a,e,s);return oe(c)},registry:r.registry}};export{be as createDefaultShardRegistry,_e as createQueryCoordinator,ke as createStaticShardRegistry,Ke as pruneShardRegistry};
|
|
1
|
+
import{toErrorBody as I}from"@lunora/errors";import{b as U,a as F}from"./base64-Bl1_r2k1.mjs";import{LunoraError as v}from"./LunoraError-DksAgIpa.mjs";import{resolveShard as V}from"./applyJurisdiction-D4vryLhj.mjs";const ke=r=>({listShardKeys(e){return r[e]??[]}}),be=(r,e)=>({listShardKeys(s){if(r===void 0)throw new v(`cannot discover the shards of "${s}": the worker has no \`resolveTableSharding\` to tell a sharded table from a root one, and no shard registry is configured`,{code:"BAD_REQUEST",status:400});const o=r(s)?.mode.kind;if(o==="shardBy")throw new v(`cannot discover the shards of "${s}": it is \`.shardBy()\` and the worker has no shard registry — declare \`.shardRegistry((env) => env.SHARD_REGISTRY)\` on the app builder and bind \`SHARD_REGISTRY\` to \`ShardRegistryDO\` (or pass \`queryCoordinator\` to \`createWorker\`)`,{code:"BAD_REQUEST",status:400});return o==="global"?[]:[e]}}),P=16,x=5e3,y=r=>r!==null&&typeof r=="object"&&"result"in r?r.result:r,L=r=>{const e=r??{};return{changed:typeof e.changed=="number"?e.changed:0,processed:typeof e.processed=="number"?e.processed:0,status:typeof e.status=="string"?e.status:void 0}},$=(r,e)=>r?"failed":e?"in_progress":"completed",j=r=>{const e=[];let s=0,o=0,t=0,n=0,a=!1,c=!1;for(const d of r){if(d.kind==="err"){o+=1,e.push({error:{message:d.message,timedOut:d.timedOut},shardKey:d.shardKey});continue}s+=1;const i=y(d.value),u=L(i);t+=u.changed,n+=u.processed,a||=u.status==="in_progress",c||=u.status==="failed",e.push({result:i,shardKey:d.shardKey})}return{changed:t,failed:o,ok:s,processed:n,shards:e,status:$(c,a||o>0)}},G=r=>{const e=r??{};return{before:typeof e.before=="number"&&Number.isFinite(e.before)?e.before:0,total:typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0}},H=r=>{const e=[];let s=0,o=0,t=0,n=0;for(const a of r){if(a.kind==="err"){o+=1,e.push({error:{message:a.message,timedOut:a.timedOut},shardKey:a.shardKey});continue}s+=1;const c=G(y(a.value));t+=c.before,n+=c.total,e.push({result:c,shardKey:a.shardKey})}return{failed:o,ok:s,partial:o>0,position:t+1,shards:e,total:n}},B=0,D=1,J=2,k=(r,e)=>r<e?-1:r>e?1:0,E=r=>r==null?B:typeof r=="number"?D:J,O=(r,e)=>{const s=E(r),o=E(e);return s!==o?s<o?-1:1:s===B?0:s===D?k(r,e):k(String(r),String(e))},Q=(r,e,s)=>{const o=O(r.partitionKey,e.partitionKey);if(o!==0)return o;const t=Math.max(r.sortValues.length,e.sortValues.length);for(let n=0;n<t;n+=1){const a=O(r.sortValues[n],e.sortValues[n]);if(a!==0)return s[n]==="desc"?-a:a}return O(r.rowId,e.rowId)},Y=r=>F(new TextEncoder().encode(JSON.stringify(r))),W=r=>{try{const e=JSON.parse(new TextDecoder().decode(U(r)));if(e!==null&&typeof e=="object"&&"perShard"in e){const{perShard:s}=e;if(s!==null&&typeof s=="object")return{perShard:s}}}catch{}return{perShard:{}}},X=r=>{const e=r??{},s=Array.isArray(e.rows)?e.rows:[];return{directions:Array.isArray(e.directions)?e.directions:[],hasMore:e.hasMore===!0,rows:s}},z=(r,e)=>{let s;for(const o of r){const t=o.rows[o.head];t!==void 0&&(s===void 0||Q(t.key,s.row.key,e)<0)&&(s={row:t,slice:o})}return s},Z=(r,e)=>{let s=!1;const o=new Set;for(const n of r)o.add(n.shardKey),(n.head<n.rows.length||n.hasMore)&&(s=!0);const t={...e};for(const n of Object.keys(e))o.has(n)||(s=!0);return s?Y({perShard:t}):null},q=(r,e,s,o)=>{const t=[],n={...o};for(;t.length<e;){const c=z(r,s);if(c===void 0)break;t.push(c.row.doc),n[c.slice.shardKey]=c.row.key,c.slice.head+=1}const a=Z(r,n);return{isDone:a===null,nextCursor:a,page:t}},ee=r=>{const e=[];let s=0,o=0;for(const t of r){if(t.kind==="err"){o+=1,e.push({error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const n=y(t.value),a=Array.isArray(n?.rows)?n.rows:[];e.push({rows:a,shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},re=r=>{const e=[];let s=0,o=0;for(const{outcome:t,sinceEpoch:n,sinceSeq:a}of r){if(t.kind==="err"){o+=1,e.push({cursor:a,error:{code:t.code,message:t.message,timedOut:t.timedOut},shardKey:t.shardKey,...n===void 0?{}:{epoch:n}});continue}s+=1;const c=y(t.value),d=Array.isArray(c?.changes)?c.changes:[],i=typeof c?.cursor=="number"?c.cursor:a,u=typeof c?.epoch=="string"&&c.epoch.length>0?c.epoch:n;e.push({changes:d,cursor:i,shardKey:t.shardKey,...u===void 0?{}:{epoch:u}})}return{failed:o,ok:s,shards:e}},te=r=>{let e=0,s=0,o=0;for(const t of r){if(t.kind==="err"){s+=1;continue}e+=1;const n=y(t.value);o+=typeof n?.applied=="number"?n.applied:0}return{applied:o,failed:s,ok:e}},se=r=>{const e=r??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},oe=r=>{const e=[];let s=0,o=0;for(const t of r){if(t.kind==="err"){o+=1,e.push({requests:0,shardKey:t.shardKey});continue}s+=1,e.push({requests:se(y(t.value)),shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},ne=r=>{const e=[],s={},o=[];let t=0,n=0,a=0;for(const c of r){if(c.kind==="err"){a+=1,e.push({error:{message:c.message,timedOut:c.timedOut},shardKey:c.shardKey});continue}n+=1;const d=y(c.value),i=d?.inserted??{};for(const[l,f]of Object.entries(i))s[l]=(s[l]??0)+f;const u=d?.errors;Array.isArray(u)&&o.push(...u),t+=d?.conflicts??0,e.push({result:{conflicts:d?.conflicts??0,errors:d?.errors??[],inserted:i},shardKey:c.shardKey})}return{conflicts:t,errors:o,failed:a,inserted:s,ok:n,shards:e}},m=r=>({body:JSON.stringify({args:r.args??{},functionPath:r.functionPath}),headers:{"content-type":"application/json",...r.headers}}),ae=async r=>{try{const s=(await r.json())?.error;return typeof s?.code!="string"||s.code.length===0?void 0:{code:s.code,message:typeof s.message=="string"?s.message:""}}catch{return}},g=async(r,e,s,o)=>{const t=V(r,e),n=new AbortController,a=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:n.signal});let c;const d=new Promise(u=>{c=setTimeout(()=>{try{n.abort()}catch{}u({code:"SHARD_TIMEOUT",kind:"err",message:`shard "${e}" timed out after ${String(o)}ms`,shardKey:e,timedOut:!0})},o)}),i=(async()=>{try{const u=await t.fetch(a);if(!u.ok){const f=await ae(u),p=`shard "${e}" returned ${String(u.status)}`;return{code:f?.code??"SHARD_HTTP_ERROR",kind:"err",message:f===void 0||f.message.length===0?p:`${p}: ${f.message}`,shardKey:e,timedOut:!1}}const l=await u.json();return{kind:"ok",shardKey:e,value:l}}catch(u){const{body:l}=I(u,{fallbackCode:"INTERNAL",redactedMessage:"shard call failed"});return{code:l.code,kind:"err",message:`shard "${e}" failed: ${l.message}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([i,d])}finally{c!==void 0&&clearTimeout(c)}},w=async(r,e,s)=>{if(r.length===0)return[];const o=Array.from({length:r.length});let t=0;const n=async()=>{for(;;){const c=t;t+=1;const d=r[c];if(c>=r.length||d===void 0)return;o[c]=await s(d,c)}},a=Math.min(e,r.length);return await Promise.all(Array.from({length:a},()=>n())),o},K=(r,e)=>r.length>0||e===null?r:[e],T=async(r,e,s)=>{const o=await Promise.all(e.map(async t=>K(await r.listShardKeys(t),s)));return[...new Set(o.flat())]},S=async(r,e,s,o,t)=>{const n=m(s);return w(e,o,async a=>g(r,a,n,t))},ce=r=>{const e={};for(const s of Object.keys(r).toSorted(k))e[s]=r[s]??null;return JSON.stringify(e)},ie=r=>r.flatMap(e=>Array.isArray(e)?e:[]),de=(r,e,s)=>{switch(s){case"max":return Math.max(r,e);case"min":return Math.min(r,e);case"sum":return r+e;default:return r}},ue=(r,e,s)=>{if(e===null||typeof e!="object")return;const o=e.key??{},t=e.value??null,n=ce(o),a=r.get(n);if(!a){r.set(n,{key:o,value:t});return}if(a.value===null){a.value=t;return}t!==null&&(a.value=de(a.value,t,s))},le=(r,e)=>{const s=new Map;for(const o of r)if(Array.isArray(o))for(const t of o)ue(s,t,e);return[...s.values()]},M=(r,e)=>{let s=null;for(const o of r)typeof o=="number"&&Number.isFinite(o)&&(s=s===null?o:e(s,o));return s},he=r=>{let e=0;for(const s of r)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},fe=r=>{let e=0,s=0;for(const o of r){if(o===null||typeof o!="object")continue;const t=o;typeof t.before=="number"&&Number.isFinite(t.before)&&(e+=t.before),typeof t.total=="number"&&Number.isFinite(t.total)&&(s+=t.total)}return{position:e+1,total:s}},ye=(r,e)=>{const s=[];for(const t of r)if(Array.isArray(t))for(const n of t){if(n===null||typeof n!="object")continue;const a=n[e.by],c=typeof a=="number"&&Number.isFinite(a)?a:Number.NEGATIVE_INFINITY;s.push({row:n,score:c})}const o=e.direction??"desc";return s.sort((t,n)=>o==="asc"?k(t.score,n.score):k(n.score,t.score)),s.slice(0,e.k).map(t=>t.row)},pe=(r,e)=>{switch(e.kind){case"concat":return ie(r);case"first":return r[0];case"groupBy":return le(r,e.op??"sum");case"max":return M(r,Math.max);case"min":return M(r,Math.min);case"rank":return fe(r);case"sum":return he(r);case"topK":return ye(r,e);default:return r}},N=(r,e)=>(Array.isArray(e)?e:[]).filter(s=>typeof s=="string").map(s=>({shardKey:r,table:s})),Ke=async(r,e,s)=>{const o=new Map,t=await Promise.all(s.tables.map(async i=>({keys:await r.listShardKeys(i),table:i})));for(const{keys:i,table:u}of t)for(const l of i)o.set(l,[...o.get(l)??[],u]);const n=await w([...o],P,async([i,u])=>({outcome:await g(e,i,m({args:{dryRun:s.dryRun===!0,tables:u},functionPath:"__lunora_admin__:releaseShardRegistration",headers:s.headers}),x),tables:u})),a=[],c=[],d=[];for(const{outcome:i,tables:u}of n){if(i.kind==="err"){a.push({message:i.message,shardKey:i.shardKey,tables:u});continue}const l=y(i.value)??{};c.push(...N(i.shardKey,l.kept)),d.push(...N(i.shardKey,l.released))}if(s.dryRun!==!0)for(const i of new Set(d.map(u=>u.table)))r.invalidate?.(i);return{failed:a,kept:c,released:d}},_e=r=>{const e=r.maxConcurrency??P,s=r.perShardTimeoutMs??x;if(e<1)throw new v("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(o,t){const n=await r.registry.listShardKeys(t.fanOut.table),a=await S(o,n,t,e,s),c=[],d=[];for(const i of a)i.kind==="ok"?c.push(i.value):d.push({code:i.code,message:i.message,shardKey:i.shardKey,timedOut:i.timedOut});return{data:pe(c,t.fanOut.merge),errors:d,failed:d.length,ok:c.length}},async orchestrateExport(o,t){const n=await T(r.registry,t.tables,t.defaultShardKey),a=K(n,t.defaultShardKey),c={args:{...t.args,tables:[...t.tables]},functionPath:"__lunora_admin__:exportShard",headers:t.headers},d=await S(o,a,c,e,s);return ee(d)},async orchestrateCdcSync(o,t){const n=K(await T(r.registry,t.tables,t.defaultShardKey),t.defaultShardKey),a=t.cursors??{},c=t.epochs??{},d=await w(n,e,async i=>{const u=a[i]??0,l=c[i];return{outcome:await g(o,i,m({args:{limit:t.limit,sinceEpoch:l,sinceSeq:u},functionPath:"__lunora_admin__:cdcSync",headers:t.headers}),s),sinceEpoch:l,sinceSeq:u}});return re(d)},async orchestrateImport(o,t){const{batches:n}=t,a=await w(n,e,async c=>g(o,c.shardKey,m({args:{rows:[...c.rows],startLine:c.startLine??1},functionPath:"__lunora_admin__:importShard",headers:t.headers}),s));return ne(a)},async orchestrateApplyCdc(o,t){const{batches:n}=t,a=await w(n,e,async c=>g(o,c.shardKey,m({args:{changes:[...c.changes]},functionPath:"__lunora_admin__:applyCdc",headers:t.headers}),s));return te(a)},async orchestrateMigration(o,t){const n=K(await r.registry.listShardKeys(t.table),t.defaultShardKey),a=await S(o,n,t,e,s);return j(a)},async orchestrateRank(o,t){const n=await r.registry.listShardKeys(t.table),a={args:{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:[...t.sortValues],table:t.table},functionPath:"__lunora_admin__:rankBefore",headers:t.headers},c=await S(o,n,a,e,s);return H(c)},async orchestrateRankPage(o,t){const n=await r.registry.listShardKeys(t.table),a=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),c=t.directions??[],d=t.cursor?W(t.cursor):{perShard:{}},i=await w(n,e,async h=>{const C=d.perShard[h],R={index:t.index,table:t.table,take:a};t.partitionKey!==void 0&&(R.partitionKey=t.partitionKey),C!==void 0&&(R.after=C);const b=await g(o,h,m({args:R,functionPath:"__lunora_admin__:rankPage",headers:t.headers}),s);if(b.kind==="err")return{error:{message:b.message,timedOut:b.timedOut},shardKey:h};const A=X(y(b.value));return{directions:A.directions,hasMore:A.hasMore,rows:A.rows,shardKey:h}}),u=[];let l=0,f=0,p;for(const h of i){if(h.error){f+=1;continue}l+=1,p===void 0&&h.directions&&h.directions.length>0&&(p=h.directions),u.push({hasMore:h.hasMore??!1,head:0,rows:h.rows??[],shardKey:h.shardKey})}const _=q(u,a,p??c,d.perShard);return{continueCursor:_.nextCursor,failed:f,isDone:_.isDone,ok:l,page:_.page,partial:f>0,shards:i}},async orchestrateShardTraffic(o,t){const n=await r.registry.listShardKeys(t.table),a={functionPath:"__lunora_admin__:getMetrics",headers:t.headers},c=await S(o,n,a,e,s);return oe(c)},registry:r.registry}};export{be as createDefaultShardRegistry,_e as createQueryCoordinator,ke as createStaticShardRegistry,Ke as pruneShardRegistry};
|
package/dist/packem_shared/{createShardClient-BrzRLSs9.mjs → createShardClient-BLW9uJZN.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as n}from"@lunora/errors";import{e as S,a as I}from"./identity-header-pR617HTs.mjs";import{O as w,a as p}from"./origin-paywall-B6eOO67m.mjs";import{e as N,d as f}from"./wire-codec-BLvSm5Mn.mjs";import{applyJurisdiction as g,resolveShard as L}from"./applyJurisdiction-
|
|
1
|
+
import{LunoraError as n}from"@lunora/errors";import{e as S,a as I}from"./identity-header-pR617HTs.mjs";import{O as w,a as p}from"./origin-paywall-B6eOO67m.mjs";import{e as N,d as f}from"./wire-codec-BLvSm5Mn.mjs";import{applyJurisdiction as g,resolveShard as L}from"./applyJurisdiction-D4vryLhj.mjs";const A=e=>{if(typeof e=="string")return e;const t=e?.__lunoraRef;if(typeof t!="string"||t.length===0)throw new n("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return t},E=e=>{const t=new n(e.code,e.message);return e.data!==void 0&&(t.data=f(e.data)),t},x=(e,t={})=>{const l=g(e,t.jurisdiction),m=t.system??!0,c=r=>x(e,{...t,...r});return{as:r=>c({as:r}),asSystem:()=>c({as:void 0}),call:async(r,y,o)=>{const i=A(r),h=o?.shardKey??t.shardKey;if(h===void 0||h.length===0)throw new n("INTERNAL",`createShardClient: no shard key for "${i}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const a={"content-type":"application/json"};m&&(a[p]=w,a["x-lunora-system"]="1"),t.as&&(a["x-lunora-userid"]=S(t.as.userId),t.as.claims&&(a["x-lunora-identity"]=I(t.as.claims))),o?.mutationId!==void 0&&o.mutationId.length>0&&(a["x-lunora-mutation-id"]=o.mutationId);const s=await L(l,h).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:N(y??{}),functionPath:i}),headers:a,method:"POST"})),u=s.statusText?` ${s.statusText}`:"";let d;try{d=await s.json()}catch{throw new n("INTERNAL",`createShardClient: shard response for "${i}" was not JSON (status ${String(s.status)}${u})`)}if("error"in d)throw E(d.error);if(!s.ok)throw new n("INTERNAL",`createShardClient: shard call "${i}" failed (status ${String(s.status)}${u})`);return f(d.result)},forShard:r=>c({shardKey:r})}};export{x as createShardClient};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const l=e=>{const t=e.trim();if(!t.startsWith("at "))return;let n=t.slice(3),o="<anonymous>";const i=n.lastIndexOf(" (");n.endsWith(")")&&i!==-1&&(o=n.slice(0,i),n=n.slice(i+2,-1));const s=n.lastIndexOf(":"),c=s<=0?-1:n.lastIndexOf(":",s-1),a=Number.parseInt(n.slice(c+1,s),10),r=Number.parseInt(n.slice(s+1),10);if(!(c<=0||Number.isNaN(a)||Number.isNaN(r)))return{colno:r,filename:n.slice(0,c),function:o,lineno:a}},f=e=>{const t=new Error(e.message);return t.name=e.name??e.code??"Error",e.stack!==void 0&&(t.stack=e.stack),e.code!==void 0&&(t.code=e.code),t},m=e=>{if(e===void 0)return[];const t=[];for(const n of e.split(`
|
|
2
|
+
`)){const o=l(n);o!==void 0&&t.push(o)}return t.toReversed()};export{m as parseStackFrames,f as toError};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/runtime",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.179",
|
|
4
4
|
"description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,10 +46,10 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
49
|
+
"@lunora/bindings": "1.0.0-alpha.97",
|
|
50
50
|
"@lunora/errors": "1.0.0-alpha.50",
|
|
51
|
-
"@lunora/observability": "1.0.0-alpha.
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
51
|
+
"@lunora/observability": "1.0.0-alpha.123",
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.56"
|
|
53
53
|
},
|
|
54
54
|
"peerDependencies": {
|
|
55
55
|
"@lunora/shard-engine": ">=1.0.0-alpha.24 <2.0.0-0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as Z}from"@lunora/errors";import{redactArgs as j}from"@lunora/observability";import{e as c,L as h,o as $,c as k,O as V,f as Q,g as v,h as z,w as rr,i as tr,j as or,m as er}from"./otlp-resource-BwFJnvwB.mjs";const sr=r=>{if(typeof r=="string")return r;try{return JSON.stringify(r)??String(r)}catch{return String(r)}},W=r=>typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:sr(r),nr=512,ir=200,ar=r=>{const e=r.maxItems??nr,o=r.maxDelayMs??ir;let t=[],s,d,n;const a=()=>{s!==void 0&&(clearTimeout(s),s=void 0)},y=async()=>{a();const p=t;t=[];const u=n;d=void 0,n=void 0;try{p.length>0&&await r.export(p)}catch{}finally{u?.()}},m=p=>{d===void 0&&(d=new Promise(u=>{n=u}),s=setTimeout(()=>{y()},o)),p?.(d)};return{add:(p,u)=>{for(t.push(p);t.length>e;)t.shift();m(u),t.length>=e&&y()},flush:async p=>{if(t.length===0){a();return}const u=y();return p?.(u),u},get size(){return t.length}}},cr=/["\\\u0000-\u001F\uD800-\uDFFF]/,B=r=>cr.test(r)?JSON.stringify(r):`"${r}"`,R=r=>{if(r===void 0)return"null";if(typeof r=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof r=="number"){if(Number.isNaN(r))return"nan";if(r===1/0)return"inf";if(r===-1/0)return"-inf";if(Object.is(r,-0))return"-0"}if(typeof r=="string")return B(r);if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r)){let n="[";for(let a=0;a<r.length;a++)a>0&&(n+=","),n+=R(r[a]);return n+"]"}const e=Object.getPrototypeOf(r);if(e!==null&&e!==Object.prototype){const n=r.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${n} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const o=r,t=Object.keys(o).sort();let s="{",d=!0;for(const n of t){const a=o[n];a!==void 0&&(d?d=!1:s+=",",s+=B(n),s+=":",s+=R(a))}return s+"}"},dr=1,ur=0,lr=(r,e)=>{const o=[c(h.functionPath,r.functionPath),c(h.ok,r.ok)];r.method!==void 0&&o.push(c("http.request.method",r.method)),r.path!==void 0&&o.push(c("url.path",r.path)),o.push(c("http.route",r.functionPath)),r.scheme!==void 0&&o.push(c("url.scheme",r.scheme)),r.host!==void 0&&o.push(c("server.address",r.host)),r.port!==void 0&&o.push(c("server.port",r.port)),r.userAgent!==void 0&&o.push(c("user_agent.original",r.userAgent)),r.shardKey!==void 0&&o.push(c(h.shardKey,r.shardKey)),r.rayId!==void 0&&o.push(c(h.rayId,r.rayId)),o.push(c("http.response.status_code",r.error?.status??200)),r.error&&o.push(c(h.errorType,r.error.code),c("lunora.error_status",r.error.status)),r.fanOut&&o.push(c("lunora.fanout.table",r.fanOut.table),c("lunora.fanout.shards",r.fanOut.shards),c("lunora.fanout.failed",r.fanOut.failed));const t={attributes:o,endTimeUnixNano:k(e),kind:V.server,name:r.functionPath,...r.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},spanId:r.spanId??$(8),startTimeUnixNano:k(e-r.durationMs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId??$(16)};return r.traceFlags!==void 0&&(t.flags=r.traceFlags),r.error&&(t.events=[{attributes:[c("exception.type",r.error.code),c("exception.message",r.error.message)],name:"exception",timeUnixNano:k(e)}]),t},M=(r,e)=>{const o=new Map([[h.functionPath,c(h.functionPath,r.functionPath)]]);r.shardKey!==void 0&&o.set(h.shardKey,c(h.shardKey,r.shardKey)),r.userId!==void 0&&o.set(h.userId,c(h.userId,r.userId)),r.rayId!==void 0&&o.set(h.rayId,c(h.rayId,r.rayId)),r.errorType!==void 0&&o.set(h.errorType,c(h.errorType,r.errorType));for(const[t,s]of Object.entries(e??{}))o.set(t,c(t,W(s)));return[...o.values()]},pr=r=>{const e={attributes:M({errorType:r.error?.type,functionPath:r.functionPath,rayId:r.rayId,shardKey:r.shardKey,userId:r.userId},r.attributes),endTimeUnixNano:k(r.startTs+r.durationMs),flags:r.sampled===!1?ur:dr,kind:V[r.kind??"internal"],name:r.name,parentSpanId:r.parentSpanId,spanId:r.spanId,startTimeUnixNano:k(r.startTs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId},o=t=>v(Object.fromEntries(Object.entries(t??{}).map(([s,d])=>[s,W(d)])));return r.events!==void 0&&r.events.length>0&&(e.events=r.events.map(t=>({attributes:o(t.attributes),name:t.name,timeUnixNano:k(t.ts)}))),r.links!==void 0&&r.links.length>0&&(e.links=r.links.map(t=>({attributes:o(t.attributes),spanId:t.spanId,traceId:t.traceId}))),e},fr=r=>{const e=k(r.ts),o=M({functionPath:r.functionPath,shardKey:r.shardKey},r.attributes),t=r.traceId===void 0?void 0:[{asDouble:r.value,timeUnixNano:e,traceId:r.traceId}],s={asDouble:r.value,attributes:o,...t===void 0?{}:{exemplars:t},timeUnixNano:e};return r.kind==="gauge"?{gauge:{dataPoints:[s]},name:r.name}:r.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:o,bucketCounts:["1"],count:"1",...t===void 0?{}:{exemplars:t},explicitBounds:[],max:r.value,min:r.value,sum:r.value,timeUnixNano:e}]},name:r.name}:{name:r.name,sum:{aggregationTemporality:1,dataPoints:[s],isMonotonic:!0}}},mr=r=>{const e={attributes:M({functionPath:r.functionPath,rayId:r.rayId,shardKey:r.shardKey,userId:r.userId},r.fields),body:{stringValue:r.message},severityNumber:Q[r.level],severityText:r.level.toUpperCase(),timeUnixNano:k(r.ts)};return r.traceId!==void 0&&(e.traceId=r.traceId),r.spanId!==void 0&&(e.spanId=r.spanId),r.eventName!==void 0&&(e.eventName=r.eventName,e.attributes.push(c("event.name",r.eventName))),e},hr=1024,C=5;let A=0;const yr=(r,e)=>{if(A>=C)return;A+=1;let o;try{o=new URL(r).host}catch{o="<unparseable endpoint>"}const t=A===C?" Further OTLP rejections are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] collector ${o} rejected the export with HTTP ${String(e)}; the batch is DROPPED (there is no retry).${t}`)},gr=async r=>{const e=new Blob([r]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(e).arrayBuffer()},G=async(r,e,o,t)=>{try{const s=JSON.stringify(e),{byteLength:d}=new TextEncoder().encode(s),n=(d<hr?fetch(r,{body:s,headers:o,method:"POST"}):gr(s).then(a=>fetch(r,{body:a,headers:{...o,"content-encoding":"gzip"},method:"POST"}))).then(a=>{a.ok||yr(r,a.status)},()=>{});t?.(n),await n}catch{}},br=(r,e,o,t)=>{G(r,e,o,t?.waitUntil).catch(()=>{})},O=(r,e)=>e===!0&&r.ok,Ir=r=>r.kind==="metric"?void 0:r.event.traceId,kr=r=>{const e=Map.groupBy(r,t=>Ir(t)),o=e.get(void 0)??[];return e.delete(void 0),{byTrace:e,untraced:o}},J=5,Sr=(r,e,o)=>{if(e===void 0)return r;const{byTrace:t,untraced:s}=kr(r),d=[...s];let n=0,a;for(const[y,m]of t){let p;try{p=e({logs:m.filter(u=>u.kind==="log").map(u=>u.event),rpc:m.filter(u=>u.kind==="rpc").map(u=>u.event),spans:m.filter(u=>u.kind==="span").map(u=>u.event),traceId:y})}catch(u){n+=1,n===1&&(a=u),p=!0}p&&d.push(...m)}return n>0&&o(a,n),d},P=(r,e)=>{if(e===void 0)return r;try{return e(r)??void 0}catch{return}},Tr=r=>({...r,...r.fields===void 0?{}:{fields:j(r.fields)},message:j(r.message)}),H=(r,e,o)=>{if(r.kind==="rpc"){const s=P(r.event,e?.rpc);return s===void 0?void 0:{bucket:"spans",encoded:lr(s,r.endMs)}}if(r.kind==="span"){const s=P(r.event,e?.span);return s===void 0?void 0:{bucket:"spans",encoded:pr(s)}}if(r.kind==="log"){const s=P(o?Tr(r.event):r.event,e?.log);return s===void 0?void 0:{bucket:"logs",encoded:mr(s)}}const t=P(r.event,e?.metric);return t===void 0?void 0:{bucket:"metrics",encoded:fr(t)}},wr=["fuseCloudflareTraces","instrumentDatabase","metricHistory","traceFetch"],Nr=(r={})=>{const{onlyErrors:e}=r;return{onLog:o=>{o.level==="error"||o.level==="fatal"?console.error("[lunora:log]",o.functionPath,o.message):console.log("[lunora:log]",o.functionPath,o.message)},onMetric:o=>{console.log("[lunora:metric]",`${o.name}=${String(o.value)}`,o.kind,o.functionPath)},onRpc:o=>{O(o,e)||(o.ok?console.log("[lunora:rpc]",o):console.error("[lunora:rpc]",o))},onSpan:o=>{const t=o.ok?"ok":`error ${o.error?.type??""}`.trim();console.log("[lunora:span]",o.name,`${String(o.durationMs)}ms`,t,o.functionPath)}}},Lr=r=>{const{headers:e,onlyErrors:o,transform:t,transformLog:s,url:d}=r,n=z({"content-type":"application/json"},e),a=(y,m)=>{try{const p=fetch(d,{body:JSON.stringify(y),headers:n,method:"POST"}).catch(()=>{});m?.waitUntil&&m.waitUntil(p)}catch{}};return{onLog:(y,m)=>{const p=P(y,s);p!==void 0&&a(p,m)},onRpc:(y,m)=>{if(O(y,o))return;const p=P(y,t);p!==void 0&&a(p,m)}}},Ar=r=>{const{capture:e,captureLog:o}=r;if(typeof e!="function")throw new TypeError("sentrySink requires a `capture` callback — wire your own Sentry client, e.g. `sentrySink({ capture: (event) => Sentry.captureMessage(event.name) })`. There is no `dsn` option; the runtime bundles no Sentry client.");const t=r.onlyErrors??!0;return{onLog:o?s=>{try{o(s)}catch{}}:void 0,onRpc:s=>{if(!O(s,t))try{e(s)}catch{}}}},Rr=r=>{const{dataset:e,onlyErrors:o}=r;return{onRpc:t=>{if(!O(t,o))try{e.writeDataPoint({blobs:[t.functionPath,t.ok?"ok":"error",t.shardKey??"",t.error?.code??"",t.fanOut?.table??""],doubles:[t.durationMs,t.ok?0:1,t.fanOut?.shards??0,t.fanOut?.failed??0],indexes:[t.functionPath]})}catch{}}}},Mr=r=>{const{pipeline:e,serializeFields:o}=r;return{onLog:(t,s)=>{try{const d={functionPath:t.functionPath,level:t.level,message:t.message,ts:t.ts};t.fields&&(d.fields=o===!0?JSON.stringify(t.fields):t.fields);for(const a of["shardKey","userId","traceId","spanId"])t[a]!==void 0&&(d[a]=t[a]);const n=e.send([d]).catch(()=>{});s?.waitUntil&&s.waitUntil(n)}catch{}}}},_r=r=>{const{batch:e,deploymentEnvironment:o,detectResources:t,endpoint:s,headers:d,onlyErrors:n,postProcessor:a,resourceAttributes:y,serviceNamespace:m,serviceVersion:p,tailSampler:u,token:X}=r,_=r.serviceName??"lunora",x=r.redactLogs??!0;if(e!==!1&&e?.maxItems!==void 0&&(!Number.isInteger(e.maxItems)||e.maxItems<1))throw new Z("ENV_INVALID",`otlpSink: \`batch.maxItems\` must be a positive integer, received ${String(e.maxItems)}.`);const U={...p===void 0?{}:{"service.version":p},...m===void 0?{}:{"service.namespace":m},...o===void 0?{}:{"deployment.environment":o},...y},D=new WeakMap,I=l=>{if(t!==!0||l?.resourceAttributes===void 0)return U;const i=D.get(l);if(i!==void 0)return i;const f=er(l.resourceAttributes(),U);return D.set(l,f),f};let S=s;for(;S.endsWith("/");)S=S.slice(0,-1);const F={logs:{url:`${S}/v1/logs`,wrap:or},metrics:{url:`${S}/v1/metrics`,wrap:tr},spans:{url:`${S}/v1/traces`,wrap:rr}},K=z({"content-type":"application/json"},d,X);let L=0;const q=(l,i)=>{if(L>=J)return;L+=1;const f=L===J?" Further tailSampler failures from this sink are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] tailSampler threw for ${String(i)} trace(s) in this flush window; keeping them (fail-open), so the sampling policy did NOT apply.${f}`,l)},Y=async l=>{const i=Sr(l,u,q),f=new Map;for(const g of i){const b=H(g,a,x);if(b===void 0)continue;const N=R(g.resource);let w=f.get(N);w===void 0&&(w={logs:[],metrics:[],resource:g.resource,spans:[]},f.set(N,w)),w[b.bucket].push(b.encoded)}const T=[];for(const[,g]of f)for(const b of["spans","logs","metrics"])if(g[b].length>0){const{url:N,wrap:w}=F[b];T.push(G(N,w(g[b],"@lunora/runtime",_,g.resource),K))}await Promise.all(T)};if(e===!1){const l=(i,f)=>{const T=H(i,a,x);if(T!==void 0){const{url:g,wrap:b}=F[T.bucket];br(g,b(T.encoded,"@lunora/runtime",_,i.resource),K,f)}};return{onLog:(i,f)=>{l({event:i,kind:"log",resource:I(f)},f)},onMetric:(i,f)=>{l({event:i,kind:"metric",resource:I(f)},f)},onRpc:(i,f)=>{O(i,n)||l({endMs:Date.now(),event:i,kind:"rpc",resource:I(f)},f)},onSpan:(i,f)=>{l({event:i,kind:"span",resource:I(f)},f)}}}const E=ar({export:Y,...e?.maxDelayMs===void 0?{}:{maxDelayMs:e.maxDelayMs},...e?.maxItems===void 0?{}:{maxItems:e.maxItems}});return{flush:l=>{E.flush(l?.waitUntil).catch(()=>{})},onLog:(l,i)=>{E.add({event:l,kind:"log",resource:I(i)},i?.waitUntil)},onMetric:(l,i)=>{E.add({event:l,kind:"metric",resource:I(i)},i?.waitUntil)},onRpc:(l,i)=>{O(l,n)||E.add({endMs:Date.now(),event:l,kind:"rpc",resource:I(i)},i?.waitUntil)},onSpan:(l,i)=>{E.add({event:l,kind:"span",resource:I(i)},i?.waitUntil)}}},xr=(...r)=>{const e=(t,s)=>{for(const d of r){const n=d[t];if(n)try{n.apply(d,s)}catch{}}},o={};for(const t of r)for(const s of wr)o[s]===void 0&&t[s]!==void 0&&(o[s]=t[s]);return{...o,flush:t=>{e("flush",[t])},onLog:(t,s)=>{e("onLog",[t,s])},onMetric:(t,s)=>{e("onMetric",[t,s])},onRpc:(t,s)=>{e("onRpc",[t,s])},onSpan:(t,s)=>{e("onSpan",[t,s])}}};export{Rr as analyticsEngineSink,xr as combineSinks,Nr as consoleSink,_r as otlpSink,Mr as pipelineLogSink,Ar as sentrySink,Lr as webhookSink};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{resolveShard as u}from"@lunora/platform";const s=new WeakMap,n=o=>o===void 0?void 0:{locationHint:o},f=o=>typeof o.idFromName=="function",a=o=>{if(!f(o))return o;const e=o,i=s.get(o);if(i!==void 0)return i;const c=typeof e.jurisdiction=="function"?r=>a(e.jurisdiction(r)):void 0,d=typeof e.getByName=="function"?{get:(r,t)=>e.get(r,n(t)),getByName:(r,t)=>e.getByName(r,n(t)),idForName:r=>e.idFromName(r),jurisdiction:c}:{get:(r,t)=>e.get(r,n(t)),idForName:r=>e.idFromName(r),jurisdiction:c};return s.set(o,d),d},y=(o,e)=>{if(e===void 0)return o;if(typeof o.jurisdiction!="function")throw new TypeError(`@lunora/runtime: Durable Object namespace does not support jurisdiction("${e}") — update @cloudflare/workers-types or remove the jurisdiction option`);return o.jurisdiction(e)},p=(o,e,i)=>u(a(o),e,i);export{y as applyJurisdiction,p as resolveShard};
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as pr,toErrorBody as mr}from"@lunora/errors";import{e as tn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as wr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as gr,f as yr}from"./base64-Bl1_r2k1.mjs";import{i as br,e as _r,a as Rr,E as gt,d as Er}from"./identity-header-pR617HTs.mjs";import{O as yt,a as bt}from"./origin-paywall-B6eOO67m.mjs";import{o as ge,b as nn,p as Ar,m as Sr,d as Tr,a as Or,r as vr}from"./otlp-resource-BwFJnvwB.mjs";import{r as Ir,f as _t,a as ce,S as Rt}from"./observability-DgurIZIR.mjs";import{e as Ee,d as Ye,a as kr}from"./wire-codec-BLvSm5Mn.mjs";import{d as ee,e as ne,M as rn,b as Pr,f as Dr,g as on,w as Nr,h as an,t as Ur}from"./rest-routes-D3ShCTHh.mjs";import{LunoraError as c,toErrorResponse as Et}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as we}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as nt,BACKUP_KEY_PREFIX as rt,isBackupManifestKey as Cr,backupObjectKeyOfManifest as sn,backupObjectKey as Br,backupManifestKey as xr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Hr,buildStorageAdminRoutes as Lr,STORAGE_UPLOAD_MAX_BODY_BYTES as jr,STORAGE_PATH as Mr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as $r,e as Fr,f as At,g as Kr,h as Gr}from"./export-tap-CAyZ2TWC.mjs";import{buildHealthRoutes as Qr,durableObjectProbe as Wr,d1Probe as zr,presenceProbe as je}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as Vr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as xi,routeIdentityResolvers as Hi}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Jr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{pruneShardRegistry as Yr,createQueryCoordinator as qr,createDefaultShardRegistry as Xr}from"./createQueryCoordinator-BkZPoV26.mjs";import{resolveShard as ye,applyJurisdiction as Me}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as St,handleCorsPreflight as Zr,enforceOrigin as eo,decorateResponse as $e,enforceWebSocketOrigin as Tt}from"./decorateResponse-CRrFNW1v.mjs";const to=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},cn="__lunoraBranch",no=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,cn),ro=`may not contain the reserved workflow branch-marker key ("${cn}")`,oo=async e=>{const t=[];let n;for(;;){const o=await e(n);if(t.push(...Array.isArray(o.records)?o.records:[]),o.truncated!==!0||typeof o.cursor!="string"||o.cursor.length===0)return t;if(o.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=o.cursor}},ot=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,d=a<t.length?t.charCodeAt(a):0;o|=i^d}return o===0},ao=/already[\s_-]?exists/iu,so=e=>ao.test(e instanceof Error?e.message:String(e)),io=(e,t,n,o)=>{const a=e.get(t);if(a!==void 0)return a;tn(e,o);const i=n().catch(d=>{throw e.get(t)===i&&e.delete(t),d});return e.set(t,i),i},at=new TextEncoder,co=Array.from({length:32},(e,t)=>t);new RegExp(`[${co.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const uo=64,lo=new Map,dn=async e=>io(lo,e,async()=>crypto.subtle.importKey("raw",at.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),uo),un=async(e,t)=>{const n=await dn(e),o=await crypto.subtle.sign("HMAC",n,at.encode(t));return gr(new Uint8Array(o))},ho=async(e,t,n)=>{const o=await dn(e);return crypto.subtle.verify("HMAC",o,n,at.encode(t))},fo="cf-ray",po="x-lunora-ray-id",mo=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,wo=e=>e==null?void 0:mo.exec(e.trim())?.[1]?.toLowerCase(),go=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(go);const yo=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),bo=-100,_o=15,Ro=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&yo.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>_o?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<bo?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},Ot=e=>{const t=e.cf;return t===void 0?void 0:Ro(t)},qe="::relay::",Eo=(e,t)=>`${e}${qe}${String(t)}`,Xe="::replica::",Ao=(e,t)=>`${e}${Xe}${t}`,So=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},To=(e,t,n)=>e?.[n]??t?.[n],Oo=(e,t,n,o)=>{const a=To(e,t,n);if(!(typeof a!="object"||a===null))return o.every(i=>typeof a[i]=="function")?a:void 0},vo=new Set(["1","enabled","on","true","yes"]),Io=new Set(["0","disabled","false","no","off"]),ko=(e,t)=>{const n=(e??"").trim().toLowerCase();return vo.has(n)?!0:Io.has(n)?!1:t},ln="v1",Po=6e4,Do=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Po),o=`${ln}.${String(n)}`,a=await un(e,o);return{expiresAtMs:n,token:`${o}.${a}`}},No=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[a,i,d]=o;if(a!==ln||d.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let h;try{h=yr(d)}catch{return!1}return ho(e,`${a}.${i}`,h)},N="/_lunora/admin/auth",Uo={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},C=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},he=(e,t)=>{const n=e(t);if(n===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},hn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Fe=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},vt=e=>{const t=hn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},It=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[o,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[o]=a);return n},Co={[`${N}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${N}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${N}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${N}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${N}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${N}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${N}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${N}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${N}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${N}/sign-up-invitations/create`]:{build:({body:e})=>({email:C(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:te(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${N}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:C(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${N}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${N}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${N}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${N}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${N}/users/create`]:{build:({body:e})=>({data:Fe(e,"data"),email:C(e,"email"),name:C(e,"name"),password:te(e,"password"),role:hn(e.role)}),http:"POST",method:"createUser"},[`${N}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:C(e,"userId")}},http:"POST",method:"updateUser"},[`${N}/users/role`]:{build:({body:e})=>({role:vt(e),userId:C(e,"userId")}),http:"POST",method:"setRole"},[`${N}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:C(e,"userId")}),http:"POST",method:"banUser"},[`${N}/users/unban`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"unbanUser"},[`${N}/users/password`]:{build:({body:e})=>({newPassword:C(e,"newPassword"),userId:C(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${N}/users/remove`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${N}/users/impersonate`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"impersonateUser"},[`${N}/sessions/revoke`]:{build:({body:e})=>({sessionId:C(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${N}/sessions/revoke-all`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${N}/accounts/unlink`]:{build:({body:e})=>({accountId:C(e,"accountId"),userId:C(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${N}/two-factor/disable`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${N}/passkeys/delete`]:{build:({body:e})=>({passkeyId:C(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${N}/organizations/members/remove`]:{build:({body:e})=>({memberId:C(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${N}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:C(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${N}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Fe(e,"metadata"),name:C(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${N}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Fe(e,"metadata"),name:te(e,"name"),organizationId:C(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${N}/organizations/remove`]:{build:({body:e})=>({organizationId:C(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${N}/organizations/members/add`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),role:te(e,"role"),userId:C(e,"userId")}),http:"POST",method:"addMember"},[`${N}/organizations/members/invite`]:{build:({body:e})=>({email:C(e,"email"),inviterId:te(e,"inviterId"),organizationId:C(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${N}/organizations/members/role`]:{build:({body:e})=>({memberId:C(e,"memberId"),role:vt(e)}),http:"POST",method:"updateMemberRole"},[`${N}/organizations/teams/create`]:{build:({body:e})=>({name:C(e,"name"),organizationId:C(e,"organizationId")}),http:"POST",method:"createTeam"},[`${N}/organizations/teams/update`]:{build:({body:e})=>({name:C(e,"name"),teamId:C(e,"teamId")}),http:"POST",method:"updateTeam"},[`${N}/organizations/teams/remove`]:{build:({body:e})=>({teamId:C(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${N}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:C(e,"teamId"),userId:C(e,"userId")}),http:"POST",method:"addTeamMember"},[`${N}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:C(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${N}/organizations/roles/create`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),permission:It(e),role:C(e,"role")}),http:"POST",method:"createOrgRole"},[`${N}/organizations/roles/update`]:{build:({body:e})=>({permission:It(e),roleId:C(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${N}/organizations/roles/remove`]:{build:({body:e})=>({roleId:C(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Bo=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof c)throw i;const d=i,f=typeof d.code=="string"?d.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:f,status:Uo[f]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const d=e.getAuthAdmin();if(d===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=d[i.method];if(f===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const h=new URL(a.url),m={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:T=>e.queryParameter(h,T)},b=i.build(m),S=await t(()=>f(b));return Response.json(i.returns==="void"?{ok:!0}:S,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[a,i]of Object.entries(Co))o[a]=d=>n(d,i);return o},kt="__lunora_admin__:getAuthAuditLog",Pt=e=>typeof e=="string"&&e!==""?e:void 0,Dt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,xo=e=>async(n,o)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=Pt(o.actorId),d=Pt(o.event),f=Dt(o.sinceSeq),h=Dt(o.limit),m={...i===void 0?{}:{actorId:i},...d===void 0?{}:{event:d},...f===void 0?{}:{sinceSeq:f},...h===void 0?{}:{limit:h}};let b;try{b=await a.read(m)}catch(T){throw T instanceof c?T:(console.error("[lunora] auth audit read failed:",T),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const S={entries:b};return Response.json({result:Ee(S)},{headers:{"content-type":"application/json"},status:200})},Ze="__lunora_admin__:copyAuthToJurisdiction",fn="__lunora_admin__:purgeUnpinnedAuth",Ho=e=>async(t,n,o)=>{if(n!==Ze&&n!==fn)return;e.assertAdmin(t);const a=e.getMove();if(a===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===Ze?await a.copy({force:o.force===!0}):await a.purge();return Response.json({result:Ee(i)},{headers:{"content-type":"application/json"},status:200})},Lo=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?o.push(a):n.push(a);return{globalTables:o,shardLocalTables:n}},jo=async(e,t,n,o,a,i)=>{if(n!==void 0&&o.length===0)return[];const d=await e.orchestrateExport(a,{args:{tables:o},defaultShardKey:i,headers:t,tables:o}),f=d.shards.filter(h=>h.error);if(f.length>0){const h=f.map(m=>`${m.shardKey}: ${m.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(f.length)} of ${String(d.shards.length)} shard(s) — ${h}`,{code:"EXPORT_SHARD_FAILED",status:502})}return d.shards.flatMap(h=>h.rows??[])},pn=async(e,t,n,o,a)=>{const i=o??e.listSchemaTables?.();o===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:d,shardLocalTables:f}=Lo(e,i),h=await jo(t,n,i,f,a,e.defaultShardKey??"__root__"),m=e.exportGlobals,b=o===void 0||d.length>0;return(async function*(){yield*h,b&&m&&(yield*m({tables:d}))})()},Mo=async(e,t,n,o,a,i)=>{for await(const d of await pn(e,t,n,o,i))a(d)},$o=new TextEncoder,Fo=1e3,mn=10,Ko=200,Nt=8,wn="lunoraBackupCron",Ut=24*1048576,Ct=e=>{const t=e.slice(0,mn).map(o=>sn(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Go=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const a of e)n.set(a,o),o+=a.byteLength;return n},st=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let d=0;d<Fo;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)Cr(h.key)&&h.customMetadata?.[wn]===o&&a.push(h.key);if(!f.truncated||f.cursor===void 0)break;i=f.cursor}return{eligible:a.length,stale:a.toSorted((d,f)=>f.localeCompare(d)).slice(n)}},Qo=async(e,t,n,o,a)=>{const{stale:i}=await st(e,t,n,o),d=new Set(a),f=i.filter(k=>d.has(k)),h=f.slice(0,Ko),m=i.length-h.length,b=a.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:b,remaining:m};const S=[],T=[];for(let k=0;k<h.length;k+=Nt){const w=await Promise.allSettled(h.slice(k,k+Nt).map(async g=>(await e.delete(sn(g)),await e.delete(g),g)));for(const[g,y]of w.entries())y.status==="fulfilled"?S.push(y.value):T.push(h[k+g])}return S.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(S.length)}: ${Ct(S)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${Ct(T)}`),{deleted:S,failed:T,ignored:b,remaining:m}},Wo=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=nt(e.backupPrefix??rt),o=e.backupCron,{eligible:a,stale:i}=o===void 0?{eligible:0,stale:[]}:await st(t,n,e.backupRetain,o);return{cron:o,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},zo=async(e,t,n,o,a)=>{const i=e.backupStore;if(!i)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!o||o.length===0)throw new c("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const d={authorization:`Bearer ${o}`,"content-type":"application/json"},f=e.backupTables;let h=0,m=0,b=[];await Mo(e,t,d,f,I=>{const E=$o.encode(`${JSON.stringify(I)}
|
|
2
|
-
`);if(h+=1,m+=E.byteLength,m>Ut)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Ut)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});b.push(E)},n);const T=nt(e.backupPrefix??rt),k=new Date(a.scheduledTime).toISOString(),w=Br(T,k),g=Go(b,m);b=[];const y=Hr(await crypto.subtle.digest("SHA-256",g));await i.put(w,g,{httpMetadata:{contentType:"application/x-ndjson"},sha256:y});const v={bytes:m,createdAt:k,cron:a.cron,file:w,id:k,rows:h,scheduledTime:a.scheduledTime,sha256:y,...f?{tables:f.join(",")}:{}};await i.put(xr(w),`${JSON.stringify(v,void 0,2)}
|
|
3
|
-
`,{customMetadata:{[wn]:a.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:I}=await st(i,T,e.backupRetain,a.cron);if(I.length>0){const E=I.slice(0,mn),j=I.length-E.length;console.info(`[lunora] backup retention: ${String(I.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${E.join(", ")}${j>0?` (+${String(j)} more)`:""}`)}}catch(I){console.warn(`[lunora] backup ${w} was written, but the retention report failed:`,I)}},Vo=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const o=e.backupCron,a=e.backupRetain;if(o===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return Qo(n,nt(e.backupPrefix??rt),a,o,t)},Jo="/_lunora/admin/backup/retention",Yo="/_lunora/admin/backup/prune",qo=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,a=(f,h)=>{o(f,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${h} requires a \`backupStore\` on the worker`})},i=async f=>(M(f,"GET","Backup-retention"),a(f,"retention preview"),Response.json(await Wo(t),{headers:{"cache-control":"no-store"}})),d=async f=>{M(f,"POST","Backup-prune"),a(f,"prune");const{confirm:h}=await n(f);if(!Array.isArray(h)||h.some(m=>typeof m!="string"))throw new c("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await Vo(t,h),{headers:{"cache-control":"no-store"}})};return{[Yo]:d,[Jo]:i}},Bt=500,Xo=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const o=e;if(typeof o.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(o.functionPath.startsWith("__lunora_relation__:")||o.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(o.args!==void 0&&(typeof o.args!="object"||o.args===null||Array.isArray(o.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(o.id!==void 0&&typeof o.id!="number")throw new c("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:o.args===void 0?{}:o.args,baselineSeq:typeof o.baselineSeq=="number"?o.baselineSeq:void 0,clientId:typeof o.clientId=="string"?o.clientId:void 0,clientSeq:typeof o.clientSeq=="number"?o.clientSeq:void 0,functionPath:o.functionPath,id:typeof o.id=="number"?o.id:t,mutationId:typeof o.mutationId=="string"?o.mutationId:void 0},shardKey:typeof o.shardKey=="string"?o.shardKey:n}},Zo=(e,t)=>{if(e.length>Bt)throw new c(`RPC batch exceeds the ${String(Bt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,o=new Set;for(const[a,i]of e.entries()){const{entry:d,shardKey:f}=Xo(i,a,t);if(o.has(d.id))throw new c(`batch call id ${String(d.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});o.add(d.id);const h=n.get(f)??[];h.push(d),n.set(f,h)}return n},ea="/_lunora/admin/export",ta="/_lunora/admin/import",na="/_lunora/admin/sync",ra="/_lunora/admin/connector/sync",oa="/_lunora/admin/apply",aa="/_lunora/admin/export-tap/run",sa=new TextEncoder,ia=async e=>{const n=await ne(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const o=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});o.push(a)}return{tables:o}},Ke=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,ca=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:a,knownTables:i,queryCoordinator:d,assertAdmin:f,resolveForwardContext:h,shardDO:m,prepareExportRows:b,streamingImport:S,syncGlobals:T}=e,k=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const U=await ia(E),{headers:F}=await h(E,j),W=await b(F,U.tables),J=new ReadableStream({async pull(Y){try{for await(const G of W)Y.enqueue(sa.encode(`${JSON.stringify(G)}
|
|
4
|
-
`));Y.close()}catch(G){Y.error(G)}}});return new Response(J,{headers:{"content-type":"application/x-ndjson"},status:200})},w=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const U=await ee(E),F=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},W=typeof U.epochs=="object"&&U.epochs!==null?U.epochs:{},J=typeof U.limit=="number"?U.limit:void 0,Y=typeof U.globalCursor=="number"?U.globalCursor:0,G=Ke(U.tables),{headers:re}=await h(E,j),Q=G??i(),de=await d.orchestrateCdcSync(m,{cursors:F,defaultShardKey:n,epochs:W,headers:re,limit:J,tables:Q}),oe=T?await T({limit:J,sinceSeq:Y}):void 0;return Response.json({global:oe,shards:de.shards},{status:200})},g=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const U=await ee(E),F=Fr(U.cursor),W=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,J=Ke(U.tables),{headers:Y}=await h(E,j),G=J??i(),re=await d.orchestrateCdcSync(m,{cursors:F.s,defaultShardKey:n,headers:Y,limit:W,tables:G}),Q=[],de={...F.s};let oe=!1;for(const se of re.shards)oe=At(Q,se.changes??[],Gr(W))||oe,de[se.shardKey]=se.cursor;let be=F.g;if(T){const se=await T({limit:W,sinceSeq:F.g});oe=At(Q,se.changes,W)||oe,be=se.cursor}const z=Kr({g:be,s:de,v:1}),ae={changes:Q,hasMore:oe,nextCursor:z};return Response.json(ae,{status:200})},y=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const U=await ee(E),W=(Array.isArray(U.batches)?U.batches:[]).map(Q=>Q).filter(Q=>Q!==null&&typeof Q=="object"&&typeof Q.shardKey=="string"&&Array.isArray(Q.changes)),J=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:Y}=await h(E,j),G=await d.orchestrateApplyCdc(m,{batches:W,headers:Y}),re=J.length>0&&t?await t({changes:J}):0;return Response.json({applied:G.applied+re,failed:G.failed,ok:G.ok},{status:200})},v=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const{headers:U}=await h(E,j),F=await S(E,U);return Response.json(F,{headers:{"content-type":"application/json"},status:F.failed.length>0?207:200})},I=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;if(f(E),a===void 0||Object.keys(a).length===0||o===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const U=await ee(E),F=typeof U.sink=="string"?U.sink:void 0,W=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,J=Ke(U.tables);if(F===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const Y=a[F];if(Y===void 0)throw new c(`Export-tap sink "${F}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:G}=await h(E,j),re=J??i(),Q=await $r({coordinator:d,cursorStore:o,defaultShardKey:n,headers:G,limit:W,shardDO:m,sink:Y,tables:re});return Response.json(Q,{headers:{"content-type":"application/json"},status:200})};return{[oa]:y,[ra]:g,[ea]:k,[aa]:I,[ta]:v,[na]:w}},da=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const o=n;return typeof o.table!="string"||o.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!o.doc||typeof o.doc!="object"||Array.isArray(o.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:o.table},ok:!1}:{doc:o.doc,ok:!0,table:o.table}},ua=(e,t,n,o,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:o}},la=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const o=[],a=[],i=new Map;let d=0,f=0;const h=e.body.getReader(),m=new TextDecoder;let b="",S=0;const T=k=>{f+=1;const w=k.trim();if(w.length===0)return;d+=1;const g=da(w,f);if(!g.ok){o.push(g.error);return}const{doc:y,table:v}=g,I=t.resolveTableSharding?.(v);if(I?.mode.kind==="global"){a.push({doc:y,line:f,table:v});return}const E=ua(y,v,I,n,f);if(!E.ok){o.push(E.error);return}const j=i.get(E.shardKey);j?j.rows.push({doc:y,table:v}):i.set(E.shardKey,{rows:[{doc:y,table:v}],shardKey:E.shardKey,startLine:f})};for(;;){const{done:k,value:w}=await h.read();if(k)break;if(w&&(S+=w.byteLength,S>rn))throw await h.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});b+=m.decode(w,{stream:!0});let g=b.indexOf(`
|
|
5
|
-
`);for(;g!==-1;){const y=b.slice(0,g);b=b.slice(g+1),T(y),g=b.indexOf(`
|
|
6
|
-
`)}}return b.length>0&&T(b),{errors:o,globalRows:a,perShard:i,received:d}},ha=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),xt=(e,t)=>{for(const[n,o]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+o;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},fa=async(e,t,n,o,a)=>{const i=t.defaultShardKey??"__root__",{errors:d,globalRows:f,perShard:h,received:m}=await la(e,t,i),b={conflicts:0,errors:d,failed:[],inserted:{}},S=[];if(t.resolveTableSharding===void 0&&h.size>0&&S.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const T=await n.orchestrateImport(a,{batches:[...h.values()],headers:o});xt(b,T),b.failed.push(...ha(T.shards))}if(f.length>0)if(t.importGlobals){const T=f[0]?.line??1,k=await t.importGlobals({rows:f,startLine:T});xt(b,k)}else for(const T of f)b.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:T.line,message:`row targets global table "${T.table}" but no \`importGlobals\` is configured`,table:T.table});return{conflicts:b.conflicts,errors:b.errors,failed:b.failed,inserted:b.inserted,received:m,...S.length>0?{warnings:S}:{}}},pa=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),Ge=e=>typeof e=="object"&&e!==null?e:{},Qe=e=>typeof e.kind=="string"?e.kind:"unknown",ma=(e,t)=>{let n=Ge(t),o=!1;Qe(n)==="optional"&&(o=!0,n=Ge(n._meta?.inner));const a=Qe(n),i=n._meta??{},d={kind:a,name:e,optional:o};if(a==="id"&&typeof i.tableName=="string"&&(d.table=i.tableName),a==="array"){const f=Qe(Ge(i.inner));f!=="unknown"&&(d.element=f)}return d},wa=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>ma(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),ga="/_lunora/admin/functions",ya="/_lunora/admin/cron-jobs",ba="/_lunora/admin/architecture",_a="/_lunora/admin/openapi",Ra="/_lunora/admin/openrpc",Ea="/_lunora/admin/global/tables",Aa="/_lunora/admin/global/table",Sa="/_lunora/admin/global/facet",Ht=e=>{if(e===void 0||e==="")return;let t;try{t=Ye(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(o=>{if(typeof o!="object"||o===null||typeof o.column!="string")return[];const{column:a,value:i}=o;return[{column:a,value:i}]});return n.length===0?void 0:n},Ta=Object.freeze({info:{description:'No OpenAPI spec is configured on this worker. Run `lunora codegen`, then wire the generated module to `createWorker`: `import { openApiSpec } from "./lunora/_generated/openapi"`.',title:"Lunora API",version:"0.0.0"},openapi:"3.1.0",paths:{}}),Oa=Object.freeze({info:{description:'No OpenRPC spec is configured on this worker. Run `lunora codegen --api-spec openrpc` (or `both`), then wire the generated module to `createWorker`: `import { openRpcSpec } from "./lunora/_generated/openrpc"`.',title:"Lunora RPC",version:"0.0.0"},methods:[],openrpc:"1.3.2"}),va=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:a,requireAdminOption:i}=e,d=w=>{M(w,"GET","Functions");const g=i(w,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),y=Object.entries(g).flatMap(([v,I])=>I.visibility==="internal"||I.kind==="stream"?[]:[{args:wa(I.args),kind:I.kind,path:v}]).toSorted((v,I)=>v.path.localeCompare(I.path));return Response.json({functions:y},{headers:{"content-type":"application/json"},status:200})},f=w=>{M(w,"GET","Cron-jobs");const g=i(w,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),y=Object.entries(g).flatMap(([v,I])=>I.map(E=>({args:E.args,cron:v,functionPath:E.functionPath,name:E.name,shardKey:E.shardKey,workflow:E.workflow}))).toSorted((v,I)=>v.name.localeCompare(I.name));return Response.json({jobs:y},{headers:{"content-type":"application/json"},status:200})},h=w=>(M(w,"GET","Architecture"),t(w),Response.json(n.architecture??pa,{headers:{"content-type":"application/json"},status:200})),m=w=>(M(w,"GET","OpenAPI"),t(w),Response.json(n.openApiSpec??Ta,{headers:{"content-type":"application/json"},status:200})),b=w=>(M(w,"GET","OpenRPC"),t(w),Response.json(n.openRpcSpec??Oa,{headers:{"content-type":"application/json"},status:200})),S=async w=>{M(w,"GET","Global-tables");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await g.listTables(),{headers:{"content-type":"application/json"},status:200})},T=async w=>{M(w,"GET","Global-table");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),y=new URL(w.url),v=a(y,"table");if(v===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const I=await g.readTablePage({...o(w),filters:Ht(a(y,"filters")),table:v});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},k=async w=>{M(w,"GET","Global-facet");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),y=new URL(w.url),v=a(y,"table"),I=a(y,"column");if(v===void 0||I===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const E=a(y,"limit"),j=E===void 0?void 0:Number(E),H=await g.facetColumn({column:I,filters:Ht(a(y,"filters")),limit:j!==void 0&&Number.isFinite(j)?j:void 0,table:v});return Response.json(H,{headers:{"content-type":"application/json"},status:200})};return{[ya]:f,[ga]:d,[Sa]:k,[Aa]:T,[Ea]:S,[ba]:h,[_a]:m,[Ra]:b}},Ia="/_lunora/admin/kv/namespaces",ka="/_lunora/admin/kv/keys",gn="/_lunora/admin/kv/value",yn=32*1048576,Lt=60,Pa=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=w=>n(w,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=w=>Response.json(w,{headers:{"content-type":"application/json"},status:200}),i=(w,g)=>{const y=new URL(w.url),v=y.searchParams.get("namespace")??"",I=y.searchParams.get("key")??"";if(v==="")throw new c(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(I==="")throw new c(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:I,namespace:v}},d=async(w,g)=>{if(!(await w.listNamespaces()).some(v=>v.binding===g))throw new c(`Unknown KV namespace binding \`${g}\``,{code:"NOT_FOUND",status:404})},f=async w=>(M(w,"GET","KV-namespaces"),a({namespaces:await o(w).listNamespaces()})),h=async w=>{M(w,"GET","KV-keys");const g=o(w),y=new URL(w.url),v=y.searchParams.get("namespace")??"";if(v==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const I=y.searchParams.get("prefix")??void 0,E=y.searchParams.get("cursor")??void 0,j=y.searchParams.get("limit"),H=j===null?void 0:Number.parseInt(j,10);if(H!==void 0&&(!Number.isInteger(H)||H<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const U=H===void 0?void 0:Math.min(H,1e3);return await d(g,v),a(await g.listKeys({cursor:E,limit:U,namespace:v,prefix:I}))},T={DELETE:async w=>{const g=o(w),y=i(w,"DELETE");return await d(g,y.namespace),await g.deleteKey(y),a({deleted:!0})},GET:async w=>{const g=o(w),y=i(w,"GET");return await d(g,y.namespace),a(await g.getValue(y))},PUT:async w=>{const g=o(w),y=await t(w,yn);if(typeof y.namespace!="string"||y.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof y.key!="string"||y.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof y.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(y.expirationTtl!==void 0&&(typeof y.expirationTtl!="number"||!Number.isInteger(y.expirationTtl)||y.expirationTtl<Lt))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const v=Math.floor(Date.now()/1e3)+Lt;if(y.expiration!==void 0&&(typeof y.expiration!="number"||!Number.isInteger(y.expiration)||y.expiration<v))throw new c("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await d(g,y.namespace),await g.putValue({expiration:y.expiration,expirationTtl:y.expirationTtl,key:y.key,metadata:y.metadata,namespace:y.namespace,value:y.value}),a({ok:!0})}},k=w=>{const g=T[w.method];if(!g)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(w)};return{[Ia]:f,[ka]:h,[gn]:k}},Da="/_lunora/migrate",Na="/_lunora/admin/pitr",Ua="/_lunora/admin/rank",Ca="/_lunora/admin/rankpage",Ba="/_lunora/admin/shard-registry/prune",xa="/_lunora/admin/shard-traffic",Ha=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),La=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),ja=async e=>{const n=await ne(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!Ha.has(n.functionPath))throw new c("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},Ma=async e=>{const n=await ne(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new c("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new c("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new c("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new c("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},$a=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new c('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Fa=e=>{if(typeof e.table!="string"||e.table.length===0)throw new c("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new c("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new c("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new c("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new c("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Ka=async e=>{const n=await ne(e,"Rank page")??{};Fa(n);const o=$a(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:o,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},Ga=async e=>{const n=await ne(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},Qa=async e=>{const n=await ne(e,"Shard-registry prune")??{};if(n.tables!==void 0&&!(Array.isArray(n.tables)&&n.tables.every(o=>typeof o=="string")))throw new c("Shard-registry prune `tables` must be an array of table names",{code:"BAD_REQUEST",status:400});return{dryRun:n.dryRun===!0,tables:n.tables}},Wa=async e=>{const n=await ee(e);if(typeof n.functionPath!="string"||!La.has(n.functionPath))throw new c("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new c("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},za=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:a,resolveForwardContext:i,shardDO:d,shardedTables:f}=e,h=(g,y)=>{if(g.method!=="POST")throw new c(`${y} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(g))throw new c("Admin auth required",{code:"FORBIDDEN",status:403})},m=async(g,y)=>{h(g,"Migration");const v=await ja(g),{headers:I}=await i(g,y),E=await a.orchestrateMigration(d,{args:v.args,defaultShardKey:t,functionPath:v.functionPath,headers:I,table:v.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},b=async(g,y)=>{h(g,"Rank");const v=await Ma(g),{headers:I}=await i(g,y),E=await a.orchestrateRank(d,{headers:I,index:v.index,partitionKey:v.partitionKey,rowId:v.rowId,sortValues:v.sortValues,table:v.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},S=async(g,y)=>{h(g,"Rank page");const v=await Ka(g),{headers:I}=await i(g,y),E=await a.orchestrateRankPage(d,{...v,headers:I});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},T=async(g,y)=>{h(g,"Shard-traffic");const v=await Ga(g),{headers:I}=await i(g,y),E=await a.orchestrateShardTraffic(d,{headers:I,table:v.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},k=async(g,y)=>{h(g,"Shard-registry prune");const v=await Qa(g),I=f(),E=(v.tables??[]).filter(U=>!I.includes(U));if(E.length>0)throw new c(`Shard-registry prune names tables that are not \`.shardBy()\`: ${E.join(", ")}`,{code:"BAD_REQUEST",status:400});const{headers:j}=await i(g,y),H=await Yr(a.registry,d,{dryRun:v.dryRun,headers:j,tables:v.tables??I});return Response.json(H,{status:H.failed.length>0?207:200})},w=async(g,y)=>{if(M(g,"POST","PITR"),!o(g))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const v=await Wa(g),{headers:I}=await i(g,y),E=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:v.args,functionPath:v.functionPath}),headers:I,method:"POST"});return n(d,v.shardKey??t,E)};return{[Da]:m,[Na]:w,[Ua]:b,[Ca]:S,[Ba]:k,[xa]:T}},Va=1,Ja=0,Ya=32,qa=512,Xa=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Za=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>qa)return;const n=t.split(",");if(!(n.length>Ya)){for(const o of n)if(!Xa.test(o.trim()))return;return t}},es=e=>{const t=Ar(e.headers.get("traceparent"));if(t===void 0)return;const n=Za(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},jt=(e,t={})=>{const n=es(e),o=t.trustInbound===!0?n:void 0,a=ge(8),i=o?.traceId??ge(16),d=Ir(t.sampling,o===void 0?a:i),{rayId:f}=t,h=d.isTraced&&(o===void 0||o.sampled);return{decision:d,ignoredUpstream:n!==void 0&&o===void 0,trace:{sampled:h,spanId:a,traceFlags:h?Va:Ja,traceId:i,...o?.parentSpanId===void 0?{}:{parentSpanId:o.parentSpanId},...o?.traceState===void 0?{}:{traceState:o.traceState},...f===void 0?{}:{rayId:f}}}},Mt=(e,t)=>{t.traceparent=nn(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState),e.rayId!==void 0&&(t[po]=e.rayId)},ts=(e,t)=>{let n;return()=>{if(n===void 0){const o=vr(e),a=t===void 0?void 0:t.cf;n=Sr(Or(o),Tr(o,a))}return n}},ns="/_lunora/admin/scheduled",rs="/_lunora/admin/scheduled/status",os="/_lunora/admin/scheduled/ws",as="/_lunora/admin/scheduled/cancel",ss="/_lunora/admin/scheduled/dead",is="/_lunora/admin/scheduled/dead/retry",cs="/_lunora/admin/scheduled/dead/cancel",ds="/_lunora/admin/scheduled/pool/release",us=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:a}=e,i=(m,b)=>S=>{if(S.method!=="GET")throw new c(`${b} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(S.url).searchParams.get("cursor"),k=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return o(S).fetch(new Request(`https://scheduler.internal${m}${k}`,{method:"GET"}))},d=(m,b,S=b)=>async T=>{if(T.method!=="POST")throw new c(`${S} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const k=o(T),w=await ne(T,b);if(typeof w?.id!="string"||w.id==="")throw new c(`${b} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return k.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))},f=async m=>{if(m.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const b=o(m),S=await ne(m,"Scheduled pool-release");if(typeof S?.pool!="string"||S.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const T=typeof S.id=="string"&&S.id!==""?S.id:void 0;return b.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(T===void 0?{pool:S.pool}:{id:T,pool:S.pool}),headers:{"content-type":"application/json"},method:"POST"}))},h=async m=>{if(m.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(m))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const b=n();return ye(b,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[as]:d("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[cs]:d("/dead/cancel","Scheduled dead-letter action"),[ss]:i("/dead","Scheduled dead-letter"),[is]:d("/dead/retry","Scheduled dead-letter action"),[ns]:i("/list","Scheduled-list"),[ds]:f,[rs]:i("/status","Scheduler-status"),[os]:h}},ls="/_lunora/scheduled",bn="/_lunora/queue",_n=16*1048576,hs=e=>{const{assertAdmin:t,dispatchScheduled:n,queueHandler:o}=e,a=async(d,f,h)=>{if(t(d),d.method!=="POST")throw new c("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const m=await ne(d,"Scheduled tick"),b=typeof m?.cron=="string"?m.cron:"";if(b==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:b,noRetry:()=>{},scheduledTime:Date.now()},f,h),Response.json({cron:b,ok:!0})},i=async(d,f,h)=>{if(t(d),d.method!=="POST")throw new c("queue dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!o)throw new c("no queueHandler configured",{code:"BAD_REQUEST",status:400});const m=await ne(d,"Queue dispatch",_n);if(!Array.isArray(m?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const b=typeof m.queue=="string"?m.queue:"",S=m.messages.filter(k=>typeof k=="object"&&k!==null&&typeof k.id=="string").map(k=>({body:k.body,id:k.id})),T=await o({messages:S,queue:b},f,h);return Response.json({retry:T?.retry??[]})};return{[bn]:i,[ls]:a}},fs=(e,...t)=>{let n=e.cf;for(const o of t){if(typeof n!="object"||n===null)return;n=n[o]}return typeof n=="string"?n:void 0},et={mtls:e=>fs(e,"tlsClientAuth","certVerified")==="SUCCESS"},ps=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(et,e)?et[e]:void 0)??(()=>!1),ms=e=>typeof e=="string"&&Object.hasOwn(et,e),ws=e=>{const t=ms(e)?e:void 0;if(e!==void 0&&t===void 0)return()=>{};let n=!1;return o=>{n||t!==void 0&&o.cf!==void 0||(n=!0,console.warn(t===void 0?'[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.':`[lunora] \`trustInboundTraceContext: "${t}"\` cannot be satisfied on this host: the request carries no platform-injected \`cf\` metadata, which is what that signal reads, so every inbound \`traceparent\` is ignored and this request starts a new trace. Off Cloudflare, trust the upstream some other way — \`trustInboundTraceContext: true\` when nothing untrusted can reach this worker, or a predicate that verifies whatever your own front door sets. Set it to \`false\` to keep this behaviour and silence this message.`))}},gs="/_lunora/admin/vector/indexes",ys="/_lunora/admin/vector/query",bs=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=async i=>{M(i,"GET","Vector-indexes");const d=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await d.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async i=>{M(i,"POST","Vector-query");const d=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(d.queryIndex===void 0)throw new c("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const h=await t(i);if(typeof h.name!="string"||h.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof h.text!="string"||h.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(h.topK!==void 0&&(typeof h.topK!="number"||!Number.isInteger(h.topK)||h.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const m=await d.queryIndex({name:h.name,text:h.text,topK:h.topK});return Response.json(m,{headers:{"content-type":"application/json"},status:200})};return{[gs]:o,[ys]:a}},_s="/_lunora/admin/workflows/instances",Rs="/_lunora/admin/workflows/instance",Es="/_lunora/admin/workflows/status",As={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Ss=e=>e!==null&&Object.hasOwn(As,e)?e:void 0,$t=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const o=Number(n);return Number.isInteger(o)&&o>0?o:void 0},We=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new c(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},Ft=()=>{throw new c("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Ts=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,o=async(d,f,h)=>{M(d,"GET","Workflows instances"),t(d);const m=n(f);if(!m)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const b=We(h,"name"),S=Ss(h.searchParams.get("status"));return Response.json(await m.listInstances({page:$t(h,"page"),perPage:$t(h,"perPage"),status:S,workflowName:b}))},a=async(d,f,h)=>{M(d,"GET","Workflows instance"),t(d);const m=n(f);return m?Response.json(await m.getInstance({instanceId:We(h,"id"),workflowName:We(h,"name")})):Ft()},i=async(d,f)=>{M(d,"POST","Workflows status"),t(d);const h=n(f);if(!h)return Ft();const m=await ne(d,"Workflows status");if(typeof m?.name!="string"||m.name===""||typeof m.id!="string"||m.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:b}=m;if(b!=="pause"&&b!=="resume"&&b!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await h.setInstanceStatus({action:b,instanceId:m.id,workflowName:m.name}))};return{[Rs]:a,[_s]:o,[Es]:i}},Os={[gn]:yn,[bn]:_n,[Mr]:jr},Kt="/_lunora/rpc",vs="/_lunora/rpc-batch",Is="/_lunora/ws",Re=(e,t,n)=>({resourceAttributes:ts(e,t),...n===void 0?{}:{waitUntil:n}}),ze=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Gt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ve=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0,o=wo(e.headers.get(fo)),a=o===void 0?{}:{rayId:o};let i;try{i=new URL(e.url)}catch{return{method:t,...a,userAgent:n}}const d=i.port===""?void 0:Number(i.port);return{host:i.hostname,method:t,path:i.pathname,port:Number.isNaN(d)?void 0:d,...a,scheme:i.protocol.replace(":",""),userAgent:n}},Qt="/_lunora/voice/",ks="/_lunora/scheduler/dispatch",Ps="/_lunora/admin/cron-jobs/run",Ds="/_lunora/admin/ws-token",Ns="/_lunora/admin/",Ne="/_lunora/",Us="/_lunora/migrate",Cs="/_lunora/status",Bs=e=>e.startsWith(Ns)||e===Us,xs="__lunora_relation__:",ve=e=>{if(e.startsWith(xs))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Ie=async e=>await e===!0,Wt=(e,t)=>{const n=e.headers.get(gt);if(n===null)return;const o=Er(n);if(o===void 0)throw new c(`malformed ${gt} header`,{code:"BAD_REQUEST",status:400});if(o.subject!==(t?.userId??null))throw new c("the session changed since this write was queued",{code:"IDENTITY_MISMATCH",status:409})},Hs=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},zt="/api/auth",Ls="__lunora_admin__:recordAuthEvent",Vt="__lunora_admin__:listPushSubscriptions",js=["/sign-in","/sign-up","/callback"],Ms=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return js.some(a=>o===a||o.startsWith(`${a}/`))},Jt=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},ke=(e,t,n,o)=>{const a=pr(n),i=a?n.code:"INTERNAL_SERVER_ERROR",d=a?n.status:500,f=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:f,status:d},functionPath:e,ok:!1,...o.fanOut?{fanOut:{failed:0,shards:0,table:o.fanOut.table}}:{},...o.shardKey?{shardKey:o.shardKey}:{}}},Rn=e=>{const{exp:t,expiresAtMs:n}=e;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},En=({identity:e})=>e!==null&&br(Rn(e)),$s=e=>{if(En(e))throw new c("authentication token expired",{code:"TOKEN_EXPIRED",status:401});return e},Fs=e=>{if(!En(e))return e;const t={...e.headers};return delete t["x-lunora-identity"],delete t["x-lunora-identity-exp"],delete t["x-lunora-userid"],{claims:null,headers:t,identity:null,userId:null}},Yt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Ks=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},tt=new WeakMap,Gs=async(e,t,n,o,a=tt.get(e))=>{const i={"content-type":"application/json"},d=e.headers.get("authorization"),f=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),m=e.headers.get("x-lunora-mutation-id"),b=e.headers.get("x-lunora-client-id"),S=e.headers.get("x-lunora-client-seq"),T=e.headers.get("x-lunora-base-seq");d&&(i.authorization=d),f&&(i.cookie=f),h&&(i["x-d1-bookmark"]=h),m&&(i["x-lunora-mutation-id"]=m),b&&(i["x-lunora-client-id"]=b),S&&(i["x-lunora-client-seq"]=S),T&&(i["x-lunora-base-seq"]=T);const k=Ur(e.headers,o);if(k&&(i["x-lunora-client-ip"]=k),i["x-lunora-origin"]=new URL(e.url).origin,!n)return{claims:null,headers:i,identity:null,userId:null};const w=await n(e,t,a);if(!w||typeof w.userId!="string"||w.userId.length===0)return{claims:null,headers:i,identity:null,userId:null};i["x-lunora-userid"]=_r(w.userId);const g=Rn(w);g!==void 0&&(i["x-lunora-identity-exp"]=String(g));const{userId:y,...v}=w,I=Object.keys(v).length>0?v:null;return I&&(i["x-lunora-identity"]=Rr(I)),{claims:I,headers:i,identity:w,userId:y}},Qs=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Ws=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new c("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new c("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new c("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!Qs.has(n.kind))throw new c("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new c("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new c("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},zs=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},Je=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new c("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new c(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},Vs=async e=>{const t=await an(e);let n;try{n=JSON.parse(t)}catch{throw new c("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new c("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const o=n;if(o.args!==void 0&&on(o.args,"RPC"),o.shardKey!==void 0&&typeof o.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,i=Ws(a.fanOut),d=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const f=d.table;if(typeof f=="string"&&f!==i.table)throw new c("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});d.table=i.table}return{args:d,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},Pe=new Map,Js=5e3,Ys=4096,qs=async(e,t)=>{const n=Date.now(),o=Pe.get(t);if(o!==void 0&&o.expiresMs>n)return o.relayCount;o!==void 0&&Pe.delete(t);let a=0;try{const i=await ye(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const f=(await i.json()).relayCount;typeof f=="number"&&f>0&&(a=Math.floor(f))}}catch{a=0}return tn(Pe,Ys),Pe.set(t,{expiresMs:n+Js,relayCount:a}),a},qt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},De=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),Xs=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],Zs=(e,t)=>{for(const n of Xs){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},Xt=(e,t)=>{const n=new Headers(e.headers),o=[...n.keys()];for(const a of o)a.startsWith("x-lunora-")&&n.delete(a);return Zs(n,t),n},ei=async(e,t,n)=>e.length===0||n.length===0?!1:ot(await un(e,t),n),Zt=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[o,...a]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:ot(t,a.join(" ").trim())},en=async(e,t,n)=>{if(!t||t.length===0)return!1;const o=new URL(e.url).searchParams.get("token");return o===null?!1:await No(t,o)?!0:n?!1:ot(t,o)},ti=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return zr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return je(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return je(`queue:${e}`,!0);if(typeof n.connectionString=="string")return je(`hyperdrive:${e}`,!0)},ni=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(Ne))throw new c(`route "${t}" is under the reserved ${Ne} prefix, which the framework owns. App routes registered there shadow the internal endpoint AND its admin gate — pick a path outside the prefix.`,{code:"MISCONFIGURED",status:500})},ri=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new c("`x402Charge` requires `functions`: paid (.x402) procedures are read from the function registry, so without it every paid procedure would dispatch FREE. Build the worker with `defineApp()` (which supplies the registry) or pass `functions` explicitly.",{code:"MISCONFIGURED",status:500})},An=e=>{ri(e);const t=ps(e.trustInboundTraceContext),n=ws(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",a=e.queryCoordinator??qr({registry:Xr(e.resolveTableSharding,o)}),i=Vr(e.resolveIdentity,e.identity),d=Me(e.shardDO,e.jurisdiction),f=e.schedulerDO===void 0?void 0:Me(e.schedulerDO,e.jurisdiction),h=e.voiceAgents===void 0?void 0:Object.fromEntries(Object.entries(e.voiceAgents).map(([r,s])=>[r,Me(s,e.jurisdiction)]));let m=!1;const b=r=>{if(r===void 0||e.jurisdiction===void 0)return r;m||(m=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},S=async(r,s,l,u=e.shardRegion?.(s))=>ye(r,s,b(u)).fetch(l);let T;const k=()=>e.adminToken??T;let w;const g=()=>e.requireEphemeralWsToken??w??!0;let y;const v=r=>{const s=r??{};if(y??=qt(r,e.shardDO),w===void 0&&e.requireEphemeralWsToken===void 0){const u=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof u=="string"&&u.length>0&&(w=ko(u,!0))}if(T!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(T=l)},I=new WeakSet,E=r=>Zt(r,k())||I.has(r),j=async r=>{if(!(e.adminGate===void 0||I.has(r)))try{await Ie(e.adminGate(r,tt.get(r)))&&I.add(r)}catch{}},H=async(r,s,l,u)=>{const p=await Gs(r,s,l,e.trustedClientIpHeader,u);return e.functions!==void 0&&(p.headers[bt]=yt),p},U=async(r,s,l,u)=>$s(await H(r,s,l,u)),F=async(r,s)=>{const l=await H(r,s,e.resolveIdentity);if(I.has(r)&&l.headers.authorization===void 0){const u=k();u!==void 0&&(l.headers.authorization=`Bearer ${u}`)}return l};let W=!1,J=!1;const Y=()=>{J||(J=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},G=r=>{if(!e.allowUnauthenticatedShardAccess){const s=r==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${r} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${r} access (relying solely on per-row RLS).`,{code:r==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}W||(W=!0,console.warn([`[lunora] SECURITY: serving ${r} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},re=async(r,s,l=!1)=>{if(s.includes(qe)||s.includes(Xe))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(!l)if(e.authorizeShard){if(!await Ie(e.authorizeShard({identity:r,shardKey:s})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==o&&G("shard")},Q=za({defaultShard:o,forwardToShard:S,isAdmin:E,queryCoordinator:a,resolveForwardContext:F,shardDO:d,shardedTables:()=>(e.listSchemaTables?.()??[]).filter(r=>e.resolveTableSharding?.(r)?.mode.kind==="shardBy")}),de=async(r,s,l,u,p,R)=>{ve(r);const O={"content-type":"application/json",[bt]:yt,"x-lunora-system":"1"};return p?.userId!==void 0&&p.userId.length>0&&(O["x-lunora-userid"]=p.userId),p?.identity!==void 0&&p.identity.length>0&&(O["x-lunora-identity"]=p.identity),u!==void 0&&u.length>0&&(O["x-lunora-mutation-id"]=u),R!==void 0&&R.length>0&&(O.traceparent=R),S(d,l,De(r,s,O))},oe=async(r,s,l,u,p)=>{const R=Oo(l.env,l.context?.exports,r,["create"]);if(R===void 0)throw new c(`${u} targets workflow "${r}", which is on neither ctx.exports nor env`,{code:"CRON_JOB_FAILED",status:500});if(no(s))throw new c(`${u} params ${ro}`,{code:"BAD_REQUEST",status:400});try{await R.create(p===void 0?{params:s}:{id:p,params:s})}catch(O){if(!so(O))throw O}},be=async(r,s,l,u)=>{if(r.workflow){await oe(r.workflow,r.args??{},{context:l,env:s},`cron job "${r.name}"`);return}if(r.functionPath===void 0)throw new c(`cron job "${r.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const p=await de(r.functionPath,r.args??{},r.shardKey??o,void 0,void 0,u);if(!p.ok)throw new c(`cron job "${r.name}" (${r.functionPath}) failed with shard status ${String(p.status)}`,{code:"CRON_JOB_FAILED",status:500})},z=r=>{if(!E(r))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},ae=(r,s,l)=>{if(z(r),s===void 0)throw new c(l.message,{code:l.code,status:400});return s},se=async(r,s,l,u,p,R)=>{const O=e.cronJobs?.[r];if(!O)return 0;for(const P of O)try{await be(P,s,l,R)}catch(D){u.push(p(D))}return O.length},Sn=async(r,s,l)=>{if(z(r),M(r,"POST","cron-jobs run"),!e.cronJobs)throw new c("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const u=await ee(r),p=typeof u.name=="string"?u.name:"";if(p==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const R=Object.values(e.cronJobs).flat().find(O=>O.name===p);if(!R)throw new c(`no cron job named "${p}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await be(R,s,l),Response.json({name:p,ran:!0},{status:200})},it=async r=>{const s=typeof r.pool=="string"&&r.pool.length>0?r.pool:void 0;if(!s||!f||typeof r.id!="string")return;const l=typeof r.instanceName=="string"&&r.instanceName.length>0?r.instanceName:"default";try{await ye(f,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:r.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Tn=async(r,s,l)=>{M(r,"POST","Scheduler dispatch");const u=await an(r),p=s??{},R=typeof p.LUNORA_SCHEDULER_SECRET=="string"?p.LUNORA_SCHEDULER_SECRET:void 0,O=e.adminToken??(typeof p.LUNORA_ADMIN_TOKEN=="string"?p.LUNORA_ADMIN_TOKEN:void 0),P=r.headers.get("x-lunora-scheduler-signature");let D=!1;if(P&&R?D=await ei(R,u,P):O&&(D=Zt(r,O)),!D)throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let A;try{A=JSON.parse(u)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const _=A??{},B=_.args??{},L=typeof _.id=="string"&&_.id.length>0?_.id:void 0;if(typeof _.workflow=="string"&&_.workflow.length>0)return await oe(_.workflow,B,{context:l,env:s},"scheduled workflow",L),await it(_),Response.json({ok:!0},{status:200});if(typeof _.functionPath!="string"||_.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const V=typeof _.shardKey=="string"&&_.shardKey.length>0?_.shardKey:o,x=Hs(r),ue=await de(_.functionPath,B,V,L,x,r.headers.get("traceparent")??void 0);return await it(_),ue},On=xo({assertAdmin:z,getReader:()=>e.authAuditReader}),vn=Ho({assertAdmin:z,getMove:()=>e.authJurisdictionMove}),In=async(r,s)=>{z(r);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:Ee({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const u=s?.kind,p=s?.userId,R=s?.limit,O=u==="fcm"||u==="web-push"?u:void 0,P=typeof p=="string"&&p!==""?p:void 0,D=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,A=D>0?Math.min(D,1e3):1e3,B=(await l.list({kind:O,limit:A,userId:P})).filter(L=>O!==void 0&&L.kind!==O?!1:P===void 0||(L.userId??null)===P).map(({keys:L,token:V,...x})=>x);return Response.json({result:Ee({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},kn=async(r,s)=>{if(!s.fanOut&&!(s.functionPath!==kt&&s.functionPath!==Vt&&s.functionPath!==Ze&&s.functionPath!==fn))return await j(r),s.functionPath===kt?On(r,s.args??{}):s.functionPath===Vt?In(r,s.args):vn(r,s.functionPath,s.args??{})},Pn=ca({applyGlobals:e.applyGlobals,assertAdmin:z,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:o,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:a,resolveForwardContext:F,shardDO:d,prepareExportRows:async(r,s)=>pn(e,a,r,s,d),streamingImport:(r,s)=>fa(r,e,a,s,d),syncGlobals:e.syncGlobals}),Ue=(r,s)=>{const l=r.searchParams.get(s);return l===null||l===""?void 0:l},Ce=r=>{const s=new URL(r.url),l=s.searchParams.get("limit"),u=s.searchParams.get("offset"),p=l===null?void 0:Number.parseInt(l,10),R=u===null?void 0:Number.parseInt(u,10);return{limit:p!==void 0&&Number.isFinite(p)&&p>=0?p:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},ct=()=>{if(f===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return f},Dn=us({checkWsAdmin:async r=>E(r)||en(r,k(),g()),requireSchedulerNamespace:ct,resolveSchedulerStub:r=>(z(r),ye(ct(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Nn=Ts({assertAdmin:z,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Un=Lr({assertAdmin:z,parsePaging:Ce,queryParameter:Ue,readBodyBytes:Dr,requireAdminOption:ae,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Cn=qo({options:e,readJsonBody:ee,requireAdminOption:ae}),Bn=bs({readJsonBody:ee,requireAdminOption:ae,vectorIntrospector:e.vectorIntrospector}),xn=Pa({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:ae}),Hn=Jr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:ae}),Ln=va({assertAdmin:z,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,architecture:e.architecture,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ce,queryParameter:Ue,requireAdminOption:ae}),jn=r=>{const s=[],l=d??r?.SHARD;if(l!==void 0&&s.push(Wr("durable-object:default",l,o)),e.health?.disableBindingProbes!==!0)for(const[u,p]of Object.entries(r??{})){const R=ti(u,p);R!==void 0&&s.push(R)}for(const u of e.health?.probes??[])s.push(u);return s},Mn=Qr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:E,resolveProbes:jn}),$n=r=>{const s=A=>"args"in A?{...A,args:Ye(A.args)}:A,l=e.schedulerInstanceName??"default",u=()=>ye(r,l),p=async(A,_)=>{const B=await u().fetch(new Request(`https://scheduler.internal${A}`,_));if(!B.ok)throw new c(`ctx.scheduler: SchedulerDO ${A} failed (${String(B.status)}): ${await B.text()}`,{code:"INTERNAL",status:500});return await B.json()},R=async(A,_)=>await p(A,{body:JSON.stringify(_),headers:{"content-type":"application/json"},method:"POST"}),O=A=>{const _=A;if(_==null)throw new c("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof _.binding=="string"&&_.binding.length>0)return{workflow:_.binding};if(typeof _.__lunoraRef=="string")return{functionPath:_.__lunoraRef};throw new c("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},P=async()=>(await oo(async _=>p(_===void 0?"/list":`/list?cursor=${encodeURIComponent(_)}`,{method:"GET"}))).map(_=>s(_)),D=async(A,_,B={})=>{const L=O(_),{id:V}=await R("/schedule",{args:kr("ctx.scheduler",String(L.functionPath??L.workflow),B),scheduledFor:Math.ceil(A),...L});return V};return{cancel:async A=>await R("/cancel",{id:A}),get:async A=>{const _=await p(`/get?id=${encodeURIComponent(A)}`,{method:"GET"});return _.record===void 0?null:s(_.record)},list:P,runAfter:async(A,_,B)=>{if(!Number.isFinite(A)||A<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await D(Date.now()+A,_,B)},runAt:async(A,_,B)=>{if(!Number.isFinite(A))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await D(A,_,B)}}},Fn=async(r,s,l)=>{const{claims:u,headers:p,userId:R}=Fs(await H(r,s,i)),O=Re(s,r,A=>l.waitUntil?.(A)),P=A=>async(_,B={})=>{const L=_.__lunoraRef;if(typeof L!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ve(L);const V=await Se(r,L,Ee(B),A,{...p,"x-lunora-system":"1"},O),x=await V.json();if(x.error)throw new c(x.error.message??"shard RPC failed",{code:x.error.code??"INTERNAL",status:V.status});return Ye(x.result)},D=P(o);return{auth:{getIdentity:()=>Promise.resolve(u),userId:R},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),forShard:A=>{const _=P(A);return{runAction:_,runMutation:_,runQuery:_}},runAction:D,runMutation:D,runQuery:D,...f===void 0?{}:{scheduler:$n(f)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:to(e.storage(s,new URL(r.url).origin))}}},Kn=async(r,s,l)=>{if(!e.httpRouter)return;const u=await Fn(r,s,l);try{return await e.httpRouter.fetch(r,{...s,__lunoraCtx:u},l)}catch(p){return console.error("[lunora] httpRouter (SSR) handler threw:",p),new Response("Internal Server Error",{status:500})}},Gn=async(r,s,l)=>{if(r.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const u=Tt(r,ie);if(u)return u;const p=l.searchParams.get("shard")??o,{headers:R,identity:O}=await H(r,s,i),P=E(r)||await en(r,k(),g());await re(O,p,P);const D=Xt(r,R),A=qt(s,e.shardDO);if(A!==void 0){D.set("x-lunora-shard-binding",A);const _=await qs(d,p);if(_>0){const B=Eo(p,Math.floor(Math.random()*_));return S(d,B,new Request(r,{headers:D}),Ot(r))}}return S(d,p,new Request(r,{headers:D}))},Qn=async(r,s,l)=>{if(h===void 0)return new Response("Not found",{status:404});if(r.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const u=Tt(r,ie);if(u)return u;let p;try{p=decodeURIComponent(l.pathname.slice(Qt.length))}catch{return new Response("Unknown voice agent",{status:404})}const R=Object.hasOwn(h,p)?h[p]:void 0;if(R===void 0)return new Response("Unknown voice agent",{status:404});const O=l.searchParams.get("threadKey");if(O===null||O.length===0)return new Response("Missing threadKey",{status:400});const{headers:P,identity:D}=await H(r,s,i);if(e.authorizeShard){if(!await Ie(e.authorizeShard({identity:D,shardKey:O})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else G("shard");const A=Xt(r,P);return S(R,O,new Request(r,{headers:A}))},Wn=async(r,s,l)=>{if(e.authorizeFanOut){if(!await Ie(e.authorizeFanOut(l,r.table,s)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new c("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});G("fan-out")},Ae=async(r,s)=>{if(!(!r.fanOut&&r.functionPath.startsWith("__lunora_admin__:"))){if(r.fanOut){await Wn(r.fanOut,r.functionPath,s);return}await re(s,r.shardKey??o)}},zn=(r,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){Y();return}if(e.functions[s]?.kind!=="query"||l.includes(Xe)||l.includes(qe))return;const u=Ot(r);return u===void 0?void 0:{name:Ao(l,u),region:u}},Vn=async(r,s,l,u,p)=>{const R=zn(r,s,u);if(R!==void 0){const O={...p,"x-lunora-replica-read":"1",...y===void 0?{}:{"x-lunora-shard-binding":y}},P=So(r.headers.get("x-lunora-min-seq"));P!==void 0&&(O["x-lunora-min-seq"]=String(P));const D=await S(d,R.name,De(s,l,O),R.region);if(D.status!==421)return D}return S(d,u,De(s,l,p))},Se=async(r,s,l,u,p,R)=>{const O=Date.now(),{observability:P,sampling:D}=e,A=Ve(r),{decision:_,ignoredUpstream:B,trace:L}=jt(r,{...A.rayId===void 0?{}:{rayId:A.rayId},...D===void 0?{}:{sampling:D},trustInbound:t(r)});B&&n(r);const V={...p,[Rt]:_.keepErrors?"1":"0"};Mt(L,V);try{const x=await Vn(r,s,l,u,V);ce(P,{...A,...Gt(L),durationMs:Date.now()-O,functionPath:s,ok:x.ok,shardKey:u,...x.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(x.status)}`,status:x.status}}},R,void 0,{isTraced:L.sampled,keepErrors:_.keepErrors});const ue=new Response(x.body,{headers:x.headers,status:x.status,statusText:x.statusText});return ue.headers.set("x-lunora-shard-key",u),ue}catch(x){throw ce(P,{...A,...Gt(L),...ke(s,Date.now()-O,x,{shardKey:u})},R,void 0,{isTraced:L.sampled,keepErrors:_.keepErrors}),x}},Jn=r=>{if(r.fanOut&&r.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});r.fanOut||ve(r.functionPath)},Yn=async(r,s,l)=>{M(r,"POST","RPC");const u=await Vs(r);zs(s,u),Jn(u);const p=await kn(r,u);if(p!==void 0)return p;const{headers:R,identity:O}=await U(r,s,i);Wt(r,O),await Ae(u,O);const P=Je(u,e);{const D=Date.now(),{observability:A}=e,_=Ve(r),B=Re(s,r,l&&(x=>l.waitUntil?.(x)));if(u.fanOut)try{const x=await a.fanOut(d,{args:u.args??{},fanOut:u.fanOut,functionPath:u.functionPath,headers:R});return ce(A,{durationMs:Date.now()-D,fanOut:{failed:x.failed,shards:x.ok+x.failed,table:u.fanOut.table},functionPath:u.functionPath,..._,ok:!0},B),Response.json(x,{headers:{"content-type":"application/json"},status:200})}catch(x){throw ce(A,{...ke(u.functionPath,Date.now()-D,x,{fanOut:{table:u.fanOut.table}}),..._},B),x}const L=u.shardKey??o,V=()=>Se(r,u.functionPath,u.args??{},L,R,B);return P&&e.x402Charge?e.x402Charge(r,{functionPath:u.functionPath,price:P.price},V,ze(l)):V()}},qn=async(r,s,l)=>{M(r,"POST","RPC batch");const u=await ee(r),{calls:p}=u;if(!Array.isArray(p))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:O}=await U(r,s,i);Wt(r,O);const P=Zo(p,o);for(const $ of P.values())for(const K of $)if(e.functions?.[K.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${K.functionPath}" cannot be called in a batch; dispatch it individually over ${Kt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...P.entries()].flatMap(([$,K])=>K.map(Z=>Ae({args:Z.args,functionPath:Z.functionPath,shardKey:$},O))));const{observability:D,sampling:A}=e,_=Re(s,r,l&&($=>l.waitUntil?.($))),B=Ve(r),{decision:L,ignoredUpstream:V,trace:x}=jt(r,{...B.rayId===void 0?{}:{rayId:B.rayId},...A===void 0?{}:{sampling:A},trustInbound:t(r)});V&&n(r);const ue={isTraced:x.sampled,keepErrors:L.keepErrors},dr=$=>{const K={...R,"content-type":"application/json",[Rt]:L.keepErrors?"1":"0"};return Mt({...x,spanId:$},K),K},Be=$=>({parentSpanId:$,spanId:ge(8),traceFlags:x.traceFlags,traceId:x.traceId}),Oe=[],xe=[],ht=($,K,Z,le)=>({body:{error:{code:Z,message:le}},id:$.id,status:K}),ft=($,K,Z,le,fe)=>{for(const q of $)ce(D,fe(q),_,void 0,ue),Oe.push(ht(q,K,Z,le))},ur=($,K,Z,le,fe,q)=>{for(const _e of $){const pe=fe.get(_e.id)??q,me=pe<400;ce(D,{durationMs:le,functionPath:_e.functionPath,...B,...Be(Z),ok:me,shardKey:K,...me?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},_,void 0,ue)}};await Promise.all([...P.entries()].map(async([$,K])=>{const Z=ge(8),le=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:K}),headers:new Headers(dr(Z)),method:"POST"}),fe=Date.now();let q;try{q=await S(d,$,le)}catch(X){const Le=Date.now()-fe,{body:wt}=mr(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});ft(K,502,wt.code,wt.message,fr=>({...ke(fr.functionPath,Le,X,{shardKey:$}),...B,...Be(Z)}));return}const _e=Date.now()-fe,pe=q.headers.get("x-d1-bookmark");pe&&xe.push(pe);let me;try{me=await q.json()}catch{const X=`shard batch returned a non-JSON response (${String(q.status)})`;ft(K,q.status,"SHARD_ERROR",X,Le=>({durationMs:_e,error:{code:"SHARD_ERROR",message:X,status:q.status},functionPath:Le.functionPath,...B,...Be(Z),ok:!1,shardKey:$}));return}const He=Array.isArray(me.results)?me.results:[],lr=new Map(He.map(X=>[X.id,X.status??q.status])),hr=new Set(He.map(X=>X.id));ur(K,$,Z,_e,lr,q.status),Oe.push(...He);for(const X of K)hr.has(X.id)||Oe.push(ht(X,q.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const pt={"content-type":"application/json"},[mt]=xe;return xe.length===1&&mt!==void 0&&(pt["x-d1-bookmark"]=mt),Response.json({results:Oe},{headers:pt,status:200})},Xn=async(r,s,l,u={},p={})=>{try{const R=l.__lunoraRef;if(typeof R!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ve(R);const{headers:O,identity:P}=await U(r,s,i,p.context),D={args:u,functionPath:R,shardKey:p.shardKey};await Ae(D,P);const A=p.shardKey??o,_=Re(s,r,p.waitUntil),B=()=>Se(r,R,u,A,O,_),L=Je(D,e);return L&&e.x402Charge?await e.x402Charge(r,{functionPath:R,price:L.price},B,ze(p.waitUntil?{waitUntil:p.waitUntil}:p.context)):await B()}catch(R){return Et(R)}},dt=async(r,s,l)=>{const{observability:u}=e,p=Date.now(),R=ge(16),O=ge(8),P=Yt(s),D=nn(R,O,!0);try{const A=await l(D);return ce(u,{durationMs:Date.now()-p,functionPath:r,ok:!0,spanId:O,traceId:R},P),A}catch(A){throw ce(u,{...ke(r,Date.now()-p,A,{}),spanId:O,traceId:R},P),A}finally{_t(u,P)}},ut=async(r,s,l,u)=>{v(s);const p=[],R=_=>_ instanceof Error?_:new Error(String(_)),O=e.crons?.[r.cron];if(O)try{await O(r,s,l)}catch(_){p.push(R(_))}const P=await se(r.cron,s,l,p,R,u),D=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===r.cron;if(D)try{await zo(e,a,d,k(),r)}catch(_){p.push(R(_))}if(!O&&P===0&&!D){const _=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${r.cron}") fired but no cron handler is registered for that expression. Registered: ${_.length===0?"(none)":_.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[A]=p;if(p.length===1&&A)throw A;if(p.length>1)throw new AggregateError(p,`scheduled("${r.cron}") had ${String(p.length)} failure(s)`)},Zn=hs({assertAdmin:z,dispatchScheduled:ut,queueHandler:e.queueHandler}),er=async(r,s)=>{try{const l=r??{},u=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!u||u.length===0)return;await S(d,o,De(Ls,{outcome:s},{authorization:`Bearer ${u}`,"content-type":"application/json"}))}catch{}},tr=async(r,s,l,u)=>{if(!e.authHandler)return;const p=e.authBasePath??zt,R=Jt(l.pathname,p)?Nr(r):void 0;let O;try{O=await e.authHandler(R?.request??r)}catch(P){throw R?.overflowed()?new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413}):P}if(R?.overflowed())throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});if(O)return Ms(l.pathname,p)&&u.waitUntil?.(er(s,O.status>=400?"fail":"ok")),O},nr=async({args:r,env:s,functionPath:l,request:u,shardKey:p,waitUntil:R})=>{on(r,"REST");const O={functionPath:l,...p===void 0?{}:{shardKey:p}},{headers:P,identity:D}=await U(u,s,i);await Ae(O,D);const A=p??o,_=Re(s,u,R),B=()=>Se(u,l,r,A,P,_),L=Je(O,e);return L&&e.x402Charge?e.x402Charge(u,{functionPath:l,price:L.price},B,ze({waitUntil:R})):B()},rr=Pr({functions:e.functions??{},invoke:nr,readJsonBody:ee,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Te=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0;ni(Te);const or={[Cs]:r=>r.method!=="GET"&&r.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Is]:(r,s,l)=>Gn(r,s,l),[Kt]:(r,s,l,u)=>Yn(r,s,u),[vs]:(r,s,l,u)=>qn(r,s,u),[ks]:(r,s,l,u)=>Tn(r,s,u),[Ps]:(r,s,l,u)=>Sn(r,s,u),[Ds]:async r=>{M(r,"POST","ws-token"),z(r);const s=k();if(s===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Do(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...Q,...Pn,...Dn,...Nn,...Un,...Cn,...Bn,...xn,...Hn,...Ln,...Mn,...rr,...Bo({assertAdmin:z,getAuthAdmin:()=>e.authAdmin,parsePaging:Ce,queryParameter:Ue,readJsonBody:ee})};let ie=St(e.security),lt=!1;const ar=r=>{lt||(lt=!0,ie=St(e.security,r??{}))},sr=async(r,s)=>{Bs(s)&&await j(r)},ir=(r,s)=>{if(!(s.pathname.startsWith(Ne)||e.authHandler!==void 0&&Jt(s.pathname,e.authBasePath??zt))||r.method!=="POST"&&r.method!=="PUT")return;const u=Number(r.headers.get("content-length")??""),p=Os[s.pathname]??rn;if(Number.isFinite(u)&&u>p)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},cr=async(r,s,l)=>{tt.set(r,l);const u=new URL(r.url);ir(r,u);const p=await tr(r,s,u,l);if(p)return p;if(Te){const A=`${r.method} ${u.pathname}`,_=Te[A]??Te[u.pathname];if(_)return _(r,s,l)}const R=Zn[u.pathname];if(R)return R(r,s,l);const O=or[u.pathname];if(O)return await sr(r,u.pathname),O(r,s,u,l);if(e.voiceAgents!==void 0&&u.pathname.startsWith(Qt))return Qn(r,s,u);if(u.pathname.startsWith(Ne))return new Response("Not found",{status:404});const P=await Kn(r,s,l);if(P&&P.status!==404)return P;const D=await e.authDiscoveryHandler?.(r);return D?(await P?.body?.cancel(),D):P??new Response("Not found",{status:404})};return{async fetch(r,s,l){e.passThroughOnException&&l.passThroughOnException?.(),ar(s),v(s);const u=Zr(r,ie);if(u)return u;const p=eo(r,ie);if(p)return $e(p,r,ie);try{const R=await cr(r,s,l);return $e(R,r,ie)}catch(R){return $e(Et(R),r,ie)}finally{_t(e.observability,Yt(l))}},async queue(r,s,l){await dt(`queue:${Ks(r)}`,l,async u=>{await e.queue?.(r,s,l,{traceparent:u})})},async scheduled(r,s,l){await dt(`cron:${r.cron}`,l,async u=>{await ut(r,s,l,u)})},serverQuery:Xn}},oi=e=>An(e),ai=e=>typeof e=="function"?{fetch:e}:e,si=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,ii=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},Di=(e,t)=>{const n=ai(e),{email:o,queue:a,scheduled:i}=ii(e),d=h=>{const b={...oi({...h,httpRouter:n})};return i!==void 0&&!si(h)&&(b.scheduled=async(S,T,k)=>{await i(S,T,k)}),a!==void 0&&h.queue===void 0&&(b.queue=async(S,T,k)=>{await a(S,T,k)}),o!==void 0&&(b.email=async(S,T,k)=>{await o(S,T,k)}),b};if(typeof t!="function")return d(t);const f=t;return{fetch:(h,m,b)=>d(f(m)).fetch(h,m,b),queue:(h,m,b)=>d(f(m)).queue?.(h,m,b)??Promise.resolve(),scheduled:(h,m,b)=>d(f(m)).scheduled(h,m,b),serverQuery:(h,m,b,S,T)=>d(f(m)).serverQuery(h,m,b,S,T),...o===void 0?{}:{email:(h,m,b)=>d(f(m)).email?.(h,m,b)??Promise.resolve()}}},ci=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new c("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},Ni=(e={})=>(t,n,o)=>An(ci(e,n)).fetch(t,n,o??wr),Ui=e=>e;export{Ze as COPY_AUTH_TO_JURISDICTION_OP,kt as GET_AUTH_AUDIT_LOG_OP,wr as NOOP_EXECUTION_CONTEXT,fn as PURGE_UNPINNED_AUTH_OP,xi as composeIdentityResolvers,oi as composeWorker,Ni as createLunoraHandler,An as createWorker,Ui as defineRpcEnvelope,qs as probeRelayCount,ci as resolveLunoraOptions,Hi as routeIdentityResolvers,Di as withFrameworkWorker};
|