@lunora/runtime 1.0.0-alpha.279 → 1.0.0-alpha.280

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -2035,8 +2035,9 @@ interface LogEvent {
2035
2035
  /**
2036
2036
  * Structured fields the caller attached (`ctx.log.info(message, fields)` or a
2037
2037
  * bound `ctx.log.with(fields)` child), already normalized to a fresh bag of
2038
- * JSON-safe primitives (see `shared/log-fields.ts`). Absent for a plain
2039
- * console-style call.
2038
+ * JSON-safe primitives (see `shared/log-fields.ts`). An `Error` value arrives
2039
+ * as the JSON of its name, message, stack and cause chain; `parseLoggedError`
2040
+ * reads it back. Absent for a plain console-style call.
2040
2041
  */
2041
2042
  fields?: LogFields;
2042
2043
  /** Function path that emitted the line, e.g. `"messages:list"`. */
package/dist/index.d.ts CHANGED
@@ -2035,8 +2035,9 @@ interface LogEvent {
2035
2035
  /**
2036
2036
  * Structured fields the caller attached (`ctx.log.info(message, fields)` or a
2037
2037
  * bound `ctx.log.with(fields)` child), already normalized to a fresh bag of
2038
- * JSON-safe primitives (see `shared/log-fields.ts`). Absent for a plain
2039
- * console-style call.
2038
+ * JSON-safe primitives (see `shared/log-fields.ts`). An `Error` value arrives
2039
+ * as the JSON of its name, message, stack and cause chain; `parseLoggedError`
2040
+ * reads it back. Absent for a plain console-style call.
2040
2041
  */
2041
2042
  fields?: LogFields;
2042
2043
  /** Function path that emitted the line, e.g. `"messages:list"`. */
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 p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as x,toFivetranResponse as R}from"./packem_shared/toAirbyteMessages-DY0vsuEn.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as b}from"./packem_shared/composeWorker-g2VSFC4t.mjs";import{createCrossShardRelationCapabilities as C}from"./packem_shared/createCrossShardRelationCapabilities-Bm04PAy7.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-w_RLPiwj.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-PkZWF-_g.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w}from"./packem_shared/export-tap-C2B_SATf.mjs";import{HEALTH_PATH as Y,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-B8ndDG3s.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{m as $,a as ee}from"./packem_shared/memoize-identity-DzVUB2rt.mjs";import{e as oe,a as te}from"./packem_shared/observability-9slk__Gi.mjs";import{enrichSink as se,filterSink as ie}from"./packem_shared/enrichSink-BLCB5VpU.mjs";import{a as ne,c as ce,b as me,o as fe,p as Ee,w as xe}from"./packem_shared/observability-sinks-CRKDJlAP.mjs";import{D as Se,c as le}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as ue,createStaticShardRegistry as _e}from"./packem_shared/createQueryCoordinator-CaQF9cds.mjs";import{applyJurisdiction as be,resolveShard as ye}from"./packem_shared/applyJurisdiction-DKQE8kOA.mjs";import{a as Oe,r as Ae,b as Le}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as he,b as He,c as Pe,r as ge}from"./packem_shared/rest-routes-Br05k63D.mjs";import{d as Ie,e as De,h as Fe,r as Me}from"./packem_shared/security-headers-CZVK7xvl.mjs";import{createShardClient as Ge}from"./packem_shared/createShardClient-Dar1gB9v.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ue}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-Onz8HkiB.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Be}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as ze}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as je,routeIdentityResolvers as Ve}from"./packem_shared/composeIdentityResolvers-CpdHuDyk.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Se as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,Y as HEALTH_PATH,z as HEALTH_READY_PATH,Be as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,ze as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ue as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ne as analyticsEngineSink,be as applyJurisdiction,Oe as applyRestCache,he as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,He as buildRestRoutes,ce as combineSinks,je as composeIdentityResolvers,l as composeWorker,me as consoleSink,C as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,d as createLunoraHandler,M as createMemoryCursorStore,le as createPipelineLogReader,ue as createQueryCoordinator,Pe as createRestRateLimit,Ge as createShardClient,_e as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Ie as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,De as enforceOrigin,se as enrichSink,ie as filterSink,Fe as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,fe as otlpSink,H as parseStackFrames,Ee as pipelineLogSink,W as presenceProbe,G as r2Sink,Ae as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Me as resolveSecurity,ye as resolveShard,Le as restCacheHeaders,ge as restSurfaceFromRegistry,Ve as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,x as toAirbyteMessages,P as toError,I as toErrorResponse,R as toFivetranResponse,w as webhookExportSink,xe as webhookSink,b as withFrameworkWorker};
1
+ import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as x,toFivetranResponse as R}from"./packem_shared/toAirbyteMessages-DY0vsuEn.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as b}from"./packem_shared/composeWorker-ka0CpeBE.mjs";import{createCrossShardRelationCapabilities as C}from"./packem_shared/createCrossShardRelationCapabilities-Bm04PAy7.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-w_RLPiwj.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-PkZWF-_g.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w}from"./packem_shared/export-tap-C2B_SATf.mjs";import{HEALTH_PATH as Y,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-B8ndDG3s.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{m as $,a as ee}from"./packem_shared/memoize-identity-DzVUB2rt.mjs";import{e as oe,a as te}from"./packem_shared/observability-9slk__Gi.mjs";import{enrichSink as se,filterSink as ie}from"./packem_shared/enrichSink-D4Q4jLT5.mjs";import{a as ne,c as ce,b as me,o as fe,p as Ee,w as xe}from"./packem_shared/observability-sinks-CTGNb3dU.mjs";import{D as Se,c as le}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as ue,createStaticShardRegistry as _e}from"./packem_shared/createQueryCoordinator-CaQF9cds.mjs";import{applyJurisdiction as be,resolveShard as ye}from"./packem_shared/applyJurisdiction-DKQE8kOA.mjs";import{a as Oe,r as Ae,b as Le}from"./packem_shared/rest-cache-q5V06Etw.mjs";import{a as he,b as He,c as Pe,r as ge}from"./packem_shared/rest-routes-D5NWHmVl.mjs";import{d as Ie,e as De,h as Fe,r as Me}from"./packem_shared/security-headers-0DqdJ04h.mjs";import{createShardClient as Ge}from"./packem_shared/createShardClient-Dar1gB9v.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ue}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-Onz8HkiB.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Be}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as ze}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as je,routeIdentityResolvers as Ve}from"./packem_shared/composeIdentityResolvers-CpdHuDyk.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Se as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,Y as HEALTH_PATH,z as HEALTH_READY_PATH,Be as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,ze as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ue as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ne as analyticsEngineSink,be as applyJurisdiction,Oe as applyRestCache,he as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,He as buildRestRoutes,ce as combineSinks,je as composeIdentityResolvers,l as composeWorker,me as consoleSink,C as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,d as createLunoraHandler,M as createMemoryCursorStore,le as createPipelineLogReader,ue as createQueryCoordinator,Pe as createRestRateLimit,Ge as createShardClient,_e as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Ie as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,De as enforceOrigin,se as enrichSink,ie as filterSink,Fe as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,fe as otlpSink,H as parseStackFrames,Ee as pipelineLogSink,W as presenceProbe,G as r2Sink,Ae as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Me as resolveSecurity,ye as resolveShard,Le as restCacheHeaders,ge as restSurfaceFromRegistry,Ve as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,x as toAirbyteMessages,P as toError,I as toErrorResponse,R as toFivetranResponse,w as webhookExportSink,xe as webhookSink,b as withFrameworkWorker};
@@ -1 +1 @@
1
- import"./otlp-resource-BBR8xs6m.mjs";import{S as a,a as s,c as S,b as e,o as k,p,w as c}from"./observability-sinks-CRKDJlAP.mjs";export{a as SINK_CONFIG_FIELDS,s as analyticsEngineSink,S as combineSinks,e as consoleSink,k as otlpSink,p as pipelineLogSink,c as webhookSink};
1
+ import"./otlp-resource-BBR8xs6m.mjs";import{S as a,a as s,c as S,b as e,o as k,p,w as c}from"./observability-sinks-CTGNb3dU.mjs";export{a as SINK_CONFIG_FIELDS,s as analyticsEngineSink,S as combineSinks,e as consoleSink,k as otlpSink,p as pipelineLogSink,c as webhookSink};
@@ -1 +1 @@
1
- import{a as s,e as r,r as t,b as c}from"./rest-cache-CmHN871W.mjs";export{s as applyRestCache,r as effectiveRestScope,t as requestCarriesCredentials,c as restCacheHeaders};
1
+ import{a as s,e as r,r as t,b as c}from"./rest-cache-q5V06Etw.mjs";export{s as applyRestCache,r as effectiveRestScope,t as requestCarriesCredentials,c as restCacheHeaders};
@@ -1 +1 @@
1
- import{a as o,b as i,c as m,r as R}from"./rest-routes-Br05k63D.mjs";import"./rest-cache-CmHN871W.mjs";import"./LunoraError-PkZWF-_g.mjs";import"./method-guard-8Jo4Q8uS.mjs";export{o as argsFromQuery,i as buildRestRoutes,m as createRestRateLimit,R as restSurfaceFromRegistry};
1
+ import{a as o,b as i,c as m,r as R}from"./rest-routes-D5NWHmVl.mjs";import"./rest-cache-q5V06Etw.mjs";import"./LunoraError-PkZWF-_g.mjs";import"./method-guard-8Jo4Q8uS.mjs";export{o as argsFromQuery,i as buildRestRoutes,m as createRestRateLimit,R as restSurfaceFromRegistry};
@@ -1,4 +1,4 @@
1
- import{isLunoraError as Tr,toErrorBody as ms}from"@lunora/errors";import{encodeWire as he,decodeWire as rt,encodeArgsOrThrow as ws}from"@lunora/wire";import{t as Ft,f as Kt}from"./base64-Bl1_r2k1.mjs";import{e as ot,b as gs}from"./memoize-identity-DzVUB2rt.mjs";import{d as fn,E as pn,a as ys,b as _s,W as mn}from"./error-detail-C46mdOTW.mjs";import{NOOP_EXECUTION_CONTEXT as bs}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{d as Es,a as As,i as Ts,e as Ss,E as wn,b as Rs}from"./identity-header-CG1FNe-S.mjs";import{O as Sr,a as Rr}from"./origin-paywall-B6eOO67m.mjs";import{o as Ne,b as vr,p as vs,m as Os,d as Ns,a as Is,r as ks}from"./otlp-resource-BBR8xs6m.mjs";import{r as Ds,f as gn,a as me,S as yn}from"./observability-9slk__Gi.mjs";import{LunoraError as l,toErrorResponse as _n}from"./LunoraError-PkZWF-_g.mjs";import{resolveShard as pe,applyJurisdiction as Qe}from"./applyJurisdiction-DKQE8kOA.mjs";import{d as ne,e as se,M as Or,b as Ps,f as Us,g as Nr,w as Cs,h as Ir,t as Ls}from"./rest-routes-Br05k63D.mjs";import{a as F,m as Oe}from"./method-guard-8Jo4Q8uS.mjs";import{normalizeBackupPrefix as Gt,BACKUP_KEY_PREFIX as Wt,isBackupManifestKey as xs,backupObjectKeyOfManifest as kr,backupObjectKey as Bs,backupManifestKey as $s}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Ms,buildStorageAdminRoutes as Hs,STORAGE_UPLOAD_MAX_BODY_BYTES as js,STORAGE_PATH as Fs}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-Onz8HkiB.mjs";import{b as Ks,e as Gs,f as bn,g as Ws,h as Qs}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as Vs,durableObjectProbe as zs,d1Probe as Js,presenceProbe as Et}from"./HEALTH_PATH-B8ndDG3s.mjs";import{wrapResolverWithContract as Ys}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{composeIdentityResolvers as rh,routeIdentityResolvers as oh}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{buildLogArchiveAdminRoutes as Xs}from"./LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{pruneShardRegistry as qs,createQueryCoordinator as Zs,createDefaultShardRegistry as ea,refreshShardHeadersPerCall as ta,refreshedShardHeaders as na}from"./createQueryCoordinator-CaQF9cds.mjs";import{i as En,r as An,h as ra,e as oa,d as At,a as Tn}from"./security-headers-CZVK7xvl.mjs";const sa=(e,t,n,r)=>{const s=e.get(t);if(s!==void 0)return s;ot(e,r);const a=n().catch(d=>{throw e.get(t)===a&&e.delete(t),d});return e.set(t,a),a},aa=new TextEncoder,ia=64,ca=new Map,Dr=async e=>sa(ca,e,async()=>crypto.subtle.importKey("raw",aa.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),ia),Pr=new TextEncoder,da=Array.from({length:32},(e,t)=>t);new RegExp(`[${da.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const pt=async(e,t)=>{const n=await Dr(e),r=await crypto.subtle.sign("HMAC",n,Pr.encode(t));return Ft(new Uint8Array(r))},Ur=async(e,t,n)=>{const r=await Dr(e);return crypto.subtle.verify("HMAC",r,n,Pr.encode(t))},Cr="lnat",ua="__lunora_admin_revocations__",la=/^[a-z0-9][a-z0-9_-]{0,63}$/u,ha=/^[\w-]{43}$/u,tt="x-lunora-admin-signal",fa="as1",pa=6e4,ma=5e3,Lr=e=>la.test(e),wa=e=>{const t=e.split(".");if(t.length!==3||t[0]!==Cr)return;const[,n,r]=t;return Lr(n)&&ha.test(r)?{name:n,secret:r}:void 0},xr=e=>{const t=e?/^bearer\s+(\S+)\s*$/iu.exec(e):void 0;return t?.[1]===void 0?void 0:wa(t[1])},ga=e=>{const t=Ft(crypto.getRandomValues(new Uint8Array(32)));return{secret:t,token:`${Cr}.${e}.${t}`}},Br=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))].map(n=>n.toString(16).padStart(2,"0")).join(""),ya=async(e,t,n=Date.now(),r=Number.POSITIVE_INFINITY)=>{const s=`${fa}.${String(Math.floor(Math.min(n+pa,r)))}.${t}`;return`${s}.${await pt(e,s)}`},Lt=["disabled","schema","schema_and_log","schema_and_log_and_data"],_a="schema",ba=e=>e==null||e===""?_a:typeof e=="string"&&Lt.includes(e)?e:"disabled",Ea=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},$r="__lunoraBranch",Aa=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,$r),Ta=`may not contain the reserved workflow branch-marker key ("${$r}")`,Sa=new Set(["exp","expiresAtMs","iat","jti","nbf"]),xt=e=>Array.isArray(e)?`[${e.map(t=>xt(t)).join(",")}]`:typeof e=="object"&&e!==null?`{${Object.entries(e).filter(([,n])=>n!==void 0).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${xt(r)}`).join(",")}}`:JSON.stringify(e)??"null",Ra=e=>{const t=Object.fromEntries(Object.entries(e??{}).filter(([n])=>!Sa.has(n)));return Object.keys(t).length===0?"":xt(t)},va=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ue=(e,t)=>e>>>t|e<<32-t,Oa=e=>{const t=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),n=new Uint8Array(Math.ceil((e.length+9)/64)*64);n.set(e),n[e.length]=128;const r=new DataView(n.buffer);r.setUint32(n.length-8,Math.floor(e.length*8/2**32)),r.setUint32(n.length-4,e.length*8>>>0);const s=new Uint32Array(64);for(let u=0;u<n.length;u+=64){for(let A=0;A<16;A+=1)s[A]=r.getUint32(u+A*4);for(let A=16;A<64;A+=1){const S=s[A-15],k=s[A-2],_=ue(S,7)^ue(S,18)^S>>>3,P=ue(k,17)^ue(k,19)^k>>>10;s[A]=s[A-16]+_+s[A-7]+P>>>0}let[c,w,g,b,p,N,y,E]=t;for(let A=0;A<64;A+=1){const S=ue(p,6)^ue(p,11)^ue(p,25),k=p&N^~p&y,_=E+S+k+va[A]+s[A]>>>0,P=ue(c,2)^ue(c,13)^ue(c,22),v=c&w^c&g^w&g,C=P+v>>>0;E=y,y=N,N=p,p=b+_>>>0,b=g,g=w,w=c,c=_+C>>>0}[c,w,g,b,p,N,y,E].forEach((A,S)=>{t[S]=t[S]+A>>>0})}const a=new Uint8Array(32),d=new DataView(a.buffer);return t.forEach((u,c)=>{d.setUint32(c*4,u)}),a},Na=(e,t)=>Ft(Oa(new TextEncoder().encode(`${JSON.stringify(e??null)}|${Ra(t)}`)).subarray(0,16)),Ia=async e=>{const t=[];let n;for(;;){const r=await e(n);if(t.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return t;if(r.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=r.cursor}},ka=/already[\s_-]?exists/iu,Da=e=>ka.test(e instanceof Error?e.message:String(e)),Pa="/_lunora/live/publish",Ua="cf-ray",Ca="x-lunora-ray-id",La=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,xa=e=>e==null?void 0:La.exec(e.trim())?.[1]?.toLowerCase(),Ba=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Ba);const $a=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Ma=-100,Ha=15,ja=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&$a.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Ha?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Ma?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},Sn=e=>{const t=e.cf;return t===void 0?void 0:ja(t)},st="::relay::",Fa=(e,t)=>`${e}${st}${String(t)}`,at="::replica::",Ka=(e,t)=>`${e}${at}${t}`,Ga=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Wa=(e,t)=>{const n={...e};return delete n.shardKey,t!==void 0&&(n.shardKey=t),n},Mr=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let s=0;s<n;s+=1){const a=s<e.length?e.charCodeAt(s):0,d=s<t.length?t.charCodeAt(s):0;r|=a^d}return r===0},Qa="/_lunora/scheduler/dispatch",Va="__lunora_relation__:",za=e=>e.startsWith(Va),Hr="agents:agentRun",Ja=(e,t,n)=>e===Hr&&t!==n,Ya=`\`${Hr}\` runs on the default shard only, where agent threads live; to run an agent's tools on another shard, start it from a mutation on that shard with \`ctx.agents.<name>.run\``,it=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...s]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:Mr(t,s.join(" ").trim())},Xa=async(e,t,n)=>{const r=e.headers.get("x-lunora-scheduler-signature"),{schedulerSecret:s}=n;return r!==null&&r.length>0&&s!==void 0&&s.length>0?Mr(await pt(s,t),r):it(e,n.adminToken)},Rn="/_lunora/ws/reauth",qa="/_lunora/claims",Za="x-lunora-scheduled-for",ei=({forwardedIdentity:e,mutationId:t,scheduledFor:n,traceparent:r})=>{const s={"content-type":"application/json",[Rr]:Sr,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(s["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(s["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(s["x-lunora-mutation-id"]=t),r!==void 0&&r.length>0&&(s.traceparent=r),n!==void 0&&Number.isFinite(n)&&(s[Za]=String(Math.trunc(n))),s},ti=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}}},ni=(e,t,n)=>e?.[n]??t?.[n],ri=(e,t,n,r)=>{const s=ni(e,t,n);if(!(typeof s!="object"||s===null))return r.every(a=>typeof s[a]=="function")?s:void 0},jr="v1",oi=6e4,si=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??oi),r=`${jr}.${String(n)}`,s=await pt(e,r);return{expiresAtMs:n,token:`${r}.${s}`}},ai=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const r=t.split(".");if(r.length!==3)return!1;const[s,a,d]=r;if(s!==jr||d.length===0)return!1;const u=Number(a);if(!Number.isFinite(u)||u<=n)return!1;let c;try{c=Kt(d)}catch{return!1}return Ur(e,`${s}.${a}`,c)},ii="https://admin-revocations.internal",ci=(e,t)=>{const n=async(r,s)=>{const a=t();if(a===void 0)throw new l("named admin tokens require a configured LUNORA_ADMIN_TOKEN, which signs them",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const d=await pe(e,ua).fetch(new Request(`${ii}${r}`,{...s,headers:{authorization:`Bearer ${a}`,"content-type":"application/json"}}));if(!d.ok)throw new l(`admin revocation store answered ${String(d.status)}`,{code:"SHARD_UNAVAILABLE",status:503});return d};return{revoke:async(r,s)=>{await n("/revoke",{body:JSON.stringify({createdAt:s,name:r}),method:"POST"})},isRevoked:async(r,s)=>{const u=(await(await n(`/revoked?name=${encodeURIComponent(r)}&createdAt=${String(s)}`,{method:"GET"})).json())?.revoked;if(typeof u!="boolean")throw new l("admin revocation store answered garbage",{code:"SHARD_UNAVAILABLE",status:503});return u},latestRevoked:async r=>{const d=(await(await n(`/latest?name=${encodeURIComponent(r)}`,{method:"GET"})).json())?.latest;if(d!==null){if(typeof d!="number")throw new l("admin revocation store answered garbage",{code:"SHARD_UNAVAILABLE",status:503});return d}}}},di="/_lunora/admin/tokens",ui="__lunora_admin__:createAdminToken",vn="__lunora_admin__:listAdminTokens",li="__lunora_admin__:revokeAdminToken",Tt={"cache-control":"no-store"},On=e=>{if(typeof e!="string"||!Lr(e))throw new l("admin token `name` must match /^[a-z0-9][a-z0-9_-]{0,63}$/",{code:"BAD_REQUEST",status:400});return e},hi=e=>{const t=e.now??Date.now,n=async a=>{const d=await e.readJsonBody(a),u=On(d.name),{expiresAt:c}=d;if(c!==void 0&&(typeof c!="number"||!Number.isFinite(c)||c<=t()))throw new l("admin token `expiresAt` must be a future epoch-ms number",{code:"BAD_REQUEST",status:400});if(e.revocations===void 0)throw new l('named admin tokens need the ADMIN_REVOCATIONS Durable Object binding; export AdminRevocationDO from the worker entry (`export { AdminRevocationDO } from "./lunora/_generated/adminRevocations.js"`) and bind it',{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const{secret:w,token:g}=ga(u),b=await e.revocations.latestRevoked(u),p=b===void 0?t():Math.max(t(),b+1),N=await e.callStore(ui,{createdAt:p,digest:await Br(w),expiresAt:c,name:u});return e.evict(u),Response.json({...N,token:g},{headers:Tt,status:201})},r=async()=>{const{revocations:a}=e;if(a===void 0)throw new l("no admin revocation store is bound, so named admin tokens are refused; export AdminRevocationDO and bind ADMIN_REVOCATIONS",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const{tokens:d}=await e.callStore(vn,{}),u=await Promise.all(d.map(async c=>await a.isRevoked(c.name,c.createdAt)?{...c,revoked:!0}:c));return Response.json({tokens:u},{headers:Tt})},s=async a=>{const d=On(new URL(a.url).searchParams.get("name")??void 0);if(e.revocations===void 0)throw new l("no admin revocation store is bound, so no named admin token can exist",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const{tokens:u}=await e.callStore(vn,{}),c=u.find(w=>w.name===d);if(c===void 0)throw new l(`no admin token named "${d}"`,{code:"NOT_FOUND",status:404});try{await e.revocations.revoke(d,c.createdAt),await e.callStore(li,{createdAt:c.createdAt,name:d})}finally{e.evict(d)}return Response.json({revoked:!0},{headers:Tt})};return{[di]:async a=>(e.assertRootAdmin(a),a.method==="GET"?r():a.method==="POST"?n(a):a.method==="DELETE"?s(a):new Response(void 0,{headers:{allow:"GET, POST, DELETE"},status:405}))}},fi=3e4,pi=5e3,mi=1024,Nn=20,In=1e3,wi=5e3,gi=1024,yi=({listNames:e,lookup:t,now:n=Date.now})=>{const r=new Map,s=new Map,a=new Map,d=new Map,u=new Map;let c=Nn,w=n();const g=()=>{const _=n()-w,P=Math.floor(_/In);return P>0&&(c=Math.min(Nn,c+P),w+=P*In),c<=0?!1:(c-=1,!0)},b=(_,P)=>{for(const[v,C]of _)C.name===P&&_.delete(v)},p=_=>{u.has(_)||(ot(u,gi),u.set(_,!0))};let N=Number.NEGATIVE_INFINITY,y;const E=()=>y!==void 0?y:e===void 0||n()-N<wi?Promise.resolve():(N=n(),y=(async()=>{try{for(const _ of await e())p(_)}catch{}finally{y=void 0}})(),y),A=async _=>(await E(),u.has(_)),S=(_,P,v)=>{const C=t(_,P);d.set(v,C);const M=()=>{d.get(v)===C&&d.delete(v)};return C.finally(M).catch(()=>{}),C},k=(_,P,v,C)=>{C?p(_):u.delete(_),ot(s,mi),s.set(C?P:v,{name:_,until:n()+pi})};return{evict:_=>{b(r,_),b(s,_),u.delete(_);for(const P of d.keys())P.startsWith(`${_}\0`)&&d.delete(P);a.set(_,(a.get(_)??0)+1)},verify:async _=>{const P=xr(_);if(P===void 0)return;const{name:v}=P,C=await Br(P.secret),M=`${v}\0${C}`,H=`${v}\0*`,G=r.get(M);if(G!==void 0&&G.until>n())return G;if((s.get(H)?.until??0)>n()||(s.get(M)?.until??0)>n())return;r.delete(M),s.delete(M),s.delete(H);const z=a.get(v);let Q=d.get(M);if(Q===void 0){if(!(u.has(v)||g())&&!await A(v))return;Q=S(v,C,M)}const Y=await Q;if(a.get(v)!==z)return;if(!Y.live){if(Y.transient===!0)return;k(v,M,H,Y.nameKnown);return}const X=Math.min(n()+fi,Y.expiresAt??Number.POSITIVE_INFINITY);if(X<=n())return;p(v);const ce={name:v,until:X,...Y.expiresAt===void 0?{}:{expiresAt:Y.expiresAt}};return r.set(M,ce),ce}}},_i="x",kn=" ",bi={'"':'"',"'":"'","[":"]","`":"`"},Fr=(e,t)=>{let n=t+2;for(;n<e.length&&e[n]!==`
1
+ import{isLunoraError as Tr,toErrorBody as ms}from"@lunora/errors";import{encodeWire as he,decodeWire as rt,encodeArgsOrThrow as ws}from"@lunora/wire";import{t as Ft,f as Kt}from"./base64-Bl1_r2k1.mjs";import{e as ot,b as gs}from"./memoize-identity-DzVUB2rt.mjs";import{d as fn,E as pn,a as ys,b as _s,W as mn}from"./error-detail-C46mdOTW.mjs";import{NOOP_EXECUTION_CONTEXT as bs}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{d as Es,a as As,i as Ts,e as Ss,E as wn,b as Rs}from"./identity-header-CG1FNe-S.mjs";import{O as Sr,a as Rr}from"./origin-paywall-B6eOO67m.mjs";import{o as Ne,b as vr,p as vs,m as Os,d as Ns,a as Is,r as ks}from"./otlp-resource-BBR8xs6m.mjs";import{r as Ds,f as gn,a as me,S as yn}from"./observability-9slk__Gi.mjs";import{LunoraError as l,toErrorResponse as _n}from"./LunoraError-PkZWF-_g.mjs";import{resolveShard as pe,applyJurisdiction as Qe}from"./applyJurisdiction-DKQE8kOA.mjs";import{d as ne,e as se,M as Or,b as Ps,f as Us,g as Nr,w as Cs,h as Ir,t as Ls}from"./rest-routes-D5NWHmVl.mjs";import{a as F,m as Oe}from"./method-guard-8Jo4Q8uS.mjs";import{normalizeBackupPrefix as Gt,BACKUP_KEY_PREFIX as Wt,isBackupManifestKey as xs,backupObjectKeyOfManifest as kr,backupObjectKey as Bs,backupManifestKey as $s}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Ms,buildStorageAdminRoutes as Hs,STORAGE_UPLOAD_MAX_BODY_BYTES as js,STORAGE_PATH as Fs}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-Onz8HkiB.mjs";import{b as Ks,e as Gs,f as bn,g as Ws,h as Qs}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as Vs,durableObjectProbe as zs,d1Probe as Js,presenceProbe as Et}from"./HEALTH_PATH-B8ndDG3s.mjs";import{wrapResolverWithContract as Ys}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{composeIdentityResolvers as rh,routeIdentityResolvers as oh}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{buildLogArchiveAdminRoutes as Xs}from"./LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{pruneShardRegistry as qs,createQueryCoordinator as Zs,createDefaultShardRegistry as ea,refreshShardHeadersPerCall as ta,refreshedShardHeaders as na}from"./createQueryCoordinator-CaQF9cds.mjs";import{i as En,r as An,h as ra,e as oa,d as At,a as Tn}from"./security-headers-0DqdJ04h.mjs";const sa=(e,t,n,r)=>{const s=e.get(t);if(s!==void 0)return s;ot(e,r);const a=n().catch(d=>{throw e.get(t)===a&&e.delete(t),d});return e.set(t,a),a},aa=new TextEncoder,ia=64,ca=new Map,Dr=async e=>sa(ca,e,async()=>crypto.subtle.importKey("raw",aa.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),ia),Pr=new TextEncoder,da=Array.from({length:32},(e,t)=>t);new RegExp(`[${da.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const pt=async(e,t)=>{const n=await Dr(e),r=await crypto.subtle.sign("HMAC",n,Pr.encode(t));return Ft(new Uint8Array(r))},Ur=async(e,t,n)=>{const r=await Dr(e);return crypto.subtle.verify("HMAC",r,n,Pr.encode(t))},Cr="lnat",ua="__lunora_admin_revocations__",la=/^[a-z0-9][a-z0-9_-]{0,63}$/u,ha=/^[\w-]{43}$/u,tt="x-lunora-admin-signal",fa="as1",pa=6e4,ma=5e3,Lr=e=>la.test(e),wa=e=>{const t=e.split(".");if(t.length!==3||t[0]!==Cr)return;const[,n,r]=t;return Lr(n)&&ha.test(r)?{name:n,secret:r}:void 0},xr=e=>{const t=e?/^bearer\s+(\S+)\s*$/iu.exec(e):void 0;return t?.[1]===void 0?void 0:wa(t[1])},ga=e=>{const t=Ft(crypto.getRandomValues(new Uint8Array(32)));return{secret:t,token:`${Cr}.${e}.${t}`}},Br=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))].map(n=>n.toString(16).padStart(2,"0")).join(""),ya=async(e,t,n=Date.now(),r=Number.POSITIVE_INFINITY)=>{const s=`${fa}.${String(Math.floor(Math.min(n+pa,r)))}.${t}`;return`${s}.${await pt(e,s)}`},Lt=["disabled","schema","schema_and_log","schema_and_log_and_data"],_a="schema",ba=e=>e==null||e===""?_a:typeof e=="string"&&Lt.includes(e)?e:"disabled",Ea=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},$r="__lunoraBranch",Aa=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,$r),Ta=`may not contain the reserved workflow branch-marker key ("${$r}")`,Sa=new Set(["exp","expiresAtMs","iat","jti","nbf"]),xt=e=>Array.isArray(e)?`[${e.map(t=>xt(t)).join(",")}]`:typeof e=="object"&&e!==null?`{${Object.entries(e).filter(([,n])=>n!==void 0).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${xt(r)}`).join(",")}}`:JSON.stringify(e)??"null",Ra=e=>{const t=Object.fromEntries(Object.entries(e??{}).filter(([n])=>!Sa.has(n)));return Object.keys(t).length===0?"":xt(t)},va=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ue=(e,t)=>e>>>t|e<<32-t,Oa=e=>{const t=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),n=new Uint8Array(Math.ceil((e.length+9)/64)*64);n.set(e),n[e.length]=128;const r=new DataView(n.buffer);r.setUint32(n.length-8,Math.floor(e.length*8/2**32)),r.setUint32(n.length-4,e.length*8>>>0);const s=new Uint32Array(64);for(let u=0;u<n.length;u+=64){for(let A=0;A<16;A+=1)s[A]=r.getUint32(u+A*4);for(let A=16;A<64;A+=1){const S=s[A-15],k=s[A-2],_=ue(S,7)^ue(S,18)^S>>>3,P=ue(k,17)^ue(k,19)^k>>>10;s[A]=s[A-16]+_+s[A-7]+P>>>0}let[c,w,g,b,p,N,y,E]=t;for(let A=0;A<64;A+=1){const S=ue(p,6)^ue(p,11)^ue(p,25),k=p&N^~p&y,_=E+S+k+va[A]+s[A]>>>0,P=ue(c,2)^ue(c,13)^ue(c,22),v=c&w^c&g^w&g,C=P+v>>>0;E=y,y=N,N=p,p=b+_>>>0,b=g,g=w,w=c,c=_+C>>>0}[c,w,g,b,p,N,y,E].forEach((A,S)=>{t[S]=t[S]+A>>>0})}const a=new Uint8Array(32),d=new DataView(a.buffer);return t.forEach((u,c)=>{d.setUint32(c*4,u)}),a},Na=(e,t)=>Ft(Oa(new TextEncoder().encode(`${JSON.stringify(e??null)}|${Ra(t)}`)).subarray(0,16)),Ia=async e=>{const t=[];let n;for(;;){const r=await e(n);if(t.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return t;if(r.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=r.cursor}},ka=/already[\s_-]?exists/iu,Da=e=>ka.test(e instanceof Error?e.message:String(e)),Pa="/_lunora/live/publish",Ua="cf-ray",Ca="x-lunora-ray-id",La=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,xa=e=>e==null?void 0:La.exec(e.trim())?.[1]?.toLowerCase(),Ba=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Ba);const $a=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Ma=-100,Ha=15,ja=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&$a.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Ha?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Ma?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},Sn=e=>{const t=e.cf;return t===void 0?void 0:ja(t)},st="::relay::",Fa=(e,t)=>`${e}${st}${String(t)}`,at="::replica::",Ka=(e,t)=>`${e}${at}${t}`,Ga=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Wa=(e,t)=>{const n={...e};return delete n.shardKey,t!==void 0&&(n.shardKey=t),n},Mr=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let s=0;s<n;s+=1){const a=s<e.length?e.charCodeAt(s):0,d=s<t.length?t.charCodeAt(s):0;r|=a^d}return r===0},Qa="/_lunora/scheduler/dispatch",Va="__lunora_relation__:",za=e=>e.startsWith(Va),Hr="agents:agentRun",Ja=(e,t,n)=>e===Hr&&t!==n,Ya=`\`${Hr}\` runs on the default shard only, where agent threads live; to run an agent's tools on another shard, start it from a mutation on that shard with \`ctx.agents.<name>.run\``,it=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...s]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:Mr(t,s.join(" ").trim())},Xa=async(e,t,n)=>{const r=e.headers.get("x-lunora-scheduler-signature"),{schedulerSecret:s}=n;return r!==null&&r.length>0&&s!==void 0&&s.length>0?Mr(await pt(s,t),r):it(e,n.adminToken)},Rn="/_lunora/ws/reauth",qa="/_lunora/claims",Za="x-lunora-scheduled-for",ei=({forwardedIdentity:e,mutationId:t,scheduledFor:n,traceparent:r})=>{const s={"content-type":"application/json",[Rr]:Sr,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(s["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(s["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(s["x-lunora-mutation-id"]=t),r!==void 0&&r.length>0&&(s.traceparent=r),n!==void 0&&Number.isFinite(n)&&(s[Za]=String(Math.trunc(n))),s},ti=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}}},ni=(e,t,n)=>e?.[n]??t?.[n],ri=(e,t,n,r)=>{const s=ni(e,t,n);if(!(typeof s!="object"||s===null))return r.every(a=>typeof s[a]=="function")?s:void 0},jr="v1",oi=6e4,si=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??oi),r=`${jr}.${String(n)}`,s=await pt(e,r);return{expiresAtMs:n,token:`${r}.${s}`}},ai=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const r=t.split(".");if(r.length!==3)return!1;const[s,a,d]=r;if(s!==jr||d.length===0)return!1;const u=Number(a);if(!Number.isFinite(u)||u<=n)return!1;let c;try{c=Kt(d)}catch{return!1}return Ur(e,`${s}.${a}`,c)},ii="https://admin-revocations.internal",ci=(e,t)=>{const n=async(r,s)=>{const a=t();if(a===void 0)throw new l("named admin tokens require a configured LUNORA_ADMIN_TOKEN, which signs them",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const d=await pe(e,ua).fetch(new Request(`${ii}${r}`,{...s,headers:{authorization:`Bearer ${a}`,"content-type":"application/json"}}));if(!d.ok)throw new l(`admin revocation store answered ${String(d.status)}`,{code:"SHARD_UNAVAILABLE",status:503});return d};return{revoke:async(r,s)=>{await n("/revoke",{body:JSON.stringify({createdAt:s,name:r}),method:"POST"})},isRevoked:async(r,s)=>{const u=(await(await n(`/revoked?name=${encodeURIComponent(r)}&createdAt=${String(s)}`,{method:"GET"})).json())?.revoked;if(typeof u!="boolean")throw new l("admin revocation store answered garbage",{code:"SHARD_UNAVAILABLE",status:503});return u},latestRevoked:async r=>{const d=(await(await n(`/latest?name=${encodeURIComponent(r)}`,{method:"GET"})).json())?.latest;if(d!==null){if(typeof d!="number")throw new l("admin revocation store answered garbage",{code:"SHARD_UNAVAILABLE",status:503});return d}}}},di="/_lunora/admin/tokens",ui="__lunora_admin__:createAdminToken",vn="__lunora_admin__:listAdminTokens",li="__lunora_admin__:revokeAdminToken",Tt={"cache-control":"no-store"},On=e=>{if(typeof e!="string"||!Lr(e))throw new l("admin token `name` must match /^[a-z0-9][a-z0-9_-]{0,63}$/",{code:"BAD_REQUEST",status:400});return e},hi=e=>{const t=e.now??Date.now,n=async a=>{const d=await e.readJsonBody(a),u=On(d.name),{expiresAt:c}=d;if(c!==void 0&&(typeof c!="number"||!Number.isFinite(c)||c<=t()))throw new l("admin token `expiresAt` must be a future epoch-ms number",{code:"BAD_REQUEST",status:400});if(e.revocations===void 0)throw new l('named admin tokens need the ADMIN_REVOCATIONS Durable Object binding; export AdminRevocationDO from the worker entry (`export { AdminRevocationDO } from "./lunora/_generated/adminRevocations.js"`) and bind it',{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const{secret:w,token:g}=ga(u),b=await e.revocations.latestRevoked(u),p=b===void 0?t():Math.max(t(),b+1),N=await e.callStore(ui,{createdAt:p,digest:await Br(w),expiresAt:c,name:u});return e.evict(u),Response.json({...N,token:g},{headers:Tt,status:201})},r=async()=>{const{revocations:a}=e;if(a===void 0)throw new l("no admin revocation store is bound, so named admin tokens are refused; export AdminRevocationDO and bind ADMIN_REVOCATIONS",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const{tokens:d}=await e.callStore(vn,{}),u=await Promise.all(d.map(async c=>await a.isRevoked(c.name,c.createdAt)?{...c,revoked:!0}:c));return Response.json({tokens:u},{headers:Tt})},s=async a=>{const d=On(new URL(a.url).searchParams.get("name")??void 0);if(e.revocations===void 0)throw new l("no admin revocation store is bound, so no named admin token can exist",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const{tokens:u}=await e.callStore(vn,{}),c=u.find(w=>w.name===d);if(c===void 0)throw new l(`no admin token named "${d}"`,{code:"NOT_FOUND",status:404});try{await e.revocations.revoke(d,c.createdAt),await e.callStore(li,{createdAt:c.createdAt,name:d})}finally{e.evict(d)}return Response.json({revoked:!0},{headers:Tt})};return{[di]:async a=>(e.assertRootAdmin(a),a.method==="GET"?r():a.method==="POST"?n(a):a.method==="DELETE"?s(a):new Response(void 0,{headers:{allow:"GET, POST, DELETE"},status:405}))}},fi=3e4,pi=5e3,mi=1024,Nn=20,In=1e3,wi=5e3,gi=1024,yi=({listNames:e,lookup:t,now:n=Date.now})=>{const r=new Map,s=new Map,a=new Map,d=new Map,u=new Map;let c=Nn,w=n();const g=()=>{const _=n()-w,P=Math.floor(_/In);return P>0&&(c=Math.min(Nn,c+P),w+=P*In),c<=0?!1:(c-=1,!0)},b=(_,P)=>{for(const[v,C]of _)C.name===P&&_.delete(v)},p=_=>{u.has(_)||(ot(u,gi),u.set(_,!0))};let N=Number.NEGATIVE_INFINITY,y;const E=()=>y!==void 0?y:e===void 0||n()-N<wi?Promise.resolve():(N=n(),y=(async()=>{try{for(const _ of await e())p(_)}catch{}finally{y=void 0}})(),y),A=async _=>(await E(),u.has(_)),S=(_,P,v)=>{const C=t(_,P);d.set(v,C);const M=()=>{d.get(v)===C&&d.delete(v)};return C.finally(M).catch(()=>{}),C},k=(_,P,v,C)=>{C?p(_):u.delete(_),ot(s,mi),s.set(C?P:v,{name:_,until:n()+pi})};return{evict:_=>{b(r,_),b(s,_),u.delete(_);for(const P of d.keys())P.startsWith(`${_}\0`)&&d.delete(P);a.set(_,(a.get(_)??0)+1)},verify:async _=>{const P=xr(_);if(P===void 0)return;const{name:v}=P,C=await Br(P.secret),M=`${v}\0${C}`,H=`${v}\0*`,G=r.get(M);if(G!==void 0&&G.until>n())return G;if((s.get(H)?.until??0)>n()||(s.get(M)?.until??0)>n())return;r.delete(M),s.delete(M),s.delete(H);const z=a.get(v);let Q=d.get(M);if(Q===void 0){if(!(u.has(v)||g())&&!await A(v))return;Q=S(v,C,M)}const Y=await Q;if(a.get(v)!==z)return;if(!Y.live){if(Y.transient===!0)return;k(v,M,H,Y.nameKnown);return}const X=Math.min(n()+fi,Y.expiresAt??Number.POSITIVE_INFINITY);if(X<=n())return;p(v);const ce={name:v,until:X,...Y.expiresAt===void 0?{}:{expiresAt:Y.expiresAt}};return r.set(M,ce),ce}}},_i="x",kn=" ",bi={'"':'"',"'":"'","[":"]","`":"`"},Fr=(e,t)=>{let n=t+2;for(;n<e.length&&e[n]!==`
2
2
  `;)n+=1;return n},Kr=(e,t)=>{const n=e.indexOf("*/",t+2);return n===-1?-1:n+2},Ei=e=>{const t=e.split("");let n=0;for(;n<e.length;){const r=e[n]??"",s=bi[r];if(r==="-"&&e[n+1]==="-"){const a=Fr(e,n);t.fill(kn,n,a),n=a}else if(r==="/"&&e[n+1]==="*"){const a=Kr(e,n);if(a===-1)return;t.fill(kn,n,a),n=a}else if(s!==void 0){let a=n+1;for(;a<e.length;)if(e[a]!==s)a+=1;else if(s!=="]"&&e[a+1]===s)a+=2;else break;if(a>=e.length)return;t.fill(_i,n,a+1),n=a+1}else n+=1}for(let r=0;r<e.length;r+=1)e[r]===`
3
3
  `&&(t[r]=`
4
4
  `);return t.join("")},Ai="__lunora_admin_tokens__",Qt=new Set([Ai,"dbstat","sqlite_dbpage"]),Gr="pragma_",Ti=e=>/[\p{L}_]/u.test(e)||(e.codePointAt(0)??0)>127,Si=e=>/[\p{L}\p{N}_$]/u.test(e)||(e.codePointAt(0)??0)>127,Ri=/^pragma_\w+$/u,vi=e=>Qt.has(e)||Ri.test(e)?e:void 0,Dn=e=>{if(Qt.has(e)||e.startsWith(Gr))return e},Pn=(e,t,n)=>{let r="",s=t+1;for(;s<e.length;){const a=e[s];if(a===n){if(n!=="]"&&e[s+1]===n){r+=n,s+=2;continue}return{end:s+1,text:r}}r+=a,s+=1}},Un={'"':'"',"`":"`","[":"]"},St=e=>{const t=e.toLowerCase().replaceAll(/["'`[\]]/gu,"");for(const n of Qt)if(t.includes(n))return n;return/\bpragma_/u.test(t)?Gr:void 0},Oi=e=>{let t=0;for(;t<e.length;){const n=e[t];if(/\s/u.test(n))t+=1;else if(n==="-"&&e[t+1]==="-"){const r=e.indexOf(`
@@ -1 +1 @@
1
- import{d as s,e as a,a as i,h as n,r as t}from"./security-headers-CZVK7xvl.mjs";import"./LunoraError-PkZWF-_g.mjs";export{s as decorateResponse,a as enforceOrigin,i as enforceWebSocketOrigin,n as handleCorsPreflight,t as resolveSecurity};
1
+ import{d as s,e as a,a as i,h as n,r as t}from"./security-headers-0DqdJ04h.mjs";import"./LunoraError-PkZWF-_g.mjs";export{s as decorateResponse,a as enforceOrigin,i as enforceWebSocketOrigin,n as handleCorsPreflight,t as resolveSecurity};
@@ -0,0 +1 @@
1
+ import{redactArgs as b,redactCredentials as y}from"@lunora/observability";import{S,n as O,t as x}from"./observability-sinks-CTGNb3dU.mjs";const d=t=>{try{t()}catch{}},m=(t,o)=>{const r={};for(const n of S)t[n]!==void 0&&(r[n]=t[n]);return t.flush&&(r.flush=n=>{d(()=>t.flush?.(n))}),t.onLog&&(r.onLog=(n,c)=>{const e=o.log===void 0?n:o.log(n);e!==void 0&&d(()=>t.onLog?.(e,c))}),t.onMetric&&(r.onMetric=(n,c)=>{const e=o.metric===void 0?n:o.metric(n);e!==void 0&&d(()=>t.onMetric?.(e,c))}),t.onRpc&&(r.onRpc=(n,c)=>{const e=o.rpc===void 0?n:o.rpc(n);e!==void 0&&d(()=>t.onRpc?.(e,c))}),t.onSpan&&(r.onSpan=(n,c)=>{const e=o.span===void 0?n:o.span(n);e!==void 0&&d(()=>t.onSpan?.(e,c))}),r},g=5;let l=0;const E=t=>{if(l>=g)return;l+=1;const o=l===g?" Further enricher failures are silenced until the isolate restarts.":"";try{console.error(`[lunora:observability] enrichSink's enricher threw; delivering the event without its extra attributes.${o}`,t instanceof Error?t.name:typeof t)}catch{}},j=(t,o,r)=>{if(t instanceof Error)return r==="full"?x(t,o):String(t);const n=Reflect.get(t,"toJSON");if(typeof n=="function"){const e=n.call(t);return e!==t?o(e):Object.fromEntries(Object.entries(t).map(([i,s])=>[i,o(s)]))}if(Array.isArray(t))return t.map(e=>o(e));const c=Object.getPrototypeOf(t);return c!==Object.prototype&&c!==null?t:Object.fromEntries(Object.entries(t).map(([e,i])=>[e,o(i)]))},u=t=>({ancestors:new WeakSet,copies:new WeakMap,errors:t}),a=(t,o)=>{if(typeof t=="symbol"||typeof t=="function"||typeof t=="bigint")return String(t);if(typeof t!="object"||t===null)return t;if(!o.ancestors.has(t)){if(o.copies.has(t))return o.copies.get(t);o.ancestors.add(t);try{const r=j(t,n=>a(n,o),o.errors);return o.copies.set(t,r),r}finally{o.ancestors.delete(t)}}},p=(t,o,r)=>{try{const n=t(a(o,u("full")),r),c=n===void 0?void 0:Object.fromEntries(Object.entries(n).filter(([,f])=>f!==void 0)),e=r==="log"?"full":"headline",i=c===void 0?void 0:a(c,u(e)),s=r==="log"?b(i):y(i);return O(s,void 0,e)}catch(n){E(n);return}},A=(t,o)=>m(t,{log:r=>{const n=p(o,r,"log");return n===void 0?r:{...r,fields:{...n,...r.fields}}},metric:r=>{const n=p(o,r,"metric");return n===void 0?r:{...r,attributes:{...n,...r.attributes}}},rpc:r=>{const n=p(o,r,"rpc");return n===void 0?r:{...r,attributes:{...n,...r.attributes}}},span:r=>{const n=p(o,r,"span");return n===void 0?r:{...r,attributes:{...n,...r.attributes}}}}),h=(t,o)=>{const r=t.split("*");if(r.length===1)return o===t;const n=r[0]??"",c=r.at(-1)??"";if(o.length<n.length+c.length||!o.startsWith(n)||!o.endsWith(c))return!1;const e=o.length-c.length;let i=n.length;for(const s of r.slice(1,-1)){const f=o.indexOf(s,i);if(f===-1||f+s.length>e)return!1;i=f+s.length}return i<=e},R=(t,o)=>o.exclude?.some(r=>h(r,t))?!1:o.include===void 0||o.include.length===0||o.include.some(r=>h(r,t)),M=(t,o)=>{const r=n=>R(n.functionPath,o)?n:void 0;return m(t,{log:r,metric:r,rpc:r,span:r})};export{A as enrichSink,M as filterSink,h as globMatch};
@@ -0,0 +1,6 @@
1
+ import{LunoraError as ut}from"@lunora/errors";import{redactCredentials as lt,redactArgs as M}from"@lunora/observability";import{stableStringify as ft}from"@lunora/wire";import{e as c,L as y,c as Y,o as G,f as S,O as q,g as pt,h as Z,w as mt,i as ht,j as yt,m as gt}from"./otlp-resource-BBR8xs6m.mjs";import{t as bt}from"./error-detail-C46mdOTW.mjs";const kt=t=>{if(typeof t=="string")return t;if(t instanceof Error)return String(t);try{return JSON.stringify(t)??String(t)}catch{return String(t)}},St=4,It=10,Q=3584,Et=4,V=512,v=["all","root","short","none","minimal"],tt=8,Tt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),rt=t=>{if(!Tt(t))return!1;const r=Object.getPrototypeOf(t);return r===Object.prototype||r===null},x=(t,r=0,o=new WeakSet)=>t instanceof Error?!0:typeof t!="object"||t===null||r>=tt||o.has(t)?!1:(o.add(t),Array.isArray(t)?t.some(s=>x(s,r+1,o)):rt(t)&&Object.values(t).some(s=>x(s,r+1,o))),ot=t=>{if(typeof t=="bigint")return String(t);if(typeof t!="object"||t===null)return t;try{return JSON.stringify(t),t}catch{return}},Ot=(t,r,o)=>{if(t!==void 0)return r==="none"||r==="minimal"||r==="root"&&o>0?"":r==="short"?t.split(`
2
+ `).slice(0,Et+1).join(`
3
+ `):t},j=(t,r,o,s)=>({...s===void 0?{}:{child:s},errors:t,mask:o,memo:new WeakMap,mode:r,path:new Set}),st=(t,r,o)=>{if(!r.path.has(t)){if(r.memo.has(t))return r.memo.get(t);r.path.add(t);try{const s=o();return r.memo.set(t,s),s}finally{r.path.delete(t)}}},et=(t,r,o)=>{Object.defineProperty(t,r,{configurable:!0,enumerable:!0,value:o,writable:!0})},U=(t,r,o)=>r.path.has(t)||o>St?{message:t.message,name:t.name}:st(t,r,()=>{const s=u=>u instanceof Error?U(u,r,o+1):(r.child??(h=>P(h,r,0,o+1)))(u),e=r.mode==="minimal",n={message:e&&t.message.length>V?`${t.message.slice(0,V)}…`:t.message,name:t.name};if(!e)for(const[u,h]of Object.entries(t))u!=="message"&&u!=="name"&&et(n,u,s(h));const d=Ot(t.stack,r.mode,o);return d!==void 0&&(n.stack=d),t.cause!==void 0&&(n.cause=s(t.cause)),t instanceof AggregateError&&Array.isArray(t.errors)&&(n.errors=t.errors.slice(0,It).map(u=>s(u))),r.mask(n)}),P=(t,r,o,s)=>t instanceof Error?r.errors==="full"?U(t,r,s):String(t):typeof t!="object"||t===null||o>=tt||!(Array.isArray(t)||rt(t))?ot(t):st(t,r,()=>Array.isArray(t)?t.map(e=>P(e,r,o+1,s)):Object.fromEntries(Object.entries(t).map(([e,a])=>[e,P(a,r,o+1,s)]))),At=t=>{try{return JSON.stringify(t).length}catch{return Number.POSITIVE_INFINITY}},D=t=>t,tr=(t,r=ot)=>{let o;for(const s of v)if(o=U(t,j("full",s,D,r),0),At(o)<=Q)break;return o},Pt=(t,r,o)=>{if(r==="headline")return JSON.stringify(P(t,j("headline","none",o),0,0));let s;for(const e of v)if(s=JSON.stringify(P(t,j("full",e,o),0,0)),s===void 0||s.length<=Q)break;return s},_=(t,r="headline",o=D)=>{if(typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;try{return!x(t)||r==="headline"&&t instanceof Error?kt(t):Pt(t,r,o)??String(t)}catch{return String(t)}},rr=(t,r,o="headline",s=D)=>{if(t===void 0&&r===void 0)return;const e={};if(t!==void 0)for(const[a,n]of Object.entries(t))et(e,a,_(n,o,s));return Object.keys(e).length===0?void 0:e},Rt=512,wt=200,_t=t=>{const r=t.maxItems??Rt,o=t.maxDelayMs??wt;let s=[],e,a,n;const d=()=>{e!==void 0&&(clearTimeout(e),e=void 0)},u=async()=>{d();const p=s;s=[];const l=n;a=void 0,n=void 0;try{p.length>0&&await t.export(p)}catch{}finally{l?.()}},h=p=>{a===void 0&&(a=new Promise(l=>{n=l}),e=setTimeout(()=>{u()},o)),p?.(a)};return{add:(p,l)=>{for(s.push(p);s.length>r;)s.shift();h(l),s.length>=r&&u()},flush:async p=>{if(s.length===0){d();return}const l=u();return p?.(l),l},get size(){return s.length}}},Nt=1,Lt=0,Mt=new Set(["cloudflare.ray_id","error.type","http.request.method","http.response.status_code","http.route","lunora.error_status","lunora.fanout.failed","lunora.fanout.shards","lunora.fanout.table","lunora.function_path","lunora.ok","lunora.shard_key","server.address","server.port","url.path","url.scheme","user_agent.original"]),xt={errorType:y.errorType,functionPath:y.functionPath,rayId:y.rayId,shardKey:y.shardKey,userId:y.userId},jt=t=>{const r=bt(t);return r===void 0?[]:[c("lunora.error.internal",JSON.stringify(lt(r)))]},nt=(t,r,o,s)=>[c("exception.type",t),c("exception.message",r),...o===void 0?[]:[c("exception.stacktrace",o)],...s===void 0?[]:jt(s)],Ut=(t,r)=>{const o=[c(y.functionPath,t.functionPath),c(y.ok,t.ok)];if(t.method!==void 0&&o.push(c("http.request.method",t.method)),t.path!==void 0&&o.push(c("url.path",t.path)),o.push(c("http.route",t.functionPath)),t.scheme!==void 0&&o.push(c("url.scheme",t.scheme)),t.host!==void 0&&o.push(c("server.address",t.host)),t.port!==void 0&&o.push(c("server.port",t.port)),t.userAgent!==void 0&&o.push(c("user_agent.original",t.userAgent)),t.shardKey!==void 0&&o.push(c(y.shardKey,t.shardKey)),t.rayId!==void 0&&o.push(c(y.rayId,t.rayId)),o.push(c("http.response.status_code",t.error?.status??200)),t.error&&o.push(c(y.errorType,t.error.code),c("lunora.error_status",t.error.status)),t.fanOut&&o.push(c("lunora.fanout.table",t.fanOut.table),c("lunora.fanout.shards",t.fanOut.shards),c("lunora.fanout.failed",t.fanOut.failed)),t.attributes!==void 0){const e=new Set([...Mt,...o.map(n=>n.key)]),a=Y(Object.fromEntries(Object.entries(t.attributes).map(([n,d])=>[n,_(d)])));o.push(...a.filter(n=>!e.has(n.key)))}const s={attributes:o,endTimeUnixNano:S(r),kind:q.server,name:t.functionPath,...t.parentSpanId===void 0?{}:{parentSpanId:t.parentSpanId},spanId:t.spanId??G(8),startTimeUnixNano:S(r-t.durationMs),status:t.ok?{code:1}:{code:2,message:t.error?.message??""},traceId:t.traceId??G(16)};return t.traceFlags!==void 0&&(s.flags=t.traceFlags),t.error&&(s.events=[{attributes:nt(t.error.code,t.error.message,t.error.stack,t.error.internal),name:"exception",timeUnixNano:S(r)}]),s},F=(t,r)=>{const o=new Map,s=new Set(Object.keys(t).map(e=>xt[e]));for(const[e,a]of Object.entries(r??{}))s.has(e)||o.set(e,c(e,_(a)));return o.set(y.functionPath,c(y.functionPath,t.functionPath)),t.shardKey!==void 0&&o.set(y.shardKey,c(y.shardKey,t.shardKey)),t.userId!==void 0&&o.set(y.userId,c(y.userId,t.userId)),t.rayId!==void 0&&o.set(y.rayId,c(y.rayId,t.rayId)),t.errorType!==void 0&&o.set(y.errorType,c(y.errorType,t.errorType)),[...o.values()]},Dt=t=>{const r={attributes:F({errorType:t.error?.type,functionPath:t.functionPath,rayId:t.rayId,shardKey:t.shardKey,userId:t.userId},t.attributes),endTimeUnixNano:S(t.startTs+t.durationMs),flags:t.sampled===!1?Lt:Nt,kind:q[t.kind??"internal"],name:t.name,parentSpanId:t.parentSpanId,spanId:t.spanId,startTimeUnixNano:S(t.startTs),status:t.ok?{code:1}:{code:2,message:t.error?.message??""},traceId:t.traceId},o=s=>Y(Object.fromEntries(Object.entries(s??{}).map(([e,a])=>[e,_(a)])));return t.events!==void 0&&t.events.length>0&&(r.events=t.events.map(s=>({attributes:o(s.attributes),name:s.name,timeUnixNano:S(s.ts)}))),t.links!==void 0&&t.links.length>0&&(r.links=t.links.map(s=>({attributes:o(s.attributes),spanId:s.spanId,traceId:s.traceId}))),r},Ft=t=>{const r=S(t.ts),o=F({functionPath:t.functionPath,shardKey:t.shardKey},t.attributes),s=t.traceId===void 0?void 0:[{asDouble:t.value,timeUnixNano:r,traceId:t.traceId}],e={asDouble:t.value,attributes:o,...s===void 0?{}:{exemplars:s},timeUnixNano:r};return t.kind==="gauge"?{gauge:{dataPoints:[e]},name:t.name}:t.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:o,bucketCounts:["1"],count:"1",...s===void 0?{}:{exemplars:s},explicitBounds:[],max:t.value,min:t.value,sum:t.value,timeUnixNano:r}]},name:t.name}:{name:t.name,sum:{aggregationTemporality:1,dataPoints:[e],isMonotonic:!0}}},Kt=t=>{const r={attributes:F({functionPath:t.functionPath,rayId:t.rayId,shardKey:t.shardKey,userId:t.userId},t.fields),body:{stringValue:t.message},severityNumber:pt[t.level],severityText:t.level.toUpperCase(),timeUnixNano:S(t.ts)};if(t.traceId!==void 0&&(r.traceId=t.traceId),t.spanId!==void 0&&(r.spanId=t.spanId),t.error!==void 0){const o=nt(t.error.name,t.error.message,t.error.stack,t.error.internal),s=new Set(o.map(e=>e.key));r.attributes=[...r.attributes.filter(e=>!s.has(e.key)),...o]}return t.eventName!==void 0&&(r.eventName=t.eventName,r.attributes=[...r.attributes.filter(o=>o.key!=="event.name"),c("event.name",t.eventName)]),r},$t=1024,X=5;let L=0;const Ct=(t,r)=>{if(L>=X)return;L+=1;let o;try{o=new URL(t).host}catch{o="<unparseable endpoint>"}const s=L===X?" Further OTLP rejections are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] collector ${o} rejected the export with HTTP ${String(r)}; the batch is DROPPED (there is no retry).${s}`)},Ht=async t=>{const r=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(r).arrayBuffer()},at=async(t,r,o,s)=>{try{const e=JSON.stringify(r),{byteLength:a}=new TextEncoder().encode(e),n=(a<$t?fetch(t,{body:e,headers:o,method:"POST"}):Ht(e).then(d=>fetch(t,{body:d,headers:{...o,"content-encoding":"gzip"},method:"POST"}))).then(d=>{d.ok||Ct(t,d.status)},()=>{});s?.(n),await n}catch{}},Bt=(t,r,o,s)=>{at(t,r,o,s?.waitUntil).catch(()=>{})},R=(t,r)=>r===!0&&t.ok,Jt=t=>t.kind==="metric"?void 0:t.event.traceId,Gt=t=>{const r=Map.groupBy(t,s=>Jt(s)),o=r.get(void 0)??[];return r.delete(void 0),{byTrace:r,untraced:o}},z=5,Vt=(t,r,o)=>{if(r===void 0)return t;const{byTrace:s,untraced:e}=Gt(t),a=[...e];let n=0,d;for(const[u,h]of s){let p;try{p=r({logs:h.filter(l=>l.kind==="log").map(l=>l.event),rpc:h.filter(l=>l.kind==="rpc").map(l=>l.event),spans:h.filter(l=>l.kind==="span").map(l=>l.event),traceId:u})}catch(l){n+=1,n===1&&(d=l),p=!0}p&&a.push(...h)}return n>0&&o(d,n),a},O=(t,r)=>{let o;try{o=r===void 0?t:r(t)}catch{o=void 0}return o??void 0},Xt=t=>{const r=M(t.message);if(t.stack===void 0)return{...t,message:r};const o=`: ${t.message}`,s=t.stack.indexOf(o),a=t.message!==""&&s!==-1&&!t.stack.slice(0,s).includes(`
4
+ `)?t.stack.slice(s+o.length):t.stack.split(`
5
+ `).filter(n=>n.trimStart().startsWith("at ")).map(n=>`
6
+ ${n}`).join("");return{...t,message:r,stack:`${t.name}: ${r}${a}`}},zt=t=>({...t,...t.error===void 0?{}:{error:Xt(t.error)},...t.fields===void 0?{}:{fields:M(t.fields)},message:M(t.message)}),W=(t,r,o)=>{if(t.kind==="rpc"){const e=O(t.event,r?.rpc);return e===void 0?void 0:{bucket:"spans",encoded:Ut(e,t.endMs)}}if(t.kind==="span"){const e=O(t.event,r?.span);return e===void 0?void 0:{bucket:"spans",encoded:Dt(e)}}if(t.kind==="log"){const e=O(o?zt(t.event):t.event,r?.log);return e===void 0?void 0:{bucket:"logs",encoded:Kt(e)}}const s=O(t.event,r?.metric);return s===void 0?void 0:{bucket:"metrics",encoded:Ft(s)}},Wt=["fuseCloudflareTraces","instrumentDatabase","metricHistory","traceFetch"],or=(t={})=>{const{onlyErrors:r}=t;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=>{R(o,r)||(o.ok?console.log("[lunora:rpc]",o):console.error("[lunora:rpc]",o))},onSpan:o=>{const s=o.ok?"ok":`error ${o.error?.type??""}`.trim();console.log("[lunora:span]",o.name,`${String(o.durationMs)}ms`,s,o.functionPath)}}},sr=t=>{const{headers:r,onlyErrors:o,transform:s,transformLog:e,url:a}=t,n=Z({"content-type":"application/json"},r),d=(u,h)=>{try{const p=fetch(a,{body:JSON.stringify(u),headers:n,method:"POST"}).catch(()=>{});h?.waitUntil&&h.waitUntil(p)}catch{}};return{onLog:(u,h)=>{const p=O(u,e);p!==void 0&&d(p,h)},onRpc:(u,h)=>{if(R(u,o))return;const p=O(u,s);p!==void 0&&d(p,h)}}},er=t=>{const{dataset:r,onlyErrors:o}=t;return{onRpc:s=>{if(!R(s,o))try{r.writeDataPoint({blobs:[s.functionPath,s.ok?"ok":"error",s.shardKey??"",s.error?.code??"",s.fanOut?.table??""],doubles:[s.durationMs,s.ok?0:1,s.fanOut?.shards??0,s.fanOut?.failed??0],indexes:[s.functionPath]})}catch{}}}},nr=t=>{const{pipeline:r,serializeFields:o}=t;return{onLog:(s,e)=>{try{const a={functionPath:s.functionPath,level:s.level,message:s.message,ts:s.ts};s.fields&&(a.fields=o===!0?JSON.stringify(s.fields):s.fields);for(const d of["shardKey","userId","traceId","spanId"])s[d]!==void 0&&(a[d]=s[d]);const n=r.send([a]).catch(()=>{});e?.waitUntil&&e.waitUntil(n)}catch{}}}},ar=t=>{const{batch:r,deploymentEnvironment:o,detectResources:s,endpoint:e,headers:a,onlyErrors:n,postProcessor:d,resourceAttributes:u,serviceNamespace:h,serviceVersion:p,tailSampler:l,token:it}=t,K=t.serviceName??"lunora",$=t.redactLogs??!0;if(r!==!1&&r?.maxItems!==void 0&&(!Number.isInteger(r.maxItems)||r.maxItems<1))throw new ut("ENV_INVALID",`otlpSink: \`batch.maxItems\` must be a positive integer, received ${String(r.maxItems)}.`);const C={...p===void 0?{}:{"service.version":p},...h===void 0?{}:{"service.namespace":h},...o===void 0?{}:{"deployment.environment":o},...u},H=new WeakMap,k=f=>{if(s!==!0||f?.resourceAttributes===void 0)return C;const i=H.get(f);if(i!==void 0)return i;const m=gt(f.resourceAttributes(),C);return H.set(f,m),m};let I=e;for(;I.endsWith("/");)I=I.slice(0,-1);const B={logs:{url:`${I}/v1/logs`,wrap:yt},metrics:{url:`${I}/v1/metrics`,wrap:ht},spans:{url:`${I}/v1/traces`,wrap:mt}},J=Z({"content-type":"application/json"},a,it);let N=0;const ct=(f,i)=>{if(N>=z)return;N+=1;const m=N===z?" 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.${m}`,f)},dt=async f=>{const i=Vt(f,l,ct),m=new Map;for(const g of i){const b=W(g,d,$);if(b===void 0)continue;const w=ft(g.resource);let T=m.get(w);T===void 0&&(T={logs:[],metrics:[],resource:g.resource,spans:[]},m.set(w,T)),T[b.bucket].push(b.encoded)}const E=[];for(const[,g]of m)for(const b of["spans","logs","metrics"])if(g[b].length>0){const{url:w,wrap:T}=B[b];E.push(at(w,T(g[b],"@lunora/runtime",K,g.resource),J))}await Promise.all(E)};if(r===!1){const f=(i,m)=>{const E=W(i,d,$);if(E!==void 0){const{url:g,wrap:b}=B[E.bucket];Bt(g,b(E.encoded,"@lunora/runtime",K,i.resource),J,m)}};return{onLog:(i,m)=>{f({event:i,kind:"log",resource:k(m)},m)},onMetric:(i,m)=>{f({event:i,kind:"metric",resource:k(m)},m)},onRpc:(i,m)=>{R(i,n)||f({endMs:Date.now(),event:i,kind:"rpc",resource:k(m)},m)},onSpan:(i,m)=>{f({event:i,kind:"span",resource:k(m)},m)}}}const A=_t({export:dt,...r?.maxDelayMs===void 0?{}:{maxDelayMs:r.maxDelayMs},...r?.maxItems===void 0?{}:{maxItems:r.maxItems}});return{flush:f=>{A.flush(f?.waitUntil).catch(()=>{})},onLog:(f,i)=>{A.add({event:f,kind:"log",resource:k(i)},i?.waitUntil)},onMetric:(f,i)=>{A.add({event:f,kind:"metric",resource:k(i)},i?.waitUntil)},onRpc:(f,i)=>{R(f,n)||A.add({endMs:Date.now(),event:f,kind:"rpc",resource:k(i)},i?.waitUntil)},onSpan:(f,i)=>{A.add({event:f,kind:"span",resource:k(i)},i?.waitUntil)}}},ir=(...t)=>{const r=(s,e)=>{for(const a of t){const n=a[s];if(n)try{n.apply(a,e)}catch{}}},o={};for(const s of t)for(const e of Wt)o[e]===void 0&&s[e]!==void 0&&(o[e]=s[e]);return{...o,flush:s=>{r("flush",[s])},onLog:(s,e)=>{r("onLog",[s,e])},onMetric:(s,e)=>{r("onMetric",[s,e])},onRpc:(s,e)=>{r("onRpc",[s,e])},onSpan:(s,e)=>{r("onSpan",[s,e])}}};export{Wt as S,er as a,or as b,ir as c,rr as n,ar as o,nr as p,tr as t,sr as w};
@@ -0,0 +1 @@
1
+ const m="/_lunora/rest",h=["authorization","cf-access-jwt-assertion","cookie","payment-signature","x-payment"],d=["x-d1-bookmark","x-lunora-shard-key"],v=e=>[...h,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],l=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u,p=e=>l.test(e),E=(e,t,a=[])=>t?.access!==void 0||h.some(s=>e.has(s))||a.some(s=>!p(s)||e.has(s)),u=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,c=(...e)=>{const t=[];for(const a of e)for(const s of a?.split(",")??[]){const n=s.trim().toLowerCase();n!==""&&!t.includes(n)&&t.push(n)}return t.length===0?void 0:t.join(", ")},g=(e,t)=>{const a=[t,`max-age=${String(u(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&a.push(`stale-while-revalidate=${String(u(e.staleWhileRevalidate))}`),a.join(", ")},R=e=>e.scope==="public"?c(e.vary,...v(e),...d):c(e.vary,...d),f=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},x=e=>{const t=f(e);if(t!==void 0)return`${m}/${t.namespace}/${t.name}`},A=e=>e==="query"?"GET":"POST",H=e=>{const t=[];for(const a of e){if(a.exposure?.rest!==!0||a.kind==="stream")continue;const s=f(a.functionPath),n=x(a.functionPath);s===void 0||n===void 0||t.push({functionPath:a.functionPath,kind:a.kind,method:A(a.kind),name:s.name,namespace:s.namespace,path:n})}return t.sort((a,s)=>a.path<s.path?-1:+(a.path>s.path)),t},C=(e,t,a)=>E(e.headers,a,t.credentialHeaders),S=(e,t,a)=>e.scope==="public"&&!C(t,e,a)?"public":"private",b=(e,t,a,s)=>{if(t.method!=="GET"||a<200||a>299)return;const n={"cache-control":g(e,S(e,t,s))};e.tag!==void 0&&e.tag!==""&&(n["cache-tag"]=e.tag);const r=R(e);return r!==void 0&&(n.vary=r),n},k=(e,t,a,s)=>{if(t===void 0)return e;const n=b(t,a,e.status,s);if(n===void 0)return e;const r=new Response(e.body,e);for(const[i,o]of Object.entries(n))r.headers.set(i,i==="vary"?c(r.headers.get("vary")??void 0,o)??o:o);return r};export{k as a,b,u as c,R as d,S as e,H as f,C as r};
@@ -1 +1 @@
1
- import{c as O,d as P,e as B,a as x,f as D}from"./rest-cache-CmHN871W.mjs";import{LunoraError as h}from"./LunoraError-PkZWF-_g.mjs";import{m as j}from"./method-guard-8Jo4Q8uS.mjs";import{w as C}from"./worker-version-B-qCFtEJ.mjs";const U=async(e,r)=>{if(!e.body)return"";const t=e.body.getReader(),o=new TextDecoder;let n=0,c="";for(;;){const{done:i,value:a}=await t.read();if(i)break;if(a){if(n+=a.byteLength,n>r)return await t.cancel().catch(()=>{}),null;c+=o.decode(a,{stream:!0})}}return c+=o.decode(),c},f=1048576,T=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),I=async(e,r=f)=>{const t=await U(e,r);if(t===null)throw new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});return t},ne=async(e,r=f)=>{if(!e.body)return new ArrayBuffer(0);const t=e.body.getReader(),o=[];let n=0;for(;;){const{done:a,value:d}=await t.read();if(a)break;if(d){if(n+=d.byteLength,n>r)throw await t.cancel().catch(()=>{}),new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});o.push(d)}}const c=new Uint8Array(n);let i=0;for(const a of o)c.set(a,i),i+=a.byteLength;return c.buffer},ce=(e,r=f)=>{const t=e.body;let o=!1;if(t===null)return{overflowed:()=>o,request:e};let n,c=0;const i=new ReadableStream({cancel:async a=>{await(n??t).cancel(a)},pull:async a=>{n??=t.getReader();const{done:d,value:s}=await n.read();if(d){a.close();return}if(c+=s.byteLength,c>r){o=!0,a.error(new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})),n.cancel().catch(()=>{});return}a.enqueue(s)}},{highWaterMark:0});return{overflowed:()=>o,request:new Request(e,{body:i,duplex:"half"})}},G=async(e,r,t=f)=>{try{const o=await I(e,t);return o===""?{}:JSON.parse(o)}catch(o){throw o instanceof h?o:new h(`${r} body must be valid JSON`,{code:"BAD_REQUEST",status:400})}},ie=async(e,r=f)=>{const t=await G(e,"Request",r);if(!T(t))throw new h("Request body must be an object",{code:"BAD_REQUEST",status:400});return t},N=(e,r)=>{if(!T(e))throw new h(`${r} \`args\` must be an object`,{code:"BAD_REQUEST",status:400})},M=/^[\d.:a-f]+$/iu,$=e=>{const r=e.indexOf("%"),t=r===-1?e:e.slice(0,r);if(!t.includes(":")||!M.test(t))return e;let o;try{o=new URL(`http://[${t}]/`).hostname.slice(1,-1)}catch{return e}const[n="",c]=o.split("::"),i=n===""?[]:n.split(":"),a=c===void 0||c===""?[]:c.split(":"),d=[...i,...Array.from({length:8-i.length-a.length},()=>"0"),...a].map(s=>Number.parseInt(s,16));if(d.slice(0,5).every(s=>s===0)&&d[5]===65535){const[s=0,u=0]=d.slice(6);return[s>>8,s&255,u>>8,u&255].join(".")}return`${d.slice(0,4).map(s=>s.toString(16)).join(":")}::/64`},R="__lunora_key",K="x-lunora-edge-cache",Y=["x-d1-bookmark","x-lunora-shard-key"],H=()=>{try{return globalThis.caches?.default}catch{return}},F=":deploy",_=e=>e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r!==""),J=(e,r)=>{const t=e.headers.get("vary");return t===null?!0:_(t).every(o=>o!=="*"&&r.includes(o))},Q=(e,r)=>{if(e===void 0||r===null||e.scope!=="public"||O(e.maxAge)<=0)return;const t=_(P(e)??""),o=(n,c)=>{const i=new URL(n.url);i.searchParams.delete(R),i.searchParams.sort();const a=C(c),d=[...a===void 0?[]:[`${F}=${a}`],...t.map(s=>`${s}=${n.headers.get(s)??""}`)];return d.length>0&&i.searchParams.set(R,d.join("\0")),new Request(i.toString(),{method:"GET"})};return{forRequest:(n,c,i)=>{const a=r??H();if(a===void 0||n.method!=="GET"||B(e,n,i)!=="public")return;let d;try{d=o(n,c)}catch{return}return{lookup:async()=>{let s;try{s=await a.match(d)}catch{return}if(s===void 0)return;const u=new Response(s.body,s);return u.headers.set(K,"hit"),u},store:s=>{if(s.status!==200||s.headers.has("set-cookie")||s.headers.has("payment-response")||s.headers.has("x-payment-response")||!J(s,t))return s;try{const u=new Response(s.clone().body,s);for(const l of Y)u.headers.delete(l);const w=Promise.resolve(a.put(d,u)).catch(()=>{});i?.waitUntil&&i.waitUntil(w)}catch{}return s}}}}},W=()=>globalThis.navigator?.userAgent==="Cloudflare-Workers",V=(e,r)=>{if(W())return e.get("cf-connecting-ip")??void 0;if(r===void 0)return;const t=e.get(r)?.trim();return t===void 0||t===""||t.includes(",")?void 0:t},X=(e,r)=>{if(r.x402!==void 0&&r.expose?.cache?.scope==="public")throw new h(`REST route "${e}" is paid (.x402) but declares \`cache: { scope: "public" }\`: a shared cache would replay the paid response to callers who never paid. Use \`scope: "private"\` or drop the cache policy.`,{code:"MISCONFIGURED",status:500})},z=e=>D(Object.entries(e).map(([r,t])=>({exposure:t.expose,functionPath:r,kind:t.kind}))),Z=(e,r)=>{const t=e.searchParams.get("shardKey");if(t!==null&&t!=="")return t;const o=r.headers.get("x-lunora-shard-key");return o===null||o===""?void 0:o},q=e=>{const r=Object.create(null);for(const[t,o]of e.searchParams.entries())if(!(t==="shardKey"||t===R))try{r[t]=JSON.parse(o)}catch{r[t]=o}return r},de=e=>{const{edgeCache:r,functions:t,invoke:o,rateLimit:n,readJsonBody:c}=e,i={};for(const a of z(t)){const d=a.kind==="query"?["GET","POST"]:["POST"],s=t[a.functionPath];X(a.functionPath,s);const u=s.expose?.cache,w=Q(u,r);i[a.path]=async(l,v,te,y)=>{const b=j(l,d);if(b)return b;const E=new URL(l.url);if(n){const m=await n(l,a.functionPath);if(m)return m}const g=w?.forRequest(l,v,y),A=await g?.lookup();if(A)return A;let p;l.method==="GET"?p=q(E):p=l.body===null?{}:await c(l),N(p,"REST");const L=Z(E,l),k=await o({args:p,env:v,functionPath:a.functionPath,request:l,...L===void 0?{}:{shardKey:L},...y?.waitUntil===void 0?{}:{waitUntil:m=>y.waitUntil?.(m)}}),S=x(k,u,l,y);return g?g.store(S):S}}return i},ee=()=>Response.json({error:{code:"INTERNAL",message:"REST rate limit: no caller key could be resolved. Declare `trustedClientIpHeader` (a header your proxy stamps and callers cannot write), or pass `key` to identify callers by something unforgeable."}},{headers:{"content-type":"application/json"},status:500}),le=(e,r)=>async(t,o)=>{let n;if(r.key)n=r.key(t,o);else{const a=V(t.headers,r.trustedClientIpHeader);n=a===void 0?void 0:$(a)}if(n===void 0||n==="")return ee();const c=await e.limit(r.name,{key:n});if(c.ok)return;if(c.reason==="deny")return Response.json({error:{code:"FORBIDDEN",message:"Request denied"}},{headers:{"content-type":"application/json"},status:403});const i=Math.max(1,Math.ceil(c.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(i)},status:429})};export{f as M,q as a,de as b,le as c,ie as d,G as e,ne as f,N as g,I as h,z as r,V as t,ce as w};
1
+ import{c as O,d as P,e as B,a as x,f as D}from"./rest-cache-q5V06Etw.mjs";import{LunoraError as h}from"./LunoraError-PkZWF-_g.mjs";import{m as j}from"./method-guard-8Jo4Q8uS.mjs";import{w as C}from"./worker-version-B-qCFtEJ.mjs";const U=async(e,r)=>{if(!e.body)return"";const t=e.body.getReader(),o=new TextDecoder;let n=0,c="";for(;;){const{done:i,value:a}=await t.read();if(i)break;if(a){if(n+=a.byteLength,n>r)return await t.cancel().catch(()=>{}),null;c+=o.decode(a,{stream:!0})}}return c+=o.decode(),c},f=1048576,T=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),I=async(e,r=f)=>{const t=await U(e,r);if(t===null)throw new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});return t},ne=async(e,r=f)=>{if(!e.body)return new ArrayBuffer(0);const t=e.body.getReader(),o=[];let n=0;for(;;){const{done:a,value:d}=await t.read();if(a)break;if(d){if(n+=d.byteLength,n>r)throw await t.cancel().catch(()=>{}),new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});o.push(d)}}const c=new Uint8Array(n);let i=0;for(const a of o)c.set(a,i),i+=a.byteLength;return c.buffer},ce=(e,r=f)=>{const t=e.body;let o=!1;if(t===null)return{overflowed:()=>o,request:e};let n,c=0;const i=new ReadableStream({cancel:async a=>{await(n??t).cancel(a)},pull:async a=>{n??=t.getReader();const{done:d,value:s}=await n.read();if(d){a.close();return}if(c+=s.byteLength,c>r){o=!0,a.error(new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})),n.cancel().catch(()=>{});return}a.enqueue(s)}},{highWaterMark:0});return{overflowed:()=>o,request:new Request(e,{body:i,duplex:"half"})}},G=async(e,r,t=f)=>{try{const o=await I(e,t);return o===""?{}:JSON.parse(o)}catch(o){throw o instanceof h?o:new h(`${r} body must be valid JSON`,{code:"BAD_REQUEST",status:400})}},ie=async(e,r=f)=>{const t=await G(e,"Request",r);if(!T(t))throw new h("Request body must be an object",{code:"BAD_REQUEST",status:400});return t},N=(e,r)=>{if(!T(e))throw new h(`${r} \`args\` must be an object`,{code:"BAD_REQUEST",status:400})},M=/^[\d.:a-f]+$/iu,$=e=>{const r=e.indexOf("%"),t=r===-1?e:e.slice(0,r);if(!t.includes(":")||!M.test(t))return e;let o;try{o=new URL(`http://[${t}]/`).hostname.slice(1,-1)}catch{return e}const[n="",c]=o.split("::"),i=n===""?[]:n.split(":"),a=c===void 0||c===""?[]:c.split(":"),d=[...i,...Array.from({length:8-i.length-a.length},()=>"0"),...a].map(s=>Number.parseInt(s,16));if(d.slice(0,5).every(s=>s===0)&&d[5]===65535){const[s=0,u=0]=d.slice(6);return[s>>8,s&255,u>>8,u&255].join(".")}return`${d.slice(0,4).map(s=>s.toString(16)).join(":")}::/64`},R="__lunora_key",K="x-lunora-edge-cache",Y=["x-d1-bookmark","x-lunora-shard-key"],H=()=>{try{return globalThis.caches?.default}catch{return}},F=":deploy",_=e=>e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r!==""),J=(e,r)=>{const t=e.headers.get("vary");return t===null?!0:_(t).every(o=>o!=="*"&&r.includes(o))},Q=(e,r)=>{if(e===void 0||r===null||e.scope!=="public"||O(e.maxAge)<=0)return;const t=_(P(e)??""),o=(n,c)=>{const i=new URL(n.url);i.searchParams.delete(R),i.searchParams.sort();const a=C(c),d=[...a===void 0?[]:[`${F}=${a}`],...t.map(s=>`${s}=${n.headers.get(s)??""}`)];return d.length>0&&i.searchParams.set(R,d.join("\0")),new Request(i.toString(),{method:"GET"})};return{forRequest:(n,c,i)=>{const a=r??H();if(a===void 0||n.method!=="GET"||B(e,n,i)!=="public")return;let d;try{d=o(n,c)}catch{return}return{lookup:async()=>{let s;try{s=await a.match(d)}catch{return}if(s===void 0)return;const u=new Response(s.body,s);return u.headers.set(K,"hit"),u},store:s=>{if(s.status!==200||s.headers.has("set-cookie")||s.headers.has("payment-response")||s.headers.has("x-payment-response")||!J(s,t))return s;try{const u=new Response(s.clone().body,s);for(const l of Y)u.headers.delete(l);const w=Promise.resolve(a.put(d,u)).catch(()=>{});i?.waitUntil&&i.waitUntil(w)}catch{}return s}}}}},W=()=>globalThis.navigator?.userAgent==="Cloudflare-Workers",V=(e,r)=>{if(W())return e.get("cf-connecting-ip")??void 0;if(r===void 0)return;const t=e.get(r)?.trim();return t===void 0||t===""||t.includes(",")?void 0:t},X=(e,r)=>{if(r.x402!==void 0&&r.expose?.cache?.scope==="public")throw new h(`REST route "${e}" is paid (.x402) but declares \`cache: { scope: "public" }\`: a shared cache would replay the paid response to callers who never paid. Use \`scope: "private"\` or drop the cache policy.`,{code:"MISCONFIGURED",status:500})},z=e=>D(Object.entries(e).map(([r,t])=>({exposure:t.expose,functionPath:r,kind:t.kind}))),Z=(e,r)=>{const t=e.searchParams.get("shardKey");if(t!==null&&t!=="")return t;const o=r.headers.get("x-lunora-shard-key");return o===null||o===""?void 0:o},q=e=>{const r=Object.create(null);for(const[t,o]of e.searchParams.entries())if(!(t==="shardKey"||t===R))try{r[t]=JSON.parse(o)}catch{r[t]=o}return r},de=e=>{const{edgeCache:r,functions:t,invoke:o,rateLimit:n,readJsonBody:c}=e,i={};for(const a of z(t)){const d=a.kind==="query"?["GET","POST"]:["POST"],s=t[a.functionPath];X(a.functionPath,s);const u=s.expose?.cache,w=Q(u,r);i[a.path]=async(l,v,te,y)=>{const b=j(l,d);if(b)return b;const E=new URL(l.url);if(n){const m=await n(l,a.functionPath);if(m)return m}const g=w?.forRequest(l,v,y),A=await g?.lookup();if(A)return A;let p;l.method==="GET"?p=q(E):p=l.body===null?{}:await c(l),N(p,"REST");const L=Z(E,l),k=await o({args:p,env:v,functionPath:a.functionPath,request:l,...L===void 0?{}:{shardKey:L},...y?.waitUntil===void 0?{}:{waitUntil:m=>y.waitUntil?.(m)}}),S=x(k,u,l,y);return g?g.store(S):S}}return i},ee=()=>Response.json({error:{code:"INTERNAL",message:"REST rate limit: no caller key could be resolved. Declare `trustedClientIpHeader` (a header your proxy stamps and callers cannot write), or pass `key` to identify callers by something unforgeable."}},{headers:{"content-type":"application/json"},status:500}),le=(e,r)=>async(t,o)=>{let n;if(r.key)n=r.key(t,o);else{const a=V(t.headers,r.trustedClientIpHeader);n=a===void 0?void 0:$(a)}if(n===void 0||n==="")return ee();const c=await e.limit(r.name,{key:n});if(c.ok)return;if(c.reason==="deny")return Response.json({error:{code:"FORBIDDEN",message:"Request denied"}},{headers:{"content-type":"application/json"},status:403});const i=Math.max(1,Math.ceil(c.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(i)},status:429})};export{f as M,q as a,de as b,le as c,ie as d,G as e,ne as f,N as g,I as h,z as r,V as t,ce as w};
@@ -1 +1 @@
1
- import{LunoraError as g}from"./LunoraError-PkZWF-_g.mjs";const D=new Set(["0","disabled","false","no","off"]),C=new Set(["1","enabled","on","true","yes"]),O=e=>typeof e=="string"&&D.has(e.trim().toLowerCase()),R=e=>typeof e=="string"&&C.has(e.trim().toLowerCase()),S=e=>{if(e===null||typeof e!="object")return!1;const s=Object.getPrototypeOf(e);return s===null||s===Object.prototype},N="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",_="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",P=31536e3,I={coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0},k=e=>{if(e===!1)return;const s=e===void 0||e===!0?{}:e,o=s.maxAge??P,r=s.includeSubDomains??!0;return`max-age=${String(o)}${r?"; includeSubDomains":""}${s.preload===!0?"; preload":""}`},x=(e,s)=>s!==void 0?["frame-ancestors 'self'",...s].join(" "):e==="DENY"?"frame-ancestors 'none'":e==="SAMEORIGIN"?"frame-ancestors 'self'":void 0,H=/^[a-z][\d+.a-z-]*:\/\/(?:\*\.)?[\d.a-z-]+(?::\d{1,5})?$/iu,w=e=>[...e].every(s=>s===" "||s>=" "&&s!==""&&s<="ÿ"),T=["same-origin","same-origin-allow-popups","unsafe-none"],j=["DENY","SAMEORIGIN"],f=["includeSubDomains","maxAge","preload"],b=["csp","permissionsPolicy","referrerPolicy"],u=[...b,"crossOriginOpenerPolicy","frameAncestors","frameOptions","hsts"],d=e=>e.map(s=>JSON.stringify(s)).join(", "),U=(e,s)=>{if(typeof e=="boolean")return e;if(!S(e)){s.push("security.headers.hsts must be a boolean or an object { maxAge?, includeSubDomains?, preload? }");return}for(const n of Object.keys(e).filter(i=>!f.includes(i)))s.push(`security.headers.hsts.${n} is not an option (expected ${d(f)})`);const{includeSubDomains:o,maxAge:r,preload:t}=e;r!==void 0&&!(typeof r=="number"&&Number.isSafeInteger(r)&&r>=0)&&s.push(`security.headers.hsts.maxAge must be a whole number of seconds (got ${JSON.stringify(r)})`);for(const[n,i]of[["includeSubDomains",o],["preload",t]])i!==void 0&&typeof i!="boolean"&&s.push(`security.headers.hsts.${n} must be a boolean`);return{...o===void 0?{}:{includeSubDomains:o},...r===void 0?{}:{maxAge:r},...t===void 0?{}:{preload:t}}},p=(e,s,o,r)=>{if(s===void 0||s===!1||o.includes(s))return s;r.push(`security.headers.${e} must be one of ${d(o)} or false (got ${JSON.stringify(s)})`)},$=(e,s)=>{if(e!==void 0){if(!Array.isArray(e)){s.push('security.headers.frameAncestors must be an array of origins like ["https://partner.example"]');return}for(const o of e)(typeof o!="string"||!H.test(o)||!w(o))&&s.push(`security.headers.frameAncestors entry ${JSON.stringify(o)} is not an origin like "https://partner.example"`);return[...e]}},M=e=>{if(e===void 0||typeof e=="boolean")return{ok:!0,value:e};if(!S(e))return{ok:!1,problems:[`security.headers must be a boolean or an object (got ${Array.isArray(e)?"an array":JSON.stringify(e)})`]};const s=Object.keys(e).filter(r=>!u.includes(r)).map(r=>`security.headers.${r} is not an option (expected ${d(u)})`),o={};for(const r of b){const t=e[r];t===void 0||t===!1?o[r]=t:typeof t!="string"?s.push(`security.headers.${r} must be a string or false`):w(t)?o[r]=t:s.push(`security.headers.${r} contains a line break or control character`)}return o.crossOriginOpenerPolicy=p("crossOriginOpenerPolicy",e.crossOriginOpenerPolicy,T,s),o.frameOptions=p("frameOptions",e.frameOptions,j,s),o.frameAncestors=$(e.frameAncestors,s),o.hsts=e.hsts===void 0?void 0:U(e.hsts,s),o.frameAncestors!==void 0&&typeof o.csp=="string"&&s.push("security.headers.frameAncestors cannot be combined with a csp string: put the frame-ancestors directive in the csp"),o.frameAncestors!==void 0&&o.frameOptions==="DENY"&&s.push('security.headers.frameAncestors cannot be combined with frameOptions: "DENY"'),o.frameAncestors!==void 0&&o.csp===!1&&s.push("security.headers.frameAncestors needs the Content-Security-Policy that carries it; it cannot be combined with csp: false"),s.length>0?{ok:!1,problems:s}:{ok:!0,value:Object.fromEntries(Object.entries(o).filter(([,r])=>r!==void 0))}},X=(e,s)=>e??(O(s)?!1:void 0),F=e=>{if(e===!1)return I;const s=e===void 0||e===!0?{}:e,o=s.frameAncestors!==void 0||s.frameOptions===!1?void 0:s.frameOptions??"SAMEORIGIN",r=["base-uri 'none'","object-src 'none'",x(o,s.frameAncestors)].filter(n=>n!==void 0).join("; ");let t;return typeof s.csp=="string"?t={htmlValue:s.csp,value:s.csp}:s.csp!==!1&&(t={htmlValue:r,value:N}),{coop:s.crossOriginOpenerPolicy===!1?void 0:s.crossOriginOpenerPolicy??"same-origin-allow-popups",csp:t,enabled:!0,frameOptions:o,hsts:k(s.hsts),permissionsPolicy:s.permissionsPolicy===!1?void 0:s.permissionsPolicy??_,referrerPolicy:s.referrerPolicy===!1?void 0:s.referrerPolicy??"strict-origin-when-cross-origin"}},h=["Authorization","Content-Type","Last-Event-ID","X-D1-Bookmark","X-Lunora-Client-Id","X-Lunora-Client-Seq","X-Lunora-Expect-Subject","X-Lunora-Min-Seq","X-Lunora-Mutation-Id","X-Lunora-Shard-Key"],m=["DELETE","GET","HEAD","PATCH","POST","PUT"],G=new Set(["GET","HEAD","OPTIONS"]),Y=e=>{const s={allowCredentials:!1,allowedHeaders:h,allowedMethods:m,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return s;const o=e.allowCredentials??!1,r=e.allowedOrigins;let t,n;if(typeof r=="function"){const i=v=>r(v)===!0;t=i,n=i,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${o?" AND reflects matching origins with credentials (`allowCredentials: true`)":""} — ensure it matches ONLY trusted origins by exact equality; an over-broad predicate (e.g. \`() => true\`, or \`endsWith\`/\`includes\` checks) defeats the allowlist.`)}else{const i=r;if(i.includes("*")&&o)throw new g('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=a=>i.includes("*")||i.includes(a),n=a=>i.includes(a)}return{allowCredentials:o,allowedHeaders:[...new Set([...h,...e.allowedHeaders??[]])],allowedMethods:e.allowedMethods??m,enabled:!0,isAllowed:t,isExplicitlyAllowed:n,maxAge:e.maxAge??600}},B=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const s=e===void 0||e===!0?{}:e;return{allowLoopback:s.allowLoopback??!0,enabled:!0,trustedOrigins:s.trustedOrigins??[]}},V=e=>{const s=e?.LUNORA_ALLOWED_ORIGINS;if(typeof s!="string")return;const o=s.split(",").map(n=>n.trim()).filter(n=>n.length>0);return o.length===0?void 0:{allowCredentials:!o.includes("*")&&R(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:o}},q=(e,s)=>{const o=M(X(e?.headers,s?.LUNORA_SECURITY_HEADERS)),r=e?.csrf??(O(s?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??V(s);if(!o.ok)throw new g(`@lunora/runtime: ${o.problems.join("; ")}`);return{cors:Y(t),csrf:B(r),headers:F(o.value)}},K=new Set(["127.0.0.1","::1","[::1]","localhost"]),y=e=>{try{return K.has(new URL(e).hostname)}catch{return!1}},l=e=>{if(e)try{return new URL(e).origin}catch{return}},A=(e,s,o)=>e===s||o.csrf.trustedOrigins.includes(e)||o.csrf.allowLoopback&&y(s)&&y(e)?!0:o.cors.enabled&&o.cors.isExplicitlyAllowed(e),E=(e,s,o)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:o,message:`${e} rejected: Origin ${s===void 0?"was missing":`"${s}"`} is not trusted (this worker serves "${o}"). Add it to \`security.csrf.trustedOrigins\` (or LUNORA_ALLOWED_ORIGINS) if it is yours. Behind a dev proxy this usually means the proxy rewrote the host: keep both ends on loopback, or list the dev-server origin.`,receivedOrigin:s}},{headers:{"content-type":"application/json"},status:403}),ee=(e,s)=>{if(!s.csrf.enabled||G.has(e.method)||!e.headers.get("cookie"))return;const o=new URL(e.url).origin,r=l(e.headers.get("origin"))??l(e.headers.get("referer"));if(!(r!==void 0&&A(r,o,s)))return E("cross-origin state-changing request",r,o)},se=(e,s)=>{if(!s.csrf.enabled||!e.headers.get("cookie"))return;const o=new URL(e.url).origin,r=l(e.headers.get("origin"));if(!(r!==void 0&&A(r,o,s)))return E("cross-origin websocket upgrade",r,o)},W=["X-D1-Bookmark","X-Lunora-Edge-Cache","X-Lunora-Live-Connection","X-Lunora-Shard-Key"],L=(e,s)=>{const o=new Headers;return o.set("access-control-allow-origin",e),o.set("access-control-expose-headers",W.join(", ")),o.append("vary","Origin"),s.allowCredentials&&o.set("access-control-allow-credentials","true"),o},oe=(e,s)=>{if(!s.cors.enabled||e.method!=="OPTIONS")return;const o=e.headers.get("origin");if(!o||!e.headers.get("access-control-request-method")||!s.cors.isAllowed(o))return;const r=L(o,s.cors),t=e.headers.get("access-control-request-headers");r.set("access-control-allow-methods",s.cors.allowedMethods.join(", "));let n;if(t===null)n=s.cors.allowedHeaders.join(", ");else{const i=new Set(s.cors.allowedHeaders.map(a=>a.toLowerCase()));n=t.split(",").map(a=>a.trim()).filter(a=>a.length>0&&i.has(a.toLowerCase())).join(", ")}return r.set("access-control-allow-headers",n),r.set("access-control-max-age",String(s.cors.maxAge)),new Response(null,{headers:r,status:204})},J=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),c=(e,s,o)=>{e.has(s)||e.set(s,o)},z=(e,s,o,r)=>{r.hsts!==void 0&&new URL(s.url).protocol==="https:"&&c(e,"strict-transport-security",r.hsts),c(e,"x-content-type-options","nosniff"),r.frameOptions!==void 0&&c(e,"x-frame-options",r.frameOptions),r.referrerPolicy!==void 0&&c(e,"referrer-policy",r.referrerPolicy),r.permissionsPolicy!==void 0&&c(e,"permissions-policy",r.permissionsPolicy),r.coop!==void 0&&c(e,"cross-origin-opener-policy",r.coop),r.csp!==void 0&&c(e,"content-security-policy",J(o)?r.csp.htmlValue:r.csp.value)},Q=(e,s,o)=>{const r=s.headers.get("origin");if(!(!r||!o.isAllowed(r)))for(const[t,n]of L(r,o).entries())t==="vary"?e.append("vary",n):c(e,t,n)},re=(e,s,o)=>{if(e.status===101||e.webSocket)return e;const r=new Headers(e.headers);return o.headers.enabled&&z(r,s,e,o.headers),o.cors.enabled&&Q(r,s,o.cors),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})};export{se as a,re as d,ee as e,oe as h,S as i,q as r};
1
+ import{LunoraError as g}from"./LunoraError-PkZWF-_g.mjs";const D=new Set(["0","disabled","false","no","off"]),C=new Set(["1","enabled","on","true","yes"]),O=e=>typeof e=="string"&&D.has(e.trim().toLowerCase()),R=e=>typeof e=="string"&&C.has(e.trim().toLowerCase()),S=e=>{if(e===null||typeof e!="object")return!1;const s=Object.getPrototypeOf(e);return s===null||s===Object.prototype},_="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",N="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",P=31536e3,I={coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0},k=e=>{if(e===!1)return;const s=e===void 0||e===!0?{}:e,o=s.maxAge??P,r=s.includeSubDomains??!0;return`max-age=${String(o)}${r?"; includeSubDomains":""}${s.preload===!0?"; preload":""}`},x=(e,s)=>s!==void 0?["frame-ancestors 'self'",...s].join(" "):e==="DENY"?"frame-ancestors 'none'":e==="SAMEORIGIN"?"frame-ancestors 'self'":void 0,H=/^[a-z][\d+.a-z-]*:\/\/(?:\*\.)?[\d.a-z-]+(?::\d{1,5})?$/iu,w=e=>[...e].every(s=>s===" "||s>=" "&&s!==""&&s<="ÿ"),T=["same-origin","same-origin-allow-popups","unsafe-none"],U=["DENY","SAMEORIGIN"],f=["includeSubDomains","maxAge","preload"],b=["csp","permissionsPolicy","referrerPolicy"],u=[...b,"crossOriginOpenerPolicy","frameAncestors","frameOptions","hsts"],d=e=>e.map(s=>JSON.stringify(s)).join(", "),j=(e,s)=>{if(typeof e=="boolean")return e;if(!S(e)){s.push("security.headers.hsts must be a boolean or an object { maxAge?, includeSubDomains?, preload? }");return}for(const n of Object.keys(e).filter(i=>!f.includes(i)))s.push(`security.headers.hsts.${n} is not an option (expected ${d(f)})`);const{includeSubDomains:o,maxAge:r,preload:t}=e;r!==void 0&&!(typeof r=="number"&&Number.isSafeInteger(r)&&r>=0)&&s.push(`security.headers.hsts.maxAge must be a whole number of seconds (got ${JSON.stringify(r)})`);for(const[n,i]of[["includeSubDomains",o],["preload",t]])i!==void 0&&typeof i!="boolean"&&s.push(`security.headers.hsts.${n} must be a boolean`);return{...o===void 0?{}:{includeSubDomains:o},...r===void 0?{}:{maxAge:r},...t===void 0?{}:{preload:t}}},p=(e,s,o,r)=>{if(s===void 0||s===!1||o.includes(s))return s;r.push(`security.headers.${e} must be one of ${d(o)} or false (got ${JSON.stringify(s)})`)},$=(e,s)=>{if(e!==void 0){if(!Array.isArray(e)){s.push('security.headers.frameAncestors must be an array of origins like ["https://partner.example"]');return}for(const o of e)(typeof o!="string"||!H.test(o)||!w(o))&&s.push(`security.headers.frameAncestors entry ${JSON.stringify(o)} is not an origin like "https://partner.example"`);return[...e]}},M=e=>{if(e===void 0||typeof e=="boolean")return{ok:!0,value:e};if(!S(e))return{ok:!1,problems:[`security.headers must be a boolean or an object (got ${Array.isArray(e)?"an array":JSON.stringify(e)})`]};const s=Object.keys(e).filter(r=>!u.includes(r)).map(r=>`security.headers.${r} is not an option (expected ${d(u)})`),o={};for(const r of b){const t=e[r];t===void 0||t===!1?o[r]=t:typeof t!="string"?s.push(`security.headers.${r} must be a string or false`):w(t)?o[r]=t:s.push(`security.headers.${r} contains a line break or control character`)}return o.crossOriginOpenerPolicy=p("crossOriginOpenerPolicy",e.crossOriginOpenerPolicy,T,s),o.frameOptions=p("frameOptions",e.frameOptions,U,s),o.frameAncestors=$(e.frameAncestors,s),o.hsts=e.hsts===void 0?void 0:j(e.hsts,s),o.frameAncestors!==void 0&&typeof o.csp=="string"&&s.push("security.headers.frameAncestors cannot be combined with a csp string: put the frame-ancestors directive in the csp"),o.frameAncestors!==void 0&&o.frameOptions==="DENY"&&s.push('security.headers.frameAncestors cannot be combined with frameOptions: "DENY"'),o.frameAncestors!==void 0&&o.csp===!1&&s.push("security.headers.frameAncestors needs the Content-Security-Policy that carries it; it cannot be combined with csp: false"),s.length>0?{ok:!1,problems:s}:{ok:!0,value:Object.fromEntries(Object.entries(o).filter(([,r])=>r!==void 0))}},X=(e,s)=>e??(O(s)?!1:void 0),F=e=>{if(e===!1)return I;const s=e===void 0||e===!0?{}:e,o=s.frameAncestors!==void 0||s.frameOptions===!1?void 0:s.frameOptions??"SAMEORIGIN",r=["base-uri 'none'","object-src 'none'",x(o,s.frameAncestors)].filter(n=>n!==void 0).join("; ");let t;return typeof s.csp=="string"?t={htmlValue:s.csp,value:s.csp}:s.csp!==!1&&(t={htmlValue:r,value:_}),{coop:s.crossOriginOpenerPolicy===!1?void 0:s.crossOriginOpenerPolicy??"same-origin-allow-popups",csp:t,enabled:!0,frameOptions:o,hsts:k(s.hsts),permissionsPolicy:s.permissionsPolicy===!1?void 0:s.permissionsPolicy??N,referrerPolicy:s.referrerPolicy===!1?void 0:s.referrerPolicy??"strict-origin-when-cross-origin"}},h=["Authorization","Content-Type","Last-Event-ID","X-D1-Bookmark","X-Lunora-Client-Id","X-Lunora-Client-Seq","X-Lunora-Expect-Subject","X-Lunora-Min-Seq","X-Lunora-Mutation-Id","X-Lunora-Shard-Key"],m=["DELETE","GET","HEAD","PATCH","POST","PUT"],Y=new Set(["GET","HEAD","OPTIONS"]),G=e=>{const s={allowCredentials:!1,allowedHeaders:h,allowedMethods:m,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return s;const o=e.allowCredentials??!1,r=e.allowedOrigins;let t,n;if(typeof r=="function"){const i=v=>r(v)===!0;t=i,n=i,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${o?" AND reflects matching origins with credentials (`allowCredentials: true`)":""} — ensure it matches ONLY trusted origins by exact equality; an over-broad predicate (e.g. \`() => true\`, or \`endsWith\`/\`includes\` checks) defeats the allowlist.`)}else{const i=r;if(i.includes("*")&&o)throw new g('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=a=>i.includes("*")||i.includes(a),n=a=>i.includes(a)}return{allowCredentials:o,allowedHeaders:[...new Set([...h,...e.allowedHeaders??[]])],allowedMethods:e.allowedMethods??m,enabled:!0,isAllowed:t,isExplicitlyAllowed:n,maxAge:e.maxAge??600}},B=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const s=e===void 0||e===!0?{}:e;return{allowLoopback:s.allowLoopback??!0,enabled:!0,trustedOrigins:s.trustedOrigins??[]}},V=e=>{const s=e?.LUNORA_ALLOWED_ORIGINS;if(typeof s!="string")return;const o=s.split(",").map(n=>n.trim()).filter(n=>n.length>0);return o.length===0?void 0:{allowCredentials:!o.includes("*")&&R(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:o}},q=(e,s)=>{const o=M(X(e?.headers,s?.LUNORA_SECURITY_HEADERS)),r=e?.csrf??(O(s?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??V(s);if(!o.ok)throw new g(`@lunora/runtime: ${o.problems.join("; ")}`);return{cors:G(t),csrf:B(r),headers:F(o.value)}},K=new Set(["127.0.0.1","::1","[::1]","localhost"]),y=e=>{try{return K.has(new URL(e).hostname)}catch{return!1}},l=e=>{if(e)try{return new URL(e).origin}catch{return}},A=(e,s,o)=>e===s||o.csrf.trustedOrigins.includes(e)||o.csrf.allowLoopback&&y(s)&&y(e)?!0:o.cors.enabled&&o.cors.isExplicitlyAllowed(e),E=(e,s,o)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:o,message:`${e} rejected: Origin ${s===void 0?"was missing":`"${s}"`} is not trusted (this worker serves "${o}"). Add it to \`security.csrf.trustedOrigins\` (or LUNORA_ALLOWED_ORIGINS) if it is yours. Behind a dev proxy this usually means the proxy rewrote the host: keep both ends on loopback, or list the dev-server origin.`,receivedOrigin:s}},{headers:{"content-type":"application/json"},status:403}),ee=(e,s)=>{if(!s.csrf.enabled||Y.has(e.method)||!e.headers.get("cookie"))return;const o=new URL(e.url).origin,r=l(e.headers.get("origin"))??l(e.headers.get("referer"));if(!(r!==void 0&&A(r,o,s)))return E("cross-origin state-changing request",r,o)},se=(e,s)=>{if(!s.csrf.enabled||!e.headers.get("cookie"))return;const o=new URL(e.url).origin,r=l(e.headers.get("origin"));if(!(r!==void 0&&A(r,o,s)))return E("cross-origin websocket upgrade",r,o)},W=["X-D1-Bookmark","X-Lunora-Edge-Cache","X-Lunora-Live-Connection","X-Lunora-Shard-Key"],L=(e,s)=>{const o=new Headers;return o.set("access-control-allow-origin",e),o.set("access-control-expose-headers",W.join(", ")),o.append("vary","Origin"),s.allowCredentials&&o.set("access-control-allow-credentials","true"),o},oe=(e,s)=>{if(!s.cors.enabled||e.method!=="OPTIONS")return;const o=e.headers.get("origin");if(!o||!e.headers.get("access-control-request-method")||!s.cors.isAllowed(o))return;const r=L(o,s.cors),t=e.headers.get("access-control-request-headers");r.set("access-control-allow-methods",s.cors.allowedMethods.join(", "));let n;if(t===null)n=s.cors.allowedHeaders.join(", ");else{const i=new Set(s.cors.allowedHeaders.map(a=>a.toLowerCase()));n=t.split(",").map(a=>a.trim()).filter(a=>a.length>0&&i.has(a.toLowerCase())).join(", ")}return r.set("access-control-allow-headers",n),r.set("access-control-max-age",String(s.cors.maxAge)),new Response(null,{headers:r,status:204})},J=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),c=(e,s,o)=>{e.has(s)||e.set(s,o)},z=(e,s,o,r)=>{r.hsts!==void 0&&new URL(s.url).protocol==="https:"&&c(e,"strict-transport-security",r.hsts),c(e,"x-content-type-options","nosniff"),r.frameOptions!==void 0&&c(e,"x-frame-options",r.frameOptions),r.referrerPolicy!==void 0&&c(e,"referrer-policy",r.referrerPolicy),r.permissionsPolicy!==void 0&&c(e,"permissions-policy",r.permissionsPolicy),r.coop!==void 0&&c(e,"cross-origin-opener-policy",r.coop),r.csp!==void 0&&c(e,"content-security-policy",J(o)?r.csp.htmlValue:r.csp.value)},Q=(e,s,o)=>{const r=s.headers.get("origin");if(!(!r||!o.isAllowed(r)))for(const[t,n]of L(r,o).entries())t==="vary"?e.append("vary",n):c(e,t,n)},re=(e,s,o)=>{if(e.status===101||e.webSocket)return e;const r=new Headers(e.headers);return o.headers.enabled&&z(r,s,e,o.headers),o.cors.enabled&&Q(r,s,o.cors),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})};export{se as a,re as d,ee as e,oe as h,S as i,q as r};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.279",
3
+ "version": "1.0.0-alpha.280",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1 +0,0 @@
1
- import{redactArgs as h,redactCredentials as b}from"@lunora/observability";import{S as y,n as O}from"./observability-sinks-CRKDJlAP.mjs";const f=t=>{try{t()}catch{}},u=(t,n)=>{const r={};for(const o of y)t[o]!==void 0&&(r[o]=t[o]);return t.flush&&(r.flush=o=>{f(()=>t.flush?.(o))}),t.onLog&&(r.onLog=(o,e)=>{const c=n.log===void 0?o:n.log(o);c!==void 0&&f(()=>t.onLog?.(c,e))}),t.onMetric&&(r.onMetric=(o,e)=>{const c=n.metric===void 0?o:n.metric(o);c!==void 0&&f(()=>t.onMetric?.(c,e))}),t.onRpc&&(r.onRpc=(o,e)=>{const c=n.rpc===void 0?o:n.rpc(o);c!==void 0&&f(()=>t.onRpc?.(c,e))}),t.onSpan&&(r.onSpan=(o,e)=>{const c=n.span===void 0?o:n.span(o);c!==void 0&&f(()=>t.onSpan?.(c,e))}),r},l=5;let a=0;const S=t=>{if(a>=l)return;a+=1;const n=a===l?" Further enricher failures are silenced until the isolate restarts.":"";try{console.error(`[lunora:observability] enrichSink's enricher threw; delivering the event without its extra attributes.${n}`,t instanceof Error?t.name:typeof t)}catch{}},j=(t,n)=>{if(t instanceof Error)return n({...Object.fromEntries(Object.entries(t)),message:t.message,name:t.name});const r=Reflect.get(t,"toJSON");if(typeof r=="function"){const e=r.call(t);return e!==t?n(e):Object.fromEntries(Object.entries(t).map(([c,s])=>[c,n(s)]))}if(Array.isArray(t))return t.map(e=>n(e));const o=Object.getPrototypeOf(t);return o!==Object.prototype&&o!==null?t:Object.fromEntries(Object.entries(t).map(([e,c])=>[e,n(c)]))},x=()=>({ancestors:new WeakSet,copies:new WeakMap}),g=(t,n=x())=>{if(typeof t=="symbol"||typeof t=="function")return String(t);if(typeof t!="object"||t===null)return t;if(!n.ancestors.has(t)){if(n.copies.has(t))return n.copies.get(t);n.ancestors.add(t);try{const r=j(t,o=>g(o,n));return n.copies.set(t,r),r}finally{n.ancestors.delete(t)}}},d=(t,n,r)=>{try{const o=t(g(n),r),e=o===void 0?void 0:Object.fromEntries(Object.entries(o).filter(([,i])=>i!==void 0)),c=e===void 0?void 0:g(e),s=r==="log"?h(c):b(c);return O(s)}catch(o){S(o);return}},A=(t,n)=>u(t,{log:r=>{const o=d(n,r,"log");return o===void 0?r:{...r,fields:{...o,...r.fields}}},metric:r=>{const o=d(n,r,"metric");return o===void 0?r:{...r,attributes:{...o,...r.attributes}}},rpc:r=>{const o=d(n,r,"rpc");return o===void 0?r:{...r,attributes:{...o,...r.attributes}}},span:r=>{const o=d(n,r,"span");return o===void 0?r:{...r,attributes:{...o,...r.attributes}}}}),m=(t,n)=>{const r=t.split("*");if(r.length===1)return n===t;const o=r[0]??"",e=r.at(-1)??"";if(n.length<o.length+e.length||!n.startsWith(o)||!n.endsWith(e))return!1;const c=n.length-e.length;let s=o.length;for(const i of r.slice(1,-1)){const p=n.indexOf(i,s);if(p===-1||p+i.length>c)return!1;s=p+i.length}return s<=c},E=(t,n)=>n.exclude?.some(r=>m(r,t))?!1:n.include===void 0||n.include.length===0||n.include.some(r=>m(r,t)),L=(t,n)=>{const r=o=>E(o.functionPath,n)?o:void 0;return u(t,{log:r,metric:r,rpc:r,span:r})};export{A as enrichSink,L as filterSink,m as globMatch};
@@ -1,4 +0,0 @@
1
- import{LunoraError as Z}from"@lunora/errors";import{redactCredentials as Q,redactArgs as N}from"@lunora/observability";import{stableStringify as v}from"@lunora/wire";import{e as c,L as m,c as H,o as j,f as I,O as z,g as rr,h as J,w as tr,i as or,j as sr,m as er}from"./otlp-resource-BBR8xs6m.mjs";import{t as ar}from"./error-detail-C46mdOTW.mjs";const nr=r=>{if(typeof r=="string")return r;if(r instanceof Error)return String(r);try{return JSON.stringify(r)??String(r)}catch{return String(r)}},R=r=>typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:nr(r),ir=(r,s,t)=>{Object.defineProperty(r,s,{configurable:!0,enumerable:!0,value:t,writable:!0})},Dr=(r,s)=>{if(r===void 0&&s===void 0)return;const t={};if(r!==void 0)for(const[o,e]of Object.entries(r))ir(t,o,R(e));return Object.keys(t).length===0?void 0:t},cr=512,dr=200,ur=r=>{const s=r.maxItems??cr,t=r.maxDelayMs??dr;let o=[],e,i,a;const p=()=>{e!==void 0&&(clearTimeout(e),e=void 0)},g=async()=>{p();const l=o;o=[];const d=a;i=void 0,a=void 0;try{l.length>0&&await r.export(l)}catch{}finally{d?.()}},h=l=>{i===void 0&&(i=new Promise(d=>{a=d}),e=setTimeout(()=>{g()},t)),l?.(i)};return{add:(l,d)=>{for(o.push(l);o.length>s;)o.shift();h(d),o.length>=s&&g()},flush:async l=>{if(o.length===0){p();return}const d=g();return l?.(d),d},get size(){return o.length}}},lr=1,pr=0,fr=new Set(["cloudflare.ray_id","error.type","http.request.method","http.response.status_code","http.route","lunora.error_status","lunora.fanout.failed","lunora.fanout.shards","lunora.fanout.table","lunora.function_path","lunora.ok","lunora.shard_key","server.address","server.port","url.path","url.scheme","user_agent.original"]),mr={errorType:m.errorType,functionPath:m.functionPath,rayId:m.rayId,shardKey:m.shardKey,userId:m.userId},hr=r=>{const s=ar(r);return s===void 0?[]:[c("lunora.error.internal",JSON.stringify(Q(s)))]},G=(r,s,t,o)=>[c("exception.type",r),c("exception.message",s),...t===void 0?[]:[c("exception.stacktrace",t)],...o===void 0?[]:hr(o)],gr=(r,s)=>{const t=[c(m.functionPath,r.functionPath),c(m.ok,r.ok)];if(r.method!==void 0&&t.push(c("http.request.method",r.method)),r.path!==void 0&&t.push(c("url.path",r.path)),t.push(c("http.route",r.functionPath)),r.scheme!==void 0&&t.push(c("url.scheme",r.scheme)),r.host!==void 0&&t.push(c("server.address",r.host)),r.port!==void 0&&t.push(c("server.port",r.port)),r.userAgent!==void 0&&t.push(c("user_agent.original",r.userAgent)),r.shardKey!==void 0&&t.push(c(m.shardKey,r.shardKey)),r.rayId!==void 0&&t.push(c(m.rayId,r.rayId)),t.push(c("http.response.status_code",r.error?.status??200)),r.error&&t.push(c(m.errorType,r.error.code),c("lunora.error_status",r.error.status)),r.fanOut&&t.push(c("lunora.fanout.table",r.fanOut.table),c("lunora.fanout.shards",r.fanOut.shards),c("lunora.fanout.failed",r.fanOut.failed)),r.attributes!==void 0){const e=new Set([...fr,...t.map(a=>a.key)]),i=H(Object.fromEntries(Object.entries(r.attributes).map(([a,p])=>[a,R(p)])));t.push(...i.filter(a=>!e.has(a.key)))}const o={attributes:t,endTimeUnixNano:I(s),kind:z.server,name:r.functionPath,...r.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},spanId:r.spanId??j(8),startTimeUnixNano:I(s-r.durationMs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId??j(16)};return r.traceFlags!==void 0&&(o.flags=r.traceFlags),r.error&&(o.events=[{attributes:G(r.error.code,r.error.message,r.error.stack,r.error.internal),name:"exception",timeUnixNano:I(s)}]),o},x=(r,s)=>{const t=new Map,o=new Set(Object.keys(r).map(e=>mr[e]));for(const[e,i]of Object.entries(s??{}))o.has(e)||t.set(e,c(e,R(i)));return t.set(m.functionPath,c(m.functionPath,r.functionPath)),r.shardKey!==void 0&&t.set(m.shardKey,c(m.shardKey,r.shardKey)),r.userId!==void 0&&t.set(m.userId,c(m.userId,r.userId)),r.rayId!==void 0&&t.set(m.rayId,c(m.rayId,r.rayId)),r.errorType!==void 0&&t.set(m.errorType,c(m.errorType,r.errorType)),[...t.values()]},yr=r=>{const s={attributes:x({errorType:r.error?.type,functionPath:r.functionPath,rayId:r.rayId,shardKey:r.shardKey,userId:r.userId},r.attributes),endTimeUnixNano:I(r.startTs+r.durationMs),flags:r.sampled===!1?pr:lr,kind:z[r.kind??"internal"],name:r.name,parentSpanId:r.parentSpanId,spanId:r.spanId,startTimeUnixNano:I(r.startTs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId},t=o=>H(Object.fromEntries(Object.entries(o??{}).map(([e,i])=>[e,R(i)])));return r.events!==void 0&&r.events.length>0&&(s.events=r.events.map(o=>({attributes:t(o.attributes),name:o.name,timeUnixNano:I(o.ts)}))),r.links!==void 0&&r.links.length>0&&(s.links=r.links.map(o=>({attributes:t(o.attributes),spanId:o.spanId,traceId:o.traceId}))),s},br=r=>{const s=I(r.ts),t=x({functionPath:r.functionPath,shardKey:r.shardKey},r.attributes),o=r.traceId===void 0?void 0:[{asDouble:r.value,timeUnixNano:s,traceId:r.traceId}],e={asDouble:r.value,attributes:t,...o===void 0?{}:{exemplars:o},timeUnixNano:s};return r.kind==="gauge"?{gauge:{dataPoints:[e]},name:r.name}:r.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:t,bucketCounts:["1"],count:"1",...o===void 0?{}:{exemplars:o},explicitBounds:[],max:r.value,min:r.value,sum:r.value,timeUnixNano:s}]},name:r.name}:{name:r.name,sum:{aggregationTemporality:1,dataPoints:[e],isMonotonic:!0}}},kr=r=>{const s={attributes:x({functionPath:r.functionPath,rayId:r.rayId,shardKey:r.shardKey,userId:r.userId},r.fields),body:{stringValue:r.message},severityNumber:rr[r.level],severityText:r.level.toUpperCase(),timeUnixNano:I(r.ts)};if(r.traceId!==void 0&&(s.traceId=r.traceId),r.spanId!==void 0&&(s.spanId=r.spanId),r.error!==void 0){const t=G(r.error.name,r.error.message,r.error.stack,r.error.internal),o=new Set(t.map(e=>e.key));s.attributes=[...s.attributes.filter(e=>!o.has(e.key)),...t]}return r.eventName!==void 0&&(s.eventName=r.eventName,s.attributes=[...s.attributes.filter(t=>t.key!=="event.name"),c("event.name",r.eventName)]),s},Ir=1024,B=5;let _=0;const Sr=(r,s)=>{if(_>=B)return;_+=1;let t;try{t=new URL(r).host}catch{t="<unparseable endpoint>"}const o=_===B?" Further OTLP rejections are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] collector ${t} rejected the export with HTTP ${String(s)}; the batch is DROPPED (there is no retry).${o}`)},Tr=async r=>{const s=new Blob([r]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(s).arrayBuffer()},W=async(r,s,t,o)=>{try{const e=JSON.stringify(s),{byteLength:i}=new TextEncoder().encode(e),a=(i<Ir?fetch(r,{body:e,headers:t,method:"POST"}):Tr(e).then(p=>fetch(r,{body:p,headers:{...t,"content-encoding":"gzip"},method:"POST"}))).then(p=>{p.ok||Sr(r,p.status)},()=>{});o?.(a),await a}catch{}},Pr=(r,s,t,o)=>{W(r,s,t,o?.waitUntil).catch(()=>{})},E=(r,s)=>s===!0&&r.ok,wr=r=>r.kind==="metric"?void 0:r.event.traceId,Or=r=>{const s=Map.groupBy(r,o=>wr(o)),t=s.get(void 0)??[];return s.delete(void 0),{byTrace:s,untraced:t}},C=5,Er=(r,s,t)=>{if(s===void 0)return r;const{byTrace:o,untraced:e}=Or(r),i=[...e];let a=0,p;for(const[g,h]of o){let l;try{l=s({logs:h.filter(d=>d.kind==="log").map(d=>d.event),rpc:h.filter(d=>d.kind==="rpc").map(d=>d.event),spans:h.filter(d=>d.kind==="span").map(d=>d.event),traceId:g})}catch(d){a+=1,a===1&&(p=d),l=!0}l&&i.push(...h)}return a>0&&t(p,a),i},w=(r,s)=>{let t;try{t=s===void 0?r:s(r)}catch{t=void 0}return t??void 0},Lr=r=>{const s=N(r.message);if(r.stack===void 0)return{...r,message:s};const t=`: ${r.message}`,o=r.stack.indexOf(t),i=r.message!==""&&o!==-1&&!r.stack.slice(0,o).includes(`
2
- `)?r.stack.slice(o+t.length):r.stack.split(`
3
- `).filter(a=>a.trimStart().startsWith("at ")).map(a=>`
4
- ${a}`).join("");return{...r,message:s,stack:`${r.name}: ${s}${i}`}},Rr=r=>({...r,...r.error===void 0?{}:{error:Lr(r.error)},...r.fields===void 0?{}:{fields:N(r.fields)},message:N(r.message)}),V=(r,s,t)=>{if(r.kind==="rpc"){const e=w(r.event,s?.rpc);return e===void 0?void 0:{bucket:"spans",encoded:gr(e,r.endMs)}}if(r.kind==="span"){const e=w(r.event,s?.span);return e===void 0?void 0:{bucket:"spans",encoded:yr(e)}}if(r.kind==="log"){const e=w(t?Rr(r.event):r.event,s?.log);return e===void 0?void 0:{bucket:"logs",encoded:kr(e)}}const o=w(r.event,s?.metric);return o===void 0?void 0:{bucket:"metrics",encoded:br(o)}},Ar=["fuseCloudflareTraces","instrumentDatabase","metricHistory","traceFetch"],Fr=(r={})=>{const{onlyErrors:s}=r;return{onLog:t=>{t.level==="error"||t.level==="fatal"?console.error("[lunora:log]",t.functionPath,t.message):console.log("[lunora:log]",t.functionPath,t.message)},onMetric:t=>{console.log("[lunora:metric]",`${t.name}=${String(t.value)}`,t.kind,t.functionPath)},onRpc:t=>{E(t,s)||(t.ok?console.log("[lunora:rpc]",t):console.error("[lunora:rpc]",t))},onSpan:t=>{const o=t.ok?"ok":`error ${t.error?.type??""}`.trim();console.log("[lunora:span]",t.name,`${String(t.durationMs)}ms`,o,t.functionPath)}}},Kr=r=>{const{headers:s,onlyErrors:t,transform:o,transformLog:e,url:i}=r,a=J({"content-type":"application/json"},s),p=(g,h)=>{try{const l=fetch(i,{body:JSON.stringify(g),headers:a,method:"POST"}).catch(()=>{});h?.waitUntil&&h.waitUntil(l)}catch{}};return{onLog:(g,h)=>{const l=w(g,e);l!==void 0&&p(l,h)},onRpc:(g,h)=>{if(E(g,t))return;const l=w(g,o);l!==void 0&&p(l,h)}}},$r=r=>{const{dataset:s,onlyErrors:t}=r;return{onRpc:o=>{if(!E(o,t))try{s.writeDataPoint({blobs:[o.functionPath,o.ok?"ok":"error",o.shardKey??"",o.error?.code??"",o.fanOut?.table??""],doubles:[o.durationMs,o.ok?0:1,o.fanOut?.shards??0,o.fanOut?.failed??0],indexes:[o.functionPath]})}catch{}}}},jr=r=>{const{pipeline:s,serializeFields:t}=r;return{onLog:(o,e)=>{try{const i={functionPath:o.functionPath,level:o.level,message:o.message,ts:o.ts};o.fields&&(i.fields=t===!0?JSON.stringify(o.fields):o.fields);for(const p of["shardKey","userId","traceId","spanId"])o[p]!==void 0&&(i[p]=o[p]);const a=s.send([i]).catch(()=>{});e?.waitUntil&&e.waitUntil(a)}catch{}}}},Br=r=>{const{batch:s,deploymentEnvironment:t,detectResources:o,endpoint:e,headers:i,onlyErrors:a,postProcessor:p,resourceAttributes:g,serviceNamespace:h,serviceVersion:l,tailSampler:d,token:X}=r,M=r.serviceName??"lunora",U=r.redactLogs??!0;if(s!==!1&&s?.maxItems!==void 0&&(!Number.isInteger(s.maxItems)||s.maxItems<1))throw new Z("ENV_INVALID",`otlpSink: \`batch.maxItems\` must be a positive integer, received ${String(s.maxItems)}.`);const D={...l===void 0?{}:{"service.version":l},...h===void 0?{}:{"service.namespace":h},...t===void 0?{}:{"deployment.environment":t},...g},F=new WeakMap,k=u=>{if(o!==!0||u?.resourceAttributes===void 0)return D;const n=F.get(u);if(n!==void 0)return n;const f=er(u.resourceAttributes(),D);return F.set(u,f),f};let S=e;for(;S.endsWith("/");)S=S.slice(0,-1);const K={logs:{url:`${S}/v1/logs`,wrap:sr},metrics:{url:`${S}/v1/metrics`,wrap:or},spans:{url:`${S}/v1/traces`,wrap:tr}},$=J({"content-type":"application/json"},i,X);let A=0;const Y=(u,n)=>{if(A>=C)return;A+=1;const f=A===C?" Further tailSampler failures from this sink are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] tailSampler threw for ${String(n)} trace(s) in this flush window; keeping them (fail-open), so the sampling policy did NOT apply.${f}`,u)},q=async u=>{const n=Er(u,d,Y),f=new Map;for(const y of n){const b=V(y,p,U);if(b===void 0)continue;const L=v(y.resource);let P=f.get(L);P===void 0&&(P={logs:[],metrics:[],resource:y.resource,spans:[]},f.set(L,P)),P[b.bucket].push(b.encoded)}const T=[];for(const[,y]of f)for(const b of["spans","logs","metrics"])if(y[b].length>0){const{url:L,wrap:P}=K[b];T.push(W(L,P(y[b],"@lunora/runtime",M,y.resource),$))}await Promise.all(T)};if(s===!1){const u=(n,f)=>{const T=V(n,p,U);if(T!==void 0){const{url:y,wrap:b}=K[T.bucket];Pr(y,b(T.encoded,"@lunora/runtime",M,n.resource),$,f)}};return{onLog:(n,f)=>{u({event:n,kind:"log",resource:k(f)},f)},onMetric:(n,f)=>{u({event:n,kind:"metric",resource:k(f)},f)},onRpc:(n,f)=>{E(n,a)||u({endMs:Date.now(),event:n,kind:"rpc",resource:k(f)},f)},onSpan:(n,f)=>{u({event:n,kind:"span",resource:k(f)},f)}}}const O=ur({export:q,...s?.maxDelayMs===void 0?{}:{maxDelayMs:s.maxDelayMs},...s?.maxItems===void 0?{}:{maxItems:s.maxItems}});return{flush:u=>{O.flush(u?.waitUntil).catch(()=>{})},onLog:(u,n)=>{O.add({event:u,kind:"log",resource:k(n)},n?.waitUntil)},onMetric:(u,n)=>{O.add({event:u,kind:"metric",resource:k(n)},n?.waitUntil)},onRpc:(u,n)=>{E(u,a)||O.add({endMs:Date.now(),event:u,kind:"rpc",resource:k(n)},n?.waitUntil)},onSpan:(u,n)=>{O.add({event:u,kind:"span",resource:k(n)},n?.waitUntil)}}},Cr=(...r)=>{const s=(o,e)=>{for(const i of r){const a=i[o];if(a)try{a.apply(i,e)}catch{}}},t={};for(const o of r)for(const e of Ar)t[e]===void 0&&o[e]!==void 0&&(t[e]=o[e]);return{...t,flush:o=>{s("flush",[o])},onLog:(o,e)=>{s("onLog",[o,e])},onMetric:(o,e)=>{s("onMetric",[o,e])},onRpc:(o,e)=>{s("onRpc",[o,e])},onSpan:(o,e)=>{s("onSpan",[o,e])}}};export{Ar as S,$r as a,Fr as b,Cr as c,Dr as n,Br as o,jr as p,Kr as w};
@@ -1 +0,0 @@
1
- const m="/_lunora/rest",v=["authorization","cf-access-jwt-assertion","cookie","payment-signature","x-payment"],d=["x-d1-bookmark","x-lunora-shard-key"],h=e=>[...v,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],u=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,c=(...e)=>{const t=[];for(const a of e)for(const s of a?.split(",")??[]){const n=s.trim().toLowerCase();n!==""&&!t.includes(n)&&t.push(n)}return t.length===0?void 0:t.join(", ")},l=(e,t)=>{const a=[t,`max-age=${String(u(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&a.push(`stale-while-revalidate=${String(u(e.staleWhileRevalidate))}`),a.join(", ")},p=e=>e.scope==="public"?c(e.vary,...h(e),...d):c(e.vary,...d),f=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},g=e=>{const t=f(e);if(t!==void 0)return`${m}/${t.namespace}/${t.name}`},E=e=>e==="query"?"GET":"POST",b=e=>{const t=[];for(const a of e){if(a.exposure?.rest!==!0||a.kind==="stream")continue;const s=f(a.functionPath),n=g(a.functionPath);s===void 0||n===void 0||t.push({functionPath:a.functionPath,kind:a.kind,method:E(a.kind),name:s.name,namespace:s.namespace,path:n})}return t.sort((a,s)=>a.path<s.path?-1:+(a.path>s.path)),t},R=(e,t,a)=>a?.access!==void 0||h(t).some(s=>e.headers.has(s)),x=(e,t,a)=>e.scope==="public"&&!R(t,e,a)?"public":"private",S=(e,t,a,s)=>{if(t.method!=="GET"||a<200||a>299)return;const n={"cache-control":l(e,x(e,t,s))};e.tag!==void 0&&e.tag!==""&&(n["cache-tag"]=e.tag);const r=p(e);return r!==void 0&&(n.vary=r),n},C=(e,t,a,s)=>{if(t===void 0)return e;const n=S(t,a,e.status,s);if(n===void 0)return e;const r=new Response(e.body,e);for(const[i,o]of Object.entries(n))r.headers.set(i,i==="vary"?c(r.headers.get("vary")??void 0,o)??o:o);return r};export{C as a,S as b,u as c,p as d,x as e,b as f,R as r};