@lunora/runtime 1.0.0-alpha.83 → 1.0.0-alpha.84

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 CHANGED
@@ -873,29 +873,6 @@ type MergeStrategy = {
873
873
  kind: "groupBy";
874
874
  op?: "max" | "min" | "sum";
875
875
  };
876
- /**
877
- * Convenience: build the right wire-serializable {@link MergeStrategy} for a
878
- * given aggregate read. The reader doesn't know which op the caller chose, so
879
- * a fan-out wrapper passes the user's op + by-keys through this to derive the
880
- * merge.
881
- *
882
- * - `count` → `sum`.
883
- * - `aggregate({ op })` → `sum`/`max`/`min` (or throws for `avg`).
884
- * - `groupBy({ by, agg })` → `groupBy({ op })` (defaults to `sum` since
885
- * `groupBy`'s default reducer is `count`).
886
- * @returns the derived {@link MergeStrategy}.
887
- */
888
- declare const mergeStrategyForAggregate: (input: {
889
- agg?: {
890
- op?: "avg" | "count" | "max" | "min" | "sum";
891
- };
892
- kind: "groupBy";
893
- } | {
894
- kind: "count";
895
- } | {
896
- kind: "scalar";
897
- op: "avg" | "count" | "max" | "min" | "sum";
898
- }) => MergeStrategy;
899
876
  interface FanOutSpec {
900
877
  merge: MergeStrategy;
901
878
  /** Table whose shard keys drive the fan-out. */
@@ -938,6 +915,21 @@ interface QueryCoordinatorOptions {
938
915
  /** Required — drives which shards to fan out to. */
939
916
  registry: ShardRegistry;
940
917
  }
918
+ /**
919
+ * Shard a fan-out falls back to when registry discovery finds nothing — normally
920
+ * the worker's `"__root__"` — or `null` to deliberately keep an empty discovery
921
+ * as an empty fan-out.
922
+ *
923
+ * Required on every request that has it, with no default, on purpose. Discovery
924
+ * is registry-driven and a registry only knows the keys an app registers for its
925
+ * `.shardBy(...)` tables, so on a plain root-DO app it comes back empty and a
926
+ * fan-out that reads that as "nothing to do" reports success having touched
927
+ * nothing: an export streamed an empty NDJSON backup, a migration reported
928
+ * `completed` with `processed: 0`. Fan-outs inherited that bug by simply not
929
+ * passing the field, so omission is no longer expressible — say `null` when you
930
+ * mean it. See {@link withDefaultShard}.
931
+ */
932
+ type DefaultShardKey = string | null;
941
933
  interface FanOutRequest {
942
934
  args?: Record<string, unknown>;
943
935
  fanOut: FanOutSpec;
@@ -958,12 +950,8 @@ interface FanOutRequest {
958
950
  */
959
951
  interface MigrationFanOutRequest {
960
952
  args?: Record<string, unknown>;
961
- /**
962
- * Shard to fall back to when registry discovery finds nothing — normally
963
- * `"__root__"`. See {@link withDefaultShard}; omit it to keep an empty
964
- * discovery as an empty fan-out.
965
- */
966
- defaultShardKey?: string;
953
+ /** {@link DefaultShardKey} — the shard fallback, or `null` for none. */
954
+ defaultShardKey: DefaultShardKey;
967
955
  functionPath: string;
968
956
  headers?: Record<string, string>;
969
957
  /** Table whose live shard keys the migration runs across. */
@@ -1171,22 +1159,8 @@ interface QueryCoordinator {
1171
1159
  */
1172
1160
  interface ExportFanOutRequest {
1173
1161
  args?: Record<string, unknown>;
1174
- /**
1175
- * Shard to fall back to when registry discovery yields NOTHING for the
1176
- * requested tables — normally `"__root__"`.
1177
- *
1178
- * Discovery is registry-driven, and a registry only knows the shard keys an
1179
- * app registers for its `.shardBy(...)` tables. A plain root-DO table has no
1180
- * entry and never will, so the union came back empty and the export fanned
1181
- * out to zero shards — returning an empty NDJSON body that looks like a
1182
- * successful backup of a table that simply had no rows. `orchestrateImport`
1183
- * has always resolved the same case to the default shard; export not doing so
1184
- * meant a round trip could silently write back nothing.
1185
- *
1186
- * Omit to keep the old "no keys, no shards" behavior (a caller that has
1187
- * already resolved its own shard set).
1188
- */
1189
- defaultShardKey?: string;
1162
+ /** {@link DefaultShardKey} — the shard fallback, or `null` for none. */
1163
+ defaultShardKey: DefaultShardKey;
1190
1164
  headers?: Record<string, string>;
1191
1165
  /**
1192
1166
  * Tables driving the fan-out. Shards are derived from the union of each
@@ -1222,12 +1196,8 @@ interface ExportFanOutResult {
1222
1196
  */
1223
1197
  interface CdcSyncFanOutRequest {
1224
1198
  cursors?: Record<string, number>;
1225
- /**
1226
- * Shard to fall back to when registry discovery finds nothing — normally
1227
- * `"__root__"`. See {@link withDefaultShard}; omit it to keep an empty
1228
- * discovery as an empty fan-out.
1229
- */
1230
- defaultShardKey?: string;
1199
+ /** {@link DefaultShardKey} — the shard fallback, or `null` for none. */
1200
+ defaultShardKey: DefaultShardKey;
1231
1201
  headers?: Record<string, string>;
1232
1202
  limit?: number;
1233
1203
  tables: ReadonlyArray<string>;
@@ -1423,6 +1393,16 @@ interface RunExportTapOptions {
1423
1393
  coordinator: QueryCoordinator;
1424
1394
  /** Durable cursor store (per-shard watermark). */
1425
1395
  cursorStore: ExportCursorStore;
1396
+ /**
1397
+ * Shard to drain when registry discovery finds nothing — normally the
1398
+ * worker's `"__root__"` — or `null` to keep an empty discovery as an empty
1399
+ * pass. Forwarded verbatim to `orchestrateCdcSync`, and required for the
1400
+ * same reason it is required there: a registry only knows the keys an app
1401
+ * registers for its `.shardBy(...)` tables, so on a plain root-DO app
1402
+ * discovery is `[]` and a caller that omitted this drained no shards while
1403
+ * reporting `{ delivered: 0, hasMore: false }` against a full change feed.
1404
+ */
1405
+ defaultShardKey: string | null;
1426
1406
  /** Headers forwarded to each shard (identity / admin bearer). */
1427
1407
  headers?: Record<string, string>;
1428
1408
  /** Base backoff in ms for the first retry (doubles each attempt, capped at `maxBackoffMs`). Defaults to `100`. */
@@ -3679,11 +3659,6 @@ interface WorkerOptions {
3679
3659
  * the same expression as {@link WorkerOptions.backupCron} runs alongside it.
3680
3660
  */
3681
3661
  crons?: Record<string, CronHandler>;
3682
- /**
3683
- * D1 binding for `.global()` tables. Currently unused by the routing
3684
- * layer; downstream packages will read it from `env.DB` directly.
3685
- */
3686
- d1?: unknown;
3687
3662
  /** Default shard key used when an envelope omits one. */
3688
3663
  defaultShardKey?: string;
3689
3664
  /**
@@ -4948,6 +4923,16 @@ declare const otlpSink: (options: OtlpSinkOptions) => ObservabilitySink;
4948
4923
  *
4949
4924
  * Each child sink is invoked in order; a throw from one does not prevent the
4950
4925
  * others from running (each call is individually guarded).
4926
+ *
4927
+ * A sink is not only its five callbacks: `fuseCloudflareTraces`,
4928
+ * `instrumentDatabase`, `metricHistory` and `traceFetch` are configuration the
4929
+ * shard DO reads directly off this object. They are carried through here,
4930
+ * FIRST-WINS across the children in argument order — returning only the
4931
+ * callbacks meant that
4932
+ * `combineSinks({ ...otlpSink(…), traceFetch: { propagate } }, consoleSink())`
4933
+ * produced a sink with no `traceFetch`, silently reverting to the `true` default
4934
+ * and injecting `traceparent` into every outbound `ctx.fetch` — including the
4935
+ * third-party hosts the predicate existed to exclude.
4951
4936
  * @param sinks The sinks to fan out to.
4952
4937
  */
4953
4938
  declare const combineSinks: (...sinks: ObservabilitySink[]) => ObservabilitySink;
@@ -5082,4 +5067,4 @@ export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolve
5082
5067
  * surface — without a name for it, a caller cannot hoist a shared attribute bag
5083
5068
  * into a typed constant.
5084
5069
  */
5085
- 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 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 SentrySinkOptions, 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 StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, 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, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
5070
+ 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 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 SentrySinkOptions, 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 StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, 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, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
package/dist/index.d.ts CHANGED
@@ -873,29 +873,6 @@ type MergeStrategy = {
873
873
  kind: "groupBy";
874
874
  op?: "max" | "min" | "sum";
875
875
  };
876
- /**
877
- * Convenience: build the right wire-serializable {@link MergeStrategy} for a
878
- * given aggregate read. The reader doesn't know which op the caller chose, so
879
- * a fan-out wrapper passes the user's op + by-keys through this to derive the
880
- * merge.
881
- *
882
- * - `count` → `sum`.
883
- * - `aggregate({ op })` → `sum`/`max`/`min` (or throws for `avg`).
884
- * - `groupBy({ by, agg })` → `groupBy({ op })` (defaults to `sum` since
885
- * `groupBy`'s default reducer is `count`).
886
- * @returns the derived {@link MergeStrategy}.
887
- */
888
- declare const mergeStrategyForAggregate: (input: {
889
- agg?: {
890
- op?: "avg" | "count" | "max" | "min" | "sum";
891
- };
892
- kind: "groupBy";
893
- } | {
894
- kind: "count";
895
- } | {
896
- kind: "scalar";
897
- op: "avg" | "count" | "max" | "min" | "sum";
898
- }) => MergeStrategy;
899
876
  interface FanOutSpec {
900
877
  merge: MergeStrategy;
901
878
  /** Table whose shard keys drive the fan-out. */
@@ -938,6 +915,21 @@ interface QueryCoordinatorOptions {
938
915
  /** Required — drives which shards to fan out to. */
939
916
  registry: ShardRegistry;
940
917
  }
918
+ /**
919
+ * Shard a fan-out falls back to when registry discovery finds nothing — normally
920
+ * the worker's `"__root__"` — or `null` to deliberately keep an empty discovery
921
+ * as an empty fan-out.
922
+ *
923
+ * Required on every request that has it, with no default, on purpose. Discovery
924
+ * is registry-driven and a registry only knows the keys an app registers for its
925
+ * `.shardBy(...)` tables, so on a plain root-DO app it comes back empty and a
926
+ * fan-out that reads that as "nothing to do" reports success having touched
927
+ * nothing: an export streamed an empty NDJSON backup, a migration reported
928
+ * `completed` with `processed: 0`. Fan-outs inherited that bug by simply not
929
+ * passing the field, so omission is no longer expressible — say `null` when you
930
+ * mean it. See {@link withDefaultShard}.
931
+ */
932
+ type DefaultShardKey = string | null;
941
933
  interface FanOutRequest {
942
934
  args?: Record<string, unknown>;
943
935
  fanOut: FanOutSpec;
@@ -958,12 +950,8 @@ interface FanOutRequest {
958
950
  */
959
951
  interface MigrationFanOutRequest {
960
952
  args?: Record<string, unknown>;
961
- /**
962
- * Shard to fall back to when registry discovery finds nothing — normally
963
- * `"__root__"`. See {@link withDefaultShard}; omit it to keep an empty
964
- * discovery as an empty fan-out.
965
- */
966
- defaultShardKey?: string;
953
+ /** {@link DefaultShardKey} — the shard fallback, or `null` for none. */
954
+ defaultShardKey: DefaultShardKey;
967
955
  functionPath: string;
968
956
  headers?: Record<string, string>;
969
957
  /** Table whose live shard keys the migration runs across. */
@@ -1171,22 +1159,8 @@ interface QueryCoordinator {
1171
1159
  */
1172
1160
  interface ExportFanOutRequest {
1173
1161
  args?: Record<string, unknown>;
1174
- /**
1175
- * Shard to fall back to when registry discovery yields NOTHING for the
1176
- * requested tables — normally `"__root__"`.
1177
- *
1178
- * Discovery is registry-driven, and a registry only knows the shard keys an
1179
- * app registers for its `.shardBy(...)` tables. A plain root-DO table has no
1180
- * entry and never will, so the union came back empty and the export fanned
1181
- * out to zero shards — returning an empty NDJSON body that looks like a
1182
- * successful backup of a table that simply had no rows. `orchestrateImport`
1183
- * has always resolved the same case to the default shard; export not doing so
1184
- * meant a round trip could silently write back nothing.
1185
- *
1186
- * Omit to keep the old "no keys, no shards" behavior (a caller that has
1187
- * already resolved its own shard set).
1188
- */
1189
- defaultShardKey?: string;
1162
+ /** {@link DefaultShardKey} — the shard fallback, or `null` for none. */
1163
+ defaultShardKey: DefaultShardKey;
1190
1164
  headers?: Record<string, string>;
1191
1165
  /**
1192
1166
  * Tables driving the fan-out. Shards are derived from the union of each
@@ -1222,12 +1196,8 @@ interface ExportFanOutResult {
1222
1196
  */
1223
1197
  interface CdcSyncFanOutRequest {
1224
1198
  cursors?: Record<string, number>;
1225
- /**
1226
- * Shard to fall back to when registry discovery finds nothing — normally
1227
- * `"__root__"`. See {@link withDefaultShard}; omit it to keep an empty
1228
- * discovery as an empty fan-out.
1229
- */
1230
- defaultShardKey?: string;
1199
+ /** {@link DefaultShardKey} — the shard fallback, or `null` for none. */
1200
+ defaultShardKey: DefaultShardKey;
1231
1201
  headers?: Record<string, string>;
1232
1202
  limit?: number;
1233
1203
  tables: ReadonlyArray<string>;
@@ -1423,6 +1393,16 @@ interface RunExportTapOptions {
1423
1393
  coordinator: QueryCoordinator;
1424
1394
  /** Durable cursor store (per-shard watermark). */
1425
1395
  cursorStore: ExportCursorStore;
1396
+ /**
1397
+ * Shard to drain when registry discovery finds nothing — normally the
1398
+ * worker's `"__root__"` — or `null` to keep an empty discovery as an empty
1399
+ * pass. Forwarded verbatim to `orchestrateCdcSync`, and required for the
1400
+ * same reason it is required there: a registry only knows the keys an app
1401
+ * registers for its `.shardBy(...)` tables, so on a plain root-DO app
1402
+ * discovery is `[]` and a caller that omitted this drained no shards while
1403
+ * reporting `{ delivered: 0, hasMore: false }` against a full change feed.
1404
+ */
1405
+ defaultShardKey: string | null;
1426
1406
  /** Headers forwarded to each shard (identity / admin bearer). */
1427
1407
  headers?: Record<string, string>;
1428
1408
  /** Base backoff in ms for the first retry (doubles each attempt, capped at `maxBackoffMs`). Defaults to `100`. */
@@ -3679,11 +3659,6 @@ interface WorkerOptions {
3679
3659
  * the same expression as {@link WorkerOptions.backupCron} runs alongside it.
3680
3660
  */
3681
3661
  crons?: Record<string, CronHandler>;
3682
- /**
3683
- * D1 binding for `.global()` tables. Currently unused by the routing
3684
- * layer; downstream packages will read it from `env.DB` directly.
3685
- */
3686
- d1?: unknown;
3687
3662
  /** Default shard key used when an envelope omits one. */
3688
3663
  defaultShardKey?: string;
3689
3664
  /**
@@ -4948,6 +4923,16 @@ declare const otlpSink: (options: OtlpSinkOptions) => ObservabilitySink;
4948
4923
  *
4949
4924
  * Each child sink is invoked in order; a throw from one does not prevent the
4950
4925
  * others from running (each call is individually guarded).
4926
+ *
4927
+ * A sink is not only its five callbacks: `fuseCloudflareTraces`,
4928
+ * `instrumentDatabase`, `metricHistory` and `traceFetch` are configuration the
4929
+ * shard DO reads directly off this object. They are carried through here,
4930
+ * FIRST-WINS across the children in argument order — returning only the
4931
+ * callbacks meant that
4932
+ * `combineSinks({ ...otlpSink(…), traceFetch: { propagate } }, consoleSink())`
4933
+ * produced a sink with no `traceFetch`, silently reverting to the `true` default
4934
+ * and injecting `traceparent` into every outbound `ctx.fetch` — including the
4935
+ * third-party hosts the predicate existed to exclude.
4951
4936
  * @param sinks The sinks to fan out to.
4952
4937
  */
4953
4938
  declare const combineSinks: (...sinks: ObservabilitySink[]) => ObservabilitySink;
@@ -5082,4 +5067,4 @@ export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolve
5082
5067
  * surface — without a name for it, a caller cannot hoist a shared attribute bag
5083
5068
  * into a typed constant.
5084
5069
  */
5085
- 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 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 SentrySinkOptions, 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 StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, 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, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
5070
+ 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 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 SentrySinkOptions, 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 StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, 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, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-CIjE6Vm1.mjs";import{composeWorker as S,createLunoraHandler as x,createWorker as _,defineRpcEnvelope as d,resolveLunoraOptions as l,withFrameworkWorker as u}from"./packem_shared/composeWorker-Bz6FNFLU.mjs";import{createCrossShardRelationCapabilities as k}from"./packem_shared/createCrossShardRelationCapabilities-BRX27FkU.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as C,createDynamicShardRegistry as L}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as b,toErrorResponse as g}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{createKvCursorStore as H,createMemoryCursorStore as I,defineExportSink as P,r2Sink as v,runExportTap as D,sanitizeChange as F,webhookExportSink as M}from"./packem_shared/createKvCursorStore-DLm6fYoN.mjs";import{HEALTH_PATH as K,HEALTH_READY_PATH as N,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-jZsuCmSs.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-jgHjdsz2.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as J,a as Z}from"./packem_shared/observability-vDK-rMbs.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-D9xt5_FI.mjs";import{D as pe,a as ce,c as me}from"./packem_shared/pipeline-log-reader-BGrl66P5.mjs";import{createQueryCoordinator as Ee,createStaticShardRegistry as Re,mergeStrategyForAggregate as Se}from"./packem_shared/createQueryCoordinator-B4Zk2HfK.mjs";import{applyJurisdiction as _e,resolveShard as de}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as ye,b as ke}from"./packem_shared/rest-cache-CPSyD1RD.mjs";import{a as Ae,b as Ce,c as Le,r as Te,d as be}from"./packem_shared/rest-routes-Dq17Zntv.mjs";import{decorateResponse as he,enforceOrigin as He,handleCorsPreflight as Ie,resolveSecurity as Pe}from"./packem_shared/decorateResponse-BuqVnrmc.mjs";import{createShardClient as De}from"./packem_shared/createShardClient-0Tz9JwbX.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Me}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ke}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ue}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ye,routeIdentityResolvers as we}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,ce as DEFAULT_LOG_LIMIT,A as DEFAULT_REGISTRY_CACHE_TTL_MS,K as HEALTH_PATH,N as HEALTH_READY_PATH,Ke as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,b as LunoraError,Ue as NOOP_EXECUTION_CONTEXT,C as SHARD_REGISTRY_DO_NAME,Me as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,_e as applyJurisdiction,ue as applyRestCache,Ae as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ye as composeIdentityResolvers,S as composeWorker,oe as consoleSink,k as createCrossShardRelationCapabilities,L as createDynamicShardRegistry,H as createKvCursorStore,x as createLunoraHandler,I as createMemoryCursorStore,me as createPipelineLogReader,Ee as createQueryCoordinator,Le as createRestRateLimit,De as createShardClient,Re as createStaticShardRegistry,_ as createWorker,B as d1Probe,he as decorateResponse,P as defineExportSink,d as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,He as enforceOrigin,Ie as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,Se as mergeStrategyForAggregate,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,v as r2Sink,Te as readShardKey,ye as requestCarriesCredentials,j as resolveLogArchiveFromEnv,l as resolveLunoraOptions,Pe as resolveSecurity,de as resolveShard,ke as restCacheHeaders,be as restSurfaceFromRegistry,we as routeIdentityResolvers,D as runExportTap,F as sanitizeChange,se as sentrySink,f as toAirbyteMessages,g as toErrorResponse,E as toFivetranResponse,M as webhookExportSink,ie as webhookSink,u as withFrameworkWorker};
1
+ import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-CIjE6Vm1.mjs";import{composeWorker as S,createLunoraHandler as x,createWorker as d,defineRpcEnvelope as _,resolveLunoraOptions as l,withFrameworkWorker as u}from"./packem_shared/composeWorker-C6smX1pe.mjs";import{createCrossShardRelationCapabilities as k}from"./packem_shared/createCrossShardRelationCapabilities-kKGcOgYm.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as C,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as b}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as T,toErrorResponse as h}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as I,a as P,d as g,r as v,b as D,s as M,w as F}from"./packem_shared/export-tap-CgiuS5w4.mjs";import{HEALTH_PATH as K,HEALTH_READY_PATH as N,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-jZsuCmSs.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-Btzcg6oL.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as J,a as Z}from"./packem_shared/observability-vDK-rMbs.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-B3sQ6FPW.mjs";import{D as pe,a as ce,c as me}from"./packem_shared/pipeline-log-reader-BGrl66P5.mjs";import{createQueryCoordinator as Ee,createStaticShardRegistry as Re}from"./packem_shared/createQueryCoordinator-Ctr3eqmp.mjs";import{applyJurisdiction as xe,resolveShard as de}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as le,r as ue,b as ye}from"./packem_shared/rest-cache-CPSyD1RD.mjs";import{a as Oe,b as Ce,c as Le,r as be,d as Ae}from"./packem_shared/rest-routes-Dq17Zntv.mjs";import{decorateResponse as he,enforceOrigin as He,handleCorsPreflight as Ie,resolveSecurity as Pe}from"./packem_shared/decorateResponse-BuqVnrmc.mjs";import{createShardClient as ve}from"./packem_shared/createShardClient-0Tz9JwbX.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Me}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ge}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ne}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Be,routeIdentityResolvers as Ye}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,ce as DEFAULT_LOG_LIMIT,C as DEFAULT_REGISTRY_CACHE_TTL_MS,K as HEALTH_PATH,N as HEALTH_READY_PATH,Ge as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,T as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Me as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,xe as applyJurisdiction,le as applyRestCache,Oe as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Be as composeIdentityResolvers,S as composeWorker,oe as consoleSink,k as createCrossShardRelationCapabilities,b as createDynamicShardRegistry,I as createKvCursorStore,x as createLunoraHandler,P as createMemoryCursorStore,me as createPipelineLogReader,Ee as createQueryCoordinator,Le as createRestRateLimit,ve as createShardClient,Re as createStaticShardRegistry,d as createWorker,B as d1Probe,he as decorateResponse,g as defineExportSink,_ as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,He as enforceOrigin,Ie as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,v as r2Sink,be as readShardKey,ue as requestCarriesCredentials,j as resolveLogArchiveFromEnv,l as resolveLunoraOptions,Pe as resolveSecurity,de as resolveShard,ye as restCacheHeaders,Ae as restSurfaceFromRegistry,Ye as routeIdentityResolvers,D as runExportTap,M as sanitizeChange,se as sentrySink,f as toAirbyteMessages,h as toErrorResponse,E as toFivetranResponse,F as webhookExportSink,ie as webhookSink,u as withFrameworkWorker};
@@ -0,0 +1 @@
1
+ import{createR2Sql as h}from"@lunora/bindings/r2sql";import{LOG_ARCHIVE_NOT_CONFIGURED as l}from"./LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{L,c as A}from"./pipeline-log-reader-BGrl66P5.mjs";import{LunoraError as _}from"./LunoraError-DksAgIpa.mjs";import{a as R}from"./method-guard-BG_vJNTl.mjs";const v="/_lunora/admin/logs/archive",m="LUNORA_LOG_ARCHIVE_TABLE",C="LUNORA_LOG_ARCHIVE_NAMESPACE",V=e=>{if(typeof e!="object"||e===null)return;const o=e,s=o[m];if(typeof s!="string"||s==="")return;const n=o[C];return{table:s,...typeof n=="string"&&n!==""?{namespace:n}:{}}},T=new Set(L),O=e=>typeof e=="string"&&e!==""?e:void 0,S=(e,o)=>{if(e!==void 0){if(typeof e!="string"||!T.has(e))throw new _(`logs archive: invalid \`${o}\` — expected one of ${L.join(", ")}`,{code:"BAD_REQUEST",status:400});return e}},p=(e,o)=>{if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e))throw new _(`logs archive: invalid \`${o}\` — expected a finite number`,{code:"BAD_REQUEST",status:400});return e}},b=e=>{const o={},s=r=>{const t=O(e[r]);t!==void 0&&(o[r]=t)},n=r=>{const t=S(e[r],r);t!==void 0&&(o[r]=t)},i=r=>{const t=p(e[r],r);t!==void 0&&(o[r]=t)};s("functionPath"),s("functionPathPrefix"),s("traceId"),s("shardKey"),s("userId"),n("level"),n("minLevel"),i("sinceTs"),i("untilTs"),i("limit");const c=e.cursor;if(typeof c=="object"&&c!==null){const r=c,t=p(r.ts,"cursor.ts");if(t!==void 0){const a=r.seen;if(a!==void 0&&(!Array.isArray(a)||a.some(d=>typeof d!="string")))throw new _("logs archive: invalid `cursor.seen` — expected an array of strings",{code:"BAD_REQUEST",status:400});const u=a;o.cursor=u===void 0||u.length===0?{ts:t}:{seen:u,ts:t}}}return o},y=e=>{const o=e.R2_SQL_ACCOUNT_ID??e.CLOUDFLARE_ACCOUNT_ID,s=e.R2_SQL_TOKEN,n=e.R2_SQL_BUCKET,i=[];if((o===void 0||o==="")&&i.push("R2_SQL_ACCOUNT_ID"),(s===void 0||s==="")&&i.push("R2_SQL_TOKEN"),(n===void 0||n==="")&&i.push("R2_SQL_BUCKET"),i.length>0)throw new _(`log archive not configured (missing ${i.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET must be set — see the observability docs.`,{code:l,status:400});return{accountId:o,apiToken:s,bucket:n}},B=e=>{const{createReader:o=A,readJsonBody:s,requireAdminOption:n}=e,i=async(c,r)=>{R(c,"POST","Log-archive");const t=n(c,e.logArchive,{code:l,message:"log archive requires a `logArchive` config (an R2 Data Catalog table) on the worker — see the observability docs"}),{accountId:a,apiToken:u,bucket:d}=y(r??{}),g=b(await s(c)),E=h({accountId:a,apiToken:u,bucket:d}),f=await o(E,{columnMap:t.columnMap,namespace:t.namespace,table:t.table}).query(g);return Response.json(f,{headers:{"content-type":"application/json"},status:200})};return{[v]:i}};export{l as LOG_ARCHIVE_NOT_CONFIGURED,v as LOG_ARCHIVE_PATH,B as buildLogArchiveAdminRoutes,V as resolveLogArchiveFromEnv};
@@ -0,0 +1 @@
1
+ import{e as p,L as y,o as x,c as S,O as $,f as X,g as q,h as J,w as G,i as Y,j as Z,m as Q}from"./otlp-resource-DeXhb949.mjs";const v=r=>{if(typeof r=="string")return r;try{return JSON.stringify(r)??String(r)}catch{return String(r)}},C=r=>typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:v(r),rr=512,tr=200,or=r=>{const s=r.maxItems??rr,o=r.maxDelayMs??tr;let t=[],e,a,n;const c=()=>{e!==void 0&&(clearTimeout(e),e=void 0)},h=async()=>{c();const l=t;t=[];const d=n;a=void 0,n=void 0;try{l.length>0&&await r.export(l)}catch{}finally{d?.()}},m=l=>{a===void 0&&(a=new Promise(d=>{n=d}),e=setTimeout(()=>{h()},o)),l?.(a)};return{add:(l,d)=>{for(t.push(l);t.length>s;)t.shift();m(d),t.length>=s&&h()},flush:async l=>{if(t.length===0){c();return}const d=h();return l?.(d),d},get size(){return t.length}}},sr=/["\\\u0000-\u001F\uD800-\uDFFF]/,D=r=>sr.test(r)?JSON.stringify(r):`"${r}"`,A=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 D(r);if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r)){let n="[";for(let c=0;c<r.length;c++)c>0&&(n+=","),n+=A(r[c]);return n+"]"}const s=Object.getPrototypeOf(r);if(s!==null&&s!==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 e="{",a=!0;for(const n of t){const c=o[n];c!==void 0&&(a?a=!1:e+=",",e+=D(n),e+=":",e+=A(c))}return e+"}"},er=(r,s)=>{const o=[p(y.functionPath,r.functionPath),p(y.ok,r.ok)];r.method!==void 0&&o.push(p("http.request.method",r.method)),r.path!==void 0&&o.push(p("url.path",r.path)),o.push(p("http.route",r.functionPath)),r.scheme!==void 0&&o.push(p("url.scheme",r.scheme)),r.host!==void 0&&o.push(p("server.address",r.host)),r.port!==void 0&&o.push(p("server.port",r.port)),r.userAgent!==void 0&&o.push(p("user_agent.original",r.userAgent)),r.shardKey!==void 0&&o.push(p(y.shardKey,r.shardKey)),o.push(p("http.response.status_code",r.error?.status??200)),r.error&&o.push(p(y.errorType,r.error.code),p("lunora.error_status",r.error.status)),r.fanOut&&o.push(p("lunora.fanout.table",r.fanOut.table),p("lunora.fanout.shards",r.fanOut.shards),p("lunora.fanout.failed",r.fanOut.failed));const t={attributes:o,endTimeUnixNano:S(s),kind:$.server,name:r.functionPath,...r.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},spanId:r.spanId??x(8),startTimeUnixNano:S(s-r.durationMs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId??x(16)};return r.traceFlags!==void 0&&(t.flags=r.traceFlags),r.error&&(t.events=[{attributes:[p("exception.type",r.error.code),p("exception.message",r.error.message)],name:"exception",timeUnixNano:S(s)}]),t},L=(r,s)=>{const o=new Map([[y.functionPath,p(y.functionPath,r.functionPath)]]);r.shardKey!==void 0&&o.set(y.shardKey,p(y.shardKey,r.shardKey)),r.userId!==void 0&&o.set(y.userId,p(y.userId,r.userId)),r.errorType!==void 0&&o.set(y.errorType,p(y.errorType,r.errorType));for(const[t,e]of Object.entries(s??{}))o.set(t,p(t,C(e)));return[...o.values()]},nr=r=>{const s={attributes:L({errorType:r.error?.type,functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.attributes),endTimeUnixNano:S(r.startTs+r.durationMs),kind:$[r.kind??"internal"],name:r.name,parentSpanId:r.parentSpanId,spanId:r.spanId,startTimeUnixNano:S(r.startTs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId},o=t=>q(Object.fromEntries(Object.entries(t??{}).map(([e,a])=>[e,C(a)])));return r.events!==void 0&&r.events.length>0&&(s.events=r.events.map(t=>({attributes:o(t.attributes),name:t.name,timeUnixNano:S(t.ts)}))),r.links!==void 0&&r.links.length>0&&(s.links=r.links.map(t=>({attributes:o(t.attributes),spanId:t.spanId,traceId:t.traceId}))),s},ir=r=>{const s=S(r.ts),o=L({functionPath:r.functionPath,shardKey:r.shardKey},r.attributes),t={asDouble:r.value,attributes:o,timeUnixNano:s};return r.kind==="gauge"?{gauge:{dataPoints:[t]},name:r.name}:r.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:o,bucketCounts:["1"],count:"1",explicitBounds:[],max:r.value,min:r.value,sum:r.value,timeUnixNano:s}]},name:r.name}:{name:r.name,sum:{aggregationTemporality:1,dataPoints:[t],isMonotonic:!0}}},ar=r=>{const s={attributes:L({functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.fields),body:{stringValue:r.message},severityNumber:X[r.level],severityText:r.level.toUpperCase(),timeUnixNano:S(r.ts)};return r.traceId!==void 0&&(s.traceId=r.traceId),r.spanId!==void 0&&(s.spanId=r.spanId),r.eventName!==void 0&&(s.eventName=r.eventName,s.attributes.push(p("event.name",r.eventName))),s},cr=1024,dr=async r=>{const s=new Blob([r]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(s).arrayBuffer()},H=async(r,s,o,t)=>{try{const e=JSON.stringify(s),{byteLength:a}=new TextEncoder().encode(e),n=(a<cr?fetch(r,{body:e,headers:o,method:"POST"}):dr(e).then(c=>fetch(r,{body:c,headers:{...o,"content-encoding":"gzip"},method:"POST"}))).then(()=>{},()=>{});t?.(n),await n}catch{}},ur=(r,s,o,t)=>{H(r,s,o,t?.waitUntil).catch(()=>{})},O=(r,s)=>s===!0&&r.ok,pr=r=>r.kind==="metric"?void 0:r.event.traceId,lr=r=>{const s=Map.groupBy(r,t=>pr(t)),o=s.get(void 0)??[];return s.delete(void 0),{byTrace:s,untraced:o}},j=5,fr=(r,s,o)=>{if(s===void 0)return r;const{byTrace:t,untraced:e}=lr(r),a=[...e];let n=0,c;for(const[h,m]of t){let l;try{l=s({logs:m.filter(d=>d.kind==="log").map(d=>d.event),rpc:m.filter(d=>d.kind==="rpc").map(d=>d.event),spans:m.filter(d=>d.kind==="span").map(d=>d.event),traceId:h})}catch(d){n+=1,n===1&&(c=d),l=!0}l&&a.push(...m)}return n>0&&o(c,n),a},P=(r,s)=>{if(s===void 0)return r;try{return s(r)??void 0}catch{return}},B=(r,s)=>{if(r.kind==="rpc"){const t=P(r.event,s?.rpc);return t===void 0?void 0:{bucket:"spans",encoded:er(t,r.endMs)}}if(r.kind==="span"){const t=P(r.event,s?.span);return t===void 0?void 0:{bucket:"spans",encoded:nr(t)}}if(r.kind==="log"){const t=P(r.event,s?.log);return t===void 0?void 0:{bucket:"logs",encoded:ar(t)}}const o=P(r.event,s?.metric);return o===void 0?void 0:{bucket:"metrics",encoded:ir(o)}},mr=["fuseCloudflareTraces","instrumentDatabase","metricHistory","traceFetch"],yr=(r={})=>{const{onlyErrors:s}=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,s)||(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)}}},gr=r=>{const{headers:s,onlyErrors:o,transform:t,transformLog:e,url:a}=r,n=J({"content-type":"application/json"},s),c=(h,m)=>{try{const l=fetch(a,{body:JSON.stringify(h),headers:n,method:"POST"}).catch(()=>{});m?.waitUntil&&m.waitUntil(l)}catch{}};return{onLog:(h,m)=>{const l=P(h,e);l!==void 0&&c(l,m)},onRpc:(h,m)=>{if(O(h,o))return;const l=P(h,t);l!==void 0&&c(l,m)}}},br=r=>{const{capture:s,captureLog:o}=r,t=r.onlyErrors??!0;return{onLog:o?e=>{try{o(e)}catch{}}:void 0,onRpc:e=>{if(!O(e,t))try{s(e)}catch{}}}},kr=r=>{const{dataset:s,onlyErrors:o}=r;return{onRpc:t=>{if(!O(t,o))try{s.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{}}}},Sr=r=>{const{pipeline:s,serializeFields:o}=r;return{onLog:(t,e)=>{try{const a={functionPath:t.functionPath,level:t.level,message:t.message,ts:t.ts};t.fields&&(a.fields=o===!0?JSON.stringify(t.fields):t.fields);for(const c of["shardKey","userId","traceId","spanId"])t[c]!==void 0&&(a[c]=t[c]);const n=s.send([a]).catch(()=>{});e?.waitUntil&&e.waitUntil(n)}catch{}}}},Ir=r=>{const{batch:s,deploymentEnvironment:o,detectResources:t,endpoint:e,headers:a,onlyErrors:n,postProcessor:c,resourceAttributes:h,serviceNamespace:m,serviceVersion:l,tailSampler:d,token:z}=r,R=r.serviceName??"lunora",U={...l===void 0?{}:{"service.version":l},...m===void 0?{}:{"service.namespace":m},...o===void 0?{}:{"deployment.environment":o},...h},F=new WeakMap,k=u=>{if(t!==!0||u?.resourceAttributes===void 0)return U;const i=F.get(u);if(i!==void 0)return i;const f=Q(u.resourceAttributes(),U);return F.set(u,f),f};let I=e;for(;I.endsWith("/");)I=I.slice(0,-1);const _={logs:{url:`${I}/v1/logs`,wrap:Z},metrics:{url:`${I}/v1/metrics`,wrap:Y},spans:{url:`${I}/v1/traces`,wrap:G}},K=J({"content-type":"application/json"},a,z);let M=0;const V=(u,i)=>{if(M>=j)return;M+=1;const f=M===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}`,u)},W=async u=>{const i=fr(u,d,V),f=new Map;for(const g of i){const b=B(g,c);if(b===void 0)continue;const E=A(g.resource);let T=f.get(E);T===void 0&&(T={logs:[],metrics:[],resource:g.resource,spans:[]},f.set(E,T)),T[b.bucket].push(b.encoded)}const w=[];for(const[,g]of f)for(const b of["spans","logs","metrics"])if(g[b].length>0){const{url:E,wrap:T}=_[b];w.push(H(E,T(g[b],"@lunora/runtime",R,g.resource),K))}await Promise.all(w)};if(s===!1){const u=(i,f)=>{const w=B(i,c);if(w!==void 0){const{url:g,wrap:b}=_[w.bucket];ur(g,b(w.encoded,"@lunora/runtime",R,i.resource),K,f)}};return{onLog:(i,f)=>{u({event:i,kind:"log",resource:k(f)},f)},onMetric:(i,f)=>{u({event:i,kind:"metric",resource:k(f)},f)},onRpc:(i,f)=>{O(i,n)||u({endMs:Date.now(),event:i,kind:"rpc",resource:k(f)},f)},onSpan:(i,f)=>{u({event:i,kind:"span",resource:k(f)},f)}}}const N=or({export:W,...s?.maxDelayMs===void 0?{}:{maxDelayMs:s.maxDelayMs},...s?.maxItems===void 0?{}:{maxItems:s.maxItems}});return{flush:u=>{N.flush(u?.waitUntil).catch(()=>{})},onLog:(u,i)=>{N.add({event:u,kind:"log",resource:k(i)},i?.waitUntil)},onMetric:(u,i)=>{N.add({event:u,kind:"metric",resource:k(i)},i?.waitUntil)},onRpc:(u,i)=>{O(u,n)||N.add({endMs:Date.now(),event:u,kind:"rpc",resource:k(i)},i?.waitUntil)},onSpan:(u,i)=>{N.add({event:u,kind:"span",resource:k(i)},i?.waitUntil)}}},wr=(...r)=>{const s=(t,e)=>{for(const a of r){const n=a[t];if(n)try{n.apply(a,e)}catch{}}},o={};for(const t of r)for(const e of mr)o[e]===void 0&&t[e]!==void 0&&(o[e]=t[e]);return{...o,flush:t=>{s("flush",[t])},onLog:(t,e)=>{s("onLog",[t,e])},onMetric:(t,e)=>{s("onMetric",[t,e])},onRpc:(t,e)=>{s("onRpc",[t,e])},onSpan:(t,e)=>{s("onSpan",[t,e])}}};export{kr as analyticsEngineSink,wr as combineSinks,yr as consoleSink,Ir as otlpSink,Sr as pipelineLogSink,br as sentrySink,gr as webhookSink};
@@ -0,0 +1,6 @@
1
+ import{isLunoraError as Dn,toErrorBody as Nn}from"@lunora/errors";import{e as Nt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Un}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as Cn,f as Bn}from"./base64-Bl1_r2k1.mjs";import{e as xn,a as Hn}from"./identity-header-C4Z5pldl.mjs";import{o as Te,b as Ln,p as Mn,m as Kn,d as jn,a as $n,r as Fn}from"./otlp-resource-DeXhb949.mjs";import{e as Qe}from"./wire-codec-BsPOEXGn.mjs";import{e as ee,f as be,M as Ut,b as Gn,g as Qn,h as Ct,i as Bt}from"./rest-routes-Dq17Zntv.mjs";import{LunoraError as d,toErrorResponse as ot}from"./LunoraError-DksAgIpa.mjs";import{a as K,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as We,BACKUP_KEY_PREFIX as Ve,isBackupManifestKey as zn,backupObjectKeyOfManifest as xt,backupObjectKey as Wn,backupManifestKey as Vn}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as qn,buildStorageAdminRoutes as Jn,STORAGE_UPLOAD_MAX_BODY_BYTES as Yn,STORAGE_PATH as Xn}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{b as Zn,e as er,f as at,g as tr,h as nr}from"./export-tap-CgiuS5w4.mjs";import{buildHealthRoutes as rr,durableObjectProbe as or,d1Probe as ar,presenceProbe as Be}from"./HEALTH_PATH-jZsuCmSs.mjs";import{wrapResolverWithContract as sr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as As,routeIdentityResolvers as Ts}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as ir}from"./LOG_ARCHIVE_PATH-Btzcg6oL.mjs";import{r as cr,f as st,a as de}from"./observability-vDK-rMbs.mjs";import{resolveShard as we,applyJurisdiction as it}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as ct,handleCorsPreflight as dr,enforceOrigin as ur,decorateResponse as xe,enforceWebSocketOrigin as dt}from"./decorateResponse-BuqVnrmc.mjs";const lr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n={...t,bucketName:"default"};return n.bucket=()=>n,n},Ht="__lunoraBranch",hr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Ht),fr=`may not contain the reserved workflow branch-marker key ("${Ht}")`,qe=(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,u=a<t.length?t.charCodeAt(a):0;o|=i^u}return o===0},pr=(e,t,n,o)=>{const a=e.get(t);if(a!==void 0)return a;Nt(e,o);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},Je=new TextEncoder,mr=Array.from({length:32},(e,t)=>t);new RegExp(`[${mr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const wr=64,gr=new Map,Lt=async e=>pr(gr,e,async()=>crypto.subtle.importKey("raw",Je.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),wr),Mt=async(e,t)=>{const n=await Lt(e),o=await crypto.subtle.sign("HMAC",n,Je.encode(t));return Cn(new Uint8Array(o))},yr=async(e,t,n)=>{const o=await Lt(e);return crypto.subtle.verify("HMAC",o,n,Je.encode(t))},br=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(br);const _r=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Rr=-100,Er=15,Sr=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&_r.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Er?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Rr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},ut=e=>{const t=e.cf;return t===void 0?void 0:Sr(t)},Kt="::relay::",Ar=(e,t)=>`${e}${Kt}${String(t)}`,jt="::replica::",Tr=(e,t)=>`${e}${jt}${t}`,Or=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},vr=new Set(["1","enabled","on","true","yes"]),kr=new Set(["0","disabled","false","no","off"]),Ir=(e,t)=>{const n=(e??"").trim().toLowerCase();return vr.has(n)?!0:kr.has(n)?!1:t},$t="v1",Pr=6e4,Dr=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Pr),o=`${$t}.${String(n)}`,a=await Mt(e,o);return{expiresAtMs:n,token:`${o}.${a}`}},Nr=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,u]=o;if(a!==$t||u.length===0)return!1;const h=Number(i);if(!Number.isFinite(h)||h<=n)return!1;let f;try{f=Bn(u)}catch{return!1}return yr(e,`${a}.${i}`,f)},P="/_lunora/admin/auth",Ur={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},N=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new d(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},he=(e,t)=>{const n=e(t);if(n===void 0)throw new d(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},Ft=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},ae=(e,t)=>typeof e[t]=="string"?e[t]:void 0,He=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},lt=e=>{const t=Ft(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new d("`role` is required",{code:"BAD_REQUEST",status:400});return t},ht=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`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},Cr={[`${P}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${P}/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"},[`${P}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${P}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${P}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${P}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:He(e,"data"),email:N(e,"email"),name:N(e,"name"),password:ae(e,"password"),role:Ft(e.role)}),http:"POST",method:"createUser"},[`${P}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:N(e,"userId")}},http:"POST",method:"updateUser"},[`${P}/users/role`]:{build:({body:e})=>({role:lt(e),userId:N(e,"userId")}),http:"POST",method:"setRole"},[`${P}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:ae(e,"reason"),userId:N(e,"userId")}),http:"POST",method:"banUser"},[`${P}/users/unban`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"unbanUser"},[`${P}/users/password`]:{build:({body:e})=>({newPassword:N(e,"newPassword"),userId:N(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${P}/users/remove`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${P}/users/impersonate`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"impersonateUser"},[`${P}/sessions/revoke`]:{build:({body:e})=>({sessionId:N(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${P}/sessions/revoke-all`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${P}/accounts/unlink`]:{build:({body:e})=>({accountId:N(e,"accountId"),userId:N(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${P}/two-factor/disable`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${P}/passkeys/delete`]:{build:({body:e})=>({passkeyId:N(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${P}/organizations/members/remove`]:{build:({body:e})=>({memberId:N(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${P}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:N(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${P}/organizations/create`]:{build:({body:e})=>({logo:ae(e,"logo"),metadata:He(e,"metadata"),name:N(e,"name"),ownerId:ae(e,"ownerId"),slug:ae(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:ae(e,"logo"),metadata:He(e,"metadata"),name:ae(e,"name"),organizationId:N(e,"organizationId"),slug:ae(e,"slug")}),http:"POST",method:"updateOrganization"},[`${P}/organizations/remove`]:{build:({body:e})=>({organizationId:N(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${P}/organizations/members/add`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),role:ae(e,"role"),userId:N(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:N(e,"email"),inviterId:ae(e,"inviterId"),organizationId:N(e,"organizationId"),role:ae(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:N(e,"memberId"),role:lt(e)}),http:"POST",method:"updateMemberRole"},[`${P}/organizations/teams/create`]:{build:({body:e})=>({name:N(e,"name"),organizationId:N(e,"organizationId")}),http:"POST",method:"createTeam"},[`${P}/organizations/teams/update`]:{build:({body:e})=>({name:N(e,"name"),teamId:N(e,"teamId")}),http:"POST",method:"updateTeam"},[`${P}/organizations/teams/remove`]:{build:({body:e})=>({teamId:N(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${P}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:N(e,"teamId"),userId:N(e,"userId")}),http:"POST",method:"addTeamMember"},[`${P}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:N(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${P}/organizations/roles/create`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),permission:ht(e),role:N(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:ht(e),roleId:N(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${P}/organizations/roles/remove`]:{build:({body:e})=>({roleId:N(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Br=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof d)throw i;const u=i,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new d("auth admin operation failed",{code:h,status:Ur[h]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new d(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new d("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[i.method];if(h===void 0)throw new d(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(a.url),w={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:v=>e.queryParameter(f,v)},E=i.build(w),O=await t(()=>h(E));return Response.json(i.returns==="void"?{ok:!0}:O,{headers:{"content-type":"application/json"},status:200})},o={};for(const[a,i]of Object.entries(Cr))o[a]=u=>n(u,i);return o},xr="__lunora_admin__:getAuthAuditLog",ft=e=>typeof e=="string"&&e!==""?e:void 0,pt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Hr=e=>async(n,o)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new d("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=ft(o.actorId),u=ft(o.event),h=pt(o.sinceSeq),f=pt(o.limit),w={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...f===void 0?{}:{limit:f}};let E;try{E=await a.read(w)}catch(v){throw v instanceof d?v:(console.error("[lunora] auth audit read failed:",v),new d("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const O={entries:E};return Response.json({result:Qe(O)},{headers:{"content-type":"application/json"},status:200})},Lr=(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}},Mr=async(e,t,n,o,a,i,u)=>{if(n!==void 0&&o.length===0)return;const h=await e.orchestrateExport(i,{args:{tables:o},defaultShardKey:u,headers:t,tables:o});for(const f of h.shards)if(!f.error)for(const w of f.rows??[])a(w)},Gt=async(e,t,n,o,a,i)=>{const u=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:h,shardLocalTables:f}=Lr(e,u);await Mr(t,n,u,f,a,i,e.defaultShardKey??"__root__");const w=e.exportGlobals;if((o===void 0||h.length>0)&&w)for await(const O of w({tables:h}))a(O)},Kr=new TextEncoder,jr=1e3,Qt=10,$r=200,mt=8,zt="lunoraBackupCron",wt=24*1048576,gt=e=>{const t=e.slice(0,Qt).map(o=>xt(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Fr=(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},Ye=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let u=0;u<jr;u+=1){const h=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const f of h.objects)zn(f.key)&&f.customMetadata?.[zt]===o&&a.push(f.key);if(!h.truncated||h.cursor===void 0)break;i=h.cursor}return{eligible:a.length,stale:a.toSorted((u,h)=>h.localeCompare(u)).slice(n)}},Gr=async(e,t,n,o,a)=>{const{stale:i}=await Ye(e,t,n,o),u=new Set(a),h=i.filter(g=>u.has(g)),f=h.slice(0,$r),w=i.length-f.length,E=a.length-h.length;if(f.length===0)return{deleted:[],failed:[],ignored:E,remaining:w};const O=[],v=[];for(let g=0;g<f.length;g+=mt){const b=await Promise.allSettled(f.slice(g,g+mt).map(async _=>(await e.delete(xt(_)),await e.delete(_),_)));for(const[_,p]of b.entries())p.status==="fulfilled"?O.push(p.value):v.push(f[g+_])}return O.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(O.length)}: ${gt(O)}`),v.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(v.length)}: ${gt(v)}`),{deleted:O,failed:v,ignored:E,remaining:w}},Qr=async e=>{const t=e.backupStore;if(!t)throw new d("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=We(e.backupPrefix??Ve),o=e.backupCron,{eligible:a,stale:i}=o===void 0?{eligible:0,stale:[]}:await Ye(t,n,e.backupRetain,o);return{cron:o,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},zr=async(e,t,n,o)=>{const a=e.backupStore,i=e.queryCoordinator;if(!a)throw new d("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!i)throw new d("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!n||n.length===0)throw new d("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const u={authorization:`Bearer ${n}`,"content-type":"application/json"},h=e.backupTables;let f=0,w=0,E=[];await Gt(e,i,u,h,D=>{const M=Kr.encode(`${JSON.stringify(D)}
2
+ `);if(f+=1,w+=M.byteLength,w>wt)throw new d(`scheduled backup reached ${String(w)} bytes of NDJSON, past the ${String(wt)}-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});E.push(M)},t);const v=We(e.backupPrefix??Ve),g=new Date(o.scheduledTime).toISOString(),b=Wn(v,g),_=Fr(E,w);E=[];const p=qn(await crypto.subtle.digest("SHA-256",_));await a.put(b,_,{httpMetadata:{contentType:"application/x-ndjson"},sha256:p});const A={bytes:w,createdAt:g,cron:o.cron,file:b,id:g,rows:f,scheduledTime:o.scheduledTime,sha256:p,...h?{tables:h.join(",")}:{}};await a.put(Vn(b),`${JSON.stringify(A,void 0,2)}
3
+ `,{customMetadata:{[zt]:o.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:D}=await Ye(a,v,e.backupRetain,o.cron);if(D.length>0){const M=D.slice(0,Qt),I=D.length-M.length;console.info(`[lunora] backup retention: ${String(D.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${M.join(", ")}${I>0?` (+${String(I)} more)`:""}`)}}catch(D){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,D)}},Wr=async(e,t)=>{const n=e.backupStore;if(!n)throw new d("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 d("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 Gr(n,We(e.backupPrefix??Ve),a,o,t)},Vr="/_lunora/admin/backup/retention",qr="/_lunora/admin/backup/prune",Jr=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,a=(h,f)=>{o(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},i=async h=>(K(h,"GET","Backup-retention"),a(h,"retention preview"),Response.json(await Qr(t),{headers:{"cache-control":"no-store"}})),u=async h=>{K(h,"POST","Backup-prune"),a(h,"prune");const{confirm:f}=await n(h);if(!Array.isArray(f)||f.some(w=>typeof w!="string"))throw new d("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 Wr(t,f),{headers:{"cache-control":"no-store"}})};return{[qr]:u,[Vr]:i}},yt=500,Yr=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new d("each batch call must be an object",{code:"BAD_REQUEST",status:400});const o=e;if(typeof o.functionPath!="string")throw new d("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 d("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 d("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:o.args===void 0?{}:o.args,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}},Xr=(e,t)=>{if(e.length>yt)throw new d(`RPC batch exceeds the ${String(yt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map;for(const[o,a]of e.entries()){const{entry:i,shardKey:u}=Yr(a,o,t),h=n.get(u)??[];h.push(i),n.set(u,h)}return n},Zr="/_lunora/admin/export",eo="/_lunora/admin/import",to="/_lunora/admin/sync",no="/_lunora/admin/connector/sync",ro="/_lunora/admin/apply",oo="/_lunora/admin/export-tap/run",ao=new TextEncoder,so=async e=>{const n=await be(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new d("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 d("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});o.push(a)}return{tables:o}},Le=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,io=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:a,knownTables:i,queryCoordinator:u,assertAdmin:h,requireAdminOption:f,resolveForwardContext:w,shardDO:E,streamExportRows:O,streamingImport:v,syncGlobals:g}=e,b=async(I,j)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),U=await so(I),{headers:$}=await w(I,j),F=new ReadableStream({async pull(W){const te=V=>{W.enqueue(ao.encode(`${JSON.stringify(V)}
4
+ `))};try{await O(Y,$,U.tables,te),W.close()}catch(V){W.error(V)}}});return new Response(F,{headers:{"content-type":"application/x-ndjson"},status:200})},_=async(I,j)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),U=await ee(I),$=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},F=typeof U.limit=="number"?U.limit:void 0,W=typeof U.globalCursor=="number"?U.globalCursor:0,te=Le(U.tables),{headers:V}=await w(I,j),se=te??i(),G=await Y.orchestrateCdcSync(E,{cursors:$,defaultShardKey:n,headers:V,limit:F,tables:se}),q=g?await g({limit:F,sinceSeq:W}):void 0;return Response.json({global:q,shards:G.shards},{status:200})},p=async(I,j)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),U=await ee(I),$=er(U.cursor),F=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,W=Le(U.tables),{headers:te}=await w(I,j),V=W??i(),se=await Y.orchestrateCdcSync(E,{cursors:$.s,defaultShardKey:n,headers:te,limit:F,tables:V}),G=[],q={...$.s};let Z=!1;for(const ie of se.shards)Z=at(G,ie.changes??[],nr(F))||Z,q[ie.shardKey]=ie.cursor;let _e=$.g;if(g){const ie=await g({limit:F,sinceSeq:$.g});Z=at(G,ie.changes,F)||Z,_e=ie.cursor}const Oe=tr({g:_e,s:q,v:1}),ve={changes:G,hasMore:Z,nextCursor:Oe};return Response.json(ve,{status:200})},A=async(I,j)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),U=await ee(I),F=(Array.isArray(U.batches)?U.batches:[]).map(G=>G).filter(G=>G!==null&&typeof G=="object"&&typeof G.shardKey=="string"&&Array.isArray(G.changes)),W=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:te}=await w(I,j),V=await Y.orchestrateApplyCdc(E,{batches:F,headers:te}),se=W.length>0&&t?await t({changes:W}):0;return Response.json({applied:V.applied+se,failed:V.failed,ok:V.ok},{status:200})},D=async(I,j)=>{const H=me(I,["POST"]);if(H)return H;h(I);const{headers:Y}=await w(I,j),U=await v(I,Y);return Response.json(U,{headers:{"content-type":"application/json"},status:U.failed.length>0?207:200})},M=async(I,j)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(a===void 0||Object.keys(a).length===0||o===void 0)throw new d("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const U=await ee(I),$=typeof U.sink=="string"?U.sink:void 0,F=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,W=Le(U.tables);if($===void 0)throw new d("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const te=a[$];if(te===void 0)throw new d(`Export-tap sink "${$}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:V}=await w(I,j),se=W??i(),G=await Zn({coordinator:Y,cursorStore:o,defaultShardKey:n,headers:V,limit:F,shardDO:E,sink:te,tables:se});return Response.json(G,{headers:{"content-type":"application/json"},status:200})};return{[ro]:A,[no]:p,[Zr]:b,[oo]:M,[eo]:D,[to]:_}},co=(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}},uo=(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}},lo=async(e,t,n)=>{if(!e.body)throw new d("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const o=[],a=[],i=new Map;let u=0,h=0;const f=e.body.getReader(),w=new TextDecoder;let E="",O=0;const v=g=>{h+=1;const b=g.trim();if(b.length===0)return;u+=1;const _=co(b,h);if(!_.ok){o.push(_.error);return}const{doc:p,table:A}=_,D=t.resolveTableSharding?.(A);if(D?.mode.kind==="global"){a.push({doc:p,line:h,table:A});return}const M=uo(p,A,D,n,h);if(!M.ok){o.push(M.error);return}const I=i.get(M.shardKey);I?I.rows.push({doc:p,table:A}):i.set(M.shardKey,{rows:[{doc:p,table:A}],shardKey:M.shardKey,startLine:h})};for(;;){const{done:g,value:b}=await f.read();if(g)break;if(b&&(O+=b.byteLength,O>Ut))throw await f.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=w.decode(b,{stream:!0});let _=E.indexOf(`
5
+ `);for(;_!==-1;){const p=E.slice(0,_);E=E.slice(_+1),v(p),_=E.indexOf(`
6
+ `)}}return E.length>0&&v(E),{errors:o,globalRows:a,perShard:i,received:u}},ho=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),bt=(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},fo=async(e,t,n,o)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:h,received:f}=await lo(e,t,a),w={conflicts:0,errors:i,failed:[],inserted:{}},E=[];if(t.resolveTableSharding===void 0&&h.size>0&&E.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 O=t.queryCoordinator;if(!O)throw new d("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const v=await O.orchestrateImport(o,{batches:[...h.values()],headers:n});bt(w,v),w.failed.push(...ho(v.shards))}if(u.length>0)if(t.importGlobals){const O=u[0]?.line??1,v=await t.importGlobals({rows:u,startLine:O});bt(w,v)}else for(const O of u)w.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:O.line,message:`row targets global table "${O.table}" but no \`importGlobals\` is configured`,table:O.table});return{conflicts:w.conflicts,errors:w.errors,failed:w.failed,inserted:w.inserted,received:f,...E.length>0?{warnings:E}:{}}},Me=e=>typeof e=="object"&&e!==null?e:{},Ke=e=>typeof e.kind=="string"?e.kind:"unknown",po=(e,t)=>{let n=Me(t),o=!1;Ke(n)==="optional"&&(o=!0,n=Me(n._meta?.inner));const a=Ke(n),i=n._meta??{},u={kind:a,name:e,optional:o};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const h=Ke(Me(i.inner));h!=="unknown"&&(u.element=h)}return u},mo=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>po(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),wo="/_lunora/admin/functions",go="/_lunora/admin/cron-jobs",yo="/_lunora/admin/openapi",bo="/_lunora/admin/openrpc",_o="/_lunora/admin/global/tables",Ro="/_lunora/admin/global/table",Eo="/_lunora/admin/global/facet",_t=e=>{if(e===void 0||e==="")return;let t;try{t=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},So=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:{}}),Ao=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"}),To=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:a,requireAdminOption:i}=e,u=g=>{K(g,"GET","Functions");const b=i(g,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(b).flatMap(([p,A])=>A.visibility==="internal"||A.kind==="stream"?[]:[{args:mo(A.args),kind:A.kind,path:p}]).toSorted((p,A)=>p.path.localeCompare(A.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},h=g=>{K(g,"GET","Cron-jobs");const b=i(g,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(b).flatMap(([p,A])=>A.map(D=>({args:D.args,cron:p,functionPath:D.functionPath,name:D.name,shardKey:D.shardKey,workflow:D.workflow}))).toSorted((p,A)=>p.name.localeCompare(A.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},f=g=>(K(g,"GET","OpenAPI"),t(g),Response.json(n.openApiSpec??So,{headers:{"content-type":"application/json"},status:200})),w=g=>(K(g,"GET","OpenRPC"),t(g),Response.json(n.openRpcSpec??Ao,{headers:{"content-type":"application/json"},status:200})),E=async g=>{K(g,"GET","Global-tables");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await b.listTables(),{headers:{"content-type":"application/json"},status:200})},O=async g=>{K(g,"GET","Global-table");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),p=a(_,"table");if(p===void 0)throw new d("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const A=await b.readTablePage({...o(g),filters:_t(a(_,"filters")),table:p});return Response.json(A,{headers:{"content-type":"application/json"},status:200})},v=async g=>{K(g,"GET","Global-facet");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),p=a(_,"table"),A=a(_,"column");if(p===void 0||A===void 0)throw new d("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const D=a(_,"limit"),M=D===void 0?void 0:Number(D),I=await b.facetColumn({column:A,filters:_t(a(_,"filters")),limit:M!==void 0&&Number.isFinite(M)?M:void 0,table:p});return Response.json(I,{headers:{"content-type":"application/json"},status:200})};return{[go]:h,[wo]:u,[Eo]:v,[Ro]:O,[_o]:E,[yo]:f,[bo]:w}},Oo="/_lunora/admin/kv/namespaces",vo="/_lunora/admin/kv/keys",Wt="/_lunora/admin/kv/value",Vt=32*1048576,Rt=60,ko=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=b=>n(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),i=(b,_)=>{const p=new URL(b.url),A=p.searchParams.get("namespace")??"",D=p.searchParams.get("key")??"";if(A==="")throw new d(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(D==="")throw new d(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:D,namespace:A}},u=async(b,_)=>{if(!(await b.listNamespaces()).some(A=>A.binding===_))throw new d(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},h=async b=>(K(b,"GET","KV-namespaces"),a({namespaces:await o(b).listNamespaces()})),f=async b=>{K(b,"GET","KV-keys");const _=o(b),p=new URL(b.url),A=p.searchParams.get("namespace")??"";if(A==="")throw new d("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const D=p.searchParams.get("prefix")??void 0,M=p.searchParams.get("cursor")??void 0,I=p.searchParams.get("limit"),j=I===null?void 0:Number.parseInt(I,10);if(j!==void 0&&(!Number.isInteger(j)||j<1))throw new d("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const H=j===void 0?void 0:Math.min(j,1e3);return await u(_,A),a(await _.listKeys({cursor:M,limit:H,namespace:A,prefix:D}))},v={DELETE:async b=>{const _=o(b),p=i(b,"DELETE");return await u(_,p.namespace),await _.deleteKey(p),a({deleted:!0})},GET:async b=>{const _=o(b),p=i(b,"GET");return await u(_,p.namespace),a(await _.getValue(p))},PUT:async b=>{const _=o(b),p=await t(b,Vt);if(typeof p.namespace!="string"||p.namespace==="")throw new d("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new d("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new d("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<Rt))throw new d("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const A=Math.floor(Date.now()/1e3)+Rt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<A))throw new d("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(_,p.namespace),await _.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),a({ok:!0})}},g=b=>{const _=v[b.method];if(!_)throw new d("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(b)};return{[Oo]:h,[vo]:f,[Wt]:g}},Io="/_lunora/migrate",Po="/_lunora/admin/pitr",Do="/_lunora/admin/rank",No="/_lunora/admin/rankpage",Uo="/_lunora/admin/shard-traffic",Co=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Bo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),xo=async e=>{const n=await be(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!Co.has(n.functionPath))throw new d("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},Ho=async e=>{const n=await be(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new d("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new d("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new d("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new d("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}},Lo=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new d('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Mo=e=>{if(typeof e.table!="string"||e.table.length===0)throw new d("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new d("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new d("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 d("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 d("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Ko=async e=>{const n=await be(e,"Rank page")??{};Mo(n);const o=Lo(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}},jo=async e=>{const n=await be(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},$o=async e=>{const n=await ee(e);if(typeof n.functionPath!="string"||!Bo.has(n.functionPath))throw new d("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 d("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},Fo=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:a,resolveForwardContext:i,shardDO:u}=e,h=(g,b)=>{if(g.method!=="POST")throw new d(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(g))throw new d("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new d(`${b} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},f=async(g,b)=>{const _=h(g,"Migration"),p=await xo(g),{headers:A}=await i(g,b),D=await _.orchestrateMigration(u,{args:p.args,defaultShardKey:t,functionPath:p.functionPath,headers:A,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},w=async(g,b)=>{const _=h(g,"Rank"),p=await Ho(g),{headers:A}=await i(g,b),D=await _.orchestrateRank(u,{headers:A,index:p.index,partitionKey:p.partitionKey,rowId:p.rowId,sortValues:p.sortValues,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},E=async(g,b)=>{const _=h(g,"Rank page"),p=await Ko(g),{headers:A}=await i(g,b),D=await _.orchestrateRankPage(u,{...p,headers:A});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},O=async(g,b)=>{const _=h(g,"Shard-traffic"),p=await jo(g),{headers:A}=await i(g,b),D=await _.orchestrateShardTraffic(u,{headers:A,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},v=async(g,b)=>{if(K(g,"POST","PITR"),!o(g))throw new d("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const _=await $o(g),{headers:p}=await i(g,b),A=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:_.args,functionPath:_.functionPath}),headers:p,method:"POST"});return n(u,_.shardKey??t,A)};return{[Io]:f,[Po]:v,[Do]:w,[No]:E,[Uo]:O}},Go=1,Qo=0,zo=32,Wo=512,Vo=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,qo=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Wo)return;const n=t.split(",");if(!(n.length>zo)){for(const o of n)if(!Vo.test(o.trim()))return;return t}},Jo=e=>{const t=Mn(e.headers.get("traceparent"));if(t===void 0)return;const n=qo(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},Yo=(e,t={})=>{const n=Jo(e),o=t.trustInbound===!0?n:void 0,a=Te(8),i=o?.traceId??Te(16),u=cr(t.sampling,o===void 0?a:i),h=u.isTraced&&(o===void 0||o.sampled);return{decision:u,ignoredUpstream:n!==void 0&&o===void 0,trace:{sampled:h,spanId:a,traceFlags:h?Go:Qo,traceId:i,...o?.parentSpanId===void 0?{}:{parentSpanId:o.parentSpanId},...o?.traceState===void 0?{}:{traceState:o.traceState}}}},Xo=(e,t)=>{t.traceparent=Ln(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Zo=(e,t)=>{let n;return()=>{if(n===void 0){const o=Fn(e),a=t===void 0?void 0:t.cf;n=Kn($n(o),jn(o,a))}return n}},ea="/_lunora/admin/scheduled",ta="/_lunora/admin/scheduled/status",na="/_lunora/admin/scheduled/ws",ra="/_lunora/admin/scheduled/cancel",oa="/_lunora/admin/scheduled/dead",aa="/_lunora/admin/scheduled/dead/retry",sa="/_lunora/admin/scheduled/dead/cancel",ia=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:a}=e,i=(f,w)=>E=>{if(E.method!=="GET")throw new d(`${w} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return o(E).fetch(new Request(`https://scheduler.internal${f}`,{method:"GET"}))},u=(f,w,E=w)=>async O=>{if(O.method!=="POST")throw new d(`${E} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const v=o(O),g=await O.json().catch(()=>{});if(typeof g?.id!="string"||g.id==="")throw new d(`${w} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return v.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:g.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(f))throw new d("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const w=n();return we(w,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ra]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[sa]:u("/dead/cancel","Scheduled dead-letter action"),[oa]:i("/dead","Scheduled dead-letter"),[aa]:u("/dead/retry","Scheduled dead-letter action"),[ea]:i("/list","Scheduled-list"),[ta]:i("/status","Scheduler-status"),[na]:h}},ca=(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=>ca(e,"tlsClientAuth","certVerified")==="SUCCESS"},da=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(Et,e)?Et[e]:void 0)??(()=>!1),ua=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[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.'))}},la="/_lunora/admin/vector/indexes",ha="/_lunora/admin/vector/query",fa=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=async i=>{K(i,"GET","Vector-indexes");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async i=>{K(i,"POST","Vector-query");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new d("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const f=await t(i);if(typeof f.name!="string"||f.name==="")throw new d("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof f.text!="string"||f.text==="")throw new d("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(f.topK!==void 0&&(typeof f.topK!="number"||!Number.isInteger(f.topK)||f.topK<1))throw new d("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const w=await u.queryIndex({name:f.name,text:f.text,topK:f.topK});return Response.json(w,{headers:{"content-type":"application/json"},status:200})};return{[la]:o,[ha]:a}},pa="/_lunora/admin/workflows/instances",ma="/_lunora/admin/workflows/instance",wa="/_lunora/admin/workflows/status",ga={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},ya=e=>e!==null&&Object.hasOwn(ga,e)?e:void 0,St=(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},je=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new d(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},At=()=>{throw new d("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},ba=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,o=async(u,h,f)=>{K(u,"GET","Workflows instances"),t(u);const w=n(h);if(!w)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const E=je(f,"name"),O=ya(f.searchParams.get("status"));return Response.json(await w.listInstances({page:St(f,"page"),perPage:St(f,"perPage"),status:O,workflowName:E}))},a=async(u,h,f)=>{K(u,"GET","Workflows instance"),t(u);const w=n(h);return w?Response.json(await w.getInstance({instanceId:je(f,"id"),workflowName:je(f,"name")})):At()},i=async(u,h)=>{K(u,"POST","Workflows status"),t(u);const f=n(h);if(!f)return At();const w=await u.json().catch(()=>{});if(typeof w?.name!="string"||w.name===""||typeof w.id!="string"||w.id==="")throw new d("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:E}=w;if(E!=="pause"&&E!=="resume"&&E!=="terminate")throw new d("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:E,instanceId:w.id,workflowName:w.name}))};return{[ma]:a,[pa]:o,[wa]:i}},_a={[Wt]:Vt,[Xn]:Yn},Tt="/_lunora/rpc",Ra="/_lunora/rpc-batch",Ea="/_lunora/ws",Ee=(e,t,n)=>({resourceAttributes:Zo(e,t),...n===void 0?{}:{waitUntil:n}}),$e=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Ot=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Fe=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let o;try{o=new URL(e.url)}catch{return{method:t,userAgent:n}}const a=o.port===""?void 0:Number(o.port);return{host:o.hostname,method:t,path:o.pathname,port:Number.isNaN(a)?void 0:a,scheme:o.protocol.replace(":",""),userAgent:n}},vt="/_lunora/voice/",Sa="/_lunora/scheduler/dispatch",Aa="/_lunora/admin/cron-jobs/run",Ta="/_lunora/admin/ws-token",Oa="/_lunora/admin/",va="/_lunora/migrate",ka="/_lunora/status",Ia=e=>e.startsWith(Oa)||e===va,Pa=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}}},Da="/api/auth",Na="__lunora_admin__:recordAuthEvent",Ua="__lunora_admin__:listPushSubscriptions",Ca=["/sign-in","/sign-up","/callback"],Ba=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return Ca.some(a=>o===a||o.startsWith(`${a}/`))},Se=(e,t,n,o)=>{const a=Dn(n),i=a?n.code:"INTERNAL_SERVER_ERROR",u=a?n.status:500,h=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:h,status:u},functionPath:e,ok:!1,...o.fanOut?{fanOut:{failed:0,shards:0,table:o.fanOut.table}}:{},...o.shardKey?{shardKey:o.shardKey}:{}}},xa=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},kt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Ha=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ze=new WeakMap,ue=async(e,t,n,o=ze.get(e))=>{const a={"content-type":"application/json"},i=e.headers.get("authorization"),u=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),f=e.headers.get("x-lunora-mutation-id"),w=e.headers.get("x-lunora-client-id"),E=e.headers.get("x-lunora-client-seq");i&&(a.authorization=i),u&&(a.cookie=u),h&&(a["x-d1-bookmark"]=h),f&&(a["x-lunora-mutation-id"]=f),w&&(a["x-lunora-client-id"]=w),E&&(a["x-lunora-client-seq"]=E);const O=e.headers.get("cf-connecting-ip");if(O&&(a["x-lunora-client-ip"]=O),!n)return{claims:null,headers:a,identity:null,userId:null};const v=await n(e,t,o);if(!v||typeof v.userId!="string"||v.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=xn(v.userId);const g=xa(v);g!==void 0&&(a["x-lunora-identity-exp"]=String(g));const{userId:b,..._}=v,p=Object.keys(_).length>0?_:null;return p&&(a["x-lunora-identity"]=Hn(p)),{claims:p,headers:a,identity:v,userId:b}},La=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Ma=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new d("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 d("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new d("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!La.has(n.kind))throw new d("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 d("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 d("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Ka=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},Ge=(e,t)=>{const n=t.functions?.[e.functionPath]?.x402;if(n){if(e.fanOut)throw new d("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new d(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},ja=async e=>{const t=await Bt(e);let n;try{n=JSON.parse(t)}catch{throw new d("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new d("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const o=n;if(o.args!==void 0&&Ct(o.args,"RPC"),o.shardKey!==void 0&&typeof o.shardKey!="string")throw new d("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,i=Ma(a.fanOut),u=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==i.table)throw new d("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},Ae=new Map,$a=5e3,Fa=4096,Ga=async(e,t)=>{const n=Date.now(),o=Ae.get(t);if(o!==void 0&&o.expiresMs>n)return o.relayCount;o!==void 0&&Ae.delete(t);let a=0;try{const i=await we(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const h=(await i.json()).relayCount;typeof h=="number"&&h>0&&(a=Math.floor(h))}}catch{a=0}return Nt(Ae,Fa),Ae.set(t,{expiresMs:n+$a,relayCount:a}),a},It=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},ye=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),Qa=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],Pt=(e,t)=>{for(const n of Qa){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},za=async(e,t,n)=>e.length===0||n.length===0?!1:qe(await Mt(e,t),n),Dt=(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:qe(t,a.join(" ").trim())},Wa=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 Nr(t,o)?!0:n?!1:qe(t,o)},Va=(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 ar(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return Be(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return Be(`queue:${e}`,!0);if(typeof n.connectionString=="string")return Be(`hyperdrive:${e}`,!0)},qt=e=>{const t=da(e.trustInboundTraceContext),n=ua(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",a=sr(e.resolveIdentity,e.identity),i=it(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:it(e.schedulerDO,e.jurisdiction);let h=!1;const f=r=>{if(r===void 0||e.jurisdiction===void 0)return r;h||(h=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},w=async(r,s,l,c=e.shardRegion?.(s))=>we(r,s,f(c)).fetch(l);let E;const O=()=>e.adminToken??E;let v;const g=()=>e.requireEphemeralWsToken??v??!0;let b;const _=r=>{const s=r??{};if(b??=It(r,e.shardDO),v===void 0&&e.requireEphemeralWsToken===void 0){const c=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(v=Ir(c,!0))}if(E!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(E=l)},p=new WeakSet,A=r=>Dt(r,O())||p.has(r),D=async(r,s)=>{const l=await ue(r,s,e.resolveIdentity);if(p.has(r)&&l.headers.authorization===void 0){const c=O();c!==void 0&&(l.headers.authorization=`Bearer ${c}`)}return l};let M=!1,I=!1;const j=()=>{I||(I=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},H=r=>{if(!e.allowUnauthenticatedShardAccess){const s=r==="fan-out"?"authorizeFanOut":"authorizeShard";throw new d(`${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})}M||(M=!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("")))},Y=async(r,s)=>{if(e.authorizeShard){if(!await e.authorizeShard({identity:r,shardKey:s}))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==o&&H("shard")},U=Fo({defaultShard:o,forwardToShard:w,isAdmin:A,queryCoordinator:e.queryCoordinator,resolveForwardContext:D,shardDO:i}),$=async(r,s,l,c,m)=>{const R={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(R["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(R["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(R["x-lunora-mutation-id"]=c),w(i,l,ye(r,s,R))},F=async(r,s,l,c)=>{const m=l?.[r];if(!m||typeof m.create!="function")throw new d(`${c} targets workflow binding "${r}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(hr(s))throw new d(`${c} params ${fr}`,{code:"BAD_REQUEST",status:400});await m.create({params:s})},W=async(r,s)=>{if(r.workflow){await F(r.workflow,r.args??{},s,`cron job "${r.name}"`);return}if(r.functionPath===void 0)throw new d(`cron job "${r.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const l=await $(r.functionPath,r.args??{},r.shardKey??o);if(!l.ok)throw new d(`cron job "${r.name}" (${r.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},te=async(r,s,l,c)=>{const m=e.cronJobs?.[r];if(m)for(const R of m)try{await W(R,s)}catch(k){l.push(c(k))}},V=async(r,s)=>{if(!A(r))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(K(r,"POST","cron-jobs run"),!e.cronJobs)throw new d("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await ee(r),c=typeof l.name=="string"?l.name:"";if(c==="")throw new d("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(R=>R.name===c);if(!m)throw new d(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await W(m,s),Response.json({name:c,ran:!0},{status:200})},se=async r=>{const s=typeof r.pool=="string"&&r.pool.length>0?r.pool:void 0;if(!s||!u||typeof r.id!="string")return;const l=typeof r.instanceName=="string"&&r.instanceName.length>0?r.instanceName:"default";try{await we(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:r.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},G=async(r,s)=>{K(r,"POST","Scheduler dispatch");const l=await Bt(r),c=s??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,R=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),k=r.headers.get("x-lunora-scheduler-signature");let y=!1;if(k&&m?y=await za(m,l,k):R&&(y=Dt(r,R)),!y)throw new d("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let S;try{S=JSON.parse(l)}catch{throw new d("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const T=S??{},C=T.args??{};if(typeof T.workflow=="string"&&T.workflow.length>0)return await F(T.workflow,C,s,"scheduled workflow"),await se(T),Response.json({ok:!0},{status:200});if(typeof T.functionPath!="string"||T.functionPath.length===0)throw new d("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const B=typeof T.shardKey=="string"&&T.shardKey.length>0?T.shardKey:o,x=typeof T.id=="string"&&T.id.length>0?T.id:void 0,re=Pa(r),L=await $(T.functionPath,C,B,x,re);return await se(T),L},q=r=>{if(!A(r))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},Z=(r,s,l)=>{if(q(r),s===void 0)throw new d(l.message,{code:l.code,status:400});return s},_e=Hr({assertAdmin:q,getReader:()=>e.authAuditReader}),Oe=async(r,s)=>{q(r);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:Qe({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const c=s?.kind,m=s?.userId,R=s?.limit,k=c==="fcm"||c==="web-push"?c:void 0,y=typeof m=="string"&&m!==""?m:void 0,S=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,T=S>0?Math.min(S,1e3):1e3,B=(await l.list({kind:k,limit:T,userId:y})).filter(x=>k!==void 0&&x.kind!==k?!1:y===void 0||(x.userId??null)===y).map(({keys:x,token:re,...L})=>L);return Response.json({result:Qe({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},ve=async(r,s)=>{if(!s.fanOut){if(s.functionPath===xr)return _e(r,s.args??{});if(s.functionPath===Ua)return Oe(r,s.args)}},ie=io({applyGlobals:e.applyGlobals,assertAdmin:q,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:o,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:Z,resolveForwardContext:D,shardDO:i,streamExportRows:(r,s,l,c)=>Gt(e,r,s,l,c,i),streamingImport:(r,s)=>fo(r,e,s,i),syncGlobals:e.syncGlobals}),ke=(r,s)=>{const l=r.searchParams.get(s);return l===null||l===""?void 0:l},Ie=r=>{const s=new URL(r.url),l=s.searchParams.get("limit"),c=s.searchParams.get("offset"),m=l===null?void 0:Number.parseInt(l,10),R=c===null?void 0:Number.parseInt(c,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},Xe=()=>{if(u===void 0)throw new d("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},Jt=ia({checkWsAdmin:async r=>A(r)||Wa(r,O(),g()),requireSchedulerNamespace:Xe,resolveSchedulerStub:r=>(q(r),we(Xe(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Yt=ba({assertAdmin:q,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Xt=Jn({assertAdmin:q,parsePaging:Ie,queryParameter:ke,readBodyBytes:Qn,requireAdminOption:Z,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Zt=Jr({options:e,readJsonBody:ee,requireAdminOption:Z}),en=fa({readJsonBody:ee,requireAdminOption:Z,vectorIntrospector:e.vectorIntrospector}),tn=ko({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:Z}),nn=ir({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:Z}),rn=To({assertAdmin:q,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ie,queryParameter:ke,requireAdminOption:Z}),on=r=>{const s=[],l=i??r?.SHARD;if(l!==void 0&&s.push(or("durable-object:default",l,o)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(r??{})){const R=Va(c,m);R!==void 0&&s.push(R)}for(const c of e.health?.probes??[])s.push(c);return s},an=rr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:A,resolveProbes:on}),sn=r=>{const s=e.schedulerInstanceName??"default",l=()=>we(r,s),c=async(y,S)=>{const T=await l().fetch(new Request(`https://scheduler.internal${y}`,S));if(!T.ok)throw new d(`ctx.scheduler: SchedulerDO ${y} failed (${String(T.status)}): ${await T.text()}`,{code:"INTERNAL",status:500});return await T.json()},m=async(y,S)=>await c(y,{body:JSON.stringify(S),headers:{"content-type":"application/json"},method:"POST"}),R=y=>{const S=y;if(S==null)throw new d("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof S.binding=="string"&&S.binding.length>0)return{workflow:S.binding};if(typeof S.__lunoraRef=="string")return{functionPath:S.__lunoraRef};throw new d("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})},k=async(y,S,T={})=>{const{id:C}=await m("/schedule",{args:T,scheduledFor:y,...R(S)});return C};return{cancel:async y=>await m("/cancel",{id:y}),get:async y=>await c(`/get?id=${encodeURIComponent(y)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(y,S,T)=>{if(!Number.isFinite(y)||y<0)throw new d("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await k(Date.now()+y,S,T)},runAt:async(y,S,T)=>{if(!Number.isFinite(y))throw new d("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await k(y,S,T)}}},cn=async(r,s,l)=>{const{claims:c,headers:m,userId:R}=await ue(r,s,a),k=async(y,S={})=>{const T=y.__lunoraRef;if(typeof T!="string")throw new d("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const C=ye(T,S,{...m,"x-lunora-system":"1"}),B=await w(i,o,C),x=await B.json();if(x.error)throw new d(x.error.message??"shard RPC failed",{code:x.error.code??"INTERNAL",status:B.status});return x.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:R},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),runAction:k,runMutation:k,runQuery:k,...u===void 0?{}:{scheduler:sn(u)},...e.storage===void 0?{}:{storage:lr(e.storage(s))}}},dn=async(r,s,l)=>{if(!e.httpRouter)return;const c=await cn(r,s,l);try{return await e.httpRouter.fetch(r,{...s,__lunoraCtx:c},l)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},un=async(r,s,l)=>{if(r.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=dt(r,ce);if(c)return c;const m=l.searchParams.get("shard")??o,{headers:R,identity:k}=await ue(r,s,a);await Y(k,m);const y=new Headers(r.headers),S=[...y.keys()];for(const C of S)C.startsWith("x-lunora-")&&y.delete(C);Pt(y,R);const T=It(s,e.shardDO);if(T!==void 0){y.set("x-lunora-shard-binding",T);const C=await Ga(i,m);if(C>0){const B=Ar(m,Math.floor(Math.random()*C));return w(i,B,new Request(r,{headers:y}),ut(r))}}return w(i,m,new Request(r,{headers:y}))},ln=async(r,s,l)=>{const{voiceAgents:c}=e;if(c===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 m=dt(r,ce);if(m)return m;let R;try{R=decodeURIComponent(l.pathname.slice(vt.length))}catch{return new Response("Unknown voice agent",{status:404})}const k=Object.hasOwn(c,R)?c[R]:void 0;if(k===void 0)return new Response("Unknown voice agent",{status:404});const y=l.searchParams.get("threadKey");if(y===null||y.length===0)return new Response("Missing threadKey",{status:400});const{headers:S,identity:T}=await ue(r,s,a);if(e.authorizeShard){if(!await e.authorizeShard({identity:T,shardKey:y}))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else H("shard");const C=new Headers(r.headers);for(const B of C.keys())B.startsWith("x-lunora-")&&C.delete(B);return Pt(C,S),w(k,y,new Request(r,{headers:C}))},hn=async(r,s,l)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(l,r.table,s))throw new d("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new d("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 d("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});H("fan-out")},Re=async(r,s)=>{if(!(!r.fanOut&&r.functionPath.startsWith("__lunora_admin__:"))){if(r.fanOut){await hn(r.fanOut,r.functionPath,s);return}await Y(s,r.shardKey??o)}},fn=(r,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){j();return}if(e.functions[s]?.kind!=="query"||l.includes(jt)||l.includes(Kt))return;const c=ut(r);return c===void 0?void 0:{name:Tr(l,c),region:c}},pn=async(r,s,l,c,m)=>{const R=fn(r,s,c);if(R!==void 0){const k={...m,"x-lunora-replica-read":"1",...b===void 0?{}:{"x-lunora-shard-binding":b}},y=Or(r.headers.get("x-lunora-min-seq"));y!==void 0&&(k["x-lunora-min-seq"]=String(y));const S=await w(i,R.name,ye(s,l,k),R.region);if(S.status!==421)return S}return w(i,c,ye(s,l,m))},Pe=async(r,s,l,c,m,R)=>{const k=Date.now(),{observability:y,sampling:S}=e,T=Fe(r),{decision:C,ignoredUpstream:B,trace:x}=Yo(r,{...S===void 0?{}:{sampling:S},trustInbound:t(r)});B&&n();const re={...m,"x-lunora-sample-errors":C.keepErrors?"1":"0"};Xo(x,re);try{const L=await pn(r,s,l,c,re);de(y,{...T,...Ot(x),durationMs:Date.now()-k,functionPath:s,ok:L.ok,shardKey:c,...L.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(L.status)}`,status:L.status}}},R,void 0,{isTraced:x.sampled,keepErrors:C.keepErrors});const ne=new Response(L.body,{headers:L.headers,status:L.status,statusText:L.statusText});return ne.headers.set("x-lunora-shard-key",c),ne}catch(L){throw de(y,{...T,...Ot(x),...Se(s,Date.now()-k,L,{shardKey:c})},R,void 0,{isTraced:x.sampled,keepErrors:C.keepErrors}),L}},mn=r=>{if(r.fanOut&&r.shardKey)throw new d("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!r.fanOut&&r.functionPath.startsWith("__lunora_relation__:"))throw new d("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(r.fanOut&&!e.queryCoordinator)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},wn=async(r,s,l)=>{K(r,"POST","RPC");const c=await ja(r);Ka(s,c),mn(c);const m=await ve(r,c);if(m!==void 0)return m;const{headers:R,identity:k}=await ue(r,s,a);await Re(c,k);const y=Ge(c,e);{const S=Date.now(),{observability:T}=e,C=Fe(r),B=Ee(s,r,l&&(L=>l.waitUntil?.(L)));if(c.fanOut){const L=e.queryCoordinator;if(!L)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ne=await L.fanOut(i,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:R});return de(T,{durationMs:Date.now()-S,fanOut:{failed:ne.failed,shards:ne.ok+ne.failed,table:c.fanOut.table},functionPath:c.functionPath,...C,ok:!0},B),Response.json(ne,{headers:{"content-type":"application/json"},status:200})}catch(ne){throw de(T,{...Se(c.functionPath,Date.now()-S,ne,{fanOut:{table:c.fanOut.table}}),...C},B),ne}}const x=c.shardKey??o,re=()=>Pe(r,c.functionPath,c.args??{},x,R,B);return y&&e.x402Charge?e.x402Charge(r,{functionPath:c.functionPath,price:y.price},re,$e(l)):re()}},gn=async(r,s,l)=>{K(r,"POST","RPC batch");const c=await ee(r),{calls:m}=c;if(!Array.isArray(m))throw new d("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:k}=await ue(r,s,a),y=Xr(m,o);for(const Q of y.values())for(const z of Q)if(e.functions?.[z.functionPath]?.x402)throw new d(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${Tt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...y.entries()].flatMap(([Q,z])=>z.map(oe=>Re({args:oe.args,functionPath:oe.functionPath,shardKey:Q},k))));const{observability:S}=e,T=Ee(s,r,l&&(Q=>l.waitUntil?.(Q))),C=Fe(r),B=[],x=[],re=(Q,z,oe,le)=>({body:{error:{code:oe,message:le}},id:Q.id,status:z}),L=(Q,z,oe,le,fe)=>{for(const J of Q)de(S,fe(J),T),B.push(re(J,z,oe,le))},ne=(Q,z,oe,le,fe)=>{for(const J of Q){const pe=le.get(J.id)??fe,ge=pe<400;de(S,{durationMs:oe,functionPath:J.functionPath,...C,ok:ge,shardKey:z,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},T)}};await Promise.all([...y.entries()].map(async([Q,z])=>{const oe=new Headers(R);oe.set("content-type","application/json");const le=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:oe,method:"POST"}),fe=Date.now();let J;try{J=await w(i,Q,le)}catch(X){const Ce=Date.now()-fe,{body:rt}=Nn(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});L(z,502,rt.code,rt.message,Pn=>({...Se(Pn.functionPath,Ce,X,{shardKey:Q}),...C}));return}const pe=Date.now()-fe,ge=J.headers.get("x-d1-bookmark");ge&&x.push(ge);let Ne;try{Ne=await J.json()}catch{const X=`shard batch returned a non-JSON response (${String(J.status)})`;L(z,J.status,"SHARD_ERROR",X,Ce=>({durationMs:pe,error:{code:"SHARD_ERROR",message:X,status:J.status},functionPath:Ce.functionPath,...C,ok:!1,shardKey:Q}));return}const Ue=Array.isArray(Ne.results)?Ne.results:[],kn=new Map(Ue.map(X=>[X.id,X.status??J.status])),In=new Set(Ue.map(X=>X.id));ne(z,Q,pe,kn,J.status),B.push(...Ue);for(const X of z)In.has(X.id)||B.push(re(X,J.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const tt={"content-type":"application/json"},[nt]=x;return x.length===1&&nt!==void 0&&(tt["x-d1-bookmark"]=nt),Response.json({results:B},{headers:tt,status:200})},yn=async(r,s,l,c={},m={})=>{try{const R=l.__lunoraRef;if(typeof R!="string")throw new d("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:k,identity:y}=await ue(r,s,a,m.context),S={args:c,functionPath:R,shardKey:m.shardKey};await Re(S,y);const T=m.shardKey??o,C=Ee(s,r,m.waitUntil),B=()=>Pe(r,R,c,T,k,C),x=Ge(S,e);return x&&e.x402Charge?await e.x402Charge(r,{functionPath:R,price:x.price},B,$e(m.waitUntil?{waitUntil:m.waitUntil}:m.context)):await B()}catch(R){return ot(R)}},Ze=async(r,s,l)=>{const{observability:c}=e,m=Date.now(),R=Te(16),k=Te(8),y=kt(s);try{const S=await l();return de(c,{durationMs:Date.now()-m,functionPath:r,ok:!0,spanId:k,traceId:R},y),S}catch(S){throw de(c,{...Se(r,Date.now()-m,S,{}),spanId:k,traceId:R},y),S}finally{st(c,y)}},bn=async(r,s,l)=>{_(s);const c=[],m=y=>y instanceof Error?y:new Error(String(y)),R=e.crons?.[r.cron];if(R)try{await R(r,s,l)}catch(y){c.push(m(y))}if(await te(r.cron,s,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===r.cron)try{await zr(e,i,O(),r)}catch(y){c.push(m(y))}const[k]=c;if(c.length===1&&k)throw k;if(c.length>1)throw new AggregateError(c,`scheduled("${r.cron}") had ${String(c.length)} failure(s)`)},_n=async(r,s)=>{try{const l=r??{},c=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await w(i,o,ye(Na,{outcome:s},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},Rn=async(r,s,l,c)=>{if(!e.authHandler)return;const m=await e.authHandler(r);if(!m)return;const R=e.authBasePath??Da;return Ba(l.pathname,R)&&c.waitUntil?.(_n(s,m.status>=400?"fail":"ok")),m},En=async({args:r,env:s,functionPath:l,request:c,shardKey:m,waitUntil:R})=>{Ct(r,"REST");const k={functionPath:l,...m===void 0?{}:{shardKey:m}},{headers:y,identity:S}=await ue(c,s,a);await Re(k,S);const T=m??o,C=Ee(s,c,R),B=()=>Pe(c,l,r,T,y,C),x=Ge(k,e);return x&&e.x402Charge?e.x402Charge(c,{functionPath:l,price:x.price},B,$e({waitUntil:R})):B()},Sn=Gn({functions:e.functions??{},invoke:En,readJsonBody:ee,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),De=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,An={[ka]: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"}}),[Ea]:(r,s,l)=>un(r,s,l),[Tt]:(r,s,l,c)=>wn(r,s,c),[Ra]:(r,s,l,c)=>gn(r,s,c),[Sa]:(r,s)=>G(r,s),[Aa]:(r,s)=>V(r,s),[Ta]:async r=>{K(r,"POST","ws-token"),q(r);const s=O();if(s===void 0)throw new d("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Dr(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...U,...ie,...Jt,...Yt,...Xt,...Zt,...en,...tn,...nn,...rn,...an,...Sn,...Br({assertAdmin:q,getAuthAdmin:()=>e.authAdmin,parsePaging:Ie,queryParameter:ke,readJsonBody:ee})};let ce=ct(e.security),et=!1;const Tn=r=>{et||(et=!0,ce=ct(e.security,r??{}))},On=async(r,s)=>{if(!(e.adminGate===void 0||!Ia(s)))try{await e.adminGate(r,ze.get(r))&&p.add(r)}catch{}},vn=async(r,s,l)=>{ze.set(r,l);const c=new URL(r.url);if(r.method==="POST"||r.method==="PUT"){const y=Number(r.headers.get("content-length")??""),S=_a[c.pathname]??Ut;if(Number.isFinite(y)&&y>S)throw new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await Rn(r,s,c,l);if(m)return m;if(De){const y=`${r.method} ${c.pathname}`,S=De[y]??De[c.pathname];if(S)return S(r,s,l)}const R=An[c.pathname];if(R)return await On(r,c.pathname),R(r,s,c,l);if(e.voiceAgents!==void 0&&c.pathname.startsWith(vt))return ln(r,s,c);const k=await dn(r,s,l);return k||new Response("Not found",{status:404})};return{async fetch(r,s,l){e.passThroughOnException&&l.passThroughOnException?.(),Tn(s),_(s);const c=dr(r,ce);if(c)return c;const m=ur(r,ce);if(m)return xe(m,r,ce);try{const R=await vn(r,s,l);return xe(R,r,ce)}catch(R){return xe(ot(R),r,ce)}finally{st(e.observability,kt(l))}},async queue(r,s,l){await Ze(`queue:${Ha(r)}`,l,async()=>{await e.queue?.(r,s,l)})},async scheduled(r,s,l){await Ze(`cron:${r.cron}`,l,async()=>{await bn(r,s,l)})},serverQuery:yn}},qa=e=>qt(e),Ja=e=>typeof e=="function"?{fetch:e}:e,Ya=e=>!!(e.crons??e.cronJobs??e.backupCron),bs=(e,t)=>{const n=Ja(e),o=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=u=>{const h=qa({...u,httpRouter:n});return o!==void 0&&!Ya(u)?{...h,scheduled:async(f,w,E)=>{await o(f,w,E)}}:h};if(typeof t!="function")return a(t);const i=t;return{fetch:(u,h,f)=>a(i(h)).fetch(u,h,f),queue:(u,h,f)=>a(i(h)).queue?.(u,h,f)??Promise.resolve(),scheduled:(u,h,f)=>a(i(h)).scheduled(u,h,f),serverQuery:(u,h,f,w,E)=>a(i(h)).serverQuery(u,h,f,w,E)}},Xa=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new d("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},_s=(e={})=>(t,n,o)=>qt(Xa(e,n)).fetch(t,n,o??Un),Rs=e=>e;export{xr as GET_AUTH_AUDIT_LOG_OP,Un as NOOP_EXECUTION_CONTEXT,As as composeIdentityResolvers,qa as composeWorker,_s as createLunoraHandler,qt as createWorker,Rs as defineRpcEnvelope,Ga as probeRelayCount,Xa as resolveLunoraOptions,Ts as routeIdentityResolvers,bs as withFrameworkWorker};
@@ -0,0 +1 @@
1
+ import{e as c,a as u}from"./identity-header-C4Z5pldl.mjs";import{d as f}from"./wire-codec-BsPOEXGn.mjs";import{LunoraError as s}from"./LunoraError-DksAgIpa.mjs";const l="/_lunora/rpc",h=e=>{const a={"content-type":"application/json"};return e.userId!==void 0&&e.userId.length>0&&(a["x-lunora-userid"]=c(e.userId)),e.identity!==void 0&&(a["x-lunora-identity"]=u(e.identity)),a},d=async(e,a,o)=>{const t=await(e.fetch??globalThis.fetch)(new Request(`${e.origin}${l}`,{body:JSON.stringify(a),headers:h(e),method:"POST"}));if(!t.ok)throw new s(`cross-shard relation ${o} failed: worker returned ${String(t.status)}`);const r=await t.json();if(typeof r.failed=="number"&&r.failed>0){const i=(typeof r.ok=="number"?r.ok:0)+r.failed;throw new s(`cross-shard relation ${o} failed on ${String(r.failed)} of ${String(i)} shard(s) — refusing to return a partial result`)}return f(r.data)},_=e=>({crossShardCounter:async(n,t)=>{const r=await d(e,{args:{table:n,where:t},fanOut:{merge:{kind:"sum"},table:n},functionPath:"__lunora_relation__:count"},"count");return typeof r=="number"?r:0},crossShardReader:async(n,t)=>{const r=await d(e,{args:{...t,table:n},fanOut:{merge:{kind:"concat"},table:n},functionPath:"__lunora_relation__:read"},"read");return{continueCursor:null,isDone:!0,page:Array.isArray(r)?r:[]}}});export{_ as createCrossShardRelationCapabilities};
@@ -0,0 +1 @@
1
+ import{c as o,a as s,d as t,r as i,b as n,s as p,w as S}from"./export-tap-CgiuS5w4.mjs";import"./portable-json-DPJbalfn.mjs";export{o as createKvCursorStore,s as createMemoryCursorStore,t as defineExportSink,i as r2Sink,n as runExportTap,p as sanitizeChange,S as webhookExportSink};
@@ -0,0 +1 @@
1
+ import{b as T,a as E}from"./base64-Bl1_r2k1.mjs";import{LunoraError as U}from"./LunoraError-DksAgIpa.mjs";import{resolveShard as I}from"./applyJurisdiction-C0ddU7Tg.mjs";const pe=r=>({listShardKeys(e){return r[e]??[]}}),F=16,B=5e3,h=r=>r!==null&&typeof r=="object"&&"result"in r?r.result:r,V=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}},D=(r,e)=>r?"failed":e?"in_progress":"completed",L=r=>{const e=[];let s=0,n=0,t=0,o=0,a=!1,c=!1;for(const i of r){if(i.kind==="err"){n+=1,e.push({error:{message:i.message,timedOut:i.timedOut},shardKey:i.shardKey});continue}s+=1;const l=h(i.value),u=V(l);t+=u.changed,o+=u.processed,a||=u.status==="in_progress",c||=u.status==="failed",e.push({result:l,shardKey:i.shardKey})}return{changed:t,failed:n,ok:s,processed:o,shards:e,status:D(c,a||n>0)}},j=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}},J=r=>{const e=[];let s=0,n=0,t=0,o=0;for(const a of r){if(a.kind==="err"){n+=1,e.push({error:{message:a.message,timedOut:a.timedOut},shardKey:a.shardKey});continue}s+=1;const c=j(h(a.value));t+=c.before,o+=c.total,e.push({result:c,shardKey:a.shardKey})}return{failed:n,ok:s,partial:n>0,position:t+1,shards:e,total:o}},P=0,v=1,$=2,k=(r,e)=>r<e?-1:r>e?1:0,M=r=>r==null?P:typeof r=="number"?v:$,O=(r,e)=>{const s=M(r),n=M(e);return s!==n?s<n?-1:1:s===P?0:s===v?k(r,e):k(String(r),String(e))},G=(r,e,s)=>{const n=O(r.partitionKey,e.partitionKey);if(n!==0)return n;const t=Math.max(r.sortValues.length,e.sortValues.length);for(let o=0;o<t;o+=1){const a=O(r.sortValues[o],e.sortValues[o]);if(a!==0)return s[o]==="desc"?-a:a}return O(r.rowId,e.rowId)},Q=r=>E(new TextEncoder().encode(JSON.stringify(r))),Y=r=>{try{const e=JSON.parse(new TextDecoder().decode(T(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:{}}},H=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}},W=(r,e)=>{let s;for(const n of r){const t=n.rows[n.head];t!==void 0&&(s===void 0||G(t.key,s.row.key,e)<0)&&(s={row:t,slice:n})}return s},X=(r,e)=>{let s=!1;const n=new Set;for(const o of r)n.add(o.shardKey),(o.head<o.rows.length||o.hasMore)&&(s=!0);const t={...e};for(const o of Object.keys(e))n.has(o)||(s=!0);return s?Q({perShard:t}):null},z=(r,e,s,n)=>{const t=[],o={...n};for(;t.length<e;){const c=W(r,s);if(c===void 0)break;t.push(c.row.doc),o[c.slice.shardKey]=c.row.key,c.slice.head+=1}const a=X(r,o);return{isDone:a===null,nextCursor:a,page:t}},Z=r=>{const e=[];let s=0,n=0;for(const t of r){if(t.kind==="err"){n+=1,e.push({error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const o=h(t.value),a=Array.isArray(o?.rows)?o.rows:[];e.push({rows:a,shardKey:t.shardKey})}return{failed:n,ok:s,shards:e}},q=r=>{const e=[];let s=0,n=0;for(const{outcome:t,sinceSeq:o}of r){if(t.kind==="err"){n+=1,e.push({cursor:o,error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const a=h(t.value),c=Array.isArray(a?.changes)?a.changes:[],i=typeof a?.cursor=="number"?a.cursor:o;e.push({changes:c,cursor:i,shardKey:t.shardKey})}return{failed:n,ok:s,shards:e}},ee=r=>{let e=0,s=0,n=0;for(const t of r){if(t.kind==="err"){s+=1;continue}e+=1;const o=h(t.value);n+=typeof o?.applied=="number"?o.applied:0}return{applied:n,failed:s,ok:e}},re=r=>{const e=r??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},te=r=>{const e=[];let s=0,n=0;for(const t of r){if(t.kind==="err"){n+=1,e.push({requests:0,shardKey:t.shardKey});continue}s+=1,e.push({requests:re(h(t.value)),shardKey:t.shardKey})}return{failed:n,ok:s,shards:e}},se=r=>{const e=[],s={},n=[];let t=0,o=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}o+=1;const i=h(c.value),l=i?.inserted??{};for(const[f,y]of Object.entries(l))s[f]=(s[f]??0)+y;const u=i?.errors;Array.isArray(u)&&n.push(...u),t+=i?.conflicts??0,e.push({result:{conflicts:i?.conflicts??0,errors:i?.errors??[],inserted:l},shardKey:c.shardKey})}return{conflicts:t,errors:n,failed:a,inserted:s,ok:o,shards:e}},p=r=>({body:JSON.stringify({args:r.args??{},functionPath:r.functionPath}),headers:{"content-type":"application/json",...r.headers}}),g=async(r,e,s,n)=>{const t=I(r,e),o=new AbortController,a=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:o.signal});let c;const i=new Promise(u=>{c=setTimeout(()=>{try{o.abort()}catch{}u({kind:"err",message:`shard "${e}" timed out after ${String(n)}ms`,shardKey:e,timedOut:!0})},n)}),l=(async()=>{try{const u=await t.fetch(a);if(!u.ok)return{kind:"err",message:`shard "${e}" returned ${String(u.status)}`,shardKey:e,timedOut:!1};const f=await u.json();return{kind:"ok",shardKey:e,value:f}}catch(u){const f=u instanceof Error?u.message:String(u);return{kind:"err",message:`shard "${e}" threw: ${f}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([l,i])}finally{c!==void 0&&clearTimeout(c)}},w=async(r,e,s)=>{if(r.length===0)return[];const n=Array.from({length:r.length});let t=0;const o=async()=>{for(;;){const c=t;t+=1;const i=r[c];if(c>=r.length||i===void 0)return;n[c]=await s(i,c)}},a=Math.min(e,r.length);return await Promise.all(Array.from({length:a},()=>o())),n},x=async(r,e)=>{const s=await Promise.all(e.map(async n=>r.listShardKeys(n)));return[...new Set(s.flat())]},R=(r,e)=>r.length>0||e===null?r:[e],m=async(r,e,s,n,t)=>{const o=p(s);return w(e,n,async a=>g(r,a,o,t))},ne=r=>{const e={};for(const s of Object.keys(r).toSorted(k))e[s]=r[s]??null;return JSON.stringify(e)},oe=r=>r.flatMap(e=>Array.isArray(e)?e:[]),ae=(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}},ce=(r,e,s)=>{if(e===null||typeof e!="object")return;const n=e.key??{},t=e.value??null,o=ne(n),a=r.get(o);if(!a){r.set(o,{key:n,value:t});return}if(a.value===null){a.value=t;return}t!==null&&(a.value=ae(a.value,t,s))},ie=(r,e)=>{const s=new Map;for(const n of r)if(Array.isArray(n))for(const t of n)ce(s,t,e);return[...s.values()]},N=(r,e)=>{let s=null;for(const n of r)typeof n=="number"&&Number.isFinite(n)&&(s=s===null?n:e(s,n));return s},ue=r=>{let e=0;for(const s of r)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},le=r=>{let e=0,s=0;for(const n of r){if(n===null||typeof n!="object")continue;const t=n;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}},de=(r,e)=>{const s=[];for(const t of r)if(Array.isArray(t))for(const o of t){if(o===null||typeof o!="object")continue;const a=o[e.by],c=typeof a=="number"&&Number.isFinite(a)?a:Number.NEGATIVE_INFINITY;s.push({row:o,score:c})}const n=e.direction??"desc";return s.sort((t,o)=>n==="asc"?k(t.score,o.score):k(o.score,t.score)),s.slice(0,e.k).map(t=>t.row)},fe=(r,e)=>{switch(e.kind){case"concat":return oe(r);case"first":return r[0];case"groupBy":return ie(r,e.op??"sum");case"max":return N(r,Math.max);case"min":return N(r,Math.min);case"rank":return le(r);case"sum":return ue(r);case"topK":return de(r,e);default:return r}},ge=r=>{const e=r.maxConcurrency??F,s=r.perShardTimeoutMs??B;if(e<1)throw new U("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(n,t){const o=await r.registry.listShardKeys(t.fanOut.table),a=await m(n,o,t,e,s),c=[],i=[];for(const l of a)l.kind==="ok"?c.push(l.value):i.push({message:l.message,shardKey:l.shardKey,timedOut:l.timedOut});return{data:fe(c,t.fanOut.merge),errors:i,failed:i.length,ok:c.length}},async orchestrateExport(n,t){const o=await x(r.registry,t.tables),a=R(o,t.defaultShardKey),c={args:{...t.args,tables:[...t.tables]},functionPath:"__lunora_admin__:exportShard",headers:t.headers},i=await m(n,a,c,e,s);return Z(i)},async orchestrateCdcSync(n,t){const o=R(await x(r.registry,t.tables),t.defaultShardKey),a=t.cursors??{},c=await w(o,e,async i=>{const l=a[i]??0;return{outcome:await g(n,i,p({args:{limit:t.limit,sinceSeq:l},functionPath:"__lunora_admin__:cdcSync",headers:t.headers}),s),sinceSeq:l}});return q(c)},async orchestrateImport(n,t){const{batches:o}=t,a=await w(o,e,async c=>g(n,c.shardKey,p({args:{rows:[...c.rows],startLine:c.startLine??1},functionPath:"__lunora_admin__:importShard",headers:t.headers}),s));return se(a)},async orchestrateApplyCdc(n,t){const{batches:o}=t,a=await w(o,e,async c=>g(n,c.shardKey,p({args:{changes:[...c.changes]},functionPath:"__lunora_admin__:applyCdc",headers:t.headers}),s));return ee(a)},async orchestrateMigration(n,t){const o=R(await r.registry.listShardKeys(t.table),t.defaultShardKey),a=await m(n,o,t,e,s);return L(a)},async orchestrateRank(n,t){const o=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 m(n,o,a,e,s);return J(c)},async orchestrateRankPage(n,t){const o=await r.registry.listShardKeys(t.table),a=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),c=t.directions??[],i=t.cursor?Y(t.cursor):{perShard:{}},l=await w(o,e,async d=>{const C=i.perShard[d],_={index:t.index,table:t.table,take:a};t.partitionKey!==void 0&&(_.partitionKey=t.partitionKey),C!==void 0&&(_.after=C);const b=await g(n,d,p({args:_,functionPath:"__lunora_admin__:rankPage",headers:t.headers}),s);if(b.kind==="err")return{error:{message:b.message,timedOut:b.timedOut},shardKey:d};const A=H(h(b.value));return{directions:A.directions,hasMore:A.hasMore,rows:A.rows,shardKey:d}}),u=[];let f=0,y=0,S;for(const d of l){if(d.error){y+=1;continue}f+=1,S===void 0&&d.directions&&d.directions.length>0&&(S=d.directions),u.push({hasMore:d.hasMore??!1,head:0,rows:d.rows??[],shardKey:d.shardKey})}const K=z(u,a,S??c,i.perShard);return{continueCursor:K.nextCursor,failed:y,isDone:K.isDone,ok:f,page:K.page,partial:y>0,shards:l}},async orchestrateShardTraffic(n,t){const o=await r.registry.listShardKeys(t.table),a={functionPath:"__lunora_admin__:getMetrics",headers:t.headers},c=await m(n,o,a,e,s);return te(c)},registry:r.registry}};export{ge as createQueryCoordinator,pe as createStaticShardRegistry};
@@ -0,0 +1,3 @@
1
+ import{f as K,t as j}from"./base64-Bl1_r2k1.mjs";import{t as O}from"./portable-json-DPJbalfn.mjs";const N=new TextEncoder,q=e=>j(N.encode(JSON.stringify(e))),B=e=>{const r={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return r;try{const t=JSON.parse(new TextDecoder().decode(K(e))),o=t.s&&typeof t.s=="object"?t.s:{},s={};for(const[i,n]of Object.entries(o))typeof n=="number"&&Number.isFinite(n)&&(s[i]=n);return{g:typeof t.g=="number"&&Number.isFinite(t.g)?t.g:0,s,v:1}}catch{return r}},P=e=>{const r=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",o=t==="delete"||t==="insert"||t==="update"?t:"upsert",s=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(s===void 0?{}:{_id:s}),op:o,table:r}},M=e=>Math.max(1,Math.min(e??1e3,1e4)),D=(e,r,t)=>{for(const o of r)e.push(P(o));return t!==void 0&&r.length>=t},R=e=>new Promise(r=>{setTimeout(r,e)}),$=e=>{const r=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",o=t==="delete"||t==="insert"||t==="update"?t:"upsert",s=typeof e.id=="string"?e.id:void 0,i=e.doc&&typeof e.doc=="object"?O(e.doc):void 0,n=typeof e.seq=="number"&&Number.isFinite(e.seq)?e.seq:void 0,c=typeof e.ts=="number"&&Number.isFinite(e.ts)?e.ts:void 0;return{op:o,table:r,...i===void 0?{}:{doc:i},...s===void 0?{}:{id:s},...n===void 0?{}:{seq:n},...c===void 0?{}:{ts:c}}},T=async(e,r,t,o,s,i)=>{let n=0;for(;;)try{await e.deliver(r);return}catch(c){if(n>=t)throw c instanceof Error?c:new Error(String(c));const d=Math.min(o*2**n,s);await i(d),n+=1}},I=async e=>{const{coordinator:r,cursorStore:t,defaultShardKey:o,headers:s,initialBackoffMs:i=100,limit:n,maxBackoffMs:c=5e3,maxRetries:d=3,shardDO:S,sink:p,sleep:k=R,tables:C}=e,h=await t.read(p.name),b=await r.orchestrateCdcSync(S,{cursors:h,defaultShardKey:o,headers:s,limit:n,tables:C}),l={...h},m=[];let v=0,f=!1;for(const a of b.shards){if(a.error){m.push({error:a.error.message,shardKey:a.shardKey}),f=!0;continue}const y=a.changes??[];if(y.length===0){l[a.shardKey]=a.cursor;continue}const g=y.map(u=>$(u)),E={changes:g,cursor:a.cursor,shardKey:a.shardKey,sink:p.name};try{await T(p,E,d,i,c,k),l[a.shardKey]=a.cursor,v+=g.length,y.length>=M(n)&&(f=!0)}catch(u){m.push({error:u instanceof Error?u.message:String(u),shardKey:a.shardKey}),f=!0}}return await t.write(p.name,l),{cursors:l,delivered:v,failures:m,hasMore:f,shards:b.shards.length}},x=e=>{if(typeof e.name!="string"||e.name.length===0)throw new Error("defineExportSink: `name` must be a non-empty string");if(typeof e.deliver!="function")throw new TypeError("defineExportSink: `deliver` must be a function");return{deliver:e.deliver,name:e.name}},w=e=>`${e.map(r=>JSON.stringify(r)).join(`
2
+ `)}
3
+ `,J=e=>{const r=e.fetchImpl??((t,o)=>fetch(t,o));return x({deliver:async t=>{const o=await r(e.url,{body:w(t.changes),headers:{"content-type":"application/x-ndjson","x-lunora-cursor":String(t.cursor),"x-lunora-shard":t.shardKey,"x-lunora-sink":t.sink,...e.headers},method:"POST"});if(!o.ok)throw new Error(`webhook export sink "${e.name}" returned ${String(o.status)}`)},name:e.name})},U=e=>{let r=e.prefix??"cdc";for(;r.endsWith("/");)r=r.slice(0,-1);return x({deliver:async t=>{const o=`${r}/${t.shardKey}/${String(t.cursor)}.ndjson`;await e.bucket.put(o,w(t.changes),{httpMetadata:{contentType:"application/x-ndjson"}})},name:e.name})},z=()=>{const e={};return{read:r=>Promise.resolve({...e[r]}),snapshot:()=>structuredClone(e),write:(r,t)=>(e[r]={...t},Promise.resolve())}},W=(e,r)=>{const t=r?.keyPrefix??"__lunora_source_cursor:export",o=s=>`${t}:${s}`;return{read:async s=>{const i=await e.get(o(s),"json");if(i===null||typeof i!="object")return{};const n={};for(const[c,d]of Object.entries(i))typeof d=="number"&&Number.isFinite(d)&&(n[c]=d);return n},write:async(s,i)=>{await e.put(o(s),JSON.stringify(i))}}};export{z as a,I as b,W as c,x as d,B as e,D as f,q as g,M as h,U as r,$ as s,J as w};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.83",
3
+ "version": "1.0.0-alpha.84",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,9 +46,9 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/bindings": "1.0.0-alpha.42",
49
+ "@lunora/bindings": "1.0.0-alpha.43",
50
50
  "@lunora/errors": "1.0.0-alpha.26",
51
- "@lunora/platform": "1.0.0-alpha.21"
51
+ "@lunora/platform": "1.0.0-alpha.22"
52
52
  },
53
53
  "peerDependencies": {
54
54
  "@lunora/shard-engine": ">=1.0.0-alpha.24 <2.0.0-0",
@@ -1 +0,0 @@
1
- import{createR2Sql as R}from"@lunora/bindings/r2sql";import{LOG_ARCHIVE_NOT_CONFIGURED as _}from"./LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{L as d,c as h}from"./pipeline-log-reader-BGrl66P5.mjs";import{LunoraError as a}from"./LunoraError-DksAgIpa.mjs";import{a as A}from"./method-guard-BG_vJNTl.mjs";const m="/_lunora/admin/logs/archive",v="LUNORA_LOG_ARCHIVE_TABLE",C="LUNORA_LOG_ARCHIVE_NAMESPACE",V=o=>{if(typeof o!="object"||o===null)return;const e=o,t=e[v];if(typeof t!="string"||t==="")return;const r=e[C];return{table:t,...typeof r=="string"&&r!==""?{namespace:r}:{}}},O=new Set(d),T=o=>typeof o=="string"&&o!==""?o:void 0,S=(o,e)=>{if(o!==void 0){if(typeof o!="string"||!O.has(o))throw new a(`logs archive: invalid \`${e}\` — expected one of ${d.join(", ")}`,{code:"BAD_REQUEST",status:400});return o}},u=(o,e)=>{if(o!==void 0){if(typeof o!="number"||!Number.isFinite(o))throw new a(`logs archive: invalid \`${e}\` — expected a finite number`,{code:"BAD_REQUEST",status:400});return o}},b=o=>{const e={},t=s=>{const n=T(o[s]);n!==void 0&&(e[s]=n)},r=s=>{const n=S(o[s],s);n!==void 0&&(e[s]=n)},i=s=>{const n=u(o[s],s);n!==void 0&&(e[s]=n)};t("functionPath"),t("functionPathPrefix"),t("traceId"),t("shardKey"),t("userId"),r("level"),r("minLevel"),i("sinceTs"),i("untilTs"),i("limit");const c=o.cursor;if(typeof c=="object"&&c!==null){const s=u(c.ts,"cursor.ts");s!==void 0&&(e.cursor={ts:s})}return e},N=o=>{const e=o.R2_SQL_ACCOUNT_ID??o.CLOUDFLARE_ACCOUNT_ID,t=o.R2_SQL_TOKEN,r=o.R2_SQL_BUCKET,i=[];if((e===void 0||e==="")&&i.push("R2_SQL_ACCOUNT_ID"),(t===void 0||t==="")&&i.push("R2_SQL_TOKEN"),(r===void 0||r==="")&&i.push("R2_SQL_BUCKET"),i.length>0)throw new a(`log archive not configured (missing ${i.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET must be set — see the observability docs.`,{code:_,status:400});return{accountId:e,apiToken:t,bucket:r}},G=o=>{const{createReader:e=h,readJsonBody:t,requireAdminOption:r}=o,i=async(c,s)=>{A(c,"POST","Log-archive");const n=r(c,o.logArchive,{code:_,message:"log archive requires a `logArchive` config (an R2 Data Catalog table) on the worker — see the observability docs"}),{accountId:L,apiToken:p,bucket:l}=N(s??{}),E=b(await t(c)),g=R({accountId:L,apiToken:p,bucket:l}),f=await e(g,{columnMap:n.columnMap,namespace:n.namespace,table:n.table}).query(E);return Response.json(f,{headers:{"content-type":"application/json"},status:200})};return{[m]:i}};export{_ as LOG_ARCHIVE_NOT_CONFIGURED,m as LOG_ARCHIVE_PATH,G as buildLogArchiveAdminRoutes,V as resolveLogArchiveFromEnv};
@@ -1 +0,0 @@
1
- import{e as p,L as y,o as F,c as S,O as $,f as X,g as q,h as J,w as Y,i as G,j as Z,m as Q}from"./otlp-resource-DeXhb949.mjs";const v=r=>{if(typeof r=="string")return r;try{return JSON.stringify(r)??String(r)}catch{return String(r)}},z=r=>typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:v(r),rr=512,tr=200,or=r=>{const s=r.maxItems??rr,t=r.maxDelayMs??tr;let o=[],e,a,i;const c=()=>{e!==void 0&&(clearTimeout(e),e=void 0)},h=async()=>{c();const l=o;o=[];const d=i;a=void 0,i=void 0;try{l.length>0&&await r.export(l)}catch{}finally{d?.()}},m=l=>{a===void 0&&(a=new Promise(d=>{i=d}),e=setTimeout(()=>{h()},t)),l?.(a)};return{add:(l,d)=>{for(o.push(l);o.length>s;)o.shift();m(d),o.length>=s&&h()},flush:async l=>{if(o.length===0){c();return}const d=h();return l?.(d),d},get size(){return o.length}}},sr=/["\\\u0000-\u001F\uD800-\uDFFF]/,D=r=>sr.test(r)?JSON.stringify(r):`"${r}"`,E=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 D(r);if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r)){let i="[";for(let c=0;c<r.length;c++)c>0&&(i+=","),i+=E(r[c]);return i+"]"}const s=Object.getPrototypeOf(r);if(s!==null&&s!==Object.prototype){const i=r.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 t=r,o=Object.keys(t).sort();let e="{",a=!0;for(const i of o){const c=t[i];c!==void 0&&(a?a=!1:e+=",",e+=D(i),e+=":",e+=E(c))}return e+"}"},er=(r,s)=>{const t=[p(y.functionPath,r.functionPath),p(y.ok,r.ok)];r.method!==void 0&&t.push(p("http.request.method",r.method)),r.path!==void 0&&t.push(p("url.path",r.path)),t.push(p("http.route",r.functionPath)),r.scheme!==void 0&&t.push(p("url.scheme",r.scheme)),r.host!==void 0&&t.push(p("server.address",r.host)),r.port!==void 0&&t.push(p("server.port",r.port)),r.userAgent!==void 0&&t.push(p("user_agent.original",r.userAgent)),r.shardKey!==void 0&&t.push(p(y.shardKey,r.shardKey)),t.push(p("http.response.status_code",r.error?.status??200)),r.error&&t.push(p(y.errorType,r.error.code),p("lunora.error_status",r.error.status)),r.fanOut&&t.push(p("lunora.fanout.table",r.fanOut.table),p("lunora.fanout.shards",r.fanOut.shards),p("lunora.fanout.failed",r.fanOut.failed));const o={attributes:t,endTimeUnixNano:S(s),kind:$.server,name:r.functionPath,...r.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},spanId:r.spanId??F(8),startTimeUnixNano:S(s-r.durationMs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId??F(16)};return r.traceFlags!==void 0&&(o.flags=r.traceFlags),r.error&&(o.events=[{attributes:[p("exception.type",r.error.code),p("exception.message",r.error.message)],name:"exception",timeUnixNano:S(s)}]),o},L=(r,s)=>{const t=new Map([[y.functionPath,p(y.functionPath,r.functionPath)]]);r.shardKey!==void 0&&t.set(y.shardKey,p(y.shardKey,r.shardKey)),r.userId!==void 0&&t.set(y.userId,p(y.userId,r.userId)),r.errorType!==void 0&&t.set(y.errorType,p(y.errorType,r.errorType));for(const[o,e]of Object.entries(s??{}))t.set(o,p(o,z(e)));return[...t.values()]},nr=r=>{const s={attributes:L({errorType:r.error?.type,functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.attributes),endTimeUnixNano:S(r.startTs+r.durationMs),kind:$[r.kind??"internal"],name:r.name,parentSpanId:r.parentSpanId,spanId:r.spanId,startTimeUnixNano:S(r.startTs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId},t=o=>q(Object.fromEntries(Object.entries(o??{}).map(([e,a])=>[e,z(a)])));return r.events!==void 0&&r.events.length>0&&(s.events=r.events.map(o=>({attributes:t(o.attributes),name:o.name,timeUnixNano:S(o.ts)}))),r.links!==void 0&&r.links.length>0&&(s.links=r.links.map(o=>({attributes:t(o.attributes),spanId:o.spanId,traceId:o.traceId}))),s},ir=r=>{const s=S(r.ts),t=L({functionPath:r.functionPath,shardKey:r.shardKey},r.attributes),o={asDouble:r.value,attributes:t,timeUnixNano:s};return r.kind==="gauge"?{gauge:{dataPoints:[o]},name:r.name}:r.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:t,bucketCounts:["1"],count:"1",explicitBounds:[],max:r.value,min:r.value,sum:r.value,timeUnixNano:s}]},name:r.name}:{name:r.name,sum:{aggregationTemporality:1,dataPoints:[o],isMonotonic:!0}}},ar=r=>{const s={attributes:L({functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.fields),body:{stringValue:r.message},severityNumber:X[r.level],severityText:r.level.toUpperCase(),timeUnixNano:S(r.ts)};return r.traceId!==void 0&&(s.traceId=r.traceId),r.spanId!==void 0&&(s.spanId=r.spanId),r.eventName!==void 0&&(s.eventName=r.eventName,s.attributes.push(p("event.name",r.eventName))),s},cr=1024,dr=async r=>{const s=new Blob([r]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(s).arrayBuffer()},H=async(r,s,t,o)=>{try{const e=JSON.stringify(s),{byteLength:a}=new TextEncoder().encode(e),i=(a<cr?fetch(r,{body:e,headers:t,method:"POST"}):dr(e).then(c=>fetch(r,{body:c,headers:{...t,"content-encoding":"gzip"},method:"POST"}))).then(()=>{},()=>{});o?.(i),await i}catch{}},ur=(r,s,t,o)=>{H(r,s,t,o?.waitUntil).catch(()=>{})},O=(r,s)=>s===!0&&r.ok,pr=r=>r.kind==="metric"?void 0:r.event.traceId,lr=r=>{const s=Map.groupBy(r,o=>pr(o)),t=s.get(void 0)??[];return s.delete(void 0),{byTrace:s,untraced:t}},j=5,fr=(r,s,t)=>{if(s===void 0)return r;const{byTrace:o,untraced:e}=lr(r),a=[...e];let i=0,c;for(const[h,m]of o){let l;try{l=s({logs:m.filter(d=>d.kind==="log").map(d=>d.event),rpc:m.filter(d=>d.kind==="rpc").map(d=>d.event),spans:m.filter(d=>d.kind==="span").map(d=>d.event),traceId:h})}catch(d){i+=1,i===1&&(c=d),l=!0}l&&a.push(...m)}return i>0&&t(c,i),a},P=(r,s)=>{if(s===void 0)return r;try{return s(r)??void 0}catch{return}},B=(r,s)=>{if(r.kind==="rpc"){const o=P(r.event,s?.rpc);return o===void 0?void 0:{bucket:"spans",encoded:er(o,r.endMs)}}if(r.kind==="span"){const o=P(r.event,s?.span);return o===void 0?void 0:{bucket:"spans",encoded:nr(o)}}if(r.kind==="log"){const o=P(r.event,s?.log);return o===void 0?void 0:{bucket:"logs",encoded:ar(o)}}const t=P(r.event,s?.metric);return t===void 0?void 0:{bucket:"metrics",encoded:ir(t)}},hr=(r={})=>{const{onlyErrors:s}=r;return{onLog:t=>{t.level==="error"||t.level==="fatal"?console.error("[lunora:log]",t.functionPath,t.message):console.log("[lunora:log]",t.functionPath,t.message)},onMetric:t=>{console.log("[lunora:metric]",`${t.name}=${String(t.value)}`,t.kind,t.functionPath)},onRpc:t=>{O(t,s)||(t.ok?console.log("[lunora:rpc]",t):console.error("[lunora:rpc]",t))},onSpan:t=>{const o=t.ok?"ok":`error ${t.error?.type??""}`.trim();console.log("[lunora:span]",t.name,`${String(t.durationMs)}ms`,o,t.functionPath)}}},yr=r=>{const{headers:s,onlyErrors:t,transform:o,transformLog:e,url:a}=r,i=J({"content-type":"application/json"},s),c=(h,m)=>{try{const l=fetch(a,{body:JSON.stringify(h),headers:i,method:"POST"}).catch(()=>{});m?.waitUntil&&m.waitUntil(l)}catch{}};return{onLog:(h,m)=>{const l=P(h,e);l!==void 0&&c(l,m)},onRpc:(h,m)=>{if(O(h,t))return;const l=P(h,o);l!==void 0&&c(l,m)}}},gr=r=>{const{capture:s,captureLog:t}=r,o=r.onlyErrors??!0;return{onLog:t?e=>{try{t(e)}catch{}}:void 0,onRpc:e=>{if(!O(e,o))try{s(e)}catch{}}}},br=r=>{const{dataset:s,onlyErrors:t}=r;return{onRpc:o=>{if(!O(o,t))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{}}}},kr=r=>{const{pipeline:s,serializeFields:t}=r;return{onLog:(o,e)=>{try{const a={functionPath:o.functionPath,level:o.level,message:o.message,ts:o.ts};o.fields&&(a.fields=t===!0?JSON.stringify(o.fields):o.fields);for(const c of["shardKey","userId","traceId","spanId"])o[c]!==void 0&&(a[c]=o[c]);const i=s.send([a]).catch(()=>{});e?.waitUntil&&e.waitUntil(i)}catch{}}}},Sr=r=>{const{batch:s,deploymentEnvironment:t,detectResources:o,endpoint:e,headers:a,onlyErrors:i,postProcessor:c,resourceAttributes:h,serviceNamespace:m,serviceVersion:l,tailSampler:d,token:C}=r,R=r.serviceName??"lunora",U={...l===void 0?{}:{"service.version":l},...m===void 0?{}:{"service.namespace":m},...t===void 0?{}:{"deployment.environment":t},...h},x=new WeakMap,k=u=>{if(o!==!0||u?.resourceAttributes===void 0)return U;const n=x.get(u);if(n!==void 0)return n;const f=Q(u.resourceAttributes(),U);return x.set(u,f),f};let I=e;for(;I.endsWith("/");)I=I.slice(0,-1);const K={logs:{url:`${I}/v1/logs`,wrap:Z},metrics:{url:`${I}/v1/metrics`,wrap:G},spans:{url:`${I}/v1/traces`,wrap:Y}},_=J({"content-type":"application/json"},a,C);let A=0;const V=(u,n)=>{if(A>=j)return;A+=1;const f=A===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}`,u)},W=async u=>{const n=fr(u,d,V),f=new Map;for(const g of n){const b=B(g,c);if(b===void 0)continue;const M=E(g.resource);let T=f.get(M);T===void 0&&(T={logs:[],metrics:[],resource:g.resource,spans:[]},f.set(M,T)),T[b.bucket].push(b.encoded)}const w=[];for(const[,g]of f)for(const b of["spans","logs","metrics"])if(g[b].length>0){const{url:M,wrap:T}=K[b];w.push(H(M,T(g[b],"@lunora/runtime",R,g.resource),_))}await Promise.all(w)};if(s===!1){const u=(n,f)=>{const w=B(n,c);if(w!==void 0){const{url:g,wrap:b}=K[w.bucket];ur(g,b(w.encoded,"@lunora/runtime",R,n.resource),_,f)}};return{onLog:(n,f)=>{u({event:n,kind:"log",resource:k(f)},f)},onMetric:(n,f)=>{u({event:n,kind:"metric",resource:k(f)},f)},onRpc:(n,f)=>{O(n,i)||u({endMs:Date.now(),event:n,kind:"rpc",resource:k(f)},f)},onSpan:(n,f)=>{u({event:n,kind:"span",resource:k(f)},f)}}}const N=or({export:W,...s?.maxDelayMs===void 0?{}:{maxDelayMs:s.maxDelayMs},...s?.maxItems===void 0?{}:{maxItems:s.maxItems}});return{flush:u=>{N.flush(u?.waitUntil).catch(()=>{})},onLog:(u,n)=>{N.add({event:u,kind:"log",resource:k(n)},n?.waitUntil)},onMetric:(u,n)=>{N.add({event:u,kind:"metric",resource:k(n)},n?.waitUntil)},onRpc:(u,n)=>{O(u,i)||N.add({endMs:Date.now(),event:u,kind:"rpc",resource:k(n)},n?.waitUntil)},onSpan:(u,n)=>{N.add({event:u,kind:"span",resource:k(n)},n?.waitUntil)}}},Ir=(...r)=>{const s=(t,o)=>{for(const e of r){const a=e[t];if(a)try{a.apply(e,o)}catch{}}};return{flush:t=>{s("flush",[t])},onLog:(t,o)=>{s("onLog",[t,o])},onMetric:(t,o)=>{s("onMetric",[t,o])},onRpc:(t,o)=>{s("onRpc",[t,o])},onSpan:(t,o)=>{s("onSpan",[t,o])}}};export{br as analyticsEngineSink,Ir as combineSinks,hr as consoleSink,Sr as otlpSink,kr as pipelineLogSink,gr as sentrySink,yr as webhookSink};
@@ -1,6 +0,0 @@
1
- import{isLunoraError as Un,toErrorBody as Cn}from"@lunora/errors";import{e as Nt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Bn}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as Ut,f as Ct}from"./base64-Bl1_r2k1.mjs";import{e as xn,a as Hn}from"./identity-header-C4Z5pldl.mjs";import{o as Te,b as Ln,p as Mn,m as jn,d as Kn,a as $n,r as Fn}from"./otlp-resource-DeXhb949.mjs";import{e as Fe}from"./wire-codec-BsPOEXGn.mjs";import{e as ee,f as be,M as Bt,b as Gn,g as Qn,h as xt,i as Ht}from"./rest-routes-Dq17Zntv.mjs";import{LunoraError as d,toErrorResponse as nt}from"./LunoraError-DksAgIpa.mjs";import{a as j,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as Qe,BACKUP_KEY_PREFIX as ze,isBackupManifestKey as zn,backupObjectKeyOfManifest as Lt,backupObjectKey as Wn,backupManifestKey as Vn}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Jn,buildStorageAdminRoutes as qn,STORAGE_UPLOAD_MAX_BODY_BYTES as Yn,STORAGE_PATH as Xn}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{runExportTap as Zn}from"./createKvCursorStore-DLm6fYoN.mjs";import{buildHealthRoutes as er,durableObjectProbe as tr,d1Probe as nr,presenceProbe as Be}from"./HEALTH_PATH-jZsuCmSs.mjs";import{wrapResolverWithContract as rr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as As,routeIdentityResolvers as Ts}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as or}from"./LOG_ARCHIVE_PATH-jgHjdsz2.mjs";import{r as ar,f as rt,a as de}from"./observability-vDK-rMbs.mjs";import{resolveShard as we,applyJurisdiction as ot}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as at,handleCorsPreflight as sr,enforceOrigin as ir,decorateResponse as xe,enforceWebSocketOrigin as st}from"./decorateResponse-BuqVnrmc.mjs";const cr=e=>{const n=e??{};if(typeof n.bucket=="function")return n;const t={...n,bucketName:"default"};return t.bucket=()=>t,t},Mt="__lunoraBranch",dr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Mt),ur=`may not contain the reserved workflow branch-marker key ("${Mt}")`,We=(e,n)=>{const t=Math.max(e.length,n.length);let r=e.length^n.length;for(let a=0;a<t;a+=1){const s=a<e.length?e.charCodeAt(a):0,u=a<n.length?n.charCodeAt(a):0;r|=s^u}return r===0},lr=(e,n,t,r)=>{const a=e.get(n);if(a!==void 0)return a;Nt(e,r);const s=t().catch(u=>{throw e.get(n)===s&&e.delete(n),u});return e.set(n,s),s},Ve=new TextEncoder,hr=Array.from({length:32},(e,n)=>n);new RegExp(`[${hr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const fr=64,pr=new Map,jt=async e=>lr(pr,e,async()=>crypto.subtle.importKey("raw",Ve.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),fr),Kt=async(e,n)=>{const t=await jt(e),r=await crypto.subtle.sign("HMAC",t,Ve.encode(n));return Ut(new Uint8Array(r))},mr=async(e,n,t)=>{const r=await jt(e);return crypto.subtle.verify("HMAC",r,t,Ve.encode(n))},wr=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(wr);const gr=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),yr=-100,br=15,_r=e=>{const n=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&gr.has(e.country)?"me":"apac";case"EU":return Number.isFinite(n)&&n>br?"eeur":"weur";case"NA":return Number.isFinite(n)&&n<yr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},it=e=>{const n=e.cf;return n===void 0?void 0:_r(n)},$t="::relay::",Rr=(e,n)=>`${e}${$t}${String(n)}`,Ft="::replica::",Er=(e,n)=>`${e}${Ft}${n}`,Sr=e=>{if(e==null||!/^\d+$/.test(e))return;const n=Number.parseInt(e,10);return Number.isSafeInteger(n)&&n>0?n:void 0},Ar=new Set(["1","enabled","on","true","yes"]),Tr=new Set(["0","disabled","false","no","off"]),Or=(e,n)=>{const t=(e??"").trim().toLowerCase();return Ar.has(t)?!0:Tr.has(t)?!1:n},Gt="v1",vr=6e4,kr=async(e,n={})=>{const t=(n.now??Date.now())+(n.ttlMs??vr),r=`${Gt}.${String(t)}`,a=await Kt(e,r);return{expiresAtMs:t,token:`${r}.${a}`}},Ir=async(e,n,t=Date.now())=>{if(e.length===0||n.length===0)return!1;const r=n.split(".");if(r.length!==3)return!1;const[a,s,u]=r;if(a!==Gt||u.length===0)return!1;const h=Number(s);if(!Number.isFinite(h)||h<=t)return!1;let f;try{f=Ct(u)}catch{return!1}return mr(e,`${a}.${s}`,f)},P="/_lunora/admin/auth",Pr={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},N=(e,n)=>{const t=e[n];if(typeof t!="string"||t==="")throw new d(`\`${n}\` is required`,{code:"BAD_REQUEST",status:400});return t},he=(e,n)=>{const t=e(n);if(t===void 0)throw new d(`\`${n}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return t},Qt=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(n=>typeof n=="string"))return e},ae=(e,n)=>typeof e[n]=="string"?e[n]:void 0,He=(e,n)=>{const t=e[n];return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0},ct=e=>{const n=Qt(e.role);if(n===void 0||typeof n=="string"&&n.trim()==="")throw new d("`role` is required",{code:"BAD_REQUEST",status:400});return n},dt=e=>{const n=e.permission;if(typeof n!="object"||n===null||Array.isArray(n))throw new d("`permission` object is required",{code:"BAD_REQUEST",status:400});const t={};for(const[r,a]of Object.entries(n))Array.isArray(a)&&a.every(s=>typeof s=="string")&&(t[r]=a);return t},Dr={[`${P}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${P}/users`]:{build:({paging:e,query:n})=>{const t=n("sortDirection");return{...e,filterField:n("filterField"),filterValue:n("filterValue"),search:n("search"),searchField:n("searchField"),sortBy:n("sortBy"),sortDirection:t==="asc"||t==="desc"?t:void 0}},http:"GET",method:"listUsers"},[`${P}/sessions`]:{build:({paging:e,query:n})=>({...e,userId:n("userId")}),http:"GET",method:"listSessions"},[`${P}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${P}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${P}/organizations/members`]:{build:({paging:e,query:n})=>({...e,organizationId:he(n,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:n})=>({...e,organizationId:he(n,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:n})=>({...e,organizationId:he(n,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:n})=>({...e,teamId:he(n,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:n})=>({...e,organizationId:he(n,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:He(e,"data"),email:N(e,"email"),name:N(e,"name"),password:ae(e,"password"),role:Qt(e.role)}),http:"POST",method:"createUser"},[`${P}/users/update`]:{build:({body:e})=>{const{data:n}=e;if(typeof n!="object"||n===null||Array.isArray(n))throw new d("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:n,userId:N(e,"userId")}},http:"POST",method:"updateUser"},[`${P}/users/role`]:{build:({body:e})=>({role:ct(e),userId:N(e,"userId")}),http:"POST",method:"setRole"},[`${P}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:ae(e,"reason"),userId:N(e,"userId")}),http:"POST",method:"banUser"},[`${P}/users/unban`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"unbanUser"},[`${P}/users/password`]:{build:({body:e})=>({newPassword:N(e,"newPassword"),userId:N(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${P}/users/remove`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${P}/users/impersonate`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"impersonateUser"},[`${P}/sessions/revoke`]:{build:({body:e})=>({sessionId:N(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${P}/sessions/revoke-all`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${P}/accounts/unlink`]:{build:({body:e})=>({accountId:N(e,"accountId"),userId:N(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${P}/two-factor/disable`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${P}/passkeys/delete`]:{build:({body:e})=>({passkeyId:N(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${P}/organizations/members/remove`]:{build:({body:e})=>({memberId:N(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${P}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:N(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${P}/organizations/create`]:{build:({body:e})=>({logo:ae(e,"logo"),metadata:He(e,"metadata"),name:N(e,"name"),ownerId:ae(e,"ownerId"),slug:ae(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:ae(e,"logo"),metadata:He(e,"metadata"),name:ae(e,"name"),organizationId:N(e,"organizationId"),slug:ae(e,"slug")}),http:"POST",method:"updateOrganization"},[`${P}/organizations/remove`]:{build:({body:e})=>({organizationId:N(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${P}/organizations/members/add`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),role:ae(e,"role"),userId:N(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:N(e,"email"),inviterId:ae(e,"inviterId"),organizationId:N(e,"organizationId"),role:ae(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:N(e,"memberId"),role:ct(e)}),http:"POST",method:"updateMemberRole"},[`${P}/organizations/teams/create`]:{build:({body:e})=>({name:N(e,"name"),organizationId:N(e,"organizationId")}),http:"POST",method:"createTeam"},[`${P}/organizations/teams/update`]:{build:({body:e})=>({name:N(e,"name"),teamId:N(e,"teamId")}),http:"POST",method:"updateTeam"},[`${P}/organizations/teams/remove`]:{build:({body:e})=>({teamId:N(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${P}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:N(e,"teamId"),userId:N(e,"userId")}),http:"POST",method:"addTeamMember"},[`${P}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:N(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${P}/organizations/roles/create`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),permission:dt(e),role:N(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:dt(e),roleId:N(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${P}/organizations/roles/remove`]:{build:({body:e})=>({roleId:N(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Nr=e=>{const n=async a=>{try{return await a()}catch(s){if(s instanceof d)throw s;const u=s,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",s),new d("auth admin operation failed",{code:h,status:Pr[h]??500})}},t=async(a,s)=>{if(e.assertAdmin(a),a.method!==s.http)throw new d(`Auth admin endpoint requires ${s.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new d("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[s.method];if(h===void 0)throw new d(`auth admin does not support \`${s.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(a.url),w={body:s.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:k=>e.queryParameter(f,k)},E=s.build(w),O=await n(()=>h(E));return Response.json(s.returns==="void"?{ok:!0}:O,{headers:{"content-type":"application/json"},status:200})},r={};for(const[a,s]of Object.entries(Dr))r[a]=u=>t(u,s);return r},Ur="__lunora_admin__:getAuthAuditLog",ut=e=>typeof e=="string"&&e!==""?e:void 0,lt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Cr=e=>async(t,r)=>{e.assertAdmin(t);const a=e.getReader();if(a===void 0)throw new d("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const s=ut(r.actorId),u=ut(r.event),h=lt(r.sinceSeq),f=lt(r.limit),w={...s===void 0?{}:{actorId:s},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...f===void 0?{}:{limit:f}};let E;try{E=await a.read(w)}catch(k){throw k instanceof d?k:(console.error("[lunora] auth audit read failed:",k),new d("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const O={entries:E};return Response.json({result:Fe(O)},{headers:{"content-type":"application/json"},status:200})},Br=(e,n)=>{const t=[],r=[];if(n&&n.length>0)for(const a of n)e.resolveTableSharding?.(a)?.mode.kind==="global"?r.push(a):t.push(a);return{globalTables:r,shardLocalTables:t}},xr=async(e,n,t,r,a,s,u)=>{if(t!==void 0&&r.length===0)return;const h=await e.orchestrateExport(s,{args:{tables:r},defaultShardKey:u,headers:n,tables:r});for(const f of h.shards)if(!f.error)for(const w of f.rows??[])a(w)},zt=async(e,n,t,r,a,s)=>{const u=r??e.listSchemaTables?.();r===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:h,shardLocalTables:f}=Br(e,u);await xr(n,t,u,f,a,s,e.defaultShardKey??"__root__");const w=e.exportGlobals;if((r===void 0||h.length>0)&&w)for await(const O of w({tables:h}))a(O)},Hr=new TextEncoder,Lr=1e3,Wt=10,Mr=200,ht=8,Vt="lunoraBackupCron",ft=24*1048576,pt=e=>{const n=e.slice(0,Wt).map(r=>Lt(r)),t=e.length-n.length;return`${n.join(", ")}${t>0?` (+${String(t)} more)`:""}`},jr=(e,n)=>{const t=new Uint8Array(new ArrayBuffer(n));let r=0;for(const a of e)t.set(a,r),r+=a.byteLength;return t},Je=async(e,n,t,r)=>{if(t===void 0||!Number.isInteger(t)||t<=0)return{eligible:0,stale:[]};const a=[];let s;for(let u=0;u<Lr;u+=1){const h=await e.list({cursor:s,include:["customMetadata"],prefix:n});for(const f of h.objects)zn(f.key)&&f.customMetadata?.[Vt]===r&&a.push(f.key);if(!h.truncated||h.cursor===void 0)break;s=h.cursor}return{eligible:a.length,stale:a.toSorted((u,h)=>h.localeCompare(u)).slice(t)}},Kr=async(e,n,t,r,a)=>{const{stale:s}=await Je(e,n,t,r),u=new Set(a),h=s.filter(g=>u.has(g)),f=h.slice(0,Mr),w=s.length-f.length,E=a.length-h.length;if(f.length===0)return{deleted:[],failed:[],ignored:E,remaining:w};const O=[],k=[];for(let g=0;g<f.length;g+=ht){const b=await Promise.allSettled(f.slice(g,g+ht).map(async _=>(await e.delete(Lt(_)),await e.delete(_),_)));for(const[_,p]of b.entries())p.status==="fulfilled"?O.push(p.value):k.push(f[g+_])}return O.length>0&&console.info(`[lunora] backup prune kept the newest ${String(t)} and deleted ${String(O.length)}: ${pt(O)}`),k.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(k.length)}: ${pt(k)}`),{deleted:O,failed:k,ignored:E,remaining:w}},$r=async e=>{const n=e.backupStore;if(!n)throw new d("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const t=Qe(e.backupPrefix??ze),r=e.backupCron,{eligible:a,stale:s}=r===void 0?{eligible:0,stale:[]}:await Je(n,t,e.backupRetain,r);return{cron:r,eligible:a,keep:e.backupRetain??0,prefix:t,wouldDelete:s}},Fr=async(e,n,t,r)=>{const a=e.backupStore,s=e.queryCoordinator;if(!a)throw new d("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!s)throw new d("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!t||t.length===0)throw new d("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const u={authorization:`Bearer ${t}`,"content-type":"application/json"},h=e.backupTables;let f=0,w=0,E=[];await zt(e,s,u,h,D=>{const M=Hr.encode(`${JSON.stringify(D)}
2
- `);if(f+=1,w+=M.byteLength,w>ft)throw new d(`scheduled backup reached ${String(w)} bytes of NDJSON, past the ${String(ft)}-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});E.push(M)},n);const k=Qe(e.backupPrefix??ze),g=new Date(r.scheduledTime).toISOString(),b=Wn(k,g),_=jr(E,w);E=[];const p=Jn(await crypto.subtle.digest("SHA-256",_));await a.put(b,_,{httpMetadata:{contentType:"application/x-ndjson"},sha256:p});const A={bytes:w,createdAt:g,cron:r.cron,file:b,id:g,rows:f,scheduledTime:r.scheduledTime,sha256:p,...h?{tables:h.join(",")}:{}};await a.put(Vn(b),`${JSON.stringify(A,void 0,2)}
3
- `,{customMetadata:{[Vt]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:D}=await Je(a,k,e.backupRetain,r.cron);if(D.length>0){const M=D.slice(0,Wt),I=D.length-M.length;console.info(`[lunora] backup retention: ${String(D.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${M.join(", ")}${I>0?` (+${String(I)} more)`:""}`)}}catch(D){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,D)}},Gr=async(e,n)=>{const t=e.backupStore;if(!t)throw new d("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=e.backupCron,a=e.backupRetain;if(r===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new d("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 Kr(t,Qe(e.backupPrefix??ze),a,r,n)},Qr="/_lunora/admin/backup/retention",zr="/_lunora/admin/backup/prune",Wr=e=>{const{options:n,readJsonBody:t,requireAdminOption:r}=e,a=(h,f)=>{r(h,n.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},s=async h=>(j(h,"GET","Backup-retention"),a(h,"retention preview"),Response.json(await $r(n),{headers:{"cache-control":"no-store"}})),u=async h=>{j(h,"POST","Backup-prune"),a(h,"prune");const{confirm:f}=await t(h);if(!Array.isArray(f)||f.some(w=>typeof w!="string"))throw new d("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 Gr(n,f),{headers:{"cache-control":"no-store"}})};return{[zr]:u,[Qr]:s}},mt=500,Vr=(e,n,t)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new d("each batch call must be an object",{code:"BAD_REQUEST",status:400});const r=e;if(typeof r.functionPath!="string")throw new d("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(r.functionPath.startsWith("__lunora_relation__:")||r.functionPath.startsWith("__lunora_admin__"))throw new d("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(r.args!==void 0&&(typeof r.args!="object"||r.args===null||Array.isArray(r.args)))throw new d("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:r.args===void 0?{}:r.args,clientId:typeof r.clientId=="string"?r.clientId:void 0,clientSeq:typeof r.clientSeq=="number"?r.clientSeq:void 0,functionPath:r.functionPath,id:typeof r.id=="number"?r.id:n,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:t}},Jr=(e,n)=>{if(e.length>mt)throw new d(`RPC batch exceeds the ${String(mt)}-call limit`,{code:"BAD_REQUEST",status:400});const t=new Map;for(const[r,a]of e.entries()){const{entry:s,shardKey:u}=Vr(a,r,n),h=t.get(u)??[];h.push(s),t.set(u,h)}return t},qr=new TextEncoder,Yr=e=>Ut(qr.encode(JSON.stringify(e))),Xr=e=>{const n={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return n;try{const t=JSON.parse(new TextDecoder().decode(Ct(e))),r=t.s&&typeof t.s=="object"?t.s:{},a={};for(const[s,u]of Object.entries(r))typeof u=="number"&&Number.isFinite(u)&&(a[s]=u);return{g:typeof t.g=="number"&&Number.isFinite(t.g)?t.g:0,s:a,v:1}}catch{return n}},Zr=e=>{const n=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",r=t==="delete"||t==="insert"||t==="update"?t:"upsert",a=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(a===void 0?{}:{_id:a}),op:r,table:n}},wt=(e,n,t)=>{for(const r of n)e.push(Zr(r));return t!==void 0&&n.length>=t},eo="/_lunora/admin/export",to="/_lunora/admin/import",no="/_lunora/admin/sync",ro="/_lunora/admin/connector/sync",oo="/_lunora/admin/apply",ao="/_lunora/admin/export-tap/run",so=new TextEncoder,io=async e=>{const t=await be(e,"Export")??{};if(t.tables===void 0)return{tables:void 0};if(!Array.isArray(t.tables))throw new d("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const a of t.tables){if(typeof a!="string"||a.length===0)throw new d("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(a)}return{tables:r}},Le=e=>Array.isArray(e)?e.filter(n=>typeof n=="string"):void 0,co=e=>{const{applyGlobals:n,defaultShardKey:t,exportCursorStore:r,exportSinks:a,knownTables:s,queryCoordinator:u,assertAdmin:h,requireAdminOption:f,resolveForwardContext:w,shardDO:E,streamExportRows:O,streamingImport:k,syncGlobals:g}=e,b=async(I,K)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),U=await io(I),{headers:$}=await w(I,K),F=new ReadableStream({async pull(W){const te=V=>{W.enqueue(so.encode(`${JSON.stringify(V)}
4
- `))};try{await O(Y,$,U.tables,te),W.close()}catch(V){W.error(V)}}});return new Response(F,{headers:{"content-type":"application/x-ndjson"},status:200})},_=async(I,K)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),U=await ee(I),$=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},F=typeof U.limit=="number"?U.limit:void 0,W=typeof U.globalCursor=="number"?U.globalCursor:0,te=Le(U.tables),{headers:V}=await w(I,K),se=te??s(),G=await Y.orchestrateCdcSync(E,{cursors:$,defaultShardKey:t,headers:V,limit:F,tables:se}),J=g?await g({limit:F,sinceSeq:W}):void 0;return Response.json({global:J,shards:G.shards},{status:200})},p=async(I,K)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),U=await ee(I),$=Xr(U.cursor),F=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,W=Le(U.tables),{headers:te}=await w(I,K),V=W??s(),se=await Y.orchestrateCdcSync(E,{cursors:$.s,headers:te,limit:F,tables:V}),G=[],J={...$.s};let Z=!1;for(const ie of se.shards)Z=wt(G,ie.changes??[],F)||Z,J[ie.shardKey]=ie.cursor;let _e=$.g;if(g){const ie=await g({limit:F,sinceSeq:$.g});Z=wt(G,ie.changes,F)||Z,_e=ie.cursor}const Oe=Yr({g:_e,s:J,v:1}),ve={changes:G,hasMore:Z,nextCursor:Oe};return Response.json(ve,{status:200})},A=async(I,K)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),U=await ee(I),F=(Array.isArray(U.batches)?U.batches:[]).map(G=>G).filter(G=>G!==null&&typeof G=="object"&&typeof G.shardKey=="string"&&Array.isArray(G.changes)),W=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:te}=await w(I,K),V=await Y.orchestrateApplyCdc(E,{batches:F,headers:te}),se=W.length>0&&n?await n({changes:W}):0;return Response.json({applied:V.applied+se,failed:V.failed,ok:V.ok},{status:200})},D=async(I,K)=>{const H=me(I,["POST"]);if(H)return H;h(I);const{headers:Y}=await w(I,K),U=await k(I,Y);return Response.json(U,{headers:{"content-type":"application/json"},status:200})},M=async(I,K)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(a===void 0||Object.keys(a).length===0||r===void 0)throw new d("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const U=await ee(I),$=typeof U.sink=="string"?U.sink:void 0,F=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,W=Le(U.tables);if($===void 0)throw new d("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const te=a[$];if(te===void 0)throw new d(`Export-tap sink "${$}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:V}=await w(I,K),se=W??s(),G=await Zn({coordinator:Y,cursorStore:r,headers:V,limit:F,shardDO:E,sink:te,tables:se});return Response.json(G,{headers:{"content-type":"application/json"},status:200})};return{[oo]:A,[ro]:p,[eo]:b,[ao]:M,[to]:D,[no]:_}},uo=(e,n)=>{let t;try{t=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:n,message:"line is not valid JSON",table:""},ok:!1}}if(!t||typeof t!="object"||Array.isArray(t))return{error:{code:"BAD_ROW",line:n,message:"row must be a JSON object",table:""},ok:!1};const r=t;return typeof r.table!="string"||r.table.length===0?{error:{code:"BAD_ROW",line:n,message:"row is missing `table`",table:""},ok:!1}:!r.doc||typeof r.doc!="object"||Array.isArray(r.doc)?{error:{code:"BAD_ROW",line:n,message:"row is missing or malformed `doc`",table:r.table},ok:!1}:{doc:r.doc,ok:!0,table:r.table}},lo=(e,n,t,r,a)=>{if(t?.mode.kind==="shardBy"&&typeof t.mode.field=="string"){const s=e[t.mode.field];return s==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${t.mode.field}" for table "${n}"`,table:n},ok:!1}:{ok:!0,shardKey:typeof s=="string"?s:JSON.stringify(s)}}return{ok:!0,shardKey:r}},ho=async(e,n,t)=>{if(!e.body)throw new d("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],a=[],s=new Map;let u=0,h=0;const f=e.body.getReader(),w=new TextDecoder;let E="",O=0;const k=g=>{h+=1;const b=g.trim();if(b.length===0)return;u+=1;const _=uo(b,h);if(!_.ok){r.push(_.error);return}const{doc:p,table:A}=_,D=n.resolveTableSharding?.(A);if(D?.mode.kind==="global"){a.push({doc:p,line:h,table:A});return}const M=lo(p,A,D,t,h);if(!M.ok){r.push(M.error);return}const I=s.get(M.shardKey);I?I.rows.push({doc:p,table:A}):s.set(M.shardKey,{rows:[{doc:p,table:A}],shardKey:M.shardKey,startLine:h})};for(;;){const{done:g,value:b}=await f.read();if(g)break;if(b&&(O+=b.byteLength,O>Bt))throw await f.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=w.decode(b,{stream:!0});let _=E.indexOf(`
5
- `);for(;_!==-1;){const p=E.slice(0,_);E=E.slice(_+1),k(p),_=E.indexOf(`
6
- `)}}return E.length>0&&k(E),{errors:r,globalRows:a,perShard:s,received:u}},gt=(e,n)=>{for(const[t,r]of Object.entries(n.inserted))e.inserted[t]=(e.inserted[t]??0)+r;for(const t of n.errors)e.errors.push({...t});e.conflicts+=n.conflicts},fo=async(e,n,t,r)=>{const a=n.defaultShardKey??"__root__",{errors:s,globalRows:u,perShard:h,received:f}=await ho(e,n,a),w={conflicts:0,errors:s,inserted:{}},E=[];if(n.resolveTableSharding===void 0&&h.size>0&&E.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 O=n.queryCoordinator;if(!O)throw new d("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const k=await O.orchestrateImport(r,{batches:[...h.values()],headers:t});gt(w,k)}if(u.length>0)if(n.importGlobals){const O=u[0]?.line??1,k=await n.importGlobals({rows:u,startLine:O});gt(w,k)}else for(const O of u)w.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:O.line,message:`row targets global table "${O.table}" but no \`importGlobals\` is configured`,table:O.table});return{conflicts:w.conflicts,errors:w.errors,inserted:w.inserted,received:f,...E.length>0?{warnings:E}:{}}},Me=e=>typeof e=="object"&&e!==null?e:{},je=e=>typeof e.kind=="string"?e.kind:"unknown",po=(e,n)=>{let t=Me(n),r=!1;je(t)==="optional"&&(r=!0,t=Me(t._meta?.inner));const a=je(t),s=t._meta??{},u={kind:a,name:e,optional:r};if(a==="id"&&typeof s.tableName=="string"&&(u.table=s.tableName),a==="array"){const h=je(Me(s.inner));h!=="unknown"&&(u.element=h)}return u},mo=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([n,t])=>po(n,t)).toSorted((n,t)=>n.name.localeCompare(t.name)),wo="/_lunora/admin/functions",go="/_lunora/admin/cron-jobs",yo="/_lunora/admin/openapi",bo="/_lunora/admin/openrpc",_o="/_lunora/admin/global/tables",Ro="/_lunora/admin/global/table",Eo="/_lunora/admin/global/facet",yt=e=>{if(e===void 0||e==="")return;let n;try{n=JSON.parse(e)}catch{return}if(!Array.isArray(n))return;const t=n.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:a,value:s}=r;return[{column:a,value:s}]});return t.length===0?void 0:t},So=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:{}}),Ao=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"}),To=e=>{const{assertAdmin:n,options:t,parsePaging:r,queryParameter:a,requireAdminOption:s}=e,u=g=>{j(g,"GET","Functions");const b=s(g,t.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(b).flatMap(([p,A])=>A.visibility==="internal"||A.kind==="stream"?[]:[{args:mo(A.args),kind:A.kind,path:p}]).toSorted((p,A)=>p.path.localeCompare(A.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},h=g=>{j(g,"GET","Cron-jobs");const b=s(g,t.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(b).flatMap(([p,A])=>A.map(D=>({args:D.args,cron:p,functionPath:D.functionPath,name:D.name,shardKey:D.shardKey,workflow:D.workflow}))).toSorted((p,A)=>p.name.localeCompare(A.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},f=g=>(j(g,"GET","OpenAPI"),n(g),Response.json(t.openApiSpec??So,{headers:{"content-type":"application/json"},status:200})),w=g=>(j(g,"GET","OpenRPC"),n(g),Response.json(t.openRpcSpec??Ao,{headers:{"content-type":"application/json"},status:200})),E=async g=>{j(g,"GET","Global-tables");const b=s(g,t.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await b.listTables(),{headers:{"content-type":"application/json"},status:200})},O=async g=>{j(g,"GET","Global-table");const b=s(g,t.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),p=a(_,"table");if(p===void 0)throw new d("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const A=await b.readTablePage({...r(g),filters:yt(a(_,"filters")),table:p});return Response.json(A,{headers:{"content-type":"application/json"},status:200})},k=async g=>{j(g,"GET","Global-facet");const b=s(g,t.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),p=a(_,"table"),A=a(_,"column");if(p===void 0||A===void 0)throw new d("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const D=a(_,"limit"),M=D===void 0?void 0:Number(D),I=await b.facetColumn({column:A,filters:yt(a(_,"filters")),limit:M!==void 0&&Number.isFinite(M)?M:void 0,table:p});return Response.json(I,{headers:{"content-type":"application/json"},status:200})};return{[go]:h,[wo]:u,[Eo]:k,[Ro]:O,[_o]:E,[yo]:f,[bo]:w}},Oo="/_lunora/admin/kv/namespaces",vo="/_lunora/admin/kv/keys",Jt="/_lunora/admin/kv/value",qt=32*1048576,bt=60,ko=e=>{const{readJsonBody:n,requireAdminOption:t}=e,r=b=>t(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),s=(b,_)=>{const p=new URL(b.url),A=p.searchParams.get("namespace")??"",D=p.searchParams.get("key")??"";if(A==="")throw new d(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(D==="")throw new d(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:D,namespace:A}},u=async(b,_)=>{if(!(await b.listNamespaces()).some(A=>A.binding===_))throw new d(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},h=async b=>(j(b,"GET","KV-namespaces"),a({namespaces:await r(b).listNamespaces()})),f=async b=>{j(b,"GET","KV-keys");const _=r(b),p=new URL(b.url),A=p.searchParams.get("namespace")??"";if(A==="")throw new d("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const D=p.searchParams.get("prefix")??void 0,M=p.searchParams.get("cursor")??void 0,I=p.searchParams.get("limit"),K=I===null?void 0:Number.parseInt(I,10);if(K!==void 0&&(!Number.isInteger(K)||K<1))throw new d("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const H=K===void 0?void 0:Math.min(K,1e3);return await u(_,A),a(await _.listKeys({cursor:M,limit:H,namespace:A,prefix:D}))},k={DELETE:async b=>{const _=r(b),p=s(b,"DELETE");return await u(_,p.namespace),await _.deleteKey(p),a({deleted:!0})},GET:async b=>{const _=r(b),p=s(b,"GET");return await u(_,p.namespace),a(await _.getValue(p))},PUT:async b=>{const _=r(b),p=await n(b,qt);if(typeof p.namespace!="string"||p.namespace==="")throw new d("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new d("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new d("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<bt))throw new d("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const A=Math.floor(Date.now()/1e3)+bt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<A))throw new d("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(_,p.namespace),await _.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),a({ok:!0})}},g=b=>{const _=k[b.method];if(!_)throw new d("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(b)};return{[Oo]:h,[vo]:f,[Jt]:g}},Io="/_lunora/migrate",Po="/_lunora/admin/pitr",Do="/_lunora/admin/rank",No="/_lunora/admin/rankpage",Uo="/_lunora/admin/shard-traffic",Co=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Bo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),xo=async e=>{const t=await be(e,"Migration")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.functionPath!="string"||!Co.has(t.functionPath))throw new d("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,table:t.table}},Ho=async e=>{const t=await be(e,"Rank")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.index!="string"||t.index.length===0)throw new d("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof t.partitionKey!="string")throw new d("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof t.rowId!="string"||t.rowId.length===0)throw new d("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(t.sortValues))throw new d("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:t.sortValues,table:t.table}},Lo=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(n=>n!=="asc"&&n!=="desc"))throw new d('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Mo=e=>{if(typeof e.table!="string"||e.table.length===0)throw new d("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new d("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new d("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 d("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 d("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},jo=async e=>{const t=await be(e,"Rank page")??{};Mo(t);const r=Lo(t.directions);return{cursor:typeof t.cursor=="string"?t.cursor:null,directions:r,index:t.index,partitionKey:typeof t.partitionKey=="string"?t.partitionKey:void 0,table:t.table,take:typeof t.take=="number"?t.take:void 0}},Ko=async e=>{const t=await be(e,"Shard-traffic")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:t.table}},$o=async e=>{const t=await ee(e);if(typeof t.functionPath!="string"||!Bo.has(t.functionPath))throw new d("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new d("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},Fo=e=>{const{defaultShard:n,forwardToShard:t,isAdmin:r,queryCoordinator:a,resolveForwardContext:s,shardDO:u}=e,h=(g,b)=>{if(g.method!=="POST")throw new d(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(g))throw new d("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new d(`${b} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},f=async(g,b)=>{const _=h(g,"Migration"),p=await xo(g),{headers:A}=await s(g,b),D=await _.orchestrateMigration(u,{args:p.args,defaultShardKey:n,functionPath:p.functionPath,headers:A,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},w=async(g,b)=>{const _=h(g,"Rank"),p=await Ho(g),{headers:A}=await s(g,b),D=await _.orchestrateRank(u,{headers:A,index:p.index,partitionKey:p.partitionKey,rowId:p.rowId,sortValues:p.sortValues,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},E=async(g,b)=>{const _=h(g,"Rank page"),p=await jo(g),{headers:A}=await s(g,b),D=await _.orchestrateRankPage(u,{...p,headers:A});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},O=async(g,b)=>{const _=h(g,"Shard-traffic"),p=await Ko(g),{headers:A}=await s(g,b),D=await _.orchestrateShardTraffic(u,{headers:A,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},k=async(g,b)=>{if(j(g,"POST","PITR"),!r(g))throw new d("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const _=await $o(g),{headers:p}=await s(g,b),A=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:_.args,functionPath:_.functionPath}),headers:p,method:"POST"});return t(u,_.shardKey??n,A)};return{[Io]:f,[Po]:k,[Do]:w,[No]:E,[Uo]:O}},Go=1,Qo=0,zo=32,Wo=512,Vo=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Jo=e=>{if(e==null)return;const n=e.trim();if(n.length===0||n.length>Wo)return;const t=n.split(",");if(!(t.length>zo)){for(const r of t)if(!Vo.test(r.trim()))return;return n}},qo=e=>{const n=Mn(e.headers.get("traceparent"));if(n===void 0)return;const t=Jo(e.headers.get("tracestate"));return{parentSpanId:n.parentSpanId,sampled:n.sampled,traceId:n.traceId,...t===void 0?{}:{traceState:t}}},Yo=(e,n={})=>{const t=qo(e),r=n.trustInbound===!0?t:void 0,a=Te(8),s=r?.traceId??Te(16),u=ar(n.sampling,r===void 0?a:s),h=u.isTraced&&(r===void 0||r.sampled);return{decision:u,ignoredUpstream:t!==void 0&&r===void 0,trace:{sampled:h,spanId:a,traceFlags:h?Go:Qo,traceId:s,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState}}}},Xo=(e,n)=>{n.traceparent=Ln(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(n.tracestate=e.traceState)},Zo=(e,n)=>{let t;return()=>{if(t===void 0){const r=Fn(e),a=n===void 0?void 0:n.cf;t=jn($n(r),Kn(r,a))}return t}},ea="/_lunora/admin/scheduled",ta="/_lunora/admin/scheduled/status",na="/_lunora/admin/scheduled/ws",ra="/_lunora/admin/scheduled/cancel",oa="/_lunora/admin/scheduled/dead",aa="/_lunora/admin/scheduled/dead/retry",sa="/_lunora/admin/scheduled/dead/cancel",ia=e=>{const{checkWsAdmin:n,requireSchedulerNamespace:t,resolveSchedulerStub:r,schedulerInstanceName:a}=e,s=(f,w)=>E=>{if(E.method!=="GET")throw new d(`${w} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return r(E).fetch(new Request(`https://scheduler.internal${f}`,{method:"GET"}))},u=(f,w,E=w)=>async O=>{if(O.method!=="POST")throw new d(`${E} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const k=r(O),g=await O.json().catch(()=>{});if(typeof g?.id!="string"||g.id==="")throw new d(`${w} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return k.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:g.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await n(f))throw new d("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const w=t();return we(w,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ra]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[sa]:u("/dead/cancel","Scheduled dead-letter action"),[oa]:s("/dead","Scheduled dead-letter"),[aa]:u("/dead/retry","Scheduled dead-letter action"),[ea]:s("/list","Scheduled-list"),[ta]:s("/status","Scheduler-status"),[na]:h}},ca=(e,...n)=>{let t=e.cf;for(const r of n){if(typeof t!="object"||t===null)return;t=t[r]}return typeof t=="string"?t:void 0},_t={mtls:e=>ca(e,"tlsClientAuth","certVerified")==="SUCCESS"},da=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(_t,e)?_t[e]:void 0)??(()=>!1),ua=e=>{if(e!==void 0)return()=>{};let n=!1;return()=>{n||(n=!0,console.warn('[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.'))}},la="/_lunora/admin/vector/indexes",ha="/_lunora/admin/vector/query",fa=e=>{const{readJsonBody:n,requireAdminOption:t}=e,r=async s=>{j(s,"GET","Vector-indexes");const u=t(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async s=>{j(s,"POST","Vector-query");const u=t(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new d("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const f=await n(s);if(typeof f.name!="string"||f.name==="")throw new d("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof f.text!="string"||f.text==="")throw new d("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(f.topK!==void 0&&(typeof f.topK!="number"||!Number.isInteger(f.topK)||f.topK<1))throw new d("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const w=await u.queryIndex({name:f.name,text:f.text,topK:f.topK});return Response.json(w,{headers:{"content-type":"application/json"},status:200})};return{[la]:r,[ha]:a}},pa="/_lunora/admin/workflows/instances",ma="/_lunora/admin/workflows/instance",wa="/_lunora/admin/workflows/status",ga={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},ya=e=>e!==null&&Object.hasOwn(ga,e)?e:void 0,Rt=(e,n)=>{const t=e.searchParams.get(n);if(t===null)return;const r=Number(t);return Number.isInteger(r)&&r>0?r:void 0},Ke=(e,n)=>{const t=e.searchParams.get(n);if(t===null||t==="")throw new d(`Workflows admin endpoint requires a \`${n}\` query parameter`,{code:"BAD_REQUEST",status:400});return t},Et=()=>{throw new d("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},ba=e=>{const{assertAdmin:n,resolveWorkflowsClient:t}=e,r=async(u,h,f)=>{j(u,"GET","Workflows instances"),n(u);const w=t(h);if(!w)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const E=Ke(f,"name"),O=ya(f.searchParams.get("status"));return Response.json(await w.listInstances({page:Rt(f,"page"),perPage:Rt(f,"perPage"),status:O,workflowName:E}))},a=async(u,h,f)=>{j(u,"GET","Workflows instance"),n(u);const w=t(h);return w?Response.json(await w.getInstance({instanceId:Ke(f,"id"),workflowName:Ke(f,"name")})):Et()},s=async(u,h)=>{j(u,"POST","Workflows status"),n(u);const f=t(h);if(!f)return Et();const w=await u.json().catch(()=>{});if(typeof w?.name!="string"||w.name===""||typeof w.id!="string"||w.id==="")throw new d("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:E}=w;if(E!=="pause"&&E!=="resume"&&E!=="terminate")throw new d("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:E,instanceId:w.id,workflowName:w.name}))};return{[ma]:a,[pa]:r,[wa]:s}},_a={[Jt]:qt,[Xn]:Yn},St="/_lunora/rpc",Ra="/_lunora/rpc-batch",Ea="/_lunora/ws",Ee=(e,n,t)=>({resourceAttributes:Zo(e,n),...t===void 0?{}:{waitUntil:t}}),At=e=>e?.waitUntil?{waitUntil:n=>e.waitUntil?.(n)}:{},Tt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),$e=e=>{const{method:n}=e,t=e.headers.get("user-agent")??void 0;let r;try{r=new URL(e.url)}catch{return{method:n,userAgent:t}}const a=r.port===""?void 0:Number(r.port);return{host:r.hostname,method:n,path:r.pathname,port:Number.isNaN(a)?void 0:a,scheme:r.protocol.replace(":",""),userAgent:t}},Ot="/_lunora/voice/",Sa="/_lunora/scheduler/dispatch",Aa="/_lunora/admin/cron-jobs/run",Ta="/_lunora/admin/ws-token",Oa="/_lunora/admin/",va="/_lunora/migrate",ka="/_lunora/status",Ia=e=>e.startsWith(Oa)||e===va,Pa=e=>{const n=e.headers.get("x-lunora-userid"),t=e.headers.get("x-lunora-identity");if(!(n===null&&t===null))return{...t===null?{}:{identity:t},...n===null?{}:{userId:n}}},Da="/api/auth",Na="__lunora_admin__:recordAuthEvent",Ua="__lunora_admin__:listPushSubscriptions",Ca=["/sign-in","/sign-up","/callback"],Ba=(e,n)=>{const t=n.endsWith("/")?n.slice(0,-1):n;if(!e.startsWith(`${t}/`))return!1;const r=e.slice(t.length);return Ca.some(a=>r===a||r.startsWith(`${a}/`))},Se=(e,n,t,r)=>{const a=Un(t),s=a?t.code:"INTERNAL_SERVER_ERROR",u=a?t.status:500,h=t instanceof Error?t.message:String(t);return{durationMs:n,error:{code:s,message:h,status:u},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},xa=e=>{const{exp:n,expiresAtMs:t}=e;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof n=="number"&&Number.isFinite(n))return n*1e3},vt=e=>e.waitUntil?{waitUntil:n=>{e.waitUntil?.(n)}}:void 0,Ha=e=>{const n=e?.queue;return typeof n=="string"&&n.length>0?n:"unknown"},Ge=new WeakMap,ue=async(e,n,t,r=Ge.get(e))=>{const a={"content-type":"application/json"},s=e.headers.get("authorization"),u=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),f=e.headers.get("x-lunora-mutation-id"),w=e.headers.get("x-lunora-client-id"),E=e.headers.get("x-lunora-client-seq");s&&(a.authorization=s),u&&(a.cookie=u),h&&(a["x-d1-bookmark"]=h),f&&(a["x-lunora-mutation-id"]=f),w&&(a["x-lunora-client-id"]=w),E&&(a["x-lunora-client-seq"]=E);const O=e.headers.get("cf-connecting-ip");if(O&&(a["x-lunora-client-ip"]=O),!t)return{claims:null,headers:a,identity:null,userId:null};const k=await t(e,n,r);if(!k||typeof k.userId!="string"||k.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=xn(k.userId);const g=xa(k);g!==void 0&&(a["x-lunora-identity-exp"]=String(g));const{userId:b,..._}=k,p=Object.keys(_).length>0?_:null;return p&&(a["x-lunora-identity"]=Hn(p)),{claims:p,headers:a,identity:k,userId:b}},La=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Ma=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new d("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.table!="string"||n.table.length===0)throw new d("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!n.merge||typeof n.merge!="object")throw new d("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const t=n.merge;if(typeof t.kind!="string"||!La.has(t.kind))throw new d("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(t.kind==="topK"){if(typeof t.k!="number"||!Number.isInteger(t.k)||t.k<0)throw new d("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof t.by!="string"||t.by.length===0)throw new d("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return n},ja=(e,n)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${n.fanOut?"fan-out":`shard=${n.shardKey??"(root)"}`} ${n.functionPath}`)},kt=(e,n)=>{const t=n.functions?.[e.functionPath]?.x402;if(t){if(e.fanOut)throw new d("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!n.x402Charge)throw new d(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return t}},Ka=async e=>{const n=await Ht(e);let t;try{t=JSON.parse(n)}catch{throw new d("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!t||typeof t!="object"||typeof t.functionPath!="string")throw new d("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const r=t;if(r.args!==void 0&&xt(r.args,"RPC"),r.shardKey!==void 0&&typeof r.shardKey!="string")throw new d("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=t,s=Ma(a.fanOut),u=a.args??{};if(s&&a.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==s.table)throw new d("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=s.table}return{args:u,fanOut:s,functionPath:a.functionPath,shardKey:a.shardKey}},Ae=new Map,$a=5e3,Fa=4096,Ga=async(e,n)=>{const t=Date.now(),r=Ae.get(n);if(r!==void 0&&r.expiresMs>t)return r.relayCount;r!==void 0&&Ae.delete(n);let a=0;try{const s=await we(e,n).fetch(new Request("https://shard.internal/_lunora/route"));if(s.ok){const h=(await s.json()).relayCount;typeof h=="number"&&h>0&&(a=Math.floor(h))}}catch{a=0}return Nt(Ae,Fa),Ae.set(n,{expiresMs:t+$a,relayCount:a}),a},It=(e,n)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,t])=>t===n)?.[0]},ye=(e,n,t)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:n,functionPath:e}),headers:t,method:"POST"}),Qa=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],Pt=(e,n)=>{for(const t of Qa){e.delete(t);const r=n[t];r!==void 0&&e.set(t,r)}},za=async(e,n,t)=>e.length===0||t.length===0?!1:We(await Kt(e,n),t),Dt=(e,n)=>{if(!n||n.length===0)return!1;const t=e.headers.get("authorization");if(!t)return!1;const[r,...a]=t.split(" ");return r?.toLowerCase()!=="bearer"?!1:We(n,a.join(" ").trim())},Wa=async(e,n,t)=>{if(!n||n.length===0)return!1;const r=new URL(e.url).searchParams.get("token");return r===null?!1:await Ir(n,r)?!0:t?!1:We(n,r)},Va=(e,n)=>{if(n===null||typeof n!="object"&&typeof n!="function")return;const t=n;if(typeof t.prepare=="function"&&typeof t.batch=="function"&&typeof t.dump=="function")return nr(`d1:${e}`,n);if(typeof t.list=="function"&&typeof t.head=="function"&&typeof t.createMultipartUpload=="function")return Be(`r2:${e}`,!0);if(typeof t.send=="function"&&typeof t.sendBatch=="function"&&typeof t.get!="function")return Be(`queue:${e}`,!0);if(typeof t.connectionString=="string")return Be(`hyperdrive:${e}`,!0)},Yt=e=>{const n=da(e.trustInboundTraceContext),t=ua(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",a=rr(e.resolveIdentity,e.identity),s=ot(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:ot(e.schedulerDO,e.jurisdiction);let h=!1;const f=o=>{if(o===void 0||e.jurisdiction===void 0)return o;h||(h=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},w=async(o,i,l,c=e.shardRegion?.(i))=>we(o,i,f(c)).fetch(l);let E;const O=()=>e.adminToken??E;let k;const g=()=>e.requireEphemeralWsToken??k??!0;let b;const _=o=>{const i=o??{};if(b??=It(o,e.shardDO),k===void 0&&e.requireEphemeralWsToken===void 0){const c=i.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(k=Or(c,!0))}if(E!==void 0||e.adminToken!==void 0)return;const l=i.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(E=l)},p=new WeakSet,A=o=>Dt(o,O())||p.has(o),D=async(o,i)=>{const l=await ue(o,i,e.resolveIdentity);if(p.has(o)&&l.headers.authorization===void 0){const c=O();c!==void 0&&(l.headers.authorization=`Bearer ${c}`)}return l};let M=!1,I=!1;const K=()=>{I||(I=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},H=o=>{if(!e.allowUnauthenticatedShardAccess){const i=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new d(`${o} access is default-denied: configure \`${i}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}M||(M=!0,console.warn([`[lunora] SECURITY: serving ${o} 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("")))},Y=async(o,i)=>{if(e.authorizeShard){if(!await e.authorizeShard({identity:o,shardKey:i}))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else i!==r&&H("shard")},U=Fo({defaultShard:r,forwardToShard:w,isAdmin:A,queryCoordinator:e.queryCoordinator,resolveForwardContext:D,shardDO:s}),$=async(o,i,l,c,m)=>{const R={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(R["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(R["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(R["x-lunora-mutation-id"]=c),w(s,l,ye(o,i,R))},F=async(o,i,l,c)=>{const m=l?.[o];if(!m||typeof m.create!="function")throw new d(`${c} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(dr(i))throw new d(`${c} params ${ur}`,{code:"BAD_REQUEST",status:400});await m.create({params:i})},W=async(o,i)=>{if(o.workflow){await F(o.workflow,o.args??{},i,`cron job "${o.name}"`);return}if(o.functionPath===void 0)throw new d(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const l=await $(o.functionPath,o.args??{},o.shardKey??r);if(!l.ok)throw new d(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},te=async(o,i,l,c)=>{const m=e.cronJobs?.[o];if(m)for(const R of m)try{await W(R,i)}catch(v){l.push(c(v))}},V=async(o,i)=>{if(!A(o))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(j(o,"POST","cron-jobs run"),!e.cronJobs)throw new d("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await ee(o),c=typeof l.name=="string"?l.name:"";if(c==="")throw new d("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(R=>R.name===c);if(!m)throw new d(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await W(m,i),Response.json({name:c,ran:!0},{status:200})},se=async o=>{const i=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!i||!u||typeof o.id!="string")return;const l=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await we(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:i}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},G=async(o,i)=>{j(o,"POST","Scheduler dispatch");const l=await Ht(o),c=i??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,R=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),v=o.headers.get("x-lunora-scheduler-signature");let y=!1;if(v&&m?y=await za(m,l,v):R&&(y=Dt(o,R)),!y)throw new d("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let S;try{S=JSON.parse(l)}catch{throw new d("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const T=S??{},C=T.args??{};if(typeof T.workflow=="string"&&T.workflow.length>0)return await F(T.workflow,C,i,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof T.functionPath!="string"||T.functionPath.length===0)throw new d("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const B=typeof T.shardKey=="string"&&T.shardKey.length>0?T.shardKey:r,x=typeof T.id=="string"&&T.id.length>0?T.id:void 0,re=Pa(o),L=await $(T.functionPath,C,B,x,re);return await se(T),L},J=o=>{if(!A(o))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},Z=(o,i,l)=>{if(J(o),i===void 0)throw new d(l.message,{code:l.code,status:400});return i},_e=Cr({assertAdmin:J,getReader:()=>e.authAuditReader}),Oe=async(o,i)=>{J(o);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:Fe({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const c=i?.kind,m=i?.userId,R=i?.limit,v=c==="fcm"||c==="web-push"?c:void 0,y=typeof m=="string"&&m!==""?m:void 0,S=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,T=S>0?Math.min(S,1e3):1e3,B=(await l.list({kind:v,limit:T,userId:y})).filter(x=>v!==void 0&&x.kind!==v?!1:y===void 0||(x.userId??null)===y).map(({keys:x,token:re,...L})=>L);return Response.json({result:Fe({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},ve=async(o,i)=>{if(!i.fanOut){if(i.functionPath===Ur)return _e(o,i.args??{});if(i.functionPath===Ua)return Oe(o,i.args)}},ie=co({applyGlobals:e.applyGlobals,assertAdmin:J,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:r,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:Z,resolveForwardContext:D,shardDO:s,streamExportRows:(o,i,l,c)=>zt(e,o,i,l,c,s),streamingImport:(o,i)=>fo(o,e,i,s),syncGlobals:e.syncGlobals}),ke=(o,i)=>{const l=o.searchParams.get(i);return l===null||l===""?void 0:l},Ie=o=>{const i=new URL(o.url),l=i.searchParams.get("limit"),c=i.searchParams.get("offset"),m=l===null?void 0:Number.parseInt(l,10),R=c===null?void 0:Number.parseInt(c,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},qe=()=>{if(u===void 0)throw new d("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},Xt=ia({checkWsAdmin:async o=>A(o)||Wa(o,O(),g()),requireSchedulerNamespace:qe,resolveSchedulerStub:o=>(J(o),we(qe(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Zt=ba({assertAdmin:J,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),en=qn({assertAdmin:J,parsePaging:Ie,queryParameter:ke,readBodyBytes:Qn,requireAdminOption:Z,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),tn=Wr({options:e,readJsonBody:ee,requireAdminOption:Z}),nn=fa({readJsonBody:ee,requireAdminOption:Z,vectorIntrospector:e.vectorIntrospector}),rn=ko({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:Z}),on=or({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:Z}),an=To({assertAdmin:J,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ie,queryParameter:ke,requireAdminOption:Z}),sn=o=>{const i=[],l=s??o?.SHARD;if(l!==void 0&&i.push(tr("durable-object:default",l,r)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(o??{})){const R=Va(c,m);R!==void 0&&i.push(R)}for(const c of e.health?.probes??[])i.push(c);return i},cn=er({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:A,resolveProbes:sn}),dn=o=>{const i=e.schedulerInstanceName??"default",l=()=>we(o,i),c=async(y,S)=>{const T=await l().fetch(new Request(`https://scheduler.internal${y}`,S));if(!T.ok)throw new d(`ctx.scheduler: SchedulerDO ${y} failed (${String(T.status)}): ${await T.text()}`,{code:"INTERNAL",status:500});return await T.json()},m=async(y,S)=>await c(y,{body:JSON.stringify(S),headers:{"content-type":"application/json"},method:"POST"}),R=y=>{const S=y;if(S==null)throw new d("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof S.binding=="string"&&S.binding.length>0)return{workflow:S.binding};if(typeof S.__lunoraRef=="string")return{functionPath:S.__lunoraRef};throw new d("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})},v=async(y,S,T={})=>{const{id:C}=await m("/schedule",{args:T,scheduledFor:y,...R(S)});return C};return{cancel:async y=>await m("/cancel",{id:y}),get:async y=>await c(`/get?id=${encodeURIComponent(y)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(y,S,T)=>{if(!Number.isFinite(y)||y<0)throw new d("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await v(Date.now()+y,S,T)},runAt:async(y,S,T)=>{if(!Number.isFinite(y))throw new d("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await v(y,S,T)}}},un=async(o,i,l)=>{const{claims:c,headers:m,userId:R}=await ue(o,i,a),v=async(y,S={})=>{const T=y.__lunoraRef;if(typeof T!="string")throw new d("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const C=ye(T,S,{...m,"x-lunora-system":"1"}),B=await w(s,r,C),x=await B.json();if(x.error)throw new d(x.error.message??"shard RPC failed",{code:x.error.code??"INTERNAL",status:B.status});return x.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:R},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),runAction:v,runMutation:v,runQuery:v,...u===void 0?{}:{scheduler:dn(u)},...e.storage===void 0?{}:{storage:cr(e.storage(i))}}},ln=async(o,i,l)=>{if(!e.httpRouter)return;const c=await un(o,i,l);try{return await e.httpRouter.fetch(o,{...i,__lunoraCtx:c},l)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},hn=async(o,i,l)=>{if(o.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=st(o,ce);if(c)return c;const m=l.searchParams.get("shard")??r,{headers:R,identity:v}=await ue(o,i,a);await Y(v,m);const y=new Headers(o.headers),S=[...y.keys()];for(const C of S)C.startsWith("x-lunora-")&&y.delete(C);Pt(y,R);const T=It(i,e.shardDO);if(T!==void 0){y.set("x-lunora-shard-binding",T);const C=await Ga(s,m);if(C>0){const B=Rr(m,Math.floor(Math.random()*C));return w(s,B,new Request(o,{headers:y}),it(o))}}return w(s,m,new Request(o,{headers:y}))},fn=async(o,i,l)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=st(o,ce);if(m)return m;let R;try{R=decodeURIComponent(l.pathname.slice(Ot.length))}catch{return new Response("Unknown voice agent",{status:404})}const v=Object.hasOwn(c,R)?c[R]:void 0;if(v===void 0)return new Response("Unknown voice agent",{status:404});const y=l.searchParams.get("threadKey");if(y===null||y.length===0)return new Response("Missing threadKey",{status:400});const{headers:S,identity:T}=await ue(o,i,a);if(e.authorizeShard){if(!await e.authorizeShard({identity:T,shardKey:y}))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else H("shard");const C=new Headers(o.headers);for(const B of C.keys())B.startsWith("x-lunora-")&&C.delete(B);return Pt(C,S),w(v,y,new Request(o,{headers:C}))},pn=async(o,i,l)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(l,o.table,i))throw new d("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(i.startsWith("__lunora_relation__:"))throw new d("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 d("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});H("fan-out")},Re=async(o,i)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await pn(o.fanOut,o.functionPath,i);return}await Y(i,o.shardKey??r)}},mn=(o,i,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){K();return}if(e.functions[i]?.kind!=="query"||l.includes(Ft)||l.includes($t))return;const c=it(o);return c===void 0?void 0:{name:Er(l,c),region:c}},wn=async(o,i,l,c,m)=>{const R=mn(o,i,c);if(R!==void 0){const v={...m,"x-lunora-replica-read":"1",...b===void 0?{}:{"x-lunora-shard-binding":b}},y=Sr(o.headers.get("x-lunora-min-seq"));y!==void 0&&(v["x-lunora-min-seq"]=String(y));const S=await w(s,R.name,ye(i,l,v),R.region);if(S.status!==421)return S}return w(s,c,ye(i,l,m))},Pe=async(o,i,l,c,m,R)=>{const v=Date.now(),{observability:y,sampling:S}=e,T=$e(o),{decision:C,ignoredUpstream:B,trace:x}=Yo(o,{...S===void 0?{}:{sampling:S},trustInbound:n(o)});B&&t();const re={...m,"x-lunora-sample-errors":C.keepErrors?"1":"0"};Xo(x,re);try{const L=await wn(o,i,l,c,re);de(y,{...T,...Tt(x),durationMs:Date.now()-v,functionPath:i,ok:L.ok,shardKey:c,...L.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(L.status)}`,status:L.status}}},R,void 0,{isTraced:x.sampled,keepErrors:C.keepErrors});const ne=new Response(L.body,{headers:L.headers,status:L.status,statusText:L.statusText});return ne.headers.set("x-lunora-shard-key",c),ne}catch(L){throw de(y,{...T,...Tt(x),...Se(i,Date.now()-v,L,{shardKey:c})},R,void 0,{isTraced:x.sampled,keepErrors:C.keepErrors}),L}},gn=o=>{if(o.fanOut&&o.shardKey)throw new d("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!o.fanOut&&o.functionPath.startsWith("__lunora_relation__:"))throw new d("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(o.fanOut&&!e.queryCoordinator)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},yn=async(o,i,l)=>{j(o,"POST","RPC");const c=await Ka(o);ja(i,c),gn(c);const m=await ve(o,c);if(m!==void 0)return m;const{headers:R,identity:v}=await ue(o,i,a);await Re(c,v);const y=kt(c,e);{const S=Date.now(),{observability:T}=e,C=$e(o),B=Ee(i,o,l&&(L=>l.waitUntil?.(L)));if(c.fanOut){const L=e.queryCoordinator;if(!L)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ne=await L.fanOut(s,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:R});return de(T,{durationMs:Date.now()-S,fanOut:{failed:ne.failed,shards:ne.ok+ne.failed,table:c.fanOut.table},functionPath:c.functionPath,...C,ok:!0},B),Response.json(ne,{headers:{"content-type":"application/json"},status:200})}catch(ne){throw de(T,{...Se(c.functionPath,Date.now()-S,ne,{fanOut:{table:c.fanOut.table}}),...C},B),ne}}const x=c.shardKey??r,re=()=>Pe(o,c.functionPath,c.args??{},x,R,B);return y&&e.x402Charge?e.x402Charge(o,{functionPath:c.functionPath,price:y.price},re,At(l)):re()}},bn=async(o,i,l)=>{j(o,"POST","RPC batch");const c=await ee(o),{calls:m}=c;if(!Array.isArray(m))throw new d("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:v}=await ue(o,i,a),y=Jr(m,r);for(const Q of y.values())for(const z of Q)if(e.functions?.[z.functionPath]?.x402)throw new d(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${St}`,{code:"BAD_REQUEST",status:400});await Promise.all([...y.entries()].flatMap(([Q,z])=>z.map(oe=>Re({args:oe.args,functionPath:oe.functionPath,shardKey:Q},v))));const{observability:S}=e,T=Ee(i,o,l&&(Q=>l.waitUntil?.(Q))),C=$e(o),B=[],x=[],re=(Q,z,oe,le)=>({body:{error:{code:oe,message:le}},id:Q.id,status:z}),L=(Q,z,oe,le,fe)=>{for(const q of Q)de(S,fe(q),T),B.push(re(q,z,oe,le))},ne=(Q,z,oe,le,fe)=>{for(const q of Q){const pe=le.get(q.id)??fe,ge=pe<400;de(S,{durationMs:oe,functionPath:q.functionPath,...C,ok:ge,shardKey:z,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},T)}};await Promise.all([...y.entries()].map(async([Q,z])=>{const oe=new Headers(R);oe.set("content-type","application/json");const le=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:oe,method:"POST"}),fe=Date.now();let q;try{q=await w(s,Q,le)}catch(X){const Ce=Date.now()-fe,{body:tt}=Cn(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});L(z,502,tt.code,tt.message,Nn=>({...Se(Nn.functionPath,Ce,X,{shardKey:Q}),...C}));return}const pe=Date.now()-fe,ge=q.headers.get("x-d1-bookmark");ge&&x.push(ge);let Ne;try{Ne=await q.json()}catch{const X=`shard batch returned a non-JSON response (${String(q.status)})`;L(z,q.status,"SHARD_ERROR",X,Ce=>({durationMs:pe,error:{code:"SHARD_ERROR",message:X,status:q.status},functionPath:Ce.functionPath,...C,ok:!1,shardKey:Q}));return}const Ue=Array.isArray(Ne.results)?Ne.results:[],Pn=new Map(Ue.map(X=>[X.id,X.status??q.status])),Dn=new Set(Ue.map(X=>X.id));ne(z,Q,pe,Pn,q.status),B.push(...Ue);for(const X of z)Dn.has(X.id)||B.push(re(X,q.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const Ze={"content-type":"application/json"},[et]=x;return x.length===1&&et!==void 0&&(Ze["x-d1-bookmark"]=et),Response.json({results:B},{headers:Ze,status:200})},_n=async(o,i,l,c={},m={})=>{try{const R=l.__lunoraRef;if(typeof R!="string")throw new d("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:v,identity:y}=await ue(o,i,a,m.context);await Re({args:c,functionPath:R,shardKey:m.shardKey},y);const S=m.shardKey??r,T=Ee(i,o,m.waitUntil);return await Pe(o,R,c,S,v,T)}catch(R){return nt(R)}},Ye=async(o,i,l)=>{const{observability:c}=e,m=Date.now(),R=Te(16),v=Te(8),y=vt(i);try{const S=await l();return de(c,{durationMs:Date.now()-m,functionPath:o,ok:!0,spanId:v,traceId:R},y),S}catch(S){throw de(c,{...Se(o,Date.now()-m,S,{}),spanId:v,traceId:R},y),S}finally{rt(c,y)}},Rn=async(o,i,l)=>{_(i);const c=[],m=y=>y instanceof Error?y:new Error(String(y)),R=e.crons?.[o.cron];if(R)try{await R(o,i,l)}catch(y){c.push(m(y))}if(await te(o.cron,i,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron)try{await Fr(e,s,O(),o)}catch(y){c.push(m(y))}const[v]=c;if(c.length===1&&v)throw v;if(c.length>1)throw new AggregateError(c,`scheduled("${o.cron}") had ${String(c.length)} failure(s)`)},En=async(o,i)=>{try{const l=o??{},c=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await w(s,r,ye(Na,{outcome:i},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},Sn=async(o,i,l,c)=>{if(!e.authHandler)return;const m=await e.authHandler(o);if(!m)return;const R=e.authBasePath??Da;return Ba(l.pathname,R)&&c.waitUntil?.(En(i,m.status>=400?"fail":"ok")),m},An=async({args:o,env:i,functionPath:l,request:c,shardKey:m,waitUntil:R})=>{xt(o,"REST");const v={functionPath:l,...m===void 0?{}:{shardKey:m}},{headers:y,identity:S}=await ue(c,i,a);await Re(v,S);const T=m??r,C=Ee(i,c,R),B=()=>Pe(c,l,o,T,y,C),x=kt(v,e);return x&&e.x402Charge?e.x402Charge(c,{functionPath:l,price:x.price},B,At({waitUntil:R})):B()},Tn=Gn({functions:e.functions??{},invoke:An,readJsonBody:ee,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),De=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,On={[ka]:o=>o.method!=="GET"&&o.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Ea]:(o,i,l)=>hn(o,i,l),[St]:(o,i,l,c)=>yn(o,i,c),[Ra]:(o,i,l,c)=>bn(o,i,c),[Sa]:(o,i)=>G(o,i),[Aa]:(o,i)=>V(o,i),[Ta]:async o=>{j(o,"POST","ws-token"),J(o);const i=O();if(i===void 0)throw new d("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await kr(i);return Response.json(l,{headers:{"cache-control":"no-store"}})},...U,...ie,...Xt,...Zt,...en,...tn,...nn,...rn,...on,...an,...cn,...Tn,...Nr({assertAdmin:J,getAuthAdmin:()=>e.authAdmin,parsePaging:Ie,queryParameter:ke,readJsonBody:ee})};let ce=at(e.security),Xe=!1;const vn=o=>{Xe||(Xe=!0,ce=at(e.security,o??{}))},kn=async(o,i)=>{if(!(e.adminGate===void 0||!Ia(i)))try{await e.adminGate(o,Ge.get(o))&&p.add(o)}catch{}},In=async(o,i,l)=>{Ge.set(o,l);const c=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const y=Number(o.headers.get("content-length")??""),S=_a[c.pathname]??Bt;if(Number.isFinite(y)&&y>S)throw new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await Sn(o,i,c,l);if(m)return m;if(De){const y=`${o.method} ${c.pathname}`,S=De[y]??De[c.pathname];if(S)return S(o,i,l)}const R=On[c.pathname];if(R)return await kn(o,c.pathname),R(o,i,c,l);if(e.voiceAgents!==void 0&&c.pathname.startsWith(Ot))return fn(o,i,c);const v=await ln(o,i,l);return v||new Response("Not found",{status:404})};return{async fetch(o,i,l){e.passThroughOnException&&l.passThroughOnException?.(),vn(i),_(i);const c=sr(o,ce);if(c)return c;const m=ir(o,ce);if(m)return xe(m,o,ce);try{const R=await In(o,i,l);return xe(R,o,ce)}catch(R){return xe(nt(R),o,ce)}finally{rt(e.observability,vt(l))}},async queue(o,i,l){await Ye(`queue:${Ha(o)}`,l,async()=>{await e.queue?.(o,i,l)})},async scheduled(o,i,l){await Ye(`cron:${o.cron}`,l,async()=>{await Rn(o,i,l)})},serverQuery:_n}},Ja=e=>Yt(e),qa=e=>typeof e=="function"?{fetch:e}:e,Ya=e=>!!(e.crons??e.cronJobs??e.backupCron),bs=(e,n)=>{const t=qa(e),r=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=u=>{const h=Ja({...u,httpRouter:t});return r!==void 0&&!Ya(u)?{...h,scheduled:async(f,w,E)=>{await r(f,w,E)}}:h};if(typeof n!="function")return a(n);const s=n;return{fetch:(u,h,f)=>a(s(h)).fetch(u,h,f),queue:(u,h,f)=>a(s(h)).queue?.(u,h,f)??Promise.resolve(),scheduled:(u,h,f)=>a(s(h)).scheduled(u,h,f),serverQuery:(u,h,f,w,E)=>a(s(h)).serverQuery(u,h,f,w,E)}},Xa=(e,n)=>{if(typeof e=="function")return e(n);const t=e.shardDO??n?.SHARD;if(!t)throw new d("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:t}},_s=(e={})=>(n,t,r)=>Yt(Xa(e,t)).fetch(n,t,r??Bn),Rs=e=>e;export{Ur as GET_AUTH_AUDIT_LOG_OP,Bn as NOOP_EXECUTION_CONTEXT,As as composeIdentityResolvers,Ja as composeWorker,_s as createLunoraHandler,Yt as createWorker,Rs as defineRpcEnvelope,Ga as probeRelayCount,Xa as resolveLunoraOptions,Ts as routeIdentityResolvers,bs as withFrameworkWorker};
@@ -1 +0,0 @@
1
- import{e as c,a as u}from"./identity-header-C4Z5pldl.mjs";import{LunoraError as s}from"./LunoraError-DksAgIpa.mjs";const f="/_lunora/rpc",l=e=>{const a={"content-type":"application/json"};return e.userId!==void 0&&e.userId.length>0&&(a["x-lunora-userid"]=c(e.userId)),e.identity!==void 0&&(a["x-lunora-identity"]=u(e.identity)),a},d=async(e,a,o)=>{const t=await(e.fetch??globalThis.fetch)(new Request(`${e.origin}${f}`,{body:JSON.stringify(a),headers:l(e),method:"POST"}));if(!t.ok)throw new s(`cross-shard relation ${o} failed: worker returned ${String(t.status)}`);const r=await t.json();if(typeof r.failed=="number"&&r.failed>0){const i=(typeof r.ok=="number"?r.ok:0)+r.failed;throw new s(`cross-shard relation ${o} failed on ${String(r.failed)} of ${String(i)} shard(s) — refusing to return a partial result`)}return r.data},g=e=>({crossShardCounter:async(n,t)=>{const r=await d(e,{args:{table:n,where:t},fanOut:{merge:{kind:"sum"},table:n},functionPath:"__lunora_relation__:count"},"count");return typeof r=="number"?r:0},crossShardReader:async(n,t)=>{const r=await d(e,{args:{...t,table:n},fanOut:{merge:{kind:"concat"},table:n},functionPath:"__lunora_relation__:read"},"read");return{continueCursor:null,isDone:!0,page:Array.isArray(r)?r:[]}}});export{g as createCrossShardRelationCapabilities};
@@ -1,3 +0,0 @@
1
- import{t as E}from"./portable-json-DPJbalfn.mjs";const j=e=>new Promise(t=>{setTimeout(t,e)}),C=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",s=r==="delete"||r==="insert"||r==="update"?r:"upsert",n=typeof e.id=="string"?e.id:void 0,o=e.doc&&typeof e.doc=="object"?E(e.doc):void 0,i=typeof e.seq=="number"&&Number.isFinite(e.seq)?e.seq:void 0,c=typeof e.ts=="number"&&Number.isFinite(e.ts)?e.ts:void 0;return{op:s,table:t,...o===void 0?{}:{doc:o},...n===void 0?{}:{id:n},...i===void 0?{}:{seq:i},...c===void 0?{}:{ts:c}}},$=async(e,t,r,s,n,o)=>{let i=0;for(;;)try{await e.deliver(t);return}catch(c){if(i>=r)throw c instanceof Error?c:new Error(String(c));const d=Math.min(s*2**i,n);await o(d),i+=1}},M=async e=>{const{coordinator:t,cursorStore:r,headers:s,initialBackoffMs:n=100,limit:o,maxBackoffMs:i=5e3,maxRetries:c=3,shardDO:d,sink:p,sleep:g=j,tables:w}=e,f=await r.read(p.name),v=await t.orchestrateCdcSync(d,{cursors:f,headers:s,limit:o,tables:w}),h={...f},y=[];let x=0,l=!1;for(const a of v.shards){if(a.error){y.push({error:a.error.message,shardKey:a.shardKey}),l=!0;continue}const m=a.changes??[];if(m.length===0){h[a.shardKey]=a.cursor;continue}const k=m.map(u=>C(u)),K={changes:k,cursor:a.cursor,shardKey:a.shardKey,sink:p.name};try{await $(p,K,c,n,i,g),h[a.shardKey]=a.cursor,x+=k.length,o!==void 0&&m.length>=o&&(l=!0)}catch(u){y.push({error:u instanceof Error?u.message:String(u),shardKey:a.shardKey}),l=!0}}return await r.write(p.name,h),{cursors:h,delivered:x,failures:y,hasMore:l,shards:v.shards.length}},S=e=>{if(typeof e.name!="string"||e.name.length===0)throw new Error("defineExportSink: `name` must be a non-empty string");if(typeof e.deliver!="function")throw new TypeError("defineExportSink: `deliver` must be a function");return{deliver:e.deliver,name:e.name}},b=e=>`${e.map(t=>JSON.stringify(t)).join(`
2
- `)}
3
- `,N=e=>{const t=e.fetchImpl??((r,s)=>fetch(r,s));return S({deliver:async r=>{const s=await t(e.url,{body:b(r.changes),headers:{"content-type":"application/x-ndjson","x-lunora-cursor":String(r.cursor),"x-lunora-shard":r.shardKey,"x-lunora-sink":r.sink,...e.headers},method:"POST"});if(!s.ok)throw new Error(`webhook export sink "${e.name}" returned ${String(s.status)}`)},name:e.name})},O=e=>{let t=e.prefix??"cdc";for(;t.endsWith("/");)t=t.slice(0,-1);return S({deliver:async r=>{const s=`${t}/${r.shardKey}/${String(r.cursor)}.ndjson`;await e.bucket.put(s,b(r.changes),{httpMetadata:{contentType:"application/x-ndjson"}})},name:e.name})},T=()=>{const e={};return{read:t=>Promise.resolve({...e[t]}),snapshot:()=>structuredClone(e),write:(t,r)=>(e[t]={...r},Promise.resolve())}},q=(e,t)=>{const r=t?.keyPrefix??"__lunora_source_cursor:export",s=n=>`${r}:${n}`;return{read:async n=>{const o=await e.get(s(n),"json");if(o===null||typeof o!="object")return{};const i={};for(const[c,d]of Object.entries(o))typeof d=="number"&&Number.isFinite(d)&&(i[c]=d);return i},write:async(n,o)=>{await e.put(s(n),JSON.stringify(o))}}};export{q as createKvCursorStore,T as createMemoryCursorStore,S as defineExportSink,O as r2Sink,M as runExportTap,C as sanitizeChange,N as webhookExportSink};
@@ -1 +0,0 @@
1
- import{b as E,a as B}from"./base64-Bl1_r2k1.mjs";import{LunoraError as C}from"./LunoraError-DksAgIpa.mjs";import{resolveShard as U}from"./applyJurisdiction-C0ddU7Tg.mjs";const pe=r=>({listShardKeys(e){return r[e]??[]}}),ge=r=>{if(r.kind==="count")return{kind:"sum"};if(r.kind==="scalar"){if(r.op==="count"||r.op==="sum")return{kind:"sum"};if(r.op==="max")return{kind:"max"};if(r.op==="min")return{kind:"min"};throw new C('aggregate({ op: "avg" }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})}const e=r.agg?.op??"count";if(e==="count"||e==="sum")return{kind:"groupBy",op:"sum"};if(e==="max")return{kind:"groupBy",op:"max"};if(e==="min")return{kind:"groupBy",op:"min"};throw new C('groupBy({ agg: { op: "avg" } }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})},F=16,I=5e3,h=r=>r!==null&&typeof r=="object"&&"result"in r?r.result:r,D=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}},V=(r,e)=>r?"failed":e?"in_progress":"completed",L=r=>{const e=[];let s=0,o=0,t=0,n=0,a=!1,c=!1;for(const i of r){if(i.kind==="err"){o+=1,e.push({error:{message:i.message,timedOut:i.timedOut},shardKey:i.shardKey});continue}s+=1;const d=h(i.value),u=D(d);t+=u.changed,n+=u.processed,a||=u.status==="in_progress",c||=u.status==="failed",e.push({result:d,shardKey:i.shardKey})}return{changed:t,failed:o,ok:s,processed:n,shards:e,status:V(c,a||o>0)}},j=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}},J=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=j(h(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}},P=0,T=1,$=2,w=(r,e)=>r<e?-1:r>e?1:0,M=r=>r==null?P:typeof r=="number"?T:$,R=(r,e)=>{const s=M(r),o=M(e);return s!==o?s<o?-1:1:s===P?0:s===T?w(r,e):w(String(r),String(e))},G=(r,e,s)=>{const o=R(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=R(r.sortValues[n],e.sortValues[n]);if(a!==0)return s[n]==="desc"?-a:a}return R(r.rowId,e.rowId)},Q=r=>B(new TextEncoder().encode(JSON.stringify(r))),Y=r=>{try{const e=JSON.parse(new TextDecoder().decode(E(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:{}}},H=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}},W=(r,e)=>{let s;for(const o of r){const t=o.rows[o.head];t!==void 0&&(s===void 0||G(t.key,s.row.key,e)<0)&&(s={row:t,slice:o})}return s},X=(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?Q({perShard:t}):null},z=(r,e,s,o)=>{const t=[],n={...o};for(;t.length<e;){const c=W(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=X(r,n);return{isDone:a===null,nextCursor:a,page:t}},Z=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=h(t.value),a=Array.isArray(n?.rows)?n.rows:[];e.push({rows:a,shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},q=r=>{const e=[];let s=0,o=0;for(const{outcome:t,sinceSeq:n}of r){if(t.kind==="err"){o+=1,e.push({cursor:n,error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const a=h(t.value),c=Array.isArray(a?.changes)?a.changes:[],i=typeof a?.cursor=="number"?a.cursor:n;e.push({changes:c,cursor:i,shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},ee=r=>{let e=0,s=0,o=0;for(const t of r){if(t.kind==="err"){s+=1;continue}e+=1;const n=h(t.value);o+=typeof n?.applied=="number"?n.applied:0}return{applied:o,failed:s,ok:e}},re=r=>{const e=r??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},te=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:re(h(t.value)),shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},se=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 i=h(c.value),d=i?.inserted??{};for(const[f,y]of Object.entries(d))s[f]=(s[f]??0)+y;const u=i?.errors;Array.isArray(u)&&o.push(...u),t+=i?.conflicts??0,e.push({result:{conflicts:i?.conflicts??0,errors:i?.errors??[],inserted:d},shardKey:c.shardKey})}return{conflicts:t,errors:o,failed:a,inserted:s,ok:n,shards:e}},p=r=>({body:JSON.stringify({args:r.args??{},functionPath:r.functionPath}),headers:{"content-type":"application/json",...r.headers}}),g=async(r,e,s,o)=>{const t=U(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 i=new Promise(u=>{c=setTimeout(()=>{try{n.abort()}catch{}u({kind:"err",message:`shard "${e}" timed out after ${String(o)}ms`,shardKey:e,timedOut:!0})},o)}),d=(async()=>{try{const u=await t.fetch(a);if(!u.ok)return{kind:"err",message:`shard "${e}" returned ${String(u.status)}`,shardKey:e,timedOut:!1};const f=await u.json();return{kind:"ok",shardKey:e,value:f}}catch(u){const f=u instanceof Error?u.message:String(u);return{kind:"err",message:`shard "${e}" threw: ${f}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([d,i])}finally{c!==void 0&&clearTimeout(c)}},k=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 i=r[c];if(c>=r.length||i===void 0)return;o[c]=await s(i,c)}},a=Math.min(e,r.length);return await Promise.all(Array.from({length:a},()=>n())),o},v=async(r,e)=>{const s=await Promise.all(e.map(async o=>r.listShardKeys(o)));return[...new Set(s.flat())]},O=(r,e)=>r.length>0||e===void 0?r:[e],m=async(r,e,s,o,t)=>{const n=p(s);return k(e,o,async a=>g(r,a,n,t))},oe=r=>{const e={};for(const s of Object.keys(r).toSorted(w))e[s]=r[s]??null;return JSON.stringify(e)},ne=r=>r.flatMap(e=>Array.isArray(e)?e:[]),ae=(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}},ce=(r,e,s)=>{if(e===null||typeof e!="object")return;const o=e.key??{},t=e.value??null,n=oe(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=ae(a.value,t,s))},ie=(r,e)=>{const s=new Map;for(const o of r)if(Array.isArray(o))for(const t of o)ce(s,t,e);return[...s.values()]},N=(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},ue=r=>{let e=0;for(const s of r)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},de=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}},le=(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"?w(t.score,n.score):w(n.score,t.score)),s.slice(0,e.k).map(t=>t.row)},fe=(r,e)=>{switch(e.kind){case"concat":return ne(r);case"first":return r[0];case"groupBy":return ie(r,e.op??"sum");case"max":return N(r,Math.max);case"min":return N(r,Math.min);case"rank":return de(r);case"sum":return ue(r);case"topK":return le(r,e);default:return r}},ke=r=>{const e=r.maxConcurrency??F,s=r.perShardTimeoutMs??I;if(e<1)throw new C("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 m(o,n,t,e,s),c=[],i=[];for(const d of a)d.kind==="ok"?c.push(d.value):i.push({message:d.message,shardKey:d.shardKey,timedOut:d.timedOut});return{data:fe(c,t.fanOut.merge),errors:i,failed:i.length,ok:c.length}},async orchestrateExport(o,t){const n=await v(r.registry,t.tables),a=O(n,t.defaultShardKey),c={args:{...t.args,tables:[...t.tables]},functionPath:"__lunora_admin__:exportShard",headers:t.headers},i=await m(o,a,c,e,s);return Z(i)},async orchestrateCdcSync(o,t){const n=O(await v(r.registry,t.tables),t.defaultShardKey),a=t.cursors??{},c=await k(n,e,async i=>{const d=a[i]??0;return{outcome:await g(o,i,p({args:{limit:t.limit,sinceSeq:d},functionPath:"__lunora_admin__:cdcSync",headers:t.headers}),s),sinceSeq:d}});return q(c)},async orchestrateImport(o,t){const{batches:n}=t,a=await k(n,e,async c=>g(o,c.shardKey,p({args:{rows:[...c.rows],startLine:c.startLine??1},functionPath:"__lunora_admin__:importShard",headers:t.headers}),s));return se(a)},async orchestrateApplyCdc(o,t){const{batches:n}=t,a=await k(n,e,async c=>g(o,c.shardKey,p({args:{changes:[...c.changes]},functionPath:"__lunora_admin__:applyCdc",headers:t.headers}),s));return ee(a)},async orchestrateMigration(o,t){const n=O(await r.registry.listShardKeys(t.table),t.defaultShardKey),a=await m(o,n,t,e,s);return L(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 m(o,n,a,e,s);return J(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??[],i=t.cursor?Y(t.cursor):{perShard:{}},d=await k(n,e,async l=>{const x=i.perShard[l],_={index:t.index,table:t.table,take:a};t.partitionKey!==void 0&&(_.partitionKey=t.partitionKey),x!==void 0&&(_.after=x);const S=await g(o,l,p({args:_,functionPath:"__lunora_admin__:rankPage",headers:t.headers}),s);if(S.kind==="err")return{error:{message:S.message,timedOut:S.timedOut},shardKey:l};const A=H(h(S.value));return{directions:A.directions,hasMore:A.hasMore,rows:A.rows,shardKey:l}}),u=[];let f=0,y=0,b;for(const l of d){if(l.error){y+=1;continue}f+=1,b===void 0&&l.directions&&l.directions.length>0&&(b=l.directions),u.push({hasMore:l.hasMore??!1,head:0,rows:l.rows??[],shardKey:l.shardKey})}const K=z(u,a,b??c,i.perShard);return{continueCursor:K.nextCursor,failed:y,isDone:K.isDone,ok:f,page:K.page,partial:y>0,shards:d}},async orchestrateShardTraffic(o,t){const n=await r.registry.listShardKeys(t.table),a={functionPath:"__lunora_admin__:getMetrics",headers:t.headers},c=await m(o,n,a,e,s);return te(c)},registry:r.registry}};export{ke as createQueryCoordinator,pe as createStaticShardRegistry,ge as mergeStrategyForAggregate};