@lunora/runtime 1.0.0-alpha.163 → 1.0.0-alpha.165

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
@@ -897,6 +897,8 @@ declare const resolveShard: (namespace: ShardNamespaceInput, shardKey: string, l
897
897
  * strategy's identity (empty array for `concat`, `0` for `sum`, etc.).
898
898
  */
899
899
  interface ShardRegistry {
900
+ /** Drop any cached listing for `table` (every table when omitted) — a registry that caches implements it, so a prune shows up at once in this isolate. */
901
+ invalidate?: (table?: string) => void;
900
902
  listShardKeys: (table: string) => Promise<ReadonlyArray<string>> | ReadonlyArray<string>;
901
903
  }
902
904
  /**
@@ -4105,9 +4107,10 @@ interface WorkerOptions {
4105
4107
  */
4106
4108
  passThroughOnException?: boolean;
4107
4109
  /**
4108
- * Coordinator for cross-shard RPCs. When absent, envelopes with
4109
- * `fanOut` set are rejected with a 400. Construct via
4110
- * `createQueryCoordinator({ registry })`.
4110
+ * Coordinator for cross-shard RPCs and the admin fan-outs. Construct via
4111
+ * `createQueryCoordinator({ registry })`. When absent, the worker uses one
4112
+ * whose registry covers root and `.global()` tables and rejects a
4113
+ * `.shardBy()` table with a 400, since only a real registry knows its keys.
4111
4114
  */
4112
4115
  queryCoordinator?: QueryCoordinator;
4113
4116
  /**
package/dist/index.d.ts CHANGED
@@ -897,6 +897,8 @@ declare const resolveShard: (namespace: ShardNamespaceInput, shardKey: string, l
897
897
  * strategy's identity (empty array for `concat`, `0` for `sum`, etc.).
898
898
  */
899
899
  interface ShardRegistry {
900
+ /** Drop any cached listing for `table` (every table when omitted) — a registry that caches implements it, so a prune shows up at once in this isolate. */
901
+ invalidate?: (table?: string) => void;
900
902
  listShardKeys: (table: string) => Promise<ReadonlyArray<string>> | ReadonlyArray<string>;
901
903
  }
902
904
  /**
@@ -4105,9 +4107,10 @@ interface WorkerOptions {
4105
4107
  */
4106
4108
  passThroughOnException?: boolean;
4107
4109
  /**
4108
- * Coordinator for cross-shard RPCs. When absent, envelopes with
4109
- * `fanOut` set are rejected with a 400. Construct via
4110
- * `createQueryCoordinator({ registry })`.
4110
+ * Coordinator for cross-shard RPCs and the admin fan-outs. Construct via
4111
+ * `createQueryCoordinator({ registry })`. When absent, the worker uses one
4112
+ * whose registry covers root and `.global()` tables and rejects a
4113
+ * `.shardBy()` table with a 400, since only a real registry knows its keys.
4111
4114
  */
4112
4115
  queryCoordinator?: QueryCoordinator;
4113
4116
  /**
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as n,backupObjectKeyOfManifest as p,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as R,toFivetranResponse as x}from"./packem_shared/toAirbyteMessages-2d_iJXPf.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as y}from"./packem_shared/composeWorker-B-Hbe7oP.mjs";import{createCrossShardRelationCapabilities as O}from"./packem_shared/createCrossShardRelationCapabilities-BiXSW10v.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as H,toErrorResponse as P}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as v,a as I,d as D,r as M,b as F,s as N,w as G}from"./packem_shared/export-tap-CAyZ2TWC.mjs";import{HEALTH_PATH as U,HEALTH_READY_PATH as B,buildHealthRoutes as Y,d1Probe as w,durableObjectProbe as z,presenceProbe as X}from"./packem_shared/HEALTH_PATH-D0i8LhwT.mjs";import{LOG_ARCHIVE_PATH as V,resolveLogArchiveFromEnv as W}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as J,memoizeIdentityPerRequest as Q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as $,a as ee}from"./packem_shared/observability-DgurIZIR.mjs";import{analyticsEngineSink as oe,combineSinks as te,consoleSink as ae,otlpSink as se,pipelineLogSink as ie,sentrySink as ne,webhookSink as pe}from"./packem_shared/analyticsEngineSink-BlkElAL2.mjs";import{D as me,c as fe}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as Re,createStaticShardRegistry as xe}from"./packem_shared/createQueryCoordinator-D3__w6LU.mjs";import{applyJurisdiction as le,resolveShard as de}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as _e,r as ke,b as ye}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as Oe,b as be,c as Ae,r as Le}from"./packem_shared/rest-routes-D3ShCTHh.mjs";import{decorateResponse as he,enforceOrigin as He,handleCorsPreflight as Pe,resolveSecurity as ge}from"./packem_shared/decorateResponse-CRrFNW1v.mjs";import{createShardClient as Ie}from"./packem_shared/createShardClient-BrzRLSs9.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Me}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ne}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ke}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Be,routeIdentityResolvers as Ye}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,me as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,U as HEALTH_PATH,B as HEALTH_READY_PATH,Ne as LOG_ARCHIVE_NOT_CONFIGURED,V as LOG_ARCHIVE_PATH,H as LunoraError,Ke as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Me as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,oe as analyticsEngineSink,le as applyJurisdiction,_e as applyRestCache,Oe as argsFromQuery,i as backupManifestKey,n as backupObjectKey,p as backupObjectKeyOfManifest,Y as buildHealthRoutes,be as buildRestRoutes,te as combineSinks,Be as composeIdentityResolvers,l as composeWorker,ae as consoleSink,O as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,v as createKvCursorStore,d as createLunoraHandler,I as createMemoryCursorStore,fe as createPipelineLogReader,Re as createQueryCoordinator,Ae as createRestRateLimit,Ie as createShardClient,xe as createStaticShardRegistry,u as createWorker,w as d1Probe,t as declareAppJurisdiction,he as decorateResponse,D as defineExportSink,_ as defineRpcEnvelope,z as durableObjectProbe,$ as emitLogEvent,ee as emitRpcEvent,He as enforceOrigin,Pe as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,J as memoizeIdentity,Q as memoizeIdentityPerRequest,f as normalizeBackupPrefix,se as otlpSink,ie as pipelineLogSink,X as presenceProbe,M as r2Sink,ke as requestCarriesCredentials,W as resolveLogArchiveFromEnv,k as resolveLunoraOptions,ge as resolveSecurity,de as resolveShard,ye as restCacheHeaders,Le as restSurfaceFromRegistry,Ye as routeIdentityResolvers,F as runExportTap,N as sanitizeChange,ne as sentrySink,R as toAirbyteMessages,P as toErrorResponse,x as toFivetranResponse,G as webhookExportSink,pe as webhookSink,y as withFrameworkWorker};
1
+ import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as n,backupObjectKeyOfManifest as p,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as R,toFivetranResponse as x}from"./packem_shared/toAirbyteMessages-2d_iJXPf.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as y}from"./packem_shared/composeWorker-CnDhIWiX.mjs";import{createCrossShardRelationCapabilities as O}from"./packem_shared/createCrossShardRelationCapabilities-BiXSW10v.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-BSKqUsWS.mjs";import{LunoraError as H,toErrorResponse as P}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as v,a as I,d as D,r as M,b as F,s as N,w as G}from"./packem_shared/export-tap-CAyZ2TWC.mjs";import{HEALTH_PATH as U,HEALTH_READY_PATH as B,buildHealthRoutes as Y,d1Probe as w,durableObjectProbe as z,presenceProbe as X}from"./packem_shared/HEALTH_PATH-D0i8LhwT.mjs";import{LOG_ARCHIVE_PATH as V,resolveLogArchiveFromEnv as W}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as J,memoizeIdentityPerRequest as Q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as $,a as ee}from"./packem_shared/observability-DgurIZIR.mjs";import{analyticsEngineSink as oe,combineSinks as te,consoleSink as ae,otlpSink as se,pipelineLogSink as ie,sentrySink as ne,webhookSink as pe}from"./packem_shared/analyticsEngineSink-BlkElAL2.mjs";import{D as me,c as fe}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as Re,createStaticShardRegistry as xe}from"./packem_shared/createQueryCoordinator-BkZPoV26.mjs";import{applyJurisdiction as le,resolveShard as de}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as _e,r as ke,b as ye}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as Oe,b as be,c as Ae,r as Le}from"./packem_shared/rest-routes-D3ShCTHh.mjs";import{decorateResponse as he,enforceOrigin as He,handleCorsPreflight as Pe,resolveSecurity as ge}from"./packem_shared/decorateResponse-CRrFNW1v.mjs";import{createShardClient as Ie}from"./packem_shared/createShardClient-BrzRLSs9.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Me}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ne}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ke}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Be,routeIdentityResolvers as Ye}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,me as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,U as HEALTH_PATH,B as HEALTH_READY_PATH,Ne as LOG_ARCHIVE_NOT_CONFIGURED,V as LOG_ARCHIVE_PATH,H as LunoraError,Ke as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Me as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,oe as analyticsEngineSink,le as applyJurisdiction,_e as applyRestCache,Oe as argsFromQuery,i as backupManifestKey,n as backupObjectKey,p as backupObjectKeyOfManifest,Y as buildHealthRoutes,be as buildRestRoutes,te as combineSinks,Be as composeIdentityResolvers,l as composeWorker,ae as consoleSink,O as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,v as createKvCursorStore,d as createLunoraHandler,I as createMemoryCursorStore,fe as createPipelineLogReader,Re as createQueryCoordinator,Ae as createRestRateLimit,Ie as createShardClient,xe as createStaticShardRegistry,u as createWorker,w as d1Probe,t as declareAppJurisdiction,he as decorateResponse,D as defineExportSink,_ as defineRpcEnvelope,z as durableObjectProbe,$ as emitLogEvent,ee as emitRpcEvent,He as enforceOrigin,Pe as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,J as memoizeIdentity,Q as memoizeIdentityPerRequest,f as normalizeBackupPrefix,se as otlpSink,ie as pipelineLogSink,X as presenceProbe,M as r2Sink,ke as requestCarriesCredentials,W as resolveLogArchiveFromEnv,k as resolveLunoraOptions,ge as resolveSecurity,de as resolveShard,ye as restCacheHeaders,Le as restSurfaceFromRegistry,Ye as routeIdentityResolvers,F as runExportTap,N as sanitizeChange,ne as sentrySink,R as toAirbyteMessages,P as toErrorResponse,x as toFivetranResponse,G as webhookExportSink,pe as webhookSink,y as withFrameworkWorker};
@@ -0,0 +1 @@
1
+ import{LunoraError as a}from"./LunoraError-DksAgIpa.mjs";import{applyJurisdiction as S,resolveShard as _}from"./applyJurisdiction-C0ddU7Tg.mjs";const l="__lunora_shard_registry__",f=3e4,y="https://shard-registry.internal",g=async r=>await r.json(),T=r=>{const p=r.instanceName??l,i=r.cacheTtlMs??f,n=new Map,w=S(r.namespace,r.jurisdiction),c=()=>_(w,p),d=async(e,t)=>c().fetch(new Request(`${y}${e}`,{body:JSON.stringify(t),headers:{"content-type":"application/json"},method:"POST"})),h=async e=>c().fetch(new Request(`${y}${e}`,{method:"GET"}));return{invalidate(e){e===void 0?n.clear():n.delete(e)},async listShardKeys(e){const t=Date.now(),s=n.get(e);if(s&&s.expiresAt>t)return s.shardKeys;const o=await h(`/list?table=${encodeURIComponent(e)}`);if(!o.ok)throw new a(`shard registry /list returned ${String(o.status)}`);const{shardKeys:u}=await g(o);return i>0&&n.set(e,{expiresAt:t+i,shardKeys:u}),u},async register(e,t){const s=await d("/register",{shardKey:t,table:e});if(!s.ok)throw new a(`shard registry /register returned ${String(s.status)}`);n.delete(e)},async snapshot(){const e=await h("/snapshot");if(!e.ok)throw new a(`shard registry /snapshot returned ${String(e.status)}`);const{tables:t}=await g(e);return t},async unregister(e,t){const s=await d("/unregister",{shardKey:t,table:e});if(!s.ok)throw new a(`shard registry /unregister returned ${String(s.status)}`);n.delete(e)}}};export{f as DEFAULT_REGISTRY_CACHE_TTL_MS,l as SHARD_REGISTRY_DO_NAME,T as createDynamicShardRegistry};
@@ -0,0 +1,6 @@
1
+ import{isLunoraError as pr,toErrorBody as mr}from"@lunora/errors";import{e as tn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as wr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as gr,f as yr}from"./base64-Bl1_r2k1.mjs";import{i as br,e as _r,a as Rr,E as gt,d as Er}from"./identity-header-pR617HTs.mjs";import{O as yt,a as bt}from"./origin-paywall-B6eOO67m.mjs";import{o as we,b as nn,p as Sr,m as Ar,d as Tr,a as Or,r as vr}from"./otlp-resource-BI3MvjSy.mjs";import{r as Ir,f as _t,a as ce,S as Rt}from"./observability-DgurIZIR.mjs";import{e as Ee,d as Ye,a as kr}from"./wire-codec-BLvSm5Mn.mjs";import{d as ee,e as ne,M as rn,b as Pr,f as Dr,g as on,w as Nr,h as an,t as Ur}from"./rest-routes-D3ShCTHh.mjs";import{LunoraError as c,toErrorResponse as Et}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as nt,BACKUP_KEY_PREFIX as rt,isBackupManifestKey as Cr,backupObjectKeyOfManifest as sn,backupObjectKey as Br,backupManifestKey as xr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Hr,buildStorageAdminRoutes as Lr,STORAGE_UPLOAD_MAX_BODY_BYTES as jr,STORAGE_PATH as Mr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as $r,e as Kr,f as St,g as Fr,h as Gr}from"./export-tap-CAyZ2TWC.mjs";import{buildHealthRoutes as Qr,durableObjectProbe as Wr,d1Probe as zr,presenceProbe as je}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as Vr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Ii,routeIdentityResolvers as ki}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Jr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{pruneShardRegistry as Yr,createQueryCoordinator as qr,createDefaultShardRegistry as Xr}from"./createQueryCoordinator-BkZPoV26.mjs";import{resolveShard as ge,applyJurisdiction as Me}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as At,handleCorsPreflight as Zr,enforceOrigin as eo,decorateResponse as $e,enforceWebSocketOrigin as Tt}from"./decorateResponse-CRrFNW1v.mjs";const to=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},cn="__lunoraBranch",no=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,cn),ro=`may not contain the reserved workflow branch-marker key ("${cn}")`,oo=async e=>{const t=[];let n;for(;;){const o=await e(n);if(t.push(...Array.isArray(o.records)?o.records:[]),o.truncated!==!0||typeof o.cursor!="string"||o.cursor.length===0)return t;if(o.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=o.cursor}},ot=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,u=a<t.length?t.charCodeAt(a):0;o|=i^u}return o===0},ao=/already[\s_-]?exists/iu,so=e=>ao.test(e instanceof Error?e.message:String(e)),io=(e,t,n,o)=>{const a=e.get(t);if(a!==void 0)return a;tn(e,o);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},at=new TextEncoder,co=Array.from({length:32},(e,t)=>t);new RegExp(`[${co.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const uo=64,lo=new Map,dn=async e=>io(lo,e,async()=>crypto.subtle.importKey("raw",at.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),uo),un=async(e,t)=>{const n=await dn(e),o=await crypto.subtle.sign("HMAC",n,at.encode(t));return gr(new Uint8Array(o))},ho=async(e,t,n)=>{const o=await dn(e);return crypto.subtle.verify("HMAC",o,n,at.encode(t))},fo=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(fo);const po=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),mo=-100,wo=15,go=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&po.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>wo?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<mo?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},Ot=e=>{const t=e.cf;return t===void 0?void 0:go(t)},qe="::relay::",yo=(e,t)=>`${e}${qe}${String(t)}`,Xe="::replica::",bo=(e,t)=>`${e}${Xe}${t}`,_o=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Ro=new Set(["1","enabled","on","true","yes"]),Eo=new Set(["0","disabled","false","no","off"]),So=(e,t)=>{const n=(e??"").trim().toLowerCase();return Ro.has(n)?!0:Eo.has(n)?!1:t},ln="v1",Ao=6e4,To=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Ao),o=`${ln}.${String(n)}`,a=await un(e,o);return{expiresAtMs:n,token:`${o}.${a}`}},Oo=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[a,i,u]=o;if(a!==ln||u.length===0)return!1;const h=Number(i);if(!Number.isFinite(h)||h<=n)return!1;let f;try{f=yr(u)}catch{return!1}return ho(e,`${a}.${i}`,f)},D="/_lunora/admin/auth",vo={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},C=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},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},hn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ke=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},vt=e=>{const t=hn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},It=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[o,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[o]=a);return n},Io={[`${D}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${D}/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"},[`${D}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${D}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${D}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${D}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${D}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${D}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${D}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${D}/sign-up-invitations/create`]:{build:({body:e})=>({email:C(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:te(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${D}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:C(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${D}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${D}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${D}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${D}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${D}/users/create`]:{build:({body:e})=>({data:Ke(e,"data"),email:C(e,"email"),name:C(e,"name"),password:te(e,"password"),role:hn(e.role)}),http:"POST",method:"createUser"},[`${D}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:C(e,"userId")}},http:"POST",method:"updateUser"},[`${D}/users/role`]:{build:({body:e})=>({role:vt(e),userId:C(e,"userId")}),http:"POST",method:"setRole"},[`${D}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:C(e,"userId")}),http:"POST",method:"banUser"},[`${D}/users/unban`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"unbanUser"},[`${D}/users/password`]:{build:({body:e})=>({newPassword:C(e,"newPassword"),userId:C(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${D}/users/remove`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${D}/users/impersonate`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"impersonateUser"},[`${D}/sessions/revoke`]:{build:({body:e})=>({sessionId:C(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${D}/sessions/revoke-all`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${D}/accounts/unlink`]:{build:({body:e})=>({accountId:C(e,"accountId"),userId:C(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${D}/two-factor/disable`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${D}/passkeys/delete`]:{build:({body:e})=>({passkeyId:C(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${D}/organizations/members/remove`]:{build:({body:e})=>({memberId:C(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${D}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:C(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${D}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ke(e,"metadata"),name:C(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${D}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ke(e,"metadata"),name:te(e,"name"),organizationId:C(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${D}/organizations/remove`]:{build:({body:e})=>({organizationId:C(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${D}/organizations/members/add`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),role:te(e,"role"),userId:C(e,"userId")}),http:"POST",method:"addMember"},[`${D}/organizations/members/invite`]:{build:({body:e})=>({email:C(e,"email"),inviterId:te(e,"inviterId"),organizationId:C(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${D}/organizations/members/role`]:{build:({body:e})=>({memberId:C(e,"memberId"),role:vt(e)}),http:"POST",method:"updateMemberRole"},[`${D}/organizations/teams/create`]:{build:({body:e})=>({name:C(e,"name"),organizationId:C(e,"organizationId")}),http:"POST",method:"createTeam"},[`${D}/organizations/teams/update`]:{build:({body:e})=>({name:C(e,"name"),teamId:C(e,"teamId")}),http:"POST",method:"updateTeam"},[`${D}/organizations/teams/remove`]:{build:({body:e})=>({teamId:C(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${D}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:C(e,"teamId"),userId:C(e,"userId")}),http:"POST",method:"addTeamMember"},[`${D}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:C(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${D}/organizations/roles/create`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),permission:It(e),role:C(e,"role")}),http:"POST",method:"createOrgRole"},[`${D}/organizations/roles/update`]:{build:({body:e})=>({permission:It(e),roleId:C(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${D}/organizations/roles/remove`]:{build:({body:e})=>({roleId:C(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},ko=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:vo[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 f=new URL(a.url),m={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:T=>e.queryParameter(f,T)},y=i.build(m),A=await t(()=>h(y));return Response.json(i.returns==="void"?{ok:!0}:A,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[a,i]of Object.entries(Io))o[a]=u=>n(u,i);return o},kt="__lunora_admin__:getAuthAuditLog",Pt=e=>typeof e=="string"&&e!==""?e:void 0,Dt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Po=e=>async(n,o)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=Pt(o.actorId),u=Pt(o.event),h=Dt(o.sinceSeq),f=Dt(o.limit),m={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...f===void 0?{}:{limit:f}};let y;try{y=await a.read(m)}catch(T){throw T instanceof c?T:(console.error("[lunora] auth audit read failed:",T),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const A={entries:y};return Response.json({result:Ee(A)},{headers:{"content-type":"application/json"},status:200})},Ze="__lunora_admin__:copyAuthToJurisdiction",fn="__lunora_admin__:purgeUnpinnedAuth",Do=e=>async(t,n,o)=>{if(n!==Ze&&n!==fn)return;e.assertAdmin(t);const a=e.getMove();if(a===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===Ze?await a.copy({force:o.force===!0}):await a.purge();return Response.json({result:Ee(i)},{headers:{"content-type":"application/json"},status:200})},No=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?o.push(a):n.push(a);return{globalTables:o,shardLocalTables:n}},Uo=async(e,t,n,o,a,i)=>{if(n!==void 0&&o.length===0)return[];const u=await e.orchestrateExport(a,{args:{tables:o},defaultShardKey:i,headers:t,tables:o}),h=u.shards.filter(f=>f.error);if(h.length>0){const f=h.map(m=>`${m.shardKey}: ${m.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(h.length)} of ${String(u.shards.length)} shard(s) — ${f}`,{code:"EXPORT_SHARD_FAILED",status:502})}return u.shards.flatMap(f=>f.rows??[])},pn=async(e,t,n,o,a)=>{const i=o??e.listSchemaTables?.();o===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:u,shardLocalTables:h}=No(e,i),f=await Uo(t,n,i,h,a,e.defaultShardKey??"__root__"),m=e.exportGlobals,y=o===void 0||u.length>0;return(async function*(){yield*f,y&&m&&(yield*m({tables:u}))})()},Co=async(e,t,n,o,a,i)=>{for await(const u of await pn(e,t,n,o,i))a(u)},Bo=new TextEncoder,xo=1e3,mn=10,Ho=200,Nt=8,wn="lunoraBackupCron",Ut=24*1048576,Ct=e=>{const t=e.slice(0,mn).map(o=>sn(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Lo=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const a of e)n.set(a,o),o+=a.byteLength;return n},st=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let u=0;u<xo;u+=1){const h=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const f of h.objects)Cr(f.key)&&f.customMetadata?.[wn]===o&&a.push(f.key);if(!h.truncated||h.cursor===void 0)break;i=h.cursor}return{eligible:a.length,stale:a.toSorted((u,h)=>h.localeCompare(u)).slice(n)}},jo=async(e,t,n,o,a)=>{const{stale:i}=await st(e,t,n,o),u=new Set(a),h=i.filter(R=>u.has(R)),f=h.slice(0,Ho),m=i.length-f.length,y=a.length-h.length;if(f.length===0)return{deleted:[],failed:[],ignored:y,remaining:m};const A=[],T=[];for(let R=0;R<f.length;R+=Nt){const E=await Promise.allSettled(f.slice(R,R+Nt).map(async w=>(await e.delete(sn(w)),await e.delete(w),w)));for(const[w,g]of E.entries())g.status==="fulfilled"?A.push(g.value):T.push(f[R+w])}return A.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(A.length)}: ${Ct(A)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${Ct(T)}`),{deleted:A,failed:T,ignored:y,remaining:m}},Mo=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=nt(e.backupPrefix??rt),o=e.backupCron,{eligible:a,stale:i}=o===void 0?{eligible:0,stale:[]}:await st(t,n,e.backupRetain,o);return{cron:o,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},$o=async(e,t,n,o,a)=>{const i=e.backupStore;if(!i)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!o||o.length===0)throw new c("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const u={authorization:`Bearer ${o}`,"content-type":"application/json"},h=e.backupTables;let f=0,m=0,y=[];await Co(e,t,u,h,k=>{const S=Bo.encode(`${JSON.stringify(k)}
2
+ `);if(f+=1,m+=S.byteLength,m>Ut)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Ut)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});y.push(S)},n);const T=nt(e.backupPrefix??rt),R=new Date(a.scheduledTime).toISOString(),E=Br(T,R),w=Lo(y,m);y=[];const g=Hr(await crypto.subtle.digest("SHA-256",w));await i.put(E,w,{httpMetadata:{contentType:"application/x-ndjson"},sha256:g});const O={bytes:m,createdAt:R,cron:a.cron,file:E,id:R,rows:f,scheduledTime:a.scheduledTime,sha256:g,...h?{tables:h.join(",")}:{}};await i.put(xr(E),`${JSON.stringify(O,void 0,2)}
3
+ `,{customMetadata:{[wn]:a.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:k}=await st(i,T,e.backupRetain,a.cron);if(k.length>0){const S=k.slice(0,mn),j=k.length-S.length;console.info(`[lunora] backup retention: ${String(k.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${S.join(", ")}${j>0?` (+${String(j)} more)`:""}`)}}catch(k){console.warn(`[lunora] backup ${E} was written, but the retention report failed:`,k)}},Ko=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const o=e.backupCron,a=e.backupRetain;if(o===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return jo(n,nt(e.backupPrefix??rt),a,o,t)},Fo="/_lunora/admin/backup/retention",Go="/_lunora/admin/backup/prune",Qo=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,a=(h,f)=>{o(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},i=async h=>(M(h,"GET","Backup-retention"),a(h,"retention preview"),Response.json(await Mo(t),{headers:{"cache-control":"no-store"}})),u=async h=>{M(h,"POST","Backup-prune"),a(h,"prune");const{confirm:f}=await n(h);if(!Array.isArray(f)||f.some(m=>typeof m!="string"))throw new c("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await Ko(t,f),{headers:{"cache-control":"no-store"}})};return{[Go]:u,[Fo]:i}},Bt=500,Wo=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const o=e;if(typeof o.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(o.functionPath.startsWith("__lunora_relation__:")||o.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(o.args!==void 0&&(typeof o.args!="object"||o.args===null||Array.isArray(o.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(o.id!==void 0&&typeof o.id!="number")throw new c("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:o.args===void 0?{}:o.args,baselineSeq:typeof o.baselineSeq=="number"?o.baselineSeq:void 0,clientId:typeof o.clientId=="string"?o.clientId:void 0,clientSeq:typeof o.clientSeq=="number"?o.clientSeq:void 0,functionPath:o.functionPath,id:typeof o.id=="number"?o.id:t,mutationId:typeof o.mutationId=="string"?o.mutationId:void 0},shardKey:typeof o.shardKey=="string"?o.shardKey:n}},zo=(e,t)=>{if(e.length>Bt)throw new c(`RPC batch exceeds the ${String(Bt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,o=new Set;for(const[a,i]of e.entries()){const{entry:u,shardKey:h}=Wo(i,a,t);if(o.has(u.id))throw new c(`batch call id ${String(u.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});o.add(u.id);const f=n.get(h)??[];f.push(u),n.set(h,f)}return n},Vo="/_lunora/admin/export",Jo="/_lunora/admin/import",Yo="/_lunora/admin/sync",qo="/_lunora/admin/connector/sync",Xo="/_lunora/admin/apply",Zo="/_lunora/admin/export-tap/run",ea=new TextEncoder,ta=async e=>{const n=await ne(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const o=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});o.push(a)}return{tables:o}},Fe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,na=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:a,knownTables:i,queryCoordinator:u,assertAdmin:h,resolveForwardContext:f,shardDO:m,prepareExportRows:y,streamingImport:A,syncGlobals:T}=e,R=async(S,j)=>{const H=me(S,["POST"]);if(H)return H;h(S);const N=await ta(S),{headers:K}=await f(S,j),W=await y(K,N.tables),J=new ReadableStream({async pull(Y){try{for await(const G of W)Y.enqueue(ea.encode(`${JSON.stringify(G)}
4
+ `));Y.close()}catch(G){Y.error(G)}}});return new Response(J,{headers:{"content-type":"application/x-ndjson"},status:200})},E=async(S,j)=>{const H=me(S,["POST"]);if(H)return H;h(S);const N=await ee(S),K=typeof N.cursors=="object"&&N.cursors!==null?N.cursors:{},W=typeof N.epochs=="object"&&N.epochs!==null?N.epochs:{},J=typeof N.limit=="number"?N.limit:void 0,Y=typeof N.globalCursor=="number"?N.globalCursor:0,G=Fe(N.tables),{headers:re}=await f(S,j),Q=G??i(),de=await u.orchestrateCdcSync(m,{cursors:K,defaultShardKey:n,epochs:W,headers:re,limit:J,tables:Q}),oe=T?await T({limit:J,sinceSeq:Y}):void 0;return Response.json({global:oe,shards:de.shards},{status:200})},w=async(S,j)=>{const H=me(S,["POST"]);if(H)return H;h(S);const N=await ee(S),K=Kr(N.cursor),W=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,J=Fe(N.tables),{headers:Y}=await f(S,j),G=J??i(),re=await u.orchestrateCdcSync(m,{cursors:K.s,defaultShardKey:n,headers:Y,limit:W,tables:G}),Q=[],de={...K.s};let oe=!1;for(const se of re.shards)oe=St(Q,se.changes??[],Gr(W))||oe,de[se.shardKey]=se.cursor;let ye=K.g;if(T){const se=await T({limit:W,sinceSeq:K.g});oe=St(Q,se.changes,W)||oe,ye=se.cursor}const z=Fr({g:ye,s:de,v:1}),ae={changes:Q,hasMore:oe,nextCursor:z};return Response.json(ae,{status:200})},g=async(S,j)=>{const H=me(S,["POST"]);if(H)return H;h(S);const N=await ee(S),W=(Array.isArray(N.batches)?N.batches:[]).map(Q=>Q).filter(Q=>Q!==null&&typeof Q=="object"&&typeof Q.shardKey=="string"&&Array.isArray(Q.changes)),J=Array.isArray(N.globalChanges)?N.globalChanges:[],{headers:Y}=await f(S,j),G=await u.orchestrateApplyCdc(m,{batches:W,headers:Y}),re=J.length>0&&t?await t({changes:J}):0;return Response.json({applied:G.applied+re,failed:G.failed,ok:G.ok},{status:200})},O=async(S,j)=>{const H=me(S,["POST"]);if(H)return H;h(S);const{headers:N}=await f(S,j),K=await A(S,N);return Response.json(K,{headers:{"content-type":"application/json"},status:K.failed.length>0?207:200})},k=async(S,j)=>{const H=me(S,["POST"]);if(H)return H;if(h(S),a===void 0||Object.keys(a).length===0||o===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const N=await ee(S),K=typeof N.sink=="string"?N.sink:void 0,W=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,J=Fe(N.tables);if(K===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const Y=a[K];if(Y===void 0)throw new c(`Export-tap sink "${K}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:G}=await f(S,j),re=J??i(),Q=await $r({coordinator:u,cursorStore:o,defaultShardKey:n,headers:G,limit:W,shardDO:m,sink:Y,tables:re});return Response.json(Q,{headers:{"content-type":"application/json"},status:200})};return{[Xo]:g,[qo]:w,[Vo]:R,[Zo]:k,[Jo]:O,[Yo]:E}},ra=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const o=n;return typeof o.table!="string"||o.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!o.doc||typeof o.doc!="object"||Array.isArray(o.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:o.table},ok:!1}:{doc:o.doc,ok:!0,table:o.table}},oa=(e,t,n,o,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:o}},aa=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const o=[],a=[],i=new Map;let u=0,h=0;const f=e.body.getReader(),m=new TextDecoder;let y="",A=0;const T=R=>{h+=1;const E=R.trim();if(E.length===0)return;u+=1;const w=ra(E,h);if(!w.ok){o.push(w.error);return}const{doc:g,table:O}=w,k=t.resolveTableSharding?.(O);if(k?.mode.kind==="global"){a.push({doc:g,line:h,table:O});return}const S=oa(g,O,k,n,h);if(!S.ok){o.push(S.error);return}const j=i.get(S.shardKey);j?j.rows.push({doc:g,table:O}):i.set(S.shardKey,{rows:[{doc:g,table:O}],shardKey:S.shardKey,startLine:h})};for(;;){const{done:R,value:E}=await f.read();if(R)break;if(E&&(A+=E.byteLength,A>rn))throw await f.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});y+=m.decode(E,{stream:!0});let w=y.indexOf(`
5
+ `);for(;w!==-1;){const g=y.slice(0,w);y=y.slice(w+1),T(g),w=y.indexOf(`
6
+ `)}}return y.length>0&&T(y),{errors:o,globalRows:a,perShard:i,received:u}},sa=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),xt=(e,t)=>{for(const[n,o]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+o;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},ia=async(e,t,n,o,a)=>{const i=t.defaultShardKey??"__root__",{errors:u,globalRows:h,perShard:f,received:m}=await aa(e,t,i),y={conflicts:0,errors:u,failed:[],inserted:{}},A=[];if(t.resolveTableSharding===void 0&&f.size>0&&A.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"),f.size>0){const T=await n.orchestrateImport(a,{batches:[...f.values()],headers:o});xt(y,T),y.failed.push(...sa(T.shards))}if(h.length>0)if(t.importGlobals){const T=h[0]?.line??1,R=await t.importGlobals({rows:h,startLine:T});xt(y,R)}else for(const T of h)y.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:T.line,message:`row targets global table "${T.table}" but no \`importGlobals\` is configured`,table:T.table});return{conflicts:y.conflicts,errors:y.errors,failed:y.failed,inserted:y.inserted,received:m,...A.length>0?{warnings:A}:{}}},Ge=e=>typeof e=="object"&&e!==null?e:{},Qe=e=>typeof e.kind=="string"?e.kind:"unknown",ca=(e,t)=>{let n=Ge(t),o=!1;Qe(n)==="optional"&&(o=!0,n=Ge(n._meta?.inner));const a=Qe(n),i=n._meta??{},u={kind:a,name:e,optional:o};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const h=Qe(Ge(i.inner));h!=="unknown"&&(u.element=h)}return u},da=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>ca(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),ua="/_lunora/admin/functions",la="/_lunora/admin/cron-jobs",ha="/_lunora/admin/openapi",fa="/_lunora/admin/openrpc",pa="/_lunora/admin/global/tables",ma="/_lunora/admin/global/table",wa="/_lunora/admin/global/facet",Ht=e=>{if(e===void 0||e==="")return;let t;try{t=Ye(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(o=>{if(typeof o!="object"||o===null||typeof o.column!="string")return[];const{column:a,value:i}=o;return[{column:a,value:i}]});return n.length===0?void 0:n},ga=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:{}}),ya=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"}),ba=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:a,requireAdminOption:i}=e,u=R=>{M(R,"GET","Functions");const E=i(R,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),w=Object.entries(E).flatMap(([g,O])=>O.visibility==="internal"||O.kind==="stream"?[]:[{args:da(O.args),kind:O.kind,path:g}]).toSorted((g,O)=>g.path.localeCompare(O.path));return Response.json({functions:w},{headers:{"content-type":"application/json"},status:200})},h=R=>{M(R,"GET","Cron-jobs");const E=i(R,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),w=Object.entries(E).flatMap(([g,O])=>O.map(k=>({args:k.args,cron:g,functionPath:k.functionPath,name:k.name,shardKey:k.shardKey,workflow:k.workflow}))).toSorted((g,O)=>g.name.localeCompare(O.name));return Response.json({jobs:w},{headers:{"content-type":"application/json"},status:200})},f=R=>(M(R,"GET","OpenAPI"),t(R),Response.json(n.openApiSpec??ga,{headers:{"content-type":"application/json"},status:200})),m=R=>(M(R,"GET","OpenRPC"),t(R),Response.json(n.openRpcSpec??ya,{headers:{"content-type":"application/json"},status:200})),y=async R=>{M(R,"GET","Global-tables");const E=i(R,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await E.listTables(),{headers:{"content-type":"application/json"},status:200})},A=async R=>{M(R,"GET","Global-table");const E=i(R,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),w=new URL(R.url),g=a(w,"table");if(g===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const O=await E.readTablePage({...o(R),filters:Ht(a(w,"filters")),table:g});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},T=async R=>{M(R,"GET","Global-facet");const E=i(R,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),w=new URL(R.url),g=a(w,"table"),O=a(w,"column");if(g===void 0||O===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const k=a(w,"limit"),S=k===void 0?void 0:Number(k),j=await E.facetColumn({column:O,filters:Ht(a(w,"filters")),limit:S!==void 0&&Number.isFinite(S)?S:void 0,table:g});return Response.json(j,{headers:{"content-type":"application/json"},status:200})};return{[la]:h,[ua]:u,[wa]:T,[ma]:A,[pa]:y,[ha]:f,[fa]:m}},_a="/_lunora/admin/kv/namespaces",Ra="/_lunora/admin/kv/keys",gn="/_lunora/admin/kv/value",yn=32*1048576,Lt=60,Ea=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=E=>n(E,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=E=>Response.json(E,{headers:{"content-type":"application/json"},status:200}),i=(E,w)=>{const g=new URL(E.url),O=g.searchParams.get("namespace")??"",k=g.searchParams.get("key")??"";if(O==="")throw new c(`KV-value ${w} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(k==="")throw new c(`KV-value ${w} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:k,namespace:O}},u=async(E,w)=>{if(!(await E.listNamespaces()).some(O=>O.binding===w))throw new c(`Unknown KV namespace binding \`${w}\``,{code:"NOT_FOUND",status:404})},h=async E=>(M(E,"GET","KV-namespaces"),a({namespaces:await o(E).listNamespaces()})),f=async E=>{M(E,"GET","KV-keys");const w=o(E),g=new URL(E.url),O=g.searchParams.get("namespace")??"";if(O==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const k=g.searchParams.get("prefix")??void 0,S=g.searchParams.get("cursor")??void 0,j=g.searchParams.get("limit"),H=j===null?void 0:Number.parseInt(j,10);if(H!==void 0&&(!Number.isInteger(H)||H<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const N=H===void 0?void 0:Math.min(H,1e3);return await u(w,O),a(await w.listKeys({cursor:S,limit:N,namespace:O,prefix:k}))},T={DELETE:async E=>{const w=o(E),g=i(E,"DELETE");return await u(w,g.namespace),await w.deleteKey(g),a({deleted:!0})},GET:async E=>{const w=o(E),g=i(E,"GET");return await u(w,g.namespace),a(await w.getValue(g))},PUT:async E=>{const w=o(E),g=await t(E,yn);if(typeof g.namespace!="string"||g.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof g.key!="string"||g.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof g.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(g.expirationTtl!==void 0&&(typeof g.expirationTtl!="number"||!Number.isInteger(g.expirationTtl)||g.expirationTtl<Lt))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const O=Math.floor(Date.now()/1e3)+Lt;if(g.expiration!==void 0&&(typeof g.expiration!="number"||!Number.isInteger(g.expiration)||g.expiration<O))throw new c("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(w,g.namespace),await w.putValue({expiration:g.expiration,expirationTtl:g.expirationTtl,key:g.key,metadata:g.metadata,namespace:g.namespace,value:g.value}),a({ok:!0})}},R=E=>{const w=T[E.method];if(!w)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return w(E)};return{[_a]:h,[Ra]:f,[gn]:R}},Sa="/_lunora/migrate",Aa="/_lunora/admin/pitr",Ta="/_lunora/admin/rank",Oa="/_lunora/admin/rankpage",va="/_lunora/admin/shard-registry/prune",Ia="/_lunora/admin/shard-traffic",ka=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Pa=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Da=async e=>{const n=await ne(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!ka.has(n.functionPath))throw new c("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},Na=async e=>{const n=await ne(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new c("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new c("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new c("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new c("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},Ua=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}},Ca=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})},Ba=async e=>{const n=await ne(e,"Rank page")??{};Ca(n);const o=Ua(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:o,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},xa=async e=>{const n=await ne(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},Ha=async e=>{const n=await ne(e,"Shard-registry prune")??{};if(n.tables!==void 0&&!(Array.isArray(n.tables)&&n.tables.every(o=>typeof o=="string")))throw new c("Shard-registry prune `tables` must be an array of table names",{code:"BAD_REQUEST",status:400});return{dryRun:n.dryRun===!0,tables:n.tables}},La=async e=>{const n=await ee(e);if(typeof n.functionPath!="string"||!Pa.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}},ja=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:a,resolveForwardContext:i,shardDO:u,shardedTables:h}=e,f=(w,g)=>{if(w.method!=="POST")throw new c(`${g} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(w))throw new c("Admin auth required",{code:"FORBIDDEN",status:403})},m=async(w,g)=>{f(w,"Migration");const O=await Da(w),{headers:k}=await i(w,g),S=await a.orchestrateMigration(u,{args:O.args,defaultShardKey:t,functionPath:O.functionPath,headers:k,table:O.table});return Response.json(S,{headers:{"content-type":"application/json"},status:200})},y=async(w,g)=>{f(w,"Rank");const O=await Na(w),{headers:k}=await i(w,g),S=await a.orchestrateRank(u,{headers:k,index:O.index,partitionKey:O.partitionKey,rowId:O.rowId,sortValues:O.sortValues,table:O.table});return Response.json(S,{headers:{"content-type":"application/json"},status:200})},A=async(w,g)=>{f(w,"Rank page");const O=await Ba(w),{headers:k}=await i(w,g),S=await a.orchestrateRankPage(u,{...O,headers:k});return Response.json(S,{headers:{"content-type":"application/json"},status:200})},T=async(w,g)=>{f(w,"Shard-traffic");const O=await xa(w),{headers:k}=await i(w,g),S=await a.orchestrateShardTraffic(u,{headers:k,table:O.table});return Response.json(S,{headers:{"content-type":"application/json"},status:200})},R=async(w,g)=>{f(w,"Shard-registry prune");const O=await Ha(w),k=h(),S=(O.tables??[]).filter(N=>!k.includes(N));if(S.length>0)throw new c(`Shard-registry prune names tables that are not \`.shardBy()\`: ${S.join(", ")}`,{code:"BAD_REQUEST",status:400});const{headers:j}=await i(w,g),H=await Yr(a.registry,u,{dryRun:O.dryRun,headers:j,tables:O.tables??k});return Response.json(H,{status:H.failed.length>0?207:200})},E=async(w,g)=>{if(M(w,"POST","PITR"),!o(w))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const O=await La(w),{headers:k}=await i(w,g),S=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:O.args,functionPath:O.functionPath}),headers:k,method:"POST"});return n(u,O.shardKey??t,S)};return{[Sa]:m,[Aa]:E,[Ta]:y,[Oa]:A,[va]:R,[Ia]:T}},Ma=1,$a=0,Ka=32,Fa=512,Ga=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Qa=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Fa)return;const n=t.split(",");if(!(n.length>Ka)){for(const o of n)if(!Ga.test(o.trim()))return;return t}},Wa=e=>{const t=Sr(e.headers.get("traceparent"));if(t===void 0)return;const n=Qa(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},jt=(e,t={})=>{const n=Wa(e),o=t.trustInbound===!0?n:void 0,a=we(8),i=o?.traceId??we(16),u=Ir(t.sampling,o===void 0?a:i),h=u.isTraced&&(o===void 0||o.sampled);return{decision:u,ignoredUpstream:n!==void 0&&o===void 0,trace:{sampled:h,spanId:a,traceFlags:h?Ma:$a,traceId:i,...o?.parentSpanId===void 0?{}:{parentSpanId:o.parentSpanId},...o?.traceState===void 0?{}:{traceState:o.traceState}}}},Mt=(e,t)=>{t.traceparent=nn(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},za=(e,t)=>{let n;return()=>{if(n===void 0){const o=vr(e),a=t===void 0?void 0:t.cf;n=Ar(Or(o),Tr(o,a))}return n}},Va="/_lunora/admin/scheduled",Ja="/_lunora/admin/scheduled/status",Ya="/_lunora/admin/scheduled/ws",qa="/_lunora/admin/scheduled/cancel",Xa="/_lunora/admin/scheduled/dead",Za="/_lunora/admin/scheduled/dead/retry",es="/_lunora/admin/scheduled/dead/cancel",ts="/_lunora/admin/scheduled/pool/release",ns=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:a}=e,i=(m,y)=>A=>{if(A.method!=="GET")throw new c(`${y} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(A.url).searchParams.get("cursor"),R=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return o(A).fetch(new Request(`https://scheduler.internal${m}${R}`,{method:"GET"}))},u=(m,y,A=y)=>async T=>{if(T.method!=="POST")throw new c(`${A} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const R=o(T),E=await ne(T,y);if(typeof E?.id!="string"||E.id==="")throw new c(`${y} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return R.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:E.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async m=>{if(m.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const y=o(m),A=await ne(m,"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 y.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"}))},f=async m=>{if(m.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(m))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const y=n();return ge(y,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[qa]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[es]:u("/dead/cancel","Scheduled dead-letter action"),[Xa]:i("/dead","Scheduled dead-letter"),[Za]:u("/dead/retry","Scheduled dead-letter action"),[Va]:i("/list","Scheduled-list"),[ts]:h,[Ja]:i("/status","Scheduler-status"),[Ya]:f}},rs="/_lunora/scheduled",bn="/_lunora/queue",_n=16*1048576,os=e=>{const{assertAdmin:t,dispatchScheduled:n,queueHandler:o}=e,a=async(u,h,f)=>{if(t(u),u.method!=="POST")throw new c("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const m=await ne(u,"Scheduled tick"),y=typeof m?.cron=="string"?m.cron:"";if(y==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:y,noRetry:()=>{},scheduledTime:Date.now()},h,f),Response.json({cron:y,ok:!0})},i=async(u,h,f)=>{if(t(u),u.method!=="POST")throw new c("queue dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!o)throw new c("no queueHandler configured",{code:"BAD_REQUEST",status:400});const m=await ne(u,"Queue dispatch",_n);if(!Array.isArray(m?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const y=typeof m.queue=="string"?m.queue:"",A=m.messages.filter(R=>typeof R=="object"&&R!==null&&typeof R.id=="string").map(R=>({body:R.body,id:R.id})),T=await o({messages:A,queue:y},h,f);return Response.json({retry:T?.retry??[]})};return{[bn]:i,[rs]:a}},as=(e,...t)=>{let n=e.cf;for(const o of t){if(typeof n!="object"||n===null)return;n=n[o]}return typeof n=="string"?n:void 0},et={mtls:e=>as(e,"tlsClientAuth","certVerified")==="SUCCESS"},ss=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(et,e)?et[e]:void 0)??(()=>!1),is=e=>typeof e=="string"&&Object.hasOwn(et,e),cs=e=>{const t=is(e)?e:void 0;if(e!==void 0&&t===void 0)return()=>{};let n=!1;return o=>{n||t!==void 0&&o.cf!==void 0||(n=!0,console.warn(t===void 0?'[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.':`[lunora] \`trustInboundTraceContext: "${t}"\` cannot be satisfied on this host: the request carries no platform-injected \`cf\` metadata, which is what that signal reads, so every inbound \`traceparent\` is ignored and this request starts a new trace. Off Cloudflare, trust the upstream some other way — \`trustInboundTraceContext: true\` when nothing untrusted can reach this worker, or a predicate that verifies whatever your own front door sets. Set it to \`false\` to keep this behaviour and silence this message.`))}},ds="/_lunora/admin/vector/indexes",us="/_lunora/admin/vector/query",ls=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=async i=>{M(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=>{M(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 f=await t(i);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 m=await u.queryIndex({name:f.name,text:f.text,topK:f.topK});return Response.json(m,{headers:{"content-type":"application/json"},status:200})};return{[ds]:o,[us]:a}},hs="/_lunora/admin/workflows/instances",fs="/_lunora/admin/workflows/instance",ps="/_lunora/admin/workflows/status",ms={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},ws=e=>e!==null&&Object.hasOwn(ms,e)?e:void 0,$t=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const o=Number(n);return Number.isInteger(o)&&o>0?o:void 0},We=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new c(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},Kt=()=>{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})},gs=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,o=async(u,h,f)=>{M(u,"GET","Workflows instances"),t(u);const m=n(h);if(!m)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const y=We(f,"name"),A=ws(f.searchParams.get("status"));return Response.json(await m.listInstances({page:$t(f,"page"),perPage:$t(f,"perPage"),status:A,workflowName:y}))},a=async(u,h,f)=>{M(u,"GET","Workflows instance"),t(u);const m=n(h);return m?Response.json(await m.getInstance({instanceId:We(f,"id"),workflowName:We(f,"name")})):Kt()},i=async(u,h)=>{M(u,"POST","Workflows status"),t(u);const f=n(h);if(!f)return Kt();const m=await ne(u,"Workflows status");if(typeof m?.name!="string"||m.name===""||typeof m.id!="string"||m.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:y}=m;if(y!=="pause"&&y!=="resume"&&y!=="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:y,instanceId:m.id,workflowName:m.name}))};return{[fs]:a,[hs]:o,[ps]:i}},ys={[gn]:yn,[bn]:_n,[Mr]:jr},Ft="/_lunora/rpc",bs="/_lunora/rpc-batch",_s="/_lunora/ws",Re=(e,t,n)=>({resourceAttributes:za(e,t),...n===void 0?{}:{waitUntil:n}}),ze=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Gt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ve=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let o;try{o=new URL(e.url)}catch{return{method:t,userAgent:n}}const a=o.port===""?void 0:Number(o.port);return{host:o.hostname,method:t,path:o.pathname,port:Number.isNaN(a)?void 0:a,scheme:o.protocol.replace(":",""),userAgent:n}},Qt="/_lunora/voice/",Rs="/_lunora/scheduler/dispatch",Es="/_lunora/admin/cron-jobs/run",Ss="/_lunora/admin/ws-token",As="/_lunora/admin/",Ne="/_lunora/",Ts="/_lunora/migrate",Os="/_lunora/status",vs=e=>e.startsWith(As)||e===Ts,Is="__lunora_relation__:",ve=e=>{if(e.startsWith(Is))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Ie=async e=>await e===!0,Wt=(e,t)=>{const n=e.headers.get(gt);if(n===null)return;const o=Er(n);if(o===void 0)throw new c(`malformed ${gt} header`,{code:"BAD_REQUEST",status:400});if(o.subject!==(t?.userId??null))throw new c("the session changed since this write was queued",{code:"IDENTITY_MISMATCH",status:409})},ks=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},zt="/api/auth",Ps="__lunora_admin__:recordAuthEvent",Vt="__lunora_admin__:listPushSubscriptions",Ds=["/sign-in","/sign-up","/callback"],Ns=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return Ds.some(a=>o===a||o.startsWith(`${a}/`))},Jt=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},ke=(e,t,n,o)=>{const a=pr(n),i=a?n.code:"INTERNAL_SERVER_ERROR",u=a?n.status:500,h=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:h,status:u},functionPath:e,ok:!1,...o.fanOut?{fanOut:{failed:0,shards:0,table:o.fanOut.table}}:{},...o.shardKey?{shardKey:o.shardKey}:{}}},Rn=e=>{const{exp:t,expiresAtMs:n}=e;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},En=({identity:e})=>e!==null&&br(Rn(e)),Us=e=>{if(En(e))throw new c("authentication token expired",{code:"TOKEN_EXPIRED",status:401});return e},Cs=e=>{if(!En(e))return e;const t={...e.headers};return delete t["x-lunora-identity"],delete t["x-lunora-identity-exp"],delete t["x-lunora-userid"],{claims:null,headers:t,identity:null,userId:null}},Yt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Bs=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},tt=new WeakMap,xs=async(e,t,n,o,a=tt.get(e))=>{const i={"content-type":"application/json"},u=e.headers.get("authorization"),h=e.headers.get("cookie"),f=e.headers.get("x-d1-bookmark"),m=e.headers.get("x-lunora-mutation-id"),y=e.headers.get("x-lunora-client-id"),A=e.headers.get("x-lunora-client-seq"),T=e.headers.get("x-lunora-base-seq");u&&(i.authorization=u),h&&(i.cookie=h),f&&(i["x-d1-bookmark"]=f),m&&(i["x-lunora-mutation-id"]=m),y&&(i["x-lunora-client-id"]=y),A&&(i["x-lunora-client-seq"]=A),T&&(i["x-lunora-base-seq"]=T);const R=Ur(e.headers,o);if(R&&(i["x-lunora-client-ip"]=R),i["x-lunora-origin"]=new URL(e.url).origin,!n)return{claims:null,headers:i,identity:null,userId:null};const E=await n(e,t,a);if(!E||typeof E.userId!="string"||E.userId.length===0)return{claims:null,headers:i,identity:null,userId:null};i["x-lunora-userid"]=_r(E.userId);const w=Rn(E);w!==void 0&&(i["x-lunora-identity-exp"]=String(w));const{userId:g,...O}=E,k=Object.keys(O).length>0?O:null;return k&&(i["x-lunora-identity"]=Rr(k)),{claims:k,headers:i,identity:E,userId:g}},Hs=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Ls=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"||!Hs.has(n.kind))throw new c("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new c("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new c("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},js=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},Je=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new c("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new c(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},Ms=async e=>{const t=await an(e);let n;try{n=JSON.parse(t)}catch{throw new c("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new c("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const o=n;if(o.args!==void 0&&on(o.args,"RPC"),o.shardKey!==void 0&&typeof o.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,i=Ls(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}},Pe=new Map,$s=5e3,Ks=4096,Fs=async(e,t)=>{const n=Date.now(),o=Pe.get(t);if(o!==void 0&&o.expiresMs>n)return o.relayCount;o!==void 0&&Pe.delete(t);let a=0;try{const i=await 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 tn(Pe,Ks),Pe.set(t,{expiresMs:n+$s,relayCount:a}),a},qt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},De=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),Gs=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],Qs=(e,t)=>{for(const n of Gs){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},Xt=(e,t)=>{const n=new Headers(e.headers),o=[...n.keys()];for(const a of o)a.startsWith("x-lunora-")&&n.delete(a);return Qs(n,t),n},Ws=async(e,t,n)=>e.length===0||n.length===0?!1:ot(await un(e,t),n),Zt=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[o,...a]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:ot(t,a.join(" ").trim())},en=async(e,t,n)=>{if(!t||t.length===0)return!1;const o=new URL(e.url).searchParams.get("token");return o===null?!1:await Oo(t,o)?!0:n?!1:ot(t,o)},zs=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return zr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return je(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return je(`queue:${e}`,!0);if(typeof n.connectionString=="string")return je(`hyperdrive:${e}`,!0)},Vs=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(Ne))throw new c(`route "${t}" is under the reserved ${Ne} prefix, which the framework owns. App routes registered there shadow the internal endpoint AND its admin gate — pick a path outside the prefix.`,{code:"MISCONFIGURED",status:500})},Js=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})},Sn=e=>{Js(e);const t=ss(e.trustInboundTraceContext),n=cs(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",a=e.queryCoordinator??qr({registry:Xr(e.resolveTableSharding,o)}),i=Vr(e.resolveIdentity,e.identity),u=Me(e.shardDO,e.jurisdiction),h=e.schedulerDO===void 0?void 0:Me(e.schedulerDO,e.jurisdiction),f=e.voiceAgents===void 0?void 0:Object.fromEntries(Object.entries(e.voiceAgents).map(([r,s])=>[r,Me(s,e.jurisdiction)]));let m=!1;const y=r=>{if(r===void 0||e.jurisdiction===void 0)return r;m||(m=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},A=async(r,s,l,d=e.shardRegion?.(s))=>ge(r,s,y(d)).fetch(l);let T;const R=()=>e.adminToken??T;let E;const w=()=>e.requireEphemeralWsToken??E??!0;let g;const O=r=>{const s=r??{};if(g??=qt(r,e.shardDO),E===void 0&&e.requireEphemeralWsToken===void 0){const d=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof d=="string"&&d.length>0&&(E=So(d,!0))}if(T!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(T=l)},k=new WeakSet,S=r=>Zt(r,R())||k.has(r),j=async r=>{if(!(e.adminGate===void 0||k.has(r)))try{await Ie(e.adminGate(r,tt.get(r)))&&k.add(r)}catch{}},H=async(r,s,l,d)=>{const p=await xs(r,s,l,e.trustedClientIpHeader,d);return e.functions!==void 0&&(p.headers[bt]=yt),p},N=async(r,s,l,d)=>Us(await H(r,s,l,d)),K=async(r,s)=>{const l=await H(r,s,e.resolveIdentity);if(k.has(r)&&l.headers.authorization===void 0){const d=R();d!==void 0&&(l.headers.authorization=`Bearer ${d}`)}return l};let W=!1,J=!1;const Y=()=>{J||(J=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},G=r=>{if(!e.allowUnauthenticatedShardAccess){const s=r==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${r} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${r} access (relying solely on per-row RLS).`,{code:r==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}W||(W=!0,console.warn([`[lunora] SECURITY: serving ${r} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},re=async(r,s,l=!1)=>{if(s.includes(qe)||s.includes(Xe))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(!l)if(e.authorizeShard){if(!await Ie(e.authorizeShard({identity:r,shardKey:s})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==o&&G("shard")},Q=ja({defaultShard:o,forwardToShard:A,isAdmin:S,queryCoordinator:a,resolveForwardContext:K,shardDO:u,shardedTables:()=>(e.listSchemaTables?.()??[]).filter(r=>e.resolveTableSharding?.(r)?.mode.kind==="shardBy")}),de=async(r,s,l,d,p,b)=>{ve(r);const I={"content-type":"application/json",[bt]:yt,"x-lunora-system":"1"};return p?.userId!==void 0&&p.userId.length>0&&(I["x-lunora-userid"]=p.userId),p?.identity!==void 0&&p.identity.length>0&&(I["x-lunora-identity"]=p.identity),d!==void 0&&d.length>0&&(I["x-lunora-mutation-id"]=d),b!==void 0&&b.length>0&&(I.traceparent=b),A(u,l,De(r,s,I))},oe=async(r,s,l,d,p)=>{const b=l?.[r];if(!b||typeof b.create!="function")throw new c(`${d} targets workflow binding "${r}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(no(s))throw new c(`${d} params ${ro}`,{code:"BAD_REQUEST",status:400});try{await b.create(p===void 0?{params:s}:{id:p,params:s})}catch(I){if(!so(I))throw I}},ye=async(r,s,l)=>{if(r.workflow){await oe(r.workflow,r.args??{},s,`cron job "${r.name}"`);return}if(r.functionPath===void 0)throw new c(`cron job "${r.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const d=await de(r.functionPath,r.args??{},r.shardKey??o,void 0,void 0,l);if(!d.ok)throw new c(`cron job "${r.name}" (${r.functionPath}) failed with shard status ${String(d.status)}`,{code:"CRON_JOB_FAILED",status:500})},z=r=>{if(!S(r))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},ae=(r,s,l)=>{if(z(r),s===void 0)throw new c(l.message,{code:l.code,status:400});return s},se=async(r,s,l,d,p)=>{const b=e.cronJobs?.[r];if(!b)return 0;for(const I of b)try{await ye(I,s,p)}catch(P){l.push(d(P))}return b.length},An=async(r,s)=>{if(z(r),M(r,"POST","cron-jobs run"),!e.cronJobs)throw new c("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await ee(r),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 p=Object.values(e.cronJobs).flat().find(b=>b.name===d);if(!p)throw new c(`no cron job named "${d}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await ye(p,s),Response.json({name:d,ran:!0},{status:200})},it=async r=>{const s=typeof r.pool=="string"&&r.pool.length>0?r.pool:void 0;if(!s||!h||typeof r.id!="string")return;const l=typeof r.instanceName=="string"&&r.instanceName.length>0?r.instanceName:"default";try{await ge(h,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:r.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Tn=async(r,s)=>{M(r,"POST","Scheduler dispatch");const l=await an(r),d=s??{},p=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),I=r.headers.get("x-lunora-scheduler-signature");let P=!1;if(I&&p?P=await Ws(p,l,I):b&&(P=Zt(r,b)),!P)throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let U;try{U=JSON.parse(l)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const _=U??{},v=_.args??{},B=typeof _.id=="string"&&_.id.length>0?_.id:void 0;if(typeof _.workflow=="string"&&_.workflow.length>0)return await oe(_.workflow,v,s,"scheduled workflow",B),await it(_),Response.json({ok:!0},{status:200});if(typeof _.functionPath!="string"||_.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const L=typeof _.shardKey=="string"&&_.shardKey.length>0?_.shardKey:o,V=ks(r),x=await de(_.functionPath,v,L,B,V,r.headers.get("traceparent")??void 0);return await it(_),x},On=Po({assertAdmin:z,getReader:()=>e.authAuditReader}),vn=Do({assertAdmin:z,getMove:()=>e.authJurisdictionMove}),In=async(r,s)=>{z(r);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:Ee({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const d=s?.kind,p=s?.userId,b=s?.limit,I=d==="fcm"||d==="web-push"?d:void 0,P=typeof p=="string"&&p!==""?p:void 0,U=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,_=U>0?Math.min(U,1e3):1e3,B=(await l.list({kind:I,limit:_,userId:P})).filter(L=>I!==void 0&&L.kind!==I?!1:P===void 0||(L.userId??null)===P).map(({keys:L,token:V,...x})=>x);return Response.json({result:Ee({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},kn=async(r,s)=>{if(!s.fanOut&&!(s.functionPath!==kt&&s.functionPath!==Vt&&s.functionPath!==Ze&&s.functionPath!==fn))return await j(r),s.functionPath===kt?On(r,s.args??{}):s.functionPath===Vt?In(r,s.args):vn(r,s.functionPath,s.args??{})},Pn=na({applyGlobals:e.applyGlobals,assertAdmin:z,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:o,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:a,resolveForwardContext:K,shardDO:u,prepareExportRows:async(r,s)=>pn(e,a,r,s,u),streamingImport:(r,s)=>ia(r,e,a,s,u),syncGlobals:e.syncGlobals}),Ue=(r,s)=>{const l=r.searchParams.get(s);return l===null||l===""?void 0:l},Ce=r=>{const s=new URL(r.url),l=s.searchParams.get("limit"),d=s.searchParams.get("offset"),p=l===null?void 0:Number.parseInt(l,10),b=d===null?void 0:Number.parseInt(d,10);return{limit:p!==void 0&&Number.isFinite(p)&&p>=0?p:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},ct=()=>{if(h===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return h},Dn=ns({checkWsAdmin:async r=>S(r)||en(r,R(),w()),requireSchedulerNamespace:ct,resolveSchedulerStub:r=>(z(r),ge(ct(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Nn=gs({assertAdmin:z,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Un=Lr({assertAdmin:z,parsePaging:Ce,queryParameter:Ue,readBodyBytes:Dr,requireAdminOption:ae,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Cn=Qo({options:e,readJsonBody:ee,requireAdminOption:ae}),Bn=ls({readJsonBody:ee,requireAdminOption:ae,vectorIntrospector:e.vectorIntrospector}),xn=Ea({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:ae}),Hn=Jr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:ae}),Ln=ba({assertAdmin:z,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ce,queryParameter:Ue,requireAdminOption:ae}),jn=r=>{const s=[],l=u??r?.SHARD;if(l!==void 0&&s.push(Wr("durable-object:default",l,o)),e.health?.disableBindingProbes!==!0)for(const[d,p]of Object.entries(r??{})){const b=zs(d,p);b!==void 0&&s.push(b)}for(const d of e.health?.probes??[])s.push(d);return s},Mn=Qr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:S,resolveProbes:jn}),$n=r=>{const s=_=>"args"in _?{..._,args:Ye(_.args)}:_,l=e.schedulerInstanceName??"default",d=()=>ge(r,l),p=async(_,v)=>{const B=await d().fetch(new Request(`https://scheduler.internal${_}`,v));if(!B.ok)throw new c(`ctx.scheduler: SchedulerDO ${_} failed (${String(B.status)}): ${await B.text()}`,{code:"INTERNAL",status:500});return await B.json()},b=async(_,v)=>await p(_,{body:JSON.stringify(v),headers:{"content-type":"application/json"},method:"POST"}),I=_=>{const v=_;if(v==null)throw new c("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof v.binding=="string"&&v.binding.length>0)return{workflow:v.binding};if(typeof v.__lunoraRef=="string")return{functionPath:v.__lunoraRef};throw new c("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},P=async()=>(await oo(async v=>p(v===void 0?"/list":`/list?cursor=${encodeURIComponent(v)}`,{method:"GET"}))).map(v=>s(v)),U=async(_,v,B={})=>{const L=I(v),{id:V}=await b("/schedule",{args:kr("ctx.scheduler",String(L.functionPath??L.workflow),B),scheduledFor:Math.ceil(_),...L});return V};return{cancel:async _=>await b("/cancel",{id:_}),get:async _=>{const v=await p(`/get?id=${encodeURIComponent(_)}`,{method:"GET"});return v.record===void 0?null:s(v.record)},list:P,runAfter:async(_,v,B)=>{if(!Number.isFinite(_)||_<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await U(Date.now()+_,v,B)},runAt:async(_,v,B)=>{if(!Number.isFinite(_))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await U(_,v,B)}}},Kn=async(r,s,l)=>{const{claims:d,headers:p,userId:b}=Cs(await H(r,s,i)),I=Re(s,r,_=>l.waitUntil?.(_)),P=_=>async(v,B={})=>{const L=v.__lunoraRef;if(typeof L!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ve(L);const V=await Ae(r,L,Ee(B),_,{...p,"x-lunora-system":"1"},I),x=await V.json();if(x.error)throw new c(x.error.message??"shard RPC failed",{code:x.error.code??"INTERNAL",status:V.status});return Ye(x.result)},U=P(o);return{auth:{getIdentity:()=>Promise.resolve(d),userId:b},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),forShard:_=>{const v=P(_);return{runAction:v,runMutation:v,runQuery:v}},runAction:U,runMutation:U,runQuery:U,...h===void 0?{}:{scheduler:$n(h)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:to(e.storage(s,new URL(r.url).origin))}}},Fn=async(r,s,l)=>{if(!e.httpRouter)return;const d=await Kn(r,s,l);try{return await e.httpRouter.fetch(r,{...s,__lunoraCtx:d},l)}catch(p){return console.error("[lunora] httpRouter (SSR) handler threw:",p),new Response("Internal Server Error",{status:500})}},Gn=async(r,s,l)=>{if(r.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const d=Tt(r,ie);if(d)return d;const p=l.searchParams.get("shard")??o,{headers:b,identity:I}=await H(r,s,i),P=S(r)||await en(r,R(),w());await re(I,p,P);const U=Xt(r,b),_=qt(s,e.shardDO);if(_!==void 0){U.set("x-lunora-shard-binding",_);const v=await Fs(u,p);if(v>0){const B=yo(p,Math.floor(Math.random()*v));return A(u,B,new Request(r,{headers:U}),Ot(r))}}return A(u,p,new Request(r,{headers:U}))},Qn=async(r,s,l)=>{if(f===void 0)return new Response("Not found",{status:404});if(r.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const d=Tt(r,ie);if(d)return d;let p;try{p=decodeURIComponent(l.pathname.slice(Qt.length))}catch{return new Response("Unknown voice agent",{status:404})}const b=Object.hasOwn(f,p)?f[p]:void 0;if(b===void 0)return new Response("Unknown voice agent",{status:404});const I=l.searchParams.get("threadKey");if(I===null||I.length===0)return new Response("Missing threadKey",{status:400});const{headers:P,identity:U}=await H(r,s,i);if(e.authorizeShard){if(!await Ie(e.authorizeShard({identity:U,shardKey:I})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else G("shard");const _=Xt(r,P);return A(b,I,new Request(r,{headers:_}))},Wn=async(r,s,l)=>{if(e.authorizeFanOut){if(!await Ie(e.authorizeFanOut(l,r.table,s)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new c("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});G("fan-out")},Se=async(r,s)=>{if(!(!r.fanOut&&r.functionPath.startsWith("__lunora_admin__:"))){if(r.fanOut){await Wn(r.fanOut,r.functionPath,s);return}await re(s,r.shardKey??o)}},zn=(r,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){Y();return}if(e.functions[s]?.kind!=="query"||l.includes(Xe)||l.includes(qe))return;const d=Ot(r);return d===void 0?void 0:{name:bo(l,d),region:d}},Vn=async(r,s,l,d,p)=>{const b=zn(r,s,d);if(b!==void 0){const I={...p,"x-lunora-replica-read":"1",...g===void 0?{}:{"x-lunora-shard-binding":g}},P=_o(r.headers.get("x-lunora-min-seq"));P!==void 0&&(I["x-lunora-min-seq"]=String(P));const U=await A(u,b.name,De(s,l,I),b.region);if(U.status!==421)return U}return A(u,d,De(s,l,p))},Ae=async(r,s,l,d,p,b)=>{const I=Date.now(),{observability:P,sampling:U}=e,_=Ve(r),{decision:v,ignoredUpstream:B,trace:L}=jt(r,{...U===void 0?{}:{sampling:U},trustInbound:t(r)});B&&n(r);const V={...p,[Rt]:v.keepErrors?"1":"0"};Mt(L,V);try{const x=await Vn(r,s,l,d,V);ce(P,{..._,...Gt(L),durationMs:Date.now()-I,functionPath:s,ok:x.ok,shardKey:d,...x.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(x.status)}`,status:x.status}}},b,void 0,{isTraced:L.sampled,keepErrors:v.keepErrors});const be=new Response(x.body,{headers:x.headers,status:x.status,statusText:x.statusText});return be.headers.set("x-lunora-shard-key",d),be}catch(x){throw ce(P,{..._,...Gt(L),...ke(s,Date.now()-I,x,{shardKey:d})},b,void 0,{isTraced:L.sampled,keepErrors:v.keepErrors}),x}},Jn=r=>{if(r.fanOut&&r.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});r.fanOut||ve(r.functionPath)},Yn=async(r,s,l)=>{M(r,"POST","RPC");const d=await Ms(r);js(s,d),Jn(d);const p=await kn(r,d);if(p!==void 0)return p;const{headers:b,identity:I}=await N(r,s,i);Wt(r,I),await Se(d,I);const P=Je(d,e);{const U=Date.now(),{observability:_}=e,v=Ve(r),B=Re(s,r,l&&(x=>l.waitUntil?.(x)));if(d.fanOut)try{const x=await a.fanOut(u,{args:d.args??{},fanOut:d.fanOut,functionPath:d.functionPath,headers:b});return ce(_,{durationMs:Date.now()-U,fanOut:{failed:x.failed,shards:x.ok+x.failed,table:d.fanOut.table},functionPath:d.functionPath,...v,ok:!0},B),Response.json(x,{headers:{"content-type":"application/json"},status:200})}catch(x){throw ce(_,{...ke(d.functionPath,Date.now()-U,x,{fanOut:{table:d.fanOut.table}}),...v},B),x}const L=d.shardKey??o,V=()=>Ae(r,d.functionPath,d.args??{},L,b,B);return P&&e.x402Charge?e.x402Charge(r,{functionPath:d.functionPath,price:P.price},V,ze(l)):V()}},qn=async(r,s,l)=>{M(r,"POST","RPC batch");const d=await ee(r),{calls:p}=d;if(!Array.isArray(p))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:b,identity:I}=await N(r,s,i);Wt(r,I);const P=zo(p,o);for(const $ of P.values())for(const F of $)if(e.functions?.[F.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${F.functionPath}" cannot be called in a batch; dispatch it individually over ${Ft}`,{code:"BAD_REQUEST",status:400});await Promise.all([...P.entries()].flatMap(([$,F])=>F.map(Z=>Se({args:Z.args,functionPath:Z.functionPath,shardKey:$},I))));const{observability:U,sampling:_}=e,v=Re(s,r,l&&($=>l.waitUntil?.($))),B=Ve(r),{decision:L,ignoredUpstream:V,trace:x}=jt(r,{..._===void 0?{}:{sampling:_},trustInbound:t(r)});V&&n(r);const be={isTraced:x.sampled,keepErrors:L.keepErrors},dr=$=>{const F={...b,"content-type":"application/json",[Rt]:L.keepErrors?"1":"0"};return Mt({...x,spanId:$},F),F},Be=$=>({parentSpanId:$,spanId:we(8),traceFlags:x.traceFlags,traceId:x.traceId}),Oe=[],xe=[],ht=($,F,Z,ue)=>({body:{error:{code:Z,message:ue}},id:$.id,status:F}),ft=($,F,Z,ue,he)=>{for(const q of $)ce(U,he(q),v,void 0,be),Oe.push(ht(q,F,Z,ue))},ur=($,F,Z,ue,he,q)=>{for(const _e of $){const fe=he.get(_e.id)??q,pe=fe<400;ce(U,{durationMs:ue,functionPath:_e.functionPath,...B,...Be(Z),ok:pe,shardKey:F,...pe?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(fe)}`,status:fe}}},v,void 0,be)}};await Promise.all([...P.entries()].map(async([$,F])=>{const Z=we(8),ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:F}),headers:new Headers(dr(Z)),method:"POST"}),he=Date.now();let q;try{q=await A(u,$,ue)}catch(X){const Le=Date.now()-he,{body:wt}=mr(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});ft(F,502,wt.code,wt.message,fr=>({...ke(fr.functionPath,Le,X,{shardKey:$}),...B,...Be(Z)}));return}const _e=Date.now()-he,fe=q.headers.get("x-d1-bookmark");fe&&xe.push(fe);let pe;try{pe=await q.json()}catch{const X=`shard batch returned a non-JSON response (${String(q.status)})`;ft(F,q.status,"SHARD_ERROR",X,Le=>({durationMs:_e,error:{code:"SHARD_ERROR",message:X,status:q.status},functionPath:Le.functionPath,...B,...Be(Z),ok:!1,shardKey:$}));return}const He=Array.isArray(pe.results)?pe.results:[],lr=new Map(He.map(X=>[X.id,X.status??q.status])),hr=new Set(He.map(X=>X.id));ur(F,$,Z,_e,lr,q.status),Oe.push(...He);for(const X of F)hr.has(X.id)||Oe.push(ht(X,q.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const pt={"content-type":"application/json"},[mt]=xe;return xe.length===1&&mt!==void 0&&(pt["x-d1-bookmark"]=mt),Response.json({results:Oe},{headers:pt,status:200})},Xn=async(r,s,l,d={},p={})=>{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});ve(b);const{headers:I,identity:P}=await N(r,s,i,p.context),U={args:d,functionPath:b,shardKey:p.shardKey};await Se(U,P);const _=p.shardKey??o,v=Re(s,r,p.waitUntil),B=()=>Ae(r,b,d,_,I,v),L=Je(U,e);return L&&e.x402Charge?await e.x402Charge(r,{functionPath:b,price:L.price},B,ze(p.waitUntil?{waitUntil:p.waitUntil}:p.context)):await B()}catch(b){return Et(b)}},dt=async(r,s,l)=>{const{observability:d}=e,p=Date.now(),b=we(16),I=we(8),P=Yt(s),U=nn(b,I,!0);try{const _=await l(U);return ce(d,{durationMs:Date.now()-p,functionPath:r,ok:!0,spanId:I,traceId:b},P),_}catch(_){throw ce(d,{...ke(r,Date.now()-p,_,{}),spanId:I,traceId:b},P),_}finally{_t(d,P)}},ut=async(r,s,l,d)=>{O(s);const p=[],b=v=>v instanceof Error?v:new Error(String(v)),I=e.crons?.[r.cron];if(I)try{await I(r,s,l)}catch(v){p.push(b(v))}const P=await se(r.cron,s,p,b,d),U=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===r.cron;if(U)try{await $o(e,a,u,R(),r)}catch(v){p.push(b(v))}if(!I&&P===0&&!U){const v=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${r.cron}") fired but no cron handler is registered for that expression. Registered: ${v.length===0?"(none)":v.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[_]=p;if(p.length===1&&_)throw _;if(p.length>1)throw new AggregateError(p,`scheduled("${r.cron}") had ${String(p.length)} failure(s)`)},Zn=os({assertAdmin:z,dispatchScheduled:ut,queueHandler:e.queueHandler}),er=async(r,s)=>{try{const l=r??{},d=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!d||d.length===0)return;await A(u,o,De(Ps,{outcome:s},{authorization:`Bearer ${d}`,"content-type":"application/json"}))}catch{}},tr=async(r,s,l,d)=>{if(!e.authHandler)return;const p=e.authBasePath??zt,b=Jt(l.pathname,p)?Nr(r):void 0;let I;try{I=await e.authHandler(b?.request??r)}catch(P){throw b?.overflowed()?new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413}):P}if(b?.overflowed())throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});if(I)return Ns(l.pathname,p)&&d.waitUntil?.(er(s,I.status>=400?"fail":"ok")),I},nr=async({args:r,env:s,functionPath:l,request:d,shardKey:p,waitUntil:b})=>{on(r,"REST");const I={functionPath:l,...p===void 0?{}:{shardKey:p}},{headers:P,identity:U}=await N(d,s,i);await Se(I,U);const _=p??o,v=Re(s,d,b),B=()=>Ae(d,l,r,_,P,v),L=Je(I,e);return L&&e.x402Charge?e.x402Charge(d,{functionPath:l,price:L.price},B,ze({waitUntil:b})):B()},rr=Pr({functions:e.functions??{},invoke:nr,readJsonBody:ee,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Te=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0;Vs(Te);const or={[Os]:r=>r.method!=="GET"&&r.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[_s]:(r,s,l)=>Gn(r,s,l),[Ft]:(r,s,l,d)=>Yn(r,s,d),[bs]:(r,s,l,d)=>qn(r,s,d),[Rs]:(r,s)=>Tn(r,s),[Es]:(r,s)=>An(r,s),[Ss]:async r=>{M(r,"POST","ws-token"),z(r);const s=R();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 To(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...Q,...Pn,...Dn,...Nn,...Un,...Cn,...Bn,...xn,...Hn,...Ln,...Mn,...rr,...ko({assertAdmin:z,getAuthAdmin:()=>e.authAdmin,parsePaging:Ce,queryParameter:Ue,readJsonBody:ee})};let ie=At(e.security),lt=!1;const ar=r=>{lt||(lt=!0,ie=At(e.security,r??{}))},sr=async(r,s)=>{vs(s)&&await j(r)},ir=(r,s)=>{if(!(s.pathname.startsWith(Ne)||e.authHandler!==void 0&&Jt(s.pathname,e.authBasePath??zt))||r.method!=="POST"&&r.method!=="PUT")return;const d=Number(r.headers.get("content-length")??""),p=ys[s.pathname]??rn;if(Number.isFinite(d)&&d>p)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},cr=async(r,s,l)=>{tt.set(r,l);const d=new URL(r.url);ir(r,d);const p=await tr(r,s,d,l);if(p)return p;if(Te){const U=`${r.method} ${d.pathname}`,_=Te[U]??Te[d.pathname];if(_)return _(r,s,l)}const b=Zn[d.pathname];if(b)return b(r,s,l);const I=or[d.pathname];if(I)return await sr(r,d.pathname),I(r,s,d,l);if(e.voiceAgents!==void 0&&d.pathname.startsWith(Qt))return Qn(r,s,d);if(d.pathname.startsWith(Ne))return new Response("Not found",{status:404});const P=await Fn(r,s,l);return P||new Response("Not found",{status:404})};return{async fetch(r,s,l){e.passThroughOnException&&l.passThroughOnException?.(),ar(s),O(s);const d=Zr(r,ie);if(d)return d;const p=eo(r,ie);if(p)return $e(p,r,ie);try{const b=await cr(r,s,l);return $e(b,r,ie)}catch(b){return $e(Et(b),r,ie)}finally{_t(e.observability,Yt(l))}},async queue(r,s,l){await dt(`queue:${Bs(r)}`,l,async d=>{await e.queue?.(r,s,l,{traceparent:d})})},async scheduled(r,s,l){await dt(`cron:${r.cron}`,l,async d=>{await ut(r,s,l,d)})},serverQuery:Xn}},Ys=e=>Sn(e),qs=e=>typeof e=="function"?{fetch:e}:e,Xs=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,Zs=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},Si=(e,t)=>{const n=qs(e),{email:o,queue:a,scheduled:i}=Zs(e),u=f=>{const y={...Ys({...f,httpRouter:n})};return i!==void 0&&!Xs(f)&&(y.scheduled=async(A,T,R)=>{await i(A,T,R)}),a!==void 0&&f.queue===void 0&&(y.queue=async(A,T,R)=>{await a(A,T,R)}),o!==void 0&&(y.email=async(A,T,R)=>{await o(A,T,R)}),y};if(typeof t!="function")return u(t);const h=t;return{fetch:(f,m,y)=>u(h(m)).fetch(f,m,y),queue:(f,m,y)=>u(h(m)).queue?.(f,m,y)??Promise.resolve(),scheduled:(f,m,y)=>u(h(m)).scheduled(f,m,y),serverQuery:(f,m,y,A,T)=>u(h(m)).serverQuery(f,m,y,A,T),...o===void 0?{}:{email:(f,m,y)=>u(h(m)).email?.(f,m,y)??Promise.resolve()}}},ei=(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}},Ai=(e={})=>(t,n,o)=>Sn(ei(e,n)).fetch(t,n,o??wr),Ti=e=>e;export{Ze as COPY_AUTH_TO_JURISDICTION_OP,kt as GET_AUTH_AUDIT_LOG_OP,wr as NOOP_EXECUTION_CONTEXT,fn as PURGE_UNPINNED_AUTH_OP,Ii as composeIdentityResolvers,Ys as composeWorker,Ai as createLunoraHandler,Sn as createWorker,Ti as defineRpcEnvelope,Fs as probeRelayCount,ei as resolveLunoraOptions,ki as routeIdentityResolvers,Si as withFrameworkWorker};
@@ -0,0 +1 @@
1
+ import{toErrorBody as I}from"@lunora/errors";import{b as U,a as F}from"./base64-Bl1_r2k1.mjs";import{LunoraError as v}from"./LunoraError-DksAgIpa.mjs";import{resolveShard as V}from"./applyJurisdiction-C0ddU7Tg.mjs";const ke=r=>({listShardKeys(e){return r[e]??[]}}),be=(r,e)=>({listShardKeys(s){if(r===void 0)throw new v(`cannot discover the shards of "${s}": the worker has no \`resolveTableSharding\` to tell a sharded table from a root one, and no shard registry is configured`,{code:"BAD_REQUEST",status:400});const o=r(s)?.mode.kind;if(o==="shardBy")throw new v(`cannot discover the shards of "${s}": it is \`.shardBy()\` and the worker has no shard registry — declare \`.shardRegistry((env) => env.SHARD_REGISTRY)\` on the app builder and bind \`SHARD_REGISTRY\` to \`ShardRegistryDO\` (or pass \`queryCoordinator\` to \`createWorker\`)`,{code:"BAD_REQUEST",status:400});return o==="global"?[]:[e]}}),P=16,x=5e3,y=r=>r!==null&&typeof r=="object"&&"result"in r?r.result:r,L=r=>{const e=r??{};return{changed:typeof e.changed=="number"?e.changed:0,processed:typeof e.processed=="number"?e.processed:0,status:typeof e.status=="string"?e.status:void 0}},$=(r,e)=>r?"failed":e?"in_progress":"completed",j=r=>{const e=[];let s=0,o=0,t=0,n=0,a=!1,c=!1;for(const d of r){if(d.kind==="err"){o+=1,e.push({error:{message:d.message,timedOut:d.timedOut},shardKey:d.shardKey});continue}s+=1;const i=y(d.value),u=L(i);t+=u.changed,n+=u.processed,a||=u.status==="in_progress",c||=u.status==="failed",e.push({result:i,shardKey:d.shardKey})}return{changed:t,failed:o,ok:s,processed:n,shards:e,status:$(c,a||o>0)}},G=r=>{const e=r??{};return{before:typeof e.before=="number"&&Number.isFinite(e.before)?e.before:0,total:typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0}},H=r=>{const e=[];let s=0,o=0,t=0,n=0;for(const a of r){if(a.kind==="err"){o+=1,e.push({error:{message:a.message,timedOut:a.timedOut},shardKey:a.shardKey});continue}s+=1;const c=G(y(a.value));t+=c.before,n+=c.total,e.push({result:c,shardKey:a.shardKey})}return{failed:o,ok:s,partial:o>0,position:t+1,shards:e,total:n}},B=0,D=1,J=2,k=(r,e)=>r<e?-1:r>e?1:0,E=r=>r==null?B:typeof r=="number"?D:J,O=(r,e)=>{const s=E(r),o=E(e);return s!==o?s<o?-1:1:s===B?0:s===D?k(r,e):k(String(r),String(e))},Q=(r,e,s)=>{const o=O(r.partitionKey,e.partitionKey);if(o!==0)return o;const t=Math.max(r.sortValues.length,e.sortValues.length);for(let n=0;n<t;n+=1){const a=O(r.sortValues[n],e.sortValues[n]);if(a!==0)return s[n]==="desc"?-a:a}return O(r.rowId,e.rowId)},Y=r=>F(new TextEncoder().encode(JSON.stringify(r))),W=r=>{try{const e=JSON.parse(new TextDecoder().decode(U(r)));if(e!==null&&typeof e=="object"&&"perShard"in e){const{perShard:s}=e;if(s!==null&&typeof s=="object")return{perShard:s}}}catch{}return{perShard:{}}},X=r=>{const e=r??{},s=Array.isArray(e.rows)?e.rows:[];return{directions:Array.isArray(e.directions)?e.directions:[],hasMore:e.hasMore===!0,rows:s}},z=(r,e)=>{let s;for(const o of r){const t=o.rows[o.head];t!==void 0&&(s===void 0||Q(t.key,s.row.key,e)<0)&&(s={row:t,slice:o})}return s},Z=(r,e)=>{let s=!1;const o=new Set;for(const n of r)o.add(n.shardKey),(n.head<n.rows.length||n.hasMore)&&(s=!0);const t={...e};for(const n of Object.keys(e))o.has(n)||(s=!0);return s?Y({perShard:t}):null},q=(r,e,s,o)=>{const t=[],n={...o};for(;t.length<e;){const c=z(r,s);if(c===void 0)break;t.push(c.row.doc),n[c.slice.shardKey]=c.row.key,c.slice.head+=1}const a=Z(r,n);return{isDone:a===null,nextCursor:a,page:t}},ee=r=>{const e=[];let s=0,o=0;for(const t of r){if(t.kind==="err"){o+=1,e.push({error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const n=y(t.value),a=Array.isArray(n?.rows)?n.rows:[];e.push({rows:a,shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},re=r=>{const e=[];let s=0,o=0;for(const{outcome:t,sinceEpoch:n,sinceSeq:a}of r){if(t.kind==="err"){o+=1,e.push({cursor:a,error:{code:t.code,message:t.message,timedOut:t.timedOut},shardKey:t.shardKey,...n===void 0?{}:{epoch:n}});continue}s+=1;const c=y(t.value),d=Array.isArray(c?.changes)?c.changes:[],i=typeof c?.cursor=="number"?c.cursor:a,u=typeof c?.epoch=="string"&&c.epoch.length>0?c.epoch:n;e.push({changes:d,cursor:i,shardKey:t.shardKey,...u===void 0?{}:{epoch:u}})}return{failed:o,ok:s,shards:e}},te=r=>{let e=0,s=0,o=0;for(const t of r){if(t.kind==="err"){s+=1;continue}e+=1;const n=y(t.value);o+=typeof n?.applied=="number"?n.applied:0}return{applied:o,failed:s,ok:e}},se=r=>{const e=r??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},oe=r=>{const e=[];let s=0,o=0;for(const t of r){if(t.kind==="err"){o+=1,e.push({requests:0,shardKey:t.shardKey});continue}s+=1,e.push({requests:se(y(t.value)),shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},ne=r=>{const e=[],s={},o=[];let t=0,n=0,a=0;for(const c of r){if(c.kind==="err"){a+=1,e.push({error:{message:c.message,timedOut:c.timedOut},shardKey:c.shardKey});continue}n+=1;const d=y(c.value),i=d?.inserted??{};for(const[l,f]of Object.entries(i))s[l]=(s[l]??0)+f;const u=d?.errors;Array.isArray(u)&&o.push(...u),t+=d?.conflicts??0,e.push({result:{conflicts:d?.conflicts??0,errors:d?.errors??[],inserted:i},shardKey:c.shardKey})}return{conflicts:t,errors:o,failed:a,inserted:s,ok:n,shards:e}},m=r=>({body:JSON.stringify({args:r.args??{},functionPath:r.functionPath}),headers:{"content-type":"application/json",...r.headers}}),ae=async r=>{try{const s=(await r.json())?.error;return typeof s?.code!="string"||s.code.length===0?void 0:{code:s.code,message:typeof s.message=="string"?s.message:""}}catch{return}},g=async(r,e,s,o)=>{const t=V(r,e),n=new AbortController,a=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:n.signal});let c;const d=new Promise(u=>{c=setTimeout(()=>{try{n.abort()}catch{}u({code:"SHARD_TIMEOUT",kind:"err",message:`shard "${e}" timed out after ${String(o)}ms`,shardKey:e,timedOut:!0})},o)}),i=(async()=>{try{const u=await t.fetch(a);if(!u.ok){const f=await ae(u),p=`shard "${e}" returned ${String(u.status)}`;return{code:f?.code??"SHARD_HTTP_ERROR",kind:"err",message:f===void 0||f.message.length===0?p:`${p}: ${f.message}`,shardKey:e,timedOut:!1}}const l=await u.json();return{kind:"ok",shardKey:e,value:l}}catch(u){const{body:l}=I(u,{fallbackCode:"INTERNAL",redactedMessage:"shard call failed"});return{code:l.code,kind:"err",message:`shard "${e}" failed: ${l.message}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([i,d])}finally{c!==void 0&&clearTimeout(c)}},w=async(r,e,s)=>{if(r.length===0)return[];const o=Array.from({length:r.length});let t=0;const n=async()=>{for(;;){const c=t;t+=1;const d=r[c];if(c>=r.length||d===void 0)return;o[c]=await s(d,c)}},a=Math.min(e,r.length);return await Promise.all(Array.from({length:a},()=>n())),o},K=(r,e)=>r.length>0||e===null?r:[e],T=async(r,e,s)=>{const o=await Promise.all(e.map(async t=>K(await r.listShardKeys(t),s)));return[...new Set(o.flat())]},S=async(r,e,s,o,t)=>{const n=m(s);return w(e,o,async a=>g(r,a,n,t))},ce=r=>{const e={};for(const s of Object.keys(r).toSorted(k))e[s]=r[s]??null;return JSON.stringify(e)},ie=r=>r.flatMap(e=>Array.isArray(e)?e:[]),de=(r,e,s)=>{switch(s){case"max":return Math.max(r,e);case"min":return Math.min(r,e);case"sum":return r+e;default:return r}},ue=(r,e,s)=>{if(e===null||typeof e!="object")return;const o=e.key??{},t=e.value??null,n=ce(o),a=r.get(n);if(!a){r.set(n,{key:o,value:t});return}if(a.value===null){a.value=t;return}t!==null&&(a.value=de(a.value,t,s))},le=(r,e)=>{const s=new Map;for(const o of r)if(Array.isArray(o))for(const t of o)ue(s,t,e);return[...s.values()]},M=(r,e)=>{let s=null;for(const o of r)typeof o=="number"&&Number.isFinite(o)&&(s=s===null?o:e(s,o));return s},he=r=>{let e=0;for(const s of r)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},fe=r=>{let e=0,s=0;for(const o of r){if(o===null||typeof o!="object")continue;const t=o;typeof t.before=="number"&&Number.isFinite(t.before)&&(e+=t.before),typeof t.total=="number"&&Number.isFinite(t.total)&&(s+=t.total)}return{position:e+1,total:s}},ye=(r,e)=>{const s=[];for(const t of r)if(Array.isArray(t))for(const n of t){if(n===null||typeof n!="object")continue;const a=n[e.by],c=typeof a=="number"&&Number.isFinite(a)?a:Number.NEGATIVE_INFINITY;s.push({row:n,score:c})}const o=e.direction??"desc";return s.sort((t,n)=>o==="asc"?k(t.score,n.score):k(n.score,t.score)),s.slice(0,e.k).map(t=>t.row)},pe=(r,e)=>{switch(e.kind){case"concat":return ie(r);case"first":return r[0];case"groupBy":return le(r,e.op??"sum");case"max":return M(r,Math.max);case"min":return M(r,Math.min);case"rank":return fe(r);case"sum":return he(r);case"topK":return ye(r,e);default:return r}},N=(r,e)=>(Array.isArray(e)?e:[]).filter(s=>typeof s=="string").map(s=>({shardKey:r,table:s})),Ke=async(r,e,s)=>{const o=new Map,t=await Promise.all(s.tables.map(async i=>({keys:await r.listShardKeys(i),table:i})));for(const{keys:i,table:u}of t)for(const l of i)o.set(l,[...o.get(l)??[],u]);const n=await w([...o],P,async([i,u])=>({outcome:await g(e,i,m({args:{dryRun:s.dryRun===!0,tables:u},functionPath:"__lunora_admin__:releaseShardRegistration",headers:s.headers}),x),tables:u})),a=[],c=[],d=[];for(const{outcome:i,tables:u}of n){if(i.kind==="err"){a.push({message:i.message,shardKey:i.shardKey,tables:u});continue}const l=y(i.value)??{};c.push(...N(i.shardKey,l.kept)),d.push(...N(i.shardKey,l.released))}if(s.dryRun!==!0)for(const i of new Set(d.map(u=>u.table)))r.invalidate?.(i);return{failed:a,kept:c,released:d}},_e=r=>{const e=r.maxConcurrency??P,s=r.perShardTimeoutMs??x;if(e<1)throw new v("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(o,t){const n=await r.registry.listShardKeys(t.fanOut.table),a=await S(o,n,t,e,s),c=[],d=[];for(const i of a)i.kind==="ok"?c.push(i.value):d.push({code:i.code,message:i.message,shardKey:i.shardKey,timedOut:i.timedOut});return{data:pe(c,t.fanOut.merge),errors:d,failed:d.length,ok:c.length}},async orchestrateExport(o,t){const n=await T(r.registry,t.tables,t.defaultShardKey),a=K(n,t.defaultShardKey),c={args:{...t.args,tables:[...t.tables]},functionPath:"__lunora_admin__:exportShard",headers:t.headers},d=await S(o,a,c,e,s);return ee(d)},async orchestrateCdcSync(o,t){const n=K(await T(r.registry,t.tables,t.defaultShardKey),t.defaultShardKey),a=t.cursors??{},c=t.epochs??{},d=await w(n,e,async i=>{const u=a[i]??0,l=c[i];return{outcome:await g(o,i,m({args:{limit:t.limit,sinceEpoch:l,sinceSeq:u},functionPath:"__lunora_admin__:cdcSync",headers:t.headers}),s),sinceEpoch:l,sinceSeq:u}});return re(d)},async orchestrateImport(o,t){const{batches:n}=t,a=await w(n,e,async c=>g(o,c.shardKey,m({args:{rows:[...c.rows],startLine:c.startLine??1},functionPath:"__lunora_admin__:importShard",headers:t.headers}),s));return ne(a)},async orchestrateApplyCdc(o,t){const{batches:n}=t,a=await w(n,e,async c=>g(o,c.shardKey,m({args:{changes:[...c.changes]},functionPath:"__lunora_admin__:applyCdc",headers:t.headers}),s));return te(a)},async orchestrateMigration(o,t){const n=K(await r.registry.listShardKeys(t.table),t.defaultShardKey),a=await S(o,n,t,e,s);return j(a)},async orchestrateRank(o,t){const n=await r.registry.listShardKeys(t.table),a={args:{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:[...t.sortValues],table:t.table},functionPath:"__lunora_admin__:rankBefore",headers:t.headers},c=await S(o,n,a,e,s);return H(c)},async orchestrateRankPage(o,t){const n=await r.registry.listShardKeys(t.table),a=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),c=t.directions??[],d=t.cursor?W(t.cursor):{perShard:{}},i=await w(n,e,async h=>{const C=d.perShard[h],R={index:t.index,table:t.table,take:a};t.partitionKey!==void 0&&(R.partitionKey=t.partitionKey),C!==void 0&&(R.after=C);const b=await g(o,h,m({args:R,functionPath:"__lunora_admin__:rankPage",headers:t.headers}),s);if(b.kind==="err")return{error:{message:b.message,timedOut:b.timedOut},shardKey:h};const A=X(y(b.value));return{directions:A.directions,hasMore:A.hasMore,rows:A.rows,shardKey:h}}),u=[];let l=0,f=0,p;for(const h of i){if(h.error){f+=1;continue}l+=1,p===void 0&&h.directions&&h.directions.length>0&&(p=h.directions),u.push({hasMore:h.hasMore??!1,head:0,rows:h.rows??[],shardKey:h.shardKey})}const _=q(u,a,p??c,d.perShard);return{continueCursor:_.nextCursor,failed:f,isDone:_.isDone,ok:l,page:_.page,partial:f>0,shards:i}},async orchestrateShardTraffic(o,t){const n=await r.registry.listShardKeys(t.table),a={functionPath:"__lunora_admin__:getMetrics",headers:t.headers},c=await S(o,n,a,e,s);return oe(c)},registry:r.registry}};export{be as createDefaultShardRegistry,_e as createQueryCoordinator,ke as createStaticShardRegistry,Ke as pruneShardRegistry};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.163",
3
+ "version": "1.0.0-alpha.165",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,10 +46,10 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/bindings": "1.0.0-alpha.84",
49
+ "@lunora/bindings": "1.0.0-alpha.86",
50
50
  "@lunora/errors": "1.0.0-alpha.47",
51
- "@lunora/observability": "1.0.0-alpha.108",
52
- "@lunora/platform": "1.0.0-alpha.43"
51
+ "@lunora/observability": "1.0.0-alpha.110",
52
+ "@lunora/platform": "1.0.0-alpha.45"
53
53
  },
54
54
  "peerDependencies": {
55
55
  "@lunora/shard-engine": ">=1.0.0-alpha.24 <2.0.0-0",
@@ -1 +0,0 @@
1
- import{LunoraError as a}from"./LunoraError-DksAgIpa.mjs";import{applyJurisdiction as _,resolveShard as l}from"./applyJurisdiction-C0ddU7Tg.mjs";const f="__lunora_shard_registry__",m=3e4,g="https://shard-registry.internal",p=async r=>await r.json(),E=r=>{const w=r.instanceName??f,c=r.cacheTtlMs??m,n=new Map,S=_(r.namespace,r.jurisdiction);let i;const d=()=>(i??=l(S,w),i),h=async(e,t)=>d().fetch(new Request(`${g}${e}`,{body:JSON.stringify(t),headers:{"content-type":"application/json"},method:"POST"})),u=async e=>d().fetch(new Request(`${g}${e}`,{method:"GET"}));return{invalidate(e){e===void 0?n.clear():n.delete(e)},async listShardKeys(e){const t=Date.now(),s=n.get(e);if(s&&s.expiresAt>t)return s.shardKeys;const o=await u(`/list?table=${encodeURIComponent(e)}`);if(!o.ok)throw new a(`shard registry /list returned ${String(o.status)}`);const{shardKeys:y}=await p(o);return c>0&&n.set(e,{expiresAt:t+c,shardKeys:y}),y},async register(e,t){const s=await h("/register",{shardKey:t,table:e});if(!s.ok)throw new a(`shard registry /register returned ${String(s.status)}`);n.delete(e)},async snapshot(){const e=await u("/snapshot");if(!e.ok)throw new a(`shard registry /snapshot returned ${String(e.status)}`);const{tables:t}=await p(e);return t},async unregister(e,t){const s=await h("/unregister",{shardKey:t,table:e});if(!s.ok)throw new a(`shard registry /unregister returned ${String(s.status)}`);n.delete(e)}}};export{m as DEFAULT_REGISTRY_CACHE_TTL_MS,f as SHARD_REGISTRY_DO_NAME,E as createDynamicShardRegistry};
@@ -1,6 +0,0 @@
1
- import{isLunoraError as fr,toErrorBody as pr}from"@lunora/errors";import{e as nn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as mr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as wr,f as gr}from"./base64-Bl1_r2k1.mjs";import{i as yr,e as br,a as _r,E as yt,d as Er}from"./identity-header-pR617HTs.mjs";import{O as bt,a as _t}from"./origin-paywall-B6eOO67m.mjs";import{o as ge,b as rn,p as Rr,m as Ar,d as Sr,a as Tr,r as Or}from"./otlp-resource-BI3MvjSy.mjs";import{r as vr,f as Et,a as ue,S as Rt}from"./observability-DgurIZIR.mjs";import{e as Ee,d as Xe,a as Ir}from"./wire-codec-BLvSm5Mn.mjs";import{d as re,e as ie,M as on,b as kr,f as Pr,g as an,w as Dr,h as sn,t as Nr}from"./rest-routes-D3ShCTHh.mjs";import{LunoraError as c,toErrorResponse as At}from"./LunoraError-DksAgIpa.mjs";import{a as $,m as we}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as ot,BACKUP_KEY_PREFIX as at,isBackupManifestKey as Ur,backupObjectKeyOfManifest as cn,backupObjectKey as Cr,backupManifestKey as Br}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as xr,buildStorageAdminRoutes as Hr,STORAGE_UPLOAD_MAX_BODY_BYTES as Lr,STORAGE_PATH as jr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as Mr,e as $r,f as St,g as Kr,h as Fr}from"./export-tap-CAyZ2TWC.mjs";import{buildHealthRoutes as Gr,durableObjectProbe as Qr,d1Probe as Wr,presenceProbe as $e}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as zr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as _i,routeIdentityResolvers as Ei}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Vr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{resolveShard as ye,applyJurisdiction as Ke}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as Tt,handleCorsPreflight as qr,enforceOrigin as Jr,decorateResponse as Fe,enforceWebSocketOrigin as Ot}from"./decorateResponse-CRrFNW1v.mjs";const Yr=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},dn="__lunoraBranch",Xr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,dn),Zr=`may not contain the reserved workflow branch-marker key ("${dn}")`,eo=async e=>{const t=[];let n;for(;;){const o=await e(n);if(t.push(...Array.isArray(o.records)?o.records:[]),o.truncated!==!0||typeof o.cursor!="string"||o.cursor.length===0)return t;if(o.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=o.cursor}},st=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,u=a<t.length?t.charCodeAt(a):0;o|=i^u}return o===0},to=/already[\s_-]?exists/iu,no=e=>to.test(e instanceof Error?e.message:String(e)),ro=(e,t,n,o)=>{const a=e.get(t);if(a!==void 0)return a;nn(e,o);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},it=new TextEncoder,oo=Array.from({length:32},(e,t)=>t);new RegExp(`[${oo.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const ao=64,so=new Map,un=async e=>ro(so,e,async()=>crypto.subtle.importKey("raw",it.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),ao),ln=async(e,t)=>{const n=await un(e),o=await crypto.subtle.sign("HMAC",n,it.encode(t));return wr(new Uint8Array(o))},io=async(e,t,n)=>{const o=await un(e);return crypto.subtle.verify("HMAC",o,n,it.encode(t))},co=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(co);const uo=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),lo=-100,ho=15,fo=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&uo.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>ho?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<lo?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},vt=e=>{const t=e.cf;return t===void 0?void 0:fo(t)},Ze="::relay::",po=(e,t)=>`${e}${Ze}${String(t)}`,et="::replica::",mo=(e,t)=>`${e}${et}${t}`,wo=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},go=new Set(["1","enabled","on","true","yes"]),yo=new Set(["0","disabled","false","no","off"]),bo=(e,t)=>{const n=(e??"").trim().toLowerCase();return go.has(n)?!0:yo.has(n)?!1:t},hn="v1",_o=6e4,Eo=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??_o),o=`${hn}.${String(n)}`,a=await ln(e,o);return{expiresAtMs:n,token:`${o}.${a}`}},Ro=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[a,i,u]=o;if(a!==hn||u.length===0)return!1;const h=Number(i);if(!Number.isFinite(h)||h<=n)return!1;let p;try{p=gr(u)}catch{return!1}return io(e,`${a}.${i}`,p)},D="/_lunora/admin/auth",Ao={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},U=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},he=(e,t)=>{const n=e(t);if(n===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},fn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},ae=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ge=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},It=e=>{const t=fn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},kt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[o,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[o]=a);return n},So={[`${D}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${D}/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"},[`${D}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${D}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${D}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${D}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${D}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${D}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${D}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${D}/sign-up-invitations/create`]:{build:({body:e})=>({email:U(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:ae(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${D}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:U(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${D}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${D}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${D}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${D}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${D}/users/create`]:{build:({body:e})=>({data:Ge(e,"data"),email:U(e,"email"),name:U(e,"name"),password:ae(e,"password"),role:fn(e.role)}),http:"POST",method:"createUser"},[`${D}/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:U(e,"userId")}},http:"POST",method:"updateUser"},[`${D}/users/role`]:{build:({body:e})=>({role:It(e),userId:U(e,"userId")}),http:"POST",method:"setRole"},[`${D}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:ae(e,"reason"),userId:U(e,"userId")}),http:"POST",method:"banUser"},[`${D}/users/unban`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"unbanUser"},[`${D}/users/password`]:{build:({body:e})=>({newPassword:U(e,"newPassword"),userId:U(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${D}/users/remove`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${D}/users/impersonate`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"impersonateUser"},[`${D}/sessions/revoke`]:{build:({body:e})=>({sessionId:U(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${D}/sessions/revoke-all`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${D}/accounts/unlink`]:{build:({body:e})=>({accountId:U(e,"accountId"),userId:U(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${D}/two-factor/disable`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${D}/passkeys/delete`]:{build:({body:e})=>({passkeyId:U(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${D}/organizations/members/remove`]:{build:({body:e})=>({memberId:U(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${D}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:U(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${D}/organizations/create`]:{build:({body:e})=>({logo:ae(e,"logo"),metadata:Ge(e,"metadata"),name:U(e,"name"),ownerId:ae(e,"ownerId"),slug:ae(e,"slug")}),http:"POST",method:"createOrganization"},[`${D}/organizations/update`]:{build:({body:e})=>({logo:ae(e,"logo"),metadata:Ge(e,"metadata"),name:ae(e,"name"),organizationId:U(e,"organizationId"),slug:ae(e,"slug")}),http:"POST",method:"updateOrganization"},[`${D}/organizations/remove`]:{build:({body:e})=>({organizationId:U(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${D}/organizations/members/add`]:{build:({body:e})=>({organizationId:U(e,"organizationId"),role:ae(e,"role"),userId:U(e,"userId")}),http:"POST",method:"addMember"},[`${D}/organizations/members/invite`]:{build:({body:e})=>({email:U(e,"email"),inviterId:ae(e,"inviterId"),organizationId:U(e,"organizationId"),role:ae(e,"role")}),http:"POST",method:"inviteMember"},[`${D}/organizations/members/role`]:{build:({body:e})=>({memberId:U(e,"memberId"),role:It(e)}),http:"POST",method:"updateMemberRole"},[`${D}/organizations/teams/create`]:{build:({body:e})=>({name:U(e,"name"),organizationId:U(e,"organizationId")}),http:"POST",method:"createTeam"},[`${D}/organizations/teams/update`]:{build:({body:e})=>({name:U(e,"name"),teamId:U(e,"teamId")}),http:"POST",method:"updateTeam"},[`${D}/organizations/teams/remove`]:{build:({body:e})=>({teamId:U(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${D}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:U(e,"teamId"),userId:U(e,"userId")}),http:"POST",method:"addTeamMember"},[`${D}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:U(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${D}/organizations/roles/create`]:{build:({body:e})=>({organizationId:U(e,"organizationId"),permission:kt(e),role:U(e,"role")}),http:"POST",method:"createOrgRole"},[`${D}/organizations/roles/update`]:{build:({body:e})=>({permission:kt(e),roleId:U(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${D}/organizations/roles/remove`]:{build:({body:e})=>({roleId:U(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},To=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:Ao[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),f={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:T=>e.queryParameter(p,T)},g=i.build(f),A=await t(()=>h(g));return Response.json(i.returns==="void"?{ok:!0}:A,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[a,i]of Object.entries(So))o[a]=u=>n(u,i);return o},Pt="__lunora_admin__:getAuthAuditLog",Dt=e=>typeof e=="string"&&e!==""?e:void 0,Nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Oo=e=>async(n,o)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=Dt(o.actorId),u=Dt(o.event),h=Nt(o.sinceSeq),p=Nt(o.limit),f={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...p===void 0?{}:{limit:p}};let g;try{g=await a.read(f)}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:g};return Response.json({result:Ee(A)},{headers:{"content-type":"application/json"},status:200})},tt="__lunora_admin__:copyAuthToJurisdiction",pn="__lunora_admin__:purgeUnpinnedAuth",vo=e=>async(t,n,o)=>{if(n!==tt&&n!==pn)return;e.assertAdmin(t);const a=e.getMove();if(a===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===tt?await a.copy({force:o.force===!0}):await a.purge();return Response.json({result:Ee(i)},{headers:{"content-type":"application/json"},status:200})},Io=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?o.push(a):n.push(a);return{globalTables:o,shardLocalTables:n}},ko=async(e,t,n,o,a,i,u)=>{if(n!==void 0&&o.length===0)return;const h=await e.orchestrateExport(i,{args:{tables:o},defaultShardKey:u,headers:t,tables:o}),p=h.shards.filter(f=>f.error);if(p.length>0){const f=p.map(g=>`${g.shardKey}: ${g.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(p.length)} of ${String(h.shards.length)} shard(s) — ${f}`,{code:"EXPORT_SHARD_FAILED",status:502})}for(const f of h.shards)for(const g of f.rows??[])a(g)},mn=async(e,t,n,o,a,i)=>{const u=o??e.listSchemaTables?.();o===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:h,shardLocalTables:p}=Io(e,u);await ko(t,n,u,p,a,i,e.defaultShardKey??"__root__");const f=e.exportGlobals;if((o===void 0||h.length>0)&&f)for await(const A of f({tables:h}))a(A)},Po=new TextEncoder,Do=1e3,wn=10,No=200,Ut=8,gn="lunoraBackupCron",Ct=24*1048576,Bt=e=>{const t=e.slice(0,wn).map(o=>cn(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Uo=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const a of e)n.set(a,o),o+=a.byteLength;return n},ct=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let u=0;u<Do;u+=1){const h=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const p of h.objects)Ur(p.key)&&p.customMetadata?.[gn]===o&&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)}},Co=async(e,t,n,o,a)=>{const{stale:i}=await ct(e,t,n,o),u=new Set(a),h=i.filter(m=>u.has(m)),p=h.slice(0,No),f=i.length-p.length,g=a.length-h.length;if(p.length===0)return{deleted:[],failed:[],ignored:g,remaining:f};const A=[],T=[];for(let m=0;m<p.length;m+=Ut){const b=await Promise.allSettled(p.slice(m,m+Ut).map(async R=>(await e.delete(cn(R)),await e.delete(R),R)));for(const[R,y]of b.entries())y.status==="fulfilled"?A.push(y.value):T.push(p[m+R])}return A.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(A.length)}: ${Bt(A)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${Bt(T)}`),{deleted:A,failed:T,ignored:g,remaining:f}},Bo=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=ot(e.backupPrefix??at),o=e.backupCron,{eligible:a,stale:i}=o===void 0?{eligible:0,stale:[]}:await ct(t,n,e.backupRetain,o);return{cron:o,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},xo=async(e,t,n,o)=>{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,f=0,g=[];await mn(e,i,u,h,P=>{const L=Po.encode(`${JSON.stringify(P)}
2
- `);if(p+=1,f+=L.byteLength,f>Ct)throw new c(`scheduled backup reached ${String(f)} bytes of NDJSON, past the ${String(Ct)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});g.push(L)},t);const T=ot(e.backupPrefix??at),m=new Date(o.scheduledTime).toISOString(),b=Cr(T,m),R=Uo(g,f);g=[];const y=xr(await crypto.subtle.digest("SHA-256",R));await a.put(b,R,{httpMetadata:{contentType:"application/x-ndjson"},sha256:y});const v={bytes:f,createdAt:m,cron:o.cron,file:b,id:m,rows:p,scheduledTime:o.scheduledTime,sha256:y,...h?{tables:h.join(",")}:{}};await a.put(Br(b),`${JSON.stringify(v,void 0,2)}
3
- `,{customMetadata:{[gn]:o.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:P}=await ct(a,T,e.backupRetain,o.cron);if(P.length>0){const L=P.slice(0,wn),I=P.length-L.length;console.info(`[lunora] backup retention: ${String(P.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${L.join(", ")}${I>0?` (+${String(I)} more)`:""}`)}}catch(P){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,P)}},Ho=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const o=e.backupCron,a=e.backupRetain;if(o===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return Co(n,ot(e.backupPrefix??at),a,o,t)},Lo="/_lunora/admin/backup/retention",jo="/_lunora/admin/backup/prune",Mo=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,a=(h,p)=>{o(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${p} requires a \`backupStore\` on the worker`})},i=async h=>($(h,"GET","Backup-retention"),a(h,"retention preview"),Response.json(await Bo(t),{headers:{"cache-control":"no-store"}})),u=async h=>{$(h,"POST","Backup-prune"),a(h,"prune");const{confirm:p}=await n(h);if(!Array.isArray(p)||p.some(f=>typeof f!="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 Ho(t,p),{headers:{"cache-control":"no-store"}})};return{[jo]:u,[Lo]:i}},xt=500,$o=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const o=e;if(typeof o.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(o.functionPath.startsWith("__lunora_relation__:")||o.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(o.args!==void 0&&(typeof o.args!="object"||o.args===null||Array.isArray(o.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(o.id!==void 0&&typeof o.id!="number")throw new c("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:o.args===void 0?{}:o.args,baselineSeq:typeof o.baselineSeq=="number"?o.baselineSeq:void 0,clientId:typeof o.clientId=="string"?o.clientId:void 0,clientSeq:typeof o.clientSeq=="number"?o.clientSeq:void 0,functionPath:o.functionPath,id:typeof o.id=="number"?o.id:t,mutationId:typeof o.mutationId=="string"?o.mutationId:void 0},shardKey:typeof o.shardKey=="string"?o.shardKey:n}},Ko=(e,t)=>{if(e.length>xt)throw new c(`RPC batch exceeds the ${String(xt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,o=new Set;for(const[a,i]of e.entries()){const{entry:u,shardKey:h}=$o(i,a,t);if(o.has(u.id))throw new c(`batch call id ${String(u.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});o.add(u.id);const p=n.get(h)??[];p.push(u),n.set(h,p)}return n},Fo="/_lunora/admin/export",Go="/_lunora/admin/import",Qo="/_lunora/admin/sync",Wo="/_lunora/admin/connector/sync",zo="/_lunora/admin/apply",Vo="/_lunora/admin/export-tap/run",qo=new TextEncoder,Jo=async e=>{const n=await ie(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const o=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});o.push(a)}return{tables:o}},Qe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,Yo=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:a,knownTables:i,queryCoordinator:u,assertAdmin:h,requireAdminOption:p,resolveForwardContext:f,shardDO:g,streamExportRows:A,streamingImport:T,syncGlobals:m}=e,b=async(I,j)=>{const M=we(I,["POST"]);if(M)return M;const X=p(I,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),C=await Jo(I),{headers:q}=await f(I,j),W=new ReadableStream({async pull(z){const oe=V=>{z.enqueue(qo.encode(`${JSON.stringify(V)}
4
- `))};try{await A(X,q,C.tables,oe),z.close()}catch(V){z.error(V)}}});return new Response(W,{headers:{"content-type":"application/x-ndjson"},status:200})},R=async(I,j)=>{const M=we(I,["POST"]);if(M)return M;const X=p(I,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),C=await re(I),q=typeof C.cursors=="object"&&C.cursors!==null?C.cursors:{},W=typeof C.epochs=="object"&&C.epochs!==null?C.epochs:{},z=typeof C.limit=="number"?C.limit:void 0,oe=typeof C.globalCursor=="number"?C.globalCursor:0,V=Qe(C.tables),{headers:se}=await f(I,j),Q=V??i(),G=await X.orchestrateCdcSync(g,{cursors:q,defaultShardKey:n,epochs:W,headers:se,limit:z,tables:Q}),J=m?await m({limit:z,sinceSeq:oe}):void 0;return Response.json({global:J,shards:G.shards},{status:200})},y=async(I,j)=>{const M=we(I,["POST"]);if(M)return M;const X=p(I,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),C=await re(I),q=$r(C.cursor),W=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,z=Qe(C.tables),{headers:oe}=await f(I,j),V=z??i(),se=await X.orchestrateCdcSync(g,{cursors:q.s,defaultShardKey:n,headers:oe,limit:W,tables:V}),Q=[],G={...q.s};let J=!1;for(const ce of se.shards)J=St(Q,ce.changes??[],Fr(W))||J,G[ce.shardKey]=ce.cursor;let Re=q.g;if(m){const ce=await m({limit:W,sinceSeq:q.g});J=St(Q,ce.changes,W)||J,Re=ce.cursor}const Ce=Kr({g:Re,s:G,v:1}),Ae={changes:Q,hasMore:J,nextCursor:Ce};return Response.json(Ae,{status:200})},v=async(I,j)=>{const M=we(I,["POST"]);if(M)return M;const X=p(I,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),C=await re(I),W=(Array.isArray(C.batches)?C.batches:[]).map(Q=>Q).filter(Q=>Q!==null&&typeof Q=="object"&&typeof Q.shardKey=="string"&&Array.isArray(Q.changes)),z=Array.isArray(C.globalChanges)?C.globalChanges:[],{headers:oe}=await f(I,j),V=await X.orchestrateApplyCdc(g,{batches:W,headers:oe}),se=z.length>0&&t?await t({changes:z}):0;return Response.json({applied:V.applied+se,failed:V.failed,ok:V.ok},{status:200})},P=async(I,j)=>{const M=we(I,["POST"]);if(M)return M;h(I);const{headers:X}=await f(I,j),C=await T(I,X);return Response.json(C,{headers:{"content-type":"application/json"},status:C.failed.length>0?207:200})},L=async(I,j)=>{const M=we(I,["POST"]);if(M)return M;const X=p(I,u,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(a===void 0||Object.keys(a).length===0||o===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const C=await re(I),q=typeof C.sink=="string"?C.sink:void 0,W=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,z=Qe(C.tables);if(q===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const oe=a[q];if(oe===void 0)throw new c(`Export-tap sink "${q}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:V}=await f(I,j),se=z??i(),Q=await Mr({coordinator:X,cursorStore:o,defaultShardKey:n,headers:V,limit:W,shardDO:g,sink:oe,tables:se});return Response.json(Q,{headers:{"content-type":"application/json"},status:200})};return{[zo]:v,[Wo]:y,[Fo]:b,[Vo]:L,[Go]:P,[Qo]:R}},Xo=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const o=n;return typeof o.table!="string"||o.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!o.doc||typeof o.doc!="object"||Array.isArray(o.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:o.table},ok:!1}:{doc:o.doc,ok:!0,table:o.table}},Zo=(e,t,n,o,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:o}},ea=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const o=[],a=[],i=new Map;let u=0,h=0;const p=e.body.getReader(),f=new TextDecoder;let g="",A=0;const T=m=>{h+=1;const b=m.trim();if(b.length===0)return;u+=1;const R=Xo(b,h);if(!R.ok){o.push(R.error);return}const{doc:y,table:v}=R,P=t.resolveTableSharding?.(v);if(P?.mode.kind==="global"){a.push({doc:y,line:h,table:v});return}const L=Zo(y,v,P,n,h);if(!L.ok){o.push(L.error);return}const I=i.get(L.shardKey);I?I.rows.push({doc:y,table:v}):i.set(L.shardKey,{rows:[{doc:y,table:v}],shardKey:L.shardKey,startLine:h})};for(;;){const{done:m,value:b}=await p.read();if(m)break;if(b&&(A+=b.byteLength,A>on))throw await p.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});g+=f.decode(b,{stream:!0});let R=g.indexOf(`
5
- `);for(;R!==-1;){const y=g.slice(0,R);g=g.slice(R+1),T(y),R=g.indexOf(`
6
- `)}}return g.length>0&&T(g),{errors:o,globalRows:a,perShard:i,received:u}},ta=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),Ht=(e,t)=>{for(const[n,o]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+o;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},na=async(e,t,n,o)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:h,received:p}=await ea(e,t,a),f={conflicts:0,errors:i,failed:[],inserted:{}},g=[];if(t.resolveTableSharding===void 0&&h.size>0&&g.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(o,{batches:[...h.values()],headers:n});Ht(f,T),f.failed.push(...ta(T.shards))}if(u.length>0)if(t.importGlobals){const A=u[0]?.line??1,T=await t.importGlobals({rows:u,startLine:A});Ht(f,T)}else for(const A of u)f.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:f.conflicts,errors:f.errors,failed:f.failed,inserted:f.inserted,received:p,...g.length>0?{warnings:g}:{}}},We=e=>typeof e=="object"&&e!==null?e:{},ze=e=>typeof e.kind=="string"?e.kind:"unknown",ra=(e,t)=>{let n=We(t),o=!1;ze(n)==="optional"&&(o=!0,n=We(n._meta?.inner));const a=ze(n),i=n._meta??{},u={kind:a,name:e,optional:o};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const h=ze(We(i.inner));h!=="unknown"&&(u.element=h)}return u},oa=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>ra(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),aa="/_lunora/admin/functions",sa="/_lunora/admin/cron-jobs",ia="/_lunora/admin/openapi",ca="/_lunora/admin/openrpc",da="/_lunora/admin/global/tables",ua="/_lunora/admin/global/table",la="/_lunora/admin/global/facet",Lt=e=>{if(e===void 0||e==="")return;let t;try{t=Xe(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(o=>{if(typeof o!="object"||o===null||typeof o.column!="string")return[];const{column:a,value:i}=o;return[{column:a,value:i}]});return n.length===0?void 0:n},ha=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:{}}),fa=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"}),pa=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:a,requireAdminOption:i}=e,u=m=>{$(m,"GET","Functions");const b=i(m,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),R=Object.entries(b).flatMap(([y,v])=>v.visibility==="internal"||v.kind==="stream"?[]:[{args:oa(v.args),kind:v.kind,path:y}]).toSorted((y,v)=>y.path.localeCompare(v.path));return Response.json({functions:R},{headers:{"content-type":"application/json"},status:200})},h=m=>{$(m,"GET","Cron-jobs");const b=i(m,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),R=Object.entries(b).flatMap(([y,v])=>v.map(P=>({args:P.args,cron:y,functionPath:P.functionPath,name:P.name,shardKey:P.shardKey,workflow:P.workflow}))).toSorted((y,v)=>y.name.localeCompare(v.name));return Response.json({jobs:R},{headers:{"content-type":"application/json"},status:200})},p=m=>($(m,"GET","OpenAPI"),t(m),Response.json(n.openApiSpec??ha,{headers:{"content-type":"application/json"},status:200})),f=m=>($(m,"GET","OpenRPC"),t(m),Response.json(n.openRpcSpec??fa,{headers:{"content-type":"application/json"},status:200})),g=async m=>{$(m,"GET","Global-tables");const b=i(m,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await b.listTables(),{headers:{"content-type":"application/json"},status:200})},A=async m=>{$(m,"GET","Global-table");const b=i(m,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(m.url),y=a(R,"table");if(y===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const v=await b.readTablePage({...o(m),filters:Lt(a(R,"filters")),table:y});return Response.json(v,{headers:{"content-type":"application/json"},status:200})},T=async m=>{$(m,"GET","Global-facet");const b=i(m,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(m.url),y=a(R,"table"),v=a(R,"column");if(y===void 0||v===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const P=a(R,"limit"),L=P===void 0?void 0:Number(P),I=await b.facetColumn({column:v,filters:Lt(a(R,"filters")),limit:L!==void 0&&Number.isFinite(L)?L:void 0,table:y});return Response.json(I,{headers:{"content-type":"application/json"},status:200})};return{[sa]:h,[aa]:u,[la]:T,[ua]:A,[da]:g,[ia]:p,[ca]:f}},ma="/_lunora/admin/kv/namespaces",wa="/_lunora/admin/kv/keys",yn="/_lunora/admin/kv/value",bn=32*1048576,jt=60,ga=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=b=>n(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),i=(b,R)=>{const y=new URL(b.url),v=y.searchParams.get("namespace")??"",P=y.searchParams.get("key")??"";if(v==="")throw new c(`KV-value ${R} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(P==="")throw new c(`KV-value ${R} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:P,namespace:v}},u=async(b,R)=>{if(!(await b.listNamespaces()).some(v=>v.binding===R))throw new c(`Unknown KV namespace binding \`${R}\``,{code:"NOT_FOUND",status:404})},h=async b=>($(b,"GET","KV-namespaces"),a({namespaces:await o(b).listNamespaces()})),p=async b=>{$(b,"GET","KV-keys");const R=o(b),y=new URL(b.url),v=y.searchParams.get("namespace")??"";if(v==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const P=y.searchParams.get("prefix")??void 0,L=y.searchParams.get("cursor")??void 0,I=y.searchParams.get("limit"),j=I===null?void 0:Number.parseInt(I,10);if(j!==void 0&&(!Number.isInteger(j)||j<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const M=j===void 0?void 0:Math.min(j,1e3);return await u(R,v),a(await R.listKeys({cursor:L,limit:M,namespace:v,prefix:P}))},T={DELETE:async b=>{const R=o(b),y=i(b,"DELETE");return await u(R,y.namespace),await R.deleteKey(y),a({deleted:!0})},GET:async b=>{const R=o(b),y=i(b,"GET");return await u(R,y.namespace),a(await R.getValue(y))},PUT:async b=>{const R=o(b),y=await t(b,bn);if(typeof y.namespace!="string"||y.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof y.key!="string"||y.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof y.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(y.expirationTtl!==void 0&&(typeof y.expirationTtl!="number"||!Number.isInteger(y.expirationTtl)||y.expirationTtl<jt))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const v=Math.floor(Date.now()/1e3)+jt;if(y.expiration!==void 0&&(typeof y.expiration!="number"||!Number.isInteger(y.expiration)||y.expiration<v))throw new c("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(R,y.namespace),await R.putValue({expiration:y.expiration,expirationTtl:y.expirationTtl,key:y.key,metadata:y.metadata,namespace:y.namespace,value:y.value}),a({ok:!0})}},m=b=>{const R=T[b.method];if(!R)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return R(b)};return{[ma]:h,[wa]:p,[yn]:m}},ya="/_lunora/migrate",ba="/_lunora/admin/pitr",_a="/_lunora/admin/rank",Ea="/_lunora/admin/rankpage",Ra="/_lunora/admin/shard-traffic",Aa=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Sa=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Ta=async e=>{const n=await ie(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"||!Aa.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}},Oa=async e=>{const n=await ie(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}},va=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}},Ia=e=>{if(typeof e.table!="string"||e.table.length===0)throw new c("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new c("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new c("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new c("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new c("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},ka=async e=>{const n=await ie(e,"Rank page")??{};Ia(n);const o=va(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:o,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},Pa=async e=>{const n=await ie(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}},Da=async e=>{const n=await re(e);if(typeof n.functionPath!="string"||!Sa.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}},Na=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:a,resolveForwardContext:i,shardDO:u}=e,h=(m,b)=>{if(m.method!=="POST")throw new c(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(m))throw new c("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new c(`${b} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},p=async(m,b)=>{const R=h(m,"Migration"),y=await Ta(m),{headers:v}=await i(m,b),P=await R.orchestrateMigration(u,{args:y.args,defaultShardKey:t,functionPath:y.functionPath,headers:v,table:y.table});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},f=async(m,b)=>{const R=h(m,"Rank"),y=await Oa(m),{headers:v}=await i(m,b),P=await R.orchestrateRank(u,{headers:v,index:y.index,partitionKey:y.partitionKey,rowId:y.rowId,sortValues:y.sortValues,table:y.table});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},g=async(m,b)=>{const R=h(m,"Rank page"),y=await ka(m),{headers:v}=await i(m,b),P=await R.orchestrateRankPage(u,{...y,headers:v});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},A=async(m,b)=>{const R=h(m,"Shard-traffic"),y=await Pa(m),{headers:v}=await i(m,b),P=await R.orchestrateShardTraffic(u,{headers:v,table:y.table});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},T=async(m,b)=>{if($(m,"POST","PITR"),!o(m))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const R=await Da(m),{headers:y}=await i(m,b),v=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:R.args,functionPath:R.functionPath}),headers:y,method:"POST"});return n(u,R.shardKey??t,v)};return{[ya]:p,[ba]:T,[_a]:f,[Ea]:g,[Ra]:A}},Ua=1,Ca=0,Ba=32,xa=512,Ha=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,La=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>xa)return;const n=t.split(",");if(!(n.length>Ba)){for(const o of n)if(!Ha.test(o.trim()))return;return t}},ja=e=>{const t=Rr(e.headers.get("traceparent"));if(t===void 0)return;const n=La(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},Mt=(e,t={})=>{const n=ja(e),o=t.trustInbound===!0?n:void 0,a=ge(8),i=o?.traceId??ge(16),u=vr(t.sampling,o===void 0?a:i),h=u.isTraced&&(o===void 0||o.sampled);return{decision:u,ignoredUpstream:n!==void 0&&o===void 0,trace:{sampled:h,spanId:a,traceFlags:h?Ua:Ca,traceId:i,...o?.parentSpanId===void 0?{}:{parentSpanId:o.parentSpanId},...o?.traceState===void 0?{}:{traceState:o.traceState}}}},$t=(e,t)=>{t.traceparent=rn(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Ma=(e,t)=>{let n;return()=>{if(n===void 0){const o=Or(e),a=t===void 0?void 0:t.cf;n=Ar(Tr(o),Sr(o,a))}return n}},$a="/_lunora/admin/scheduled",Ka="/_lunora/admin/scheduled/status",Fa="/_lunora/admin/scheduled/ws",Ga="/_lunora/admin/scheduled/cancel",Qa="/_lunora/admin/scheduled/dead",Wa="/_lunora/admin/scheduled/dead/retry",za="/_lunora/admin/scheduled/dead/cancel",Va="/_lunora/admin/scheduled/pool/release",qa=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:a}=e,i=(f,g)=>A=>{if(A.method!=="GET")throw new c(`${g} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(A.url).searchParams.get("cursor"),m=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return o(A).fetch(new Request(`https://scheduler.internal${f}${m}`,{method:"GET"}))},u=(f,g,A=g)=>async T=>{if(T.method!=="POST")throw new c(`${A} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const m=o(T),b=await ie(T,g);if(typeof b?.id!="string"||b.id==="")throw new c(`${g} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return m.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:b.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async f=>{if(f.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const g=o(f),A=await ie(f,"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 g.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 f=>{if(f.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(f))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const g=n();return ye(g,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[Ga]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[za]:u("/dead/cancel","Scheduled dead-letter action"),[Qa]:i("/dead","Scheduled dead-letter"),[Wa]:u("/dead/retry","Scheduled dead-letter action"),[$a]:i("/list","Scheduled-list"),[Va]:h,[Ka]:i("/status","Scheduler-status"),[Fa]:p}},Ja="/_lunora/scheduled",_n="/_lunora/queue",En=16*1048576,Ya=e=>{const{assertAdmin:t,dispatchScheduled:n,queueHandler:o}=e,a=async(u,h,p)=>{if(t(u),u.method!=="POST")throw new c("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const f=await ie(u,"Scheduled tick"),g=typeof f?.cron=="string"?f.cron:"";if(g==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:g,noRetry:()=>{},scheduledTime:Date.now()},h,p),Response.json({cron:g,ok:!0})},i=async(u,h,p)=>{if(t(u),u.method!=="POST")throw new c("queue dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!o)throw new c("no queueHandler configured",{code:"BAD_REQUEST",status:400});const f=await ie(u,"Queue dispatch",En);if(!Array.isArray(f?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const g=typeof f.queue=="string"?f.queue:"",A=f.messages.filter(m=>typeof m=="object"&&m!==null&&typeof m.id=="string").map(m=>({body:m.body,id:m.id})),T=await o({messages:A,queue:g},h,p);return Response.json({retry:T?.retry??[]})};return{[_n]:i,[Ja]:a}},Xa=(e,...t)=>{let n=e.cf;for(const o of t){if(typeof n!="object"||n===null)return;n=n[o]}return typeof n=="string"?n:void 0},nt={mtls:e=>Xa(e,"tlsClientAuth","certVerified")==="SUCCESS"},Za=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(nt,e)?nt[e]:void 0)??(()=>!1),es=e=>typeof e=="string"&&Object.hasOwn(nt,e),ts=e=>{const t=es(e)?e:void 0;if(e!==void 0&&t===void 0)return()=>{};let n=!1;return o=>{n||t!==void 0&&o.cf!==void 0||(n=!0,console.warn(t===void 0?'[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.':`[lunora] \`trustInboundTraceContext: "${t}"\` cannot be satisfied on this host: the request carries no platform-injected \`cf\` metadata, which is what that signal reads, so every inbound \`traceparent\` is ignored and this request starts a new trace. Off Cloudflare, trust the upstream some other way — \`trustInboundTraceContext: true\` when nothing untrusted can reach this worker, or a predicate that verifies whatever your own front door sets. Set it to \`false\` to keep this behaviour and silence this message.`))}},ns="/_lunora/admin/vector/indexes",rs="/_lunora/admin/vector/query",os=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=async i=>{$(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=>{$(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 f=await u.queryIndex({name:p.name,text:p.text,topK:p.topK});return Response.json(f,{headers:{"content-type":"application/json"},status:200})};return{[ns]:o,[rs]:a}},as="/_lunora/admin/workflows/instances",ss="/_lunora/admin/workflows/instance",is="/_lunora/admin/workflows/status",cs={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},ds=e=>e!==null&&Object.hasOwn(cs,e)?e:void 0,Kt=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const o=Number(n);return Number.isInteger(o)&&o>0?o:void 0},Ve=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new c(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},Ft=()=>{throw new c("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},us=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,o=async(u,h,p)=>{$(u,"GET","Workflows instances"),t(u);const f=n(h);if(!f)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const g=Ve(p,"name"),A=ds(p.searchParams.get("status"));return Response.json(await f.listInstances({page:Kt(p,"page"),perPage:Kt(p,"perPage"),status:A,workflowName:g}))},a=async(u,h,p)=>{$(u,"GET","Workflows instance"),t(u);const f=n(h);return f?Response.json(await f.getInstance({instanceId:Ve(p,"id"),workflowName:Ve(p,"name")})):Ft()},i=async(u,h)=>{$(u,"POST","Workflows status"),t(u);const p=n(h);if(!p)return Ft();const f=await ie(u,"Workflows status");if(typeof f?.name!="string"||f.name===""||typeof f.id!="string"||f.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:g}=f;if(g!=="pause"&&g!=="resume"&&g!=="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:g,instanceId:f.id,workflowName:f.name}))};return{[ss]:a,[as]:o,[is]:i}},ls={[yn]:bn,[_n]:En,[jr]:Lr},Gt="/_lunora/rpc",hs="/_lunora/rpc-batch",fs="/_lunora/ws",_e=(e,t,n)=>({resourceAttributes:Ma(e,t),...n===void 0?{}:{waitUntil:n}}),qe=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Qt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Je=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let o;try{o=new URL(e.url)}catch{return{method:t,userAgent:n}}const a=o.port===""?void 0:Number(o.port);return{host:o.hostname,method:t,path:o.pathname,port:Number.isNaN(a)?void 0:a,scheme:o.protocol.replace(":",""),userAgent:n}},Wt="/_lunora/voice/",ps="/_lunora/scheduler/dispatch",ms="/_lunora/admin/cron-jobs/run",ws="/_lunora/admin/ws-token",gs="/_lunora/admin/",Ue="/_lunora/",ys="/_lunora/migrate",bs="/_lunora/status",_s=e=>e.startsWith(gs)||e===ys,Es="__lunora_relation__:",Ie=e=>{if(e.startsWith(Es))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},ke=async e=>await e===!0,zt=(e,t)=>{const n=e.headers.get(yt);if(n===null)return;const o=Er(n);if(o===void 0)throw new c(`malformed ${yt} header`,{code:"BAD_REQUEST",status:400});if(o.subject!==(t?.userId??null))throw new c("the session changed since this write was queued",{code:"IDENTITY_MISMATCH",status:409})},Rs=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}}},Vt="/api/auth",As="__lunora_admin__:recordAuthEvent",qt="__lunora_admin__:listPushSubscriptions",Ss=["/sign-in","/sign-up","/callback"],Ts=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return Ss.some(a=>o===a||o.startsWith(`${a}/`))},Jt=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},Pe=(e,t,n,o)=>{const a=fr(n),i=a?n.code:"INTERNAL_SERVER_ERROR",u=a?n.status:500,h=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:h,status:u},functionPath:e,ok:!1,...o.fanOut?{fanOut:{failed:0,shards:0,table:o.fanOut.table}}:{},...o.shardKey?{shardKey:o.shardKey}:{}}},Rn=e=>{const{exp:t,expiresAtMs:n}=e;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},An=({identity:e})=>e!==null&&yr(Rn(e)),Os=e=>{if(An(e))throw new c("authentication token expired",{code:"TOKEN_EXPIRED",status:401});return e},vs=e=>{if(!An(e))return e;const t={...e.headers};return delete t["x-lunora-identity"],delete t["x-lunora-identity-exp"],delete t["x-lunora-userid"],{claims:null,headers:t,identity:null,userId:null}},Yt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Is=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},rt=new WeakMap,ks=async(e,t,n,o,a=rt.get(e))=>{const i={"content-type":"application/json"},u=e.headers.get("authorization"),h=e.headers.get("cookie"),p=e.headers.get("x-d1-bookmark"),f=e.headers.get("x-lunora-mutation-id"),g=e.headers.get("x-lunora-client-id"),A=e.headers.get("x-lunora-client-seq"),T=e.headers.get("x-lunora-base-seq");u&&(i.authorization=u),h&&(i.cookie=h),p&&(i["x-d1-bookmark"]=p),f&&(i["x-lunora-mutation-id"]=f),g&&(i["x-lunora-client-id"]=g),A&&(i["x-lunora-client-seq"]=A),T&&(i["x-lunora-base-seq"]=T);const m=Nr(e.headers,o);if(m&&(i["x-lunora-client-ip"]=m),i["x-lunora-origin"]=new URL(e.url).origin,!n)return{claims:null,headers:i,identity:null,userId:null};const b=await n(e,t,a);if(!b||typeof b.userId!="string"||b.userId.length===0)return{claims:null,headers:i,identity:null,userId:null};i["x-lunora-userid"]=br(b.userId);const R=Rn(b);R!==void 0&&(i["x-lunora-identity-exp"]=String(R));const{userId:y,...v}=b,P=Object.keys(v).length>0?v:null;return P&&(i["x-lunora-identity"]=_r(P)),{claims:P,headers:i,identity:b,userId:y}},Ps=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Ds=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"||!Ps.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},Ns=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},Ye=(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}},Us=async e=>{const t=await sn(e);let n;try{n=JSON.parse(t)}catch{throw new c("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new c("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const o=n;if(o.args!==void 0&&an(o.args,"RPC"),o.shardKey!==void 0&&typeof o.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,i=Ds(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}},De=new Map,Cs=5e3,Bs=4096,xs=async(e,t)=>{const n=Date.now(),o=De.get(t);if(o!==void 0&&o.expiresMs>n)return o.relayCount;o!==void 0&&De.delete(t);let a=0;try{const i=await ye(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 nn(De,Bs),De.set(t,{expiresMs:n+Cs,relayCount:a}),a},Xt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},Ne=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),Hs=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],Ls=(e,t)=>{for(const n of Hs){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},Zt=(e,t)=>{const n=new Headers(e.headers),o=[...n.keys()];for(const a of o)a.startsWith("x-lunora-")&&n.delete(a);return Ls(n,t),n},js=async(e,t,n)=>e.length===0||n.length===0?!1:st(await ln(e,t),n),en=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[o,...a]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:st(t,a.join(" ").trim())},tn=async(e,t,n)=>{if(!t||t.length===0)return!1;const o=new URL(e.url).searchParams.get("token");return o===null?!1:await Ro(t,o)?!0:n?!1:st(t,o)},Ms=(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 Wr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return $e(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return $e(`queue:${e}`,!0);if(typeof n.connectionString=="string")return $e(`hyperdrive:${e}`,!0)},$s=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(Ue))throw new c(`route "${t}" is under the reserved ${Ue} prefix, which the framework owns. App routes registered there shadow the internal endpoint AND its admin gate — pick a path outside the prefix.`,{code:"MISCONFIGURED",status:500})},Ks=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})},Sn=e=>{Ks(e);const t=Za(e.trustInboundTraceContext),n=ts(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",a=zr(e.resolveIdentity,e.identity),i=Ke(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:Ke(e.schedulerDO,e.jurisdiction),h=e.voiceAgents===void 0?void 0:Object.fromEntries(Object.entries(e.voiceAgents).map(([r,s])=>[r,Ke(s,e.jurisdiction)]));let p=!1;const f=r=>{if(r===void 0||e.jurisdiction===void 0)return r;p||(p=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},g=async(r,s,l,d=e.shardRegion?.(s))=>ye(r,s,f(d)).fetch(l);let A;const T=()=>e.adminToken??A;let m;const b=()=>e.requireEphemeralWsToken??m??!0;let R;const y=r=>{const s=r??{};if(R??=Xt(r,e.shardDO),m===void 0&&e.requireEphemeralWsToken===void 0){const d=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof d=="string"&&d.length>0&&(m=bo(d,!0))}if(A!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(A=l)},v=new WeakSet,P=r=>en(r,T())||v.has(r),L=async r=>{if(!(e.adminGate===void 0||v.has(r)))try{await ke(e.adminGate(r,rt.get(r)))&&v.add(r)}catch{}},I=async(r,s,l,d)=>{const w=await ks(r,s,l,e.trustedClientIpHeader,d);return e.functions!==void 0&&(w.headers[_t]=bt),w},j=async(r,s,l,d)=>Os(await I(r,s,l,d)),M=async(r,s)=>{const l=await I(r,s,e.resolveIdentity);if(v.has(r)&&l.headers.authorization===void 0){const d=T();d!==void 0&&(l.headers.authorization=`Bearer ${d}`)}return l};let X=!1,C=!1;const q=()=>{C||(C=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},W=r=>{if(!e.allowUnauthenticatedShardAccess){const s=r==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${r} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${r} access (relying solely on per-row RLS).`,{code:r==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}X||(X=!0,console.warn([`[lunora] SECURITY: serving ${r} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},z=async(r,s,l=!1)=>{if(s.includes(Ze)||s.includes(et))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(!l)if(e.authorizeShard){if(!await ke(e.authorizeShard({identity:r,shardKey:s})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==o&&W("shard")},oe=Na({defaultShard:o,forwardToShard:g,isAdmin:P,queryCoordinator:e.queryCoordinator,resolveForwardContext:M,shardDO:i}),V=async(r,s,l,d,w,_)=>{Ie(r);const O={"content-type":"application/json",[_t]:bt,"x-lunora-system":"1"};return w?.userId!==void 0&&w.userId.length>0&&(O["x-lunora-userid"]=w.userId),w?.identity!==void 0&&w.identity.length>0&&(O["x-lunora-identity"]=w.identity),d!==void 0&&d.length>0&&(O["x-lunora-mutation-id"]=d),_!==void 0&&_.length>0&&(O.traceparent=_),g(i,l,Ne(r,s,O))},se=async(r,s,l,d,w)=>{const _=l?.[r];if(!_||typeof _.create!="function")throw new c(`${d} targets workflow binding "${r}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(Xr(s))throw new c(`${d} params ${Zr}`,{code:"BAD_REQUEST",status:400});try{await _.create(w===void 0?{params:s}:{id:w,params:s})}catch(O){if(!no(O))throw O}},Q=async(r,s,l)=>{if(r.workflow){await se(r.workflow,r.args??{},s,`cron job "${r.name}"`);return}if(r.functionPath===void 0)throw new c(`cron job "${r.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const d=await V(r.functionPath,r.args??{},r.shardKey??o,void 0,void 0,l);if(!d.ok)throw new c(`cron job "${r.name}" (${r.functionPath}) failed with shard status ${String(d.status)}`,{code:"CRON_JOB_FAILED",status:500})},G=r=>{if(!P(r))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},J=(r,s,l)=>{if(G(r),s===void 0)throw new c(l.message,{code:l.code,status:400});return s},Re=async(r,s,l,d,w)=>{const _=e.cronJobs?.[r];if(!_)return 0;for(const O of _)try{await Q(O,s,w)}catch(k){l.push(d(k))}return _.length},Ce=async(r,s)=>{if(G(r),$(r,"POST","cron-jobs run"),!e.cronJobs)throw new c("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await re(r),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 w=Object.values(e.cronJobs).flat().find(_=>_.name===d);if(!w)throw new c(`no cron job named "${d}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await Q(w,s),Response.json({name:d,ran:!0},{status:200})},Ae=async r=>{const s=typeof r.pool=="string"&&r.pool.length>0?r.pool:void 0;if(!s||!u||typeof r.id!="string")return;const l=typeof r.instanceName=="string"&&r.instanceName.length>0?r.instanceName:"default";try{await ye(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:r.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},ce=async(r,s)=>{$(r,"POST","Scheduler dispatch");const l=await sn(r),d=s??{},w=typeof d.LUNORA_SCHEDULER_SECRET=="string"?d.LUNORA_SCHEDULER_SECRET:void 0,_=e.adminToken??(typeof d.LUNORA_ADMIN_TOKEN=="string"?d.LUNORA_ADMIN_TOKEN:void 0),O=r.headers.get("x-lunora-scheduler-signature");let k=!1;if(O&&w?k=await js(w,l,O):_&&(k=en(r,_)),!k)throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let N;try{N=JSON.parse(l)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const E=N??{},S=E.args??{},B=typeof E.id=="string"&&E.id.length>0?E.id:void 0;if(typeof E.workflow=="string"&&E.workflow.length>0)return await se(E.workflow,S,s,"scheduled workflow",B),await Ae(E),Response.json({ok:!0},{status:200});if(typeof E.functionPath!="string"||E.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const x=typeof E.shardKey=="string"&&E.shardKey.length>0?E.shardKey:o,Y=Rs(r),H=await V(E.functionPath,S,x,B,Y,r.headers.get("traceparent")??void 0);return await Ae(E),H},Tn=Oo({assertAdmin:G,getReader:()=>e.authAuditReader}),On=vo({assertAdmin:G,getMove:()=>e.authJurisdictionMove}),vn=async(r,s)=>{G(r);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:Ee({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const d=s?.kind,w=s?.userId,_=s?.limit,O=d==="fcm"||d==="web-push"?d:void 0,k=typeof w=="string"&&w!==""?w:void 0,N=typeof _=="number"&&Number.isFinite(_)?Math.trunc(_):0,E=N>0?Math.min(N,1e3):1e3,B=(await l.list({kind:O,limit:E,userId:k})).filter(x=>O!==void 0&&x.kind!==O?!1:k===void 0||(x.userId??null)===k).map(({keys:x,token:Y,...H})=>H);return Response.json({result:Ee({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},In=async(r,s)=>{if(!s.fanOut&&!(s.functionPath!==Pt&&s.functionPath!==qt&&s.functionPath!==tt&&s.functionPath!==pn))return await L(r),s.functionPath===Pt?Tn(r,s.args??{}):s.functionPath===qt?vn(r,s.args):On(r,s.functionPath,s.args??{})},kn=Yo({applyGlobals:e.applyGlobals,assertAdmin:G,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:o,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:J,resolveForwardContext:M,shardDO:i,streamExportRows:(r,s,l,d)=>mn(e,r,s,l,d,i),streamingImport:(r,s)=>na(r,e,s,i),syncGlobals:e.syncGlobals}),Be=(r,s)=>{const l=r.searchParams.get(s);return l===null||l===""?void 0:l},xe=r=>{const s=new URL(r.url),l=s.searchParams.get("limit"),d=s.searchParams.get("offset"),w=l===null?void 0:Number.parseInt(l,10),_=d===null?void 0:Number.parseInt(d,10);return{limit:w!==void 0&&Number.isFinite(w)&&w>=0?w:void 0,offset:_!==void 0&&Number.isFinite(_)&&_>=0?_:void 0}},dt=()=>{if(u===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},Pn=qa({checkWsAdmin:async r=>P(r)||tn(r,T(),b()),requireSchedulerNamespace:dt,resolveSchedulerStub:r=>(G(r),ye(dt(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Dn=us({assertAdmin:G,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Nn=Hr({assertAdmin:G,parsePaging:xe,queryParameter:Be,readBodyBytes:Pr,requireAdminOption:J,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Un=Mo({options:e,readJsonBody:re,requireAdminOption:J}),Cn=os({readJsonBody:re,requireAdminOption:J,vectorIntrospector:e.vectorIntrospector}),Bn=ga({kvIntrospector:e.kvIntrospector,readJsonBody:re,requireAdminOption:J}),xn=Vr({logArchive:e.logArchive,readJsonBody:re,requireAdminOption:J}),Hn=pa({assertAdmin:G,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:xe,queryParameter:Be,requireAdminOption:J}),Ln=r=>{const s=[],l=i??r?.SHARD;if(l!==void 0&&s.push(Qr("durable-object:default",l,o)),e.health?.disableBindingProbes!==!0)for(const[d,w]of Object.entries(r??{})){const _=Ms(d,w);_!==void 0&&s.push(_)}for(const d of e.health?.probes??[])s.push(d);return s},jn=Gr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:P,resolveProbes:Ln}),Mn=r=>{const s=E=>"args"in E?{...E,args:Xe(E.args)}:E,l=e.schedulerInstanceName??"default",d=()=>ye(r,l),w=async(E,S)=>{const B=await d().fetch(new Request(`https://scheduler.internal${E}`,S));if(!B.ok)throw new c(`ctx.scheduler: SchedulerDO ${E} failed (${String(B.status)}): ${await B.text()}`,{code:"INTERNAL",status:500});return await B.json()},_=async(E,S)=>await w(E,{body:JSON.stringify(S),headers:{"content-type":"application/json"},method:"POST"}),O=E=>{const S=E;if(S==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 S.binding=="string"&&S.binding.length>0)return{workflow:S.binding};if(typeof S.__lunoraRef=="string")return{functionPath:S.__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 eo(async S=>w(S===void 0?"/list":`/list?cursor=${encodeURIComponent(S)}`,{method:"GET"}))).map(S=>s(S)),N=async(E,S,B={})=>{const x=O(S),{id:Y}=await _("/schedule",{args:Ir("ctx.scheduler",String(x.functionPath??x.workflow),B),scheduledFor:Math.ceil(E),...x});return Y};return{cancel:async E=>await _("/cancel",{id:E}),get:async E=>{const S=await w(`/get?id=${encodeURIComponent(E)}`,{method:"GET"});return S.record===void 0?null:s(S.record)},list:k,runAfter:async(E,S,B)=>{if(!Number.isFinite(E)||E<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await N(Date.now()+E,S,B)},runAt:async(E,S,B)=>{if(!Number.isFinite(E))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await N(E,S,B)}}},$n=async(r,s,l)=>{const{claims:d,headers:w,userId:_}=vs(await I(r,s,a)),O=_e(s,r,E=>l.waitUntil?.(E)),k=E=>async(S,B={})=>{const x=S.__lunoraRef;if(typeof x!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Ie(x);const Y=await Te(r,x,Ee(B),E,{...w,"x-lunora-system":"1"},O),H=await Y.json();if(H.error)throw new c(H.error.message??"shard RPC failed",{code:H.error.code??"INTERNAL",status:Y.status});return Xe(H.result)},N=k(o);return{auth:{getIdentity:()=>Promise.resolve(d),userId:_},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),forShard:E=>{const S=k(E);return{runAction:S,runMutation:S,runQuery:S}},runAction:N,runMutation:N,runQuery:N,...u===void 0?{}:{scheduler:Mn(u)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:Yr(e.storage(s,new URL(r.url).origin))}}},Kn=async(r,s,l)=>{if(!e.httpRouter)return;const d=await $n(r,s,l);try{return await e.httpRouter.fetch(r,{...s,__lunoraCtx:d},l)}catch(w){return console.error("[lunora] httpRouter (SSR) handler threw:",w),new Response("Internal Server Error",{status:500})}},Fn=async(r,s,l)=>{if(r.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const d=Ot(r,de);if(d)return d;const w=l.searchParams.get("shard")??o,{headers:_,identity:O}=await I(r,s,a),k=P(r)||await tn(r,T(),b());await z(O,w,k);const N=Zt(r,_),E=Xt(s,e.shardDO);if(E!==void 0){N.set("x-lunora-shard-binding",E);const S=await xs(i,w);if(S>0){const B=po(w,Math.floor(Math.random()*S));return g(i,B,new Request(r,{headers:N}),vt(r))}}return g(i,w,new Request(r,{headers:N}))},Gn=async(r,s,l)=>{if(h===void 0)return new Response("Not found",{status:404});if(r.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const d=Ot(r,de);if(d)return d;let w;try{w=decodeURIComponent(l.pathname.slice(Wt.length))}catch{return new Response("Unknown voice agent",{status:404})}const _=Object.hasOwn(h,w)?h[w]:void 0;if(_===void 0)return new Response("Unknown voice agent",{status:404});const O=l.searchParams.get("threadKey");if(O===null||O.length===0)return new Response("Missing threadKey",{status:400});const{headers:k,identity:N}=await I(r,s,a);if(e.authorizeShard){if(!await ke(e.authorizeShard({identity:N,shardKey:O})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else W("shard");const E=Zt(r,k);return g(_,O,new Request(r,{headers:E}))},Qn=async(r,s,l)=>{if(e.authorizeFanOut){if(!await ke(e.authorizeFanOut(l,r.table,s)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new c("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});W("fan-out")},Se=async(r,s)=>{if(!(!r.fanOut&&r.functionPath.startsWith("__lunora_admin__:"))){if(r.fanOut){await Qn(r.fanOut,r.functionPath,s);return}await z(s,r.shardKey??o)}},Wn=(r,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){q();return}if(e.functions[s]?.kind!=="query"||l.includes(et)||l.includes(Ze))return;const d=vt(r);return d===void 0?void 0:{name:mo(l,d),region:d}},zn=async(r,s,l,d,w)=>{const _=Wn(r,s,d);if(_!==void 0){const O={...w,"x-lunora-replica-read":"1",...R===void 0?{}:{"x-lunora-shard-binding":R}},k=wo(r.headers.get("x-lunora-min-seq"));k!==void 0&&(O["x-lunora-min-seq"]=String(k));const N=await g(i,_.name,Ne(s,l,O),_.region);if(N.status!==421)return N}return g(i,d,Ne(s,l,w))},Te=async(r,s,l,d,w,_)=>{const O=Date.now(),{observability:k,sampling:N}=e,E=Je(r),{decision:S,ignoredUpstream:B,trace:x}=Mt(r,{...N===void 0?{}:{sampling:N},trustInbound:t(r)});B&&n(r);const Y={...w,[Rt]:S.keepErrors?"1":"0"};$t(x,Y);try{const H=await zn(r,s,l,d,Y);ue(k,{...E,...Qt(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}}},_,void 0,{isTraced:x.sampled,keepErrors:S.keepErrors});const te=new Response(H.body,{headers:H.headers,status:H.status,statusText:H.statusText});return te.headers.set("x-lunora-shard-key",d),te}catch(H){throw ue(k,{...E,...Qt(x),...Pe(s,Date.now()-O,H,{shardKey:d})},_,void 0,{isTraced:x.sampled,keepErrors:S.keepErrors}),H}},Vn=r=>{if(r.fanOut&&r.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(r.fanOut||Ie(r.functionPath),r.fanOut&&!e.queryCoordinator)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},qn=async(r,s,l)=>{$(r,"POST","RPC");const d=await Us(r);Ns(s,d),Vn(d);const w=await In(r,d);if(w!==void 0)return w;const{headers:_,identity:O}=await j(r,s,a);zt(r,O),await Se(d,O);const k=Ye(d,e);{const N=Date.now(),{observability:E}=e,S=Je(r),B=_e(s,r,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 te=await H.fanOut(i,{args:d.args??{},fanOut:d.fanOut,functionPath:d.functionPath,headers:_});return ue(E,{durationMs:Date.now()-N,fanOut:{failed:te.failed,shards:te.ok+te.failed,table:d.fanOut.table},functionPath:d.functionPath,...S,ok:!0},B),Response.json(te,{headers:{"content-type":"application/json"},status:200})}catch(te){throw ue(E,{...Pe(d.functionPath,Date.now()-N,te,{fanOut:{table:d.fanOut.table}}),...S},B),te}}const x=d.shardKey??o,Y=()=>Te(r,d.functionPath,d.args??{},x,_,B);return k&&e.x402Charge?e.x402Charge(r,{functionPath:d.functionPath,price:k.price},Y,qe(l)):Y()}},Jn=async(r,s,l)=>{$(r,"POST","RPC batch");const d=await re(r),{calls:w}=d;if(!Array.isArray(w))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:_,identity:O}=await j(r,s,a);zt(r,O);const k=Ko(w,o);for(const K of k.values())for(const F of K)if(e.functions?.[F.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${F.functionPath}" cannot be called in a batch; dispatch it individually over ${Gt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...k.entries()].flatMap(([K,F])=>F.map(ne=>Se({args:ne.args,functionPath:ne.functionPath,shardKey:K},O))));const{observability:N,sampling:E}=e,S=_e(s,r,l&&(K=>l.waitUntil?.(K))),B=Je(r),{decision:x,ignoredUpstream:Y,trace:H}=Mt(r,{...E===void 0?{}:{sampling:E},trustInbound:t(r)});Y&&n(r);const te={isTraced:H.sampled,keepErrors:x.keepErrors},cr=K=>{const F={..._,"content-type":"application/json",[Rt]:x.keepErrors?"1":"0"};return $t({...H,spanId:K},F),F},He=K=>({parentSpanId:K,spanId:ge(8),traceFlags:H.traceFlags,traceId:H.traceId}),ve=[],Le=[],ft=(K,F,ne,le)=>({body:{error:{code:ne,message:le}},id:K.id,status:F}),pt=(K,F,ne,le,fe)=>{for(const Z of K)ue(N,fe(Z),S,void 0,te),ve.push(ft(Z,F,ne,le))},dr=(K,F,ne,le,fe,Z)=>{for(const be of K){const pe=fe.get(be.id)??Z,me=pe<400;ue(N,{durationMs:le,functionPath:be.functionPath,...B,...He(ne),ok:me,shardKey:F,...me?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},S,void 0,te)}};await Promise.all([...k.entries()].map(async([K,F])=>{const ne=ge(8),le=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:F}),headers:new Headers(cr(ne)),method:"POST"}),fe=Date.now();let Z;try{Z=await g(i,K,le)}catch(ee){const Me=Date.now()-fe,{body:gt}=pr(ee,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});pt(F,502,gt.code,gt.message,hr=>({...Pe(hr.functionPath,Me,ee,{shardKey:K}),...B,...He(ne)}));return}const be=Date.now()-fe,pe=Z.headers.get("x-d1-bookmark");pe&&Le.push(pe);let me;try{me=await Z.json()}catch{const ee=`shard batch returned a non-JSON response (${String(Z.status)})`;pt(F,Z.status,"SHARD_ERROR",ee,Me=>({durationMs:be,error:{code:"SHARD_ERROR",message:ee,status:Z.status},functionPath:Me.functionPath,...B,...He(ne),ok:!1,shardKey:K}));return}const je=Array.isArray(me.results)?me.results:[],ur=new Map(je.map(ee=>[ee.id,ee.status??Z.status])),lr=new Set(je.map(ee=>ee.id));dr(F,K,ne,be,ur,Z.status),ve.push(...je);for(const ee of F)lr.has(ee.id)||ve.push(ft(ee,Z.status,"SHARD_ERROR",`shard batch omitted result for call ${String(ee.id)}`))}));const mt={"content-type":"application/json"},[wt]=Le;return Le.length===1&&wt!==void 0&&(mt["x-d1-bookmark"]=wt),Response.json({results:ve},{headers:mt,status:200})},Yn=async(r,s,l,d={},w={})=>{try{const _=l.__lunoraRef;if(typeof _!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Ie(_);const{headers:O,identity:k}=await j(r,s,a,w.context),N={args:d,functionPath:_,shardKey:w.shardKey};await Se(N,k);const E=w.shardKey??o,S=_e(s,r,w.waitUntil),B=()=>Te(r,_,d,E,O,S),x=Ye(N,e);return x&&e.x402Charge?await e.x402Charge(r,{functionPath:_,price:x.price},B,qe(w.waitUntil?{waitUntil:w.waitUntil}:w.context)):await B()}catch(_){return At(_)}},ut=async(r,s,l)=>{const{observability:d}=e,w=Date.now(),_=ge(16),O=ge(8),k=Yt(s),N=rn(_,O,!0);try{const E=await l(N);return ue(d,{durationMs:Date.now()-w,functionPath:r,ok:!0,spanId:O,traceId:_},k),E}catch(E){throw ue(d,{...Pe(r,Date.now()-w,E,{}),spanId:O,traceId:_},k),E}finally{Et(d,k)}},lt=async(r,s,l,d)=>{y(s);const w=[],_=S=>S instanceof Error?S:new Error(String(S)),O=e.crons?.[r.cron];if(O)try{await O(r,s,l)}catch(S){w.push(_(S))}const k=await Re(r.cron,s,w,_,d),N=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===r.cron;if(N)try{await xo(e,i,T(),r)}catch(S){w.push(_(S))}if(!O&&k===0&&!N){const S=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${r.cron}") fired but no cron handler is registered for that expression. Registered: ${S.length===0?"(none)":S.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[E]=w;if(w.length===1&&E)throw E;if(w.length>1)throw new AggregateError(w,`scheduled("${r.cron}") had ${String(w.length)} failure(s)`)},Xn=Ya({assertAdmin:G,dispatchScheduled:lt,queueHandler:e.queueHandler}),Zn=async(r,s)=>{try{const l=r??{},d=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!d||d.length===0)return;await g(i,o,Ne(As,{outcome:s},{authorization:`Bearer ${d}`,"content-type":"application/json"}))}catch{}},er=async(r,s,l,d)=>{if(!e.authHandler)return;const w=e.authBasePath??Vt,_=Jt(l.pathname,w)?Dr(r):void 0;let O;try{O=await e.authHandler(_?.request??r)}catch(k){throw _?.overflowed()?new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413}):k}if(_?.overflowed())throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});if(O)return Ts(l.pathname,w)&&d.waitUntil?.(Zn(s,O.status>=400?"fail":"ok")),O},tr=async({args:r,env:s,functionPath:l,request:d,shardKey:w,waitUntil:_})=>{an(r,"REST");const O={functionPath:l,...w===void 0?{}:{shardKey:w}},{headers:k,identity:N}=await j(d,s,a);await Se(O,N);const E=w??o,S=_e(s,d,_),B=()=>Te(d,l,r,E,k,S),x=Ye(O,e);return x&&e.x402Charge?e.x402Charge(d,{functionPath:l,price:x.price},B,qe({waitUntil:_})):B()},nr=kr({functions:e.functions??{},invoke:tr,readJsonBody:re,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Oe=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0;$s(Oe);const rr={[bs]:r=>r.method!=="GET"&&r.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[fs]:(r,s,l)=>Fn(r,s,l),[Gt]:(r,s,l,d)=>qn(r,s,d),[hs]:(r,s,l,d)=>Jn(r,s,d),[ps]:(r,s)=>ce(r,s),[ms]:(r,s)=>Ce(r,s),[ws]:async r=>{$(r,"POST","ws-token"),G(r);const s=T();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 Eo(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...oe,...kn,...Pn,...Dn,...Nn,...Un,...Cn,...Bn,...xn,...Hn,...jn,...nr,...To({assertAdmin:G,getAuthAdmin:()=>e.authAdmin,parsePaging:xe,queryParameter:Be,readJsonBody:re})};let de=Tt(e.security),ht=!1;const or=r=>{ht||(ht=!0,de=Tt(e.security,r??{}))},ar=async(r,s)=>{_s(s)&&await L(r)},sr=(r,s)=>{if(!(s.pathname.startsWith(Ue)||e.authHandler!==void 0&&Jt(s.pathname,e.authBasePath??Vt))||r.method!=="POST"&&r.method!=="PUT")return;const d=Number(r.headers.get("content-length")??""),w=ls[s.pathname]??on;if(Number.isFinite(d)&&d>w)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},ir=async(r,s,l)=>{rt.set(r,l);const d=new URL(r.url);sr(r,d);const w=await er(r,s,d,l);if(w)return w;if(Oe){const N=`${r.method} ${d.pathname}`,E=Oe[N]??Oe[d.pathname];if(E)return E(r,s,l)}const _=Xn[d.pathname];if(_)return _(r,s,l);const O=rr[d.pathname];if(O)return await ar(r,d.pathname),O(r,s,d,l);if(e.voiceAgents!==void 0&&d.pathname.startsWith(Wt))return Gn(r,s,d);if(d.pathname.startsWith(Ue))return new Response("Not found",{status:404});const k=await Kn(r,s,l);return k||new Response("Not found",{status:404})};return{async fetch(r,s,l){e.passThroughOnException&&l.passThroughOnException?.(),or(s),y(s);const d=qr(r,de);if(d)return d;const w=Jr(r,de);if(w)return Fe(w,r,de);try{const _=await ir(r,s,l);return Fe(_,r,de)}catch(_){return Fe(At(_),r,de)}finally{Et(e.observability,Yt(l))}},async queue(r,s,l){await ut(`queue:${Is(r)}`,l,async d=>{await e.queue?.(r,s,l,{traceparent:d})})},async scheduled(r,s,l){await ut(`cron:${r.cron}`,l,async d=>{await lt(r,s,l,d)})},serverQuery:Yn}},Fs=e=>Sn(e),Gs=e=>typeof e=="function"?{fetch:e}:e,Qs=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,Ws=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},mi=(e,t)=>{const n=Gs(e),{email:o,queue:a,scheduled:i}=Ws(e),u=p=>{const g={...Fs({...p,httpRouter:n})};return i!==void 0&&!Qs(p)&&(g.scheduled=async(A,T,m)=>{await i(A,T,m)}),a!==void 0&&p.queue===void 0&&(g.queue=async(A,T,m)=>{await a(A,T,m)}),o!==void 0&&(g.email=async(A,T,m)=>{await o(A,T,m)}),g};if(typeof t!="function")return u(t);const h=t;return{fetch:(p,f,g)=>u(h(f)).fetch(p,f,g),queue:(p,f,g)=>u(h(f)).queue?.(p,f,g)??Promise.resolve(),scheduled:(p,f,g)=>u(h(f)).scheduled(p,f,g),serverQuery:(p,f,g,A,T)=>u(h(f)).serverQuery(p,f,g,A,T),...o===void 0?{}:{email:(p,f,g)=>u(h(f)).email?.(p,f,g)??Promise.resolve()}}},zs=(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}},wi=(e={})=>(t,n,o)=>Sn(zs(e,n)).fetch(t,n,o??mr),gi=e=>e;export{tt as COPY_AUTH_TO_JURISDICTION_OP,Pt as GET_AUTH_AUDIT_LOG_OP,mr as NOOP_EXECUTION_CONTEXT,pn as PURGE_UNPINNED_AUTH_OP,_i as composeIdentityResolvers,Fs as composeWorker,wi as createLunoraHandler,Sn as createWorker,gi as defineRpcEnvelope,xs as probeRelayCount,zs as resolveLunoraOptions,Ei as routeIdentityResolvers,mi as withFrameworkWorker};
@@ -1 +0,0 @@
1
- import{toErrorBody as T}from"@lunora/errors";import{b as E,a as I}from"./base64-Bl1_r2k1.mjs";import{LunoraError as U}from"./LunoraError-DksAgIpa.mjs";import{resolveShard as B}from"./applyJurisdiction-C0ddU7Tg.mjs";const be=t=>({listShardKeys(e){return t[e]??[]}}),F=16,D=5e3,y=t=>t!==null&&typeof t=="object"&&"result"in t?t.result:t,V=t=>{const e=t??{};return{changed:typeof e.changed=="number"?e.changed:0,processed:typeof e.processed=="number"?e.processed:0,status:typeof e.status=="string"?e.status:void 0}},L=(t,e)=>t?"failed":e?"in_progress":"completed",j=t=>{const e=[];let s=0,o=0,r=0,n=0,a=!1,c=!1;for(const i of t){if(i.kind==="err"){o+=1,e.push({error:{message:i.message,timedOut:i.timedOut},shardKey:i.shardKey});continue}s+=1;const d=y(i.value),u=V(d);r+=u.changed,n+=u.processed,a||=u.status==="in_progress",c||=u.status==="failed",e.push({result:d,shardKey:i.shardKey})}return{changed:r,failed:o,ok:s,processed:n,shards:e,status:L(c,a||o>0)}},$=t=>{const e=t??{};return{before:typeof e.before=="number"&&Number.isFinite(e.before)?e.before:0,total:typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0}},J=t=>{const e=[];let s=0,o=0,r=0,n=0;for(const a of t){if(a.kind==="err"){o+=1,e.push({error:{message:a.message,timedOut:a.timedOut},shardKey:a.shardKey});continue}s+=1;const c=$(y(a.value));r+=c.before,n+=c.total,e.push({result:c,shardKey:a.shardKey})}return{failed:o,ok:s,partial:o>0,position:r+1,shards:e,total:n}},x=0,P=1,G=2,k=(t,e)=>t<e?-1:t>e?1:0,M=t=>t==null?x:typeof t=="number"?P:G,O=(t,e)=>{const s=M(t),o=M(e);return s!==o?s<o?-1:1:s===x?0:s===P?k(t,e):k(String(t),String(e))},H=(t,e,s)=>{const o=O(t.partitionKey,e.partitionKey);if(o!==0)return o;const r=Math.max(t.sortValues.length,e.sortValues.length);for(let n=0;n<r;n+=1){const a=O(t.sortValues[n],e.sortValues[n]);if(a!==0)return s[n]==="desc"?-a:a}return O(t.rowId,e.rowId)},Q=t=>I(new TextEncoder().encode(JSON.stringify(t))),Y=t=>{try{const e=JSON.parse(new TextDecoder().decode(E(t)));if(e!==null&&typeof e=="object"&&"perShard"in e){const{perShard:s}=e;if(s!==null&&typeof s=="object")return{perShard:s}}}catch{}return{perShard:{}}},W=t=>{const e=t??{},s=Array.isArray(e.rows)?e.rows:[];return{directions:Array.isArray(e.directions)?e.directions:[],hasMore:e.hasMore===!0,rows:s}},X=(t,e)=>{let s;for(const o of t){const r=o.rows[o.head];r!==void 0&&(s===void 0||H(r.key,s.row.key,e)<0)&&(s={row:r,slice:o})}return s},z=(t,e)=>{let s=!1;const o=new Set;for(const n of t)o.add(n.shardKey),(n.head<n.rows.length||n.hasMore)&&(s=!0);const r={...e};for(const n of Object.keys(e))o.has(n)||(s=!0);return s?Q({perShard:r}):null},Z=(t,e,s,o)=>{const r=[],n={...o};for(;r.length<e;){const c=X(t,s);if(c===void 0)break;r.push(c.row.doc),n[c.slice.shardKey]=c.row.key,c.slice.head+=1}const a=z(t,n);return{isDone:a===null,nextCursor:a,page:r}},q=t=>{const e=[];let s=0,o=0;for(const r of t){if(r.kind==="err"){o+=1,e.push({error:{message:r.message,timedOut:r.timedOut},shardKey:r.shardKey});continue}s+=1;const n=y(r.value),a=Array.isArray(n?.rows)?n.rows:[];e.push({rows:a,shardKey:r.shardKey})}return{failed:o,ok:s,shards:e}},ee=t=>{const e=[];let s=0,o=0;for(const{outcome:r,sinceEpoch:n,sinceSeq:a}of t){if(r.kind==="err"){o+=1,e.push({cursor:a,error:{code:r.code,message:r.message,timedOut:r.timedOut},shardKey:r.shardKey,...n===void 0?{}:{epoch:n}});continue}s+=1;const c=y(r.value),i=Array.isArray(c?.changes)?c.changes:[],d=typeof c?.cursor=="number"?c.cursor:a,u=typeof c?.epoch=="string"&&c.epoch.length>0?c.epoch:n;e.push({changes:i,cursor:d,shardKey:r.shardKey,...u===void 0?{}:{epoch:u}})}return{failed:o,ok:s,shards:e}},re=t=>{let e=0,s=0,o=0;for(const r of t){if(r.kind==="err"){s+=1;continue}e+=1;const n=y(r.value);o+=typeof n?.applied=="number"?n.applied:0}return{applied:o,failed:s,ok:e}},te=t=>{const e=t??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},se=t=>{const e=[];let s=0,o=0;for(const r of t){if(r.kind==="err"){o+=1,e.push({requests:0,shardKey:r.shardKey});continue}s+=1,e.push({requests:te(y(r.value)),shardKey:r.shardKey})}return{failed:o,ok:s,shards:e}},oe=t=>{const e=[],s={},o=[];let r=0,n=0,a=0;for(const c of t){if(c.kind==="err"){a+=1,e.push({error:{message:c.message,timedOut:c.timedOut},shardKey:c.shardKey});continue}n+=1;const i=y(c.value),d=i?.inserted??{};for(const[l,h]of Object.entries(d))s[l]=(s[l]??0)+h;const u=i?.errors;Array.isArray(u)&&o.push(...u),r+=i?.conflicts??0,e.push({result:{conflicts:i?.conflicts??0,errors:i?.errors??[],inserted:d},shardKey:c.shardKey})}return{conflicts:r,errors:o,failed:a,inserted:s,ok:n,shards:e}},g=t=>({body:JSON.stringify({args:t.args??{},functionPath:t.functionPath}),headers:{"content-type":"application/json",...t.headers}}),ne=async t=>{try{const s=(await t.json())?.error;return typeof s?.code!="string"||s.code.length===0?void 0:{code:s.code,message:typeof s.message=="string"?s.message:""}}catch{return}},w=async(t,e,s,o)=>{const r=B(t,e),n=new AbortController,a=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:n.signal});let c;const i=new Promise(u=>{c=setTimeout(()=>{try{n.abort()}catch{}u({code:"SHARD_TIMEOUT",kind:"err",message:`shard "${e}" timed out after ${String(o)}ms`,shardKey:e,timedOut:!0})},o)}),d=(async()=>{try{const u=await r.fetch(a);if(!u.ok){const h=await ne(u),m=`shard "${e}" returned ${String(u.status)}`;return{code:h?.code??"SHARD_HTTP_ERROR",kind:"err",message:h===void 0||h.message.length===0?m:`${m}: ${h.message}`,shardKey:e,timedOut:!1}}const l=await u.json();return{kind:"ok",shardKey:e,value:l}}catch(u){const{body:l}=T(u,{fallbackCode:"INTERNAL",redactedMessage:"shard call failed"});return{code:l.code,kind:"err",message:`shard "${e}" failed: ${l.message}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([d,i])}finally{c!==void 0&&clearTimeout(c)}},b=async(t,e,s)=>{if(t.length===0)return[];const o=Array.from({length:t.length});let r=0;const n=async()=>{for(;;){const c=r;r+=1;const i=t[c];if(c>=t.length||i===void 0)return;o[c]=await s(i,c)}},a=Math.min(e,t.length);return await Promise.all(Array.from({length:a},()=>n())),o},K=(t,e)=>t.length>0||e===null?t:[e],v=async(t,e,s)=>{const o=await Promise.all(e.map(async r=>K(await t.listShardKeys(r),s)));return[...new Set(o.flat())]},p=async(t,e,s,o,r)=>{const n=g(s);return b(e,o,async a=>w(t,a,n,r))},ae=t=>{const e={};for(const s of Object.keys(t).toSorted(k))e[s]=t[s]??null;return JSON.stringify(e)},ce=t=>t.flatMap(e=>Array.isArray(e)?e:[]),ie=(t,e,s)=>{switch(s){case"max":return Math.max(t,e);case"min":return Math.min(t,e);case"sum":return t+e;default:return t}},ue=(t,e,s)=>{if(e===null||typeof e!="object")return;const o=e.key??{},r=e.value??null,n=ae(o),a=t.get(n);if(!a){t.set(n,{key:o,value:r});return}if(a.value===null){a.value=r;return}r!==null&&(a.value=ie(a.value,r,s))},de=(t,e)=>{const s=new Map;for(const o of t)if(Array.isArray(o))for(const r of o)ue(s,r,e);return[...s.values()]},N=(t,e)=>{let s=null;for(const o of t)typeof o=="number"&&Number.isFinite(o)&&(s=s===null?o:e(s,o));return s},le=t=>{let e=0;for(const s of t)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},fe=t=>{let e=0,s=0;for(const o of t){if(o===null||typeof o!="object")continue;const r=o;typeof r.before=="number"&&Number.isFinite(r.before)&&(e+=r.before),typeof r.total=="number"&&Number.isFinite(r.total)&&(s+=r.total)}return{position:e+1,total:s}},he=(t,e)=>{const s=[];for(const r of t)if(Array.isArray(r))for(const n of r){if(n===null||typeof n!="object")continue;const a=n[e.by],c=typeof a=="number"&&Number.isFinite(a)?a:Number.NEGATIVE_INFINITY;s.push({row:n,score:c})}const o=e.direction??"desc";return s.sort((r,n)=>o==="asc"?k(r.score,n.score):k(n.score,r.score)),s.slice(0,e.k).map(r=>r.row)},ye=(t,e)=>{switch(e.kind){case"concat":return ce(t);case"first":return t[0];case"groupBy":return de(t,e.op??"sum");case"max":return N(t,Math.max);case"min":return N(t,Math.min);case"rank":return fe(t);case"sum":return le(t);case"topK":return he(t,e);default:return t}},ke=t=>{const e=t.maxConcurrency??F,s=t.perShardTimeoutMs??D;if(e<1)throw new U("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(o,r){const n=await t.registry.listShardKeys(r.fanOut.table),a=await p(o,n,r,e,s),c=[],i=[];for(const d of a)d.kind==="ok"?c.push(d.value):i.push({code:d.code,message:d.message,shardKey:d.shardKey,timedOut:d.timedOut});return{data:ye(c,r.fanOut.merge),errors:i,failed:i.length,ok:c.length}},async orchestrateExport(o,r){const n=await v(t.registry,r.tables,r.defaultShardKey),a=K(n,r.defaultShardKey),c={args:{...r.args,tables:[...r.tables]},functionPath:"__lunora_admin__:exportShard",headers:r.headers},i=await p(o,a,c,e,s);return q(i)},async orchestrateCdcSync(o,r){const n=K(await v(t.registry,r.tables,r.defaultShardKey),r.defaultShardKey),a=r.cursors??{},c=r.epochs??{},i=await b(n,e,async d=>{const u=a[d]??0,l=c[d];return{outcome:await w(o,d,g({args:{limit:r.limit,sinceEpoch:l,sinceSeq:u},functionPath:"__lunora_admin__:cdcSync",headers:r.headers}),s),sinceEpoch:l,sinceSeq:u}});return ee(i)},async orchestrateImport(o,r){const{batches:n}=r,a=await b(n,e,async c=>w(o,c.shardKey,g({args:{rows:[...c.rows],startLine:c.startLine??1},functionPath:"__lunora_admin__:importShard",headers:r.headers}),s));return oe(a)},async orchestrateApplyCdc(o,r){const{batches:n}=r,a=await b(n,e,async c=>w(o,c.shardKey,g({args:{changes:[...c.changes]},functionPath:"__lunora_admin__:applyCdc",headers:r.headers}),s));return re(a)},async orchestrateMigration(o,r){const n=K(await t.registry.listShardKeys(r.table),r.defaultShardKey),a=await p(o,n,r,e,s);return j(a)},async orchestrateRank(o,r){const n=await t.registry.listShardKeys(r.table),a={args:{index:r.index,partitionKey:r.partitionKey,rowId:r.rowId,sortValues:[...r.sortValues],table:r.table},functionPath:"__lunora_admin__:rankBefore",headers:r.headers},c=await p(o,n,a,e,s);return J(c)},async orchestrateRankPage(o,r){const n=await t.registry.listShardKeys(r.table),a=Math.max(1,Math.min(1e3,Math.floor(r.take??100))),c=r.directions??[],i=r.cursor?Y(r.cursor):{perShard:{}},d=await b(n,e,async f=>{const C=i.perShard[f],A={index:r.index,table:r.table,take:a};r.partitionKey!==void 0&&(A.partitionKey=r.partitionKey),C!==void 0&&(A.after=C);const S=await w(o,f,g({args:A,functionPath:"__lunora_admin__:rankPage",headers:r.headers}),s);if(S.kind==="err")return{error:{message:S.message,timedOut:S.timedOut},shardKey:f};const R=W(y(S.value));return{directions:R.directions,hasMore:R.hasMore,rows:R.rows,shardKey:f}}),u=[];let l=0,h=0,m;for(const f of d){if(f.error){h+=1;continue}l+=1,m===void 0&&f.directions&&f.directions.length>0&&(m=f.directions),u.push({hasMore:f.hasMore??!1,head:0,rows:f.rows??[],shardKey:f.shardKey})}const _=Z(u,a,m??c,i.perShard);return{continueCursor:_.nextCursor,failed:h,isDone:_.isDone,ok:l,page:_.page,partial:h>0,shards:d}},async orchestrateShardTraffic(o,r){const n=await t.registry.listShardKeys(r.table),a={functionPath:"__lunora_admin__:getMetrics",headers:r.headers},c=await p(o,n,a,e,s);return se(c)},registry:t.registry}};export{ke as createQueryCoordinator,be as createStaticShardRegistry};