@lunora/runtime 1.0.0-alpha.92 → 1.0.0-alpha.94
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 +36 -4
- package/dist/index.d.ts +36 -4
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{argsFromQuery-BmKHT_05.mjs → argsFromQuery-D8hbb24F.mjs} +1 -1
- package/dist/packem_shared/composeWorker-B_dbXCev.mjs +6 -0
- package/dist/packem_shared/{createCrossShardRelationCapabilities-DlM1uNSP.mjs → createCrossShardRelationCapabilities-B6jWmfjn.mjs} +1 -1
- package/dist/packem_shared/{createKvCursorStore-Irk1yRJm.mjs → createKvCursorStore-CiXokqz5.mjs} +1 -1
- package/dist/packem_shared/{createShardClient-BaZZLHHu.mjs → createShardClient-CECfFWIM.mjs} +1 -1
- package/dist/packem_shared/decorateResponse-Y2sCM0w1.mjs +1 -0
- package/dist/packem_shared/{export-tap-H6oPBoSr.mjs → export-tap-mRfLykiL.mjs} +1 -1
- package/dist/packem_shared/{portable-json-FqR-Y3KD.mjs → portable-json-DcwKZHQ7.mjs} +1 -1
- package/dist/packem_shared/rest-routes-BbMQwlSV.mjs +1 -0
- package/dist/packem_shared/{toAirbyteMessages-CetjLpiw.mjs → toAirbyteMessages-BX5SK-Ss.mjs} +1 -1
- package/dist/packem_shared/wire-codec-BX_-4Tmg.mjs +1 -0
- package/package.json +4 -4
- package/dist/packem_shared/composeWorker-CgM6lJBI.mjs +0 -6
- package/dist/packem_shared/decorateResponse-CCRm2CFM.mjs +0 -1
- package/dist/packem_shared/rest-routes-CpwDstbq.mjs +0 -1
- package/dist/packem_shared/wire-codec-DBWN80s9.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -426,6 +426,7 @@ interface AuthImpersonation {
|
|
|
426
426
|
interface AuthCapabilities {
|
|
427
427
|
accounts: boolean;
|
|
428
428
|
admin: boolean;
|
|
429
|
+
inviteOnly: boolean;
|
|
429
430
|
organization: boolean;
|
|
430
431
|
passkey: boolean;
|
|
431
432
|
twoFactor: boolean;
|
|
@@ -522,6 +523,11 @@ interface AuthAdmin {
|
|
|
522
523
|
permission: Record<string, string[]>;
|
|
523
524
|
role: string;
|
|
524
525
|
}) => Promise<Record<string, unknown>>;
|
|
526
|
+
createSignUpInvitation?: (input: {
|
|
527
|
+
email: string;
|
|
528
|
+
expiresInSeconds?: number;
|
|
529
|
+
invitedBy?: string;
|
|
530
|
+
}) => Promise<Record<string, unknown>>;
|
|
525
531
|
createTeam?: (input: {
|
|
526
532
|
name: string;
|
|
527
533
|
organizationId: string;
|
|
@@ -584,6 +590,10 @@ interface AuthAdmin {
|
|
|
584
590
|
offset?: number;
|
|
585
591
|
userId?: string;
|
|
586
592
|
}) => Promise<AuthPage<AuthSession>>;
|
|
593
|
+
listSignUpInvitations?: (options: {
|
|
594
|
+
limit?: number;
|
|
595
|
+
offset?: number;
|
|
596
|
+
}) => Promise<AuthPage<Record<string, unknown>>>;
|
|
587
597
|
listTeamMembers?: (options: {
|
|
588
598
|
limit?: number;
|
|
589
599
|
offset?: number;
|
|
@@ -607,6 +617,9 @@ interface AuthAdmin {
|
|
|
607
617
|
removeUser?: (input: {
|
|
608
618
|
userId: string;
|
|
609
619
|
}) => Promise<void>;
|
|
620
|
+
revokeSignUpInvitation?: (input: {
|
|
621
|
+
email: string;
|
|
622
|
+
}) => Promise<void>;
|
|
610
623
|
revokeUserSession?: (input: {
|
|
611
624
|
sessionId: string;
|
|
612
625
|
}) => Promise<void>;
|
|
@@ -2558,6 +2571,7 @@ interface RateLimiterLike {
|
|
|
2558
2571
|
key?: string;
|
|
2559
2572
|
}) => Promise<{
|
|
2560
2573
|
ok: boolean;
|
|
2574
|
+
reason?: string;
|
|
2561
2575
|
retryAfter: number;
|
|
2562
2576
|
}>;
|
|
2563
2577
|
}
|
|
@@ -2565,10 +2579,16 @@ interface RateLimiterLike {
|
|
|
2565
2579
|
* Adapt a `@lunora/ratelimit` limiter into a {@link RestRateLimit} gate for the
|
|
2566
2580
|
* public REST surface (plan 167). Pass the limiter and the rate name to charge;
|
|
2567
2581
|
* `key` isolates the limit per caller (IP / user / API key — defaults to the
|
|
2568
|
-
* `cf-connecting-ip` header, else
|
|
2569
|
-
*
|
|
2570
|
-
*
|
|
2571
|
-
*
|
|
2582
|
+
* `cf-connecting-ip` header, else {@link UNRESOLVED_IP_BUCKET}).
|
|
2583
|
+
*
|
|
2584
|
+
* A rate rejection becomes a `429` with a `Retry-After` header (seconds, ceil of
|
|
2585
|
+
* the limiter's ms). A deny-list hit becomes a `403` and no `Retry-After` —
|
|
2586
|
+
* matching both `@lunora/ratelimit` entry points, and the only honest answer for
|
|
2587
|
+
* a denial that never clears: its `retryAfter` is `Infinity`, which renders as
|
|
2588
|
+
* the header value `"Infinity"` and invites a client to retry forever.
|
|
2589
|
+
*
|
|
2590
|
+
* The runtime imports nothing from `@lunora/ratelimit` — build the limiter in
|
|
2591
|
+
* the worker entry and pass it here.
|
|
2572
2592
|
*/
|
|
2573
2593
|
declare const createRestRateLimit: (limiter: RateLimiterLike, options: {
|
|
2574
2594
|
key?: (request: Request, functionPath: string) => string | undefined;
|
|
@@ -2877,6 +2897,18 @@ interface HttpActionContext {
|
|
|
2877
2897
|
}) => Promise<unknown>;
|
|
2878
2898
|
};
|
|
2879
2899
|
fetch: typeof globalThis.fetch;
|
|
2900
|
+
/**
|
|
2901
|
+
* The same `run*` trio bound to a named shard, mirroring
|
|
2902
|
+
* `createShardClient(...).forShard(key)`.
|
|
2903
|
+
*
|
|
2904
|
+
* An HTTP action runs in the WORKER, not inside a shard, so — unlike a
|
|
2905
|
+
* query/mutation ctx, whose `run*` is already inside the owning DO — it has
|
|
2906
|
+
* to be told which shard to talk to. `ctx.run*` alone targets the default
|
|
2907
|
+
* shard, which on a `.shardBy(...)` app is the root DO: a webhook that read
|
|
2908
|
+
* `ctx.runQuery(api.messages.list, { channelId })` got the root shard's rows
|
|
2909
|
+
* (usually none) with no error and no way to say otherwise.
|
|
2910
|
+
*/
|
|
2911
|
+
forShard: (shardKey: string) => Pick<HttpActionContext, "runAction" | "runMutation" | "runQuery">;
|
|
2880
2912
|
runAction: <R>(reference: unknown, args?: Record<string, unknown>) => Promise<R>;
|
|
2881
2913
|
runMutation: <R>(reference: unknown, args?: Record<string, unknown>) => Promise<R>;
|
|
2882
2914
|
runQuery: <R>(reference: unknown, args?: Record<string, unknown>) => Promise<R>;
|
package/dist/index.d.ts
CHANGED
|
@@ -426,6 +426,7 @@ interface AuthImpersonation {
|
|
|
426
426
|
interface AuthCapabilities {
|
|
427
427
|
accounts: boolean;
|
|
428
428
|
admin: boolean;
|
|
429
|
+
inviteOnly: boolean;
|
|
429
430
|
organization: boolean;
|
|
430
431
|
passkey: boolean;
|
|
431
432
|
twoFactor: boolean;
|
|
@@ -522,6 +523,11 @@ interface AuthAdmin {
|
|
|
522
523
|
permission: Record<string, string[]>;
|
|
523
524
|
role: string;
|
|
524
525
|
}) => Promise<Record<string, unknown>>;
|
|
526
|
+
createSignUpInvitation?: (input: {
|
|
527
|
+
email: string;
|
|
528
|
+
expiresInSeconds?: number;
|
|
529
|
+
invitedBy?: string;
|
|
530
|
+
}) => Promise<Record<string, unknown>>;
|
|
525
531
|
createTeam?: (input: {
|
|
526
532
|
name: string;
|
|
527
533
|
organizationId: string;
|
|
@@ -584,6 +590,10 @@ interface AuthAdmin {
|
|
|
584
590
|
offset?: number;
|
|
585
591
|
userId?: string;
|
|
586
592
|
}) => Promise<AuthPage<AuthSession>>;
|
|
593
|
+
listSignUpInvitations?: (options: {
|
|
594
|
+
limit?: number;
|
|
595
|
+
offset?: number;
|
|
596
|
+
}) => Promise<AuthPage<Record<string, unknown>>>;
|
|
587
597
|
listTeamMembers?: (options: {
|
|
588
598
|
limit?: number;
|
|
589
599
|
offset?: number;
|
|
@@ -607,6 +617,9 @@ interface AuthAdmin {
|
|
|
607
617
|
removeUser?: (input: {
|
|
608
618
|
userId: string;
|
|
609
619
|
}) => Promise<void>;
|
|
620
|
+
revokeSignUpInvitation?: (input: {
|
|
621
|
+
email: string;
|
|
622
|
+
}) => Promise<void>;
|
|
610
623
|
revokeUserSession?: (input: {
|
|
611
624
|
sessionId: string;
|
|
612
625
|
}) => Promise<void>;
|
|
@@ -2558,6 +2571,7 @@ interface RateLimiterLike {
|
|
|
2558
2571
|
key?: string;
|
|
2559
2572
|
}) => Promise<{
|
|
2560
2573
|
ok: boolean;
|
|
2574
|
+
reason?: string;
|
|
2561
2575
|
retryAfter: number;
|
|
2562
2576
|
}>;
|
|
2563
2577
|
}
|
|
@@ -2565,10 +2579,16 @@ interface RateLimiterLike {
|
|
|
2565
2579
|
* Adapt a `@lunora/ratelimit` limiter into a {@link RestRateLimit} gate for the
|
|
2566
2580
|
* public REST surface (plan 167). Pass the limiter and the rate name to charge;
|
|
2567
2581
|
* `key` isolates the limit per caller (IP / user / API key — defaults to the
|
|
2568
|
-
* `cf-connecting-ip` header, else
|
|
2569
|
-
*
|
|
2570
|
-
*
|
|
2571
|
-
*
|
|
2582
|
+
* `cf-connecting-ip` header, else {@link UNRESOLVED_IP_BUCKET}).
|
|
2583
|
+
*
|
|
2584
|
+
* A rate rejection becomes a `429` with a `Retry-After` header (seconds, ceil of
|
|
2585
|
+
* the limiter's ms). A deny-list hit becomes a `403` and no `Retry-After` —
|
|
2586
|
+
* matching both `@lunora/ratelimit` entry points, and the only honest answer for
|
|
2587
|
+
* a denial that never clears: its `retryAfter` is `Infinity`, which renders as
|
|
2588
|
+
* the header value `"Infinity"` and invites a client to retry forever.
|
|
2589
|
+
*
|
|
2590
|
+
* The runtime imports nothing from `@lunora/ratelimit` — build the limiter in
|
|
2591
|
+
* the worker entry and pass it here.
|
|
2572
2592
|
*/
|
|
2573
2593
|
declare const createRestRateLimit: (limiter: RateLimiterLike, options: {
|
|
2574
2594
|
key?: (request: Request, functionPath: string) => string | undefined;
|
|
@@ -2877,6 +2897,18 @@ interface HttpActionContext {
|
|
|
2877
2897
|
}) => Promise<unknown>;
|
|
2878
2898
|
};
|
|
2879
2899
|
fetch: typeof globalThis.fetch;
|
|
2900
|
+
/**
|
|
2901
|
+
* The same `run*` trio bound to a named shard, mirroring
|
|
2902
|
+
* `createShardClient(...).forShard(key)`.
|
|
2903
|
+
*
|
|
2904
|
+
* An HTTP action runs in the WORKER, not inside a shard, so — unlike a
|
|
2905
|
+
* query/mutation ctx, whose `run*` is already inside the owning DO — it has
|
|
2906
|
+
* to be told which shard to talk to. `ctx.run*` alone targets the default
|
|
2907
|
+
* shard, which on a `.shardBy(...)` app is the root DO: a webhook that read
|
|
2908
|
+
* `ctx.runQuery(api.messages.list, { channelId })` got the root shard's rows
|
|
2909
|
+
* (usually none) with no error and no way to say otherwise.
|
|
2910
|
+
*/
|
|
2911
|
+
forShard: (shardKey: string) => Pick<HttpActionContext, "runAction" | "runMutation" | "runQuery">;
|
|
2880
2912
|
runAction: <R>(reference: unknown, args?: Record<string, unknown>) => Promise<R>;
|
|
2881
2913
|
runMutation: <R>(reference: unknown, args?: Record<string, unknown>) => Promise<R>;
|
|
2882
2914
|
runQuery: <R>(reference: unknown, args?: Record<string, unknown>) => Promise<R>;
|
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-
|
|
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-BX5SK-Ss.mjs";import{composeWorker as x,createLunoraHandler as S,createWorker as l,defineRpcEnvelope as u,resolveLunoraOptions as _,withFrameworkWorker as d}from"./packem_shared/composeWorker-B_dbXCev.mjs";import{createCrossShardRelationCapabilities as y}from"./packem_shared/createCrossShardRelationCapabilities-B6jWmfjn.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-mRfLykiL.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-B1hLjwgx.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-DOreZlpn.mjs";import{D as pe,c as ce}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as fe,createStaticShardRegistry as Ee}from"./packem_shared/createQueryCoordinator-DlWITOu1.mjs";import{applyJurisdiction as xe,resolveShard as Se}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as _e,b as de}from"./packem_shared/rest-cache-D1BlbZb1.mjs";import{a as ye,b as Ce,c as Oe,r as be}from"./packem_shared/rest-routes-BbMQwlSV.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-CECfFWIM.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ie}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Me}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ne}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ke,routeIdentityResolvers as Ue}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,O as DEFAULT_REGISTRY_CACHE_TTL_MS,G as HEALTH_PATH,K as HEALTH_READY_PATH,Me as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,T as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,b as SHARD_REGISTRY_DO_NAME,Ie as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,xe as applyJurisdiction,ue as applyRestCache,ye as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ke as composeIdentityResolvers,x as composeWorker,oe as consoleSink,y as createCrossShardRelationCapabilities,A as createDynamicShardRegistry,P as createKvCursorStore,S as createLunoraHandler,g as createMemoryCursorStore,ce as createPipelineLogReader,fe as createQueryCoordinator,Oe as createRestRateLimit,ge as createShardClient,Ee as createStaticShardRegistry,l as createWorker,B as d1Probe,Le as decorateResponse,v as defineExportSink,u as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,Te as enforceOrigin,he as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,I as r2Sink,_e as requestCarriesCredentials,j as resolveLogArchiveFromEnv,_ as resolveLunoraOptions,He as resolveSecurity,Se as resolveShard,de as restCacheHeaders,be as restSurfaceFromRegistry,Ue as routeIdentityResolvers,D as runExportTap,M as sanitizeChange,se as sentrySink,f as toAirbyteMessages,h as toErrorResponse,E as toFivetranResponse,F as webhookExportSink,ie as webhookSink,d as withFrameworkWorker};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./rest-cache-D1BlbZb1.mjs";import{a,b as o,c as i,r as m}from"./rest-routes-
|
|
1
|
+
import"./rest-cache-D1BlbZb1.mjs";import{a,b as o,c as i,r as m}from"./rest-routes-BbMQwlSV.mjs";import"./method-guard-BG_vJNTl.mjs";export{a as argsFromQuery,o as buildRestRoutes,i as createRestRateLimit,m as restSurfaceFromRegistry};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{isLunoraError as Hn,toErrorBody as Ln}from"@lunora/errors";import{e as Lt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Mn}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as $n,f as jn}from"./base64-Bl1_r2k1.mjs";import{e as Kn,a as Fn}from"./identity-header-C4Z5pldl.mjs";import{o as Ie,b as Gn,p as Qn,m as zn,d as Wn,a as Vn,r as Jn}from"./otlp-resource-DeXhb949.mjs";import{e as ke,d as Mt}from"./wire-codec-BX_-4Tmg.mjs";import{d as te,e as he,M as $t,b as qn,f as Yn,g as jt,h as Kt}from"./rest-routes-BbMQwlSV.mjs";import{LunoraError as d,toErrorResponse as ct}from"./LunoraError-DksAgIpa.mjs";import{a as $,m as we}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as Ye,BACKUP_KEY_PREFIX as Xe,isBackupManifestKey as Xn,backupObjectKeyOfManifest as Ft,backupObjectKey as Zn,backupManifestKey as er}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as tr,buildStorageAdminRoutes as nr,STORAGE_UPLOAD_MAX_BODY_BYTES as rr,STORAGE_PATH as or}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{b as ar,e as sr,f as dt,g as ir,h as cr}from"./export-tap-mRfLykiL.mjs";import{buildHealthRoutes as dr,durableObjectProbe as ur,d1Probe as lr,presenceProbe as Le}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as hr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Hs,routeIdentityResolvers as Ls}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as fr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{r as pr,f as ut,a as ce}from"./observability-B1hLjwgx.mjs";import{resolveShard as ge,applyJurisdiction as lt}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as ht,handleCorsPreflight as mr,enforceOrigin as wr,decorateResponse as Me,enforceWebSocketOrigin as ft}from"./decorateResponse-Y2sCM0w1.mjs";const gr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},Gt="__lunoraBranch",yr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Gt),br=`may not contain the reserved workflow branch-marker key ("${Gt}")`,_r=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}},Ze=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,u=a<t.length?t.charCodeAt(a):0;r|=i^u}return r===0},Rr=/already[\s_-]?exists/iu,Er=e=>Rr.test(e instanceof Error?e.message:String(e)),Sr=(e,t,n,r)=>{const a=e.get(t);if(a!==void 0)return a;Lt(e,r);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},et=new TextEncoder,Ar=Array.from({length:32},(e,t)=>t);new RegExp(`[${Ar.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Tr=64,Or=new Map,Qt=async e=>Sr(Or,e,async()=>crypto.subtle.importKey("raw",et.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),Tr),zt=async(e,t)=>{const n=await Qt(e),r=await crypto.subtle.sign("HMAC",n,et.encode(t));return $n(new Uint8Array(r))},vr=async(e,t,n)=>{const r=await Qt(e);return crypto.subtle.verify("HMAC",r,n,et.encode(t))},kr=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(kr);const Ir=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Pr=-100,Nr=15,Dr=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Ir.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Nr?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Pr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},pt=e=>{const t=e.cf;return t===void 0?void 0:Dr(t)},Ve="::relay::",Ur=(e,t)=>`${e}${Ve}${String(t)}`,Je="::replica::",Cr=(e,t)=>`${e}${Je}${t}`,Br=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},xr=new Set(["1","enabled","on","true","yes"]),Hr=new Set(["0","disabled","false","no","off"]),Lr=(e,t)=>{const n=(e??"").trim().toLowerCase();return xr.has(n)?!0:Hr.has(n)?!1:t},Wt="v1",Mr=6e4,$r=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Mr),r=`${Wt}.${String(n)}`,a=await zt(e,r);return{expiresAtMs:n,token:`${r}.${a}`}},jr=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const r=t.split(".");if(r.length!==3)return!1;const[a,i,u]=r;if(a!==Wt||u.length===0)return!1;const h=Number(i);if(!Number.isFinite(h)||h<=n)return!1;let p;try{p=jn(u)}catch{return!1}return vr(e,`${a}.${i}`,p)},k="/_lunora/admin/auth",Kr={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},N=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new d(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},le=(e,t)=>{const n=e(t);if(n===void 0)throw new d(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},Vt=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,$e=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},mt=e=>{const t=Vt(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new d("`role` is required",{code:"BAD_REQUEST",status:400});return t},wt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[r,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[r]=a);return n},Fr={[`${k}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${k}/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"},[`${k}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${k}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${k}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${k}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${k}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${k}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${k}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${k}/sign-up-invitations/create`]:{build:({body:e})=>({email:N(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:re(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${k}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:N(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${k}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${k}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${k}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${k}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${k}/users/create`]:{build:({body:e})=>({data:$e(e,"data"),email:N(e,"email"),name:N(e,"name"),password:re(e,"password"),role:Vt(e.role)}),http:"POST",method:"createUser"},[`${k}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:N(e,"userId")}},http:"POST",method:"updateUser"},[`${k}/users/role`]:{build:({body:e})=>({role:mt(e),userId:N(e,"userId")}),http:"POST",method:"setRole"},[`${k}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:N(e,"userId")}),http:"POST",method:"banUser"},[`${k}/users/unban`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"unbanUser"},[`${k}/users/password`]:{build:({body:e})=>({newPassword:N(e,"newPassword"),userId:N(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${k}/users/remove`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${k}/users/impersonate`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"impersonateUser"},[`${k}/sessions/revoke`]:{build:({body:e})=>({sessionId:N(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${k}/sessions/revoke-all`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${k}/accounts/unlink`]:{build:({body:e})=>({accountId:N(e,"accountId"),userId:N(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${k}/two-factor/disable`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${k}/passkeys/delete`]:{build:({body:e})=>({passkeyId:N(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${k}/organizations/members/remove`]:{build:({body:e})=>({memberId:N(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${k}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:N(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${k}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:$e(e,"metadata"),name:N(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${k}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:$e(e,"metadata"),name:re(e,"name"),organizationId:N(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${k}/organizations/remove`]:{build:({body:e})=>({organizationId:N(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${k}/organizations/members/add`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),role:re(e,"role"),userId:N(e,"userId")}),http:"POST",method:"addMember"},[`${k}/organizations/members/invite`]:{build:({body:e})=>({email:N(e,"email"),inviterId:re(e,"inviterId"),organizationId:N(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${k}/organizations/members/role`]:{build:({body:e})=>({memberId:N(e,"memberId"),role:mt(e)}),http:"POST",method:"updateMemberRole"},[`${k}/organizations/teams/create`]:{build:({body:e})=>({name:N(e,"name"),organizationId:N(e,"organizationId")}),http:"POST",method:"createTeam"},[`${k}/organizations/teams/update`]:{build:({body:e})=>({name:N(e,"name"),teamId:N(e,"teamId")}),http:"POST",method:"updateTeam"},[`${k}/organizations/teams/remove`]:{build:({body:e})=>({teamId:N(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${k}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:N(e,"teamId"),userId:N(e,"userId")}),http:"POST",method:"addTeamMember"},[`${k}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:N(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${k}/organizations/roles/create`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),permission:wt(e),role:N(e,"role")}),http:"POST",method:"createOrgRole"},[`${k}/organizations/roles/update`]:{build:({body:e})=>({permission:wt(e),roleId:N(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${k}/organizations/roles/remove`]:{build:({body:e})=>({roleId:N(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Gr=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof d)throw i;const u=i,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new d("auth admin operation failed",{code:h,status:Kr[h]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new d(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new d("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[i.method];if(h===void 0)throw new d(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const p=new URL(a.url),m={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:T=>e.queryParameter(p,T)},S=i.build(m),A=await t(()=>h(S));return Response.json(i.returns==="void"?{ok:!0}:A,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[a,i]of Object.entries(Fr))r[a]=u=>n(u,i);return r},gt="__lunora_admin__:getAuthAuditLog",yt=e=>typeof e=="string"&&e!==""?e:void 0,bt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Qr=e=>async(n,r)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new d("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=yt(r.actorId),u=yt(r.event),h=bt(r.sinceSeq),p=bt(r.limit),m={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...p===void 0?{}:{limit:p}};let S;try{S=await a.read(m)}catch(T){throw T instanceof d?T:(console.error("[lunora] auth audit read failed:",T),new d("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const A={entries:S};return Response.json({result:ke(A)},{headers:{"content-type":"application/json"},status:200})},zr=(e,t)=>{const n=[],r=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?r.push(a):n.push(a);return{globalTables:r,shardLocalTables:n}},Wr=async(e,t,n,r,a,i,u)=>{if(n!==void 0&&r.length===0)return;const h=await e.orchestrateExport(i,{args:{tables:r},defaultShardKey:u,headers:t,tables:r});for(const p of h.shards)if(!p.error)for(const m of p.rows??[])a(m)},Jt=async(e,t,n,r,a,i)=>{const u=r??e.listSchemaTables?.();r===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:h,shardLocalTables:p}=zr(e,u);await Wr(t,n,u,p,a,i,e.defaultShardKey??"__root__");const m=e.exportGlobals;if((r===void 0||h.length>0)&&m)for await(const A of m({tables:h}))a(A)},Vr=new TextEncoder,Jr=1e3,qt=10,qr=200,_t=8,Yt="lunoraBackupCron",Rt=24*1048576,Et=e=>{const t=e.slice(0,qt).map(r=>Ft(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Yr=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const a of e)n.set(a,r),r+=a.byteLength;return n},tt=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let u=0;u<Jr;u+=1){const h=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const p of h.objects)Xn(p.key)&&p.customMetadata?.[Yt]===r&&a.push(p.key);if(!h.truncated||h.cursor===void 0)break;i=h.cursor}return{eligible:a.length,stale:a.toSorted((u,h)=>h.localeCompare(u)).slice(n)}},Xr=async(e,t,n,r,a)=>{const{stale:i}=await tt(e,t,n,r),u=new Set(a),h=i.filter(g=>u.has(g)),p=h.slice(0,qr),m=i.length-p.length,S=a.length-h.length;if(p.length===0)return{deleted:[],failed:[],ignored:S,remaining:m};const A=[],T=[];for(let g=0;g<p.length;g+=_t){const b=await Promise.allSettled(p.slice(g,g+_t).map(async R=>(await e.delete(Ft(R)),await e.delete(R),R)));for(const[R,f]of b.entries())f.status==="fulfilled"?A.push(f.value):T.push(p[g+R])}return A.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(A.length)}: ${Et(A)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${Et(T)}`),{deleted:A,failed:T,ignored:S,remaining:m}},Zr=async e=>{const t=e.backupStore;if(!t)throw new d("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=Ye(e.backupPrefix??Xe),r=e.backupCron,{eligible:a,stale:i}=r===void 0?{eligible:0,stale:[]}:await tt(t,n,e.backupRetain,r);return{cron:r,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},eo=async(e,t,n,r)=>{const a=e.backupStore,i=e.queryCoordinator;if(!a)throw new d("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!i)throw new d("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!n||n.length===0)throw new d("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const u={authorization:`Bearer ${n}`,"content-type":"application/json"},h=e.backupTables;let p=0,m=0,S=[];await Jt(e,i,u,h,U=>{const M=Vr.encode(`${JSON.stringify(U)}
|
|
2
|
+
`);if(p+=1,m+=M.byteLength,m>Rt)throw new d(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Rt)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});S.push(M)},t);const T=Ye(e.backupPrefix??Xe),g=new Date(r.scheduledTime).toISOString(),b=Zn(T,g),R=Yr(S,m);S=[];const f=tr(await crypto.subtle.digest("SHA-256",R));await a.put(b,R,{httpMetadata:{contentType:"application/x-ndjson"},sha256:f});const O={bytes:m,createdAt:g,cron:r.cron,file:b,id:g,rows:p,scheduledTime:r.scheduledTime,sha256:f,...h?{tables:h.join(",")}:{}};await a.put(er(b),`${JSON.stringify(O,void 0,2)}
|
|
3
|
+
`,{customMetadata:{[Yt]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:U}=await tt(a,T,e.backupRetain,r.cron);if(U.length>0){const M=U.slice(0,qt),I=U.length-M.length;console.info(`[lunora] backup retention: ${String(U.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${M.join(", ")}${I>0?` (+${String(I)} more)`:""}`)}}catch(U){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,U)}},to=async(e,t)=>{const n=e.backupStore;if(!n)throw new d("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=e.backupCron,a=e.backupRetain;if(r===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new d("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return Xr(n,Ye(e.backupPrefix??Xe),a,r,t)},no="/_lunora/admin/backup/retention",ro="/_lunora/admin/backup/prune",oo=e=>{const{options:t,readJsonBody:n,requireAdminOption:r}=e,a=(h,p)=>{r(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${p} requires a \`backupStore\` on the worker`})},i=async h=>($(h,"GET","Backup-retention"),a(h,"retention preview"),Response.json(await Zr(t),{headers:{"cache-control":"no-store"}})),u=async h=>{$(h,"POST","Backup-prune"),a(h,"prune");const{confirm:p}=await n(h);if(!Array.isArray(p)||p.some(m=>typeof m!="string"))throw new d("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await to(t,p),{headers:{"cache-control":"no-store"}})};return{[ro]:u,[no]:i}},St=500,ao=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new d("each batch call must be an object",{code:"BAD_REQUEST",status:400});const r=e;if(typeof r.functionPath!="string")throw new d("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(r.functionPath.startsWith("__lunora_relation__:")||r.functionPath.startsWith("__lunora_admin__"))throw new d("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(r.args!==void 0&&(typeof r.args!="object"||r.args===null||Array.isArray(r.args)))throw new d("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:r.args===void 0?{}:r.args,clientId:typeof r.clientId=="string"?r.clientId:void 0,clientSeq:typeof r.clientSeq=="number"?r.clientSeq:void 0,functionPath:r.functionPath,id:typeof r.id=="number"?r.id:t,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:n}},so=(e,t)=>{if(e.length>St)throw new d(`RPC batch exceeds the ${String(St)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map;for(const[r,a]of e.entries()){const{entry:i,shardKey:u}=ao(a,r,t),h=n.get(u)??[];h.push(i),n.set(u,h)}return n},io="/_lunora/admin/export",co="/_lunora/admin/import",uo="/_lunora/admin/sync",lo="/_lunora/admin/connector/sync",ho="/_lunora/admin/apply",fo="/_lunora/admin/export-tap/run",po=new TextEncoder,mo=async e=>{const n=await he(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new d("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new d("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(a)}return{tables:r}},je=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,wo=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:a,knownTables:i,queryCoordinator:u,assertAdmin:h,requireAdminOption:p,resolveForwardContext:m,shardDO:S,streamExportRows:A,streamingImport:T,syncGlobals:g}=e,b=async(I,K)=>{const j=we(I,["POST"]);if(j)return j;const W=p(I,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),C=await mo(I),{headers:V}=await m(I,K),F=new ReadableStream({async pull(J){const ee=L=>{J.enqueue(po.encode(`${JSON.stringify(L)}
|
|
4
|
+
`))};try{await A(W,V,C.tables,ee),J.close()}catch(L){J.error(L)}}});return new Response(F,{headers:{"content-type":"application/x-ndjson"},status:200})},R=async(I,K)=>{const j=we(I,["POST"]);if(j)return j;const W=p(I,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),C=await te(I),V=typeof C.cursors=="object"&&C.cursors!==null?C.cursors:{},F=typeof C.limit=="number"?C.limit:void 0,J=typeof C.globalCursor=="number"?C.globalCursor:0,ee=je(C.tables),{headers:L}=await m(I,K),q=ee??i(),G=await W.orchestrateCdcSync(S,{cursors:V,defaultShardKey:n,headers:L,limit:F,tables:q}),fe=g?await g({limit:F,sinceSeq:J}):void 0;return Response.json({global:fe,shards:G.shards},{status:200})},f=async(I,K)=>{const j=we(I,["POST"]);if(j)return j;const W=p(I,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),C=await te(I),V=sr(C.cursor),F=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,J=je(C.tables),{headers:ee}=await m(I,K),L=J??i(),q=await W.orchestrateCdcSync(S,{cursors:V.s,defaultShardKey:n,headers:ee,limit:F,tables:L}),G=[],fe={...V.s};let ae=!1;for(const se of q.shards)ae=dt(G,se.changes??[],cr(F))||ae,fe[se.shardKey]=se.cursor;let _e=V.g;if(g){const se=await g({limit:F,sinceSeq:V.g});ae=dt(G,se.changes,F)||ae,_e=se.cursor}const Pe=ir({g:_e,s:fe,v:1}),Ne={changes:G,hasMore:ae,nextCursor:Pe};return Response.json(Ne,{status:200})},O=async(I,K)=>{const j=we(I,["POST"]);if(j)return j;const W=p(I,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),C=await te(I),F=(Array.isArray(C.batches)?C.batches:[]).map(G=>G).filter(G=>G!==null&&typeof G=="object"&&typeof G.shardKey=="string"&&Array.isArray(G.changes)),J=Array.isArray(C.globalChanges)?C.globalChanges:[],{headers:ee}=await m(I,K),L=await W.orchestrateApplyCdc(S,{batches:F,headers:ee}),q=J.length>0&&t?await t({changes:J}):0;return Response.json({applied:L.applied+q,failed:L.failed,ok:L.ok},{status:200})},U=async(I,K)=>{const j=we(I,["POST"]);if(j)return j;h(I);const{headers:W}=await m(I,K),C=await T(I,W);return Response.json(C,{headers:{"content-type":"application/json"},status:C.failed.length>0?207:200})},M=async(I,K)=>{const j=we(I,["POST"]);if(j)return j;const W=p(I,u,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(a===void 0||Object.keys(a).length===0||r===void 0)throw new d("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const C=await te(I),V=typeof C.sink=="string"?C.sink:void 0,F=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,J=je(C.tables);if(V===void 0)throw new d("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const ee=a[V];if(ee===void 0)throw new d(`Export-tap sink "${V}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:L}=await m(I,K),q=J??i(),G=await ar({coordinator:W,cursorStore:r,defaultShardKey:n,headers:L,limit:F,shardDO:S,sink:ee,tables:q});return Response.json(G,{headers:{"content-type":"application/json"},status:200})};return{[ho]:O,[lo]:f,[io]:b,[fo]:M,[co]:U,[uo]:R}},go=(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}},yo=(e,t,n,r,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:r}},bo=async(e,t,n)=>{if(!e.body)throw new d("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],a=[],i=new Map;let u=0,h=0;const p=e.body.getReader(),m=new TextDecoder;let S="",A=0;const T=g=>{h+=1;const b=g.trim();if(b.length===0)return;u+=1;const R=go(b,h);if(!R.ok){r.push(R.error);return}const{doc:f,table:O}=R,U=t.resolveTableSharding?.(O);if(U?.mode.kind==="global"){a.push({doc:f,line:h,table:O});return}const M=yo(f,O,U,n,h);if(!M.ok){r.push(M.error);return}const I=i.get(M.shardKey);I?I.rows.push({doc:f,table:O}):i.set(M.shardKey,{rows:[{doc:f,table:O}],shardKey:M.shardKey,startLine:h})};for(;;){const{done:g,value:b}=await p.read();if(g)break;if(b&&(A+=b.byteLength,A>$t))throw await p.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});S+=m.decode(b,{stream:!0});let R=S.indexOf(`
|
|
5
|
+
`);for(;R!==-1;){const f=S.slice(0,R);S=S.slice(R+1),T(f),R=S.indexOf(`
|
|
6
|
+
`)}}return S.length>0&&T(S),{errors:r,globalRows:a,perShard:i,received:u}},_o=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),At=(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},Ro=async(e,t,n,r)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:h,received:p}=await bo(e,t,a),m={conflicts:0,errors:i,failed:[],inserted:{}},S=[];if(t.resolveTableSharding===void 0&&h.size>0&&S.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const A=t.queryCoordinator;if(!A)throw new d("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const T=await A.orchestrateImport(r,{batches:[...h.values()],headers:n});At(m,T),m.failed.push(..._o(T.shards))}if(u.length>0)if(t.importGlobals){const A=u[0]?.line??1,T=await t.importGlobals({rows:u,startLine:A});At(m,T)}else for(const A of u)m.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:A.line,message:`row targets global table "${A.table}" but no \`importGlobals\` is configured`,table:A.table});return{conflicts:m.conflicts,errors:m.errors,failed:m.failed,inserted:m.inserted,received:p,...S.length>0?{warnings:S}:{}}},Ke=e=>typeof e=="object"&&e!==null?e:{},Fe=e=>typeof e.kind=="string"?e.kind:"unknown",Eo=(e,t)=>{let n=Ke(t),r=!1;Fe(n)==="optional"&&(r=!0,n=Ke(n._meta?.inner));const a=Fe(n),i=n._meta??{},u={kind:a,name:e,optional:r};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const h=Fe(Ke(i.inner));h!=="unknown"&&(u.element=h)}return u},So=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>Eo(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),Ao="/_lunora/admin/functions",To="/_lunora/admin/cron-jobs",Oo="/_lunora/admin/openapi",vo="/_lunora/admin/openrpc",ko="/_lunora/admin/global/tables",Io="/_lunora/admin/global/table",Po="/_lunora/admin/global/facet",Tt=e=>{if(e===void 0||e==="")return;let t;try{t=Mt(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:a,value:i}=r;return[{column:a,value:i}]});return n.length===0?void 0:n},No=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:{}}),Do=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"}),Uo=e=>{const{assertAdmin:t,options:n,parsePaging:r,queryParameter:a,requireAdminOption:i}=e,u=g=>{$(g,"GET","Functions");const b=i(g,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),R=Object.entries(b).flatMap(([f,O])=>O.visibility==="internal"||O.kind==="stream"?[]:[{args:So(O.args),kind:O.kind,path:f}]).toSorted((f,O)=>f.path.localeCompare(O.path));return Response.json({functions:R},{headers:{"content-type":"application/json"},status:200})},h=g=>{$(g,"GET","Cron-jobs");const b=i(g,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),R=Object.entries(b).flatMap(([f,O])=>O.map(U=>({args:U.args,cron:f,functionPath:U.functionPath,name:U.name,shardKey:U.shardKey,workflow:U.workflow}))).toSorted((f,O)=>f.name.localeCompare(O.name));return Response.json({jobs:R},{headers:{"content-type":"application/json"},status:200})},p=g=>($(g,"GET","OpenAPI"),t(g),Response.json(n.openApiSpec??No,{headers:{"content-type":"application/json"},status:200})),m=g=>($(g,"GET","OpenRPC"),t(g),Response.json(n.openRpcSpec??Do,{headers:{"content-type":"application/json"},status:200})),S=async g=>{$(g,"GET","Global-tables");const b=i(g,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})},A=async g=>{$(g,"GET","Global-table");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(g.url),f=a(R,"table");if(f===void 0)throw new d("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const O=await b.readTablePage({...r(g),filters:Tt(a(R,"filters")),table:f});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},T=async g=>{$(g,"GET","Global-facet");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(g.url),f=a(R,"table"),O=a(R,"column");if(f===void 0||O===void 0)throw new d("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const U=a(R,"limit"),M=U===void 0?void 0:Number(U),I=await b.facetColumn({column:O,filters:Tt(a(R,"filters")),limit:M!==void 0&&Number.isFinite(M)?M:void 0,table:f});return Response.json(I,{headers:{"content-type":"application/json"},status:200})};return{[To]:h,[Ao]:u,[Po]:T,[Io]:A,[ko]:S,[Oo]:p,[vo]:m}},Co="/_lunora/admin/kv/namespaces",Bo="/_lunora/admin/kv/keys",Xt="/_lunora/admin/kv/value",Zt=32*1048576,Ot=60,xo=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"}),a=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),i=(b,R)=>{const f=new URL(b.url),O=f.searchParams.get("namespace")??"",U=f.searchParams.get("key")??"";if(O==="")throw new d(`KV-value ${R} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(U==="")throw new d(`KV-value ${R} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:U,namespace:O}},u=async(b,R)=>{if(!(await b.listNamespaces()).some(O=>O.binding===R))throw new d(`Unknown KV namespace binding \`${R}\``,{code:"NOT_FOUND",status:404})},h=async b=>($(b,"GET","KV-namespaces"),a({namespaces:await r(b).listNamespaces()})),p=async b=>{$(b,"GET","KV-keys");const R=r(b),f=new URL(b.url),O=f.searchParams.get("namespace")??"";if(O==="")throw new d("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const U=f.searchParams.get("prefix")??void 0,M=f.searchParams.get("cursor")??void 0,I=f.searchParams.get("limit"),K=I===null?void 0:Number.parseInt(I,10);if(K!==void 0&&(!Number.isInteger(K)||K<1))throw new d("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const j=K===void 0?void 0:Math.min(K,1e3);return await u(R,O),a(await R.listKeys({cursor:M,limit:j,namespace:O,prefix:U}))},T={DELETE:async b=>{const R=r(b),f=i(b,"DELETE");return await u(R,f.namespace),await R.deleteKey(f),a({deleted:!0})},GET:async b=>{const R=r(b),f=i(b,"GET");return await u(R,f.namespace),a(await R.getValue(f))},PUT:async b=>{const R=r(b),f=await t(b,Zt);if(typeof f.namespace!="string"||f.namespace==="")throw new d("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof f.key!="string"||f.key==="")throw new d("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof f.value!="string")throw new d("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(f.expirationTtl!==void 0&&(typeof f.expirationTtl!="number"||!Number.isInteger(f.expirationTtl)||f.expirationTtl<Ot))throw new d("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const O=Math.floor(Date.now()/1e3)+Ot;if(f.expiration!==void 0&&(typeof f.expiration!="number"||!Number.isInteger(f.expiration)||f.expiration<O))throw new d("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(R,f.namespace),await R.putValue({expiration:f.expiration,expirationTtl:f.expirationTtl,key:f.key,metadata:f.metadata,namespace:f.namespace,value:f.value}),a({ok:!0})}},g=b=>{const R=T[b.method];if(!R)throw new d("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return R(b)};return{[Co]:h,[Bo]:p,[Xt]:g}},Ho="/_lunora/migrate",Lo="/_lunora/admin/pitr",Mo="/_lunora/admin/rank",$o="/_lunora/admin/rankpage",jo="/_lunora/admin/shard-traffic",Ko=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Fo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Go=async e=>{const n=await he(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!Ko.has(n.functionPath))throw new d("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},Qo=async e=>{const n=await he(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new d("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new d("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new d("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new d("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},zo=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new d('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Wo=e=>{if(typeof e.table!="string"||e.table.length===0)throw new d("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new d("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new d("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new d("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new d("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Vo=async e=>{const n=await he(e,"Rank page")??{};Wo(n);const r=zo(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}},Jo=async e=>{const n=await he(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},qo=async e=>{const n=await te(e);if(typeof n.functionPath!="string"||!Fo.has(n.functionPath))throw new d("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new d("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},Yo=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:r,queryCoordinator:a,resolveForwardContext:i,shardDO:u}=e,h=(g,b)=>{if(g.method!=="POST")throw new d(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(g))throw new d("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new d(`${b} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},p=async(g,b)=>{const R=h(g,"Migration"),f=await Go(g),{headers:O}=await i(g,b),U=await R.orchestrateMigration(u,{args:f.args,defaultShardKey:t,functionPath:f.functionPath,headers:O,table:f.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},m=async(g,b)=>{const R=h(g,"Rank"),f=await Qo(g),{headers:O}=await i(g,b),U=await R.orchestrateRank(u,{headers:O,index:f.index,partitionKey:f.partitionKey,rowId:f.rowId,sortValues:f.sortValues,table:f.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},S=async(g,b)=>{const R=h(g,"Rank page"),f=await Vo(g),{headers:O}=await i(g,b),U=await R.orchestrateRankPage(u,{...f,headers:O});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},A=async(g,b)=>{const R=h(g,"Shard-traffic"),f=await Jo(g),{headers:O}=await i(g,b),U=await R.orchestrateShardTraffic(u,{headers:O,table:f.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},T=async(g,b)=>{if($(g,"POST","PITR"),!r(g))throw new d("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const R=await qo(g),{headers:f}=await i(g,b),O=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:R.args,functionPath:R.functionPath}),headers:f,method:"POST"});return n(u,R.shardKey??t,O)};return{[Ho]:p,[Lo]:T,[Mo]:m,[$o]:S,[jo]:A}},Xo=1,Zo=0,ea=32,ta=512,na=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,ra=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>ta)return;const n=t.split(",");if(!(n.length>ea)){for(const r of n)if(!na.test(r.trim()))return;return t}},oa=e=>{const t=Qn(e.headers.get("traceparent"));if(t===void 0)return;const n=ra(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},aa=(e,t={})=>{const n=oa(e),r=t.trustInbound===!0?n:void 0,a=Ie(8),i=r?.traceId??Ie(16),u=pr(t.sampling,r===void 0?a:i),h=u.isTraced&&(r===void 0||r.sampled);return{decision:u,ignoredUpstream:n!==void 0&&r===void 0,trace:{sampled:h,spanId:a,traceFlags:h?Xo:Zo,traceId:i,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState}}}},sa=(e,t)=>{t.traceparent=Gn(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},ia=(e,t)=>{let n;return()=>{if(n===void 0){const r=Jn(e),a=t===void 0?void 0:t.cf;n=zn(Vn(r),Wn(r,a))}return n}},ca="/_lunora/admin/scheduled",da="/_lunora/admin/scheduled/status",ua="/_lunora/admin/scheduled/ws",la="/_lunora/admin/scheduled/cancel",ha="/_lunora/admin/scheduled/dead",fa="/_lunora/admin/scheduled/dead/retry",pa="/_lunora/admin/scheduled/dead/cancel",ma="/_lunora/admin/scheduled/pool/release",wa=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:r,schedulerInstanceName:a}=e,i=(m,S)=>A=>{if(A.method!=="GET")throw new d(`${S} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(A.url).searchParams.get("cursor"),g=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return r(A).fetch(new Request(`https://scheduler.internal${m}${g}`,{method:"GET"}))},u=(m,S,A=S)=>async T=>{if(T.method!=="POST")throw new d(`${A} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const g=r(T),b=await he(T,S);if(typeof b?.id!="string"||b.id==="")throw new d(`${S} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return g.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:b.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async m=>{if(m.method!=="POST")throw new d("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const S=r(m),A=await he(m,"Scheduled pool-release");if(typeof A?.pool!="string"||A.pool==="")throw new d("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const T=typeof A.id=="string"&&A.id!==""?A.id:void 0;return S.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(T===void 0?{pool:A.pool}:{id:T,pool:A.pool}),headers:{"content-type":"application/json"},method:"POST"}))},p=async m=>{if(m.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(m))throw new d("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const S=n();return ge(S,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[la]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[pa]:u("/dead/cancel","Scheduled dead-letter action"),[ha]:i("/dead","Scheduled dead-letter"),[fa]:u("/dead/retry","Scheduled dead-letter action"),[ca]:i("/list","Scheduled-list"),[ma]:h,[da]:i("/status","Scheduler-status"),[ua]:p}},ga=(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},vt={mtls:e=>ga(e,"tlsClientAuth","certVerified")==="SUCCESS"},ya=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(vt,e)?vt[e]:void 0)??(()=>!1),ba=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.'))}},_a="/_lunora/admin/vector/indexes",Ra="/_lunora/admin/vector/query",Ea=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=async i=>{$(i,"GET","Vector-indexes");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async i=>{$(i,"POST","Vector-query");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new d("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const p=await t(i);if(typeof p.name!="string"||p.name==="")throw new d("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof p.text!="string"||p.text==="")throw new d("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 d("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const m=await u.queryIndex({name:p.name,text:p.text,topK:p.topK});return Response.json(m,{headers:{"content-type":"application/json"},status:200})};return{[_a]:r,[Ra]:a}},Sa="/_lunora/admin/workflows/instances",Aa="/_lunora/admin/workflows/instance",Ta="/_lunora/admin/workflows/status",Oa={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},va=e=>e!==null&&Object.hasOwn(Oa,e)?e:void 0,kt=(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 d(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},It=()=>{throw new d("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},ka=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,r=async(u,h,p)=>{$(u,"GET","Workflows instances"),t(u);const m=n(h);if(!m)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const S=Ge(p,"name"),A=va(p.searchParams.get("status"));return Response.json(await m.listInstances({page:kt(p,"page"),perPage:kt(p,"perPage"),status:A,workflowName:S}))},a=async(u,h,p)=>{$(u,"GET","Workflows instance"),t(u);const m=n(h);return m?Response.json(await m.getInstance({instanceId:Ge(p,"id"),workflowName:Ge(p,"name")})):It()},i=async(u,h)=>{$(u,"POST","Workflows status"),t(u);const p=n(h);if(!p)return It();const m=await u.json().catch(()=>{});if(typeof m?.name!="string"||m.name===""||typeof m.id!="string"||m.id==="")throw new d("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:S}=m;if(S!=="pause"&&S!=="resume"&&S!=="terminate")throw new d("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await p.setInstanceStatus({action:S,instanceId:m.id,workflowName:m.name}))};return{[Aa]:a,[Sa]:r,[Ta]:i}},Ia={[Xt]:Zt,[or]:rr},Pt="/_lunora/rpc",Pa="/_lunora/rpc-batch",Na="/_lunora/ws",be=(e,t,n)=>({resourceAttributes:ia(e,t),...n===void 0?{}:{waitUntil:n}}),Qe=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Nt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),ze=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let r;try{r=new URL(e.url)}catch{return{method:t,userAgent:n}}const a=r.port===""?void 0:Number(r.port);return{host:r.hostname,method:t,path:r.pathname,port:Number.isNaN(a)?void 0:a,scheme:r.protocol.replace(":",""),userAgent:n}},Dt="/_lunora/voice/",Da="/_lunora/scheduler/dispatch",Ua="/_lunora/admin/cron-jobs/run",Ca="/_lunora/admin/ws-token",Ba="/_lunora/admin/",xa="/_lunora/",Ha="/_lunora/migrate",La="/_lunora/status",Ma=e=>e.startsWith(Ba)||e===Ha,$a="__lunora_relation__:",Se=e=>{if(e.startsWith($a))throw new d("`__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,ja=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}}},Ut="/api/auth",Ka="__lunora_admin__:recordAuthEvent",Fa="__lunora_admin__:listPushSubscriptions",Ga=["/sign-in","/sign-up","/callback"],Qa=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const r=e.slice(n.length);return Ga.some(a=>r===a||r.startsWith(`${a}/`))},za=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},Te=(e,t,n,r)=>{const a=Hn(n),i=a?n.code:"INTERNAL_SERVER_ERROR",u=a?n.status:500,h=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:h,status:u},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},Wa=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},Ct=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Va=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},qe=new WeakMap,de=async(e,t,n,r=qe.get(e))=>{const a={"content-type":"application/json"},i=e.headers.get("authorization"),u=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),p=e.headers.get("x-lunora-mutation-id"),m=e.headers.get("x-lunora-client-id"),S=e.headers.get("x-lunora-client-seq");i&&(a.authorization=i),u&&(a.cookie=u),h&&(a["x-d1-bookmark"]=h),p&&(a["x-lunora-mutation-id"]=p),m&&(a["x-lunora-client-id"]=m),S&&(a["x-lunora-client-seq"]=S);const A=e.headers.get("cf-connecting-ip");if(A&&(a["x-lunora-client-ip"]=A),!n)return{claims:null,headers:a,identity:null,userId:null};const T=await n(e,t,r);if(!T||typeof T.userId!="string"||T.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=Kn(T.userId);const g=Wa(T);g!==void 0&&(a["x-lunora-identity-exp"]=String(g));const{userId:b,...R}=T,f=Object.keys(R).length>0?R:null;return f&&(a["x-lunora-identity"]=Fn(f)),{claims:f,headers:a,identity:T,userId:b}},Ja=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),qa=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new d("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new d("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new d("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!Ja.has(n.kind))throw new d("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new d("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new d("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Ya=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},We=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new d("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new d(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},Xa=async e=>{const t=await Kt(e);let n;try{n=JSON.parse(t)}catch{throw new d("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new d("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const r=n;if(r.args!==void 0&&jt(r.args,"RPC"),r.shardKey!==void 0&&typeof r.shardKey!="string")throw new d("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,i=qa(a.fanOut),u=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==i.table)throw new d("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},Oe=new Map,Za=5e3,es=4096,ts=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 a=0;try{const i=await ge(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const h=(await i.json()).relayCount;typeof h=="number"&&h>0&&(a=Math.floor(h))}}catch{a=0}return Lt(Oe,es),Oe.set(t,{expiresMs:n+Za,relayCount:a}),a},Bt=(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"}),ns=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],rs=(e,t)=>{for(const n of ns){e.delete(n);const r=t[n];r!==void 0&&e.set(n,r)}},xt=(e,t)=>{const n=new Headers(e.headers),r=[...n.keys()];for(const a of r)a.startsWith("x-lunora-")&&n.delete(a);return rs(n,t),n},os=async(e,t,n)=>e.length===0||n.length===0?!1:Ze(await zt(e,t),n),Ht=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...a]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:Ze(t,a.join(" ").trim())},as=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 jr(t,r)?!0:n?!1:Ze(t,r)},ss=(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 lr(`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)},is=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new d("`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})},en=e=>{is(e);const t=ya(e.trustInboundTraceContext),n=ba(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",a=hr(e.resolveIdentity,e.identity),i=lt(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:lt(e.schedulerDO,e.jurisdiction);let h=!1;const p=o=>{if(o===void 0||e.jurisdiction===void 0)return o;h||(h=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},m=async(o,s,l,c=e.shardRegion?.(s))=>ge(o,s,p(c)).fetch(l);let S;const A=()=>e.adminToken??S;let T;const g=()=>e.requireEphemeralWsToken??T??!0;let b;const R=o=>{const s=o??{};if(b??=Bt(o,e.shardDO),T===void 0&&e.requireEphemeralWsToken===void 0){const c=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(T=Lr(c,!0))}if(S!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(S=l)},f=new WeakSet,O=o=>Ht(o,A())||f.has(o),U=async o=>{if(!(e.adminGate===void 0||f.has(o)))try{await Ae(e.adminGate(o,qe.get(o)))&&f.add(o)}catch{}},M=async(o,s)=>{const l=await de(o,s,e.resolveIdentity);if(f.has(o)&&l.headers.authorization===void 0){const c=A();c!==void 0&&(l.headers.authorization=`Bearer ${c}`)}return l};let I=!1,K=!1;const j=()=>{K||(K=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},W=o=>{if(!e.allowUnauthenticatedShardAccess){const s=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new d(`${o} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}I||(I=!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("")))},C=async(o,s)=>{if(s.includes(Ve)||s.includes(Je))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(e.authorizeShard){if(!await Ae(e.authorizeShard({identity:o,shardKey:s})))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==r&&W("shard")},V=Yo({defaultShard:r,forwardToShard:m,isAdmin:O,queryCoordinator:e.queryCoordinator,resolveForwardContext:M,shardDO:i}),F=async(o,s,l,c,w)=>{Se(o);const y={"content-type":"application/json","x-lunora-system":"1"};return w?.userId!==void 0&&w.userId.length>0&&(y["x-lunora-userid"]=w.userId),w?.identity!==void 0&&w.identity.length>0&&(y["x-lunora-identity"]=w.identity),c!==void 0&&c.length>0&&(y["x-lunora-mutation-id"]=c),m(i,l,ve(o,s,y))},J=async(o,s,l,c,w)=>{const y=l?.[o];if(!y||typeof y.create!="function")throw new d(`${c} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(yr(s))throw new d(`${c} params ${br}`,{code:"BAD_REQUEST",status:400});try{await y.create(w===void 0?{params:s}:{id:w,params:s})}catch(P){if(!Er(P))throw P}},ee=async(o,s)=>{if(o.workflow){await J(o.workflow,o.args??{},s,`cron job "${o.name}"`);return}if(o.functionPath===void 0)throw new d(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const l=await F(o.functionPath,o.args??{},o.shardKey??r);if(!l.ok)throw new d(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},L=o=>{if(!O(o))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},q=(o,s,l)=>{if(L(o),s===void 0)throw new d(l.message,{code:l.code,status:400});return s},G=async(o,s,l,c)=>{const w=e.cronJobs?.[o];if(!w)return 0;for(const y of w)try{await ee(y,s)}catch(P){l.push(c(P))}return w.length},fe=async(o,s)=>{if(L(o),$(o,"POST","cron-jobs run"),!e.cronJobs)throw new d("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await te(o),c=typeof l.name=="string"?l.name:"";if(c==="")throw new d("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const w=Object.values(e.cronJobs).flat().find(y=>y.name===c);if(!w)throw new d(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await ee(w,s),Response.json({name:c,ran:!0},{status:200})},ae=async o=>{const s=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!s||!u||typeof o.id!="string")return;const l=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await ge(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},_e=async(o,s)=>{$(o,"POST","Scheduler dispatch");const l=await Kt(o),c=s??{},w=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,y=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),P=o.headers.get("x-lunora-scheduler-signature");let v=!1;if(P&&w?v=await os(w,l,P):y&&(v=Ht(o,y)),!v)throw new d("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let E;try{E=JSON.parse(l)}catch{throw new d("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const _=E??{},D=_.args??{},H=typeof _.id=="string"&&_.id.length>0?_.id:void 0;if(typeof _.workflow=="string"&&_.workflow.length>0)return await J(_.workflow,D,s,"scheduled workflow",H),await ae(_),Response.json({ok:!0},{status:200});if(typeof _.functionPath!="string"||_.functionPath.length===0)throw new d("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const x=typeof _.shardKey=="string"&&_.shardKey.length>0?_.shardKey:r,X=ja(o),B=await F(_.functionPath,D,x,H,X);return await ae(_),B},Pe=Qr({assertAdmin:L,getReader:()=>e.authAuditReader}),Ne=async(o,s)=>{L(o);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:ke({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const c=s?.kind,w=s?.userId,y=s?.limit,P=c==="fcm"||c==="web-push"?c:void 0,v=typeof w=="string"&&w!==""?w:void 0,E=typeof y=="number"&&Number.isFinite(y)?Math.trunc(y):0,_=E>0?Math.min(E,1e3):1e3,H=(await l.list({kind:P,limit:_,userId:v})).filter(x=>P!==void 0&&x.kind!==P?!1:v===void 0||(x.userId??null)===v).map(({keys:x,token:X,...B})=>B);return Response.json({result:ke({subscriptions:H})},{headers:{"content-type":"application/json"},status:200})},se=async(o,s)=>{if(!s.fanOut&&!(s.functionPath!==gt&&s.functionPath!==Fa))return await U(o),s.functionPath===gt?Pe(o,s.args??{}):Ne(o,s.args)},tn=wo({applyGlobals:e.applyGlobals,assertAdmin:L,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:r,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:q,resolveForwardContext:M,shardDO:i,streamExportRows:(o,s,l,c)=>Jt(e,o,s,l,c,i),streamingImport:(o,s)=>Ro(o,e,s,i),syncGlobals:e.syncGlobals}),De=(o,s)=>{const l=o.searchParams.get(s);return l===null||l===""?void 0:l},Ue=o=>{const s=new URL(o.url),l=s.searchParams.get("limit"),c=s.searchParams.get("offset"),w=l===null?void 0:Number.parseInt(l,10),y=c===null?void 0:Number.parseInt(c,10);return{limit:w!==void 0&&Number.isFinite(w)&&w>=0?w:void 0,offset:y!==void 0&&Number.isFinite(y)&&y>=0?y:void 0}},nt=()=>{if(u===void 0)throw new d("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},nn=wa({checkWsAdmin:async o=>O(o)||as(o,A(),g()),requireSchedulerNamespace:nt,resolveSchedulerStub:o=>(L(o),ge(nt(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),rn=ka({assertAdmin:L,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),on=nr({assertAdmin:L,parsePaging:Ue,queryParameter:De,readBodyBytes:Yn,requireAdminOption:q,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),an=oo({options:e,readJsonBody:te,requireAdminOption:q}),sn=Ea({readJsonBody:te,requireAdminOption:q,vectorIntrospector:e.vectorIntrospector}),cn=xo({kvIntrospector:e.kvIntrospector,readJsonBody:te,requireAdminOption:q}),dn=fr({logArchive:e.logArchive,readJsonBody:te,requireAdminOption:q}),un=Uo({assertAdmin:L,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ue,queryParameter:De,requireAdminOption:q}),ln=o=>{const s=[],l=i??o?.SHARD;if(l!==void 0&&s.push(ur("durable-object:default",l,r)),e.health?.disableBindingProbes!==!0)for(const[c,w]of Object.entries(o??{})){const y=ss(c,w);y!==void 0&&s.push(y)}for(const c of e.health?.probes??[])s.push(c);return s},hn=dr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:O,resolveProbes:ln}),fn=o=>{const s=e.schedulerInstanceName??"default",l=()=>ge(o,s),c=async(E,_)=>{const D=await l().fetch(new Request(`https://scheduler.internal${E}`,_));if(!D.ok)throw new d(`ctx.scheduler: SchedulerDO ${E} failed (${String(D.status)}): ${await D.text()}`,{code:"INTERNAL",status:500});return await D.json()},w=async(E,_)=>await c(E,{body:JSON.stringify(_),headers:{"content-type":"application/json"},method:"POST"}),y=E=>{const _=E;if(_==null)throw new d("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof _.binding=="string"&&_.binding.length>0)return{workflow:_.binding};if(typeof _.__lunoraRef=="string")return{functionPath:_.__lunoraRef};throw new d("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},P=async()=>await _r(async E=>c(E===void 0?"/list":`/list?cursor=${encodeURIComponent(E)}`,{method:"GET"})),v=async(E,_,D={})=>{const{id:H}=await w("/schedule",{args:D,scheduledFor:E,...y(_)});return H};return{cancel:async E=>await w("/cancel",{id:E}),get:async E=>await c(`/get?id=${encodeURIComponent(E)}`,{method:"GET"}),list:P,runAfter:async(E,_,D)=>{if(!Number.isFinite(E)||E<0)throw new d("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await v(Date.now()+E,_,D)},runAt:async(E,_,D)=>{if(!Number.isFinite(E))throw new d("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await v(E,_,D)}}},pn=async(o,s,l)=>{const{claims:c,headers:w,userId:y}=await de(o,s,a),P=be(s,o,_=>l.waitUntil?.(_)),v=_=>async(D,H={})=>{const x=D.__lunoraRef;if(typeof x!="string")throw new d("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Se(x);const X=await Ee(o,x,ke(H),_,{...w,"x-lunora-system":"1"},P),B=await X.json();if(B.error)throw new d(B.error.message??"shard RPC failed",{code:B.error.code??"INTERNAL",status:X.status});return Mt(B.result)},E=v(r);return{auth:{getIdentity:()=>Promise.resolve(c),userId:y},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),forShard:_=>{const D=v(_);return{runAction:D,runMutation:D,runQuery:D}},runAction:E,runMutation:E,runQuery:E,...u===void 0?{}:{scheduler:fn(u)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:gr(e.storage(s))}}},mn=async(o,s,l)=>{if(!e.httpRouter)return;const c=await pn(o,s,l);try{return await e.httpRouter.fetch(o,{...s,__lunoraCtx:c},l)}catch(w){return console.error("[lunora] httpRouter (SSR) handler threw:",w),new Response("Internal Server Error",{status:500})}},wn=async(o,s,l)=>{if(o.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=ft(o,ie);if(c)return c;const w=l.searchParams.get("shard")??r,{headers:y,identity:P}=await de(o,s,a);await C(P,w);const v=xt(o,y),E=Bt(s,e.shardDO);if(E!==void 0){v.set("x-lunora-shard-binding",E);const _=await ts(i,w);if(_>0){const D=Ur(w,Math.floor(Math.random()*_));return m(i,D,new Request(o,{headers:v}),pt(o))}}return m(i,w,new Request(o,{headers:v}))},gn=async(o,s,l)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const w=ft(o,ie);if(w)return w;let y;try{y=decodeURIComponent(l.pathname.slice(Dt.length))}catch{return new Response("Unknown voice agent",{status:404})}const P=Object.hasOwn(c,y)?c[y]:void 0;if(P===void 0)return new Response("Unknown voice agent",{status:404});const v=l.searchParams.get("threadKey");if(v===null||v.length===0)return new Response("Missing threadKey",{status:400});const{headers:E,identity:_}=await de(o,s,a);if(e.authorizeShard){if(!await Ae(e.authorizeShard({identity:_,shardKey:v})))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else W("shard");const D=xt(o,E);return m(P,v,new Request(o,{headers:D}))},yn=async(o,s,l)=>{if(e.authorizeFanOut){if(!await Ae(e.authorizeFanOut(l,o.table,s)))throw new d("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new d("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new d("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});W("fan-out")},Re=async(o,s)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await yn(o.fanOut,o.functionPath,s);return}await C(s,o.shardKey??r)}},bn=(o,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){j();return}if(e.functions[s]?.kind!=="query"||l.includes(Je)||l.includes(Ve))return;const c=pt(o);return c===void 0?void 0:{name:Cr(l,c),region:c}},_n=async(o,s,l,c,w)=>{const y=bn(o,s,c);if(y!==void 0){const P={...w,"x-lunora-replica-read":"1",...b===void 0?{}:{"x-lunora-shard-binding":b}},v=Br(o.headers.get("x-lunora-min-seq"));v!==void 0&&(P["x-lunora-min-seq"]=String(v));const E=await m(i,y.name,ve(s,l,P),y.region);if(E.status!==421)return E}return m(i,c,ve(s,l,w))},Ee=async(o,s,l,c,w,y)=>{const P=Date.now(),{observability:v,sampling:E}=e,_=ze(o),{decision:D,ignoredUpstream:H,trace:x}=aa(o,{...E===void 0?{}:{sampling:E},trustInbound:t(o)});H&&n();const X={...w,"x-lunora-sample-errors":D.keepErrors?"1":"0"};sa(x,X);try{const B=await _n(o,s,l,c,X);ce(v,{..._,...Nt(x),durationMs:Date.now()-P,functionPath:s,ok:B.ok,shardKey:c,...B.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(B.status)}`,status:B.status}}},y,void 0,{isTraced:x.sampled,keepErrors:D.keepErrors});const ne=new Response(B.body,{headers:B.headers,status:B.status,statusText:B.statusText});return ne.headers.set("x-lunora-shard-key",c),ne}catch(B){throw ce(v,{..._,...Nt(x),...Te(s,Date.now()-P,B,{shardKey:c})},y,void 0,{isTraced:x.sampled,keepErrors:D.keepErrors}),B}},Rn=o=>{if(o.fanOut&&o.shardKey)throw new d("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(o.fanOut||Se(o.functionPath),o.fanOut&&!e.queryCoordinator)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},En=async(o,s,l)=>{$(o,"POST","RPC");const c=await Xa(o);Ya(s,c),Rn(c);const w=await se(o,c);if(w!==void 0)return w;const{headers:y,identity:P}=await de(o,s,a);await Re(c,P);const v=We(c,e);{const E=Date.now(),{observability:_}=e,D=ze(o),H=be(s,o,l&&(B=>l.waitUntil?.(B)));if(c.fanOut){const B=e.queryCoordinator;if(!B)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ne=await B.fanOut(i,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:y});return ce(_,{durationMs:Date.now()-E,fanOut:{failed:ne.failed,shards:ne.ok+ne.failed,table:c.fanOut.table},functionPath:c.functionPath,...D,ok:!0},H),Response.json(ne,{headers:{"content-type":"application/json"},status:200})}catch(ne){throw ce(_,{...Te(c.functionPath,Date.now()-E,ne,{fanOut:{table:c.fanOut.table}}),...D},H),ne}}const x=c.shardKey??r,X=()=>Ee(o,c.functionPath,c.args??{},x,y,H);return v&&e.x402Charge?e.x402Charge(o,{functionPath:c.functionPath,price:v.price},X,Qe(l)):X()}},Sn=async(o,s,l)=>{$(o,"POST","RPC batch");const c=await te(o),{calls:w}=c;if(!Array.isArray(w))throw new d("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:y,identity:P}=await de(o,s,a),v=so(w,r);for(const Q of v.values())for(const z of Q)if(e.functions?.[z.functionPath]?.x402)throw new d(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${Pt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...v.entries()].flatMap(([Q,z])=>z.map(oe=>Re({args:oe.args,functionPath:oe.functionPath,shardKey:Q},P))));const{observability:E}=e,_=be(s,o,l&&(Q=>l.waitUntil?.(Q))),D=ze(o),H=[],x=[],X=(Q,z,oe,ue)=>({body:{error:{code:oe,message:ue}},id:Q.id,status:z}),B=(Q,z,oe,ue,pe)=>{for(const Y of Q)ce(E,pe(Y),_),H.push(X(Y,z,oe,ue))},ne=(Q,z,oe,ue,pe)=>{for(const Y of Q){const me=ue.get(Y.id)??pe,ye=me<400;ce(E,{durationMs:oe,functionPath:Y.functionPath,...D,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},_)}};await Promise.all([...v.entries()].map(async([Q,z])=>{const oe=new Headers(y);oe.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:oe,method:"POST"}),pe=Date.now();let Y;try{Y=await m(i,Q,ue)}catch(Z){const He=Date.now()-pe,{body:it}=Ln(Z,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});B(z,502,it.code,it.message,xn=>({...Te(xn.functionPath,He,Z,{shardKey:Q}),...D}));return}const me=Date.now()-pe,ye=Y.headers.get("x-d1-bookmark");ye&&x.push(ye);let Be;try{Be=await Y.json()}catch{const Z=`shard batch returned a non-JSON response (${String(Y.status)})`;B(z,Y.status,"SHARD_ERROR",Z,He=>({durationMs:me,error:{code:"SHARD_ERROR",message:Z,status:Y.status},functionPath:He.functionPath,...D,ok:!1,shardKey:Q}));return}const xe=Array.isArray(Be.results)?Be.results:[],Cn=new Map(xe.map(Z=>[Z.id,Z.status??Y.status])),Bn=new Set(xe.map(Z=>Z.id));ne(z,Q,me,Cn,Y.status),H.push(...xe);for(const Z of z)Bn.has(Z.id)||H.push(X(Z,Y.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Z.id)}`))}));const at={"content-type":"application/json"},[st]=x;return x.length===1&&st!==void 0&&(at["x-d1-bookmark"]=st),Response.json({results:H},{headers:at,status:200})},An=async(o,s,l,c={},w={})=>{try{const y=l.__lunoraRef;if(typeof y!="string")throw new d("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Se(y);const{headers:P,identity:v}=await de(o,s,a,w.context),E={args:c,functionPath:y,shardKey:w.shardKey};await Re(E,v);const _=w.shardKey??r,D=be(s,o,w.waitUntil),H=()=>Ee(o,y,c,_,P,D),x=We(E,e);return x&&e.x402Charge?await e.x402Charge(o,{functionPath:y,price:x.price},H,Qe(w.waitUntil?{waitUntil:w.waitUntil}:w.context)):await H()}catch(y){return ct(y)}},rt=async(o,s,l)=>{const{observability:c}=e,w=Date.now(),y=Ie(16),P=Ie(8),v=Ct(s);try{const E=await l();return ce(c,{durationMs:Date.now()-w,functionPath:o,ok:!0,spanId:P,traceId:y},v),E}catch(E){throw ce(c,{...Te(o,Date.now()-w,E,{}),spanId:P,traceId:y},v),E}finally{ut(c,v)}},Tn=async(o,s,l)=>{R(s);const c=[],w=_=>_ instanceof Error?_:new Error(String(_)),y=e.crons?.[o.cron];if(y)try{await y(o,s,l)}catch(_){c.push(w(_))}const P=await G(o.cron,s,c,w),v=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron;if(v)try{await eo(e,i,A(),o)}catch(_){c.push(w(_))}if(!y&&P===0&&!v){const _=[...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: ${_.length===0?"(none)":_.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[E]=c;if(c.length===1&&E)throw E;if(c.length>1)throw new AggregateError(c,`scheduled("${o.cron}") had ${String(c.length)} failure(s)`)},On=async(o,s)=>{try{const l=o??{},c=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await m(i,r,ve(Ka,{outcome:s},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},vn=async(o,s,l,c)=>{if(!e.authHandler)return;const w=await e.authHandler(o);if(!w)return;const y=e.authBasePath??Ut;return Qa(l.pathname,y)&&c.waitUntil?.(On(s,w.status>=400?"fail":"ok")),w},kn=async({args:o,env:s,functionPath:l,request:c,shardKey:w,waitUntil:y})=>{jt(o,"REST");const P={functionPath:l,...w===void 0?{}:{shardKey:w}},{headers:v,identity:E}=await de(c,s,a);await Re(P,E);const _=w??r,D=be(s,c,y),H=()=>Ee(c,l,o,_,v,D),x=We(P,e);return x&&e.x402Charge?e.x402Charge(c,{functionPath:l,price:x.price},H,Qe({waitUntil:y})):H()},In=qn({functions:e.functions??{},invoke:kn,readJsonBody:te,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ce=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Pn={[La]: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"}}),[Na]:(o,s,l)=>wn(o,s,l),[Pt]:(o,s,l,c)=>En(o,s,c),[Pa]:(o,s,l,c)=>Sn(o,s,c),[Da]:(o,s)=>_e(o,s),[Ua]:(o,s)=>fe(o,s),[Ca]:async o=>{$(o,"POST","ws-token"),L(o);const s=A();if(s===void 0)throw new d("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await $r(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...V,...tn,...nn,...rn,...on,...an,...sn,...cn,...dn,...un,...hn,...In,...Gr({assertAdmin:L,getAuthAdmin:()=>e.authAdmin,parsePaging:Ue,queryParameter:De,readJsonBody:te})};let ie=ht(e.security),ot=!1;const Nn=o=>{ot||(ot=!0,ie=ht(e.security,o??{}))},Dn=async(o,s)=>{Ma(s)&&await U(o)},Un=async(o,s,l)=>{qe.set(o,l);const c=new URL(o.url);if((c.pathname.startsWith(xa)||e.authHandler!==void 0&&za(c.pathname,e.authBasePath??Ut))&&(o.method==="POST"||o.method==="PUT")){const E=Number(o.headers.get("content-length")??""),_=Ia[c.pathname]??$t;if(Number.isFinite(E)&&E>_)throw new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const y=await vn(o,s,c,l);if(y)return y;if(Ce){const E=`${o.method} ${c.pathname}`,_=Ce[E]??Ce[c.pathname];if(_)return _(o,s,l)}const P=Pn[c.pathname];if(P)return await Dn(o,c.pathname),P(o,s,c,l);if(e.voiceAgents!==void 0&&c.pathname.startsWith(Dt))return gn(o,s,c);const v=await mn(o,s,l);return v||new Response("Not found",{status:404})};return{async fetch(o,s,l){e.passThroughOnException&&l.passThroughOnException?.(),Nn(s),R(s);const c=mr(o,ie);if(c)return c;const w=wr(o,ie);if(w)return Me(w,o,ie);try{const y=await Un(o,s,l);return Me(y,o,ie)}catch(y){return Me(ct(y),o,ie)}finally{ut(e.observability,Ct(l))}},async queue(o,s,l){await rt(`queue:${Va(o)}`,l,async()=>{await e.queue?.(o,s,l)})},async scheduled(o,s,l){await rt(`cron:${o.cron}`,l,async()=>{await Tn(o,s,l)})},serverQuery:An}},cs=e=>en(e),ds=e=>typeof e=="function"?{fetch:e}:e,us=e=>!!(e.crons??e.cronJobs??e.backupCron),Ds=(e,t)=>{const n=ds(e),r=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=u=>{const h=cs({...u,httpRouter:n});return r!==void 0&&!us(u)?{...h,scheduled:async(p,m,S)=>{await r(p,m,S)}}:h};if(typeof t!="function")return a(t);const i=t;return{fetch:(u,h,p)=>a(i(h)).fetch(u,h,p),queue:(u,h,p)=>a(i(h)).queue?.(u,h,p)??Promise.resolve(),scheduled:(u,h,p)=>a(i(h)).scheduled(u,h,p),serverQuery:(u,h,p,m,S)=>a(i(h)).serverQuery(u,h,p,m,S)}},ls=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new d("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},Us=(e={})=>(t,n,r)=>en(ls(e,n)).fetch(t,n,r??Mn),Cs=e=>e;export{gt as GET_AUTH_AUDIT_LOG_OP,Mn as NOOP_EXECUTION_CONTEXT,Hs as composeIdentityResolvers,cs as composeWorker,Us as createLunoraHandler,en as createWorker,Cs as defineRpcEnvelope,ts as probeRelayCount,ls as resolveLunoraOptions,Ls as routeIdentityResolvers,Ds as withFrameworkWorker};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as c,a as u}from"./identity-header-C4Z5pldl.mjs";import{d as f}from"./wire-codec-
|
|
1
|
+
import{e as c,a as u}from"./identity-header-C4Z5pldl.mjs";import{d as f}from"./wire-codec-BX_-4Tmg.mjs";import{LunoraError as s}from"./LunoraError-DksAgIpa.mjs";const l="/_lunora/rpc",h=e=>{const a={"content-type":"application/json"};return e.userId!==void 0&&e.userId.length>0&&(a["x-lunora-userid"]=c(e.userId)),e.identity!==void 0&&(a["x-lunora-identity"]=u(e.identity)),a},d=async(e,a,o)=>{const t=await(e.fetch??globalThis.fetch)(new Request(`${e.origin}${l}`,{body:JSON.stringify(a),headers:h(e),method:"POST"}));if(!t.ok)throw new s(`cross-shard relation ${o} failed: worker returned ${String(t.status)}`);const r=await t.json();if(typeof r.failed=="number"&&r.failed>0){const i=(typeof r.ok=="number"?r.ok:0)+r.failed;throw new s(`cross-shard relation ${o} failed on ${String(r.failed)} of ${String(i)} shard(s) — refusing to return a partial result`)}return f(r.data)},_=e=>({crossShardCounter:async(n,t)=>{const r=await d(e,{args:{table:n,where:t},fanOut:{merge:{kind:"sum"},table:n},functionPath:"__lunora_relation__:count"},"count");return typeof r=="number"?r:0},crossShardReader:async(n,t)=>{const r=await d(e,{args:{...t,table:n},fanOut:{merge:{kind:"concat"},table:n},functionPath:"__lunora_relation__:read"},"read");return{continueCursor:null,isDone:!0,page:Array.isArray(r)?r:[]}}});export{_ as createCrossShardRelationCapabilities};
|
package/dist/packem_shared/{createKvCursorStore-Irk1yRJm.mjs → createKvCursorStore-CiXokqz5.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as o,a as s,d as t,r as i,b as n,s as p,w as S}from"./export-tap-
|
|
1
|
+
import{c as o,a as s,d as t,r as i,b as n,s as p,w as S}from"./export-tap-mRfLykiL.mjs";import"./portable-json-DcwKZHQ7.mjs";export{o as createKvCursorStore,s as createMemoryCursorStore,t as defineExportSink,i as r2Sink,n as runExportTap,p as sanitizeChange,S as webhookExportSink};
|
package/dist/packem_shared/{createShardClient-BaZZLHHu.mjs → createShardClient-CECfFWIM.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as n}from"@lunora/errors";import{e as S,a as w}from"./identity-header-C4Z5pldl.mjs";import{e as g,d as f}from"./wire-codec-
|
|
1
|
+
import{LunoraError as n}from"@lunora/errors";import{e as S,a as w}from"./identity-header-C4Z5pldl.mjs";import{e as g,d as f}from"./wire-codec-BX_-4Tmg.mjs";import{applyJurisdiction as p,resolveShard as N}from"./applyJurisdiction-C0ddU7Tg.mjs";const I=e=>{if(typeof e=="string")return e;const t=e?.__lunoraRef;if(typeof t!="string"||t.length===0)throw new n("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return t},x=e=>{const t=new n(e.code,e.message);return e.data!==void 0&&(t.data=f(e.data)),t},$=(e,t={})=>{const l=p(e,t.jurisdiction),m=t.system??!0,c=r=>$(e,{...t,...r});return{as:r=>c({as:r}),asSystem:()=>c({as:void 0}),call:async(r,y,o)=>{const d=I(r),h=o?.shardKey??t.shardKey;if(h===void 0||h.length===0)throw new n("INTERNAL",`createShardClient: no shard key for "${d}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const s={"content-type":"application/json"};m&&(s["x-lunora-system"]="1"),t.as&&(s["x-lunora-userid"]=S(t.as.userId),t.as.claims&&(s["x-lunora-identity"]=w(t.as.claims))),o?.mutationId!==void 0&&o.mutationId.length>0&&(s["x-lunora-mutation-id"]=o.mutationId);const a=await N(l,h).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:g(y??{}),functionPath:d}),headers:s,method:"POST"})),u=a.statusText?` ${a.statusText}`:"";let i;try{i=await a.json()}catch{throw new n("INTERNAL",`createShardClient: shard response for "${d}" was not JSON (status ${String(a.status)}${u})`)}if("error"in i)throw x(i.error);if(!a.ok)throw new n("INTERNAL",`createShardClient: shard call "${d}" failed (status ${String(a.status)}${u})`);return f(i.result)},forShard:r=>c({shardKey:r})}};export{$ as createShardClient};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as O}from"./LunoraError-DksAgIpa.mjs";const y=new Set(["0","disabled","false","no","off"]),E=new Set(["1","enabled","on","true","yes"]),d=e=>typeof e=="string"&&y.has(e.trim().toLowerCase()),S=e=>typeof e=="string"&&E.has(e.trim().toLowerCase()),L="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",A=e=>{const o=["base-uri 'none'","object-src 'none'"];return e==="DENY"?o.push("frame-ancestors 'none'"):e==="SAMEORIGIN"&&o.push("frame-ancestors 'self'"),o.join("; ")},b="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",u=["Authorization","Content-Type","X-D1-Bookmark","X-Lunora-Client-Id","X-Lunora-Client-Seq","X-Lunora-Min-Seq","X-Lunora-Mutation-Id","X-Lunora-Shard-Key"],f=["DELETE","GET","HEAD","PATCH","POST","PUT"],C=31536e3,v=new Set(["GET","HEAD","OPTIONS"]),R=e=>{if(e===!1)return;const o=e===void 0||e===!0?{}:e,s=o.maxAge??C,r=o.includeSubDomains??!0;return`max-age=${String(s)}${r?"; includeSubDomains":""}${o.preload?"; preload":""}`},D=(e,o)=>{if(e!==!1)return typeof e=="string"?{htmlValue:e,value:e}:{htmlValue:o,value:L}},_=e=>{if(e===!1)return{coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0};const o=e===void 0||e===!0?{}:e,s=o.frameOptions===!1?void 0:o.frameOptions??"SAMEORIGIN";return{coop:"same-origin",csp:D(o.csp,A(s)),enabled:!0,frameOptions:s,hsts:R(o.hsts),permissionsPolicy:o.permissionsPolicy===!1?void 0:o.permissionsPolicy??b,referrerPolicy:o.referrerPolicy===!1?void 0:o.referrerPolicy??"strict-origin-when-cross-origin"}},N=e=>{const o={allowCredentials:!1,allowedHeaders:u,allowedMethods:f,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return o;const s=e.allowCredentials??!1,r=e.allowedOrigins;let t,n;if(typeof r=="function"){const a=m=>r(m)===!0;t=a,n=a,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${s?" AND reflects matching origins with credentials (`allowCredentials: true`)":""} — ensure it matches ONLY trusted origins by exact equality; an over-broad predicate (e.g. \`() => true\`, or \`endsWith\`/\`includes\` checks) defeats the allowlist.`)}else{const a=r;if(a.includes("*")&&s)throw new O('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=i=>a.includes("*")||a.includes(i),n=i=>a.includes(i)}return{allowCredentials:s,allowedHeaders:e.allowedHeaders??u,allowedMethods:e.allowedMethods??f,enabled:!0,isAllowed:t,isExplicitlyAllowed:n,maxAge:e.maxAge??600}},H=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const o=e===void 0||e===!0?{}:e;return{allowLoopback:o.allowLoopback??!0,enabled:!0,trustedOrigins:o.trustedOrigins??[]}},I=e=>{const o=e?.LUNORA_ALLOWED_ORIGINS;if(typeof o!="string")return;const s=o.split(",").map(n=>n.trim()).filter(n=>n.length>0);return s.length===0?void 0:{allowCredentials:!s.includes("*")&&S(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:s}},j=(e,o)=>{const s=e?.headers??(d(o?.LUNORA_SECURITY_HEADERS)?!1:void 0),r=e?.csrf??(d(o?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??I(o);return{cors:N(t),csrf:H(r),headers:_(s)}},P=new Set(["127.0.0.1","::1","[::1]","localhost"]),p=e=>{try{return P.has(new URL(e).hostname)}catch{return!1}},c=e=>{if(e)try{return new URL(e).origin}catch{return}},h=(e,o,s)=>e===o||s.csrf.trustedOrigins.includes(e)||s.csrf.allowLoopback&&p(o)&&p(e)?!0:s.cors.enabled&&s.cors.isExplicitlyAllowed(e),w=(e,o,s)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:s,message:`${e} rejected: Origin ${o===void 0?"was missing":`"${o}"`} is not trusted (this worker serves "${s}"). Add it to \`security.csrf.trustedOrigins\` (or LUNORA_ALLOWED_ORIGINS) if it is yours. Behind a dev proxy this usually means the proxy rewrote the host: keep both ends on loopback, or list the dev-server origin.`,receivedOrigin:o}},{headers:{"content-type":"application/json"},status:403}),F=(e,o)=>{if(!o.csrf.enabled||v.has(e.method)||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"))??c(e.headers.get("referer"));if(!(r!==void 0&&h(r,s,o)))return w("cross-origin state-changing request",r,s)},X=(e,o)=>{if(!o.csrf.enabled||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"));if(!(r!==void 0&&h(r,s,o)))return w("cross-origin websocket upgrade",r,s)},T=["X-D1-Bookmark","X-Lunora-Edge-Cache","X-Lunora-Shard-Key"],g=(e,o)=>{const s=new Headers;return s.set("access-control-allow-origin",e),s.set("access-control-expose-headers",T.join(", ")),s.append("vary","Origin"),o.allowCredentials&&s.set("access-control-allow-credentials","true"),s},B=(e,o)=>{if(!o.cors.enabled||e.method!=="OPTIONS")return;const s=e.headers.get("origin");if(!s||!e.headers.get("access-control-request-method")||!o.cors.isAllowed(s))return;const r=g(s,o.cors),t=e.headers.get("access-control-request-headers");r.set("access-control-allow-methods",o.cors.allowedMethods.join(", "));let n;if(t===null)n=o.cors.allowedHeaders.join(", ");else{const a=new Set(o.cors.allowedHeaders.map(i=>i.toLowerCase()));n=t.split(",").map(i=>i.trim()).filter(i=>i.length>0&&a.has(i.toLowerCase())).join(", ")}return r.set("access-control-allow-headers",n),r.set("access-control-max-age",String(o.cors.maxAge)),new Response(null,{headers:r,status:204})},x=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),l=(e,o,s)=>{e.has(o)||e.set(o,s)},k=(e,o,s,r)=>{if(r.hsts!==void 0&&new URL(o.url).protocol==="https:"&&l(e,"strict-transport-security",r.hsts),l(e,"x-content-type-options","nosniff"),r.frameOptions!==void 0&&l(e,"x-frame-options",r.frameOptions),r.referrerPolicy!==void 0&&l(e,"referrer-policy",r.referrerPolicy),r.permissionsPolicy!==void 0&&l(e,"permissions-policy",r.permissionsPolicy),r.coop!==void 0&&l(e,"cross-origin-opener-policy",r.coop),r.csp!==void 0){const t=x(s)?r.csp.htmlValue:r.csp.value;t!==void 0&&l(e,"content-security-policy",t)}},U=(e,o,s)=>{const r=o.headers.get("origin");if(!(!r||!s.isAllowed(r)))for(const[t,n]of g(r,s).entries())t==="vary"?e.append("vary",n):l(e,t,n)},V=(e,o,s)=>{if(e.status===101||e.webSocket)return e;const r=new Headers(e.headers);return s.headers.enabled&&k(r,o,e,s.headers),s.cors.enabled&&U(r,o,s.cors),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})};export{V as decorateResponse,F as enforceOrigin,X as enforceWebSocketOrigin,B as handleCorsPreflight,j as resolveSecurity};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{f as K,t as j}from"./base64-Bl1_r2k1.mjs";import{t as O}from"./portable-json-
|
|
1
|
+
import{f as K,t as j}from"./base64-Bl1_r2k1.mjs";import{t as O}from"./portable-json-DcwKZHQ7.mjs";const N=new TextEncoder,q=e=>j(N.encode(JSON.stringify(e))),B=e=>{const r={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return r;try{const t=JSON.parse(new TextDecoder().decode(K(e))),o=t.s&&typeof t.s=="object"?t.s:{},s={};for(const[i,n]of Object.entries(o))typeof n=="number"&&Number.isFinite(n)&&(s[i]=n);return{g:typeof t.g=="number"&&Number.isFinite(t.g)?t.g:0,s,v:1}}catch{return r}},P=e=>{const r=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",o=t==="delete"||t==="insert"||t==="update"?t:"upsert",s=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(s===void 0?{}:{_id:s}),op:o,table:r}},M=e=>Math.max(1,Math.min(e??1e3,1e4)),D=(e,r,t)=>{for(const o of r)e.push(P(o));return t!==void 0&&r.length>=t},R=e=>new Promise(r=>{setTimeout(r,e)}),$=e=>{const r=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",o=t==="delete"||t==="insert"||t==="update"?t:"upsert",s=typeof e.id=="string"?e.id:void 0,i=e.doc&&typeof e.doc=="object"?O(e.doc):void 0,n=typeof e.seq=="number"&&Number.isFinite(e.seq)?e.seq:void 0,c=typeof e.ts=="number"&&Number.isFinite(e.ts)?e.ts:void 0;return{op:o,table:r,...i===void 0?{}:{doc:i},...s===void 0?{}:{id:s},...n===void 0?{}:{seq:n},...c===void 0?{}:{ts:c}}},T=async(e,r,t,o,s,i)=>{let n=0;for(;;)try{await e.deliver(r);return}catch(c){if(n>=t)throw c instanceof Error?c:new Error(String(c));const d=Math.min(o*2**n,s);await i(d),n+=1}},I=async e=>{const{coordinator:r,cursorStore:t,defaultShardKey:o,headers:s,initialBackoffMs:i=100,limit:n,maxBackoffMs:c=5e3,maxRetries:d=3,shardDO:S,sink:p,sleep:k=R,tables:C}=e,h=await t.read(p.name),b=await r.orchestrateCdcSync(S,{cursors:h,defaultShardKey:o,headers:s,limit:n,tables:C}),l={...h},m=[];let v=0,f=!1;for(const a of b.shards){if(a.error){m.push({error:a.error.message,shardKey:a.shardKey}),f=!0;continue}const y=a.changes??[];if(y.length===0){l[a.shardKey]=a.cursor;continue}const g=y.map(u=>$(u)),E={changes:g,cursor:a.cursor,shardKey:a.shardKey,sink:p.name};try{await T(p,E,d,i,c,k),l[a.shardKey]=a.cursor,v+=g.length,y.length>=M(n)&&(f=!0)}catch(u){m.push({error:u instanceof Error?u.message:String(u),shardKey:a.shardKey}),f=!0}}return await t.write(p.name,l),{cursors:l,delivered:v,failures:m,hasMore:f,shards:b.shards.length}},x=e=>{if(typeof e.name!="string"||e.name.length===0)throw new Error("defineExportSink: `name` must be a non-empty string");if(typeof e.deliver!="function")throw new TypeError("defineExportSink: `deliver` must be a function");return{deliver:e.deliver,name:e.name}},w=e=>`${e.map(r=>JSON.stringify(r)).join(`
|
|
2
2
|
`)}
|
|
3
3
|
`,J=e=>{const r=e.fetchImpl??((t,o)=>fetch(t,o));return x({deliver:async t=>{const o=await r(e.url,{body:w(t.changes),headers:{"content-type":"application/x-ndjson","x-lunora-cursor":String(t.cursor),"x-lunora-shard":t.shardKey,"x-lunora-sink":t.sink,...e.headers},method:"POST"});if(!o.ok)throw new Error(`webhook export sink "${e.name}" returned ${String(o.status)}`)},name:e.name})},U=e=>{let r=e.prefix??"cdc";for(;r.endsWith("/");)r=r.slice(0,-1);return x({deliver:async t=>{const o=`${r}/${t.shardKey}/${String(t.cursor)}.ndjson`;await e.bucket.put(o,w(t.changes),{httpMetadata:{contentType:"application/x-ndjson"}})},name:e.name})},z=()=>{const e={};return{read:r=>Promise.resolve({...e[r]}),snapshot:()=>structuredClone(e),write:(r,t)=>(e[r]={...t},Promise.resolve())}},W=(e,r)=>{const t=r?.keyPrefix??"__lunora_source_cursor:export",o=s=>`${t}:${s}`;return{read:async s=>{const i=await e.get(o(s),"json");if(i===null||typeof i!="object")return{};const n={};for(const[c,d]of Object.entries(i))typeof d=="number"&&Number.isFinite(d)&&(n[c]=d);return n},write:async(s,i)=>{await e.put(o(s),JSON.stringify(i))}}};export{z as a,I as b,W as c,x as d,B as e,D as f,q as g,M as h,U as r,$ as s,J as w};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as i}from"./base64-Bl1_r2k1.mjs";import{d as f,i as s}from"./wire-codec-
|
|
1
|
+
import{a as i}from"./base64-Bl1_r2k1.mjs";import{d as f,i as s}from"./wire-codec-BX_-4Tmg.mjs";const o=r=>{if(typeof r=="bigint")return r.toString();if(r instanceof ArrayBuffer)return i(new Uint8Array(r));if(ArrayBuffer.isView(r))return i(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));if(Array.isArray(r))return r.map(t=>o(t));if(s(r)){const t={};for(const e of Object.keys(r)){const n=o(r[e]);e==="__proto__"?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}return t}return r},y=r=>o(f(r));export{y as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as S,d as T,e as O,a as B,f as P}from"./rest-cache-D1BlbZb1.mjs";import{LunoraError as l}from"./LunoraError-DksAgIpa.mjs";import{m as D}from"./method-guard-BG_vJNTl.mjs";const w=1048576,_=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),U=async(e,r=w)=>{if(!e.body)return"";const t=e.body.getReader(),a=new TextDecoder;let i=0,s="";for(;;){const{done:o,value:n}=await t.read();if(o)break;if(n){if(i+=n.byteLength,i>r)throw await t.cancel().catch(()=>{}),new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});s+=a.decode(n,{stream:!0})}}return s+=a.decode(),s},W=async(e,r=w)=>{if(!e.body)return new ArrayBuffer(0);const t=e.body.getReader(),a=[];let i=0;for(;;){const{done:n,value:c}=await t.read();if(n)break;if(c){if(i+=c.byteLength,i>r)throw await t.cancel().catch(()=>{}),new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});a.push(c)}}const s=new Uint8Array(i);let o=0;for(const n of a)s.set(n,o),o+=n.byteLength;return s.buffer},j=async(e,r,t=w)=>{try{const a=await U(e,t);return a===""?{}:JSON.parse(a)}catch(a){throw a instanceof l?a:new l(`${r} body must be valid JSON`,{code:"BAD_REQUEST",status:400})}},X=async(e,r=w)=>{const t=await j(e,"Request",r);if(!_(t))throw new l("Request body must be an object",{code:"BAD_REQUEST",status:400});return t},x=(e,r)=>{if(!_(e))throw new l(`${r} \`args\` must be an object`,{code:"BAD_REQUEST",status:400})},b="__lunora_vary",C="x-lunora-edge-cache",G=["x-d1-bookmark","x-lunora-shard-key"],M=()=>{try{return globalThis.caches?.default}catch{return}},k=e=>e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r!==""),J=(e,r)=>{const t=e.headers.get("vary");return t===null?!0:k(t).every(a=>a!=="*"&&r.includes(a))},K=(e,r)=>{if(e===void 0||r===null||e.scope!=="public"||S(e.maxAge)<=0)return;const t=()=>r??M(),a=k(T(e)??""),i=o=>{const n=new URL(o.url);return n.searchParams.delete(b),a.length>0&&n.searchParams.set(b,a.map(c=>`${c}=${o.headers.get(c)??""}`).join("\0")),new Request(n.toString(),{method:"GET"})},s=(o,n)=>o.method==="GET"&&O(e,o,n)==="public";return{lookup:async(o,n)=>{const c=t();if(c===void 0||!s(o,n))return;let u;try{u=await c.match(i(o))}catch{return}if(u===void 0)return;const h=new Response(u.body,u);return h.headers.set(C,"hit"),h},store:(o,n,c)=>{const u=t();if(u===void 0||!s(n,c)||o.status!==200||o.headers.has("set-cookie")||o.headers.has("x-payment-response")||!J(o,a))return o;try{const h=new Response(o.clone().body,o);for(const R of G)h.headers.delete(R);const d=Promise.resolve(u.put(i(n),h)).catch(()=>{});c?.waitUntil&&c.waitUntil(d)}catch{}return o}}},N=e=>P(Object.entries(e).map(([r,t])=>({exposure:t.expose,functionPath:r,kind:t.kind}))),Y=(e,r)=>{const t=e.searchParams.get("shardKey");if(t!==null&&t!=="")return t;const a=r.headers.get("x-lunora-shard-key");return a===null||a===""?void 0:a},F=e=>{const r=Object.create(null);for(const[t,a]of e.searchParams.entries())if(!(t==="shardKey"||t===b))try{r[t]=JSON.parse(a)}catch{r[t]=a}return r},z=e=>{const{edgeCache:r,functions:t,invoke:a,rateLimit:i,readJsonBody:s}=e,o={};for(const n of N(t)){const c=n.kind==="query"?["GET","POST"]:["POST"],u=t[n.functionPath].expose?.cache,h=K(u,r);o[n.path]=async(d,R,Q,f)=>{const E=D(d,c);if(E)return E;const g=new URL(d.url);if(i){const m=await i(d,n.functionPath);if(m)return m}const v=await h?.lookup(d,f);if(v)return v;let y;d.method==="GET"?y=F(g):y=d.body===null?{}:await s(d),x(y,"REST");const p=Y(g,d),L=await a({args:y,env:R,functionPath:n.functionPath,request:d,...p===void 0?{}:{shardKey:p},...f?.waitUntil===void 0?{}:{waitUntil:m=>f.waitUntil?.(m)}}),A=B(L,u,d,f);return h?h.store(A,d,f):A}}return o},H="no-trusted-ip",Z=(e,r)=>async(t,a)=>{const i=(r.key?r.key(t,a):t.headers.get("cf-connecting-ip"))??H,s=await e.limit(r.name,{key:i});if(s.ok)return;if(s.reason==="deny")return Response.json({error:{code:"FORBIDDEN",message:"Request denied"}},{headers:{"content-type":"application/json"},status:403});const o=Math.max(1,Math.ceil(s.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(o)},status:429})};export{w as M,F as a,z as b,Z as c,X as d,j as e,W as f,x as g,U as h,N as r};
|
package/dist/packem_shared/{toAirbyteMessages-CetjLpiw.mjs → toAirbyteMessages-BX5SK-Ss.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as b}from"./portable-json-
|
|
1
|
+
import{t as b}from"./portable-json-DcwKZHQ7.mjs";const p="_id",f=(t,n=p)=>{const o=Object.create(null),s=Object.create(null),c=Object.create(null),a=Object.create(null),h=e=>typeof n=="string"?n:n[e]??p,l=(e,r)=>{const u=e[r];if(u)return u;const d=[];return e[r]=d,d};for(const e of t.changes){a[e.table]??={primary_key:[h(e.table)]};const r=b(e.doc);e.op==="delete"?l(c,e.table).push(r):e.op==="update"?l(s,e.table).push(r):l(o,e.table).push(r)}return{delete:c,hasMore:t.hasMore,insert:o,schema:a,state:{cursor:t.nextCursor},update:s}},m=(t,n=Date.now())=>{const o=[];for(const s of t.changes){const c=b(s.doc),a=s.op==="delete"?{...c,_lunora_deleted:!0}:c;o.push({record:{data:a,emitted_at:n,stream:s.table},type:"RECORD"})}return o.push({state:{data:{cursor:t.nextCursor}},type:"STATE"}),o};export{m as toAirbyteMessages,f as toFivetranResponse};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as p,b as E}from"./base64-Bl1_r2k1.mjs";const o="$lunora.wire$",d=64,g=1024,w="__proto__",A={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},l={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},O=e=>{if(e===null||typeof e!="object")return!1;const n=Object.getPrototypeOf(e);return n===null||n===Object.prototype},y=(e,n=0)=>{if(n>d)throw new RangeError(`wire-codec: value nesting exceeds the ${d}-level limit`);if(e===void 0)return[o,"undefined"];if(e===null)return null;const u=typeof e;if(u==="bigint")return[o,"bigint",e.toString()];if(u==="number"){const r=e;return Number.isNaN(r)?[o,"nan"]:r===1/0?[o,"inf"]:r===-1/0?[o,"-inf"]:r}if(u!=="object")return e;if(e instanceof Date)return[o,"date",y(e.getTime(),n+1)];if(e instanceof Error){const r=e,t={};for(const i of Object.keys(r)){if(r[i]===void 0)continue;const a=y(r[i],n+1);i===w?Object.defineProperty(t,i,{configurable:!0,enumerable:!0,value:a,writable:!0}):t[i]=a}const c=[o,"error",r.name,r.message,t];return r.cause!==void 0&&c.push(y(r.cause,n+1)),c}if(e instanceof URL)return[o,"url",e.href];if(e instanceof Map)return[o,"map",[...e.entries()].map(([r,t])=>[y(r,n+1),y(t,n+1)])];if(e instanceof Set)return[o,"set",[...e].map(r=>y(r,n+1))];if(e instanceof ArrayBuffer)return[o,"bytes",p(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,t=r.constructor.name,c=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return t==="Uint8Array"?[o,"bytes",p(c)]:[o,"bytes",p(c),t]}if(Array.isArray(e)){const r=e.map(t=>y(t,n+1));return r.length>0&&r[0]===o?[o,"arr",r]:r}if(!O(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const b=e,s={};for(const r of Object.keys(b)){const t=b[r];if(t===void 0)continue;const c=y(t,n+1);r===w?Object.defineProperty(s,r,{configurable:!0,enumerable:!0,value:c,writable:!0}):s[r]=c}return s},f=(e,n=0)=>{if(n>d)throw new RangeError(`wire-codec: value nesting exceeds the ${d}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===o)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>f(r,n+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>g||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${g} digits)`);return BigInt(r)}case"date":{const r=f(e[2],n+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(t=>{if(!Array.isArray(t)||t.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[f(t[0],n+1),f(t[1],n+1)]}))}case"set":return new Set(e[2].map(r=>f(r,n+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],t=e[3],c=(Object.hasOwn(l,r)?l[r]:void 0)??Error,i=new c(t);i.name!==r&&Object.defineProperty(i,"name",{configurable:!0,value:r,writable:!0});const a=f(e[4],n+1);if(a===null||typeof a!="object"||Array.isArray(a))throw new TypeError("wire-codec: malformed error — props must be an object");for(const m of Object.keys(a))m===w?Object.defineProperty(i,m,{configurable:!0,enumerable:!0,value:a[m],writable:!0}):i[m]=a[m];return e.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:f(e[5],n+1),writable:!0}),i}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const t=E(r),c=e[3]??"Uint8Array";if(c==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const i=Object.hasOwn(A,c)?A[c]:void 0;return i?new i(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>f(r,n+1))}return e.map(s=>f(s,n+1))}const u=e,b={};for(const s of Object.keys(u)){const r=f(u[s],n+1);s===w?Object.defineProperty(b,s,{configurable:!0,enumerable:!0,value:r,writable:!0}):b[s]=r}return b};export{f as d,y as e,O as i};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/runtime",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.94",
|
|
4
4
|
"description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,9 +46,9 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
50
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
51
|
-
"@lunora/observability": "1.0.0-alpha.
|
|
49
|
+
"@lunora/bindings": "1.0.0-alpha.50",
|
|
50
|
+
"@lunora/errors": "1.0.0-alpha.32",
|
|
51
|
+
"@lunora/observability": "1.0.0-alpha.57",
|
|
52
52
|
"@lunora/platform": "1.0.0-alpha.26"
|
|
53
53
|
},
|
|
54
54
|
"peerDependencies": {
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as Bn,toErrorBody as xn}from"@lunora/errors";import{e as Ht}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Hn}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as Ln,f as Mn}from"./base64-Bl1_r2k1.mjs";import{e as jn,a as $n}from"./identity-header-C4Z5pldl.mjs";import{o as ve,b as Kn,p as Fn,m as Gn,d as Qn,a as zn,r as Wn}from"./otlp-resource-DeXhb949.mjs";import{e as We,d as Vn}from"./wire-codec-DBWN80s9.mjs";import{d as ee,e as he,M as Lt,b as Jn,f as qn,g as Mt,h as jt}from"./rest-routes-CpwDstbq.mjs";import{LunoraError as c,toErrorResponse as ct}from"./LunoraError-DksAgIpa.mjs";import{a as j,m as we}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as Ye,BACKUP_KEY_PREFIX as Xe,isBackupManifestKey as Yn,backupObjectKeyOfManifest as $t,backupObjectKey as Xn,backupManifestKey as Zn}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as er,buildStorageAdminRoutes as tr,STORAGE_UPLOAD_MAX_BODY_BYTES as nr,STORAGE_PATH as rr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{b as or,e as ar,f as dt,g as sr,h as ir}from"./export-tap-H6oPBoSr.mjs";import{buildHealthRoutes as cr,durableObjectProbe as dr,d1Probe as ur,presenceProbe as He}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as lr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Us,routeIdentityResolvers as Cs}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as hr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{r as fr,f as ut,a as ce}from"./observability-B1hLjwgx.mjs";import{resolveShard as ge,applyJurisdiction as lt}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as ht,handleCorsPreflight as pr,enforceOrigin as mr,decorateResponse as Le,enforceWebSocketOrigin as ft}from"./decorateResponse-CCRm2CFM.mjs";const wr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},Kt="__lunoraBranch",gr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Kt),yr=`may not contain the reserved workflow branch-marker key ("${Kt}")`,br=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}},Ze=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,u=a<t.length?t.charCodeAt(a):0;r|=i^u}return r===0},_r=(e,t,n,r)=>{const a=e.get(t);if(a!==void 0)return a;Ht(e,r);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},et=new TextEncoder,Rr=Array.from({length:32},(e,t)=>t);new RegExp(`[${Rr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Er=64,Ar=new Map,Ft=async e=>_r(Ar,e,async()=>crypto.subtle.importKey("raw",et.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),Er),Gt=async(e,t)=>{const n=await Ft(e),r=await crypto.subtle.sign("HMAC",n,et.encode(t));return Ln(new Uint8Array(r))},Sr=async(e,t,n)=>{const r=await Ft(e);return crypto.subtle.verify("HMAC",r,n,et.encode(t))},Tr=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Tr);const Or=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),vr=-100,kr=15,Ir=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Or.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>kr?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<vr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},pt=e=>{const t=e.cf;return t===void 0?void 0:Ir(t)},Ve="::relay::",Pr=(e,t)=>`${e}${Ve}${String(t)}`,Je="::replica::",Nr=(e,t)=>`${e}${Je}${t}`,Dr=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Ur=new Set(["1","enabled","on","true","yes"]),Cr=new Set(["0","disabled","false","no","off"]),Br=(e,t)=>{const n=(e??"").trim().toLowerCase();return Ur.has(n)?!0:Cr.has(n)?!1:t},Qt="v1",xr=6e4,Hr=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??xr),r=`${Qt}.${String(n)}`,a=await Gt(e,r);return{expiresAtMs:n,token:`${r}.${a}`}},Lr=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const r=t.split(".");if(r.length!==3)return!1;const[a,i,u]=r;if(a!==Qt||u.length===0)return!1;const h=Number(i);if(!Number.isFinite(h)||h<=n)return!1;let p;try{p=Mn(u)}catch{return!1}return Sr(e,`${a}.${i}`,p)},P="/_lunora/admin/auth",Mr={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},D=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new 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},oe=(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},mt=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},wt=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,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[r]=a);return n},jr={[`${P}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${P}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${P}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${P}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${P}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${P}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:Me(e,"data"),email:D(e,"email"),name:D(e,"name"),password:oe(e,"password"),role:zt(e.role)}),http:"POST",method:"createUser"},[`${P}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:D(e,"userId")}},http:"POST",method:"updateUser"},[`${P}/users/role`]:{build:({body:e})=>({role:mt(e),userId:D(e,"userId")}),http:"POST",method:"setRole"},[`${P}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:oe(e,"reason"),userId:D(e,"userId")}),http:"POST",method:"banUser"},[`${P}/users/unban`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"unbanUser"},[`${P}/users/password`]:{build:({body:e})=>({newPassword:D(e,"newPassword"),userId:D(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${P}/users/remove`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${P}/users/impersonate`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"impersonateUser"},[`${P}/sessions/revoke`]:{build:({body:e})=>({sessionId:D(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${P}/sessions/revoke-all`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${P}/accounts/unlink`]:{build:({body:e})=>({accountId:D(e,"accountId"),userId:D(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${P}/two-factor/disable`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${P}/passkeys/delete`]:{build:({body:e})=>({passkeyId:D(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${P}/organizations/members/remove`]:{build:({body:e})=>({memberId:D(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${P}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:D(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${P}/organizations/create`]:{build:({body:e})=>({logo:oe(e,"logo"),metadata:Me(e,"metadata"),name:D(e,"name"),ownerId:oe(e,"ownerId"),slug:oe(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:oe(e,"logo"),metadata:Me(e,"metadata"),name:oe(e,"name"),organizationId:D(e,"organizationId"),slug:oe(e,"slug")}),http:"POST",method:"updateOrganization"},[`${P}/organizations/remove`]:{build:({body:e})=>({organizationId:D(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${P}/organizations/members/add`]:{build:({body:e})=>({organizationId:D(e,"organizationId"),role:oe(e,"role"),userId:D(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:D(e,"email"),inviterId:oe(e,"inviterId"),organizationId:D(e,"organizationId"),role:oe(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:D(e,"memberId"),role:mt(e)}),http:"POST",method:"updateMemberRole"},[`${P}/organizations/teams/create`]:{build:({body:e})=>({name:D(e,"name"),organizationId:D(e,"organizationId")}),http:"POST",method:"createTeam"},[`${P}/organizations/teams/update`]:{build:({body:e})=>({name:D(e,"name"),teamId:D(e,"teamId")}),http:"POST",method:"updateTeam"},[`${P}/organizations/teams/remove`]:{build:({body:e})=>({teamId:D(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${P}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:D(e,"teamId"),userId:D(e,"userId")}),http:"POST",method:"addTeamMember"},[`${P}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:D(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${P}/organizations/roles/create`]:{build:({body:e})=>({organizationId:D(e,"organizationId"),permission:wt(e),role:D(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:wt(e),roleId:D(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${P}/organizations/roles/remove`]:{build:({body:e})=>({roleId:D(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},$r=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof c)throw i;const u=i,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:h,status:Mr[h]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[i.method];if(h===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const p=new URL(a.url),m={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:T=>e.queryParameter(p,T)},A=i.build(m),S=await t(()=>h(A));return Response.json(i.returns==="void"?{ok:!0}:S,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[a,i]of Object.entries(jr))r[a]=u=>n(u,i);return r},gt="__lunora_admin__:getAuthAuditLog",yt=e=>typeof e=="string"&&e!==""?e:void 0,bt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Kr=e=>async(n,r)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=yt(r.actorId),u=yt(r.event),h=bt(r.sinceSeq),p=bt(r.limit),m={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...p===void 0?{}:{limit:p}};let A;try{A=await a.read(m)}catch(T){throw T instanceof c?T:(console.error("[lunora] auth audit read failed:",T),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const S={entries:A};return Response.json({result:We(S)},{headers:{"content-type":"application/json"},status:200})},Fr=(e,t)=>{const n=[],r=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?r.push(a):n.push(a);return{globalTables:r,shardLocalTables:n}},Gr=async(e,t,n,r,a,i,u)=>{if(n!==void 0&&r.length===0)return;const h=await e.orchestrateExport(i,{args:{tables:r},defaultShardKey:u,headers:t,tables:r});for(const p of h.shards)if(!p.error)for(const m of p.rows??[])a(m)},Wt=async(e,t,n,r,a,i)=>{const u=r??e.listSchemaTables?.();r===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:h,shardLocalTables:p}=Fr(e,u);await Gr(t,n,u,p,a,i,e.defaultShardKey??"__root__");const m=e.exportGlobals;if((r===void 0||h.length>0)&&m)for await(const S of m({tables:h}))a(S)},Qr=new TextEncoder,zr=1e3,Vt=10,Wr=200,_t=8,Jt="lunoraBackupCron",Rt=24*1048576,Et=e=>{const t=e.slice(0,Vt).map(r=>$t(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Vr=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const a of e)n.set(a,r),r+=a.byteLength;return n},tt=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let u=0;u<zr;u+=1){const h=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const p of h.objects)Yn(p.key)&&p.customMetadata?.[Jt]===r&&a.push(p.key);if(!h.truncated||h.cursor===void 0)break;i=h.cursor}return{eligible:a.length,stale:a.toSorted((u,h)=>h.localeCompare(u)).slice(n)}},Jr=async(e,t,n,r,a)=>{const{stale:i}=await tt(e,t,n,r),u=new Set(a),h=i.filter(g=>u.has(g)),p=h.slice(0,Wr),m=i.length-p.length,A=a.length-h.length;if(p.length===0)return{deleted:[],failed:[],ignored:A,remaining:m};const S=[],T=[];for(let g=0;g<p.length;g+=_t){const y=await Promise.allSettled(p.slice(g,g+_t).map(async _=>(await e.delete($t(_)),await e.delete(_),_)));for(const[_,f]of y.entries())f.status==="fulfilled"?S.push(f.value):T.push(p[g+_])}return S.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(S.length)}: ${Et(S)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${Et(T)}`),{deleted:S,failed:T,ignored:A,remaining:m}},qr=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=Ye(e.backupPrefix??Xe),r=e.backupCron,{eligible:a,stale:i}=r===void 0?{eligible:0,stale:[]}:await tt(t,n,e.backupRetain,r);return{cron:r,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},Yr=async(e,t,n,r)=>{const a=e.backupStore,i=e.queryCoordinator;if(!a)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"},h=e.backupTables;let p=0,m=0,A=[];await Wt(e,i,u,h,N=>{const M=Qr.encode(`${JSON.stringify(N)}
|
|
2
|
-
`);if(p+=1,m+=M.byteLength,m>Rt)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Rt)}-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});A.push(M)},t);const T=Ye(e.backupPrefix??Xe),g=new Date(r.scheduledTime).toISOString(),y=Xn(T,g),_=Vr(A,m);A=[];const f=er(await crypto.subtle.digest("SHA-256",_));await a.put(y,_,{httpMetadata:{contentType:"application/x-ndjson"},sha256:f});const O={bytes:m,createdAt:g,cron:r.cron,file:y,id:g,rows:p,scheduledTime:r.scheduledTime,sha256:f,...h?{tables:h.join(",")}:{}};await a.put(Zn(y),`${JSON.stringify(O,void 0,2)}
|
|
3
|
-
`,{customMetadata:{[Jt]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:N}=await tt(a,T,e.backupRetain,r.cron);if(N.length>0){const M=N.slice(0,Vt),k=N.length-M.length;console.info(`[lunora] backup retention: ${String(N.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${M.join(", ")}${k>0?` (+${String(k)} more)`:""}`)}}catch(N){console.warn(`[lunora] backup ${y} was written, but the retention report failed:`,N)}},Xr=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,a=e.backupRetain;if(r===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return Jr(n,Ye(e.backupPrefix??Xe),a,r,t)},Zr="/_lunora/admin/backup/retention",eo="/_lunora/admin/backup/prune",to=e=>{const{options:t,readJsonBody:n,requireAdminOption:r}=e,a=(h,p)=>{r(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${p} requires a \`backupStore\` on the worker`})},i=async h=>(j(h,"GET","Backup-retention"),a(h,"retention preview"),Response.json(await qr(t),{headers:{"cache-control":"no-store"}})),u=async h=>{j(h,"POST","Backup-prune"),a(h,"prune");const{confirm:p}=await n(h);if(!Array.isArray(p)||p.some(m=>typeof m!="string"))throw new c("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await Xr(t,p),{headers:{"cache-control":"no-store"}})};return{[eo]:u,[Zr]:i}},At=500,no=(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});return{entry:{args:r.args===void 0?{}:r.args,clientId:typeof r.clientId=="string"?r.clientId:void 0,clientSeq:typeof r.clientSeq=="number"?r.clientSeq:void 0,functionPath:r.functionPath,id:typeof r.id=="number"?r.id:t,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:n}},ro=(e,t)=>{if(e.length>At)throw new c(`RPC batch exceeds the ${String(At)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map;for(const[r,a]of e.entries()){const{entry:i,shardKey:u}=no(a,r,t),h=n.get(u)??[];h.push(i),n.set(u,h)}return n},oo="/_lunora/admin/export",ao="/_lunora/admin/import",so="/_lunora/admin/sync",io="/_lunora/admin/connector/sync",co="/_lunora/admin/apply",uo="/_lunora/admin/export-tap/run",lo=new TextEncoder,ho=async e=>{const n=await he(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 a of n.tables){if(typeof a!="string"||a.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(a)}return{tables:r}},je=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,fo=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:a,knownTables:i,queryCoordinator:u,assertAdmin:h,requireAdminOption:p,resolveForwardContext:m,shardDO:A,streamExportRows:S,streamingImport:T,syncGlobals:g}=e,y=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const W=p(k,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),C=await ho(k),{headers:V}=await m(k,K),F=new ReadableStream({async pull(J){const Z=H=>{J.enqueue(lo.encode(`${JSON.stringify(H)}
|
|
4
|
-
`))};try{await S(W,V,C.tables,Z),J.close()}catch(H){J.error(H)}}});return new Response(F,{headers:{"content-type":"application/x-ndjson"},status:200})},_=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const W=p(k,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),C=await ee(k),V=typeof C.cursors=="object"&&C.cursors!==null?C.cursors:{},F=typeof C.limit=="number"?C.limit:void 0,J=typeof C.globalCursor=="number"?C.globalCursor:0,Z=je(C.tables),{headers:H}=await m(k,K),q=Z??i(),G=await W.orchestrateCdcSync(A,{cursors:V,defaultShardKey:n,headers:H,limit:F,tables:q}),fe=g?await g({limit:F,sinceSeq:J}):void 0;return Response.json({global:fe,shards:G.shards},{status:200})},f=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const W=p(k,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),C=await ee(k),V=ar(C.cursor),F=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,J=je(C.tables),{headers:Z}=await m(k,K),H=J??i(),q=await W.orchestrateCdcSync(A,{cursors:V.s,defaultShardKey:n,headers:Z,limit:F,tables:H}),G=[],fe={...V.s};let ae=!1;for(const se of q.shards)ae=dt(G,se.changes??[],ir(F))||ae,fe[se.shardKey]=se.cursor;let _e=V.g;if(g){const se=await g({limit:F,sinceSeq:V.g});ae=dt(G,se.changes,F)||ae,_e=se.cursor}const ke=sr({g:_e,s:fe,v:1}),Ie={changes:G,hasMore:ae,nextCursor:ke};return Response.json(Ie,{status:200})},O=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const W=p(k,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),C=await ee(k),F=(Array.isArray(C.batches)?C.batches:[]).map(G=>G).filter(G=>G!==null&&typeof G=="object"&&typeof G.shardKey=="string"&&Array.isArray(G.changes)),J=Array.isArray(C.globalChanges)?C.globalChanges:[],{headers:Z}=await m(k,K),H=await W.orchestrateApplyCdc(A,{batches:F,headers:Z}),q=J.length>0&&t?await t({changes:J}):0;return Response.json({applied:H.applied+q,failed:H.failed,ok:H.ok},{status:200})},N=async(k,K)=>{const $=we(k,["POST"]);if($)return $;h(k);const{headers:W}=await m(k,K),C=await T(k,W);return Response.json(C,{headers:{"content-type":"application/json"},status:C.failed.length>0?207:200})},M=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const W=p(k,u,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(a===void 0||Object.keys(a).length===0||r===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const C=await ee(k),V=typeof C.sink=="string"?C.sink:void 0,F=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,J=je(C.tables);if(V===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const Z=a[V];if(Z===void 0)throw new c(`Export-tap sink "${V}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:H}=await m(k,K),q=J??i(),G=await or({coordinator:W,cursorStore:r,defaultShardKey:n,headers:H,limit:F,shardDO:A,sink:Z,tables:q});return Response.json(G,{headers:{"content-type":"application/json"},status:200})};return{[co]:O,[io]:f,[oo]:y,[uo]:M,[ao]:N,[so]:_}},po=(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}},mo=(e,t,n,r,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:r}},wo=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],a=[],i=new Map;let u=0,h=0;const p=e.body.getReader(),m=new TextDecoder;let A="",S=0;const T=g=>{h+=1;const y=g.trim();if(y.length===0)return;u+=1;const _=po(y,h);if(!_.ok){r.push(_.error);return}const{doc:f,table:O}=_,N=t.resolveTableSharding?.(O);if(N?.mode.kind==="global"){a.push({doc:f,line:h,table:O});return}const M=mo(f,O,N,n,h);if(!M.ok){r.push(M.error);return}const k=i.get(M.shardKey);k?k.rows.push({doc:f,table:O}):i.set(M.shardKey,{rows:[{doc:f,table:O}],shardKey:M.shardKey,startLine:h})};for(;;){const{done:g,value:y}=await p.read();if(g)break;if(y&&(S+=y.byteLength,S>Lt))throw await p.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});A+=m.decode(y,{stream:!0});let _=A.indexOf(`
|
|
5
|
-
`);for(;_!==-1;){const f=A.slice(0,_);A=A.slice(_+1),T(f),_=A.indexOf(`
|
|
6
|
-
`)}}return A.length>0&&T(A),{errors:r,globalRows:a,perShard:i,received:u}},go=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),St=(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},yo=async(e,t,n,r)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:h,received:p}=await wo(e,t,a),m={conflicts:0,errors:i,failed:[],inserted:{}},A=[];if(t.resolveTableSharding===void 0&&h.size>0&&A.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const S=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:[...h.values()],headers:n});St(m,T),m.failed.push(...go(T.shards))}if(u.length>0)if(t.importGlobals){const S=u[0]?.line??1,T=await t.importGlobals({rows:u,startLine:S});St(m,T)}else for(const S of u)m.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:m.conflicts,errors:m.errors,failed:m.failed,inserted:m.inserted,received:p,...A.length>0?{warnings:A}:{}}},$e=e=>typeof e=="object"&&e!==null?e:{},Ke=e=>typeof e.kind=="string"?e.kind:"unknown",bo=(e,t)=>{let n=$e(t),r=!1;Ke(n)==="optional"&&(r=!0,n=$e(n._meta?.inner));const a=Ke(n),i=n._meta??{},u={kind:a,name:e,optional:r};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const h=Ke($e(i.inner));h!=="unknown"&&(u.element=h)}return u},_o=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>bo(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),Ro="/_lunora/admin/functions",Eo="/_lunora/admin/cron-jobs",Ao="/_lunora/admin/openapi",So="/_lunora/admin/openrpc",To="/_lunora/admin/global/tables",Oo="/_lunora/admin/global/table",vo="/_lunora/admin/global/facet",Tt=e=>{if(e===void 0||e==="")return;let t;try{t=Vn(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:a,value:i}=r;return[{column:a,value:i}]});return n.length===0?void 0:n},ko=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:{}}),Io=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"}),Po=e=>{const{assertAdmin:t,options:n,parsePaging:r,queryParameter:a,requireAdminOption:i}=e,u=g=>{j(g,"GET","Functions");const y=i(g,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(y).flatMap(([f,O])=>O.visibility==="internal"||O.kind==="stream"?[]:[{args:_o(O.args),kind:O.kind,path:f}]).toSorted((f,O)=>f.path.localeCompare(O.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},h=g=>{j(g,"GET","Cron-jobs");const y=i(g,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(y).flatMap(([f,O])=>O.map(N=>({args:N.args,cron:f,functionPath:N.functionPath,name:N.name,shardKey:N.shardKey,workflow:N.workflow}))).toSorted((f,O)=>f.name.localeCompare(O.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},p=g=>(j(g,"GET","OpenAPI"),t(g),Response.json(n.openApiSpec??ko,{headers:{"content-type":"application/json"},status:200})),m=g=>(j(g,"GET","OpenRPC"),t(g),Response.json(n.openRpcSpec??Io,{headers:{"content-type":"application/json"},status:200})),A=async g=>{j(g,"GET","Global-tables");const y=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await y.listTables(),{headers:{"content-type":"application/json"},status:200})},S=async g=>{j(g,"GET","Global-table");const y=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),f=a(_,"table");if(f===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const O=await y.readTablePage({...r(g),filters:Tt(a(_,"filters")),table:f});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},T=async g=>{j(g,"GET","Global-facet");const y=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),f=a(_,"table"),O=a(_,"column");if(f===void 0||O===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const N=a(_,"limit"),M=N===void 0?void 0:Number(N),k=await y.facetColumn({column:O,filters:Tt(a(_,"filters")),limit:M!==void 0&&Number.isFinite(M)?M:void 0,table:f});return Response.json(k,{headers:{"content-type":"application/json"},status:200})};return{[Eo]:h,[Ro]:u,[vo]:T,[Oo]:S,[To]:A,[Ao]:p,[So]:m}},No="/_lunora/admin/kv/namespaces",Do="/_lunora/admin/kv/keys",qt="/_lunora/admin/kv/value",Yt=32*1048576,Ot=60,Uo=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=y=>n(y,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=y=>Response.json(y,{headers:{"content-type":"application/json"},status:200}),i=(y,_)=>{const f=new URL(y.url),O=f.searchParams.get("namespace")??"",N=f.searchParams.get("key")??"";if(O==="")throw new c(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(N==="")throw new c(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:N,namespace:O}},u=async(y,_)=>{if(!(await y.listNamespaces()).some(O=>O.binding===_))throw new c(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},h=async y=>(j(y,"GET","KV-namespaces"),a({namespaces:await r(y).listNamespaces()})),p=async y=>{j(y,"GET","KV-keys");const _=r(y),f=new URL(y.url),O=f.searchParams.get("namespace")??"";if(O==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const N=f.searchParams.get("prefix")??void 0,M=f.searchParams.get("cursor")??void 0,k=f.searchParams.get("limit"),K=k===null?void 0:Number.parseInt(k,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(_,O),a(await _.listKeys({cursor:M,limit:$,namespace:O,prefix:N}))},T={DELETE:async y=>{const _=r(y),f=i(y,"DELETE");return await u(_,f.namespace),await _.deleteKey(f),a({deleted:!0})},GET:async y=>{const _=r(y),f=i(y,"GET");return await u(_,f.namespace),a(await _.getValue(f))},PUT:async y=>{const _=r(y),f=await t(y,Yt);if(typeof f.namespace!="string"||f.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof f.key!="string"||f.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof f.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(f.expirationTtl!==void 0&&(typeof f.expirationTtl!="number"||!Number.isInteger(f.expirationTtl)||f.expirationTtl<Ot))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const O=Math.floor(Date.now()/1e3)+Ot;if(f.expiration!==void 0&&(typeof f.expiration!="number"||!Number.isInteger(f.expiration)||f.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(_,f.namespace),await _.putValue({expiration:f.expiration,expirationTtl:f.expirationTtl,key:f.key,metadata:f.metadata,namespace:f.namespace,value:f.value}),a({ok:!0})}},g=y=>{const _=T[y.method];if(!_)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(y)};return{[No]:h,[Do]:p,[qt]:g}},Co="/_lunora/migrate",Bo="/_lunora/admin/pitr",xo="/_lunora/admin/rank",Ho="/_lunora/admin/rankpage",Lo="/_lunora/admin/shard-traffic",Mo=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),jo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),$o=async e=>{const n=await he(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"||!Mo.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}},Ko=async e=>{const n=await he(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}},Fo=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}},Go=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})},Qo=async e=>{const n=await he(e,"Rank page")??{};Go(n);const r=Fo(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}},zo=async e=>{const n=await he(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}},Wo=async e=>{const n=await ee(e);if(typeof n.functionPath!="string"||!jo.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}},Vo=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:r,queryCoordinator:a,resolveForwardContext:i,shardDO:u}=e,h=(g,y)=>{if(g.method!=="POST")throw new c(`${y} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(g))throw new c("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new c(`${y} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},p=async(g,y)=>{const _=h(g,"Migration"),f=await $o(g),{headers:O}=await i(g,y),N=await _.orchestrateMigration(u,{args:f.args,defaultShardKey:t,functionPath:f.functionPath,headers:O,table:f.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},m=async(g,y)=>{const _=h(g,"Rank"),f=await Ko(g),{headers:O}=await i(g,y),N=await _.orchestrateRank(u,{headers:O,index:f.index,partitionKey:f.partitionKey,rowId:f.rowId,sortValues:f.sortValues,table:f.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},A=async(g,y)=>{const _=h(g,"Rank page"),f=await Qo(g),{headers:O}=await i(g,y),N=await _.orchestrateRankPage(u,{...f,headers:O});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},S=async(g,y)=>{const _=h(g,"Shard-traffic"),f=await zo(g),{headers:O}=await i(g,y),N=await _.orchestrateShardTraffic(u,{headers:O,table:f.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},T=async(g,y)=>{if(j(g,"POST","PITR"),!r(g))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const _=await Wo(g),{headers:f}=await i(g,y),O=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:_.args,functionPath:_.functionPath}),headers:f,method:"POST"});return n(u,_.shardKey??t,O)};return{[Co]:p,[Bo]:T,[xo]:m,[Ho]:A,[Lo]:S}},Jo=1,qo=0,Yo=32,Xo=512,Zo=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,ea=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Xo)return;const n=t.split(",");if(!(n.length>Yo)){for(const r of n)if(!Zo.test(r.trim()))return;return t}},ta=e=>{const t=Fn(e.headers.get("traceparent"));if(t===void 0)return;const n=ea(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},na=(e,t={})=>{const n=ta(e),r=t.trustInbound===!0?n:void 0,a=ve(8),i=r?.traceId??ve(16),u=fr(t.sampling,r===void 0?a:i),h=u.isTraced&&(r===void 0||r.sampled);return{decision:u,ignoredUpstream:n!==void 0&&r===void 0,trace:{sampled:h,spanId:a,traceFlags:h?Jo:qo,traceId:i,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState}}}},ra=(e,t)=>{t.traceparent=Kn(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},oa=(e,t)=>{let n;return()=>{if(n===void 0){const r=Wn(e),a=t===void 0?void 0:t.cf;n=Gn(zn(r),Qn(r,a))}return n}},aa="/_lunora/admin/scheduled",sa="/_lunora/admin/scheduled/status",ia="/_lunora/admin/scheduled/ws",ca="/_lunora/admin/scheduled/cancel",da="/_lunora/admin/scheduled/dead",ua="/_lunora/admin/scheduled/dead/retry",la="/_lunora/admin/scheduled/dead/cancel",ha="/_lunora/admin/scheduled/pool/release",fa=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:r,schedulerInstanceName:a}=e,i=(m,A)=>S=>{if(S.method!=="GET")throw new c(`${A} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(S.url).searchParams.get("cursor"),g=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return r(S).fetch(new Request(`https://scheduler.internal${m}${g}`,{method:"GET"}))},u=(m,A,S=A)=>async T=>{if(T.method!=="POST")throw new c(`${S} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const g=r(T),y=await he(T,A);if(typeof y?.id!="string"||y.id==="")throw new c(`${A} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return g.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:y.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async m=>{if(m.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const A=r(m),S=await he(m,"Scheduled pool-release");if(typeof S?.pool!="string"||S.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const T=typeof S.id=="string"&&S.id!==""?S.id:void 0;return A.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 m=>{if(m.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(m))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const A=n();return ge(A,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ca]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[la]:u("/dead/cancel","Scheduled dead-letter action"),[da]:i("/dead","Scheduled dead-letter"),[ua]:u("/dead/retry","Scheduled dead-letter action"),[aa]:i("/list","Scheduled-list"),[ha]:h,[sa]:i("/status","Scheduler-status"),[ia]:p}},pa=(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},vt={mtls:e=>pa(e,"tlsClientAuth","certVerified")==="SUCCESS"},ma=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(vt,e)?vt[e]:void 0)??(()=>!1),wa=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.'))}},ga="/_lunora/admin/vector/indexes",ya="/_lunora/admin/vector/query",ba=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})},a=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 m=await u.queryIndex({name:p.name,text:p.text,topK:p.topK});return Response.json(m,{headers:{"content-type":"application/json"},status:200})};return{[ga]:r,[ya]:a}},_a="/_lunora/admin/workflows/instances",Ra="/_lunora/admin/workflows/instance",Ea="/_lunora/admin/workflows/status",Aa={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Sa=e=>e!==null&&Object.hasOwn(Aa,e)?e:void 0,kt=(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},Fe=(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},It=()=>{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})},Ta=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,r=async(u,h,p)=>{j(u,"GET","Workflows instances"),t(u);const m=n(h);if(!m)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const A=Fe(p,"name"),S=Sa(p.searchParams.get("status"));return Response.json(await m.listInstances({page:kt(p,"page"),perPage:kt(p,"perPage"),status:S,workflowName:A}))},a=async(u,h,p)=>{j(u,"GET","Workflows instance"),t(u);const m=n(h);return m?Response.json(await m.getInstance({instanceId:Fe(p,"id"),workflowName:Fe(p,"name")})):It()},i=async(u,h)=>{j(u,"POST","Workflows status"),t(u);const p=n(h);if(!p)return It();const m=await u.json().catch(()=>{});if(typeof m?.name!="string"||m.name===""||typeof m.id!="string"||m.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:A}=m;if(A!=="pause"&&A!=="resume"&&A!=="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:A,instanceId:m.id,workflowName:m.name}))};return{[Ra]:a,[_a]:r,[Ea]:i}},Oa={[qt]:Yt,[rr]:nr},Pt="/_lunora/rpc",va="/_lunora/rpc-batch",ka="/_lunora/ws",Ee=(e,t,n)=>({resourceAttributes:oa(e,t),...n===void 0?{}:{waitUntil:n}}),Ge=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Nt=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 a=r.port===""?void 0:Number(r.port);return{host:r.hostname,method:t,path:r.pathname,port:Number.isNaN(a)?void 0:a,scheme:r.protocol.replace(":",""),userAgent:n}},Dt="/_lunora/voice/",Ia="/_lunora/scheduler/dispatch",Pa="/_lunora/admin/cron-jobs/run",Na="/_lunora/admin/ws-token",Da="/_lunora/admin/",Ua="/_lunora/migrate",Ca="/_lunora/status",Ba=e=>e.startsWith(Da)||e===Ua,xa="__lunora_relation__:",Ae=e=>{if(e.startsWith(xa))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Se=async e=>await e===!0,Ha=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}}},La="/api/auth",Ma="__lunora_admin__:recordAuthEvent",ja="__lunora_admin__:listPushSubscriptions",$a=["/sign-in","/sign-up","/callback"],Ka=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const r=e.slice(n.length);return $a.some(a=>r===a||r.startsWith(`${a}/`))},Te=(e,t,n,r)=>{const a=Bn(n),i=a?n.code:"INTERNAL_SERVER_ERROR",u=a?n.status:500,h=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:h,status:u},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},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},Ut=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Ga=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},qe=new WeakMap,de=async(e,t,n,r=qe.get(e))=>{const a={"content-type":"application/json"},i=e.headers.get("authorization"),u=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),p=e.headers.get("x-lunora-mutation-id"),m=e.headers.get("x-lunora-client-id"),A=e.headers.get("x-lunora-client-seq");i&&(a.authorization=i),u&&(a.cookie=u),h&&(a["x-d1-bookmark"]=h),p&&(a["x-lunora-mutation-id"]=p),m&&(a["x-lunora-client-id"]=m),A&&(a["x-lunora-client-seq"]=A);const S=e.headers.get("cf-connecting-ip");if(S&&(a["x-lunora-client-ip"]=S),!n)return{claims:null,headers:a,identity:null,userId:null};const T=await n(e,t,r);if(!T||typeof T.userId!="string"||T.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=jn(T.userId);const g=Fa(T);g!==void 0&&(a["x-lunora-identity-exp"]=String(g));const{userId:y,..._}=T,f=Object.keys(_).length>0?_:null;return f&&(a["x-lunora-identity"]=$n(f)),{claims:f,headers:a,identity:T,userId:y}},Qa=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),za=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"||!Qa.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},Wa=(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}},Va=async e=>{const t=await jt(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&&Mt(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 a=n,i=za(a.fanOut),u=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==i.table)throw new 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:a.functionPath,shardKey:a.shardKey}},Oe=new Map,Ja=5e3,qa=4096,Ya=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 a=0;try{const i=await ge(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const h=(await i.json()).relayCount;typeof h=="number"&&h>0&&(a=Math.floor(h))}}catch{a=0}return Ht(Oe,qa),Oe.set(t,{expiresMs:n+Ja,relayCount:a}),a},Ct=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},be=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),Xa=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],Za=(e,t)=>{for(const n of Xa){e.delete(n);const r=t[n];r!==void 0&&e.set(n,r)}},Bt=(e,t)=>{const n=new Headers(e.headers),r=[...n.keys()];for(const a of r)a.startsWith("x-lunora-")&&n.delete(a);return Za(n,t),n},es=async(e,t,n)=>e.length===0||n.length===0?!1:Ze(await Gt(e,t),n),xt=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...a]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:Ze(t,a.join(" ").trim())},ts=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 Lr(t,r)?!0:n?!1:Ze(t,r)},ns=(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 ur(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return He(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return He(`queue:${e}`,!0);if(typeof n.connectionString=="string")return He(`hyperdrive:${e}`,!0)},rs=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})},Xt=e=>{rs(e);const t=ma(e.trustInboundTraceContext),n=wa(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",a=lr(e.resolveIdentity,e.identity),i=lt(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:lt(e.schedulerDO,e.jurisdiction);let h=!1;const p=o=>{if(o===void 0||e.jurisdiction===void 0)return o;h||(h=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},m=async(o,s,l,d=e.shardRegion?.(s))=>ge(o,s,p(d)).fetch(l);let A;const S=()=>e.adminToken??A;let T;const g=()=>e.requireEphemeralWsToken??T??!0;let y;const _=o=>{const s=o??{};if(y??=Ct(o,e.shardDO),T===void 0&&e.requireEphemeralWsToken===void 0){const d=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof d=="string"&&d.length>0&&(T=Br(d,!0))}if(A!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(A=l)},f=new WeakSet,O=o=>xt(o,S())||f.has(o),N=async o=>{if(!(e.adminGate===void 0||f.has(o)))try{await Se(e.adminGate(o,qe.get(o)))&&f.add(o)}catch{}},M=async(o,s)=>{const l=await de(o,s,e.resolveIdentity);if(f.has(o)&&l.headers.authorization===void 0){const d=S();d!==void 0&&(l.headers.authorization=`Bearer ${d}`)}return l};let k=!1,K=!1;const $=()=>{K||(K=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},W=o=>{if(!e.allowUnauthenticatedShardAccess){const s=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${o} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}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("")))},C=async(o,s)=>{if(s.includes(Ve)||s.includes(Je))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(e.authorizeShard){if(!await Se(e.authorizeShard({identity:o,shardKey:s})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==r&&W("shard")},V=Vo({defaultShard:r,forwardToShard:m,isAdmin:O,queryCoordinator:e.queryCoordinator,resolveForwardContext:M,shardDO:i}),F=async(o,s,l,d,w)=>{Ae(o);const b={"content-type":"application/json","x-lunora-system":"1"};return w?.userId!==void 0&&w.userId.length>0&&(b["x-lunora-userid"]=w.userId),w?.identity!==void 0&&w.identity.length>0&&(b["x-lunora-identity"]=w.identity),d!==void 0&&d.length>0&&(b["x-lunora-mutation-id"]=d),m(i,l,be(o,s,b))},J=async(o,s,l,d)=>{const w=l?.[o];if(!w||typeof w.create!="function")throw new c(`${d} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(gr(s))throw new c(`${d} params ${yr}`,{code:"BAD_REQUEST",status:400});await w.create({params:s})},Z=async(o,s)=>{if(o.workflow){await J(o.workflow,o.args??{},s,`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 l=await F(o.functionPath,o.args??{},o.shardKey??r);if(!l.ok)throw new c(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},H=o=>{if(!O(o))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},q=(o,s,l)=>{if(H(o),s===void 0)throw new c(l.message,{code:l.code,status:400});return s},G=async(o,s,l,d)=>{const w=e.cronJobs?.[o];if(!w)return 0;for(const b of w)try{await Z(b,s)}catch(I){l.push(d(I))}return w.length},fe=async(o,s)=>{if(H(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 ee(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 w=Object.values(e.cronJobs).flat().find(b=>b.name===d);if(!w)throw new c(`no cron job named "${d}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await Z(w,s),Response.json({name:d,ran:!0},{status:200})},ae=async o=>{const s=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!s||!u||typeof o.id!="string")return;const l=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await ge(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},_e=async(o,s)=>{j(o,"POST","Scheduler dispatch");const l=await jt(o),d=s??{},w=typeof d.LUNORA_SCHEDULER_SECRET=="string"?d.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof d.LUNORA_ADMIN_TOKEN=="string"?d.LUNORA_ADMIN_TOKEN:void 0),I=o.headers.get("x-lunora-scheduler-signature");let v=!1;if(I&&w?v=await es(w,l,I):b&&(v=xt(o,b)),!v)throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let E;try{E=JSON.parse(l)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const R=E??{},U=R.args??{};if(typeof R.workflow=="string"&&R.workflow.length>0)return await J(R.workflow,U,s,"scheduled workflow"),await ae(R),Response.json({ok:!0},{status:200});if(typeof R.functionPath!="string"||R.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const x=typeof R.shardKey=="string"&&R.shardKey.length>0?R.shardKey:r,B=typeof R.id=="string"&&R.id.length>0?R.id:void 0,ne=Ha(o),L=await F(R.functionPath,U,x,B,ne);return await ae(R),L},ke=Kr({assertAdmin:H,getReader:()=>e.authAuditReader}),Ie=async(o,s)=>{H(o);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:We({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const d=s?.kind,w=s?.userId,b=s?.limit,I=d==="fcm"||d==="web-push"?d:void 0,v=typeof w=="string"&&w!==""?w:void 0,E=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,R=E>0?Math.min(E,1e3):1e3,x=(await l.list({kind:I,limit:R,userId:v})).filter(B=>I!==void 0&&B.kind!==I?!1:v===void 0||(B.userId??null)===v).map(({keys:B,token:ne,...L})=>L);return Response.json({result:We({subscriptions:x})},{headers:{"content-type":"application/json"},status:200})},se=async(o,s)=>{if(!s.fanOut&&!(s.functionPath!==gt&&s.functionPath!==ja))return await N(o),s.functionPath===gt?ke(o,s.args??{}):Ie(o,s.args)},Zt=fo({applyGlobals:e.applyGlobals,assertAdmin:H,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:r,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:q,resolveForwardContext:M,shardDO:i,streamExportRows:(o,s,l,d)=>Wt(e,o,s,l,d,i),streamingImport:(o,s)=>yo(o,e,s,i),syncGlobals:e.syncGlobals}),Pe=(o,s)=>{const l=o.searchParams.get(s);return l===null||l===""?void 0:l},Ne=o=>{const s=new URL(o.url),l=s.searchParams.get("limit"),d=s.searchParams.get("offset"),w=l===null?void 0:Number.parseInt(l,10),b=d===null?void 0:Number.parseInt(d,10);return{limit:w!==void 0&&Number.isFinite(w)&&w>=0?w:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},nt=()=>{if(u===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},en=fa({checkWsAdmin:async o=>O(o)||ts(o,S(),g()),requireSchedulerNamespace:nt,resolveSchedulerStub:o=>(H(o),ge(nt(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),tn=Ta({assertAdmin:H,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),nn=tr({assertAdmin:H,parsePaging:Ne,queryParameter:Pe,readBodyBytes:qn,requireAdminOption:q,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),rn=to({options:e,readJsonBody:ee,requireAdminOption:q}),on=ba({readJsonBody:ee,requireAdminOption:q,vectorIntrospector:e.vectorIntrospector}),an=Uo({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:q}),sn=hr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:q}),cn=Po({assertAdmin:H,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ne,queryParameter:Pe,requireAdminOption:q}),dn=o=>{const s=[],l=i??o?.SHARD;if(l!==void 0&&s.push(dr("durable-object:default",l,r)),e.health?.disableBindingProbes!==!0)for(const[d,w]of Object.entries(o??{})){const b=ns(d,w);b!==void 0&&s.push(b)}for(const d of e.health?.probes??[])s.push(d);return s},un=cr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:O,resolveProbes:dn}),ln=o=>{const s=e.schedulerInstanceName??"default",l=()=>ge(o,s),d=async(E,R)=>{const U=await l().fetch(new Request(`https://scheduler.internal${E}`,R));if(!U.ok)throw new c(`ctx.scheduler: SchedulerDO ${E} failed (${String(U.status)}): ${await U.text()}`,{code:"INTERNAL",status:500});return await U.json()},w=async(E,R)=>await d(E,{body:JSON.stringify(R),headers:{"content-type":"application/json"},method:"POST"}),b=E=>{const R=E;if(R==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 R.binding=="string"&&R.binding.length>0)return{workflow:R.binding};if(typeof R.__lunoraRef=="string")return{functionPath:R.__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})},I=async()=>await br(async E=>d(E===void 0?"/list":`/list?cursor=${encodeURIComponent(E)}`,{method:"GET"})),v=async(E,R,U={})=>{const{id:x}=await w("/schedule",{args:U,scheduledFor:E,...b(R)});return x};return{cancel:async E=>await w("/cancel",{id:E}),get:async E=>await d(`/get?id=${encodeURIComponent(E)}`,{method:"GET"}),list:I,runAfter:async(E,R,U)=>{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 v(Date.now()+E,R,U)},runAt:async(E,R,U)=>{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 v(E,R,U)}}},hn=async(o,s,l)=>{const{claims:d,headers:w,userId:b}=await de(o,s,a),I=async(v,E={})=>{const R=v.__lunoraRef;if(typeof R!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Ae(R);const U=be(R,E,{...w,"x-lunora-system":"1"}),x=await m(i,r,U),B=await x.json();if(B.error)throw new c(B.error.message??"shard RPC failed",{code:B.error.code??"INTERNAL",status:x.status});return B.result};return{auth:{getIdentity:()=>Promise.resolve(d),userId:b},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),runAction:I,runMutation:I,runQuery:I,...u===void 0?{}:{scheduler:ln(u)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:wr(e.storage(s))}}},fn=async(o,s,l)=>{if(!e.httpRouter)return;const d=await hn(o,s,l);try{return await e.httpRouter.fetch(o,{...s,__lunoraCtx:d},l)}catch(w){return console.error("[lunora] httpRouter (SSR) handler threw:",w),new Response("Internal Server Error",{status:500})}},pn=async(o,s,l)=>{if(o.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const d=ft(o,ie);if(d)return d;const w=l.searchParams.get("shard")??r,{headers:b,identity:I}=await de(o,s,a);await C(I,w);const v=Bt(o,b),E=Ct(s,e.shardDO);if(E!==void 0){v.set("x-lunora-shard-binding",E);const R=await Ya(i,w);if(R>0){const U=Pr(w,Math.floor(Math.random()*R));return m(i,U,new Request(o,{headers:v}),pt(o))}}return m(i,w,new Request(o,{headers:v}))},mn=async(o,s,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 w=ft(o,ie);if(w)return w;let b;try{b=decodeURIComponent(l.pathname.slice(Dt.length))}catch{return new Response("Unknown voice agent",{status:404})}const I=Object.hasOwn(d,b)?d[b]:void 0;if(I===void 0)return new Response("Unknown voice agent",{status:404});const v=l.searchParams.get("threadKey");if(v===null||v.length===0)return new Response("Missing threadKey",{status:400});const{headers:E,identity:R}=await de(o,s,a);if(e.authorizeShard){if(!await Se(e.authorizeShard({identity:R,shardKey:v})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else W("shard");const U=Bt(o,E);return m(I,v,new Request(o,{headers:U}))},wn=async(o,s,l)=>{if(e.authorizeFanOut){if(!await Se(e.authorizeFanOut(l,o.table,s)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new c("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});W("fan-out")},Re=async(o,s)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await wn(o.fanOut,o.functionPath,s);return}await C(s,o.shardKey??r)}},gn=(o,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){$();return}if(e.functions[s]?.kind!=="query"||l.includes(Je)||l.includes(Ve))return;const d=pt(o);return d===void 0?void 0:{name:Nr(l,d),region:d}},yn=async(o,s,l,d,w)=>{const b=gn(o,s,d);if(b!==void 0){const I={...w,"x-lunora-replica-read":"1",...y===void 0?{}:{"x-lunora-shard-binding":y}},v=Dr(o.headers.get("x-lunora-min-seq"));v!==void 0&&(I["x-lunora-min-seq"]=String(v));const E=await m(i,b.name,be(s,l,I),b.region);if(E.status!==421)return E}return m(i,d,be(s,l,w))},De=async(o,s,l,d,w,b)=>{const I=Date.now(),{observability:v,sampling:E}=e,R=Qe(o),{decision:U,ignoredUpstream:x,trace:B}=na(o,{...E===void 0?{}:{sampling:E},trustInbound:t(o)});x&&n();const ne={...w,"x-lunora-sample-errors":U.keepErrors?"1":"0"};ra(B,ne);try{const L=await yn(o,s,l,d,ne);ce(v,{...R,...Nt(B),durationMs:Date.now()-I,functionPath:s,ok:L.ok,shardKey:d,...L.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(L.status)}`,status:L.status}}},b,void 0,{isTraced:B.sampled,keepErrors:U.keepErrors});const te=new Response(L.body,{headers:L.headers,status:L.status,statusText:L.statusText});return te.headers.set("x-lunora-shard-key",d),te}catch(L){throw ce(v,{...R,...Nt(B),...Te(s,Date.now()-I,L,{shardKey:d})},b,void 0,{isTraced:B.sampled,keepErrors:U.keepErrors}),L}},bn=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||Ae(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})},_n=async(o,s,l)=>{j(o,"POST","RPC");const d=await Va(o);Wa(s,d),bn(d);const w=await se(o,d);if(w!==void 0)return w;const{headers:b,identity:I}=await de(o,s,a);await Re(d,I);const v=ze(d,e);{const E=Date.now(),{observability:R}=e,U=Qe(o),x=Ee(s,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 te=await L.fanOut(i,{args:d.args??{},fanOut:d.fanOut,functionPath:d.functionPath,headers:b});return ce(R,{durationMs:Date.now()-E,fanOut:{failed:te.failed,shards:te.ok+te.failed,table:d.fanOut.table},functionPath:d.functionPath,...U,ok:!0},x),Response.json(te,{headers:{"content-type":"application/json"},status:200})}catch(te){throw ce(R,{...Te(d.functionPath,Date.now()-E,te,{fanOut:{table:d.fanOut.table}}),...U},x),te}}const B=d.shardKey??r,ne=()=>De(o,d.functionPath,d.args??{},B,b,x);return v&&e.x402Charge?e.x402Charge(o,{functionPath:d.functionPath,price:v.price},ne,Ge(l)):ne()}},Rn=async(o,s,l)=>{j(o,"POST","RPC batch");const d=await ee(o),{calls:w}=d;if(!Array.isArray(w))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:b,identity:I}=await de(o,s,a),v=ro(w,r);for(const Q of v.values())for(const z of Q)if(e.functions?.[z.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${Pt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...v.entries()].flatMap(([Q,z])=>z.map(re=>Re({args:re.args,functionPath:re.functionPath,shardKey:Q},I))));const{observability:E}=e,R=Ee(s,o,l&&(Q=>l.waitUntil?.(Q))),U=Qe(o),x=[],B=[],ne=(Q,z,re,ue)=>({body:{error:{code:re,message:ue}},id:Q.id,status:z}),L=(Q,z,re,ue,pe)=>{for(const Y of Q)ce(E,pe(Y),R),x.push(ne(Y,z,re,ue))},te=(Q,z,re,ue,pe)=>{for(const Y of Q){const me=ue.get(Y.id)??pe,ye=me<400;ce(E,{durationMs:re,functionPath:Y.functionPath,...U,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},R)}};await Promise.all([...v.entries()].map(async([Q,z])=>{const re=new Headers(b);re.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:re,method:"POST"}),pe=Date.now();let Y;try{Y=await m(i,Q,ue)}catch(X){const xe=Date.now()-pe,{body:it}=xn(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});L(z,502,it.code,it.message,Cn=>({...Te(Cn.functionPath,xe,X,{shardKey:Q}),...U}));return}const me=Date.now()-pe,ye=Y.headers.get("x-d1-bookmark");ye&&B.push(ye);let Ce;try{Ce=await Y.json()}catch{const X=`shard batch returned a non-JSON response (${String(Y.status)})`;L(z,Y.status,"SHARD_ERROR",X,xe=>({durationMs:me,error:{code:"SHARD_ERROR",message:X,status:Y.status},functionPath:xe.functionPath,...U,ok:!1,shardKey:Q}));return}const Be=Array.isArray(Ce.results)?Ce.results:[],Dn=new Map(Be.map(X=>[X.id,X.status??Y.status])),Un=new Set(Be.map(X=>X.id));te(z,Q,me,Dn,Y.status),x.push(...Be);for(const X of z)Un.has(X.id)||x.push(ne(X,Y.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const at={"content-type":"application/json"},[st]=B;return B.length===1&&st!==void 0&&(at["x-d1-bookmark"]=st),Response.json({results:x},{headers:at,status:200})},En=async(o,s,l,d={},w={})=>{try{const b=l.__lunoraRef;if(typeof b!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Ae(b);const{headers:I,identity:v}=await de(o,s,a,w.context),E={args:d,functionPath:b,shardKey:w.shardKey};await Re(E,v);const R=w.shardKey??r,U=Ee(s,o,w.waitUntil),x=()=>De(o,b,d,R,I,U),B=ze(E,e);return B&&e.x402Charge?await e.x402Charge(o,{functionPath:b,price:B.price},x,Ge(w.waitUntil?{waitUntil:w.waitUntil}:w.context)):await x()}catch(b){return ct(b)}},rt=async(o,s,l)=>{const{observability:d}=e,w=Date.now(),b=ve(16),I=ve(8),v=Ut(s);try{const E=await l();return ce(d,{durationMs:Date.now()-w,functionPath:o,ok:!0,spanId:I,traceId:b},v),E}catch(E){throw ce(d,{...Te(o,Date.now()-w,E,{}),spanId:I,traceId:b},v),E}finally{ut(d,v)}},An=async(o,s,l)=>{_(s);const d=[],w=R=>R instanceof Error?R:new Error(String(R)),b=e.crons?.[o.cron];if(b)try{await b(o,s,l)}catch(R){d.push(w(R))}const I=await G(o.cron,s,d,w),v=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron;if(v)try{await Yr(e,i,S(),o)}catch(R){d.push(w(R))}if(!b&&I===0&&!v){const R=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${o.cron}") fired but no cron handler is registered for that expression. Registered: ${R.length===0?"(none)":R.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[E]=d;if(d.length===1&&E)throw E;if(d.length>1)throw new AggregateError(d,`scheduled("${o.cron}") had ${String(d.length)} failure(s)`)},Sn=async(o,s)=>{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 m(i,r,be(Ma,{outcome:s},{authorization:`Bearer ${d}`,"content-type":"application/json"}))}catch{}},Tn=async(o,s,l,d)=>{if(!e.authHandler)return;const w=await e.authHandler(o);if(!w)return;const b=e.authBasePath??La;return Ka(l.pathname,b)&&d.waitUntil?.(Sn(s,w.status>=400?"fail":"ok")),w},On=async({args:o,env:s,functionPath:l,request:d,shardKey:w,waitUntil:b})=>{Mt(o,"REST");const I={functionPath:l,...w===void 0?{}:{shardKey:w}},{headers:v,identity:E}=await de(d,s,a);await Re(I,E);const R=w??r,U=Ee(s,d,b),x=()=>De(d,l,o,R,v,U),B=ze(I,e);return B&&e.x402Charge?e.x402Charge(d,{functionPath:l,price:B.price},x,Ge({waitUntil:b})):x()},vn=Jn({functions:e.functions??{},invoke:On,readJsonBody:ee,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ue=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,kn={[Ca]: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"}}),[ka]:(o,s,l)=>pn(o,s,l),[Pt]:(o,s,l,d)=>_n(o,s,d),[va]:(o,s,l,d)=>Rn(o,s,d),[Ia]:(o,s)=>_e(o,s),[Pa]:(o,s)=>fe(o,s),[Na]:async o=>{j(o,"POST","ws-token"),H(o);const s=S();if(s===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Hr(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...V,...Zt,...en,...tn,...nn,...rn,...on,...an,...sn,...cn,...un,...vn,...$r({assertAdmin:H,getAuthAdmin:()=>e.authAdmin,parsePaging:Ne,queryParameter:Pe,readJsonBody:ee})};let ie=ht(e.security),ot=!1;const In=o=>{ot||(ot=!0,ie=ht(e.security,o??{}))},Pn=async(o,s)=>{Ba(s)&&await N(o)},Nn=async(o,s,l)=>{qe.set(o,l);const d=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const v=Number(o.headers.get("content-length")??""),E=Oa[d.pathname]??Lt;if(Number.isFinite(v)&&v>E)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const w=await Tn(o,s,d,l);if(w)return w;if(Ue){const v=`${o.method} ${d.pathname}`,E=Ue[v]??Ue[d.pathname];if(E)return E(o,s,l)}const b=kn[d.pathname];if(b)return await Pn(o,d.pathname),b(o,s,d,l);if(e.voiceAgents!==void 0&&d.pathname.startsWith(Dt))return mn(o,s,d);const I=await fn(o,s,l);return I||new Response("Not found",{status:404})};return{async fetch(o,s,l){e.passThroughOnException&&l.passThroughOnException?.(),In(s),_(s);const d=pr(o,ie);if(d)return d;const w=mr(o,ie);if(w)return Le(w,o,ie);try{const b=await Nn(o,s,l);return Le(b,o,ie)}catch(b){return Le(ct(b),o,ie)}finally{ut(e.observability,Ut(l))}},async queue(o,s,l){await rt(`queue:${Ga(o)}`,l,async()=>{await e.queue?.(o,s,l)})},async scheduled(o,s,l){await rt(`cron:${o.cron}`,l,async()=>{await An(o,s,l)})},serverQuery:En}},os=e=>Xt(e),as=e=>typeof e=="function"?{fetch:e}:e,ss=e=>!!(e.crons??e.cronJobs??e.backupCron),ks=(e,t)=>{const n=as(e),r=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=u=>{const h=os({...u,httpRouter:n});return r!==void 0&&!ss(u)?{...h,scheduled:async(p,m,A)=>{await r(p,m,A)}}:h};if(typeof t!="function")return a(t);const i=t;return{fetch:(u,h,p)=>a(i(h)).fetch(u,h,p),queue:(u,h,p)=>a(i(h)).queue?.(u,h,p)??Promise.resolve(),scheduled:(u,h,p)=>a(i(h)).scheduled(u,h,p),serverQuery:(u,h,p,m,A)=>a(i(h)).serverQuery(u,h,p,m,A)}},is=(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}},Is=(e={})=>(t,n,r)=>Xt(is(e,n)).fetch(t,n,r??Hn),Ps=e=>e;export{gt as GET_AUTH_AUDIT_LOG_OP,Hn as NOOP_EXECUTION_CONTEXT,Us as composeIdentityResolvers,os as composeWorker,Is as createLunoraHandler,Xt as createWorker,Ps as defineRpcEnvelope,Ya as probeRelayCount,is as resolveLunoraOptions,Cs as routeIdentityResolvers,ks as withFrameworkWorker};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as O}from"./LunoraError-DksAgIpa.mjs";const E=new Set(["0","disabled","false","no","off"]),y=new Set(["1","enabled","on","true","yes"]),d=e=>typeof e=="string"&&E.has(e.trim().toLowerCase()),S=e=>typeof e=="string"&&y.has(e.trim().toLowerCase()),L="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",A=e=>{const o=["base-uri 'none'","object-src 'none'"];return e==="DENY"?o.push("frame-ancestors 'none'"):e==="SAMEORIGIN"&&o.push("frame-ancestors 'self'"),o.join("; ")},b="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",u=["Authorization","Content-Type","X-D1-Bookmark","X-Lunora-Client-Id","X-Lunora-Client-Seq","X-Lunora-Min-Seq","X-Lunora-Mutation-Id"],f=["DELETE","GET","HEAD","PATCH","POST","PUT"],C=31536e3,v=new Set(["GET","HEAD","OPTIONS"]),R=e=>{if(e===!1)return;const o=e===void 0||e===!0?{}:e,s=o.maxAge??C,r=o.includeSubDomains??!0;return`max-age=${String(s)}${r?"; includeSubDomains":""}${o.preload?"; preload":""}`},D=(e,o)=>{if(e!==!1)return typeof e=="string"?{htmlValue:e,value:e}:{htmlValue:o,value:L}},_=e=>{if(e===!1)return{coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0};const o=e===void 0||e===!0?{}:e,s=o.frameOptions===!1?void 0:o.frameOptions??"SAMEORIGIN";return{coop:"same-origin",csp:D(o.csp,A(s)),enabled:!0,frameOptions:s,hsts:R(o.hsts),permissionsPolicy:o.permissionsPolicy===!1?void 0:o.permissionsPolicy??b,referrerPolicy:o.referrerPolicy===!1?void 0:o.referrerPolicy??"strict-origin-when-cross-origin"}},N=e=>{const o={allowCredentials:!1,allowedHeaders:u,allowedMethods:f,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return o;const s=e.allowCredentials??!1,r=e.allowedOrigins;let t,n;if(typeof r=="function"){const a=m=>r(m)===!0;t=a,n=a,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${s?" AND reflects matching origins with credentials (`allowCredentials: true`)":""} — ensure it matches ONLY trusted origins by exact equality; an over-broad predicate (e.g. \`() => true\`, or \`endsWith\`/\`includes\` checks) defeats the allowlist.`)}else{const a=r;if(a.includes("*")&&s)throw new O('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=i=>a.includes("*")||a.includes(i),n=i=>a.includes(i)}return{allowCredentials:s,allowedHeaders:e.allowedHeaders??u,allowedMethods:e.allowedMethods??f,enabled:!0,isAllowed:t,isExplicitlyAllowed:n,maxAge:e.maxAge??600}},H=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const o=e===void 0||e===!0?{}:e;return{allowLoopback:o.allowLoopback??!0,enabled:!0,trustedOrigins:o.trustedOrigins??[]}},I=e=>{const o=e?.LUNORA_ALLOWED_ORIGINS;if(typeof o!="string")return;const s=o.split(",").map(n=>n.trim()).filter(n=>n.length>0);return s.length===0?void 0:{allowCredentials:!s.includes("*")&&S(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:s}},j=(e,o)=>{const s=e?.headers??(d(o?.LUNORA_SECURITY_HEADERS)?!1:void 0),r=e?.csrf??(d(o?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??I(o);return{cors:N(t),csrf:H(r),headers:_(s)}},P=new Set(["127.0.0.1","::1","[::1]","localhost"]),p=e=>{try{return P.has(new URL(e).hostname)}catch{return!1}},c=e=>{if(e)try{return new URL(e).origin}catch{return}},w=(e,o,s)=>e===o||s.csrf.trustedOrigins.includes(e)||s.csrf.allowLoopback&&p(o)&&p(e)?!0:s.cors.enabled&&s.cors.isExplicitlyAllowed(e),h=(e,o,s)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:s,message:`${e} rejected: Origin ${o===void 0?"was missing":`"${o}"`} is not trusted (this worker serves "${s}"). Add it to \`security.csrf.trustedOrigins\` (or LUNORA_ALLOWED_ORIGINS) if it is yours. Behind a dev proxy this usually means the proxy rewrote the host: keep both ends on loopback, or list the dev-server origin.`,receivedOrigin:o}},{headers:{"content-type":"application/json"},status:403}),F=(e,o)=>{if(!o.csrf.enabled||v.has(e.method)||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"))??c(e.headers.get("referer"));if(!(r!==void 0&&w(r,s,o)))return h("cross-origin state-changing request",r,s)},X=(e,o)=>{if(!o.csrf.enabled||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"));if(!(r!==void 0&&w(r,s,o)))return h("cross-origin websocket upgrade",r,s)},T=["X-D1-Bookmark","X-Lunora-Edge-Cache","X-Lunora-Shard-Key"],g=(e,o)=>{const s=new Headers;return s.set("access-control-allow-origin",e),s.set("access-control-expose-headers",T.join(", ")),s.append("vary","Origin"),o.allowCredentials&&s.set("access-control-allow-credentials","true"),s},B=(e,o)=>{if(!o.cors.enabled||e.method!=="OPTIONS")return;const s=e.headers.get("origin");if(!s||!e.headers.get("access-control-request-method")||!o.cors.isAllowed(s))return;const r=g(s,o.cors),t=e.headers.get("access-control-request-headers");r.set("access-control-allow-methods",o.cors.allowedMethods.join(", "));let n;if(t===null)n=o.cors.allowedHeaders.join(", ");else{const a=new Set(o.cors.allowedHeaders.map(i=>i.toLowerCase()));n=t.split(",").map(i=>i.trim()).filter(i=>i.length>0&&a.has(i.toLowerCase())).join(", ")}return r.set("access-control-allow-headers",n),r.set("access-control-max-age",String(o.cors.maxAge)),new Response(null,{headers:r,status:204})},x=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),l=(e,o,s)=>{e.has(o)||e.set(o,s)},k=(e,o,s,r)=>{if(r.hsts!==void 0&&new URL(o.url).protocol==="https:"&&l(e,"strict-transport-security",r.hsts),l(e,"x-content-type-options","nosniff"),r.frameOptions!==void 0&&l(e,"x-frame-options",r.frameOptions),r.referrerPolicy!==void 0&&l(e,"referrer-policy",r.referrerPolicy),r.permissionsPolicy!==void 0&&l(e,"permissions-policy",r.permissionsPolicy),r.coop!==void 0&&l(e,"cross-origin-opener-policy",r.coop),r.csp!==void 0){const t=x(s)?r.csp.htmlValue:r.csp.value;t!==void 0&&l(e,"content-security-policy",t)}},U=(e,o,s)=>{const r=o.headers.get("origin");if(!(!r||!s.isAllowed(r)))for(const[t,n]of g(r,s).entries())t==="vary"?e.append("vary",n):l(e,t,n)},V=(e,o,s)=>{if(e.status===101||e.webSocket)return e;const r=new Headers(e.headers);return s.headers.enabled&&k(r,o,e,s.headers),s.cors.enabled&&U(r,o,s.cors),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})};export{V as decorateResponse,F as enforceOrigin,X as enforceWebSocketOrigin,B as handleCorsPreflight,j as resolveSecurity};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as S,d as T,e as O,a as P,f as B}from"./rest-cache-D1BlbZb1.mjs";import{LunoraError as l}from"./LunoraError-DksAgIpa.mjs";import{m as D}from"./method-guard-BG_vJNTl.mjs";const w=1048576,p=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),U=async(t,r=w)=>{if(!t.body)return"";const e=t.body.getReader(),a=new TextDecoder;let s=0,i="";for(;;){const{done:o,value:n}=await e.read();if(o)break;if(n){if(s+=n.byteLength,s>r)throw await e.cancel().catch(()=>{}),new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});i+=a.decode(n,{stream:!0})}}return i+=a.decode(),i},W=async(t,r=w)=>{if(!t.body)return new ArrayBuffer(0);const e=t.body.getReader(),a=[];let s=0;for(;;){const{done:n,value:c}=await e.read();if(n)break;if(c){if(s+=c.byteLength,s>r)throw await e.cancel().catch(()=>{}),new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});a.push(c)}}const i=new Uint8Array(s);let o=0;for(const n of a)i.set(n,o),o+=n.byteLength;return i.buffer},j=async(t,r,e=w)=>{try{const a=await U(t,e);return a===""?{}:JSON.parse(a)}catch(a){throw a instanceof l?a:new l(`${r} body must be valid JSON`,{code:"BAD_REQUEST",status:400})}},I=async(t,r=w)=>{const e=await j(t,"Request",r);if(!p(e))throw new l("Request body must be an object",{code:"BAD_REQUEST",status:400});return e},x=(t,r)=>{if(!p(t))throw new l(`${r} \`args\` must be an object`,{code:"BAD_REQUEST",status:400})},R="__lunora_vary",G="x-lunora-edge-cache",C=["x-d1-bookmark","x-lunora-shard-key"],M=()=>{try{return globalThis.caches?.default}catch{return}},L=t=>t.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r!==""),J=(t,r)=>{const e=t.headers.get("vary");return e===null?!0:L(e).every(a=>a!=="*"&&r.includes(a))},Y=(t,r)=>{if(t===void 0||r===null||t.scope!=="public"||S(t.maxAge)<=0)return;const e=()=>r??M(),a=L(T(t)??""),s=o=>{const n=new URL(o.url);return n.searchParams.delete(R),a.length>0&&n.searchParams.set(R,a.map(c=>`${c}=${o.headers.get(c)??""}`).join("\0")),new Request(n.toString(),{method:"GET"})},i=(o,n)=>o.method==="GET"&&O(t,o,n)==="public";return{lookup:async(o,n)=>{const c=e();if(c===void 0||!i(o,n))return;let u;try{u=await c.match(s(o))}catch{return}if(u===void 0)return;const h=new Response(u.body,u);return h.headers.set(G,"hit"),h},store:(o,n,c)=>{const u=e();if(u===void 0||!i(n,c)||o.status!==200||o.headers.has("set-cookie")||o.headers.has("x-payment-response")||!J(o,a))return o;try{const h=new Response(o.clone().body,o);for(const b of C)h.headers.delete(b);const d=Promise.resolve(u.put(s(n),h)).catch(()=>{});c?.waitUntil&&c.waitUntil(d)}catch{}return o}}},H=t=>B(Object.entries(t).map(([r,e])=>({exposure:e.expose,functionPath:r,kind:e.kind}))),K=(t,r)=>{const e=t.searchParams.get("shardKey");if(e!==null&&e!=="")return e;const a=r.headers.get("x-lunora-shard-key");return a===null||a===""?void 0:a},Q=t=>{const r=Object.create(null);for(const[e,a]of t.searchParams.entries())if(!(e==="shardKey"||e===R))try{r[e]=JSON.parse(a)}catch{r[e]=a}return r},X=t=>{const{edgeCache:r,functions:e,invoke:a,rateLimit:s,readJsonBody:i}=t,o={};for(const n of H(e)){const c=n.kind==="query"?["GET","POST"]:["POST"],u=e[n.functionPath].expose?.cache,h=Y(u,r);o[n.path]=async(d,b,F,f)=>{const g=D(d,c);if(g)return g;const v=new URL(d.url);if(s){const m=await s(d,n.functionPath);if(m)return m}const E=await h?.lookup(d,f);if(E)return E;let y;d.method==="GET"?y=Q(v):y=d.body===null?{}:await i(d),x(y,"REST");const A=K(v,d),_=await a({args:y,env:b,functionPath:n.functionPath,request:d,...A===void 0?{}:{shardKey:A},...f?.waitUntil===void 0?{}:{waitUntil:m=>f.waitUntil?.(m)}}),k=P(_,u,d,f);return h?h.store(k,d,f):k}}return o},z=(t,r)=>async(e,a)=>{const s=r.key?r.key(e,a):e.headers.get("cf-connecting-ip")??void 0,i=await t.limit(r.name,s===void 0?{}:{key:s});if(i.ok)return;const o=Math.max(1,Math.ceil(i.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(o)},status:429})};export{w as M,Q as a,X as b,z as c,I as d,j as e,W as f,x as g,U as h,H as r};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as d,b as E}from"./base64-Bl1_r2k1.mjs";const o="$lunora.wire$",w=64,g=1024,p="__proto__",A={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},l={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},O=e=>{if(e===null||typeof e!="object")return!1;const n=Object.getPrototypeOf(e);return n===null||n===Object.prototype},a=(e,n=0)=>{if(n>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(e===void 0)return[o,"undefined"];if(e===null)return null;const y=typeof e;if(y==="bigint")return[o,"bigint",e.toString()];if(y==="number"){const r=e;return Number.isNaN(r)?[o,"nan"]:r===1/0?[o,"inf"]:r===-1/0?[o,"-inf"]:r}if(y!=="object")return e;if(e instanceof Date)return[o,"date",a(e.getTime(),n+1)];if(e instanceof Error){const r=e,t={};for(const s of Object.keys(r))r[s]!==void 0&&(t[s]=a(r[s],n+1));const i=[o,"error",r.name,r.message,t];return r.cause!==void 0&&i.push(a(r.cause,n+1)),i}if(e instanceof URL)return[o,"url",e.href];if(e instanceof Map)return[o,"map",[...e.entries()].map(([r,t])=>[a(r,n+1),a(t,n+1)])];if(e instanceof Set)return[o,"set",[...e].map(r=>a(r,n+1))];if(e instanceof ArrayBuffer)return[o,"bytes",d(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,t=r.constructor.name,i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return t==="Uint8Array"?[o,"bytes",d(i)]:[o,"bytes",d(i),t]}if(Array.isArray(e)){const r=e.map(t=>a(t,n+1));return r.length>0&&r[0]===o?[o,"arr",r]:r}if(!O(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const u=e,c={};for(const r of Object.keys(u)){const t=u[r];if(t===void 0)continue;const i=a(t,n+1);r===p?Object.defineProperty(c,r,{configurable:!0,enumerable:!0,value:i,writable:!0}):c[r]=i}return c},f=(e,n=0)=>{if(n>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===o)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>f(r,n+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>g||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${g} digits)`);return BigInt(r)}case"date":{const r=f(e[2],n+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(t=>{if(!Array.isArray(t)||t.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[f(t[0],n+1),f(t[1],n+1)]}))}case"set":return new Set(e[2].map(r=>f(r,n+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],t=e[3],i=(Object.hasOwn(l,r)?l[r]:void 0)??Error,s=new i(t);s.name!==r&&Object.defineProperty(s,"name",{configurable:!0,value:r,writable:!0});const b=f(e[4],n+1);if(b===null||typeof b!="object"||Array.isArray(b))throw new TypeError("wire-codec: malformed error — props must be an object");for(const m of Object.keys(b))m===p?Object.defineProperty(s,m,{configurable:!0,enumerable:!0,value:b[m],writable:!0}):s[m]=b[m];return e.length>5&&Object.defineProperty(s,"cause",{configurable:!0,value:f(e[5],n+1),writable:!0}),s}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const t=E(r),i=e[3]??"Uint8Array";if(i==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const s=Object.hasOwn(A,i)?A[i]:void 0;return s?new s(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>f(r,n+1))}return e.map(c=>f(c,n+1))}const y=e,u={};for(const c of Object.keys(y)){const r=f(y[c],n+1);c===p?Object.defineProperty(u,c,{configurable:!0,enumerable:!0,value:r,writable:!0}):u[c]=r}return u};export{f as d,a as e,O as i};
|