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

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