@lunora/runtime 1.0.0-alpha.214 → 1.0.0-alpha.216

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
@@ -3095,6 +3095,18 @@ interface HttpActionContext {
3095
3095
  }) => Promise<unknown>;
3096
3096
  };
3097
3097
  fetch: typeof globalThis.fetch;
3098
+ /**
3099
+ * Forward a server-to-server request to a shard DO, carrying the caller's
3100
+ * resolved identity headers. Structural mirror of `@lunora/server`'s
3101
+ * `ShardFetch` — kept structural so the runtime stays free of a
3102
+ * `@lunora/server` dependency. The live-stream primitive uses it to reach
3103
+ * the shard's SSE + subscriber-registry endpoints.
3104
+ */
3105
+ fetchShard: (shardKey: string | undefined, path: string, init?: {
3106
+ body?: string;
3107
+ headers?: Record<string, string>;
3108
+ method?: string;
3109
+ }) => Promise<Response>;
3098
3110
  /**
3099
3111
  * The same `run*` trio bound to a named shard, mirroring
3100
3112
  * `createShardClient(...).forShard(key)`.
@@ -3107,6 +3119,17 @@ interface HttpActionContext {
3107
3119
  * (usually none) with no error and no way to say otherwise.
3108
3120
  */
3109
3121
  forShard: (shardKey: string) => Pick<HttpActionContext, "runAction" | "runMutation" | "runQuery">;
3122
+ /**
3123
+ * Publish an arbitrary event to a live topic on a stream. Structural mirror of
3124
+ * `@lunora/server`'s `LivePublisher`. Present on every worker; built with
3125
+ * `liveStreams: false` (a target that does not serve live streams), its `publish` rejects.
3126
+ */
3127
+ live?: {
3128
+ publish: (topic: string, payload: unknown, options: {
3129
+ shardKey?: string;
3130
+ stream: string;
3131
+ }) => Promise<void>;
3132
+ };
3110
3133
  runAction: <R>(reference: unknown, args?: Record<string, unknown>) => Promise<R>;
3111
3134
  runMutation: <R>(reference: unknown, args?: Record<string, unknown>) => Promise<R>;
3112
3135
  runQuery: <R>(reference: unknown, args?: Record<string, unknown>) => Promise<R>;
@@ -3572,7 +3595,19 @@ interface TriggerTrace {
3572
3595
  * runtime decoupled from `@lunora/queue`'s structural batch type) along with the
3573
3596
  * invocation's own {@link TriggerTrace}.
3574
3597
  */
3575
- type QueueConsumerHandler = (batch: unknown, env: unknown, context: ExecutionContextLike, trigger: TriggerTrace) => Promise<void>;
3598
+ type QueueConsumerHandler = (batch: unknown, env: unknown, context: ExecutionContextLike, trigger: TriggerTrace, live: QueueLivePublisherLike, fetchImpl: typeof fetch | undefined) => Promise<void>;
3599
+ /**
3600
+ * The publisher a queue consumer's `ctx.live` is. The Worker forwards it to the
3601
+ * shard (a consumer runs in the Worker, not in a shard); codegen passes it on only
3602
+ * for an app whose target serves live streams. Structural, so `@lunora/queue` types
3603
+ * its own copy and this package stays decoupled from it.
3604
+ */
3605
+ interface QueueLivePublisherLike {
3606
+ publish: (topic: string, payload: unknown, options: {
3607
+ shardKey?: string;
3608
+ stream: string;
3609
+ }) => Promise<void>;
3610
+ }
3576
3611
  /**
3577
3612
  * A single code-defined cron job, shaped like an entry of the generated
3578
3613
  * `LUNORA_CRONS` map. `functionPath` is the `"namespace:fn"` to run, `args` its
@@ -4128,6 +4163,13 @@ interface WorkerOptions {
4128
4163
  * other DOs of a `.shardBy(...)` one.
4129
4164
  */
4130
4165
  listSchemaTables?: () => ReadonlyArray<string>;
4166
+ /**
4167
+ * Whether the target serves live topic streams. Defaults to `true`. `false` keeps
4168
+ * `ctx.live` on the HTTP action context and on a direct queue consumer, but its `publish`
4169
+ * rejects with `LIVE_STREAMS_UNSUPPORTED`, so no publish reaches a shard with no subscriber
4170
+ * to reach. Codegen sets it from the target's capability matrix.
4171
+ */
4172
+ liveStreams?: boolean;
4131
4173
  /**
4132
4174
  * The durable log archive's read config — the R2 Data Catalog (Iceberg)
4133
4175
  * table `pipelineLogSink` writes to, so the studio Logs panel's Archive feed
@@ -4211,6 +4253,13 @@ interface WorkerOptions {
4211
4253
  * stays decoupled from the queue package. Omitted when no push queues exist.
4212
4254
  */
4213
4255
  queue?: QueueConsumerHandler;
4256
+ /**
4257
+ * The `fetch` a queue consumer's `ctx.run` / `message.run` dispatches through.
4258
+ * Omitted, the dispatcher uses global `fetch` against `LUNORA_ORIGIN_URL`, which
4259
+ * is right on Cloudflare. A host with no origin to answer that URL (Node) passes
4260
+ * its own dispatch here, e.g. `platform.dispatch` wrapped as a `fetch`.
4261
+ */
4262
+ queueFetchImpl?: typeof fetch;
4214
4263
  /**
4215
4264
  * Queue-batch handler. WfP namespaced Workers can't be
4216
4265
  * queue consumers, so a platform-owned consumer forwards batches to the
package/dist/index.d.ts CHANGED
@@ -3095,6 +3095,18 @@ interface HttpActionContext {
3095
3095
  }) => Promise<unknown>;
3096
3096
  };
3097
3097
  fetch: typeof globalThis.fetch;
3098
+ /**
3099
+ * Forward a server-to-server request to a shard DO, carrying the caller's
3100
+ * resolved identity headers. Structural mirror of `@lunora/server`'s
3101
+ * `ShardFetch` — kept structural so the runtime stays free of a
3102
+ * `@lunora/server` dependency. The live-stream primitive uses it to reach
3103
+ * the shard's SSE + subscriber-registry endpoints.
3104
+ */
3105
+ fetchShard: (shardKey: string | undefined, path: string, init?: {
3106
+ body?: string;
3107
+ headers?: Record<string, string>;
3108
+ method?: string;
3109
+ }) => Promise<Response>;
3098
3110
  /**
3099
3111
  * The same `run*` trio bound to a named shard, mirroring
3100
3112
  * `createShardClient(...).forShard(key)`.
@@ -3107,6 +3119,17 @@ interface HttpActionContext {
3107
3119
  * (usually none) with no error and no way to say otherwise.
3108
3120
  */
3109
3121
  forShard: (shardKey: string) => Pick<HttpActionContext, "runAction" | "runMutation" | "runQuery">;
3122
+ /**
3123
+ * Publish an arbitrary event to a live topic on a stream. Structural mirror of
3124
+ * `@lunora/server`'s `LivePublisher`. Present on every worker; built with
3125
+ * `liveStreams: false` (a target that does not serve live streams), its `publish` rejects.
3126
+ */
3127
+ live?: {
3128
+ publish: (topic: string, payload: unknown, options: {
3129
+ shardKey?: string;
3130
+ stream: string;
3131
+ }) => Promise<void>;
3132
+ };
3110
3133
  runAction: <R>(reference: unknown, args?: Record<string, unknown>) => Promise<R>;
3111
3134
  runMutation: <R>(reference: unknown, args?: Record<string, unknown>) => Promise<R>;
3112
3135
  runQuery: <R>(reference: unknown, args?: Record<string, unknown>) => Promise<R>;
@@ -3572,7 +3595,19 @@ interface TriggerTrace {
3572
3595
  * runtime decoupled from `@lunora/queue`'s structural batch type) along with the
3573
3596
  * invocation's own {@link TriggerTrace}.
3574
3597
  */
3575
- type QueueConsumerHandler = (batch: unknown, env: unknown, context: ExecutionContextLike, trigger: TriggerTrace) => Promise<void>;
3598
+ type QueueConsumerHandler = (batch: unknown, env: unknown, context: ExecutionContextLike, trigger: TriggerTrace, live: QueueLivePublisherLike, fetchImpl: typeof fetch | undefined) => Promise<void>;
3599
+ /**
3600
+ * The publisher a queue consumer's `ctx.live` is. The Worker forwards it to the
3601
+ * shard (a consumer runs in the Worker, not in a shard); codegen passes it on only
3602
+ * for an app whose target serves live streams. Structural, so `@lunora/queue` types
3603
+ * its own copy and this package stays decoupled from it.
3604
+ */
3605
+ interface QueueLivePublisherLike {
3606
+ publish: (topic: string, payload: unknown, options: {
3607
+ shardKey?: string;
3608
+ stream: string;
3609
+ }) => Promise<void>;
3610
+ }
3576
3611
  /**
3577
3612
  * A single code-defined cron job, shaped like an entry of the generated
3578
3613
  * `LUNORA_CRONS` map. `functionPath` is the `"namespace:fn"` to run, `args` its
@@ -4128,6 +4163,13 @@ interface WorkerOptions {
4128
4163
  * other DOs of a `.shardBy(...)` one.
4129
4164
  */
4130
4165
  listSchemaTables?: () => ReadonlyArray<string>;
4166
+ /**
4167
+ * Whether the target serves live topic streams. Defaults to `true`. `false` keeps
4168
+ * `ctx.live` on the HTTP action context and on a direct queue consumer, but its `publish`
4169
+ * rejects with `LIVE_STREAMS_UNSUPPORTED`, so no publish reaches a shard with no subscriber
4170
+ * to reach. Codegen sets it from the target's capability matrix.
4171
+ */
4172
+ liveStreams?: boolean;
4131
4173
  /**
4132
4174
  * The durable log archive's read config — the R2 Data Catalog (Iceberg)
4133
4175
  * table `pipelineLogSink` writes to, so the studio Logs panel's Archive feed
@@ -4211,6 +4253,13 @@ interface WorkerOptions {
4211
4253
  * stays decoupled from the queue package. Omitted when no push queues exist.
4212
4254
  */
4213
4255
  queue?: QueueConsumerHandler;
4256
+ /**
4257
+ * The `fetch` a queue consumer's `ctx.run` / `message.run` dispatches through.
4258
+ * Omitted, the dispatcher uses global `fetch` against `LUNORA_ORIGIN_URL`, which
4259
+ * is right on Cloudflare. A host with no origin to answer that URL (Node) passes
4260
+ * its own dispatch here, e.g. `platform.dispatch` wrapped as a `fetch`.
4261
+ */
4262
+ queueFetchImpl?: typeof fetch;
4214
4263
  /**
4215
4264
  * Queue-batch handler. WfP namespaced Workers can't be
4216
4265
  * queue consumers, so a platform-owned consumer forwards batches to the
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as R,toFivetranResponse as x}from"./packem_shared/toAirbyteMessages-DY0vsuEn.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as y}from"./packem_shared/composeWorker-jjXafR9H.mjs";import{createCrossShardRelationCapabilities as O}from"./packem_shared/createCrossShardRelationCapabilities-BmGOuTrp.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-CdACWUQW.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w as B}from"./packem_shared/export-tap-C2B_SATf.mjs";import{HEALTH_PATH as w,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-CAX2UeFy.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as $,memoizeIdentityPerRequest as ee}from"./packem_shared/memoizeIdentity-BNnHkqeF.mjs";import{e as oe,a as te}from"./packem_shared/observability-DgurIZIR.mjs";import{analyticsEngineSink as se,combineSinks as ie,consoleSink as pe,otlpSink as ne,pipelineLogSink as ce,webhookSink as me}from"./packem_shared/analyticsEngineSink-BZB-ZYCP.mjs";import{D as Ee,c as Re}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as Se,createStaticShardRegistry as le}from"./packem_shared/createQueryCoordinator-es4jrL6Q.mjs";import{applyJurisdiction as ue,resolveShard as _e}from"./packem_shared/applyJurisdiction-D4vryLhj.mjs";import{a as ye,r as Ce,b as Oe}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as Ae,b as Le,c as Te,r as he}from"./packem_shared/rest-routes-DQkyqlym.mjs";import{decorateResponse as Pe,enforceOrigin as ge,handleCorsPreflight as ve,resolveSecurity as Ie}from"./packem_shared/decorateResponse-BxMmYMux.mjs";import{createShardClient as Fe}from"./packem_shared/createShardClient-DIVRljRz.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ne}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ke}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Be}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as we,routeIdentityResolvers as ze}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Ee as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,w as HEALTH_PATH,z as HEALTH_READY_PATH,Ke as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,Be as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ne as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,se as analyticsEngineSink,ue as applyJurisdiction,ye as applyRestCache,Ae as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,Le as buildRestRoutes,ie as combineSinks,we as composeIdentityResolvers,l as composeWorker,pe as consoleSink,O as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,d as createLunoraHandler,M as createMemoryCursorStore,Re as createPipelineLogReader,Se as createQueryCoordinator,Te as createRestRateLimit,Fe as createShardClient,le as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Pe as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,ge as enforceOrigin,ve as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,ne as otlpSink,H as parseStackFrames,ce as pipelineLogSink,W as presenceProbe,G as r2Sink,Ce as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Ie as resolveSecurity,_e as resolveShard,Oe as restCacheHeaders,he as restSurfaceFromRegistry,ze as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,R as toAirbyteMessages,P as toError,I as toErrorResponse,x as toFivetranResponse,B as webhookExportSink,me as webhookSink,y as withFrameworkWorker};
1
+ import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as R,toFivetranResponse as x}from"./packem_shared/toAirbyteMessages-DY0vsuEn.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as y}from"./packem_shared/composeWorker-CpBdENRS.mjs";import{createCrossShardRelationCapabilities as O}from"./packem_shared/createCrossShardRelationCapabilities-BmGOuTrp.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-CdACWUQW.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w as B}from"./packem_shared/export-tap-C2B_SATf.mjs";import{HEALTH_PATH as w,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-CAX2UeFy.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as $,memoizeIdentityPerRequest as ee}from"./packem_shared/memoizeIdentity-BNnHkqeF.mjs";import{e as oe,a as te}from"./packem_shared/observability-DgurIZIR.mjs";import{analyticsEngineSink as se,combineSinks as ie,consoleSink as pe,otlpSink as ne,pipelineLogSink as ce,webhookSink as me}from"./packem_shared/analyticsEngineSink-BZB-ZYCP.mjs";import{D as Ee,c as Re}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as Se,createStaticShardRegistry as le}from"./packem_shared/createQueryCoordinator-es4jrL6Q.mjs";import{applyJurisdiction as ue,resolveShard as _e}from"./packem_shared/applyJurisdiction-D4vryLhj.mjs";import{a as ye,r as Ce,b as Oe}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as Ae,b as Le,c as Te,r as he}from"./packem_shared/rest-routes-DQkyqlym.mjs";import{decorateResponse as Pe,enforceOrigin as ge,handleCorsPreflight as ve,resolveSecurity as Ie}from"./packem_shared/decorateResponse-CRBbtPYT.mjs";import{createShardClient as Fe}from"./packem_shared/createShardClient-DIVRljRz.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ne}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ke}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Be}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as we,routeIdentityResolvers as ze}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Ee as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,w as HEALTH_PATH,z as HEALTH_READY_PATH,Ke as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,Be as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ne as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,se as analyticsEngineSink,ue as applyJurisdiction,ye as applyRestCache,Ae as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,Le as buildRestRoutes,ie as combineSinks,we as composeIdentityResolvers,l as composeWorker,pe as consoleSink,O as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,d as createLunoraHandler,M as createMemoryCursorStore,Re as createPipelineLogReader,Se as createQueryCoordinator,Te as createRestRateLimit,Fe as createShardClient,le as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Pe as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,ge as enforceOrigin,ve as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,ne as otlpSink,H as parseStackFrames,ce as pipelineLogSink,W as presenceProbe,G as r2Sink,Ce as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Ie as resolveSecurity,_e as resolveShard,Oe as restCacheHeaders,he as restSurfaceFromRegistry,ze as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,R as toAirbyteMessages,P as toError,I as toErrorResponse,x as toFivetranResponse,B as webhookExportSink,me as webhookSink,y as withFrameworkWorker};
@@ -0,0 +1,6 @@
1
+ import{isLunoraError as wr,toErrorBody as gr}from"@lunora/errors";import{encodeWire as ye,decodeWire as Xe,encodeArgsOrThrow as yr}from"@lunora/wire";import{e as rn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as br}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{i as _r,e as Rr,a as Er,E as yt,d as Sr}from"./identity-header-pR617HTs.mjs";import{O as on,a as sn}from"./origin-paywall-B6eOO67m.mjs";import{o as be,b as an,p as Tr,m as Ar,d as Or,a as vr,r as Ir}from"./otlp-resource-BwFJnvwB.mjs";import{r as Pr,f as bt,a as ue,S as _t}from"./observability-DgurIZIR.mjs";import{t as kr,f as Dr}from"./base64-Bl1_r2k1.mjs";import{d as ne,e as oe,M as cn,b as Nr,f as Ur,g as dn,w as Cr,h as un,t as Br}from"./rest-routes-DQkyqlym.mjs";import{LunoraError as c,toErrorResponse as Rt}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as ge}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as ot,BACKUP_KEY_PREFIX as st,isBackupManifestKey as xr,backupObjectKeyOfManifest as ln,backupObjectKey as Hr,backupManifestKey as Lr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as jr,buildStorageAdminRoutes as Mr,STORAGE_UPLOAD_MAX_BODY_BYTES as $r,STORAGE_PATH as Fr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as Kr,e as Gr,f as Et,g as Qr,h as Wr}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as zr,durableObjectProbe as Vr,d1Probe as Jr,presenceProbe as $e}from"./HEALTH_PATH-CAX2UeFy.mjs";import{wrapResolverWithContract as Yr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Fi,routeIdentityResolvers as Ki}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as qr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{pruneShardRegistry as Xr,createQueryCoordinator as Zr,createDefaultShardRegistry as eo}from"./createQueryCoordinator-es4jrL6Q.mjs";import{resolveShard as _e,applyJurisdiction as Fe}from"./applyJurisdiction-D4vryLhj.mjs";import{resolveSecurity as St,handleCorsPreflight as to,enforceOrigin as no,decorateResponse as Ke,enforceWebSocketOrigin as Tt}from"./decorateResponse-CRBbtPYT.mjs";const ro=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,s={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return s.bucket=()=>s,s},hn="__lunoraBranch",oo=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,hn),so=`may not contain the reserved workflow branch-marker key ("${hn}")`,ao=async e=>{const t=[];let n;for(;;){const r=await e(n);if(t.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return t;if(r.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=r.cursor}},io=/already[\s_-]?exists/iu,co=e=>io.test(e instanceof Error?e.message:String(e)),At="x-lunora-want-error-detail",Ot="x-lunora-error-detail",uo=8192,lo=e=>{if(!(e instanceof Error))return{message:String(e),name:typeof e};const{code:t}=e;return{...typeof t=="string"?{code:t}:{},message:e.message,name:e.name,...e.stack===void 0?{}:{stack:e.stack.slice(0,uo)}}},vt=e=>{if(e!=null)try{const t=JSON.parse(decodeURIComponent(e));return typeof t?.message=="string"&&typeof t.name=="string"?t:void 0}catch{return}},ho="/_lunora/live/publish",fo="cf-ray",po="x-lunora-ray-id",mo=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,wo=e=>e==null?void 0:mo.exec(e.trim())?.[1]?.toLowerCase(),go=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(go);const yo=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),bo=-100,_o=15,Ro=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&yo.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>_o?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<bo?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},It=e=>{const t=e.cf;return t===void 0?void 0:Ro(t)},Ze="::relay::",Eo=(e,t)=>`${e}${Ze}${String(t)}`,et="::replica::",So=(e,t)=>`${e}${et}${t}`,To=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},fn=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let s=0;s<n;s+=1){const i=s<e.length?e.charCodeAt(s):0,d=s<t.length?t.charCodeAt(s):0;r|=i^d}return r===0},Ao=(e,t,n,r)=>{const s=e.get(t);if(s!==void 0)return s;rn(e,r);const i=n().catch(d=>{throw e.get(t)===i&&e.delete(t),d});return e.set(t,i),i},at=new TextEncoder,Oo=Array.from({length:32},(e,t)=>t);new RegExp(`[${Oo.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const vo=64,Io=new Map,pn=async e=>Ao(Io,e,async()=>crypto.subtle.importKey("raw",at.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),vo),mn=async(e,t)=>{const n=await pn(e),r=await crypto.subtle.sign("HMAC",n,at.encode(t));return kr(new Uint8Array(r))},Po=async(e,t,n)=>{const r=await pn(e);return crypto.subtle.verify("HMAC",r,n,at.encode(t))},ko="/_lunora/scheduler/dispatch",Do="__lunora_relation__:",No=e=>e.startsWith(Do),wn=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...s]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:fn(t,s.join(" ").trim())},Uo=async(e,t,n)=>{const r=e.headers.get("x-lunora-scheduler-signature"),{schedulerSecret:s}=n;return r!==null&&r.length>0&&s!==void 0&&s.length>0?fn(await mn(s,t),r):wn(e,n.adminToken)},Co=({forwardedIdentity:e,mutationId:t,traceparent:n})=>{const r={"content-type":"application/json",[sn]:on,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(r["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(r["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(r["x-lunora-mutation-id"]=t),n!==void 0&&n.length>0&&(r.traceparent=n),r},Bo=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}}},xo=(e,t,n)=>e?.[n]??t?.[n],Ho=(e,t,n,r)=>{const s=xo(e,t,n);if(!(typeof s!="object"||s===null))return r.every(i=>typeof s[i]=="function")?s:void 0},gn="v1",Lo=6e4,jo=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Lo),r=`${gn}.${String(n)}`,s=await mn(e,r);return{expiresAtMs:n,token:`${r}.${s}`}},Mo=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const r=t.split(".");if(r.length!==3)return!1;const[s,i,d]=r;if(s!==gn||d.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let h;try{h=Dr(d)}catch{return!1}return Po(e,`${s}.${i}`,h)},U="/_lunora/admin/auth",$o={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},B=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},me=(e,t)=>{const n=e(t);if(n===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},yn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},re=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ge=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},Pt=e=>{const t=yn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},kt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[r,s]of Object.entries(t))Array.isArray(s)&&s.every(i=>typeof i=="string")&&(n[r]=s);return n},Fo={[`${U}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${U}/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"},[`${U}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${U}/accounts`]:{build:({query:e})=>({userId:me(e,"userId")}),http:"GET",method:"listAccounts"},[`${U}/passkeys`]:{build:({query:e})=>({userId:me(e,"userId")}),http:"GET",method:"listPasskeys"},[`${U}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${U}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listMembers"},[`${U}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${U}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${U}/sign-up-invitations/create`]:{build:({body:e})=>({email:B(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:re(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${U}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:B(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${U}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${U}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listTeams"},[`${U}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:me(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${U}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${U}/users/create`]:{build:({body:e})=>({data:Ge(e,"data"),email:B(e,"email"),name:B(e,"name"),password:re(e,"password"),role:yn(e.role)}),http:"POST",method:"createUser"},[`${U}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:B(e,"userId")}},http:"POST",method:"updateUser"},[`${U}/users/role`]:{build:({body:e})=>({role:Pt(e),userId:B(e,"userId")}),http:"POST",method:"setRole"},[`${U}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:B(e,"userId")}),http:"POST",method:"banUser"},[`${U}/users/unban`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"unbanUser"},[`${U}/users/password`]:{build:({body:e})=>({newPassword:B(e,"newPassword"),userId:B(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${U}/users/remove`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${U}/users/impersonate`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"impersonateUser"},[`${U}/sessions/revoke`]:{build:({body:e})=>({sessionId:B(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${U}/sessions/revoke-all`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${U}/accounts/unlink`]:{build:({body:e})=>({accountId:B(e,"accountId"),userId:B(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${U}/two-factor/disable`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${U}/passkeys/delete`]:{build:({body:e})=>({passkeyId:B(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${U}/organizations/members/remove`]:{build:({body:e})=>({memberId:B(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${U}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:B(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${U}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:Ge(e,"metadata"),name:B(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${U}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:Ge(e,"metadata"),name:re(e,"name"),organizationId:B(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${U}/organizations/remove`]:{build:({body:e})=>({organizationId:B(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${U}/organizations/members/add`]:{build:({body:e})=>({organizationId:B(e,"organizationId"),role:re(e,"role"),userId:B(e,"userId")}),http:"POST",method:"addMember"},[`${U}/organizations/members/invite`]:{build:({body:e})=>({email:B(e,"email"),inviterId:re(e,"inviterId"),organizationId:B(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${U}/organizations/members/role`]:{build:({body:e})=>({memberId:B(e,"memberId"),role:Pt(e)}),http:"POST",method:"updateMemberRole"},[`${U}/organizations/teams/create`]:{build:({body:e})=>({name:B(e,"name"),organizationId:B(e,"organizationId")}),http:"POST",method:"createTeam"},[`${U}/organizations/teams/update`]:{build:({body:e})=>({name:B(e,"name"),teamId:B(e,"teamId")}),http:"POST",method:"updateTeam"},[`${U}/organizations/teams/remove`]:{build:({body:e})=>({teamId:B(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${U}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:B(e,"teamId"),userId:B(e,"userId")}),http:"POST",method:"addTeamMember"},[`${U}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:B(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${U}/organizations/roles/create`]:{build:({body:e})=>({organizationId:B(e,"organizationId"),permission:kt(e),role:B(e,"role")}),http:"POST",method:"createOrgRole"},[`${U}/organizations/roles/update`]:{build:({body:e})=>({permission:kt(e),roleId:B(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${U}/organizations/roles/remove`]:{build:({body:e})=>({roleId:B(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Ko=e=>{const t=async s=>{try{return await s()}catch(i){if(i instanceof c)throw i;const d=i,f=typeof d.code=="string"?d.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:f,status:$o[f]??500})}},n=async(s,i)=>{if(e.assertAdmin(s),s.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const d=e.getAuthAdmin();if(d===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=d[i.method];if(f===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const h=new URL(s.url),m={body:i.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:T=>e.queryParameter(h,T)},_=i.build(m),S=await t(()=>f(_));return Response.json(i.returns==="void"?{ok:!0}:S,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[s,i]of Object.entries(Fo))r[s]=d=>n(d,i);return r},Dt="__lunora_admin__:getAuthAuditLog",Nt=e=>typeof e=="string"&&e!==""?e:void 0,Ut=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Go=e=>async(n,r)=>{e.assertAdmin(n);const s=e.getReader();if(s===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=Nt(r.actorId),d=Nt(r.event),f=Ut(r.sinceSeq),h=Ut(r.limit),m={...i===void 0?{}:{actorId:i},...d===void 0?{}:{event:d},...f===void 0?{}:{sinceSeq:f},...h===void 0?{}:{limit:h}};let _;try{_=await s.read(m)}catch(T){throw T instanceof c?T:(console.error("[lunora] auth audit read failed:",T),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const S={entries:_};return Response.json({result:ye(S)},{headers:{"content-type":"application/json"},status:200})},tt="__lunora_admin__:copyAuthToJurisdiction",bn="__lunora_admin__:purgeUnpinnedAuth",Qo=e=>async(t,n,r)=>{if(n!==tt&&n!==bn)return;e.assertAdmin(t);const s=e.getMove();if(s===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===tt?await s.copy({force:r.force===!0}):await s.purge();return Response.json({result:ye(i)},{headers:{"content-type":"application/json"},status:200})},Wo=(e,t)=>{const n=[],r=[];if(t&&t.length>0)for(const s of t)e.resolveTableSharding?.(s)?.mode.kind==="global"?r.push(s):n.push(s);return{globalTables:r,shardLocalTables:n}},zo=async(e,t,n,r,s,i)=>{if(n!==void 0&&r.length===0)return[];const d=await e.orchestrateExport(s,{args:{tables:r},defaultShardKey:i,headers:t,tables:r}),f=d.shards.filter(h=>h.error);if(f.length>0){const h=f.map(m=>`${m.shardKey}: ${m.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(f.length)} of ${String(d.shards.length)} shard(s) — ${h}`,{code:"EXPORT_SHARD_FAILED",status:502})}return d.shards.flatMap(h=>h.rows??[])},_n=async(e,t,n,r,s)=>{const i=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:d,shardLocalTables:f}=Wo(e,i),h=await zo(t,n,i,f,s,e.defaultShardKey??"__root__"),m=e.exportGlobals,_=r===void 0||d.length>0;return(async function*(){yield*h,_&&m&&(yield*m({tables:d}))})()},Vo=async(e,t,n,r,s,i)=>{for await(const d of await _n(e,t,n,r,i))s(d)},Jo=new TextEncoder,Yo=1e3,Rn=10,qo=200,Ct=8,En="lunoraBackupCron",Bt=24*1048576,xt=e=>{const t=e.slice(0,Rn).map(r=>ln(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Xo=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const s of e)n.set(s,r),r+=s.byteLength;return n},it=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const s=[];let i;for(let d=0;d<Yo;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)xr(h.key)&&h.customMetadata?.[En]===r&&s.push(h.key);if(!f.truncated||f.cursor===void 0)break;i=f.cursor}return{eligible:s.length,stale:s.toSorted((d,f)=>f.localeCompare(d)).slice(n)}},Zo=async(e,t,n,r,s)=>{const{stale:i}=await it(e,t,n,r),d=new Set(s),f=i.filter(P=>d.has(P)),h=f.slice(0,qo),m=i.length-h.length,_=s.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:_,remaining:m};const S=[],T=[];for(let P=0;P<h.length;P+=Ct){const w=await Promise.allSettled(h.slice(P,P+Ct).map(async g=>(await e.delete(ln(g)),await e.delete(g),g)));for(const[g,b]of w.entries())b.status==="fulfilled"?S.push(b.value):T.push(h[P+g])}return S.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(S.length)}: ${xt(S)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${xt(T)}`),{deleted:S,failed:T,ignored:_,remaining:m}},es=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=ot(e.backupPrefix??st),r=e.backupCron,{eligible:s,stale:i}=r===void 0?{eligible:0,stale:[]}:await it(t,n,e.backupRetain,r);return{cron:r,eligible:s,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},ts=async(e,t,n,r,s)=>{const i=e.backupStore;if(!i)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!r||r.length===0)throw new c("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const d={authorization:`Bearer ${r}`,"content-type":"application/json"},f=e.backupTables;let h=0,m=0,_=[];await Vo(e,t,d,f,I=>{const E=Jo.encode(`${JSON.stringify(I)}
2
+ `);if(h+=1,m+=E.byteLength,m>Bt)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Bt)}-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});_.push(E)},n);const T=ot(e.backupPrefix??st),P=new Date(s.scheduledTime).toISOString(),w=Hr(T,P),g=Xo(_,m);_=[];const b=jr(await crypto.subtle.digest("SHA-256",g));await i.put(w,g,{httpMetadata:{contentType:"application/x-ndjson"},sha256:b});const A={bytes:m,createdAt:P,cron:s.cron,file:w,id:P,rows:h,scheduledTime:s.scheduledTime,sha256:b,...f?{tables:f.join(",")}:{}};await i.put(Lr(w),`${JSON.stringify(A,void 0,2)}
3
+ `,{customMetadata:{[En]:s.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:I}=await it(i,T,e.backupRetain,s.cron);if(I.length>0){const E=I.slice(0,Rn),L=I.length-E.length;console.info(`[lunora] backup retention: ${String(I.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${E.join(", ")}${L>0?` (+${String(L)} more)`:""}`)}}catch(I){console.warn(`[lunora] backup ${w} was written, but the retention report failed:`,I)}},ns=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=e.backupCron,s=e.backupRetain;if(r===void 0||s===void 0||!Number.isInteger(s)||s<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return Zo(n,ot(e.backupPrefix??st),s,r,t)},rs="/_lunora/admin/backup/retention",os="/_lunora/admin/backup/prune",ss=e=>{const{options:t,readJsonBody:n,requireAdminOption:r}=e,s=(f,h)=>{r(f,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${h} requires a \`backupStore\` on the worker`})},i=async f=>(M(f,"GET","Backup-retention"),s(f,"retention preview"),Response.json(await es(t),{headers:{"cache-control":"no-store"}})),d=async f=>{M(f,"POST","Backup-prune"),s(f,"prune");const{confirm:h}=await n(f);if(!Array.isArray(h)||h.some(m=>typeof m!="string"))throw new c("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await ns(t,h),{headers:{"cache-control":"no-store"}})};return{[os]:d,[rs]:i}},Ht=500,as=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const r=e;if(typeof r.functionPath!="string")throw new c("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 c("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 c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(r.id!==void 0&&typeof r.id!="number")throw new c("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:r.args===void 0?{}:r.args,baselineSeq:typeof r.baselineSeq=="number"?r.baselineSeq:void 0,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:t,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:n}},is=(e,t)=>{if(e.length>Ht)throw new c(`RPC batch exceeds the ${String(Ht)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,r=new Set;for(const[s,i]of e.entries()){const{entry:d,shardKey:f}=as(i,s,t);if(r.has(d.id))throw new c(`batch call id ${String(d.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});r.add(d.id);const h=n.get(f)??[];h.push(d),n.set(f,h)}return n},cs="/_lunora/admin/export",ds="/_lunora/admin/import",us="/_lunora/admin/sync",ls="/_lunora/admin/connector/sync",hs="/_lunora/admin/apply",fs="/_lunora/admin/export-tap/run",ps=new TextEncoder,ms=async e=>{const n=await oe(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const s of n.tables){if(typeof s!="string"||s.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(s)}return{tables:r}},Qe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,ws=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:s,knownTables:i,queryCoordinator:d,assertAdmin:f,resolveForwardContext:h,shardDO:m,prepareExportRows:_,streamingImport:S,syncGlobals:T}=e,P=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await ms(E),{headers:K}=await h(E,L),q=await _(K,C.tables),V=new ReadableStream({async pull(G){try{for await(const J of q)G.enqueue(ps.encode(`${JSON.stringify(J)}
4
+ `));G.close()}catch(J){G.error(J)}}});return new Response(V,{headers:{"content-type":"application/x-ndjson"},status:200})},w=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await ne(E),K=typeof C.cursors=="object"&&C.cursors!==null?C.cursors:{},q=typeof C.epochs=="object"&&C.epochs!==null?C.epochs:{},V=typeof C.limit=="number"?C.limit:void 0,G=typeof C.globalCursor=="number"?C.globalCursor:0,J=Qe(C.tables),{headers:se}=await h(E,L),W=J??i(),le=await d.orchestrateCdcSync(m,{cursors:K,defaultShardKey:n,epochs:q,headers:se,limit:V,tables:W}),ae=T?await T({limit:V,sinceSeq:G}):void 0;return Response.json({global:ae,shards:le.shards},{status:200})},g=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await ne(E),K=Gr(C.cursor),q=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,V=Qe(C.tables),{headers:G}=await h(E,L),J=V??i(),se=await d.orchestrateCdcSync(m,{cursors:K.s,defaultShardKey:n,headers:G,limit:q,tables:J}),W=[],le={...K.s};let ae=!1;for(const ce of se.shards)ae=Et(W,ce.changes??[],Wr(q))||ae,le[ce.shardKey]=ce.cursor;let z=K.g;if(T){const ce=await T({limit:q,sinceSeq:K.g});ae=Et(W,ce.changes,q)||ae,z=ce.cursor}const ie=Qr({g:z,s:le,v:1}),xe={changes:W,hasMore:ae,nextCursor:ie};return Response.json(xe,{status:200})},b=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await ne(E),q=(Array.isArray(C.batches)?C.batches:[]).map(W=>W).filter(W=>W!==null&&typeof W=="object"&&typeof W.shardKey=="string"&&Array.isArray(W.changes)),V=Array.isArray(C.globalChanges)?C.globalChanges:[],{headers:G}=await h(E,L),J=await d.orchestrateApplyCdc(m,{batches:q,headers:G}),se=V.length>0&&t?await t({changes:V}):0;return Response.json({applied:J.applied+se,failed:J.failed,ok:J.ok},{status:200})},A=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const{headers:C}=await h(E,L),K=await S(E,C);return Response.json(K,{headers:{"content-type":"application/json"},status:K.failed.length>0?207:200})},I=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;if(f(E),s===void 0||Object.keys(s).length===0||r===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const C=await ne(E),K=typeof C.sink=="string"?C.sink:void 0,q=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,V=Qe(C.tables);if(K===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const G=s[K];if(G===void 0)throw new c(`Export-tap sink "${K}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:J}=await h(E,L),se=V??i(),W=await Kr({coordinator:d,cursorStore:r,defaultShardKey:n,headers:J,limit:q,shardDO:m,sink:G,tables:se});return Response.json(W,{headers:{"content-type":"application/json"},status:200})};return{[hs]:b,[ls]:g,[cs]:P,[fs]:I,[ds]:A,[us]:w}},gs=(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 r=n;return typeof r.table!="string"||r.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!r.doc||typeof r.doc!="object"||Array.isArray(r.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:r.table},ok:!1}:{doc:r.doc,ok:!0,table:r.table}},ys=(e,t,n,r,s)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:s,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:r}},bs=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],s=[],i=new Map;let d=0,f=0;const h=e.body.getReader(),m=new TextDecoder;let _="",S=0;const T=P=>{f+=1;const w=P.trim();if(w.length===0)return;d+=1;const g=gs(w,f);if(!g.ok){r.push(g.error);return}const{doc:b,table:A}=g,I=t.resolveTableSharding?.(A);if(I?.mode.kind==="global"){s.push({doc:b,line:f,table:A});return}const E=ys(b,A,I,n,f);if(!E.ok){r.push(E.error);return}const L=i.get(E.shardKey);L?L.rows.push({doc:b,table:A}):i.set(E.shardKey,{rows:[{doc:b,table:A}],shardKey:E.shardKey,startLine:f})};for(;;){const{done:P,value:w}=await h.read();if(P)break;if(w&&(S+=w.byteLength,S>cn))throw await h.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});_+=m.decode(w,{stream:!0});let g=_.indexOf(`
5
+ `);for(;g!==-1;){const b=_.slice(0,g);_=_.slice(g+1),T(b),g=_.indexOf(`
6
+ `)}}return _.length>0&&T(_),{errors:r,globalRows:s,perShard:i,received:d}},_s=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),Lt=(e,t)=>{for(const[n,r]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+r;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},Rs=async(e,t,n,r,s)=>{const i=t.defaultShardKey??"__root__",{errors:d,globalRows:f,perShard:h,received:m}=await bs(e,t,i),_={conflicts:0,errors:d,failed:[],inserted:{}},S=[];if(t.resolveTableSharding===void 0&&h.size>0&&S.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const T=await n.orchestrateImport(s,{batches:[...h.values()],headers:r});Lt(_,T),_.failed.push(..._s(T.shards))}if(f.length>0)if(t.importGlobals){const T=f[0]?.line??1,P=await t.importGlobals({rows:f,startLine:T});Lt(_,P)}else for(const T of f)_.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:T.line,message:`row targets global table "${T.table}" but no \`importGlobals\` is configured`,table:T.table});return{conflicts:_.conflicts,errors:_.errors,failed:_.failed,inserted:_.inserted,received:m,...S.length>0?{warnings:S}:{}}},Es=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),We=e=>typeof e=="object"&&e!==null?e:{},ze=e=>typeof e.kind=="string"?e.kind:"unknown",Ss=(e,t)=>{let n=We(t),r=!1;ze(n)==="optional"&&(r=!0,n=We(n._meta?.inner));const s=ze(n),i=n._meta??{},d={kind:s,name:e,optional:r};if(s==="id"&&typeof i.tableName=="string"&&(d.table=i.tableName),s==="array"){const f=ze(We(i.inner));f!=="unknown"&&(d.element=f)}return d},Ts=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>Ss(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),As="/_lunora/admin/functions",Os="/_lunora/admin/cron-jobs",vs="/_lunora/admin/architecture",Is="/_lunora/admin/openapi",Ps="/_lunora/admin/openrpc",ks="/_lunora/admin/global/tables",Ds="/_lunora/admin/global/table",Ns="/_lunora/admin/global/facet",jt=e=>{if(e===void 0||e==="")return;let t;try{t=Xe(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:s,value:i}=r;return[{column:s,value:i}]});return n.length===0?void 0:n},Us=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:{}}),Cs=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"}),Bs=e=>{const{assertAdmin:t,options:n,parsePaging:r,queryParameter:s,requireAdminOption:i}=e,d=w=>{M(w,"GET","Functions");const g=i(w,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),b=Object.entries(g).flatMap(([A,I])=>I.visibility==="internal"||I.kind==="stream"?[]:[{args:[...I.argumentDescriptors??Ts(I.args)],kind:I.kind,path:A}]).toSorted((A,I)=>A.path.localeCompare(I.path));return Response.json({functions:b},{headers:{"content-type":"application/json"},status:200})},f=w=>{M(w,"GET","Cron-jobs");const g=i(w,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),b=Object.entries(g).flatMap(([A,I])=>I.map(E=>({args:E.args,cron:A,functionPath:E.functionPath,name:E.name,shardKey:E.shardKey,workflow:E.workflow}))).toSorted((A,I)=>A.name.localeCompare(I.name));return Response.json({jobs:b},{headers:{"content-type":"application/json"},status:200})},h=w=>(M(w,"GET","Architecture"),t(w),Response.json(n.architecture??Es,{headers:{"content-type":"application/json"},status:200})),m=w=>(M(w,"GET","OpenAPI"),t(w),Response.json(n.openApiSpec??Us,{headers:{"content-type":"application/json"},status:200})),_=w=>(M(w,"GET","OpenRPC"),t(w),Response.json(n.openRpcSpec??Cs,{headers:{"content-type":"application/json"},status:200})),S=async w=>{M(w,"GET","Global-tables");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await g.listTables(),{headers:{"content-type":"application/json"},status:200})},T=async w=>{M(w,"GET","Global-table");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),b=new URL(w.url),A=s(b,"table");if(A===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const I=await g.readTablePage({...r(w),filters:jt(s(b,"filters")),table:A});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},P=async w=>{M(w,"GET","Global-facet");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),b=new URL(w.url),A=s(b,"table"),I=s(b,"column");if(A===void 0||I===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const E=s(b,"limit"),L=E===void 0?void 0:Number(E),j=await g.facetColumn({column:I,filters:jt(s(b,"filters")),limit:L!==void 0&&Number.isFinite(L)?L:void 0,table:A});return Response.json(j,{headers:{"content-type":"application/json"},status:200})};return{[Os]:f,[As]:d,[Ns]:P,[Ds]:T,[ks]:S,[vs]:h,[Is]:m,[Ps]:_}},xs="/_lunora/admin/kv/namespaces",Hs="/_lunora/admin/kv/keys",Sn="/_lunora/admin/kv/value",Tn=32*1048576,Mt=60,Ls=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=w=>n(w,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),s=w=>Response.json(w,{headers:{"content-type":"application/json"},status:200}),i=(w,g)=>{const b=new URL(w.url),A=b.searchParams.get("namespace")??"",I=b.searchParams.get("key")??"";if(A==="")throw new c(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(I==="")throw new c(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:I,namespace:A}},d=async(w,g)=>{if(!(await w.listNamespaces()).some(A=>A.binding===g))throw new c(`Unknown KV namespace binding \`${g}\``,{code:"NOT_FOUND",status:404})},f=async w=>(M(w,"GET","KV-namespaces"),s({namespaces:await r(w).listNamespaces()})),h=async w=>{M(w,"GET","KV-keys");const g=r(w),b=new URL(w.url),A=b.searchParams.get("namespace")??"";if(A==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const I=b.searchParams.get("prefix")??void 0,E=b.searchParams.get("cursor")??void 0,L=b.searchParams.get("limit"),j=L===null?void 0:Number.parseInt(L,10);if(j!==void 0&&(!Number.isInteger(j)||j<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const C=j===void 0?void 0:Math.min(j,1e3);return await d(g,A),s(await g.listKeys({cursor:E,limit:C,namespace:A,prefix:I}))},T={DELETE:async w=>{const g=r(w),b=i(w,"DELETE");return await d(g,b.namespace),await g.deleteKey(b),s({deleted:!0})},GET:async w=>{const g=r(w),b=i(w,"GET");return await d(g,b.namespace),s(await g.getValue(b))},PUT:async w=>{const g=r(w),b=await t(w,Tn);if(typeof b.namespace!="string"||b.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof b.key!="string"||b.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof b.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(b.expirationTtl!==void 0&&(typeof b.expirationTtl!="number"||!Number.isInteger(b.expirationTtl)||b.expirationTtl<Mt))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const A=Math.floor(Date.now()/1e3)+Mt;if(b.expiration!==void 0&&(typeof b.expiration!="number"||!Number.isInteger(b.expiration)||b.expiration<A))throw new c("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await d(g,b.namespace),await g.putValue({expiration:b.expiration,expirationTtl:b.expirationTtl,key:b.key,metadata:b.metadata,namespace:b.namespace,value:b.value}),s({ok:!0})}},P=w=>{const g=T[w.method];if(!g)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(w)};return{[xs]:f,[Hs]:h,[Sn]:P}},js="/_lunora/migrate",Ms="/_lunora/admin/pitr",$s="/_lunora/admin/rank",Fs="/_lunora/admin/rankpage",Ks="/_lunora/admin/shard-registry/prune",Gs="/_lunora/admin/shard-traffic",Qs=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Ws=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),zs=async e=>{const n=await oe(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!Qs.has(n.functionPath))throw new c("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},Vs=async e=>{const n=await oe(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new c("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new c("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new c("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new c("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},Js=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new c('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Ys=e=>{if(typeof e.table!="string"||e.table.length===0)throw new c("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new c("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new c("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new c("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new c("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},qs=async e=>{const n=await oe(e,"Rank page")??{};Ys(n);const r=Js(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:r,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},Xs=async e=>{const n=await oe(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},Zs=async e=>{const n=await oe(e,"Shard-registry prune")??{};if(n.tables!==void 0&&!(Array.isArray(n.tables)&&n.tables.every(r=>typeof r=="string")))throw new c("Shard-registry prune `tables` must be an array of table names",{code:"BAD_REQUEST",status:400});return{dryRun:n.dryRun===!0,tables:n.tables}},ea=async e=>{const n=await ne(e);if(typeof n.functionPath!="string"||!Ws.has(n.functionPath))throw new c("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new c("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},ta=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:r,queryCoordinator:s,resolveForwardContext:i,shardDO:d,shardedTables:f}=e,h=(g,b)=>{if(g.method!=="POST")throw new c(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(g))throw new c("Admin auth required",{code:"FORBIDDEN",status:403})},m=async(g,b)=>{h(g,"Migration");const A=await zs(g),{headers:I}=await i(g,b),E=await s.orchestrateMigration(d,{args:A.args,defaultShardKey:t,functionPath:A.functionPath,headers:I,table:A.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},_=async(g,b)=>{h(g,"Rank");const A=await Vs(g),{headers:I}=await i(g,b),E=await s.orchestrateRank(d,{headers:I,index:A.index,partitionKey:A.partitionKey,rowId:A.rowId,sortValues:A.sortValues,table:A.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},S=async(g,b)=>{h(g,"Rank page");const A=await qs(g),{headers:I}=await i(g,b),E=await s.orchestrateRankPage(d,{...A,headers:I});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},T=async(g,b)=>{h(g,"Shard-traffic");const A=await Xs(g),{headers:I}=await i(g,b),E=await s.orchestrateShardTraffic(d,{headers:I,table:A.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},P=async(g,b)=>{h(g,"Shard-registry prune");const A=await Zs(g),I=f(),E=(A.tables??[]).filter(C=>!I.includes(C));if(E.length>0)throw new c(`Shard-registry prune names tables that are not \`.shardBy()\`: ${E.join(", ")}`,{code:"BAD_REQUEST",status:400});const{headers:L}=await i(g,b),j=await Xr(s.registry,d,{dryRun:A.dryRun,headers:L,tables:A.tables??I});return Response.json(j,{status:j.failed.length>0?207:200})},w=async(g,b)=>{if(M(g,"POST","PITR"),!r(g))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const A=await ea(g),{headers:I}=await i(g,b),E=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:A.args,functionPath:A.functionPath}),headers:I,method:"POST"});return n(d,A.shardKey??t,E)};return{[js]:m,[Ms]:w,[$s]:_,[Fs]:S,[Ks]:P,[Gs]:T}},na=1,ra=0,oa=32,sa=512,aa=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,ia=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>sa)return;const n=t.split(",");if(!(n.length>oa)){for(const r of n)if(!aa.test(r.trim()))return;return t}},ca=e=>{const t=Tr(e.headers.get("traceparent"));if(t===void 0)return;const n=ia(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},$t=(e,t={})=>{const n=ca(e),r=t.trustInbound===!0?n:void 0,s=be(8),i=r?.traceId??be(16),d=Pr(t.sampling,r===void 0?s:i),{rayId:f}=t,h=d.isTraced&&(r===void 0||r.sampled);return{decision:d,ignoredUpstream:n!==void 0&&r===void 0,trace:{sampled:h,spanId:s,traceFlags:h?na:ra,traceId:i,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState},...f===void 0?{}:{rayId:f}}}},Ft=(e,t)=>{t.traceparent=an(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState),e.rayId!==void 0&&(t[po]=e.rayId)},da=(e,t)=>{let n;return()=>{if(n===void 0){const r=Ir(e),s=t===void 0?void 0:t.cf;n=Ar(vr(r),Or(r,s))}return n}},ua="/_lunora/admin/scheduled",la="/_lunora/admin/scheduled/status",ha="/_lunora/admin/scheduled/ws",fa="/_lunora/admin/scheduled/cancel",pa="/_lunora/admin/scheduled/dead",ma="/_lunora/admin/scheduled/dead/retry",wa="/_lunora/admin/scheduled/dead/cancel",ga="/_lunora/admin/scheduled/pool/release",ya=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:r,schedulerInstanceName:s}=e,i=(m,_)=>S=>{if(S.method!=="GET")throw new c(`${_} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(S.url).searchParams.get("cursor"),P=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return r(S).fetch(new Request(`https://scheduler.internal${m}${P}`,{method:"GET"}))},d=(m,_,S=_)=>async T=>{if(T.method!=="POST")throw new c(`${S} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const P=r(T),w=await oe(T,_);if(typeof w?.id!="string"||w.id==="")throw new c(`${_} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return P.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))},f=async m=>{if(m.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const _=r(m),S=await oe(m,"Scheduled pool-release");if(typeof S?.pool!="string"||S.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const T=typeof S.id=="string"&&S.id!==""?S.id:void 0;return _.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(T===void 0?{pool:S.pool}:{id:T,pool:S.pool}),headers:{"content-type":"application/json"},method:"POST"}))},h=async m=>{if(m.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(m))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const _=n();return _e(_,s).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[fa]:d("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[wa]:d("/dead/cancel","Scheduled dead-letter action"),[pa]:i("/dead","Scheduled dead-letter"),[ma]:d("/dead/retry","Scheduled dead-letter action"),[ua]:i("/list","Scheduled-list"),[ga]:f,[la]:i("/status","Scheduler-status"),[ha]:h}},ba="/_lunora/scheduled",An="/_lunora/queue",On=16*1048576,_a=e=>{const{assertAdmin:t,dispatchScheduled:n,queueHandler:r}=e,s=async(d,f,h)=>{if(t(d),d.method!=="POST")throw new c("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const m=await oe(d,"Scheduled tick"),_=typeof m?.cron=="string"?m.cron:"";if(_==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:_,noRetry:()=>{},scheduledTime:Date.now()},f,h),Response.json({cron:_,ok:!0})},i=async(d,f,h)=>{if(t(d),d.method!=="POST")throw new c("queue dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!r)throw new c("no queueHandler configured",{code:"BAD_REQUEST",status:400});const m=await oe(d,"Queue dispatch",On);if(!Array.isArray(m?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const _=typeof m.queue=="string"?m.queue:"",S=m.messages.filter(P=>typeof P=="object"&&P!==null&&typeof P.id=="string").map(P=>({body:P.body,id:P.id})),T=await r({messages:S,queue:_},f,h);return Response.json({retry:T?.retry??[]})};return{[An]:i,[ba]:s}},Ra=(e,...t)=>{let n=e.cf;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return typeof n=="string"?n:void 0},nt={mtls:e=>Ra(e,"tlsClientAuth","certVerified")==="SUCCESS"},Ea=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(nt,e)?nt[e]:void 0)??(()=>!1),Sa=e=>typeof e=="string"&&Object.hasOwn(nt,e),Ta=e=>{const t=Sa(e)?e:void 0;if(e!==void 0&&t===void 0)return()=>{};let n=!1;return r=>{n||t!==void 0&&r.cf!==void 0||(n=!0,console.warn(t===void 0?'[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.':`[lunora] \`trustInboundTraceContext: "${t}"\` cannot be satisfied on this host: the request carries no platform-injected \`cf\` metadata, which is what that signal reads, so every inbound \`traceparent\` is ignored and this request starts a new trace. Off Cloudflare, trust the upstream some other way — \`trustInboundTraceContext: true\` when nothing untrusted can reach this worker, or a predicate that verifies whatever your own front door sets. Set it to \`false\` to keep this behaviour and silence this message.`))}},Aa="/_lunora/admin/vector/indexes",Oa="/_lunora/admin/vector/query",va=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=async i=>{M(i,"GET","Vector-indexes");const d=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await d.listIndexes()},{headers:{"content-type":"application/json"},status:200})},s=async i=>{M(i,"POST","Vector-query");const d=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(d.queryIndex===void 0)throw new c("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const h=await t(i);if(typeof h.name!="string"||h.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof h.text!="string"||h.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(h.topK!==void 0&&(typeof h.topK!="number"||!Number.isInteger(h.topK)||h.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const m=await d.queryIndex({name:h.name,text:h.text,topK:h.topK});return Response.json(m,{headers:{"content-type":"application/json"},status:200})};return{[Aa]:r,[Oa]:s}},Ia="/_lunora/admin/workflows/instances",Pa="/_lunora/admin/workflows/instance",ka="/_lunora/admin/workflows/status",Da={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Na=e=>e!==null&&Object.hasOwn(Da,e)?e:void 0,Kt=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const r=Number(n);return Number.isInteger(r)&&r>0?r:void 0},Ve=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new c(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},Gt=()=>{throw new c("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Ua=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,r=async(d,f,h)=>{M(d,"GET","Workflows instances"),t(d);const m=n(f);if(!m)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const _=Ve(h,"name"),S=Na(h.searchParams.get("status"));return Response.json(await m.listInstances({page:Kt(h,"page"),perPage:Kt(h,"perPage"),status:S,workflowName:_}))},s=async(d,f,h)=>{M(d,"GET","Workflows instance"),t(d);const m=n(f);return m?Response.json(await m.getInstance({instanceId:Ve(h,"id"),workflowName:Ve(h,"name")})):Gt()},i=async(d,f)=>{M(d,"POST","Workflows status"),t(d);const h=n(f);if(!h)return Gt();const m=await oe(d,"Workflows status");if(typeof m?.name!="string"||m.name===""||typeof m.id!="string"||m.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:_}=m;if(_!=="pause"&&_!=="resume"&&_!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await h.setInstanceStatus({action:_,instanceId:m.id,workflowName:m.name}))};return{[Pa]:s,[Ia]:r,[ka]:i}},Ca={[Sn]:Tn,[An]:On,[Fr]:$r},Ba="https://queue.lunora.internal",Qt=()=>({publish:()=>Promise.reject(new c("ctx.live.publish is unavailable: this worker does not serve live streams",{code:"LIVE_STREAMS_UNSUPPORTED",status:501}))}),xa=async(e,t)=>{const n=new c(`ctx.live.publish to "${t}" failed with HTTP ${String(e.status)}`,{code:"INTERNAL",status:e.status>=400?e.status:500});let r;try{r=await e.json()}catch{return n}const s=r?.error;return typeof s?.code!="string"||e.status<400?n:new c(typeof s.message=="string"?s.message:`ctx.live.publish to "${t}" was refused`,{code:s.code,status:e.status})},Wt="/_lunora/rpc",Ha="/_lunora/rpc-batch",La="/_lunora/ws",Ae=(e,t,n)=>({resourceAttributes:da(e,t),...n===void 0?{}:{waitUntil:n}}),Je=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},zt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ye=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0,r=wo(e.headers.get(fo)),s=r===void 0?{}:{rayId:r};let i;try{i=new URL(e.url)}catch{return{method:t,...s,userAgent:n}}const d=i.port===""?void 0:Number(i.port);return{host:i.hostname,method:t,path:i.pathname,port:Number.isNaN(d)?void 0:d,...s,scheme:i.protocol.replace(":",""),userAgent:n}},Vt="/_lunora/voice/",ja="/_lunora/admin/cron-jobs/run",Ma="/_lunora/admin/ws-token",$a="/_lunora/admin/",Be="/_lunora/",Fa="/_lunora/migrate",Ka="/_lunora/status",Ga=e=>e.startsWith($a)||e===Fa,ke=e=>{if(No(e))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},De=async e=>await e===!0,Jt=(e,t)=>{const n=e.headers.get(yt);if(n===null)return;const r=Sr(n);if(r===void 0)throw new c(`malformed ${yt} header`,{code:"BAD_REQUEST",status:400});if(r.subject!==(t?.userId??null))throw new c("the session changed since this write was queued",{code:"IDENTITY_MISMATCH",status:409})},Yt="/api/auth",Qa="__lunora_admin__:recordAuthEvent",qt="__lunora_admin__:listPushSubscriptions",Wa=["/sign-in","/sign-up","/callback"],za=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const r=e.slice(n.length);return Wa.some(s=>r===s||r.startsWith(`${s}/`))},Xt=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},Ne=(e,t,n,r)=>{const s=wr(n),i=s?n.code:"INTERNAL_SERVER_ERROR",d=s?n.status:500,{message:f,name:h,stack:m}=lo(n);return{durationMs:t,error:{code:i,message:f,name:h,status:d,...m===void 0?{}:{stack:m}},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},vn=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},In=({identity:e})=>e!==null&&_r(vn(e)),Va=e=>{if(In(e))throw new c("authentication token expired",{code:"TOKEN_EXPIRED",status:401});return e},Ja=e=>{if(!In(e))return e;const t={...e.headers};return delete t["x-lunora-identity"],delete t["x-lunora-identity-exp"],delete t["x-lunora-userid"],{claims:null,headers:t,identity:null,userId:null}},Zt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Ya=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},rt=new WeakMap,qa=async(e,t,n,r,s=rt.get(e))=>{const i={"content-type":"application/json"},d=e.headers.get("authorization"),f=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),m=e.headers.get("x-lunora-mutation-id"),_=e.headers.get("x-lunora-client-id"),S=e.headers.get("x-lunora-client-seq"),T=e.headers.get("x-lunora-base-seq");d&&(i.authorization=d),f&&(i.cookie=f),h&&(i["x-d1-bookmark"]=h),m&&(i["x-lunora-mutation-id"]=m),_&&(i["x-lunora-client-id"]=_),S&&(i["x-lunora-client-seq"]=S),T&&(i["x-lunora-base-seq"]=T);const P=Br(e.headers,r);if(P&&(i["x-lunora-client-ip"]=P),i["x-lunora-origin"]=new URL(e.url).origin,!n)return{claims:null,headers:i,identity:null,userId:null};const w=await n(e,t,s);if(!w||typeof w.userId!="string"||w.userId.length===0)return{claims:null,headers:i,identity:null,userId:null};i["x-lunora-userid"]=Rr(w.userId);const g=vn(w);g!==void 0&&(i["x-lunora-identity-exp"]=String(g));const{userId:b,...A}=w,I=Object.keys(A).length>0?A:null;return I&&(i["x-lunora-identity"]=Er(I)),{claims:I,headers:i,identity:w,userId:b}},Xa=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Za=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new c("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new c("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new c("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!Xa.has(n.kind))throw new c("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new c("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new c("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},ei=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},qe=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new c("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new c(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},ti=async e=>{const t=await un(e);let n;try{n=JSON.parse(t)}catch{throw new c("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new c("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const r=n;if(r.args!==void 0&&dn(r.args,"RPC"),r.shardKey!==void 0&&typeof r.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const s=n,i=Za(s.fanOut),d=s.args??{};if(i&&s.functionPath.startsWith("__lunora_relation__:")){const f=d.table;if(typeof f=="string"&&f!==i.table)throw new c("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});d.table=i.table}return{args:d,fanOut:i,functionPath:s.functionPath,shardKey:s.shardKey}},Ue=new Map,ni=5e3,ri=4096,oi=async(e,t)=>{const n=Date.now(),r=Ue.get(t);if(r!==void 0&&r.expiresMs>n)return r.relayCount;r!==void 0&&Ue.delete(t);let s=0;try{const i=await _e(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const d=await i.json();typeof d.relayCount=="number"&&d.relayCount>0&&(s=Math.floor(d.relayCount))}}catch{s=0}return rn(Ue,ri),Ue.set(t,{expiresMs:n+ni,relayCount:s}),s},en=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},Ce=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),si=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],ai=(e,t)=>{for(const n of si){e.delete(n);const r=t[n];r!==void 0&&e.set(n,r)}},tn=(e,t)=>{const n=new Headers(e.headers),r=[...n.keys()];for(const s of r)s.startsWith("x-lunora-")&&n.delete(s);return ai(n,t),n},nn=async(e,t)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:Mo(t,n)},ii=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return Jr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return $e(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return $e(`queue:${e}`,!0);if(typeof n.connectionString=="string")return $e(`hyperdrive:${e}`,!0)},ci=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(Be))throw new c(`route "${t}" is under the reserved ${Be} prefix, which the framework owns. App routes registered there shadow the internal endpoint AND its admin gate — pick a path outside the prefix.`,{code:"MISCONFIGURED",status:500})},di=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new c("`x402Charge` requires `functions`: paid (.x402) procedures are read from the function registry, so without it every paid procedure would dispatch FREE. Build the worker with `defineApp()` (which supplies the registry) or pass `functions` explicitly.",{code:"MISCONFIGURED",status:500})},Pn=e=>{di(e);const t=Ea(e.trustInboundTraceContext),n=Ta(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",s=e.queryCoordinator??Zr({registry:eo(e.resolveTableSharding,r)}),i=Yr(e.resolveIdentity,e.identity),d=Fe(e.shardDO,e.jurisdiction),f=e.schedulerDO===void 0?void 0:Fe(e.schedulerDO,e.jurisdiction),h=e.voiceAgents===void 0?void 0:Object.fromEntries(Object.entries(e.voiceAgents).map(([o,a])=>[o,Fe(a,e.jurisdiction)]));let m=!1;const _=o=>{if(o===void 0||e.jurisdiction===void 0)return o;m||(m=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},S=async(o,a,l,u=e.shardRegion?.(a))=>_e(o,a,_(u)).fetch(l);let T;const P=()=>e.adminToken??T;let w;const g=o=>{const a=o??{};if(w??=en(o,e.shardDO),T!==void 0||e.adminToken!==void 0)return;const l=a.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(T=l)},b=new WeakSet,A=o=>wn(o,P())||b.has(o),I=async o=>{if(!(e.adminGate===void 0||b.has(o)))try{await De(e.adminGate(o,rt.get(o)))&&b.add(o)}catch{}},E=async(o,a,l,u)=>{const p=await qa(o,a,l,e.trustedClientIpHeader,u);return e.functions!==void 0&&(p.headers[sn]=on),p},L=async(o,a,l,u)=>Va(await E(o,a,l,u)),j=async(o,a)=>{const l=await E(o,a,e.resolveIdentity);if(b.has(o)&&l.headers.authorization===void 0){const u=P();u!==void 0&&(l.headers.authorization=`Bearer ${u}`)}return l};let C=!1,K=!1;const q=()=>{K||(K=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},V=o=>{if(!e.allowUnauthenticatedShardAccess){const a=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${o} access is default-denied: configure \`${a}\` 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})}C||(C=!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("")))},G=async(o,a,l=!1)=>{if(a.includes(Ze)||a.includes(et))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(!l)if(e.authorizeShard){if(!await De(e.authorizeShard({identity:o,shardKey:a})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else a!==r&&V("shard")},J=ta({defaultShard:r,forwardToShard:S,isAdmin:A,queryCoordinator:s,resolveForwardContext:j,shardDO:d,shardedTables:()=>(e.listSchemaTables?.()??[]).filter(o=>e.resolveTableSharding?.(o)?.mode.kind==="shardBy")}),se=async(o,a,l,u,p)=>{const y=u.shardKey??r;p==="trusted"?await G(null,y,!0):y!==r&&await G(p.identity,y);const O=await S(d,y,new Request(new URL(ho,o),{body:JSON.stringify({data:ye(l??null),stream:u.stream,topic:a}),headers:{"content-type":"application/json"},method:"POST"}));if(!O.ok)throw await xa(O,a)},W=async(o,a,l,u,p,y)=>{ke(o);const O=Co({forwardedIdentity:p,mutationId:u,traceparent:y});return S(d,l,Ce(o,a,O))},le=async(o,a,l,u,p)=>{const y=Ho(l.env,l.context?.exports,o,["create"]);if(y===void 0)throw new c(`${u} targets workflow "${o}", which is on neither ctx.exports nor env`,{code:"CRON_JOB_FAILED",status:500});if(oo(a))throw new c(`${u} params ${so}`,{code:"BAD_REQUEST",status:400});try{await y.create(p===void 0?{params:a}:{id:p,params:a})}catch(O){if(!co(O))throw O}},ae=async(o,a,l,u)=>{if(o.workflow){await le(o.workflow,o.args??{},{context:l,env:a},`cron job "${o.name}"`);return}if(o.functionPath===void 0)throw new c(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const p=await W(o.functionPath,o.args??{},o.shardKey??r,void 0,void 0,u);if(!p.ok)throw new c(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(p.status)}`,{code:"CRON_JOB_FAILED",status:500})},z=o=>{if(!A(o))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},ie=(o,a,l)=>{if(z(o),a===void 0)throw new c(l.message,{code:l.code,status:400});return a},xe=async(o,a,l,u,p,y)=>{const O=e.cronJobs?.[o];if(!O)return 0;for(const D of O)try{await ae(D,a,l,y)}catch(N){u.push(p(N))}return O.length},ce=async(o,a,l)=>{if(z(o),M(o,"POST","cron-jobs run"),!e.cronJobs)throw new c("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const u=await ne(o),p=typeof u.name=="string"?u.name:"";if(p==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const y=Object.values(e.cronJobs).flat().find(O=>O.name===p);if(!y)throw new c(`no cron job named "${p}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await ae(y,a,l),Response.json({name:p,ran:!0},{status:200})},ct=async o=>{const a=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!a||!f||typeof o.id!="string")return;const l=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await _e(f,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:a}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},kn=async(o,a,l)=>{M(o,"POST","Scheduler dispatch");const u=await un(o),p=a??{},y=typeof p.LUNORA_SCHEDULER_SECRET=="string"?p.LUNORA_SCHEDULER_SECRET:void 0,O=e.adminToken??(typeof p.LUNORA_ADMIN_TOKEN=="string"?p.LUNORA_ADMIN_TOKEN:void 0);if(!await Uo(o,u,{adminToken:O,schedulerSecret:y}))throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let N;try{N=JSON.parse(u)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const R=N??{},v=R.args??{},k=typeof R.id=="string"&&R.id.length>0?R.id:void 0;if(typeof R.workflow=="string"&&R.workflow.length>0)return await le(R.workflow,v,{context:l,env:a},"scheduled workflow",k),await ct(R),Response.json({ok:!0},{status:200});if(typeof R.functionPath!="string"||R.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const H=typeof R.shardKey=="string"&&R.shardKey.length>0?R.shardKey:r,$=Bo(o),x=await W(R.functionPath,v,H,k,$,o.headers.get("traceparent")??void 0);return await ct(R),x},Dn=Go({assertAdmin:z,getReader:()=>e.authAuditReader}),Nn=Qo({assertAdmin:z,getMove:()=>e.authJurisdictionMove}),Un=async(o,a)=>{z(o);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:ye({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const u=a?.kind,p=a?.userId,y=a?.limit,O=u==="fcm"||u==="web-push"?u:void 0,D=typeof p=="string"&&p!==""?p:void 0,N=typeof y=="number"&&Number.isFinite(y)?Math.trunc(y):0,R=N>0?Math.min(N,1e3):1e3,k=(await l.list({kind:O,limit:R,userId:D})).filter(H=>O!==void 0&&H.kind!==O?!1:D===void 0||(H.userId??null)===D).map(({keys:H,token:$,...x})=>x);return Response.json({result:ye({subscriptions:k})},{headers:{"content-type":"application/json"},status:200})},Cn=async(o,a)=>{if(!a.fanOut&&!(a.functionPath!==Dt&&a.functionPath!==qt&&a.functionPath!==tt&&a.functionPath!==bn))return await I(o),a.functionPath===Dt?Dn(o,a.args??{}):a.functionPath===qt?Un(o,a.args):Nn(o,a.functionPath,a.args??{})},Bn=ws({applyGlobals:e.applyGlobals,assertAdmin:z,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:r,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:s,resolveForwardContext:j,shardDO:d,prepareExportRows:async(o,a)=>_n(e,s,o,a,d),streamingImport:(o,a)=>Rs(o,e,s,a,d),syncGlobals:e.syncGlobals}),He=(o,a)=>{const l=o.searchParams.get(a);return l===null||l===""?void 0:l},Le=o=>{const a=new URL(o.url),l=a.searchParams.get("limit"),u=a.searchParams.get("offset"),p=l===null?void 0:Number.parseInt(l,10),y=u===null?void 0:Number.parseInt(u,10);return{limit:p!==void 0&&Number.isFinite(p)&&p>=0?p:void 0,offset:y!==void 0&&Number.isFinite(y)&&y>=0?y:void 0}},dt=()=>{if(f===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return f},xn=ya({checkWsAdmin:async o=>A(o)||nn(o,P()),requireSchedulerNamespace:dt,resolveSchedulerStub:o=>(z(o),_e(dt(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Hn=Ua({assertAdmin:z,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Ln=Mr({assertAdmin:z,parsePaging:Le,queryParameter:He,readBodyBytes:Ur,requireAdminOption:ie,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),jn=ss({options:e,readJsonBody:ne,requireAdminOption:ie}),Mn=va({readJsonBody:ne,requireAdminOption:ie,vectorIntrospector:e.vectorIntrospector}),$n=Ls({kvIntrospector:e.kvIntrospector,readJsonBody:ne,requireAdminOption:ie}),Fn=qr({logArchive:e.logArchive,readJsonBody:ne,requireAdminOption:ie}),Kn=Bs({assertAdmin:z,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,architecture:e.architecture,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Le,queryParameter:He,requireAdminOption:ie}),Gn=o=>{const a=[],l=d??o?.SHARD;if(l!==void 0&&a.push(Vr("durable-object:default",l,r)),e.health?.disableBindingProbes!==!0)for(const[u,p]of Object.entries(o??{})){const y=ii(u,p);y!==void 0&&a.push(y)}for(const u of e.health?.probes??[])a.push(u);return a},Qn=zr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:A,resolveProbes:Gn}),Wn=o=>{const a=R=>"args"in R?{...R,args:Xe(R.args)}:R,l=e.schedulerInstanceName??"default",u=()=>_e(o,l),p=async(R,v)=>{const k=await u().fetch(new Request(`https://scheduler.internal${R}`,v));if(!k.ok)throw new c(`ctx.scheduler: SchedulerDO ${R} failed (${String(k.status)}): ${await k.text()}`,{code:"INTERNAL",status:500});return await k.json()},y=async(R,v)=>await p(R,{body:JSON.stringify(v),headers:{"content-type":"application/json"},method:"POST"}),O=R=>{const v=R;if(v==null)throw new c("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof v.binding=="string"&&v.binding.length>0)return{workflow:v.binding};if(typeof v.__lunoraRef=="string")return{functionPath:v.__lunoraRef};throw new c("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},D=async()=>(await ao(async v=>p(v===void 0?"/list":`/list?cursor=${encodeURIComponent(v)}`,{method:"GET"}))).map(v=>a(v)),N=async(R,v,k={})=>{const H=O(v),{id:$}=await y("/schedule",{args:yr("ctx.scheduler",String(H.functionPath??H.workflow),k),scheduledFor:Math.ceil(R),...H});return $};return{cancel:async R=>await y("/cancel",{id:R}),get:async R=>{const v=await p(`/get?id=${encodeURIComponent(R)}`,{method:"GET"});return v.record===void 0?null:a(v.record)},list:D,runAfter:async(R,v,k)=>{if(!Number.isFinite(R)||R<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await N(Date.now()+R,v,k)},runAt:async(R,v,k)=>{if(!Number.isFinite(R))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await N(R,v,k)}}},zn=async(o,a,l)=>{const{claims:u,headers:p,identity:y,userId:O}=Ja(await E(o,a,i)),D=Ae(a,o,k=>l.waitUntil?.(k)),N=k=>async(H,$={})=>{const x=H.__lunoraRef;if(typeof x!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ke(x),k!==r&&await G(y,k);const X=await ve(o,x,ye($),k,{...p,"x-lunora-system":"1"},D),Z=await X.json();if(Z.error)throw new c(Z.error.message??"shard RPC failed",{code:Z.error.code??"INTERNAL",status:X.status});return Xe(Z.result)},R=N(r),v=async(k,H,$={})=>{k!==void 0&&k!==r&&await G(y,k);const x=new Headers;for(const[X,Z]of Object.entries($.headers??{}))X.toLowerCase().startsWith("x-lunora-")||x.set(X,Z);for(const[X,Z]of Object.entries(p))x.set(X,Z);return S(d,k??r,new Request(new URL(H,o.url),{headers:x,method:$.method??"GET",...$.body===void 0?{}:{body:$.body}}))};return{auth:{getIdentity:()=>Promise.resolve(u),userId:O},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),fetchShard:v,forShard:k=>{const H=N(k);return{runAction:H,runMutation:H,runQuery:H}},live:e.liveStreams===!1?Qt():{publish:(k,H,$)=>se(o.url,k,H,$,{identity:y})},runAction:R,runMutation:R,runQuery:R,...f===void 0?{}:{scheduler:Wn(f)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:ro(e.storage(a,new URL(o.url).origin))}}},Vn=async(o,a,l)=>{if(!e.httpRouter)return;const u=await zn(o,a,l);try{return await e.httpRouter.fetch(o,{...a,__lunoraCtx:u},l)}catch(p){return console.error("[lunora] httpRouter (SSR) handler threw:",p),new Response("Internal Server Error",{status:500})}},Jn=async(o,a,l)=>{if(o.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const u=Tt(o,de);if(u)return u;const p=l.searchParams.get("shard")??r,{headers:y,identity:O}=await E(o,a,i),D=A(o)||await nn(o,P());await G(O,p,D);const N=tn(o,y),R=en(a,e.shardDO);if(R!==void 0){N.set("x-lunora-shard-binding",R);const v=await oi(d,p);if(v>0){const k=Eo(p,Math.floor(Math.random()*v));return S(d,k,new Request(o,{headers:N}),It(o))}}return S(d,p,new Request(o,{headers:N}))},Yn=async(o,a,l)=>{if(h===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 u=Tt(o,de);if(u)return u;let p;try{p=decodeURIComponent(l.pathname.slice(Vt.length))}catch{return new Response("Unknown voice agent",{status:404})}const y=Object.hasOwn(h,p)?h[p]:void 0;if(y===void 0)return new Response("Unknown voice agent",{status:404});const O=l.searchParams.get("threadKey");if(O===null||O.length===0)return new Response("Missing threadKey",{status:400});const{headers:D,identity:N}=await E(o,a,i);if(e.authorizeShard){if(!await De(e.authorizeShard({identity:N,shardKey:O})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else V("shard");const R=tn(o,D);return S(y,O,new Request(o,{headers:R}))},qn=async(o,a,l)=>{if(e.authorizeFanOut){if(!await De(e.authorizeFanOut(l,o.table,a)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(a.startsWith("__lunora_relation__:"))throw new c("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});V("fan-out")},Oe=async(o,a)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await qn(o.fanOut,o.functionPath,a);return}await G(a,o.shardKey??r)}},Xn=(o,a,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){q();return}if(e.functions[a]?.kind!=="query"||l.includes(et)||l.includes(Ze))return;const u=It(o);return u===void 0?void 0:{name:So(l,u),region:u}},Zn=async(o,a,l,u,p)=>{const y=Xn(o,a,u);if(y!==void 0){const O={...p,"x-lunora-replica-read":"1",...w===void 0?{}:{"x-lunora-shard-binding":w}},D=To(o.headers.get("x-lunora-min-seq"));D!==void 0&&(O["x-lunora-min-seq"]=String(D));const N=await S(d,y.name,Ce(a,l,O),y.region);if(N.status!==421)return N}return S(d,u,Ce(a,l,p))},ve=async(o,a,l,u,p,y)=>{const O=Date.now(),{observability:D,sampling:N}=e,R=Ye(o),{decision:v,ignoredUpstream:k,trace:H}=$t(o,{...R.rayId===void 0?{}:{rayId:R.rayId},...N===void 0?{}:{sampling:N},trustInbound:t(o)});k&&n(o);const $={...p,[_t]:v.keepErrors?"1":"0",[At]:"1"};Ft(H,$);try{const x=await Zn(o,a,l,u,$),X=vt(x.headers.get(Ot));ue(D,{...R,...zt(H),durationMs:Date.now()-O,functionPath:a,ok:x.ok,shardKey:u,...x.ok?{}:{error:{...X,code:X?.code??"SHARD_ERROR",message:X?.message??`shard returned ${String(x.status)}`,status:x.status}}},y,void 0,{isTraced:H.sampled,keepErrors:v.keepErrors});const Z=new Response(x.body,{headers:x.headers,status:x.status,statusText:x.statusText});return Z.headers.set("x-lunora-shard-key",u),Z.headers.delete(Ot),Z}catch(x){throw ue(D,{...R,...zt(H),...Ne(a,Date.now()-O,x,{shardKey:u})},y,void 0,{isTraced:H.sampled,keepErrors:v.keepErrors}),x}},er=o=>{if(o.fanOut&&o.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});o.fanOut||ke(o.functionPath)},tr=async(o,a,l)=>{M(o,"POST","RPC");const u=await ti(o);ei(a,u),er(u);const p=await Cn(o,u);if(p!==void 0)return p;const{headers:y,identity:O}=await L(o,a,i);Jt(o,O),await Oe(u,O);const D=qe(u,e);{const N=Date.now(),{observability:R}=e,v=Ye(o),k=Ae(a,o,l&&(x=>l.waitUntil?.(x)));if(u.fanOut)try{const x=await s.fanOut(d,{args:u.args??{},fanOut:u.fanOut,functionPath:u.functionPath,headers:y});return ue(R,{durationMs:Date.now()-N,fanOut:{failed:x.failed,shards:x.ok+x.failed,table:u.fanOut.table},functionPath:u.functionPath,...v,ok:!0},k),Response.json(x,{headers:{"content-type":"application/json"},status:200})}catch(x){throw ue(R,{...Ne(u.functionPath,Date.now()-N,x,{fanOut:{table:u.fanOut.table}}),...v},k),x}const H=u.shardKey??r,$=()=>ve(o,u.functionPath,u.args??{},H,y,k);return D&&e.x402Charge?e.x402Charge(o,{functionPath:u.functionPath,price:D.price},$,Je(l)):$()}},nr=async(o,a,l)=>{M(o,"POST","RPC batch");const u=await ne(o),{calls:p}=u;if(!Array.isArray(p))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:y,identity:O}=await L(o,a,i);Jt(o,O);const D=is(p,r);for(const F of D.values())for(const Q of F)if(e.functions?.[Q.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${Q.functionPath}" cannot be called in a batch; dispatch it individually over ${Wt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...D.entries()].flatMap(([F,Q])=>Q.map(ee=>Oe({args:ee.args,functionPath:ee.functionPath,shardKey:F},O))));const{observability:N,sampling:R}=e,v=Ae(a,o,l&&(F=>l.waitUntil?.(F))),k=Ye(o),{decision:H,ignoredUpstream:$,trace:x}=$t(o,{...k.rayId===void 0?{}:{rayId:k.rayId},...R===void 0?{}:{sampling:R},trustInbound:t(o)});$&&n(o);const X={isTraced:x.sampled,keepErrors:H.keepErrors},Z=F=>{const Q={...y,"content-type":"application/json",[_t]:H.keepErrors?"1":"0",[At]:"1"};return Ft({...x,spanId:F},Q),Q},je=F=>({parentSpanId:F,spanId:be(8),traceFlags:x.traceFlags,traceId:x.traceId}),Pe=[],Me=[],ft=(F,Q,ee,he)=>({body:{error:{code:ee,message:he}},id:F.id,status:Q}),pt=(F,Q,ee,he,we)=>{for(const te of F)ue(N,we(te),v,void 0,X),Pe.push(ft(te,Q,ee,he))},pr=(F,Q,ee,he,we,te)=>{for(const Re of F){const Ee=we.get(Re.id),fe=Ee?.status??te,pe=fe<400,Se=pe?void 0:vt(Ee?.errorDetail);ue(N,{durationMs:he,functionPath:Re.functionPath,...k,...je(ee),ok:pe,shardKey:Q,...pe?{}:{error:{...Se,code:Se?.code??"SHARD_ERROR",message:Se?.message??`batched call returned ${String(fe)}`,status:fe}}},v,void 0,X)}};await Promise.all([...D.entries()].map(async([F,Q])=>{const ee=be(8),he=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:Q}),headers:new Headers(Z(ee)),method:"POST"}),we=Date.now();let te;try{te=await S(d,F,he)}catch(Y){const Te=Date.now()-we,{body:gt}=gr(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});pt(Q,502,gt.code,gt.message,mr=>({...Ne(mr.functionPath,Te,Y,{shardKey:F}),...k,...je(ee)}));return}const Re=Date.now()-we,Ee=te.headers.get("x-d1-bookmark");Ee&&Me.push(Ee);let fe;try{fe=await te.json()}catch{const Y=`shard batch returned a non-JSON response (${String(te.status)})`;pt(Q,te.status,"SHARD_ERROR",Y,Te=>({durationMs:Re,error:{code:"SHARD_ERROR",message:Y,status:te.status},functionPath:Te.functionPath,...k,...je(ee),ok:!1,shardKey:F}));return}const pe=Array.isArray(fe.results)?fe.results:[],Se=new Set(pe.map(Y=>Y.id));pr(Q,F,ee,Re,new Map(pe.map(Y=>[Y.id,Y])),te.status),Pe.push(...pe.map(({errorDetail:Y,...Te})=>Te));for(const Y of Q)Se.has(Y.id)||Pe.push(ft(Y,te.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const mt={"content-type":"application/json"},[wt]=Me;return Me.length===1&&wt!==void 0&&(mt["x-d1-bookmark"]=wt),Response.json({results:Pe},{headers:mt,status:200})},rr=async(o,a,l,u={},p={})=>{try{const y=l.__lunoraRef;if(typeof y!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ke(y);const{headers:O,identity:D}=await L(o,a,i,p.context),N={args:u,functionPath:y,shardKey:p.shardKey};await Oe(N,D);const R=p.shardKey??r,v=Ae(a,o,p.waitUntil),k=()=>ve(o,y,u,R,O,v),H=qe(N,e);return H&&e.x402Charge?await e.x402Charge(o,{functionPath:y,price:H.price},k,Je(p.waitUntil?{waitUntil:p.waitUntil}:p.context)):await k()}catch(y){return Rt(y)}},ut=async(o,a,l)=>{const{observability:u}=e,p=Date.now(),y=be(16),O=be(8),D=Zt(a),N=an(y,O,!0);try{const R=await l(N);return ue(u,{durationMs:Date.now()-p,functionPath:o,ok:!0,spanId:O,traceId:y},D),R}catch(R){throw ue(u,{...Ne(o,Date.now()-p,R,{}),spanId:O,traceId:y},D),R}finally{bt(u,D)}},lt=async(o,a,l,u)=>{g(a);const p=[],y=v=>v instanceof Error?v:new Error(String(v)),O=e.crons?.[o.cron];if(O)try{await O(o,a,l)}catch(v){p.push(y(v))}const D=await xe(o.cron,a,l,p,y,u),N=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron;if(N)try{await ts(e,s,d,P(),o)}catch(v){p.push(y(v))}if(!O&&D===0&&!N){const v=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${o.cron}") fired but no cron handler is registered for that expression. Registered: ${v.length===0?"(none)":v.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[R]=p;if(p.length===1&&R)throw R;if(p.length>1)throw new AggregateError(p,`scheduled("${o.cron}") had ${String(p.length)} failure(s)`)},or=_a({assertAdmin:z,dispatchScheduled:lt,queueHandler:e.queueHandler}),sr=async(o,a)=>{try{const l=o??{},u=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!u||u.length===0)return;await S(d,r,Ce(Qa,{outcome:a},{authorization:`Bearer ${u}`,"content-type":"application/json"}))}catch{}},ar=async(o,a,l,u)=>{if(!e.authHandler)return;const p=e.authBasePath??Yt,y=Xt(l.pathname,p)?Cr(o):void 0;let O;try{O=await e.authHandler(y?.request??o)}catch(D){throw y?.overflowed()?new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413}):D}if(y?.overflowed())throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});if(O)return za(l.pathname,p)&&u.waitUntil?.(sr(a,O.status>=400?"fail":"ok")),O},ir=async({args:o,env:a,functionPath:l,request:u,shardKey:p,waitUntil:y})=>{dn(o,"REST");const O={functionPath:l,...p===void 0?{}:{shardKey:p}},{headers:D,identity:N}=await L(u,a,i);await Oe(O,N);const R=p??r,v=Ae(a,u,y),k=()=>ve(u,l,o,R,D,v),H=qe(O,e);return H&&e.x402Charge?e.x402Charge(u,{functionPath:l,price:H.price},k,Je({waitUntil:y})):k()},cr=Nr({functions:e.functions??{},invoke:ir,readJsonBody:ne,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ie=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0;ci(Ie);const dr={[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"}}),[La]:(o,a,l)=>Jn(o,a,l),[Wt]:(o,a,l,u)=>tr(o,a,u),[Ha]:(o,a,l,u)=>nr(o,a,u),[ko]:(o,a,l,u)=>kn(o,a,u),[ja]:(o,a,l,u)=>ce(o,a,u),[Ma]:async o=>{M(o,"POST","ws-token"),z(o);const a=P();if(a===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await jo(a);return Response.json(l,{headers:{"cache-control":"no-store"}})},...J,...Bn,...xn,...Hn,...Ln,...jn,...Mn,...$n,...Fn,...Kn,...Qn,...cr,...Ko({assertAdmin:z,getAuthAdmin:()=>e.authAdmin,parsePaging:Le,queryParameter:He,readJsonBody:ne})};let de=St(e.security),ht=!1;const ur=o=>{ht||(ht=!0,de=St(e.security,o??{}))},lr=async(o,a)=>{Ga(a)&&await I(o)},hr=(o,a)=>{if(!(a.pathname.startsWith(Be)||e.authHandler!==void 0&&Xt(a.pathname,e.authBasePath??Yt))||o.method!=="POST"&&o.method!=="PUT")return;const u=Number(o.headers.get("content-length")??""),p=Ca[a.pathname]??cn;if(Number.isFinite(u)&&u>p)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},fr=async(o,a,l)=>{rt.set(o,l);const u=new URL(o.url);hr(o,u);const p=await ar(o,a,u,l);if(p)return p;if(Ie){const R=`${o.method} ${u.pathname}`,v=Ie[R]??Ie[u.pathname];if(v)return v(o,a,l)}const y=or[u.pathname];if(y)return y(o,a,l);const O=dr[u.pathname];if(O)return await lr(o,u.pathname),O(o,a,u,l);if(e.voiceAgents!==void 0&&u.pathname.startsWith(Vt))return Yn(o,a,u);if(u.pathname.startsWith(Be))return new Response("Not found",{status:404});const D=await Vn(o,a,l);if(D&&D.status!==404)return D;const N=await e.authDiscoveryHandler?.(o);return N?(await D?.body?.cancel(),N):D??new Response("Not found",{status:404})};return{async fetch(o,a,l){e.passThroughOnException&&l.passThroughOnException?.(),ur(a),g(a);const u=to(o,de);if(u)return u;const p=no(o,de);if(p)return Ke(p,o,de);try{const y=await fr(o,a,l);return Ke(y,o,de)}catch(y){return Ke(Rt(y),o,de)}finally{bt(e.observability,Zt(l))}},async queue(o,a,l){await ut(`queue:${Ya(o)}`,l,async u=>{const p=e.liveStreams===!1?Qt():{publish:(y,O,D)=>se(Ba,y,O,D,"trusted")};await e.queue?.(o,a,l,{traceparent:u},p,e.queueFetchImpl)})},async scheduled(o,a,l){await ut(`cron:${o.cron}`,l,async u=>{await lt(o,a,l,u)})},serverQuery:rr}},ui=e=>Pn(e),li=e=>typeof e=="function"?{fetch:e}:e,hi=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,fi=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},Hi=(e,t)=>{const n=li(e),{email:r,queue:s,scheduled:i}=fi(e),d=h=>{const _={...ui({...h,httpRouter:n})};return i!==void 0&&!hi(h)&&(_.scheduled=async(S,T,P)=>{await i(S,T,P)}),s!==void 0&&h.queue===void 0&&(_.queue=async(S,T,P)=>{await s(S,T,P)}),r!==void 0&&(_.email=async(S,T,P)=>{await r(S,T,P)}),_};if(typeof t!="function")return d(t);const f=t;return{fetch:(h,m,_)=>d(f(m)).fetch(h,m,_),queue:(h,m,_)=>d(f(m)).queue?.(h,m,_)??Promise.resolve(),scheduled:(h,m,_)=>d(f(m)).scheduled(h,m,_),serverQuery:(h,m,_,S,T)=>d(f(m)).serverQuery(h,m,_,S,T),...r===void 0?{}:{email:(h,m,_)=>d(f(m)).email?.(h,m,_)??Promise.resolve()}}},pi=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new c("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},Li=(e={})=>(t,n,r)=>Pn(pi(e,n)).fetch(t,n,r??br),ji=e=>e;export{tt as COPY_AUTH_TO_JURISDICTION_OP,Dt as GET_AUTH_AUDIT_LOG_OP,br as NOOP_EXECUTION_CONTEXT,bn as PURGE_UNPINNED_AUTH_OP,Fi as composeIdentityResolvers,ui as composeWorker,Li as createLunoraHandler,Pn as createWorker,ji as defineRpcEnvelope,oi as probeRelayCount,pi as resolveLunoraOptions,Ki as routeIdentityResolvers,Hi as withFrameworkWorker};
@@ -1 +1 @@
1
- import{LunoraError as O}from"./LunoraError-DksAgIpa.mjs";const E=new Set(["0","disabled","false","no","off"]),y=new Set(["1","enabled","on","true","yes"]),d=e=>typeof e=="string"&&E.has(e.trim().toLowerCase()),S=e=>typeof e=="string"&&y.has(e.trim().toLowerCase()),L="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",A=e=>{const o=["base-uri 'none'","object-src 'none'"];return e==="DENY"?o.push("frame-ancestors 'none'"):e==="SAMEORIGIN"&&o.push("frame-ancestors 'self'"),o.join("; ")},b="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",u=["Authorization","Content-Type","Last-Event-ID","X-D1-Bookmark","X-Lunora-Client-Id","X-Lunora-Client-Seq","X-Lunora-Expect-Subject","X-Lunora-Min-Seq","X-Lunora-Mutation-Id","X-Lunora-Shard-Key"],f=["DELETE","GET","HEAD","PATCH","POST","PUT"],v=31536e3,C=new Set(["GET","HEAD","OPTIONS"]),R=e=>{if(e===!1)return;const o=e===void 0||e===!0?{}:e,s=o.maxAge??v,r=o.includeSubDomains??!0;return`max-age=${String(s)}${r?"; includeSubDomains":""}${o.preload?"; preload":""}`},D=(e,o)=>{if(e!==!1)return typeof e=="string"?{htmlValue:e,value:e}:{htmlValue:o,value:L}},_=e=>{if(e===!1)return{coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0};const o=e===void 0||e===!0?{}:e,s=o.frameOptions===!1?void 0:o.frameOptions??"SAMEORIGIN";return{coop:"same-origin",csp:D(o.csp,A(s)),enabled:!0,frameOptions:s,hsts:R(o.hsts),permissionsPolicy:o.permissionsPolicy===!1?void 0:o.permissionsPolicy??b,referrerPolicy:o.referrerPolicy===!1?void 0:o.referrerPolicy??"strict-origin-when-cross-origin"}},N=e=>{const o={allowCredentials:!1,allowedHeaders:u,allowedMethods:f,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return o;const s=e.allowCredentials??!1,r=e.allowedOrigins;let t,n;if(typeof r=="function"){const a=m=>r(m)===!0;t=a,n=a,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${s?" AND reflects matching origins with credentials (`allowCredentials: true`)":""} — ensure it matches ONLY trusted origins by exact equality; an over-broad predicate (e.g. \`() => true\`, or \`endsWith\`/\`includes\` checks) defeats the allowlist.`)}else{const a=r;if(a.includes("*")&&s)throw new O('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=i=>a.includes("*")||a.includes(i),n=i=>a.includes(i)}return{allowCredentials:s,allowedHeaders:[...new Set([...u,...e.allowedHeaders??[]])],allowedMethods:e.allowedMethods??f,enabled:!0,isAllowed:t,isExplicitlyAllowed:n,maxAge:e.maxAge??600}},H=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const o=e===void 0||e===!0?{}:e;return{allowLoopback:o.allowLoopback??!0,enabled:!0,trustedOrigins:o.trustedOrigins??[]}},I=e=>{const o=e?.LUNORA_ALLOWED_ORIGINS;if(typeof o!="string")return;const s=o.split(",").map(n=>n.trim()).filter(n=>n.length>0);return s.length===0?void 0:{allowCredentials:!s.includes("*")&&S(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:s}},j=(e,o)=>{const s=e?.headers??(d(o?.LUNORA_SECURITY_HEADERS)?!1:void 0),r=e?.csrf??(d(o?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??I(o);return{cors:N(t),csrf:H(r),headers:_(s)}},x=new Set(["127.0.0.1","::1","[::1]","localhost"]),p=e=>{try{return x.has(new URL(e).hostname)}catch{return!1}},c=e=>{if(e)try{return new URL(e).origin}catch{return}},w=(e,o,s)=>e===o||s.csrf.trustedOrigins.includes(e)||s.csrf.allowLoopback&&p(o)&&p(e)?!0:s.cors.enabled&&s.cors.isExplicitlyAllowed(e),h=(e,o,s)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:s,message:`${e} rejected: Origin ${o===void 0?"was missing":`"${o}"`} is not trusted (this worker serves "${s}"). Add it to \`security.csrf.trustedOrigins\` (or LUNORA_ALLOWED_ORIGINS) if it is yours. Behind a dev proxy this usually means the proxy rewrote the host: keep both ends on loopback, or list the dev-server origin.`,receivedOrigin:o}},{headers:{"content-type":"application/json"},status:403}),X=(e,o)=>{if(!o.csrf.enabled||C.has(e.method)||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"))??c(e.headers.get("referer"));if(!(r!==void 0&&w(r,s,o)))return h("cross-origin state-changing request",r,s)},F=(e,o)=>{if(!o.csrf.enabled||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"));if(!(r!==void 0&&w(r,s,o)))return h("cross-origin websocket upgrade",r,s)},P=["X-D1-Bookmark","X-Lunora-Edge-Cache","X-Lunora-Shard-Key"],g=(e,o)=>{const s=new Headers;return s.set("access-control-allow-origin",e),s.set("access-control-expose-headers",P.join(", ")),s.append("vary","Origin"),o.allowCredentials&&s.set("access-control-allow-credentials","true"),s},B=(e,o)=>{if(!o.cors.enabled||e.method!=="OPTIONS")return;const s=e.headers.get("origin");if(!s||!e.headers.get("access-control-request-method")||!o.cors.isAllowed(s))return;const r=g(s,o.cors),t=e.headers.get("access-control-request-headers");r.set("access-control-allow-methods",o.cors.allowedMethods.join(", "));let n;if(t===null)n=o.cors.allowedHeaders.join(", ");else{const a=new Set(o.cors.allowedHeaders.map(i=>i.toLowerCase()));n=t.split(",").map(i=>i.trim()).filter(i=>i.length>0&&a.has(i.toLowerCase())).join(", ")}return r.set("access-control-allow-headers",n),r.set("access-control-max-age",String(o.cors.maxAge)),new Response(null,{headers:r,status:204})},T=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),l=(e,o,s)=>{e.has(o)||e.set(o,s)},k=(e,o,s,r)=>{if(r.hsts!==void 0&&new URL(o.url).protocol==="https:"&&l(e,"strict-transport-security",r.hsts),l(e,"x-content-type-options","nosniff"),r.frameOptions!==void 0&&l(e,"x-frame-options",r.frameOptions),r.referrerPolicy!==void 0&&l(e,"referrer-policy",r.referrerPolicy),r.permissionsPolicy!==void 0&&l(e,"permissions-policy",r.permissionsPolicy),r.coop!==void 0&&l(e,"cross-origin-opener-policy",r.coop),r.csp!==void 0){const t=T(s)?r.csp.htmlValue:r.csp.value;t!==void 0&&l(e,"content-security-policy",t)}},U=(e,o,s)=>{const r=o.headers.get("origin");if(!(!r||!s.isAllowed(r)))for(const[t,n]of g(r,s).entries())t==="vary"?e.append("vary",n):l(e,t,n)},V=(e,o,s)=>{if(e.status===101||e.webSocket)return e;const r=new Headers(e.headers);return s.headers.enabled&&k(r,o,e,s.headers),s.cors.enabled&&U(r,o,s.cors),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})};export{V as decorateResponse,X as enforceOrigin,F as enforceWebSocketOrigin,B as handleCorsPreflight,j as resolveSecurity};
1
+ import{LunoraError as O}from"./LunoraError-DksAgIpa.mjs";const E=new Set(["0","disabled","false","no","off"]),y=new Set(["1","enabled","on","true","yes"]),d=e=>typeof e=="string"&&E.has(e.trim().toLowerCase()),S=e=>typeof e=="string"&&y.has(e.trim().toLowerCase()),L="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",A=e=>{const o=["base-uri 'none'","object-src 'none'"];return e==="DENY"?o.push("frame-ancestors 'none'"):e==="SAMEORIGIN"&&o.push("frame-ancestors 'self'"),o.join("; ")},b="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",u=["Authorization","Content-Type","Last-Event-ID","X-D1-Bookmark","X-Lunora-Client-Id","X-Lunora-Client-Seq","X-Lunora-Expect-Subject","X-Lunora-Min-Seq","X-Lunora-Mutation-Id","X-Lunora-Shard-Key"],f=["DELETE","GET","HEAD","PATCH","POST","PUT"],v=31536e3,C=new Set(["GET","HEAD","OPTIONS"]),R=e=>{if(e===!1)return;const o=e===void 0||e===!0?{}:e,s=o.maxAge??v,r=o.includeSubDomains??!0;return`max-age=${String(s)}${r?"; includeSubDomains":""}${o.preload?"; preload":""}`},D=(e,o)=>{if(e!==!1)return typeof e=="string"?{htmlValue:e,value:e}:{htmlValue:o,value:L}},_=e=>{if(e===!1)return{coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0};const o=e===void 0||e===!0?{}:e,s=o.frameOptions===!1?void 0:o.frameOptions??"SAMEORIGIN";return{coop:"same-origin",csp:D(o.csp,A(s)),enabled:!0,frameOptions:s,hsts:R(o.hsts),permissionsPolicy:o.permissionsPolicy===!1?void 0:o.permissionsPolicy??b,referrerPolicy:o.referrerPolicy===!1?void 0:o.referrerPolicy??"strict-origin-when-cross-origin"}},N=e=>{const o={allowCredentials:!1,allowedHeaders:u,allowedMethods:f,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return o;const s=e.allowCredentials??!1,r=e.allowedOrigins;let t,n;if(typeof r=="function"){const a=m=>r(m)===!0;t=a,n=a,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${s?" AND reflects matching origins with credentials (`allowCredentials: true`)":""} — ensure it matches ONLY trusted origins by exact equality; an over-broad predicate (e.g. \`() => true\`, or \`endsWith\`/\`includes\` checks) defeats the allowlist.`)}else{const a=r;if(a.includes("*")&&s)throw new O('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=i=>a.includes("*")||a.includes(i),n=i=>a.includes(i)}return{allowCredentials:s,allowedHeaders:[...new Set([...u,...e.allowedHeaders??[]])],allowedMethods:e.allowedMethods??f,enabled:!0,isAllowed:t,isExplicitlyAllowed:n,maxAge:e.maxAge??600}},H=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const o=e===void 0||e===!0?{}:e;return{allowLoopback:o.allowLoopback??!0,enabled:!0,trustedOrigins:o.trustedOrigins??[]}},I=e=>{const o=e?.LUNORA_ALLOWED_ORIGINS;if(typeof o!="string")return;const s=o.split(",").map(n=>n.trim()).filter(n=>n.length>0);return s.length===0?void 0:{allowCredentials:!s.includes("*")&&S(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:s}},X=(e,o)=>{const s=e?.headers??(d(o?.LUNORA_SECURITY_HEADERS)?!1:void 0),r=e?.csrf??(d(o?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??I(o);return{cors:N(t),csrf:H(r),headers:_(s)}},x=new Set(["127.0.0.1","::1","[::1]","localhost"]),p=e=>{try{return x.has(new URL(e).hostname)}catch{return!1}},c=e=>{if(e)try{return new URL(e).origin}catch{return}},w=(e,o,s)=>e===o||s.csrf.trustedOrigins.includes(e)||s.csrf.allowLoopback&&p(o)&&p(e)?!0:s.cors.enabled&&s.cors.isExplicitlyAllowed(e),h=(e,o,s)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:s,message:`${e} rejected: Origin ${o===void 0?"was missing":`"${o}"`} is not trusted (this worker serves "${s}"). Add it to \`security.csrf.trustedOrigins\` (or LUNORA_ALLOWED_ORIGINS) if it is yours. Behind a dev proxy this usually means the proxy rewrote the host: keep both ends on loopback, or list the dev-server origin.`,receivedOrigin:o}},{headers:{"content-type":"application/json"},status:403}),j=(e,o)=>{if(!o.csrf.enabled||C.has(e.method)||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"))??c(e.headers.get("referer"));if(!(r!==void 0&&w(r,s,o)))return h("cross-origin state-changing request",r,s)},F=(e,o)=>{if(!o.csrf.enabled||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"));if(!(r!==void 0&&w(r,s,o)))return h("cross-origin websocket upgrade",r,s)},P=["X-D1-Bookmark","X-Lunora-Edge-Cache","X-Lunora-Live-Connection","X-Lunora-Shard-Key"],g=(e,o)=>{const s=new Headers;return s.set("access-control-allow-origin",e),s.set("access-control-expose-headers",P.join(", ")),s.append("vary","Origin"),o.allowCredentials&&s.set("access-control-allow-credentials","true"),s},B=(e,o)=>{if(!o.cors.enabled||e.method!=="OPTIONS")return;const s=e.headers.get("origin");if(!s||!e.headers.get("access-control-request-method")||!o.cors.isAllowed(s))return;const r=g(s,o.cors),t=e.headers.get("access-control-request-headers");r.set("access-control-allow-methods",o.cors.allowedMethods.join(", "));let n;if(t===null)n=o.cors.allowedHeaders.join(", ");else{const a=new Set(o.cors.allowedHeaders.map(i=>i.toLowerCase()));n=t.split(",").map(i=>i.trim()).filter(i=>i.length>0&&a.has(i.toLowerCase())).join(", ")}return r.set("access-control-allow-headers",n),r.set("access-control-max-age",String(o.cors.maxAge)),new Response(null,{headers:r,status:204})},T=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),l=(e,o,s)=>{e.has(o)||e.set(o,s)},k=(e,o,s,r)=>{if(r.hsts!==void 0&&new URL(o.url).protocol==="https:"&&l(e,"strict-transport-security",r.hsts),l(e,"x-content-type-options","nosniff"),r.frameOptions!==void 0&&l(e,"x-frame-options",r.frameOptions),r.referrerPolicy!==void 0&&l(e,"referrer-policy",r.referrerPolicy),r.permissionsPolicy!==void 0&&l(e,"permissions-policy",r.permissionsPolicy),r.coop!==void 0&&l(e,"cross-origin-opener-policy",r.coop),r.csp!==void 0){const t=T(s)?r.csp.htmlValue:r.csp.value;t!==void 0&&l(e,"content-security-policy",t)}},U=(e,o,s)=>{const r=o.headers.get("origin");if(!(!r||!s.isAllowed(r)))for(const[t,n]of g(r,s).entries())t==="vary"?e.append("vary",n):l(e,t,n)},V=(e,o,s)=>{if(e.status===101||e.webSocket)return e;const r=new Headers(e.headers);return s.headers.enabled&&k(r,o,e,s.headers),s.cors.enabled&&U(r,o,s.cors),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})};export{V as decorateResponse,j as enforceOrigin,F as enforceWebSocketOrigin,B as handleCorsPreflight,X as resolveSecurity};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.214",
3
+ "version": "1.0.0-alpha.216",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,10 +46,10 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/bindings": "1.0.0-alpha.119",
49
+ "@lunora/bindings": "1.0.0-alpha.121",
50
50
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
51
- "@lunora/observability": "1.0.0-alpha.148",
52
- "@lunora/platform": "1.0.0-alpha.67",
51
+ "@lunora/observability": "1.0.0-alpha.150",
52
+ "@lunora/platform": "1.0.0-alpha.68",
53
53
  "@lunora/wire": "1.0.0-alpha.1"
54
54
  },
55
55
  "peerDependencies": {
@@ -1,6 +0,0 @@
1
- import{isLunoraError as pr,toErrorBody as mr}from"@lunora/errors";import{encodeWire as Te,decodeWire as Xe,encodeArgsOrThrow as wr}from"@lunora/wire";import{e as tn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as gr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{i as yr,e as br,a as _r,E as gt,d as Rr}from"./identity-header-pR617HTs.mjs";import{O as nn,a as rn}from"./origin-paywall-B6eOO67m.mjs";import{o as we,b as on,p as Er,m as Ar,d as Tr,a as Sr,r as Or}from"./otlp-resource-BwFJnvwB.mjs";import{r as vr,f as yt,a as ie,S as bt}from"./observability-DgurIZIR.mjs";import{t as Ir,f as kr}from"./base64-Bl1_r2k1.mjs";import{d as ee,e as ne,M as an,b as Pr,f as Dr,g as sn,w as Nr,h as cn,t as Ur}from"./rest-routes-DQkyqlym.mjs";import{LunoraError as c,toErrorResponse as _t}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as ot,BACKUP_KEY_PREFIX as at,isBackupManifestKey as Cr,backupObjectKeyOfManifest as dn,backupObjectKey as Br,backupManifestKey as xr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Hr,buildStorageAdminRoutes as Lr,STORAGE_UPLOAD_MAX_BODY_BYTES as jr,STORAGE_PATH as Mr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as $r,e as Kr,f as Rt,g as Fr,h as Gr}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as Qr,durableObjectProbe as Wr,d1Probe as zr,presenceProbe as $e}from"./HEALTH_PATH-CAX2UeFy.mjs";import{wrapResolverWithContract as Vr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Hi,routeIdentityResolvers as Li}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Jr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{pruneShardRegistry as Yr,createQueryCoordinator as qr,createDefaultShardRegistry as Xr}from"./createQueryCoordinator-es4jrL6Q.mjs";import{resolveShard as ge,applyJurisdiction as Ke}from"./applyJurisdiction-D4vryLhj.mjs";import{resolveSecurity as Et,handleCorsPreflight as Zr,enforceOrigin as eo,decorateResponse as Fe,enforceWebSocketOrigin as At}from"./decorateResponse-BxMmYMux.mjs";const to=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},un="__lunoraBranch",no=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,un),ro=`may not contain the reserved workflow branch-marker key ("${un}")`,oo=async e=>{const t=[];let n;for(;;){const r=await e(n);if(t.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return t;if(r.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=r.cursor}},ao=/already[\s_-]?exists/iu,so=e=>ao.test(e instanceof Error?e.message:String(e)),Tt="x-lunora-want-error-detail",St="x-lunora-error-detail",io=8192,co=e=>{if(!(e instanceof Error))return{message:String(e),name:typeof e};const{code:t}=e;return{...typeof t=="string"?{code:t}:{},message:e.message,name:e.name,...e.stack===void 0?{}:{stack:e.stack.slice(0,io)}}},Ot=e=>{if(e!=null)try{const t=JSON.parse(decodeURIComponent(e));return typeof t?.message=="string"&&typeof t.name=="string"?t:void 0}catch{return}},uo="cf-ray",lo="x-lunora-ray-id",ho=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,fo=e=>e==null?void 0:ho.exec(e.trim())?.[1]?.toLowerCase(),po=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(po);const mo=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),wo=-100,go=15,yo=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&mo.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>go?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<wo?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},vt=e=>{const t=e.cf;return t===void 0?void 0:yo(t)},Ze="::relay::",bo=(e,t)=>`${e}${Ze}${String(t)}`,et="::replica::",_o=(e,t)=>`${e}${et}${t}`,Ro=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},ln=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,d=a<t.length?t.charCodeAt(a):0;r|=i^d}return r===0},Eo=(e,t,n,r)=>{const a=e.get(t);if(a!==void 0)return a;tn(e,r);const i=n().catch(d=>{throw e.get(t)===i&&e.delete(t),d});return e.set(t,i),i},st=new TextEncoder,Ao=Array.from({length:32},(e,t)=>t);new RegExp(`[${Ao.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const To=64,So=new Map,hn=async e=>Eo(So,e,async()=>crypto.subtle.importKey("raw",st.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),To),fn=async(e,t)=>{const n=await hn(e),r=await crypto.subtle.sign("HMAC",n,st.encode(t));return Ir(new Uint8Array(r))},Oo=async(e,t,n)=>{const r=await hn(e);return crypto.subtle.verify("HMAC",r,n,st.encode(t))},vo="/_lunora/scheduler/dispatch",Io="__lunora_relation__:",ko=e=>e.startsWith(Io),pn=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...a]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:ln(t,a.join(" ").trim())},Po=async(e,t,n)=>{const r=e.headers.get("x-lunora-scheduler-signature"),{schedulerSecret:a}=n;return r!==null&&r.length>0&&a!==void 0&&a.length>0?ln(await fn(a,t),r):pn(e,n.adminToken)},Do=({forwardedIdentity:e,mutationId:t,traceparent:n})=>{const r={"content-type":"application/json",[rn]:nn,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(r["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(r["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(r["x-lunora-mutation-id"]=t),n!==void 0&&n.length>0&&(r.traceparent=n),r},No=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}}},Uo=(e,t,n)=>e?.[n]??t?.[n],Co=(e,t,n,r)=>{const a=Uo(e,t,n);if(!(typeof a!="object"||a===null))return r.every(i=>typeof a[i]=="function")?a:void 0},mn="v1",Bo=6e4,xo=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Bo),r=`${mn}.${String(n)}`,a=await fn(e,r);return{expiresAtMs:n,token:`${r}.${a}`}},Ho=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const r=t.split(".");if(r.length!==3)return!1;const[a,i,d]=r;if(a!==mn||d.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let h;try{h=kr(d)}catch{return!1}return Oo(e,`${a}.${i}`,h)},N="/_lunora/admin/auth",Lo={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},C=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},he=(e,t)=>{const n=e(t);if(n===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},wn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ge=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},It=e=>{const t=wn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},kt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[r,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[r]=a);return n},jo={[`${N}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${N}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${N}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${N}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${N}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${N}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${N}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${N}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${N}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${N}/sign-up-invitations/create`]:{build:({body:e})=>({email:C(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:te(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${N}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:C(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${N}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${N}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${N}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${N}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${N}/users/create`]:{build:({body:e})=>({data:Ge(e,"data"),email:C(e,"email"),name:C(e,"name"),password:te(e,"password"),role:wn(e.role)}),http:"POST",method:"createUser"},[`${N}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:C(e,"userId")}},http:"POST",method:"updateUser"},[`${N}/users/role`]:{build:({body:e})=>({role:It(e),userId:C(e,"userId")}),http:"POST",method:"setRole"},[`${N}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:C(e,"userId")}),http:"POST",method:"banUser"},[`${N}/users/unban`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"unbanUser"},[`${N}/users/password`]:{build:({body:e})=>({newPassword:C(e,"newPassword"),userId:C(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${N}/users/remove`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${N}/users/impersonate`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"impersonateUser"},[`${N}/sessions/revoke`]:{build:({body:e})=>({sessionId:C(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${N}/sessions/revoke-all`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${N}/accounts/unlink`]:{build:({body:e})=>({accountId:C(e,"accountId"),userId:C(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${N}/two-factor/disable`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${N}/passkeys/delete`]:{build:({body:e})=>({passkeyId:C(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${N}/organizations/members/remove`]:{build:({body:e})=>({memberId:C(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${N}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:C(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${N}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ge(e,"metadata"),name:C(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${N}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ge(e,"metadata"),name:te(e,"name"),organizationId:C(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${N}/organizations/remove`]:{build:({body:e})=>({organizationId:C(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${N}/organizations/members/add`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),role:te(e,"role"),userId:C(e,"userId")}),http:"POST",method:"addMember"},[`${N}/organizations/members/invite`]:{build:({body:e})=>({email:C(e,"email"),inviterId:te(e,"inviterId"),organizationId:C(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${N}/organizations/members/role`]:{build:({body:e})=>({memberId:C(e,"memberId"),role:It(e)}),http:"POST",method:"updateMemberRole"},[`${N}/organizations/teams/create`]:{build:({body:e})=>({name:C(e,"name"),organizationId:C(e,"organizationId")}),http:"POST",method:"createTeam"},[`${N}/organizations/teams/update`]:{build:({body:e})=>({name:C(e,"name"),teamId:C(e,"teamId")}),http:"POST",method:"updateTeam"},[`${N}/organizations/teams/remove`]:{build:({body:e})=>({teamId:C(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${N}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:C(e,"teamId"),userId:C(e,"userId")}),http:"POST",method:"addTeamMember"},[`${N}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:C(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${N}/organizations/roles/create`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),permission:kt(e),role:C(e,"role")}),http:"POST",method:"createOrgRole"},[`${N}/organizations/roles/update`]:{build:({body:e})=>({permission:kt(e),roleId:C(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${N}/organizations/roles/remove`]:{build:({body:e})=>({roleId:C(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Mo=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof c)throw i;const d=i,f=typeof d.code=="string"?d.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:f,status:Lo[f]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const d=e.getAuthAdmin();if(d===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=d[i.method];if(f===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const h=new URL(a.url),m={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:S=>e.queryParameter(h,S)},b=i.build(m),T=await t(()=>f(b));return Response.json(i.returns==="void"?{ok:!0}:T,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[a,i]of Object.entries(jo))r[a]=d=>n(d,i);return r},Pt="__lunora_admin__:getAuthAuditLog",Dt=e=>typeof e=="string"&&e!==""?e:void 0,Nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,$o=e=>async(n,r)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=Dt(r.actorId),d=Dt(r.event),f=Nt(r.sinceSeq),h=Nt(r.limit),m={...i===void 0?{}:{actorId:i},...d===void 0?{}:{event:d},...f===void 0?{}:{sinceSeq:f},...h===void 0?{}:{limit:h}};let b;try{b=await a.read(m)}catch(S){throw S instanceof c?S:(console.error("[lunora] auth audit read failed:",S),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const T={entries:b};return Response.json({result:Te(T)},{headers:{"content-type":"application/json"},status:200})},tt="__lunora_admin__:copyAuthToJurisdiction",gn="__lunora_admin__:purgeUnpinnedAuth",Ko=e=>async(t,n,r)=>{if(n!==tt&&n!==gn)return;e.assertAdmin(t);const a=e.getMove();if(a===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===tt?await a.copy({force:r.force===!0}):await a.purge();return Response.json({result:Te(i)},{headers:{"content-type":"application/json"},status:200})},Fo=(e,t)=>{const n=[],r=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?r.push(a):n.push(a);return{globalTables:r,shardLocalTables:n}},Go=async(e,t,n,r,a,i)=>{if(n!==void 0&&r.length===0)return[];const d=await e.orchestrateExport(a,{args:{tables:r},defaultShardKey:i,headers:t,tables:r}),f=d.shards.filter(h=>h.error);if(f.length>0){const h=f.map(m=>`${m.shardKey}: ${m.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(f.length)} of ${String(d.shards.length)} shard(s) — ${h}`,{code:"EXPORT_SHARD_FAILED",status:502})}return d.shards.flatMap(h=>h.rows??[])},yn=async(e,t,n,r,a)=>{const i=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:d,shardLocalTables:f}=Fo(e,i),h=await Go(t,n,i,f,a,e.defaultShardKey??"__root__"),m=e.exportGlobals,b=r===void 0||d.length>0;return(async function*(){yield*h,b&&m&&(yield*m({tables:d}))})()},Qo=async(e,t,n,r,a,i)=>{for await(const d of await yn(e,t,n,r,i))a(d)},Wo=new TextEncoder,zo=1e3,bn=10,Vo=200,Ut=8,_n="lunoraBackupCron",Ct=24*1048576,Bt=e=>{const t=e.slice(0,bn).map(r=>dn(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Jo=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const a of e)n.set(a,r),r+=a.byteLength;return n},it=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let d=0;d<zo;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)Cr(h.key)&&h.customMetadata?.[_n]===r&&a.push(h.key);if(!f.truncated||f.cursor===void 0)break;i=f.cursor}return{eligible:a.length,stale:a.toSorted((d,f)=>f.localeCompare(d)).slice(n)}},Yo=async(e,t,n,r,a)=>{const{stale:i}=await it(e,t,n,r),d=new Set(a),f=i.filter(k=>d.has(k)),h=f.slice(0,Vo),m=i.length-h.length,b=a.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:b,remaining:m};const T=[],S=[];for(let k=0;k<h.length;k+=Ut){const w=await Promise.allSettled(h.slice(k,k+Ut).map(async g=>(await e.delete(dn(g)),await e.delete(g),g)));for(const[g,y]of w.entries())y.status==="fulfilled"?T.push(y.value):S.push(h[k+g])}return T.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(T.length)}: ${Bt(T)}`),S.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(S.length)}: ${Bt(S)}`),{deleted:T,failed:S,ignored:b,remaining:m}},qo=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=ot(e.backupPrefix??at),r=e.backupCron,{eligible:a,stale:i}=r===void 0?{eligible:0,stale:[]}:await it(t,n,e.backupRetain,r);return{cron:r,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},Xo=async(e,t,n,r,a)=>{const i=e.backupStore;if(!i)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!r||r.length===0)throw new c("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const d={authorization:`Bearer ${r}`,"content-type":"application/json"},f=e.backupTables;let h=0,m=0,b=[];await Qo(e,t,d,f,I=>{const E=Wo.encode(`${JSON.stringify(I)}
2
- `);if(h+=1,m+=E.byteLength,m>Ct)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Ct)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});b.push(E)},n);const S=ot(e.backupPrefix??at),k=new Date(a.scheduledTime).toISOString(),w=Br(S,k),g=Jo(b,m);b=[];const y=Hr(await crypto.subtle.digest("SHA-256",g));await i.put(w,g,{httpMetadata:{contentType:"application/x-ndjson"},sha256:y});const O={bytes:m,createdAt:k,cron:a.cron,file:w,id:k,rows:h,scheduledTime:a.scheduledTime,sha256:y,...f?{tables:f.join(",")}:{}};await i.put(xr(w),`${JSON.stringify(O,void 0,2)}
3
- `,{customMetadata:{[_n]:a.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:I}=await it(i,S,e.backupRetain,a.cron);if(I.length>0){const E=I.slice(0,bn),H=I.length-E.length;console.info(`[lunora] backup retention: ${String(I.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${E.join(", ")}${H>0?` (+${String(H)} more)`:""}`)}}catch(I){console.warn(`[lunora] backup ${w} was written, but the retention report failed:`,I)}},Zo=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=e.backupCron,a=e.backupRetain;if(r===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return Yo(n,ot(e.backupPrefix??at),a,r,t)},ea="/_lunora/admin/backup/retention",ta="/_lunora/admin/backup/prune",na=e=>{const{options:t,readJsonBody:n,requireAdminOption:r}=e,a=(f,h)=>{r(f,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${h} requires a \`backupStore\` on the worker`})},i=async f=>(M(f,"GET","Backup-retention"),a(f,"retention preview"),Response.json(await qo(t),{headers:{"cache-control":"no-store"}})),d=async f=>{M(f,"POST","Backup-prune"),a(f,"prune");const{confirm:h}=await n(f);if(!Array.isArray(h)||h.some(m=>typeof m!="string"))throw new c("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await Zo(t,h),{headers:{"cache-control":"no-store"}})};return{[ta]:d,[ea]:i}},xt=500,ra=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const r=e;if(typeof r.functionPath!="string")throw new c("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 c("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 c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(r.id!==void 0&&typeof r.id!="number")throw new c("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:r.args===void 0?{}:r.args,baselineSeq:typeof r.baselineSeq=="number"?r.baselineSeq:void 0,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:t,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:n}},oa=(e,t)=>{if(e.length>xt)throw new c(`RPC batch exceeds the ${String(xt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,r=new Set;for(const[a,i]of e.entries()){const{entry:d,shardKey:f}=ra(i,a,t);if(r.has(d.id))throw new c(`batch call id ${String(d.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});r.add(d.id);const h=n.get(f)??[];h.push(d),n.set(f,h)}return n},aa="/_lunora/admin/export",sa="/_lunora/admin/import",ia="/_lunora/admin/sync",ca="/_lunora/admin/connector/sync",da="/_lunora/admin/apply",ua="/_lunora/admin/export-tap/run",la=new TextEncoder,ha=async e=>{const n=await ne(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(a)}return{tables:r}},Qe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,fa=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:a,knownTables:i,queryCoordinator:d,assertAdmin:f,resolveForwardContext:h,shardDO:m,prepareExportRows:b,streamingImport:T,syncGlobals:S}=e,k=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await ha(E),{headers:F}=await h(E,H),q=await b(F,U.tables),W=new ReadableStream({async pull(z){try{for await(const V of q)z.enqueue(la.encode(`${JSON.stringify(V)}
4
- `));z.close()}catch(V){z.error(V)}}});return new Response(W,{headers:{"content-type":"application/x-ndjson"},status:200})},w=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await ee(E),F=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},q=typeof U.epochs=="object"&&U.epochs!==null?U.epochs:{},W=typeof U.limit=="number"?U.limit:void 0,z=typeof U.globalCursor=="number"?U.globalCursor:0,V=Qe(U.tables),{headers:re}=await h(E,H),Q=V??i(),ce=await d.orchestrateCdcSync(m,{cursors:F,defaultShardKey:n,epochs:q,headers:re,limit:W,tables:Q}),$=S?await S({limit:W,sinceSeq:z}):void 0;return Response.json({global:$,shards:ce.shards},{status:200})},g=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await ee(E),F=Kr(U.cursor),q=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,W=Qe(U.tables),{headers:z}=await h(E,H),V=W??i(),re=await d.orchestrateCdcSync(m,{cursors:F.s,defaultShardKey:n,headers:z,limit:q,tables:V}),Q=[],ce={...F.s};let $=!1;for(const ae of re.shards)$=Rt(Q,ae.changes??[],Gr(q))||$,ce[ae.shardKey]=ae.cursor;let oe=F.g;if(S){const ae=await S({limit:q,sinceSeq:F.g});$=Rt(Q,ae.changes,q)||$,oe=ae.cursor}const Be=Fr({g:oe,s:ce,v:1}),xe={changes:Q,hasMore:$,nextCursor:Be};return Response.json(xe,{status:200})},y=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await ee(E),q=(Array.isArray(U.batches)?U.batches:[]).map(Q=>Q).filter(Q=>Q!==null&&typeof Q=="object"&&typeof Q.shardKey=="string"&&Array.isArray(Q.changes)),W=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:z}=await h(E,H),V=await d.orchestrateApplyCdc(m,{batches:q,headers:z}),re=W.length>0&&t?await t({changes:W}):0;return Response.json({applied:V.applied+re,failed:V.failed,ok:V.ok},{status:200})},O=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const{headers:U}=await h(E,H),F=await T(E,U);return Response.json(F,{headers:{"content-type":"application/json"},status:F.failed.length>0?207:200})},I=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;if(f(E),a===void 0||Object.keys(a).length===0||r===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const U=await ee(E),F=typeof U.sink=="string"?U.sink:void 0,q=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,W=Qe(U.tables);if(F===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const z=a[F];if(z===void 0)throw new c(`Export-tap sink "${F}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:V}=await h(E,H),re=W??i(),Q=await $r({coordinator:d,cursorStore:r,defaultShardKey:n,headers:V,limit:q,shardDO:m,sink:z,tables:re});return Response.json(Q,{headers:{"content-type":"application/json"},status:200})};return{[da]:y,[ca]:g,[aa]:k,[ua]:I,[sa]:O,[ia]:w}},pa=(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 r=n;return typeof r.table!="string"||r.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!r.doc||typeof r.doc!="object"||Array.isArray(r.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:r.table},ok:!1}:{doc:r.doc,ok:!0,table:r.table}},ma=(e,t,n,r,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:r}},wa=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],a=[],i=new Map;let d=0,f=0;const h=e.body.getReader(),m=new TextDecoder;let b="",T=0;const S=k=>{f+=1;const w=k.trim();if(w.length===0)return;d+=1;const g=pa(w,f);if(!g.ok){r.push(g.error);return}const{doc:y,table:O}=g,I=t.resolveTableSharding?.(O);if(I?.mode.kind==="global"){a.push({doc:y,line:f,table:O});return}const E=ma(y,O,I,n,f);if(!E.ok){r.push(E.error);return}const H=i.get(E.shardKey);H?H.rows.push({doc:y,table:O}):i.set(E.shardKey,{rows:[{doc:y,table:O}],shardKey:E.shardKey,startLine:f})};for(;;){const{done:k,value:w}=await h.read();if(k)break;if(w&&(T+=w.byteLength,T>an))throw await h.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});b+=m.decode(w,{stream:!0});let g=b.indexOf(`
5
- `);for(;g!==-1;){const y=b.slice(0,g);b=b.slice(g+1),S(y),g=b.indexOf(`
6
- `)}}return b.length>0&&S(b),{errors:r,globalRows:a,perShard:i,received:d}},ga=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),Ht=(e,t)=>{for(const[n,r]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+r;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},ya=async(e,t,n,r,a)=>{const i=t.defaultShardKey??"__root__",{errors:d,globalRows:f,perShard:h,received:m}=await wa(e,t,i),b={conflicts:0,errors:d,failed:[],inserted:{}},T=[];if(t.resolveTableSharding===void 0&&h.size>0&&T.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const S=await n.orchestrateImport(a,{batches:[...h.values()],headers:r});Ht(b,S),b.failed.push(...ga(S.shards))}if(f.length>0)if(t.importGlobals){const S=f[0]?.line??1,k=await t.importGlobals({rows:f,startLine:S});Ht(b,k)}else for(const S of f)b.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:S.line,message:`row targets global table "${S.table}" but no \`importGlobals\` is configured`,table:S.table});return{conflicts:b.conflicts,errors:b.errors,failed:b.failed,inserted:b.inserted,received:m,...T.length>0?{warnings:T}:{}}},ba=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),We=e=>typeof e=="object"&&e!==null?e:{},ze=e=>typeof e.kind=="string"?e.kind:"unknown",_a=(e,t)=>{let n=We(t),r=!1;ze(n)==="optional"&&(r=!0,n=We(n._meta?.inner));const a=ze(n),i=n._meta??{},d={kind:a,name:e,optional:r};if(a==="id"&&typeof i.tableName=="string"&&(d.table=i.tableName),a==="array"){const f=ze(We(i.inner));f!=="unknown"&&(d.element=f)}return d},Ra=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>_a(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),Ea="/_lunora/admin/functions",Aa="/_lunora/admin/cron-jobs",Ta="/_lunora/admin/architecture",Sa="/_lunora/admin/openapi",Oa="/_lunora/admin/openrpc",va="/_lunora/admin/global/tables",Ia="/_lunora/admin/global/table",ka="/_lunora/admin/global/facet",Lt=e=>{if(e===void 0||e==="")return;let t;try{t=Xe(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:a,value:i}=r;return[{column:a,value:i}]});return n.length===0?void 0:n},Pa=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:{}}),Da=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"}),Na=e=>{const{assertAdmin:t,options:n,parsePaging:r,queryParameter:a,requireAdminOption:i}=e,d=w=>{M(w,"GET","Functions");const g=i(w,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),y=Object.entries(g).flatMap(([O,I])=>I.visibility==="internal"||I.kind==="stream"?[]:[{args:[...I.argumentDescriptors??Ra(I.args)],kind:I.kind,path:O}]).toSorted((O,I)=>O.path.localeCompare(I.path));return Response.json({functions:y},{headers:{"content-type":"application/json"},status:200})},f=w=>{M(w,"GET","Cron-jobs");const g=i(w,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),y=Object.entries(g).flatMap(([O,I])=>I.map(E=>({args:E.args,cron:O,functionPath:E.functionPath,name:E.name,shardKey:E.shardKey,workflow:E.workflow}))).toSorted((O,I)=>O.name.localeCompare(I.name));return Response.json({jobs:y},{headers:{"content-type":"application/json"},status:200})},h=w=>(M(w,"GET","Architecture"),t(w),Response.json(n.architecture??ba,{headers:{"content-type":"application/json"},status:200})),m=w=>(M(w,"GET","OpenAPI"),t(w),Response.json(n.openApiSpec??Pa,{headers:{"content-type":"application/json"},status:200})),b=w=>(M(w,"GET","OpenRPC"),t(w),Response.json(n.openRpcSpec??Da,{headers:{"content-type":"application/json"},status:200})),T=async w=>{M(w,"GET","Global-tables");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await g.listTables(),{headers:{"content-type":"application/json"},status:200})},S=async w=>{M(w,"GET","Global-table");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),y=new URL(w.url),O=a(y,"table");if(O===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const I=await g.readTablePage({...r(w),filters:Lt(a(y,"filters")),table:O});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},k=async w=>{M(w,"GET","Global-facet");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),y=new URL(w.url),O=a(y,"table"),I=a(y,"column");if(O===void 0||I===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const E=a(y,"limit"),H=E===void 0?void 0:Number(E),L=await g.facetColumn({column:I,filters:Lt(a(y,"filters")),limit:H!==void 0&&Number.isFinite(H)?H:void 0,table:O});return Response.json(L,{headers:{"content-type":"application/json"},status:200})};return{[Aa]:f,[Ea]:d,[ka]:k,[Ia]:S,[va]:T,[Ta]:h,[Sa]:m,[Oa]:b}},Ua="/_lunora/admin/kv/namespaces",Ca="/_lunora/admin/kv/keys",Rn="/_lunora/admin/kv/value",En=32*1048576,jt=60,Ba=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=w=>n(w,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=w=>Response.json(w,{headers:{"content-type":"application/json"},status:200}),i=(w,g)=>{const y=new URL(w.url),O=y.searchParams.get("namespace")??"",I=y.searchParams.get("key")??"";if(O==="")throw new c(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(I==="")throw new c(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:I,namespace:O}},d=async(w,g)=>{if(!(await w.listNamespaces()).some(O=>O.binding===g))throw new c(`Unknown KV namespace binding \`${g}\``,{code:"NOT_FOUND",status:404})},f=async w=>(M(w,"GET","KV-namespaces"),a({namespaces:await r(w).listNamespaces()})),h=async w=>{M(w,"GET","KV-keys");const g=r(w),y=new URL(w.url),O=y.searchParams.get("namespace")??"";if(O==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const I=y.searchParams.get("prefix")??void 0,E=y.searchParams.get("cursor")??void 0,H=y.searchParams.get("limit"),L=H===null?void 0:Number.parseInt(H,10);if(L!==void 0&&(!Number.isInteger(L)||L<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const U=L===void 0?void 0:Math.min(L,1e3);return await d(g,O),a(await g.listKeys({cursor:E,limit:U,namespace:O,prefix:I}))},S={DELETE:async w=>{const g=r(w),y=i(w,"DELETE");return await d(g,y.namespace),await g.deleteKey(y),a({deleted:!0})},GET:async w=>{const g=r(w),y=i(w,"GET");return await d(g,y.namespace),a(await g.getValue(y))},PUT:async w=>{const g=r(w),y=await t(w,En);if(typeof y.namespace!="string"||y.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof y.key!="string"||y.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof y.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(y.expirationTtl!==void 0&&(typeof y.expirationTtl!="number"||!Number.isInteger(y.expirationTtl)||y.expirationTtl<jt))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const O=Math.floor(Date.now()/1e3)+jt;if(y.expiration!==void 0&&(typeof y.expiration!="number"||!Number.isInteger(y.expiration)||y.expiration<O))throw new c("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await d(g,y.namespace),await g.putValue({expiration:y.expiration,expirationTtl:y.expirationTtl,key:y.key,metadata:y.metadata,namespace:y.namespace,value:y.value}),a({ok:!0})}},k=w=>{const g=S[w.method];if(!g)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(w)};return{[Ua]:f,[Ca]:h,[Rn]:k}},xa="/_lunora/migrate",Ha="/_lunora/admin/pitr",La="/_lunora/admin/rank",ja="/_lunora/admin/rankpage",Ma="/_lunora/admin/shard-registry/prune",$a="/_lunora/admin/shard-traffic",Ka=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Fa=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Ga=async e=>{const n=await ne(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!Ka.has(n.functionPath))throw new c("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},Qa=async e=>{const n=await ne(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new c("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new c("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new c("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new c("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},Wa=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new c('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},za=e=>{if(typeof e.table!="string"||e.table.length===0)throw new c("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new c("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new c("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new c("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new c("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Va=async e=>{const n=await ne(e,"Rank page")??{};za(n);const r=Wa(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:r,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},Ja=async e=>{const n=await ne(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},Ya=async e=>{const n=await ne(e,"Shard-registry prune")??{};if(n.tables!==void 0&&!(Array.isArray(n.tables)&&n.tables.every(r=>typeof r=="string")))throw new c("Shard-registry prune `tables` must be an array of table names",{code:"BAD_REQUEST",status:400});return{dryRun:n.dryRun===!0,tables:n.tables}},qa=async e=>{const n=await ee(e);if(typeof n.functionPath!="string"||!Fa.has(n.functionPath))throw new c("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new c("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},Xa=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:r,queryCoordinator:a,resolveForwardContext:i,shardDO:d,shardedTables:f}=e,h=(g,y)=>{if(g.method!=="POST")throw new c(`${y} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(g))throw new c("Admin auth required",{code:"FORBIDDEN",status:403})},m=async(g,y)=>{h(g,"Migration");const O=await Ga(g),{headers:I}=await i(g,y),E=await a.orchestrateMigration(d,{args:O.args,defaultShardKey:t,functionPath:O.functionPath,headers:I,table:O.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},b=async(g,y)=>{h(g,"Rank");const O=await Qa(g),{headers:I}=await i(g,y),E=await a.orchestrateRank(d,{headers:I,index:O.index,partitionKey:O.partitionKey,rowId:O.rowId,sortValues:O.sortValues,table:O.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},T=async(g,y)=>{h(g,"Rank page");const O=await Va(g),{headers:I}=await i(g,y),E=await a.orchestrateRankPage(d,{...O,headers:I});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},S=async(g,y)=>{h(g,"Shard-traffic");const O=await Ja(g),{headers:I}=await i(g,y),E=await a.orchestrateShardTraffic(d,{headers:I,table:O.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},k=async(g,y)=>{h(g,"Shard-registry prune");const O=await Ya(g),I=f(),E=(O.tables??[]).filter(U=>!I.includes(U));if(E.length>0)throw new c(`Shard-registry prune names tables that are not \`.shardBy()\`: ${E.join(", ")}`,{code:"BAD_REQUEST",status:400});const{headers:H}=await i(g,y),L=await Yr(a.registry,d,{dryRun:O.dryRun,headers:H,tables:O.tables??I});return Response.json(L,{status:L.failed.length>0?207:200})},w=async(g,y)=>{if(M(g,"POST","PITR"),!r(g))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const O=await qa(g),{headers:I}=await i(g,y),E=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:O.args,functionPath:O.functionPath}),headers:I,method:"POST"});return n(d,O.shardKey??t,E)};return{[xa]:m,[Ha]:w,[La]:b,[ja]:T,[Ma]:k,[$a]:S}},Za=1,es=0,ts=32,ns=512,rs=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,os=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>ns)return;const n=t.split(",");if(!(n.length>ts)){for(const r of n)if(!rs.test(r.trim()))return;return t}},as=e=>{const t=Er(e.headers.get("traceparent"));if(t===void 0)return;const n=os(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},Mt=(e,t={})=>{const n=as(e),r=t.trustInbound===!0?n:void 0,a=we(8),i=r?.traceId??we(16),d=vr(t.sampling,r===void 0?a:i),{rayId:f}=t,h=d.isTraced&&(r===void 0||r.sampled);return{decision:d,ignoredUpstream:n!==void 0&&r===void 0,trace:{sampled:h,spanId:a,traceFlags:h?Za:es,traceId:i,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState},...f===void 0?{}:{rayId:f}}}},$t=(e,t)=>{t.traceparent=on(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState),e.rayId!==void 0&&(t[lo]=e.rayId)},ss=(e,t)=>{let n;return()=>{if(n===void 0){const r=Or(e),a=t===void 0?void 0:t.cf;n=Ar(Sr(r),Tr(r,a))}return n}},is="/_lunora/admin/scheduled",cs="/_lunora/admin/scheduled/status",ds="/_lunora/admin/scheduled/ws",us="/_lunora/admin/scheduled/cancel",ls="/_lunora/admin/scheduled/dead",hs="/_lunora/admin/scheduled/dead/retry",fs="/_lunora/admin/scheduled/dead/cancel",ps="/_lunora/admin/scheduled/pool/release",ms=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:r,schedulerInstanceName:a}=e,i=(m,b)=>T=>{if(T.method!=="GET")throw new c(`${b} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const S=new URL(T.url).searchParams.get("cursor"),k=S===null||S===""?"":`?cursor=${encodeURIComponent(S)}`;return r(T).fetch(new Request(`https://scheduler.internal${m}${k}`,{method:"GET"}))},d=(m,b,T=b)=>async S=>{if(S.method!=="POST")throw new c(`${T} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const k=r(S),w=await ne(S,b);if(typeof w?.id!="string"||w.id==="")throw new c(`${b} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return k.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))},f=async m=>{if(m.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const b=r(m),T=await ne(m,"Scheduled pool-release");if(typeof T?.pool!="string"||T.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const S=typeof T.id=="string"&&T.id!==""?T.id:void 0;return b.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(S===void 0?{pool:T.pool}:{id:S,pool:T.pool}),headers:{"content-type":"application/json"},method:"POST"}))},h=async m=>{if(m.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(m))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const b=n();return ge(b,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[us]:d("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[fs]:d("/dead/cancel","Scheduled dead-letter action"),[ls]:i("/dead","Scheduled dead-letter"),[hs]:d("/dead/retry","Scheduled dead-letter action"),[is]:i("/list","Scheduled-list"),[ps]:f,[cs]:i("/status","Scheduler-status"),[ds]:h}},ws="/_lunora/scheduled",An="/_lunora/queue",Tn=16*1048576,gs=e=>{const{assertAdmin:t,dispatchScheduled:n,queueHandler:r}=e,a=async(d,f,h)=>{if(t(d),d.method!=="POST")throw new c("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const m=await ne(d,"Scheduled tick"),b=typeof m?.cron=="string"?m.cron:"";if(b==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:b,noRetry:()=>{},scheduledTime:Date.now()},f,h),Response.json({cron:b,ok:!0})},i=async(d,f,h)=>{if(t(d),d.method!=="POST")throw new c("queue dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!r)throw new c("no queueHandler configured",{code:"BAD_REQUEST",status:400});const m=await ne(d,"Queue dispatch",Tn);if(!Array.isArray(m?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const b=typeof m.queue=="string"?m.queue:"",T=m.messages.filter(k=>typeof k=="object"&&k!==null&&typeof k.id=="string").map(k=>({body:k.body,id:k.id})),S=await r({messages:T,queue:b},f,h);return Response.json({retry:S?.retry??[]})};return{[An]:i,[ws]:a}},ys=(e,...t)=>{let n=e.cf;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return typeof n=="string"?n:void 0},nt={mtls:e=>ys(e,"tlsClientAuth","certVerified")==="SUCCESS"},bs=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(nt,e)?nt[e]:void 0)??(()=>!1),_s=e=>typeof e=="string"&&Object.hasOwn(nt,e),Rs=e=>{const t=_s(e)?e:void 0;if(e!==void 0&&t===void 0)return()=>{};let n=!1;return r=>{n||t!==void 0&&r.cf!==void 0||(n=!0,console.warn(t===void 0?'[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.':`[lunora] \`trustInboundTraceContext: "${t}"\` cannot be satisfied on this host: the request carries no platform-injected \`cf\` metadata, which is what that signal reads, so every inbound \`traceparent\` is ignored and this request starts a new trace. Off Cloudflare, trust the upstream some other way — \`trustInboundTraceContext: true\` when nothing untrusted can reach this worker, or a predicate that verifies whatever your own front door sets. Set it to \`false\` to keep this behaviour and silence this message.`))}},Es="/_lunora/admin/vector/indexes",As="/_lunora/admin/vector/query",Ts=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=async i=>{M(i,"GET","Vector-indexes");const d=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await d.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async i=>{M(i,"POST","Vector-query");const d=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(d.queryIndex===void 0)throw new c("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const h=await t(i);if(typeof h.name!="string"||h.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof h.text!="string"||h.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(h.topK!==void 0&&(typeof h.topK!="number"||!Number.isInteger(h.topK)||h.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const m=await d.queryIndex({name:h.name,text:h.text,topK:h.topK});return Response.json(m,{headers:{"content-type":"application/json"},status:200})};return{[Es]:r,[As]:a}},Ss="/_lunora/admin/workflows/instances",Os="/_lunora/admin/workflows/instance",vs="/_lunora/admin/workflows/status",Is={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},ks=e=>e!==null&&Object.hasOwn(Is,e)?e:void 0,Kt=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const r=Number(n);return Number.isInteger(r)&&r>0?r:void 0},Ve=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new c(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},Ft=()=>{throw new c("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Ps=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,r=async(d,f,h)=>{M(d,"GET","Workflows instances"),t(d);const m=n(f);if(!m)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const b=Ve(h,"name"),T=ks(h.searchParams.get("status"));return Response.json(await m.listInstances({page:Kt(h,"page"),perPage:Kt(h,"perPage"),status:T,workflowName:b}))},a=async(d,f,h)=>{M(d,"GET","Workflows instance"),t(d);const m=n(f);return m?Response.json(await m.getInstance({instanceId:Ve(h,"id"),workflowName:Ve(h,"name")})):Ft()},i=async(d,f)=>{M(d,"POST","Workflows status"),t(d);const h=n(f);if(!h)return Ft();const m=await ne(d,"Workflows status");if(typeof m?.name!="string"||m.name===""||typeof m.id!="string"||m.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:b}=m;if(b!=="pause"&&b!=="resume"&&b!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await h.setInstanceStatus({action:b,instanceId:m.id,workflowName:m.name}))};return{[Os]:a,[Ss]:r,[vs]:i}},Ds={[Rn]:En,[An]:Tn,[Mr]:jr},Gt="/_lunora/rpc",Ns="/_lunora/rpc-batch",Us="/_lunora/ws",Ae=(e,t,n)=>({resourceAttributes:ss(e,t),...n===void 0?{}:{waitUntil:n}}),Je=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Qt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ye=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0,r=fo(e.headers.get(uo)),a=r===void 0?{}:{rayId:r};let i;try{i=new URL(e.url)}catch{return{method:t,...a,userAgent:n}}const d=i.port===""?void 0:Number(i.port);return{host:i.hostname,method:t,path:i.pathname,port:Number.isNaN(d)?void 0:d,...a,scheme:i.protocol.replace(":",""),userAgent:n}},Wt="/_lunora/voice/",Cs="/_lunora/admin/cron-jobs/run",Bs="/_lunora/admin/ws-token",xs="/_lunora/admin/",Ce="/_lunora/",Hs="/_lunora/migrate",Ls="/_lunora/status",js=e=>e.startsWith(xs)||e===Hs,ke=e=>{if(ko(e))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Pe=async e=>await e===!0,zt=(e,t)=>{const n=e.headers.get(gt);if(n===null)return;const r=Rr(n);if(r===void 0)throw new c(`malformed ${gt} header`,{code:"BAD_REQUEST",status:400});if(r.subject!==(t?.userId??null))throw new c("the session changed since this write was queued",{code:"IDENTITY_MISMATCH",status:409})},Vt="/api/auth",Ms="__lunora_admin__:recordAuthEvent",Jt="__lunora_admin__:listPushSubscriptions",$s=["/sign-in","/sign-up","/callback"],Ks=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const r=e.slice(n.length);return $s.some(a=>r===a||r.startsWith(`${a}/`))},Yt=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},De=(e,t,n,r)=>{const a=pr(n),i=a?n.code:"INTERNAL_SERVER_ERROR",d=a?n.status:500,{message:f,name:h,stack:m}=co(n);return{durationMs:t,error:{code:i,message:f,name:h,status:d,...m===void 0?{}:{stack:m}},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},Sn=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},On=({identity:e})=>e!==null&&yr(Sn(e)),Fs=e=>{if(On(e))throw new c("authentication token expired",{code:"TOKEN_EXPIRED",status:401});return e},Gs=e=>{if(!On(e))return e;const t={...e.headers};return delete t["x-lunora-identity"],delete t["x-lunora-identity-exp"],delete t["x-lunora-userid"],{claims:null,headers:t,identity:null,userId:null}},qt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Qs=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},rt=new WeakMap,Ws=async(e,t,n,r,a=rt.get(e))=>{const i={"content-type":"application/json"},d=e.headers.get("authorization"),f=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),m=e.headers.get("x-lunora-mutation-id"),b=e.headers.get("x-lunora-client-id"),T=e.headers.get("x-lunora-client-seq"),S=e.headers.get("x-lunora-base-seq");d&&(i.authorization=d),f&&(i.cookie=f),h&&(i["x-d1-bookmark"]=h),m&&(i["x-lunora-mutation-id"]=m),b&&(i["x-lunora-client-id"]=b),T&&(i["x-lunora-client-seq"]=T),S&&(i["x-lunora-base-seq"]=S);const k=Ur(e.headers,r);if(k&&(i["x-lunora-client-ip"]=k),i["x-lunora-origin"]=new URL(e.url).origin,!n)return{claims:null,headers:i,identity:null,userId:null};const w=await n(e,t,a);if(!w||typeof w.userId!="string"||w.userId.length===0)return{claims:null,headers:i,identity:null,userId:null};i["x-lunora-userid"]=br(w.userId);const g=Sn(w);g!==void 0&&(i["x-lunora-identity-exp"]=String(g));const{userId:y,...O}=w,I=Object.keys(O).length>0?O:null;return I&&(i["x-lunora-identity"]=_r(I)),{claims:I,headers:i,identity:w,userId:y}},zs=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Vs=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new c("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new c("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new c("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!zs.has(n.kind))throw new c("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new c("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new c("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Js=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},qe=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new c("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new c(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},Ys=async e=>{const t=await cn(e);let n;try{n=JSON.parse(t)}catch{throw new c("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new c("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const r=n;if(r.args!==void 0&&sn(r.args,"RPC"),r.shardKey!==void 0&&typeof r.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,i=Vs(a.fanOut),d=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const f=d.table;if(typeof f=="string"&&f!==i.table)throw new c("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});d.table=i.table}return{args:d,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},Ne=new Map,qs=5e3,Xs=4096,Zs=async(e,t)=>{const n=Date.now(),r=Ne.get(t);if(r!==void 0&&r.expiresMs>n)return r.relayCount;r!==void 0&&Ne.delete(t);let a=0;try{const i=await ge(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const d=await i.json();typeof d.relayCount=="number"&&d.relayCount>0&&(a=Math.floor(d.relayCount))}}catch{a=0}return tn(Ne,Xs),Ne.set(t,{expiresMs:n+qs,relayCount:a}),a},Xt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},Ue=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),ei=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],ti=(e,t)=>{for(const n of ei){e.delete(n);const r=t[n];r!==void 0&&e.set(n,r)}},Zt=(e,t)=>{const n=new Headers(e.headers),r=[...n.keys()];for(const a of r)a.startsWith("x-lunora-")&&n.delete(a);return ti(n,t),n},en=async(e,t)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:Ho(t,n)},ni=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return zr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return $e(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return $e(`queue:${e}`,!0);if(typeof n.connectionString=="string")return $e(`hyperdrive:${e}`,!0)},ri=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(Ce))throw new c(`route "${t}" is under the reserved ${Ce} prefix, which the framework owns. App routes registered there shadow the internal endpoint AND its admin gate — pick a path outside the prefix.`,{code:"MISCONFIGURED",status:500})},oi=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new c("`x402Charge` requires `functions`: paid (.x402) procedures are read from the function registry, so without it every paid procedure would dispatch FREE. Build the worker with `defineApp()` (which supplies the registry) or pass `functions` explicitly.",{code:"MISCONFIGURED",status:500})},vn=e=>{oi(e);const t=bs(e.trustInboundTraceContext),n=Rs(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",a=e.queryCoordinator??qr({registry:Xr(e.resolveTableSharding,r)}),i=Vr(e.resolveIdentity,e.identity),d=Ke(e.shardDO,e.jurisdiction),f=e.schedulerDO===void 0?void 0:Ke(e.schedulerDO,e.jurisdiction),h=e.voiceAgents===void 0?void 0:Object.fromEntries(Object.entries(e.voiceAgents).map(([o,s])=>[o,Ke(s,e.jurisdiction)]));let m=!1;const b=o=>{if(o===void 0||e.jurisdiction===void 0)return o;m||(m=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},T=async(o,s,l,u=e.shardRegion?.(s))=>ge(o,s,b(u)).fetch(l);let S;const k=()=>e.adminToken??S;let w;const g=o=>{const s=o??{};if(w??=Xt(o,e.shardDO),S!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(S=l)},y=new WeakSet,O=o=>pn(o,k())||y.has(o),I=async o=>{if(!(e.adminGate===void 0||y.has(o)))try{await Pe(e.adminGate(o,rt.get(o)))&&y.add(o)}catch{}},E=async(o,s,l,u)=>{const p=await Ws(o,s,l,e.trustedClientIpHeader,u);return e.functions!==void 0&&(p.headers[rn]=nn),p},H=async(o,s,l,u)=>Fs(await E(o,s,l,u)),L=async(o,s)=>{const l=await E(o,s,e.resolveIdentity);if(y.has(o)&&l.headers.authorization===void 0){const u=k();u!==void 0&&(l.headers.authorization=`Bearer ${u}`)}return l};let U=!1,F=!1;const q=()=>{F||(F=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},W=o=>{if(!e.allowUnauthenticatedShardAccess){const s=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${o} access is default-denied: configure \`${s}\` 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})}U||(U=!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("")))},z=async(o,s,l=!1)=>{if(s.includes(Ze)||s.includes(et))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(!l)if(e.authorizeShard){if(!await Pe(e.authorizeShard({identity:o,shardKey:s})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==r&&W("shard")},V=Xa({defaultShard:r,forwardToShard:T,isAdmin:O,queryCoordinator:a,resolveForwardContext:L,shardDO:d,shardedTables:()=>(e.listSchemaTables?.()??[]).filter(o=>e.resolveTableSharding?.(o)?.mode.kind==="shardBy")}),re=async(o,s,l,u,p,R)=>{ke(o);const v=Do({forwardedIdentity:p,mutationId:u,traceparent:R});return T(d,l,Ue(o,s,v))},Q=async(o,s,l,u,p)=>{const R=Co(l.env,l.context?.exports,o,["create"]);if(R===void 0)throw new c(`${u} targets workflow "${o}", which is on neither ctx.exports nor env`,{code:"CRON_JOB_FAILED",status:500});if(no(s))throw new c(`${u} params ${ro}`,{code:"BAD_REQUEST",status:400});try{await R.create(p===void 0?{params:s}:{id:p,params:s})}catch(v){if(!so(v))throw v}},ce=async(o,s,l,u)=>{if(o.workflow){await Q(o.workflow,o.args??{},{context:l,env:s},`cron job "${o.name}"`);return}if(o.functionPath===void 0)throw new c(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const p=await re(o.functionPath,o.args??{},o.shardKey??r,void 0,void 0,u);if(!p.ok)throw new c(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(p.status)}`,{code:"CRON_JOB_FAILED",status:500})},$=o=>{if(!O(o))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},oe=(o,s,l)=>{if($(o),s===void 0)throw new c(l.message,{code:l.code,status:400});return s},Be=async(o,s,l,u,p,R)=>{const v=e.cronJobs?.[o];if(!v)return 0;for(const P of v)try{await ce(P,s,l,R)}catch(D){u.push(p(D))}return v.length},xe=async(o,s,l)=>{if($(o),M(o,"POST","cron-jobs run"),!e.cronJobs)throw new c("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const u=await ee(o),p=typeof u.name=="string"?u.name:"";if(p==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const R=Object.values(e.cronJobs).flat().find(v=>v.name===p);if(!R)throw new c(`no cron job named "${p}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await ce(R,s,l),Response.json({name:p,ran:!0},{status:200})},ae=async o=>{const s=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!s||!f||typeof o.id!="string")return;const l=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await ge(f,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},In=async(o,s,l)=>{M(o,"POST","Scheduler dispatch");const u=await cn(o),p=s??{},R=typeof p.LUNORA_SCHEDULER_SECRET=="string"?p.LUNORA_SCHEDULER_SECRET:void 0,v=e.adminToken??(typeof p.LUNORA_ADMIN_TOKEN=="string"?p.LUNORA_ADMIN_TOKEN:void 0);if(!await Po(o,u,{adminToken:v,schedulerSecret:R}))throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let D;try{D=JSON.parse(u)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const _=D??{},A=_.args??{},B=typeof _.id=="string"&&_.id.length>0?_.id:void 0;if(typeof _.workflow=="string"&&_.workflow.length>0)return await Q(_.workflow,A,{context:l,env:s},"scheduled workflow",B),await ae(_),Response.json({ok:!0},{status:200});if(typeof _.functionPath!="string"||_.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const j=typeof _.shardKey=="string"&&_.shardKey.length>0?_.shardKey:r,J=No(o),x=await re(_.functionPath,A,j,B,J,o.headers.get("traceparent")??void 0);return await ae(_),x},kn=$o({assertAdmin:$,getReader:()=>e.authAuditReader}),Pn=Ko({assertAdmin:$,getMove:()=>e.authJurisdictionMove}),Dn=async(o,s)=>{$(o);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:Te({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const u=s?.kind,p=s?.userId,R=s?.limit,v=u==="fcm"||u==="web-push"?u:void 0,P=typeof p=="string"&&p!==""?p:void 0,D=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,_=D>0?Math.min(D,1e3):1e3,B=(await l.list({kind:v,limit:_,userId:P})).filter(j=>v!==void 0&&j.kind!==v?!1:P===void 0||(j.userId??null)===P).map(({keys:j,token:J,...x})=>x);return Response.json({result:Te({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},Nn=async(o,s)=>{if(!s.fanOut&&!(s.functionPath!==Pt&&s.functionPath!==Jt&&s.functionPath!==tt&&s.functionPath!==gn))return await I(o),s.functionPath===Pt?kn(o,s.args??{}):s.functionPath===Jt?Dn(o,s.args):Pn(o,s.functionPath,s.args??{})},Un=fa({applyGlobals:e.applyGlobals,assertAdmin:$,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:r,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:a,resolveForwardContext:L,shardDO:d,prepareExportRows:async(o,s)=>yn(e,a,o,s,d),streamingImport:(o,s)=>ya(o,e,a,s,d),syncGlobals:e.syncGlobals}),He=(o,s)=>{const l=o.searchParams.get(s);return l===null||l===""?void 0:l},Le=o=>{const s=new URL(o.url),l=s.searchParams.get("limit"),u=s.searchParams.get("offset"),p=l===null?void 0:Number.parseInt(l,10),R=u===null?void 0:Number.parseInt(u,10);return{limit:p!==void 0&&Number.isFinite(p)&&p>=0?p:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},ct=()=>{if(f===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return f},Cn=ms({checkWsAdmin:async o=>O(o)||en(o,k()),requireSchedulerNamespace:ct,resolveSchedulerStub:o=>($(o),ge(ct(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Bn=Ps({assertAdmin:$,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),xn=Lr({assertAdmin:$,parsePaging:Le,queryParameter:He,readBodyBytes:Dr,requireAdminOption:oe,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Hn=na({options:e,readJsonBody:ee,requireAdminOption:oe}),Ln=Ts({readJsonBody:ee,requireAdminOption:oe,vectorIntrospector:e.vectorIntrospector}),jn=Ba({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:oe}),Mn=Jr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:oe}),$n=Na({assertAdmin:$,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,architecture:e.architecture,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Le,queryParameter:He,requireAdminOption:oe}),Kn=o=>{const s=[],l=d??o?.SHARD;if(l!==void 0&&s.push(Wr("durable-object:default",l,r)),e.health?.disableBindingProbes!==!0)for(const[u,p]of Object.entries(o??{})){const R=ni(u,p);R!==void 0&&s.push(R)}for(const u of e.health?.probes??[])s.push(u);return s},Fn=Qr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:O,resolveProbes:Kn}),Gn=o=>{const s=_=>"args"in _?{..._,args:Xe(_.args)}:_,l=e.schedulerInstanceName??"default",u=()=>ge(o,l),p=async(_,A)=>{const B=await u().fetch(new Request(`https://scheduler.internal${_}`,A));if(!B.ok)throw new c(`ctx.scheduler: SchedulerDO ${_} failed (${String(B.status)}): ${await B.text()}`,{code:"INTERNAL",status:500});return await B.json()},R=async(_,A)=>await p(_,{body:JSON.stringify(A),headers:{"content-type":"application/json"},method:"POST"}),v=_=>{const A=_;if(A==null)throw new c("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof A.binding=="string"&&A.binding.length>0)return{workflow:A.binding};if(typeof A.__lunoraRef=="string")return{functionPath:A.__lunoraRef};throw new c("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},P=async()=>(await oo(async A=>p(A===void 0?"/list":`/list?cursor=${encodeURIComponent(A)}`,{method:"GET"}))).map(A=>s(A)),D=async(_,A,B={})=>{const j=v(A),{id:J}=await R("/schedule",{args:wr("ctx.scheduler",String(j.functionPath??j.workflow),B),scheduledFor:Math.ceil(_),...j});return J};return{cancel:async _=>await R("/cancel",{id:_}),get:async _=>{const A=await p(`/get?id=${encodeURIComponent(_)}`,{method:"GET"});return A.record===void 0?null:s(A.record)},list:P,runAfter:async(_,A,B)=>{if(!Number.isFinite(_)||_<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await D(Date.now()+_,A,B)},runAt:async(_,A,B)=>{if(!Number.isFinite(_))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await D(_,A,B)}}},Qn=async(o,s,l)=>{const{claims:u,headers:p,userId:R}=Gs(await E(o,s,i)),v=Ae(s,o,_=>l.waitUntil?.(_)),P=_=>async(A,B={})=>{const j=A.__lunoraRef;if(typeof j!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ke(j);const J=await Oe(o,j,Te(B),_,{...p,"x-lunora-system":"1"},v),x=await J.json();if(x.error)throw new c(x.error.message??"shard RPC failed",{code:x.error.code??"INTERNAL",status:J.status});return Xe(x.result)},D=P(r);return{auth:{getIdentity:()=>Promise.resolve(u),userId:R},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),forShard:_=>{const A=P(_);return{runAction:A,runMutation:A,runQuery:A}},runAction:D,runMutation:D,runQuery:D,...f===void 0?{}:{scheduler:Gn(f)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:to(e.storage(s,new URL(o.url).origin))}}},Wn=async(o,s,l)=>{if(!e.httpRouter)return;const u=await Qn(o,s,l);try{return await e.httpRouter.fetch(o,{...s,__lunoraCtx:u},l)}catch(p){return console.error("[lunora] httpRouter (SSR) handler threw:",p),new Response("Internal Server Error",{status:500})}},zn=async(o,s,l)=>{if(o.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const u=At(o,se);if(u)return u;const p=l.searchParams.get("shard")??r,{headers:R,identity:v}=await E(o,s,i),P=O(o)||await en(o,k());await z(v,p,P);const D=Zt(o,R),_=Xt(s,e.shardDO);if(_!==void 0){D.set("x-lunora-shard-binding",_);const A=await Zs(d,p);if(A>0){const B=bo(p,Math.floor(Math.random()*A));return T(d,B,new Request(o,{headers:D}),vt(o))}}return T(d,p,new Request(o,{headers:D}))},Vn=async(o,s,l)=>{if(h===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 u=At(o,se);if(u)return u;let p;try{p=decodeURIComponent(l.pathname.slice(Wt.length))}catch{return new Response("Unknown voice agent",{status:404})}const R=Object.hasOwn(h,p)?h[p]:void 0;if(R===void 0)return new Response("Unknown voice agent",{status:404});const v=l.searchParams.get("threadKey");if(v===null||v.length===0)return new Response("Missing threadKey",{status:400});const{headers:P,identity:D}=await E(o,s,i);if(e.authorizeShard){if(!await Pe(e.authorizeShard({identity:D,shardKey:v})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else W("shard");const _=Zt(o,P);return T(R,v,new Request(o,{headers:_}))},Jn=async(o,s,l)=>{if(e.authorizeFanOut){if(!await Pe(e.authorizeFanOut(l,o.table,s)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new c("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});W("fan-out")},Se=async(o,s)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await Jn(o.fanOut,o.functionPath,s);return}await z(s,o.shardKey??r)}},Yn=(o,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){q();return}if(e.functions[s]?.kind!=="query"||l.includes(et)||l.includes(Ze))return;const u=vt(o);return u===void 0?void 0:{name:_o(l,u),region:u}},qn=async(o,s,l,u,p)=>{const R=Yn(o,s,u);if(R!==void 0){const v={...p,"x-lunora-replica-read":"1",...w===void 0?{}:{"x-lunora-shard-binding":w}},P=Ro(o.headers.get("x-lunora-min-seq"));P!==void 0&&(v["x-lunora-min-seq"]=String(P));const D=await T(d,R.name,Ue(s,l,v),R.region);if(D.status!==421)return D}return T(d,u,Ue(s,l,p))},Oe=async(o,s,l,u,p,R)=>{const v=Date.now(),{observability:P,sampling:D}=e,_=Ye(o),{decision:A,ignoredUpstream:B,trace:j}=Mt(o,{..._.rayId===void 0?{}:{rayId:_.rayId},...D===void 0?{}:{sampling:D},trustInbound:t(o)});B&&n(o);const J={...p,[bt]:A.keepErrors?"1":"0",[Tt]:"1"};$t(j,J);try{const x=await qn(o,s,l,u,J),fe=Ot(x.headers.get(St));ie(P,{..._,...Qt(j),durationMs:Date.now()-v,functionPath:s,ok:x.ok,shardKey:u,...x.ok?{}:{error:{...fe,code:fe?.code??"SHARD_ERROR",message:fe?.message??`shard returned ${String(x.status)}`,status:x.status}}},R,void 0,{isTraced:j.sampled,keepErrors:A.keepErrors});const ye=new Response(x.body,{headers:x.headers,status:x.status,statusText:x.statusText});return ye.headers.set("x-lunora-shard-key",u),ye.headers.delete(St),ye}catch(x){throw ie(P,{..._,...Qt(j),...De(s,Date.now()-v,x,{shardKey:u})},R,void 0,{isTraced:j.sampled,keepErrors:A.keepErrors}),x}},Xn=o=>{if(o.fanOut&&o.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});o.fanOut||ke(o.functionPath)},Zn=async(o,s,l)=>{M(o,"POST","RPC");const u=await Ys(o);Js(s,u),Xn(u);const p=await Nn(o,u);if(p!==void 0)return p;const{headers:R,identity:v}=await H(o,s,i);zt(o,v),await Se(u,v);const P=qe(u,e);{const D=Date.now(),{observability:_}=e,A=Ye(o),B=Ae(s,o,l&&(x=>l.waitUntil?.(x)));if(u.fanOut)try{const x=await a.fanOut(d,{args:u.args??{},fanOut:u.fanOut,functionPath:u.functionPath,headers:R});return ie(_,{durationMs:Date.now()-D,fanOut:{failed:x.failed,shards:x.ok+x.failed,table:u.fanOut.table},functionPath:u.functionPath,...A,ok:!0},B),Response.json(x,{headers:{"content-type":"application/json"},status:200})}catch(x){throw ie(_,{...De(u.functionPath,Date.now()-D,x,{fanOut:{table:u.fanOut.table}}),...A},B),x}const j=u.shardKey??r,J=()=>Oe(o,u.functionPath,u.args??{},j,R,B);return P&&e.x402Charge?e.x402Charge(o,{functionPath:u.functionPath,price:P.price},J,Je(l)):J()}},er=async(o,s,l)=>{M(o,"POST","RPC batch");const u=await ee(o),{calls:p}=u;if(!Array.isArray(p))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:v}=await H(o,s,i);zt(o,v);const P=oa(p,r);for(const K of P.values())for(const G of K)if(e.functions?.[G.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${G.functionPath}" cannot be called in a batch; dispatch it individually over ${Gt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...P.entries()].flatMap(([K,G])=>G.map(X=>Se({args:X.args,functionPath:X.functionPath,shardKey:K},v))));const{observability:D,sampling:_}=e,A=Ae(s,o,l&&(K=>l.waitUntil?.(K))),B=Ye(o),{decision:j,ignoredUpstream:J,trace:x}=Mt(o,{...B.rayId===void 0?{}:{rayId:B.rayId},..._===void 0?{}:{sampling:_},trustInbound:t(o)});J&&n(o);const fe={isTraced:x.sampled,keepErrors:j.keepErrors},ye=K=>{const G={...R,"content-type":"application/json",[bt]:j.keepErrors?"1":"0",[Tt]:"1"};return $t({...x,spanId:K},G),G},je=K=>({parentSpanId:K,spanId:we(8),traceFlags:x.traceFlags,traceId:x.traceId}),Ie=[],Me=[],ht=(K,G,X,de)=>({body:{error:{code:X,message:de}},id:K.id,status:G}),ft=(K,G,X,de,pe)=>{for(const Z of K)ie(D,pe(Z),A,void 0,fe),Ie.push(ht(Z,G,X,de))},hr=(K,G,X,de,pe,Z)=>{for(const be of K){const _e=pe.get(be.id),ue=_e?.status??Z,le=ue<400,Re=le?void 0:Ot(_e?.errorDetail);ie(D,{durationMs:de,functionPath:be.functionPath,...B,...je(X),ok:le,shardKey:G,...le?{}:{error:{...Re,code:Re?.code??"SHARD_ERROR",message:Re?.message??`batched call returned ${String(ue)}`,status:ue}}},A,void 0,fe)}};await Promise.all([...P.entries()].map(async([K,G])=>{const X=we(8),de=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:G}),headers:new Headers(ye(X)),method:"POST"}),pe=Date.now();let Z;try{Z=await T(d,K,de)}catch(Y){const Ee=Date.now()-pe,{body:wt}=mr(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});ft(G,502,wt.code,wt.message,fr=>({...De(fr.functionPath,Ee,Y,{shardKey:K}),...B,...je(X)}));return}const be=Date.now()-pe,_e=Z.headers.get("x-d1-bookmark");_e&&Me.push(_e);let ue;try{ue=await Z.json()}catch{const Y=`shard batch returned a non-JSON response (${String(Z.status)})`;ft(G,Z.status,"SHARD_ERROR",Y,Ee=>({durationMs:be,error:{code:"SHARD_ERROR",message:Y,status:Z.status},functionPath:Ee.functionPath,...B,...je(X),ok:!1,shardKey:K}));return}const le=Array.isArray(ue.results)?ue.results:[],Re=new Set(le.map(Y=>Y.id));hr(G,K,X,be,new Map(le.map(Y=>[Y.id,Y])),Z.status),Ie.push(...le.map(({errorDetail:Y,...Ee})=>Ee));for(const Y of G)Re.has(Y.id)||Ie.push(ht(Y,Z.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const pt={"content-type":"application/json"},[mt]=Me;return Me.length===1&&mt!==void 0&&(pt["x-d1-bookmark"]=mt),Response.json({results:Ie},{headers:pt,status:200})},tr=async(o,s,l,u={},p={})=>{try{const R=l.__lunoraRef;if(typeof R!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ke(R);const{headers:v,identity:P}=await H(o,s,i,p.context),D={args:u,functionPath:R,shardKey:p.shardKey};await Se(D,P);const _=p.shardKey??r,A=Ae(s,o,p.waitUntil),B=()=>Oe(o,R,u,_,v,A),j=qe(D,e);return j&&e.x402Charge?await e.x402Charge(o,{functionPath:R,price:j.price},B,Je(p.waitUntil?{waitUntil:p.waitUntil}:p.context)):await B()}catch(R){return _t(R)}},dt=async(o,s,l)=>{const{observability:u}=e,p=Date.now(),R=we(16),v=we(8),P=qt(s),D=on(R,v,!0);try{const _=await l(D);return ie(u,{durationMs:Date.now()-p,functionPath:o,ok:!0,spanId:v,traceId:R},P),_}catch(_){throw ie(u,{...De(o,Date.now()-p,_,{}),spanId:v,traceId:R},P),_}finally{yt(u,P)}},ut=async(o,s,l,u)=>{g(s);const p=[],R=A=>A instanceof Error?A:new Error(String(A)),v=e.crons?.[o.cron];if(v)try{await v(o,s,l)}catch(A){p.push(R(A))}const P=await Be(o.cron,s,l,p,R,u),D=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron;if(D)try{await Xo(e,a,d,k(),o)}catch(A){p.push(R(A))}if(!v&&P===0&&!D){const A=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${o.cron}") fired but no cron handler is registered for that expression. Registered: ${A.length===0?"(none)":A.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[_]=p;if(p.length===1&&_)throw _;if(p.length>1)throw new AggregateError(p,`scheduled("${o.cron}") had ${String(p.length)} failure(s)`)},nr=gs({assertAdmin:$,dispatchScheduled:ut,queueHandler:e.queueHandler}),rr=async(o,s)=>{try{const l=o??{},u=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!u||u.length===0)return;await T(d,r,Ue(Ms,{outcome:s},{authorization:`Bearer ${u}`,"content-type":"application/json"}))}catch{}},or=async(o,s,l,u)=>{if(!e.authHandler)return;const p=e.authBasePath??Vt,R=Yt(l.pathname,p)?Nr(o):void 0;let v;try{v=await e.authHandler(R?.request??o)}catch(P){throw R?.overflowed()?new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413}):P}if(R?.overflowed())throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});if(v)return Ks(l.pathname,p)&&u.waitUntil?.(rr(s,v.status>=400?"fail":"ok")),v},ar=async({args:o,env:s,functionPath:l,request:u,shardKey:p,waitUntil:R})=>{sn(o,"REST");const v={functionPath:l,...p===void 0?{}:{shardKey:p}},{headers:P,identity:D}=await H(u,s,i);await Se(v,D);const _=p??r,A=Ae(s,u,R),B=()=>Oe(u,l,o,_,P,A),j=qe(v,e);return j&&e.x402Charge?e.x402Charge(u,{functionPath:l,price:j.price},B,Je({waitUntil:R})):B()},sr=Pr({functions:e.functions??{},invoke:ar,readJsonBody:ee,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),ve=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0;ri(ve);const ir={[Ls]: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"}}),[Us]:(o,s,l)=>zn(o,s,l),[Gt]:(o,s,l,u)=>Zn(o,s,u),[Ns]:(o,s,l,u)=>er(o,s,u),[vo]:(o,s,l,u)=>In(o,s,u),[Cs]:(o,s,l,u)=>xe(o,s,u),[Bs]:async o=>{M(o,"POST","ws-token"),$(o);const s=k();if(s===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await xo(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...V,...Un,...Cn,...Bn,...xn,...Hn,...Ln,...jn,...Mn,...$n,...Fn,...sr,...Mo({assertAdmin:$,getAuthAdmin:()=>e.authAdmin,parsePaging:Le,queryParameter:He,readJsonBody:ee})};let se=Et(e.security),lt=!1;const cr=o=>{lt||(lt=!0,se=Et(e.security,o??{}))},dr=async(o,s)=>{js(s)&&await I(o)},ur=(o,s)=>{if(!(s.pathname.startsWith(Ce)||e.authHandler!==void 0&&Yt(s.pathname,e.authBasePath??Vt))||o.method!=="POST"&&o.method!=="PUT")return;const u=Number(o.headers.get("content-length")??""),p=Ds[s.pathname]??an;if(Number.isFinite(u)&&u>p)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},lr=async(o,s,l)=>{rt.set(o,l);const u=new URL(o.url);ur(o,u);const p=await or(o,s,u,l);if(p)return p;if(ve){const _=`${o.method} ${u.pathname}`,A=ve[_]??ve[u.pathname];if(A)return A(o,s,l)}const R=nr[u.pathname];if(R)return R(o,s,l);const v=ir[u.pathname];if(v)return await dr(o,u.pathname),v(o,s,u,l);if(e.voiceAgents!==void 0&&u.pathname.startsWith(Wt))return Vn(o,s,u);if(u.pathname.startsWith(Ce))return new Response("Not found",{status:404});const P=await Wn(o,s,l);if(P&&P.status!==404)return P;const D=await e.authDiscoveryHandler?.(o);return D?(await P?.body?.cancel(),D):P??new Response("Not found",{status:404})};return{async fetch(o,s,l){e.passThroughOnException&&l.passThroughOnException?.(),cr(s),g(s);const u=Zr(o,se);if(u)return u;const p=eo(o,se);if(p)return Fe(p,o,se);try{const R=await lr(o,s,l);return Fe(R,o,se)}catch(R){return Fe(_t(R),o,se)}finally{yt(e.observability,qt(l))}},async queue(o,s,l){await dt(`queue:${Qs(o)}`,l,async u=>{await e.queue?.(o,s,l,{traceparent:u})})},async scheduled(o,s,l){await dt(`cron:${o.cron}`,l,async u=>{await ut(o,s,l,u)})},serverQuery:tr}},ai=e=>vn(e),si=e=>typeof e=="function"?{fetch:e}:e,ii=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,ci=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},Ni=(e,t)=>{const n=si(e),{email:r,queue:a,scheduled:i}=ci(e),d=h=>{const b={...ai({...h,httpRouter:n})};return i!==void 0&&!ii(h)&&(b.scheduled=async(T,S,k)=>{await i(T,S,k)}),a!==void 0&&h.queue===void 0&&(b.queue=async(T,S,k)=>{await a(T,S,k)}),r!==void 0&&(b.email=async(T,S,k)=>{await r(T,S,k)}),b};if(typeof t!="function")return d(t);const f=t;return{fetch:(h,m,b)=>d(f(m)).fetch(h,m,b),queue:(h,m,b)=>d(f(m)).queue?.(h,m,b)??Promise.resolve(),scheduled:(h,m,b)=>d(f(m)).scheduled(h,m,b),serverQuery:(h,m,b,T,S)=>d(f(m)).serverQuery(h,m,b,T,S),...r===void 0?{}:{email:(h,m,b)=>d(f(m)).email?.(h,m,b)??Promise.resolve()}}},di=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new c("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},Ui=(e={})=>(t,n,r)=>vn(di(e,n)).fetch(t,n,r??gr),Ci=e=>e;export{tt as COPY_AUTH_TO_JURISDICTION_OP,Pt as GET_AUTH_AUDIT_LOG_OP,gr as NOOP_EXECUTION_CONTEXT,gn as PURGE_UNPINNED_AUTH_OP,Hi as composeIdentityResolvers,ai as composeWorker,Ui as createLunoraHandler,vn as createWorker,Ci as defineRpcEnvelope,Zs as probeRelayCount,di as resolveLunoraOptions,Li as routeIdentityResolvers,Ni as withFrameworkWorker};