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