@lunora/runtime 1.0.0-alpha.72 → 1.0.0-alpha.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -3431,6 +3431,21 @@ interface NotifySubscriptionFilter {
3431
3431
  /** Restrict to a single owning user. */
3432
3432
  userId?: null | string;
3433
3433
  }
3434
+ /**
3435
+ * The caller a {@link WorkerOptions.authorizeShard} decision is made for.
3436
+ *
3437
+ * Every value that reaches this gate originates OUTSIDE the trust boundary — an
3438
+ * RPC, a REST call, a WebSocket upgrade, an in-process `serverQuery`. Dispatch
3439
+ * that originates INSIDE it (a firing cron, a scheduler job) never reaches the
3440
+ * gate at all, so `identity: null` means exactly one thing here: an
3441
+ * unauthenticated end user.
3442
+ */
3443
+ interface ShardCaller {
3444
+ /** The identity `resolveIdentity` produced for this request, or `null` when the caller is unauthenticated. */
3445
+ identity: ResolvedIdentity | null;
3446
+ /** The shard the caller named (the default shard when the request named none). */
3447
+ shardKey: string;
3448
+ }
3434
3449
  interface WorkerOptions {
3435
3450
  /**
3436
3451
  * An additional, async authorization gate for the `/_lunora/admin/*` plane
@@ -3552,14 +3567,23 @@ interface WorkerOptions {
3552
3567
  */
3553
3568
  authorizeFanOut?: (identity: ResolvedIdentity | null, table: string, functionPath: string) => boolean | Promise<boolean>;
3554
3569
  /**
3555
- * Optional per-shard authorization callback. Called from both the RPC
3556
- * dispatch path and the WebSocket upgrade path after `resolveIdentity`
3557
- * has produced an identity but before the request is forwarded to the
3558
- * named shard. Returning `false` (or a promise resolving to `false`)
3559
- * causes the runtime to reject the request with a 403
3560
- * `FORBIDDEN_SHARD` error. When unset, the runtime allows the
3561
- * request preserving the historical "any client may name any
3562
- * shard" posture.
3570
+ * Optional per-shard authorization callback for CLIENT-ORIGINATED access.
3571
+ * Called from the RPC, REST, in-process `serverQuery`, and WebSocket-upgrade
3572
+ * paths after `resolveIdentity` has produced an identity but before the
3573
+ * request is forwarded to the named shard. Returning `false` (or a promise
3574
+ * resolving to `false`) rejects the request with a 403 `FORBIDDEN_SHARD`.
3575
+ * When unset, naming a non-default shard is default-denied unless the worker
3576
+ * opts into open access with `allowUnauthenticatedShardAccess: true`.
3577
+ *
3578
+ * SCOPE — this is a gate on CALLERS, so it only ever runs where there is one.
3579
+ * Server-initiated dispatch (a firing cron, a scheduler job) does NOT pass
3580
+ * through it: those originate inside the trust boundary (the worker's own
3581
+ * `scheduled()` handler, or the HMAC/admin-bearer-gated scheduler endpoint,
3582
+ * which authenticates first), and they carry no end-user identity to judge.
3583
+ * The reserved `__lunora_admin__:*` RPCs are exempt for the same reason.
3584
+ * A gate that sees `identity: null` is therefore always looking at an
3585
+ * anonymous END USER, and `({ identity }) => identity?.userId !== undefined`
3586
+ * is a correct, complete gate — it cannot starve the scheduler.
3563
3587
  *
3564
3588
  * Note: this callback does NOT gate fan-out envelopes — fan-out
3565
3589
  * targets every live shard for a table and must be authorized at the
@@ -3567,7 +3591,7 @@ interface WorkerOptions {
3567
3591
  * without `authorizeFanOut` causes fan-out envelopes to be denied by
3568
3592
  * default.
3569
3593
  */
3570
- authorizeShard?: (identity: ResolvedIdentity | null, shardKey: string) => boolean | Promise<boolean>;
3594
+ authorizeShard?: (caller: ShardCaller) => boolean | Promise<boolean>;
3571
3595
  /**
3572
3596
  * Cron expression that triggers the built-in backup. When set alongside
3573
3597
  * {@link WorkerOptions.backupStore} and {@link WorkerOptions.adminToken}, the
@@ -5003,4 +5027,4 @@ export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolve
5003
5027
  * surface — without a name for it, a caller cannot hoist a shared attribute bag
5004
5028
  * into a typed constant.
5005
5029
  */
5006
- type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
5030
+ type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
package/dist/index.d.ts CHANGED
@@ -3431,6 +3431,21 @@ interface NotifySubscriptionFilter {
3431
3431
  /** Restrict to a single owning user. */
3432
3432
  userId?: null | string;
3433
3433
  }
3434
+ /**
3435
+ * The caller a {@link WorkerOptions.authorizeShard} decision is made for.
3436
+ *
3437
+ * Every value that reaches this gate originates OUTSIDE the trust boundary — an
3438
+ * RPC, a REST call, a WebSocket upgrade, an in-process `serverQuery`. Dispatch
3439
+ * that originates INSIDE it (a firing cron, a scheduler job) never reaches the
3440
+ * gate at all, so `identity: null` means exactly one thing here: an
3441
+ * unauthenticated end user.
3442
+ */
3443
+ interface ShardCaller {
3444
+ /** The identity `resolveIdentity` produced for this request, or `null` when the caller is unauthenticated. */
3445
+ identity: ResolvedIdentity | null;
3446
+ /** The shard the caller named (the default shard when the request named none). */
3447
+ shardKey: string;
3448
+ }
3434
3449
  interface WorkerOptions {
3435
3450
  /**
3436
3451
  * An additional, async authorization gate for the `/_lunora/admin/*` plane
@@ -3552,14 +3567,23 @@ interface WorkerOptions {
3552
3567
  */
3553
3568
  authorizeFanOut?: (identity: ResolvedIdentity | null, table: string, functionPath: string) => boolean | Promise<boolean>;
3554
3569
  /**
3555
- * Optional per-shard authorization callback. Called from both the RPC
3556
- * dispatch path and the WebSocket upgrade path after `resolveIdentity`
3557
- * has produced an identity but before the request is forwarded to the
3558
- * named shard. Returning `false` (or a promise resolving to `false`)
3559
- * causes the runtime to reject the request with a 403
3560
- * `FORBIDDEN_SHARD` error. When unset, the runtime allows the
3561
- * request preserving the historical "any client may name any
3562
- * shard" posture.
3570
+ * Optional per-shard authorization callback for CLIENT-ORIGINATED access.
3571
+ * Called from the RPC, REST, in-process `serverQuery`, and WebSocket-upgrade
3572
+ * paths after `resolveIdentity` has produced an identity but before the
3573
+ * request is forwarded to the named shard. Returning `false` (or a promise
3574
+ * resolving to `false`) rejects the request with a 403 `FORBIDDEN_SHARD`.
3575
+ * When unset, naming a non-default shard is default-denied unless the worker
3576
+ * opts into open access with `allowUnauthenticatedShardAccess: true`.
3577
+ *
3578
+ * SCOPE — this is a gate on CALLERS, so it only ever runs where there is one.
3579
+ * Server-initiated dispatch (a firing cron, a scheduler job) does NOT pass
3580
+ * through it: those originate inside the trust boundary (the worker's own
3581
+ * `scheduled()` handler, or the HMAC/admin-bearer-gated scheduler endpoint,
3582
+ * which authenticates first), and they carry no end-user identity to judge.
3583
+ * The reserved `__lunora_admin__:*` RPCs are exempt for the same reason.
3584
+ * A gate that sees `identity: null` is therefore always looking at an
3585
+ * anonymous END USER, and `({ identity }) => identity?.userId !== undefined`
3586
+ * is a correct, complete gate — it cannot starve the scheduler.
3563
3587
  *
3564
3588
  * Note: this callback does NOT gate fan-out envelopes — fan-out
3565
3589
  * targets every live shard for a table and must be authorized at the
@@ -3567,7 +3591,7 @@ interface WorkerOptions {
3567
3591
  * without `authorizeFanOut` causes fan-out envelopes to be denied by
3568
3592
  * default.
3569
3593
  */
3570
- authorizeShard?: (identity: ResolvedIdentity | null, shardKey: string) => boolean | Promise<boolean>;
3594
+ authorizeShard?: (caller: ShardCaller) => boolean | Promise<boolean>;
3571
3595
  /**
3572
3596
  * Cron expression that triggers the built-in backup. When set alongside
3573
3597
  * {@link WorkerOptions.backupStore} and {@link WorkerOptions.adminToken}, the
@@ -5003,4 +5027,4 @@ export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolve
5003
5027
  * surface — without a name for it, a caller cannot hoist a shared attribute bag
5004
5028
  * into a typed constant.
5005
5029
  */
5006
- type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
5030
+ type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
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-CZimuevO.mjs";import{composeWorker as S,createLunoraHandler as x,createWorker as _,defineRpcEnvelope as d,resolveLunoraOptions as l,withFrameworkWorker as u}from"./packem_shared/composeWorker-D41ytQme.mjs";import{createCrossShardRelationCapabilities as k}from"./packem_shared/createCrossShardRelationCapabilities-DgQYQzd1.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as C,createDynamicShardRegistry as L}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as b,toErrorResponse as g}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{createKvCursorStore as H,createMemoryCursorStore as I,defineExportSink as P,r2Sink as v,runExportTap as D,sanitizeChange as F,webhookExportSink as M}from"./packem_shared/createKvCursorStore-kQ8HNv0l.mjs";import{HEALTH_PATH as K,HEALTH_READY_PATH as N,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-jZsuCmSs.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-jgHjdsz2.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-vDK-rMbs.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-BgmqAmTM.mjs";import{D as pe,a as ce,c as me}from"./packem_shared/pipeline-log-reader-BGrl66P5.mjs";import{createQueryCoordinator as Ee,createStaticShardRegistry as Re,mergeStrategyForAggregate as Se}from"./packem_shared/createQueryCoordinator-CnNyazLX.mjs";import{applyJurisdiction as _e,resolveShard as de}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as ye,b as ke}from"./packem_shared/rest-cache-CPSyD1RD.mjs";import{a as Ae,b as Ce,c as Le,r as Te,d as be}from"./packem_shared/rest-routes-Dq17Zntv.mjs";import{decorateResponse as he,enforceOrigin as He,handleCorsPreflight as Ie,resolveSecurity as Pe}from"./packem_shared/decorateResponse-BuqVnrmc.mjs";import{createShardClient as De}from"./packem_shared/createShardClient-CCncsgTs.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Me}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ke}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ue}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ye,routeIdentityResolvers as we}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,ce as DEFAULT_LOG_LIMIT,A as DEFAULT_REGISTRY_CACHE_TTL_MS,K as HEALTH_PATH,N as HEALTH_READY_PATH,Ke as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,b as LunoraError,Ue as NOOP_EXECUTION_CONTEXT,C as SHARD_REGISTRY_DO_NAME,Me as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,_e as applyJurisdiction,ue as applyRestCache,Ae as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ye as composeIdentityResolvers,S as composeWorker,oe as consoleSink,k as createCrossShardRelationCapabilities,L as createDynamicShardRegistry,H as createKvCursorStore,x as createLunoraHandler,I as createMemoryCursorStore,me as createPipelineLogReader,Ee as createQueryCoordinator,Le as createRestRateLimit,De as createShardClient,Re as createStaticShardRegistry,_ as createWorker,B as d1Probe,he as decorateResponse,P as defineExportSink,d as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,He as enforceOrigin,Ie as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,Se as mergeStrategyForAggregate,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,v as r2Sink,Te as readShardKey,ye as requestCarriesCredentials,j as resolveLogArchiveFromEnv,l as resolveLunoraOptions,Pe as resolveSecurity,de as resolveShard,ke as restCacheHeaders,be as restSurfaceFromRegistry,we as routeIdentityResolvers,D as runExportTap,F as sanitizeChange,se as sentrySink,f as toAirbyteMessages,g as toErrorResponse,E as toFivetranResponse,M as webhookExportSink,ie as webhookSink,u as withFrameworkWorker};
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-CZimuevO.mjs";import{composeWorker as S,createLunoraHandler as x,createWorker as _,defineRpcEnvelope as d,resolveLunoraOptions as l,withFrameworkWorker as u}from"./packem_shared/composeWorker-DFhiNfmF.mjs";import{createCrossShardRelationCapabilities as k}from"./packem_shared/createCrossShardRelationCapabilities-DgQYQzd1.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as C,createDynamicShardRegistry as L}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as b,toErrorResponse as g}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{createKvCursorStore as H,createMemoryCursorStore as I,defineExportSink as P,r2Sink as v,runExportTap as D,sanitizeChange as F,webhookExportSink as M}from"./packem_shared/createKvCursorStore-kQ8HNv0l.mjs";import{HEALTH_PATH as K,HEALTH_READY_PATH as N,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-jZsuCmSs.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-jgHjdsz2.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-vDK-rMbs.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-BgmqAmTM.mjs";import{D as pe,a as ce,c as me}from"./packem_shared/pipeline-log-reader-BGrl66P5.mjs";import{createQueryCoordinator as Ee,createStaticShardRegistry as Re,mergeStrategyForAggregate as Se}from"./packem_shared/createQueryCoordinator-CnNyazLX.mjs";import{applyJurisdiction as _e,resolveShard as de}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as ye,b as ke}from"./packem_shared/rest-cache-CPSyD1RD.mjs";import{a as Ae,b as Ce,c as Le,r as Te,d as be}from"./packem_shared/rest-routes-Dq17Zntv.mjs";import{decorateResponse as he,enforceOrigin as He,handleCorsPreflight as Ie,resolveSecurity as Pe}from"./packem_shared/decorateResponse-BuqVnrmc.mjs";import{createShardClient as De}from"./packem_shared/createShardClient-CCncsgTs.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Me}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ke}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ue}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ye,routeIdentityResolvers as we}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,ce as DEFAULT_LOG_LIMIT,A as DEFAULT_REGISTRY_CACHE_TTL_MS,K as HEALTH_PATH,N as HEALTH_READY_PATH,Ke as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,b as LunoraError,Ue as NOOP_EXECUTION_CONTEXT,C as SHARD_REGISTRY_DO_NAME,Me as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,_e as applyJurisdiction,ue as applyRestCache,Ae as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ye as composeIdentityResolvers,S as composeWorker,oe as consoleSink,k as createCrossShardRelationCapabilities,L as createDynamicShardRegistry,H as createKvCursorStore,x as createLunoraHandler,I as createMemoryCursorStore,me as createPipelineLogReader,Ee as createQueryCoordinator,Le as createRestRateLimit,De as createShardClient,Re as createStaticShardRegistry,_ as createWorker,B as d1Probe,he as decorateResponse,P as defineExportSink,d as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,He as enforceOrigin,Ie as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,Se as mergeStrategyForAggregate,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,v as r2Sink,Te as readShardKey,ye as requestCarriesCredentials,j as resolveLogArchiveFromEnv,l as resolveLunoraOptions,Pe as resolveSecurity,de as resolveShard,ke as restCacheHeaders,be as restSurfaceFromRegistry,we as routeIdentityResolvers,D as runExportTap,F as sanitizeChange,se as sentrySink,f as toAirbyteMessages,g as toErrorResponse,E as toFivetranResponse,M as webhookExportSink,ie as webhookSink,u as withFrameworkWorker};
@@ -3,4 +3,4 @@ import{isLunoraError as Dn,toErrorBody as Nn}from"@lunora/errors";import{e as Dt
3
3
  `,{customMetadata:{[Qt]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:D}=await Ve(a,v,e.backupRetain,r.cron);if(D.length>0){const T=D.slice(0,Gt),x=D.length-T.length;console.info(`[lunora] backup retention: ${String(D.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${T.join(", ")}${x>0?` (+${String(x)} more)`:""}`)}}catch(D){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,D)}},Gr=async(e,n)=>{const t=e.backupStore;if(!t)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 $r(t,Ge(e.backupPrefix??Qe),a,r,n)},Qr="/_lunora/admin/backup/retention",zr="/_lunora/admin/backup/prune",Wr=e=>{const{options:n,readJsonBody:t,requireAdminOption:r}=e,a=(u,f)=>{r(u,n.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},s=async u=>(j(u,"GET","Backup-retention"),a(u,"retention preview"),Response.json(await Kr(n),{headers:{"cache-control":"no-store"}})),l=async u=>{j(u,"POST","Backup-prune"),a(u,"prune");const{confirm:f}=await t(u);if(!Array.isArray(f)||f.some(g=>typeof g!="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 Gr(n,f),{headers:{"cache-control":"no-store"}})};return{[zr]:l,[Qr]:s}},pt=500,Vr=(e,n,t)=>{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:n,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:t}},Jr=(e,n)=>{if(e.length>pt)throw new d(`RPC batch exceeds the ${String(pt)}-call limit`,{code:"BAD_REQUEST",status:400});const t=new Map;for(const[r,a]of e.entries()){const{entry:s,shardKey:l}=Vr(a,r,n),u=t.get(l)??[];u.push(s),t.set(l,u)}return t},qr=new TextEncoder,Yr=e=>{const n=JSON.stringify(e),t=qr.encode(n);let r="";for(const a of t)r+=String.fromCodePoint(a);return btoa(r).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Xr=e=>{const n={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return n;try{const t=atob(e.replaceAll("-","+").replaceAll("_","/")),r=new Uint8Array(t.length);for(let u=0;u<t.length;u+=1)r[u]=t.codePointAt(u)??0;const a=JSON.parse(new TextDecoder().decode(r)),s=a.s&&typeof a.s=="object"?a.s:{},l={};for(const[u,f]of Object.entries(s))typeof f=="number"&&Number.isFinite(f)&&(l[u]=f);return{g:typeof a.g=="number"&&Number.isFinite(a.g)?a.g:0,s:l,v:1}}catch{return n}},Zr=e=>{const n=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",r=t==="delete"||t==="insert"||t==="update"?t:"upsert",a=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(a===void 0?{}:{_id:a}),op:r,table:n}},mt=(e,n,t)=>{for(const r of n)e.push(Zr(r));return t!==void 0&&n.length>=t},eo="/_lunora/admin/export",to="/_lunora/admin/import",no="/_lunora/admin/sync",ro="/_lunora/admin/connector/sync",oo="/_lunora/admin/apply",ao="/_lunora/admin/export-tap/run",so=new TextEncoder,io=async e=>{const t=await be(e,"Export")??{};if(t.tables===void 0)return{tables:void 0};if(!Array.isArray(t.tables))throw new d("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const a of t.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}},He=e=>Array.isArray(e)?e.filter(n=>typeof n=="string"):void 0,co=e=>{const{applyGlobals:n,exportCursorStore:t,exportSinks:r,knownTables:a,queryCoordinator:s,assertAdmin:l,requireAdminOption:u,resolveForwardContext:f,shardDO:g,streamExportRows:E,streamingImport:k,syncGlobals:v}=e,w=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),U=await io(T),{headers:W}=await f(T,x),K=new ReadableStream({async pull(V){const X=J=>{V.enqueue(so.encode(`${JSON.stringify(J)}
4
4
  `))};try{await E($,W,U.tables,X),V.close()}catch(J){V.error(J)}}});return new Response(K,{headers:{"content-type":"application/x-ndjson"},status:200})},b=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),U=await Z(T),W=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},K=typeof U.limit=="number"?U.limit:void 0,V=typeof U.globalCursor=="number"?U.globalCursor:0,X=He(U.tables),{headers:J}=await f(T,x),ae=X??a(),F=await $.orchestrateCdcSync(g,{cursors:W,headers:J,limit:K,tables:ae}),he=v?await v({limit:K,sinceSeq:V}):void 0;return Response.json({global:he,shards:F.shards},{status:200})},_=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),U=await Z(T),W=Xr(U.cursor),K=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,V=He(U.tables),{headers:X}=await f(T,x),J=V??a(),ae=await $.orchestrateCdcSync(g,{cursors:W.s,headers:X,limit:K,tables:J}),F=[],he={...W.s};let G=!1;for(const se of ae.shards)G=mt(F,se.changes??[],K)||G,he[se.shardKey]=se.cursor;let oe=W.g;if(v){const se=await v({limit:K,sinceSeq:W.g});G=mt(F,se.changes,K)||G,oe=se.cursor}const Te=Yr({g:oe,s:he,v:1}),Oe={changes:F,hasMore:G,nextCursor:Te};return Response.json(Oe,{status:200})},p=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),U=await Z(T),K=(Array.isArray(U.batches)?U.batches:[]).map(F=>F).filter(F=>F!==null&&typeof F=="object"&&typeof F.shardKey=="string"&&Array.isArray(F.changes)),V=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:X}=await f(T,x),J=await $.orchestrateApplyCdc(g,{batches:K,headers:X}),ae=V.length>0&&n?await n({changes:V}):0;return Response.json({applied:J.applied+ae,failed:J.failed,ok:J.ok},{status:200})},S=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;l(T);const{headers:$}=await f(T,x),U=await k(T,$);return Response.json(U,{headers:{"content-type":"application/json"},status:200})},D=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(r===void 0||Object.keys(r).length===0||t===void 0)throw new d("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const U=await Z(T),W=typeof U.sink=="string"?U.sink:void 0,K=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,V=He(U.tables);if(W===void 0)throw new d("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const X=r[W];if(X===void 0)throw new d(`Export-tap sink "${W}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:J}=await f(T,x),ae=V??a(),F=await Yn({coordinator:$,cursorStore:t,headers:J,limit:K,shardDO:g,sink:X,tables:ae});return Response.json(F,{headers:{"content-type":"application/json"},status:200})};return{[oo]:p,[ro]:_,[eo]:w,[ao]:D,[to]:S,[no]:b}},uo=(e,n)=>{let t;try{t=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:n,message:"line is not valid JSON",table:""},ok:!1}}if(!t||typeof t!="object"||Array.isArray(t))return{error:{code:"BAD_ROW",line:n,message:"row must be a JSON object",table:""},ok:!1};const r=t;return typeof r.table!="string"||r.table.length===0?{error:{code:"BAD_ROW",line:n,message:"row is missing `table`",table:""},ok:!1}:!r.doc||typeof r.doc!="object"||Array.isArray(r.doc)?{error:{code:"BAD_ROW",line:n,message:"row is missing or malformed `doc`",table:r.table},ok:!1}:{doc:r.doc,ok:!0,table:r.table}},lo=(e,n,t,r,a)=>{if(t?.mode.kind==="shardBy"&&typeof t.mode.field=="string"){const s=e[t.mode.field];return s==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${t.mode.field}" for table "${n}"`,table:n},ok:!1}:{ok:!0,shardKey:typeof s=="string"?s:JSON.stringify(s)}}return{ok:!0,shardKey:r}},ho=async(e,n,t)=>{if(!e.body)throw new d("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],a=[],s=new Map;let l=0,u=0;const f=e.body.getReader(),g=new TextDecoder;let E="",k=0;const v=w=>{u+=1;const b=w.trim();if(b.length===0)return;l+=1;const _=uo(b,u);if(!_.ok){r.push(_.error);return}const{doc:p,table:S}=_,D=n.resolveTableSharding?.(S);if(D?.mode.kind==="global"){a.push({doc:p,line:u,table:S});return}const T=lo(p,S,D,t,u);if(!T.ok){r.push(T.error);return}const x=s.get(T.shardKey);x?x.rows.push({doc:p,table:S}):s.set(T.shardKey,{rows:[{doc:p,table:S}],shardKey:T.shardKey,startLine:u})};for(;;){const{done:w,value:b}=await f.read();if(w)break;if(b&&(k+=b.byteLength,k>Nt))throw await f.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=g.decode(b,{stream:!0});let _=E.indexOf(`
5
5
  `);for(;_!==-1;){const p=E.slice(0,_);E=E.slice(_+1),v(p),_=E.indexOf(`
6
- `)}}return E.length>0&&v(E),{errors:r,globalRows:a,perShard:s,received:l}},wt=(e,n)=>{for(const[t,r]of Object.entries(n.inserted))e.inserted[t]=(e.inserted[t]??0)+r;for(const t of n.errors)e.errors.push({...t});e.conflicts+=n.conflicts},fo=async(e,n,t,r)=>{const a=n.defaultShardKey??"__root__",{errors:s,globalRows:l,perShard:u,received:f}=await ho(e,n,a),g={conflicts:0,errors:s,inserted:{}},E=[];if(n.resolveTableSharding===void 0&&u.size>0&&E.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"),u.size>0){const k=n.queryCoordinator;if(!k)throw new d("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const v=await k.orchestrateImport(r,{batches:[...u.values()],headers:t});wt(g,v)}if(l.length>0)if(n.importGlobals){const k=l[0]?.line??1,v=await n.importGlobals({rows:l,startLine:k});wt(g,v)}else for(const k of l)g.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:k.line,message:`row targets global table "${k.table}" but no \`importGlobals\` is configured`,table:k.table});return{conflicts:g.conflicts,errors:g.errors,inserted:g.inserted,received:f,...E.length>0?{warnings:E}:{}}},Le=e=>typeof e=="object"&&e!==null?e:{},Me=e=>typeof e.kind=="string"?e.kind:"unknown",po=(e,n)=>{let t=Le(n),r=!1;Me(t)==="optional"&&(r=!0,t=Le(t._meta?.inner));const a=Me(t),s=t._meta??{},l={kind:a,name:e,optional:r};if(a==="id"&&typeof s.tableName=="string"&&(l.table=s.tableName),a==="array"){const u=Me(Le(s.inner));u!=="unknown"&&(l.element=u)}return l},mo=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([n,t])=>po(n,t)).toSorted((n,t)=>n.name.localeCompare(t.name)),wo="/_lunora/admin/functions",go="/_lunora/admin/cron-jobs",yo="/_lunora/admin/openapi",bo="/_lunora/admin/openrpc",_o="/_lunora/admin/global/tables",Ro="/_lunora/admin/global/table",Eo="/_lunora/admin/global/facet",gt=e=>{if(e===void 0||e==="")return;let n;try{n=JSON.parse(e)}catch{return}if(!Array.isArray(n))return;const t=n.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:a,value:s}=r;return[{column:a,value:s}]});return t.length===0?void 0:t},Ao=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:{}}),So=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"}),To=e=>{const{assertAdmin:n,options:t,parsePaging:r,queryParameter:a,requireAdminOption:s}=e,l=w=>{j(w,"GET","Functions");const b=s(w,t.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(b).flatMap(([p,S])=>S.visibility==="internal"||S.kind==="stream"?[]:[{args:mo(S.args),kind:S.kind,path:p}]).toSorted((p,S)=>p.path.localeCompare(S.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},u=w=>{j(w,"GET","Cron-jobs");const b=s(w,t.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(b).flatMap(([p,S])=>S.map(D=>({args:D.args,cron:p,functionPath:D.functionPath,name:D.name,shardKey:D.shardKey,workflow:D.workflow}))).toSorted((p,S)=>p.name.localeCompare(S.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},f=w=>(j(w,"GET","OpenAPI"),n(w),Response.json(t.openApiSpec??Ao,{headers:{"content-type":"application/json"},status:200})),g=w=>(j(w,"GET","OpenRPC"),n(w),Response.json(t.openRpcSpec??So,{headers:{"content-type":"application/json"},status:200})),E=async w=>{j(w,"GET","Global-tables");const b=s(w,t.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})},k=async w=>{j(w,"GET","Global-table");const b=s(w,t.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(w.url),p=a(_,"table");if(p===void 0)throw new d("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const S=await b.readTablePage({...r(w),filters:gt(a(_,"filters")),table:p});return Response.json(S,{headers:{"content-type":"application/json"},status:200})},v=async w=>{j(w,"GET","Global-facet");const b=s(w,t.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(w.url),p=a(_,"table"),S=a(_,"column");if(p===void 0||S===void 0)throw new d("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const D=a(_,"limit"),T=D===void 0?void 0:Number(D),x=await b.facetColumn({column:S,filters:gt(a(_,"filters")),limit:T!==void 0&&Number.isFinite(T)?T:void 0,table:p});return Response.json(x,{headers:{"content-type":"application/json"},status:200})};return{[go]:u,[wo]:l,[Eo]:v,[Ro]:k,[_o]:E,[yo]:f,[bo]:g}},Oo="/_lunora/admin/kv/namespaces",vo="/_lunora/admin/kv/keys",zt="/_lunora/admin/kv/value",Wt=32*1048576,yt=60,ko=e=>{const{readJsonBody:n,requireAdminOption:t}=e,r=b=>t(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}),s=(b,_)=>{const p=new URL(b.url),S=p.searchParams.get("namespace")??"",D=p.searchParams.get("key")??"";if(S==="")throw new d(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(D==="")throw new d(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:D,namespace:S}},l=async(b,_)=>{if(!(await b.listNamespaces()).some(S=>S.binding===_))throw new d(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},u=async b=>(j(b,"GET","KV-namespaces"),a({namespaces:await r(b).listNamespaces()})),f=async b=>{j(b,"GET","KV-keys");const _=r(b),p=new URL(b.url),S=p.searchParams.get("namespace")??"";if(S==="")throw new d("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const D=p.searchParams.get("prefix")??void 0,T=p.searchParams.get("cursor")??void 0,x=p.searchParams.get("limit"),H=x===null?void 0:Number.parseInt(x,10);if(H!==void 0&&(!Number.isInteger(H)||H<1))throw new d("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const $=H===void 0?void 0:Math.min(H,1e3);return await l(_,S),a(await _.listKeys({cursor:T,limit:$,namespace:S,prefix:D}))},v={DELETE:async b=>{const _=r(b),p=s(b,"DELETE");return await l(_,p.namespace),await _.deleteKey(p),a({deleted:!0})},GET:async b=>{const _=r(b),p=s(b,"GET");return await l(_,p.namespace),a(await _.getValue(p))},PUT:async b=>{const _=r(b),p=await n(b,Wt);if(typeof p.namespace!="string"||p.namespace==="")throw new d("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new d("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new d("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<yt))throw new d("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const S=Math.floor(Date.now()/1e3)+yt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<S))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 l(_,p.namespace),await _.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),a({ok:!0})}},w=b=>{const _=v[b.method];if(!_)throw new d("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(b)};return{[Oo]:u,[vo]:f,[zt]:w}},Io="/_lunora/migrate",Po="/_lunora/admin/pitr",Do="/_lunora/admin/rank",No="/_lunora/admin/rankpage",Uo="/_lunora/admin/shard-traffic",Co=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Bo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),xo=async e=>{const t=await be(e,"Migration")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.functionPath!="string"||!Co.has(t.functionPath))throw new d("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,table:t.table}},Ho=async e=>{const t=await be(e,"Rank")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.index!="string"||t.index.length===0)throw new d("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof t.partitionKey!="string")throw new d("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof t.rowId!="string"||t.rowId.length===0)throw new d("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(t.sortValues))throw new d("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:t.sortValues,table:t.table}},Lo=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(n=>n!=="asc"&&n!=="desc"))throw new d('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Mo=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})},jo=async e=>{const t=await be(e,"Rank page")??{};Mo(t);const r=Lo(t.directions);return{cursor:typeof t.cursor=="string"?t.cursor:null,directions:r,index:t.index,partitionKey:typeof t.partitionKey=="string"?t.partitionKey:void 0,table:t.table,take:typeof t.take=="number"?t.take:void 0}},$o=async e=>{const t=await be(e,"Shard-traffic")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:t.table}},Ko=async e=>{const t=await Z(e);if(typeof t.functionPath!="string"||!Bo.has(t.functionPath))throw new d("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new d("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},Fo=e=>{const{defaultShard:n,forwardToShard:t,isAdmin:r,queryCoordinator:a,resolveForwardContext:s,shardDO:l}=e,u=(w,b)=>{if(w.method!=="POST")throw new d(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(w))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},f=async(w,b)=>{const _=u(w,"Migration"),p=await xo(w),{headers:S}=await s(w,b),D=await _.orchestrateMigration(l,{args:p.args,functionPath:p.functionPath,headers:S,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},g=async(w,b)=>{const _=u(w,"Rank"),p=await Ho(w),{headers:S}=await s(w,b),D=await _.orchestrateRank(l,{headers:S,index:p.index,partitionKey:p.partitionKey,rowId:p.rowId,sortValues:p.sortValues,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},E=async(w,b)=>{const _=u(w,"Rank page"),p=await jo(w),{headers:S}=await s(w,b),D=await _.orchestrateRankPage(l,{...p,headers:S});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},k=async(w,b)=>{const _=u(w,"Shard-traffic"),p=await $o(w),{headers:S}=await s(w,b),D=await _.orchestrateShardTraffic(l,{headers:S,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},v=async(w,b)=>{if(j(w,"POST","PITR"),!r(w))throw new d("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const _=await Ko(w),{headers:p}=await s(w,b),S=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:_.args,functionPath:_.functionPath}),headers:p,method:"POST"});return t(l,_.shardKey??n,S)};return{[Io]:f,[Po]:v,[Do]:g,[No]:E,[Uo]:k}},Go=1,Qo=0,zo=32,Wo=512,Vo=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Jo=e=>{if(e==null)return;const n=e.trim();if(n.length===0||n.length>Wo)return;const t=n.split(",");if(!(t.length>zo)){for(const r of t)if(!Vo.test(r.trim()))return;return n}},qo=e=>{const n=Hn(e.headers.get("traceparent"));if(n===void 0)return;const t=Jo(e.headers.get("tracestate"));return{parentSpanId:n.parentSpanId,sampled:n.sampled,traceId:n.traceId,...t===void 0?{}:{traceState:t}}},Yo=(e,n={})=>{const t=qo(e),r=n.trustInbound===!0?t:void 0,a=Se(8),s=r?.traceId??Se(16),l=rr(n.sampling,r===void 0?a:s),u=l.isTraced&&(r===void 0||r.sampled);return{decision:l,ignoredUpstream:t!==void 0&&r===void 0,trace:{sampled:u,spanId:a,traceFlags:u?Go:Qo,traceId:s,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState}}}},Xo=(e,n)=>{n.traceparent=xn(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(n.tracestate=e.traceState)},Zo=(e,n)=>{let t;return()=>{if(t===void 0){const r=$n(e),a=n===void 0?void 0:n.cf;t=Ln(jn(r),Mn(r,a))}return t}},ea="/_lunora/admin/scheduled",ta="/_lunora/admin/scheduled/status",na="/_lunora/admin/scheduled/ws",ra="/_lunora/admin/scheduled/cancel",oa="/_lunora/admin/scheduled/dead",aa="/_lunora/admin/scheduled/dead/retry",sa="/_lunora/admin/scheduled/dead/cancel",ia=e=>{const{checkWsAdmin:n,requireSchedulerNamespace:t,resolveSchedulerStub:r,schedulerInstanceName:a}=e,s=(f,g)=>E=>{if(E.method!=="GET")throw new d(`${g} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return r(E).fetch(new Request(`https://scheduler.internal${f}`,{method:"GET"}))},l=(f,g,E=g)=>async k=>{if(k.method!=="POST")throw new d(`${E} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const v=r(k),w=await k.json().catch(()=>{});if(typeof w?.id!="string"||w.id==="")throw new d(`${g} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return v.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))},u=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await n(f))throw new d("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const g=t();return we(g,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ra]:l("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[sa]:l("/dead/cancel","Scheduled dead-letter action"),[oa]:s("/dead","Scheduled dead-letter"),[aa]:l("/dead/retry","Scheduled dead-letter action"),[ea]:s("/list","Scheduled-list"),[ta]:s("/status","Scheduler-status"),[na]:u}},ca=(e,...n)=>{let t=e.cf;for(const r of n){if(typeof t!="object"||t===null)return;t=t[r]}return typeof t=="string"?t:void 0},bt={mtls:e=>ca(e,"tlsClientAuth","certVerified")==="SUCCESS"},da=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(bt,e)?bt[e]:void 0)??(()=>!1),ua=e=>{if(e!==void 0)return()=>{};let n=!1;return()=>{n||(n=!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.'))}},la="/_lunora/admin/vector/indexes",ha="/_lunora/admin/vector/query",fa=e=>{const{readJsonBody:n,requireAdminOption:t}=e,r=async s=>{j(s,"GET","Vector-indexes");const l=t(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await l.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async s=>{j(s,"POST","Vector-query");const l=t(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(l.queryIndex===void 0)throw new d("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const f=await n(s);if(typeof f.name!="string"||f.name==="")throw new d("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof f.text!="string"||f.text==="")throw new d("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(f.topK!==void 0&&(typeof f.topK!="number"||!Number.isInteger(f.topK)||f.topK<1))throw new d("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const g=await l.queryIndex({name:f.name,text:f.text,topK:f.topK});return Response.json(g,{headers:{"content-type":"application/json"},status:200})};return{[la]:r,[ha]:a}},pa="/_lunora/admin/workflows/instances",ma="/_lunora/admin/workflows/instance",wa="/_lunora/admin/workflows/status",ga={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},ya=e=>e!==null&&Object.hasOwn(ga,e)?e:void 0,_t=(e,n)=>{const t=e.searchParams.get(n);if(t===null)return;const r=Number(t);return Number.isInteger(r)&&r>0?r:void 0},je=(e,n)=>{const t=e.searchParams.get(n);if(t===null||t==="")throw new d(`Workflows admin endpoint requires a \`${n}\` query parameter`,{code:"BAD_REQUEST",status:400});return t},Rt=()=>{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})},ba=e=>{const{assertAdmin:n,resolveWorkflowsClient:t}=e,r=async(l,u,f)=>{j(l,"GET","Workflows instances"),n(l);const g=t(u);if(!g)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const E=je(f,"name"),k=ya(f.searchParams.get("status"));return Response.json(await g.listInstances({page:_t(f,"page"),perPage:_t(f,"perPage"),status:k,workflowName:E}))},a=async(l,u,f)=>{j(l,"GET","Workflows instance"),n(l);const g=t(u);return g?Response.json(await g.getInstance({instanceId:je(f,"id"),workflowName:je(f,"name")})):Rt()},s=async(l,u)=>{j(l,"POST","Workflows status"),n(l);const f=t(u);if(!f)return Rt();const g=await l.json().catch(()=>{});if(typeof g?.name!="string"||g.name===""||typeof g.id!="string"||g.id==="")throw new d("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:E}=g;if(E!=="pause"&&E!=="resume"&&E!=="terminate")throw new d("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:E,instanceId:g.id,workflowName:g.name}))};return{[ma]:a,[pa]:r,[wa]:s}},_a={[zt]:Wt,[qn]:Jn},Et="/_lunora/rpc",Ra="/_lunora/rpc-batch",Ea="/_lunora/ws",Re=(e,n,t)=>({resourceAttributes:Zo(e,n),...t===void 0?{}:{waitUntil:t}}),At=e=>e?.waitUntil?{waitUntil:n=>e.waitUntil?.(n)}:{},St=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),$e=e=>{const{method:n}=e,t=e.headers.get("user-agent")??void 0;let r;try{r=new URL(e.url)}catch{return{method:n,userAgent:t}}const a=r.port===""?void 0:Number(r.port);return{host:r.hostname,method:n,path:r.pathname,port:Number.isNaN(a)?void 0:a,scheme:r.protocol.replace(":",""),userAgent:t}},Tt="/_lunora/voice/",Aa="/_lunora/scheduler/dispatch",Sa="/_lunora/admin/cron-jobs/run",Ta="/_lunora/admin/ws-token",Oa="/_lunora/admin/",va="/_lunora/migrate",ka="/_lunora/status",Ia=e=>e.startsWith(Oa)||e===va,Pa=e=>{const n=e.headers.get("x-lunora-userid"),t=e.headers.get("x-lunora-identity");if(!(n===null&&t===null))return{...t===null?{}:{identity:t},...n===null?{}:{userId:n}}},Da="/api/auth",Na="__lunora_admin__:recordAuthEvent",Ua="__lunora_admin__:listPushSubscriptions",Ca=["/sign-in","/sign-up","/callback"],Ba=(e,n)=>{const t=n.endsWith("/")?n.slice(0,-1):n;if(!e.startsWith(`${t}/`))return!1;const r=e.slice(t.length);return Ca.some(a=>r===a||r.startsWith(`${a}/`))},Ee=(e,n,t,r)=>{const a=Dn(t),s=a?t.code:"INTERNAL_SERVER_ERROR",l=a?t.status:500,u=t instanceof Error?t.message:String(t);return{durationMs:n,error:{code:s,message:u,status:l},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},xa=e=>{const{exp:n,expiresAtMs:t}=e;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof n=="number"&&Number.isFinite(n))return n*1e3},Ot=e=>e.waitUntil?{waitUntil:n=>{e.waitUntil?.(n)}}:void 0,Ha=e=>{const n=e?.queue;return typeof n=="string"&&n.length>0?n:"unknown"},Fe=new WeakMap,de=async(e,n,t,r=Fe.get(e))=>{const a={"content-type":"application/json"},s=e.headers.get("authorization"),l=e.headers.get("cookie"),u=e.headers.get("x-d1-bookmark"),f=e.headers.get("x-lunora-mutation-id"),g=e.headers.get("x-lunora-client-id"),E=e.headers.get("x-lunora-client-seq");s&&(a.authorization=s),l&&(a.cookie=l),u&&(a["x-d1-bookmark"]=u),f&&(a["x-lunora-mutation-id"]=f),g&&(a["x-lunora-client-id"]=g),E&&(a["x-lunora-client-seq"]=E);const k=e.headers.get("cf-connecting-ip");if(k&&(a["x-lunora-client-ip"]=k),!t)return{claims:null,headers:a,identity:null,userId:null};const v=await t(e,n,r);if(!v||typeof v.userId!="string"||v.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=Cn(v.userId);const w=xa(v);w!==void 0&&(a["x-lunora-identity-exp"]=String(w));const{userId:b,..._}=v,p=Object.keys(_).length>0?_:null;return p&&(a["x-lunora-identity"]=Bn(p)),{claims:p,headers:a,identity:v,userId:b}},La=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Ma=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 n=e;if(typeof n.table!="string"||n.table.length===0)throw new d("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!n.merge||typeof n.merge!="object")throw new d("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const t=n.merge;if(typeof t.kind!="string"||!La.has(t.kind))throw new d("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(t.kind==="topK"){if(typeof t.k!="number"||!Number.isInteger(t.k)||t.k<0)throw new d("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof t.by!="string"||t.by.length===0)throw new d("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return n},ja=(e,n)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${n.fanOut?"fan-out":`shard=${n.shardKey??"(root)"}`} ${n.functionPath}`)},vt=(e,n)=>{const t=n.functions?.[e.functionPath]?.x402;if(t){if(e.fanOut)throw new d("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!n.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 t}},$a=async e=>{const n=await Ct(e);let t;try{t=JSON.parse(n)}catch{throw new d("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!t||typeof t!="object"||typeof t.functionPath!="string")throw new d("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const r=t;if(r.args!==void 0&&Ut(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=t,s=Ma(a.fanOut),l=a.args??{};if(s&&a.functionPath.startsWith("__lunora_relation__:")){const u=l.table;if(typeof u=="string"&&u!==s.table)throw new d("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});l.table=s.table}return{args:l,fanOut:s,functionPath:a.functionPath,shardKey:a.shardKey}},Ae=new Map,Ka=5e3,Fa=4096,Ga=async(e,n)=>{const t=Date.now(),r=Ae.get(n);if(r!==void 0&&r.expiresMs>t)return r.relayCount;r!==void 0&&Ae.delete(n);let a=0;try{const s=await we(e,n).fetch(new Request("https://shard.internal/_lunora/route"));if(s.ok){const u=(await s.json()).relayCount;typeof u=="number"&&u>0&&(a=Math.floor(u))}}catch{a=0}return Dt(Ae,Fa),Ae.set(n,{expiresMs:t+Ka,relayCount:a}),a},kt=(e,n)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,t])=>t===n)?.[0]},ye=(e,n,t)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:n,functionPath:e}),headers:t,method:"POST"}),Qa=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],It=(e,n)=>{for(const t of Qa){e.delete(t);const r=n[t];r!==void 0&&e.set(t,r)}},za=async(e,n,t)=>e.length===0||t.length===0?!1:ze(await Lt(e,n),t),Pt=(e,n)=>{if(!n||n.length===0)return!1;const t=e.headers.get("authorization");if(!t)return!1;const[r,...a]=t.split(" ");return r?.toLowerCase()!=="bearer"?!1:ze(n,a.join(" ").trim())},Wa=async(e,n,t)=>{if(!n||n.length===0)return!1;const r=new URL(e.url).searchParams.get("token");return r===null?!1:await Ir(n,r)?!0:t?!1:ze(n,r)},Va=(e,n)=>{if(n===null||typeof n!="object"&&typeof n!="function")return;const t=n;if(typeof t.prepare=="function"&&typeof t.batch=="function"&&typeof t.dump=="function")return er(`d1:${e}`,n);if(typeof t.list=="function"&&typeof t.head=="function"&&typeof t.createMultipartUpload=="function")return Ce(`r2:${e}`,!0);if(typeof t.send=="function"&&typeof t.sendBatch=="function"&&typeof t.get!="function")return Ce(`queue:${e}`,!0);if(typeof t.connectionString=="string")return Ce(`hyperdrive:${e}`,!0)},Vt=e=>{const n=da(e.trustInboundTraceContext),t=ua(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",a=tr(e.resolveIdentity,e.identity),s=rt(e.shardDO,e.jurisdiction),l=e.schedulerDO===void 0?void 0:rt(e.schedulerDO,e.jurisdiction);let u=!1;const f=o=>{if(o===void 0||e.jurisdiction===void 0)return o;u||(u=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},g=async(o,i,h,c=e.shardRegion?.(i))=>we(o,i,f(c)).fetch(h);let E;const k=()=>e.adminToken??E;let v;const w=()=>e.requireEphemeralWsToken??v??!0;let b;const _=o=>{const i=o??{};if(b??=kt(o,e.shardDO),v===void 0&&e.requireEphemeralWsToken===void 0){const c=i.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(v=Or(c,!0))}if(E!==void 0||e.adminToken!==void 0)return;const h=i.LUNORA_ADMIN_TOKEN;typeof h=="string"&&h.length>0&&(E=h)},p=new WeakSet,S=o=>Pt(o,k())||p.has(o),D=async(o,i)=>{const h=await de(o,i,e.resolveIdentity);if(p.has(o)&&h.headers.authorization===void 0){const c=k();c!==void 0&&(h.headers.authorization=`Bearer ${c}`)}return h};let T=!1,x=!1;const H=()=>{x||(x=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},$=o=>{if(!e.allowUnauthenticatedShardAccess){const i=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new d(`${o} access is default-denied: configure \`${i}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}T||(T=!0,console.warn([`[lunora] SECURITY: serving ${o} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},U=async(o,i,h=!0)=>{if(e.authorizeShard){if(!await e.authorizeShard(o,i))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else h&&i!==r&&$("shard")},W=Fo({defaultShard:r,forwardToShard:g,isAdmin:S,queryCoordinator:e.queryCoordinator,resolveForwardContext:D,shardDO:s}),K=async(o,i,h,c,m)=>{await U(null,h,!1);const R={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(R["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(R["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(R["x-lunora-mutation-id"]=c),g(s,h,ye(o,i,R))},V=async(o,i,h,c)=>{const m=h?.[o];if(!m||typeof m.create!="function")throw new d(`${c} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(ir(i))throw new d(`${c} params ${cr}`,{code:"BAD_REQUEST",status:400});await m.create({params:i})},X=async(o,i)=>{if(o.workflow){await V(o.workflow,o.args??{},i,`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 h=await K(o.functionPath,o.args??{},o.shardKey??r);if(!h.ok)throw new d(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(h.status)}`,{code:"CRON_JOB_FAILED",status:500})},J=async(o,i,h,c)=>{const m=e.cronJobs?.[o];if(m)for(const R of m)try{await X(R,i)}catch(I){h.push(c(I))}},ae=async(o,i)=>{if(!S(o))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(j(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 h=await Z(o),c=typeof h.name=="string"?h.name:"";if(c==="")throw new d("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(R=>R.name===c);if(!m)throw new d(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await X(m,i),Response.json({name:c,ran:!0},{status:200})},F=async o=>{const i=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!i||!l||typeof o.id!="string")return;const h=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await we(l,h).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:i}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},he=async(o,i)=>{j(o,"POST","Scheduler dispatch");const h=await Ct(o),c=i??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,R=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),I=o.headers.get("x-lunora-scheduler-signature");let y=!1;if(I&&m?y=await za(m,h,I):R&&(y=Pt(o,R)),!y)throw new d("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let A;try{A=JSON.parse(h)}catch{throw new d("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const O=A??{},C=O.args??{};if(typeof O.workflow=="string"&&O.workflow.length>0)return await V(O.workflow,C,i,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof O.functionPath!="string"||O.functionPath.length===0)throw new d("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const B=typeof O.shardKey=="string"&&O.shardKey.length>0?O.shardKey:r,L=typeof O.id=="string"&&O.id.length>0?O.id:void 0,te=Pa(o),M=await K(O.functionPath,C,B,L,te);return await F(O),M},G=o=>{if(!S(o))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},oe=(o,i,h)=>{if(G(o),i===void 0)throw new d(h.message,{code:h.code,status:400});return i},Te=Cr({assertAdmin:G,getReader:()=>e.authAuditReader}),Oe=async(o,i)=>{G(o);const h=e.notifySubscriptionStore;if(h===void 0)return Response.json({result:Ke({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const c=i?.kind,m=i?.userId,R=i?.limit,I=c==="fcm"||c==="web-push"?c:void 0,y=typeof m=="string"&&m!==""?m:void 0,A=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,O=A>0?Math.min(A,1e3):1e3,B=(await h.list({kind:I,limit:O,userId:y})).filter(L=>I!==void 0&&L.kind!==I?!1:y===void 0||(L.userId??null)===y).map(({keys:L,token:te,...M})=>M);return Response.json({result:Ke({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},se=async(o,i)=>{if(!i.fanOut){if(i.functionPath===Ur)return Te(o,i.args??{});if(i.functionPath===Ua)return Oe(o,i.args)}},Jt=co({applyGlobals:e.applyGlobals,assertAdmin:G,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:oe,resolveForwardContext:D,shardDO:s,streamExportRows:(o,i,h,c)=>Ft(e,o,i,h,c,s),streamingImport:(o,i)=>fo(o,e,i,s),syncGlobals:e.syncGlobals}),ve=(o,i)=>{const h=o.searchParams.get(i);return h===null||h===""?void 0:h},ke=o=>{const i=new URL(o.url),h=i.searchParams.get("limit"),c=i.searchParams.get("offset"),m=h===null?void 0:Number.parseInt(h,10),R=c===null?void 0:Number.parseInt(c,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},Je=()=>{if(l===void 0)throw new d("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return l},qt=ia({checkWsAdmin:async o=>S(o)||Wa(o,k(),w()),requireSchedulerNamespace:Je,resolveSchedulerStub:o=>(G(o),we(Je(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Yt=ba({assertAdmin:G,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Xt=Vn({assertAdmin:G,parsePaging:ke,queryParameter:ve,readBodyBytes:Fn,requireAdminOption:oe,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Zt=Wr({options:e,readJsonBody:Z,requireAdminOption:oe}),en=fa({readJsonBody:Z,requireAdminOption:oe,vectorIntrospector:e.vectorIntrospector}),tn=ko({kvIntrospector:e.kvIntrospector,readJsonBody:Z,requireAdminOption:oe}),nn=nr({logArchive:e.logArchive,readJsonBody:Z,requireAdminOption:oe}),rn=To({assertAdmin:G,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:ke,queryParameter:ve,requireAdminOption:oe}),on=o=>{const i=[],h=s??o?.SHARD;if(h!==void 0&&i.push(Zn("durable-object:default",h,r)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(o??{})){const R=Va(c,m);R!==void 0&&i.push(R)}for(const c of e.health?.probes??[])i.push(c);return i},an=Xn({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:S,resolveProbes:on}),sn=o=>{const i=e.schedulerInstanceName??"default",h=()=>we(o,i),c=async(y,A)=>{const O=await h().fetch(new Request(`https://scheduler.internal${y}`,A));if(!O.ok)throw new d(`ctx.scheduler: SchedulerDO ${y} failed (${String(O.status)}): ${await O.text()}`,{code:"INTERNAL",status:500});return await O.json()},m=async(y,A)=>await c(y,{body:JSON.stringify(A),headers:{"content-type":"application/json"},method:"POST"}),R=y=>{const A=y;if(A==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 A.binding=="string"&&A.binding.length>0)return{workflow:A.binding};if(typeof A.__lunoraRef=="string")return{functionPath:A.__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})},I=async(y,A,O={})=>{const{id:C}=await m("/schedule",{args:O,scheduledFor:y,...R(A)});return C};return{cancel:async y=>await m("/cancel",{id:y}),get:async y=>await c(`/get?id=${encodeURIComponent(y)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(y,A,O)=>{if(!Number.isFinite(y)||y<0)throw new d("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await I(Date.now()+y,A,O)},runAt:async(y,A,O)=>{if(!Number.isFinite(y))throw new d("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await I(y,A,O)}}},cn=async(o,i,h)=>{const{claims:c,headers:m,userId:R}=await de(o,i,a),I=async(y,A={})=>{const O=y.__lunoraRef;if(typeof O!="string")throw new d("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const C=ye(O,A,{...m,"x-lunora-system":"1"}),B=await g(s,r,C),L=await B.json();if(L.error)throw new d(L.error.message??"shard RPC failed",{code:L.error.code??"INTERNAL",status:B.status});return L.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:R},cache:h.cache,fetch:globalThis.fetch.bind(globalThis),runAction:I,runMutation:I,runQuery:I,...l===void 0?{}:{scheduler:sn(l)},...e.storage===void 0?{}:{storage:sr(e.storage(i))}}},dn=async(o,i,h)=>{if(!e.httpRouter)return;const c=await cn(o,i,h);try{return await e.httpRouter.fetch(o,{...i,__lunoraCtx:c},h)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},un=async(o,i,h)=>{if(o.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=at(o,ie);if(c)return c;const m=h.searchParams.get("shard")??r,{headers:R,identity:I}=await de(o,i,a);await U(I,m);const y=new Headers(o.headers),A=[...y.keys()];for(const C of A)C.startsWith("x-lunora-")&&y.delete(C);It(y,R);const O=kt(i,e.shardDO);if(O!==void 0){y.set("x-lunora-shard-binding",O);const C=await Ga(s,m);if(C>0){const B=Rr(m,Math.floor(Math.random()*C));return g(s,B,new Request(o,{headers:y}),st(o))}}return g(s,m,new Request(o,{headers:y}))},ln=async(o,i,h)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=at(o,ie);if(m)return m;let R;try{R=decodeURIComponent(h.pathname.slice(Tt.length))}catch{return new Response("Unknown voice agent",{status:404})}const I=Object.hasOwn(c,R)?c[R]:void 0;if(I===void 0)return new Response("Unknown voice agent",{status:404});const y=h.searchParams.get("threadKey");if(y===null||y.length===0)return new Response("Missing threadKey",{status:400});const{headers:A,identity:O}=await de(o,i,a);if(e.authorizeShard){if(!await e.authorizeShard(O,y))return new Response("Forbidden",{status:403})}else $("shard");const C=new Headers(o.headers);for(const B of C.keys())B.startsWith("x-lunora-")&&C.delete(B);return It(C,A),g(I,y,new Request(o,{headers:C}))},hn=async(o,i,h)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(h,o.table,i))throw new d("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(i.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});$("fan-out")},_e=async(o,i)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await hn(o.fanOut,o.functionPath,i);return}await U(i,o.shardKey??r)}},fn=(o,i,h)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){H();return}if(e.functions[i]?.kind!=="query"||h.includes(jt)||h.includes(Mt))return;const c=st(o);return c===void 0?void 0:{name:Er(h,c),region:c}},pn=async(o,i,h,c,m)=>{const R=fn(o,i,c);if(R!==void 0){const I={...m,"x-lunora-replica-read":"1",...b===void 0?{}:{"x-lunora-shard-binding":b}},y=Ar(o.headers.get("x-lunora-min-seq"));y!==void 0&&(I["x-lunora-min-seq"]=String(y));const A=await g(s,R.name,ye(i,h,I),R.region);if(A.status!==421)return A}return g(s,c,ye(i,h,m))},Ie=async(o,i,h,c,m,R)=>{const I=Date.now(),{observability:y,sampling:A}=e,O=$e(o),{decision:C,ignoredUpstream:B,trace:L}=Yo(o,{...A===void 0?{}:{sampling:A},trustInbound:n(o)});B&&t();const te={...m,"x-lunora-sample-errors":C.keepErrors?"1":"0"};Xo(L,te);try{const M=await pn(o,i,h,c,te);ce(y,{...O,...St(L),durationMs:Date.now()-I,functionPath:i,ok:M.ok,shardKey:c,...M.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(M.status)}`,status:M.status}}},R,void 0,{isTraced:L.sampled,keepErrors:C.keepErrors});const ee=new Response(M.body,{headers:M.headers,status:M.status,statusText:M.statusText});return ee.headers.set("x-lunora-shard-key",c),ee}catch(M){throw ce(y,{...O,...St(L),...Ee(i,Date.now()-I,M,{shardKey:c})},R,void 0,{isTraced:L.sampled,keepErrors:C.keepErrors}),M}},mn=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&&o.functionPath.startsWith("__lunora_relation__:"))throw new d("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(o.fanOut&&!e.queryCoordinator)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},wn=async(o,i,h)=>{j(o,"POST","RPC");const c=await $a(o);ja(i,c),mn(c);const m=await se(o,c);if(m!==void 0)return m;const{headers:R,identity:I}=await de(o,i,a);await _e(c,I);const y=vt(c,e);{const A=Date.now(),{observability:O}=e,C=$e(o),B=Re(i,o,h&&(M=>h.waitUntil?.(M)));if(c.fanOut){const M=e.queryCoordinator;if(!M)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ee=await M.fanOut(s,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:R});return ce(O,{durationMs:Date.now()-A,fanOut:{failed:ee.failed,shards:ee.ok+ee.failed,table:c.fanOut.table},functionPath:c.functionPath,...C,ok:!0},B),Response.json(ee,{headers:{"content-type":"application/json"},status:200})}catch(ee){throw ce(O,{...Ee(c.functionPath,Date.now()-A,ee,{fanOut:{table:c.fanOut.table}}),...C},B),ee}}const L=c.shardKey??r,te=()=>Ie(o,c.functionPath,c.args??{},L,R,B);return y&&e.x402Charge?e.x402Charge(o,{functionPath:c.functionPath,price:y.price},te,At(h)):te()}},gn=async(o,i,h)=>{j(o,"POST","RPC batch");const c=await Z(o),{calls:m}=c;if(!Array.isArray(m))throw new d("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:I}=await de(o,i,a),y=Jr(m,r);for(const Q of y.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 ${Et}`,{code:"BAD_REQUEST",status:400});await Promise.all([...y.entries()].flatMap(([Q,z])=>z.map(ne=>_e({args:ne.args,functionPath:ne.functionPath,shardKey:Q},I))));const{observability:A}=e,O=Re(i,o,h&&(Q=>h.waitUntil?.(Q))),C=$e(o),B=[],L=[],te=(Q,z,ne,ue)=>({body:{error:{code:ne,message:ue}},id:Q.id,status:z}),M=(Q,z,ne,ue,fe)=>{for(const q of Q)ce(A,fe(q),O),B.push(te(q,z,ne,ue))},ee=(Q,z,ne,ue,fe)=>{for(const q of Q){const pe=ue.get(q.id)??fe,ge=pe<400;ce(A,{durationMs:ne,functionPath:q.functionPath,...C,ok:ge,shardKey:z,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},O)}};await Promise.all([...y.entries()].map(async([Q,z])=>{const ne=new Headers(R);ne.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:ne,method:"POST"}),fe=Date.now();let q;try{q=await g(s,Q,ue)}catch(Y){const Ue=Date.now()-fe,{body:et}=Nn(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});M(z,502,et.code,et.message,Pn=>({...Ee(Pn.functionPath,Ue,Y,{shardKey:Q}),...C}));return}const pe=Date.now()-fe,ge=q.headers.get("x-d1-bookmark");ge&&L.push(ge);let De;try{De=await q.json()}catch{const Y=`shard batch returned a non-JSON response (${String(q.status)})`;M(z,q.status,"SHARD_ERROR",Y,Ue=>({durationMs:pe,error:{code:"SHARD_ERROR",message:Y,status:q.status},functionPath:Ue.functionPath,...C,ok:!1,shardKey:Q}));return}const Ne=Array.isArray(De.results)?De.results:[],kn=new Map(Ne.map(Y=>[Y.id,Y.status??q.status])),In=new Set(Ne.map(Y=>Y.id));ee(z,Q,pe,kn,q.status),B.push(...Ne);for(const Y of z)In.has(Y.id)||B.push(te(Y,q.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const Xe={"content-type":"application/json"},[Ze]=L;return L.length===1&&Ze!==void 0&&(Xe["x-d1-bookmark"]=Ze),Response.json({results:B},{headers:Xe,status:200})},yn=async(o,i,h,c={},m={})=>{try{const R=h.__lunoraRef;if(typeof R!="string")throw new d("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:I,identity:y}=await de(o,i,a,m.context);await _e({args:c,functionPath:R,shardKey:m.shardKey},y);const A=m.shardKey??r,O=Re(i,o,m.waitUntil);return await Ie(o,R,c,A,I,O)}catch(R){return tt(R)}},qe=async(o,i,h)=>{const{observability:c}=e,m=Date.now(),R=Se(16),I=Se(8),y=Ot(i);try{const A=await h();return ce(c,{durationMs:Date.now()-m,functionPath:o,ok:!0,spanId:I,traceId:R},y),A}catch(A){throw ce(c,{...Ee(o,Date.now()-m,A,{}),spanId:I,traceId:R},y),A}finally{nt(c,y)}},bn=async(o,i,h)=>{_(i);const c=[],m=y=>y instanceof Error?y:new Error(String(y)),R=e.crons?.[o.cron];if(R)try{await R(o,i,h)}catch(y){c.push(m(y))}if(await J(o.cron,i,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron)try{await Fr(e,s,k(),o)}catch(y){c.push(m(y))}const[I]=c;if(c.length===1&&I)throw I;if(c.length>1)throw new AggregateError(c,`scheduled("${o.cron}") had ${String(c.length)} failure(s)`)},_n=async(o,i)=>{try{const h=o??{},c=e.adminToken??(typeof h.LUNORA_ADMIN_TOKEN=="string"?h.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await g(s,r,ye(Na,{outcome:i},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},Rn=async(o,i,h,c)=>{if(!e.authHandler)return;const m=await e.authHandler(o);if(!m)return;const R=e.authBasePath??Da;return Ba(h.pathname,R)&&c.waitUntil?.(_n(i,m.status>=400?"fail":"ok")),m},En=async({args:o,env:i,functionPath:h,request:c,shardKey:m,waitUntil:R})=>{Ut(o,"REST");const I={functionPath:h,...m===void 0?{}:{shardKey:m}},{headers:y,identity:A}=await de(c,i,a);await _e(I,A);const O=m??r,C=Re(i,c,R),B=()=>Ie(c,h,o,O,y,C),L=vt(I,e);return L&&e.x402Charge?e.x402Charge(c,{functionPath:h,price:L.price},B,At({waitUntil:R})):B()},An=Kn({functions:e.functions??{},invoke:En,readJsonBody:Z,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Pe=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Sn={[ka]: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"}}),[Ea]:(o,i,h)=>un(o,i,h),[Et]:(o,i,h,c)=>wn(o,i,c),[Ra]:(o,i,h,c)=>gn(o,i,c),[Aa]:(o,i)=>he(o,i),[Sa]:(o,i)=>ae(o,i),[Ta]:async o=>{j(o,"POST","ws-token"),G(o);const i=k();if(i===void 0)throw new d("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const h=await kr(i);return Response.json(h,{headers:{"cache-control":"no-store"}})},...W,...Jt,...qt,...Yt,...Xt,...Zt,...en,...tn,...nn,...rn,...an,...An,...Nr({assertAdmin:G,getAuthAdmin:()=>e.authAdmin,parsePaging:ke,queryParameter:ve,readJsonBody:Z})};let ie=ot(e.security),Ye=!1;const Tn=o=>{Ye||(Ye=!0,ie=ot(e.security,o??{}))},On=async(o,i)=>{if(!(e.adminGate===void 0||!Ia(i)))try{await e.adminGate(o,Fe.get(o))&&p.add(o)}catch{}},vn=async(o,i,h)=>{Fe.set(o,h);const c=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const y=Number(o.headers.get("content-length")??""),A=_a[c.pathname]??Nt;if(Number.isFinite(y)&&y>A)throw new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await Rn(o,i,c,h);if(m)return m;if(Pe){const y=`${o.method} ${c.pathname}`,A=Pe[y]??Pe[c.pathname];if(A)return A(o,i,h)}const R=Sn[c.pathname];if(R)return await On(o,c.pathname),R(o,i,c,h);if(e.voiceAgents!==void 0&&c.pathname.startsWith(Tt))return ln(o,i,c);const I=await dn(o,i,h);return I||new Response("Not found",{status:404})};return{async fetch(o,i,h){e.passThroughOnException&&h.passThroughOnException?.(),Tn(i),_(i);const c=or(o,ie);if(c)return c;const m=ar(o,ie);if(m)return Be(m,o,ie);try{const R=await vn(o,i,h);return Be(R,o,ie)}catch(R){return Be(tt(R),o,ie)}finally{nt(e.observability,Ot(h))}},async queue(o,i,h){await qe(`queue:${Ha(o)}`,h,async()=>{await e.queue?.(o,i,h)})},async scheduled(o,i,h){await qe(`cron:${o.cron}`,h,async()=>{await bn(o,i,h)})},serverQuery:yn}},Ja=e=>Vt(e),qa=e=>typeof e=="function"?{fetch:e}:e,Ya=e=>!!(e.crons??e.cronJobs??e.backupCron),ys=(e,n)=>{const t=qa(e),r=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=l=>{const u=Ja({...l,httpRouter:t});return r!==void 0&&!Ya(l)?{...u,scheduled:async(f,g,E)=>{await r(f,g,E)}}:u};if(typeof n!="function")return a(n);const s=n;return{fetch:(l,u,f)=>a(s(u)).fetch(l,u,f),queue:(l,u,f)=>a(s(u)).queue?.(l,u,f)??Promise.resolve(),scheduled:(l,u,f)=>a(s(u)).scheduled(l,u,f),serverQuery:(l,u,f,g,E)=>a(s(u)).serverQuery(l,u,f,g,E)}},Xa=(e,n)=>{if(typeof e=="function")return e(n);const t=e.shardDO??n?.SHARD;if(!t)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:t}},bs=(e={})=>(n,t,r)=>Vt(Xa(e,t)).fetch(n,t,r??Un),_s=e=>e;export{Ur as GET_AUTH_AUDIT_LOG_OP,Un as NOOP_EXECUTION_CONTEXT,As as composeIdentityResolvers,Ja as composeWorker,bs as createLunoraHandler,Vt as createWorker,_s as defineRpcEnvelope,Ga as probeRelayCount,Xa as resolveLunoraOptions,Ss as routeIdentityResolvers,ys as withFrameworkWorker};
6
+ `)}}return E.length>0&&v(E),{errors:r,globalRows:a,perShard:s,received:l}},wt=(e,n)=>{for(const[t,r]of Object.entries(n.inserted))e.inserted[t]=(e.inserted[t]??0)+r;for(const t of n.errors)e.errors.push({...t});e.conflicts+=n.conflicts},fo=async(e,n,t,r)=>{const a=n.defaultShardKey??"__root__",{errors:s,globalRows:l,perShard:u,received:f}=await ho(e,n,a),g={conflicts:0,errors:s,inserted:{}},E=[];if(n.resolveTableSharding===void 0&&u.size>0&&E.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"),u.size>0){const k=n.queryCoordinator;if(!k)throw new d("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const v=await k.orchestrateImport(r,{batches:[...u.values()],headers:t});wt(g,v)}if(l.length>0)if(n.importGlobals){const k=l[0]?.line??1,v=await n.importGlobals({rows:l,startLine:k});wt(g,v)}else for(const k of l)g.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:k.line,message:`row targets global table "${k.table}" but no \`importGlobals\` is configured`,table:k.table});return{conflicts:g.conflicts,errors:g.errors,inserted:g.inserted,received:f,...E.length>0?{warnings:E}:{}}},Le=e=>typeof e=="object"&&e!==null?e:{},Me=e=>typeof e.kind=="string"?e.kind:"unknown",po=(e,n)=>{let t=Le(n),r=!1;Me(t)==="optional"&&(r=!0,t=Le(t._meta?.inner));const a=Me(t),s=t._meta??{},l={kind:a,name:e,optional:r};if(a==="id"&&typeof s.tableName=="string"&&(l.table=s.tableName),a==="array"){const u=Me(Le(s.inner));u!=="unknown"&&(l.element=u)}return l},mo=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([n,t])=>po(n,t)).toSorted((n,t)=>n.name.localeCompare(t.name)),wo="/_lunora/admin/functions",go="/_lunora/admin/cron-jobs",yo="/_lunora/admin/openapi",bo="/_lunora/admin/openrpc",_o="/_lunora/admin/global/tables",Ro="/_lunora/admin/global/table",Eo="/_lunora/admin/global/facet",gt=e=>{if(e===void 0||e==="")return;let n;try{n=JSON.parse(e)}catch{return}if(!Array.isArray(n))return;const t=n.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:a,value:s}=r;return[{column:a,value:s}]});return t.length===0?void 0:t},Ao=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:{}}),So=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"}),To=e=>{const{assertAdmin:n,options:t,parsePaging:r,queryParameter:a,requireAdminOption:s}=e,l=w=>{j(w,"GET","Functions");const b=s(w,t.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(b).flatMap(([p,S])=>S.visibility==="internal"||S.kind==="stream"?[]:[{args:mo(S.args),kind:S.kind,path:p}]).toSorted((p,S)=>p.path.localeCompare(S.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},u=w=>{j(w,"GET","Cron-jobs");const b=s(w,t.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(b).flatMap(([p,S])=>S.map(D=>({args:D.args,cron:p,functionPath:D.functionPath,name:D.name,shardKey:D.shardKey,workflow:D.workflow}))).toSorted((p,S)=>p.name.localeCompare(S.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},f=w=>(j(w,"GET","OpenAPI"),n(w),Response.json(t.openApiSpec??Ao,{headers:{"content-type":"application/json"},status:200})),g=w=>(j(w,"GET","OpenRPC"),n(w),Response.json(t.openRpcSpec??So,{headers:{"content-type":"application/json"},status:200})),E=async w=>{j(w,"GET","Global-tables");const b=s(w,t.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})},k=async w=>{j(w,"GET","Global-table");const b=s(w,t.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(w.url),p=a(_,"table");if(p===void 0)throw new d("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const S=await b.readTablePage({...r(w),filters:gt(a(_,"filters")),table:p});return Response.json(S,{headers:{"content-type":"application/json"},status:200})},v=async w=>{j(w,"GET","Global-facet");const b=s(w,t.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(w.url),p=a(_,"table"),S=a(_,"column");if(p===void 0||S===void 0)throw new d("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const D=a(_,"limit"),T=D===void 0?void 0:Number(D),x=await b.facetColumn({column:S,filters:gt(a(_,"filters")),limit:T!==void 0&&Number.isFinite(T)?T:void 0,table:p});return Response.json(x,{headers:{"content-type":"application/json"},status:200})};return{[go]:u,[wo]:l,[Eo]:v,[Ro]:k,[_o]:E,[yo]:f,[bo]:g}},Oo="/_lunora/admin/kv/namespaces",vo="/_lunora/admin/kv/keys",zt="/_lunora/admin/kv/value",Wt=32*1048576,yt=60,ko=e=>{const{readJsonBody:n,requireAdminOption:t}=e,r=b=>t(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}),s=(b,_)=>{const p=new URL(b.url),S=p.searchParams.get("namespace")??"",D=p.searchParams.get("key")??"";if(S==="")throw new d(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(D==="")throw new d(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:D,namespace:S}},l=async(b,_)=>{if(!(await b.listNamespaces()).some(S=>S.binding===_))throw new d(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},u=async b=>(j(b,"GET","KV-namespaces"),a({namespaces:await r(b).listNamespaces()})),f=async b=>{j(b,"GET","KV-keys");const _=r(b),p=new URL(b.url),S=p.searchParams.get("namespace")??"";if(S==="")throw new d("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const D=p.searchParams.get("prefix")??void 0,T=p.searchParams.get("cursor")??void 0,x=p.searchParams.get("limit"),H=x===null?void 0:Number.parseInt(x,10);if(H!==void 0&&(!Number.isInteger(H)||H<1))throw new d("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const $=H===void 0?void 0:Math.min(H,1e3);return await l(_,S),a(await _.listKeys({cursor:T,limit:$,namespace:S,prefix:D}))},v={DELETE:async b=>{const _=r(b),p=s(b,"DELETE");return await l(_,p.namespace),await _.deleteKey(p),a({deleted:!0})},GET:async b=>{const _=r(b),p=s(b,"GET");return await l(_,p.namespace),a(await _.getValue(p))},PUT:async b=>{const _=r(b),p=await n(b,Wt);if(typeof p.namespace!="string"||p.namespace==="")throw new d("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new d("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new d("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<yt))throw new d("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const S=Math.floor(Date.now()/1e3)+yt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<S))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 l(_,p.namespace),await _.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),a({ok:!0})}},w=b=>{const _=v[b.method];if(!_)throw new d("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(b)};return{[Oo]:u,[vo]:f,[zt]:w}},Io="/_lunora/migrate",Po="/_lunora/admin/pitr",Do="/_lunora/admin/rank",No="/_lunora/admin/rankpage",Uo="/_lunora/admin/shard-traffic",Co=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Bo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),xo=async e=>{const t=await be(e,"Migration")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.functionPath!="string"||!Co.has(t.functionPath))throw new d("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,table:t.table}},Ho=async e=>{const t=await be(e,"Rank")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.index!="string"||t.index.length===0)throw new d("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof t.partitionKey!="string")throw new d("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof t.rowId!="string"||t.rowId.length===0)throw new d("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(t.sortValues))throw new d("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:t.sortValues,table:t.table}},Lo=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(n=>n!=="asc"&&n!=="desc"))throw new d('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Mo=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})},jo=async e=>{const t=await be(e,"Rank page")??{};Mo(t);const r=Lo(t.directions);return{cursor:typeof t.cursor=="string"?t.cursor:null,directions:r,index:t.index,partitionKey:typeof t.partitionKey=="string"?t.partitionKey:void 0,table:t.table,take:typeof t.take=="number"?t.take:void 0}},$o=async e=>{const t=await be(e,"Shard-traffic")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:t.table}},Ko=async e=>{const t=await Z(e);if(typeof t.functionPath!="string"||!Bo.has(t.functionPath))throw new d("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new d("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},Fo=e=>{const{defaultShard:n,forwardToShard:t,isAdmin:r,queryCoordinator:a,resolveForwardContext:s,shardDO:l}=e,u=(w,b)=>{if(w.method!=="POST")throw new d(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(w))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},f=async(w,b)=>{const _=u(w,"Migration"),p=await xo(w),{headers:S}=await s(w,b),D=await _.orchestrateMigration(l,{args:p.args,functionPath:p.functionPath,headers:S,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},g=async(w,b)=>{const _=u(w,"Rank"),p=await Ho(w),{headers:S}=await s(w,b),D=await _.orchestrateRank(l,{headers:S,index:p.index,partitionKey:p.partitionKey,rowId:p.rowId,sortValues:p.sortValues,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},E=async(w,b)=>{const _=u(w,"Rank page"),p=await jo(w),{headers:S}=await s(w,b),D=await _.orchestrateRankPage(l,{...p,headers:S});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},k=async(w,b)=>{const _=u(w,"Shard-traffic"),p=await $o(w),{headers:S}=await s(w,b),D=await _.orchestrateShardTraffic(l,{headers:S,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},v=async(w,b)=>{if(j(w,"POST","PITR"),!r(w))throw new d("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const _=await Ko(w),{headers:p}=await s(w,b),S=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:_.args,functionPath:_.functionPath}),headers:p,method:"POST"});return t(l,_.shardKey??n,S)};return{[Io]:f,[Po]:v,[Do]:g,[No]:E,[Uo]:k}},Go=1,Qo=0,zo=32,Wo=512,Vo=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Jo=e=>{if(e==null)return;const n=e.trim();if(n.length===0||n.length>Wo)return;const t=n.split(",");if(!(t.length>zo)){for(const r of t)if(!Vo.test(r.trim()))return;return n}},qo=e=>{const n=Hn(e.headers.get("traceparent"));if(n===void 0)return;const t=Jo(e.headers.get("tracestate"));return{parentSpanId:n.parentSpanId,sampled:n.sampled,traceId:n.traceId,...t===void 0?{}:{traceState:t}}},Yo=(e,n={})=>{const t=qo(e),r=n.trustInbound===!0?t:void 0,a=Se(8),s=r?.traceId??Se(16),l=rr(n.sampling,r===void 0?a:s),u=l.isTraced&&(r===void 0||r.sampled);return{decision:l,ignoredUpstream:t!==void 0&&r===void 0,trace:{sampled:u,spanId:a,traceFlags:u?Go:Qo,traceId:s,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState}}}},Xo=(e,n)=>{n.traceparent=xn(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(n.tracestate=e.traceState)},Zo=(e,n)=>{let t;return()=>{if(t===void 0){const r=$n(e),a=n===void 0?void 0:n.cf;t=Ln(jn(r),Mn(r,a))}return t}},ea="/_lunora/admin/scheduled",ta="/_lunora/admin/scheduled/status",na="/_lunora/admin/scheduled/ws",ra="/_lunora/admin/scheduled/cancel",oa="/_lunora/admin/scheduled/dead",aa="/_lunora/admin/scheduled/dead/retry",sa="/_lunora/admin/scheduled/dead/cancel",ia=e=>{const{checkWsAdmin:n,requireSchedulerNamespace:t,resolveSchedulerStub:r,schedulerInstanceName:a}=e,s=(f,g)=>E=>{if(E.method!=="GET")throw new d(`${g} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return r(E).fetch(new Request(`https://scheduler.internal${f}`,{method:"GET"}))},l=(f,g,E=g)=>async k=>{if(k.method!=="POST")throw new d(`${E} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const v=r(k),w=await k.json().catch(()=>{});if(typeof w?.id!="string"||w.id==="")throw new d(`${g} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return v.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))},u=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await n(f))throw new d("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const g=t();return we(g,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ra]:l("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[sa]:l("/dead/cancel","Scheduled dead-letter action"),[oa]:s("/dead","Scheduled dead-letter"),[aa]:l("/dead/retry","Scheduled dead-letter action"),[ea]:s("/list","Scheduled-list"),[ta]:s("/status","Scheduler-status"),[na]:u}},ca=(e,...n)=>{let t=e.cf;for(const r of n){if(typeof t!="object"||t===null)return;t=t[r]}return typeof t=="string"?t:void 0},bt={mtls:e=>ca(e,"tlsClientAuth","certVerified")==="SUCCESS"},da=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(bt,e)?bt[e]:void 0)??(()=>!1),ua=e=>{if(e!==void 0)return()=>{};let n=!1;return()=>{n||(n=!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.'))}},la="/_lunora/admin/vector/indexes",ha="/_lunora/admin/vector/query",fa=e=>{const{readJsonBody:n,requireAdminOption:t}=e,r=async s=>{j(s,"GET","Vector-indexes");const l=t(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await l.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async s=>{j(s,"POST","Vector-query");const l=t(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(l.queryIndex===void 0)throw new d("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const f=await n(s);if(typeof f.name!="string"||f.name==="")throw new d("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof f.text!="string"||f.text==="")throw new d("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(f.topK!==void 0&&(typeof f.topK!="number"||!Number.isInteger(f.topK)||f.topK<1))throw new d("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const g=await l.queryIndex({name:f.name,text:f.text,topK:f.topK});return Response.json(g,{headers:{"content-type":"application/json"},status:200})};return{[la]:r,[ha]:a}},pa="/_lunora/admin/workflows/instances",ma="/_lunora/admin/workflows/instance",wa="/_lunora/admin/workflows/status",ga={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},ya=e=>e!==null&&Object.hasOwn(ga,e)?e:void 0,_t=(e,n)=>{const t=e.searchParams.get(n);if(t===null)return;const r=Number(t);return Number.isInteger(r)&&r>0?r:void 0},je=(e,n)=>{const t=e.searchParams.get(n);if(t===null||t==="")throw new d(`Workflows admin endpoint requires a \`${n}\` query parameter`,{code:"BAD_REQUEST",status:400});return t},Rt=()=>{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})},ba=e=>{const{assertAdmin:n,resolveWorkflowsClient:t}=e,r=async(l,u,f)=>{j(l,"GET","Workflows instances"),n(l);const g=t(u);if(!g)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const E=je(f,"name"),k=ya(f.searchParams.get("status"));return Response.json(await g.listInstances({page:_t(f,"page"),perPage:_t(f,"perPage"),status:k,workflowName:E}))},a=async(l,u,f)=>{j(l,"GET","Workflows instance"),n(l);const g=t(u);return g?Response.json(await g.getInstance({instanceId:je(f,"id"),workflowName:je(f,"name")})):Rt()},s=async(l,u)=>{j(l,"POST","Workflows status"),n(l);const f=t(u);if(!f)return Rt();const g=await l.json().catch(()=>{});if(typeof g?.name!="string"||g.name===""||typeof g.id!="string"||g.id==="")throw new d("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:E}=g;if(E!=="pause"&&E!=="resume"&&E!=="terminate")throw new d("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:E,instanceId:g.id,workflowName:g.name}))};return{[ma]:a,[pa]:r,[wa]:s}},_a={[zt]:Wt,[qn]:Jn},Et="/_lunora/rpc",Ra="/_lunora/rpc-batch",Ea="/_lunora/ws",Re=(e,n,t)=>({resourceAttributes:Zo(e,n),...t===void 0?{}:{waitUntil:t}}),At=e=>e?.waitUntil?{waitUntil:n=>e.waitUntil?.(n)}:{},St=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),$e=e=>{const{method:n}=e,t=e.headers.get("user-agent")??void 0;let r;try{r=new URL(e.url)}catch{return{method:n,userAgent:t}}const a=r.port===""?void 0:Number(r.port);return{host:r.hostname,method:n,path:r.pathname,port:Number.isNaN(a)?void 0:a,scheme:r.protocol.replace(":",""),userAgent:t}},Tt="/_lunora/voice/",Aa="/_lunora/scheduler/dispatch",Sa="/_lunora/admin/cron-jobs/run",Ta="/_lunora/admin/ws-token",Oa="/_lunora/admin/",va="/_lunora/migrate",ka="/_lunora/status",Ia=e=>e.startsWith(Oa)||e===va,Pa=e=>{const n=e.headers.get("x-lunora-userid"),t=e.headers.get("x-lunora-identity");if(!(n===null&&t===null))return{...t===null?{}:{identity:t},...n===null?{}:{userId:n}}},Da="/api/auth",Na="__lunora_admin__:recordAuthEvent",Ua="__lunora_admin__:listPushSubscriptions",Ca=["/sign-in","/sign-up","/callback"],Ba=(e,n)=>{const t=n.endsWith("/")?n.slice(0,-1):n;if(!e.startsWith(`${t}/`))return!1;const r=e.slice(t.length);return Ca.some(a=>r===a||r.startsWith(`${a}/`))},Ee=(e,n,t,r)=>{const a=Dn(t),s=a?t.code:"INTERNAL_SERVER_ERROR",l=a?t.status:500,u=t instanceof Error?t.message:String(t);return{durationMs:n,error:{code:s,message:u,status:l},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},xa=e=>{const{exp:n,expiresAtMs:t}=e;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof n=="number"&&Number.isFinite(n))return n*1e3},Ot=e=>e.waitUntil?{waitUntil:n=>{e.waitUntil?.(n)}}:void 0,Ha=e=>{const n=e?.queue;return typeof n=="string"&&n.length>0?n:"unknown"},Fe=new WeakMap,de=async(e,n,t,r=Fe.get(e))=>{const a={"content-type":"application/json"},s=e.headers.get("authorization"),l=e.headers.get("cookie"),u=e.headers.get("x-d1-bookmark"),f=e.headers.get("x-lunora-mutation-id"),g=e.headers.get("x-lunora-client-id"),E=e.headers.get("x-lunora-client-seq");s&&(a.authorization=s),l&&(a.cookie=l),u&&(a["x-d1-bookmark"]=u),f&&(a["x-lunora-mutation-id"]=f),g&&(a["x-lunora-client-id"]=g),E&&(a["x-lunora-client-seq"]=E);const k=e.headers.get("cf-connecting-ip");if(k&&(a["x-lunora-client-ip"]=k),!t)return{claims:null,headers:a,identity:null,userId:null};const v=await t(e,n,r);if(!v||typeof v.userId!="string"||v.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=Cn(v.userId);const w=xa(v);w!==void 0&&(a["x-lunora-identity-exp"]=String(w));const{userId:b,..._}=v,p=Object.keys(_).length>0?_:null;return p&&(a["x-lunora-identity"]=Bn(p)),{claims:p,headers:a,identity:v,userId:b}},La=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Ma=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 n=e;if(typeof n.table!="string"||n.table.length===0)throw new d("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!n.merge||typeof n.merge!="object")throw new d("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const t=n.merge;if(typeof t.kind!="string"||!La.has(t.kind))throw new d("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(t.kind==="topK"){if(typeof t.k!="number"||!Number.isInteger(t.k)||t.k<0)throw new d("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof t.by!="string"||t.by.length===0)throw new d("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return n},ja=(e,n)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${n.fanOut?"fan-out":`shard=${n.shardKey??"(root)"}`} ${n.functionPath}`)},vt=(e,n)=>{const t=n.functions?.[e.functionPath]?.x402;if(t){if(e.fanOut)throw new d("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!n.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 t}},$a=async e=>{const n=await Ct(e);let t;try{t=JSON.parse(n)}catch{throw new d("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!t||typeof t!="object"||typeof t.functionPath!="string")throw new d("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const r=t;if(r.args!==void 0&&Ut(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=t,s=Ma(a.fanOut),l=a.args??{};if(s&&a.functionPath.startsWith("__lunora_relation__:")){const u=l.table;if(typeof u=="string"&&u!==s.table)throw new d("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});l.table=s.table}return{args:l,fanOut:s,functionPath:a.functionPath,shardKey:a.shardKey}},Ae=new Map,Ka=5e3,Fa=4096,Ga=async(e,n)=>{const t=Date.now(),r=Ae.get(n);if(r!==void 0&&r.expiresMs>t)return r.relayCount;r!==void 0&&Ae.delete(n);let a=0;try{const s=await we(e,n).fetch(new Request("https://shard.internal/_lunora/route"));if(s.ok){const u=(await s.json()).relayCount;typeof u=="number"&&u>0&&(a=Math.floor(u))}}catch{a=0}return Dt(Ae,Fa),Ae.set(n,{expiresMs:t+Ka,relayCount:a}),a},kt=(e,n)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,t])=>t===n)?.[0]},ye=(e,n,t)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:n,functionPath:e}),headers:t,method:"POST"}),Qa=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],It=(e,n)=>{for(const t of Qa){e.delete(t);const r=n[t];r!==void 0&&e.set(t,r)}},za=async(e,n,t)=>e.length===0||t.length===0?!1:ze(await Lt(e,n),t),Pt=(e,n)=>{if(!n||n.length===0)return!1;const t=e.headers.get("authorization");if(!t)return!1;const[r,...a]=t.split(" ");return r?.toLowerCase()!=="bearer"?!1:ze(n,a.join(" ").trim())},Wa=async(e,n,t)=>{if(!n||n.length===0)return!1;const r=new URL(e.url).searchParams.get("token");return r===null?!1:await Ir(n,r)?!0:t?!1:ze(n,r)},Va=(e,n)=>{if(n===null||typeof n!="object"&&typeof n!="function")return;const t=n;if(typeof t.prepare=="function"&&typeof t.batch=="function"&&typeof t.dump=="function")return er(`d1:${e}`,n);if(typeof t.list=="function"&&typeof t.head=="function"&&typeof t.createMultipartUpload=="function")return Ce(`r2:${e}`,!0);if(typeof t.send=="function"&&typeof t.sendBatch=="function"&&typeof t.get!="function")return Ce(`queue:${e}`,!0);if(typeof t.connectionString=="string")return Ce(`hyperdrive:${e}`,!0)},Vt=e=>{const n=da(e.trustInboundTraceContext),t=ua(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",a=tr(e.resolveIdentity,e.identity),s=rt(e.shardDO,e.jurisdiction),l=e.schedulerDO===void 0?void 0:rt(e.schedulerDO,e.jurisdiction);let u=!1;const f=o=>{if(o===void 0||e.jurisdiction===void 0)return o;u||(u=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},g=async(o,i,h,c=e.shardRegion?.(i))=>we(o,i,f(c)).fetch(h);let E;const k=()=>e.adminToken??E;let v;const w=()=>e.requireEphemeralWsToken??v??!0;let b;const _=o=>{const i=o??{};if(b??=kt(o,e.shardDO),v===void 0&&e.requireEphemeralWsToken===void 0){const c=i.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(v=Or(c,!0))}if(E!==void 0||e.adminToken!==void 0)return;const h=i.LUNORA_ADMIN_TOKEN;typeof h=="string"&&h.length>0&&(E=h)},p=new WeakSet,S=o=>Pt(o,k())||p.has(o),D=async(o,i)=>{const h=await de(o,i,e.resolveIdentity);if(p.has(o)&&h.headers.authorization===void 0){const c=k();c!==void 0&&(h.headers.authorization=`Bearer ${c}`)}return h};let T=!1,x=!1;const H=()=>{x||(x=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},$=o=>{if(!e.allowUnauthenticatedShardAccess){const i=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new d(`${o} access is default-denied: configure \`${i}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}T||(T=!0,console.warn([`[lunora] SECURITY: serving ${o} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},U=async(o,i)=>{if(e.authorizeShard){if(!await e.authorizeShard({identity:o,shardKey:i}))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else i!==r&&$("shard")},W=Fo({defaultShard:r,forwardToShard:g,isAdmin:S,queryCoordinator:e.queryCoordinator,resolveForwardContext:D,shardDO:s}),K=async(o,i,h,c,m)=>{const R={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(R["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(R["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(R["x-lunora-mutation-id"]=c),g(s,h,ye(o,i,R))},V=async(o,i,h,c)=>{const m=h?.[o];if(!m||typeof m.create!="function")throw new d(`${c} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(ir(i))throw new d(`${c} params ${cr}`,{code:"BAD_REQUEST",status:400});await m.create({params:i})},X=async(o,i)=>{if(o.workflow){await V(o.workflow,o.args??{},i,`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 h=await K(o.functionPath,o.args??{},o.shardKey??r);if(!h.ok)throw new d(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(h.status)}`,{code:"CRON_JOB_FAILED",status:500})},J=async(o,i,h,c)=>{const m=e.cronJobs?.[o];if(m)for(const R of m)try{await X(R,i)}catch(I){h.push(c(I))}},ae=async(o,i)=>{if(!S(o))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(j(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 h=await Z(o),c=typeof h.name=="string"?h.name:"";if(c==="")throw new d("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(R=>R.name===c);if(!m)throw new d(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await X(m,i),Response.json({name:c,ran:!0},{status:200})},F=async o=>{const i=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!i||!l||typeof o.id!="string")return;const h=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await we(l,h).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:i}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},he=async(o,i)=>{j(o,"POST","Scheduler dispatch");const h=await Ct(o),c=i??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,R=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),I=o.headers.get("x-lunora-scheduler-signature");let y=!1;if(I&&m?y=await za(m,h,I):R&&(y=Pt(o,R)),!y)throw new d("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let A;try{A=JSON.parse(h)}catch{throw new d("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const O=A??{},C=O.args??{};if(typeof O.workflow=="string"&&O.workflow.length>0)return await V(O.workflow,C,i,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof O.functionPath!="string"||O.functionPath.length===0)throw new d("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const B=typeof O.shardKey=="string"&&O.shardKey.length>0?O.shardKey:r,L=typeof O.id=="string"&&O.id.length>0?O.id:void 0,te=Pa(o),M=await K(O.functionPath,C,B,L,te);return await F(O),M},G=o=>{if(!S(o))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},oe=(o,i,h)=>{if(G(o),i===void 0)throw new d(h.message,{code:h.code,status:400});return i},Te=Cr({assertAdmin:G,getReader:()=>e.authAuditReader}),Oe=async(o,i)=>{G(o);const h=e.notifySubscriptionStore;if(h===void 0)return Response.json({result:Ke({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const c=i?.kind,m=i?.userId,R=i?.limit,I=c==="fcm"||c==="web-push"?c:void 0,y=typeof m=="string"&&m!==""?m:void 0,A=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,O=A>0?Math.min(A,1e3):1e3,B=(await h.list({kind:I,limit:O,userId:y})).filter(L=>I!==void 0&&L.kind!==I?!1:y===void 0||(L.userId??null)===y).map(({keys:L,token:te,...M})=>M);return Response.json({result:Ke({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},se=async(o,i)=>{if(!i.fanOut){if(i.functionPath===Ur)return Te(o,i.args??{});if(i.functionPath===Ua)return Oe(o,i.args)}},Jt=co({applyGlobals:e.applyGlobals,assertAdmin:G,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:oe,resolveForwardContext:D,shardDO:s,streamExportRows:(o,i,h,c)=>Ft(e,o,i,h,c,s),streamingImport:(o,i)=>fo(o,e,i,s),syncGlobals:e.syncGlobals}),ve=(o,i)=>{const h=o.searchParams.get(i);return h===null||h===""?void 0:h},ke=o=>{const i=new URL(o.url),h=i.searchParams.get("limit"),c=i.searchParams.get("offset"),m=h===null?void 0:Number.parseInt(h,10),R=c===null?void 0:Number.parseInt(c,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},Je=()=>{if(l===void 0)throw new d("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return l},qt=ia({checkWsAdmin:async o=>S(o)||Wa(o,k(),w()),requireSchedulerNamespace:Je,resolveSchedulerStub:o=>(G(o),we(Je(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Yt=ba({assertAdmin:G,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Xt=Vn({assertAdmin:G,parsePaging:ke,queryParameter:ve,readBodyBytes:Fn,requireAdminOption:oe,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Zt=Wr({options:e,readJsonBody:Z,requireAdminOption:oe}),en=fa({readJsonBody:Z,requireAdminOption:oe,vectorIntrospector:e.vectorIntrospector}),tn=ko({kvIntrospector:e.kvIntrospector,readJsonBody:Z,requireAdminOption:oe}),nn=nr({logArchive:e.logArchive,readJsonBody:Z,requireAdminOption:oe}),rn=To({assertAdmin:G,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:ke,queryParameter:ve,requireAdminOption:oe}),on=o=>{const i=[],h=s??o?.SHARD;if(h!==void 0&&i.push(Zn("durable-object:default",h,r)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(o??{})){const R=Va(c,m);R!==void 0&&i.push(R)}for(const c of e.health?.probes??[])i.push(c);return i},an=Xn({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:S,resolveProbes:on}),sn=o=>{const i=e.schedulerInstanceName??"default",h=()=>we(o,i),c=async(y,A)=>{const O=await h().fetch(new Request(`https://scheduler.internal${y}`,A));if(!O.ok)throw new d(`ctx.scheduler: SchedulerDO ${y} failed (${String(O.status)}): ${await O.text()}`,{code:"INTERNAL",status:500});return await O.json()},m=async(y,A)=>await c(y,{body:JSON.stringify(A),headers:{"content-type":"application/json"},method:"POST"}),R=y=>{const A=y;if(A==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 A.binding=="string"&&A.binding.length>0)return{workflow:A.binding};if(typeof A.__lunoraRef=="string")return{functionPath:A.__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})},I=async(y,A,O={})=>{const{id:C}=await m("/schedule",{args:O,scheduledFor:y,...R(A)});return C};return{cancel:async y=>await m("/cancel",{id:y}),get:async y=>await c(`/get?id=${encodeURIComponent(y)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(y,A,O)=>{if(!Number.isFinite(y)||y<0)throw new d("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await I(Date.now()+y,A,O)},runAt:async(y,A,O)=>{if(!Number.isFinite(y))throw new d("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await I(y,A,O)}}},cn=async(o,i,h)=>{const{claims:c,headers:m,userId:R}=await de(o,i,a),I=async(y,A={})=>{const O=y.__lunoraRef;if(typeof O!="string")throw new d("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const C=ye(O,A,{...m,"x-lunora-system":"1"}),B=await g(s,r,C),L=await B.json();if(L.error)throw new d(L.error.message??"shard RPC failed",{code:L.error.code??"INTERNAL",status:B.status});return L.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:R},cache:h.cache,fetch:globalThis.fetch.bind(globalThis),runAction:I,runMutation:I,runQuery:I,...l===void 0?{}:{scheduler:sn(l)},...e.storage===void 0?{}:{storage:sr(e.storage(i))}}},dn=async(o,i,h)=>{if(!e.httpRouter)return;const c=await cn(o,i,h);try{return await e.httpRouter.fetch(o,{...i,__lunoraCtx:c},h)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},un=async(o,i,h)=>{if(o.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=at(o,ie);if(c)return c;const m=h.searchParams.get("shard")??r,{headers:R,identity:I}=await de(o,i,a);await U(I,m);const y=new Headers(o.headers),A=[...y.keys()];for(const C of A)C.startsWith("x-lunora-")&&y.delete(C);It(y,R);const O=kt(i,e.shardDO);if(O!==void 0){y.set("x-lunora-shard-binding",O);const C=await Ga(s,m);if(C>0){const B=Rr(m,Math.floor(Math.random()*C));return g(s,B,new Request(o,{headers:y}),st(o))}}return g(s,m,new Request(o,{headers:y}))},ln=async(o,i,h)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=at(o,ie);if(m)return m;let R;try{R=decodeURIComponent(h.pathname.slice(Tt.length))}catch{return new Response("Unknown voice agent",{status:404})}const I=Object.hasOwn(c,R)?c[R]:void 0;if(I===void 0)return new Response("Unknown voice agent",{status:404});const y=h.searchParams.get("threadKey");if(y===null||y.length===0)return new Response("Missing threadKey",{status:400});const{headers:A,identity:O}=await de(o,i,a);if(e.authorizeShard){if(!await e.authorizeShard({identity:O,shardKey:y}))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else $("shard");const C=new Headers(o.headers);for(const B of C.keys())B.startsWith("x-lunora-")&&C.delete(B);return It(C,A),g(I,y,new Request(o,{headers:C}))},hn=async(o,i,h)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(h,o.table,i))throw new d("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(i.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});$("fan-out")},_e=async(o,i)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await hn(o.fanOut,o.functionPath,i);return}await U(i,o.shardKey??r)}},fn=(o,i,h)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){H();return}if(e.functions[i]?.kind!=="query"||h.includes(jt)||h.includes(Mt))return;const c=st(o);return c===void 0?void 0:{name:Er(h,c),region:c}},pn=async(o,i,h,c,m)=>{const R=fn(o,i,c);if(R!==void 0){const I={...m,"x-lunora-replica-read":"1",...b===void 0?{}:{"x-lunora-shard-binding":b}},y=Ar(o.headers.get("x-lunora-min-seq"));y!==void 0&&(I["x-lunora-min-seq"]=String(y));const A=await g(s,R.name,ye(i,h,I),R.region);if(A.status!==421)return A}return g(s,c,ye(i,h,m))},Ie=async(o,i,h,c,m,R)=>{const I=Date.now(),{observability:y,sampling:A}=e,O=$e(o),{decision:C,ignoredUpstream:B,trace:L}=Yo(o,{...A===void 0?{}:{sampling:A},trustInbound:n(o)});B&&t();const te={...m,"x-lunora-sample-errors":C.keepErrors?"1":"0"};Xo(L,te);try{const M=await pn(o,i,h,c,te);ce(y,{...O,...St(L),durationMs:Date.now()-I,functionPath:i,ok:M.ok,shardKey:c,...M.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(M.status)}`,status:M.status}}},R,void 0,{isTraced:L.sampled,keepErrors:C.keepErrors});const ee=new Response(M.body,{headers:M.headers,status:M.status,statusText:M.statusText});return ee.headers.set("x-lunora-shard-key",c),ee}catch(M){throw ce(y,{...O,...St(L),...Ee(i,Date.now()-I,M,{shardKey:c})},R,void 0,{isTraced:L.sampled,keepErrors:C.keepErrors}),M}},mn=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&&o.functionPath.startsWith("__lunora_relation__:"))throw new d("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(o.fanOut&&!e.queryCoordinator)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},wn=async(o,i,h)=>{j(o,"POST","RPC");const c=await $a(o);ja(i,c),mn(c);const m=await se(o,c);if(m!==void 0)return m;const{headers:R,identity:I}=await de(o,i,a);await _e(c,I);const y=vt(c,e);{const A=Date.now(),{observability:O}=e,C=$e(o),B=Re(i,o,h&&(M=>h.waitUntil?.(M)));if(c.fanOut){const M=e.queryCoordinator;if(!M)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ee=await M.fanOut(s,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:R});return ce(O,{durationMs:Date.now()-A,fanOut:{failed:ee.failed,shards:ee.ok+ee.failed,table:c.fanOut.table},functionPath:c.functionPath,...C,ok:!0},B),Response.json(ee,{headers:{"content-type":"application/json"},status:200})}catch(ee){throw ce(O,{...Ee(c.functionPath,Date.now()-A,ee,{fanOut:{table:c.fanOut.table}}),...C},B),ee}}const L=c.shardKey??r,te=()=>Ie(o,c.functionPath,c.args??{},L,R,B);return y&&e.x402Charge?e.x402Charge(o,{functionPath:c.functionPath,price:y.price},te,At(h)):te()}},gn=async(o,i,h)=>{j(o,"POST","RPC batch");const c=await Z(o),{calls:m}=c;if(!Array.isArray(m))throw new d("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:I}=await de(o,i,a),y=Jr(m,r);for(const Q of y.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 ${Et}`,{code:"BAD_REQUEST",status:400});await Promise.all([...y.entries()].flatMap(([Q,z])=>z.map(ne=>_e({args:ne.args,functionPath:ne.functionPath,shardKey:Q},I))));const{observability:A}=e,O=Re(i,o,h&&(Q=>h.waitUntil?.(Q))),C=$e(o),B=[],L=[],te=(Q,z,ne,ue)=>({body:{error:{code:ne,message:ue}},id:Q.id,status:z}),M=(Q,z,ne,ue,fe)=>{for(const q of Q)ce(A,fe(q),O),B.push(te(q,z,ne,ue))},ee=(Q,z,ne,ue,fe)=>{for(const q of Q){const pe=ue.get(q.id)??fe,ge=pe<400;ce(A,{durationMs:ne,functionPath:q.functionPath,...C,ok:ge,shardKey:z,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},O)}};await Promise.all([...y.entries()].map(async([Q,z])=>{const ne=new Headers(R);ne.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:ne,method:"POST"}),fe=Date.now();let q;try{q=await g(s,Q,ue)}catch(Y){const Ue=Date.now()-fe,{body:et}=Nn(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});M(z,502,et.code,et.message,Pn=>({...Ee(Pn.functionPath,Ue,Y,{shardKey:Q}),...C}));return}const pe=Date.now()-fe,ge=q.headers.get("x-d1-bookmark");ge&&L.push(ge);let De;try{De=await q.json()}catch{const Y=`shard batch returned a non-JSON response (${String(q.status)})`;M(z,q.status,"SHARD_ERROR",Y,Ue=>({durationMs:pe,error:{code:"SHARD_ERROR",message:Y,status:q.status},functionPath:Ue.functionPath,...C,ok:!1,shardKey:Q}));return}const Ne=Array.isArray(De.results)?De.results:[],kn=new Map(Ne.map(Y=>[Y.id,Y.status??q.status])),In=new Set(Ne.map(Y=>Y.id));ee(z,Q,pe,kn,q.status),B.push(...Ne);for(const Y of z)In.has(Y.id)||B.push(te(Y,q.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const Xe={"content-type":"application/json"},[Ze]=L;return L.length===1&&Ze!==void 0&&(Xe["x-d1-bookmark"]=Ze),Response.json({results:B},{headers:Xe,status:200})},yn=async(o,i,h,c={},m={})=>{try{const R=h.__lunoraRef;if(typeof R!="string")throw new d("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:I,identity:y}=await de(o,i,a,m.context);await _e({args:c,functionPath:R,shardKey:m.shardKey},y);const A=m.shardKey??r,O=Re(i,o,m.waitUntil);return await Ie(o,R,c,A,I,O)}catch(R){return tt(R)}},qe=async(o,i,h)=>{const{observability:c}=e,m=Date.now(),R=Se(16),I=Se(8),y=Ot(i);try{const A=await h();return ce(c,{durationMs:Date.now()-m,functionPath:o,ok:!0,spanId:I,traceId:R},y),A}catch(A){throw ce(c,{...Ee(o,Date.now()-m,A,{}),spanId:I,traceId:R},y),A}finally{nt(c,y)}},bn=async(o,i,h)=>{_(i);const c=[],m=y=>y instanceof Error?y:new Error(String(y)),R=e.crons?.[o.cron];if(R)try{await R(o,i,h)}catch(y){c.push(m(y))}if(await J(o.cron,i,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron)try{await Fr(e,s,k(),o)}catch(y){c.push(m(y))}const[I]=c;if(c.length===1&&I)throw I;if(c.length>1)throw new AggregateError(c,`scheduled("${o.cron}") had ${String(c.length)} failure(s)`)},_n=async(o,i)=>{try{const h=o??{},c=e.adminToken??(typeof h.LUNORA_ADMIN_TOKEN=="string"?h.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await g(s,r,ye(Na,{outcome:i},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},Rn=async(o,i,h,c)=>{if(!e.authHandler)return;const m=await e.authHandler(o);if(!m)return;const R=e.authBasePath??Da;return Ba(h.pathname,R)&&c.waitUntil?.(_n(i,m.status>=400?"fail":"ok")),m},En=async({args:o,env:i,functionPath:h,request:c,shardKey:m,waitUntil:R})=>{Ut(o,"REST");const I={functionPath:h,...m===void 0?{}:{shardKey:m}},{headers:y,identity:A}=await de(c,i,a);await _e(I,A);const O=m??r,C=Re(i,c,R),B=()=>Ie(c,h,o,O,y,C),L=vt(I,e);return L&&e.x402Charge?e.x402Charge(c,{functionPath:h,price:L.price},B,At({waitUntil:R})):B()},An=Kn({functions:e.functions??{},invoke:En,readJsonBody:Z,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Pe=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Sn={[ka]: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"}}),[Ea]:(o,i,h)=>un(o,i,h),[Et]:(o,i,h,c)=>wn(o,i,c),[Ra]:(o,i,h,c)=>gn(o,i,c),[Aa]:(o,i)=>he(o,i),[Sa]:(o,i)=>ae(o,i),[Ta]:async o=>{j(o,"POST","ws-token"),G(o);const i=k();if(i===void 0)throw new d("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const h=await kr(i);return Response.json(h,{headers:{"cache-control":"no-store"}})},...W,...Jt,...qt,...Yt,...Xt,...Zt,...en,...tn,...nn,...rn,...an,...An,...Nr({assertAdmin:G,getAuthAdmin:()=>e.authAdmin,parsePaging:ke,queryParameter:ve,readJsonBody:Z})};let ie=ot(e.security),Ye=!1;const Tn=o=>{Ye||(Ye=!0,ie=ot(e.security,o??{}))},On=async(o,i)=>{if(!(e.adminGate===void 0||!Ia(i)))try{await e.adminGate(o,Fe.get(o))&&p.add(o)}catch{}},vn=async(o,i,h)=>{Fe.set(o,h);const c=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const y=Number(o.headers.get("content-length")??""),A=_a[c.pathname]??Nt;if(Number.isFinite(y)&&y>A)throw new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await Rn(o,i,c,h);if(m)return m;if(Pe){const y=`${o.method} ${c.pathname}`,A=Pe[y]??Pe[c.pathname];if(A)return A(o,i,h)}const R=Sn[c.pathname];if(R)return await On(o,c.pathname),R(o,i,c,h);if(e.voiceAgents!==void 0&&c.pathname.startsWith(Tt))return ln(o,i,c);const I=await dn(o,i,h);return I||new Response("Not found",{status:404})};return{async fetch(o,i,h){e.passThroughOnException&&h.passThroughOnException?.(),Tn(i),_(i);const c=or(o,ie);if(c)return c;const m=ar(o,ie);if(m)return Be(m,o,ie);try{const R=await vn(o,i,h);return Be(R,o,ie)}catch(R){return Be(tt(R),o,ie)}finally{nt(e.observability,Ot(h))}},async queue(o,i,h){await qe(`queue:${Ha(o)}`,h,async()=>{await e.queue?.(o,i,h)})},async scheduled(o,i,h){await qe(`cron:${o.cron}`,h,async()=>{await bn(o,i,h)})},serverQuery:yn}},Ja=e=>Vt(e),qa=e=>typeof e=="function"?{fetch:e}:e,Ya=e=>!!(e.crons??e.cronJobs??e.backupCron),ys=(e,n)=>{const t=qa(e),r=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=l=>{const u=Ja({...l,httpRouter:t});return r!==void 0&&!Ya(l)?{...u,scheduled:async(f,g,E)=>{await r(f,g,E)}}:u};if(typeof n!="function")return a(n);const s=n;return{fetch:(l,u,f)=>a(s(u)).fetch(l,u,f),queue:(l,u,f)=>a(s(u)).queue?.(l,u,f)??Promise.resolve(),scheduled:(l,u,f)=>a(s(u)).scheduled(l,u,f),serverQuery:(l,u,f,g,E)=>a(s(u)).serverQuery(l,u,f,g,E)}},Xa=(e,n)=>{if(typeof e=="function")return e(n);const t=e.shardDO??n?.SHARD;if(!t)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:t}},bs=(e={})=>(n,t,r)=>Vt(Xa(e,t)).fetch(n,t,r??Un),_s=e=>e;export{Ur as GET_AUTH_AUDIT_LOG_OP,Un as NOOP_EXECUTION_CONTEXT,As as composeIdentityResolvers,Ja as composeWorker,bs as createLunoraHandler,Vt as createWorker,_s as defineRpcEnvelope,Ga as probeRelayCount,Xa as resolveLunoraOptions,Ss as routeIdentityResolvers,ys as withFrameworkWorker};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.72",
3
+ "version": "1.0.0-alpha.74",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,8 +46,8 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/bindings": "1.0.0-alpha.36",
50
- "@lunora/errors": "1.0.0-alpha.22",
49
+ "@lunora/bindings": "1.0.0-alpha.38",
50
+ "@lunora/errors": "1.0.0-alpha.23",
51
51
  "@lunora/platform": "1.0.0-alpha.17"
52
52
  },
53
53
  "engines": {