@lunora/runtime 1.0.0-alpha.44 → 1.0.0-alpha.46
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 +9 -9
- package/dist/index.d.ts +9 -9
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-BclNO0yc.mjs +1 -0
- package/dist/packem_shared/{HEALTH_PATH-BEE0A_lZ.mjs → HEALTH_PATH-BpCNEAIa.mjs} +1 -1
- package/dist/packem_shared/applyJurisdiction-8bzZjAPR.mjs +1 -0
- package/dist/packem_shared/composeWorker-bD00YFPt.mjs +6 -0
- package/dist/packem_shared/{createQueryCoordinator-DqrEvhPD.mjs → createQueryCoordinator-DYm2p9dH.mjs} +1 -1
- package/dist/packem_shared/{createShardClient-62qcYKGl.mjs → createShardClient-BkZ9FokE.mjs} +1 -1
- package/package.json +4 -3
- package/dist/packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-CsNnfJzB.mjs +0 -1
- package/dist/packem_shared/applyJurisdiction-uRQLx282.mjs +0 -1
- package/dist/packem_shared/composeWorker-i1cHDFrr.mjs +0 -6
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { RankDirection, RankPageRow, DatabaseWriterLike } from '@lunora/
|
|
2
|
-
export type { RankDirection as RankPageDirection, RankPageRowKey as RankPageKey, RankPageRow, ShardRankPageResult } from '@lunora/
|
|
1
|
+
import { RankDirection, RankPageRow, DatabaseWriterLike } from '@lunora/shard-engine';
|
|
2
|
+
export type { RankDirection as RankPageDirection, RankPageRowKey as RankPageKey, RankPageRow, ShardRankPageResult } from '@lunora/shard-engine';
|
|
3
3
|
import { R2SqlClient } from '@lunora/bindings/r2sql';
|
|
4
4
|
import { WorkflowsRestClient } from '@lunora/workflow';
|
|
5
5
|
import { LunoraError as LunoraError$1, ErrorBody } from '@lunora/errors';
|
|
@@ -642,7 +642,12 @@ interface ResolvedShard {
|
|
|
642
642
|
* compliance boundary the caller asked for.
|
|
643
643
|
*/
|
|
644
644
|
declare const applyJurisdiction: (namespace: ShardNamespaceLike, jurisdiction?: DurableObjectJurisdiction) => ShardNamespaceLike;
|
|
645
|
-
/**
|
|
645
|
+
/**
|
|
646
|
+
* Look up a shard stub by name through the `@lunora/platform` `ShardDirectory`
|
|
647
|
+
* contract. Preserves the historical preference — `getByName` when present,
|
|
648
|
+
* else `idFromName` + `get` — but the preference now lives in one place (the
|
|
649
|
+
* contract's `resolveShard`) rather than being restated per resolution path.
|
|
650
|
+
*/
|
|
646
651
|
declare const resolveShard: (namespace: ShardNamespaceLike, shardKey: string) => ResolvedShard;
|
|
647
652
|
/**
|
|
648
653
|
* Source of "which shard keys exist for a given table right now". Returning
|
|
@@ -1405,12 +1410,7 @@ declare const buildHealthRoutes: (deps: HealthRouteDeps) => Record<string, (requ
|
|
|
1405
1410
|
* an unknown path) proves the DO answered; only a thrown error means the object
|
|
1406
1411
|
* is unreachable. Never inspects the response body, so it cannot leak state.
|
|
1407
1412
|
*/
|
|
1408
|
-
declare const durableObjectProbe: (name: string, namespace:
|
|
1409
|
-
get: (id: unknown) => {
|
|
1410
|
-
fetch: (request: Request) => Promise<Response>;
|
|
1411
|
-
};
|
|
1412
|
-
idFromName: (id: string) => unknown;
|
|
1413
|
-
}, shardKey: string) => HealthProbe;
|
|
1413
|
+
declare const durableObjectProbe: (name: string, namespace: ShardNamespaceLike, shardKey: string) => HealthProbe;
|
|
1414
1414
|
/**
|
|
1415
1415
|
* Active probe of a D1 database: run `SELECT 1`. Healthy when it resolves. The
|
|
1416
1416
|
* binding is passed structurally (only `.prepare().first()` is used) so the
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { RankDirection, RankPageRow, DatabaseWriterLike } from '@lunora/
|
|
2
|
-
export type { RankDirection as RankPageDirection, RankPageRowKey as RankPageKey, RankPageRow, ShardRankPageResult } from '@lunora/
|
|
1
|
+
import { RankDirection, RankPageRow, DatabaseWriterLike } from '@lunora/shard-engine';
|
|
2
|
+
export type { RankDirection as RankPageDirection, RankPageRowKey as RankPageKey, RankPageRow, ShardRankPageResult } from '@lunora/shard-engine';
|
|
3
3
|
import { R2SqlClient } from '@lunora/bindings/r2sql';
|
|
4
4
|
import { WorkflowsRestClient } from '@lunora/workflow';
|
|
5
5
|
import { LunoraError as LunoraError$1, ErrorBody } from '@lunora/errors';
|
|
@@ -642,7 +642,12 @@ interface ResolvedShard {
|
|
|
642
642
|
* compliance boundary the caller asked for.
|
|
643
643
|
*/
|
|
644
644
|
declare const applyJurisdiction: (namespace: ShardNamespaceLike, jurisdiction?: DurableObjectJurisdiction) => ShardNamespaceLike;
|
|
645
|
-
/**
|
|
645
|
+
/**
|
|
646
|
+
* Look up a shard stub by name through the `@lunora/platform` `ShardDirectory`
|
|
647
|
+
* contract. Preserves the historical preference — `getByName` when present,
|
|
648
|
+
* else `idFromName` + `get` — but the preference now lives in one place (the
|
|
649
|
+
* contract's `resolveShard`) rather than being restated per resolution path.
|
|
650
|
+
*/
|
|
646
651
|
declare const resolveShard: (namespace: ShardNamespaceLike, shardKey: string) => ResolvedShard;
|
|
647
652
|
/**
|
|
648
653
|
* Source of "which shard keys exist for a given table right now". Returning
|
|
@@ -1405,12 +1410,7 @@ declare const buildHealthRoutes: (deps: HealthRouteDeps) => Record<string, (requ
|
|
|
1405
1410
|
* an unknown path) proves the DO answered; only a thrown error means the object
|
|
1406
1411
|
* is unreachable. Never inspects the response body, so it cannot leak state.
|
|
1407
1412
|
*/
|
|
1408
|
-
declare const durableObjectProbe: (name: string, namespace:
|
|
1409
|
-
get: (id: unknown) => {
|
|
1410
|
-
fetch: (request: Request) => Promise<Response>;
|
|
1411
|
-
};
|
|
1412
|
-
idFromName: (id: string) => unknown;
|
|
1413
|
-
}, shardKey: string) => HealthProbe;
|
|
1413
|
+
declare const durableObjectProbe: (name: string, namespace: ShardNamespaceLike, shardKey: string) => HealthProbe;
|
|
1414
1414
|
/**
|
|
1415
1415
|
* Active probe of a D1 database: run `SELECT 1`. Healthy when it resolves. The
|
|
1416
1416
|
* binding is passed structurally (only `.prepare().first()` is used) so the
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toAirbyteMessages as t,toFivetranResponse as a}from"./packem_shared/toAirbyteMessages-DBTuFjb5.mjs";import{composeWorker as s,createLunoraHandler as n,createWorker as p,defineRpcEnvelope as m,resolveLunoraOptions as c,withFrameworkWorker as R}from"./packem_shared/composeWorker-
|
|
1
|
+
import{toAirbyteMessages as t,toFivetranResponse as a}from"./packem_shared/toAirbyteMessages-DBTuFjb5.mjs";import{composeWorker as s,createLunoraHandler as n,createWorker as p,defineRpcEnvelope as m,resolveLunoraOptions as c,withFrameworkWorker as R}from"./packem_shared/composeWorker-bD00YFPt.mjs";import{createCrossShardRelationCapabilities as E}from"./packem_shared/createCrossShardRelationCapabilities-CMWiFA5s.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as f,SHARD_REGISTRY_DO_NAME as l,createDynamicShardRegistry as x}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-BclNO0yc.mjs";import{LunoraError as C,toErrorResponse as L}from"./packem_shared/LunoraError-ByasbDmd.mjs";import{createKvCursorStore as y,createMemoryCursorStore as g,defineExportSink as T,r2Sink as A,runExportTap as h,sanitizeChange as k,webhookExportSink as O}from"./packem_shared/createKvCursorStore-C24tEuYk.mjs";import{HEALTH_PATH as v,HEALTH_READY_PATH as I,buildHealthRoutes as b,d1Probe as F,durableObjectProbe as P,presenceProbe as D}from"./packem_shared/HEALTH_PATH-BpCNEAIa.mjs";import{LOG_ARCHIVE_PATH as G,resolveLogArchiveFromEnv as M}from"./packem_shared/LOG_ARCHIVE_PATH-DGsEec3K.mjs";import{memoizeIdentity as w,memoizeIdentityPerRequest as z}from"./packem_shared/memoizeIdentity-CZGtDc4H.mjs";import{e as W,a as Y}from"./packem_shared/observability-DYnm-d4g.mjs";import{analyticsEngineSink as K,combineSinks as Q,consoleSink as X,otlpSink as j,pipelineLogSink as J,sentrySink as B,webhookSink as Z}from"./packem_shared/analyticsEngineSink-CUWYuLHs.mjs";import{D as ee,a as re,c as oe}from"./packem_shared/pipeline-log-reader-DU_CCGDA.mjs";import{createQueryCoordinator as ae,createStaticShardRegistry as ie,mergeStrategyForAggregate as se}from"./packem_shared/createQueryCoordinator-DYm2p9dH.mjs";import{applyJurisdiction as pe,resolveShard as me}from"./packem_shared/applyJurisdiction-8bzZjAPR.mjs";import{R as Re,d as Se,o as Ee}from"./packem_shared/rest-cache-5unAzdFN.mjs";import{argsFromQuery as fe,buildRestRoutes as le,createRestRateLimit as xe,readShardKey as _e,restSurfaceFromRegistry as Ce}from"./packem_shared/argsFromQuery-BkJXnIpe.mjs";import{decorateResponse as ue,enforceOrigin as ye,handleCorsPreflight as ge,resolveSecurity as Te}from"./packem_shared/decorateResponse-DBIWsRSZ.mjs";import{createShardClient as he}from"./packem_shared/createShardClient-BkZ9FokE.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Oe}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as ve}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as be,routeIdentityResolvers as Fe}from"./packem_shared/composeIdentityResolvers-DwE0Jbww.mjs";const e="0.0.0";export{ee as DEFAULT_LOG_COLUMNS,re as DEFAULT_LOG_LIMIT,f as DEFAULT_REGISTRY_CACHE_TTL_MS,v as HEALTH_PATH,I as HEALTH_READY_PATH,Oe as LOG_ARCHIVE_NOT_CONFIGURED,G as LOG_ARCHIVE_PATH,C as LunoraError,ve as NOOP_EXECUTION_CONTEXT,l as SHARD_REGISTRY_DO_NAME,e as VERSION,K as analyticsEngineSink,pe as applyJurisdiction,Re as applyRestCache,fe as argsFromQuery,b as buildHealthRoutes,le as buildRestRoutes,Q as combineSinks,be as composeIdentityResolvers,s as composeWorker,X as consoleSink,E as createCrossShardRelationCapabilities,x as createDynamicShardRegistry,y as createKvCursorStore,n as createLunoraHandler,g as createMemoryCursorStore,oe as createPipelineLogReader,ae as createQueryCoordinator,xe as createRestRateLimit,he as createShardClient,ie as createStaticShardRegistry,p as createWorker,F as d1Probe,ue as decorateResponse,T as defineExportSink,m as defineRpcEnvelope,P as durableObjectProbe,W as emitLogEvent,Y as emitRpcEvent,ye as enforceOrigin,ge as handleCorsPreflight,w as memoizeIdentity,z as memoizeIdentityPerRequest,se as mergeStrategyForAggregate,j as otlpSink,J as pipelineLogSink,D as presenceProbe,A as r2Sink,_e as readShardKey,Se as requestCarriesCredentials,M as resolveLogArchiveFromEnv,c as resolveLunoraOptions,Te as resolveSecurity,me as resolveShard,Ee as restCacheHeaders,Ce as restSurfaceFromRegistry,Fe as routeIdentityResolvers,h as runExportTap,k as sanitizeChange,B as sentrySink,t as toAirbyteMessages,L as toErrorResponse,a as toFivetranResponse,O as webhookExportSink,Z as webhookSink,R as withFrameworkWorker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as n}from"./LunoraError-ByasbDmd.mjs";import{applyJurisdiction as S,resolveShard as _}from"./applyJurisdiction-8bzZjAPR.mjs";const m="__lunora_shard_registry__",f=3e4,g="https://shard-registry.internal",l=async r=>await r.json(),T=r=>{const w=r.instanceName??m,o=r.cacheTtlMs??f,a=new Map,p=S(r.namespace,r.jurisdiction);let c;const d=()=>(c??=_(p,w),c),h=async(t,e)=>d().fetch(new Request(`${g}${t}`,{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"})),y=async t=>d().fetch(new Request(`${g}${t}`,{method:"GET"}));return{invalidate(t){t===void 0?a.clear():a.delete(t)},async listShardKeys(t){const e=Date.now(),s=a.get(t);if(s&&s.expiresAt>e)return s.shardKeys;const i=await y(`/list?table=${encodeURIComponent(t)}`);if(!i.ok)throw new n(`shard registry /list returned ${String(i.status)}`);const{shardKeys:u}=await l(i);return o>0&&a.set(t,{expiresAt:e+o,shardKeys:u}),u},async register(t,e){const s=await h("/register",{shardKey:e,table:t});if(!s.ok)throw new n(`shard registry /register returned ${String(s.status)}`);a.delete(t)},async snapshot(){const t=await y("/snapshot");if(!t.ok)throw new n(`shard registry /snapshot returned ${String(t.status)}`);const{tables:e}=await l(t);return e},async unregister(t,e){const s=await h("/unregister",{shardKey:e,table:t});if(!s.ok)throw new n(`shard registry /unregister returned ${String(s.status)}`);a.delete(t)}}};export{f as DEFAULT_REGISTRY_CACHE_TTL_MS,m as SHARD_REGISTRY_DO_NAME,T as createDynamicShardRegistry};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as k}from"./LunoraError-ByasbDmd.mjs";import{d as H}from"./method-guard-BbuR0VfS.mjs";const
|
|
1
|
+
import{LunoraError as k}from"./LunoraError-ByasbDmd.mjs";import{d as H}from"./method-guard-BbuR0VfS.mjs";import{resolveShard as R}from"./applyJurisdiction-8bzZjAPR.mjs";const T="/_lunora/health",P="/_lunora/health/ready",_=a=>a==="liveness"?["liveness"]:a==="readiness"?["readiness"]:["liveness","readiness"];class j{#e=new Map;addChecker(e,s,t){this.#e.set(e,{run:s,types:t.type})}async getReport(e){const s=[...this.#e].filter(([,r])=>e===void 0||r.types.includes(e)),t=await Promise.all(s.map(async([r,o])=>[r,await o.run()]));return{healthy:t.every(([,r])=>r.health.healthy),report:Object.fromEntries(t)}}}const N=a=>{const e=new j,s=new Set;for(const t of a)t.critical&&s.add(t.name),e.addChecker(t.name,async()=>{let r;try{r=await t.check()}catch(o){r={healthy:!1,message:o instanceof Error?o.message:"probe failed"}}return{health:{healthy:r.healthy,...r.message===void 0?{}:{message:r.message}}}},{type:_(t.kind)});return{criticalNames:s,registry:e}},S=(a,e)=>{const s=a.includes(":")?a.slice(0,a.indexOf(":")):"probe",t=(e.get(s)??0)+1;return e.set(s,t),t===1?s:`${s}#${String(t)}`},C=(a,e)=>a?"unhealthy":e?"degraded":"healthy",O=(a,e,s,t,r)=>{const o=[];let d=!1,u=!1;const m=new Map;for(const[h,c]of Object.entries(a)){const n=e.has(h),i=c.health.healthy;u=u||!i,d=d||!i&&n;const l=s==="admin"?h:S(h,m);o.push({critical:n,...s==="admin"&&c.health.message!==void 0?{message:c.health.message}:{},name:l,status:i?"up":"down"})}return o.sort((h,c)=>h.name.localeCompare(c.name)),{anyCriticalDown:d,body:{appName:t,appVersion:r,checks:o,status:C(d,u),timestamp:new Date().toISOString()}}},q=a=>{const{appName:e="lunora",appVersion:s="0.0.0",auth:t="public",cacheTtlMs:r,isAdmin:o,resolveProbes:d}=a,u=n=>r!==void 0?r:n==="readiness"?0:t==="public"?5e3:0,m={},h=n=>{if(t==="admin"&&!o(n))throw new k("health endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},c=async(n,i,l)=>{const f=H(n,["GET","HEAD"]);if(f)return f;h(n);const y=u(l);if(y>0){const p=m[l];if(p!==void 0&&Date.now()<p.expiresAt)return Response.json(p.body,{headers:{"cache-control":"no-store"},status:p.down?503:200})}const{criticalNames:w,registry:v}=N(d(i)),{healthy:E,report:A}=await v.getReport(l==="readiness"?"readiness":void 0),{anyCriticalDown:D,body:g}=O(A,w,t,e,s),b=l==="readiness"?!E:D;return y>0&&(m[l]={body:g,down:b,expiresAt:Date.now()+y}),Response.json(g,{headers:{"cache-control":"no-store"},status:b?503:200})};return{[T]:(n,i)=>c(n,i,"aggregate"),[P]:(n,i)=>c(n,i,"readiness")}},$=(a,e,s)=>({check:async()=>{try{return await R(e,s).fetch(new Request("https://shard.internal/_lunora/status",{method:"GET"})),{healthy:!0}}catch{return{healthy:!1,message:"durable object unreachable"}}},critical:!0,name:a}),I=(a,e)=>({check:async()=>{try{return await e.prepare("SELECT 1").first(),{healthy:!0}}catch{return{healthy:!1,message:"d1 query failed"}}},critical:!0,name:a}),B=(a,e)=>({check:()=>e?{healthy:!0}:{healthy:!1,message:"binding not configured"},critical:!1,name:a});export{T as HEALTH_PATH,P as HEALTH_READY_PATH,q as buildHealthRoutes,I as d1Probe,$ as durableObjectProbe,B as presenceProbe};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{resolveShard as s}from"@lunora/platform";const n=new WeakMap,d=o=>{const r=n.get(o);if(r!==void 0)return r;const t=typeof o.jurisdiction=="function"?i=>d(o.jurisdiction(i)):void 0,e=typeof o.getByName=="function"?{get:i=>o.get(i),getByName:i=>o.getByName(i),idForName:i=>o.idFromName(i),jurisdiction:t}:{get:i=>o.get(i),idForName:i=>o.idFromName(i),jurisdiction:t};return n.set(o,e),e},a=(o,r)=>{if(r===void 0)return o;if(typeof o.jurisdiction!="function")throw new TypeError(`@lunora/runtime: Durable Object namespace does not support jurisdiction("${r}") — update @cloudflare/workers-types or remove the jurisdiction option`);return o.jurisdiction(r)},c=(o,r)=>s(d(o),r);export{a as applyJurisdiction,c as resolveShard};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{isLunoraError as rr,toErrorBody as nr}from"@lunora/errors";import{NOOP_EXECUTION_CONTEXT as or}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{O as Re,m as ar,A as sr,R as ir,d as dr,i as ur,s as cr}from"./otlp-resource-B-ByO9qo.mjs";import{LunoraError as s,toErrorResponse as We}from"./LunoraError-ByasbDmd.mjs";import{runExportTap as lr}from"./createKvCursorStore-C24tEuYk.mjs";import{d as me}from"./method-guard-BbuR0VfS.mjs";import{buildHealthRoutes as hr,durableObjectProbe as pr,d1Probe as fr,presenceProbe as Ne}from"./HEALTH_PATH-BpCNEAIa.mjs";import{wrapResolverWithContract as wr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as ma,routeIdentityResolvers as ya}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as mr}from"./LOG_ARCHIVE_PATH-DGsEec3K.mjs";import{o as yr,f as He,a as ue}from"./observability-DYnm-d4g.mjs";import{resolveShard as Se,applyJurisdiction as Je}from"./applyJurisdiction-8bzZjAPR.mjs";import{buildRestRoutes as gr}from"./argsFromQuery-BkJXnIpe.mjs";import{resolveSecurity as Ve,handleCorsPreflight as br,enforceOrigin as Or,decorateResponse as Ue,enforceWebSocketOrigin as Ye}from"./decorateResponse-DBIWsRSZ.mjs";const yt=(e,t)=>{if(e.size<t)return;const r=e.keys().next().value;r!==void 0&&e.delete(r)},Er="::relay::",Tr=(e,t)=>`${e}${Er}${String(t)}`,je=new TextEncoder,_r=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Rr=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let a=0;a<r.length;a+=1)n[a]=r.codePointAt(a)??0;return n},Sr=64,qe=new Map,gt=async e=>{const t=qe.get(e);if(t)return t;yt(qe,Sr);const r=crypto.subtle.importKey("raw",je.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return qe.set(e,r),r},Ar=async(e,t)=>{const r=await gt(e),n=await crypto.subtle.sign("HMAC",r,je.encode(t));return _r(new Uint8Array(n))},vr=async(e,t,r)=>{const n=await gt(e);return crypto.subtle.verify("HMAC",n,r,je.encode(t))},bt="v1",Dr=6e4,kr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Dr),n=`${bt}.${String(r)}`,a=await Ar(e,n);return{expiresAtMs:r,token:`${n}.${a}`}},Ir=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[a,i,c]=n;if(a!==bt||c.length===0)return!1;const l=Number(i);if(!Number.isFinite(l)||l<=r)return!1;let m;try{m=Rr(c)}catch{return!1}return vr(e,`${a}.${i}`,m)},D="/_lunora/admin/auth",Pr={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},I=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new s(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},he=(e,t)=>{const r=e(t);if(r===void 0)throw new s(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},$e=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},ee=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Xe=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},Ze=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new s("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(r[n]=a);return r},Nr={[`${D}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${D}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${D}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${D}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${D}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${D}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${D}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${D}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${D}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${D}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${D}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${D}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${D}/users/create`]:{build:({body:e})=>({data:typeof e.data=="object"&&e.data!==null&&!Array.isArray(e.data)?e.data:void 0,email:I(e,"email"),name:I(e,"name"),password:ee(e,"password"),role:$e(e.role)}),http:"POST",method:"createUser"},[`${D}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new s("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:I(e,"userId")}},http:"POST",method:"updateUser"},[`${D}/users/role`]:{build:({body:e})=>{const t=$e(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new s("`role` is required",{code:"BAD_REQUEST",status:400});return{role:t,userId:I(e,"userId")}},http:"POST",method:"setRole"},[`${D}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:ee(e,"reason"),userId:I(e,"userId")}),http:"POST",method:"banUser"},[`${D}/users/unban`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"unbanUser"},[`${D}/users/password`]:{build:({body:e})=>({newPassword:I(e,"newPassword"),userId:I(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${D}/users/remove`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${D}/users/impersonate`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"impersonateUser"},[`${D}/sessions/revoke`]:{build:({body:e})=>({sessionId:I(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${D}/sessions/revoke-all`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${D}/accounts/unlink`]:{build:({body:e})=>({accountId:I(e,"accountId"),userId:I(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${D}/two-factor/disable`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${D}/passkeys/delete`]:{build:({body:e})=>({passkeyId:I(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${D}/organizations/members/remove`]:{build:({body:e})=>({memberId:I(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${D}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:I(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${D}/organizations/create`]:{build:({body:e})=>({logo:ee(e,"logo"),metadata:Xe(e,"metadata"),name:I(e,"name"),ownerId:ee(e,"ownerId"),slug:ee(e,"slug")}),http:"POST",method:"createOrganization"},[`${D}/organizations/update`]:{build:({body:e})=>({logo:ee(e,"logo"),metadata:Xe(e,"metadata"),name:ee(e,"name"),organizationId:I(e,"organizationId"),slug:ee(e,"slug")}),http:"POST",method:"updateOrganization"},[`${D}/organizations/remove`]:{build:({body:e})=>({organizationId:I(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${D}/organizations/members/add`]:{build:({body:e})=>({organizationId:I(e,"organizationId"),role:ee(e,"role"),userId:I(e,"userId")}),http:"POST",method:"addMember"},[`${D}/organizations/members/invite`]:{build:({body:e})=>({email:I(e,"email"),inviterId:ee(e,"inviterId"),organizationId:I(e,"organizationId"),role:ee(e,"role")}),http:"POST",method:"inviteMember"},[`${D}/organizations/members/role`]:{build:({body:e})=>{const t=$e(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new s("`role` is required",{code:"BAD_REQUEST",status:400});return{memberId:I(e,"memberId"),role:t}},http:"POST",method:"updateMemberRole"},[`${D}/organizations/teams/create`]:{build:({body:e})=>({name:I(e,"name"),organizationId:I(e,"organizationId")}),http:"POST",method:"createTeam"},[`${D}/organizations/teams/update`]:{build:({body:e})=>({name:I(e,"name"),teamId:I(e,"teamId")}),http:"POST",method:"updateTeam"},[`${D}/organizations/teams/remove`]:{build:({body:e})=>({teamId:I(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${D}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:I(e,"teamId"),userId:I(e,"userId")}),http:"POST",method:"addTeamMember"},[`${D}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:I(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${D}/organizations/roles/create`]:{build:({body:e})=>({organizationId:I(e,"organizationId"),permission:Ze(e),role:I(e,"role")}),http:"POST",method:"createOrgRole"},[`${D}/organizations/roles/update`]:{build:({body:e})=>({permission:Ze(e),roleId:I(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${D}/organizations/roles/remove`]:{build:({body:e})=>({roleId:I(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Ur=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof s)throw i;const c=i,l=typeof c.code=="string"?c.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new s("auth admin operation failed",{code:l,status:Pr[l]??500})}},r=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new s(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const c=e.getAuthAdmin();if(c===void 0)throw new s("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const l=c[i.method];if(l===void 0)throw new s(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const m=new URL(a.url),O={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:g=>e.queryParameter(m,g)},A=i.build(O),y=await t(()=>l(A));return Response.json(i.returns==="void"?{ok:!0}:y,{headers:{"content-type":"application/json"},status:200})},n={};for(const[a,i]of Object.entries(Nr))n[a]=c=>r(c,i);return n},qr="__lunora_admin__:getAuthAuditLog",et=e=>typeof e=="string"&&e!==""?e:void 0,tt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,$r=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new s("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const a={},i=et(r.actorId),c=et(r.event),l=tt(r.sinceSeq),m=tt(r.limit);i!==void 0&&(a.actorId=i),c!==void 0&&(a.event=c),l!==void 0&&(a.sinceSeq=l),m!==void 0&&(a.limit=m);let O;try{O=await n.read(a)}catch(y){throw y instanceof s?y:(console.error("[lunora] auth audit read failed:",y),new s("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const A={entries:O};return Response.json(A,{headers:{"content-type":"application/json"},status:200})},rt=500,Lr=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new s("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new s("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new s("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new s("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},xr=(e,t)=>{if(e.length>rt)throw new s(`RPC batch exceeds the ${String(rt)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,a]of e.entries()){const{entry:i,shardKey:c}=Lr(a,n,t),l=r.get(c)??[];l.push(i),r.set(c,l)}return r},ge=1048576,se=async(e,t=ge)=>{if(!e.body)return"";const r=e.body.getReader(),n=new TextDecoder;let a=0,i="";for(;;){const{done:c,value:l}=await r.read();if(c)break;if(l){if(a+=l.byteLength,a>t)throw await r.cancel().catch(()=>{}),new s("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});i+=n.decode(l,{stream:!0})}}return i+=n.decode(),i},Br=async(e,t=ge)=>{if(!e.body)return new ArrayBuffer(0);const r=e.body.getReader(),n=[];let a=0;for(;;){const{done:l,value:m}=await r.read();if(l)break;if(m){if(a+=m.byteLength,a>t)throw await r.cancel().catch(()=>{}),new s("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});n.push(m)}}const i=new Uint8Array(a);let c=0;for(const l of n)i.set(l,c),c+=l.byteLength;return i.buffer},te=async(e,t=ge)=>{try{const r=await se(e,t);return r===""?{}:JSON.parse(r)}catch(r){throw r instanceof s?r:new s("Request body must be valid JSON",{code:"BAD_REQUEST",status:400})}},Cr=new TextEncoder,jr=e=>{const t=JSON.stringify(e),r=Cr.encode(t);let n="";for(const a of r)n+=String.fromCodePoint(a);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Gr=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let l=0;l<r.length;l+=1)n[l]=r.codePointAt(l)??0;const a=JSON.parse(new TextDecoder().decode(n)),i=a.s&&typeof a.s=="object"?a.s:{},c={};for(const[l,m]of Object.entries(i))typeof m=="number"&&Number.isFinite(m)&&(c[l]=m);return{g:typeof a.g=="number"&&Number.isFinite(a.g)?a.g:0,s:c,v:1}}catch{return t}},Kr=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",a=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(a===void 0?{}:{_id:a}),op:n,table:t}},nt=(e,t,r)=>{for(const n of t)e.push(Kr(n));return r!==void 0&&t.length>=r},Mr="/_lunora/admin/export",Fr="/_lunora/admin/import",Qr="/_lunora/admin/sync",zr="/_lunora/admin/connector/sync",Wr="/_lunora/admin/apply",Hr="/_lunora/admin/export-tap/run",Jr=new TextEncoder,Vr=async e=>{let t;try{const a=await se(e);t=a===""?{}:JSON.parse(a)}catch(a){throw a instanceof s?a:new s("Export body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(r.tables===void 0)return{tables:void 0};if(!Array.isArray(r.tables))throw new s("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const n=[];for(const a of r.tables){if(typeof a!="string"||a.length===0)throw new s("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});n.push(a)}return{tables:n}},Yr=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:a,queryCoordinator:i,assertAdmin:c,requireAdminOption:l,resolveForwardContext:m,shardDO:O,streamExportRows:A,streamingImport:y,syncGlobals:g}=e,p=async(S,G)=>{const B=me(S,["POST"]);if(B)return B;const Y=l(S,i,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),N=await Vr(S),{headers:M}=await m(S,G),F=new ReadableStream({async pull(C){const K=X=>{C.enqueue(Jr.encode(`${JSON.stringify(X)}
|
|
2
|
+
`))};try{await A(Y,M,N.tables,K),C.close()}catch(X){C.error(X)}}});return new Response(F,{headers:{"content-type":"application/x-ndjson"},status:200})},w=async(S,G)=>{const B=me(S,["POST"]);if(B)return B;const Y=l(S,i,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),N=await te(S),M=typeof N.cursors=="object"&&N.cursors!==null?N.cursors:{},F=typeof N.limit=="number"?N.limit:void 0,C=typeof N.globalCursor=="number"?N.globalCursor:0,K=Array.isArray(N.tables)?N.tables.filter(Z=>typeof Z=="string"):void 0,{headers:X}=await m(S,G),J=K??a(),oe=await Y.orchestrateCdcSync(O,{cursors:M,headers:X,limit:F,tables:J}),ie=g?await g({limit:F,sinceSeq:C}):void 0;return Response.json({global:ie,shards:oe.shards},{status:200})},T=async(S,G)=>{const B=me(S,["POST"]);if(B)return B;const Y=l(S,i,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),N=await te(S),M=Gr(N.cursor),F=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,C=Array.isArray(N.tables)?N.tables.filter(re=>typeof re=="string"):void 0,{headers:K}=await m(S,G),X=C??a(),J=await Y.orchestrateCdcSync(O,{cursors:M.s,headers:K,limit:F,tables:X}),oe=[],ie={...M.s};let Z=!1;for(const re of J.shards)Z=nt(oe,re.changes??[],F)||Z,ie[re.shardKey]=re.cursor;let pe=M.g;if(g){const re=await g({limit:F,sinceSeq:M.g});Z=nt(oe,re.changes,F)||Z,pe=re.cursor}const be=jr({g:pe,s:ie,v:1}),Ae={changes:oe,hasMore:Z,nextCursor:be};return Response.json(Ae,{status:200})},_=async(S,G)=>{const B=me(S,["POST"]);if(B)return B;const Y=l(S,i,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),N=await te(S),M=(Array.isArray(N.batches)?N.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),F=Array.isArray(N.globalChanges)?N.globalChanges:[],{headers:C}=await m(S,G),K=await Y.orchestrateApplyCdc(O,{batches:M,headers:C}),X=F.length>0&&t?await t({changes:F}):0;return Response.json({applied:K.applied+X,failed:K.failed,ok:K.ok},{status:200})},P=async(S,G)=>{const B=me(S,["POST"]);if(B)return B;c(S);const{headers:Y}=await m(S,G),N=await y(S,Y);return Response.json(N,{headers:{"content-type":"application/json"},status:200})},q=async(S,G)=>{const B=me(S,["POST"]);if(B)return B;const Y=l(S,i,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new s("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const N=await te(S),M=typeof N.sink=="string"?N.sink:void 0,F=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,C=Array.isArray(N.tables)?N.tables.filter(ie=>typeof ie=="string"):void 0;if(M===void 0)throw new s("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const K=n[M];if(K===void 0)throw new s(`Export-tap sink "${M}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:X}=await m(S,G),J=C??a(),oe=await lr({coordinator:Y,cursorStore:r,headers:X,limit:F,shardDO:O,sink:K,tables:J});return Response.json(oe,{headers:{"content-type":"application/json"},status:200})};return{[Wr]:_,[zr]:T,[Mr]:p,[Hr]:q,[Fr]:P,[Qr]:w}},Ot=e=>[],Xr=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?n.push(a):r.push(a);return{globalTables:n,shardLocalTables:r}},Zr=async(e,t,r,n,a,i,c)=>{if(n!==void 0&&a.length===0)return;const l=n===void 0?[]:a,m=n===void 0?Ot():[],O=l.length>0?l:m,A=await t.orchestrateExport(c,{args:{tables:l},headers:r,tables:O});for(const y of A.shards)if(!y.error)for(const g of y.rows??[])i(g)},ot=async(e,t,r,n,a,i)=>{const{globalTables:c,shardLocalTables:l}=Xr(e,n);await Zr(e,t,r,n,l,a,i);const m=e.exportGlobals;if((n===void 0||c.length>0)&&m){const O=n===void 0?[]:c;for await(const A of m({tables:O}))a(A)}},en=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},tn=(e,t,r,n,a)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const i=e[r.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:n}},rn=async(e,t,r)=>{if(!e.body)throw new s("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],a=[],i=new Map;let c=0;const l=e.body.getReader(),m=new TextDecoder;let O="",A=0;const y=g=>{c+=1;const p=g.trim();if(p.length===0)return;const w=en(p,c);if(!w.ok){n.push(w.error);return}const{doc:T,table:_}=w,P=t.resolveTableSharding?.(_);if(P?.mode.kind==="global"){a.push({doc:T,line:c,table:_});return}const q=tn(T,_,P,r,c);if(!q.ok){n.push(q.error);return}const S=i.get(q.shardKey);S?S.rows.push({doc:T,table:_}):i.set(q.shardKey,{rows:[{doc:T,table:_}],shardKey:q.shardKey,startLine:c})};for(;;){const{done:g,value:p}=await l.read();if(g)break;if(p&&(A+=p.byteLength,A>ge))throw await l.cancel().catch(()=>{}),new s("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});O+=m.decode(p,{stream:!0});let w=O.indexOf(`
|
|
3
|
+
`);for(;w!==-1;){const T=O.slice(0,w);O=O.slice(w+1),y(T),w=O.indexOf(`
|
|
4
|
+
`)}}return O.length>0&&y(O),{errors:n,globalRows:a,perShard:i}},at=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},nn=async(e,t,r,n)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:c,perShard:l}=await rn(e,t,a),m={conflicts:0,errors:i,inserted:{}};if(l.size>0){const O=t.queryCoordinator;if(!O)throw new s("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const A=await O.orchestrateImport(n,{batches:[...l.values()],headers:r});at(m,A)}if(c.length>0)if(t.importGlobals){const O=c[0]?.line??1,A=await t.importGlobals({rows:c,startLine:O});at(m,A)}else for(const O of c)m.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:O.line,message:`row targets global table "${O.table}" but no \`importGlobals\` is configured`,table:O.table});return{conflicts:m.conflicts,errors:m.errors,inserted:m.inserted}},Le=e=>typeof e=="object"&&e!==null?e:{},xe=e=>typeof e.kind=="string"?e.kind:"unknown",on=(e,t)=>{let r=Le(t),n=!1;xe(r)==="optional"&&(n=!0,r=Le(r._meta?.inner));const a=xe(r),i=r._meta??{},c={kind:a,name:e,optional:n};if(a==="id"&&typeof i.tableName=="string"&&(c.table=i.tableName),a==="array"){const l=xe(Le(i.inner));l!=="unknown"&&(c.element=l)}return c},an=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>on(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),sn="/_lunora/admin/functions",dn="/_lunora/admin/cron-jobs",un="/_lunora/admin/openapi",cn="/_lunora/admin/openrpc",ln="/_lunora/admin/global/tables",hn="/_lunora/admin/global/table",pn="/_lunora/admin/global/facet",st=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:a,value:i}=n;return[{column:a,value:i}]});return r.length===0?void 0:r},fn=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:{}}),wn=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"}),mn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:a,requireAdminOption:i}=e,c=p=>{if(p.method!=="GET")throw new s("Functions endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),T=Object.entries(w).flatMap(([_,P])=>P.visibility==="internal"||P.kind==="stream"?[]:[{args:an(P.args),kind:P.kind,path:_}]).toSorted((_,P)=>_.path.localeCompare(P.path));return Response.json({functions:T},{headers:{"content-type":"application/json"},status:200})},l=p=>{if(p.method!=="GET")throw new s("Cron-jobs endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),T=Object.entries(w).flatMap(([_,P])=>P.map(q=>({args:q.args,cron:_,functionPath:q.functionPath,name:q.name,shardKey:q.shardKey,workflow:q.workflow}))).toSorted((_,P)=>_.name.localeCompare(P.name));return Response.json({jobs:T},{headers:{"content-type":"application/json"},status:200})},m=p=>{if(p.method!=="GET")throw new s("OpenAPI endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openApiSpec??fn,{headers:{"content-type":"application/json"},status:200})},O=p=>{if(p.method!=="GET")throw new s("OpenRPC endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openRpcSpec??wn,{headers:{"content-type":"application/json"},status:200})},A=async p=>{if(p.method!=="GET")throw new s("Global-tables endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await w.listTables(),{headers:{"content-type":"application/json"},status:200})},y=async p=>{if(p.method!=="GET")throw new s("Global-table endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),T=new URL(p.url),_=a(T,"table");if(_===void 0)throw new s("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const P=await w.readTablePage({...n(p),filters:st(a(T,"filters")),table:_});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},g=async p=>{if(p.method!=="GET")throw new s("Global-facet endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),T=new URL(p.url),_=a(T,"table"),P=a(T,"column");if(_===void 0||P===void 0)throw new s("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const q=a(T,"limit"),S=q===void 0?void 0:Number(q),G=await w.facetColumn({column:P,filters:st(a(T,"filters")),limit:S!==void 0&&Number.isFinite(S)?S:void 0,table:_});return Response.json(G,{headers:{"content-type":"application/json"},status:200})};return{[dn]:l,[sn]:c,[pn]:g,[hn]:y,[ln]:A,[un]:m,[cn]:O}},yn="/_lunora/admin/kv/namespaces",gn="/_lunora/admin/kv/keys",Et="/_lunora/admin/kv/value",Tt=32*1048576,it=60,bn=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=y=>r(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,g)=>{const p=new URL(y.url),w=p.searchParams.get("namespace")??"",T=p.searchParams.get("key")??"";if(w==="")throw new s(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(T==="")throw new s(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:T,namespace:w}},c=async(y,g)=>{if(!(await y.listNamespaces()).some(p=>p.binding===g))throw new s(`Unknown KV namespace binding \`${g}\``,{code:"NOT_FOUND",status:404})},l=async y=>{if(y.method!=="GET")throw new s("KV-namespaces endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return a({namespaces:await n(y).listNamespaces()})},m=async y=>{if(y.method!=="GET")throw new s("KV-keys endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(y),p=new URL(y.url),w=p.searchParams.get("namespace")??"";if(w==="")throw new s("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const T=p.searchParams.get("prefix")??void 0,_=p.searchParams.get("cursor")??void 0,P=p.searchParams.get("limit"),q=P===null?void 0:Number.parseInt(P,10);if(q!==void 0&&(!Number.isInteger(q)||q<1))throw new s("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const S=q===void 0?void 0:Math.min(q,1e3);return await c(g,w),a(await g.listKeys({cursor:_,limit:S,namespace:w,prefix:T}))},O={DELETE:async y=>{const g=n(y),p=i(y,"DELETE");return await c(g,p.namespace),await g.deleteKey(p),a({deleted:!0})},GET:async y=>{const g=n(y),p=i(y,"GET");return await c(g,p.namespace),a(await g.getValue(p))},PUT:async y=>{const g=n(y),p=await t(y,Tt);if(typeof p.namespace!="string"||p.namespace==="")throw new s("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new s("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new s("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<it))throw new s("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const w=Math.floor(Date.now()/1e3)+it;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<w))throw new s("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await c(g,p.namespace),await g.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),a({ok:!0})}},A=y=>{const g=O[y.method];if(!g)throw new s("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(y)};return{[yn]:l,[gn]:m,[Et]:A}},On="/_lunora/migrate",En="/_lunora/admin/pitr",Tn="/_lunora/admin/rank",_n="/_lunora/admin/rankpage",Rn="/_lunora/admin/shard-traffic",Sn=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),An=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),vn=async e=>{let t;try{const n=await se(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof s?n:new s("Migration body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new s("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.functionPath!="string"||!Sn.has(r.functionPath))throw new s("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:r.args??{},functionPath:r.functionPath,table:r.table}},Dn=async e=>{let t;try{const n=await se(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof s?n:new s("Rank body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new s("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.index!="string"||r.index.length===0)throw new s("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof r.partitionKey!="string")throw new s("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof r.rowId!="string"||r.rowId.length===0)throw new s("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(r.sortValues))throw new s("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:r.index,partitionKey:r.partitionKey,rowId:r.rowId,sortValues:r.sortValues,table:r.table}},kn=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new s('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},In=e=>{if(typeof e.table!="string"||e.table.length===0)throw new s("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new s("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new s("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 s("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 s("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Pn=async e=>{let t;try{const a=await se(e);t=a===""?{}:JSON.parse(a)}catch(a){throw a instanceof s?a:new s("Rank page body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};In(r);const n=kn(r.directions);return{cursor:typeof r.cursor=="string"?r.cursor:null,directions:n,index:r.index,partitionKey:typeof r.partitionKey=="string"?r.partitionKey:void 0,table:r.table,take:typeof r.take=="number"?r.take:void 0}},Nn=async e=>{let t;try{const n=await se(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof s?n:new s("Shard-traffic body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new s("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:r.table}},Un=async e=>{const t=await te(e);if(typeof t.functionPath!="string"||!An.has(t.functionPath))throw new s("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new s("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},qn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:a,resolveForwardContext:i,shardDO:c}=e,l=async(g,p)=>{if(g.method!=="POST")throw new s("Migration endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Migration endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await vn(g),{headers:T}=await i(g,p),_=await a.orchestrateMigration(c,{args:w.args,functionPath:w.functionPath,headers:T,table:w.table});return Response.json(_,{headers:{"content-type":"application/json"},status:200})},m=async(g,p)=>{if(g.method!=="POST")throw new s("Rank endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Rank endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await Dn(g),{headers:T}=await i(g,p),_=await a.orchestrateRank(c,{headers:T,index:w.index,partitionKey:w.partitionKey,rowId:w.rowId,sortValues:w.sortValues,table:w.table});return Response.json(_,{headers:{"content-type":"application/json"},status:200})},O=async(g,p)=>{if(g.method!=="POST")throw new s("Rank page endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Rank page endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await Pn(g),{headers:T}=await i(g,p),_=await a.orchestrateRankPage(c,{...w,headers:T});return Response.json(_,{headers:{"content-type":"application/json"},status:200})},A=async(g,p)=>{if(g.method!=="POST")throw new s("Shard-traffic endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Shard-traffic endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await Nn(g),{headers:T}=await i(g,p),_=await a.orchestrateShardTraffic(c,{headers:T,table:w.table});return Response.json(_,{headers:{"content-type":"application/json"},status:200})},y=async(g,p)=>{if(g.method!=="POST")throw new s("PITR endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const w=await Un(g),{headers:T}=await i(g,p),_=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:w.args,functionPath:w.functionPath}),headers:T,method:"POST"});return r(c,w.shardKey??t,_)};return{[On]:l,[En]:y,[Tn]:m,[_n]:O,[Rn]:A}},$n=1,Ln=0,xn=32,Bn=512,Cn=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,jn=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Bn)return;const r=t.split(",");if(!(r.length>xn)){for(const n of r)if(!Cn.test(n.trim()))return;return t}},Gn=e=>{const t=sr(e.headers.get("traceparent"));if(t===void 0)return;const r=jn(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},Kn=(e,t={})=>{const r=Gn(e),n=t.trustInbound===!0?r:void 0,a=Re(8),i=n?.traceId??Re(16),c=yr(t.sampling,n===void 0?a:i),l=c.isTraced&&(n===void 0||n.sampled);return{decision:c,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:l,spanId:a,traceFlags:l?$n:Ln,traceId:i,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},Mn=(e,t)=>{t.traceparent=ar(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Fn=(e,t)=>{let r;return()=>{if(r===void 0){const n=cr(e),a=t===void 0?void 0:t.cf;r=ir(ur(n),dr(n,a))}return r}},Qn="/_lunora/admin/scheduled",zn="/_lunora/admin/scheduled/status",Wn="/_lunora/admin/scheduled/ws",Hn="/_lunora/admin/scheduled/cancel",Jn="/_lunora/admin/scheduled/dead",Vn="/_lunora/admin/scheduled/dead/retry",Yn="/_lunora/admin/scheduled/dead/cancel",Xn=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:a}=e,i=async y=>{if(y.method!=="GET")throw new s("Scheduled-list endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(y).fetch(new Request("https://scheduler.internal/list",{method:"GET"}))},c=async y=>{if(y.method!=="GET")throw new s("Scheduler-status endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(y).fetch(new Request("https://scheduler.internal/status",{method:"GET"}))},l=async y=>{if(y.headers.get("Upgrade")!=="websocket")throw new s("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(y))throw new s("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const g=r();return Se(g,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))},m=async y=>{if(y.method!=="POST")throw new s("Scheduled-cancel endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(y),p=await y.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new s("Scheduled-cancel requires a string `id`",{code:"BAD_REQUEST",status:400});return g.fetch(new Request("https://scheduler.internal/cancel",{body:JSON.stringify({id:p.id}),headers:{"content-type":"application/json"},method:"POST"}))},O=async y=>{if(y.method!=="GET")throw new s("Scheduled dead-letter endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(y).fetch(new Request("https://scheduler.internal/dead",{method:"GET"}))},A=y=>async g=>{if(g.method!=="POST")throw new s("Scheduled dead-letter action requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const p=n(g),w=await g.json().catch(()=>{});if(typeof w?.id!="string"||w.id==="")throw new s("Scheduled dead-letter action requires a string `id`",{code:"BAD_REQUEST",status:400});return p.fetch(new Request(`https://scheduler.internal${y}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))};return{[Hn]:m,[Yn]:A("/dead/cancel"),[Jn]:O,[Vn]:A("/dead/retry"),[Qn]:i,[zn]:c,[Wn]:l}},Zn="/_lunora/admin/storage",eo="/_lunora/admin/storage/url",to="/_lunora/admin/storage/buckets",ro=10080*60,no=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:a,requireAdminOption:i,storage:c}=e,l=w=>{const T=n(w,"key");if(T===void 0)throw new s("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return T},m=async w=>{const T=i(w,c.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),_=new URL(w.url),P=await T(n(_,"prefix"),{bucket:n(_,"bucket"),cursor:n(_,"cursor"),...r(w)});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},O=w=>{if(w.method!=="GET")throw new s("Storage-buckets endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(w),Response.json({buckets:c.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})},A=async w=>{const T=i(w,c.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),_=new URL(w.url),P=l(_);return await T(P,{bucket:n(_,"bucket")}),Response.json({deleted:!0,key:P},{headers:{"content-type":"application/json"},status:200})},y=async w=>{const T=i(w,c.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),_=new URL(w.url),P=l(_),q=await a(w),S=w.headers.get("content-type"),G=S===null||S===""?void 0:S,B=await T(P,q,{bucket:n(_,"bucket"),contentType:G});return Response.json(B,{headers:{"content-type":"application/json"},status:200})},g=async w=>{switch(w.method){case"DELETE":return A(w);case"GET":return m(w);case"POST":case"PUT":return y(w);default:throw new s("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async w=>{if(w.method!=="GET")throw new s("Storage URL endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const T=i(w,c.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),_=new URL(w.url),P=l(_),q=Number(n(_,"expiresIn")??""),S=Number.isFinite(q)&&q>0?Math.min(q,ro):void 0,G=await T(P,{bucket:n(_,"bucket"),expiresInSeconds:S});return Response.json({key:P,url:G},{headers:{"content-type":"application/json"},status:200})};return{[to]:O,[Zn]:g,[eo]:p}},oo=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},ao={mtls:e=>oo(e,"tlsClientAuth","certVerified")==="SUCCESS"},so=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:Object.entries(ao).find(([t])=>t===e)?.[1]??(()=>!1),io=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.'))}},uo="/_lunora/admin/vector/indexes",co="/_lunora/admin/vector/query",lo=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async i=>{if(i.method!=="GET")throw new s("Vector-indexes endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const c=r(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await c.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async i=>{if(i.method!=="POST")throw new s("Vector-query endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const c=r(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(c.queryIndex===void 0)throw new s("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const l=await t(i);if(typeof l.name!="string"||l.name==="")throw new s("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof l.text!="string"||l.text==="")throw new s("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(l.topK!==void 0&&(typeof l.topK!="number"||!Number.isInteger(l.topK)||l.topK<1))throw new s("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const m=await c.queryIndex({name:l.name,text:l.text,topK:l.topK});return Response.json(m,{headers:{"content-type":"application/json"},status:200})};return{[uo]:n,[co]:a}},ho="/_lunora/admin/workflows/instances",po="/_lunora/admin/workflows/instance",fo="/_lunora/admin/workflows/status",wo={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},mo=e=>e!==null&&Object.hasOwn(wo,e)?e:void 0,dt=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Be=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new s(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},ut=()=>{throw new s("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},yo=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(c,l,m)=>{if(c.method!=="GET")throw new s("Workflows instances endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const O=r(l);if(!O)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const A=Be(m,"name"),y=mo(m.searchParams.get("status"));return Response.json(await O.listInstances({page:dt(m,"page"),perPage:dt(m,"perPage"),status:y,workflowName:A}))},a=async(c,l,m)=>{if(c.method!=="GET")throw new s("Workflows instance endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const O=r(l);return O?Response.json(await O.getInstance({instanceId:Be(m,"id"),workflowName:Be(m,"name")})):ut()},i=async(c,l)=>{if(c.method!=="POST")throw new s("Workflows status endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const m=r(l);if(!m)return ut();const O=await c.json().catch(()=>{});if(typeof O?.name!="string"||O.name===""||typeof O.id!="string"||O.id==="")throw new s("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:A}=O;if(A!=="pause"&&A!=="resume"&&A!=="terminate")throw new s("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await m.setInstanceStatus({action:A,instanceId:O.id,workflowName:O.name}))};return{[po]:a,[ho]:n,[fo]:i}},go=new TextEncoder,ct="/_lunora/rpc",bo="/_lunora/rpc-batch",Oo="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:Fn(e,t),...r===void 0?{}:{waitUntil:r}}),lt=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},ht=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ce=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const a=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(a)?void 0:a,scheme:n.protocol.replace(":",""),userAgent:r}},pt="/_lunora/voice/",Eo="/_lunora/scheduler/dispatch",To="/_lunora/admin/cron-jobs/run",_o="/_lunora/admin/ws-token",Ro="/_lunora/admin/",So="/_lunora/migrate",Ao="/_lunora/status",vo=e=>e.startsWith(Ro)||e===So,Do=new Set(["1","enabled","on","true","yes"]),ko=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},Io="/api/auth",Po="__lunora_admin__:recordAuthEvent",No="__lunora_admin__:listPushSubscriptions",Uo=["/sign-in","/sign-up","/callback"],qo=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return Uo.some(a=>n===a||n.startsWith(`${a}/`))},Te=(e,t,r,n)=>{const a=rr(r),i=a?r.code:"INTERNAL_SERVER_ERROR",c=a?r.status:500,l=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:i,message:l,status:c},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},$o=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},ft=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Lo=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ce=async(e,t,r)=>{const n={"content-type":"application/json"},a=e.headers.get("authorization"),i=e.headers.get("cookie"),c=e.headers.get("x-d1-bookmark"),l=e.headers.get("x-lunora-mutation-id"),m=e.headers.get("x-lunora-client-id"),O=e.headers.get("x-lunora-client-seq");a&&(n.authorization=a),i&&(n.cookie=i),c&&(n["x-d1-bookmark"]=c),l&&(n["x-lunora-mutation-id"]=l),m&&(n["x-lunora-client-id"]=m),O&&(n["x-lunora-client-seq"]=O);const A=e.headers.get("cf-connecting-ip");if(A&&(n["x-lunora-client-ip"]=A),!r)return{claims:null,headers:n,identity:null,userId:null};const y=await r(e,t);if(!y||typeof y.userId!="string"||y.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=y.userId;const g=$o(y);g!==void 0&&(n["x-lunora-identity-exp"]=String(g));const{userId:p,...w}=y,T=Object.keys(w).length>0?w:null;return T&&(n["x-lunora-identity"]=JSON.stringify(T)),{claims:T,headers:n,identity:y,userId:p}},xo=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Bo=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new s("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 s("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new s("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!xo.has(r.kind))throw new s("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new s("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new s("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Co=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},wt=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new s("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new s(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},jo=async e=>{const t=await se(e);let r;try{r=JSON.parse(t)}catch{throw new s("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new s("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new s("RPC `args` must be an object",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new s("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=r,i=Bo(a.fanOut),c=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const l=c.table;if(typeof l=="string"&&l!==i.table)throw new s("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});c.table=i.table}return{args:c,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},ae=async(e,t,r)=>Se(e,t).fetch(r),_e=new Map,Go=5e3,Ko=4096,Mo=async(e,t)=>{const r=Date.now(),n=_e.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&_e.delete(t);let a=0;try{const i=await Se(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const c=(await i.json()).relayCount;typeof c=="number"&&c>0&&(a=Math.floor(c))}}catch{a=0}return yt(_e,Ko),_e.set(t,{expiresMs:r+Go,relayCount:a}),a},Fo=(e,t)=>{if(!(e===null||typeof e!="object")){for(const[r,n]of Object.entries(e))if(n===t)return r}},Ge=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let a=0;a<r;a+=1){const i=a<e.length?e.codePointAt(a)??0:0,c=a<t.length?t.codePointAt(a)??0:0;n|=i^c}return n===0},Qo=async(e,t,r)=>{if(e.length===0||r.length===0)return!1;const n=new TextEncoder,a=await crypto.subtle.importKey("raw",n.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",a,n.encode(t)),c=new Uint8Array(i);let l="";for(const O of c)l+=String.fromCodePoint(O);const m=btoa(l).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return Ge(m,r)},mt=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...a]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:Ge(t,a.join(" ").trim())},zo=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await Ir(t,n)?!0:r?!1:Ge(t,n)},Wo=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return fr(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Ne(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Ne(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Ne(`hyperdrive:${e}`,!0)},_t=e=>{const t=so(e.trustInboundTraceContext),r=io(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",a=wr(e.resolveIdentity,e.identity),i=Je(e.shardDO,e.jurisdiction),c=e.schedulerDO===void 0?void 0:Je(e.schedulerDO,e.jurisdiction);let l;const m=()=>e.adminToken??l;let O;const A=()=>e.requireEphemeralWsToken??O??!1,y=o=>{const d=o??{};if(O===void 0&&e.requireEphemeralWsToken===void 0){const u=d.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof u=="string"&&u.length>0&&(O=Do.has(u.trim().toLowerCase()))}if(l!==void 0||e.adminToken!==void 0)return;const h=d.LUNORA_ADMIN_TOKEN;typeof h=="string"&&h.length>0&&(l=h)},g=new WeakSet,p=o=>mt(o,m())||g.has(o),w=async(o,d)=>{const h=await ce(o,d,e.resolveIdentity);if(g.has(o)&&h.headers.authorization===void 0){const u=m();u!==void 0&&(h.headers.authorization=`Bearer ${u}`)}return h};let T=!1;const _=o=>{if(!e.allowUnauthenticatedShardAccess){const d=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new s(`${o} access is default-denied: configure \`${d}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}T||(T=!0,console.warn([`[lunora] SECURITY: serving ${o} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},P=qn({defaultShard:n,forwardToShard:ae,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:w,shardDO:i}),q=async(o,d,h,u,f)=>{if(e.authorizeShard&&!await e.authorizeShard(null,h))throw new s("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});const b={"content-type":"application/json","x-lunora-system":"1"};f?.userId!==void 0&&f.userId.length>0&&(b["x-lunora-userid"]=f.userId),f?.identity!==void 0&&f.identity.length>0&&(b["x-lunora-identity"]=f.identity),u!==void 0&&u.length>0&&(b["x-lunora-mutation-id"]=u);const R=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:d,functionPath:o}),headers:b,method:"POST"});return ae(i,h,R)},S=async(o,d,h,u)=>{const f=h?.[o];if(!f||typeof f.create!="function")throw new s(`${u} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});await f.create({params:d})},G=async(o,d,h)=>S(o,d.args??{},h,`cron job "${d.name}"`),B=async(o,d)=>{if(o.workflow){await G(o.workflow,o,d);return}if(o.functionPath===void 0)throw new s(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const h=await q(o.functionPath,o.args??{},o.shardKey??n);if(!h.ok)throw new s(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(h.status)}`,{code:"CRON_JOB_FAILED",status:500})},Y=async(o,d,h,u)=>{const f=e.cronJobs?.[o];if(f)for(const b of f)try{await B(b,d)}catch(R){h.push(u(R))}},N=async(o,d)=>{if(!p(o))throw new s("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(o.method!=="POST")throw new s("cron-jobs run endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!e.cronJobs)throw new s("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const h=await te(o),u=typeof h.name=="string"?h.name:"";if(u==="")throw new s("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const f=Object.values(e.cronJobs).flat().find(b=>b.name===u);if(!f)throw new s(`no cron job named "${u}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await B(f,d),Response.json({name:u,ran:!0},{status:200})},M=async o=>{const d=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!d||!c||typeof o.id!="string")return;const h=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await c.get(c.idFromName(h)).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:d}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},F=async(o,d)=>{if(o.method!=="POST")throw new s("Scheduler dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const h=await se(o),u=d??{},f=typeof u.LUNORA_SCHEDULER_SECRET=="string"?u.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof u.LUNORA_ADMIN_TOKEN=="string"?u.LUNORA_ADMIN_TOKEN:void 0),R=o.headers.get("x-lunora-scheduler-signature");let E=!1;if(R&&f?E=await Qo(f,h,R):b&&(E=mt(o,b)),!E)throw new s("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let v;try{v=JSON.parse(h)}catch{throw new s("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const k=v??{},U=k.args??{};if(typeof k.workflow=="string"&&k.workflow.length>0)return await S(k.workflow,U,d,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof k.functionPath!="string"||k.functionPath.length===0)throw new s("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const $=typeof k.shardKey=="string"&&k.shardKey.length>0?k.shardKey:n,L=typeof k.id=="string"&&k.id.length>0?k.id:void 0,x=ko(o),W=await q(k.functionPath,U,$,L,x);return await M(k),W},C=o=>{if(!p(o))throw new s("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},K=(o,d,h)=>{if(C(o),d===void 0)throw new s(h.message,{code:h.code,status:400});return d},X=$r({assertAdmin:C,getReader:()=>e.authAuditReader}),J=async(o,d)=>{C(o);const h=e.notifySubscriptionStore;if(h===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const u=d?.kind,f=d?.userId,b=d?.limit,R=u==="fcm"||u==="web-push"?u:void 0,E=typeof f=="string"&&f!==""?f:void 0,v=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,k=v>0?Math.min(v,1e3):1e3,U=(await h.list({kind:R,limit:k,userId:E})).filter($=>R!==void 0&&$.kind!==R?!1:E===void 0||($.userId??null)===E).map(({keys:$,token:L,...x})=>x);return Response.json({subscriptions:U},{headers:{"content-type":"application/json"},status:200})},oe=async(o,d)=>{if(!d.fanOut){if(d.functionPath===qr)return X(o,d.args??{});if(d.functionPath===No)return J(o,d.args)}},ie=Yr({applyGlobals:e.applyGlobals,assertAdmin:C,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>Ot(),queryCoordinator:e.queryCoordinator,requireAdminOption:K,resolveForwardContext:w,shardDO:i,streamExportRows:(o,d,h,u)=>ot(e,o,d,h,u,i),streamingImport:(o,d)=>nn(o,e,d,i),syncGlobals:e.syncGlobals}),Z=(o,d)=>{const h=o.searchParams.get(d);return h===null||h===""?void 0:h},pe=o=>{const d=new URL(o.url),h=d.searchParams.get("limit"),u=d.searchParams.get("offset"),f=h===null?void 0:Number.parseInt(h,10),b=u===null?void 0:Number.parseInt(u,10);return{limit:f!==void 0&&Number.isFinite(f)&&f>=0?f:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},be=()=>{if(c===void 0)throw new s("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return c},Ae=Xn({checkWsAdmin:async o=>p(o)||zo(o,m(),A()),requireSchedulerNamespace:be,resolveSchedulerStub:o=>(C(o),Se(be(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),re=yo({assertAdmin:C,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Rt=no({assertAdmin:C,parsePaging:pe,queryParameter:Z,readBodyBytes:Br,requireAdminOption:K,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),St=lo({readJsonBody:te,requireAdminOption:K,vectorIntrospector:e.vectorIntrospector}),At=bn({kvIntrospector:e.kvIntrospector,readJsonBody:te,requireAdminOption:K}),vt=mr({logArchive:e.logArchive,readJsonBody:te,requireAdminOption:K}),Dt=mn({assertAdmin:C,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:Z,requireAdminOption:K}),kt=o=>{const d=[],h=i??o?.SHARD;if(h!==void 0&&d.push(pr("durable-object:default",h,n)),e.health?.disableBindingProbes!==!0)for(const[u,f]of Object.entries(o??{})){const b=Wo(u,f);b!==void 0&&d.push(b)}for(const u of e.health?.probes??[])d.push(u);return d},It=hr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:kt}),Pt=async(o,d,h)=>{const{claims:u,headers:f,userId:b}=await ce(o,d,a),R=async(E,v={})=>{const k=E.__lunoraRef;if(typeof k!="string")throw new s("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const U=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:v,functionPath:k}),headers:{...f,"x-lunora-system":"1"},method:"POST"}),$=await ae(i,n,U),L=await $.json();if(L.error)throw new s(L.error.message??"shard RPC failed",{code:L.error.code??"INTERNAL",status:$.status});return L.result};return{auth:{getIdentity:()=>Promise.resolve(u),userId:b},cache:h.cache,fetch:globalThis.fetch.bind(globalThis),runAction:R,runMutation:R,runQuery:R}},Nt=async(o,d,h)=>{if(!e.httpRouter)return;const u=await Pt(o,d,h);try{return await e.httpRouter.fetch(o,{...d,__lunoraCtx:u},h)}catch(f){return console.error("[lunora] httpRouter (SSR) handler threw:",f),new Response("Internal Server Error",{status:500})}},Ut=async(o,d,h)=>{if(o.headers.get("Upgrade")!=="websocket")throw new s("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const u=Ye(o,de);if(u)return u;const f=h.searchParams.get("shard")??n,{headers:b,identity:R}=await ce(o,d,a);if(e.authorizeShard){if(!await e.authorizeShard(R,f))throw new s("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else f!==n&&_("shard");const E=new Headers(o.headers),v=[...E.keys()];for(const x of v)x.startsWith("x-lunora-")&&E.delete(x);const k=b["x-lunora-userid"],U=b["x-lunora-identity"],$=b["x-lunora-identity-exp"];k!==void 0&&E.set("x-lunora-userid",k),U!==void 0&&E.set("x-lunora-identity",U),$!==void 0&&E.set("x-lunora-identity-exp",$);const L=Fo(d,e.shardDO);if(L!==void 0){E.set("x-lunora-shard-binding",L);const x=await Mo(i,f);if(x>0){const W=Tr(f,Math.floor(Math.random()*x));return ae(i,W,new Request(o,{headers:E}))}}return ae(i,f,new Request(o,{headers:E}))},qt=async(o,d,h)=>{const{voiceAgents:u}=e;if(u===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 f=Ye(o,de);if(f)return f;let b;try{b=decodeURIComponent(h.pathname.slice(pt.length))}catch{return new Response("Unknown voice agent",{status:404})}const R=Object.hasOwn(u,b)?u[b]:void 0;if(R===void 0)return new Response("Unknown voice agent",{status:404});const E=h.searchParams.get("threadKey");if(E===null||E.length===0)return new Response("Missing threadKey",{status:400});const{headers:v,identity:k}=await ce(o,d,a);if(e.authorizeShard){if(!await e.authorizeShard(k,E))return new Response("Forbidden",{status:403})}else _("shard");const U=new Headers(o.headers);U.delete("x-lunora-userid"),U.delete("x-lunora-identity"),U.delete("x-lunora-identity-exp");const $=v["x-lunora-userid"],L=v["x-lunora-identity"],x=v["x-lunora-identity-exp"];return $!==void 0&&U.set("x-lunora-userid",$),L!==void 0&&U.set("x-lunora-identity",L),x!==void 0&&U.set("x-lunora-identity-exp",x),ae(R,E,new Request(o,{headers:U}))},$t=async(o,d,h)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(h,o.table,d))throw new s("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(d.startsWith("__lunora_relation__:"))throw new s("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 s("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});_("fan-out")},Oe=async(o,d)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await $t(o.fanOut,o.functionPath,d);return}if(e.authorizeShard){const h=o.shardKey??n;if(!await e.authorizeShard(d,h))throw new s("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else o.shardKey!==void 0&&o.shardKey!==n&&_("shard")}},ve=async(o,d,h,u,f,b)=>{const R=Date.now(),{observability:E,sampling:v}=e,k=Ce(o),{decision:U,ignoredUpstream:$,trace:L}=Kn(o,{...v===void 0?{}:{sampling:v},trustInbound:t(o)});$&&r();const x={...f,"x-lunora-sample-errors":U.keepErrors?"1":"0"};Mn(L,x);const W=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:h,functionPath:d}),headers:x,method:"POST"});try{const j=await ae(i,u,W);return ue(E,{...k,...ht(L),durationMs:Date.now()-R,functionPath:d,ok:j.ok,shardKey:u,...j.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(j.status)}`,status:j.status}}},b,void 0,{isTraced:L.sampled,keepErrors:U.keepErrors}),j}catch(j){throw ue(E,{...k,...ht(L),...Te(d,Date.now()-R,j,{shardKey:u})},b,void 0,{isTraced:L.sampled,keepErrors:U.keepErrors}),j}},Lt=o=>{if(o.fanOut&&o.shardKey)throw new s("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!o.fanOut&&o.functionPath.startsWith("__lunora_relation__:"))throw new s("`__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 s("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},xt=async(o,d,h)=>{if(o.method!=="POST")throw new s("RPC endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const u=await jo(o);Co(d,u),Lt(u);const f=await oe(o,u);if(f!==void 0)return f;const{headers:b,identity:R}=await ce(o,d,a);await Oe(u,R);const E=wt(u,e);{const v=Date.now(),{observability:k}=e,U=Ce(o),$=Ee(d,o,h&&(W=>h.waitUntil?.(W)));if(u.fanOut){const W=e.queryCoordinator;if(!W)throw new s("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const j=await W.fanOut(i,{args:u.args??{},fanOut:u.fanOut,functionPath:u.functionPath,headers:b});return ue(k,{durationMs:Date.now()-v,fanOut:{failed:j.failed,shards:j.ok+j.failed,table:u.fanOut.table},functionPath:u.functionPath,...U,ok:!0},$),Response.json(j,{headers:{"content-type":"application/json"},status:200})}catch(j){throw ue(k,{...Te(u.functionPath,Date.now()-v,j,{fanOut:{table:u.fanOut.table}}),...U},$),j}}const L=u.shardKey??n,x=()=>ve(o,u.functionPath,u.args??{},L,b,$);return E&&e.x402Charge?e.x402Charge(o,{functionPath:u.functionPath,price:E.price},x,lt(h)):x()}},Bt=async(o,d,h)=>{if(o.method!=="POST")throw new s("RPC batch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const u=await se(o);let f;try{f=JSON.parse(u)}catch{throw new s("RPC batch body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(typeof f!="object"||f===null||Array.isArray(f))throw new s("RPC batch body must be an object",{code:"BAD_REQUEST",status:400});const{calls:b}=f;if(!Array.isArray(b))throw new s("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:E}=await ce(o,d,a),v=xr(b,n);for(const Q of v.values())for(const z of Q)if(e.functions?.[z.functionPath]?.x402)throw new s(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${ct}`,{code:"BAD_REQUEST",status:400});await Promise.all([...v.entries()].flatMap(([Q,z])=>z.map(ne=>Oe({functionPath:ne.functionPath,shardKey:Q},E))));const{observability:k}=e,U=Ee(d,o,h&&(Q=>h.waitUntil?.(Q))),$=Ce(o),L=[],x=[],W=(Q,z,ne,le)=>({body:{error:{code:ne,message:le}},id:Q.id,status:z}),j=(Q,z,ne,le,fe)=>{for(const H of Q)ue(k,fe(H),U),L.push(W(H,z,ne,le))},Xt=(Q,z,ne,le,fe)=>{for(const H of Q){const we=le.get(H.id)??fe,ye=we<400;ue(k,{durationMs:ne,functionPath:H.functionPath,...$,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(we)}`,status:we}}},U)}};await Promise.all([...v.entries()].map(async([Q,z])=>{const ne=new Headers(R);ne.set("content-type","application/json");const le=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:ne,method:"POST"}),fe=Date.now();let H;try{H=await ae(i,Q,le)}catch(V){const Pe=Date.now()-fe,{body:ze}=nr(V,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});j(z,502,ze.code,ze.message,tr=>({...Te(tr.functionPath,Pe,V,{shardKey:Q}),...$}));return}const we=Date.now()-fe,ye=H.headers.get("x-d1-bookmark");ye&&x.push(ye);let ke;try{ke=await H.json()}catch{const V=`shard batch returned a non-JSON response (${String(H.status)})`;j(z,H.status,"SHARD_ERROR",V,Pe=>({durationMs:we,error:{code:"SHARD_ERROR",message:V,status:H.status},functionPath:Pe.functionPath,...$,ok:!1,shardKey:Q}));return}const Ie=Array.isArray(ke.results)?ke.results:[],Zt=new Map(Ie.map(V=>[V.id,V.status??H.status])),er=new Set(Ie.map(V=>V.id));Xt(z,Q,we,Zt,H.status),L.push(...Ie);for(const V of z)er.has(V.id)||L.push(W(V,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(V.id)}`))}));const Fe={"content-type":"application/json"},[Qe]=x;return x.length===1&&Qe!==void 0&&(Fe["x-d1-bookmark"]=Qe),Response.json({results:L},{headers:Fe,status:200})},Ct=async(o,d,h,u={},f={})=>{try{const b=h.__lunoraRef;if(typeof b!="string")throw new s("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:R,identity:E}=await ce(o,d,a);await Oe({functionPath:b,shardKey:f.shardKey},E);const v=f.shardKey??n,k=Ee(d,o,f.waitUntil);return await ve(o,b,u,v,R,k)}catch(b){return We(b)}},jt=1e3,Gt=async(o,d)=>{const h=e.backupRetain;if(h===void 0||h<=0)return;const u=[];let f;for(let R=0;R<jt;R+=1){const E=await o.list({cursor:f,prefix:d});for(const v of E.objects)v.key.endsWith(".manifest.json")&&u.push(v.key);if(!E.truncated||E.cursor===void 0)break;f=E.cursor}const b=u.toSorted((R,E)=>E.localeCompare(R)).slice(h);await Promise.all(b.flatMap(R=>{const E=R.slice(0,-14);return[o.delete(R),o.delete(E)]}))},Kt=async o=>{const d=e.backupStore,h=e.queryCoordinator;if(!d)throw new s("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!h)throw new s("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const u=m();if(!u||u.length===0)throw new s("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const f={authorization:`Bearer ${u}`,"content-type":"application/json"},b=e.backupTables;let R=0,E=0;const v=[];await ot(e,h,f,b,W=>{const j=`${JSON.stringify(W)}
|
|
5
|
+
`;R+=1,E+=go.encode(j).byteLength,v.push(j)},i);const k=e.backupPrefix??"backups/",U=new Date(o.scheduledTime).toISOString(),$=`${k}lunora-backup-${U.replaceAll(/[.:]/gu,"-")}.ndjson`,L=`${$}.manifest.json`;await d.put($,new Blob(v,{type:"application/x-ndjson"}),{httpMetadata:{contentType:"application/x-ndjson"}});const x={bytes:E,createdAt:U,cron:o.cron,file:$,id:U,rows:R,scheduledTime:o.scheduledTime,...b?{tables:b.join(",")}:{}};await d.put(L,`${JSON.stringify(x,void 0,2)}
|
|
6
|
+
`,{httpMetadata:{contentType:"application/json"}}),await Gt(d,k)},Ke=async(o,d,h)=>{const{observability:u}=e,f=Date.now(),b=Re(16),R=Re(8),E=ft(d);try{const v=await h();return ue(u,{durationMs:Date.now()-f,functionPath:o,ok:!0,spanId:R,traceId:b},E),v}catch(v){throw ue(u,{...Te(o,Date.now()-f,v,{}),spanId:R,traceId:b},E),v}finally{He(u,E)}},Mt=async(o,d,h)=>{y(d);const u=[],f=E=>E instanceof Error?E:new Error(String(E)),b=e.crons?.[o.cron];if(b)try{await b(o,d,h)}catch(E){u.push(f(E))}if(await Y(o.cron,d,u,f),e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron)try{await Kt(o)}catch(E){u.push(f(E))}const[R]=u;if(u.length===1&&R)throw R;if(u.length>1)throw new AggregateError(u,`scheduled("${o.cron}") had ${String(u.length)} failure(s)`)},Ft=async(o,d)=>{try{const h=o??{},u=e.adminToken??(typeof h.LUNORA_ADMIN_TOKEN=="string"?h.LUNORA_ADMIN_TOKEN:void 0);if(!u||u.length===0)return;const f=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:{outcome:d},functionPath:Po}),headers:{authorization:`Bearer ${u}`,"content-type":"application/json"},method:"POST"});await ae(i,n,f)}catch{}},Qt=async(o,d,h,u)=>{if(!e.authHandler)return;const f=await e.authHandler(o);if(!f)return;const b=e.authBasePath??Io;return qo(h.pathname,b)&&u.waitUntil?.(Ft(d,f.status>=400?"fail":"ok")),f},zt=async({args:o,env:d,functionPath:h,request:u,shardKey:f,waitUntil:b})=>{const R={functionPath:h,...f===void 0?{}:{shardKey:f}},{headers:E,identity:v}=await ce(u,d,a);await Oe(R,v);const k=f??n,U=Ee(d,u,b),$=()=>ve(u,h,o,k,E,U),L=wt(R,e);return L&&e.x402Charge?e.x402Charge(u,{functionPath:h,price:L.price},$,lt({waitUntil:b})):$()},Wt=gr({functions:e.functions??{},invoke:zt,readJsonBody:te,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),De=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Ht={[Ao]: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"}}),[Oo]:(o,d,h)=>Ut(o,d,h),[ct]:(o,d,h,u)=>xt(o,d,u),[bo]:(o,d,h,u)=>Bt(o,d,u),[Eo]:(o,d)=>F(o,d),[To]:(o,d)=>N(o,d),[_o]:async o=>{if(o.method!=="POST")throw new s("ws-token endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});C(o);const d=m();if(d===void 0)throw new s("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const h=await kr(d);return Response.json(h,{headers:{"cache-control":"no-store"}})},...P,...ie,...Ae,...re,...Rt,...St,...At,...vt,...Dt,...It,...Wt,...Ur({assertAdmin:C,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:Z,readJsonBody:te})};let de=Ve(e.security),Me=!1;const Jt=o=>{Me||(Me=!0,de=Ve(e.security,o??{}))},Vt=async(o,d)=>{if(!(e.adminGate===void 0||!vo(d)))try{await e.adminGate(o)&&g.add(o)}catch{}},Yt=async(o,d,h)=>{const u=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const E=Number(o.headers.get("content-length")??""),v=u.pathname===Et?Tt:ge;if(Number.isFinite(E)&&E>v)throw new s("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const f=await Qt(o,d,u,h);if(f)return f;if(De){const E=`${o.method} ${u.pathname}`,v=De[E]??De[u.pathname];if(v)return v(o,d,h)}const b=Ht[u.pathname];return b?(await Vt(o,u.pathname),b(o,d,u,h)):e.voiceAgents!==void 0&&u.pathname.startsWith(pt)?qt(o,d,u):await Nt(o,d,h)||new Response("Not found",{status:404})};return{async fetch(o,d,h){e.passThroughOnException&&h.passThroughOnException?.(),Jt(d),y(d);const u=br(o,de);if(u)return u;const f=Or(o,de);if(f)return Ue(f,o,de);try{const b=await Yt(o,d,h);return Ue(b,o,de)}catch(b){return Ue(We(b),o,de)}finally{He(e.observability,ft(h))}},async queue(o,d,h){await Ke(`queue:${Lo(o)}`,h,async()=>{await e.queue?.(o,d,h)})},async scheduled(o,d,h){await Ke(`cron:${o.cron}`,h,async()=>{await Mt(o,d,h)})},serverQuery:Ct}},Ho=e=>_t(e),Jo=e=>typeof e=="function"?{fetch:e}:e,Vo=e=>!!(e.crons??e.cronJobs??e.backupCron),la=(e,t)=>{const r=Jo(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=c=>{const l=Ho({...c,httpRouter:r});return n!==void 0&&!Vo(c)?{...l,scheduled:async(m,O,A)=>{await n(m,O,A)}}:l};if(typeof t!="function")return a(t);const i=t;return{fetch:(c,l,m)=>a(i(l)).fetch(c,l,m),queue:(c,l,m)=>a(i(l)).queue?.(c,l,m)??Promise.resolve(),scheduled:(c,l,m)=>a(i(l)).scheduled(c,l,m),serverQuery:(c,l,m,O,A)=>a(i(l)).serverQuery(c,l,m,O,A)}},Yo=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new s("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},ha=(e={})=>(t,r,n)=>_t(Yo(e,r)).fetch(t,r,n??or),pa=e=>e;export{qr as GET_AUTH_AUDIT_LOG_OP,or as NOOP_EXECUTION_CONTEXT,ma as composeIdentityResolvers,Ho as composeWorker,ha as createLunoraHandler,_t as createWorker,pa as defineRpcEnvelope,Mo as probeRelayCount,Yo as resolveLunoraOptions,ya as routeIdentityResolvers,la as withFrameworkWorker};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as M}from"./LunoraError-ByasbDmd.mjs";import{resolveShard as C}from"./applyJurisdiction-uRQLx282.mjs";const ye=t=>({listShardKeys(e){return t[e]??[]}}),me=t=>{if(t.kind==="count")return{kind:"sum"};if(t.kind==="scalar"){if(t.op==="count"||t.op==="sum")return{kind:"sum"};if(t.op==="max")return{kind:"max"};if(t.op==="min")return{kind:"min"};throw new M('aggregate({ op: "avg" }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})}const e=t.agg?.op??"count";if(e==="count"||e==="sum")return{kind:"groupBy",op:"sum"};if(e==="max")return{kind:"groupBy",op:"max"};if(e==="min")return{kind:"groupBy",op:"min"};throw new M('groupBy({ agg: { op: "avg" } }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})},q=16,F=5e3,m=t=>t!==null&&typeof t=="object"&&"result"in t?t.result:t,B=t=>{const e=t??{};return{changed:typeof e.changed=="number"?e.changed:0,processed:typeof e.processed=="number"?e.processed:0,status:typeof e.status=="string"?e.status:void 0}},I=(t,e)=>t?"failed":e?"in_progress":"completed",R=t=>{const e=[];let s=0,o=0,r=0,a=0,n=!1,i=!1;for(const u of t){if(u.kind==="err"){o+=1,e.push({error:{message:u.message,timedOut:u.timedOut},shardKey:u.shardKey});continue}s+=1;const d=m(u.value),c=B(d);r+=c.changed,a+=c.processed,n||=c.status==="in_progress",i||=c.status==="failed",e.push({result:d,shardKey:u.shardKey})}return{changed:r,failed:o,ok:s,processed:a,shards:e,status:I(i,n||o>0)}},D=t=>{const e=t??{};return{before:typeof e.before=="number"&&Number.isFinite(e.before)?e.before:0,total:typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0}},V=t=>{const e=[];let s=0,o=0,r=0,a=0;for(const n of t){if(n.kind==="err"){o+=1,e.push({error:{message:n.message,timedOut:n.timedOut},shardKey:n.shardKey});continue}s+=1;const i=D(m(n.value));r+=i.before,a+=i.total,e.push({result:i,shardKey:n.shardKey})}return{failed:o,ok:s,partial:o>0,position:r+1,shards:e,total:a}},T=0,j=1,$=2,N=t=>t==null?T:typeof t=="number"?j:$,x=(t,e)=>{const s=N(t),o=N(e);if(s!==o)return s<o?-1:1;if(s===T)return 0;if(s===j){const n=t,i=e;return n<i?-1:n>i?1:0}const r=String(t),a=String(e);return r<a?-1:r>a?1:0},J=(t,e,s)=>{const o=x(t.partitionKey,e.partitionKey);if(o!==0)return o;const r=Math.max(t.sortValues.length,e.sortValues.length);for(let a=0;a<r;a+=1){const n=x(t.sortValues[a],e.sortValues[a]);if(n!==0)return s[a]==="desc"?-n:n}return x(t.rowId,e.rowId)},Q=t=>{const e=JSON.stringify(t),s=new TextEncoder().encode(e);let o="";for(const r of s)o+=String.fromCodePoint(r);return btoa(o)},U=t=>{let e;try{const s=atob(t),o=Uint8Array.from(s,r=>r.codePointAt(0)??0);e=new TextDecoder().decode(o)}catch{return{perShard:{}}}try{const s=JSON.parse(e);if(s!==null&&typeof s=="object"&&"perShard"in s){const{perShard:o}=s;if(o!==null&&typeof o=="object")return{perShard:o}}}catch{}return{perShard:{}}},L=t=>{const e=t??{},s=Array.isArray(e.rows)?e.rows:[];return{directions:Array.isArray(e.directions)?e.directions:[],hasMore:e.hasMore===!0,rows:s}},G=(t,e)=>{let s,o;for(const r of t){const a=r.rows[r.head];a!==void 0&&(o===void 0||J(a.key,o,e)<0)&&(s=r,o=a.key)}return s},Y=(t,e)=>{let s=!1;const o=new Set;for(const a of t)o.add(a.shardKey),(a.head<a.rows.length||a.hasMore)&&(s=!0);const r={...e};for(const a of Object.keys(e))o.has(a)||(s=!0);return s?Q({perShard:r}):null},z=(t,e,s,o)=>{const r=[],a={...o};for(;r.length<e;){const i=G(t,s);if(i===void 0)break;const u=i.rows[i.head];u!==void 0&&(r.push(u.doc),a[i.shardKey]=u.key),i.head+=1}const n=Y(t,a);return{isDone:n===null,nextCursor:n,page:r}},H=t=>{const e=[];let s=0,o=0;for(const r of t){if(r.kind==="err"){o+=1,e.push({error:{message:r.message,timedOut:r.timedOut},shardKey:r.shardKey});continue}s+=1;const a=m(r.value),n=Array.isArray(a?.rows)?a.rows:[];e.push({rows:n,shardKey:r.shardKey})}return{failed:o,ok:s,shards:e}},W=t=>{const e=[];let s=0,o=0;for(const{outcome:r,sinceSeq:a}of t){if(r.kind==="err"){o+=1,e.push({cursor:a,error:{message:r.message,timedOut:r.timedOut},shardKey:r.shardKey});continue}s+=1;const n=m(r.value),i=Array.isArray(n?.changes)?n.changes:[],u=typeof n?.cursor=="number"?n.cursor:a;e.push({changes:i,cursor:u,shardKey:r.shardKey})}return{failed:o,ok:s,shards:e}},X=t=>{let e=0,s=0,o=0;for(const r of t){if(r.kind==="err"){s+=1;continue}e+=1;const a=m(r.value);o+=typeof a?.applied=="number"?a.applied:0}return{applied:o,failed:s,ok:e}},Z=t=>{const e=t??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},ee=t=>{const e=[];let s=0,o=0;for(const r of t){if(r.kind==="err"){o+=1,e.push({requests:0,shardKey:r.shardKey});continue}s+=1,e.push({requests:Z(m(r.value)),shardKey:r.shardKey})}return{failed:o,ok:s,shards:e}},te=t=>{const e=[],s={},o=[];let r=0,a=0,n=0;for(const i of t){if(i.kind==="err"){n+=1,e.push({error:{message:i.message,timedOut:i.timedOut},shardKey:i.shardKey});continue}a+=1;const u=m(i.value),d=u?.inserted??{};for(const[l,p]of Object.entries(d))s[l]=(s[l]??0)+p;const c=u?.errors;Array.isArray(c)&&o.push(...c),r+=u?.conflicts??0,e.push({result:{conflicts:u?.conflicts??0,errors:u?.errors??[],inserted:d},shardKey:i.shardKey})}return{conflicts:r,errors:o,failed:n,inserted:s,ok:a,shards:e}},k=t=>({body:JSON.stringify({args:t.args??{},functionPath:t.functionPath}),headers:{"content-type":"application/json",...t.headers}}),S=async(t,e,s,o)=>{const r=C(t,e),a=new AbortController,n=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:a.signal});let i;const u=new Promise(c=>{i=setTimeout(()=>{try{a.abort()}catch{}c({kind:"err",message:`shard "${e}" timed out after ${String(o)}ms`,shardKey:e,timedOut:!0})},o)}),d=(async()=>{try{const c=await r.fetch(n);if(!c.ok)return{kind:"err",message:`shard "${e}" returned ${String(c.status)}`,shardKey:e,timedOut:!1};const l=await c.json();return{kind:"ok",shardKey:e,value:l}}catch(c){const l=c instanceof Error?c.message:String(c);return{kind:"err",message:`shard "${e}" threw: ${l}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([d,u])}finally{i!==void 0&&clearTimeout(i)}},K=async(t,e,s,o,r)=>{if(e.length===0)return[];const a=k(s),n=Array.from({length:e.length});let i=0;const u=async()=>{for(;;){const c=i;i+=1;const l=e[c];if(c>=e.length||l===void 0)return;n[c]=await S(t,l,a,r)}},d=Math.min(o,e.length);return await Promise.all(Array.from({length:d},()=>u())),n},re=(t,e)=>t<e?-1:t>e?1:0,se=t=>{const e={};for(const s of Object.keys(t).toSorted(re))e[s]=t[s]??null;return JSON.stringify(e)},oe=t=>{const e=[];for(const s of t)Array.isArray(s)&&e.push(...s);return e},ae=(t,e,s)=>{switch(s){case"max":return Math.max(t,e);case"min":return Math.min(t,e);case"sum":return t+e;default:return t}},ne=(t,e,s)=>{if(e===null||typeof e!="object")return;const o=e.key??{},r=e.value??null,a=se(o),n=t.get(a);if(!n){t.set(a,{key:o,value:r});return}if(n.value===null){n.value=r;return}r!==null&&(n.value=ae(n.value,r,s))},ie=(t,e)=>{const s=new Map;for(const o of t)if(Array.isArray(o))for(const r of o)ne(s,r,e);return[...s.values()]},E=(t,e)=>{let s=null;for(const o of t)typeof o=="number"&&Number.isFinite(o)&&(s=s===null?o:e(s,o));return s},ce=t=>{let e=0;for(const s of t)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},ue=t=>{let e=0,s=0;for(const o of t){if(o===null||typeof o!="object")continue;const r=o;typeof r.before=="number"&&Number.isFinite(r.before)&&(e+=r.before),typeof r.total=="number"&&Number.isFinite(r.total)&&(s+=r.total)}return{position:e+1,total:s}},de=(t,e)=>{const s=[];for(const a of t)if(Array.isArray(a))for(const n of a){if(n===null||typeof n!="object")continue;const i=n[e.by],u=typeof i=="number"&&Number.isFinite(i)?i:Number.NEGATIVE_INFINITY;s.push({row:n,score:u})}const o=e.direction??"desc",r=(a,n)=>a<n?-1:a>n?1:0;return s.sort((a,n)=>o==="asc"?r(a.score,n.score):r(n.score,a.score)),s.slice(0,e.k).map(a=>a.row)},le=(t,e)=>{switch(e.kind){case"concat":return oe(t);case"first":return t[0];case"groupBy":return ie(t,e.op??"sum");case"max":return E(t,(s,o)=>Math.max(s,o));case"min":return E(t,(s,o)=>Math.min(s,o));case"rank":return ue(t);case"sum":return ce(t);case"topK":return de(t,e);default:return t}},ge=t=>{const e=t.maxConcurrency??q,s=t.perShardTimeoutMs??F;if(e<1)throw new M("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(o,r){const a=await t.registry.listShardKeys(r.fanOut.table),n=await K(o,a,r,e,s),i=[],u=[],d=[];for(const c of n)c.kind==="ok"?(i.push(c.value),u.push(c.shardKey)):d.push({message:c.message,shardKey:c.shardKey,timedOut:c.timedOut});return{data:le(i,r.fanOut.merge),errors:d,failed:d.length,ok:u.length}},async orchestrateExport(o,r){const a=new Set,n=await Promise.all(r.tables.map(async c=>t.registry.listShardKeys(c)));for(const c of n)for(const l of c)a.add(l);const i=[...a],u={args:{...r.args,tables:[...r.tables]},functionPath:"__lunora_admin__:exportShard",headers:r.headers},d=await K(o,i,u,e,s);return H(d)},async orchestrateCdcSync(o,r){const a=new Set,n=await Promise.all(r.tables.map(async f=>t.registry.listShardKeys(f)));for(const f of n)for(const y of f)a.add(y);const i=[...a],u=r.cursors??{},d=Array.from({length:i.length});let c=0;const l=Math.min(e,i.length),p=async()=>{for(;;){const f=c;c+=1;const y=i[f];if(f>=i.length||y===void 0)return;const g=u[y]??0,b=await S(o,y,k({args:{limit:r.limit,sinceSeq:g},functionPath:"__lunora_admin__:cdcSync",headers:r.headers}),s);d[f]={outcome:b,sinceSeq:g}}};return l>0&&await Promise.all(Array.from({length:l},()=>p())),W(d)},async orchestrateImport(o,r){const{batches:a}=r,n=Array.from({length:a.length});let i=0;const u=Math.min(e,a.length),d=async()=>{for(;;){const c=i;i+=1;const l=a[c];if(c>=a.length||l===void 0)return;n[c]=await S(o,l.shardKey,k({args:{rows:[...l.rows],startLine:l.startLine??1},functionPath:"__lunora_admin__:importShard",headers:r.headers}),s)}};return u>0&&await Promise.all(Array.from({length:u},()=>d())),te(n)},async orchestrateApplyCdc(o,r){const{batches:a}=r,n=Array.from({length:a.length});let i=0;const u=Math.min(e,a.length),d=async()=>{for(;;){const c=i;i+=1;const l=a[c];if(c>=a.length||l===void 0)return;n[c]=await S(o,l.shardKey,k({args:{changes:[...l.changes]},functionPath:"__lunora_admin__:applyCdc",headers:r.headers}),s)}};return u>0&&await Promise.all(Array.from({length:u},()=>d())),X(n)},async orchestrateMigration(o,r){const a=await t.registry.listShardKeys(r.table),n=await K(o,a,r,e,s);return R(n)},async orchestrateRank(o,r){const a=await t.registry.listShardKeys(r.table),n={args:{index:r.index,partitionKey:r.partitionKey,rowId:r.rowId,sortValues:[...r.sortValues],table:r.table},functionPath:"__lunora_admin__:rankBefore",headers:r.headers},i=await K(o,a,n,e,s);return V(i)},async orchestrateRankPage(o,r){const a=await t.registry.listShardKeys(r.table),n=Math.max(1,Math.min(1e3,Math.floor(r.take??100))),i=r.directions??[],u=r.cursor?U(r.cursor):{perShard:{}},d=Array.from({length:a.length});let c=0;const l=Math.min(e,a.length),p=async()=>{for(;;){const h=c;c+=1;const w=a[h];if(h>=a.length||w===void 0)return;const P=u.perShard[w],A={index:r.index,table:r.table,take:n};r.partitionKey!==void 0&&(A.partitionKey=r.partitionKey),P!==void 0&&(A.after=P);const _=await S(o,w,k({args:A,functionPath:"__lunora_admin__:rankPage",headers:r.headers}),s);if(_.kind==="err"){d[h]={error:{message:_.message,timedOut:_.timedOut},shardKey:w};continue}const O=L(m(_.value));d[h]={directions:O.directions,hasMore:O.hasMore,rows:O.rows,shardKey:w}}};l>0&&await Promise.all(Array.from({length:l},()=>p()));const f=[];let y=0,g=0,b;for(const h of d){if(h.error){g+=1;continue}y+=1,b===void 0&&h.directions&&h.directions.length>0&&(b=h.directions),f.push({hasMore:h.hasMore??!1,head:0,rows:h.rows??[],shardKey:h.shardKey})}const v=z(f,n,b??i,u.perShard);return{continueCursor:v.nextCursor,failed:g,isDone:v.isDone,ok:y,page:v.page,partial:g>0,shards:d}},async orchestrateShardTraffic(o,r){const a=await t.registry.listShardKeys(r.table),n={functionPath:"__lunora_admin__:getMetrics",headers:r.headers},i=await K(o,a,n,e,s);return ee(i)},registry:t.registry}};export{ge as createQueryCoordinator,ye as createStaticShardRegistry,me as mergeStrategyForAggregate};
|
|
1
|
+
import{LunoraError as M}from"./LunoraError-ByasbDmd.mjs";import{resolveShard as C}from"./applyJurisdiction-8bzZjAPR.mjs";const ye=t=>({listShardKeys(e){return t[e]??[]}}),me=t=>{if(t.kind==="count")return{kind:"sum"};if(t.kind==="scalar"){if(t.op==="count"||t.op==="sum")return{kind:"sum"};if(t.op==="max")return{kind:"max"};if(t.op==="min")return{kind:"min"};throw new M('aggregate({ op: "avg" }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})}const e=t.agg?.op??"count";if(e==="count"||e==="sum")return{kind:"groupBy",op:"sum"};if(e==="max")return{kind:"groupBy",op:"max"};if(e==="min")return{kind:"groupBy",op:"min"};throw new M('groupBy({ agg: { op: "avg" } }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})},q=16,F=5e3,m=t=>t!==null&&typeof t=="object"&&"result"in t?t.result:t,B=t=>{const e=t??{};return{changed:typeof e.changed=="number"?e.changed:0,processed:typeof e.processed=="number"?e.processed:0,status:typeof e.status=="string"?e.status:void 0}},I=(t,e)=>t?"failed":e?"in_progress":"completed",R=t=>{const e=[];let s=0,o=0,r=0,a=0,n=!1,i=!1;for(const u of t){if(u.kind==="err"){o+=1,e.push({error:{message:u.message,timedOut:u.timedOut},shardKey:u.shardKey});continue}s+=1;const d=m(u.value),c=B(d);r+=c.changed,a+=c.processed,n||=c.status==="in_progress",i||=c.status==="failed",e.push({result:d,shardKey:u.shardKey})}return{changed:r,failed:o,ok:s,processed:a,shards:e,status:I(i,n||o>0)}},D=t=>{const e=t??{};return{before:typeof e.before=="number"&&Number.isFinite(e.before)?e.before:0,total:typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0}},V=t=>{const e=[];let s=0,o=0,r=0,a=0;for(const n of t){if(n.kind==="err"){o+=1,e.push({error:{message:n.message,timedOut:n.timedOut},shardKey:n.shardKey});continue}s+=1;const i=D(m(n.value));r+=i.before,a+=i.total,e.push({result:i,shardKey:n.shardKey})}return{failed:o,ok:s,partial:o>0,position:r+1,shards:e,total:a}},T=0,j=1,$=2,N=t=>t==null?T:typeof t=="number"?j:$,x=(t,e)=>{const s=N(t),o=N(e);if(s!==o)return s<o?-1:1;if(s===T)return 0;if(s===j){const n=t,i=e;return n<i?-1:n>i?1:0}const r=String(t),a=String(e);return r<a?-1:r>a?1:0},J=(t,e,s)=>{const o=x(t.partitionKey,e.partitionKey);if(o!==0)return o;const r=Math.max(t.sortValues.length,e.sortValues.length);for(let a=0;a<r;a+=1){const n=x(t.sortValues[a],e.sortValues[a]);if(n!==0)return s[a]==="desc"?-n:n}return x(t.rowId,e.rowId)},Q=t=>{const e=JSON.stringify(t),s=new TextEncoder().encode(e);let o="";for(const r of s)o+=String.fromCodePoint(r);return btoa(o)},U=t=>{let e;try{const s=atob(t),o=Uint8Array.from(s,r=>r.codePointAt(0)??0);e=new TextDecoder().decode(o)}catch{return{perShard:{}}}try{const s=JSON.parse(e);if(s!==null&&typeof s=="object"&&"perShard"in s){const{perShard:o}=s;if(o!==null&&typeof o=="object")return{perShard:o}}}catch{}return{perShard:{}}},L=t=>{const e=t??{},s=Array.isArray(e.rows)?e.rows:[];return{directions:Array.isArray(e.directions)?e.directions:[],hasMore:e.hasMore===!0,rows:s}},G=(t,e)=>{let s,o;for(const r of t){const a=r.rows[r.head];a!==void 0&&(o===void 0||J(a.key,o,e)<0)&&(s=r,o=a.key)}return s},Y=(t,e)=>{let s=!1;const o=new Set;for(const a of t)o.add(a.shardKey),(a.head<a.rows.length||a.hasMore)&&(s=!0);const r={...e};for(const a of Object.keys(e))o.has(a)||(s=!0);return s?Q({perShard:r}):null},z=(t,e,s,o)=>{const r=[],a={...o};for(;r.length<e;){const i=G(t,s);if(i===void 0)break;const u=i.rows[i.head];u!==void 0&&(r.push(u.doc),a[i.shardKey]=u.key),i.head+=1}const n=Y(t,a);return{isDone:n===null,nextCursor:n,page:r}},H=t=>{const e=[];let s=0,o=0;for(const r of t){if(r.kind==="err"){o+=1,e.push({error:{message:r.message,timedOut:r.timedOut},shardKey:r.shardKey});continue}s+=1;const a=m(r.value),n=Array.isArray(a?.rows)?a.rows:[];e.push({rows:n,shardKey:r.shardKey})}return{failed:o,ok:s,shards:e}},W=t=>{const e=[];let s=0,o=0;for(const{outcome:r,sinceSeq:a}of t){if(r.kind==="err"){o+=1,e.push({cursor:a,error:{message:r.message,timedOut:r.timedOut},shardKey:r.shardKey});continue}s+=1;const n=m(r.value),i=Array.isArray(n?.changes)?n.changes:[],u=typeof n?.cursor=="number"?n.cursor:a;e.push({changes:i,cursor:u,shardKey:r.shardKey})}return{failed:o,ok:s,shards:e}},X=t=>{let e=0,s=0,o=0;for(const r of t){if(r.kind==="err"){s+=1;continue}e+=1;const a=m(r.value);o+=typeof a?.applied=="number"?a.applied:0}return{applied:o,failed:s,ok:e}},Z=t=>{const e=t??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},ee=t=>{const e=[];let s=0,o=0;for(const r of t){if(r.kind==="err"){o+=1,e.push({requests:0,shardKey:r.shardKey});continue}s+=1,e.push({requests:Z(m(r.value)),shardKey:r.shardKey})}return{failed:o,ok:s,shards:e}},te=t=>{const e=[],s={},o=[];let r=0,a=0,n=0;for(const i of t){if(i.kind==="err"){n+=1,e.push({error:{message:i.message,timedOut:i.timedOut},shardKey:i.shardKey});continue}a+=1;const u=m(i.value),d=u?.inserted??{};for(const[l,p]of Object.entries(d))s[l]=(s[l]??0)+p;const c=u?.errors;Array.isArray(c)&&o.push(...c),r+=u?.conflicts??0,e.push({result:{conflicts:u?.conflicts??0,errors:u?.errors??[],inserted:d},shardKey:i.shardKey})}return{conflicts:r,errors:o,failed:n,inserted:s,ok:a,shards:e}},k=t=>({body:JSON.stringify({args:t.args??{},functionPath:t.functionPath}),headers:{"content-type":"application/json",...t.headers}}),S=async(t,e,s,o)=>{const r=C(t,e),a=new AbortController,n=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:a.signal});let i;const u=new Promise(c=>{i=setTimeout(()=>{try{a.abort()}catch{}c({kind:"err",message:`shard "${e}" timed out after ${String(o)}ms`,shardKey:e,timedOut:!0})},o)}),d=(async()=>{try{const c=await r.fetch(n);if(!c.ok)return{kind:"err",message:`shard "${e}" returned ${String(c.status)}`,shardKey:e,timedOut:!1};const l=await c.json();return{kind:"ok",shardKey:e,value:l}}catch(c){const l=c instanceof Error?c.message:String(c);return{kind:"err",message:`shard "${e}" threw: ${l}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([d,u])}finally{i!==void 0&&clearTimeout(i)}},K=async(t,e,s,o,r)=>{if(e.length===0)return[];const a=k(s),n=Array.from({length:e.length});let i=0;const u=async()=>{for(;;){const c=i;i+=1;const l=e[c];if(c>=e.length||l===void 0)return;n[c]=await S(t,l,a,r)}},d=Math.min(o,e.length);return await Promise.all(Array.from({length:d},()=>u())),n},re=(t,e)=>t<e?-1:t>e?1:0,se=t=>{const e={};for(const s of Object.keys(t).toSorted(re))e[s]=t[s]??null;return JSON.stringify(e)},oe=t=>{const e=[];for(const s of t)Array.isArray(s)&&e.push(...s);return e},ae=(t,e,s)=>{switch(s){case"max":return Math.max(t,e);case"min":return Math.min(t,e);case"sum":return t+e;default:return t}},ne=(t,e,s)=>{if(e===null||typeof e!="object")return;const o=e.key??{},r=e.value??null,a=se(o),n=t.get(a);if(!n){t.set(a,{key:o,value:r});return}if(n.value===null){n.value=r;return}r!==null&&(n.value=ae(n.value,r,s))},ie=(t,e)=>{const s=new Map;for(const o of t)if(Array.isArray(o))for(const r of o)ne(s,r,e);return[...s.values()]},E=(t,e)=>{let s=null;for(const o of t)typeof o=="number"&&Number.isFinite(o)&&(s=s===null?o:e(s,o));return s},ce=t=>{let e=0;for(const s of t)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},ue=t=>{let e=0,s=0;for(const o of t){if(o===null||typeof o!="object")continue;const r=o;typeof r.before=="number"&&Number.isFinite(r.before)&&(e+=r.before),typeof r.total=="number"&&Number.isFinite(r.total)&&(s+=r.total)}return{position:e+1,total:s}},de=(t,e)=>{const s=[];for(const a of t)if(Array.isArray(a))for(const n of a){if(n===null||typeof n!="object")continue;const i=n[e.by],u=typeof i=="number"&&Number.isFinite(i)?i:Number.NEGATIVE_INFINITY;s.push({row:n,score:u})}const o=e.direction??"desc",r=(a,n)=>a<n?-1:a>n?1:0;return s.sort((a,n)=>o==="asc"?r(a.score,n.score):r(n.score,a.score)),s.slice(0,e.k).map(a=>a.row)},le=(t,e)=>{switch(e.kind){case"concat":return oe(t);case"first":return t[0];case"groupBy":return ie(t,e.op??"sum");case"max":return E(t,(s,o)=>Math.max(s,o));case"min":return E(t,(s,o)=>Math.min(s,o));case"rank":return ue(t);case"sum":return ce(t);case"topK":return de(t,e);default:return t}},ge=t=>{const e=t.maxConcurrency??q,s=t.perShardTimeoutMs??F;if(e<1)throw new M("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(o,r){const a=await t.registry.listShardKeys(r.fanOut.table),n=await K(o,a,r,e,s),i=[],u=[],d=[];for(const c of n)c.kind==="ok"?(i.push(c.value),u.push(c.shardKey)):d.push({message:c.message,shardKey:c.shardKey,timedOut:c.timedOut});return{data:le(i,r.fanOut.merge),errors:d,failed:d.length,ok:u.length}},async orchestrateExport(o,r){const a=new Set,n=await Promise.all(r.tables.map(async c=>t.registry.listShardKeys(c)));for(const c of n)for(const l of c)a.add(l);const i=[...a],u={args:{...r.args,tables:[...r.tables]},functionPath:"__lunora_admin__:exportShard",headers:r.headers},d=await K(o,i,u,e,s);return H(d)},async orchestrateCdcSync(o,r){const a=new Set,n=await Promise.all(r.tables.map(async f=>t.registry.listShardKeys(f)));for(const f of n)for(const y of f)a.add(y);const i=[...a],u=r.cursors??{},d=Array.from({length:i.length});let c=0;const l=Math.min(e,i.length),p=async()=>{for(;;){const f=c;c+=1;const y=i[f];if(f>=i.length||y===void 0)return;const g=u[y]??0,b=await S(o,y,k({args:{limit:r.limit,sinceSeq:g},functionPath:"__lunora_admin__:cdcSync",headers:r.headers}),s);d[f]={outcome:b,sinceSeq:g}}};return l>0&&await Promise.all(Array.from({length:l},()=>p())),W(d)},async orchestrateImport(o,r){const{batches:a}=r,n=Array.from({length:a.length});let i=0;const u=Math.min(e,a.length),d=async()=>{for(;;){const c=i;i+=1;const l=a[c];if(c>=a.length||l===void 0)return;n[c]=await S(o,l.shardKey,k({args:{rows:[...l.rows],startLine:l.startLine??1},functionPath:"__lunora_admin__:importShard",headers:r.headers}),s)}};return u>0&&await Promise.all(Array.from({length:u},()=>d())),te(n)},async orchestrateApplyCdc(o,r){const{batches:a}=r,n=Array.from({length:a.length});let i=0;const u=Math.min(e,a.length),d=async()=>{for(;;){const c=i;i+=1;const l=a[c];if(c>=a.length||l===void 0)return;n[c]=await S(o,l.shardKey,k({args:{changes:[...l.changes]},functionPath:"__lunora_admin__:applyCdc",headers:r.headers}),s)}};return u>0&&await Promise.all(Array.from({length:u},()=>d())),X(n)},async orchestrateMigration(o,r){const a=await t.registry.listShardKeys(r.table),n=await K(o,a,r,e,s);return R(n)},async orchestrateRank(o,r){const a=await t.registry.listShardKeys(r.table),n={args:{index:r.index,partitionKey:r.partitionKey,rowId:r.rowId,sortValues:[...r.sortValues],table:r.table},functionPath:"__lunora_admin__:rankBefore",headers:r.headers},i=await K(o,a,n,e,s);return V(i)},async orchestrateRankPage(o,r){const a=await t.registry.listShardKeys(r.table),n=Math.max(1,Math.min(1e3,Math.floor(r.take??100))),i=r.directions??[],u=r.cursor?U(r.cursor):{perShard:{}},d=Array.from({length:a.length});let c=0;const l=Math.min(e,a.length),p=async()=>{for(;;){const h=c;c+=1;const w=a[h];if(h>=a.length||w===void 0)return;const P=u.perShard[w],A={index:r.index,table:r.table,take:n};r.partitionKey!==void 0&&(A.partitionKey=r.partitionKey),P!==void 0&&(A.after=P);const _=await S(o,w,k({args:A,functionPath:"__lunora_admin__:rankPage",headers:r.headers}),s);if(_.kind==="err"){d[h]={error:{message:_.message,timedOut:_.timedOut},shardKey:w};continue}const O=L(m(_.value));d[h]={directions:O.directions,hasMore:O.hasMore,rows:O.rows,shardKey:w}}};l>0&&await Promise.all(Array.from({length:l},()=>p()));const f=[];let y=0,g=0,b;for(const h of d){if(h.error){g+=1;continue}y+=1,b===void 0&&h.directions&&h.directions.length>0&&(b=h.directions),f.push({hasMore:h.hasMore??!1,head:0,rows:h.rows??[],shardKey:h.shardKey})}const v=z(f,n,b??i,u.perShard);return{continueCursor:v.nextCursor,failed:g,isDone:v.isDone,ok:y,page:v.page,partial:g>0,shards:d}},async orchestrateShardTraffic(o,r){const a=await t.registry.listShardKeys(r.table),n={functionPath:"__lunora_admin__:getMetrics",headers:r.headers},i=await K(o,a,n,e,s);return ee(i)},registry:t.registry}};export{ge as createQueryCoordinator,ye as createStaticShardRegistry,me as mergeStrategyForAggregate};
|
package/dist/packem_shared/{createShardClient-62qcYKGl.mjs → createShardClient-BkZ9FokE.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as b}from"@lunora/errors";import{applyJurisdiction as O,resolveShard as $}from"./applyJurisdiction-
|
|
1
|
+
import{LunoraError as b}from"@lunora/errors";import{applyJurisdiction as O,resolveShard as $}from"./applyJurisdiction-8bzZjAPR.mjs";const m=e=>{let r="";for(let i=0;i<e.length;i+=32768)r+=String.fromCharCode(...e.subarray(i,i+32768));return btoa(r)},j=e=>{const r=atob(e),i=new Uint8Array(r.length);for(let c=0;c<r.length;c+=1)i[c]=r.codePointAt(c)??0;return i},s="$lunora.wire$",g=64,A=1024,v="__proto__",S={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},E={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},d=(e,r=0)=>{if(r>g)throw new RangeError(`wire-codec: value nesting exceeds the ${g}-level limit`);if(e===void 0)return[s,"undefined"];if(e===null)return null;const i=typeof e;if(i==="bigint")return[s,"bigint",e.toString()];if(i==="number"){const n=e;return Number.isNaN(n)?[s,"nan"]:n===1/0?[s,"inf"]:n===-1/0?[s,"-inf"]:n}if(i!=="object")return e;if(e instanceof Date)return[s,"date",d(e.getTime(),r+1)];if(e instanceof Error){const n=e,a={};for(const f of Object.keys(n))n[f]!==void 0&&(a[f]=d(n[f],r+1));const u=[s,"error",n.name,n.message,a];return n.cause!==void 0&&u.push(d(n.cause,r+1)),u}if(e instanceof URL)return[s,"url",e.href];if(e instanceof Map)return[s,"map",[...e.entries()].map(([n,a])=>[d(n,r+1),d(a,r+1)])];if(e instanceof Set)return[s,"set",[...e].map(n=>d(n,r+1))];if(e instanceof ArrayBuffer)return[s,"bytes",m(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const n=e,a=n.constructor.name,u=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);return a==="Uint8Array"?[s,"bytes",m(u)]:[s,"bytes",m(u),a]}if(Array.isArray(e)){const n=e.map(a=>d(a,r+1));return n.length>0&&n[0]===s?[s,"arr",n]:n}const c=Object.getPrototypeOf(e);if(c!==null&&c!==Object.prototype){const n=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${n} 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 t=e,o={};for(const n of Object.keys(t)){const a=t[n];a!==void 0&&(o[n]=d(a,r+1))}return o},l=(e,r=0)=>{if(r>g)throw new RangeError(`wire-codec: value nesting exceeds the ${g}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===s)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(t=>l(t,r+1));case"bigint":{const t=e[2];if(typeof t!="string"||t.length>A||!/^-?\d+$/.test(t))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${A} digits)`);return BigInt(t)}case"date":return new Date(l(e[2],r+1));case"map":return new Map(e[2].map(([t,o])=>[l(t,r+1),l(o,r+1)]));case"set":return new Set(e[2].map(t=>l(t,r+1)));case"url":return new URL(e[2]);case"error":{const t=e[2],o=e[3],n=(Object.hasOwn(E,t)?E[t]:void 0)??Error,a=new n(o);a.name!==t&&Object.defineProperty(a,"name",{configurable:!0,value:t,writable:!0});const u=l(e[4],r+1);for(const f of Object.keys(u))f===v?Object.defineProperty(a,f,{configurable:!0,enumerable:!0,value:u[f],writable:!0}):a[f]=u[f];return e.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:l(e[5],r+1),writable:!0}),a}case"bytes":{const t=j(e[2]),o=e[3]??"Uint8Array";if(o==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const n=Object.hasOwn(S,o)?S[o]:void 0;return n?new n(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(t=>l(t,r+1))}return e.map(t=>l(t,r+1))}const i=e,c={};for(const t of Object.keys(i)){const o=l(i[t],r+1);t===v?Object.defineProperty(c,t,{configurable:!0,enumerable:!0,value:o,writable:!0}):c[t]=o}return c},N=e=>{if(typeof e=="string")return e;const r=e?.__lunoraRef;if(typeof r!="string"||r.length===0)throw new b("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return r},R=e=>{const r=new b(e.code,e.message);return e.data!==void 0&&(r.data=l(e.data)),r},x=(e,r={})=>{const i=O(e,r.jurisdiction),c=r.system??!0,t=o=>x(e,{...r,...o});return{as:o=>t({as:o}),asSystem:()=>t({as:void 0}),call:async(o,n,a)=>{const u=N(o),f=a?.shardKey??r.shardKey;if(f===void 0||f.length===0)throw new b("INTERNAL",`createShardClient: no shard key for "${u}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const h={"content-type":"application/json"};c&&(h["x-lunora-system"]="1"),r.as&&(h["x-lunora-userid"]=r.as.userId,r.as.claims&&(h["x-lunora-identity"]=JSON.stringify(r.as.claims))),a?.mutationId!==void 0&&a.mutationId.length>0&&(h["x-lunora-mutation-id"]=a.mutationId);const y=await $(i,f).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:d(n??{}),functionPath:u}),headers:h,method:"POST"}));let p;try{p=await y.json()}catch{const w=y.statusText?` ${y.statusText}`:"";throw new b("INTERNAL",`createShardClient: shard response for "${u}" was not JSON (status ${String(y.status)}${w})`)}if("error"in p)throw R(p.error);if(!y.ok){const w=y.statusText?` ${y.statusText}`:"";throw new b("INTERNAL",`createShardClient: shard call "${u}" failed (status ${String(y.status)}${w})`)}return l(p.result)},forShard:o=>t({shardKey:o})}};export{x as createShardClient};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/runtime",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.46",
|
|
4
4
|
"description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,8 +46,9 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
50
|
-
"@lunora/errors": "1.0.0-alpha.9"
|
|
49
|
+
"@lunora/bindings": "1.0.0-alpha.14",
|
|
50
|
+
"@lunora/errors": "1.0.0-alpha.9",
|
|
51
|
+
"@lunora/platform": "1.0.0-alpha.1"
|
|
51
52
|
},
|
|
52
53
|
"engines": {
|
|
53
54
|
"node": "^22.15.0 || >=24.11.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as n}from"./LunoraError-ByasbDmd.mjs";import{applyJurisdiction as m}from"./applyJurisdiction-uRQLx282.mjs";const S="__lunora_shard_registry__",_=3e4,l="https://shard-registry.internal",w=async s=>await s.json(),$=s=>{const p=s.instanceName??S,o=s.cacheTtlMs??_,a=new Map,c=m(s.namespace,s.jurisdiction);let d;const h=()=>(d??=c.get(c.idFromName(p)),d),y=async(t,e)=>h().fetch(new Request(`${l}${t}`,{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"})),u=async t=>h().fetch(new Request(`${l}${t}`,{method:"GET"}));return{invalidate(t){t===void 0?a.clear():a.delete(t)},async listShardKeys(t){const e=Date.now(),r=a.get(t);if(r&&r.expiresAt>e)return r.shardKeys;const i=await u(`/list?table=${encodeURIComponent(t)}`);if(!i.ok)throw new n(`shard registry /list returned ${String(i.status)}`);const{shardKeys:g}=await w(i);return o>0&&a.set(t,{expiresAt:e+o,shardKeys:g}),g},async register(t,e){const r=await y("/register",{shardKey:e,table:t});if(!r.ok)throw new n(`shard registry /register returned ${String(r.status)}`);a.delete(t)},async snapshot(){const t=await u("/snapshot");if(!t.ok)throw new n(`shard registry /snapshot returned ${String(t.status)}`);const{tables:e}=await w(t);return e},async unregister(t,e){const r=await y("/unregister",{shardKey:e,table:t});if(!r.ok)throw new n(`shard registry /unregister returned ${String(r.status)}`);a.delete(t)}}};export{_ as DEFAULT_REGISTRY_CACHE_TTL_MS,S as SHARD_REGISTRY_DO_NAME,$ as createDynamicShardRegistry};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=(t,o)=>{if(o===void 0)return t;if(typeof t.jurisdiction!="function")throw new TypeError(`@lunora/runtime: Durable Object namespace does not support jurisdiction("${o}") — update @cloudflare/workers-types or remove the jurisdiction option`);return t.jurisdiction(o)},i=(t,o)=>{if(typeof t.getByName=="function")return t.getByName(o);const r=t.idFromName(o);return t.get(r)};export{e as applyJurisdiction,i as resolveShard};
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as rr,toErrorBody as nr}from"@lunora/errors";import{NOOP_EXECUTION_CONTEXT as or}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{O as Re,m as ar,A as sr,R as ir,d as dr,i as ur,s as cr}from"./otlp-resource-B-ByO9qo.mjs";import{LunoraError as s,toErrorResponse as ze}from"./LunoraError-ByasbDmd.mjs";import{runExportTap as lr}from"./createKvCursorStore-C24tEuYk.mjs";import{d as we}from"./method-guard-BbuR0VfS.mjs";import{buildHealthRoutes as hr,durableObjectProbe as pr,d1Probe as fr,presenceProbe as Pe}from"./HEALTH_PATH-BEE0A_lZ.mjs";import{wrapResolverWithContract as wr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as ma,routeIdentityResolvers as ya}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as mr}from"./LOG_ARCHIVE_PATH-DGsEec3K.mjs";import{o as yr,f as We,a as de}from"./observability-DYnm-d4g.mjs";import{resolveShard as Se,applyJurisdiction as He}from"./applyJurisdiction-uRQLx282.mjs";import{buildRestRoutes as gr}from"./argsFromQuery-BkJXnIpe.mjs";import{resolveSecurity as Je,handleCorsPreflight as br,enforceOrigin as Or,decorateResponse as Ne,enforceWebSocketOrigin as Ve}from"./decorateResponse-DBIWsRSZ.mjs";const mt=(e,t)=>{if(e.size<t)return;const r=e.keys().next().value;r!==void 0&&e.delete(r)},Er="::relay::",Tr=(e,t)=>`${e}${Er}${String(t)}`,Ce=new TextEncoder,_r=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Rr=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let a=0;a<r.length;a+=1)n[a]=r.codePointAt(a)??0;return n},Sr=64,Ue=new Map,yt=async e=>{const t=Ue.get(e);if(t)return t;mt(Ue,Sr);const r=crypto.subtle.importKey("raw",Ce.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ue.set(e,r),r},Ar=async(e,t)=>{const r=await yt(e),n=await crypto.subtle.sign("HMAC",r,Ce.encode(t));return _r(new Uint8Array(n))},vr=async(e,t,r)=>{const n=await yt(e);return crypto.subtle.verify("HMAC",n,r,Ce.encode(t))},gt="v1",Dr=6e4,kr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Dr),n=`${gt}.${String(r)}`,a=await Ar(e,n);return{expiresAtMs:r,token:`${n}.${a}`}},Ir=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[a,i,u]=n;if(a!==gt||u.length===0)return!1;const l=Number(i);if(!Number.isFinite(l)||l<=r)return!1;let y;try{y=Rr(u)}catch{return!1}return vr(e,`${a}.${i}`,y)},D="/_lunora/admin/auth",Pr={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},I=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new s(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new s(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},qe=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},X=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ye=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},Xe=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new s("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(r[n]=a);return r},Nr={[`${D}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${D}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${D}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${D}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${D}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${D}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${D}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${D}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${D}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${D}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${D}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${D}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${D}/users/create`]:{build:({body:e})=>({data:typeof e.data=="object"&&e.data!==null&&!Array.isArray(e.data)?e.data:void 0,email:I(e,"email"),name:I(e,"name"),password:X(e,"password"),role:qe(e.role)}),http:"POST",method:"createUser"},[`${D}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new s("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:I(e,"userId")}},http:"POST",method:"updateUser"},[`${D}/users/role`]:{build:({body:e})=>{const t=qe(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new s("`role` is required",{code:"BAD_REQUEST",status:400});return{role:t,userId:I(e,"userId")}},http:"POST",method:"setRole"},[`${D}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:X(e,"reason"),userId:I(e,"userId")}),http:"POST",method:"banUser"},[`${D}/users/unban`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"unbanUser"},[`${D}/users/password`]:{build:({body:e})=>({newPassword:I(e,"newPassword"),userId:I(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${D}/users/remove`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${D}/users/impersonate`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"impersonateUser"},[`${D}/sessions/revoke`]:{build:({body:e})=>({sessionId:I(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${D}/sessions/revoke-all`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${D}/accounts/unlink`]:{build:({body:e})=>({accountId:I(e,"accountId"),userId:I(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${D}/two-factor/disable`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${D}/passkeys/delete`]:{build:({body:e})=>({passkeyId:I(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${D}/organizations/members/remove`]:{build:({body:e})=>({memberId:I(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${D}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:I(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${D}/organizations/create`]:{build:({body:e})=>({logo:X(e,"logo"),metadata:Ye(e,"metadata"),name:I(e,"name"),ownerId:X(e,"ownerId"),slug:X(e,"slug")}),http:"POST",method:"createOrganization"},[`${D}/organizations/update`]:{build:({body:e})=>({logo:X(e,"logo"),metadata:Ye(e,"metadata"),name:X(e,"name"),organizationId:I(e,"organizationId"),slug:X(e,"slug")}),http:"POST",method:"updateOrganization"},[`${D}/organizations/remove`]:{build:({body:e})=>({organizationId:I(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${D}/organizations/members/add`]:{build:({body:e})=>({organizationId:I(e,"organizationId"),role:X(e,"role"),userId:I(e,"userId")}),http:"POST",method:"addMember"},[`${D}/organizations/members/invite`]:{build:({body:e})=>({email:I(e,"email"),inviterId:X(e,"inviterId"),organizationId:I(e,"organizationId"),role:X(e,"role")}),http:"POST",method:"inviteMember"},[`${D}/organizations/members/role`]:{build:({body:e})=>{const t=qe(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new s("`role` is required",{code:"BAD_REQUEST",status:400});return{memberId:I(e,"memberId"),role:t}},http:"POST",method:"updateMemberRole"},[`${D}/organizations/teams/create`]:{build:({body:e})=>({name:I(e,"name"),organizationId:I(e,"organizationId")}),http:"POST",method:"createTeam"},[`${D}/organizations/teams/update`]:{build:({body:e})=>({name:I(e,"name"),teamId:I(e,"teamId")}),http:"POST",method:"updateTeam"},[`${D}/organizations/teams/remove`]:{build:({body:e})=>({teamId:I(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${D}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:I(e,"teamId"),userId:I(e,"userId")}),http:"POST",method:"addTeamMember"},[`${D}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:I(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${D}/organizations/roles/create`]:{build:({body:e})=>({organizationId:I(e,"organizationId"),permission:Xe(e),role:I(e,"role")}),http:"POST",method:"createOrgRole"},[`${D}/organizations/roles/update`]:{build:({body:e})=>({permission:Xe(e),roleId:I(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${D}/organizations/roles/remove`]:{build:({body:e})=>({roleId:I(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Ur=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof s)throw i;const u=i,l=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new s("auth admin operation failed",{code:l,status:Pr[l]??500})}},r=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new s(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new s("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const l=u[i.method];if(l===void 0)throw new s(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const y=new URL(a.url),O={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:g=>e.queryParameter(y,g)},A=i.build(O),m=await t(()=>l(A));return Response.json(i.returns==="void"?{ok:!0}:m,{headers:{"content-type":"application/json"},status:200})},n={};for(const[a,i]of Object.entries(Nr))n[a]=u=>r(u,i);return n},qr="__lunora_admin__:getAuthAuditLog",Ze=e=>typeof e=="string"&&e!==""?e:void 0,et=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,$r=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new s("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const a={},i=Ze(r.actorId),u=Ze(r.event),l=et(r.sinceSeq),y=et(r.limit);i!==void 0&&(a.actorId=i),u!==void 0&&(a.event=u),l!==void 0&&(a.sinceSeq=l),y!==void 0&&(a.limit=y);let O;try{O=await n.read(a)}catch(m){throw m instanceof s?m:(console.error("[lunora] auth audit read failed:",m),new s("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const A={entries:O};return Response.json(A,{headers:{"content-type":"application/json"},status:200})},tt=500,Lr=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new s("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new s("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new s("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new s("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},Br=(e,t)=>{if(e.length>tt)throw new s(`RPC batch exceeds the ${String(tt)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,a]of e.entries()){const{entry:i,shardKey:u}=Lr(a,n,t),l=r.get(u)??[];l.push(i),r.set(u,l)}return r},ge=1048576,ae=async(e,t=ge)=>{if(!e.body)return"";const r=e.body.getReader(),n=new TextDecoder;let a=0,i="";for(;;){const{done:u,value:l}=await r.read();if(u)break;if(l){if(a+=l.byteLength,a>t)throw await r.cancel().catch(()=>{}),new s("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});i+=n.decode(l,{stream:!0})}}return i+=n.decode(),i},xr=async(e,t=ge)=>{if(!e.body)return new ArrayBuffer(0);const r=e.body.getReader(),n=[];let a=0;for(;;){const{done:l,value:y}=await r.read();if(l)break;if(y){if(a+=y.byteLength,a>t)throw await r.cancel().catch(()=>{}),new s("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});n.push(y)}}const i=new Uint8Array(a);let u=0;for(const l of n)i.set(l,u),u+=l.byteLength;return i.buffer},Z=async(e,t=ge)=>{try{const r=await ae(e,t);return r===""?{}:JSON.parse(r)}catch(r){throw r instanceof s?r:new s("Request body must be valid JSON",{code:"BAD_REQUEST",status:400})}},Cr=new TextEncoder,jr=e=>{const t=JSON.stringify(e),r=Cr.encode(t);let n="";for(const a of r)n+=String.fromCodePoint(a);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Gr=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let l=0;l<r.length;l+=1)n[l]=r.codePointAt(l)??0;const a=JSON.parse(new TextDecoder().decode(n)),i=a.s&&typeof a.s=="object"?a.s:{},u={};for(const[l,y]of Object.entries(i))typeof y=="number"&&Number.isFinite(y)&&(u[l]=y);return{g:typeof a.g=="number"&&Number.isFinite(a.g)?a.g:0,s:u,v:1}}catch{return t}},Mr=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",a=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(a===void 0?{}:{_id:a}),op:n,table:t}},rt=(e,t,r)=>{for(const n of t)e.push(Mr(n));return r!==void 0&&t.length>=r},Kr="/_lunora/admin/export",Qr="/_lunora/admin/import",Fr="/_lunora/admin/sync",zr="/_lunora/admin/connector/sync",Wr="/_lunora/admin/apply",Hr="/_lunora/admin/export-tap/run",Jr=new TextEncoder,Vr=async e=>{let t;try{const a=await ae(e);t=a===""?{}:JSON.parse(a)}catch(a){throw a instanceof s?a:new s("Export body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(r.tables===void 0)return{tables:void 0};if(!Array.isArray(r.tables))throw new s("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const n=[];for(const a of r.tables){if(typeof a!="string"||a.length===0)throw new s("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});n.push(a)}return{tables:n}},Yr=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:a,queryCoordinator:i,requireAdminOption:u,resolveForwardContext:l,shardDO:y,streamExportRows:O,streamingImport:A,syncGlobals:m}=e,g=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;const M=u(T,i,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),N=await Vr(T),{headers:K}=await l(T,L),Q=new ReadableStream({async pull(Y){const C=G=>{Y.enqueue(Jr.encode(`${JSON.stringify(G)}
|
|
2
|
-
`))};try{await O(M,K,N.tables,C),Y.close()}catch(G){Y.error(G)}}});return new Response(Q,{headers:{"content-type":"application/x-ndjson"},status:200})},p=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;const M=u(T,i,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),N=await Z(T),K=typeof N.cursors=="object"&&N.cursors!==null?N.cursors:{},Q=typeof N.limit=="number"?N.limit:void 0,Y=typeof N.globalCursor=="number"?N.globalCursor:0,C=Array.isArray(N.tables)?N.tables.filter(ne=>typeof ne=="string"):void 0,{headers:G}=await l(T,L),J=C??a(),re=await M.orchestrateCdcSync(y,{cursors:K,headers:G,limit:Q,tables:J}),se=m?await m({limit:Q,sinceSeq:Y}):void 0;return Response.json({global:se,shards:re.shards},{status:200})},w=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;const M=u(T,i,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),N=await Z(T),K=Gr(N.cursor),Q=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,Y=Array.isArray(N.tables)?N.tables.filter(ee=>typeof ee=="string"):void 0,{headers:C}=await l(T,L),G=Y??a(),J=await M.orchestrateCdcSync(y,{cursors:K.s,headers:C,limit:Q,tables:G}),re=[],se={...K.s};let ne=!1;for(const ee of J.shards)ne=rt(re,ee.changes??[],Q)||ne,se[ee.shardKey]=ee.cursor;let he=K.g;if(m){const ee=await m({limit:Q,sinceSeq:K.g});ne=rt(re,ee.changes,Q)||ne,he=ee.cursor}const me=jr({g:he,s:se,v:1}),be={changes:re,hasMore:ne,nextCursor:me};return Response.json(be,{status:200})},_=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;const M=u(T,i,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),N=await Z(T),K=(Array.isArray(N.batches)?N.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),Q=Array.isArray(N.globalChanges)?N.globalChanges:[],{headers:Y}=await l(T,L),C=await M.orchestrateApplyCdc(y,{batches:K,headers:Y}),G=Q.length>0&&t?await t({changes:Q}):0;return Response.json({applied:C.applied+G,failed:C.failed,ok:C.ok},{status:200})},R=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;u(T,i,{code:"BAD_REQUEST",message:"Import endpoint requires a `queryCoordinator` on the worker"});const{headers:M}=await l(T,L),N=await A(T,M);return Response.json(N,{headers:{"content-type":"application/json"},status:200})},P=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;const M=u(T,i,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new s("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const N=await Z(T),K=typeof N.sink=="string"?N.sink:void 0,Q=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,Y=Array.isArray(N.tables)?N.tables.filter(se=>typeof se=="string"):void 0;if(K===void 0)throw new s("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const C=n[K];if(C===void 0)throw new s(`Export-tap sink "${K}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:G}=await l(T,L),J=Y??a(),re=await lr({coordinator:M,cursorStore:r,headers:G,limit:Q,shardDO:y,sink:C,tables:J});return Response.json(re,{headers:{"content-type":"application/json"},status:200})};return{[Wr]:_,[zr]:w,[Kr]:g,[Hr]:P,[Qr]:R,[Fr]:p}},bt=e=>[],Xr=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?n.push(a):r.push(a);return{globalTables:n,shardLocalTables:r}},Zr=async(e,t,r,n,a,i,u)=>{if(n!==void 0&&a.length===0)return;const l=n===void 0?[]:a,y=n===void 0?bt():[],O=l.length>0?l:y,A=await t.orchestrateExport(u,{args:{tables:l},headers:r,tables:O});for(const m of A.shards)if(!m.error)for(const g of m.rows??[])i(g)},nt=async(e,t,r,n,a,i)=>{const{globalTables:u,shardLocalTables:l}=Xr(e,n);await Zr(e,t,r,n,l,a,i);const y=e.exportGlobals;if((n===void 0||u.length>0)&&y){const O=n===void 0?[]:u;for await(const A of y({tables:O}))a(A)}},en=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},tn=(e,t,r,n,a)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const i=e[r.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:n}},rn=async(e,t,r)=>{if(!e.body)throw new s("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],a=[],i=new Map;let u=0;const l=e.body.getReader(),y=new TextDecoder;let O="",A=0;const m=g=>{u+=1;const p=g.trim();if(p.length===0)return;const w=en(p,u);if(!w.ok){n.push(w.error);return}const{doc:_,table:R}=w,P=t.resolveTableSharding?.(R);if(P?.mode.kind==="global"){a.push({doc:_,line:u,table:R});return}const T=tn(_,R,P,r,u);if(!T.ok){n.push(T.error);return}const L=i.get(T.shardKey);L?L.rows.push({doc:_,table:R}):i.set(T.shardKey,{rows:[{doc:_,table:R}],shardKey:T.shardKey,startLine:u})};for(;;){const{done:g,value:p}=await l.read();if(g)break;if(p&&(A+=p.byteLength,A>ge))throw await l.cancel().catch(()=>{}),new s("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});O+=y.decode(p,{stream:!0});let w=O.indexOf(`
|
|
3
|
-
`);for(;w!==-1;){const _=O.slice(0,w);O=O.slice(w+1),m(_),w=O.indexOf(`
|
|
4
|
-
`)}}return O.length>0&&m(O),{errors:n,globalRows:a,perShard:i}},ot=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},nn=async(e,t,r,n)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:l}=await rn(e,t,a),y={conflicts:0,errors:i,inserted:{}};if(l.size>0){const O=t.queryCoordinator;if(!O)throw new s("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const A=await O.orchestrateImport(n,{batches:[...l.values()],headers:r});ot(y,A)}if(u.length>0)if(t.importGlobals){const O=u[0]?.line??1,A=await t.importGlobals({rows:u,startLine:O});ot(y,A)}else for(const O of u)y.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:O.line,message:`row targets global table "${O.table}" but no \`importGlobals\` is configured`,table:O.table});return{conflicts:y.conflicts,errors:y.errors,inserted:y.inserted}},$e=e=>typeof e=="object"&&e!==null?e:{},Le=e=>typeof e.kind=="string"?e.kind:"unknown",on=(e,t)=>{let r=$e(t),n=!1;Le(r)==="optional"&&(n=!0,r=$e(r._meta?.inner));const a=Le(r),i=r._meta??{},u={kind:a,name:e,optional:n};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const l=Le($e(i.inner));l!=="unknown"&&(u.element=l)}return u},an=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>on(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),sn="/_lunora/admin/functions",dn="/_lunora/admin/cron-jobs",un="/_lunora/admin/openapi",cn="/_lunora/admin/openrpc",ln="/_lunora/admin/global/tables",hn="/_lunora/admin/global/table",pn="/_lunora/admin/global/facet",at=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:a,value:i}=n;return[{column:a,value:i}]});return r.length===0?void 0:r},fn=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:{}}),wn=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"}),mn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:a,requireAdminOption:i}=e,u=p=>{if(p.method!=="GET")throw new s("Functions endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(w).flatMap(([R,P])=>P.visibility==="internal"||P.kind==="stream"?[]:[{args:an(P.args),kind:P.kind,path:R}]).toSorted((R,P)=>R.path.localeCompare(P.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},l=p=>{if(p.method!=="GET")throw new s("Cron-jobs endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(w).flatMap(([R,P])=>P.map(T=>({args:T.args,cron:R,functionPath:T.functionPath,name:T.name,shardKey:T.shardKey,workflow:T.workflow}))).toSorted((R,P)=>R.name.localeCompare(P.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},y=p=>{if(p.method!=="GET")throw new s("OpenAPI endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openApiSpec??fn,{headers:{"content-type":"application/json"},status:200})},O=p=>{if(p.method!=="GET")throw new s("OpenRPC endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openRpcSpec??wn,{headers:{"content-type":"application/json"},status:200})},A=async p=>{if(p.method!=="GET")throw new s("Global-tables endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await w.listTables(),{headers:{"content-type":"application/json"},status:200})},m=async p=>{if(p.method!=="GET")throw new s("Global-table endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),R=a(_,"table");if(R===void 0)throw new s("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const P=await w.readTablePage({...n(p),filters:at(a(_,"filters")),table:R});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},g=async p=>{if(p.method!=="GET")throw new s("Global-facet endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),R=a(_,"table"),P=a(_,"column");if(R===void 0||P===void 0)throw new s("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const T=a(_,"limit"),L=T===void 0?void 0:Number(T),B=await w.facetColumn({column:P,filters:at(a(_,"filters")),limit:L!==void 0&&Number.isFinite(L)?L:void 0,table:R});return Response.json(B,{headers:{"content-type":"application/json"},status:200})};return{[dn]:l,[sn]:u,[pn]:g,[hn]:m,[ln]:A,[un]:y,[cn]:O}},yn="/_lunora/admin/kv/namespaces",gn="/_lunora/admin/kv/keys",Ot="/_lunora/admin/kv/value",Et=32*1048576,st=60,bn=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=m=>r(m,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=m=>Response.json(m,{headers:{"content-type":"application/json"},status:200}),i=(m,g)=>{const p=new URL(m.url),w=p.searchParams.get("namespace")??"",_=p.searchParams.get("key")??"";if(w==="")throw new s(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(_==="")throw new s(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:_,namespace:w}},u=async(m,g)=>{if(!(await m.listNamespaces()).some(p=>p.binding===g))throw new s(`Unknown KV namespace binding \`${g}\``,{code:"NOT_FOUND",status:404})},l=async m=>{if(m.method!=="GET")throw new s("KV-namespaces endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return a({namespaces:await n(m).listNamespaces()})},y=async m=>{if(m.method!=="GET")throw new s("KV-keys endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(m),p=new URL(m.url),w=p.searchParams.get("namespace")??"";if(w==="")throw new s("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const _=p.searchParams.get("prefix")??void 0,R=p.searchParams.get("cursor")??void 0,P=p.searchParams.get("limit"),T=P===null?void 0:Number.parseInt(P,10);if(T!==void 0&&(!Number.isInteger(T)||T<1))throw new s("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const L=T===void 0?void 0:Math.min(T,1e3);return await u(g,w),a(await g.listKeys({cursor:R,limit:L,namespace:w,prefix:_}))},O={DELETE:async m=>{const g=n(m),p=i(m,"DELETE");return await u(g,p.namespace),await g.deleteKey(p),a({deleted:!0})},GET:async m=>{const g=n(m),p=i(m,"GET");return await u(g,p.namespace),a(await g.getValue(p))},PUT:async m=>{const g=n(m),p=await t(m,Et);if(typeof p.namespace!="string"||p.namespace==="")throw new s("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new s("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new s("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<st))throw new s("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const w=Math.floor(Date.now()/1e3)+st;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<w))throw new s("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(g,p.namespace),await g.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),a({ok:!0})}},A=m=>{const g=O[m.method];if(!g)throw new s("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(m)};return{[yn]:l,[gn]:y,[Ot]:A}},On="/_lunora/migrate",En="/_lunora/admin/pitr",Tn="/_lunora/admin/rank",_n="/_lunora/admin/rankpage",Rn="/_lunora/admin/shard-traffic",Sn=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),An=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),vn=async e=>{let t;try{const n=await ae(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof s?n:new s("Migration body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new s("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.functionPath!="string"||!Sn.has(r.functionPath))throw new s("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:r.args??{},functionPath:r.functionPath,table:r.table}},Dn=async e=>{let t;try{const n=await ae(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof s?n:new s("Rank body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new s("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.index!="string"||r.index.length===0)throw new s("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof r.partitionKey!="string")throw new s("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof r.rowId!="string"||r.rowId.length===0)throw new s("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(r.sortValues))throw new s("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:r.index,partitionKey:r.partitionKey,rowId:r.rowId,sortValues:r.sortValues,table:r.table}},kn=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new s('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},In=e=>{if(typeof e.table!="string"||e.table.length===0)throw new s("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new s("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new s("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 s("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 s("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Pn=async e=>{let t;try{const a=await ae(e);t=a===""?{}:JSON.parse(a)}catch(a){throw a instanceof s?a:new s("Rank page body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};In(r);const n=kn(r.directions);return{cursor:typeof r.cursor=="string"?r.cursor:null,directions:n,index:r.index,partitionKey:typeof r.partitionKey=="string"?r.partitionKey:void 0,table:r.table,take:typeof r.take=="number"?r.take:void 0}},Nn=async e=>{let t;try{const n=await ae(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof s?n:new s("Shard-traffic body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new s("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:r.table}},Un=async e=>{const t=await Z(e);if(typeof t.functionPath!="string"||!An.has(t.functionPath))throw new s("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new s("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},qn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:a,resolveForwardContext:i,shardDO:u}=e,l=async(g,p)=>{if(g.method!=="POST")throw new s("Migration endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Migration endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await vn(g),{headers:_}=await i(g,p),R=await a.orchestrateMigration(u,{args:w.args,functionPath:w.functionPath,headers:_,table:w.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},y=async(g,p)=>{if(g.method!=="POST")throw new s("Rank endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Rank endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await Dn(g),{headers:_}=await i(g,p),R=await a.orchestrateRank(u,{headers:_,index:w.index,partitionKey:w.partitionKey,rowId:w.rowId,sortValues:w.sortValues,table:w.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},O=async(g,p)=>{if(g.method!=="POST")throw new s("Rank page endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Rank page endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await Pn(g),{headers:_}=await i(g,p),R=await a.orchestrateRankPage(u,{...w,headers:_});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},A=async(g,p)=>{if(g.method!=="POST")throw new s("Shard-traffic endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Shard-traffic endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await Nn(g),{headers:_}=await i(g,p),R=await a.orchestrateShardTraffic(u,{headers:_,table:w.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},m=async(g,p)=>{if(g.method!=="POST")throw new s("PITR endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const w=await Un(g),{headers:_}=await i(g,p),R=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:w.args,functionPath:w.functionPath}),headers:_,method:"POST"});return r(u,w.shardKey??t,R)};return{[On]:l,[En]:m,[Tn]:y,[_n]:O,[Rn]:A}},$n=1,Ln=0,Bn=32,xn=512,Cn=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,jn=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>xn)return;const r=t.split(",");if(!(r.length>Bn)){for(const n of r)if(!Cn.test(n.trim()))return;return t}},Gn=e=>{const t=sr(e.headers.get("traceparent"));if(t===void 0)return;const r=jn(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},Mn=(e,t={})=>{const r=Gn(e),n=t.trustInbound===!0?r:void 0,a=Re(8),i=n?.traceId??Re(16),u=yr(t.sampling,n===void 0?a:i),l=u.isTraced&&(n===void 0||n.sampled);return{decision:u,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:l,spanId:a,traceFlags:l?$n:Ln,traceId:i,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},Kn=(e,t)=>{t.traceparent=ar(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Qn=(e,t)=>{let r;return()=>{if(r===void 0){const n=cr(e),a=t===void 0?void 0:t.cf;r=ir(ur(n),dr(n,a))}return r}},Fn="/_lunora/admin/scheduled",zn="/_lunora/admin/scheduled/status",Wn="/_lunora/admin/scheduled/ws",Hn="/_lunora/admin/scheduled/cancel",Jn="/_lunora/admin/scheduled/dead",Vn="/_lunora/admin/scheduled/dead/retry",Yn="/_lunora/admin/scheduled/dead/cancel",Xn=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:a}=e,i=async m=>{if(m.method!=="GET")throw new s("Scheduled-list endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(m).fetch(new Request("https://scheduler.internal/list",{method:"GET"}))},u=async m=>{if(m.method!=="GET")throw new s("Scheduler-status endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(m).fetch(new Request("https://scheduler.internal/status",{method:"GET"}))},l=async m=>{if(m.headers.get("Upgrade")!=="websocket")throw new s("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(m))throw new s("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const g=r();return Se(g,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))},y=async m=>{if(m.method!=="POST")throw new s("Scheduled-cancel endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(m),p=await m.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new s("Scheduled-cancel requires a string `id`",{code:"BAD_REQUEST",status:400});return g.fetch(new Request("https://scheduler.internal/cancel",{body:JSON.stringify({id:p.id}),headers:{"content-type":"application/json"},method:"POST"}))},O=async m=>{if(m.method!=="GET")throw new s("Scheduled dead-letter endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(m).fetch(new Request("https://scheduler.internal/dead",{method:"GET"}))},A=m=>async g=>{if(g.method!=="POST")throw new s("Scheduled dead-letter action requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const p=n(g),w=await g.json().catch(()=>{});if(typeof w?.id!="string"||w.id==="")throw new s("Scheduled dead-letter action requires a string `id`",{code:"BAD_REQUEST",status:400});return p.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))};return{[Hn]:y,[Yn]:A("/dead/cancel"),[Jn]:O,[Vn]:A("/dead/retry"),[Fn]:i,[zn]:u,[Wn]:l}},Zn="/_lunora/admin/storage",eo="/_lunora/admin/storage/url",to="/_lunora/admin/storage/buckets",ro=10080*60,no=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:a,requireAdminOption:i,storage:u}=e,l=w=>{const _=n(w,"key");if(_===void 0)throw new s("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return _},y=async w=>{const _=i(w,u.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),R=new URL(w.url),P=await _(n(R,"prefix"),{bucket:n(R,"bucket"),cursor:n(R,"cursor"),...r(w)});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},O=w=>{if(w.method!=="GET")throw new s("Storage-buckets endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(w),Response.json({buckets:u.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})},A=async w=>{const _=i(w,u.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),R=new URL(w.url),P=l(R);return await _(P,{bucket:n(R,"bucket")}),Response.json({deleted:!0,key:P},{headers:{"content-type":"application/json"},status:200})},m=async w=>{const _=i(w,u.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),R=new URL(w.url),P=l(R),T=await a(w),L=w.headers.get("content-type"),B=L===null||L===""?void 0:L,M=await _(P,T,{bucket:n(R,"bucket"),contentType:B});return Response.json(M,{headers:{"content-type":"application/json"},status:200})},g=async w=>{switch(w.method){case"DELETE":return A(w);case"GET":return y(w);case"POST":case"PUT":return m(w);default:throw new s("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async w=>{if(w.method!=="GET")throw new s("Storage URL endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const _=i(w,u.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),R=new URL(w.url),P=l(R),T=Number(n(R,"expiresIn")??""),L=Number.isFinite(T)&&T>0?Math.min(T,ro):void 0,B=await _(P,{bucket:n(R,"bucket"),expiresInSeconds:L});return Response.json({key:P,url:B},{headers:{"content-type":"application/json"},status:200})};return{[to]:O,[Zn]:g,[eo]:p}},oo=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},ao={mtls:e=>oo(e,"tlsClientAuth","certVerified")==="SUCCESS"},so=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:Object.entries(ao).find(([t])=>t===e)?.[1]??(()=>!1),io=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.'))}},uo="/_lunora/admin/vector/indexes",co="/_lunora/admin/vector/query",lo=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async i=>{if(i.method!=="GET")throw new s("Vector-indexes endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const u=r(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=>{if(i.method!=="POST")throw new s("Vector-query endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const u=r(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new s("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const l=await t(i);if(typeof l.name!="string"||l.name==="")throw new s("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof l.text!="string"||l.text==="")throw new s("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(l.topK!==void 0&&(typeof l.topK!="number"||!Number.isInteger(l.topK)||l.topK<1))throw new s("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const y=await u.queryIndex({name:l.name,text:l.text,topK:l.topK});return Response.json(y,{headers:{"content-type":"application/json"},status:200})};return{[uo]:n,[co]:a}},ho="/_lunora/admin/workflows/instances",po="/_lunora/admin/workflows/instance",fo="/_lunora/admin/workflows/status",wo={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},mo=e=>e!==null&&Object.hasOwn(wo,e)?e:void 0,it=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Be=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new s(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},dt=()=>{throw new s("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},yo=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(u,l,y)=>{if(u.method!=="GET")throw new s("Workflows instances endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(u);const O=r(l);if(!O)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const A=Be(y,"name"),m=mo(y.searchParams.get("status"));return Response.json(await O.listInstances({page:it(y,"page"),perPage:it(y,"perPage"),status:m,workflowName:A}))},a=async(u,l,y)=>{if(u.method!=="GET")throw new s("Workflows instance endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(u);const O=r(l);return O?Response.json(await O.getInstance({instanceId:Be(y,"id"),workflowName:Be(y,"name")})):dt()},i=async(u,l)=>{if(u.method!=="POST")throw new s("Workflows status endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});t(u);const y=r(l);if(!y)return dt();const O=await u.json().catch(()=>{});if(typeof O?.name!="string"||O.name===""||typeof O.id!="string"||O.id==="")throw new s("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:A}=O;if(A!=="pause"&&A!=="resume"&&A!=="terminate")throw new s("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await y.setInstanceStatus({action:A,instanceId:O.id,workflowName:O.name}))};return{[po]:a,[ho]:n,[fo]:i}},go=new TextEncoder,ut="/_lunora/rpc",bo="/_lunora/rpc-batch",Oo="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:Qn(e,t),...r===void 0?{}:{waitUntil:r}}),ct=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},lt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),xe=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const a=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(a)?void 0:a,scheme:n.protocol.replace(":",""),userAgent:r}},ht="/_lunora/voice/",Eo="/_lunora/scheduler/dispatch",To="/_lunora/admin/cron-jobs/run",_o="/_lunora/admin/ws-token",Ro="/_lunora/admin/",So="/_lunora/migrate",Ao="/_lunora/status",vo=e=>e.startsWith(Ro)||e===So,Do=new Set(["1","enabled","on","true","yes"]),ko=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},Io="/api/auth",Po="__lunora_admin__:recordAuthEvent",No="__lunora_admin__:listPushSubscriptions",Uo=["/sign-in","/sign-up","/callback"],qo=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return Uo.some(a=>n===a||n.startsWith(`${a}/`))},Te=(e,t,r,n)=>{const a=rr(r),i=a?r.code:"INTERNAL_SERVER_ERROR",u=a?r.status:500,l=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:i,message:l,status:u},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},$o=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},pt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Lo=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ue=async(e,t,r)=>{const n={"content-type":"application/json"},a=e.headers.get("authorization"),i=e.headers.get("cookie"),u=e.headers.get("x-d1-bookmark"),l=e.headers.get("x-lunora-mutation-id"),y=e.headers.get("x-lunora-client-id"),O=e.headers.get("x-lunora-client-seq");a&&(n.authorization=a),i&&(n.cookie=i),u&&(n["x-d1-bookmark"]=u),l&&(n["x-lunora-mutation-id"]=l),y&&(n["x-lunora-client-id"]=y),O&&(n["x-lunora-client-seq"]=O);const A=e.headers.get("cf-connecting-ip");if(A&&(n["x-lunora-client-ip"]=A),!r)return{claims:null,headers:n,identity:null,userId:null};const m=await r(e,t);if(!m||typeof m.userId!="string"||m.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=m.userId;const g=$o(m);g!==void 0&&(n["x-lunora-identity-exp"]=String(g));const{userId:p,...w}=m,_=Object.keys(w).length>0?w:null;return _&&(n["x-lunora-identity"]=JSON.stringify(_)),{claims:_,headers:n,identity:m,userId:p}},Bo=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),xo=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new s("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 s("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new s("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!Bo.has(r.kind))throw new s("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new s("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new s("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Co=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},ft=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new s("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new s(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},jo=async e=>{const t=await ae(e);let r;try{r=JSON.parse(t)}catch{throw new s("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new s("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new s("RPC `args` must be an object",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new s("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=r,i=xo(a.fanOut),u=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const l=u.table;if(typeof l=="string"&&l!==i.table)throw new s("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},oe=async(e,t,r)=>Se(e,t).fetch(r),_e=new Map,Go=5e3,Mo=4096,Ko=async(e,t)=>{const r=Date.now(),n=_e.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&_e.delete(t);let a=0;try{const i=await Se(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const u=(await i.json()).relayCount;typeof u=="number"&&u>0&&(a=Math.floor(u))}}catch{a=0}return mt(_e,Mo),_e.set(t,{expiresMs:r+Go,relayCount:a}),a},Qo=(e,t)=>{if(!(e===null||typeof e!="object")){for(const[r,n]of Object.entries(e))if(n===t)return r}},je=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let a=0;a<r;a+=1){const i=a<e.length?e.codePointAt(a)??0:0,u=a<t.length?t.codePointAt(a)??0:0;n|=i^u}return n===0},Fo=async(e,t,r)=>{if(e.length===0||r.length===0)return!1;const n=new TextEncoder,a=await crypto.subtle.importKey("raw",n.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",a,n.encode(t)),u=new Uint8Array(i);let l="";for(const O of u)l+=String.fromCodePoint(O);const y=btoa(l).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return je(y,r)},wt=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...a]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:je(t,a.join(" ").trim())},zo=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await Ir(t,n)?!0:r?!1:je(t,n)},Wo=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return fr(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Pe(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Pe(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Pe(`hyperdrive:${e}`,!0)},Tt=e=>{const t=so(e.trustInboundTraceContext),r=io(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",a=wr(e.resolveIdentity,e.identity),i=He(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:He(e.schedulerDO,e.jurisdiction);let l;const y=()=>e.adminToken??l;let O;const A=()=>e.requireEphemeralWsToken??O??!1,m=o=>{const d=o??{};if(O===void 0&&e.requireEphemeralWsToken===void 0){const c=d.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(O=Do.has(c.trim().toLowerCase()))}if(l!==void 0||e.adminToken!==void 0)return;const h=d.LUNORA_ADMIN_TOKEN;typeof h=="string"&&h.length>0&&(l=h)},g=new WeakSet,p=o=>wt(o,y())||g.has(o),w=async(o,d)=>{const h=await ue(o,d,e.resolveIdentity);if(g.has(o)&&h.headers.authorization===void 0){const c=y();c!==void 0&&(h.headers.authorization=`Bearer ${c}`)}return h};let _=!1;const R=o=>{if(!e.allowUnauthenticatedShardAccess){const d=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new s(`${o} access is default-denied: configure \`${d}\` 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})}_||(_=!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("")))},P=qn({defaultShard:n,forwardToShard:oe,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:w,shardDO:i}),T=async(o,d,h,c,f)=>{if(e.authorizeShard&&!await e.authorizeShard(null,h))throw new s("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});const b={"content-type":"application/json","x-lunora-system":"1"};f?.userId!==void 0&&f.userId.length>0&&(b["x-lunora-userid"]=f.userId),f?.identity!==void 0&&f.identity.length>0&&(b["x-lunora-identity"]=f.identity),c!==void 0&&c.length>0&&(b["x-lunora-mutation-id"]=c);const S=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:d,functionPath:o}),headers:b,method:"POST"});return oe(i,h,S)},L=async(o,d,h,c)=>{const f=h?.[o];if(!f||typeof f.create!="function")throw new s(`${c} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});await f.create({params:d})},B=async(o,d,h)=>L(o,d.args??{},h,`cron job "${d.name}"`),M=async(o,d)=>{if(o.workflow){await B(o.workflow,o,d);return}if(o.functionPath===void 0)throw new s(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const h=await T(o.functionPath,o.args??{},o.shardKey??n);if(!h.ok)throw new s(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(h.status)}`,{code:"CRON_JOB_FAILED",status:500})},N=async(o,d,h,c)=>{const f=e.cronJobs?.[o];if(f)for(const b of f)try{await M(b,d)}catch(S){h.push(c(S))}},K=async(o,d)=>{if(!p(o))throw new s("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(o.method!=="POST")throw new s("cron-jobs run endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!e.cronJobs)throw new s("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const h=await Z(o),c=typeof h.name=="string"?h.name:"";if(c==="")throw new s("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const f=Object.values(e.cronJobs).flat().find(b=>b.name===c);if(!f)throw new s(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await M(f,d),Response.json({name:c,ran:!0},{status:200})},Q=async o=>{const d=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!d||!u||typeof o.id!="string")return;const h=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await u.get(u.idFromName(h)).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:d}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Y=async(o,d)=>{if(o.method!=="POST")throw new s("Scheduler dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const h=await ae(o),c=d??{},f=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),S=o.headers.get("x-lunora-scheduler-signature");let E=!1;if(S&&f?E=await Fo(f,h,S):b&&(E=wt(o,b)),!E)throw new s("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let v;try{v=JSON.parse(h)}catch{throw new s("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const k=v??{},U=k.args??{};if(typeof k.workflow=="string"&&k.workflow.length>0)return await L(k.workflow,U,d,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof k.functionPath!="string"||k.functionPath.length===0)throw new s("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const q=typeof k.shardKey=="string"&&k.shardKey.length>0?k.shardKey:n,$=typeof k.id=="string"&&k.id.length>0?k.id:void 0,x=ko(o),W=await T(k.functionPath,U,q,$,x);return await Q(k),W},C=o=>{if(!p(o))throw new s("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},G=(o,d,h)=>{if(C(o),d===void 0)throw new s(h.message,{code:h.code,status:400});return d},J=$r({assertAdmin:C,getReader:()=>e.authAuditReader}),re=async(o,d)=>{C(o);const h=e.notifySubscriptionStore;if(h===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const c=d?.kind,f=d?.userId,b=d?.limit,S=c==="fcm"||c==="web-push"?c:void 0,E=typeof f=="string"&&f!==""?f:void 0,v=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,k=v>0?Math.min(v,1e3):1e3,U=(await h.list({kind:S,limit:k,userId:E})).filter(q=>S!==void 0&&q.kind!==S?!1:E===void 0||(q.userId??null)===E).map(({keys:q,token:$,...x})=>x);return Response.json({subscriptions:U},{headers:{"content-type":"application/json"},status:200})},se=async(o,d)=>{if(!d.fanOut){if(d.functionPath===qr)return J(o,d.args??{});if(d.functionPath===No)return re(o,d.args)}},ne=Yr({applyGlobals:e.applyGlobals,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>bt(),queryCoordinator:e.queryCoordinator,requireAdminOption:G,resolveForwardContext:w,shardDO:i,streamExportRows:(o,d,h,c)=>nt(e,o,d,h,c,i),streamingImport:(o,d)=>nn(o,e,d,i),syncGlobals:e.syncGlobals}),he=(o,d)=>{const h=o.searchParams.get(d);return h===null||h===""?void 0:h},me=o=>{const d=new URL(o.url),h=d.searchParams.get("limit"),c=d.searchParams.get("offset"),f=h===null?void 0:Number.parseInt(h,10),b=c===null?void 0:Number.parseInt(c,10);return{limit:f!==void 0&&Number.isFinite(f)&&f>=0?f:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},be=()=>{if(u===void 0)throw new s("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},ee=Xn({checkWsAdmin:async o=>p(o)||zo(o,y(),A()),requireSchedulerNamespace:be,resolveSchedulerStub:o=>(C(o),Se(be(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),_t=yo({assertAdmin:C,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Rt=no({assertAdmin:C,parsePaging:me,queryParameter:he,readBodyBytes:xr,requireAdminOption:G,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),St=lo({readJsonBody:Z,requireAdminOption:G,vectorIntrospector:e.vectorIntrospector}),At=bn({kvIntrospector:e.kvIntrospector,readJsonBody:Z,requireAdminOption:G}),vt=mr({logArchive:e.logArchive,readJsonBody:Z,requireAdminOption:G}),Dt=mn({assertAdmin:C,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:me,queryParameter:he,requireAdminOption:G}),kt=o=>{const d=[],h=i??o?.SHARD;if(h!==void 0&&d.push(pr("durable-object:default",h,n)),e.health?.disableBindingProbes!==!0)for(const[c,f]of Object.entries(o??{})){const b=Wo(c,f);b!==void 0&&d.push(b)}for(const c of e.health?.probes??[])d.push(c);return d},It=hr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:kt}),Pt=async(o,d,h)=>{const{claims:c,headers:f,userId:b}=await ue(o,d,a),S=async(E,v={})=>{const k=E.__lunoraRef;if(typeof k!="string")throw new s("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const U=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:v,functionPath:k}),headers:{...f,"x-lunora-system":"1"},method:"POST"}),q=await oe(i,n,U),$=await q.json();if($.error)throw new s($.error.message??"shard RPC failed",{code:$.error.code??"INTERNAL",status:q.status});return $.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:b},cache:h.cache,fetch:globalThis.fetch.bind(globalThis),runAction:S,runMutation:S,runQuery:S}},Nt=async(o,d,h)=>{if(!e.httpRouter)return;const c=await Pt(o,d,h);try{return await e.httpRouter.fetch(o,{...d,__lunoraCtx:c},h)}catch(f){return console.error("[lunora] httpRouter (SSR) handler threw:",f),new Response("Internal Server Error",{status:500})}},Ut=async(o,d,h)=>{if(o.headers.get("Upgrade")!=="websocket")throw new s("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=Ve(o,ie);if(c)return c;const f=h.searchParams.get("shard")??n,{headers:b,identity:S}=await ue(o,d,a);if(e.authorizeShard){if(!await e.authorizeShard(S,f))throw new s("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else f!==n&&R("shard");const E=new Headers(o.headers),v=[...E.keys()];for(const x of v)x.startsWith("x-lunora-")&&E.delete(x);const k=b["x-lunora-userid"],U=b["x-lunora-identity"],q=b["x-lunora-identity-exp"];k!==void 0&&E.set("x-lunora-userid",k),U!==void 0&&E.set("x-lunora-identity",U),q!==void 0&&E.set("x-lunora-identity-exp",q);const $=Qo(d,e.shardDO);if($!==void 0){E.set("x-lunora-shard-binding",$);const x=await Ko(i,f);if(x>0){const W=Tr(f,Math.floor(Math.random()*x));return oe(i,W,new Request(o,{headers:E}))}}return oe(i,f,new Request(o,{headers:E}))},qt=async(o,d,h)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const f=Ve(o,ie);if(f)return f;let b;try{b=decodeURIComponent(h.pathname.slice(ht.length))}catch{return new Response("Unknown voice agent",{status:404})}const S=Object.hasOwn(c,b)?c[b]:void 0;if(S===void 0)return new Response("Unknown voice agent",{status:404});const E=h.searchParams.get("threadKey");if(E===null||E.length===0)return new Response("Missing threadKey",{status:400});const{headers:v,identity:k}=await ue(o,d,a);if(e.authorizeShard){if(!await e.authorizeShard(k,E))return new Response("Forbidden",{status:403})}else R("shard");const U=new Headers(o.headers);U.delete("x-lunora-userid"),U.delete("x-lunora-identity"),U.delete("x-lunora-identity-exp");const q=v["x-lunora-userid"],$=v["x-lunora-identity"],x=v["x-lunora-identity-exp"];return q!==void 0&&U.set("x-lunora-userid",q),$!==void 0&&U.set("x-lunora-identity",$),x!==void 0&&U.set("x-lunora-identity-exp",x),oe(S,E,new Request(o,{headers:U}))},$t=async(o,d,h)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(h,o.table,d))throw new s("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(d.startsWith("__lunora_relation__:"))throw new s("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 s("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});R("fan-out")},Oe=async(o,d)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await $t(o.fanOut,o.functionPath,d);return}if(e.authorizeShard){const h=o.shardKey??n;if(!await e.authorizeShard(d,h))throw new s("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else o.shardKey!==void 0&&o.shardKey!==n&&R("shard")}},Ae=async(o,d,h,c,f,b)=>{const S=Date.now(),{observability:E,sampling:v}=e,k=xe(o),{decision:U,ignoredUpstream:q,trace:$}=Mn(o,{...v===void 0?{}:{sampling:v},trustInbound:t(o)});q&&r();const x={...f,"x-lunora-sample-errors":U.keepErrors?"1":"0"};Kn($,x);const W=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:h,functionPath:d}),headers:x,method:"POST"});try{const j=await oe(i,c,W);return de(E,{...k,...lt($),durationMs:Date.now()-S,functionPath:d,ok:j.ok,shardKey:c,...j.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(j.status)}`,status:j.status}}},b,void 0,{isTraced:$.sampled,keepErrors:U.keepErrors}),j}catch(j){throw de(E,{...k,...lt($),...Te(d,Date.now()-S,j,{shardKey:c})},b,void 0,{isTraced:$.sampled,keepErrors:U.keepErrors}),j}},Lt=o=>{if(o.fanOut&&o.shardKey)throw new s("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!o.fanOut&&o.functionPath.startsWith("__lunora_relation__:"))throw new s("`__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 s("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Bt=async(o,d,h)=>{if(o.method!=="POST")throw new s("RPC endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const c=await jo(o);Co(d,c),Lt(c);const f=await se(o,c);if(f!==void 0)return f;const{headers:b,identity:S}=await ue(o,d,a);await Oe(c,S);const E=ft(c,e);{const v=Date.now(),{observability:k}=e,U=xe(o),q=Ee(d,o,h&&(W=>h.waitUntil?.(W)));if(c.fanOut){const W=e.queryCoordinator;if(!W)throw new s("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const j=await W.fanOut(i,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:b});return de(k,{durationMs:Date.now()-v,fanOut:{failed:j.failed,shards:j.ok+j.failed,table:c.fanOut.table},functionPath:c.functionPath,...U,ok:!0},q),Response.json(j,{headers:{"content-type":"application/json"},status:200})}catch(j){throw de(k,{...Te(c.functionPath,Date.now()-v,j,{fanOut:{table:c.fanOut.table}}),...U},q),j}}const $=c.shardKey??n,x=()=>Ae(o,c.functionPath,c.args??{},$,b,q);return E&&e.x402Charge?e.x402Charge(o,{functionPath:c.functionPath,price:E.price},x,ct(h)):x()}},xt=async(o,d,h)=>{if(o.method!=="POST")throw new s("RPC batch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const c=await ae(o);let f;try{f=JSON.parse(c)}catch{throw new s("RPC batch body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(typeof f!="object"||f===null||Array.isArray(f))throw new s("RPC batch body must be an object",{code:"BAD_REQUEST",status:400});const{calls:b}=f;if(!Array.isArray(b))throw new s("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:S,identity:E}=await ue(o,d,a),v=Br(b,n);for(const F of v.values())for(const z of F)if(e.functions?.[z.functionPath]?.x402)throw new s(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${ut}`,{code:"BAD_REQUEST",status:400});await Promise.all([...v.entries()].flatMap(([F,z])=>z.map(te=>Oe({functionPath:te.functionPath,shardKey:F},E))));const{observability:k}=e,U=Ee(d,o,h&&(F=>h.waitUntil?.(F))),q=xe(o),$=[],x=[],W=(F,z,te,ce)=>({body:{error:{code:te,message:ce}},id:F.id,status:z}),j=(F,z,te,ce,pe)=>{for(const H of F)de(k,pe(H),U),$.push(W(H,z,te,ce))},Xt=(F,z,te,ce,pe)=>{for(const H of F){const fe=ce.get(H.id)??pe,ye=fe<400;de(k,{durationMs:te,functionPath:H.functionPath,...q,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(fe)}`,status:fe}}},U)}};await Promise.all([...v.entries()].map(async([F,z])=>{const te=new Headers(S);te.set("content-type","application/json");const ce=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:te,method:"POST"}),pe=Date.now();let H;try{H=await oe(i,F,ce)}catch(V){const Ie=Date.now()-pe,{body:Fe}=nr(V,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});j(z,502,Fe.code,Fe.message,tr=>({...Te(tr.functionPath,Ie,V,{shardKey:F}),...q}));return}const fe=Date.now()-pe,ye=H.headers.get("x-d1-bookmark");ye&&x.push(ye);let De;try{De=await H.json()}catch{const V=`shard batch returned a non-JSON response (${String(H.status)})`;j(z,H.status,"SHARD_ERROR",V,Ie=>({durationMs:fe,error:{code:"SHARD_ERROR",message:V,status:H.status},functionPath:Ie.functionPath,...q,ok:!1,shardKey:F}));return}const ke=Array.isArray(De.results)?De.results:[],Zt=new Map(ke.map(V=>[V.id,V.status??H.status])),er=new Set(ke.map(V=>V.id));Xt(z,F,fe,Zt,H.status),$.push(...ke);for(const V of z)er.has(V.id)||$.push(W(V,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(V.id)}`))}));const Ke={"content-type":"application/json"},[Qe]=x;return x.length===1&&Qe!==void 0&&(Ke["x-d1-bookmark"]=Qe),Response.json({results:$},{headers:Ke,status:200})},Ct=async(o,d,h,c={},f={})=>{try{const b=h.__lunoraRef;if(typeof b!="string")throw new s("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:S,identity:E}=await ue(o,d,a);await Oe({functionPath:b,shardKey:f.shardKey},E);const v=f.shardKey??n,k=Ee(d,o,f.waitUntil);return await Ae(o,b,c,v,S,k)}catch(b){return ze(b)}},jt=1e3,Gt=async(o,d)=>{const h=e.backupRetain;if(h===void 0||h<=0)return;const c=[];let f;for(let S=0;S<jt;S+=1){const E=await o.list({cursor:f,prefix:d});for(const v of E.objects)v.key.endsWith(".manifest.json")&&c.push(v.key);if(!E.truncated||E.cursor===void 0)break;f=E.cursor}const b=c.toSorted((S,E)=>E.localeCompare(S)).slice(h);await Promise.all(b.flatMap(S=>{const E=S.slice(0,-14);return[o.delete(S),o.delete(E)]}))},Mt=async o=>{const d=e.backupStore,h=e.queryCoordinator;if(!d)throw new s("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!h)throw new s("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const c=y();if(!c||c.length===0)throw new s("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const f={authorization:`Bearer ${c}`,"content-type":"application/json"},b=e.backupTables;let S=0,E=0;const v=[];await nt(e,h,f,b,W=>{const j=`${JSON.stringify(W)}
|
|
5
|
-
`;S+=1,E+=go.encode(j).byteLength,v.push(j)},i);const k=e.backupPrefix??"backups/",U=new Date(o.scheduledTime).toISOString(),q=`${k}lunora-backup-${U.replaceAll(/[.:]/gu,"-")}.ndjson`,$=`${q}.manifest.json`;await d.put(q,new Blob(v,{type:"application/x-ndjson"}),{httpMetadata:{contentType:"application/x-ndjson"}});const x={bytes:E,createdAt:U,cron:o.cron,file:q,id:U,rows:S,scheduledTime:o.scheduledTime,...b?{tables:b.join(",")}:{}};await d.put($,`${JSON.stringify(x,void 0,2)}
|
|
6
|
-
`,{httpMetadata:{contentType:"application/json"}}),await Gt(d,k)},Ge=async(o,d,h)=>{const{observability:c}=e,f=Date.now(),b=Re(16),S=Re(8),E=pt(d);try{const v=await h();return de(c,{durationMs:Date.now()-f,functionPath:o,ok:!0,spanId:S,traceId:b},E),v}catch(v){throw de(c,{...Te(o,Date.now()-f,v,{}),spanId:S,traceId:b},E),v}finally{We(c,E)}},Kt=async(o,d,h)=>{m(d);const c=[],f=E=>E instanceof Error?E:new Error(String(E)),b=e.crons?.[o.cron];if(b)try{await b(o,d,h)}catch(E){c.push(f(E))}if(await N(o.cron,d,c,f),e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron)try{await Mt(o)}catch(E){c.push(f(E))}const[S]=c;if(c.length===1&&S)throw S;if(c.length>1)throw new AggregateError(c,`scheduled("${o.cron}") had ${String(c.length)} failure(s)`)},Qt=async(o,d)=>{try{const h=o??{},c=e.adminToken??(typeof h.LUNORA_ADMIN_TOKEN=="string"?h.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;const f=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:{outcome:d},functionPath:Po}),headers:{authorization:`Bearer ${c}`,"content-type":"application/json"},method:"POST"});await oe(i,n,f)}catch{}},Ft=async(o,d,h,c)=>{if(!e.authHandler)return;const f=await e.authHandler(o);if(!f)return;const b=e.authBasePath??Io;return qo(h.pathname,b)&&c.waitUntil?.(Qt(d,f.status>=400?"fail":"ok")),f},zt=async({args:o,env:d,functionPath:h,request:c,shardKey:f,waitUntil:b})=>{const S={functionPath:h,...f===void 0?{}:{shardKey:f}},{headers:E,identity:v}=await ue(c,d,a);await Oe(S,v);const k=f??n,U=Ee(d,c,b),q=()=>Ae(c,h,o,k,E,U),$=ft(S,e);return $&&e.x402Charge?e.x402Charge(c,{functionPath:h,price:$.price},q,ct({waitUntil:b})):q()},Wt=gr({functions:e.functions??{},invoke:zt,readJsonBody:Z,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),ve=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Ht={[Ao]: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"}}),[Oo]:(o,d,h)=>Ut(o,d,h),[ut]:(o,d,h,c)=>Bt(o,d,c),[bo]:(o,d,h,c)=>xt(o,d,c),[Eo]:(o,d)=>Y(o,d),[To]:(o,d)=>K(o,d),[_o]:async o=>{if(o.method!=="POST")throw new s("ws-token endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});C(o);const d=y();if(d===void 0)throw new s("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const h=await kr(d);return Response.json(h,{headers:{"cache-control":"no-store"}})},...P,...ne,...ee,..._t,...Rt,...St,...At,...vt,...Dt,...It,...Wt,...Ur({assertAdmin:C,getAuthAdmin:()=>e.authAdmin,parsePaging:me,queryParameter:he,readJsonBody:Z})};let ie=Je(e.security),Me=!1;const Jt=o=>{Me||(Me=!0,ie=Je(e.security,o??{}))},Vt=async(o,d)=>{if(!(e.adminGate===void 0||!vo(d)))try{await e.adminGate(o)&&g.add(o)}catch{}},Yt=async(o,d,h)=>{const c=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const E=Number(o.headers.get("content-length")??""),v=c.pathname===Ot?Et:ge;if(Number.isFinite(E)&&E>v)throw new s("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const f=await Ft(o,d,c,h);if(f)return f;if(ve){const E=`${o.method} ${c.pathname}`,v=ve[E]??ve[c.pathname];if(v)return v(o,d,h)}const b=Ht[c.pathname];return b?(await Vt(o,c.pathname),b(o,d,c,h)):e.voiceAgents!==void 0&&c.pathname.startsWith(ht)?qt(o,d,c):await Nt(o,d,h)||new Response("Not found",{status:404})};return{async fetch(o,d,h){e.passThroughOnException&&h.passThroughOnException?.(),Jt(d),m(d);const c=br(o,ie);if(c)return c;const f=Or(o,ie);if(f)return Ne(f,o,ie);try{const b=await Yt(o,d,h);return Ne(b,o,ie)}catch(b){return Ne(ze(b),o,ie)}finally{We(e.observability,pt(h))}},async queue(o,d,h){await Ge(`queue:${Lo(o)}`,h,async()=>{await e.queue?.(o,d,h)})},async scheduled(o,d,h){await Ge(`cron:${o.cron}`,h,async()=>{await Kt(o,d,h)})},serverQuery:Ct}},Ho=e=>Tt(e),Jo=e=>typeof e=="function"?{fetch:e}:e,Vo=e=>!!(e.crons??e.cronJobs??e.backupCron),la=(e,t)=>{const r=Jo(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=u=>{const l=Ho({...u,httpRouter:r});return n!==void 0&&!Vo(u)?{...l,scheduled:async(y,O,A)=>{await n(y,O,A)}}:l};if(typeof t!="function")return a(t);const i=t;return{fetch:(u,l,y)=>a(i(l)).fetch(u,l,y),queue:(u,l,y)=>a(i(l)).queue?.(u,l,y)??Promise.resolve(),scheduled:(u,l,y)=>a(i(l)).scheduled(u,l,y),serverQuery:(u,l,y,O,A)=>a(i(l)).serverQuery(u,l,y,O,A)}},Yo=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new s("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},ha=(e={})=>(t,r,n)=>Tt(Yo(e,r)).fetch(t,r,n??or),pa=e=>e;export{qr as GET_AUTH_AUDIT_LOG_OP,or as NOOP_EXECUTION_CONTEXT,ma as composeIdentityResolvers,Ho as composeWorker,ha as createLunoraHandler,Tt as createWorker,pa as defineRpcEnvelope,Ko as probeRelayCount,Yo as resolveLunoraOptions,ya as routeIdentityResolvers,la as withFrameworkWorker};
|