@lunora/runtime 1.0.0-alpha.98 → 1.0.0-alpha.99

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
@@ -2588,6 +2588,13 @@ interface RateLimiterLike {
2588
2588
  * to stop; those deployments pool into {@link UNRESOLVED_IP_BUCKET} instead, and
2589
2589
  * should pass `key` to identify callers by something they cannot forge.
2590
2590
  *
2591
+ * An origin fronted by a proxy that stamps a client address can instead declare
2592
+ * that header as `trustedClientIpHeader` and get per-IP buckets back, at the cost
2593
+ * of asserting the header is unwritable by callers — the same assertion, and the
2594
+ * same consequence for getting it wrong, as `WorkerOptions.trustedClientIpHeader`
2595
+ * (which governs `ctx.ip`). Declare it in both places or the two disagree about
2596
+ * who a request came from.
2597
+ *
2591
2598
  * A rate rejection becomes a `429` with a `Retry-After` header (seconds, ceil of
2592
2599
  * the limiter's ms). A deny-list hit becomes a `403` and no `Retry-After` —
2593
2600
  * matching both `@lunora/ratelimit` entry points, and the only honest answer for
@@ -2600,6 +2607,7 @@ interface RateLimiterLike {
2600
2607
  declare const createRestRateLimit: (limiter: RateLimiterLike, options: {
2601
2608
  key?: (request: Request, functionPath: string) => string | undefined;
2602
2609
  name: string;
2610
+ trustedClientIpHeader?: string;
2603
2611
  }) => RestRateLimit;
2604
2612
  /** Per-header overrides for {@link SecurityHeadersOptions}. `false` omits the header. */
2605
2613
  interface SecurityHeadersOptions {
@@ -4170,6 +4178,51 @@ interface WorkerOptions {
4170
4178
  * endpoint. When omitted, the sync feed covers only shard-local tables.
4171
4179
  */
4172
4180
  syncGlobals?: GlobalCdcSyncFunction;
4181
+ /**
4182
+ * The header carrying the caller's IP, for an origin that is fronted by a
4183
+ * proxy. **Default: unset**, and unset is the safe answer — leave it alone
4184
+ * unless the paragraph below describes your deployment exactly.
4185
+ *
4186
+ * On Cloudflare the runtime already reads `CF-Connecting-IP`, which the edge
4187
+ * stamps over anything the client sent, and this option is ignored. Anywhere
4188
+ * else (`target: "node"`, a container, a bare process) nothing overwrites
4189
+ * that header, so the runtime resolves no IP at all: `ctx.ip` is `undefined`
4190
+ * and the REST limiter's default key pools every caller into one
4191
+ * `no-trusted-ip` bucket. That is correct for a directly-exposed host, and
4192
+ * wrong for an origin sitting BEHIND a proxy that does stamp a client address
4193
+ * — there a real per-IP limit collapses into one bucket a single client can
4194
+ * exhaust for everybody. Naming the header restores per-IP limiting:
4195
+ *
4196
+ * ```ts
4197
+ * trustedClientIpHeader: "cf-connecting-ip" // origin behind Cloudflare
4198
+ * ```
4199
+ *
4200
+ * ## What you are asserting
4201
+ *
4202
+ * That the named header is set by infrastructure **you control**, on every
4203
+ * request, replacing whatever the caller sent — and therefore that no caller
4204
+ * can choose its value. A proxy that only _forwards_ or _appends_ to a
4205
+ * client-supplied header is not such a thing, and neither is one the origin
4206
+ * can be reached around: if any route bypasses the proxy (a `*.workers.dev`
4207
+ * route left enabled, a load-balancer health port, the origin's own IP
4208
+ * reachable from the internet), a caller reaches this worker with the header
4209
+ * they typed.
4210
+ *
4211
+ * If that assertion is untrue, this is worse than leaving it unset: an
4212
+ * attacker rotates the header for a fresh rate-limit bucket per request — so
4213
+ * the limit stops applying to exactly the traffic it exists to stop, while
4214
+ * still reading as enforced — and forges the `ctx.ip` every procedure keys
4215
+ * on and every audit row records. Lock the origin to the proxy first.
4216
+ *
4217
+ * A value containing a comma is refused rather than read, because that is an
4218
+ * appended forwarding chain (`x-forwarded-for: <client>, <hop>`) whose
4219
+ * leftmost entry is client-written. Declare a header your proxy replaces.
4220
+ *
4221
+ * This governs `ctx.ip` only. `createRestRateLimit` takes the same option for
4222
+ * the REST limiter's default key; set both, or the two disagree about who a
4223
+ * request came from.
4224
+ */
4225
+ trustedClientIpHeader?: string;
4173
4226
  /**
4174
4227
  * Who may hand this worker a trace to join. Controls whether an inbound W3C
4175
4228
  * `traceparent` is continued — adopting its trace id, parenting this
package/dist/index.d.ts CHANGED
@@ -2588,6 +2588,13 @@ interface RateLimiterLike {
2588
2588
  * to stop; those deployments pool into {@link UNRESOLVED_IP_BUCKET} instead, and
2589
2589
  * should pass `key` to identify callers by something they cannot forge.
2590
2590
  *
2591
+ * An origin fronted by a proxy that stamps a client address can instead declare
2592
+ * that header as `trustedClientIpHeader` and get per-IP buckets back, at the cost
2593
+ * of asserting the header is unwritable by callers — the same assertion, and the
2594
+ * same consequence for getting it wrong, as `WorkerOptions.trustedClientIpHeader`
2595
+ * (which governs `ctx.ip`). Declare it in both places or the two disagree about
2596
+ * who a request came from.
2597
+ *
2591
2598
  * A rate rejection becomes a `429` with a `Retry-After` header (seconds, ceil of
2592
2599
  * the limiter's ms). A deny-list hit becomes a `403` and no `Retry-After` —
2593
2600
  * matching both `@lunora/ratelimit` entry points, and the only honest answer for
@@ -2600,6 +2607,7 @@ interface RateLimiterLike {
2600
2607
  declare const createRestRateLimit: (limiter: RateLimiterLike, options: {
2601
2608
  key?: (request: Request, functionPath: string) => string | undefined;
2602
2609
  name: string;
2610
+ trustedClientIpHeader?: string;
2603
2611
  }) => RestRateLimit;
2604
2612
  /** Per-header overrides for {@link SecurityHeadersOptions}. `false` omits the header. */
2605
2613
  interface SecurityHeadersOptions {
@@ -4170,6 +4178,51 @@ interface WorkerOptions {
4170
4178
  * endpoint. When omitted, the sync feed covers only shard-local tables.
4171
4179
  */
4172
4180
  syncGlobals?: GlobalCdcSyncFunction;
4181
+ /**
4182
+ * The header carrying the caller's IP, for an origin that is fronted by a
4183
+ * proxy. **Default: unset**, and unset is the safe answer — leave it alone
4184
+ * unless the paragraph below describes your deployment exactly.
4185
+ *
4186
+ * On Cloudflare the runtime already reads `CF-Connecting-IP`, which the edge
4187
+ * stamps over anything the client sent, and this option is ignored. Anywhere
4188
+ * else (`target: "node"`, a container, a bare process) nothing overwrites
4189
+ * that header, so the runtime resolves no IP at all: `ctx.ip` is `undefined`
4190
+ * and the REST limiter's default key pools every caller into one
4191
+ * `no-trusted-ip` bucket. That is correct for a directly-exposed host, and
4192
+ * wrong for an origin sitting BEHIND a proxy that does stamp a client address
4193
+ * — there a real per-IP limit collapses into one bucket a single client can
4194
+ * exhaust for everybody. Naming the header restores per-IP limiting:
4195
+ *
4196
+ * ```ts
4197
+ * trustedClientIpHeader: "cf-connecting-ip" // origin behind Cloudflare
4198
+ * ```
4199
+ *
4200
+ * ## What you are asserting
4201
+ *
4202
+ * That the named header is set by infrastructure **you control**, on every
4203
+ * request, replacing whatever the caller sent — and therefore that no caller
4204
+ * can choose its value. A proxy that only _forwards_ or _appends_ to a
4205
+ * client-supplied header is not such a thing, and neither is one the origin
4206
+ * can be reached around: if any route bypasses the proxy (a `*.workers.dev`
4207
+ * route left enabled, a load-balancer health port, the origin's own IP
4208
+ * reachable from the internet), a caller reaches this worker with the header
4209
+ * they typed.
4210
+ *
4211
+ * If that assertion is untrue, this is worse than leaving it unset: an
4212
+ * attacker rotates the header for a fresh rate-limit bucket per request — so
4213
+ * the limit stops applying to exactly the traffic it exists to stop, while
4214
+ * still reading as enforced — and forges the `ctx.ip` every procedure keys
4215
+ * on and every audit row records. Lock the origin to the proxy first.
4216
+ *
4217
+ * A value containing a comma is refused rather than read, because that is an
4218
+ * appended forwarding chain (`x-forwarded-for: <client>, <hop>`) whose
4219
+ * leftmost entry is client-written. Declare a header your proxy replaces.
4220
+ *
4221
+ * This governs `ctx.ip` only. `createRestRateLimit` takes the same option for
4222
+ * the REST limiter's default key; set both, or the two disagree about who a
4223
+ * request came from.
4224
+ */
4225
+ trustedClientIpHeader?: string;
4173
4226
  /**
4174
4227
  * Who may hand this worker a trace to join. Controls whether an inbound W3C
4175
4228
  * `traceparent` is continued — adopting its trace id, parenting this
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-2d_iJXPf.mjs";import{composeWorker as x,createLunoraHandler as S,createWorker as l,defineRpcEnvelope as u,resolveLunoraOptions as _,withFrameworkWorker as d}from"./packem_shared/composeWorker-TSwsCtpP.mjs";import{createCrossShardRelationCapabilities as y}from"./packem_shared/createCrossShardRelationCapabilities-D_S3beMO.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as O,SHARD_REGISTRY_DO_NAME as b,createDynamicShardRegistry as A}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as T,toErrorResponse as h}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as P,a as g,d as v,r as I,b as D,s as M,w as F}from"./packem_shared/export-tap-CAyZ2TWC.mjs";import{HEALTH_PATH as G,HEALTH_READY_PATH as K,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-D0i8LhwT.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as J,a as Z}from"./packem_shared/observability-B1hLjwgx.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-JUcPmzoo.mjs";import{D as pe,c as ce}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as fe,createStaticShardRegistry as Ee}from"./packem_shared/createQueryCoordinator-DlWITOu1.mjs";import{applyJurisdiction as xe,resolveShard as Se}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as _e,b as de}from"./packem_shared/rest-cache-D1BlbZb1.mjs";import{a as ye,b as Ce,c as Oe,r as be}from"./packem_shared/rest-routes-CyXGd_yB.mjs";import{decorateResponse as Le,enforceOrigin as Te,handleCorsPreflight as he,resolveSecurity as He}from"./packem_shared/decorateResponse-Y2sCM0w1.mjs";import{createShardClient as ge}from"./packem_shared/createShardClient-CAv0OrEW.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ie}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Me}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ne}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ke,routeIdentityResolvers as Ue}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,O as DEFAULT_REGISTRY_CACHE_TTL_MS,G as HEALTH_PATH,K as HEALTH_READY_PATH,Me as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,T as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,b as SHARD_REGISTRY_DO_NAME,Ie as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,xe as applyJurisdiction,ue as applyRestCache,ye as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ke as composeIdentityResolvers,x as composeWorker,oe as consoleSink,y as createCrossShardRelationCapabilities,A as createDynamicShardRegistry,P as createKvCursorStore,S as createLunoraHandler,g as createMemoryCursorStore,ce as createPipelineLogReader,fe as createQueryCoordinator,Oe as createRestRateLimit,ge as createShardClient,Ee as createStaticShardRegistry,l as createWorker,B as d1Probe,Le as decorateResponse,v as defineExportSink,u as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,Te as enforceOrigin,he as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,I as r2Sink,_e as requestCarriesCredentials,j as resolveLogArchiveFromEnv,_ as resolveLunoraOptions,He as resolveSecurity,Se as resolveShard,de as restCacheHeaders,be as restSurfaceFromRegistry,Ue as routeIdentityResolvers,D as runExportTap,M as sanitizeChange,se as sentrySink,f as toAirbyteMessages,h as toErrorResponse,E as toFivetranResponse,F as webhookExportSink,ie as webhookSink,d as withFrameworkWorker};
1
+ import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-2d_iJXPf.mjs";import{composeWorker as x,createLunoraHandler as S,createWorker as l,defineRpcEnvelope as u,resolveLunoraOptions as _,withFrameworkWorker as d}from"./packem_shared/composeWorker-ngC3Upv5.mjs";import{createCrossShardRelationCapabilities as y}from"./packem_shared/createCrossShardRelationCapabilities-D_S3beMO.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as O,SHARD_REGISTRY_DO_NAME as b,createDynamicShardRegistry as A}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as T,toErrorResponse as h}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as P,a as g,d as v,r as I,b as D,s as M,w as F}from"./packem_shared/export-tap-CAyZ2TWC.mjs";import{HEALTH_PATH as G,HEALTH_READY_PATH as K,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-D0i8LhwT.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as J,a as Z}from"./packem_shared/observability-B1hLjwgx.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-JUcPmzoo.mjs";import{D as pe,c as ce}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as fe,createStaticShardRegistry as Ee}from"./packem_shared/createQueryCoordinator-DlWITOu1.mjs";import{applyJurisdiction as xe,resolveShard as Se}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as _e,b as de}from"./packem_shared/rest-cache-D1BlbZb1.mjs";import{a as ye,b as Ce,c as Oe,r as be}from"./packem_shared/rest-routes-DfcUfNc-.mjs";import{decorateResponse as Le,enforceOrigin as Te,handleCorsPreflight as he,resolveSecurity as He}from"./packem_shared/decorateResponse-Y2sCM0w1.mjs";import{createShardClient as ge}from"./packem_shared/createShardClient-CAv0OrEW.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ie}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Me}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ne}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ke,routeIdentityResolvers as Ue}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,O as DEFAULT_REGISTRY_CACHE_TTL_MS,G as HEALTH_PATH,K as HEALTH_READY_PATH,Me as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,T as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,b as SHARD_REGISTRY_DO_NAME,Ie as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,xe as applyJurisdiction,ue as applyRestCache,ye as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ke as composeIdentityResolvers,x as composeWorker,oe as consoleSink,y as createCrossShardRelationCapabilities,A as createDynamicShardRegistry,P as createKvCursorStore,S as createLunoraHandler,g as createMemoryCursorStore,ce as createPipelineLogReader,fe as createQueryCoordinator,Oe as createRestRateLimit,ge as createShardClient,Ee as createStaticShardRegistry,l as createWorker,B as d1Probe,Le as decorateResponse,v as defineExportSink,u as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,Te as enforceOrigin,he as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,I as r2Sink,_e as requestCarriesCredentials,j as resolveLogArchiveFromEnv,_ as resolveLunoraOptions,He as resolveSecurity,Se as resolveShard,de as restCacheHeaders,be as restSurfaceFromRegistry,Ue as routeIdentityResolvers,D as runExportTap,M as sanitizeChange,se as sentrySink,f as toAirbyteMessages,h as toErrorResponse,E as toFivetranResponse,F as webhookExportSink,ie as webhookSink,d as withFrameworkWorker};
@@ -1 +1 @@
1
- import"./rest-cache-D1BlbZb1.mjs";import{a,b as o,c as i,r as m}from"./rest-routes-CyXGd_yB.mjs";import"./method-guard-BG_vJNTl.mjs";export{a as argsFromQuery,o as buildRestRoutes,i as createRestRateLimit,m as restSurfaceFromRegistry};
1
+ import"./rest-cache-D1BlbZb1.mjs";import{a,b as o,c as i,r as m}from"./rest-routes-DfcUfNc-.mjs";import"./method-guard-BG_vJNTl.mjs";export{a as argsFromQuery,o as buildRestRoutes,i as createRestRateLimit,m as restSurfaceFromRegistry};
@@ -0,0 +1,6 @@
1
+ import{isLunoraError as Ln,toErrorBody as Mn}from"@lunora/errors";import{e as Mt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as jn}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as $n,f as Kn}from"./base64-Bl1_r2k1.mjs";import{e as Fn,a as Gn}from"./identity-header-C4Z5pldl.mjs";import{o as Ie,b as jt,p as Qn,m as zn,d as Wn,a as Vn,r as Jn}from"./otlp-resource-JKBCWf6c.mjs";import{e as ke,d as Ve,a as qn}from"./wire-codec-BLvSm5Mn.mjs";import{d as te,e as he,M as $t,b as Yn,f as Xn,g as Kt,t as Zn,h as Ft}from"./rest-routes-DfcUfNc-.mjs";import{LunoraError as c,toErrorResponse as dt}from"./LunoraError-DksAgIpa.mjs";import{a as j,m as we}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as Xe,BACKUP_KEY_PREFIX as Ze,isBackupManifestKey as er,backupObjectKeyOfManifest as Gt,backupObjectKey as tr,backupManifestKey as nr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as rr,buildStorageAdminRoutes as or,STORAGE_UPLOAD_MAX_BODY_BYTES as ar,STORAGE_PATH as sr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{b as ir,e as cr,f as ut,g as dr,h as ur}from"./export-tap-CAyZ2TWC.mjs";import{buildHealthRoutes as lr,durableObjectProbe as hr,d1Probe as fr,presenceProbe as Le}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as pr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Ms,routeIdentityResolvers as js}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as mr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{r as wr,f as lt,a as ce}from"./observability-B1hLjwgx.mjs";import{resolveShard as ge,applyJurisdiction as ht}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as ft,handleCorsPreflight as gr,enforceOrigin as yr,decorateResponse as Me,enforceWebSocketOrigin as pt}from"./decorateResponse-Y2sCM0w1.mjs";const br=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},Qt="__lunoraBranch",_r=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Qt),Rr=`may not contain the reserved workflow branch-marker key ("${Qt}")`,Er=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}},et=(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 s=a<e.length?e.charCodeAt(a):0,u=a<t.length?t.charCodeAt(a):0;r|=s^u}return r===0},Sr=/already[\s_-]?exists/iu,Ar=e=>Sr.test(e instanceof Error?e.message:String(e)),Tr=(e,t,n,r)=>{const a=e.get(t);if(a!==void 0)return a;Mt(e,r);const s=n().catch(u=>{throw e.get(t)===s&&e.delete(t),u});return e.set(t,s),s},tt=new TextEncoder,Or=Array.from({length:32},(e,t)=>t);new RegExp(`[${Or.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const vr=64,kr=new Map,zt=async e=>Tr(kr,e,async()=>crypto.subtle.importKey("raw",tt.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),vr),Wt=async(e,t)=>{const n=await zt(e),r=await crypto.subtle.sign("HMAC",n,tt.encode(t));return $n(new Uint8Array(r))},Ir=async(e,t,n)=>{const r=await zt(e);return crypto.subtle.verify("HMAC",r,n,tt.encode(t))},Pr=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Pr);const Nr=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Dr=-100,Ur=15,Cr=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Nr.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Ur?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Dr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},mt=e=>{const t=e.cf;return t===void 0?void 0:Cr(t)},Je="::relay::",Br=(e,t)=>`${e}${Je}${String(t)}`,qe="::replica::",xr=(e,t)=>`${e}${qe}${t}`,Hr=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Lr=new Set(["1","enabled","on","true","yes"]),Mr=new Set(["0","disabled","false","no","off"]),jr=(e,t)=>{const n=(e??"").trim().toLowerCase();return Lr.has(n)?!0:Mr.has(n)?!1:t},Vt="v1",$r=6e4,Kr=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??$r),r=`${Vt}.${String(n)}`,a=await Wt(e,r);return{expiresAtMs:n,token:`${r}.${a}`}},Fr=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,s,u]=r;if(a!==Vt||u.length===0)return!1;const h=Number(s);if(!Number.isFinite(h)||h<=n)return!1;let f;try{f=Kn(u)}catch{return!1}return Ir(e,`${a}.${s}`,f)},P="/_lunora/admin/auth",Gr={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},D=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},le=(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},Jt=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,je=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},wt=e=>{const t=Jt(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},gt=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(s=>typeof s=="string")&&(n[r]=a);return n},Qr={[`${P}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${P}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${P}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${P}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${P}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${P}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${P}/sign-up-invitations/create`]:{build:({body:e})=>({email:D(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:re(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${P}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:D(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:je(e,"data"),email:D(e,"email"),name:D(e,"name"),password:re(e,"password"),role:Jt(e.role)}),http:"POST",method:"createUser"},[`${P}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:D(e,"userId")}},http:"POST",method:"updateUser"},[`${P}/users/role`]:{build:({body:e})=>({role:wt(e),userId:D(e,"userId")}),http:"POST",method:"setRole"},[`${P}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:D(e,"userId")}),http:"POST",method:"banUser"},[`${P}/users/unban`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"unbanUser"},[`${P}/users/password`]:{build:({body:e})=>({newPassword:D(e,"newPassword"),userId:D(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${P}/users/remove`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${P}/users/impersonate`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"impersonateUser"},[`${P}/sessions/revoke`]:{build:({body:e})=>({sessionId:D(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${P}/sessions/revoke-all`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${P}/accounts/unlink`]:{build:({body:e})=>({accountId:D(e,"accountId"),userId:D(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${P}/two-factor/disable`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${P}/passkeys/delete`]:{build:({body:e})=>({passkeyId:D(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${P}/organizations/members/remove`]:{build:({body:e})=>({memberId:D(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${P}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:D(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${P}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:je(e,"metadata"),name:D(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:je(e,"metadata"),name:re(e,"name"),organizationId:D(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${P}/organizations/remove`]:{build:({body:e})=>({organizationId:D(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${P}/organizations/members/add`]:{build:({body:e})=>({organizationId:D(e,"organizationId"),role:re(e,"role"),userId:D(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:D(e,"email"),inviterId:re(e,"inviterId"),organizationId:D(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:D(e,"memberId"),role:wt(e)}),http:"POST",method:"updateMemberRole"},[`${P}/organizations/teams/create`]:{build:({body:e})=>({name:D(e,"name"),organizationId:D(e,"organizationId")}),http:"POST",method:"createTeam"},[`${P}/organizations/teams/update`]:{build:({body:e})=>({name:D(e,"name"),teamId:D(e,"teamId")}),http:"POST",method:"updateTeam"},[`${P}/organizations/teams/remove`]:{build:({body:e})=>({teamId:D(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${P}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:D(e,"teamId"),userId:D(e,"userId")}),http:"POST",method:"addTeamMember"},[`${P}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:D(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${P}/organizations/roles/create`]:{build:({body:e})=>({organizationId:D(e,"organizationId"),permission:gt(e),role:D(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:gt(e),roleId:D(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${P}/organizations/roles/remove`]:{build:({body:e})=>({roleId:D(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},zr=e=>{const t=async a=>{try{return await a()}catch(s){if(s instanceof c)throw s;const u=s,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",s),new c("auth admin operation failed",{code:h,status:Gr[h]??500})}},n=async(a,s)=>{if(e.assertAdmin(a),a.method!==s.http)throw new c(`Auth admin endpoint requires ${s.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[s.method];if(h===void 0)throw new c(`auth admin does not support \`${s.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(a.url),w={body:s.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:k=>e.queryParameter(f,k)},S=s.build(w),A=await t(()=>h(S));return Response.json(s.returns==="void"?{ok:!0}:A,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[a,s]of Object.entries(Qr))r[a]=u=>n(u,s);return r},yt="__lunora_admin__:getAuthAuditLog",bt=e=>typeof e=="string"&&e!==""?e:void 0,_t=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Wr=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 s=bt(r.actorId),u=bt(r.event),h=_t(r.sinceSeq),f=_t(r.limit),w={...s===void 0?{}:{actorId:s},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...f===void 0?{}:{limit:f}};let S;try{S=await a.read(w)}catch(k){throw k instanceof c?k:(console.error("[lunora] auth audit read failed:",k),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const A={entries:S};return Response.json({result:ke(A)},{headers:{"content-type":"application/json"},status:200})},Vr=(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}},Jr=async(e,t,n,r,a,s,u)=>{if(n!==void 0&&r.length===0)return;const h=await e.orchestrateExport(s,{args:{tables:r},defaultShardKey:u,headers:t,tables:r});for(const f of h.shards)if(!f.error)for(const w of f.rows??[])a(w)},qt=async(e,t,n,r,a,s)=>{const u=r??e.listSchemaTables?.();r===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:h,shardLocalTables:f}=Vr(e,u);await Jr(t,n,u,f,a,s,e.defaultShardKey??"__root__");const w=e.exportGlobals;if((r===void 0||h.length>0)&&w)for await(const A of w({tables:h}))a(A)},qr=new TextEncoder,Yr=1e3,Yt=10,Xr=200,Rt=8,Xt="lunoraBackupCron",Et=24*1048576,St=e=>{const t=e.slice(0,Yt).map(r=>Gt(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Zr=(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},nt=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let s;for(let u=0;u<Yr;u+=1){const h=await e.list({cursor:s,include:["customMetadata"],prefix:t});for(const f of h.objects)er(f.key)&&f.customMetadata?.[Xt]===r&&a.push(f.key);if(!h.truncated||h.cursor===void 0)break;s=h.cursor}return{eligible:a.length,stale:a.toSorted((u,h)=>h.localeCompare(u)).slice(n)}},eo=async(e,t,n,r,a)=>{const{stale:s}=await nt(e,t,n,r),u=new Set(a),h=s.filter(g=>u.has(g)),f=h.slice(0,Xr),w=s.length-f.length,S=a.length-h.length;if(f.length===0)return{deleted:[],failed:[],ignored:S,remaining:w};const A=[],k=[];for(let g=0;g<f.length;g+=Rt){const _=await Promise.allSettled(f.slice(g,g+Rt).map(async R=>(await e.delete(Gt(R)),await e.delete(R),R)));for(const[R,p]of _.entries())p.status==="fulfilled"?A.push(p.value):k.push(f[g+R])}return A.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(A.length)}: ${St(A)}`),k.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(k.length)}: ${St(k)}`),{deleted:A,failed:k,ignored:S,remaining:w}},to=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=Xe(e.backupPrefix??Ze),r=e.backupCron,{eligible:a,stale:s}=r===void 0?{eligible:0,stale:[]}:await nt(t,n,e.backupRetain,r);return{cron:r,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:s}},no=async(e,t,n,r)=>{const a=e.backupStore,s=e.queryCoordinator;if(!a)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!s)throw new c("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!n||n.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 u={authorization:`Bearer ${n}`,"content-type":"application/json"},h=e.backupTables;let f=0,w=0,S=[];await qt(e,s,u,h,U=>{const M=qr.encode(`${JSON.stringify(U)}
2
+ `);if(f+=1,w+=M.byteLength,w>Et)throw new c(`scheduled backup reached ${String(w)} bytes of NDJSON, past the ${String(Et)}-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});S.push(M)},t);const k=Xe(e.backupPrefix??Ze),g=new Date(r.scheduledTime).toISOString(),_=tr(k,g),R=Zr(S,w);S=[];const p=rr(await crypto.subtle.digest("SHA-256",R));await a.put(_,R,{httpMetadata:{contentType:"application/x-ndjson"},sha256:p});const T={bytes:w,createdAt:g,cron:r.cron,file:_,id:g,rows:f,scheduledTime:r.scheduledTime,sha256:p,...h?{tables:h.join(",")}:{}};await a.put(nr(_),`${JSON.stringify(T,void 0,2)}
3
+ `,{customMetadata:{[Xt]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:U}=await nt(a,k,e.backupRetain,r.cron);if(U.length>0){const M=U.slice(0,Yt),N=U.length-M.length;console.info(`[lunora] backup retention: ${String(U.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${M.join(", ")}${N>0?` (+${String(N)} more)`:""}`)}}catch(U){console.warn(`[lunora] backup ${_} was written, but the retention report failed:`,U)}},ro=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 eo(n,Xe(e.backupPrefix??Ze),a,r,t)},oo="/_lunora/admin/backup/retention",ao="/_lunora/admin/backup/prune",so=e=>{const{options:t,readJsonBody:n,requireAdminOption:r}=e,a=(h,f)=>{r(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},s=async h=>(j(h,"GET","Backup-retention"),a(h,"retention preview"),Response.json(await to(t),{headers:{"cache-control":"no-store"}})),u=async h=>{j(h,"POST","Backup-prune"),a(h,"prune");const{confirm:f}=await n(h);if(!Array.isArray(f)||f.some(w=>typeof w!="string"))throw new 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 ro(t,f),{headers:{"cache-control":"no-store"}})};return{[ao]:u,[oo]:s}},At=500,io=(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});return{entry:{args:r.args===void 0?{}:r.args,clientId:typeof r.clientId=="string"?r.clientId:void 0,clientSeq:typeof r.clientSeq=="number"?r.clientSeq:void 0,functionPath:r.functionPath,id:typeof r.id=="number"?r.id:t,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:n}},co=(e,t)=>{if(e.length>At)throw new c(`RPC batch exceeds the ${String(At)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map;for(const[r,a]of e.entries()){const{entry:s,shardKey:u}=io(a,r,t),h=n.get(u)??[];h.push(s),n.set(u,h)}return n},uo="/_lunora/admin/export",lo="/_lunora/admin/import",ho="/_lunora/admin/sync",fo="/_lunora/admin/connector/sync",po="/_lunora/admin/apply",mo="/_lunora/admin/export-tap/run",wo=new TextEncoder,go=async e=>{const n=await he(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}},$e=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,yo=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:a,knownTables:s,queryCoordinator:u,assertAdmin:h,requireAdminOption:f,resolveForwardContext:w,shardDO:S,streamExportRows:A,streamingImport:k,syncGlobals:g}=e,_=async(N,K)=>{const $=we(N,["POST"]);if($)return $;const V=f(N,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),B=await go(N),{headers:J}=await w(N,K),F=new ReadableStream({async pull(q){const ee=L=>{q.enqueue(wo.encode(`${JSON.stringify(L)}
4
+ `))};try{await A(V,J,B.tables,ee),q.close()}catch(L){q.error(L)}}});return new Response(F,{headers:{"content-type":"application/x-ndjson"},status:200})},R=async(N,K)=>{const $=we(N,["POST"]);if($)return $;const V=f(N,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),B=await te(N),J=typeof B.cursors=="object"&&B.cursors!==null?B.cursors:{},F=typeof B.limit=="number"?B.limit:void 0,q=typeof B.globalCursor=="number"?B.globalCursor:0,ee=$e(B.tables),{headers:L}=await w(N,K),Y=ee??s(),G=await V.orchestrateCdcSync(S,{cursors:J,defaultShardKey:n,headers:L,limit:F,tables:Y}),fe=g?await g({limit:F,sinceSeq:q}):void 0;return Response.json({global:fe,shards:G.shards},{status:200})},p=async(N,K)=>{const $=we(N,["POST"]);if($)return $;const V=f(N,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),B=await te(N),J=cr(B.cursor),F=typeof B.limit=="number"&&B.limit>0?B.limit:void 0,q=$e(B.tables),{headers:ee}=await w(N,K),L=q??s(),Y=await V.orchestrateCdcSync(S,{cursors:J.s,defaultShardKey:n,headers:ee,limit:F,tables:L}),G=[],fe={...J.s};let ae=!1;for(const se of Y.shards)ae=ut(G,se.changes??[],ur(F))||ae,fe[se.shardKey]=se.cursor;let _e=J.g;if(g){const se=await g({limit:F,sinceSeq:J.g});ae=ut(G,se.changes,F)||ae,_e=se.cursor}const Pe=dr({g:_e,s:fe,v:1}),Ne={changes:G,hasMore:ae,nextCursor:Pe};return Response.json(Ne,{status:200})},T=async(N,K)=>{const $=we(N,["POST"]);if($)return $;const V=f(N,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),B=await te(N),F=(Array.isArray(B.batches)?B.batches:[]).map(G=>G).filter(G=>G!==null&&typeof G=="object"&&typeof G.shardKey=="string"&&Array.isArray(G.changes)),q=Array.isArray(B.globalChanges)?B.globalChanges:[],{headers:ee}=await w(N,K),L=await V.orchestrateApplyCdc(S,{batches:F,headers:ee}),Y=q.length>0&&t?await t({changes:q}):0;return Response.json({applied:L.applied+Y,failed:L.failed,ok:L.ok},{status:200})},U=async(N,K)=>{const $=we(N,["POST"]);if($)return $;h(N);const{headers:V}=await w(N,K),B=await k(N,V);return Response.json(B,{headers:{"content-type":"application/json"},status:B.failed.length>0?207:200})},M=async(N,K)=>{const $=we(N,["POST"]);if($)return $;const V=f(N,u,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(a===void 0||Object.keys(a).length===0||r===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const B=await te(N),J=typeof B.sink=="string"?B.sink:void 0,F=typeof B.limit=="number"&&B.limit>0?B.limit:void 0,q=$e(B.tables);if(J===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const ee=a[J];if(ee===void 0)throw new c(`Export-tap sink "${J}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:L}=await w(N,K),Y=q??s(),G=await ir({coordinator:V,cursorStore:r,defaultShardKey:n,headers:L,limit:F,shardDO:S,sink:ee,tables:Y});return Response.json(G,{headers:{"content-type":"application/json"},status:200})};return{[po]:T,[fo]:p,[uo]:_,[mo]:M,[lo]:U,[ho]:R}},bo=(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}},_o=(e,t,n,r,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const s=e[n.mode.field];return s==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 s=="string"?s:JSON.stringify(s)}}return{ok:!0,shardKey:r}},Ro=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],a=[],s=new Map;let u=0,h=0;const f=e.body.getReader(),w=new TextDecoder;let S="",A=0;const k=g=>{h+=1;const _=g.trim();if(_.length===0)return;u+=1;const R=bo(_,h);if(!R.ok){r.push(R.error);return}const{doc:p,table:T}=R,U=t.resolveTableSharding?.(T);if(U?.mode.kind==="global"){a.push({doc:p,line:h,table:T});return}const M=_o(p,T,U,n,h);if(!M.ok){r.push(M.error);return}const N=s.get(M.shardKey);N?N.rows.push({doc:p,table:T}):s.set(M.shardKey,{rows:[{doc:p,table:T}],shardKey:M.shardKey,startLine:h})};for(;;){const{done:g,value:_}=await f.read();if(g)break;if(_&&(A+=_.byteLength,A>$t))throw await f.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});S+=w.decode(_,{stream:!0});let R=S.indexOf(`
5
+ `);for(;R!==-1;){const p=S.slice(0,R);S=S.slice(R+1),k(p),R=S.indexOf(`
6
+ `)}}return S.length>0&&k(S),{errors:r,globalRows:a,perShard:s,received:u}},Eo=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),Tt=(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},So=async(e,t,n,r)=>{const a=t.defaultShardKey??"__root__",{errors:s,globalRows:u,perShard:h,received:f}=await Ro(e,t,a),w={conflicts:0,errors:s,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 A=t.queryCoordinator;if(!A)throw new c("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const k=await A.orchestrateImport(r,{batches:[...h.values()],headers:n});Tt(w,k),w.failed.push(...Eo(k.shards))}if(u.length>0)if(t.importGlobals){const A=u[0]?.line??1,k=await t.importGlobals({rows:u,startLine:A});Tt(w,k)}else for(const A of u)w.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:A.line,message:`row targets global table "${A.table}" but no \`importGlobals\` is configured`,table:A.table});return{conflicts:w.conflicts,errors:w.errors,failed:w.failed,inserted:w.inserted,received:f,...S.length>0?{warnings:S}:{}}},Ke=e=>typeof e=="object"&&e!==null?e:{},Fe=e=>typeof e.kind=="string"?e.kind:"unknown",Ao=(e,t)=>{let n=Ke(t),r=!1;Fe(n)==="optional"&&(r=!0,n=Ke(n._meta?.inner));const a=Fe(n),s=n._meta??{},u={kind:a,name:e,optional:r};if(a==="id"&&typeof s.tableName=="string"&&(u.table=s.tableName),a==="array"){const h=Fe(Ke(s.inner));h!=="unknown"&&(u.element=h)}return u},To=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>Ao(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),Oo="/_lunora/admin/functions",vo="/_lunora/admin/cron-jobs",ko="/_lunora/admin/openapi",Io="/_lunora/admin/openrpc",Po="/_lunora/admin/global/tables",No="/_lunora/admin/global/table",Do="/_lunora/admin/global/facet",Ot=e=>{if(e===void 0||e==="")return;let t;try{t=Ve(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:s}=r;return[{column:a,value:s}]});return n.length===0?void 0:n},Uo=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:{}}),Co=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"}),Bo=e=>{const{assertAdmin:t,options:n,parsePaging:r,queryParameter:a,requireAdminOption:s}=e,u=g=>{j(g,"GET","Functions");const _=s(g,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),R=Object.entries(_).flatMap(([p,T])=>T.visibility==="internal"||T.kind==="stream"?[]:[{args:To(T.args),kind:T.kind,path:p}]).toSorted((p,T)=>p.path.localeCompare(T.path));return Response.json({functions:R},{headers:{"content-type":"application/json"},status:200})},h=g=>{j(g,"GET","Cron-jobs");const _=s(g,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),R=Object.entries(_).flatMap(([p,T])=>T.map(U=>({args:U.args,cron:p,functionPath:U.functionPath,name:U.name,shardKey:U.shardKey,workflow:U.workflow}))).toSorted((p,T)=>p.name.localeCompare(T.name));return Response.json({jobs:R},{headers:{"content-type":"application/json"},status:200})},f=g=>(j(g,"GET","OpenAPI"),t(g),Response.json(n.openApiSpec??Uo,{headers:{"content-type":"application/json"},status:200})),w=g=>(j(g,"GET","OpenRPC"),t(g),Response.json(n.openRpcSpec??Co,{headers:{"content-type":"application/json"},status:200})),S=async g=>{j(g,"GET","Global-tables");const _=s(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await _.listTables(),{headers:{"content-type":"application/json"},status:200})},A=async g=>{j(g,"GET","Global-table");const _=s(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(g.url),p=a(R,"table");if(p===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const T=await _.readTablePage({...r(g),filters:Ot(a(R,"filters")),table:p});return Response.json(T,{headers:{"content-type":"application/json"},status:200})},k=async g=>{j(g,"GET","Global-facet");const _=s(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(g.url),p=a(R,"table"),T=a(R,"column");if(p===void 0||T===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const U=a(R,"limit"),M=U===void 0?void 0:Number(U),N=await _.facetColumn({column:T,filters:Ot(a(R,"filters")),limit:M!==void 0&&Number.isFinite(M)?M:void 0,table:p});return Response.json(N,{headers:{"content-type":"application/json"},status:200})};return{[vo]:h,[Oo]:u,[Do]:k,[No]:A,[Po]:S,[ko]:f,[Io]:w}},xo="/_lunora/admin/kv/namespaces",Ho="/_lunora/admin/kv/keys",Zt="/_lunora/admin/kv/value",en=32*1048576,vt=60,Lo=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=_=>n(_,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=_=>Response.json(_,{headers:{"content-type":"application/json"},status:200}),s=(_,R)=>{const p=new URL(_.url),T=p.searchParams.get("namespace")??"",U=p.searchParams.get("key")??"";if(T==="")throw new c(`KV-value ${R} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(U==="")throw new c(`KV-value ${R} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:U,namespace:T}},u=async(_,R)=>{if(!(await _.listNamespaces()).some(T=>T.binding===R))throw new c(`Unknown KV namespace binding \`${R}\``,{code:"NOT_FOUND",status:404})},h=async _=>(j(_,"GET","KV-namespaces"),a({namespaces:await r(_).listNamespaces()})),f=async _=>{j(_,"GET","KV-keys");const R=r(_),p=new URL(_.url),T=p.searchParams.get("namespace")??"";if(T==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const U=p.searchParams.get("prefix")??void 0,M=p.searchParams.get("cursor")??void 0,N=p.searchParams.get("limit"),K=N===null?void 0:Number.parseInt(N,10);if(K!==void 0&&(!Number.isInteger(K)||K<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const $=K===void 0?void 0:Math.min(K,1e3);return await u(R,T),a(await R.listKeys({cursor:M,limit:$,namespace:T,prefix:U}))},k={DELETE:async _=>{const R=r(_),p=s(_,"DELETE");return await u(R,p.namespace),await R.deleteKey(p),a({deleted:!0})},GET:async _=>{const R=r(_),p=s(_,"GET");return await u(R,p.namespace),a(await R.getValue(p))},PUT:async _=>{const R=r(_),p=await t(_,en);if(typeof p.namespace!="string"||p.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<vt))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const T=Math.floor(Date.now()/1e3)+vt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<T))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 u(R,p.namespace),await R.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),a({ok:!0})}},g=_=>{const R=k[_.method];if(!R)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return R(_)};return{[xo]:h,[Ho]:f,[Zt]:g}},Mo="/_lunora/migrate",jo="/_lunora/admin/pitr",$o="/_lunora/admin/rank",Ko="/_lunora/admin/rankpage",Fo="/_lunora/admin/shard-traffic",Go=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Qo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),zo=async e=>{const n=await he(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"||!Go.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}},Wo=async e=>{const n=await he(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}},Vo=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}},Jo=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})},qo=async e=>{const n=await he(e,"Rank page")??{};Jo(n);const r=Vo(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}},Yo=async e=>{const n=await he(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}},Xo=async e=>{const n=await te(e);if(typeof n.functionPath!="string"||!Qo.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}},Zo=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:r,queryCoordinator:a,resolveForwardContext:s,shardDO:u}=e,h=(g,_)=>{if(g.method!=="POST")throw new c(`${_} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(g))throw new c("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new c(`${_} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},f=async(g,_)=>{const R=h(g,"Migration"),p=await zo(g),{headers:T}=await s(g,_),U=await R.orchestrateMigration(u,{args:p.args,defaultShardKey:t,functionPath:p.functionPath,headers:T,table:p.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},w=async(g,_)=>{const R=h(g,"Rank"),p=await Wo(g),{headers:T}=await s(g,_),U=await R.orchestrateRank(u,{headers:T,index:p.index,partitionKey:p.partitionKey,rowId:p.rowId,sortValues:p.sortValues,table:p.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},S=async(g,_)=>{const R=h(g,"Rank page"),p=await qo(g),{headers:T}=await s(g,_),U=await R.orchestrateRankPage(u,{...p,headers:T});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},A=async(g,_)=>{const R=h(g,"Shard-traffic"),p=await Yo(g),{headers:T}=await s(g,_),U=await R.orchestrateShardTraffic(u,{headers:T,table:p.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},k=async(g,_)=>{if(j(g,"POST","PITR"),!r(g))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const R=await Xo(g),{headers:p}=await s(g,_),T=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:R.args,functionPath:R.functionPath}),headers:p,method:"POST"});return n(u,R.shardKey??t,T)};return{[Mo]:f,[jo]:k,[$o]:w,[Ko]:S,[Fo]:A}},ea=1,ta=0,na=32,ra=512,oa=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,aa=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>ra)return;const n=t.split(",");if(!(n.length>na)){for(const r of n)if(!oa.test(r.trim()))return;return t}},sa=e=>{const t=Qn(e.headers.get("traceparent"));if(t===void 0)return;const n=aa(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},ia=(e,t={})=>{const n=sa(e),r=t.trustInbound===!0?n:void 0,a=Ie(8),s=r?.traceId??Ie(16),u=wr(t.sampling,r===void 0?a:s),h=u.isTraced&&(r===void 0||r.sampled);return{decision:u,ignoredUpstream:n!==void 0&&r===void 0,trace:{sampled:h,spanId:a,traceFlags:h?ea:ta,traceId:s,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState}}}},ca=(e,t)=>{t.traceparent=jt(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},da=(e,t)=>{let n;return()=>{if(n===void 0){const r=Jn(e),a=t===void 0?void 0:t.cf;n=zn(Vn(r),Wn(r,a))}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:a}=e,s=(w,S)=>A=>{if(A.method!=="GET")throw new c(`${S} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const k=new URL(A.url).searchParams.get("cursor"),g=k===null||k===""?"":`?cursor=${encodeURIComponent(k)}`;return r(A).fetch(new Request(`https://scheduler.internal${w}${g}`,{method:"GET"}))},u=(w,S,A=S)=>async k=>{if(k.method!=="POST")throw new c(`${A} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const g=r(k),_=await he(k,S);if(typeof _?.id!="string"||_.id==="")throw new c(`${S} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return g.fetch(new Request(`https://scheduler.internal${w}`,{body:JSON.stringify({id:_.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async w=>{if(w.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const S=r(w),A=await he(w,"Scheduled pool-release");if(typeof A?.pool!="string"||A.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const k=typeof A.id=="string"&&A.id!==""?A.id:void 0;return S.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(k===void 0?{pool:A.pool}:{id:k,pool:A.pool}),headers:{"content-type":"application/json"},method:"POST"}))},f=async w=>{if(w.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(w))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const S=n();return ge(S,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[fa]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[wa]:u("/dead/cancel","Scheduled dead-letter action"),[pa]:s("/dead","Scheduled dead-letter"),[ma]:u("/dead/retry","Scheduled dead-letter action"),[ua]:s("/list","Scheduled-list"),[ga]:h,[la]:s("/status","Scheduler-status"),[ha]:f}},ba=(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},kt={mtls:e=>ba(e,"tlsClientAuth","certVerified")==="SUCCESS"},_a=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(kt,e)?kt[e]:void 0)??(()=>!1),Ra=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},Ea="/_lunora/admin/vector/indexes",Sa="/_lunora/admin/vector/query",Aa=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=async s=>{j(s,"GET","Vector-indexes");const u=n(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async s=>{j(s,"POST","Vector-query");const u=n(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new c("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const f=await t(s);if(typeof f.name!="string"||f.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof f.text!="string"||f.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(f.topK!==void 0&&(typeof f.topK!="number"||!Number.isInteger(f.topK)||f.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const w=await u.queryIndex({name:f.name,text:f.text,topK:f.topK});return Response.json(w,{headers:{"content-type":"application/json"},status:200})};return{[Ea]:r,[Sa]:a}},Ta="/_lunora/admin/workflows/instances",Oa="/_lunora/admin/workflows/instance",va="/_lunora/admin/workflows/status",ka={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Ia=e=>e!==null&&Object.hasOwn(ka,e)?e:void 0,It=(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},Ge=(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},Pt=()=>{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})},Pa=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,r=async(u,h,f)=>{j(u,"GET","Workflows instances"),t(u);const w=n(h);if(!w)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const S=Ge(f,"name"),A=Ia(f.searchParams.get("status"));return Response.json(await w.listInstances({page:It(f,"page"),perPage:It(f,"perPage"),status:A,workflowName:S}))},a=async(u,h,f)=>{j(u,"GET","Workflows instance"),t(u);const w=n(h);return w?Response.json(await w.getInstance({instanceId:Ge(f,"id"),workflowName:Ge(f,"name")})):Pt()},s=async(u,h)=>{j(u,"POST","Workflows status"),t(u);const f=n(h);if(!f)return Pt();const w=await u.json().catch(()=>{});if(typeof w?.name!="string"||w.name===""||typeof w.id!="string"||w.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:S}=w;if(S!=="pause"&&S!=="resume"&&S!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:S,instanceId:w.id,workflowName:w.name}))};return{[Oa]:a,[Ta]:r,[va]:s}},Na={[Zt]:en,[sr]:ar},Nt="/_lunora/rpc",Da="/_lunora/rpc-batch",Ua="/_lunora/ws",be=(e,t,n)=>({resourceAttributes:da(e,t),...n===void 0?{}:{waitUntil:n}}),Qe=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Dt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),ze=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let r;try{r=new URL(e.url)}catch{return{method:t,userAgent:n}}const a=r.port===""?void 0:Number(r.port);return{host:r.hostname,method:t,path:r.pathname,port:Number.isNaN(a)?void 0:a,scheme:r.protocol.replace(":",""),userAgent:n}},Ut="/_lunora/voice/",Ca="/_lunora/scheduler/dispatch",Ba="/_lunora/admin/cron-jobs/run",xa="/_lunora/admin/ws-token",Ha="/_lunora/admin/",La="/_lunora/",Ma="/_lunora/migrate",ja="/_lunora/status",$a=e=>e.startsWith(Ha)||e===Ma,Ka="__lunora_relation__:",Se=e=>{if(e.startsWith(Ka))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Ae=async e=>await e===!0,Fa=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}}},Ct="/api/auth",Ga="__lunora_admin__:recordAuthEvent",Qa="__lunora_admin__:listPushSubscriptions",za=["/sign-in","/sign-up","/callback"],Wa=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const r=e.slice(n.length);return za.some(a=>r===a||r.startsWith(`${a}/`))},Va=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},Te=(e,t,n,r)=>{const a=Ln(n),s=a?n.code:"INTERNAL_SERVER_ERROR",u=a?n.status:500,h=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:s,message:h,status:u},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},Ja=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},Bt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,qa=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},Ye=new WeakMap,de=async(e,t,n,r,a=Ye.get(e))=>{const s={"content-type":"application/json"},u=e.headers.get("authorization"),h=e.headers.get("cookie"),f=e.headers.get("x-d1-bookmark"),w=e.headers.get("x-lunora-mutation-id"),S=e.headers.get("x-lunora-client-id"),A=e.headers.get("x-lunora-client-seq");u&&(s.authorization=u),h&&(s.cookie=h),f&&(s["x-d1-bookmark"]=f),w&&(s["x-lunora-mutation-id"]=w),S&&(s["x-lunora-client-id"]=S),A&&(s["x-lunora-client-seq"]=A);const k=Zn(e.headers,r);if(k&&(s["x-lunora-client-ip"]=k),!n)return{claims:null,headers:s,identity:null,userId:null};const g=await n(e,t,a);if(!g||typeof g.userId!="string"||g.userId.length===0)return{claims:null,headers:s,identity:null,userId:null};s["x-lunora-userid"]=Fn(g.userId);const _=Ja(g);_!==void 0&&(s["x-lunora-identity-exp"]=String(_));const{userId:R,...p}=g,T=Object.keys(p).length>0?p:null;return T&&(s["x-lunora-identity"]=Gn(T)),{claims:T,headers:s,identity:g,userId:R}},Ya=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Xa=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"||!Ya.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},Za=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},We=(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}},es=async e=>{const t=await Ft(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&&Kt(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,s=Xa(a.fanOut),u=a.args??{};if(s&&a.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==s.table)throw new c("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=s.table}return{args:u,fanOut:s,functionPath:a.functionPath,shardKey:a.shardKey}},Oe=new Map,ts=5e3,ns=4096,rs=async(e,t)=>{const n=Date.now(),r=Oe.get(t);if(r!==void 0&&r.expiresMs>n)return r.relayCount;r!==void 0&&Oe.delete(t);let a=0;try{const s=await ge(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(s.ok){const h=(await s.json()).relayCount;typeof h=="number"&&h>0&&(a=Math.floor(h))}}catch{a=0}return Mt(Oe,ns),Oe.set(t,{expiresMs:n+ts,relayCount:a}),a},xt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},ve=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),os=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],as=(e,t)=>{for(const n of os){e.delete(n);const r=t[n];r!==void 0&&e.set(n,r)}},Ht=(e,t)=>{const n=new Headers(e.headers),r=[...n.keys()];for(const a of r)a.startsWith("x-lunora-")&&n.delete(a);return as(n,t),n},ss=async(e,t,n)=>e.length===0||n.length===0?!1:et(await Wt(e,t),n),Lt=(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:et(t,a.join(" ").trim())},is=async(e,t,n)=>{if(!t||t.length===0)return!1;const r=new URL(e.url).searchParams.get("token");return r===null?!1:await Fr(t,r)?!0:n?!1:et(t,r)},cs=(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 fr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return Le(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return Le(`queue:${e}`,!0);if(typeof n.connectionString=="string")return Le(`hyperdrive:${e}`,!0)},ds=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})},tn=e=>{ds(e);const t=_a(e.trustInboundTraceContext),n=Ra(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",a=pr(e.resolveIdentity,e.identity),s=ht(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:ht(e.schedulerDO,e.jurisdiction);let h=!1;const f=o=>{if(o===void 0||e.jurisdiction===void 0)return o;h||(h=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},w=async(o,i,l,d=e.shardRegion?.(i))=>ge(o,i,f(d)).fetch(l);let S;const A=()=>e.adminToken??S;let k;const g=()=>e.requireEphemeralWsToken??k??!0;let _;const R=o=>{const i=o??{};if(_??=xt(o,e.shardDO),k===void 0&&e.requireEphemeralWsToken===void 0){const d=i.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof d=="string"&&d.length>0&&(k=jr(d,!0))}if(S!==void 0||e.adminToken!==void 0)return;const l=i.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(S=l)},p=new WeakSet,T=o=>Lt(o,A())||p.has(o),U=async o=>{if(!(e.adminGate===void 0||p.has(o)))try{await Ae(e.adminGate(o,Ye.get(o)))&&p.add(o)}catch{}},M=async(o,i)=>{const l=await de(o,i,e.resolveIdentity,e.trustedClientIpHeader);if(p.has(o)&&l.headers.authorization===void 0){const d=A();d!==void 0&&(l.headers.authorization=`Bearer ${d}`)}return l};let N=!1,K=!1;const $=()=>{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 i=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${o} access is default-denied: configure \`${i}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}N||(N=!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("")))},B=async(o,i)=>{if(i.includes(Je)||i.includes(qe))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(e.authorizeShard){if(!await Ae(e.authorizeShard({identity:o,shardKey:i})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else i!==r&&V("shard")},J=Zo({defaultShard:r,forwardToShard:w,isAdmin:T,queryCoordinator:e.queryCoordinator,resolveForwardContext:M,shardDO:s}),F=async(o,i,l,d,m,b)=>{Se(o);const O={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(O["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(O["x-lunora-identity"]=m.identity),d!==void 0&&d.length>0&&(O["x-lunora-mutation-id"]=d),b!==void 0&&b.length>0&&(O.traceparent=b),w(s,l,ve(o,i,O))},q=async(o,i,l,d,m)=>{const b=l?.[o];if(!b||typeof b.create!="function")throw new c(`${d} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(_r(i))throw new c(`${d} params ${Rr}`,{code:"BAD_REQUEST",status:400});try{await b.create(m===void 0?{params:i}:{id:m,params:i})}catch(O){if(!Ar(O))throw O}},ee=async(o,i,l)=>{if(o.workflow){await q(o.workflow,o.args??{},i,`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 d=await F(o.functionPath,o.args??{},o.shardKey??r,void 0,void 0,l);if(!d.ok)throw new c(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(d.status)}`,{code:"CRON_JOB_FAILED",status:500})},L=o=>{if(!T(o))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},Y=(o,i,l)=>{if(L(o),i===void 0)throw new c(l.message,{code:l.code,status:400});return i},G=async(o,i,l,d,m)=>{const b=e.cronJobs?.[o];if(!b)return 0;for(const O of b)try{await ee(O,i,m)}catch(v){l.push(d(v))}return b.length},fe=async(o,i)=>{if(L(o),j(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 l=await te(o),d=typeof l.name=="string"?l.name:"";if(d==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(b=>b.name===d);if(!m)throw new c(`no cron job named "${d}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await ee(m,i),Response.json({name:d,ran:!0},{status:200})},ae=async o=>{const i=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!i||!u||typeof o.id!="string")return;const l=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await ge(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:i}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},_e=async(o,i)=>{j(o,"POST","Scheduler dispatch");const l=await Ft(o),d=i??{},m=typeof d.LUNORA_SCHEDULER_SECRET=="string"?d.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof d.LUNORA_ADMIN_TOKEN=="string"?d.LUNORA_ADMIN_TOKEN:void 0),O=o.headers.get("x-lunora-scheduler-signature");let v=!1;if(O&&m?v=await ss(m,l,O):b&&(v=Lt(o,b)),!v)throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let I;try{I=JSON.parse(l)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const y=I??{},E=y.args??{},C=typeof y.id=="string"&&y.id.length>0?y.id:void 0;if(typeof y.workflow=="string"&&y.workflow.length>0)return await q(y.workflow,E,i,"scheduled workflow",C),await ae(y),Response.json({ok:!0},{status:200});if(typeof y.functionPath!="string"||y.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const x=typeof y.shardKey=="string"&&y.shardKey.length>0?y.shardKey:r,Q=Fa(o),H=await F(y.functionPath,E,x,C,Q,o.headers.get("traceparent")??void 0);return await ae(y),H},Pe=Wr({assertAdmin:L,getReader:()=>e.authAuditReader}),Ne=async(o,i)=>{L(o);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:ke({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const d=i?.kind,m=i?.userId,b=i?.limit,O=d==="fcm"||d==="web-push"?d:void 0,v=typeof m=="string"&&m!==""?m:void 0,I=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,y=I>0?Math.min(I,1e3):1e3,C=(await l.list({kind:O,limit:y,userId:v})).filter(x=>O!==void 0&&x.kind!==O?!1:v===void 0||(x.userId??null)===v).map(({keys:x,token:Q,...H})=>H);return Response.json({result:ke({subscriptions:C})},{headers:{"content-type":"application/json"},status:200})},se=async(o,i)=>{if(!i.fanOut&&!(i.functionPath!==yt&&i.functionPath!==Qa))return await U(o),i.functionPath===yt?Pe(o,i.args??{}):Ne(o,i.args)},nn=yo({applyGlobals:e.applyGlobals,assertAdmin:L,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:r,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:Y,resolveForwardContext:M,shardDO:s,streamExportRows:(o,i,l,d)=>qt(e,o,i,l,d,s),streamingImport:(o,i)=>So(o,e,i,s),syncGlobals:e.syncGlobals}),De=(o,i)=>{const l=o.searchParams.get(i);return l===null||l===""?void 0:l},Ue=o=>{const i=new URL(o.url),l=i.searchParams.get("limit"),d=i.searchParams.get("offset"),m=l===null?void 0:Number.parseInt(l,10),b=d===null?void 0:Number.parseInt(d,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},rt=()=>{if(u===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},rn=ya({checkWsAdmin:async o=>T(o)||is(o,A(),g()),requireSchedulerNamespace:rt,resolveSchedulerStub:o=>(L(o),ge(rt(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),on=Pa({assertAdmin:L,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),an=or({assertAdmin:L,parsePaging:Ue,queryParameter:De,readBodyBytes:Xn,requireAdminOption:Y,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),sn=so({options:e,readJsonBody:te,requireAdminOption:Y}),cn=Aa({readJsonBody:te,requireAdminOption:Y,vectorIntrospector:e.vectorIntrospector}),dn=Lo({kvIntrospector:e.kvIntrospector,readJsonBody:te,requireAdminOption:Y}),un=mr({logArchive:e.logArchive,readJsonBody:te,requireAdminOption:Y}),ln=Bo({assertAdmin:L,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ue,queryParameter:De,requireAdminOption:Y}),hn=o=>{const i=[],l=s??o?.SHARD;if(l!==void 0&&i.push(hr("durable-object:default",l,r)),e.health?.disableBindingProbes!==!0)for(const[d,m]of Object.entries(o??{})){const b=cs(d,m);b!==void 0&&i.push(b)}for(const d of e.health?.probes??[])i.push(d);return i},fn=lr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:T,resolveProbes:hn}),pn=o=>{const i=y=>"args"in y?{...y,args:Ve(y.args)}:y,l=e.schedulerInstanceName??"default",d=()=>ge(o,l),m=async(y,E)=>{const C=await d().fetch(new Request(`https://scheduler.internal${y}`,E));if(!C.ok)throw new c(`ctx.scheduler: SchedulerDO ${y} failed (${String(C.status)}): ${await C.text()}`,{code:"INTERNAL",status:500});return await C.json()},b=async(y,E)=>await m(y,{body:JSON.stringify(E),headers:{"content-type":"application/json"},method:"POST"}),O=y=>{const E=y;if(E==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 E.binding=="string"&&E.binding.length>0)return{workflow:E.binding};if(typeof E.__lunoraRef=="string")return{functionPath:E.__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})},v=async()=>(await Er(async E=>m(E===void 0?"/list":`/list?cursor=${encodeURIComponent(E)}`,{method:"GET"}))).map(E=>i(E)),I=async(y,E,C={})=>{const x=O(E),{id:Q}=await b("/schedule",{args:qn("ctx.scheduler",String(x.functionPath??x.workflow),C),scheduledFor:y,...x});return Q};return{cancel:async y=>await b("/cancel",{id:y}),get:async y=>{const E=await m(`/get?id=${encodeURIComponent(y)}`,{method:"GET"});return E.record===void 0?null:i(E.record)},list:v,runAfter:async(y,E,C)=>{if(!Number.isFinite(y)||y<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await I(Date.now()+y,E,C)},runAt:async(y,E,C)=>{if(!Number.isFinite(y))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await I(y,E,C)}}},mn=async(o,i,l)=>{const{claims:d,headers:m,userId:b}=await de(o,i,a,e.trustedClientIpHeader),O=be(i,o,y=>l.waitUntil?.(y)),v=y=>async(E,C={})=>{const x=E.__lunoraRef;if(typeof x!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Se(x);const Q=await Ee(o,x,ke(C),y,{...m,"x-lunora-system":"1"},O),H=await Q.json();if(H.error)throw new c(H.error.message??"shard RPC failed",{code:H.error.code??"INTERNAL",status:Q.status});return Ve(H.result)},I=v(r);return{auth:{getIdentity:()=>Promise.resolve(d),userId:b},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),forShard:y=>{const E=v(y);return{runAction:E,runMutation:E,runQuery:E}},runAction:I,runMutation:I,runQuery:I,...u===void 0?{}:{scheduler:pn(u)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:br(e.storage(i))}}},wn=async(o,i,l)=>{if(!e.httpRouter)return;const d=await mn(o,i,l);try{return await e.httpRouter.fetch(o,{...i,__lunoraCtx:d},l)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},gn=async(o,i,l)=>{if(o.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const d=pt(o,ie);if(d)return d;const m=l.searchParams.get("shard")??r,{headers:b,identity:O}=await de(o,i,a,e.trustedClientIpHeader);await B(O,m);const v=Ht(o,b),I=xt(i,e.shardDO);if(I!==void 0){v.set("x-lunora-shard-binding",I);const y=await rs(s,m);if(y>0){const E=Br(m,Math.floor(Math.random()*y));return w(s,E,new Request(o,{headers:v}),mt(o))}}return w(s,m,new Request(o,{headers:v}))},yn=async(o,i,l)=>{const{voiceAgents:d}=e;if(d===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=pt(o,ie);if(m)return m;let b;try{b=decodeURIComponent(l.pathname.slice(Ut.length))}catch{return new Response("Unknown voice agent",{status:404})}const O=Object.hasOwn(d,b)?d[b]:void 0;if(O===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:I,identity:y}=await de(o,i,a,e.trustedClientIpHeader);if(e.authorizeShard){if(!await Ae(e.authorizeShard({identity:y,shardKey:v})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else V("shard");const E=Ht(o,I);return w(O,v,new Request(o,{headers:E}))},bn=async(o,i,l)=>{if(e.authorizeFanOut){if(!await Ae(e.authorizeFanOut(l,o.table,i)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(i.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")},Re=async(o,i)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await bn(o.fanOut,o.functionPath,i);return}await B(i,o.shardKey??r)}},_n=(o,i,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){$();return}if(e.functions[i]?.kind!=="query"||l.includes(qe)||l.includes(Je))return;const d=mt(o);return d===void 0?void 0:{name:xr(l,d),region:d}},Rn=async(o,i,l,d,m)=>{const b=_n(o,i,d);if(b!==void 0){const O={...m,"x-lunora-replica-read":"1",..._===void 0?{}:{"x-lunora-shard-binding":_}},v=Hr(o.headers.get("x-lunora-min-seq"));v!==void 0&&(O["x-lunora-min-seq"]=String(v));const I=await w(s,b.name,ve(i,l,O),b.region);if(I.status!==421)return I}return w(s,d,ve(i,l,m))},Ee=async(o,i,l,d,m,b)=>{const O=Date.now(),{observability:v,sampling:I}=e,y=ze(o),{decision:E,ignoredUpstream:C,trace:x}=ia(o,{...I===void 0?{}:{sampling:I},trustInbound:t(o)});C&&n();const Q={...m,"x-lunora-sample-errors":E.keepErrors?"1":"0"};ca(x,Q);try{const H=await Rn(o,i,l,d,Q);ce(v,{...y,...Dt(x),durationMs:Date.now()-O,functionPath:i,ok:H.ok,shardKey:d,...H.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(H.status)}`,status:H.status}}},b,void 0,{isTraced:x.sampled,keepErrors:E.keepErrors});const ne=new Response(H.body,{headers:H.headers,status:H.status,statusText:H.statusText});return ne.headers.set("x-lunora-shard-key",d),ne}catch(H){throw ce(v,{...y,...Dt(x),...Te(i,Date.now()-O,H,{shardKey:d})},b,void 0,{isTraced:x.sampled,keepErrors:E.keepErrors}),H}},En=o=>{if(o.fanOut&&o.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(o.fanOut||Se(o.functionPath),o.fanOut&&!e.queryCoordinator)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Sn=async(o,i,l)=>{j(o,"POST","RPC");const d=await es(o);Za(i,d),En(d);const m=await se(o,d);if(m!==void 0)return m;const{headers:b,identity:O}=await de(o,i,a,e.trustedClientIpHeader);await Re(d,O);const v=We(d,e);{const I=Date.now(),{observability:y}=e,E=ze(o),C=be(i,o,l&&(H=>l.waitUntil?.(H)));if(d.fanOut){const H=e.queryCoordinator;if(!H)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ne=await H.fanOut(s,{args:d.args??{},fanOut:d.fanOut,functionPath:d.functionPath,headers:b});return ce(y,{durationMs:Date.now()-I,fanOut:{failed:ne.failed,shards:ne.ok+ne.failed,table:d.fanOut.table},functionPath:d.functionPath,...E,ok:!0},C),Response.json(ne,{headers:{"content-type":"application/json"},status:200})}catch(ne){throw ce(y,{...Te(d.functionPath,Date.now()-I,ne,{fanOut:{table:d.fanOut.table}}),...E},C),ne}}const x=d.shardKey??r,Q=()=>Ee(o,d.functionPath,d.args??{},x,b,C);return v&&e.x402Charge?e.x402Charge(o,{functionPath:d.functionPath,price:v.price},Q,Qe(l)):Q()}},An=async(o,i,l)=>{j(o,"POST","RPC batch");const d=await te(o),{calls:m}=d;if(!Array.isArray(m))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:b,identity:O}=await de(o,i,a,e.trustedClientIpHeader),v=co(m,r);for(const z of v.values())for(const W of z)if(e.functions?.[W.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${W.functionPath}" cannot be called in a batch; dispatch it individually over ${Nt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...v.entries()].flatMap(([z,W])=>W.map(oe=>Re({args:oe.args,functionPath:oe.functionPath,shardKey:z},O))));const{observability:I}=e,y=be(i,o,l&&(z=>l.waitUntil?.(z))),E=ze(o),C=[],x=[],Q=(z,W,oe,ue)=>({body:{error:{code:oe,message:ue}},id:z.id,status:W}),H=(z,W,oe,ue,pe)=>{for(const X of z)ce(I,pe(X),y),C.push(Q(X,W,oe,ue))},ne=(z,W,oe,ue,pe)=>{for(const X of z){const me=ue.get(X.id)??pe,ye=me<400;ce(I,{durationMs:oe,functionPath:X.functionPath,...E,ok:ye,shardKey:W,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},y)}};await Promise.all([...v.entries()].map(async([z,W])=>{const oe=new Headers(b);oe.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:W}),headers:oe,method:"POST"}),pe=Date.now();let X;try{X=await w(s,z,ue)}catch(Z){const He=Date.now()-pe,{body:ct}=Mn(Z,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});H(W,502,ct.code,ct.message,Hn=>({...Te(Hn.functionPath,He,Z,{shardKey:z}),...E}));return}const me=Date.now()-pe,ye=X.headers.get("x-d1-bookmark");ye&&x.push(ye);let Be;try{Be=await X.json()}catch{const Z=`shard batch returned a non-JSON response (${String(X.status)})`;H(W,X.status,"SHARD_ERROR",Z,He=>({durationMs:me,error:{code:"SHARD_ERROR",message:Z,status:X.status},functionPath:He.functionPath,...E,ok:!1,shardKey:z}));return}const xe=Array.isArray(Be.results)?Be.results:[],Bn=new Map(xe.map(Z=>[Z.id,Z.status??X.status])),xn=new Set(xe.map(Z=>Z.id));ne(W,z,me,Bn,X.status),C.push(...xe);for(const Z of W)xn.has(Z.id)||C.push(Q(Z,X.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Z.id)}`))}));const st={"content-type":"application/json"},[it]=x;return x.length===1&&it!==void 0&&(st["x-d1-bookmark"]=it),Response.json({results:C},{headers:st,status:200})},Tn=async(o,i,l,d={},m={})=>{try{const b=l.__lunoraRef;if(typeof b!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Se(b);const{headers:O,identity:v}=await de(o,i,a,e.trustedClientIpHeader,m.context),I={args:d,functionPath:b,shardKey:m.shardKey};await Re(I,v);const y=m.shardKey??r,E=be(i,o,m.waitUntil),C=()=>Ee(o,b,d,y,O,E),x=We(I,e);return x&&e.x402Charge?await e.x402Charge(o,{functionPath:b,price:x.price},C,Qe(m.waitUntil?{waitUntil:m.waitUntil}:m.context)):await C()}catch(b){return dt(b)}},ot=async(o,i,l)=>{const{observability:d}=e,m=Date.now(),b=Ie(16),O=Ie(8),v=Bt(i),I=jt(b,O,!0);try{const y=await l(I);return ce(d,{durationMs:Date.now()-m,functionPath:o,ok:!0,spanId:O,traceId:b},v),y}catch(y){throw ce(d,{...Te(o,Date.now()-m,y,{}),spanId:O,traceId:b},v),y}finally{lt(d,v)}},On=async(o,i,l,d)=>{R(i);const m=[],b=E=>E instanceof Error?E:new Error(String(E)),O=e.crons?.[o.cron];if(O)try{await O(o,i,l)}catch(E){m.push(b(E))}const v=await G(o.cron,i,m,b,d),I=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron;if(I)try{await no(e,s,A(),o)}catch(E){m.push(b(E))}if(!O&&v===0&&!I){const E=[...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: ${E.length===0?"(none)":E.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[y]=m;if(m.length===1&&y)throw y;if(m.length>1)throw new AggregateError(m,`scheduled("${o.cron}") had ${String(m.length)} failure(s)`)},vn=async(o,i)=>{try{const l=o??{},d=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!d||d.length===0)return;await w(s,r,ve(Ga,{outcome:i},{authorization:`Bearer ${d}`,"content-type":"application/json"}))}catch{}},kn=async(o,i,l,d)=>{if(!e.authHandler)return;const m=await e.authHandler(o);if(!m)return;const b=e.authBasePath??Ct;return Wa(l.pathname,b)&&d.waitUntil?.(vn(i,m.status>=400?"fail":"ok")),m},In=async({args:o,env:i,functionPath:l,request:d,shardKey:m,waitUntil:b})=>{Kt(o,"REST");const O={functionPath:l,...m===void 0?{}:{shardKey:m}},{headers:v,identity:I}=await de(d,i,a,e.trustedClientIpHeader);await Re(O,I);const y=m??r,E=be(i,d,b),C=()=>Ee(d,l,o,y,v,E),x=We(O,e);return x&&e.x402Charge?e.x402Charge(d,{functionPath:l,price:x.price},C,Qe({waitUntil:b})):C()},Pn=Yn({functions:e.functions??{},invoke:In,readJsonBody:te,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ce=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Nn={[ja]: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"}}),[Ua]:(o,i,l)=>gn(o,i,l),[Nt]:(o,i,l,d)=>Sn(o,i,d),[Da]:(o,i,l,d)=>An(o,i,d),[Ca]:(o,i)=>_e(o,i),[Ba]:(o,i)=>fe(o,i),[xa]:async o=>{j(o,"POST","ws-token"),L(o);const i=A();if(i===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Kr(i);return Response.json(l,{headers:{"cache-control":"no-store"}})},...J,...nn,...rn,...on,...an,...sn,...cn,...dn,...un,...ln,...fn,...Pn,...zr({assertAdmin:L,getAuthAdmin:()=>e.authAdmin,parsePaging:Ue,queryParameter:De,readJsonBody:te})};let ie=ft(e.security),at=!1;const Dn=o=>{at||(at=!0,ie=ft(e.security,o??{}))},Un=async(o,i)=>{$a(i)&&await U(o)},Cn=async(o,i,l)=>{Ye.set(o,l);const d=new URL(o.url);if((d.pathname.startsWith(La)||e.authHandler!==void 0&&Va(d.pathname,e.authBasePath??Ct))&&(o.method==="POST"||o.method==="PUT")){const I=Number(o.headers.get("content-length")??""),y=Na[d.pathname]??$t;if(Number.isFinite(I)&&I>y)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const b=await kn(o,i,d,l);if(b)return b;if(Ce){const I=`${o.method} ${d.pathname}`,y=Ce[I]??Ce[d.pathname];if(y)return y(o,i,l)}const O=Nn[d.pathname];if(O)return await Un(o,d.pathname),O(o,i,d,l);if(e.voiceAgents!==void 0&&d.pathname.startsWith(Ut))return yn(o,i,d);const v=await wn(o,i,l);return v||new Response("Not found",{status:404})};return{async fetch(o,i,l){e.passThroughOnException&&l.passThroughOnException?.(),Dn(i),R(i);const d=gr(o,ie);if(d)return d;const m=yr(o,ie);if(m)return Me(m,o,ie);try{const b=await Cn(o,i,l);return Me(b,o,ie)}catch(b){return Me(dt(b),o,ie)}finally{lt(e.observability,Bt(l))}},async queue(o,i,l){await ot(`queue:${qa(o)}`,l,async d=>{await e.queue?.(o,i,l,{traceparent:d})})},async scheduled(o,i,l){await ot(`cron:${o.cron}`,l,async d=>{await On(o,i,l,d)})},serverQuery:Tn}},us=e=>tn(e),ls=e=>typeof e=="function"?{fetch:e}:e,hs=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,Cs=(e,t)=>{const n=ls(e),r=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=u=>{const h=us({...u,httpRouter:n});return r!==void 0&&!hs(u)?{...h,scheduled:async(f,w,S)=>{await r(f,w,S)}}:h};if(typeof t!="function")return a(t);const s=t;return{fetch:(u,h,f)=>a(s(h)).fetch(u,h,f),queue:(u,h,f)=>a(s(h)).queue?.(u,h,f)??Promise.resolve(),scheduled:(u,h,f)=>a(s(h)).scheduled(u,h,f),serverQuery:(u,h,f,w,S)=>a(s(h)).serverQuery(u,h,f,w,S)}},fs=(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}},Bs=(e={})=>(t,n,r)=>tn(fs(e,n)).fetch(t,n,r??jn),xs=e=>e;export{yt as GET_AUTH_AUDIT_LOG_OP,jn as NOOP_EXECUTION_CONTEXT,Ms as composeIdentityResolvers,us as composeWorker,Bs as createLunoraHandler,tn as createWorker,xs as defineRpcEnvelope,rs as probeRelayCount,fs as resolveLunoraOptions,js as routeIdentityResolvers,Cs as withFrameworkWorker};
@@ -0,0 +1 @@
1
+ import{c as S,d as T,e as O,a as B,f as P}from"./rest-cache-D1BlbZb1.mjs";import{LunoraError as h}from"./LunoraError-DksAgIpa.mjs";import{m as D}from"./method-guard-BG_vJNTl.mjs";const w=1048576,k=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),U=async(t,r=w)=>{if(!t.body)return"";const e=t.body.getReader(),a=new TextDecoder;let i=0,s="";for(;;){const{done:o,value:n}=await e.read();if(o)break;if(n){if(i+=n.byteLength,i>r)throw await e.cancel().catch(()=>{}),new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});s+=a.decode(n,{stream:!0})}}return s+=a.decode(),s},z=async(t,r=w)=>{if(!t.body)return new ArrayBuffer(0);const e=t.body.getReader(),a=[];let i=0;for(;;){const{done:n,value:c}=await e.read();if(n)break;if(c){if(i+=c.byteLength,i>r)throw await e.cancel().catch(()=>{}),new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});a.push(c)}}const s=new Uint8Array(i);let o=0;for(const n of a)s.set(n,o),o+=n.byteLength;return s.buffer},j=async(t,r,e=w)=>{try{const a=await U(t,e);return a===""?{}:JSON.parse(a)}catch(a){throw a instanceof h?a:new h(`${r} body must be valid JSON`,{code:"BAD_REQUEST",status:400})}},Z=async(t,r=w)=>{const e=await j(t,"Request",r);if(!k(e))throw new h("Request body must be an object",{code:"BAD_REQUEST",status:400});return e},C=(t,r)=>{if(!k(t))throw new h(`${r} \`args\` must be an object`,{code:"BAD_REQUEST",status:400})},R="__lunora_vary",x="x-lunora-edge-cache",G=["x-d1-bookmark","x-lunora-shard-key"],M=()=>{try{return globalThis.caches?.default}catch{return}},_=t=>t.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r!==""),J=(t,r)=>{const e=t.headers.get("vary");return e===null?!0:_(e).every(a=>a!=="*"&&r.includes(a))},K=(t,r)=>{if(t===void 0||r===null||t.scope!=="public"||S(t.maxAge)<=0)return;const e=()=>r??M(),a=_(T(t)??""),i=o=>{const n=new URL(o.url);return n.searchParams.delete(R),a.length>0&&n.searchParams.set(R,a.map(c=>`${c}=${o.headers.get(c)??""}`).join("\0")),new Request(n.toString(),{method:"GET"})},s=(o,n)=>o.method==="GET"&&O(t,o,n)==="public";return{lookup:async(o,n)=>{const c=e();if(c===void 0||!s(o,n))return;let u;try{u=await c.match(i(o))}catch{return}if(u===void 0)return;const l=new Response(u.body,u);return l.headers.set(x,"hit"),l},store:(o,n,c)=>{const u=e();if(u===void 0||!s(n,c)||o.status!==200||o.headers.has("set-cookie")||o.headers.has("x-payment-response")||!J(o,a))return o;try{const l=new Response(o.clone().body,o);for(const g of G)l.headers.delete(g);const d=Promise.resolve(u.put(i(n),l)).catch(()=>{});c?.waitUntil&&c.waitUntil(d)}catch{}return o}}},N=()=>globalThis.navigator?.userAgent==="Cloudflare-Workers",Y=(t,r)=>{if(N())return t.get("cf-connecting-ip")??void 0;if(r===void 0)return;const e=t.get(r)?.trim();return e===void 0||e===""||e.includes(",")?void 0:e},F=t=>P(Object.entries(t).map(([r,e])=>({exposure:e.expose,functionPath:r,kind:e.kind}))),H=(t,r)=>{const e=t.searchParams.get("shardKey");if(e!==null&&e!=="")return e;const a=r.headers.get("x-lunora-shard-key");return a===null||a===""?void 0:a},I=t=>{const r=Object.create(null);for(const[e,a]of t.searchParams.entries())if(!(e==="shardKey"||e===R))try{r[e]=JSON.parse(a)}catch{r[e]=a}return r},q=t=>{const{edgeCache:r,functions:e,invoke:a,rateLimit:i,readJsonBody:s}=t,o={};for(const n of F(e)){const c=n.kind==="query"?["GET","POST"]:["POST"],u=e[n.functionPath].expose?.cache,l=K(u,r);o[n.path]=async(d,g,V,f)=>{const b=D(d,c);if(b)return b;const v=new URL(d.url);if(i){const m=await i(d,n.functionPath);if(m)return m}const E=await l?.lookup(d,f);if(E)return E;let y;d.method==="GET"?y=I(v):y=d.body===null?{}:await s(d),C(y,"REST");const A=H(v,d),L=await a({args:y,env:g,functionPath:n.functionPath,request:d,...A===void 0?{}:{shardKey:A},...f?.waitUntil===void 0?{}:{waitUntil:m=>f.waitUntil?.(m)}}),p=B(L,u,d,f);return l?l.store(p,d,f):p}}return o},Q="no-trusted-ip",ee=(t,r)=>async(e,a)=>{const i=(r.key?r.key(e,a):Y(e.headers,r.trustedClientIpHeader))??Q,s=await t.limit(r.name,{key:i});if(s.ok)return;if(s.reason==="deny")return Response.json({error:{code:"FORBIDDEN",message:"Request denied"}},{headers:{"content-type":"application/json"},status:403});const o=Math.max(1,Math.ceil(s.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(o)},status:429})};export{w as M,I as a,q as b,ee as c,Z as d,j as e,z as f,C as g,U as h,F as r,Y as t};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.98",
3
+ "version": "1.0.0-alpha.99",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1,6 +0,0 @@
1
- import{isLunoraError as Ln,toErrorBody as Mn}from"@lunora/errors";import{e as Mt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as jn}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as $n,f as Kn}from"./base64-Bl1_r2k1.mjs";import{e as Fn,a as Gn}from"./identity-header-C4Z5pldl.mjs";import{o as Ie,b as jt,p as Qn,m as zn,d as Wn,a as Vn,r as Jn}from"./otlp-resource-JKBCWf6c.mjs";import{e as ke,d as Ve,a as qn}from"./wire-codec-BLvSm5Mn.mjs";import{d as te,e as he,M as $t,b as Yn,f as Xn,g as Kt,t as Zn,h as Ft}from"./rest-routes-CyXGd_yB.mjs";import{LunoraError as c,toErrorResponse as dt}from"./LunoraError-DksAgIpa.mjs";import{a as j,m as we}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as Xe,BACKUP_KEY_PREFIX as Ze,isBackupManifestKey as er,backupObjectKeyOfManifest as Gt,backupObjectKey as tr,backupManifestKey as nr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as rr,buildStorageAdminRoutes as or,STORAGE_UPLOAD_MAX_BODY_BYTES as ar,STORAGE_PATH as sr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{b as ir,e as cr,f as ut,g as dr,h as ur}from"./export-tap-CAyZ2TWC.mjs";import{buildHealthRoutes as lr,durableObjectProbe as hr,d1Probe as fr,presenceProbe as Le}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as pr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Ms,routeIdentityResolvers as js}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as mr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{r as wr,f as lt,a as ce}from"./observability-B1hLjwgx.mjs";import{resolveShard as ge,applyJurisdiction as ht}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as ft,handleCorsPreflight as gr,enforceOrigin as yr,decorateResponse as Me,enforceWebSocketOrigin as pt}from"./decorateResponse-Y2sCM0w1.mjs";const br=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},Qt="__lunoraBranch",_r=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Qt),Rr=`may not contain the reserved workflow branch-marker key ("${Qt}")`,Er=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}},et=(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,u=a<t.length?t.charCodeAt(a):0;r|=i^u}return r===0},Sr=/already[\s_-]?exists/iu,Ar=e=>Sr.test(e instanceof Error?e.message:String(e)),Tr=(e,t,n,r)=>{const a=e.get(t);if(a!==void 0)return a;Mt(e,r);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},tt=new TextEncoder,Or=Array.from({length:32},(e,t)=>t);new RegExp(`[${Or.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const vr=64,kr=new Map,zt=async e=>Tr(kr,e,async()=>crypto.subtle.importKey("raw",tt.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),vr),Wt=async(e,t)=>{const n=await zt(e),r=await crypto.subtle.sign("HMAC",n,tt.encode(t));return $n(new Uint8Array(r))},Ir=async(e,t,n)=>{const r=await zt(e);return crypto.subtle.verify("HMAC",r,n,tt.encode(t))},Pr=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Pr);const Nr=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Dr=-100,Ur=15,Cr=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Nr.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Ur?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Dr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},mt=e=>{const t=e.cf;return t===void 0?void 0:Cr(t)},Je="::relay::",Br=(e,t)=>`${e}${Je}${String(t)}`,qe="::replica::",xr=(e,t)=>`${e}${qe}${t}`,Hr=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Lr=new Set(["1","enabled","on","true","yes"]),Mr=new Set(["0","disabled","false","no","off"]),jr=(e,t)=>{const n=(e??"").trim().toLowerCase();return Lr.has(n)?!0:Mr.has(n)?!1:t},Vt="v1",$r=6e4,Kr=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??$r),r=`${Vt}.${String(n)}`,a=await Wt(e,r);return{expiresAtMs:n,token:`${r}.${a}`}},Fr=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,u]=r;if(a!==Vt||u.length===0)return!1;const h=Number(i);if(!Number.isFinite(h)||h<=n)return!1;let p;try{p=Kn(u)}catch{return!1}return Ir(e,`${a}.${i}`,p)},P="/_lunora/admin/auth",Gr={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},D=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},le=(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},Jt=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,je=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},wt=e=>{const t=Jt(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},gt=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},Qr={[`${P}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${P}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${P}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${P}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${P}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${P}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${P}/sign-up-invitations/create`]:{build:({body:e})=>({email:D(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:re(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${P}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:D(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:je(e,"data"),email:D(e,"email"),name:D(e,"name"),password:re(e,"password"),role:Jt(e.role)}),http:"POST",method:"createUser"},[`${P}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:D(e,"userId")}},http:"POST",method:"updateUser"},[`${P}/users/role`]:{build:({body:e})=>({role:wt(e),userId:D(e,"userId")}),http:"POST",method:"setRole"},[`${P}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:D(e,"userId")}),http:"POST",method:"banUser"},[`${P}/users/unban`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"unbanUser"},[`${P}/users/password`]:{build:({body:e})=>({newPassword:D(e,"newPassword"),userId:D(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${P}/users/remove`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${P}/users/impersonate`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"impersonateUser"},[`${P}/sessions/revoke`]:{build:({body:e})=>({sessionId:D(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${P}/sessions/revoke-all`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${P}/accounts/unlink`]:{build:({body:e})=>({accountId:D(e,"accountId"),userId:D(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${P}/two-factor/disable`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${P}/passkeys/delete`]:{build:({body:e})=>({passkeyId:D(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${P}/organizations/members/remove`]:{build:({body:e})=>({memberId:D(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${P}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:D(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${P}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:je(e,"metadata"),name:D(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:je(e,"metadata"),name:re(e,"name"),organizationId:D(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${P}/organizations/remove`]:{build:({body:e})=>({organizationId:D(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${P}/organizations/members/add`]:{build:({body:e})=>({organizationId:D(e,"organizationId"),role:re(e,"role"),userId:D(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:D(e,"email"),inviterId:re(e,"inviterId"),organizationId:D(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:D(e,"memberId"),role:wt(e)}),http:"POST",method:"updateMemberRole"},[`${P}/organizations/teams/create`]:{build:({body:e})=>({name:D(e,"name"),organizationId:D(e,"organizationId")}),http:"POST",method:"createTeam"},[`${P}/organizations/teams/update`]:{build:({body:e})=>({name:D(e,"name"),teamId:D(e,"teamId")}),http:"POST",method:"updateTeam"},[`${P}/organizations/teams/remove`]:{build:({body:e})=>({teamId:D(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${P}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:D(e,"teamId"),userId:D(e,"userId")}),http:"POST",method:"addTeamMember"},[`${P}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:D(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${P}/organizations/roles/create`]:{build:({body:e})=>({organizationId:D(e,"organizationId"),permission:gt(e),role:D(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:gt(e),roleId:D(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${P}/organizations/roles/remove`]:{build:({body:e})=>({roleId:D(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},zr=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof c)throw i;const u=i,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:h,status:Gr[h]??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 u=e.getAuthAdmin();if(u===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[i.method];if(h===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const p=new URL(a.url),w={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:T=>e.queryParameter(p,T)},S=i.build(w),A=await t(()=>h(S));return Response.json(i.returns==="void"?{ok:!0}:A,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[a,i]of Object.entries(Qr))r[a]=u=>n(u,i);return r},yt="__lunora_admin__:getAuthAuditLog",bt=e=>typeof e=="string"&&e!==""?e:void 0,_t=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Wr=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=bt(r.actorId),u=bt(r.event),h=_t(r.sinceSeq),p=_t(r.limit),w={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...p===void 0?{}:{limit:p}};let S;try{S=await a.read(w)}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 A={entries:S};return Response.json({result:ke(A)},{headers:{"content-type":"application/json"},status:200})},Vr=(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}},Jr=async(e,t,n,r,a,i,u)=>{if(n!==void 0&&r.length===0)return;const h=await e.orchestrateExport(i,{args:{tables:r},defaultShardKey:u,headers:t,tables:r});for(const p of h.shards)if(!p.error)for(const w of p.rows??[])a(w)},qt=async(e,t,n,r,a,i)=>{const u=r??e.listSchemaTables?.();r===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:h,shardLocalTables:p}=Vr(e,u);await Jr(t,n,u,p,a,i,e.defaultShardKey??"__root__");const w=e.exportGlobals;if((r===void 0||h.length>0)&&w)for await(const A of w({tables:h}))a(A)},qr=new TextEncoder,Yr=1e3,Yt=10,Xr=200,Rt=8,Xt="lunoraBackupCron",Et=24*1048576,St=e=>{const t=e.slice(0,Yt).map(r=>Gt(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Zr=(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},nt=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let u=0;u<Yr;u+=1){const h=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const p of h.objects)er(p.key)&&p.customMetadata?.[Xt]===r&&a.push(p.key);if(!h.truncated||h.cursor===void 0)break;i=h.cursor}return{eligible:a.length,stale:a.toSorted((u,h)=>h.localeCompare(u)).slice(n)}},eo=async(e,t,n,r,a)=>{const{stale:i}=await nt(e,t,n,r),u=new Set(a),h=i.filter(y=>u.has(y)),p=h.slice(0,Xr),w=i.length-p.length,S=a.length-h.length;if(p.length===0)return{deleted:[],failed:[],ignored:S,remaining:w};const A=[],T=[];for(let y=0;y<p.length;y+=Rt){const _=await Promise.allSettled(p.slice(y,y+Rt).map(async R=>(await e.delete(Gt(R)),await e.delete(R),R)));for(const[R,f]of _.entries())f.status==="fulfilled"?A.push(f.value):T.push(p[y+R])}return A.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(A.length)}: ${St(A)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${St(T)}`),{deleted:A,failed:T,ignored:S,remaining:w}},to=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=Xe(e.backupPrefix??Ze),r=e.backupCron,{eligible:a,stale:i}=r===void 0?{eligible:0,stale:[]}:await nt(t,n,e.backupRetain,r);return{cron:r,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},no=async(e,t,n,r)=>{const a=e.backupStore,i=e.queryCoordinator;if(!a)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!i)throw new c("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!n||n.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 u={authorization:`Bearer ${n}`,"content-type":"application/json"},h=e.backupTables;let p=0,w=0,S=[];await qt(e,i,u,h,U=>{const M=qr.encode(`${JSON.stringify(U)}
2
- `);if(p+=1,w+=M.byteLength,w>Et)throw new c(`scheduled backup reached ${String(w)} bytes of NDJSON, past the ${String(Et)}-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});S.push(M)},t);const T=Xe(e.backupPrefix??Ze),y=new Date(r.scheduledTime).toISOString(),_=tr(T,y),R=Zr(S,w);S=[];const f=rr(await crypto.subtle.digest("SHA-256",R));await a.put(_,R,{httpMetadata:{contentType:"application/x-ndjson"},sha256:f});const v={bytes:w,createdAt:y,cron:r.cron,file:_,id:y,rows:p,scheduledTime:r.scheduledTime,sha256:f,...h?{tables:h.join(",")}:{}};await a.put(nr(_),`${JSON.stringify(v,void 0,2)}
3
- `,{customMetadata:{[Xt]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:U}=await nt(a,T,e.backupRetain,r.cron);if(U.length>0){const M=U.slice(0,Yt),N=U.length-M.length;console.info(`[lunora] backup retention: ${String(U.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${M.join(", ")}${N>0?` (+${String(N)} more)`:""}`)}}catch(U){console.warn(`[lunora] backup ${_} was written, but the retention report failed:`,U)}},ro=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 eo(n,Xe(e.backupPrefix??Ze),a,r,t)},oo="/_lunora/admin/backup/retention",ao="/_lunora/admin/backup/prune",so=e=>{const{options:t,readJsonBody:n,requireAdminOption:r}=e,a=(h,p)=>{r(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${p} requires a \`backupStore\` on the worker`})},i=async h=>(j(h,"GET","Backup-retention"),a(h,"retention preview"),Response.json(await to(t),{headers:{"cache-control":"no-store"}})),u=async h=>{j(h,"POST","Backup-prune"),a(h,"prune");const{confirm:p}=await n(h);if(!Array.isArray(p)||p.some(w=>typeof w!="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 ro(t,p),{headers:{"cache-control":"no-store"}})};return{[ao]:u,[oo]:i}},At=500,io=(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});return{entry:{args:r.args===void 0?{}:r.args,clientId:typeof r.clientId=="string"?r.clientId:void 0,clientSeq:typeof r.clientSeq=="number"?r.clientSeq:void 0,functionPath:r.functionPath,id:typeof r.id=="number"?r.id:t,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:n}},co=(e,t)=>{if(e.length>At)throw new c(`RPC batch exceeds the ${String(At)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map;for(const[r,a]of e.entries()){const{entry:i,shardKey:u}=io(a,r,t),h=n.get(u)??[];h.push(i),n.set(u,h)}return n},uo="/_lunora/admin/export",lo="/_lunora/admin/import",ho="/_lunora/admin/sync",fo="/_lunora/admin/connector/sync",po="/_lunora/admin/apply",mo="/_lunora/admin/export-tap/run",wo=new TextEncoder,go=async e=>{const n=await he(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}},$e=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,yo=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:a,knownTables:i,queryCoordinator:u,assertAdmin:h,requireAdminOption:p,resolveForwardContext:w,shardDO:S,streamExportRows:A,streamingImport:T,syncGlobals:y}=e,_=async(N,K)=>{const $=we(N,["POST"]);if($)return $;const V=p(N,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),B=await go(N),{headers:J}=await w(N,K),F=new ReadableStream({async pull(q){const ee=L=>{q.enqueue(wo.encode(`${JSON.stringify(L)}
4
- `))};try{await A(V,J,B.tables,ee),q.close()}catch(L){q.error(L)}}});return new Response(F,{headers:{"content-type":"application/x-ndjson"},status:200})},R=async(N,K)=>{const $=we(N,["POST"]);if($)return $;const V=p(N,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),B=await te(N),J=typeof B.cursors=="object"&&B.cursors!==null?B.cursors:{},F=typeof B.limit=="number"?B.limit:void 0,q=typeof B.globalCursor=="number"?B.globalCursor:0,ee=$e(B.tables),{headers:L}=await w(N,K),Y=ee??i(),G=await V.orchestrateCdcSync(S,{cursors:J,defaultShardKey:n,headers:L,limit:F,tables:Y}),fe=y?await y({limit:F,sinceSeq:q}):void 0;return Response.json({global:fe,shards:G.shards},{status:200})},f=async(N,K)=>{const $=we(N,["POST"]);if($)return $;const V=p(N,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),B=await te(N),J=cr(B.cursor),F=typeof B.limit=="number"&&B.limit>0?B.limit:void 0,q=$e(B.tables),{headers:ee}=await w(N,K),L=q??i(),Y=await V.orchestrateCdcSync(S,{cursors:J.s,defaultShardKey:n,headers:ee,limit:F,tables:L}),G=[],fe={...J.s};let ae=!1;for(const se of Y.shards)ae=ut(G,se.changes??[],ur(F))||ae,fe[se.shardKey]=se.cursor;let _e=J.g;if(y){const se=await y({limit:F,sinceSeq:J.g});ae=ut(G,se.changes,F)||ae,_e=se.cursor}const Pe=dr({g:_e,s:fe,v:1}),Ne={changes:G,hasMore:ae,nextCursor:Pe};return Response.json(Ne,{status:200})},v=async(N,K)=>{const $=we(N,["POST"]);if($)return $;const V=p(N,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),B=await te(N),F=(Array.isArray(B.batches)?B.batches:[]).map(G=>G).filter(G=>G!==null&&typeof G=="object"&&typeof G.shardKey=="string"&&Array.isArray(G.changes)),q=Array.isArray(B.globalChanges)?B.globalChanges:[],{headers:ee}=await w(N,K),L=await V.orchestrateApplyCdc(S,{batches:F,headers:ee}),Y=q.length>0&&t?await t({changes:q}):0;return Response.json({applied:L.applied+Y,failed:L.failed,ok:L.ok},{status:200})},U=async(N,K)=>{const $=we(N,["POST"]);if($)return $;h(N);const{headers:V}=await w(N,K),B=await T(N,V);return Response.json(B,{headers:{"content-type":"application/json"},status:B.failed.length>0?207:200})},M=async(N,K)=>{const $=we(N,["POST"]);if($)return $;const V=p(N,u,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(a===void 0||Object.keys(a).length===0||r===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const B=await te(N),J=typeof B.sink=="string"?B.sink:void 0,F=typeof B.limit=="number"&&B.limit>0?B.limit:void 0,q=$e(B.tables);if(J===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const ee=a[J];if(ee===void 0)throw new c(`Export-tap sink "${J}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:L}=await w(N,K),Y=q??i(),G=await ir({coordinator:V,cursorStore:r,defaultShardKey:n,headers:L,limit:F,shardDO:S,sink:ee,tables:Y});return Response.json(G,{headers:{"content-type":"application/json"},status:200})};return{[po]:v,[fo]:f,[uo]:_,[mo]:M,[lo]:U,[ho]:R}},bo=(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}},_o=(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}},Ro=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 u=0,h=0;const p=e.body.getReader(),w=new TextDecoder;let S="",A=0;const T=y=>{h+=1;const _=y.trim();if(_.length===0)return;u+=1;const R=bo(_,h);if(!R.ok){r.push(R.error);return}const{doc:f,table:v}=R,U=t.resolveTableSharding?.(v);if(U?.mode.kind==="global"){a.push({doc:f,line:h,table:v});return}const M=_o(f,v,U,n,h);if(!M.ok){r.push(M.error);return}const N=i.get(M.shardKey);N?N.rows.push({doc:f,table:v}):i.set(M.shardKey,{rows:[{doc:f,table:v}],shardKey:M.shardKey,startLine:h})};for(;;){const{done:y,value:_}=await p.read();if(y)break;if(_&&(A+=_.byteLength,A>$t))throw await p.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});S+=w.decode(_,{stream:!0});let R=S.indexOf(`
5
- `);for(;R!==-1;){const f=S.slice(0,R);S=S.slice(R+1),T(f),R=S.indexOf(`
6
- `)}}return S.length>0&&T(S),{errors:r,globalRows:a,perShard:i,received:u}},Eo=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),Tt=(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},So=async(e,t,n,r)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:h,received:p}=await Ro(e,t,a),w={conflicts:0,errors:i,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 A=t.queryCoordinator;if(!A)throw new c("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const T=await A.orchestrateImport(r,{batches:[...h.values()],headers:n});Tt(w,T),w.failed.push(...Eo(T.shards))}if(u.length>0)if(t.importGlobals){const A=u[0]?.line??1,T=await t.importGlobals({rows:u,startLine:A});Tt(w,T)}else for(const A of u)w.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:A.line,message:`row targets global table "${A.table}" but no \`importGlobals\` is configured`,table:A.table});return{conflicts:w.conflicts,errors:w.errors,failed:w.failed,inserted:w.inserted,received:p,...S.length>0?{warnings:S}:{}}},Ke=e=>typeof e=="object"&&e!==null?e:{},Fe=e=>typeof e.kind=="string"?e.kind:"unknown",Ao=(e,t)=>{let n=Ke(t),r=!1;Fe(n)==="optional"&&(r=!0,n=Ke(n._meta?.inner));const a=Fe(n),i=n._meta??{},u={kind:a,name:e,optional:r};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const h=Fe(Ke(i.inner));h!=="unknown"&&(u.element=h)}return u},To=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>Ao(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),Oo="/_lunora/admin/functions",vo="/_lunora/admin/cron-jobs",ko="/_lunora/admin/openapi",Io="/_lunora/admin/openrpc",Po="/_lunora/admin/global/tables",No="/_lunora/admin/global/table",Do="/_lunora/admin/global/facet",Ot=e=>{if(e===void 0||e==="")return;let t;try{t=Ve(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},Uo=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:{}}),Co=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"}),Bo=e=>{const{assertAdmin:t,options:n,parsePaging:r,queryParameter:a,requireAdminOption:i}=e,u=y=>{j(y,"GET","Functions");const _=i(y,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),R=Object.entries(_).flatMap(([f,v])=>v.visibility==="internal"||v.kind==="stream"?[]:[{args:To(v.args),kind:v.kind,path:f}]).toSorted((f,v)=>f.path.localeCompare(v.path));return Response.json({functions:R},{headers:{"content-type":"application/json"},status:200})},h=y=>{j(y,"GET","Cron-jobs");const _=i(y,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),R=Object.entries(_).flatMap(([f,v])=>v.map(U=>({args:U.args,cron:f,functionPath:U.functionPath,name:U.name,shardKey:U.shardKey,workflow:U.workflow}))).toSorted((f,v)=>f.name.localeCompare(v.name));return Response.json({jobs:R},{headers:{"content-type":"application/json"},status:200})},p=y=>(j(y,"GET","OpenAPI"),t(y),Response.json(n.openApiSpec??Uo,{headers:{"content-type":"application/json"},status:200})),w=y=>(j(y,"GET","OpenRPC"),t(y),Response.json(n.openRpcSpec??Co,{headers:{"content-type":"application/json"},status:200})),S=async y=>{j(y,"GET","Global-tables");const _=i(y,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await _.listTables(),{headers:{"content-type":"application/json"},status:200})},A=async y=>{j(y,"GET","Global-table");const _=i(y,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(y.url),f=a(R,"table");if(f===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const v=await _.readTablePage({...r(y),filters:Ot(a(R,"filters")),table:f});return Response.json(v,{headers:{"content-type":"application/json"},status:200})},T=async y=>{j(y,"GET","Global-facet");const _=i(y,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(y.url),f=a(R,"table"),v=a(R,"column");if(f===void 0||v===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const U=a(R,"limit"),M=U===void 0?void 0:Number(U),N=await _.facetColumn({column:v,filters:Ot(a(R,"filters")),limit:M!==void 0&&Number.isFinite(M)?M:void 0,table:f});return Response.json(N,{headers:{"content-type":"application/json"},status:200})};return{[vo]:h,[Oo]:u,[Do]:T,[No]:A,[Po]:S,[ko]:p,[Io]:w}},xo="/_lunora/admin/kv/namespaces",Ho="/_lunora/admin/kv/keys",Zt="/_lunora/admin/kv/value",en=32*1048576,vt=60,Lo=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=_=>n(_,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=_=>Response.json(_,{headers:{"content-type":"application/json"},status:200}),i=(_,R)=>{const f=new URL(_.url),v=f.searchParams.get("namespace")??"",U=f.searchParams.get("key")??"";if(v==="")throw new c(`KV-value ${R} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(U==="")throw new c(`KV-value ${R} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:U,namespace:v}},u=async(_,R)=>{if(!(await _.listNamespaces()).some(v=>v.binding===R))throw new c(`Unknown KV namespace binding \`${R}\``,{code:"NOT_FOUND",status:404})},h=async _=>(j(_,"GET","KV-namespaces"),a({namespaces:await r(_).listNamespaces()})),p=async _=>{j(_,"GET","KV-keys");const R=r(_),f=new URL(_.url),v=f.searchParams.get("namespace")??"";if(v==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const U=f.searchParams.get("prefix")??void 0,M=f.searchParams.get("cursor")??void 0,N=f.searchParams.get("limit"),K=N===null?void 0:Number.parseInt(N,10);if(K!==void 0&&(!Number.isInteger(K)||K<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const $=K===void 0?void 0:Math.min(K,1e3);return await u(R,v),a(await R.listKeys({cursor:M,limit:$,namespace:v,prefix:U}))},T={DELETE:async _=>{const R=r(_),f=i(_,"DELETE");return await u(R,f.namespace),await R.deleteKey(f),a({deleted:!0})},GET:async _=>{const R=r(_),f=i(_,"GET");return await u(R,f.namespace),a(await R.getValue(f))},PUT:async _=>{const R=r(_),f=await t(_,en);if(typeof f.namespace!="string"||f.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof f.key!="string"||f.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof f.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(f.expirationTtl!==void 0&&(typeof f.expirationTtl!="number"||!Number.isInteger(f.expirationTtl)||f.expirationTtl<vt))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const v=Math.floor(Date.now()/1e3)+vt;if(f.expiration!==void 0&&(typeof f.expiration!="number"||!Number.isInteger(f.expiration)||f.expiration<v))throw new c("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(R,f.namespace),await R.putValue({expiration:f.expiration,expirationTtl:f.expirationTtl,key:f.key,metadata:f.metadata,namespace:f.namespace,value:f.value}),a({ok:!0})}},y=_=>{const R=T[_.method];if(!R)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return R(_)};return{[xo]:h,[Ho]:p,[Zt]:y}},Mo="/_lunora/migrate",jo="/_lunora/admin/pitr",$o="/_lunora/admin/rank",Ko="/_lunora/admin/rankpage",Fo="/_lunora/admin/shard-traffic",Go=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Qo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),zo=async e=>{const n=await he(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"||!Go.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}},Wo=async e=>{const n=await he(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}},Vo=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}},Jo=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})},qo=async e=>{const n=await he(e,"Rank page")??{};Jo(n);const r=Vo(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}},Yo=async e=>{const n=await he(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}},Xo=async e=>{const n=await te(e);if(typeof n.functionPath!="string"||!Qo.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}},Zo=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:r,queryCoordinator:a,resolveForwardContext:i,shardDO:u}=e,h=(y,_)=>{if(y.method!=="POST")throw new c(`${_} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(y))throw new c("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new c(`${_} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},p=async(y,_)=>{const R=h(y,"Migration"),f=await zo(y),{headers:v}=await i(y,_),U=await R.orchestrateMigration(u,{args:f.args,defaultShardKey:t,functionPath:f.functionPath,headers:v,table:f.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},w=async(y,_)=>{const R=h(y,"Rank"),f=await Wo(y),{headers:v}=await i(y,_),U=await R.orchestrateRank(u,{headers:v,index:f.index,partitionKey:f.partitionKey,rowId:f.rowId,sortValues:f.sortValues,table:f.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},S=async(y,_)=>{const R=h(y,"Rank page"),f=await qo(y),{headers:v}=await i(y,_),U=await R.orchestrateRankPage(u,{...f,headers:v});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},A=async(y,_)=>{const R=h(y,"Shard-traffic"),f=await Yo(y),{headers:v}=await i(y,_),U=await R.orchestrateShardTraffic(u,{headers:v,table:f.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},T=async(y,_)=>{if(j(y,"POST","PITR"),!r(y))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const R=await Xo(y),{headers:f}=await i(y,_),v=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:R.args,functionPath:R.functionPath}),headers:f,method:"POST"});return n(u,R.shardKey??t,v)};return{[Mo]:p,[jo]:T,[$o]:w,[Ko]:S,[Fo]:A}},ea=1,ta=0,na=32,ra=512,oa=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,aa=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>ra)return;const n=t.split(",");if(!(n.length>na)){for(const r of n)if(!oa.test(r.trim()))return;return t}},sa=e=>{const t=Qn(e.headers.get("traceparent"));if(t===void 0)return;const n=aa(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},ia=(e,t={})=>{const n=sa(e),r=t.trustInbound===!0?n:void 0,a=Ie(8),i=r?.traceId??Ie(16),u=wr(t.sampling,r===void 0?a:i),h=u.isTraced&&(r===void 0||r.sampled);return{decision:u,ignoredUpstream:n!==void 0&&r===void 0,trace:{sampled:h,spanId:a,traceFlags:h?ea:ta,traceId:i,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState}}}},ca=(e,t)=>{t.traceparent=jt(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},da=(e,t)=>{let n;return()=>{if(n===void 0){const r=Jn(e),a=t===void 0?void 0:t.cf;n=zn(Vn(r),Wn(r,a))}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:a}=e,i=(w,S)=>A=>{if(A.method!=="GET")throw new c(`${S} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(A.url).searchParams.get("cursor"),y=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return r(A).fetch(new Request(`https://scheduler.internal${w}${y}`,{method:"GET"}))},u=(w,S,A=S)=>async T=>{if(T.method!=="POST")throw new c(`${A} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const y=r(T),_=await he(T,S);if(typeof _?.id!="string"||_.id==="")throw new c(`${S} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return y.fetch(new Request(`https://scheduler.internal${w}`,{body:JSON.stringify({id:_.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async w=>{if(w.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const S=r(w),A=await he(w,"Scheduled pool-release");if(typeof A?.pool!="string"||A.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const T=typeof A.id=="string"&&A.id!==""?A.id:void 0;return S.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(T===void 0?{pool:A.pool}:{id:T,pool:A.pool}),headers:{"content-type":"application/json"},method:"POST"}))},p=async w=>{if(w.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(w))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const S=n();return ge(S,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[fa]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[wa]:u("/dead/cancel","Scheduled dead-letter action"),[pa]:i("/dead","Scheduled dead-letter"),[ma]:u("/dead/retry","Scheduled dead-letter action"),[ua]:i("/list","Scheduled-list"),[ga]:h,[la]:i("/status","Scheduler-status"),[ha]:p}},ba=(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},kt={mtls:e=>ba(e,"tlsClientAuth","certVerified")==="SUCCESS"},_a=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(kt,e)?kt[e]:void 0)??(()=>!1),Ra=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},Ea="/_lunora/admin/vector/indexes",Sa="/_lunora/admin/vector/query",Aa=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=async i=>{j(i,"GET","Vector-indexes");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async i=>{j(i,"POST","Vector-query");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new c("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const p=await t(i);if(typeof p.name!="string"||p.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof p.text!="string"||p.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(p.topK!==void 0&&(typeof p.topK!="number"||!Number.isInteger(p.topK)||p.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const w=await u.queryIndex({name:p.name,text:p.text,topK:p.topK});return Response.json(w,{headers:{"content-type":"application/json"},status:200})};return{[Ea]:r,[Sa]:a}},Ta="/_lunora/admin/workflows/instances",Oa="/_lunora/admin/workflows/instance",va="/_lunora/admin/workflows/status",ka={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Ia=e=>e!==null&&Object.hasOwn(ka,e)?e:void 0,It=(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},Ge=(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},Pt=()=>{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})},Pa=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,r=async(u,h,p)=>{j(u,"GET","Workflows instances"),t(u);const w=n(h);if(!w)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const S=Ge(p,"name"),A=Ia(p.searchParams.get("status"));return Response.json(await w.listInstances({page:It(p,"page"),perPage:It(p,"perPage"),status:A,workflowName:S}))},a=async(u,h,p)=>{j(u,"GET","Workflows instance"),t(u);const w=n(h);return w?Response.json(await w.getInstance({instanceId:Ge(p,"id"),workflowName:Ge(p,"name")})):Pt()},i=async(u,h)=>{j(u,"POST","Workflows status"),t(u);const p=n(h);if(!p)return Pt();const w=await u.json().catch(()=>{});if(typeof w?.name!="string"||w.name===""||typeof w.id!="string"||w.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:S}=w;if(S!=="pause"&&S!=="resume"&&S!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await p.setInstanceStatus({action:S,instanceId:w.id,workflowName:w.name}))};return{[Oa]:a,[Ta]:r,[va]:i}},Na={[Zt]:en,[sr]:ar},Nt="/_lunora/rpc",Da="/_lunora/rpc-batch",Ua="/_lunora/ws",be=(e,t,n)=>({resourceAttributes:da(e,t),...n===void 0?{}:{waitUntil:n}}),Qe=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Dt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),ze=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let r;try{r=new URL(e.url)}catch{return{method:t,userAgent:n}}const a=r.port===""?void 0:Number(r.port);return{host:r.hostname,method:t,path:r.pathname,port:Number.isNaN(a)?void 0:a,scheme:r.protocol.replace(":",""),userAgent:n}},Ut="/_lunora/voice/",Ca="/_lunora/scheduler/dispatch",Ba="/_lunora/admin/cron-jobs/run",xa="/_lunora/admin/ws-token",Ha="/_lunora/admin/",La="/_lunora/",Ma="/_lunora/migrate",ja="/_lunora/status",$a=e=>e.startsWith(Ha)||e===Ma,Ka="__lunora_relation__:",Se=e=>{if(e.startsWith(Ka))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Ae=async e=>await e===!0,Fa=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}}},Ct="/api/auth",Ga="__lunora_admin__:recordAuthEvent",Qa="__lunora_admin__:listPushSubscriptions",za=["/sign-in","/sign-up","/callback"],Wa=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const r=e.slice(n.length);return za.some(a=>r===a||r.startsWith(`${a}/`))},Va=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},Te=(e,t,n,r)=>{const a=Ln(n),i=a?n.code:"INTERNAL_SERVER_ERROR",u=a?n.status:500,h=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:h,status:u},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},Ja=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},Bt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,qa=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},Ye=new WeakMap,de=async(e,t,n,r=Ye.get(e))=>{const a={"content-type":"application/json"},i=e.headers.get("authorization"),u=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),p=e.headers.get("x-lunora-mutation-id"),w=e.headers.get("x-lunora-client-id"),S=e.headers.get("x-lunora-client-seq");i&&(a.authorization=i),u&&(a.cookie=u),h&&(a["x-d1-bookmark"]=h),p&&(a["x-lunora-mutation-id"]=p),w&&(a["x-lunora-client-id"]=w),S&&(a["x-lunora-client-seq"]=S);const A=Zn(e.headers);if(A&&(a["x-lunora-client-ip"]=A),!n)return{claims:null,headers:a,identity:null,userId:null};const T=await n(e,t,r);if(!T||typeof T.userId!="string"||T.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=Fn(T.userId);const y=Ja(T);y!==void 0&&(a["x-lunora-identity-exp"]=String(y));const{userId:_,...R}=T,f=Object.keys(R).length>0?R:null;return f&&(a["x-lunora-identity"]=Gn(f)),{claims:f,headers:a,identity:T,userId:_}},Ya=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Xa=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"||!Ya.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},Za=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},We=(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}},es=async e=>{const t=await Ft(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&&Kt(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=Xa(a.fanOut),u=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==i.table)throw new c("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},Oe=new Map,ts=5e3,ns=4096,rs=async(e,t)=>{const n=Date.now(),r=Oe.get(t);if(r!==void 0&&r.expiresMs>n)return r.relayCount;r!==void 0&&Oe.delete(t);let a=0;try{const i=await ge(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const h=(await i.json()).relayCount;typeof h=="number"&&h>0&&(a=Math.floor(h))}}catch{a=0}return Mt(Oe,ns),Oe.set(t,{expiresMs:n+ts,relayCount:a}),a},xt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},ve=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),os=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],as=(e,t)=>{for(const n of os){e.delete(n);const r=t[n];r!==void 0&&e.set(n,r)}},Ht=(e,t)=>{const n=new Headers(e.headers),r=[...n.keys()];for(const a of r)a.startsWith("x-lunora-")&&n.delete(a);return as(n,t),n},ss=async(e,t,n)=>e.length===0||n.length===0?!1:et(await Wt(e,t),n),Lt=(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:et(t,a.join(" ").trim())},is=async(e,t,n)=>{if(!t||t.length===0)return!1;const r=new URL(e.url).searchParams.get("token");return r===null?!1:await Fr(t,r)?!0:n?!1:et(t,r)},cs=(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 fr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return Le(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return Le(`queue:${e}`,!0);if(typeof n.connectionString=="string")return Le(`hyperdrive:${e}`,!0)},ds=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})},tn=e=>{ds(e);const t=_a(e.trustInboundTraceContext),n=Ra(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",a=pr(e.resolveIdentity,e.identity),i=ht(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:ht(e.schedulerDO,e.jurisdiction);let h=!1;const p=o=>{if(o===void 0||e.jurisdiction===void 0)return o;h||(h=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},w=async(o,s,l,d=e.shardRegion?.(s))=>ge(o,s,p(d)).fetch(l);let S;const A=()=>e.adminToken??S;let T;const y=()=>e.requireEphemeralWsToken??T??!0;let _;const R=o=>{const s=o??{};if(_??=xt(o,e.shardDO),T===void 0&&e.requireEphemeralWsToken===void 0){const d=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof d=="string"&&d.length>0&&(T=jr(d,!0))}if(S!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(S=l)},f=new WeakSet,v=o=>Lt(o,A())||f.has(o),U=async o=>{if(!(e.adminGate===void 0||f.has(o)))try{await Ae(e.adminGate(o,Ye.get(o)))&&f.add(o)}catch{}},M=async(o,s)=>{const l=await de(o,s,e.resolveIdentity);if(f.has(o)&&l.headers.authorization===void 0){const d=A();d!==void 0&&(l.headers.authorization=`Bearer ${d}`)}return l};let N=!1,K=!1;const $=()=>{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 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})}N||(N=!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("")))},B=async(o,s)=>{if(s.includes(Je)||s.includes(qe))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(e.authorizeShard){if(!await Ae(e.authorizeShard({identity:o,shardKey:s})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==r&&V("shard")},J=Zo({defaultShard:r,forwardToShard:w,isAdmin:v,queryCoordinator:e.queryCoordinator,resolveForwardContext:M,shardDO:i}),F=async(o,s,l,d,m,b)=>{Se(o);const O={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(O["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(O["x-lunora-identity"]=m.identity),d!==void 0&&d.length>0&&(O["x-lunora-mutation-id"]=d),b!==void 0&&b.length>0&&(O.traceparent=b),w(i,l,ve(o,s,O))},q=async(o,s,l,d,m)=>{const b=l?.[o];if(!b||typeof b.create!="function")throw new c(`${d} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(_r(s))throw new c(`${d} params ${Rr}`,{code:"BAD_REQUEST",status:400});try{await b.create(m===void 0?{params:s}:{id:m,params:s})}catch(O){if(!Ar(O))throw O}},ee=async(o,s,l)=>{if(o.workflow){await q(o.workflow,o.args??{},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 d=await F(o.functionPath,o.args??{},o.shardKey??r,void 0,void 0,l);if(!d.ok)throw new c(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(d.status)}`,{code:"CRON_JOB_FAILED",status:500})},L=o=>{if(!v(o))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},Y=(o,s,l)=>{if(L(o),s===void 0)throw new c(l.message,{code:l.code,status:400});return s},G=async(o,s,l,d,m)=>{const b=e.cronJobs?.[o];if(!b)return 0;for(const O of b)try{await ee(O,s,m)}catch(k){l.push(d(k))}return b.length},fe=async(o,s)=>{if(L(o),j(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 l=await te(o),d=typeof l.name=="string"?l.name:"";if(d==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(b=>b.name===d);if(!m)throw new c(`no cron job named "${d}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await ee(m,s),Response.json({name:d,ran:!0},{status:200})},ae=async o=>{const s=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!s||!u||typeof o.id!="string")return;const l=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await ge(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},_e=async(o,s)=>{j(o,"POST","Scheduler dispatch");const l=await Ft(o),d=s??{},m=typeof d.LUNORA_SCHEDULER_SECRET=="string"?d.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof d.LUNORA_ADMIN_TOKEN=="string"?d.LUNORA_ADMIN_TOKEN:void 0),O=o.headers.get("x-lunora-scheduler-signature");let k=!1;if(O&&m?k=await ss(m,l,O):b&&(k=Lt(o,b)),!k)throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let I;try{I=JSON.parse(l)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const g=I??{},E=g.args??{},C=typeof g.id=="string"&&g.id.length>0?g.id:void 0;if(typeof g.workflow=="string"&&g.workflow.length>0)return await q(g.workflow,E,s,"scheduled workflow",C),await ae(g),Response.json({ok:!0},{status:200});if(typeof g.functionPath!="string"||g.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const x=typeof g.shardKey=="string"&&g.shardKey.length>0?g.shardKey:r,Q=Fa(o),H=await F(g.functionPath,E,x,C,Q,o.headers.get("traceparent")??void 0);return await ae(g),H},Pe=Wr({assertAdmin:L,getReader:()=>e.authAuditReader}),Ne=async(o,s)=>{L(o);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:ke({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const d=s?.kind,m=s?.userId,b=s?.limit,O=d==="fcm"||d==="web-push"?d:void 0,k=typeof m=="string"&&m!==""?m:void 0,I=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,g=I>0?Math.min(I,1e3):1e3,C=(await l.list({kind:O,limit:g,userId:k})).filter(x=>O!==void 0&&x.kind!==O?!1:k===void 0||(x.userId??null)===k).map(({keys:x,token:Q,...H})=>H);return Response.json({result:ke({subscriptions:C})},{headers:{"content-type":"application/json"},status:200})},se=async(o,s)=>{if(!s.fanOut&&!(s.functionPath!==yt&&s.functionPath!==Qa))return await U(o),s.functionPath===yt?Pe(o,s.args??{}):Ne(o,s.args)},nn=yo({applyGlobals:e.applyGlobals,assertAdmin:L,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:r,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:Y,resolveForwardContext:M,shardDO:i,streamExportRows:(o,s,l,d)=>qt(e,o,s,l,d,i),streamingImport:(o,s)=>So(o,e,s,i),syncGlobals:e.syncGlobals}),De=(o,s)=>{const l=o.searchParams.get(s);return l===null||l===""?void 0:l},Ue=o=>{const s=new URL(o.url),l=s.searchParams.get("limit"),d=s.searchParams.get("offset"),m=l===null?void 0:Number.parseInt(l,10),b=d===null?void 0:Number.parseInt(d,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},rt=()=>{if(u===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},rn=ya({checkWsAdmin:async o=>v(o)||is(o,A(),y()),requireSchedulerNamespace:rt,resolveSchedulerStub:o=>(L(o),ge(rt(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),on=Pa({assertAdmin:L,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),an=or({assertAdmin:L,parsePaging:Ue,queryParameter:De,readBodyBytes:Xn,requireAdminOption:Y,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),sn=so({options:e,readJsonBody:te,requireAdminOption:Y}),cn=Aa({readJsonBody:te,requireAdminOption:Y,vectorIntrospector:e.vectorIntrospector}),dn=Lo({kvIntrospector:e.kvIntrospector,readJsonBody:te,requireAdminOption:Y}),un=mr({logArchive:e.logArchive,readJsonBody:te,requireAdminOption:Y}),ln=Bo({assertAdmin:L,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ue,queryParameter:De,requireAdminOption:Y}),hn=o=>{const s=[],l=i??o?.SHARD;if(l!==void 0&&s.push(hr("durable-object:default",l,r)),e.health?.disableBindingProbes!==!0)for(const[d,m]of Object.entries(o??{})){const b=cs(d,m);b!==void 0&&s.push(b)}for(const d of e.health?.probes??[])s.push(d);return s},fn=lr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:v,resolveProbes:hn}),pn=o=>{const s=g=>"args"in g?{...g,args:Ve(g.args)}:g,l=e.schedulerInstanceName??"default",d=()=>ge(o,l),m=async(g,E)=>{const C=await d().fetch(new Request(`https://scheduler.internal${g}`,E));if(!C.ok)throw new c(`ctx.scheduler: SchedulerDO ${g} failed (${String(C.status)}): ${await C.text()}`,{code:"INTERNAL",status:500});return await C.json()},b=async(g,E)=>await m(g,{body:JSON.stringify(E),headers:{"content-type":"application/json"},method:"POST"}),O=g=>{const E=g;if(E==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 E.binding=="string"&&E.binding.length>0)return{workflow:E.binding};if(typeof E.__lunoraRef=="string")return{functionPath:E.__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})},k=async()=>(await Er(async E=>m(E===void 0?"/list":`/list?cursor=${encodeURIComponent(E)}`,{method:"GET"}))).map(E=>s(E)),I=async(g,E,C={})=>{const x=O(E),{id:Q}=await b("/schedule",{args:qn("ctx.scheduler",String(x.functionPath??x.workflow),C),scheduledFor:g,...x});return Q};return{cancel:async g=>await b("/cancel",{id:g}),get:async g=>{const E=await m(`/get?id=${encodeURIComponent(g)}`,{method:"GET"});return E.record===void 0?null:s(E.record)},list:k,runAfter:async(g,E,C)=>{if(!Number.isFinite(g)||g<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await I(Date.now()+g,E,C)},runAt:async(g,E,C)=>{if(!Number.isFinite(g))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await I(g,E,C)}}},mn=async(o,s,l)=>{const{claims:d,headers:m,userId:b}=await de(o,s,a),O=be(s,o,g=>l.waitUntil?.(g)),k=g=>async(E,C={})=>{const x=E.__lunoraRef;if(typeof x!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Se(x);const Q=await Ee(o,x,ke(C),g,{...m,"x-lunora-system":"1"},O),H=await Q.json();if(H.error)throw new c(H.error.message??"shard RPC failed",{code:H.error.code??"INTERNAL",status:Q.status});return Ve(H.result)},I=k(r);return{auth:{getIdentity:()=>Promise.resolve(d),userId:b},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),forShard:g=>{const E=k(g);return{runAction:E,runMutation:E,runQuery:E}},runAction:I,runMutation:I,runQuery:I,...u===void 0?{}:{scheduler:pn(u)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:br(e.storage(s))}}},wn=async(o,s,l)=>{if(!e.httpRouter)return;const d=await mn(o,s,l);try{return await e.httpRouter.fetch(o,{...s,__lunoraCtx:d},l)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},gn=async(o,s,l)=>{if(o.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const d=pt(o,ie);if(d)return d;const m=l.searchParams.get("shard")??r,{headers:b,identity:O}=await de(o,s,a);await B(O,m);const k=Ht(o,b),I=xt(s,e.shardDO);if(I!==void 0){k.set("x-lunora-shard-binding",I);const g=await rs(i,m);if(g>0){const E=Br(m,Math.floor(Math.random()*g));return w(i,E,new Request(o,{headers:k}),mt(o))}}return w(i,m,new Request(o,{headers:k}))},yn=async(o,s,l)=>{const{voiceAgents:d}=e;if(d===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=pt(o,ie);if(m)return m;let b;try{b=decodeURIComponent(l.pathname.slice(Ut.length))}catch{return new Response("Unknown voice agent",{status:404})}const O=Object.hasOwn(d,b)?d[b]:void 0;if(O===void 0)return new Response("Unknown voice agent",{status:404});const k=l.searchParams.get("threadKey");if(k===null||k.length===0)return new Response("Missing threadKey",{status:400});const{headers:I,identity:g}=await de(o,s,a);if(e.authorizeShard){if(!await Ae(e.authorizeShard({identity:g,shardKey:k})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else V("shard");const E=Ht(o,I);return w(O,k,new Request(o,{headers:E}))},bn=async(o,s,l)=>{if(e.authorizeFanOut){if(!await Ae(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});V("fan-out")},Re=async(o,s)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await bn(o.fanOut,o.functionPath,s);return}await B(s,o.shardKey??r)}},_n=(o,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){$();return}if(e.functions[s]?.kind!=="query"||l.includes(qe)||l.includes(Je))return;const d=mt(o);return d===void 0?void 0:{name:xr(l,d),region:d}},Rn=async(o,s,l,d,m)=>{const b=_n(o,s,d);if(b!==void 0){const O={...m,"x-lunora-replica-read":"1",..._===void 0?{}:{"x-lunora-shard-binding":_}},k=Hr(o.headers.get("x-lunora-min-seq"));k!==void 0&&(O["x-lunora-min-seq"]=String(k));const I=await w(i,b.name,ve(s,l,O),b.region);if(I.status!==421)return I}return w(i,d,ve(s,l,m))},Ee=async(o,s,l,d,m,b)=>{const O=Date.now(),{observability:k,sampling:I}=e,g=ze(o),{decision:E,ignoredUpstream:C,trace:x}=ia(o,{...I===void 0?{}:{sampling:I},trustInbound:t(o)});C&&n();const Q={...m,"x-lunora-sample-errors":E.keepErrors?"1":"0"};ca(x,Q);try{const H=await Rn(o,s,l,d,Q);ce(k,{...g,...Dt(x),durationMs:Date.now()-O,functionPath:s,ok:H.ok,shardKey:d,...H.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(H.status)}`,status:H.status}}},b,void 0,{isTraced:x.sampled,keepErrors:E.keepErrors});const ne=new Response(H.body,{headers:H.headers,status:H.status,statusText:H.statusText});return ne.headers.set("x-lunora-shard-key",d),ne}catch(H){throw ce(k,{...g,...Dt(x),...Te(s,Date.now()-O,H,{shardKey:d})},b,void 0,{isTraced:x.sampled,keepErrors:E.keepErrors}),H}},En=o=>{if(o.fanOut&&o.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(o.fanOut||Se(o.functionPath),o.fanOut&&!e.queryCoordinator)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Sn=async(o,s,l)=>{j(o,"POST","RPC");const d=await es(o);Za(s,d),En(d);const m=await se(o,d);if(m!==void 0)return m;const{headers:b,identity:O}=await de(o,s,a);await Re(d,O);const k=We(d,e);{const I=Date.now(),{observability:g}=e,E=ze(o),C=be(s,o,l&&(H=>l.waitUntil?.(H)));if(d.fanOut){const H=e.queryCoordinator;if(!H)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ne=await H.fanOut(i,{args:d.args??{},fanOut:d.fanOut,functionPath:d.functionPath,headers:b});return ce(g,{durationMs:Date.now()-I,fanOut:{failed:ne.failed,shards:ne.ok+ne.failed,table:d.fanOut.table},functionPath:d.functionPath,...E,ok:!0},C),Response.json(ne,{headers:{"content-type":"application/json"},status:200})}catch(ne){throw ce(g,{...Te(d.functionPath,Date.now()-I,ne,{fanOut:{table:d.fanOut.table}}),...E},C),ne}}const x=d.shardKey??r,Q=()=>Ee(o,d.functionPath,d.args??{},x,b,C);return k&&e.x402Charge?e.x402Charge(o,{functionPath:d.functionPath,price:k.price},Q,Qe(l)):Q()}},An=async(o,s,l)=>{j(o,"POST","RPC batch");const d=await te(o),{calls:m}=d;if(!Array.isArray(m))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:b,identity:O}=await de(o,s,a),k=co(m,r);for(const z of k.values())for(const W of z)if(e.functions?.[W.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${W.functionPath}" cannot be called in a batch; dispatch it individually over ${Nt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...k.entries()].flatMap(([z,W])=>W.map(oe=>Re({args:oe.args,functionPath:oe.functionPath,shardKey:z},O))));const{observability:I}=e,g=be(s,o,l&&(z=>l.waitUntil?.(z))),E=ze(o),C=[],x=[],Q=(z,W,oe,ue)=>({body:{error:{code:oe,message:ue}},id:z.id,status:W}),H=(z,W,oe,ue,pe)=>{for(const X of z)ce(I,pe(X),g),C.push(Q(X,W,oe,ue))},ne=(z,W,oe,ue,pe)=>{for(const X of z){const me=ue.get(X.id)??pe,ye=me<400;ce(I,{durationMs:oe,functionPath:X.functionPath,...E,ok:ye,shardKey:W,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},g)}};await Promise.all([...k.entries()].map(async([z,W])=>{const oe=new Headers(b);oe.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:W}),headers:oe,method:"POST"}),pe=Date.now();let X;try{X=await w(i,z,ue)}catch(Z){const He=Date.now()-pe,{body:ct}=Mn(Z,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});H(W,502,ct.code,ct.message,Hn=>({...Te(Hn.functionPath,He,Z,{shardKey:z}),...E}));return}const me=Date.now()-pe,ye=X.headers.get("x-d1-bookmark");ye&&x.push(ye);let Be;try{Be=await X.json()}catch{const Z=`shard batch returned a non-JSON response (${String(X.status)})`;H(W,X.status,"SHARD_ERROR",Z,He=>({durationMs:me,error:{code:"SHARD_ERROR",message:Z,status:X.status},functionPath:He.functionPath,...E,ok:!1,shardKey:z}));return}const xe=Array.isArray(Be.results)?Be.results:[],Bn=new Map(xe.map(Z=>[Z.id,Z.status??X.status])),xn=new Set(xe.map(Z=>Z.id));ne(W,z,me,Bn,X.status),C.push(...xe);for(const Z of W)xn.has(Z.id)||C.push(Q(Z,X.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Z.id)}`))}));const st={"content-type":"application/json"},[it]=x;return x.length===1&&it!==void 0&&(st["x-d1-bookmark"]=it),Response.json({results:C},{headers:st,status:200})},Tn=async(o,s,l,d={},m={})=>{try{const b=l.__lunoraRef;if(typeof b!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Se(b);const{headers:O,identity:k}=await de(o,s,a,m.context),I={args:d,functionPath:b,shardKey:m.shardKey};await Re(I,k);const g=m.shardKey??r,E=be(s,o,m.waitUntil),C=()=>Ee(o,b,d,g,O,E),x=We(I,e);return x&&e.x402Charge?await e.x402Charge(o,{functionPath:b,price:x.price},C,Qe(m.waitUntil?{waitUntil:m.waitUntil}:m.context)):await C()}catch(b){return dt(b)}},ot=async(o,s,l)=>{const{observability:d}=e,m=Date.now(),b=Ie(16),O=Ie(8),k=Bt(s),I=jt(b,O,!0);try{const g=await l(I);return ce(d,{durationMs:Date.now()-m,functionPath:o,ok:!0,spanId:O,traceId:b},k),g}catch(g){throw ce(d,{...Te(o,Date.now()-m,g,{}),spanId:O,traceId:b},k),g}finally{lt(d,k)}},On=async(o,s,l,d)=>{R(s);const m=[],b=E=>E instanceof Error?E:new Error(String(E)),O=e.crons?.[o.cron];if(O)try{await O(o,s,l)}catch(E){m.push(b(E))}const k=await G(o.cron,s,m,b,d),I=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron;if(I)try{await no(e,i,A(),o)}catch(E){m.push(b(E))}if(!O&&k===0&&!I){const E=[...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: ${E.length===0?"(none)":E.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[g]=m;if(m.length===1&&g)throw g;if(m.length>1)throw new AggregateError(m,`scheduled("${o.cron}") had ${String(m.length)} failure(s)`)},vn=async(o,s)=>{try{const l=o??{},d=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!d||d.length===0)return;await w(i,r,ve(Ga,{outcome:s},{authorization:`Bearer ${d}`,"content-type":"application/json"}))}catch{}},kn=async(o,s,l,d)=>{if(!e.authHandler)return;const m=await e.authHandler(o);if(!m)return;const b=e.authBasePath??Ct;return Wa(l.pathname,b)&&d.waitUntil?.(vn(s,m.status>=400?"fail":"ok")),m},In=async({args:o,env:s,functionPath:l,request:d,shardKey:m,waitUntil:b})=>{Kt(o,"REST");const O={functionPath:l,...m===void 0?{}:{shardKey:m}},{headers:k,identity:I}=await de(d,s,a);await Re(O,I);const g=m??r,E=be(s,d,b),C=()=>Ee(d,l,o,g,k,E),x=We(O,e);return x&&e.x402Charge?e.x402Charge(d,{functionPath:l,price:x.price},C,Qe({waitUntil:b})):C()},Pn=Yn({functions:e.functions??{},invoke:In,readJsonBody:te,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ce=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Nn={[ja]: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"}}),[Ua]:(o,s,l)=>gn(o,s,l),[Nt]:(o,s,l,d)=>Sn(o,s,d),[Da]:(o,s,l,d)=>An(o,s,d),[Ca]:(o,s)=>_e(o,s),[Ba]:(o,s)=>fe(o,s),[xa]:async o=>{j(o,"POST","ws-token"),L(o);const s=A();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 Kr(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...J,...nn,...rn,...on,...an,...sn,...cn,...dn,...un,...ln,...fn,...Pn,...zr({assertAdmin:L,getAuthAdmin:()=>e.authAdmin,parsePaging:Ue,queryParameter:De,readJsonBody:te})};let ie=ft(e.security),at=!1;const Dn=o=>{at||(at=!0,ie=ft(e.security,o??{}))},Un=async(o,s)=>{$a(s)&&await U(o)},Cn=async(o,s,l)=>{Ye.set(o,l);const d=new URL(o.url);if((d.pathname.startsWith(La)||e.authHandler!==void 0&&Va(d.pathname,e.authBasePath??Ct))&&(o.method==="POST"||o.method==="PUT")){const I=Number(o.headers.get("content-length")??""),g=Na[d.pathname]??$t;if(Number.isFinite(I)&&I>g)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const b=await kn(o,s,d,l);if(b)return b;if(Ce){const I=`${o.method} ${d.pathname}`,g=Ce[I]??Ce[d.pathname];if(g)return g(o,s,l)}const O=Nn[d.pathname];if(O)return await Un(o,d.pathname),O(o,s,d,l);if(e.voiceAgents!==void 0&&d.pathname.startsWith(Ut))return yn(o,s,d);const k=await wn(o,s,l);return k||new Response("Not found",{status:404})};return{async fetch(o,s,l){e.passThroughOnException&&l.passThroughOnException?.(),Dn(s),R(s);const d=gr(o,ie);if(d)return d;const m=yr(o,ie);if(m)return Me(m,o,ie);try{const b=await Cn(o,s,l);return Me(b,o,ie)}catch(b){return Me(dt(b),o,ie)}finally{lt(e.observability,Bt(l))}},async queue(o,s,l){await ot(`queue:${qa(o)}`,l,async d=>{await e.queue?.(o,s,l,{traceparent:d})})},async scheduled(o,s,l){await ot(`cron:${o.cron}`,l,async d=>{await On(o,s,l,d)})},serverQuery:Tn}},us=e=>tn(e),ls=e=>typeof e=="function"?{fetch:e}:e,hs=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,Cs=(e,t)=>{const n=ls(e),r=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=u=>{const h=us({...u,httpRouter:n});return r!==void 0&&!hs(u)?{...h,scheduled:async(p,w,S)=>{await r(p,w,S)}}:h};if(typeof t!="function")return a(t);const i=t;return{fetch:(u,h,p)=>a(i(h)).fetch(u,h,p),queue:(u,h,p)=>a(i(h)).queue?.(u,h,p)??Promise.resolve(),scheduled:(u,h,p)=>a(i(h)).scheduled(u,h,p),serverQuery:(u,h,p,w,S)=>a(i(h)).serverQuery(u,h,p,w,S)}},fs=(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}},Bs=(e={})=>(t,n,r)=>tn(fs(e,n)).fetch(t,n,r??jn),xs=e=>e;export{yt as GET_AUTH_AUDIT_LOG_OP,jn as NOOP_EXECUTION_CONTEXT,Ms as composeIdentityResolvers,us as composeWorker,Bs as createLunoraHandler,tn as createWorker,xs as defineRpcEnvelope,rs as probeRelayCount,fs as resolveLunoraOptions,js as routeIdentityResolvers,Cs as withFrameworkWorker};
@@ -1 +0,0 @@
1
- import{c as S,d as T,e as O,a as B,f as P}from"./rest-cache-D1BlbZb1.mjs";import{LunoraError as h}from"./LunoraError-DksAgIpa.mjs";import{m as D}from"./method-guard-BG_vJNTl.mjs";const w=1048576,k=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),U=async(e,r=w)=>{if(!e.body)return"";const t=e.body.getReader(),a=new TextDecoder;let i=0,s="";for(;;){const{done:o,value:n}=await t.read();if(o)break;if(n){if(i+=n.byteLength,i>r)throw await t.cancel().catch(()=>{}),new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});s+=a.decode(n,{stream:!0})}}return s+=a.decode(),s},z=async(e,r=w)=>{if(!e.body)return new ArrayBuffer(0);const t=e.body.getReader(),a=[];let i=0;for(;;){const{done:n,value:c}=await t.read();if(n)break;if(c){if(i+=c.byteLength,i>r)throw await t.cancel().catch(()=>{}),new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});a.push(c)}}const s=new Uint8Array(i);let o=0;for(const n of a)s.set(n,o),o+=n.byteLength;return s.buffer},j=async(e,r,t=w)=>{try{const a=await U(e,t);return a===""?{}:JSON.parse(a)}catch(a){throw a instanceof h?a:new h(`${r} body must be valid JSON`,{code:"BAD_REQUEST",status:400})}},Z=async(e,r=w)=>{const t=await j(e,"Request",r);if(!k(t))throw new h("Request body must be an object",{code:"BAD_REQUEST",status:400});return t},C=(e,r)=>{if(!k(e))throw new h(`${r} \`args\` must be an object`,{code:"BAD_REQUEST",status:400})},b="__lunora_vary",x="x-lunora-edge-cache",G=["x-d1-bookmark","x-lunora-shard-key"],M=()=>{try{return globalThis.caches?.default}catch{return}},_=e=>e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r!==""),J=(e,r)=>{const t=e.headers.get("vary");return t===null?!0:_(t).every(a=>a!=="*"&&r.includes(a))},K=(e,r)=>{if(e===void 0||r===null||e.scope!=="public"||S(e.maxAge)<=0)return;const t=()=>r??M(),a=_(T(e)??""),i=o=>{const n=new URL(o.url);return n.searchParams.delete(b),a.length>0&&n.searchParams.set(b,a.map(c=>`${c}=${o.headers.get(c)??""}`).join("\0")),new Request(n.toString(),{method:"GET"})},s=(o,n)=>o.method==="GET"&&O(e,o,n)==="public";return{lookup:async(o,n)=>{const c=t();if(c===void 0||!s(o,n))return;let u;try{u=await c.match(i(o))}catch{return}if(u===void 0)return;const l=new Response(u.body,u);return l.headers.set(x,"hit"),l},store:(o,n,c)=>{const u=t();if(u===void 0||!s(n,c)||o.status!==200||o.headers.has("set-cookie")||o.headers.has("x-payment-response")||!J(o,a))return o;try{const l=new Response(o.clone().body,o);for(const R of G)l.headers.delete(R);const d=Promise.resolve(u.put(i(n),l)).catch(()=>{});c?.waitUntil&&c.waitUntil(d)}catch{}return o}}},N=()=>globalThis.navigator?.userAgent==="Cloudflare-Workers",Y=e=>N()?e.get("cf-connecting-ip")??void 0:void 0,F=e=>P(Object.entries(e).map(([r,t])=>({exposure:t.expose,functionPath:r,kind:t.kind}))),H=(e,r)=>{const t=e.searchParams.get("shardKey");if(t!==null&&t!=="")return t;const a=r.headers.get("x-lunora-shard-key");return a===null||a===""?void 0:a},I=e=>{const r=Object.create(null);for(const[t,a]of e.searchParams.entries())if(!(t==="shardKey"||t===b))try{r[t]=JSON.parse(a)}catch{r[t]=a}return r},q=e=>{const{edgeCache:r,functions:t,invoke:a,rateLimit:i,readJsonBody:s}=e,o={};for(const n of F(t)){const c=n.kind==="query"?["GET","POST"]:["POST"],u=t[n.functionPath].expose?.cache,l=K(u,r);o[n.path]=async(d,R,V,f)=>{const g=D(d,c);if(g)return g;const E=new URL(d.url);if(i){const m=await i(d,n.functionPath);if(m)return m}const v=await l?.lookup(d,f);if(v)return v;let y;d.method==="GET"?y=I(E):y=d.body===null?{}:await s(d),C(y,"REST");const p=H(E,d),L=await a({args:y,env:R,functionPath:n.functionPath,request:d,...p===void 0?{}:{shardKey:p},...f?.waitUntil===void 0?{}:{waitUntil:m=>f.waitUntil?.(m)}}),A=B(L,u,d,f);return l?l.store(A,d,f):A}}return o},Q="no-trusted-ip",ee=(e,r)=>async(t,a)=>{const i=(r.key?r.key(t,a):Y(t.headers))??Q,s=await e.limit(r.name,{key:i});if(s.ok)return;if(s.reason==="deny")return Response.json({error:{code:"FORBIDDEN",message:"Request denied"}},{headers:{"content-type":"application/json"},status:403});const o=Math.max(1,Math.ceil(s.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(o)},status:429})};export{w as M,I as a,q as b,ee as c,Z as d,j as e,z as f,C as g,U as h,F as r,Y as t};