@lunora/runtime 1.0.0-alpha.171 → 1.0.0-alpha.172
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 +21 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/analyticsEngineSink-DQyRIP6N.mjs +1 -0
- package/dist/packem_shared/composeWorker-CZpnu4gj.mjs +6 -0
- package/dist/packem_shared/{otlp-resource-BI3MvjSy.mjs → otlp-resource-BwFJnvwB.mjs} +1 -1
- package/package.json +4 -4
- package/dist/packem_shared/analyticsEngineSink-BlkElAL2.mjs +0 -1
- package/dist/packem_shared/composeWorker-BDBzY5pl.mjs +0 -6
package/dist/index.d.mts
CHANGED
|
@@ -1979,6 +1979,12 @@ interface LogEvent {
|
|
|
1979
1979
|
level: ContextLogLevel;
|
|
1980
1980
|
/** Display string — the message, or the console-style args rendered and space-joined. */
|
|
1981
1981
|
message: string;
|
|
1982
|
+
/**
|
|
1983
|
+
* Cloudflare Ray ID of the request this line was emitted under (see
|
|
1984
|
+
* `shared/ray-id.ts`) — search Cloudflare Traces by it. Absent off the edge
|
|
1985
|
+
* and for dispatches no HTTP request started (an alarm, a subscription re-run).
|
|
1986
|
+
*/
|
|
1987
|
+
rayId?: string;
|
|
1982
1988
|
/** Shard key for single-shard calls; absent for the unnamed root DO. */
|
|
1983
1989
|
shardKey?: string;
|
|
1984
1990
|
/** Span id of the RPC this line was emitted under (trace correlation), or absent. */
|
|
@@ -2352,6 +2358,11 @@ interface SpanEvent {
|
|
|
2352
2358
|
* the outermost span, which is why the fold prefers it as a trace's anchor.
|
|
2353
2359
|
*/
|
|
2354
2360
|
dispatch?: boolean;
|
|
2361
|
+
/**
|
|
2362
|
+
* Cloudflare Ray ID of the request this span ran under (see
|
|
2363
|
+
* `shared/ray-id.ts`), exported as `cloudflare.ray_id`. Absent off the edge.
|
|
2364
|
+
*/
|
|
2365
|
+
rayId?: string;
|
|
2355
2366
|
/**
|
|
2356
2367
|
* The trace's settled W3C `sampled` verdict, stamped as the span leaves for a
|
|
2357
2368
|
* sink. Absent means no verdict reached this tier, which every consumer reads
|
|
@@ -2423,6 +2434,16 @@ interface ObservabilityEvent {
|
|
|
2423
2434
|
path?: string;
|
|
2424
2435
|
/** Port of the inbound request, when available. */
|
|
2425
2436
|
port?: number;
|
|
2437
|
+
/**
|
|
2438
|
+
* Cloudflare Ray ID of the inbound request — its `cf-ray` header with the
|
|
2439
|
+
* data-center suffix dropped (`8f2a1b3c4d5e6f70`). The key Cloudflare Traces
|
|
2440
|
+
* and Workers Logs are searched by, so a Lunora event can be followed to the
|
|
2441
|
+
* platform's view of the same request. Exported on the SERVER span as
|
|
2442
|
+
* `cloudflare.ray_id`, the attribute Cloudflare's own Workers traces use.
|
|
2443
|
+
* Informational only — never an authorization input. Absent off the edge
|
|
2444
|
+
* (`wrangler dev` does not set `cf-ray`).
|
|
2445
|
+
*/
|
|
2446
|
+
rayId?: string;
|
|
2426
2447
|
/** URL scheme of the inbound request (e.g. `"https"`). */
|
|
2427
2448
|
scheme?: string;
|
|
2428
2449
|
/** Shard key for single-shard calls; absent for fan-outs. */
|
package/dist/index.d.ts
CHANGED
|
@@ -1979,6 +1979,12 @@ interface LogEvent {
|
|
|
1979
1979
|
level: ContextLogLevel;
|
|
1980
1980
|
/** Display string — the message, or the console-style args rendered and space-joined. */
|
|
1981
1981
|
message: string;
|
|
1982
|
+
/**
|
|
1983
|
+
* Cloudflare Ray ID of the request this line was emitted under (see
|
|
1984
|
+
* `shared/ray-id.ts`) — search Cloudflare Traces by it. Absent off the edge
|
|
1985
|
+
* and for dispatches no HTTP request started (an alarm, a subscription re-run).
|
|
1986
|
+
*/
|
|
1987
|
+
rayId?: string;
|
|
1982
1988
|
/** Shard key for single-shard calls; absent for the unnamed root DO. */
|
|
1983
1989
|
shardKey?: string;
|
|
1984
1990
|
/** Span id of the RPC this line was emitted under (trace correlation), or absent. */
|
|
@@ -2352,6 +2358,11 @@ interface SpanEvent {
|
|
|
2352
2358
|
* the outermost span, which is why the fold prefers it as a trace's anchor.
|
|
2353
2359
|
*/
|
|
2354
2360
|
dispatch?: boolean;
|
|
2361
|
+
/**
|
|
2362
|
+
* Cloudflare Ray ID of the request this span ran under (see
|
|
2363
|
+
* `shared/ray-id.ts`), exported as `cloudflare.ray_id`. Absent off the edge.
|
|
2364
|
+
*/
|
|
2365
|
+
rayId?: string;
|
|
2355
2366
|
/**
|
|
2356
2367
|
* The trace's settled W3C `sampled` verdict, stamped as the span leaves for a
|
|
2357
2368
|
* sink. Absent means no verdict reached this tier, which every consumer reads
|
|
@@ -2423,6 +2434,16 @@ interface ObservabilityEvent {
|
|
|
2423
2434
|
path?: string;
|
|
2424
2435
|
/** Port of the inbound request, when available. */
|
|
2425
2436
|
port?: number;
|
|
2437
|
+
/**
|
|
2438
|
+
* Cloudflare Ray ID of the inbound request — its `cf-ray` header with the
|
|
2439
|
+
* data-center suffix dropped (`8f2a1b3c4d5e6f70`). The key Cloudflare Traces
|
|
2440
|
+
* and Workers Logs are searched by, so a Lunora event can be followed to the
|
|
2441
|
+
* platform's view of the same request. Exported on the SERVER span as
|
|
2442
|
+
* `cloudflare.ray_id`, the attribute Cloudflare's own Workers traces use.
|
|
2443
|
+
* Informational only — never an authorization input. Absent off the edge
|
|
2444
|
+
* (`wrangler dev` does not set `cf-ray`).
|
|
2445
|
+
*/
|
|
2446
|
+
rayId?: string;
|
|
2426
2447
|
/** URL scheme of the inbound request (e.g. `"https"`). */
|
|
2427
2448
|
scheme?: string;
|
|
2428
2449
|
/** Shard key for single-shard calls; absent for fan-outs. */
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as n,backupObjectKeyOfManifest as p,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as R,toFivetranResponse as x}from"./packem_shared/toAirbyteMessages-2d_iJXPf.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as y}from"./packem_shared/composeWorker-
|
|
1
|
+
import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as n,backupObjectKeyOfManifest as p,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as R,toFivetranResponse as x}from"./packem_shared/toAirbyteMessages-2d_iJXPf.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as y}from"./packem_shared/composeWorker-CZpnu4gj.mjs";import{createCrossShardRelationCapabilities as O}from"./packem_shared/createCrossShardRelationCapabilities-BiXSW10v.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-BSKqUsWS.mjs";import{LunoraError as H,toErrorResponse as P}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as v,a as I,d as D,r as M,b as F,s as N,w as G}from"./packem_shared/export-tap-CAyZ2TWC.mjs";import{HEALTH_PATH as U,HEALTH_READY_PATH as B,buildHealthRoutes as Y,d1Probe as w,durableObjectProbe as z,presenceProbe as X}from"./packem_shared/HEALTH_PATH-D0i8LhwT.mjs";import{LOG_ARCHIVE_PATH as V,resolveLogArchiveFromEnv as W}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as J,memoizeIdentityPerRequest as Q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as $,a as ee}from"./packem_shared/observability-DgurIZIR.mjs";import{analyticsEngineSink as oe,combineSinks as te,consoleSink as ae,otlpSink as se,pipelineLogSink as ie,sentrySink as ne,webhookSink as pe}from"./packem_shared/analyticsEngineSink-DQyRIP6N.mjs";import{D as me,c as fe}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as Re,createStaticShardRegistry as xe}from"./packem_shared/createQueryCoordinator-BkZPoV26.mjs";import{applyJurisdiction as le,resolveShard as de}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as _e,r as ke,b as ye}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as Oe,b as be,c as Ae,r as Le}from"./packem_shared/rest-routes-D3ShCTHh.mjs";import{decorateResponse as he,enforceOrigin as He,handleCorsPreflight as Pe,resolveSecurity as ge}from"./packem_shared/decorateResponse-CRrFNW1v.mjs";import{createShardClient as Ie}from"./packem_shared/createShardClient-BrzRLSs9.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Me}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ne}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ke}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Be,routeIdentityResolvers as Ye}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,me as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,U as HEALTH_PATH,B as HEALTH_READY_PATH,Ne as LOG_ARCHIVE_NOT_CONFIGURED,V as LOG_ARCHIVE_PATH,H as LunoraError,Ke as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Me as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,oe as analyticsEngineSink,le as applyJurisdiction,_e as applyRestCache,Oe as argsFromQuery,i as backupManifestKey,n as backupObjectKey,p as backupObjectKeyOfManifest,Y as buildHealthRoutes,be as buildRestRoutes,te as combineSinks,Be as composeIdentityResolvers,l as composeWorker,ae as consoleSink,O as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,v as createKvCursorStore,d as createLunoraHandler,I as createMemoryCursorStore,fe as createPipelineLogReader,Re as createQueryCoordinator,Ae as createRestRateLimit,Ie as createShardClient,xe as createStaticShardRegistry,u as createWorker,w as d1Probe,t as declareAppJurisdiction,he as decorateResponse,D as defineExportSink,_ as defineRpcEnvelope,z as durableObjectProbe,$ as emitLogEvent,ee as emitRpcEvent,He as enforceOrigin,Pe as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,J as memoizeIdentity,Q as memoizeIdentityPerRequest,f as normalizeBackupPrefix,se as otlpSink,ie as pipelineLogSink,X as presenceProbe,M as r2Sink,ke as requestCarriesCredentials,W as resolveLogArchiveFromEnv,k as resolveLunoraOptions,ge as resolveSecurity,de as resolveShard,ye as restCacheHeaders,Le as restSurfaceFromRegistry,Ye as routeIdentityResolvers,F as runExportTap,N as sanitizeChange,ne as sentrySink,R as toAirbyteMessages,P as toErrorResponse,x as toFivetranResponse,G as webhookExportSink,pe as webhookSink,y as withFrameworkWorker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as Z}from"@lunora/errors";import{redactArgs as j}from"@lunora/observability";import{e as c,L as h,o as $,c as k,O as V,f as Q,g as v,h as z,w as rr,i as tr,j as or,m as er}from"./otlp-resource-BwFJnvwB.mjs";const sr=r=>{if(typeof r=="string")return r;try{return JSON.stringify(r)??String(r)}catch{return String(r)}},W=r=>typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:sr(r),nr=512,ir=200,ar=r=>{const e=r.maxItems??nr,o=r.maxDelayMs??ir;let t=[],s,d,n;const a=()=>{s!==void 0&&(clearTimeout(s),s=void 0)},y=async()=>{a();const p=t;t=[];const u=n;d=void 0,n=void 0;try{p.length>0&&await r.export(p)}catch{}finally{u?.()}},m=p=>{d===void 0&&(d=new Promise(u=>{n=u}),s=setTimeout(()=>{y()},o)),p?.(d)};return{add:(p,u)=>{for(t.push(p);t.length>e;)t.shift();m(u),t.length>=e&&y()},flush:async p=>{if(t.length===0){a();return}const u=y();return p?.(u),u},get size(){return t.length}}},cr=/["\\\u0000-\u001F\uD800-\uDFFF]/,B=r=>cr.test(r)?JSON.stringify(r):`"${r}"`,R=r=>{if(r===void 0)return"null";if(typeof r=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof r=="number"){if(Number.isNaN(r))return"nan";if(r===1/0)return"inf";if(r===-1/0)return"-inf";if(Object.is(r,-0))return"-0"}if(typeof r=="string")return B(r);if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r)){let n="[";for(let a=0;a<r.length;a++)a>0&&(n+=","),n+=R(r[a]);return n+"]"}const e=Object.getPrototypeOf(r);if(e!==null&&e!==Object.prototype){const n=r.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${n} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const o=r,t=Object.keys(o).sort();let s="{",d=!0;for(const n of t){const a=o[n];a!==void 0&&(d?d=!1:s+=",",s+=B(n),s+=":",s+=R(a))}return s+"}"},dr=1,ur=0,lr=(r,e)=>{const o=[c(h.functionPath,r.functionPath),c(h.ok,r.ok)];r.method!==void 0&&o.push(c("http.request.method",r.method)),r.path!==void 0&&o.push(c("url.path",r.path)),o.push(c("http.route",r.functionPath)),r.scheme!==void 0&&o.push(c("url.scheme",r.scheme)),r.host!==void 0&&o.push(c("server.address",r.host)),r.port!==void 0&&o.push(c("server.port",r.port)),r.userAgent!==void 0&&o.push(c("user_agent.original",r.userAgent)),r.shardKey!==void 0&&o.push(c(h.shardKey,r.shardKey)),r.rayId!==void 0&&o.push(c(h.rayId,r.rayId)),o.push(c("http.response.status_code",r.error?.status??200)),r.error&&o.push(c(h.errorType,r.error.code),c("lunora.error_status",r.error.status)),r.fanOut&&o.push(c("lunora.fanout.table",r.fanOut.table),c("lunora.fanout.shards",r.fanOut.shards),c("lunora.fanout.failed",r.fanOut.failed));const t={attributes:o,endTimeUnixNano:k(e),kind:V.server,name:r.functionPath,...r.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},spanId:r.spanId??$(8),startTimeUnixNano:k(e-r.durationMs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId??$(16)};return r.traceFlags!==void 0&&(t.flags=r.traceFlags),r.error&&(t.events=[{attributes:[c("exception.type",r.error.code),c("exception.message",r.error.message)],name:"exception",timeUnixNano:k(e)}]),t},M=(r,e)=>{const o=new Map([[h.functionPath,c(h.functionPath,r.functionPath)]]);r.shardKey!==void 0&&o.set(h.shardKey,c(h.shardKey,r.shardKey)),r.userId!==void 0&&o.set(h.userId,c(h.userId,r.userId)),r.rayId!==void 0&&o.set(h.rayId,c(h.rayId,r.rayId)),r.errorType!==void 0&&o.set(h.errorType,c(h.errorType,r.errorType));for(const[t,s]of Object.entries(e??{}))o.set(t,c(t,W(s)));return[...o.values()]},pr=r=>{const e={attributes:M({errorType:r.error?.type,functionPath:r.functionPath,rayId:r.rayId,shardKey:r.shardKey,userId:r.userId},r.attributes),endTimeUnixNano:k(r.startTs+r.durationMs),flags:r.sampled===!1?ur:dr,kind:V[r.kind??"internal"],name:r.name,parentSpanId:r.parentSpanId,spanId:r.spanId,startTimeUnixNano:k(r.startTs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId},o=t=>v(Object.fromEntries(Object.entries(t??{}).map(([s,d])=>[s,W(d)])));return r.events!==void 0&&r.events.length>0&&(e.events=r.events.map(t=>({attributes:o(t.attributes),name:t.name,timeUnixNano:k(t.ts)}))),r.links!==void 0&&r.links.length>0&&(e.links=r.links.map(t=>({attributes:o(t.attributes),spanId:t.spanId,traceId:t.traceId}))),e},fr=r=>{const e=k(r.ts),o=M({functionPath:r.functionPath,shardKey:r.shardKey},r.attributes),t=r.traceId===void 0?void 0:[{asDouble:r.value,timeUnixNano:e,traceId:r.traceId}],s={asDouble:r.value,attributes:o,...t===void 0?{}:{exemplars:t},timeUnixNano:e};return r.kind==="gauge"?{gauge:{dataPoints:[s]},name:r.name}:r.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:o,bucketCounts:["1"],count:"1",...t===void 0?{}:{exemplars:t},explicitBounds:[],max:r.value,min:r.value,sum:r.value,timeUnixNano:e}]},name:r.name}:{name:r.name,sum:{aggregationTemporality:1,dataPoints:[s],isMonotonic:!0}}},mr=r=>{const e={attributes:M({functionPath:r.functionPath,rayId:r.rayId,shardKey:r.shardKey,userId:r.userId},r.fields),body:{stringValue:r.message},severityNumber:Q[r.level],severityText:r.level.toUpperCase(),timeUnixNano:k(r.ts)};return r.traceId!==void 0&&(e.traceId=r.traceId),r.spanId!==void 0&&(e.spanId=r.spanId),r.eventName!==void 0&&(e.eventName=r.eventName,e.attributes.push(c("event.name",r.eventName))),e},hr=1024,C=5;let A=0;const yr=(r,e)=>{if(A>=C)return;A+=1;let o;try{o=new URL(r).host}catch{o="<unparseable endpoint>"}const t=A===C?" Further OTLP rejections are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] collector ${o} rejected the export with HTTP ${String(e)}; the batch is DROPPED (there is no retry).${t}`)},gr=async r=>{const e=new Blob([r]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(e).arrayBuffer()},G=async(r,e,o,t)=>{try{const s=JSON.stringify(e),{byteLength:d}=new TextEncoder().encode(s),n=(d<hr?fetch(r,{body:s,headers:o,method:"POST"}):gr(s).then(a=>fetch(r,{body:a,headers:{...o,"content-encoding":"gzip"},method:"POST"}))).then(a=>{a.ok||yr(r,a.status)},()=>{});t?.(n),await n}catch{}},br=(r,e,o,t)=>{G(r,e,o,t?.waitUntil).catch(()=>{})},O=(r,e)=>e===!0&&r.ok,Ir=r=>r.kind==="metric"?void 0:r.event.traceId,kr=r=>{const e=Map.groupBy(r,t=>Ir(t)),o=e.get(void 0)??[];return e.delete(void 0),{byTrace:e,untraced:o}},J=5,Sr=(r,e,o)=>{if(e===void 0)return r;const{byTrace:t,untraced:s}=kr(r),d=[...s];let n=0,a;for(const[y,m]of t){let p;try{p=e({logs:m.filter(u=>u.kind==="log").map(u=>u.event),rpc:m.filter(u=>u.kind==="rpc").map(u=>u.event),spans:m.filter(u=>u.kind==="span").map(u=>u.event),traceId:y})}catch(u){n+=1,n===1&&(a=u),p=!0}p&&d.push(...m)}return n>0&&o(a,n),d},P=(r,e)=>{if(e===void 0)return r;try{return e(r)??void 0}catch{return}},Tr=r=>({...r,...r.fields===void 0?{}:{fields:j(r.fields)},message:j(r.message)}),H=(r,e,o)=>{if(r.kind==="rpc"){const s=P(r.event,e?.rpc);return s===void 0?void 0:{bucket:"spans",encoded:lr(s,r.endMs)}}if(r.kind==="span"){const s=P(r.event,e?.span);return s===void 0?void 0:{bucket:"spans",encoded:pr(s)}}if(r.kind==="log"){const s=P(o?Tr(r.event):r.event,e?.log);return s===void 0?void 0:{bucket:"logs",encoded:mr(s)}}const t=P(r.event,e?.metric);return t===void 0?void 0:{bucket:"metrics",encoded:fr(t)}},wr=["fuseCloudflareTraces","instrumentDatabase","metricHistory","traceFetch"],Nr=(r={})=>{const{onlyErrors:e}=r;return{onLog:o=>{o.level==="error"||o.level==="fatal"?console.error("[lunora:log]",o.functionPath,o.message):console.log("[lunora:log]",o.functionPath,o.message)},onMetric:o=>{console.log("[lunora:metric]",`${o.name}=${String(o.value)}`,o.kind,o.functionPath)},onRpc:o=>{O(o,e)||(o.ok?console.log("[lunora:rpc]",o):console.error("[lunora:rpc]",o))},onSpan:o=>{const t=o.ok?"ok":`error ${o.error?.type??""}`.trim();console.log("[lunora:span]",o.name,`${String(o.durationMs)}ms`,t,o.functionPath)}}},Lr=r=>{const{headers:e,onlyErrors:o,transform:t,transformLog:s,url:d}=r,n=z({"content-type":"application/json"},e),a=(y,m)=>{try{const p=fetch(d,{body:JSON.stringify(y),headers:n,method:"POST"}).catch(()=>{});m?.waitUntil&&m.waitUntil(p)}catch{}};return{onLog:(y,m)=>{const p=P(y,s);p!==void 0&&a(p,m)},onRpc:(y,m)=>{if(O(y,o))return;const p=P(y,t);p!==void 0&&a(p,m)}}},Ar=r=>{const{capture:e,captureLog:o}=r;if(typeof e!="function")throw new TypeError("sentrySink requires a `capture` callback — wire your own Sentry client, e.g. `sentrySink({ capture: (event) => Sentry.captureMessage(event.name) })`. There is no `dsn` option; the runtime bundles no Sentry client.");const t=r.onlyErrors??!0;return{onLog:o?s=>{try{o(s)}catch{}}:void 0,onRpc:s=>{if(!O(s,t))try{e(s)}catch{}}}},Rr=r=>{const{dataset:e,onlyErrors:o}=r;return{onRpc:t=>{if(!O(t,o))try{e.writeDataPoint({blobs:[t.functionPath,t.ok?"ok":"error",t.shardKey??"",t.error?.code??"",t.fanOut?.table??""],doubles:[t.durationMs,t.ok?0:1,t.fanOut?.shards??0,t.fanOut?.failed??0],indexes:[t.functionPath]})}catch{}}}},Mr=r=>{const{pipeline:e,serializeFields:o}=r;return{onLog:(t,s)=>{try{const d={functionPath:t.functionPath,level:t.level,message:t.message,ts:t.ts};t.fields&&(d.fields=o===!0?JSON.stringify(t.fields):t.fields);for(const a of["shardKey","userId","traceId","spanId"])t[a]!==void 0&&(d[a]=t[a]);const n=e.send([d]).catch(()=>{});s?.waitUntil&&s.waitUntil(n)}catch{}}}},_r=r=>{const{batch:e,deploymentEnvironment:o,detectResources:t,endpoint:s,headers:d,onlyErrors:n,postProcessor:a,resourceAttributes:y,serviceNamespace:m,serviceVersion:p,tailSampler:u,token:X}=r,_=r.serviceName??"lunora",x=r.redactLogs??!0;if(e!==!1&&e?.maxItems!==void 0&&(!Number.isInteger(e.maxItems)||e.maxItems<1))throw new Z("ENV_INVALID",`otlpSink: \`batch.maxItems\` must be a positive integer, received ${String(e.maxItems)}.`);const U={...p===void 0?{}:{"service.version":p},...m===void 0?{}:{"service.namespace":m},...o===void 0?{}:{"deployment.environment":o},...y},D=new WeakMap,I=l=>{if(t!==!0||l?.resourceAttributes===void 0)return U;const i=D.get(l);if(i!==void 0)return i;const f=er(l.resourceAttributes(),U);return D.set(l,f),f};let S=s;for(;S.endsWith("/");)S=S.slice(0,-1);const F={logs:{url:`${S}/v1/logs`,wrap:or},metrics:{url:`${S}/v1/metrics`,wrap:tr},spans:{url:`${S}/v1/traces`,wrap:rr}},K=z({"content-type":"application/json"},d,X);let L=0;const q=(l,i)=>{if(L>=J)return;L+=1;const f=L===J?" Further tailSampler failures from this sink are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] tailSampler threw for ${String(i)} trace(s) in this flush window; keeping them (fail-open), so the sampling policy did NOT apply.${f}`,l)},Y=async l=>{const i=Sr(l,u,q),f=new Map;for(const g of i){const b=H(g,a,x);if(b===void 0)continue;const N=R(g.resource);let w=f.get(N);w===void 0&&(w={logs:[],metrics:[],resource:g.resource,spans:[]},f.set(N,w)),w[b.bucket].push(b.encoded)}const T=[];for(const[,g]of f)for(const b of["spans","logs","metrics"])if(g[b].length>0){const{url:N,wrap:w}=F[b];T.push(G(N,w(g[b],"@lunora/runtime",_,g.resource),K))}await Promise.all(T)};if(e===!1){const l=(i,f)=>{const T=H(i,a,x);if(T!==void 0){const{url:g,wrap:b}=F[T.bucket];br(g,b(T.encoded,"@lunora/runtime",_,i.resource),K,f)}};return{onLog:(i,f)=>{l({event:i,kind:"log",resource:I(f)},f)},onMetric:(i,f)=>{l({event:i,kind:"metric",resource:I(f)},f)},onRpc:(i,f)=>{O(i,n)||l({endMs:Date.now(),event:i,kind:"rpc",resource:I(f)},f)},onSpan:(i,f)=>{l({event:i,kind:"span",resource:I(f)},f)}}}const E=ar({export:Y,...e?.maxDelayMs===void 0?{}:{maxDelayMs:e.maxDelayMs},...e?.maxItems===void 0?{}:{maxItems:e.maxItems}});return{flush:l=>{E.flush(l?.waitUntil).catch(()=>{})},onLog:(l,i)=>{E.add({event:l,kind:"log",resource:I(i)},i?.waitUntil)},onMetric:(l,i)=>{E.add({event:l,kind:"metric",resource:I(i)},i?.waitUntil)},onRpc:(l,i)=>{O(l,n)||E.add({endMs:Date.now(),event:l,kind:"rpc",resource:I(i)},i?.waitUntil)},onSpan:(l,i)=>{E.add({event:l,kind:"span",resource:I(i)},i?.waitUntil)}}},xr=(...r)=>{const e=(t,s)=>{for(const d of r){const n=d[t];if(n)try{n.apply(d,s)}catch{}}},o={};for(const t of r)for(const s of wr)o[s]===void 0&&t[s]!==void 0&&(o[s]=t[s]);return{...o,flush:t=>{e("flush",[t])},onLog:(t,s)=>{e("onLog",[t,s])},onMetric:(t,s)=>{e("onMetric",[t,s])},onRpc:(t,s)=>{e("onRpc",[t,s])},onSpan:(t,s)=>{e("onSpan",[t,s])}}};export{Rr as analyticsEngineSink,xr as combineSinks,Nr as consoleSink,_r as otlpSink,Mr as pipelineLogSink,Ar as sentrySink,Lr as webhookSink};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{isLunoraError as mr,toErrorBody as wr}from"@lunora/errors";import{e as tn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as gr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as yr,f as br}from"./base64-Bl1_r2k1.mjs";import{i as _r,e as Rr,a as Er,E as gt,d as Ar}from"./identity-header-pR617HTs.mjs";import{O as yt,a as bt}from"./origin-paywall-B6eOO67m.mjs";import{o as ge,b as nn,p as Sr,m as Tr,d as Or,a as vr,r as Ir}from"./otlp-resource-BwFJnvwB.mjs";import{r as kr,f as _t,a as ce,S as Rt}from"./observability-DgurIZIR.mjs";import{e as Ee,d as Ye,a as Pr}from"./wire-codec-BLvSm5Mn.mjs";import{d as ee,e as ne,M as rn,b as Dr,f as Nr,g as on,w as Ur,h as an,t as Cr}from"./rest-routes-D3ShCTHh.mjs";import{LunoraError as c,toErrorResponse as Et}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as we}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as nt,BACKUP_KEY_PREFIX as rt,isBackupManifestKey as Br,backupObjectKeyOfManifest as sn,backupObjectKey as xr,backupManifestKey as Hr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Lr,buildStorageAdminRoutes as jr,STORAGE_UPLOAD_MAX_BODY_BYTES as Mr,STORAGE_PATH as $r}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as Kr,e as Fr,f as At,g as Gr,h as Qr}from"./export-tap-CAyZ2TWC.mjs";import{buildHealthRoutes as Wr,durableObjectProbe as zr,d1Probe as Vr,presenceProbe as je}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as Jr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Bi,routeIdentityResolvers as xi}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Yr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{pruneShardRegistry as qr,createQueryCoordinator as Xr,createDefaultShardRegistry as Zr}from"./createQueryCoordinator-BkZPoV26.mjs";import{resolveShard as ye,applyJurisdiction as Me}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as St,handleCorsPreflight as eo,enforceOrigin as to,decorateResponse as $e,enforceWebSocketOrigin as Tt}from"./decorateResponse-CRrFNW1v.mjs";const no=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},cn="__lunoraBranch",ro=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,cn),oo=`may not contain the reserved workflow branch-marker key ("${cn}")`,ao=async e=>{const t=[];let n;for(;;){const o=await e(n);if(t.push(...Array.isArray(o.records)?o.records:[]),o.truncated!==!0||typeof o.cursor!="string"||o.cursor.length===0)return t;if(o.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=o.cursor}},ot=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,d=a<t.length?t.charCodeAt(a):0;o|=i^d}return o===0},so=/already[\s_-]?exists/iu,io=e=>so.test(e instanceof Error?e.message:String(e)),co=(e,t,n,o)=>{const a=e.get(t);if(a!==void 0)return a;tn(e,o);const i=n().catch(d=>{throw e.get(t)===i&&e.delete(t),d});return e.set(t,i),i},at=new TextEncoder,uo=Array.from({length:32},(e,t)=>t);new RegExp(`[${uo.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const lo=64,ho=new Map,dn=async e=>co(ho,e,async()=>crypto.subtle.importKey("raw",at.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),lo),un=async(e,t)=>{const n=await dn(e),o=await crypto.subtle.sign("HMAC",n,at.encode(t));return yr(new Uint8Array(o))},fo=async(e,t,n)=>{const o=await dn(e);return crypto.subtle.verify("HMAC",o,n,at.encode(t))},po="x-lunora-ray-id",mo=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,ln=e=>e==null?void 0:mo.exec(e.trim())?.[1]?.toLowerCase(),wo=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(wo);const go=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),yo=-100,bo=15,_o=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&go.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>bo?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<yo?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},Ot=e=>{const t=e.cf;return t===void 0?void 0:_o(t)},qe="::relay::",Ro=(e,t)=>`${e}${qe}${String(t)}`,Xe="::replica::",Eo=(e,t)=>`${e}${Xe}${t}`,Ao=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},So=(e,t,n)=>e?.[n]??t?.[n],To=(e,t,n,o)=>{const a=So(e,t,n);if(!(typeof a!="object"||a===null))return o.every(i=>typeof a[i]=="function")?a:void 0},Oo=new Set(["1","enabled","on","true","yes"]),vo=new Set(["0","disabled","false","no","off"]),Io=(e,t)=>{const n=(e??"").trim().toLowerCase();return Oo.has(n)?!0:vo.has(n)?!1:t},hn="v1",ko=6e4,Po=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??ko),o=`${hn}.${String(n)}`,a=await un(e,o);return{expiresAtMs:n,token:`${o}.${a}`}},Do=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[a,i,d]=o;if(a!==hn||d.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let h;try{h=br(d)}catch{return!1}return fo(e,`${a}.${i}`,h)},N="/_lunora/admin/auth",No={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},C=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},he=(e,t)=>{const n=e(t);if(n===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},fn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ke=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},vt=e=>{const t=fn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},It=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[o,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[o]=a);return n},Uo={[`${N}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${N}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${N}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${N}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${N}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${N}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${N}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${N}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${N}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${N}/sign-up-invitations/create`]:{build:({body:e})=>({email:C(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:te(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${N}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:C(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${N}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${N}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${N}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${N}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${N}/users/create`]:{build:({body:e})=>({data:Ke(e,"data"),email:C(e,"email"),name:C(e,"name"),password:te(e,"password"),role:fn(e.role)}),http:"POST",method:"createUser"},[`${N}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:C(e,"userId")}},http:"POST",method:"updateUser"},[`${N}/users/role`]:{build:({body:e})=>({role:vt(e),userId:C(e,"userId")}),http:"POST",method:"setRole"},[`${N}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:C(e,"userId")}),http:"POST",method:"banUser"},[`${N}/users/unban`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"unbanUser"},[`${N}/users/password`]:{build:({body:e})=>({newPassword:C(e,"newPassword"),userId:C(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${N}/users/remove`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${N}/users/impersonate`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"impersonateUser"},[`${N}/sessions/revoke`]:{build:({body:e})=>({sessionId:C(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${N}/sessions/revoke-all`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${N}/accounts/unlink`]:{build:({body:e})=>({accountId:C(e,"accountId"),userId:C(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${N}/two-factor/disable`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${N}/passkeys/delete`]:{build:({body:e})=>({passkeyId:C(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${N}/organizations/members/remove`]:{build:({body:e})=>({memberId:C(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${N}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:C(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${N}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ke(e,"metadata"),name:C(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${N}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ke(e,"metadata"),name:te(e,"name"),organizationId:C(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${N}/organizations/remove`]:{build:({body:e})=>({organizationId:C(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${N}/organizations/members/add`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),role:te(e,"role"),userId:C(e,"userId")}),http:"POST",method:"addMember"},[`${N}/organizations/members/invite`]:{build:({body:e})=>({email:C(e,"email"),inviterId:te(e,"inviterId"),organizationId:C(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${N}/organizations/members/role`]:{build:({body:e})=>({memberId:C(e,"memberId"),role:vt(e)}),http:"POST",method:"updateMemberRole"},[`${N}/organizations/teams/create`]:{build:({body:e})=>({name:C(e,"name"),organizationId:C(e,"organizationId")}),http:"POST",method:"createTeam"},[`${N}/organizations/teams/update`]:{build:({body:e})=>({name:C(e,"name"),teamId:C(e,"teamId")}),http:"POST",method:"updateTeam"},[`${N}/organizations/teams/remove`]:{build:({body:e})=>({teamId:C(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${N}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:C(e,"teamId"),userId:C(e,"userId")}),http:"POST",method:"addTeamMember"},[`${N}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:C(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${N}/organizations/roles/create`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),permission:It(e),role:C(e,"role")}),http:"POST",method:"createOrgRole"},[`${N}/organizations/roles/update`]:{build:({body:e})=>({permission:It(e),roleId:C(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${N}/organizations/roles/remove`]:{build:({body:e})=>({roleId:C(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Co=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof c)throw i;const d=i,f=typeof d.code=="string"?d.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:f,status:No[f]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const d=e.getAuthAdmin();if(d===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=d[i.method];if(f===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const h=new URL(a.url),m={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:S=>e.queryParameter(h,S)},b=i.build(m),A=await t(()=>f(b));return Response.json(i.returns==="void"?{ok:!0}:A,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[a,i]of Object.entries(Uo))o[a]=d=>n(d,i);return o},kt="__lunora_admin__:getAuthAuditLog",Pt=e=>typeof e=="string"&&e!==""?e:void 0,Dt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Bo=e=>async(n,o)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=Pt(o.actorId),d=Pt(o.event),f=Dt(o.sinceSeq),h=Dt(o.limit),m={...i===void 0?{}:{actorId:i},...d===void 0?{}:{event:d},...f===void 0?{}:{sinceSeq:f},...h===void 0?{}:{limit:h}};let b;try{b=await a.read(m)}catch(S){throw S instanceof c?S:(console.error("[lunora] auth audit read failed:",S),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const A={entries:b};return Response.json({result:Ee(A)},{headers:{"content-type":"application/json"},status:200})},Ze="__lunora_admin__:copyAuthToJurisdiction",pn="__lunora_admin__:purgeUnpinnedAuth",xo=e=>async(t,n,o)=>{if(n!==Ze&&n!==pn)return;e.assertAdmin(t);const a=e.getMove();if(a===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===Ze?await a.copy({force:o.force===!0}):await a.purge();return Response.json({result:Ee(i)},{headers:{"content-type":"application/json"},status:200})},Ho=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?o.push(a):n.push(a);return{globalTables:o,shardLocalTables:n}},Lo=async(e,t,n,o,a,i)=>{if(n!==void 0&&o.length===0)return[];const d=await e.orchestrateExport(a,{args:{tables:o},defaultShardKey:i,headers:t,tables:o}),f=d.shards.filter(h=>h.error);if(f.length>0){const h=f.map(m=>`${m.shardKey}: ${m.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(f.length)} of ${String(d.shards.length)} shard(s) — ${h}`,{code:"EXPORT_SHARD_FAILED",status:502})}return d.shards.flatMap(h=>h.rows??[])},mn=async(e,t,n,o,a)=>{const i=o??e.listSchemaTables?.();o===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:d,shardLocalTables:f}=Ho(e,i),h=await Lo(t,n,i,f,a,e.defaultShardKey??"__root__"),m=e.exportGlobals,b=o===void 0||d.length>0;return(async function*(){yield*h,b&&m&&(yield*m({tables:d}))})()},jo=async(e,t,n,o,a,i)=>{for await(const d of await mn(e,t,n,o,i))a(d)},Mo=new TextEncoder,$o=1e3,wn=10,Ko=200,Nt=8,gn="lunoraBackupCron",Ut=24*1048576,Ct=e=>{const t=e.slice(0,wn).map(o=>sn(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Fo=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const a of e)n.set(a,o),o+=a.byteLength;return n},st=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let d=0;d<$o;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)Br(h.key)&&h.customMetadata?.[gn]===o&&a.push(h.key);if(!f.truncated||f.cursor===void 0)break;i=f.cursor}return{eligible:a.length,stale:a.toSorted((d,f)=>f.localeCompare(d)).slice(n)}},Go=async(e,t,n,o,a)=>{const{stale:i}=await st(e,t,n,o),d=new Set(a),f=i.filter(k=>d.has(k)),h=f.slice(0,Ko),m=i.length-h.length,b=a.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:b,remaining:m};const A=[],S=[];for(let k=0;k<h.length;k+=Nt){const w=await Promise.allSettled(h.slice(k,k+Nt).map(async g=>(await e.delete(sn(g)),await e.delete(g),g)));for(const[g,y]of w.entries())y.status==="fulfilled"?A.push(y.value):S.push(h[k+g])}return A.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(A.length)}: ${Ct(A)}`),S.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(S.length)}: ${Ct(S)}`),{deleted:A,failed:S,ignored:b,remaining:m}},Qo=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=nt(e.backupPrefix??rt),o=e.backupCron,{eligible:a,stale:i}=o===void 0?{eligible:0,stale:[]}:await st(t,n,e.backupRetain,o);return{cron:o,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},Wo=async(e,t,n,o,a)=>{const i=e.backupStore;if(!i)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!o||o.length===0)throw new c("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const d={authorization:`Bearer ${o}`,"content-type":"application/json"},f=e.backupTables;let h=0,m=0,b=[];await jo(e,t,d,f,I=>{const E=Mo.encode(`${JSON.stringify(I)}
|
|
2
|
+
`);if(h+=1,m+=E.byteLength,m>Ut)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Ut)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});b.push(E)},n);const S=nt(e.backupPrefix??rt),k=new Date(a.scheduledTime).toISOString(),w=xr(S,k),g=Fo(b,m);b=[];const y=Lr(await crypto.subtle.digest("SHA-256",g));await i.put(w,g,{httpMetadata:{contentType:"application/x-ndjson"},sha256:y});const v={bytes:m,createdAt:k,cron:a.cron,file:w,id:k,rows:h,scheduledTime:a.scheduledTime,sha256:y,...f?{tables:f.join(",")}:{}};await i.put(Hr(w),`${JSON.stringify(v,void 0,2)}
|
|
3
|
+
`,{customMetadata:{[gn]:a.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:I}=await st(i,S,e.backupRetain,a.cron);if(I.length>0){const E=I.slice(0,wn),j=I.length-E.length;console.info(`[lunora] backup retention: ${String(I.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${E.join(", ")}${j>0?` (+${String(j)} more)`:""}`)}}catch(I){console.warn(`[lunora] backup ${w} was written, but the retention report failed:`,I)}},zo=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const o=e.backupCron,a=e.backupRetain;if(o===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return Go(n,nt(e.backupPrefix??rt),a,o,t)},Vo="/_lunora/admin/backup/retention",Jo="/_lunora/admin/backup/prune",Yo=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,a=(f,h)=>{o(f,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${h} requires a \`backupStore\` on the worker`})},i=async f=>(M(f,"GET","Backup-retention"),a(f,"retention preview"),Response.json(await Qo(t),{headers:{"cache-control":"no-store"}})),d=async f=>{M(f,"POST","Backup-prune"),a(f,"prune");const{confirm:h}=await n(f);if(!Array.isArray(h)||h.some(m=>typeof m!="string"))throw new c("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await zo(t,h),{headers:{"cache-control":"no-store"}})};return{[Jo]:d,[Vo]:i}},Bt=500,qo=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const o=e;if(typeof o.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(o.functionPath.startsWith("__lunora_relation__:")||o.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(o.args!==void 0&&(typeof o.args!="object"||o.args===null||Array.isArray(o.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(o.id!==void 0&&typeof o.id!="number")throw new c("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:o.args===void 0?{}:o.args,baselineSeq:typeof o.baselineSeq=="number"?o.baselineSeq:void 0,clientId:typeof o.clientId=="string"?o.clientId:void 0,clientSeq:typeof o.clientSeq=="number"?o.clientSeq:void 0,functionPath:o.functionPath,id:typeof o.id=="number"?o.id:t,mutationId:typeof o.mutationId=="string"?o.mutationId:void 0},shardKey:typeof o.shardKey=="string"?o.shardKey:n}},Xo=(e,t)=>{if(e.length>Bt)throw new c(`RPC batch exceeds the ${String(Bt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,o=new Set;for(const[a,i]of e.entries()){const{entry:d,shardKey:f}=qo(i,a,t);if(o.has(d.id))throw new c(`batch call id ${String(d.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});o.add(d.id);const h=n.get(f)??[];h.push(d),n.set(f,h)}return n},Zo="/_lunora/admin/export",ea="/_lunora/admin/import",ta="/_lunora/admin/sync",na="/_lunora/admin/connector/sync",ra="/_lunora/admin/apply",oa="/_lunora/admin/export-tap/run",aa=new TextEncoder,sa=async e=>{const n=await ne(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const o=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});o.push(a)}return{tables:o}},Fe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,ia=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:a,knownTables:i,queryCoordinator:d,assertAdmin:f,resolveForwardContext:h,shardDO:m,prepareExportRows:b,streamingImport:A,syncGlobals:S}=e,k=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const U=await sa(E),{headers:K}=await h(E,j),W=await b(K,U.tables),J=new ReadableStream({async pull(Y){try{for await(const G of W)Y.enqueue(aa.encode(`${JSON.stringify(G)}
|
|
4
|
+
`));Y.close()}catch(G){Y.error(G)}}});return new Response(J,{headers:{"content-type":"application/x-ndjson"},status:200})},w=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const U=await ee(E),K=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},W=typeof U.epochs=="object"&&U.epochs!==null?U.epochs:{},J=typeof U.limit=="number"?U.limit:void 0,Y=typeof U.globalCursor=="number"?U.globalCursor:0,G=Fe(U.tables),{headers:re}=await h(E,j),Q=G??i(),de=await d.orchestrateCdcSync(m,{cursors:K,defaultShardKey:n,epochs:W,headers:re,limit:J,tables:Q}),oe=S?await S({limit:J,sinceSeq:Y}):void 0;return Response.json({global:oe,shards:de.shards},{status:200})},g=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const U=await ee(E),K=Fr(U.cursor),W=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,J=Fe(U.tables),{headers:Y}=await h(E,j),G=J??i(),re=await d.orchestrateCdcSync(m,{cursors:K.s,defaultShardKey:n,headers:Y,limit:W,tables:G}),Q=[],de={...K.s};let oe=!1;for(const se of re.shards)oe=At(Q,se.changes??[],Qr(W))||oe,de[se.shardKey]=se.cursor;let be=K.g;if(S){const se=await S({limit:W,sinceSeq:K.g});oe=At(Q,se.changes,W)||oe,be=se.cursor}const z=Gr({g:be,s:de,v:1}),ae={changes:Q,hasMore:oe,nextCursor:z};return Response.json(ae,{status:200})},y=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const U=await ee(E),W=(Array.isArray(U.batches)?U.batches:[]).map(Q=>Q).filter(Q=>Q!==null&&typeof Q=="object"&&typeof Q.shardKey=="string"&&Array.isArray(Q.changes)),J=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:Y}=await h(E,j),G=await d.orchestrateApplyCdc(m,{batches:W,headers:Y}),re=J.length>0&&t?await t({changes:J}):0;return Response.json({applied:G.applied+re,failed:G.failed,ok:G.ok},{status:200})},v=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const{headers:U}=await h(E,j),K=await A(E,U);return Response.json(K,{headers:{"content-type":"application/json"},status:K.failed.length>0?207:200})},I=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;if(f(E),a===void 0||Object.keys(a).length===0||o===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const U=await ee(E),K=typeof U.sink=="string"?U.sink:void 0,W=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,J=Fe(U.tables);if(K===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const Y=a[K];if(Y===void 0)throw new c(`Export-tap sink "${K}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:G}=await h(E,j),re=J??i(),Q=await Kr({coordinator:d,cursorStore:o,defaultShardKey:n,headers:G,limit:W,shardDO:m,sink:Y,tables:re});return Response.json(Q,{headers:{"content-type":"application/json"},status:200})};return{[ra]:y,[na]:g,[Zo]:k,[oa]:I,[ea]:v,[ta]:w}},ca=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const o=n;return typeof o.table!="string"||o.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!o.doc||typeof o.doc!="object"||Array.isArray(o.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:o.table},ok:!1}:{doc:o.doc,ok:!0,table:o.table}},da=(e,t,n,o,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:o}},ua=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const o=[],a=[],i=new Map;let d=0,f=0;const h=e.body.getReader(),m=new TextDecoder;let b="",A=0;const S=k=>{f+=1;const w=k.trim();if(w.length===0)return;d+=1;const g=ca(w,f);if(!g.ok){o.push(g.error);return}const{doc:y,table:v}=g,I=t.resolveTableSharding?.(v);if(I?.mode.kind==="global"){a.push({doc:y,line:f,table:v});return}const E=da(y,v,I,n,f);if(!E.ok){o.push(E.error);return}const j=i.get(E.shardKey);j?j.rows.push({doc:y,table:v}):i.set(E.shardKey,{rows:[{doc:y,table:v}],shardKey:E.shardKey,startLine:f})};for(;;){const{done:k,value:w}=await h.read();if(k)break;if(w&&(A+=w.byteLength,A>rn))throw await h.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});b+=m.decode(w,{stream:!0});let g=b.indexOf(`
|
|
5
|
+
`);for(;g!==-1;){const y=b.slice(0,g);b=b.slice(g+1),S(y),g=b.indexOf(`
|
|
6
|
+
`)}}return b.length>0&&S(b),{errors:o,globalRows:a,perShard:i,received:d}},la=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),xt=(e,t)=>{for(const[n,o]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+o;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},ha=async(e,t,n,o,a)=>{const i=t.defaultShardKey??"__root__",{errors:d,globalRows:f,perShard:h,received:m}=await ua(e,t,i),b={conflicts:0,errors:d,failed:[],inserted:{}},A=[];if(t.resolveTableSharding===void 0&&h.size>0&&A.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const S=await n.orchestrateImport(a,{batches:[...h.values()],headers:o});xt(b,S),b.failed.push(...la(S.shards))}if(f.length>0)if(t.importGlobals){const S=f[0]?.line??1,k=await t.importGlobals({rows:f,startLine:S});xt(b,k)}else for(const S of f)b.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:S.line,message:`row targets global table "${S.table}" but no \`importGlobals\` is configured`,table:S.table});return{conflicts:b.conflicts,errors:b.errors,failed:b.failed,inserted:b.inserted,received:m,...A.length>0?{warnings:A}:{}}},fa=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),Ge=e=>typeof e=="object"&&e!==null?e:{},Qe=e=>typeof e.kind=="string"?e.kind:"unknown",pa=(e,t)=>{let n=Ge(t),o=!1;Qe(n)==="optional"&&(o=!0,n=Ge(n._meta?.inner));const a=Qe(n),i=n._meta??{},d={kind:a,name:e,optional:o};if(a==="id"&&typeof i.tableName=="string"&&(d.table=i.tableName),a==="array"){const f=Qe(Ge(i.inner));f!=="unknown"&&(d.element=f)}return d},ma=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>pa(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),wa="/_lunora/admin/functions",ga="/_lunora/admin/cron-jobs",ya="/_lunora/admin/architecture",ba="/_lunora/admin/openapi",_a="/_lunora/admin/openrpc",Ra="/_lunora/admin/global/tables",Ea="/_lunora/admin/global/table",Aa="/_lunora/admin/global/facet",Ht=e=>{if(e===void 0||e==="")return;let t;try{t=Ye(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(o=>{if(typeof o!="object"||o===null||typeof o.column!="string")return[];const{column:a,value:i}=o;return[{column:a,value:i}]});return n.length===0?void 0:n},Sa=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:{}}),Ta=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"}),Oa=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:a,requireAdminOption:i}=e,d=w=>{M(w,"GET","Functions");const g=i(w,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),y=Object.entries(g).flatMap(([v,I])=>I.visibility==="internal"||I.kind==="stream"?[]:[{args:ma(I.args),kind:I.kind,path:v}]).toSorted((v,I)=>v.path.localeCompare(I.path));return Response.json({functions:y},{headers:{"content-type":"application/json"},status:200})},f=w=>{M(w,"GET","Cron-jobs");const g=i(w,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),y=Object.entries(g).flatMap(([v,I])=>I.map(E=>({args:E.args,cron:v,functionPath:E.functionPath,name:E.name,shardKey:E.shardKey,workflow:E.workflow}))).toSorted((v,I)=>v.name.localeCompare(I.name));return Response.json({jobs:y},{headers:{"content-type":"application/json"},status:200})},h=w=>(M(w,"GET","Architecture"),t(w),Response.json(n.architecture??fa,{headers:{"content-type":"application/json"},status:200})),m=w=>(M(w,"GET","OpenAPI"),t(w),Response.json(n.openApiSpec??Sa,{headers:{"content-type":"application/json"},status:200})),b=w=>(M(w,"GET","OpenRPC"),t(w),Response.json(n.openRpcSpec??Ta,{headers:{"content-type":"application/json"},status:200})),A=async w=>{M(w,"GET","Global-tables");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await g.listTables(),{headers:{"content-type":"application/json"},status:200})},S=async w=>{M(w,"GET","Global-table");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),y=new URL(w.url),v=a(y,"table");if(v===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const I=await g.readTablePage({...o(w),filters:Ht(a(y,"filters")),table:v});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},k=async w=>{M(w,"GET","Global-facet");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),y=new URL(w.url),v=a(y,"table"),I=a(y,"column");if(v===void 0||I===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const E=a(y,"limit"),j=E===void 0?void 0:Number(E),H=await g.facetColumn({column:I,filters:Ht(a(y,"filters")),limit:j!==void 0&&Number.isFinite(j)?j:void 0,table:v});return Response.json(H,{headers:{"content-type":"application/json"},status:200})};return{[ga]:f,[wa]:d,[Aa]:k,[Ea]:S,[Ra]:A,[ya]:h,[ba]:m,[_a]:b}},va="/_lunora/admin/kv/namespaces",Ia="/_lunora/admin/kv/keys",yn="/_lunora/admin/kv/value",bn=32*1048576,Lt=60,ka=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=w=>n(w,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=w=>Response.json(w,{headers:{"content-type":"application/json"},status:200}),i=(w,g)=>{const y=new URL(w.url),v=y.searchParams.get("namespace")??"",I=y.searchParams.get("key")??"";if(v==="")throw new c(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(I==="")throw new c(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:I,namespace:v}},d=async(w,g)=>{if(!(await w.listNamespaces()).some(v=>v.binding===g))throw new c(`Unknown KV namespace binding \`${g}\``,{code:"NOT_FOUND",status:404})},f=async w=>(M(w,"GET","KV-namespaces"),a({namespaces:await o(w).listNamespaces()})),h=async w=>{M(w,"GET","KV-keys");const g=o(w),y=new URL(w.url),v=y.searchParams.get("namespace")??"";if(v==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const I=y.searchParams.get("prefix")??void 0,E=y.searchParams.get("cursor")??void 0,j=y.searchParams.get("limit"),H=j===null?void 0:Number.parseInt(j,10);if(H!==void 0&&(!Number.isInteger(H)||H<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const U=H===void 0?void 0:Math.min(H,1e3);return await d(g,v),a(await g.listKeys({cursor:E,limit:U,namespace:v,prefix:I}))},S={DELETE:async w=>{const g=o(w),y=i(w,"DELETE");return await d(g,y.namespace),await g.deleteKey(y),a({deleted:!0})},GET:async w=>{const g=o(w),y=i(w,"GET");return await d(g,y.namespace),a(await g.getValue(y))},PUT:async w=>{const g=o(w),y=await t(w,bn);if(typeof y.namespace!="string"||y.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof y.key!="string"||y.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof y.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(y.expirationTtl!==void 0&&(typeof y.expirationTtl!="number"||!Number.isInteger(y.expirationTtl)||y.expirationTtl<Lt))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const v=Math.floor(Date.now()/1e3)+Lt;if(y.expiration!==void 0&&(typeof y.expiration!="number"||!Number.isInteger(y.expiration)||y.expiration<v))throw new c("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await d(g,y.namespace),await g.putValue({expiration:y.expiration,expirationTtl:y.expirationTtl,key:y.key,metadata:y.metadata,namespace:y.namespace,value:y.value}),a({ok:!0})}},k=w=>{const g=S[w.method];if(!g)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(w)};return{[va]:f,[Ia]:h,[yn]:k}},Pa="/_lunora/migrate",Da="/_lunora/admin/pitr",Na="/_lunora/admin/rank",Ua="/_lunora/admin/rankpage",Ca="/_lunora/admin/shard-registry/prune",Ba="/_lunora/admin/shard-traffic",xa=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Ha=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),La=async e=>{const n=await ne(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!xa.has(n.functionPath))throw new c("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},ja=async e=>{const n=await ne(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new c("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new c("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new c("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new c("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},Ma=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new c('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},$a=e=>{if(typeof e.table!="string"||e.table.length===0)throw new c("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new c("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new c("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new c("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new c("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Ka=async e=>{const n=await ne(e,"Rank page")??{};$a(n);const o=Ma(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:o,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},Fa=async e=>{const n=await ne(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},Ga=async e=>{const n=await ne(e,"Shard-registry prune")??{};if(n.tables!==void 0&&!(Array.isArray(n.tables)&&n.tables.every(o=>typeof o=="string")))throw new c("Shard-registry prune `tables` must be an array of table names",{code:"BAD_REQUEST",status:400});return{dryRun:n.dryRun===!0,tables:n.tables}},Qa=async e=>{const n=await ee(e);if(typeof n.functionPath!="string"||!Ha.has(n.functionPath))throw new c("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new c("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},Wa=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:a,resolveForwardContext:i,shardDO:d,shardedTables:f}=e,h=(g,y)=>{if(g.method!=="POST")throw new c(`${y} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(g))throw new c("Admin auth required",{code:"FORBIDDEN",status:403})},m=async(g,y)=>{h(g,"Migration");const v=await La(g),{headers:I}=await i(g,y),E=await a.orchestrateMigration(d,{args:v.args,defaultShardKey:t,functionPath:v.functionPath,headers:I,table:v.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},b=async(g,y)=>{h(g,"Rank");const v=await ja(g),{headers:I}=await i(g,y),E=await a.orchestrateRank(d,{headers:I,index:v.index,partitionKey:v.partitionKey,rowId:v.rowId,sortValues:v.sortValues,table:v.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},A=async(g,y)=>{h(g,"Rank page");const v=await Ka(g),{headers:I}=await i(g,y),E=await a.orchestrateRankPage(d,{...v,headers:I});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},S=async(g,y)=>{h(g,"Shard-traffic");const v=await Fa(g),{headers:I}=await i(g,y),E=await a.orchestrateShardTraffic(d,{headers:I,table:v.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},k=async(g,y)=>{h(g,"Shard-registry prune");const v=await Ga(g),I=f(),E=(v.tables??[]).filter(U=>!I.includes(U));if(E.length>0)throw new c(`Shard-registry prune names tables that are not \`.shardBy()\`: ${E.join(", ")}`,{code:"BAD_REQUEST",status:400});const{headers:j}=await i(g,y),H=await qr(a.registry,d,{dryRun:v.dryRun,headers:j,tables:v.tables??I});return Response.json(H,{status:H.failed.length>0?207:200})},w=async(g,y)=>{if(M(g,"POST","PITR"),!o(g))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const v=await Qa(g),{headers:I}=await i(g,y),E=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:v.args,functionPath:v.functionPath}),headers:I,method:"POST"});return n(d,v.shardKey??t,E)};return{[Pa]:m,[Da]:w,[Na]:b,[Ua]:A,[Ca]:k,[Ba]:S}},za=1,Va=0,Ja=32,Ya=512,qa=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Xa=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Ya)return;const n=t.split(",");if(!(n.length>Ja)){for(const o of n)if(!qa.test(o.trim()))return;return t}},Za=e=>{const t=Sr(e.headers.get("traceparent"));if(t===void 0)return;const n=Xa(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},jt=(e,t={})=>{const n=Za(e),o=t.trustInbound===!0?n:void 0,a=ge(8),i=o?.traceId??ge(16),d=kr(t.sampling,o===void 0?a:i),f=ln(e.headers.get("cf-ray")),h=d.isTraced&&(o===void 0||o.sampled);return{decision:d,ignoredUpstream:n!==void 0&&o===void 0,trace:{sampled:h,spanId:a,traceFlags:h?za:Va,traceId:i,...o?.parentSpanId===void 0?{}:{parentSpanId:o.parentSpanId},...o?.traceState===void 0?{}:{traceState:o.traceState},...f===void 0?{}:{rayId:f}}}},Mt=(e,t)=>{t.traceparent=nn(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState),e.rayId!==void 0&&(t[po]=e.rayId)},es=(e,t)=>{let n;return()=>{if(n===void 0){const o=Ir(e),a=t===void 0?void 0:t.cf;n=Tr(vr(o),Or(o,a))}return n}},ts="/_lunora/admin/scheduled",ns="/_lunora/admin/scheduled/status",rs="/_lunora/admin/scheduled/ws",os="/_lunora/admin/scheduled/cancel",as="/_lunora/admin/scheduled/dead",ss="/_lunora/admin/scheduled/dead/retry",is="/_lunora/admin/scheduled/dead/cancel",cs="/_lunora/admin/scheduled/pool/release",ds=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:a}=e,i=(m,b)=>A=>{if(A.method!=="GET")throw new c(`${b} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const S=new URL(A.url).searchParams.get("cursor"),k=S===null||S===""?"":`?cursor=${encodeURIComponent(S)}`;return o(A).fetch(new Request(`https://scheduler.internal${m}${k}`,{method:"GET"}))},d=(m,b,A=b)=>async S=>{if(S.method!=="POST")throw new c(`${A} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const k=o(S),w=await ne(S,b);if(typeof w?.id!="string"||w.id==="")throw new c(`${b} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return k.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))},f=async m=>{if(m.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const b=o(m),A=await ne(m,"Scheduled pool-release");if(typeof A?.pool!="string"||A.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const S=typeof A.id=="string"&&A.id!==""?A.id:void 0;return b.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(S===void 0?{pool:A.pool}:{id:S,pool:A.pool}),headers:{"content-type":"application/json"},method:"POST"}))},h=async m=>{if(m.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(m))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const b=n();return ye(b,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[os]:d("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[is]:d("/dead/cancel","Scheduled dead-letter action"),[as]:i("/dead","Scheduled dead-letter"),[ss]:d("/dead/retry","Scheduled dead-letter action"),[ts]:i("/list","Scheduled-list"),[cs]:f,[ns]:i("/status","Scheduler-status"),[rs]:h}},us="/_lunora/scheduled",_n="/_lunora/queue",Rn=16*1048576,ls=e=>{const{assertAdmin:t,dispatchScheduled:n,queueHandler:o}=e,a=async(d,f,h)=>{if(t(d),d.method!=="POST")throw new c("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const m=await ne(d,"Scheduled tick"),b=typeof m?.cron=="string"?m.cron:"";if(b==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:b,noRetry:()=>{},scheduledTime:Date.now()},f,h),Response.json({cron:b,ok:!0})},i=async(d,f,h)=>{if(t(d),d.method!=="POST")throw new c("queue dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!o)throw new c("no queueHandler configured",{code:"BAD_REQUEST",status:400});const m=await ne(d,"Queue dispatch",Rn);if(!Array.isArray(m?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const b=typeof m.queue=="string"?m.queue:"",A=m.messages.filter(k=>typeof k=="object"&&k!==null&&typeof k.id=="string").map(k=>({body:k.body,id:k.id})),S=await o({messages:A,queue:b},f,h);return Response.json({retry:S?.retry??[]})};return{[_n]:i,[us]:a}},hs=(e,...t)=>{let n=e.cf;for(const o of t){if(typeof n!="object"||n===null)return;n=n[o]}return typeof n=="string"?n:void 0},et={mtls:e=>hs(e,"tlsClientAuth","certVerified")==="SUCCESS"},fs=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(et,e)?et[e]:void 0)??(()=>!1),ps=e=>typeof e=="string"&&Object.hasOwn(et,e),ms=e=>{const t=ps(e)?e:void 0;if(e!==void 0&&t===void 0)return()=>{};let n=!1;return o=>{n||t!==void 0&&o.cf!==void 0||(n=!0,console.warn(t===void 0?'[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.':`[lunora] \`trustInboundTraceContext: "${t}"\` cannot be satisfied on this host: the request carries no platform-injected \`cf\` metadata, which is what that signal reads, so every inbound \`traceparent\` is ignored and this request starts a new trace. Off Cloudflare, trust the upstream some other way — \`trustInboundTraceContext: true\` when nothing untrusted can reach this worker, or a predicate that verifies whatever your own front door sets. Set it to \`false\` to keep this behaviour and silence this message.`))}},ws="/_lunora/admin/vector/indexes",gs="/_lunora/admin/vector/query",ys=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=async i=>{M(i,"GET","Vector-indexes");const d=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await d.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async i=>{M(i,"POST","Vector-query");const d=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(d.queryIndex===void 0)throw new c("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const h=await t(i);if(typeof h.name!="string"||h.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof h.text!="string"||h.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(h.topK!==void 0&&(typeof h.topK!="number"||!Number.isInteger(h.topK)||h.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const m=await d.queryIndex({name:h.name,text:h.text,topK:h.topK});return Response.json(m,{headers:{"content-type":"application/json"},status:200})};return{[ws]:o,[gs]:a}},bs="/_lunora/admin/workflows/instances",_s="/_lunora/admin/workflows/instance",Rs="/_lunora/admin/workflows/status",Es={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},As=e=>e!==null&&Object.hasOwn(Es,e)?e:void 0,$t=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const o=Number(n);return Number.isInteger(o)&&o>0?o:void 0},We=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new c(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},Kt=()=>{throw new c("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Ss=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,o=async(d,f,h)=>{M(d,"GET","Workflows instances"),t(d);const m=n(f);if(!m)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const b=We(h,"name"),A=As(h.searchParams.get("status"));return Response.json(await m.listInstances({page:$t(h,"page"),perPage:$t(h,"perPage"),status:A,workflowName:b}))},a=async(d,f,h)=>{M(d,"GET","Workflows instance"),t(d);const m=n(f);return m?Response.json(await m.getInstance({instanceId:We(h,"id"),workflowName:We(h,"name")})):Kt()},i=async(d,f)=>{M(d,"POST","Workflows status"),t(d);const h=n(f);if(!h)return Kt();const m=await ne(d,"Workflows status");if(typeof m?.name!="string"||m.name===""||typeof m.id!="string"||m.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:b}=m;if(b!=="pause"&&b!=="resume"&&b!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await h.setInstanceStatus({action:b,instanceId:m.id,workflowName:m.name}))};return{[_s]:a,[bs]:o,[Rs]:i}},Ts={[yn]:bn,[_n]:Rn,[$r]:Mr},Ft="/_lunora/rpc",Os="/_lunora/rpc-batch",vs="/_lunora/ws",Re=(e,t,n)=>({resourceAttributes:es(e,t),...n===void 0?{}:{waitUntil:n}}),ze=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Gt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ve=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0,o=ln(e.headers.get("cf-ray")),a=o===void 0?{}:{rayId:o};let i;try{i=new URL(e.url)}catch{return{method:t,...a,userAgent:n}}const d=i.port===""?void 0:Number(i.port);return{host:i.hostname,method:t,path:i.pathname,port:Number.isNaN(d)?void 0:d,...a,scheme:i.protocol.replace(":",""),userAgent:n}},Qt="/_lunora/voice/",Is="/_lunora/scheduler/dispatch",ks="/_lunora/admin/cron-jobs/run",Ps="/_lunora/admin/ws-token",Ds="/_lunora/admin/",Ne="/_lunora/",Ns="/_lunora/migrate",Us="/_lunora/status",Cs=e=>e.startsWith(Ds)||e===Ns,Bs="__lunora_relation__:",ve=e=>{if(e.startsWith(Bs))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Ie=async e=>await e===!0,Wt=(e,t)=>{const n=e.headers.get(gt);if(n===null)return;const o=Ar(n);if(o===void 0)throw new c(`malformed ${gt} header`,{code:"BAD_REQUEST",status:400});if(o.subject!==(t?.userId??null))throw new c("the session changed since this write was queued",{code:"IDENTITY_MISMATCH",status:409})},xs=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},zt="/api/auth",Hs="__lunora_admin__:recordAuthEvent",Vt="__lunora_admin__:listPushSubscriptions",Ls=["/sign-in","/sign-up","/callback"],js=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return Ls.some(a=>o===a||o.startsWith(`${a}/`))},Jt=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},ke=(e,t,n,o)=>{const a=mr(n),i=a?n.code:"INTERNAL_SERVER_ERROR",d=a?n.status:500,f=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:f,status:d},functionPath:e,ok:!1,...o.fanOut?{fanOut:{failed:0,shards:0,table:o.fanOut.table}}:{},...o.shardKey?{shardKey:o.shardKey}:{}}},En=e=>{const{exp:t,expiresAtMs:n}=e;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},An=({identity:e})=>e!==null&&_r(En(e)),Ms=e=>{if(An(e))throw new c("authentication token expired",{code:"TOKEN_EXPIRED",status:401});return e},$s=e=>{if(!An(e))return e;const t={...e.headers};return delete t["x-lunora-identity"],delete t["x-lunora-identity-exp"],delete t["x-lunora-userid"],{claims:null,headers:t,identity:null,userId:null}},Yt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Ks=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},tt=new WeakMap,Fs=async(e,t,n,o,a=tt.get(e))=>{const i={"content-type":"application/json"},d=e.headers.get("authorization"),f=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),m=e.headers.get("x-lunora-mutation-id"),b=e.headers.get("x-lunora-client-id"),A=e.headers.get("x-lunora-client-seq"),S=e.headers.get("x-lunora-base-seq");d&&(i.authorization=d),f&&(i.cookie=f),h&&(i["x-d1-bookmark"]=h),m&&(i["x-lunora-mutation-id"]=m),b&&(i["x-lunora-client-id"]=b),A&&(i["x-lunora-client-seq"]=A),S&&(i["x-lunora-base-seq"]=S);const k=Cr(e.headers,o);if(k&&(i["x-lunora-client-ip"]=k),i["x-lunora-origin"]=new URL(e.url).origin,!n)return{claims:null,headers:i,identity:null,userId:null};const w=await n(e,t,a);if(!w||typeof w.userId!="string"||w.userId.length===0)return{claims:null,headers:i,identity:null,userId:null};i["x-lunora-userid"]=Rr(w.userId);const g=En(w);g!==void 0&&(i["x-lunora-identity-exp"]=String(g));const{userId:y,...v}=w,I=Object.keys(v).length>0?v:null;return I&&(i["x-lunora-identity"]=Er(I)),{claims:I,headers:i,identity:w,userId:y}},Gs=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Qs=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new c("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new c("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new c("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!Gs.has(n.kind))throw new c("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new c("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new c("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Ws=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},Je=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new c("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new c(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},zs=async e=>{const t=await an(e);let n;try{n=JSON.parse(t)}catch{throw new c("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new c("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const o=n;if(o.args!==void 0&&on(o.args,"RPC"),o.shardKey!==void 0&&typeof o.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,i=Qs(a.fanOut),d=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const f=d.table;if(typeof f=="string"&&f!==i.table)throw new c("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});d.table=i.table}return{args:d,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},Pe=new Map,Vs=5e3,Js=4096,Ys=async(e,t)=>{const n=Date.now(),o=Pe.get(t);if(o!==void 0&&o.expiresMs>n)return o.relayCount;o!==void 0&&Pe.delete(t);let a=0;try{const i=await ye(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const f=(await i.json()).relayCount;typeof f=="number"&&f>0&&(a=Math.floor(f))}}catch{a=0}return tn(Pe,Js),Pe.set(t,{expiresMs:n+Vs,relayCount:a}),a},qt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},De=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),qs=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],Xs=(e,t)=>{for(const n of qs){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},Xt=(e,t)=>{const n=new Headers(e.headers),o=[...n.keys()];for(const a of o)a.startsWith("x-lunora-")&&n.delete(a);return Xs(n,t),n},Zs=async(e,t,n)=>e.length===0||n.length===0?!1:ot(await un(e,t),n),Zt=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[o,...a]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:ot(t,a.join(" ").trim())},en=async(e,t,n)=>{if(!t||t.length===0)return!1;const o=new URL(e.url).searchParams.get("token");return o===null?!1:await Do(t,o)?!0:n?!1:ot(t,o)},ei=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return Vr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return je(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return je(`queue:${e}`,!0);if(typeof n.connectionString=="string")return je(`hyperdrive:${e}`,!0)},ti=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(Ne))throw new c(`route "${t}" is under the reserved ${Ne} prefix, which the framework owns. App routes registered there shadow the internal endpoint AND its admin gate — pick a path outside the prefix.`,{code:"MISCONFIGURED",status:500})},ni=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new c("`x402Charge` requires `functions`: paid (.x402) procedures are read from the function registry, so without it every paid procedure would dispatch FREE. Build the worker with `defineApp()` (which supplies the registry) or pass `functions` explicitly.",{code:"MISCONFIGURED",status:500})},Sn=e=>{ni(e);const t=fs(e.trustInboundTraceContext),n=ms(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",a=e.queryCoordinator??Xr({registry:Zr(e.resolveTableSharding,o)}),i=Jr(e.resolveIdentity,e.identity),d=Me(e.shardDO,e.jurisdiction),f=e.schedulerDO===void 0?void 0:Me(e.schedulerDO,e.jurisdiction),h=e.voiceAgents===void 0?void 0:Object.fromEntries(Object.entries(e.voiceAgents).map(([r,s])=>[r,Me(s,e.jurisdiction)]));let m=!1;const b=r=>{if(r===void 0||e.jurisdiction===void 0)return r;m||(m=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},A=async(r,s,l,u=e.shardRegion?.(s))=>ye(r,s,b(u)).fetch(l);let S;const k=()=>e.adminToken??S;let w;const g=()=>e.requireEphemeralWsToken??w??!0;let y;const v=r=>{const s=r??{};if(y??=qt(r,e.shardDO),w===void 0&&e.requireEphemeralWsToken===void 0){const u=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof u=="string"&&u.length>0&&(w=Io(u,!0))}if(S!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(S=l)},I=new WeakSet,E=r=>Zt(r,k())||I.has(r),j=async r=>{if(!(e.adminGate===void 0||I.has(r)))try{await Ie(e.adminGate(r,tt.get(r)))&&I.add(r)}catch{}},H=async(r,s,l,u)=>{const p=await Fs(r,s,l,e.trustedClientIpHeader,u);return e.functions!==void 0&&(p.headers[bt]=yt),p},U=async(r,s,l,u)=>Ms(await H(r,s,l,u)),K=async(r,s)=>{const l=await H(r,s,e.resolveIdentity);if(I.has(r)&&l.headers.authorization===void 0){const u=k();u!==void 0&&(l.headers.authorization=`Bearer ${u}`)}return l};let W=!1,J=!1;const Y=()=>{J||(J=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},G=r=>{if(!e.allowUnauthenticatedShardAccess){const s=r==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${r} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${r} access (relying solely on per-row RLS).`,{code:r==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}W||(W=!0,console.warn([`[lunora] SECURITY: serving ${r} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},re=async(r,s,l=!1)=>{if(s.includes(qe)||s.includes(Xe))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(!l)if(e.authorizeShard){if(!await Ie(e.authorizeShard({identity:r,shardKey:s})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==o&&G("shard")},Q=Wa({defaultShard:o,forwardToShard:A,isAdmin:E,queryCoordinator:a,resolveForwardContext:K,shardDO:d,shardedTables:()=>(e.listSchemaTables?.()??[]).filter(r=>e.resolveTableSharding?.(r)?.mode.kind==="shardBy")}),de=async(r,s,l,u,p,R)=>{ve(r);const T={"content-type":"application/json",[bt]:yt,"x-lunora-system":"1"};return p?.userId!==void 0&&p.userId.length>0&&(T["x-lunora-userid"]=p.userId),p?.identity!==void 0&&p.identity.length>0&&(T["x-lunora-identity"]=p.identity),u!==void 0&&u.length>0&&(T["x-lunora-mutation-id"]=u),R!==void 0&&R.length>0&&(T.traceparent=R),A(d,l,De(r,s,T))},oe=async(r,s,l,u,p)=>{const R=To(l.env,l.context?.exports,r,["create"]);if(R===void 0)throw new c(`${u} targets workflow "${r}", which is on neither ctx.exports nor env`,{code:"CRON_JOB_FAILED",status:500});if(ro(s))throw new c(`${u} params ${oo}`,{code:"BAD_REQUEST",status:400});try{await R.create(p===void 0?{params:s}:{id:p,params:s})}catch(T){if(!io(T))throw T}},be=async(r,s,l,u)=>{if(r.workflow){await oe(r.workflow,r.args??{},{context:l,env:s},`cron job "${r.name}"`);return}if(r.functionPath===void 0)throw new c(`cron job "${r.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const p=await de(r.functionPath,r.args??{},r.shardKey??o,void 0,void 0,u);if(!p.ok)throw new c(`cron job "${r.name}" (${r.functionPath}) failed with shard status ${String(p.status)}`,{code:"CRON_JOB_FAILED",status:500})},z=r=>{if(!E(r))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},ae=(r,s,l)=>{if(z(r),s===void 0)throw new c(l.message,{code:l.code,status:400});return s},se=async(r,s,l,u,p,R)=>{const T=e.cronJobs?.[r];if(!T)return 0;for(const P of T)try{await be(P,s,l,R)}catch(D){u.push(p(D))}return T.length},Tn=async(r,s,l)=>{if(z(r),M(r,"POST","cron-jobs run"),!e.cronJobs)throw new c("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const u=await ee(r),p=typeof u.name=="string"?u.name:"";if(p==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const R=Object.values(e.cronJobs).flat().find(T=>T.name===p);if(!R)throw new c(`no cron job named "${p}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await be(R,s,l),Response.json({name:p,ran:!0},{status:200})},it=async r=>{const s=typeof r.pool=="string"&&r.pool.length>0?r.pool:void 0;if(!s||!f||typeof r.id!="string")return;const l=typeof r.instanceName=="string"&&r.instanceName.length>0?r.instanceName:"default";try{await ye(f,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:r.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},On=async(r,s,l)=>{M(r,"POST","Scheduler dispatch");const u=await an(r),p=s??{},R=typeof p.LUNORA_SCHEDULER_SECRET=="string"?p.LUNORA_SCHEDULER_SECRET:void 0,T=e.adminToken??(typeof p.LUNORA_ADMIN_TOKEN=="string"?p.LUNORA_ADMIN_TOKEN:void 0),P=r.headers.get("x-lunora-scheduler-signature");let D=!1;if(P&&R?D=await Zs(R,u,P):T&&(D=Zt(r,T)),!D)throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let O;try{O=JSON.parse(u)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const _=O??{},B=_.args??{},L=typeof _.id=="string"&&_.id.length>0?_.id:void 0;if(typeof _.workflow=="string"&&_.workflow.length>0)return await oe(_.workflow,B,{context:l,env:s},"scheduled workflow",L),await it(_),Response.json({ok:!0},{status:200});if(typeof _.functionPath!="string"||_.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const V=typeof _.shardKey=="string"&&_.shardKey.length>0?_.shardKey:o,x=xs(r),ue=await de(_.functionPath,B,V,L,x,r.headers.get("traceparent")??void 0);return await it(_),ue},vn=Bo({assertAdmin:z,getReader:()=>e.authAuditReader}),In=xo({assertAdmin:z,getMove:()=>e.authJurisdictionMove}),kn=async(r,s)=>{z(r);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:Ee({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const u=s?.kind,p=s?.userId,R=s?.limit,T=u==="fcm"||u==="web-push"?u:void 0,P=typeof p=="string"&&p!==""?p:void 0,D=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,O=D>0?Math.min(D,1e3):1e3,B=(await l.list({kind:T,limit:O,userId:P})).filter(L=>T!==void 0&&L.kind!==T?!1:P===void 0||(L.userId??null)===P).map(({keys:L,token:V,...x})=>x);return Response.json({result:Ee({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},Pn=async(r,s)=>{if(!s.fanOut&&!(s.functionPath!==kt&&s.functionPath!==Vt&&s.functionPath!==Ze&&s.functionPath!==pn))return await j(r),s.functionPath===kt?vn(r,s.args??{}):s.functionPath===Vt?kn(r,s.args):In(r,s.functionPath,s.args??{})},Dn=ia({applyGlobals:e.applyGlobals,assertAdmin:z,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:o,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:a,resolveForwardContext:K,shardDO:d,prepareExportRows:async(r,s)=>mn(e,a,r,s,d),streamingImport:(r,s)=>ha(r,e,a,s,d),syncGlobals:e.syncGlobals}),Ue=(r,s)=>{const l=r.searchParams.get(s);return l===null||l===""?void 0:l},Ce=r=>{const s=new URL(r.url),l=s.searchParams.get("limit"),u=s.searchParams.get("offset"),p=l===null?void 0:Number.parseInt(l,10),R=u===null?void 0:Number.parseInt(u,10);return{limit:p!==void 0&&Number.isFinite(p)&&p>=0?p:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},ct=()=>{if(f===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return f},Nn=ds({checkWsAdmin:async r=>E(r)||en(r,k(),g()),requireSchedulerNamespace:ct,resolveSchedulerStub:r=>(z(r),ye(ct(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Un=Ss({assertAdmin:z,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Cn=jr({assertAdmin:z,parsePaging:Ce,queryParameter:Ue,readBodyBytes:Nr,requireAdminOption:ae,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Bn=Yo({options:e,readJsonBody:ee,requireAdminOption:ae}),xn=ys({readJsonBody:ee,requireAdminOption:ae,vectorIntrospector:e.vectorIntrospector}),Hn=ka({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:ae}),Ln=Yr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:ae}),jn=Oa({assertAdmin:z,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,architecture:e.architecture,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ce,queryParameter:Ue,requireAdminOption:ae}),Mn=r=>{const s=[],l=d??r?.SHARD;if(l!==void 0&&s.push(zr("durable-object:default",l,o)),e.health?.disableBindingProbes!==!0)for(const[u,p]of Object.entries(r??{})){const R=ei(u,p);R!==void 0&&s.push(R)}for(const u of e.health?.probes??[])s.push(u);return s},$n=Wr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:E,resolveProbes:Mn}),Kn=r=>{const s=O=>"args"in O?{...O,args:Ye(O.args)}:O,l=e.schedulerInstanceName??"default",u=()=>ye(r,l),p=async(O,_)=>{const B=await u().fetch(new Request(`https://scheduler.internal${O}`,_));if(!B.ok)throw new c(`ctx.scheduler: SchedulerDO ${O} failed (${String(B.status)}): ${await B.text()}`,{code:"INTERNAL",status:500});return await B.json()},R=async(O,_)=>await p(O,{body:JSON.stringify(_),headers:{"content-type":"application/json"},method:"POST"}),T=O=>{const _=O;if(_==null)throw new c("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof _.binding=="string"&&_.binding.length>0)return{workflow:_.binding};if(typeof _.__lunoraRef=="string")return{functionPath:_.__lunoraRef};throw new c("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},P=async()=>(await ao(async _=>p(_===void 0?"/list":`/list?cursor=${encodeURIComponent(_)}`,{method:"GET"}))).map(_=>s(_)),D=async(O,_,B={})=>{const L=T(_),{id:V}=await R("/schedule",{args:Pr("ctx.scheduler",String(L.functionPath??L.workflow),B),scheduledFor:Math.ceil(O),...L});return V};return{cancel:async O=>await R("/cancel",{id:O}),get:async O=>{const _=await p(`/get?id=${encodeURIComponent(O)}`,{method:"GET"});return _.record===void 0?null:s(_.record)},list:P,runAfter:async(O,_,B)=>{if(!Number.isFinite(O)||O<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await D(Date.now()+O,_,B)},runAt:async(O,_,B)=>{if(!Number.isFinite(O))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await D(O,_,B)}}},Fn=async(r,s,l)=>{const{claims:u,headers:p,userId:R}=$s(await H(r,s,i)),T=Re(s,r,O=>l.waitUntil?.(O)),P=O=>async(_,B={})=>{const L=_.__lunoraRef;if(typeof L!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ve(L);const V=await Se(r,L,Ee(B),O,{...p,"x-lunora-system":"1"},T),x=await V.json();if(x.error)throw new c(x.error.message??"shard RPC failed",{code:x.error.code??"INTERNAL",status:V.status});return Ye(x.result)},D=P(o);return{auth:{getIdentity:()=>Promise.resolve(u),userId:R},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),forShard:O=>{const _=P(O);return{runAction:_,runMutation:_,runQuery:_}},runAction:D,runMutation:D,runQuery:D,...f===void 0?{}:{scheduler:Kn(f)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:no(e.storage(s,new URL(r.url).origin))}}},Gn=async(r,s,l)=>{if(!e.httpRouter)return;const u=await Fn(r,s,l);try{return await e.httpRouter.fetch(r,{...s,__lunoraCtx:u},l)}catch(p){return console.error("[lunora] httpRouter (SSR) handler threw:",p),new Response("Internal Server Error",{status:500})}},Qn=async(r,s,l)=>{if(r.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const u=Tt(r,ie);if(u)return u;const p=l.searchParams.get("shard")??o,{headers:R,identity:T}=await H(r,s,i),P=E(r)||await en(r,k(),g());await re(T,p,P);const D=Xt(r,R),O=qt(s,e.shardDO);if(O!==void 0){D.set("x-lunora-shard-binding",O);const _=await Ys(d,p);if(_>0){const B=Ro(p,Math.floor(Math.random()*_));return A(d,B,new Request(r,{headers:D}),Ot(r))}}return A(d,p,new Request(r,{headers:D}))},Wn=async(r,s,l)=>{if(h===void 0)return new Response("Not found",{status:404});if(r.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const u=Tt(r,ie);if(u)return u;let p;try{p=decodeURIComponent(l.pathname.slice(Qt.length))}catch{return new Response("Unknown voice agent",{status:404})}const R=Object.hasOwn(h,p)?h[p]:void 0;if(R===void 0)return new Response("Unknown voice agent",{status:404});const T=l.searchParams.get("threadKey");if(T===null||T.length===0)return new Response("Missing threadKey",{status:400});const{headers:P,identity:D}=await H(r,s,i);if(e.authorizeShard){if(!await Ie(e.authorizeShard({identity:D,shardKey:T})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else G("shard");const O=Xt(r,P);return A(R,T,new Request(r,{headers:O}))},zn=async(r,s,l)=>{if(e.authorizeFanOut){if(!await Ie(e.authorizeFanOut(l,r.table,s)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new c("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});G("fan-out")},Ae=async(r,s)=>{if(!(!r.fanOut&&r.functionPath.startsWith("__lunora_admin__:"))){if(r.fanOut){await zn(r.fanOut,r.functionPath,s);return}await re(s,r.shardKey??o)}},Vn=(r,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){Y();return}if(e.functions[s]?.kind!=="query"||l.includes(Xe)||l.includes(qe))return;const u=Ot(r);return u===void 0?void 0:{name:Eo(l,u),region:u}},Jn=async(r,s,l,u,p)=>{const R=Vn(r,s,u);if(R!==void 0){const T={...p,"x-lunora-replica-read":"1",...y===void 0?{}:{"x-lunora-shard-binding":y}},P=Ao(r.headers.get("x-lunora-min-seq"));P!==void 0&&(T["x-lunora-min-seq"]=String(P));const D=await A(d,R.name,De(s,l,T),R.region);if(D.status!==421)return D}return A(d,u,De(s,l,p))},Se=async(r,s,l,u,p,R)=>{const T=Date.now(),{observability:P,sampling:D}=e,O=Ve(r),{decision:_,ignoredUpstream:B,trace:L}=jt(r,{...D===void 0?{}:{sampling:D},trustInbound:t(r)});B&&n(r);const V={...p,[Rt]:_.keepErrors?"1":"0"};Mt(L,V);try{const x=await Jn(r,s,l,u,V);ce(P,{...O,...Gt(L),durationMs:Date.now()-T,functionPath:s,ok:x.ok,shardKey:u,...x.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(x.status)}`,status:x.status}}},R,void 0,{isTraced:L.sampled,keepErrors:_.keepErrors});const ue=new Response(x.body,{headers:x.headers,status:x.status,statusText:x.statusText});return ue.headers.set("x-lunora-shard-key",u),ue}catch(x){throw ce(P,{...O,...Gt(L),...ke(s,Date.now()-T,x,{shardKey:u})},R,void 0,{isTraced:L.sampled,keepErrors:_.keepErrors}),x}},Yn=r=>{if(r.fanOut&&r.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});r.fanOut||ve(r.functionPath)},qn=async(r,s,l)=>{M(r,"POST","RPC");const u=await zs(r);Ws(s,u),Yn(u);const p=await Pn(r,u);if(p!==void 0)return p;const{headers:R,identity:T}=await U(r,s,i);Wt(r,T),await Ae(u,T);const P=Je(u,e);{const D=Date.now(),{observability:O}=e,_=Ve(r),B=Re(s,r,l&&(x=>l.waitUntil?.(x)));if(u.fanOut)try{const x=await a.fanOut(d,{args:u.args??{},fanOut:u.fanOut,functionPath:u.functionPath,headers:R});return ce(O,{durationMs:Date.now()-D,fanOut:{failed:x.failed,shards:x.ok+x.failed,table:u.fanOut.table},functionPath:u.functionPath,..._,ok:!0},B),Response.json(x,{headers:{"content-type":"application/json"},status:200})}catch(x){throw ce(O,{...ke(u.functionPath,Date.now()-D,x,{fanOut:{table:u.fanOut.table}}),..._},B),x}const L=u.shardKey??o,V=()=>Se(r,u.functionPath,u.args??{},L,R,B);return P&&e.x402Charge?e.x402Charge(r,{functionPath:u.functionPath,price:P.price},V,ze(l)):V()}},Xn=async(r,s,l)=>{M(r,"POST","RPC batch");const u=await ee(r),{calls:p}=u;if(!Array.isArray(p))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:T}=await U(r,s,i);Wt(r,T);const P=Xo(p,o);for(const $ of P.values())for(const F of $)if(e.functions?.[F.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${F.functionPath}" cannot be called in a batch; dispatch it individually over ${Ft}`,{code:"BAD_REQUEST",status:400});await Promise.all([...P.entries()].flatMap(([$,F])=>F.map(Z=>Ae({args:Z.args,functionPath:Z.functionPath,shardKey:$},T))));const{observability:D,sampling:O}=e,_=Re(s,r,l&&($=>l.waitUntil?.($))),B=Ve(r),{decision:L,ignoredUpstream:V,trace:x}=jt(r,{...O===void 0?{}:{sampling:O},trustInbound:t(r)});V&&n(r);const ue={isTraced:x.sampled,keepErrors:L.keepErrors},ur=$=>{const F={...R,"content-type":"application/json",[Rt]:L.keepErrors?"1":"0"};return Mt({...x,spanId:$},F),F},Be=$=>({parentSpanId:$,spanId:ge(8),traceFlags:x.traceFlags,traceId:x.traceId}),Oe=[],xe=[],ht=($,F,Z,le)=>({body:{error:{code:Z,message:le}},id:$.id,status:F}),ft=($,F,Z,le,fe)=>{for(const q of $)ce(D,fe(q),_,void 0,ue),Oe.push(ht(q,F,Z,le))},lr=($,F,Z,le,fe,q)=>{for(const _e of $){const pe=fe.get(_e.id)??q,me=pe<400;ce(D,{durationMs:le,functionPath:_e.functionPath,...B,...Be(Z),ok:me,shardKey:F,...me?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},_,void 0,ue)}};await Promise.all([...P.entries()].map(async([$,F])=>{const Z=ge(8),le=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:F}),headers:new Headers(ur(Z)),method:"POST"}),fe=Date.now();let q;try{q=await A(d,$,le)}catch(X){const Le=Date.now()-fe,{body:wt}=wr(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});ft(F,502,wt.code,wt.message,pr=>({...ke(pr.functionPath,Le,X,{shardKey:$}),...B,...Be(Z)}));return}const _e=Date.now()-fe,pe=q.headers.get("x-d1-bookmark");pe&&xe.push(pe);let me;try{me=await q.json()}catch{const X=`shard batch returned a non-JSON response (${String(q.status)})`;ft(F,q.status,"SHARD_ERROR",X,Le=>({durationMs:_e,error:{code:"SHARD_ERROR",message:X,status:q.status},functionPath:Le.functionPath,...B,...Be(Z),ok:!1,shardKey:$}));return}const He=Array.isArray(me.results)?me.results:[],hr=new Map(He.map(X=>[X.id,X.status??q.status])),fr=new Set(He.map(X=>X.id));lr(F,$,Z,_e,hr,q.status),Oe.push(...He);for(const X of F)fr.has(X.id)||Oe.push(ht(X,q.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const pt={"content-type":"application/json"},[mt]=xe;return xe.length===1&&mt!==void 0&&(pt["x-d1-bookmark"]=mt),Response.json({results:Oe},{headers:pt,status:200})},Zn=async(r,s,l,u={},p={})=>{try{const R=l.__lunoraRef;if(typeof R!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ve(R);const{headers:T,identity:P}=await U(r,s,i,p.context),D={args:u,functionPath:R,shardKey:p.shardKey};await Ae(D,P);const O=p.shardKey??o,_=Re(s,r,p.waitUntil),B=()=>Se(r,R,u,O,T,_),L=Je(D,e);return L&&e.x402Charge?await e.x402Charge(r,{functionPath:R,price:L.price},B,ze(p.waitUntil?{waitUntil:p.waitUntil}:p.context)):await B()}catch(R){return Et(R)}},dt=async(r,s,l)=>{const{observability:u}=e,p=Date.now(),R=ge(16),T=ge(8),P=Yt(s),D=nn(R,T,!0);try{const O=await l(D);return ce(u,{durationMs:Date.now()-p,functionPath:r,ok:!0,spanId:T,traceId:R},P),O}catch(O){throw ce(u,{...ke(r,Date.now()-p,O,{}),spanId:T,traceId:R},P),O}finally{_t(u,P)}},ut=async(r,s,l,u)=>{v(s);const p=[],R=_=>_ instanceof Error?_:new Error(String(_)),T=e.crons?.[r.cron];if(T)try{await T(r,s,l)}catch(_){p.push(R(_))}const P=await se(r.cron,s,l,p,R,u),D=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===r.cron;if(D)try{await Wo(e,a,d,k(),r)}catch(_){p.push(R(_))}if(!T&&P===0&&!D){const _=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${r.cron}") fired but no cron handler is registered for that expression. Registered: ${_.length===0?"(none)":_.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[O]=p;if(p.length===1&&O)throw O;if(p.length>1)throw new AggregateError(p,`scheduled("${r.cron}") had ${String(p.length)} failure(s)`)},er=ls({assertAdmin:z,dispatchScheduled:ut,queueHandler:e.queueHandler}),tr=async(r,s)=>{try{const l=r??{},u=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!u||u.length===0)return;await A(d,o,De(Hs,{outcome:s},{authorization:`Bearer ${u}`,"content-type":"application/json"}))}catch{}},nr=async(r,s,l,u)=>{if(!e.authHandler)return;const p=e.authBasePath??zt,R=Jt(l.pathname,p)?Ur(r):void 0;let T;try{T=await e.authHandler(R?.request??r)}catch(P){throw R?.overflowed()?new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413}):P}if(R?.overflowed())throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});if(T)return js(l.pathname,p)&&u.waitUntil?.(tr(s,T.status>=400?"fail":"ok")),T},rr=async({args:r,env:s,functionPath:l,request:u,shardKey:p,waitUntil:R})=>{on(r,"REST");const T={functionPath:l,...p===void 0?{}:{shardKey:p}},{headers:P,identity:D}=await U(u,s,i);await Ae(T,D);const O=p??o,_=Re(s,u,R),B=()=>Se(u,l,r,O,P,_),L=Je(T,e);return L&&e.x402Charge?e.x402Charge(u,{functionPath:l,price:L.price},B,ze({waitUntil:R})):B()},or=Dr({functions:e.functions??{},invoke:rr,readJsonBody:ee,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Te=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0;ti(Te);const ar={[Us]:r=>r.method!=="GET"&&r.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[vs]:(r,s,l)=>Qn(r,s,l),[Ft]:(r,s,l,u)=>qn(r,s,u),[Os]:(r,s,l,u)=>Xn(r,s,u),[Is]:(r,s,l,u)=>On(r,s,u),[ks]:(r,s,l,u)=>Tn(r,s,u),[Ps]:async r=>{M(r,"POST","ws-token"),z(r);const s=k();if(s===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Po(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...Q,...Dn,...Nn,...Un,...Cn,...Bn,...xn,...Hn,...Ln,...jn,...$n,...or,...Co({assertAdmin:z,getAuthAdmin:()=>e.authAdmin,parsePaging:Ce,queryParameter:Ue,readJsonBody:ee})};let ie=St(e.security),lt=!1;const sr=r=>{lt||(lt=!0,ie=St(e.security,r??{}))},ir=async(r,s)=>{Cs(s)&&await j(r)},cr=(r,s)=>{if(!(s.pathname.startsWith(Ne)||e.authHandler!==void 0&&Jt(s.pathname,e.authBasePath??zt))||r.method!=="POST"&&r.method!=="PUT")return;const u=Number(r.headers.get("content-length")??""),p=Ts[s.pathname]??rn;if(Number.isFinite(u)&&u>p)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},dr=async(r,s,l)=>{tt.set(r,l);const u=new URL(r.url);cr(r,u);const p=await nr(r,s,u,l);if(p)return p;if(Te){const O=`${r.method} ${u.pathname}`,_=Te[O]??Te[u.pathname];if(_)return _(r,s,l)}const R=er[u.pathname];if(R)return R(r,s,l);const T=ar[u.pathname];if(T)return await ir(r,u.pathname),T(r,s,u,l);if(e.voiceAgents!==void 0&&u.pathname.startsWith(Qt))return Wn(r,s,u);if(u.pathname.startsWith(Ne))return new Response("Not found",{status:404});const P=await Gn(r,s,l);if(P&&P.status!==404)return P;const D=await e.authDiscoveryHandler?.(r);return D?(await P?.body?.cancel(),D):P??new Response("Not found",{status:404})};return{async fetch(r,s,l){e.passThroughOnException&&l.passThroughOnException?.(),sr(s),v(s);const u=eo(r,ie);if(u)return u;const p=to(r,ie);if(p)return $e(p,r,ie);try{const R=await dr(r,s,l);return $e(R,r,ie)}catch(R){return $e(Et(R),r,ie)}finally{_t(e.observability,Yt(l))}},async queue(r,s,l){await dt(`queue:${Ks(r)}`,l,async u=>{await e.queue?.(r,s,l,{traceparent:u})})},async scheduled(r,s,l){await dt(`cron:${r.cron}`,l,async u=>{await ut(r,s,l,u)})},serverQuery:Zn}},ri=e=>Sn(e),oi=e=>typeof e=="function"?{fetch:e}:e,ai=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,si=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},Pi=(e,t)=>{const n=oi(e),{email:o,queue:a,scheduled:i}=si(e),d=h=>{const b={...ri({...h,httpRouter:n})};return i!==void 0&&!ai(h)&&(b.scheduled=async(A,S,k)=>{await i(A,S,k)}),a!==void 0&&h.queue===void 0&&(b.queue=async(A,S,k)=>{await a(A,S,k)}),o!==void 0&&(b.email=async(A,S,k)=>{await o(A,S,k)}),b};if(typeof t!="function")return d(t);const f=t;return{fetch:(h,m,b)=>d(f(m)).fetch(h,m,b),queue:(h,m,b)=>d(f(m)).queue?.(h,m,b)??Promise.resolve(),scheduled:(h,m,b)=>d(f(m)).scheduled(h,m,b),serverQuery:(h,m,b,A,S)=>d(f(m)).serverQuery(h,m,b,A,S),...o===void 0?{}:{email:(h,m,b)=>d(f(m)).email?.(h,m,b)??Promise.resolve()}}},ii=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new c("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},Di=(e={})=>(t,n,o)=>Sn(ii(e,n)).fetch(t,n,o??gr),Ni=e=>e;export{Ze as COPY_AUTH_TO_JURISDICTION_OP,kt as GET_AUTH_AUDIT_LOG_OP,gr as NOOP_EXECUTION_CONTEXT,pn as PURGE_UNPINNED_AUTH_OP,Bi as composeIdentityResolvers,ri as composeWorker,Di as createLunoraHandler,Sn as createWorker,Ni as defineRpcEnvelope,Ys as probeRelayCount,ii as resolveLunoraOptions,xi as routeIdentityResolvers,Pi as withFrameworkWorker};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const R={debug:5,error:17,fatal:21,info:9,log:9,trace:1,warn:13},N=e=>`${String(Math.round(e))}000000`,A=Array.from({length:256},(e,r)=>r.toString(16).padStart(2,"0")),l=512,O=new Uint8Array(l);let a=l;const m=(e,r,t)=>{let o="";for(let n=0;n<t;n+=1)o+=A[e[r+n]];return o},T=e=>{if(e>l){const t=new Uint8Array(e);return crypto.getRandomValues(t),m(t,0,e)}a+e>l&&(crypto.getRandomValues(O),a=0);const r=m(O,a,e);return a+=e,r},u=/^[0-9a-f]+$/,S=(e,r,t=!0)=>`00-${e}-${r}-${t?"01":"00"}`,I=e=>{if(e==null)return;const r=e.split("-"),[t,o,n,s]=r;if(!(r.length<4||t===void 0||t.length!==2||!u.test(t)||t==="ff"||t==="00"&&r.length!==4||o===void 0||n===void 0||s===void 0||s.length!==2||!u.test(s)||o.length!==32||n.length!==16||!u.test(o)||!u.test(n)||o==="00000000000000000000000000000000"||n==="0000000000000000"))return{parentSpanId:n,sampled:(Number.parseInt(s,16)&1)===1,traceId:o}},_=(e,r)=>typeof r=="boolean"?{key:e,value:{boolValue:r}}:typeof r=="number"?Number.isFinite(r)?Number.isSafeInteger(r)?{key:e,value:{intValue:String(r)}}:{key:e,value:{doubleValue:r}}:{key:e,value:{stringValue:String(r)}}:{key:e,value:{stringValue:r}},b=e=>e===void 0?[]:Object.entries(e).map(([r,t])=>_(r,t)),h=(e,r,t)=>{const o={},n=new Map,s=(c,i)=>{const g=c.toLowerCase(),v=n.get(g);v===void 0?(n.set(g,c),o[c]=i):o[v]=i};for(const[c,i]of Object.entries(e))s(c,i);for(const[c,i]of Object.entries(r??{}))s(c,i);return t!==void 0&&t.length>0&&s("authorization",`Bearer ${t}`),o},f=e=>Array.isArray(e)?e:[e],C={client:3,consumer:5,internal:1,producer:4,server:2},L=Object.freeze({durationMs:"lunora.duration_ms",errorMessage:"error.message",errorType:"error.type",functionPath:"lunora.function_path",ok:"lunora.ok",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),p=(e,r)=>{const t={"service.name":e};for(const[o,n]of Object.entries(r??{}))t[o]=n;return Object.entries(t).map(([o,n])=>_(o,n))},V=(e,r,t,o)=>({resourceSpans:[{resource:{attributes:p(t,o)},scopeSpans:[{scope:{name:r},spans:f(e)}]}]}),M=(e,r,t,o)=>({resourceLogs:[{resource:{attributes:p(t,o)},scopeLogs:[{logRecords:f(e),scope:{name:r}}]}]}),y=(e,r,t,o)=>({resourceMetrics:[{resource:{attributes:p(t,o)},scopeMetrics:[{metrics:f(e),scope:{name:r}}]}]}),E="CF_VERSION_METADATA",d=(e,r)=>{if(typeof e!="object"||e===null)return;const t=e[r];return typeof t=="string"&&t.length>0?t:void 0},w=e=>r=>{const t=e?.[r];if(typeof t=="string")return t.length>0?t:void 0;if(r===E)return d(t,"tag")??d(t,"id")},D=e=>{const r={},t=e("SERVICE_VERSION")??e("CF_VERSION_METADATA")??e("VERCEL_GIT_COMMIT_SHA")??e("GITHUB_SHA")??e("COMMIT_SHA");t!==void 0&&(r["service.version"]=t);const o=e("DEPLOYMENT_ENVIRONMENT")??e("ENVIRONMENT")??e("NODE_ENV");return o!==void 0&&(r["deployment.environment"]=o),r},x=(e,r)=>{if(!(r!==void 0||e("CLOUDFLARE")!==void 0||e("CF_ACCOUNT_ID")!==void 0))return{};const o={"cloud.provider":"cloudflare"},n=d(r,"colo")??e("CF_COLO")??e("CLOUDFLARE_COLO");return n!==void 0&&(o["cloud.region"]=n),o},F=(...e)=>{const r={};for(const t of e)if(t!==void 0)for(const[o,n]of Object.entries(t))r[o]=n;return r};export{L,C as O,D as a,S as b,N as c,x as d,_ as e,R as f,b as g,h,y as i,M as j,F as m,T as o,I as p,w as r,V as w};
|
|
1
|
+
const R={debug:5,error:17,fatal:21,info:9,log:9,trace:1,warn:13},N=e=>`${String(Math.round(e))}000000`,A=Array.from({length:256},(e,r)=>r.toString(16).padStart(2,"0")),l=512,O=new Uint8Array(l);let a=l;const m=(e,r,t)=>{let o="";for(let n=0;n<t;n+=1)o+=A[e[r+n]];return o},T=e=>{if(e>l){const t=new Uint8Array(e);return crypto.getRandomValues(t),m(t,0,e)}a+e>l&&(crypto.getRandomValues(O),a=0);const r=m(O,a,e);return a+=e,r},u=/^[0-9a-f]+$/,S=(e,r,t=!0)=>`00-${e}-${r}-${t?"01":"00"}`,I=e=>{if(e==null)return;const r=e.split("-"),[t,o,n,s]=r;if(!(r.length<4||t===void 0||t.length!==2||!u.test(t)||t==="ff"||t==="00"&&r.length!==4||o===void 0||n===void 0||s===void 0||s.length!==2||!u.test(s)||o.length!==32||n.length!==16||!u.test(o)||!u.test(n)||o==="00000000000000000000000000000000"||n==="0000000000000000"))return{parentSpanId:n,sampled:(Number.parseInt(s,16)&1)===1,traceId:o}},_=(e,r)=>typeof r=="boolean"?{key:e,value:{boolValue:r}}:typeof r=="number"?Number.isFinite(r)?Number.isSafeInteger(r)?{key:e,value:{intValue:String(r)}}:{key:e,value:{doubleValue:r}}:{key:e,value:{stringValue:String(r)}}:{key:e,value:{stringValue:r}},b=e=>e===void 0?[]:Object.entries(e).map(([r,t])=>_(r,t)),h=(e,r,t)=>{const o={},n=new Map,s=(c,i)=>{const g=c.toLowerCase(),v=n.get(g);v===void 0?(n.set(g,c),o[c]=i):o[v]=i};for(const[c,i]of Object.entries(e))s(c,i);for(const[c,i]of Object.entries(r??{}))s(c,i);return t!==void 0&&t.length>0&&s("authorization",`Bearer ${t}`),o},f=e=>Array.isArray(e)?e:[e],C={client:3,consumer:5,internal:1,producer:4,server:2},L=Object.freeze({durationMs:"lunora.duration_ms",errorMessage:"error.message",errorType:"error.type",functionPath:"lunora.function_path",ok:"lunora.ok",rayId:"cloudflare.ray_id",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),p=(e,r)=>{const t={"service.name":e};for(const[o,n]of Object.entries(r??{}))t[o]=n;return Object.entries(t).map(([o,n])=>_(o,n))},V=(e,r,t,o)=>({resourceSpans:[{resource:{attributes:p(t,o)},scopeSpans:[{scope:{name:r},spans:f(e)}]}]}),M=(e,r,t,o)=>({resourceLogs:[{resource:{attributes:p(t,o)},scopeLogs:[{logRecords:f(e),scope:{name:r}}]}]}),y=(e,r,t,o)=>({resourceMetrics:[{resource:{attributes:p(t,o)},scopeMetrics:[{metrics:f(e),scope:{name:r}}]}]}),E="CF_VERSION_METADATA",d=(e,r)=>{if(typeof e!="object"||e===null)return;const t=e[r];return typeof t=="string"&&t.length>0?t:void 0},w=e=>r=>{const t=e?.[r];if(typeof t=="string")return t.length>0?t:void 0;if(r===E)return d(t,"tag")??d(t,"id")},D=e=>{const r={},t=e("SERVICE_VERSION")??e("CF_VERSION_METADATA")??e("VERCEL_GIT_COMMIT_SHA")??e("GITHUB_SHA")??e("COMMIT_SHA");t!==void 0&&(r["service.version"]=t);const o=e("DEPLOYMENT_ENVIRONMENT")??e("ENVIRONMENT")??e("NODE_ENV");return o!==void 0&&(r["deployment.environment"]=o),r},x=(e,r)=>{if(!(r!==void 0||e("CLOUDFLARE")!==void 0||e("CF_ACCOUNT_ID")!==void 0))return{};const o={"cloud.provider":"cloudflare"},n=d(r,"colo")??e("CF_COLO")??e("CLOUDFLARE_COLO");return n!==void 0&&(o["cloud.region"]=n),o},F=(...e)=>{const r={};for(const t of e)if(t!==void 0)for(const[o,n]of Object.entries(t))r[o]=n;return r};export{L,C as O,D as a,S as b,N as c,x as d,_ as e,R as f,b as g,h,y as i,M as j,F as m,T as o,I as p,w as r,V as w};
|
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.172",
|
|
4
4
|
"description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,10 +46,10 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
49
|
+
"@lunora/bindings": "1.0.0-alpha.92",
|
|
50
50
|
"@lunora/errors": "1.0.0-alpha.49",
|
|
51
|
-
"@lunora/observability": "1.0.0-alpha.
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
51
|
+
"@lunora/observability": "1.0.0-alpha.116",
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.51"
|
|
53
53
|
},
|
|
54
54
|
"peerDependencies": {
|
|
55
55
|
"@lunora/shard-engine": ">=1.0.0-alpha.24 <2.0.0-0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as Z}from"@lunora/errors";import{redactArgs as j}from"@lunora/observability";import{e as l,L as y,o as $,c as S,O as V,f as Q,g as v,h as z,w as rr,i as tr,j as or,m as er}from"./otlp-resource-BI3MvjSy.mjs";const sr=r=>{if(typeof r=="string")return r;try{return JSON.stringify(r)??String(r)}catch{return String(r)}},W=r=>typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:sr(r),nr=512,ir=200,ar=r=>{const e=r.maxItems??nr,o=r.maxDelayMs??ir;let t=[],s,c,n;const a=()=>{s!==void 0&&(clearTimeout(s),s=void 0)},h=async()=>{a();const p=t;t=[];const d=n;c=void 0,n=void 0;try{p.length>0&&await r.export(p)}catch{}finally{d?.()}},m=p=>{c===void 0&&(c=new Promise(d=>{n=d}),s=setTimeout(()=>{h()},o)),p?.(c)};return{add:(p,d)=>{for(t.push(p);t.length>e;)t.shift();m(d),t.length>=e&&h()},flush:async p=>{if(t.length===0){a();return}const d=h();return p?.(d),d},get size(){return t.length}}},cr=/["\\\u0000-\u001F\uD800-\uDFFF]/,B=r=>cr.test(r)?JSON.stringify(r):`"${r}"`,R=r=>{if(r===void 0)return"null";if(typeof r=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof r=="number"){if(Number.isNaN(r))return"nan";if(r===1/0)return"inf";if(r===-1/0)return"-inf";if(Object.is(r,-0))return"-0"}if(typeof r=="string")return B(r);if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r)){let n="[";for(let a=0;a<r.length;a++)a>0&&(n+=","),n+=R(r[a]);return n+"]"}const e=Object.getPrototypeOf(r);if(e!==null&&e!==Object.prototype){const n=r.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${n} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const o=r,t=Object.keys(o).sort();let s="{",c=!0;for(const n of t){const a=o[n];a!==void 0&&(c?c=!1:s+=",",s+=B(n),s+=":",s+=R(a))}return s+"}"},dr=1,ur=0,lr=(r,e)=>{const o=[l(y.functionPath,r.functionPath),l(y.ok,r.ok)];r.method!==void 0&&o.push(l("http.request.method",r.method)),r.path!==void 0&&o.push(l("url.path",r.path)),o.push(l("http.route",r.functionPath)),r.scheme!==void 0&&o.push(l("url.scheme",r.scheme)),r.host!==void 0&&o.push(l("server.address",r.host)),r.port!==void 0&&o.push(l("server.port",r.port)),r.userAgent!==void 0&&o.push(l("user_agent.original",r.userAgent)),r.shardKey!==void 0&&o.push(l(y.shardKey,r.shardKey)),o.push(l("http.response.status_code",r.error?.status??200)),r.error&&o.push(l(y.errorType,r.error.code),l("lunora.error_status",r.error.status)),r.fanOut&&o.push(l("lunora.fanout.table",r.fanOut.table),l("lunora.fanout.shards",r.fanOut.shards),l("lunora.fanout.failed",r.fanOut.failed));const t={attributes:o,endTimeUnixNano:S(e),kind:V.server,name:r.functionPath,...r.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},spanId:r.spanId??$(8),startTimeUnixNano:S(e-r.durationMs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId??$(16)};return r.traceFlags!==void 0&&(t.flags=r.traceFlags),r.error&&(t.events=[{attributes:[l("exception.type",r.error.code),l("exception.message",r.error.message)],name:"exception",timeUnixNano:S(e)}]),t},M=(r,e)=>{const o=new Map([[y.functionPath,l(y.functionPath,r.functionPath)]]);r.shardKey!==void 0&&o.set(y.shardKey,l(y.shardKey,r.shardKey)),r.userId!==void 0&&o.set(y.userId,l(y.userId,r.userId)),r.errorType!==void 0&&o.set(y.errorType,l(y.errorType,r.errorType));for(const[t,s]of Object.entries(e??{}))o.set(t,l(t,W(s)));return[...o.values()]},pr=r=>{const e={attributes:M({errorType:r.error?.type,functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.attributes),endTimeUnixNano:S(r.startTs+r.durationMs),flags:r.sampled===!1?ur:dr,kind:V[r.kind??"internal"],name:r.name,parentSpanId:r.parentSpanId,spanId:r.spanId,startTimeUnixNano:S(r.startTs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId},o=t=>v(Object.fromEntries(Object.entries(t??{}).map(([s,c])=>[s,W(c)])));return r.events!==void 0&&r.events.length>0&&(e.events=r.events.map(t=>({attributes:o(t.attributes),name:t.name,timeUnixNano:S(t.ts)}))),r.links!==void 0&&r.links.length>0&&(e.links=r.links.map(t=>({attributes:o(t.attributes),spanId:t.spanId,traceId:t.traceId}))),e},fr=r=>{const e=S(r.ts),o=M({functionPath:r.functionPath,shardKey:r.shardKey},r.attributes),t=r.traceId===void 0?void 0:[{asDouble:r.value,timeUnixNano:e,traceId:r.traceId}],s={asDouble:r.value,attributes:o,...t===void 0?{}:{exemplars:t},timeUnixNano:e};return r.kind==="gauge"?{gauge:{dataPoints:[s]},name:r.name}:r.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:o,bucketCounts:["1"],count:"1",...t===void 0?{}:{exemplars:t},explicitBounds:[],max:r.value,min:r.value,sum:r.value,timeUnixNano:e}]},name:r.name}:{name:r.name,sum:{aggregationTemporality:1,dataPoints:[s],isMonotonic:!0}}},mr=r=>{const e={attributes:M({functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.fields),body:{stringValue:r.message},severityNumber:Q[r.level],severityText:r.level.toUpperCase(),timeUnixNano:S(r.ts)};return r.traceId!==void 0&&(e.traceId=r.traceId),r.spanId!==void 0&&(e.spanId=r.spanId),r.eventName!==void 0&&(e.eventName=r.eventName,e.attributes.push(l("event.name",r.eventName))),e},hr=1024,C=5;let A=0;const yr=(r,e)=>{if(A>=C)return;A+=1;let o;try{o=new URL(r).host}catch{o="<unparseable endpoint>"}const t=A===C?" Further OTLP rejections are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] collector ${o} rejected the export with HTTP ${String(e)}; the batch is DROPPED (there is no retry).${t}`)},gr=async r=>{const e=new Blob([r]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(e).arrayBuffer()},G=async(r,e,o,t)=>{try{const s=JSON.stringify(e),{byteLength:c}=new TextEncoder().encode(s),n=(c<hr?fetch(r,{body:s,headers:o,method:"POST"}):gr(s).then(a=>fetch(r,{body:a,headers:{...o,"content-encoding":"gzip"},method:"POST"}))).then(a=>{a.ok||yr(r,a.status)},()=>{});t?.(n),await n}catch{}},br=(r,e,o,t)=>{G(r,e,o,t?.waitUntil).catch(()=>{})},O=(r,e)=>e===!0&&r.ok,kr=r=>r.kind==="metric"?void 0:r.event.traceId,Sr=r=>{const e=Map.groupBy(r,t=>kr(t)),o=e.get(void 0)??[];return e.delete(void 0),{byTrace:e,untraced:o}},J=5,Ir=(r,e,o)=>{if(e===void 0)return r;const{byTrace:t,untraced:s}=Sr(r),c=[...s];let n=0,a;for(const[h,m]of t){let p;try{p=e({logs:m.filter(d=>d.kind==="log").map(d=>d.event),rpc:m.filter(d=>d.kind==="rpc").map(d=>d.event),spans:m.filter(d=>d.kind==="span").map(d=>d.event),traceId:h})}catch(d){n+=1,n===1&&(a=d),p=!0}p&&c.push(...m)}return n>0&&o(a,n),c},P=(r,e)=>{if(e===void 0)return r;try{return e(r)??void 0}catch{return}},Tr=r=>({...r,...r.fields===void 0?{}:{fields:j(r.fields)},message:j(r.message)}),H=(r,e,o)=>{if(r.kind==="rpc"){const s=P(r.event,e?.rpc);return s===void 0?void 0:{bucket:"spans",encoded:lr(s,r.endMs)}}if(r.kind==="span"){const s=P(r.event,e?.span);return s===void 0?void 0:{bucket:"spans",encoded:pr(s)}}if(r.kind==="log"){const s=P(o?Tr(r.event):r.event,e?.log);return s===void 0?void 0:{bucket:"logs",encoded:mr(s)}}const t=P(r.event,e?.metric);return t===void 0?void 0:{bucket:"metrics",encoded:fr(t)}},wr=["fuseCloudflareTraces","instrumentDatabase","metricHistory","traceFetch"],Nr=(r={})=>{const{onlyErrors:e}=r;return{onLog:o=>{o.level==="error"||o.level==="fatal"?console.error("[lunora:log]",o.functionPath,o.message):console.log("[lunora:log]",o.functionPath,o.message)},onMetric:o=>{console.log("[lunora:metric]",`${o.name}=${String(o.value)}`,o.kind,o.functionPath)},onRpc:o=>{O(o,e)||(o.ok?console.log("[lunora:rpc]",o):console.error("[lunora:rpc]",o))},onSpan:o=>{const t=o.ok?"ok":`error ${o.error?.type??""}`.trim();console.log("[lunora:span]",o.name,`${String(o.durationMs)}ms`,t,o.functionPath)}}},Lr=r=>{const{headers:e,onlyErrors:o,transform:t,transformLog:s,url:c}=r,n=z({"content-type":"application/json"},e),a=(h,m)=>{try{const p=fetch(c,{body:JSON.stringify(h),headers:n,method:"POST"}).catch(()=>{});m?.waitUntil&&m.waitUntil(p)}catch{}};return{onLog:(h,m)=>{const p=P(h,s);p!==void 0&&a(p,m)},onRpc:(h,m)=>{if(O(h,o))return;const p=P(h,t);p!==void 0&&a(p,m)}}},Ar=r=>{const{capture:e,captureLog:o}=r;if(typeof e!="function")throw new TypeError("sentrySink requires a `capture` callback — wire your own Sentry client, e.g. `sentrySink({ capture: (event) => Sentry.captureMessage(event.name) })`. There is no `dsn` option; the runtime bundles no Sentry client.");const t=r.onlyErrors??!0;return{onLog:o?s=>{try{o(s)}catch{}}:void 0,onRpc:s=>{if(!O(s,t))try{e(s)}catch{}}}},Rr=r=>{const{dataset:e,onlyErrors:o}=r;return{onRpc:t=>{if(!O(t,o))try{e.writeDataPoint({blobs:[t.functionPath,t.ok?"ok":"error",t.shardKey??"",t.error?.code??"",t.fanOut?.table??""],doubles:[t.durationMs,t.ok?0:1,t.fanOut?.shards??0,t.fanOut?.failed??0],indexes:[t.functionPath]})}catch{}}}},Mr=r=>{const{pipeline:e,serializeFields:o}=r;return{onLog:(t,s)=>{try{const c={functionPath:t.functionPath,level:t.level,message:t.message,ts:t.ts};t.fields&&(c.fields=o===!0?JSON.stringify(t.fields):t.fields);for(const a of["shardKey","userId","traceId","spanId"])t[a]!==void 0&&(c[a]=t[a]);const n=e.send([c]).catch(()=>{});s?.waitUntil&&s.waitUntil(n)}catch{}}}},_r=r=>{const{batch:e,deploymentEnvironment:o,detectResources:t,endpoint:s,headers:c,onlyErrors:n,postProcessor:a,resourceAttributes:h,serviceNamespace:m,serviceVersion:p,tailSampler:d,token:X}=r,_=r.serviceName??"lunora",x=r.redactLogs??!0;if(e!==!1&&e?.maxItems!==void 0&&(!Number.isInteger(e.maxItems)||e.maxItems<1))throw new Z("ENV_INVALID",`otlpSink: \`batch.maxItems\` must be a positive integer, received ${String(e.maxItems)}.`);const U={...p===void 0?{}:{"service.version":p},...m===void 0?{}:{"service.namespace":m},...o===void 0?{}:{"deployment.environment":o},...h},D=new WeakMap,k=u=>{if(t!==!0||u?.resourceAttributes===void 0)return U;const i=D.get(u);if(i!==void 0)return i;const f=er(u.resourceAttributes(),U);return D.set(u,f),f};let I=s;for(;I.endsWith("/");)I=I.slice(0,-1);const F={logs:{url:`${I}/v1/logs`,wrap:or},metrics:{url:`${I}/v1/metrics`,wrap:tr},spans:{url:`${I}/v1/traces`,wrap:rr}},K=z({"content-type":"application/json"},c,X);let L=0;const q=(u,i)=>{if(L>=J)return;L+=1;const f=L===J?" Further tailSampler failures from this sink are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] tailSampler threw for ${String(i)} trace(s) in this flush window; keeping them (fail-open), so the sampling policy did NOT apply.${f}`,u)},Y=async u=>{const i=Ir(u,d,q),f=new Map;for(const g of i){const b=H(g,a,x);if(b===void 0)continue;const N=R(g.resource);let w=f.get(N);w===void 0&&(w={logs:[],metrics:[],resource:g.resource,spans:[]},f.set(N,w)),w[b.bucket].push(b.encoded)}const T=[];for(const[,g]of f)for(const b of["spans","logs","metrics"])if(g[b].length>0){const{url:N,wrap:w}=F[b];T.push(G(N,w(g[b],"@lunora/runtime",_,g.resource),K))}await Promise.all(T)};if(e===!1){const u=(i,f)=>{const T=H(i,a,x);if(T!==void 0){const{url:g,wrap:b}=F[T.bucket];br(g,b(T.encoded,"@lunora/runtime",_,i.resource),K,f)}};return{onLog:(i,f)=>{u({event:i,kind:"log",resource:k(f)},f)},onMetric:(i,f)=>{u({event:i,kind:"metric",resource:k(f)},f)},onRpc:(i,f)=>{O(i,n)||u({endMs:Date.now(),event:i,kind:"rpc",resource:k(f)},f)},onSpan:(i,f)=>{u({event:i,kind:"span",resource:k(f)},f)}}}const E=ar({export:Y,...e?.maxDelayMs===void 0?{}:{maxDelayMs:e.maxDelayMs},...e?.maxItems===void 0?{}:{maxItems:e.maxItems}});return{flush:u=>{E.flush(u?.waitUntil).catch(()=>{})},onLog:(u,i)=>{E.add({event:u,kind:"log",resource:k(i)},i?.waitUntil)},onMetric:(u,i)=>{E.add({event:u,kind:"metric",resource:k(i)},i?.waitUntil)},onRpc:(u,i)=>{O(u,n)||E.add({endMs:Date.now(),event:u,kind:"rpc",resource:k(i)},i?.waitUntil)},onSpan:(u,i)=>{E.add({event:u,kind:"span",resource:k(i)},i?.waitUntil)}}},xr=(...r)=>{const e=(t,s)=>{for(const c of r){const n=c[t];if(n)try{n.apply(c,s)}catch{}}},o={};for(const t of r)for(const s of wr)o[s]===void 0&&t[s]!==void 0&&(o[s]=t[s]);return{...o,flush:t=>{e("flush",[t])},onLog:(t,s)=>{e("onLog",[t,s])},onMetric:(t,s)=>{e("onMetric",[t,s])},onRpc:(t,s)=>{e("onRpc",[t,s])},onSpan:(t,s)=>{e("onSpan",[t,s])}}};export{Rr as analyticsEngineSink,xr as combineSinks,Nr as consoleSink,_r as otlpSink,Mr as pipelineLogSink,Ar as sentrySink,Lr as webhookSink};
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as pr,toErrorBody as mr}from"@lunora/errors";import{e as tn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as wr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as gr,f as yr}from"./base64-Bl1_r2k1.mjs";import{i as br,e as _r,a as Rr,E as gt,d as Er}from"./identity-header-pR617HTs.mjs";import{O as yt,a as bt}from"./origin-paywall-B6eOO67m.mjs";import{o as ge,b as nn,p as Sr,m as Tr,d as Ar,a as Or,r as vr}from"./otlp-resource-BI3MvjSy.mjs";import{r as Ir,f as _t,a as ce,S as Rt}from"./observability-DgurIZIR.mjs";import{e as Ee,d as Ye,a as kr}from"./wire-codec-BLvSm5Mn.mjs";import{d as ee,e as ne,M as rn,b as Pr,f as Dr,g as on,w as Nr,h as sn,t as Ur}from"./rest-routes-D3ShCTHh.mjs";import{LunoraError as c,toErrorResponse as Et}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as we}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as nt,BACKUP_KEY_PREFIX as rt,isBackupManifestKey as Cr,backupObjectKeyOfManifest as an,backupObjectKey as Br,backupManifestKey as xr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Hr,buildStorageAdminRoutes as Lr,STORAGE_UPLOAD_MAX_BODY_BYTES as jr,STORAGE_PATH as Mr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as $r,e as Kr,f as St,g as Fr,h as Gr}from"./export-tap-CAyZ2TWC.mjs";import{buildHealthRoutes as Qr,durableObjectProbe as Wr,d1Probe as zr,presenceProbe as je}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as Vr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Ni,routeIdentityResolvers as Ui}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Jr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{pruneShardRegistry as Yr,createQueryCoordinator as qr,createDefaultShardRegistry as Xr}from"./createQueryCoordinator-BkZPoV26.mjs";import{resolveShard as ye,applyJurisdiction as Me}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as Tt,handleCorsPreflight as Zr,enforceOrigin as eo,decorateResponse as $e,enforceWebSocketOrigin as At}from"./decorateResponse-CRrFNW1v.mjs";const to=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,s={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return s.bucket=()=>s,s},cn="__lunoraBranch",no=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,cn),ro=`may not contain the reserved workflow branch-marker key ("${cn}")`,oo=async e=>{const t=[];let n;for(;;){const o=await e(n);if(t.push(...Array.isArray(o.records)?o.records:[]),o.truncated!==!0||typeof o.cursor!="string"||o.cursor.length===0)return t;if(o.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=o.cursor}},ot=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let s=0;s<n;s+=1){const i=s<e.length?e.charCodeAt(s):0,u=s<t.length?t.charCodeAt(s):0;o|=i^u}return o===0},so=/already[\s_-]?exists/iu,ao=e=>so.test(e instanceof Error?e.message:String(e)),io=(e,t,n,o)=>{const s=e.get(t);if(s!==void 0)return s;tn(e,o);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},st=new TextEncoder,co=Array.from({length:32},(e,t)=>t);new RegExp(`[${co.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const uo=64,lo=new Map,dn=async e=>io(lo,e,async()=>crypto.subtle.importKey("raw",st.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),uo),un=async(e,t)=>{const n=await dn(e),o=await crypto.subtle.sign("HMAC",n,st.encode(t));return gr(new Uint8Array(o))},ho=async(e,t,n)=>{const o=await dn(e);return crypto.subtle.verify("HMAC",o,n,st.encode(t))},fo=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(fo);const po=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),mo=-100,wo=15,go=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&po.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>wo?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<mo?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},Ot=e=>{const t=e.cf;return t===void 0?void 0:go(t)},qe="::relay::",yo=(e,t)=>`${e}${qe}${String(t)}`,Xe="::replica::",bo=(e,t)=>`${e}${Xe}${t}`,_o=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Ro=(e,t,n)=>e?.[n]??t?.[n],Eo=(e,t,n,o)=>{const s=Ro(e,t,n);if(!(typeof s!="object"||s===null))return o.every(i=>typeof s[i]=="function")?s:void 0},So=new Set(["1","enabled","on","true","yes"]),To=new Set(["0","disabled","false","no","off"]),Ao=(e,t)=>{const n=(e??"").trim().toLowerCase();return So.has(n)?!0:To.has(n)?!1:t},ln="v1",Oo=6e4,vo=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Oo),o=`${ln}.${String(n)}`,s=await un(e,o);return{expiresAtMs:n,token:`${o}.${s}`}},Io=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[s,i,u]=o;if(s!==ln||u.length===0)return!1;const h=Number(i);if(!Number.isFinite(h)||h<=n)return!1;let f;try{f=yr(u)}catch{return!1}return ho(e,`${s}.${i}`,f)},N="/_lunora/admin/auth",ko={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},C=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},he=(e,t)=>{const n=e(t);if(n===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},hn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ke=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},vt=e=>{const t=hn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},It=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[o,s]of Object.entries(t))Array.isArray(s)&&s.every(i=>typeof i=="string")&&(n[o]=s);return n},Po={[`${N}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${N}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${N}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${N}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${N}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${N}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${N}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${N}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${N}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${N}/sign-up-invitations/create`]:{build:({body:e})=>({email:C(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:te(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${N}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:C(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${N}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${N}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${N}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${N}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${N}/users/create`]:{build:({body:e})=>({data:Ke(e,"data"),email:C(e,"email"),name:C(e,"name"),password:te(e,"password"),role:hn(e.role)}),http:"POST",method:"createUser"},[`${N}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:C(e,"userId")}},http:"POST",method:"updateUser"},[`${N}/users/role`]:{build:({body:e})=>({role:vt(e),userId:C(e,"userId")}),http:"POST",method:"setRole"},[`${N}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:C(e,"userId")}),http:"POST",method:"banUser"},[`${N}/users/unban`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"unbanUser"},[`${N}/users/password`]:{build:({body:e})=>({newPassword:C(e,"newPassword"),userId:C(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${N}/users/remove`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${N}/users/impersonate`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"impersonateUser"},[`${N}/sessions/revoke`]:{build:({body:e})=>({sessionId:C(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${N}/sessions/revoke-all`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${N}/accounts/unlink`]:{build:({body:e})=>({accountId:C(e,"accountId"),userId:C(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${N}/two-factor/disable`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${N}/passkeys/delete`]:{build:({body:e})=>({passkeyId:C(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${N}/organizations/members/remove`]:{build:({body:e})=>({memberId:C(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${N}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:C(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${N}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ke(e,"metadata"),name:C(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${N}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ke(e,"metadata"),name:te(e,"name"),organizationId:C(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${N}/organizations/remove`]:{build:({body:e})=>({organizationId:C(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${N}/organizations/members/add`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),role:te(e,"role"),userId:C(e,"userId")}),http:"POST",method:"addMember"},[`${N}/organizations/members/invite`]:{build:({body:e})=>({email:C(e,"email"),inviterId:te(e,"inviterId"),organizationId:C(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${N}/organizations/members/role`]:{build:({body:e})=>({memberId:C(e,"memberId"),role:vt(e)}),http:"POST",method:"updateMemberRole"},[`${N}/organizations/teams/create`]:{build:({body:e})=>({name:C(e,"name"),organizationId:C(e,"organizationId")}),http:"POST",method:"createTeam"},[`${N}/organizations/teams/update`]:{build:({body:e})=>({name:C(e,"name"),teamId:C(e,"teamId")}),http:"POST",method:"updateTeam"},[`${N}/organizations/teams/remove`]:{build:({body:e})=>({teamId:C(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${N}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:C(e,"teamId"),userId:C(e,"userId")}),http:"POST",method:"addTeamMember"},[`${N}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:C(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${N}/organizations/roles/create`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),permission:It(e),role:C(e,"role")}),http:"POST",method:"createOrgRole"},[`${N}/organizations/roles/update`]:{build:({body:e})=>({permission:It(e),roleId:C(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${N}/organizations/roles/remove`]:{build:({body:e})=>({roleId:C(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Do=e=>{const t=async s=>{try{return await s()}catch(i){if(i instanceof c)throw i;const u=i,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:h,status:ko[h]??500})}},n=async(s,i)=>{if(e.assertAdmin(s),s.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[i.method];if(h===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(s.url),m={body:i.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:T=>e.queryParameter(f,T)},b=i.build(m),S=await t(()=>h(b));return Response.json(i.returns==="void"?{ok:!0}:S,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[s,i]of Object.entries(Po))o[s]=u=>n(u,i);return o},kt="__lunora_admin__:getAuthAuditLog",Pt=e=>typeof e=="string"&&e!==""?e:void 0,Dt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,No=e=>async(n,o)=>{e.assertAdmin(n);const s=e.getReader();if(s===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=Pt(o.actorId),u=Pt(o.event),h=Dt(o.sinceSeq),f=Dt(o.limit),m={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...f===void 0?{}:{limit:f}};let b;try{b=await s.read(m)}catch(T){throw T instanceof c?T:(console.error("[lunora] auth audit read failed:",T),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const S={entries:b};return Response.json({result:Ee(S)},{headers:{"content-type":"application/json"},status:200})},Ze="__lunora_admin__:copyAuthToJurisdiction",fn="__lunora_admin__:purgeUnpinnedAuth",Uo=e=>async(t,n,o)=>{if(n!==Ze&&n!==fn)return;e.assertAdmin(t);const s=e.getMove();if(s===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===Ze?await s.copy({force:o.force===!0}):await s.purge();return Response.json({result:Ee(i)},{headers:{"content-type":"application/json"},status:200})},Co=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const s of t)e.resolveTableSharding?.(s)?.mode.kind==="global"?o.push(s):n.push(s);return{globalTables:o,shardLocalTables:n}},Bo=async(e,t,n,o,s,i)=>{if(n!==void 0&&o.length===0)return[];const u=await e.orchestrateExport(s,{args:{tables:o},defaultShardKey:i,headers:t,tables:o}),h=u.shards.filter(f=>f.error);if(h.length>0){const f=h.map(m=>`${m.shardKey}: ${m.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(h.length)} of ${String(u.shards.length)} shard(s) — ${f}`,{code:"EXPORT_SHARD_FAILED",status:502})}return u.shards.flatMap(f=>f.rows??[])},pn=async(e,t,n,o,s)=>{const i=o??e.listSchemaTables?.();o===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:u,shardLocalTables:h}=Co(e,i),f=await Bo(t,n,i,h,s,e.defaultShardKey??"__root__"),m=e.exportGlobals,b=o===void 0||u.length>0;return(async function*(){yield*f,b&&m&&(yield*m({tables:u}))})()},xo=async(e,t,n,o,s,i)=>{for await(const u of await pn(e,t,n,o,i))s(u)},Ho=new TextEncoder,Lo=1e3,mn=10,jo=200,Nt=8,wn="lunoraBackupCron",Ut=24*1048576,Ct=e=>{const t=e.slice(0,mn).map(o=>an(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Mo=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const s of e)n.set(s,o),o+=s.byteLength;return n},at=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const s=[];let i;for(let u=0;u<Lo;u+=1){const h=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const f of h.objects)Cr(f.key)&&f.customMetadata?.[wn]===o&&s.push(f.key);if(!h.truncated||h.cursor===void 0)break;i=h.cursor}return{eligible:s.length,stale:s.toSorted((u,h)=>h.localeCompare(u)).slice(n)}},$o=async(e,t,n,o,s)=>{const{stale:i}=await at(e,t,n,o),u=new Set(s),h=i.filter(k=>u.has(k)),f=h.slice(0,jo),m=i.length-f.length,b=s.length-h.length;if(f.length===0)return{deleted:[],failed:[],ignored:b,remaining:m};const S=[],T=[];for(let k=0;k<f.length;k+=Nt){const w=await Promise.allSettled(f.slice(k,k+Nt).map(async g=>(await e.delete(an(g)),await e.delete(g),g)));for(const[g,y]of w.entries())y.status==="fulfilled"?S.push(y.value):T.push(f[k+g])}return S.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(S.length)}: ${Ct(S)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${Ct(T)}`),{deleted:S,failed:T,ignored:b,remaining:m}},Ko=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=nt(e.backupPrefix??rt),o=e.backupCron,{eligible:s,stale:i}=o===void 0?{eligible:0,stale:[]}:await at(t,n,e.backupRetain,o);return{cron:o,eligible:s,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},Fo=async(e,t,n,o,s)=>{const i=e.backupStore;if(!i)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!o||o.length===0)throw new c("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const u={authorization:`Bearer ${o}`,"content-type":"application/json"},h=e.backupTables;let f=0,m=0,b=[];await xo(e,t,u,h,I=>{const E=Ho.encode(`${JSON.stringify(I)}
|
|
2
|
-
`);if(f+=1,m+=E.byteLength,m>Ut)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Ut)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});b.push(E)},n);const T=nt(e.backupPrefix??rt),k=new Date(s.scheduledTime).toISOString(),w=Br(T,k),g=Mo(b,m);b=[];const y=Hr(await crypto.subtle.digest("SHA-256",g));await i.put(w,g,{httpMetadata:{contentType:"application/x-ndjson"},sha256:y});const v={bytes:m,createdAt:k,cron:s.cron,file:w,id:k,rows:f,scheduledTime:s.scheduledTime,sha256:y,...h?{tables:h.join(",")}:{}};await i.put(xr(w),`${JSON.stringify(v,void 0,2)}
|
|
3
|
-
`,{customMetadata:{[wn]:s.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:I}=await at(i,T,e.backupRetain,s.cron);if(I.length>0){const E=I.slice(0,mn),j=I.length-E.length;console.info(`[lunora] backup retention: ${String(I.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${E.join(", ")}${j>0?` (+${String(j)} more)`:""}`)}}catch(I){console.warn(`[lunora] backup ${w} was written, but the retention report failed:`,I)}},Go=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const o=e.backupCron,s=e.backupRetain;if(o===void 0||s===void 0||!Number.isInteger(s)||s<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return $o(n,nt(e.backupPrefix??rt),s,o,t)},Qo="/_lunora/admin/backup/retention",Wo="/_lunora/admin/backup/prune",zo=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,s=(h,f)=>{o(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},i=async h=>(M(h,"GET","Backup-retention"),s(h,"retention preview"),Response.json(await Ko(t),{headers:{"cache-control":"no-store"}})),u=async h=>{M(h,"POST","Backup-prune"),s(h,"prune");const{confirm:f}=await n(h);if(!Array.isArray(f)||f.some(m=>typeof m!="string"))throw new c("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await Go(t,f),{headers:{"cache-control":"no-store"}})};return{[Wo]:u,[Qo]:i}},Bt=500,Vo=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const o=e;if(typeof o.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(o.functionPath.startsWith("__lunora_relation__:")||o.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(o.args!==void 0&&(typeof o.args!="object"||o.args===null||Array.isArray(o.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(o.id!==void 0&&typeof o.id!="number")throw new c("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:o.args===void 0?{}:o.args,baselineSeq:typeof o.baselineSeq=="number"?o.baselineSeq:void 0,clientId:typeof o.clientId=="string"?o.clientId:void 0,clientSeq:typeof o.clientSeq=="number"?o.clientSeq:void 0,functionPath:o.functionPath,id:typeof o.id=="number"?o.id:t,mutationId:typeof o.mutationId=="string"?o.mutationId:void 0},shardKey:typeof o.shardKey=="string"?o.shardKey:n}},Jo=(e,t)=>{if(e.length>Bt)throw new c(`RPC batch exceeds the ${String(Bt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,o=new Set;for(const[s,i]of e.entries()){const{entry:u,shardKey:h}=Vo(i,s,t);if(o.has(u.id))throw new c(`batch call id ${String(u.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});o.add(u.id);const f=n.get(h)??[];f.push(u),n.set(h,f)}return n},Yo="/_lunora/admin/export",qo="/_lunora/admin/import",Xo="/_lunora/admin/sync",Zo="/_lunora/admin/connector/sync",es="/_lunora/admin/apply",ts="/_lunora/admin/export-tap/run",ns=new TextEncoder,rs=async e=>{const n=await ne(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const o=[];for(const s of n.tables){if(typeof s!="string"||s.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});o.push(s)}return{tables:o}},Fe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,os=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:s,knownTables:i,queryCoordinator:u,assertAdmin:h,resolveForwardContext:f,shardDO:m,prepareExportRows:b,streamingImport:S,syncGlobals:T}=e,k=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;h(E);const U=await rs(E),{headers:K}=await f(E,j),W=await b(K,U.tables),J=new ReadableStream({async pull(Y){try{for await(const G of W)Y.enqueue(ns.encode(`${JSON.stringify(G)}
|
|
4
|
-
`));Y.close()}catch(G){Y.error(G)}}});return new Response(J,{headers:{"content-type":"application/x-ndjson"},status:200})},w=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;h(E);const U=await ee(E),K=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},W=typeof U.epochs=="object"&&U.epochs!==null?U.epochs:{},J=typeof U.limit=="number"?U.limit:void 0,Y=typeof U.globalCursor=="number"?U.globalCursor:0,G=Fe(U.tables),{headers:re}=await f(E,j),Q=G??i(),de=await u.orchestrateCdcSync(m,{cursors:K,defaultShardKey:n,epochs:W,headers:re,limit:J,tables:Q}),oe=T?await T({limit:J,sinceSeq:Y}):void 0;return Response.json({global:oe,shards:de.shards},{status:200})},g=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;h(E);const U=await ee(E),K=Kr(U.cursor),W=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,J=Fe(U.tables),{headers:Y}=await f(E,j),G=J??i(),re=await u.orchestrateCdcSync(m,{cursors:K.s,defaultShardKey:n,headers:Y,limit:W,tables:G}),Q=[],de={...K.s};let oe=!1;for(const ae of re.shards)oe=St(Q,ae.changes??[],Gr(W))||oe,de[ae.shardKey]=ae.cursor;let be=K.g;if(T){const ae=await T({limit:W,sinceSeq:K.g});oe=St(Q,ae.changes,W)||oe,be=ae.cursor}const z=Fr({g:be,s:de,v:1}),se={changes:Q,hasMore:oe,nextCursor:z};return Response.json(se,{status:200})},y=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;h(E);const U=await ee(E),W=(Array.isArray(U.batches)?U.batches:[]).map(Q=>Q).filter(Q=>Q!==null&&typeof Q=="object"&&typeof Q.shardKey=="string"&&Array.isArray(Q.changes)),J=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:Y}=await f(E,j),G=await u.orchestrateApplyCdc(m,{batches:W,headers:Y}),re=J.length>0&&t?await t({changes:J}):0;return Response.json({applied:G.applied+re,failed:G.failed,ok:G.ok},{status:200})},v=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;h(E);const{headers:U}=await f(E,j),K=await S(E,U);return Response.json(K,{headers:{"content-type":"application/json"},status:K.failed.length>0?207:200})},I=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;if(h(E),s===void 0||Object.keys(s).length===0||o===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const U=await ee(E),K=typeof U.sink=="string"?U.sink:void 0,W=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,J=Fe(U.tables);if(K===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const Y=s[K];if(Y===void 0)throw new c(`Export-tap sink "${K}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:G}=await f(E,j),re=J??i(),Q=await $r({coordinator:u,cursorStore:o,defaultShardKey:n,headers:G,limit:W,shardDO:m,sink:Y,tables:re});return Response.json(Q,{headers:{"content-type":"application/json"},status:200})};return{[es]:y,[Zo]:g,[Yo]:k,[ts]:I,[qo]:v,[Xo]:w}},ss=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const o=n;return typeof o.table!="string"||o.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!o.doc||typeof o.doc!="object"||Array.isArray(o.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:o.table},ok:!1}:{doc:o.doc,ok:!0,table:o.table}},as=(e,t,n,o,s)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:s,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:o}},is=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const o=[],s=[],i=new Map;let u=0,h=0;const f=e.body.getReader(),m=new TextDecoder;let b="",S=0;const T=k=>{h+=1;const w=k.trim();if(w.length===0)return;u+=1;const g=ss(w,h);if(!g.ok){o.push(g.error);return}const{doc:y,table:v}=g,I=t.resolveTableSharding?.(v);if(I?.mode.kind==="global"){s.push({doc:y,line:h,table:v});return}const E=as(y,v,I,n,h);if(!E.ok){o.push(E.error);return}const j=i.get(E.shardKey);j?j.rows.push({doc:y,table:v}):i.set(E.shardKey,{rows:[{doc:y,table:v}],shardKey:E.shardKey,startLine:h})};for(;;){const{done:k,value:w}=await f.read();if(k)break;if(w&&(S+=w.byteLength,S>rn))throw await f.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});b+=m.decode(w,{stream:!0});let g=b.indexOf(`
|
|
5
|
-
`);for(;g!==-1;){const y=b.slice(0,g);b=b.slice(g+1),T(y),g=b.indexOf(`
|
|
6
|
-
`)}}return b.length>0&&T(b),{errors:o,globalRows:s,perShard:i,received:u}},cs=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),xt=(e,t)=>{for(const[n,o]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+o;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},ds=async(e,t,n,o,s)=>{const i=t.defaultShardKey??"__root__",{errors:u,globalRows:h,perShard:f,received:m}=await is(e,t,i),b={conflicts:0,errors:u,failed:[],inserted:{}},S=[];if(t.resolveTableSharding===void 0&&f.size>0&&S.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),f.size>0){const T=await n.orchestrateImport(s,{batches:[...f.values()],headers:o});xt(b,T),b.failed.push(...cs(T.shards))}if(h.length>0)if(t.importGlobals){const T=h[0]?.line??1,k=await t.importGlobals({rows:h,startLine:T});xt(b,k)}else for(const T of h)b.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:T.line,message:`row targets global table "${T.table}" but no \`importGlobals\` is configured`,table:T.table});return{conflicts:b.conflicts,errors:b.errors,failed:b.failed,inserted:b.inserted,received:m,...S.length>0?{warnings:S}:{}}},us=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),Ge=e=>typeof e=="object"&&e!==null?e:{},Qe=e=>typeof e.kind=="string"?e.kind:"unknown",ls=(e,t)=>{let n=Ge(t),o=!1;Qe(n)==="optional"&&(o=!0,n=Ge(n._meta?.inner));const s=Qe(n),i=n._meta??{},u={kind:s,name:e,optional:o};if(s==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),s==="array"){const h=Qe(Ge(i.inner));h!=="unknown"&&(u.element=h)}return u},hs=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>ls(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),fs="/_lunora/admin/functions",ps="/_lunora/admin/cron-jobs",ms="/_lunora/admin/architecture",ws="/_lunora/admin/openapi",gs="/_lunora/admin/openrpc",ys="/_lunora/admin/global/tables",bs="/_lunora/admin/global/table",_s="/_lunora/admin/global/facet",Ht=e=>{if(e===void 0||e==="")return;let t;try{t=Ye(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(o=>{if(typeof o!="object"||o===null||typeof o.column!="string")return[];const{column:s,value:i}=o;return[{column:s,value:i}]});return n.length===0?void 0:n},Rs=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:{}}),Es=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"}),Ss=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:s,requireAdminOption:i}=e,u=w=>{M(w,"GET","Functions");const g=i(w,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),y=Object.entries(g).flatMap(([v,I])=>I.visibility==="internal"||I.kind==="stream"?[]:[{args:hs(I.args),kind:I.kind,path:v}]).toSorted((v,I)=>v.path.localeCompare(I.path));return Response.json({functions:y},{headers:{"content-type":"application/json"},status:200})},h=w=>{M(w,"GET","Cron-jobs");const g=i(w,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),y=Object.entries(g).flatMap(([v,I])=>I.map(E=>({args:E.args,cron:v,functionPath:E.functionPath,name:E.name,shardKey:E.shardKey,workflow:E.workflow}))).toSorted((v,I)=>v.name.localeCompare(I.name));return Response.json({jobs:y},{headers:{"content-type":"application/json"},status:200})},f=w=>(M(w,"GET","Architecture"),t(w),Response.json(n.architecture??us,{headers:{"content-type":"application/json"},status:200})),m=w=>(M(w,"GET","OpenAPI"),t(w),Response.json(n.openApiSpec??Rs,{headers:{"content-type":"application/json"},status:200})),b=w=>(M(w,"GET","OpenRPC"),t(w),Response.json(n.openRpcSpec??Es,{headers:{"content-type":"application/json"},status:200})),S=async w=>{M(w,"GET","Global-tables");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await g.listTables(),{headers:{"content-type":"application/json"},status:200})},T=async w=>{M(w,"GET","Global-table");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),y=new URL(w.url),v=s(y,"table");if(v===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const I=await g.readTablePage({...o(w),filters:Ht(s(y,"filters")),table:v});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},k=async w=>{M(w,"GET","Global-facet");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),y=new URL(w.url),v=s(y,"table"),I=s(y,"column");if(v===void 0||I===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const E=s(y,"limit"),j=E===void 0?void 0:Number(E),H=await g.facetColumn({column:I,filters:Ht(s(y,"filters")),limit:j!==void 0&&Number.isFinite(j)?j:void 0,table:v});return Response.json(H,{headers:{"content-type":"application/json"},status:200})};return{[ps]:h,[fs]:u,[_s]:k,[bs]:T,[ys]:S,[ms]:f,[ws]:m,[gs]:b}},Ts="/_lunora/admin/kv/namespaces",As="/_lunora/admin/kv/keys",gn="/_lunora/admin/kv/value",yn=32*1048576,Lt=60,Os=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=w=>n(w,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),s=w=>Response.json(w,{headers:{"content-type":"application/json"},status:200}),i=(w,g)=>{const y=new URL(w.url),v=y.searchParams.get("namespace")??"",I=y.searchParams.get("key")??"";if(v==="")throw new c(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(I==="")throw new c(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:I,namespace:v}},u=async(w,g)=>{if(!(await w.listNamespaces()).some(v=>v.binding===g))throw new c(`Unknown KV namespace binding \`${g}\``,{code:"NOT_FOUND",status:404})},h=async w=>(M(w,"GET","KV-namespaces"),s({namespaces:await o(w).listNamespaces()})),f=async w=>{M(w,"GET","KV-keys");const g=o(w),y=new URL(w.url),v=y.searchParams.get("namespace")??"";if(v==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const I=y.searchParams.get("prefix")??void 0,E=y.searchParams.get("cursor")??void 0,j=y.searchParams.get("limit"),H=j===null?void 0:Number.parseInt(j,10);if(H!==void 0&&(!Number.isInteger(H)||H<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const U=H===void 0?void 0:Math.min(H,1e3);return await u(g,v),s(await g.listKeys({cursor:E,limit:U,namespace:v,prefix:I}))},T={DELETE:async w=>{const g=o(w),y=i(w,"DELETE");return await u(g,y.namespace),await g.deleteKey(y),s({deleted:!0})},GET:async w=>{const g=o(w),y=i(w,"GET");return await u(g,y.namespace),s(await g.getValue(y))},PUT:async w=>{const g=o(w),y=await t(w,yn);if(typeof y.namespace!="string"||y.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof y.key!="string"||y.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof y.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(y.expirationTtl!==void 0&&(typeof y.expirationTtl!="number"||!Number.isInteger(y.expirationTtl)||y.expirationTtl<Lt))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const v=Math.floor(Date.now()/1e3)+Lt;if(y.expiration!==void 0&&(typeof y.expiration!="number"||!Number.isInteger(y.expiration)||y.expiration<v))throw new c("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(g,y.namespace),await g.putValue({expiration:y.expiration,expirationTtl:y.expirationTtl,key:y.key,metadata:y.metadata,namespace:y.namespace,value:y.value}),s({ok:!0})}},k=w=>{const g=T[w.method];if(!g)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(w)};return{[Ts]:h,[As]:f,[gn]:k}},vs="/_lunora/migrate",Is="/_lunora/admin/pitr",ks="/_lunora/admin/rank",Ps="/_lunora/admin/rankpage",Ds="/_lunora/admin/shard-registry/prune",Ns="/_lunora/admin/shard-traffic",Us=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Cs=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Bs=async e=>{const n=await ne(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!Us.has(n.functionPath))throw new c("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},xs=async e=>{const n=await ne(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new c("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new c("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new c("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new c("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},Hs=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new c('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Ls=e=>{if(typeof e.table!="string"||e.table.length===0)throw new c("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new c("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new c("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new c("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new c("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},js=async e=>{const n=await ne(e,"Rank page")??{};Ls(n);const o=Hs(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:o,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},Ms=async e=>{const n=await ne(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},$s=async e=>{const n=await ne(e,"Shard-registry prune")??{};if(n.tables!==void 0&&!(Array.isArray(n.tables)&&n.tables.every(o=>typeof o=="string")))throw new c("Shard-registry prune `tables` must be an array of table names",{code:"BAD_REQUEST",status:400});return{dryRun:n.dryRun===!0,tables:n.tables}},Ks=async e=>{const n=await ee(e);if(typeof n.functionPath!="string"||!Cs.has(n.functionPath))throw new c("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new c("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},Fs=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:s,resolveForwardContext:i,shardDO:u,shardedTables:h}=e,f=(g,y)=>{if(g.method!=="POST")throw new c(`${y} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(g))throw new c("Admin auth required",{code:"FORBIDDEN",status:403})},m=async(g,y)=>{f(g,"Migration");const v=await Bs(g),{headers:I}=await i(g,y),E=await s.orchestrateMigration(u,{args:v.args,defaultShardKey:t,functionPath:v.functionPath,headers:I,table:v.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},b=async(g,y)=>{f(g,"Rank");const v=await xs(g),{headers:I}=await i(g,y),E=await s.orchestrateRank(u,{headers:I,index:v.index,partitionKey:v.partitionKey,rowId:v.rowId,sortValues:v.sortValues,table:v.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},S=async(g,y)=>{f(g,"Rank page");const v=await js(g),{headers:I}=await i(g,y),E=await s.orchestrateRankPage(u,{...v,headers:I});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},T=async(g,y)=>{f(g,"Shard-traffic");const v=await Ms(g),{headers:I}=await i(g,y),E=await s.orchestrateShardTraffic(u,{headers:I,table:v.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},k=async(g,y)=>{f(g,"Shard-registry prune");const v=await $s(g),I=h(),E=(v.tables??[]).filter(U=>!I.includes(U));if(E.length>0)throw new c(`Shard-registry prune names tables that are not \`.shardBy()\`: ${E.join(", ")}`,{code:"BAD_REQUEST",status:400});const{headers:j}=await i(g,y),H=await Yr(s.registry,u,{dryRun:v.dryRun,headers:j,tables:v.tables??I});return Response.json(H,{status:H.failed.length>0?207:200})},w=async(g,y)=>{if(M(g,"POST","PITR"),!o(g))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const v=await Ks(g),{headers:I}=await i(g,y),E=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:v.args,functionPath:v.functionPath}),headers:I,method:"POST"});return n(u,v.shardKey??t,E)};return{[vs]:m,[Is]:w,[ks]:b,[Ps]:S,[Ds]:k,[Ns]:T}},Gs=1,Qs=0,Ws=32,zs=512,Vs=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Js=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>zs)return;const n=t.split(",");if(!(n.length>Ws)){for(const o of n)if(!Vs.test(o.trim()))return;return t}},Ys=e=>{const t=Sr(e.headers.get("traceparent"));if(t===void 0)return;const n=Js(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},jt=(e,t={})=>{const n=Ys(e),o=t.trustInbound===!0?n:void 0,s=ge(8),i=o?.traceId??ge(16),u=Ir(t.sampling,o===void 0?s:i),h=u.isTraced&&(o===void 0||o.sampled);return{decision:u,ignoredUpstream:n!==void 0&&o===void 0,trace:{sampled:h,spanId:s,traceFlags:h?Gs:Qs,traceId:i,...o?.parentSpanId===void 0?{}:{parentSpanId:o.parentSpanId},...o?.traceState===void 0?{}:{traceState:o.traceState}}}},Mt=(e,t)=>{t.traceparent=nn(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},qs=(e,t)=>{let n;return()=>{if(n===void 0){const o=vr(e),s=t===void 0?void 0:t.cf;n=Tr(Or(o),Ar(o,s))}return n}},Xs="/_lunora/admin/scheduled",Zs="/_lunora/admin/scheduled/status",ea="/_lunora/admin/scheduled/ws",ta="/_lunora/admin/scheduled/cancel",na="/_lunora/admin/scheduled/dead",ra="/_lunora/admin/scheduled/dead/retry",oa="/_lunora/admin/scheduled/dead/cancel",sa="/_lunora/admin/scheduled/pool/release",aa=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:s}=e,i=(m,b)=>S=>{if(S.method!=="GET")throw new c(`${b} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(S.url).searchParams.get("cursor"),k=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return o(S).fetch(new Request(`https://scheduler.internal${m}${k}`,{method:"GET"}))},u=(m,b,S=b)=>async T=>{if(T.method!=="POST")throw new c(`${S} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const k=o(T),w=await ne(T,b);if(typeof w?.id!="string"||w.id==="")throw new c(`${b} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return k.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async m=>{if(m.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const b=o(m),S=await ne(m,"Scheduled pool-release");if(typeof S?.pool!="string"||S.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const T=typeof S.id=="string"&&S.id!==""?S.id:void 0;return b.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(T===void 0?{pool:S.pool}:{id:T,pool:S.pool}),headers:{"content-type":"application/json"},method:"POST"}))},f=async m=>{if(m.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(m))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const b=n();return ye(b,s).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ta]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[oa]:u("/dead/cancel","Scheduled dead-letter action"),[na]:i("/dead","Scheduled dead-letter"),[ra]:u("/dead/retry","Scheduled dead-letter action"),[Xs]:i("/list","Scheduled-list"),[sa]:h,[Zs]:i("/status","Scheduler-status"),[ea]:f}},ia="/_lunora/scheduled",bn="/_lunora/queue",_n=16*1048576,ca=e=>{const{assertAdmin:t,dispatchScheduled:n,queueHandler:o}=e,s=async(u,h,f)=>{if(t(u),u.method!=="POST")throw new c("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const m=await ne(u,"Scheduled tick"),b=typeof m?.cron=="string"?m.cron:"";if(b==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:b,noRetry:()=>{},scheduledTime:Date.now()},h,f),Response.json({cron:b,ok:!0})},i=async(u,h,f)=>{if(t(u),u.method!=="POST")throw new c("queue dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!o)throw new c("no queueHandler configured",{code:"BAD_REQUEST",status:400});const m=await ne(u,"Queue dispatch",_n);if(!Array.isArray(m?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const b=typeof m.queue=="string"?m.queue:"",S=m.messages.filter(k=>typeof k=="object"&&k!==null&&typeof k.id=="string").map(k=>({body:k.body,id:k.id})),T=await o({messages:S,queue:b},h,f);return Response.json({retry:T?.retry??[]})};return{[bn]:i,[ia]:s}},da=(e,...t)=>{let n=e.cf;for(const o of t){if(typeof n!="object"||n===null)return;n=n[o]}return typeof n=="string"?n:void 0},et={mtls:e=>da(e,"tlsClientAuth","certVerified")==="SUCCESS"},ua=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(et,e)?et[e]:void 0)??(()=>!1),la=e=>typeof e=="string"&&Object.hasOwn(et,e),ha=e=>{const t=la(e)?e:void 0;if(e!==void 0&&t===void 0)return()=>{};let n=!1;return o=>{n||t!==void 0&&o.cf!==void 0||(n=!0,console.warn(t===void 0?'[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.':`[lunora] \`trustInboundTraceContext: "${t}"\` cannot be satisfied on this host: the request carries no platform-injected \`cf\` metadata, which is what that signal reads, so every inbound \`traceparent\` is ignored and this request starts a new trace. Off Cloudflare, trust the upstream some other way — \`trustInboundTraceContext: true\` when nothing untrusted can reach this worker, or a predicate that verifies whatever your own front door sets. Set it to \`false\` to keep this behaviour and silence this message.`))}},fa="/_lunora/admin/vector/indexes",pa="/_lunora/admin/vector/query",ma=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=async i=>{M(i,"GET","Vector-indexes");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},s=async i=>{M(i,"POST","Vector-query");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new c("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const f=await t(i);if(typeof f.name!="string"||f.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof f.text!="string"||f.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(f.topK!==void 0&&(typeof f.topK!="number"||!Number.isInteger(f.topK)||f.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const m=await u.queryIndex({name:f.name,text:f.text,topK:f.topK});return Response.json(m,{headers:{"content-type":"application/json"},status:200})};return{[fa]:o,[pa]:s}},wa="/_lunora/admin/workflows/instances",ga="/_lunora/admin/workflows/instance",ya="/_lunora/admin/workflows/status",ba={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},_a=e=>e!==null&&Object.hasOwn(ba,e)?e:void 0,$t=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const o=Number(n);return Number.isInteger(o)&&o>0?o:void 0},We=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new c(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},Kt=()=>{throw new c("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Ra=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,o=async(u,h,f)=>{M(u,"GET","Workflows instances"),t(u);const m=n(h);if(!m)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const b=We(f,"name"),S=_a(f.searchParams.get("status"));return Response.json(await m.listInstances({page:$t(f,"page"),perPage:$t(f,"perPage"),status:S,workflowName:b}))},s=async(u,h,f)=>{M(u,"GET","Workflows instance"),t(u);const m=n(h);return m?Response.json(await m.getInstance({instanceId:We(f,"id"),workflowName:We(f,"name")})):Kt()},i=async(u,h)=>{M(u,"POST","Workflows status"),t(u);const f=n(h);if(!f)return Kt();const m=await ne(u,"Workflows status");if(typeof m?.name!="string"||m.name===""||typeof m.id!="string"||m.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:b}=m;if(b!=="pause"&&b!=="resume"&&b!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:b,instanceId:m.id,workflowName:m.name}))};return{[ga]:s,[wa]:o,[ya]:i}},Ea={[gn]:yn,[bn]:_n,[Mr]:jr},Ft="/_lunora/rpc",Sa="/_lunora/rpc-batch",Ta="/_lunora/ws",Re=(e,t,n)=>({resourceAttributes:qs(e,t),...n===void 0?{}:{waitUntil:n}}),ze=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Gt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ve=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let o;try{o=new URL(e.url)}catch{return{method:t,userAgent:n}}const s=o.port===""?void 0:Number(o.port);return{host:o.hostname,method:t,path:o.pathname,port:Number.isNaN(s)?void 0:s,scheme:o.protocol.replace(":",""),userAgent:n}},Qt="/_lunora/voice/",Aa="/_lunora/scheduler/dispatch",Oa="/_lunora/admin/cron-jobs/run",va="/_lunora/admin/ws-token",Ia="/_lunora/admin/",Ne="/_lunora/",ka="/_lunora/migrate",Pa="/_lunora/status",Da=e=>e.startsWith(Ia)||e===ka,Na="__lunora_relation__:",ve=e=>{if(e.startsWith(Na))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Ie=async e=>await e===!0,Wt=(e,t)=>{const n=e.headers.get(gt);if(n===null)return;const o=Er(n);if(o===void 0)throw new c(`malformed ${gt} header`,{code:"BAD_REQUEST",status:400});if(o.subject!==(t?.userId??null))throw new c("the session changed since this write was queued",{code:"IDENTITY_MISMATCH",status:409})},Ua=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},zt="/api/auth",Ca="__lunora_admin__:recordAuthEvent",Vt="__lunora_admin__:listPushSubscriptions",Ba=["/sign-in","/sign-up","/callback"],xa=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return Ba.some(s=>o===s||o.startsWith(`${s}/`))},Jt=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},ke=(e,t,n,o)=>{const s=pr(n),i=s?n.code:"INTERNAL_SERVER_ERROR",u=s?n.status:500,h=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:h,status:u},functionPath:e,ok:!1,...o.fanOut?{fanOut:{failed:0,shards:0,table:o.fanOut.table}}:{},...o.shardKey?{shardKey:o.shardKey}:{}}},Rn=e=>{const{exp:t,expiresAtMs:n}=e;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},En=({identity:e})=>e!==null&&br(Rn(e)),Ha=e=>{if(En(e))throw new c("authentication token expired",{code:"TOKEN_EXPIRED",status:401});return e},La=e=>{if(!En(e))return e;const t={...e.headers};return delete t["x-lunora-identity"],delete t["x-lunora-identity-exp"],delete t["x-lunora-userid"],{claims:null,headers:t,identity:null,userId:null}},Yt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,ja=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},tt=new WeakMap,Ma=async(e,t,n,o,s=tt.get(e))=>{const i={"content-type":"application/json"},u=e.headers.get("authorization"),h=e.headers.get("cookie"),f=e.headers.get("x-d1-bookmark"),m=e.headers.get("x-lunora-mutation-id"),b=e.headers.get("x-lunora-client-id"),S=e.headers.get("x-lunora-client-seq"),T=e.headers.get("x-lunora-base-seq");u&&(i.authorization=u),h&&(i.cookie=h),f&&(i["x-d1-bookmark"]=f),m&&(i["x-lunora-mutation-id"]=m),b&&(i["x-lunora-client-id"]=b),S&&(i["x-lunora-client-seq"]=S),T&&(i["x-lunora-base-seq"]=T);const k=Ur(e.headers,o);if(k&&(i["x-lunora-client-ip"]=k),i["x-lunora-origin"]=new URL(e.url).origin,!n)return{claims:null,headers:i,identity:null,userId:null};const w=await n(e,t,s);if(!w||typeof w.userId!="string"||w.userId.length===0)return{claims:null,headers:i,identity:null,userId:null};i["x-lunora-userid"]=_r(w.userId);const g=Rn(w);g!==void 0&&(i["x-lunora-identity-exp"]=String(g));const{userId:y,...v}=w,I=Object.keys(v).length>0?v:null;return I&&(i["x-lunora-identity"]=Rr(I)),{claims:I,headers:i,identity:w,userId:y}},$a=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Ka=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new c("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new c("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new c("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!$a.has(n.kind))throw new c("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new c("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new c("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Fa=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},Je=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new c("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new c(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},Ga=async e=>{const t=await sn(e);let n;try{n=JSON.parse(t)}catch{throw new c("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new c("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const o=n;if(o.args!==void 0&&on(o.args,"RPC"),o.shardKey!==void 0&&typeof o.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const s=n,i=Ka(s.fanOut),u=s.args??{};if(i&&s.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==i.table)throw new c("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:s.functionPath,shardKey:s.shardKey}},Pe=new Map,Qa=5e3,Wa=4096,za=async(e,t)=>{const n=Date.now(),o=Pe.get(t);if(o!==void 0&&o.expiresMs>n)return o.relayCount;o!==void 0&&Pe.delete(t);let s=0;try{const i=await ye(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const h=(await i.json()).relayCount;typeof h=="number"&&h>0&&(s=Math.floor(h))}}catch{s=0}return tn(Pe,Wa),Pe.set(t,{expiresMs:n+Qa,relayCount:s}),s},qt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},De=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),Va=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],Ja=(e,t)=>{for(const n of Va){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},Xt=(e,t)=>{const n=new Headers(e.headers),o=[...n.keys()];for(const s of o)s.startsWith("x-lunora-")&&n.delete(s);return Ja(n,t),n},Ya=async(e,t,n)=>e.length===0||n.length===0?!1:ot(await un(e,t),n),Zt=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[o,...s]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:ot(t,s.join(" ").trim())},en=async(e,t,n)=>{if(!t||t.length===0)return!1;const o=new URL(e.url).searchParams.get("token");return o===null?!1:await Io(t,o)?!0:n?!1:ot(t,o)},qa=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return zr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return je(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return je(`queue:${e}`,!0);if(typeof n.connectionString=="string")return je(`hyperdrive:${e}`,!0)},Xa=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(Ne))throw new c(`route "${t}" is under the reserved ${Ne} prefix, which the framework owns. App routes registered there shadow the internal endpoint AND its admin gate — pick a path outside the prefix.`,{code:"MISCONFIGURED",status:500})},Za=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new c("`x402Charge` requires `functions`: paid (.x402) procedures are read from the function registry, so without it every paid procedure would dispatch FREE. Build the worker with `defineApp()` (which supplies the registry) or pass `functions` explicitly.",{code:"MISCONFIGURED",status:500})},Sn=e=>{Za(e);const t=ua(e.trustInboundTraceContext),n=ha(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",s=e.queryCoordinator??qr({registry:Xr(e.resolveTableSharding,o)}),i=Vr(e.resolveIdentity,e.identity),u=Me(e.shardDO,e.jurisdiction),h=e.schedulerDO===void 0?void 0:Me(e.schedulerDO,e.jurisdiction),f=e.voiceAgents===void 0?void 0:Object.fromEntries(Object.entries(e.voiceAgents).map(([r,a])=>[r,Me(a,e.jurisdiction)]));let m=!1;const b=r=>{if(r===void 0||e.jurisdiction===void 0)return r;m||(m=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},S=async(r,a,l,d=e.shardRegion?.(a))=>ye(r,a,b(d)).fetch(l);let T;const k=()=>e.adminToken??T;let w;const g=()=>e.requireEphemeralWsToken??w??!0;let y;const v=r=>{const a=r??{};if(y??=qt(r,e.shardDO),w===void 0&&e.requireEphemeralWsToken===void 0){const d=a.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof d=="string"&&d.length>0&&(w=Ao(d,!0))}if(T!==void 0||e.adminToken!==void 0)return;const l=a.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(T=l)},I=new WeakSet,E=r=>Zt(r,k())||I.has(r),j=async r=>{if(!(e.adminGate===void 0||I.has(r)))try{await Ie(e.adminGate(r,tt.get(r)))&&I.add(r)}catch{}},H=async(r,a,l,d)=>{const p=await Ma(r,a,l,e.trustedClientIpHeader,d);return e.functions!==void 0&&(p.headers[bt]=yt),p},U=async(r,a,l,d)=>Ha(await H(r,a,l,d)),K=async(r,a)=>{const l=await H(r,a,e.resolveIdentity);if(I.has(r)&&l.headers.authorization===void 0){const d=k();d!==void 0&&(l.headers.authorization=`Bearer ${d}`)}return l};let W=!1,J=!1;const Y=()=>{J||(J=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},G=r=>{if(!e.allowUnauthenticatedShardAccess){const a=r==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${r} access is default-denied: configure \`${a}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${r} access (relying solely on per-row RLS).`,{code:r==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}W||(W=!0,console.warn([`[lunora] SECURITY: serving ${r} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},re=async(r,a,l=!1)=>{if(a.includes(qe)||a.includes(Xe))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(!l)if(e.authorizeShard){if(!await Ie(e.authorizeShard({identity:r,shardKey:a})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else a!==o&&G("shard")},Q=Fs({defaultShard:o,forwardToShard:S,isAdmin:E,queryCoordinator:s,resolveForwardContext:K,shardDO:u,shardedTables:()=>(e.listSchemaTables?.()??[]).filter(r=>e.resolveTableSharding?.(r)?.mode.kind==="shardBy")}),de=async(r,a,l,d,p,R)=>{ve(r);const A={"content-type":"application/json",[bt]:yt,"x-lunora-system":"1"};return p?.userId!==void 0&&p.userId.length>0&&(A["x-lunora-userid"]=p.userId),p?.identity!==void 0&&p.identity.length>0&&(A["x-lunora-identity"]=p.identity),d!==void 0&&d.length>0&&(A["x-lunora-mutation-id"]=d),R!==void 0&&R.length>0&&(A.traceparent=R),S(u,l,De(r,a,A))},oe=async(r,a,l,d,p)=>{const R=Eo(l.env,l.context?.exports,r,["create"]);if(R===void 0)throw new c(`${d} targets workflow "${r}", which is on neither ctx.exports nor env`,{code:"CRON_JOB_FAILED",status:500});if(no(a))throw new c(`${d} params ${ro}`,{code:"BAD_REQUEST",status:400});try{await R.create(p===void 0?{params:a}:{id:p,params:a})}catch(A){if(!ao(A))throw A}},be=async(r,a,l,d)=>{if(r.workflow){await oe(r.workflow,r.args??{},{context:l,env:a},`cron job "${r.name}"`);return}if(r.functionPath===void 0)throw new c(`cron job "${r.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const p=await de(r.functionPath,r.args??{},r.shardKey??o,void 0,void 0,d);if(!p.ok)throw new c(`cron job "${r.name}" (${r.functionPath}) failed with shard status ${String(p.status)}`,{code:"CRON_JOB_FAILED",status:500})},z=r=>{if(!E(r))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},se=(r,a,l)=>{if(z(r),a===void 0)throw new c(l.message,{code:l.code,status:400});return a},ae=async(r,a,l,d,p,R)=>{const A=e.cronJobs?.[r];if(!A)return 0;for(const P of A)try{await be(P,a,l,R)}catch(D){d.push(p(D))}return A.length},Tn=async(r,a,l)=>{if(z(r),M(r,"POST","cron-jobs run"),!e.cronJobs)throw new c("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const d=await ee(r),p=typeof d.name=="string"?d.name:"";if(p==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const R=Object.values(e.cronJobs).flat().find(A=>A.name===p);if(!R)throw new c(`no cron job named "${p}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await be(R,a,l),Response.json({name:p,ran:!0},{status:200})},it=async r=>{const a=typeof r.pool=="string"&&r.pool.length>0?r.pool:void 0;if(!a||!h||typeof r.id!="string")return;const l=typeof r.instanceName=="string"&&r.instanceName.length>0?r.instanceName:"default";try{await ye(h,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:r.id,pool:a}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},An=async(r,a,l)=>{M(r,"POST","Scheduler dispatch");const d=await sn(r),p=a??{},R=typeof p.LUNORA_SCHEDULER_SECRET=="string"?p.LUNORA_SCHEDULER_SECRET:void 0,A=e.adminToken??(typeof p.LUNORA_ADMIN_TOKEN=="string"?p.LUNORA_ADMIN_TOKEN:void 0),P=r.headers.get("x-lunora-scheduler-signature");let D=!1;if(P&&R?D=await Ya(R,d,P):A&&(D=Zt(r,A)),!D)throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let O;try{O=JSON.parse(d)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const _=O??{},B=_.args??{},L=typeof _.id=="string"&&_.id.length>0?_.id:void 0;if(typeof _.workflow=="string"&&_.workflow.length>0)return await oe(_.workflow,B,{context:l,env:a},"scheduled workflow",L),await it(_),Response.json({ok:!0},{status:200});if(typeof _.functionPath!="string"||_.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const V=typeof _.shardKey=="string"&&_.shardKey.length>0?_.shardKey:o,x=Ua(r),ue=await de(_.functionPath,B,V,L,x,r.headers.get("traceparent")??void 0);return await it(_),ue},On=No({assertAdmin:z,getReader:()=>e.authAuditReader}),vn=Uo({assertAdmin:z,getMove:()=>e.authJurisdictionMove}),In=async(r,a)=>{z(r);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:Ee({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const d=a?.kind,p=a?.userId,R=a?.limit,A=d==="fcm"||d==="web-push"?d:void 0,P=typeof p=="string"&&p!==""?p:void 0,D=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,O=D>0?Math.min(D,1e3):1e3,B=(await l.list({kind:A,limit:O,userId:P})).filter(L=>A!==void 0&&L.kind!==A?!1:P===void 0||(L.userId??null)===P).map(({keys:L,token:V,...x})=>x);return Response.json({result:Ee({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},kn=async(r,a)=>{if(!a.fanOut&&!(a.functionPath!==kt&&a.functionPath!==Vt&&a.functionPath!==Ze&&a.functionPath!==fn))return await j(r),a.functionPath===kt?On(r,a.args??{}):a.functionPath===Vt?In(r,a.args):vn(r,a.functionPath,a.args??{})},Pn=os({applyGlobals:e.applyGlobals,assertAdmin:z,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:o,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:s,resolveForwardContext:K,shardDO:u,prepareExportRows:async(r,a)=>pn(e,s,r,a,u),streamingImport:(r,a)=>ds(r,e,s,a,u),syncGlobals:e.syncGlobals}),Ue=(r,a)=>{const l=r.searchParams.get(a);return l===null||l===""?void 0:l},Ce=r=>{const a=new URL(r.url),l=a.searchParams.get("limit"),d=a.searchParams.get("offset"),p=l===null?void 0:Number.parseInt(l,10),R=d===null?void 0:Number.parseInt(d,10);return{limit:p!==void 0&&Number.isFinite(p)&&p>=0?p:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},ct=()=>{if(h===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return h},Dn=aa({checkWsAdmin:async r=>E(r)||en(r,k(),g()),requireSchedulerNamespace:ct,resolveSchedulerStub:r=>(z(r),ye(ct(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Nn=Ra({assertAdmin:z,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Un=Lr({assertAdmin:z,parsePaging:Ce,queryParameter:Ue,readBodyBytes:Dr,requireAdminOption:se,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Cn=zo({options:e,readJsonBody:ee,requireAdminOption:se}),Bn=ma({readJsonBody:ee,requireAdminOption:se,vectorIntrospector:e.vectorIntrospector}),xn=Os({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:se}),Hn=Jr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:se}),Ln=Ss({assertAdmin:z,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,architecture:e.architecture,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ce,queryParameter:Ue,requireAdminOption:se}),jn=r=>{const a=[],l=u??r?.SHARD;if(l!==void 0&&a.push(Wr("durable-object:default",l,o)),e.health?.disableBindingProbes!==!0)for(const[d,p]of Object.entries(r??{})){const R=qa(d,p);R!==void 0&&a.push(R)}for(const d of e.health?.probes??[])a.push(d);return a},Mn=Qr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:E,resolveProbes:jn}),$n=r=>{const a=O=>"args"in O?{...O,args:Ye(O.args)}:O,l=e.schedulerInstanceName??"default",d=()=>ye(r,l),p=async(O,_)=>{const B=await d().fetch(new Request(`https://scheduler.internal${O}`,_));if(!B.ok)throw new c(`ctx.scheduler: SchedulerDO ${O} failed (${String(B.status)}): ${await B.text()}`,{code:"INTERNAL",status:500});return await B.json()},R=async(O,_)=>await p(O,{body:JSON.stringify(_),headers:{"content-type":"application/json"},method:"POST"}),A=O=>{const _=O;if(_==null)throw new c("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof _.binding=="string"&&_.binding.length>0)return{workflow:_.binding};if(typeof _.__lunoraRef=="string")return{functionPath:_.__lunoraRef};throw new c("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},P=async()=>(await oo(async _=>p(_===void 0?"/list":`/list?cursor=${encodeURIComponent(_)}`,{method:"GET"}))).map(_=>a(_)),D=async(O,_,B={})=>{const L=A(_),{id:V}=await R("/schedule",{args:kr("ctx.scheduler",String(L.functionPath??L.workflow),B),scheduledFor:Math.ceil(O),...L});return V};return{cancel:async O=>await R("/cancel",{id:O}),get:async O=>{const _=await p(`/get?id=${encodeURIComponent(O)}`,{method:"GET"});return _.record===void 0?null:a(_.record)},list:P,runAfter:async(O,_,B)=>{if(!Number.isFinite(O)||O<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await D(Date.now()+O,_,B)},runAt:async(O,_,B)=>{if(!Number.isFinite(O))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await D(O,_,B)}}},Kn=async(r,a,l)=>{const{claims:d,headers:p,userId:R}=La(await H(r,a,i)),A=Re(a,r,O=>l.waitUntil?.(O)),P=O=>async(_,B={})=>{const L=_.__lunoraRef;if(typeof L!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ve(L);const V=await Te(r,L,Ee(B),O,{...p,"x-lunora-system":"1"},A),x=await V.json();if(x.error)throw new c(x.error.message??"shard RPC failed",{code:x.error.code??"INTERNAL",status:V.status});return Ye(x.result)},D=P(o);return{auth:{getIdentity:()=>Promise.resolve(d),userId:R},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),forShard:O=>{const _=P(O);return{runAction:_,runMutation:_,runQuery:_}},runAction:D,runMutation:D,runQuery:D,...h===void 0?{}:{scheduler:$n(h)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:to(e.storage(a,new URL(r.url).origin))}}},Fn=async(r,a,l)=>{if(!e.httpRouter)return;const d=await Kn(r,a,l);try{return await e.httpRouter.fetch(r,{...a,__lunoraCtx:d},l)}catch(p){return console.error("[lunora] httpRouter (SSR) handler threw:",p),new Response("Internal Server Error",{status:500})}},Gn=async(r,a,l)=>{if(r.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const d=At(r,ie);if(d)return d;const p=l.searchParams.get("shard")??o,{headers:R,identity:A}=await H(r,a,i),P=E(r)||await en(r,k(),g());await re(A,p,P);const D=Xt(r,R),O=qt(a,e.shardDO);if(O!==void 0){D.set("x-lunora-shard-binding",O);const _=await za(u,p);if(_>0){const B=yo(p,Math.floor(Math.random()*_));return S(u,B,new Request(r,{headers:D}),Ot(r))}}return S(u,p,new Request(r,{headers:D}))},Qn=async(r,a,l)=>{if(f===void 0)return new Response("Not found",{status:404});if(r.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const d=At(r,ie);if(d)return d;let p;try{p=decodeURIComponent(l.pathname.slice(Qt.length))}catch{return new Response("Unknown voice agent",{status:404})}const R=Object.hasOwn(f,p)?f[p]:void 0;if(R===void 0)return new Response("Unknown voice agent",{status:404});const A=l.searchParams.get("threadKey");if(A===null||A.length===0)return new Response("Missing threadKey",{status:400});const{headers:P,identity:D}=await H(r,a,i);if(e.authorizeShard){if(!await Ie(e.authorizeShard({identity:D,shardKey:A})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else G("shard");const O=Xt(r,P);return S(R,A,new Request(r,{headers:O}))},Wn=async(r,a,l)=>{if(e.authorizeFanOut){if(!await Ie(e.authorizeFanOut(l,r.table,a)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(a.startsWith("__lunora_relation__:"))throw new c("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});G("fan-out")},Se=async(r,a)=>{if(!(!r.fanOut&&r.functionPath.startsWith("__lunora_admin__:"))){if(r.fanOut){await Wn(r.fanOut,r.functionPath,a);return}await re(a,r.shardKey??o)}},zn=(r,a,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){Y();return}if(e.functions[a]?.kind!=="query"||l.includes(Xe)||l.includes(qe))return;const d=Ot(r);return d===void 0?void 0:{name:bo(l,d),region:d}},Vn=async(r,a,l,d,p)=>{const R=zn(r,a,d);if(R!==void 0){const A={...p,"x-lunora-replica-read":"1",...y===void 0?{}:{"x-lunora-shard-binding":y}},P=_o(r.headers.get("x-lunora-min-seq"));P!==void 0&&(A["x-lunora-min-seq"]=String(P));const D=await S(u,R.name,De(a,l,A),R.region);if(D.status!==421)return D}return S(u,d,De(a,l,p))},Te=async(r,a,l,d,p,R)=>{const A=Date.now(),{observability:P,sampling:D}=e,O=Ve(r),{decision:_,ignoredUpstream:B,trace:L}=jt(r,{...D===void 0?{}:{sampling:D},trustInbound:t(r)});B&&n(r);const V={...p,[Rt]:_.keepErrors?"1":"0"};Mt(L,V);try{const x=await Vn(r,a,l,d,V);ce(P,{...O,...Gt(L),durationMs:Date.now()-A,functionPath:a,ok:x.ok,shardKey:d,...x.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(x.status)}`,status:x.status}}},R,void 0,{isTraced:L.sampled,keepErrors:_.keepErrors});const ue=new Response(x.body,{headers:x.headers,status:x.status,statusText:x.statusText});return ue.headers.set("x-lunora-shard-key",d),ue}catch(x){throw ce(P,{...O,...Gt(L),...ke(a,Date.now()-A,x,{shardKey:d})},R,void 0,{isTraced:L.sampled,keepErrors:_.keepErrors}),x}},Jn=r=>{if(r.fanOut&&r.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});r.fanOut||ve(r.functionPath)},Yn=async(r,a,l)=>{M(r,"POST","RPC");const d=await Ga(r);Fa(a,d),Jn(d);const p=await kn(r,d);if(p!==void 0)return p;const{headers:R,identity:A}=await U(r,a,i);Wt(r,A),await Se(d,A);const P=Je(d,e);{const D=Date.now(),{observability:O}=e,_=Ve(r),B=Re(a,r,l&&(x=>l.waitUntil?.(x)));if(d.fanOut)try{const x=await s.fanOut(u,{args:d.args??{},fanOut:d.fanOut,functionPath:d.functionPath,headers:R});return ce(O,{durationMs:Date.now()-D,fanOut:{failed:x.failed,shards:x.ok+x.failed,table:d.fanOut.table},functionPath:d.functionPath,..._,ok:!0},B),Response.json(x,{headers:{"content-type":"application/json"},status:200})}catch(x){throw ce(O,{...ke(d.functionPath,Date.now()-D,x,{fanOut:{table:d.fanOut.table}}),..._},B),x}const L=d.shardKey??o,V=()=>Te(r,d.functionPath,d.args??{},L,R,B);return P&&e.x402Charge?e.x402Charge(r,{functionPath:d.functionPath,price:P.price},V,ze(l)):V()}},qn=async(r,a,l)=>{M(r,"POST","RPC batch");const d=await ee(r),{calls:p}=d;if(!Array.isArray(p))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:A}=await U(r,a,i);Wt(r,A);const P=Jo(p,o);for(const $ of P.values())for(const F of $)if(e.functions?.[F.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${F.functionPath}" cannot be called in a batch; dispatch it individually over ${Ft}`,{code:"BAD_REQUEST",status:400});await Promise.all([...P.entries()].flatMap(([$,F])=>F.map(Z=>Se({args:Z.args,functionPath:Z.functionPath,shardKey:$},A))));const{observability:D,sampling:O}=e,_=Re(a,r,l&&($=>l.waitUntil?.($))),B=Ve(r),{decision:L,ignoredUpstream:V,trace:x}=jt(r,{...O===void 0?{}:{sampling:O},trustInbound:t(r)});V&&n(r);const ue={isTraced:x.sampled,keepErrors:L.keepErrors},dr=$=>{const F={...R,"content-type":"application/json",[Rt]:L.keepErrors?"1":"0"};return Mt({...x,spanId:$},F),F},Be=$=>({parentSpanId:$,spanId:ge(8),traceFlags:x.traceFlags,traceId:x.traceId}),Oe=[],xe=[],ht=($,F,Z,le)=>({body:{error:{code:Z,message:le}},id:$.id,status:F}),ft=($,F,Z,le,fe)=>{for(const q of $)ce(D,fe(q),_,void 0,ue),Oe.push(ht(q,F,Z,le))},ur=($,F,Z,le,fe,q)=>{for(const _e of $){const pe=fe.get(_e.id)??q,me=pe<400;ce(D,{durationMs:le,functionPath:_e.functionPath,...B,...Be(Z),ok:me,shardKey:F,...me?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},_,void 0,ue)}};await Promise.all([...P.entries()].map(async([$,F])=>{const Z=ge(8),le=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:F}),headers:new Headers(dr(Z)),method:"POST"}),fe=Date.now();let q;try{q=await S(u,$,le)}catch(X){const Le=Date.now()-fe,{body:wt}=mr(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});ft(F,502,wt.code,wt.message,fr=>({...ke(fr.functionPath,Le,X,{shardKey:$}),...B,...Be(Z)}));return}const _e=Date.now()-fe,pe=q.headers.get("x-d1-bookmark");pe&&xe.push(pe);let me;try{me=await q.json()}catch{const X=`shard batch returned a non-JSON response (${String(q.status)})`;ft(F,q.status,"SHARD_ERROR",X,Le=>({durationMs:_e,error:{code:"SHARD_ERROR",message:X,status:q.status},functionPath:Le.functionPath,...B,...Be(Z),ok:!1,shardKey:$}));return}const He=Array.isArray(me.results)?me.results:[],lr=new Map(He.map(X=>[X.id,X.status??q.status])),hr=new Set(He.map(X=>X.id));ur(F,$,Z,_e,lr,q.status),Oe.push(...He);for(const X of F)hr.has(X.id)||Oe.push(ht(X,q.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const pt={"content-type":"application/json"},[mt]=xe;return xe.length===1&&mt!==void 0&&(pt["x-d1-bookmark"]=mt),Response.json({results:Oe},{headers:pt,status:200})},Xn=async(r,a,l,d={},p={})=>{try{const R=l.__lunoraRef;if(typeof R!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ve(R);const{headers:A,identity:P}=await U(r,a,i,p.context),D={args:d,functionPath:R,shardKey:p.shardKey};await Se(D,P);const O=p.shardKey??o,_=Re(a,r,p.waitUntil),B=()=>Te(r,R,d,O,A,_),L=Je(D,e);return L&&e.x402Charge?await e.x402Charge(r,{functionPath:R,price:L.price},B,ze(p.waitUntil?{waitUntil:p.waitUntil}:p.context)):await B()}catch(R){return Et(R)}},dt=async(r,a,l)=>{const{observability:d}=e,p=Date.now(),R=ge(16),A=ge(8),P=Yt(a),D=nn(R,A,!0);try{const O=await l(D);return ce(d,{durationMs:Date.now()-p,functionPath:r,ok:!0,spanId:A,traceId:R},P),O}catch(O){throw ce(d,{...ke(r,Date.now()-p,O,{}),spanId:A,traceId:R},P),O}finally{_t(d,P)}},ut=async(r,a,l,d)=>{v(a);const p=[],R=_=>_ instanceof Error?_:new Error(String(_)),A=e.crons?.[r.cron];if(A)try{await A(r,a,l)}catch(_){p.push(R(_))}const P=await ae(r.cron,a,l,p,R,d),D=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===r.cron;if(D)try{await Fo(e,s,u,k(),r)}catch(_){p.push(R(_))}if(!A&&P===0&&!D){const _=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${r.cron}") fired but no cron handler is registered for that expression. Registered: ${_.length===0?"(none)":_.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[O]=p;if(p.length===1&&O)throw O;if(p.length>1)throw new AggregateError(p,`scheduled("${r.cron}") had ${String(p.length)} failure(s)`)},Zn=ca({assertAdmin:z,dispatchScheduled:ut,queueHandler:e.queueHandler}),er=async(r,a)=>{try{const l=r??{},d=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!d||d.length===0)return;await S(u,o,De(Ca,{outcome:a},{authorization:`Bearer ${d}`,"content-type":"application/json"}))}catch{}},tr=async(r,a,l,d)=>{if(!e.authHandler)return;const p=e.authBasePath??zt,R=Jt(l.pathname,p)?Nr(r):void 0;let A;try{A=await e.authHandler(R?.request??r)}catch(P){throw R?.overflowed()?new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413}):P}if(R?.overflowed())throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});if(A)return xa(l.pathname,p)&&d.waitUntil?.(er(a,A.status>=400?"fail":"ok")),A},nr=async({args:r,env:a,functionPath:l,request:d,shardKey:p,waitUntil:R})=>{on(r,"REST");const A={functionPath:l,...p===void 0?{}:{shardKey:p}},{headers:P,identity:D}=await U(d,a,i);await Se(A,D);const O=p??o,_=Re(a,d,R),B=()=>Te(d,l,r,O,P,_),L=Je(A,e);return L&&e.x402Charge?e.x402Charge(d,{functionPath:l,price:L.price},B,ze({waitUntil:R})):B()},rr=Pr({functions:e.functions??{},invoke:nr,readJsonBody:ee,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ae=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0;Xa(Ae);const or={[Pa]:r=>r.method!=="GET"&&r.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Ta]:(r,a,l)=>Gn(r,a,l),[Ft]:(r,a,l,d)=>Yn(r,a,d),[Sa]:(r,a,l,d)=>qn(r,a,d),[Aa]:(r,a,l,d)=>An(r,a,d),[Oa]:(r,a,l,d)=>Tn(r,a,d),[va]:async r=>{M(r,"POST","ws-token"),z(r);const a=k();if(a===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await vo(a);return Response.json(l,{headers:{"cache-control":"no-store"}})},...Q,...Pn,...Dn,...Nn,...Un,...Cn,...Bn,...xn,...Hn,...Ln,...Mn,...rr,...Do({assertAdmin:z,getAuthAdmin:()=>e.authAdmin,parsePaging:Ce,queryParameter:Ue,readJsonBody:ee})};let ie=Tt(e.security),lt=!1;const sr=r=>{lt||(lt=!0,ie=Tt(e.security,r??{}))},ar=async(r,a)=>{Da(a)&&await j(r)},ir=(r,a)=>{if(!(a.pathname.startsWith(Ne)||e.authHandler!==void 0&&Jt(a.pathname,e.authBasePath??zt))||r.method!=="POST"&&r.method!=="PUT")return;const d=Number(r.headers.get("content-length")??""),p=Ea[a.pathname]??rn;if(Number.isFinite(d)&&d>p)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},cr=async(r,a,l)=>{tt.set(r,l);const d=new URL(r.url);ir(r,d);const p=await tr(r,a,d,l);if(p)return p;if(Ae){const O=`${r.method} ${d.pathname}`,_=Ae[O]??Ae[d.pathname];if(_)return _(r,a,l)}const R=Zn[d.pathname];if(R)return R(r,a,l);const A=or[d.pathname];if(A)return await ar(r,d.pathname),A(r,a,d,l);if(e.voiceAgents!==void 0&&d.pathname.startsWith(Qt))return Qn(r,a,d);if(d.pathname.startsWith(Ne))return new Response("Not found",{status:404});const P=await Fn(r,a,l);if(P&&P.status!==404)return P;const D=await e.authDiscoveryHandler?.(r);return D?(await P?.body?.cancel(),D):P??new Response("Not found",{status:404})};return{async fetch(r,a,l){e.passThroughOnException&&l.passThroughOnException?.(),sr(a),v(a);const d=Zr(r,ie);if(d)return d;const p=eo(r,ie);if(p)return $e(p,r,ie);try{const R=await cr(r,a,l);return $e(R,r,ie)}catch(R){return $e(Et(R),r,ie)}finally{_t(e.observability,Yt(l))}},async queue(r,a,l){await dt(`queue:${ja(r)}`,l,async d=>{await e.queue?.(r,a,l,{traceparent:d})})},async scheduled(r,a,l){await dt(`cron:${r.cron}`,l,async d=>{await ut(r,a,l,d)})},serverQuery:Xn}},ei=e=>Sn(e),ti=e=>typeof e=="function"?{fetch:e}:e,ni=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,ri=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},vi=(e,t)=>{const n=ti(e),{email:o,queue:s,scheduled:i}=ri(e),u=f=>{const b={...ei({...f,httpRouter:n})};return i!==void 0&&!ni(f)&&(b.scheduled=async(S,T,k)=>{await i(S,T,k)}),s!==void 0&&f.queue===void 0&&(b.queue=async(S,T,k)=>{await s(S,T,k)}),o!==void 0&&(b.email=async(S,T,k)=>{await o(S,T,k)}),b};if(typeof t!="function")return u(t);const h=t;return{fetch:(f,m,b)=>u(h(m)).fetch(f,m,b),queue:(f,m,b)=>u(h(m)).queue?.(f,m,b)??Promise.resolve(),scheduled:(f,m,b)=>u(h(m)).scheduled(f,m,b),serverQuery:(f,m,b,S,T)=>u(h(m)).serverQuery(f,m,b,S,T),...o===void 0?{}:{email:(f,m,b)=>u(h(m)).email?.(f,m,b)??Promise.resolve()}}},oi=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new c("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},Ii=(e={})=>(t,n,o)=>Sn(oi(e,n)).fetch(t,n,o??wr),ki=e=>e;export{Ze as COPY_AUTH_TO_JURISDICTION_OP,kt as GET_AUTH_AUDIT_LOG_OP,wr as NOOP_EXECUTION_CONTEXT,fn as PURGE_UNPINNED_AUTH_OP,Ni as composeIdentityResolvers,ei as composeWorker,Ii as createLunoraHandler,Sn as createWorker,ki as defineRpcEnvelope,za as probeRelayCount,oi as resolveLunoraOptions,Ui as routeIdentityResolvers,vi as withFrameworkWorker};
|