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

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