@lunora/runtime 1.0.0-alpha.89 → 1.0.0-alpha.90

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