@lunora/runtime 1.0.0-alpha.111 → 1.0.0-alpha.112

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
@@ -3351,6 +3351,27 @@ interface ScheduledControllerLike {
3351
3351
  * trigger's `cron` expression. Runs server-side with no end-user identity.
3352
3352
  */
3353
3353
  type CronHandler = (controller: ScheduledControllerLike, env: unknown, context: ExecutionContextLike) => Promise<void> | void;
3354
+ /** One forwarded queue message: the platform's opaque `body` plus its id. */
3355
+ interface QueueForwardMessage {
3356
+ body: unknown;
3357
+ id: string;
3358
+ }
3359
+ /** A batch of queue messages forwarded to a tenant via `POST /_lunora/queue`. */
3360
+ interface QueueForwardBatch {
3361
+ messages: ReadonlyArray<QueueForwardMessage>;
3362
+ queue: string;
3363
+ }
3364
+ /** Outcome of a forwarded batch: the ids to retry (everything else is acked). */
3365
+ interface QueueForwardResult {
3366
+ retry?: ReadonlyArray<string>;
3367
+ }
3368
+ /**
3369
+ * Process a batch of queue messages forwarded by the platform. WfP namespaced
3370
+ * Workers can't be queue consumers, so a platform-owned consumer fans batches in
3371
+ * here; return the ids to retry. Env-driven side effects
3372
+ * (sending mail, etc.) belong in the app's handler.
3373
+ */
3374
+ type QueueForwardHandler = (batch: QueueForwardBatch, env: unknown, context: ExecutionContextLike) => Promise<QueueForwardResult | undefined> | QueueForwardResult | undefined;
3354
3375
  /**
3355
3376
  * The trigger's own trace, handed to a consumer so every function it dispatches
3356
3377
  * is a child of the trigger span instead of an unrelated root trace.
@@ -3968,6 +3989,13 @@ interface WorkerOptions {
3968
3989
  * stays decoupled from the queue package. Omitted when no push queues exist.
3969
3990
  */
3970
3991
  queue?: QueueConsumerHandler;
3992
+ /**
3993
+ * Queue-batch handler. WfP namespaced Workers can't be
3994
+ * queue consumers, so a platform-owned consumer forwards batches to the
3995
+ * admin-gated `POST /_lunora/queue` endpoint, which invokes this. Return the
3996
+ * message ids to retry; the rest are acked. Omit if the app has no queues.
3997
+ */
3998
+ queueHandler?: QueueForwardHandler;
3971
3999
  /**
3972
4000
  * Serve one-shot **queries** from a read replica placed in the caller's
3973
4001
  * region instead of from the shard owner. Off by default.
@@ -5282,4 +5310,4 @@ export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolve
5282
5310
  * surface — without a name for it, a caller cannot hoist a shared attribute bag
5283
5311
  * into a typed constant.
5284
5312
  */
5285
- 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 TriggerTrace, 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, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
5313
+ 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 QueueForwardBatch, type QueueForwardHandler, type QueueForwardMessage, type QueueForwardResult, 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 TriggerTrace, 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, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
package/dist/index.d.ts CHANGED
@@ -3351,6 +3351,27 @@ interface ScheduledControllerLike {
3351
3351
  * trigger's `cron` expression. Runs server-side with no end-user identity.
3352
3352
  */
3353
3353
  type CronHandler = (controller: ScheduledControllerLike, env: unknown, context: ExecutionContextLike) => Promise<void> | void;
3354
+ /** One forwarded queue message: the platform's opaque `body` plus its id. */
3355
+ interface QueueForwardMessage {
3356
+ body: unknown;
3357
+ id: string;
3358
+ }
3359
+ /** A batch of queue messages forwarded to a tenant via `POST /_lunora/queue`. */
3360
+ interface QueueForwardBatch {
3361
+ messages: ReadonlyArray<QueueForwardMessage>;
3362
+ queue: string;
3363
+ }
3364
+ /** Outcome of a forwarded batch: the ids to retry (everything else is acked). */
3365
+ interface QueueForwardResult {
3366
+ retry?: ReadonlyArray<string>;
3367
+ }
3368
+ /**
3369
+ * Process a batch of queue messages forwarded by the platform. WfP namespaced
3370
+ * Workers can't be queue consumers, so a platform-owned consumer fans batches in
3371
+ * here; return the ids to retry. Env-driven side effects
3372
+ * (sending mail, etc.) belong in the app's handler.
3373
+ */
3374
+ type QueueForwardHandler = (batch: QueueForwardBatch, env: unknown, context: ExecutionContextLike) => Promise<QueueForwardResult | undefined> | QueueForwardResult | undefined;
3354
3375
  /**
3355
3376
  * The trigger's own trace, handed to a consumer so every function it dispatches
3356
3377
  * is a child of the trigger span instead of an unrelated root trace.
@@ -3968,6 +3989,13 @@ interface WorkerOptions {
3968
3989
  * stays decoupled from the queue package. Omitted when no push queues exist.
3969
3990
  */
3970
3991
  queue?: QueueConsumerHandler;
3992
+ /**
3993
+ * Queue-batch handler. WfP namespaced Workers can't be
3994
+ * queue consumers, so a platform-owned consumer forwards batches to the
3995
+ * admin-gated `POST /_lunora/queue` endpoint, which invokes this. Return the
3996
+ * message ids to retry; the rest are acked. Omit if the app has no queues.
3997
+ */
3998
+ queueHandler?: QueueForwardHandler;
3971
3999
  /**
3972
4000
  * Serve one-shot **queries** from a read replica placed in the caller's
3973
4001
  * region instead of from the shard owner. Off by default.
@@ -5282,4 +5310,4 @@ export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolve
5282
5310
  * surface — without a name for it, a caller cannot hoist a shared attribute bag
5283
5311
  * into a typed constant.
5284
5312
  */
5285
- 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 TriggerTrace, 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, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
5313
+ 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 QueueForwardBatch, type QueueForwardHandler, type QueueForwardMessage, type QueueForwardResult, 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 TriggerTrace, 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, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, 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-2d_iJXPf.mjs";import{composeWorker as x,createLunoraHandler as S,createWorker as l,defineRpcEnvelope as u,resolveLunoraOptions as _,withFrameworkWorker as d}from"./packem_shared/composeWorker-DE4s7EQK.mjs";import{createCrossShardRelationCapabilities as y}from"./packem_shared/createCrossShardRelationCapabilities-D_S3beMO.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as O,SHARD_REGISTRY_DO_NAME as b,createDynamicShardRegistry as A}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as T,toErrorResponse as h}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as P,a as g,d as v,r as I,b as D,s as M,w as F}from"./packem_shared/export-tap-CAyZ2TWC.mjs";import{HEALTH_PATH as G,HEALTH_READY_PATH as K,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-D0i8LhwT.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as J,a as Z}from"./packem_shared/observability-B1hLjwgx.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-JUcPmzoo.mjs";import{D as pe,c as ce}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as fe,createStaticShardRegistry as Ee}from"./packem_shared/createQueryCoordinator-DlWITOu1.mjs";import{applyJurisdiction as xe,resolveShard as Se}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as _e,b as de}from"./packem_shared/rest-cache-D1BlbZb1.mjs";import{a as ye,b as Ce,c as Oe,r as be}from"./packem_shared/rest-routes-CpbO5QEx.mjs";import{decorateResponse as Le,enforceOrigin as Te,handleCorsPreflight as he,resolveSecurity as He}from"./packem_shared/decorateResponse-Y2sCM0w1.mjs";import{createShardClient as ge}from"./packem_shared/createShardClient-I984JFkv.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ie}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Me}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ne}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ke,routeIdentityResolvers as Ue}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,O as DEFAULT_REGISTRY_CACHE_TTL_MS,G as HEALTH_PATH,K as HEALTH_READY_PATH,Me as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,T as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,b as SHARD_REGISTRY_DO_NAME,Ie as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,xe as applyJurisdiction,ue as applyRestCache,ye as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ke as composeIdentityResolvers,x as composeWorker,oe as consoleSink,y as createCrossShardRelationCapabilities,A as createDynamicShardRegistry,P as createKvCursorStore,S as createLunoraHandler,g as createMemoryCursorStore,ce as createPipelineLogReader,fe as createQueryCoordinator,Oe as createRestRateLimit,ge as createShardClient,Ee as createStaticShardRegistry,l as createWorker,B as d1Probe,Le as decorateResponse,v as defineExportSink,u as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,Te as enforceOrigin,he as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,I as r2Sink,_e as requestCarriesCredentials,j as resolveLogArchiveFromEnv,_ as resolveLunoraOptions,He as resolveSecurity,Se as resolveShard,de as restCacheHeaders,be as restSurfaceFromRegistry,Ue as routeIdentityResolvers,D as runExportTap,M as sanitizeChange,se as sentrySink,f as toAirbyteMessages,h as toErrorResponse,E as toFivetranResponse,F as webhookExportSink,ie as webhookSink,d as withFrameworkWorker};
1
+ import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-2d_iJXPf.mjs";import{composeWorker as x,createLunoraHandler as S,createWorker as l,defineRpcEnvelope as u,resolveLunoraOptions as _,withFrameworkWorker as d}from"./packem_shared/composeWorker-0Hjp3WEF.mjs";import{createCrossShardRelationCapabilities as y}from"./packem_shared/createCrossShardRelationCapabilities-D_S3beMO.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as O,SHARD_REGISTRY_DO_NAME as b,createDynamicShardRegistry as A}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as T,toErrorResponse as h}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as P,a as g,d as v,r as I,b as D,s as M,w as F}from"./packem_shared/export-tap-CAyZ2TWC.mjs";import{HEALTH_PATH as G,HEALTH_READY_PATH as K,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-D0i8LhwT.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as J,a as Z}from"./packem_shared/observability-B1hLjwgx.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-JUcPmzoo.mjs";import{D as pe,c as ce}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as fe,createStaticShardRegistry as Ee}from"./packem_shared/createQueryCoordinator-DlWITOu1.mjs";import{applyJurisdiction as xe,resolveShard as Se}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as _e,b as de}from"./packem_shared/rest-cache-D1BlbZb1.mjs";import{a as ye,b as Ce,c as Oe,r as be}from"./packem_shared/rest-routes-CpbO5QEx.mjs";import{decorateResponse as Le,enforceOrigin as Te,handleCorsPreflight as he,resolveSecurity as He}from"./packem_shared/decorateResponse-Y2sCM0w1.mjs";import{createShardClient as ge}from"./packem_shared/createShardClient-I984JFkv.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ie}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Me}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ne}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ke,routeIdentityResolvers as Ue}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,O as DEFAULT_REGISTRY_CACHE_TTL_MS,G as HEALTH_PATH,K as HEALTH_READY_PATH,Me as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,T as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,b as SHARD_REGISTRY_DO_NAME,Ie as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,xe as applyJurisdiction,ue as applyRestCache,ye as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ke as composeIdentityResolvers,x as composeWorker,oe as consoleSink,y as createCrossShardRelationCapabilities,A as createDynamicShardRegistry,P as createKvCursorStore,S as createLunoraHandler,g as createMemoryCursorStore,ce as createPipelineLogReader,fe as createQueryCoordinator,Oe as createRestRateLimit,ge as createShardClient,Ee as createStaticShardRegistry,l as createWorker,B as d1Probe,Le as decorateResponse,v as defineExportSink,u as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,Te as enforceOrigin,he as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,I as r2Sink,_e as requestCarriesCredentials,j as resolveLogArchiveFromEnv,_ as resolveLunoraOptions,He as resolveSecurity,Se as resolveShard,de as restCacheHeaders,be as restSurfaceFromRegistry,Ue as routeIdentityResolvers,D as runExportTap,M as sanitizeChange,se as sentrySink,f as toAirbyteMessages,h as toErrorResponse,E as toFivetranResponse,F as webhookExportSink,ie as webhookSink,d as withFrameworkWorker};
@@ -0,0 +1,6 @@
1
+ import{isLunoraError as Gn,toErrorBody as Qn}from"@lunora/errors";import{e as Kt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Wn}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as zn,f as Vn}from"./base64-Bl1_r2k1.mjs";import{e as qn,a as Jn}from"./identity-header-C4Z5pldl.mjs";import{O as ut,a as lt}from"./origin-paywall-B6eOO67m.mjs";import{o as Ie,b as Ft,p as Yn,m as Xn,d as Zn,a as er,r as tr}from"./otlp-resource-JKBCWf6c.mjs";import{e as ke,d as Ve,a as nr}from"./wire-codec-BLvSm5Mn.mjs";import{d as te,e as le,M as Gt,b as rr,f as or,g as Qt,t as ar,h as Wt}from"./rest-routes-CpbO5QEx.mjs";import{LunoraError as d,toErrorResponse as ht}from"./LunoraError-DksAgIpa.mjs";import{a as $,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as Xe,BACKUP_KEY_PREFIX as Ze,backupObjectKey as sr,backupManifestKey as ir,isBackupManifestKey as cr,backupObjectKeyOfManifest as zt}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as dr,buildStorageAdminRoutes as ur,STORAGE_UPLOAD_MAX_BODY_BYTES as lr,STORAGE_PATH as hr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{b as fr,e as pr,f as ft,g as mr,h as wr}from"./export-tap-CAyZ2TWC.mjs";import{buildHealthRoutes as gr,durableObjectProbe as yr,d1Probe as br,presenceProbe as Le}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as _r}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Js,routeIdentityResolvers as Ys}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Er}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{r as Rr,f as pt,a as ie}from"./observability-B1hLjwgx.mjs";import{resolveShard as we,applyJurisdiction as mt}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as wt,handleCorsPreflight as Sr,enforceOrigin as Ar,decorateResponse as Me,enforceWebSocketOrigin as gt}from"./decorateResponse-Y2sCM0w1.mjs";const Tr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},Vt="__lunoraBranch",Or=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Vt),vr=`may not contain the reserved workflow branch-marker key ("${Vt}")`,kr=async e=>{const t=[];let n;for(;;){const o=await e(n);if(t.push(...Array.isArray(o.records)?o.records:[]),o.truncated!==!0||typeof o.cursor!="string"||o.cursor.length===0)return t;if(o.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=o.cursor}},et=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let a=0;a<n;a+=1){const c=a<e.length?e.charCodeAt(a):0,l=a<t.length?t.charCodeAt(a):0;o|=c^l}return o===0},Ir=/already[\s_-]?exists/iu,Pr=e=>Ir.test(e instanceof Error?e.message:String(e)),Dr=(e,t,n,o)=>{const a=e.get(t);if(a!==void 0)return a;Kt(e,o);const c=n().catch(l=>{throw e.get(t)===c&&e.delete(t),l});return e.set(t,c),c},tt=new TextEncoder,Nr=Array.from({length:32},(e,t)=>t);new RegExp(`[${Nr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Ur=64,Cr=new Map,qt=async e=>Dr(Cr,e,async()=>crypto.subtle.importKey("raw",tt.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),Ur),Jt=async(e,t)=>{const n=await qt(e),o=await crypto.subtle.sign("HMAC",n,tt.encode(t));return zn(new Uint8Array(o))},Br=async(e,t,n)=>{const o=await qt(e);return crypto.subtle.verify("HMAC",o,n,tt.encode(t))},xr=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(xr);const Hr=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Lr=-100,Mr=15,jr=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Hr.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Mr?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Lr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},yt=e=>{const t=e.cf;return t===void 0?void 0:jr(t)},qe="::relay::",$r=(e,t)=>`${e}${qe}${String(t)}`,Je="::replica::",Kr=(e,t)=>`${e}${Je}${t}`,Fr=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Gr=new Set(["1","enabled","on","true","yes"]),Qr=new Set(["0","disabled","false","no","off"]),Wr=(e,t)=>{const n=(e??"").trim().toLowerCase();return Gr.has(n)?!0:Qr.has(n)?!1:t},Yt="v1",zr=6e4,Vr=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??zr),o=`${Yt}.${String(n)}`,a=await Jt(e,o);return{expiresAtMs:n,token:`${o}.${a}`}},qr=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[a,c,l]=o;if(a!==Yt||l.length===0)return!1;const f=Number(c);if(!Number.isFinite(f)||f<=n)return!1;let m;try{m=Vn(l)}catch{return!1}return Br(e,`${a}.${c}`,m)},P="/_lunora/admin/auth",Jr={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},N=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new d(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},ue=(e,t)=>{const n=e(t);if(n===void 0)throw new d(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},Xt=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},re=(e,t)=>typeof e[t]=="string"?e[t]:void 0,je=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},bt=e=>{const t=Xt(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new d("`role` is required",{code:"BAD_REQUEST",status:400});return t},_t=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[o,a]of Object.entries(t))Array.isArray(a)&&a.every(c=>typeof c=="string")&&(n[o]=a);return n},Yr={[`${P}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${P}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${P}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${P}/accounts`]:{build:({query:e})=>({userId:ue(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:ue(e,"userId")}),http:"GET",method:"listPasskeys"},[`${P}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${P}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:ue(t,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:ue(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${P}/sign-up-invitations/create`]:{build:({body:e})=>({email:N(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:re(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${P}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:N(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:ue(t,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:ue(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:ue(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:je(e,"data"),email:N(e,"email"),name:N(e,"name"),password:re(e,"password"),role:Xt(e.role)}),http:"POST",method:"createUser"},[`${P}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:N(e,"userId")}},http:"POST",method:"updateUser"},[`${P}/users/role`]:{build:({body:e})=>({role:bt(e),userId:N(e,"userId")}),http:"POST",method:"setRole"},[`${P}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:N(e,"userId")}),http:"POST",method:"banUser"},[`${P}/users/unban`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"unbanUser"},[`${P}/users/password`]:{build:({body:e})=>({newPassword:N(e,"newPassword"),userId:N(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${P}/users/remove`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${P}/users/impersonate`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"impersonateUser"},[`${P}/sessions/revoke`]:{build:({body:e})=>({sessionId:N(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${P}/sessions/revoke-all`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${P}/accounts/unlink`]:{build:({body:e})=>({accountId:N(e,"accountId"),userId:N(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${P}/two-factor/disable`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${P}/passkeys/delete`]:{build:({body:e})=>({passkeyId:N(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${P}/organizations/members/remove`]:{build:({body:e})=>({memberId:N(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${P}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:N(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${P}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:je(e,"metadata"),name:N(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:je(e,"metadata"),name:re(e,"name"),organizationId:N(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${P}/organizations/remove`]:{build:({body:e})=>({organizationId:N(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${P}/organizations/members/add`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),role:re(e,"role"),userId:N(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:N(e,"email"),inviterId:re(e,"inviterId"),organizationId:N(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:N(e,"memberId"),role:bt(e)}),http:"POST",method:"updateMemberRole"},[`${P}/organizations/teams/create`]:{build:({body:e})=>({name:N(e,"name"),organizationId:N(e,"organizationId")}),http:"POST",method:"createTeam"},[`${P}/organizations/teams/update`]:{build:({body:e})=>({name:N(e,"name"),teamId:N(e,"teamId")}),http:"POST",method:"updateTeam"},[`${P}/organizations/teams/remove`]:{build:({body:e})=>({teamId:N(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${P}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:N(e,"teamId"),userId:N(e,"userId")}),http:"POST",method:"addTeamMember"},[`${P}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:N(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${P}/organizations/roles/create`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),permission:_t(e),role:N(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:_t(e),roleId:N(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${P}/organizations/roles/remove`]:{build:({body:e})=>({roleId:N(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Xr=e=>{const t=async a=>{try{return await a()}catch(c){if(c instanceof d)throw c;const l=c,f=typeof l.code=="string"?l.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",c),new d("auth admin operation failed",{code:f,status:Jr[f]??500})}},n=async(a,c)=>{if(e.assertAdmin(a),a.method!==c.http)throw new d(`Auth admin endpoint requires ${c.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const l=e.getAuthAdmin();if(l===void 0)throw new d("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=l[c.method];if(f===void 0)throw new d(`auth admin does not support \`${c.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const m=new URL(a.url),p={body:c.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:T=>e.queryParameter(m,T)},E=c.build(p),S=await t(()=>f(E));return Response.json(c.returns==="void"?{ok:!0}:S,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[a,c]of Object.entries(Yr))o[a]=l=>n(l,c);return o},Et="__lunora_admin__:getAuthAuditLog",Rt=e=>typeof e=="string"&&e!==""?e:void 0,St=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Zr=e=>async(n,o)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new d("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const c=Rt(o.actorId),l=Rt(o.event),f=St(o.sinceSeq),m=St(o.limit),p={...c===void 0?{}:{actorId:c},...l===void 0?{}:{event:l},...f===void 0?{}:{sinceSeq:f},...m===void 0?{}:{limit:m}};let E;try{E=await a.read(p)}catch(T){throw T instanceof d?T:(console.error("[lunora] auth audit read failed:",T),new d("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const S={entries:E};return Response.json({result:ke(S)},{headers:{"content-type":"application/json"},status:200})},eo=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?o.push(a):n.push(a);return{globalTables:o,shardLocalTables:n}},to=async(e,t,n,o,a,c,l)=>{if(n!==void 0&&o.length===0)return;const f=await e.orchestrateExport(c,{args:{tables:o},defaultShardKey:l,headers:t,tables:o});for(const m of f.shards)if(!m.error)for(const p of m.rows??[])a(p)},Zt=async(e,t,n,o,a,c)=>{const l=o??e.listSchemaTables?.();o===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:f,shardLocalTables:m}=eo(e,l);await to(t,n,l,m,a,c,e.defaultShardKey??"__root__");const p=e.exportGlobals;if((o===void 0||f.length>0)&&p)for await(const S of p({tables:f}))a(S)},no=new TextEncoder,ro=1e3,en=10,oo=200,At=8,tn="lunoraBackupCron",Tt=24*1048576,Ot=e=>{const t=e.slice(0,en).map(o=>zt(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},ao=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const a of e)n.set(a,o),o+=a.byteLength;return n},nt=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let c;for(let l=0;l<ro;l+=1){const f=await e.list({cursor:c,include:["customMetadata"],prefix:t});for(const m of f.objects)cr(m.key)&&m.customMetadata?.[tn]===o&&a.push(m.key);if(!f.truncated||f.cursor===void 0)break;c=f.cursor}return{eligible:a.length,stale:a.toSorted((l,f)=>f.localeCompare(l)).slice(n)}},so=async(e,t,n,o,a)=>{const{stale:c}=await nt(e,t,n,o),l=new Set(a),f=c.filter(w=>l.has(w)),m=f.slice(0,oo),p=c.length-m.length,E=a.length-f.length;if(m.length===0)return{deleted:[],failed:[],ignored:E,remaining:p};const S=[],T=[];for(let w=0;w<m.length;w+=At){const b=await Promise.allSettled(m.slice(w,w+At).map(async R=>(await e.delete(zt(R)),await e.delete(R),R)));for(const[R,g]of b.entries())g.status==="fulfilled"?S.push(g.value):T.push(m[w+R])}return S.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(S.length)}: ${Ot(S)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${Ot(T)}`),{deleted:S,failed:T,ignored:E,remaining:p}},io=async e=>{const t=e.backupStore;if(!t)throw new d("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=Xe(e.backupPrefix??Ze),o=e.backupCron,{eligible:a,stale:c}=o===void 0?{eligible:0,stale:[]}:await nt(t,n,e.backupRetain,o);return{cron:o,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:c}},co=async(e,t,n,o)=>{const a=e.backupStore,c=e.queryCoordinator;if(!a)throw new d("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!c)throw new d("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!n||n.length===0)throw new d("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const l={authorization:`Bearer ${n}`,"content-type":"application/json"},f=e.backupTables;let m=0,p=0,E=[];await Zt(e,c,l,f,U=>{const H=no.encode(`${JSON.stringify(U)}
2
+ `);if(m+=1,p+=H.byteLength,p>Tt)throw new d(`scheduled backup reached ${String(p)} bytes of NDJSON, past the ${String(Tt)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});E.push(H)},t);const T=Xe(e.backupPrefix??Ze),w=new Date(o.scheduledTime).toISOString(),b=sr(T,w),R=ao(E,p);E=[];const g=dr(await crypto.subtle.digest("SHA-256",R));await a.put(b,R,{httpMetadata:{contentType:"application/x-ndjson"},sha256:g});const O={bytes:p,createdAt:w,cron:o.cron,file:b,id:w,rows:m,scheduledTime:o.scheduledTime,sha256:g,...f?{tables:f.join(",")}:{}};await a.put(ir(b),`${JSON.stringify(O,void 0,2)}
3
+ `,{customMetadata:{[tn]:o.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:U}=await nt(a,T,e.backupRetain,o.cron);if(U.length>0){const H=U.slice(0,en),D=U.length-H.length;console.info(`[lunora] backup retention: ${String(U.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${H.join(", ")}${D>0?` (+${String(D)} more)`:""}`)}}catch(U){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,U)}},uo=async(e,t)=>{const n=e.backupStore;if(!n)throw new d("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const o=e.backupCron,a=e.backupRetain;if(o===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 so(n,Xe(e.backupPrefix??Ze),a,o,t)},lo="/_lunora/admin/backup/retention",ho="/_lunora/admin/backup/prune",fo=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,a=(f,m)=>{o(f,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${m} requires a \`backupStore\` on the worker`})},c=async f=>($(f,"GET","Backup-retention"),a(f,"retention preview"),Response.json(await io(t),{headers:{"cache-control":"no-store"}})),l=async f=>{$(f,"POST","Backup-prune"),a(f,"prune");const{confirm:m}=await n(f);if(!Array.isArray(m)||m.some(p=>typeof p!="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 uo(t,m),{headers:{"cache-control":"no-store"}})};return{[ho]:l,[lo]:c}},vt=500,po=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new d("each batch call must be an object",{code:"BAD_REQUEST",status:400});const o=e;if(typeof o.functionPath!="string")throw new d("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(o.functionPath.startsWith("__lunora_relation__:")||o.functionPath.startsWith("__lunora_admin__"))throw new d("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(o.args!==void 0&&(typeof o.args!="object"||o.args===null||Array.isArray(o.args)))throw new d("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(o.id!==void 0&&typeof o.id!="number")throw new d("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:o.args===void 0?{}:o.args,clientId:typeof o.clientId=="string"?o.clientId:void 0,clientSeq:typeof o.clientSeq=="number"?o.clientSeq:void 0,functionPath:o.functionPath,id:typeof o.id=="number"?o.id:t,mutationId:typeof o.mutationId=="string"?o.mutationId:void 0},shardKey:typeof o.shardKey=="string"?o.shardKey:n}},mo=(e,t)=>{if(e.length>vt)throw new d(`RPC batch exceeds the ${String(vt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,o=new Set;for(const[a,c]of e.entries()){const{entry:l,shardKey:f}=po(c,a,t);if(o.has(l.id))throw new d(`batch call id ${String(l.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});o.add(l.id);const m=n.get(f)??[];m.push(l),n.set(f,m)}return n},wo="/_lunora/admin/export",go="/_lunora/admin/import",yo="/_lunora/admin/sync",bo="/_lunora/admin/connector/sync",_o="/_lunora/admin/apply",Eo="/_lunora/admin/export-tap/run",Ro=new TextEncoder,So=async e=>{const n=await le(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new d("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const o=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new d("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});o.push(a)}return{tables:o}},$e=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,Ao=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:a,knownTables:c,queryCoordinator:l,assertAdmin:f,requireAdminOption:m,resolveForwardContext:p,shardDO:E,streamExportRows:S,streamingImport:T,syncGlobals:w}=e,b=async(D,F)=>{const M=me(D,["POST"]);if(M)return M;const Z=m(D,l,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),C=await So(D),{headers:G}=await p(D,F),q=new ReadableStream({async pull(J){const ee=Q=>{J.enqueue(Ro.encode(`${JSON.stringify(Q)}
4
+ `))};try{await S(Z,G,C.tables,ee),J.close()}catch(Q){J.error(Q)}}});return new Response(q,{headers:{"content-type":"application/x-ndjson"},status:200})},R=async(D,F)=>{const M=me(D,["POST"]);if(M)return M;const Z=m(D,l,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),C=await te(D),G=typeof C.cursors=="object"&&C.cursors!==null?C.cursors:{},q=typeof C.limit=="number"?C.limit:void 0,J=typeof C.globalCursor=="number"?C.globalCursor:0,ee=$e(C.tables),{headers:Q}=await p(D,F),K=ee??c(),j=await Z.orchestrateCdcSync(E,{cursors:G,defaultShardKey:n,headers:Q,limit:q,tables:K}),he=w?await w({limit:q,sinceSeq:J}):void 0;return Response.json({global:he,shards:j.shards},{status:200})},g=async(D,F)=>{const M=me(D,["POST"]);if(M)return M;const Z=m(D,l,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),C=await te(D),G=pr(C.cursor),q=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,J=$e(C.tables),{headers:ee}=await p(D,F),Q=J??c(),K=await Z.orchestrateCdcSync(E,{cursors:G.s,defaultShardKey:n,headers:ee,limit:q,tables:Q}),j=[],he={...G.s};let ce=!1;for(const ae of K.shards)ce=ft(j,ae.changes??[],wr(q))||ce,he[ae.shardKey]=ae.cursor;let ge=G.g;if(w){const ae=await w({limit:q,sinceSeq:G.g});ce=ft(j,ae.changes,q)||ce,ge=ae.cursor}const De=mr({g:ge,s:he,v:1}),Ne={changes:j,hasMore:ce,nextCursor:De};return Response.json(Ne,{status:200})},O=async(D,F)=>{const M=me(D,["POST"]);if(M)return M;const Z=m(D,l,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),C=await te(D),q=(Array.isArray(C.batches)?C.batches:[]).map(j=>j).filter(j=>j!==null&&typeof j=="object"&&typeof j.shardKey=="string"&&Array.isArray(j.changes)),J=Array.isArray(C.globalChanges)?C.globalChanges:[],{headers:ee}=await p(D,F),Q=await Z.orchestrateApplyCdc(E,{batches:q,headers:ee}),K=J.length>0&&t?await t({changes:J}):0;return Response.json({applied:Q.applied+K,failed:Q.failed,ok:Q.ok},{status:200})},U=async(D,F)=>{const M=me(D,["POST"]);if(M)return M;f(D);const{headers:Z}=await p(D,F),C=await T(D,Z);return Response.json(C,{headers:{"content-type":"application/json"},status:C.failed.length>0?207:200})},H=async(D,F)=>{const M=me(D,["POST"]);if(M)return M;const Z=m(D,l,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(a===void 0||Object.keys(a).length===0||o===void 0)throw new d("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const C=await te(D),G=typeof C.sink=="string"?C.sink:void 0,q=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,J=$e(C.tables);if(G===void 0)throw new d("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const ee=a[G];if(ee===void 0)throw new d(`Export-tap sink "${G}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:Q}=await p(D,F),K=J??c(),j=await fr({coordinator:Z,cursorStore:o,defaultShardKey:n,headers:Q,limit:q,shardDO:E,sink:ee,tables:K});return Response.json(j,{headers:{"content-type":"application/json"},status:200})};return{[_o]:O,[bo]:g,[wo]:b,[Eo]:H,[go]:U,[yo]:R}},To=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const o=n;return typeof o.table!="string"||o.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!o.doc||typeof o.doc!="object"||Array.isArray(o.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:o.table},ok:!1}:{doc:o.doc,ok:!0,table:o.table}},Oo=(e,t,n,o,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const c=e[n.mode.field];return c==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof c=="string"?c:JSON.stringify(c)}}return{ok:!0,shardKey:o}},vo=async(e,t,n)=>{if(!e.body)throw new d("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const o=[],a=[],c=new Map;let l=0,f=0;const m=e.body.getReader(),p=new TextDecoder;let E="",S=0;const T=w=>{f+=1;const b=w.trim();if(b.length===0)return;l+=1;const R=To(b,f);if(!R.ok){o.push(R.error);return}const{doc:g,table:O}=R,U=t.resolveTableSharding?.(O);if(U?.mode.kind==="global"){a.push({doc:g,line:f,table:O});return}const H=Oo(g,O,U,n,f);if(!H.ok){o.push(H.error);return}const D=c.get(H.shardKey);D?D.rows.push({doc:g,table:O}):c.set(H.shardKey,{rows:[{doc:g,table:O}],shardKey:H.shardKey,startLine:f})};for(;;){const{done:w,value:b}=await m.read();if(w)break;if(b&&(S+=b.byteLength,S>Gt))throw await m.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=p.decode(b,{stream:!0});let R=E.indexOf(`
5
+ `);for(;R!==-1;){const g=E.slice(0,R);E=E.slice(R+1),T(g),R=E.indexOf(`
6
+ `)}}return E.length>0&&T(E),{errors:o,globalRows:a,perShard:c,received:l}},ko=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),kt=(e,t)=>{for(const[n,o]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+o;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},Io=async(e,t,n,o)=>{const a=t.defaultShardKey??"__root__",{errors:c,globalRows:l,perShard:f,received:m}=await vo(e,t,a),p={conflicts:0,errors:c,failed:[],inserted:{}},E=[];if(t.resolveTableSharding===void 0&&f.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"),f.size>0){const S=t.queryCoordinator;if(!S)throw new d("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const T=await S.orchestrateImport(o,{batches:[...f.values()],headers:n});kt(p,T),p.failed.push(...ko(T.shards))}if(l.length>0)if(t.importGlobals){const S=l[0]?.line??1,T=await t.importGlobals({rows:l,startLine:S});kt(p,T)}else for(const S of l)p.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:S.line,message:`row targets global table "${S.table}" but no \`importGlobals\` is configured`,table:S.table});return{conflicts:p.conflicts,errors:p.errors,failed:p.failed,inserted:p.inserted,received:m,...E.length>0?{warnings:E}:{}}},Ke=e=>typeof e=="object"&&e!==null?e:{},Fe=e=>typeof e.kind=="string"?e.kind:"unknown",Po=(e,t)=>{let n=Ke(t),o=!1;Fe(n)==="optional"&&(o=!0,n=Ke(n._meta?.inner));const a=Fe(n),c=n._meta??{},l={kind:a,name:e,optional:o};if(a==="id"&&typeof c.tableName=="string"&&(l.table=c.tableName),a==="array"){const f=Fe(Ke(c.inner));f!=="unknown"&&(l.element=f)}return l},Do=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>Po(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),No="/_lunora/admin/functions",Uo="/_lunora/admin/cron-jobs",Co="/_lunora/admin/openapi",Bo="/_lunora/admin/openrpc",xo="/_lunora/admin/global/tables",Ho="/_lunora/admin/global/table",Lo="/_lunora/admin/global/facet",It=e=>{if(e===void 0||e==="")return;let t;try{t=Ve(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(o=>{if(typeof o!="object"||o===null||typeof o.column!="string")return[];const{column:a,value:c}=o;return[{column:a,value:c}]});return n.length===0?void 0:n},Mo=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:{}}),jo=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"}),$o=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:a,requireAdminOption:c}=e,l=w=>{$(w,"GET","Functions");const b=c(w,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),R=Object.entries(b).flatMap(([g,O])=>O.visibility==="internal"||O.kind==="stream"?[]:[{args:Do(O.args),kind:O.kind,path:g}]).toSorted((g,O)=>g.path.localeCompare(O.path));return Response.json({functions:R},{headers:{"content-type":"application/json"},status:200})},f=w=>{$(w,"GET","Cron-jobs");const b=c(w,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),R=Object.entries(b).flatMap(([g,O])=>O.map(U=>({args:U.args,cron:g,functionPath:U.functionPath,name:U.name,shardKey:U.shardKey,workflow:U.workflow}))).toSorted((g,O)=>g.name.localeCompare(O.name));return Response.json({jobs:R},{headers:{"content-type":"application/json"},status:200})},m=w=>($(w,"GET","OpenAPI"),t(w),Response.json(n.openApiSpec??Mo,{headers:{"content-type":"application/json"},status:200})),p=w=>($(w,"GET","OpenRPC"),t(w),Response.json(n.openRpcSpec??jo,{headers:{"content-type":"application/json"},status:200})),E=async w=>{$(w,"GET","Global-tables");const b=c(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await b.listTables(),{headers:{"content-type":"application/json"},status:200})},S=async w=>{$(w,"GET","Global-table");const b=c(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(w.url),g=a(R,"table");if(g===void 0)throw new d("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const O=await b.readTablePage({...o(w),filters:It(a(R,"filters")),table:g});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},T=async w=>{$(w,"GET","Global-facet");const b=c(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(w.url),g=a(R,"table"),O=a(R,"column");if(g===void 0||O===void 0)throw new d("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const U=a(R,"limit"),H=U===void 0?void 0:Number(U),D=await b.facetColumn({column:O,filters:It(a(R,"filters")),limit:H!==void 0&&Number.isFinite(H)?H:void 0,table:g});return Response.json(D,{headers:{"content-type":"application/json"},status:200})};return{[Uo]:f,[No]:l,[Lo]:T,[Ho]:S,[xo]:E,[Co]:m,[Bo]:p}},Ko="/_lunora/admin/kv/namespaces",Fo="/_lunora/admin/kv/keys",nn="/_lunora/admin/kv/value",rn=32*1048576,Pt=60,Go=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=b=>n(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),c=(b,R)=>{const g=new URL(b.url),O=g.searchParams.get("namespace")??"",U=g.searchParams.get("key")??"";if(O==="")throw new d(`KV-value ${R} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(U==="")throw new d(`KV-value ${R} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:U,namespace:O}},l=async(b,R)=>{if(!(await b.listNamespaces()).some(O=>O.binding===R))throw new d(`Unknown KV namespace binding \`${R}\``,{code:"NOT_FOUND",status:404})},f=async b=>($(b,"GET","KV-namespaces"),a({namespaces:await o(b).listNamespaces()})),m=async b=>{$(b,"GET","KV-keys");const R=o(b),g=new URL(b.url),O=g.searchParams.get("namespace")??"";if(O==="")throw new d("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const U=g.searchParams.get("prefix")??void 0,H=g.searchParams.get("cursor")??void 0,D=g.searchParams.get("limit"),F=D===null?void 0:Number.parseInt(D,10);if(F!==void 0&&(!Number.isInteger(F)||F<1))throw new d("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const M=F===void 0?void 0:Math.min(F,1e3);return await l(R,O),a(await R.listKeys({cursor:H,limit:M,namespace:O,prefix:U}))},T={DELETE:async b=>{const R=o(b),g=c(b,"DELETE");return await l(R,g.namespace),await R.deleteKey(g),a({deleted:!0})},GET:async b=>{const R=o(b),g=c(b,"GET");return await l(R,g.namespace),a(await R.getValue(g))},PUT:async b=>{const R=o(b),g=await t(b,rn);if(typeof g.namespace!="string"||g.namespace==="")throw new d("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof g.key!="string"||g.key==="")throw new d("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof g.value!="string")throw new d("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(g.expirationTtl!==void 0&&(typeof g.expirationTtl!="number"||!Number.isInteger(g.expirationTtl)||g.expirationTtl<Pt))throw new d("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const O=Math.floor(Date.now()/1e3)+Pt;if(g.expiration!==void 0&&(typeof g.expiration!="number"||!Number.isInteger(g.expiration)||g.expiration<O))throw new 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(R,g.namespace),await R.putValue({expiration:g.expiration,expirationTtl:g.expirationTtl,key:g.key,metadata:g.metadata,namespace:g.namespace,value:g.value}),a({ok:!0})}},w=b=>{const R=T[b.method];if(!R)throw new d("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return R(b)};return{[Ko]:f,[Fo]:m,[nn]:w}},Qo="/_lunora/migrate",Wo="/_lunora/admin/pitr",zo="/_lunora/admin/rank",Vo="/_lunora/admin/rankpage",qo="/_lunora/admin/shard-traffic",Jo=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Yo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Xo=async e=>{const n=await le(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!Jo.has(n.functionPath))throw new d("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},Zo=async e=>{const n=await le(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new d("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new d("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new d("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new d("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},ea=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new d('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},ta=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})},na=async e=>{const n=await le(e,"Rank page")??{};ta(n);const o=ea(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:o,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},ra=async e=>{const n=await le(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},oa=async e=>{const n=await te(e);if(typeof n.functionPath!="string"||!Yo.has(n.functionPath))throw new d("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new d("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},aa=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:a,resolveForwardContext:c,shardDO:l}=e,f=(w,b)=>{if(w.method!=="POST")throw new d(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(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},m=async(w,b)=>{const R=f(w,"Migration"),g=await Xo(w),{headers:O}=await c(w,b),U=await R.orchestrateMigration(l,{args:g.args,defaultShardKey:t,functionPath:g.functionPath,headers:O,table:g.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},p=async(w,b)=>{const R=f(w,"Rank"),g=await Zo(w),{headers:O}=await c(w,b),U=await R.orchestrateRank(l,{headers:O,index:g.index,partitionKey:g.partitionKey,rowId:g.rowId,sortValues:g.sortValues,table:g.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},E=async(w,b)=>{const R=f(w,"Rank page"),g=await na(w),{headers:O}=await c(w,b),U=await R.orchestrateRankPage(l,{...g,headers:O});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},S=async(w,b)=>{const R=f(w,"Shard-traffic"),g=await ra(w),{headers:O}=await c(w,b),U=await R.orchestrateShardTraffic(l,{headers:O,table:g.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},T=async(w,b)=>{if($(w,"POST","PITR"),!o(w))throw new d("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const R=await oa(w),{headers:g}=await c(w,b),O=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:R.args,functionPath:R.functionPath}),headers:g,method:"POST"});return n(l,R.shardKey??t,O)};return{[Qo]:m,[Wo]:T,[zo]:p,[Vo]:E,[qo]:S}},sa=1,ia=0,ca=32,da=512,ua=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,la=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>da)return;const n=t.split(",");if(!(n.length>ca)){for(const o of n)if(!ua.test(o.trim()))return;return t}},ha=e=>{const t=Yn(e.headers.get("traceparent"));if(t===void 0)return;const n=la(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},fa=(e,t={})=>{const n=ha(e),o=t.trustInbound===!0?n:void 0,a=Ie(8),c=o?.traceId??Ie(16),l=Rr(t.sampling,o===void 0?a:c),f=l.isTraced&&(o===void 0||o.sampled);return{decision:l,ignoredUpstream:n!==void 0&&o===void 0,trace:{sampled:f,spanId:a,traceFlags:f?sa:ia,traceId:c,...o?.parentSpanId===void 0?{}:{parentSpanId:o.parentSpanId},...o?.traceState===void 0?{}:{traceState:o.traceState}}}},pa=(e,t)=>{t.traceparent=Ft(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},ma=(e,t)=>{let n;return()=>{if(n===void 0){const o=tr(e),a=t===void 0?void 0:t.cf;n=Xn(er(o),Zn(o,a))}return n}},wa="/_lunora/admin/scheduled",ga="/_lunora/admin/scheduled/status",ya="/_lunora/admin/scheduled/ws",ba="/_lunora/admin/scheduled/cancel",_a="/_lunora/admin/scheduled/dead",Ea="/_lunora/admin/scheduled/dead/retry",Ra="/_lunora/admin/scheduled/dead/cancel",Sa="/_lunora/admin/scheduled/pool/release",Aa=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:a}=e,c=(p,E)=>S=>{if(S.method!=="GET")throw new d(`${E} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(S.url).searchParams.get("cursor"),w=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return o(S).fetch(new Request(`https://scheduler.internal${p}${w}`,{method:"GET"}))},l=(p,E,S=E)=>async T=>{if(T.method!=="POST")throw new d(`${S} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const w=o(T),b=await le(T,E);if(typeof b?.id!="string"||b.id==="")throw new d(`${E} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return w.fetch(new Request(`https://scheduler.internal${p}`,{body:JSON.stringify({id:b.id}),headers:{"content-type":"application/json"},method:"POST"}))},f=async p=>{if(p.method!=="POST")throw new d("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const E=o(p),S=await le(p,"Scheduled pool-release");if(typeof S?.pool!="string"||S.pool==="")throw new d("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const T=typeof S.id=="string"&&S.id!==""?S.id:void 0;return E.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(T===void 0?{pool:S.pool}:{id:T,pool:S.pool}),headers:{"content-type":"application/json"},method:"POST"}))},m=async p=>{if(p.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(p))throw new d("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const E=n();return we(E,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ba]:l("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[Ra]:l("/dead/cancel","Scheduled dead-letter action"),[_a]:c("/dead","Scheduled dead-letter"),[Ea]:l("/dead/retry","Scheduled dead-letter action"),[wa]:c("/list","Scheduled-list"),[Sa]:f,[ga]:c("/status","Scheduler-status"),[ya]:m}},Ta=(e,...t)=>{let n=e.cf;for(const o of t){if(typeof n!="object"||n===null)return;n=n[o]}return typeof n=="string"?n:void 0},Dt={mtls:e=>Ta(e,"tlsClientAuth","certVerified")==="SUCCESS"},Oa=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(Dt,e)?Dt[e]:void 0)??(()=>!1),va=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},ka="/_lunora/admin/vector/indexes",Ia="/_lunora/admin/vector/query",Pa=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=async c=>{$(c,"GET","Vector-indexes");const l=n(c,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 c=>{$(c,"POST","Vector-query");const l=n(c,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 m=await t(c);if(typeof m.name!="string"||m.name==="")throw new d("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof m.text!="string"||m.text==="")throw new d("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(m.topK!==void 0&&(typeof m.topK!="number"||!Number.isInteger(m.topK)||m.topK<1))throw new d("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const p=await l.queryIndex({name:m.name,text:m.text,topK:m.topK});return Response.json(p,{headers:{"content-type":"application/json"},status:200})};return{[ka]:o,[Ia]:a}},Da="/_lunora/admin/workflows/instances",Na="/_lunora/admin/workflows/instance",Ua="/_lunora/admin/workflows/status",Ca={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Ba=e=>e!==null&&Object.hasOwn(Ca,e)?e:void 0,Nt=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const o=Number(n);return Number.isInteger(o)&&o>0?o:void 0},Ge=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new d(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},Ut=()=>{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})},xa=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,o=async(l,f,m)=>{$(l,"GET","Workflows instances"),t(l);const p=n(f);if(!p)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const E=Ge(m,"name"),S=Ba(m.searchParams.get("status"));return Response.json(await p.listInstances({page:Nt(m,"page"),perPage:Nt(m,"perPage"),status:S,workflowName:E}))},a=async(l,f,m)=>{$(l,"GET","Workflows instance"),t(l);const p=n(f);return p?Response.json(await p.getInstance({instanceId:Ge(m,"id"),workflowName:Ge(m,"name")})):Ut()},c=async(l,f)=>{$(l,"POST","Workflows status"),t(l);const m=n(f);if(!m)return Ut();const p=await l.json().catch(()=>{});if(typeof p?.name!="string"||p.name===""||typeof p.id!="string"||p.id==="")throw new d("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:E}=p;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 m.setInstanceStatus({action:E,instanceId:p.id,workflowName:p.name}))};return{[Na]:a,[Da]:o,[Ua]:c}},Ha={[nn]:rn,[hr]:lr},Ct="/_lunora/rpc",La="/_lunora/rpc-batch",Ma="/_lunora/ws",be=(e,t,n)=>({resourceAttributes:ma(e,t),...n===void 0?{}:{waitUntil:n}}),Qe=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Bt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),We=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let o;try{o=new URL(e.url)}catch{return{method:t,userAgent:n}}const a=o.port===""?void 0:Number(o.port);return{host:o.hostname,method:t,path:o.pathname,port:Number.isNaN(a)?void 0:a,scheme:o.protocol.replace(":",""),userAgent:n}},xt="/_lunora/voice/",ja="/_lunora/scheduler/dispatch",$a="/_lunora/admin/cron-jobs/run",Ka="/_lunora/admin/ws-token",Fa="/_lunora/admin/",Pe="/_lunora/",Ga="/_lunora/migrate",Qa="/_lunora/status",Wa=e=>e.startsWith(Fa)||e===Ga,za="/_lunora/scheduled",Va="/_lunora/queue",qa="__lunora_relation__:",Se=e=>{if(e.startsWith(qa))throw new d("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Ae=async e=>await e===!0,Ja=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},Ht="/api/auth",Ya="__lunora_admin__:recordAuthEvent",Xa="__lunora_admin__:listPushSubscriptions",Za=["/sign-in","/sign-up","/callback"],es=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return Za.some(a=>o===a||o.startsWith(`${a}/`))},ts=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},Te=(e,t,n,o)=>{const a=Gn(n),c=a?n.code:"INTERNAL_SERVER_ERROR",l=a?n.status:500,f=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:c,message:f,status:l},functionPath:e,ok:!1,...o.fanOut?{fanOut:{failed:0,shards:0,table:o.fanOut.table}}:{},...o.shardKey?{shardKey:o.shardKey}:{}}},ns=e=>{const{exp:t,expiresAtMs:n}=e;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},Lt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,rs=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},Ye=new WeakMap,os=async(e,t,n,o,a=Ye.get(e))=>{const c={"content-type":"application/json"},l=e.headers.get("authorization"),f=e.headers.get("cookie"),m=e.headers.get("x-d1-bookmark"),p=e.headers.get("x-lunora-mutation-id"),E=e.headers.get("x-lunora-client-id"),S=e.headers.get("x-lunora-client-seq");l&&(c.authorization=l),f&&(c.cookie=f),m&&(c["x-d1-bookmark"]=m),p&&(c["x-lunora-mutation-id"]=p),E&&(c["x-lunora-client-id"]=E),S&&(c["x-lunora-client-seq"]=S);const T=ar(e.headers,o);if(T&&(c["x-lunora-client-ip"]=T),!n)return{claims:null,headers:c,identity:null,userId:null};const w=await n(e,t,a);if(!w||typeof w.userId!="string"||w.userId.length===0)return{claims:null,headers:c,identity:null,userId:null};c["x-lunora-userid"]=qn(w.userId);const b=ns(w);b!==void 0&&(c["x-lunora-identity-exp"]=String(b));const{userId:R,...g}=w,O=Object.keys(g).length>0?g:null;return O&&(c["x-lunora-identity"]=Jn(O)),{claims:O,headers:c,identity:w,userId:R}},as=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),ss=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new d("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new d("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new d("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!as.has(n.kind))throw new d("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new d("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new d("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},is=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},ze=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new d("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new d(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},cs=async e=>{const t=await Wt(e);let n;try{n=JSON.parse(t)}catch{throw new d("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new d("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const o=n;if(o.args!==void 0&&Qt(o.args,"RPC"),o.shardKey!==void 0&&typeof o.shardKey!="string")throw new d("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,c=ss(a.fanOut),l=a.args??{};if(c&&a.functionPath.startsWith("__lunora_relation__:")){const f=l.table;if(typeof f=="string"&&f!==c.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=c.table}return{args:l,fanOut:c,functionPath:a.functionPath,shardKey:a.shardKey}},Oe=new Map,ds=5e3,us=4096,ls=async(e,t)=>{const n=Date.now(),o=Oe.get(t);if(o!==void 0&&o.expiresMs>n)return o.relayCount;o!==void 0&&Oe.delete(t);let a=0;try{const c=await we(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(c.ok){const f=(await c.json()).relayCount;typeof f=="number"&&f>0&&(a=Math.floor(f))}}catch{a=0}return Kt(Oe,us),Oe.set(t,{expiresMs:n+ds,relayCount:a}),a},Mt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},ve=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),hs=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],fs=(e,t)=>{for(const n of hs){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},jt=(e,t)=>{const n=new Headers(e.headers),o=[...n.keys()];for(const a of o)a.startsWith("x-lunora-")&&n.delete(a);return fs(n,t),n},ps=async(e,t,n)=>e.length===0||n.length===0?!1:et(await Jt(e,t),n),$t=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[o,...a]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:et(t,a.join(" ").trim())},ms=async(e,t,n)=>{if(!t||t.length===0)return!1;const o=new URL(e.url).searchParams.get("token");return o===null?!1:await qr(t,o)?!0:n?!1:et(t,o)},ws=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return br(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return Le(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return Le(`queue:${e}`,!0);if(typeof n.connectionString=="string")return Le(`hyperdrive:${e}`,!0)},gs=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(Pe))throw new d(`route "${t}" is under the reserved ${Pe} prefix, which the framework owns. App routes registered there shadow the internal endpoint AND its admin gate — pick a path outside the prefix.`,{code:"MISCONFIGURED",status:500})},ys=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new d("`x402Charge` requires `functions`: paid (.x402) procedures are read from the function registry, so without it every paid procedure would dispatch FREE. Build the worker with `defineApp()` (which supplies the registry) or pass `functions` explicitly.",{code:"MISCONFIGURED",status:500})},on=e=>{ys(e);const t=Oa(e.trustInboundTraceContext),n=va(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",a=_r(e.resolveIdentity,e.identity),c=mt(e.shardDO,e.jurisdiction),l=e.schedulerDO===void 0?void 0:mt(e.schedulerDO,e.jurisdiction);let f=!1;const m=r=>{if(r===void 0||e.jurisdiction===void 0)return r;f||(f=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},p=async(r,s,u,i=e.shardRegion?.(s))=>we(r,s,m(i)).fetch(u);let E;const S=()=>e.adminToken??E;let T;const w=()=>e.requireEphemeralWsToken??T??!0;let b;const R=r=>{const s=r??{};if(b??=Mt(r,e.shardDO),T===void 0&&e.requireEphemeralWsToken===void 0){const i=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof i=="string"&&i.length>0&&(T=Wr(i,!0))}if(E!==void 0||e.adminToken!==void 0)return;const u=s.LUNORA_ADMIN_TOKEN;typeof u=="string"&&u.length>0&&(E=u)},g=new WeakSet,O=r=>$t(r,S())||g.has(r),U=async r=>{if(!(e.adminGate===void 0||g.has(r)))try{await Ae(e.adminGate(r,Ye.get(r)))&&g.add(r)}catch{}},H=async(r,s,u,i)=>{const h=await os(r,s,u,e.trustedClientIpHeader,i);return e.functions!==void 0&&(h.headers[lt]=ut),h},D=async(r,s)=>{const u=await H(r,s,e.resolveIdentity);if(g.has(r)&&u.headers.authorization===void 0){const i=S();i!==void 0&&(u.headers.authorization=`Bearer ${i}`)}return u};let F=!1,M=!1;const Z=()=>{M||(M=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},C=r=>{if(!e.allowUnauthenticatedShardAccess){const s=r==="fan-out"?"authorizeFanOut":"authorizeShard";throw new d(`${r} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${r} access (relying solely on per-row RLS).`,{code:r==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}F||(F=!0,console.warn([`[lunora] SECURITY: serving ${r} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},G=async(r,s)=>{if(s.includes(qe)||s.includes(Je))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(e.authorizeShard){if(!await Ae(e.authorizeShard({identity:r,shardKey:s})))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==o&&C("shard")},q=aa({defaultShard:o,forwardToShard:p,isAdmin:O,queryCoordinator:e.queryCoordinator,resolveForwardContext:D,shardDO:c}),J=async(r,s,u,i,h,y)=>{Se(r);const v={"content-type":"application/json",[lt]:ut,"x-lunora-system":"1"};return h?.userId!==void 0&&h.userId.length>0&&(v["x-lunora-userid"]=h.userId),h?.identity!==void 0&&h.identity.length>0&&(v["x-lunora-identity"]=h.identity),i!==void 0&&i.length>0&&(v["x-lunora-mutation-id"]=i),y!==void 0&&y.length>0&&(v.traceparent=y),p(c,u,ve(r,s,v))},ee=async(r,s,u,i,h)=>{const y=u?.[r];if(!y||typeof y.create!="function")throw new d(`${i} targets workflow binding "${r}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(Or(s))throw new d(`${i} params ${vr}`,{code:"BAD_REQUEST",status:400});try{await y.create(h===void 0?{params:s}:{id:h,params:s})}catch(v){if(!Pr(v))throw v}},Q=async(r,s,u)=>{if(r.workflow){await ee(r.workflow,r.args??{},s,`cron job "${r.name}"`);return}if(r.functionPath===void 0)throw new d(`cron job "${r.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const i=await J(r.functionPath,r.args??{},r.shardKey??o,void 0,void 0,u);if(!i.ok)throw new d(`cron job "${r.name}" (${r.functionPath}) failed with shard status ${String(i.status)}`,{code:"CRON_JOB_FAILED",status:500})},K=r=>{if(!O(r))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},j=(r,s,u)=>{if(K(r),s===void 0)throw new d(u.message,{code:u.code,status:400});return s},he=async(r,s,u,i,h)=>{const y=e.cronJobs?.[r];if(!y)return 0;for(const v of y)try{await Q(v,s,h)}catch(k){u.push(i(k))}return y.length},ce=async(r,s)=>{if(K(r),$(r,"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 u=await te(r),i=typeof u.name=="string"?u.name:"";if(i==="")throw new d("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const h=Object.values(e.cronJobs).flat().find(y=>y.name===i);if(!h)throw new d(`no cron job named "${i}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await Q(h,s),Response.json({name:i,ran:!0},{status:200})},ge=async r=>{const s=typeof r.pool=="string"&&r.pool.length>0?r.pool:void 0;if(!s||!l||typeof r.id!="string")return;const u=typeof r.instanceName=="string"&&r.instanceName.length>0?r.instanceName:"default";try{await we(l,u).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:r.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},De=async(r,s)=>{$(r,"POST","Scheduler dispatch");const u=await Wt(r),i=s??{},h=typeof i.LUNORA_SCHEDULER_SECRET=="string"?i.LUNORA_SCHEDULER_SECRET:void 0,y=e.adminToken??(typeof i.LUNORA_ADMIN_TOKEN=="string"?i.LUNORA_ADMIN_TOKEN:void 0),v=r.headers.get("x-lunora-scheduler-signature");let k=!1;if(v&&h?k=await ps(h,u,v):y&&(k=$t(r,y)),!k)throw new d("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let I;try{I=JSON.parse(u)}catch{throw new d("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const _=I??{},A=_.args??{},B=typeof _.id=="string"&&_.id.length>0?_.id:void 0;if(typeof _.workflow=="string"&&_.workflow.length>0)return await ee(_.workflow,A,s,"scheduled workflow",B),await ge(_),Response.json({ok:!0},{status:200});if(typeof _.functionPath!="string"||_.functionPath.length===0)throw new d("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const x=typeof _.shardKey=="string"&&_.shardKey.length>0?_.shardKey:o,W=Ja(r),L=await J(_.functionPath,A,x,B,W,r.headers.get("traceparent")??void 0);return await ge(_),L},Ne=Zr({assertAdmin:K,getReader:()=>e.authAuditReader}),ae=async(r,s)=>{K(r);const u=e.notifySubscriptionStore;if(u===void 0)return Response.json({result:ke({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const i=s?.kind,h=s?.userId,y=s?.limit,v=i==="fcm"||i==="web-push"?i:void 0,k=typeof h=="string"&&h!==""?h:void 0,I=typeof y=="number"&&Number.isFinite(y)?Math.trunc(y):0,_=I>0?Math.min(I,1e3):1e3,B=(await u.list({kind:v,limit:_,userId:k})).filter(x=>v!==void 0&&x.kind!==v?!1:k===void 0||(x.userId??null)===k).map(({keys:x,token:W,...L})=>L);return Response.json({result:ke({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},an=async(r,s)=>{if(!s.fanOut&&!(s.functionPath!==Et&&s.functionPath!==Xa))return await U(r),s.functionPath===Et?Ne(r,s.args??{}):ae(r,s.args)},sn=Ao({applyGlobals:e.applyGlobals,assertAdmin:K,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:o,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:j,resolveForwardContext:D,shardDO:c,streamExportRows:(r,s,u,i)=>Zt(e,r,s,u,i,c),streamingImport:(r,s)=>Io(r,e,s,c),syncGlobals:e.syncGlobals}),Ue=(r,s)=>{const u=r.searchParams.get(s);return u===null||u===""?void 0:u},Ce=r=>{const s=new URL(r.url),u=s.searchParams.get("limit"),i=s.searchParams.get("offset"),h=u===null?void 0:Number.parseInt(u,10),y=i===null?void 0:Number.parseInt(i,10);return{limit:h!==void 0&&Number.isFinite(h)&&h>=0?h:void 0,offset:y!==void 0&&Number.isFinite(y)&&y>=0?y:void 0}},rt=()=>{if(l===void 0)throw new d("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return l},cn=Aa({checkWsAdmin:async r=>O(r)||ms(r,S(),w()),requireSchedulerNamespace:rt,resolveSchedulerStub:r=>(K(r),we(rt(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),dn=xa({assertAdmin:K,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),un=ur({assertAdmin:K,parsePaging:Ce,queryParameter:Ue,readBodyBytes:or,requireAdminOption:j,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),ln=fo({options:e,readJsonBody:te,requireAdminOption:j}),hn=Pa({readJsonBody:te,requireAdminOption:j,vectorIntrospector:e.vectorIntrospector}),fn=Go({kvIntrospector:e.kvIntrospector,readJsonBody:te,requireAdminOption:j}),pn=Er({logArchive:e.logArchive,readJsonBody:te,requireAdminOption:j}),mn=$o({assertAdmin:K,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ce,queryParameter:Ue,requireAdminOption:j}),wn=r=>{const s=[],u=c??r?.SHARD;if(u!==void 0&&s.push(yr("durable-object:default",u,o)),e.health?.disableBindingProbes!==!0)for(const[i,h]of Object.entries(r??{})){const y=ws(i,h);y!==void 0&&s.push(y)}for(const i of e.health?.probes??[])s.push(i);return s},gn=gr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:O,resolveProbes:wn}),yn=r=>{const s=_=>"args"in _?{..._,args:Ve(_.args)}:_,u=e.schedulerInstanceName??"default",i=()=>we(r,u),h=async(_,A)=>{const B=await i().fetch(new Request(`https://scheduler.internal${_}`,A));if(!B.ok)throw new d(`ctx.scheduler: SchedulerDO ${_} failed (${String(B.status)}): ${await B.text()}`,{code:"INTERNAL",status:500});return await B.json()},y=async(_,A)=>await h(_,{body:JSON.stringify(A),headers:{"content-type":"application/json"},method:"POST"}),v=_=>{const A=_;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})},k=async()=>(await kr(async A=>h(A===void 0?"/list":`/list?cursor=${encodeURIComponent(A)}`,{method:"GET"}))).map(A=>s(A)),I=async(_,A,B={})=>{const x=v(A),{id:W}=await y("/schedule",{args:nr("ctx.scheduler",String(x.functionPath??x.workflow),B),scheduledFor:_,...x});return W};return{cancel:async _=>await y("/cancel",{id:_}),get:async _=>{const A=await h(`/get?id=${encodeURIComponent(_)}`,{method:"GET"});return A.record===void 0?null:s(A.record)},list:k,runAfter:async(_,A,B)=>{if(!Number.isFinite(_)||_<0)throw new d("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await I(Date.now()+_,A,B)},runAt:async(_,A,B)=>{if(!Number.isFinite(_))throw new d("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await I(_,A,B)}}},bn=async(r,s,u)=>{const{claims:i,headers:h,userId:y}=await H(r,s,a),v=be(s,r,_=>u.waitUntil?.(_)),k=_=>async(A,B={})=>{const x=A.__lunoraRef;if(typeof x!="string")throw new d("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Se(x);const W=await Ee(r,x,ke(B),_,{...h,"x-lunora-system":"1"},v),L=await W.json();if(L.error)throw new d(L.error.message??"shard RPC failed",{code:L.error.code??"INTERNAL",status:W.status});return Ve(L.result)},I=k(o);return{auth:{getIdentity:()=>Promise.resolve(i),userId:y},cache:u.cache,fetch:globalThis.fetch.bind(globalThis),forShard:_=>{const A=k(_);return{runAction:A,runMutation:A,runQuery:A}},runAction:I,runMutation:I,runQuery:I,...l===void 0?{}:{scheduler:yn(l)},...u.waitUntil===void 0?{}:{waitUntil:u.waitUntil.bind(u)},...e.storage===void 0?{}:{storage:Tr(e.storage(s))}}},_n=async(r,s,u)=>{if(!e.httpRouter)return;const i=await bn(r,s,u);try{return await e.httpRouter.fetch(r,{...s,__lunoraCtx:i},u)}catch(h){return console.error("[lunora] httpRouter (SSR) handler threw:",h),new Response("Internal Server Error",{status:500})}},En=async(r,s,u)=>{if(r.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const i=gt(r,se);if(i)return i;const h=u.searchParams.get("shard")??o,{headers:y,identity:v}=await H(r,s,a);await G(v,h);const k=jt(r,y),I=Mt(s,e.shardDO);if(I!==void 0){k.set("x-lunora-shard-binding",I);const _=await ls(c,h);if(_>0){const A=$r(h,Math.floor(Math.random()*_));return p(c,A,new Request(r,{headers:k}),yt(r))}}return p(c,h,new Request(r,{headers:k}))},Rn=async(r,s,u)=>{const{voiceAgents:i}=e;if(i===void 0)return new Response("Not found",{status:404});if(r.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const h=gt(r,se);if(h)return h;let y;try{y=decodeURIComponent(u.pathname.slice(xt.length))}catch{return new Response("Unknown voice agent",{status:404})}const v=Object.hasOwn(i,y)?i[y]:void 0;if(v===void 0)return new Response("Unknown voice agent",{status:404});const k=u.searchParams.get("threadKey");if(k===null||k.length===0)return new Response("Missing threadKey",{status:400});const{headers:I,identity:_}=await H(r,s,a);if(e.authorizeShard){if(!await Ae(e.authorizeShard({identity:_,shardKey:k})))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else C("shard");const A=jt(r,I);return p(v,k,new Request(r,{headers:A}))},Sn=async(r,s,u)=>{if(e.authorizeFanOut){if(!await Ae(e.authorizeFanOut(u,r.table,s)))throw new d("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new d("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new d("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});C("fan-out")},_e=async(r,s)=>{if(!(!r.fanOut&&r.functionPath.startsWith("__lunora_admin__:"))){if(r.fanOut){await Sn(r.fanOut,r.functionPath,s);return}await G(s,r.shardKey??o)}},An=(r,s,u)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){Z();return}if(e.functions[s]?.kind!=="query"||u.includes(Je)||u.includes(qe))return;const i=yt(r);return i===void 0?void 0:{name:Kr(u,i),region:i}},Tn=async(r,s,u,i,h)=>{const y=An(r,s,i);if(y!==void 0){const v={...h,"x-lunora-replica-read":"1",...b===void 0?{}:{"x-lunora-shard-binding":b}},k=Fr(r.headers.get("x-lunora-min-seq"));k!==void 0&&(v["x-lunora-min-seq"]=String(k));const I=await p(c,y.name,ve(s,u,v),y.region);if(I.status!==421)return I}return p(c,i,ve(s,u,h))},Ee=async(r,s,u,i,h,y)=>{const v=Date.now(),{observability:k,sampling:I}=e,_=We(r),{decision:A,ignoredUpstream:B,trace:x}=fa(r,{...I===void 0?{}:{sampling:I},trustInbound:t(r)});B&&n();const W={...h,"x-lunora-sample-errors":A.keepErrors?"1":"0"};pa(x,W);try{const L=await Tn(r,s,u,i,W);ie(k,{..._,...Bt(x),durationMs:Date.now()-v,functionPath:s,ok:L.ok,shardKey:i,...L.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(L.status)}`,status:L.status}}},y,void 0,{isTraced:x.sampled,keepErrors:A.keepErrors});const ne=new Response(L.body,{headers:L.headers,status:L.status,statusText:L.statusText});return ne.headers.set("x-lunora-shard-key",i),ne}catch(L){throw ie(k,{..._,...Bt(x),...Te(s,Date.now()-v,L,{shardKey:i})},y,void 0,{isTraced:x.sampled,keepErrors:A.keepErrors}),L}},On=r=>{if(r.fanOut&&r.shardKey)throw new d("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(r.fanOut||Se(r.functionPath),r.fanOut&&!e.queryCoordinator)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},vn=async(r,s,u)=>{$(r,"POST","RPC");const i=await cs(r);is(s,i),On(i);const h=await an(r,i);if(h!==void 0)return h;const{headers:y,identity:v}=await H(r,s,a);await _e(i,v);const k=ze(i,e);{const I=Date.now(),{observability:_}=e,A=We(r),B=be(s,r,u&&(L=>u.waitUntil?.(L)));if(i.fanOut){const L=e.queryCoordinator;if(!L)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ne=await L.fanOut(c,{args:i.args??{},fanOut:i.fanOut,functionPath:i.functionPath,headers:y});return ie(_,{durationMs:Date.now()-I,fanOut:{failed:ne.failed,shards:ne.ok+ne.failed,table:i.fanOut.table},functionPath:i.functionPath,...A,ok:!0},B),Response.json(ne,{headers:{"content-type":"application/json"},status:200})}catch(ne){throw ie(_,{...Te(i.functionPath,Date.now()-I,ne,{fanOut:{table:i.fanOut.table}}),...A},B),ne}}const x=i.shardKey??o,W=()=>Ee(r,i.functionPath,i.args??{},x,y,B);return k&&e.x402Charge?e.x402Charge(r,{functionPath:i.functionPath,price:k.price},W,Qe(u)):W()}},kn=async(r,s,u)=>{$(r,"POST","RPC batch");const i=await te(r),{calls:h}=i;if(!Array.isArray(h))throw new d("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:y,identity:v}=await H(r,s,a),k=mo(h,o);for(const z of k.values())for(const V of z)if(e.functions?.[V.functionPath]?.x402)throw new d(`paid (\`.x402\`) function "${V.functionPath}" cannot be called in a batch; dispatch it individually over ${Ct}`,{code:"BAD_REQUEST",status:400});await Promise.all([...k.entries()].flatMap(([z,V])=>V.map(oe=>_e({args:oe.args,functionPath:oe.functionPath,shardKey:z},v))));const{observability:I}=e,_=be(s,r,u&&(z=>u.waitUntil?.(z))),A=We(r),B=[],x=[],W=(z,V,oe,de)=>({body:{error:{code:oe,message:de}},id:z.id,status:V}),L=(z,V,oe,de,fe)=>{for(const Y of z)ie(I,fe(Y),_),B.push(W(Y,V,oe,de))},ne=(z,V,oe,de,fe)=>{for(const Y of z){const pe=de.get(Y.id)??fe,ye=pe<400;ie(I,{durationMs:oe,functionPath:Y.functionPath,...A,ok:ye,shardKey:V,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},_)}};await Promise.all([...k.entries()].map(async([z,V])=>{const oe=new Headers(y);oe.set("content-type","application/json");const de=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:V}),headers:oe,method:"POST"}),fe=Date.now();let Y;try{Y=await p(c,z,de)}catch(X){const He=Date.now()-fe,{body:dt}=Qn(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});L(V,502,dt.code,dt.message,Fn=>({...Te(Fn.functionPath,He,X,{shardKey:z}),...A}));return}const pe=Date.now()-fe,ye=Y.headers.get("x-d1-bookmark");ye&&x.push(ye);let Be;try{Be=await Y.json()}catch{const X=`shard batch returned a non-JSON response (${String(Y.status)})`;L(V,Y.status,"SHARD_ERROR",X,He=>({durationMs:pe,error:{code:"SHARD_ERROR",message:X,status:Y.status},functionPath:He.functionPath,...A,ok:!1,shardKey:z}));return}const xe=Array.isArray(Be.results)?Be.results:[],$n=new Map(xe.map(X=>[X.id,X.status??Y.status])),Kn=new Set(xe.map(X=>X.id));ne(V,z,pe,$n,Y.status),B.push(...xe);for(const X of V)Kn.has(X.id)||B.push(W(X,Y.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const it={"content-type":"application/json"},[ct]=x;return x.length===1&&ct!==void 0&&(it["x-d1-bookmark"]=ct),Response.json({results:B},{headers:it,status:200})},In=async(r,s,u,i={},h={})=>{try{const y=u.__lunoraRef;if(typeof y!="string")throw new d("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Se(y);const{headers:v,identity:k}=await H(r,s,a,h.context),I={args:i,functionPath:y,shardKey:h.shardKey};await _e(I,k);const _=h.shardKey??o,A=be(s,r,h.waitUntil),B=()=>Ee(r,y,i,_,v,A),x=ze(I,e);return x&&e.x402Charge?await e.x402Charge(r,{functionPath:y,price:x.price},B,Qe(h.waitUntil?{waitUntil:h.waitUntil}:h.context)):await B()}catch(y){return ht(y)}},ot=async(r,s,u)=>{const{observability:i}=e,h=Date.now(),y=Ie(16),v=Ie(8),k=Lt(s),I=Ft(y,v,!0);try{const _=await u(I);return ie(i,{durationMs:Date.now()-h,functionPath:r,ok:!0,spanId:v,traceId:y},k),_}catch(_){throw ie(i,{...Te(r,Date.now()-h,_,{}),spanId:v,traceId:y},k),_}finally{pt(i,k)}},at=async(r,s,u,i)=>{R(s);const h=[],y=A=>A instanceof Error?A:new Error(String(A)),v=e.crons?.[r.cron];if(v)try{await v(r,s,u)}catch(A){h.push(y(A))}const k=await he(r.cron,s,h,y,i),I=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===r.cron;if(I)try{await co(e,c,S(),r)}catch(A){h.push(y(A))}if(!v&&k===0&&!I){const A=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${r.cron}") fired but no cron handler is registered for that expression. Registered: ${A.length===0?"(none)":A.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[_]=h;if(h.length===1&&_)throw _;if(h.length>1)throw new AggregateError(h,`scheduled("${r.cron}") had ${String(h.length)} failure(s)`)},Pn=async(r,s,u)=>{if(K(r),r.method!=="POST")throw new d("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const i=await r.json().catch(()=>{}),h=typeof i?.cron=="string"?i.cron:"";if(h==="")throw new d("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await at({cron:h,noRetry:()=>{},scheduledTime:Date.now()},s,u),Response.json({cron:h,ok:!0})},Dn=async(r,s,u)=>{if(K(r),r.method!=="POST")throw new d("queue dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!e.queueHandler)throw new d("no queueHandler configured",{code:"BAD_REQUEST",status:400});const i=await r.json().catch(()=>{}),h=typeof i?.queue=="string"?i.queue:"",v=(Array.isArray(i?.messages)?i.messages:[]).filter(I=>typeof I=="object"&&I!==null&&typeof I.id=="string").map(I=>({body:I.body,id:I.id})),k=await e.queueHandler({messages:v,queue:h},s,u);return Response.json({retry:k?.retry??[]})},Nn=async(r,s)=>{try{const u=r??{},i=e.adminToken??(typeof u.LUNORA_ADMIN_TOKEN=="string"?u.LUNORA_ADMIN_TOKEN:void 0);if(!i||i.length===0)return;await p(c,o,ve(Ya,{outcome:s},{authorization:`Bearer ${i}`,"content-type":"application/json"}))}catch{}},Un=async(r,s,u,i)=>{if(!e.authHandler)return;const h=await e.authHandler(r);if(!h)return;const y=e.authBasePath??Ht;return es(u.pathname,y)&&i.waitUntil?.(Nn(s,h.status>=400?"fail":"ok")),h},Cn=async({args:r,env:s,functionPath:u,request:i,shardKey:h,waitUntil:y})=>{Qt(r,"REST");const v={functionPath:u,...h===void 0?{}:{shardKey:h}},{headers:k,identity:I}=await H(i,s,a);await _e(v,I);const _=h??o,A=be(s,i,y),B=()=>Ee(i,u,r,_,k,A),x=ze(v,e);return x&&e.x402Charge?e.x402Charge(i,{functionPath:u,price:x.price},B,Qe({waitUntil:y})):B()},Bn=rr({functions:e.functions??{},invoke:Cn,readJsonBody:te,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Re=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0;gs(Re);const xn={[Qa]:r=>r.method!=="GET"&&r.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Ma]:(r,s,u)=>En(r,s,u),[Ct]:(r,s,u,i)=>vn(r,s,i),[La]:(r,s,u,i)=>kn(r,s,i),[ja]:(r,s)=>De(r,s),[$a]:(r,s)=>ce(r,s),[Ka]:async r=>{$(r,"POST","ws-token"),K(r);const s=S();if(s===void 0)throw new d("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const u=await Vr(s);return Response.json(u,{headers:{"cache-control":"no-store"}})},...q,...sn,...cn,...dn,...un,...ln,...hn,...fn,...pn,...mn,...gn,...Bn,...Xr({assertAdmin:K,getAuthAdmin:()=>e.authAdmin,parsePaging:Ce,queryParameter:Ue,readJsonBody:te})};let se=wt(e.security),st=!1;const Hn=r=>{st||(st=!0,se=wt(e.security,r??{}))},Ln=async(r,s)=>{Wa(s)&&await U(r)},Mn=(r,s)=>{if(!(s.pathname.startsWith(Pe)||e.authHandler!==void 0&&ts(s.pathname,e.authBasePath??Ht))||r.method!=="POST"&&r.method!=="PUT")return;const i=Number(r.headers.get("content-length")??""),h=Ha[s.pathname]??Gt;if(Number.isFinite(i)&&i>h)throw new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},jn=async(r,s,u)=>{Ye.set(r,u);const i=new URL(r.url);Mn(r,i);const h=await Un(r,s,i,u);if(h)return h;if(Re){const k=`${r.method} ${i.pathname}`,I=Re[k]??Re[i.pathname];if(I)return I(r,s,u)}if(i.pathname===za)return Pn(r,s,u);if(i.pathname===Va)return Dn(r,s,u);const y=xn[i.pathname];if(y)return await Ln(r,i.pathname),y(r,s,i,u);if(e.voiceAgents!==void 0&&i.pathname.startsWith(xt))return Rn(r,s,i);if(i.pathname.startsWith(Pe))return new Response("Not found",{status:404});const v=await _n(r,s,u);return v||new Response("Not found",{status:404})};return{async fetch(r,s,u){e.passThroughOnException&&u.passThroughOnException?.(),Hn(s),R(s);const i=Sr(r,se);if(i)return i;const h=Ar(r,se);if(h)return Me(h,r,se);try{const y=await jn(r,s,u);return Me(y,r,se)}catch(y){return Me(ht(y),r,se)}finally{pt(e.observability,Lt(u))}},async queue(r,s,u){await ot(`queue:${rs(r)}`,u,async i=>{await e.queue?.(r,s,u,{traceparent:i})})},async scheduled(r,s,u){await ot(`cron:${r.cron}`,u,async i=>{await at(r,s,u,i)})},serverQuery:In}},bs=e=>on(e),_s=e=>typeof e=="function"?{fetch:e}:e,Es=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,Rs=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},Qs=(e,t)=>{const n=_s(e),{email:o,queue:a,scheduled:c}=Rs(e),l=m=>{const E={...bs({...m,httpRouter:n})};return c!==void 0&&!Es(m)&&(E.scheduled=async(S,T,w)=>{await c(S,T,w)}),a!==void 0&&m.queue===void 0&&(E.queue=async(S,T,w)=>{await a(S,T,w)}),o!==void 0&&(E.email=async(S,T,w)=>{await o(S,T,w)}),E};if(typeof t!="function")return l(t);const f=t;return{fetch:(m,p,E)=>l(f(p)).fetch(m,p,E),queue:(m,p,E)=>l(f(p)).queue?.(m,p,E)??Promise.resolve(),scheduled:(m,p,E)=>l(f(p)).scheduled(m,p,E),serverQuery:(m,p,E,S,T)=>l(f(p)).serverQuery(m,p,E,S,T),...o===void 0?{}:{email:(m,p,E)=>l(f(p)).email?.(m,p,E)??Promise.resolve()}}},Ss=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new d("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},Ws=(e={})=>(t,n,o)=>on(Ss(e,n)).fetch(t,n,o??Wn),zs=e=>e;export{Et as GET_AUTH_AUDIT_LOG_OP,Wn as NOOP_EXECUTION_CONTEXT,Js as composeIdentityResolvers,bs as composeWorker,Ws as createLunoraHandler,on as createWorker,zs as defineRpcEnvelope,ls as probeRelayCount,Ss as resolveLunoraOptions,Ys as routeIdentityResolvers,Qs as withFrameworkWorker};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.111",
3
+ "version": "1.0.0-alpha.112",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,10 +46,10 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/bindings": "1.0.0-alpha.55",
49
+ "@lunora/bindings": "1.0.0-alpha.56",
50
50
  "@lunora/errors": "1.0.0-alpha.35",
51
- "@lunora/observability": "1.0.0-alpha.69",
52
- "@lunora/platform": "1.0.0-alpha.28"
51
+ "@lunora/observability": "1.0.0-alpha.70",
52
+ "@lunora/platform": "1.0.0-alpha.29"
53
53
  },
54
54
  "peerDependencies": {
55
55
  "@lunora/shard-engine": ">=1.0.0-alpha.24 <2.0.0-0",
@@ -1,6 +0,0 @@
1
- import{isLunoraError as jn,toErrorBody as Kn}from"@lunora/errors";import{e as jt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Fn}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as Gn,f as Qn}from"./base64-Bl1_r2k1.mjs";import{e as Wn,a as zn}from"./identity-header-C4Z5pldl.mjs";import{O as dt,a as ut}from"./origin-paywall-B6eOO67m.mjs";import{o as Ie,b as Kt,p as Vn,m as Jn,d as qn,a as Yn,r as Xn}from"./otlp-resource-JKBCWf6c.mjs";import{e as ke,d as Ve,a as Zn}from"./wire-codec-BLvSm5Mn.mjs";import{d as te,e as le,M as Ft,b as er,f as tr,g as Gt,t as nr,h as Qt}from"./rest-routes-CpbO5QEx.mjs";import{LunoraError as c,toErrorResponse as lt}from"./LunoraError-DksAgIpa.mjs";import{a as j,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as Xe,BACKUP_KEY_PREFIX as Ze,isBackupManifestKey as rr,backupObjectKeyOfManifest as Wt,backupObjectKey as or,backupManifestKey as ar}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as sr,buildStorageAdminRoutes as ir,STORAGE_UPLOAD_MAX_BODY_BYTES as cr,STORAGE_PATH as dr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{b as ur,e as lr,f as ht,g as hr,h as fr}from"./export-tap-CAyZ2TWC.mjs";import{buildHealthRoutes as pr,durableObjectProbe as mr,d1Probe as wr,presenceProbe as Le}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as gr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Qs,routeIdentityResolvers as Ws}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as yr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{r as br,f as ft,a as ie}from"./observability-B1hLjwgx.mjs";import{resolveShard as we,applyJurisdiction as pt}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as mt,handleCorsPreflight as _r,enforceOrigin as Rr,decorateResponse as Me,enforceWebSocketOrigin as wt}from"./decorateResponse-Y2sCM0w1.mjs";const Er=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},zt="__lunoraBranch",Sr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,zt),Ar=`may not contain the reserved workflow branch-marker key ("${zt}")`,Tr=async e=>{const t=[];let n;for(;;){const r=await e(n);if(t.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return t;if(r.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=r.cursor}},et=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,l=a<t.length?t.charCodeAt(a):0;r|=i^l}return r===0},Or=/already[\s_-]?exists/iu,vr=e=>Or.test(e instanceof Error?e.message:String(e)),kr=(e,t,n,r)=>{const a=e.get(t);if(a!==void 0)return a;jt(e,r);const i=n().catch(l=>{throw e.get(t)===i&&e.delete(t),l});return e.set(t,i),i},tt=new TextEncoder,Ir=Array.from({length:32},(e,t)=>t);new RegExp(`[${Ir.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Pr=64,Nr=new Map,Vt=async e=>kr(Nr,e,async()=>crypto.subtle.importKey("raw",tt.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),Pr),Jt=async(e,t)=>{const n=await Vt(e),r=await crypto.subtle.sign("HMAC",n,tt.encode(t));return Gn(new Uint8Array(r))},Dr=async(e,t,n)=>{const r=await Vt(e);return crypto.subtle.verify("HMAC",r,n,tt.encode(t))},Ur=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Ur);const Cr=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Br=-100,xr=15,Hr=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Cr.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>xr?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Br?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},gt=e=>{const t=e.cf;return t===void 0?void 0:Hr(t)},Je="::relay::",Lr=(e,t)=>`${e}${Je}${String(t)}`,qe="::replica::",Mr=(e,t)=>`${e}${qe}${t}`,$r=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},jr=new Set(["1","enabled","on","true","yes"]),Kr=new Set(["0","disabled","false","no","off"]),Fr=(e,t)=>{const n=(e??"").trim().toLowerCase();return jr.has(n)?!0:Kr.has(n)?!1:t},qt="v1",Gr=6e4,Qr=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Gr),r=`${qt}.${String(n)}`,a=await Jt(e,r);return{expiresAtMs:n,token:`${r}.${a}`}},Wr=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const r=t.split(".");if(r.length!==3)return!1;const[a,i,l]=r;if(a!==qt||l.length===0)return!1;const h=Number(i);if(!Number.isFinite(h)||h<=n)return!1;let p;try{p=Qn(l)}catch{return!1}return Dr(e,`${a}.${i}`,p)},P="/_lunora/admin/auth",zr={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},D=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},ue=(e,t)=>{const n=e(t);if(n===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},Yt=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},re=(e,t)=>typeof e[t]=="string"?e[t]:void 0,$e=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},yt=e=>{const t=Yt(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},bt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[r,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[r]=a);return n},Vr={[`${P}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${P}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${P}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${P}/accounts`]:{build:({query:e})=>({userId:ue(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:ue(e,"userId")}),http:"GET",method:"listPasskeys"},[`${P}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${P}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:ue(t,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:ue(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${P}/sign-up-invitations/create`]:{build:({body:e})=>({email:D(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:re(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${P}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:D(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:ue(t,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:ue(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:ue(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:$e(e,"data"),email:D(e,"email"),name:D(e,"name"),password:re(e,"password"),role:Yt(e.role)}),http:"POST",method:"createUser"},[`${P}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:D(e,"userId")}},http:"POST",method:"updateUser"},[`${P}/users/role`]:{build:({body:e})=>({role:yt(e),userId:D(e,"userId")}),http:"POST",method:"setRole"},[`${P}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:D(e,"userId")}),http:"POST",method:"banUser"},[`${P}/users/unban`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"unbanUser"},[`${P}/users/password`]:{build:({body:e})=>({newPassword:D(e,"newPassword"),userId:D(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${P}/users/remove`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${P}/users/impersonate`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"impersonateUser"},[`${P}/sessions/revoke`]:{build:({body:e})=>({sessionId:D(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${P}/sessions/revoke-all`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${P}/accounts/unlink`]:{build:({body:e})=>({accountId:D(e,"accountId"),userId:D(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${P}/two-factor/disable`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${P}/passkeys/delete`]:{build:({body:e})=>({passkeyId:D(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${P}/organizations/members/remove`]:{build:({body:e})=>({memberId:D(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${P}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:D(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${P}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:$e(e,"metadata"),name:D(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:$e(e,"metadata"),name:re(e,"name"),organizationId:D(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${P}/organizations/remove`]:{build:({body:e})=>({organizationId:D(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${P}/organizations/members/add`]:{build:({body:e})=>({organizationId:D(e,"organizationId"),role:re(e,"role"),userId:D(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:D(e,"email"),inviterId:re(e,"inviterId"),organizationId:D(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:D(e,"memberId"),role:yt(e)}),http:"POST",method:"updateMemberRole"},[`${P}/organizations/teams/create`]:{build:({body:e})=>({name:D(e,"name"),organizationId:D(e,"organizationId")}),http:"POST",method:"createTeam"},[`${P}/organizations/teams/update`]:{build:({body:e})=>({name:D(e,"name"),teamId:D(e,"teamId")}),http:"POST",method:"updateTeam"},[`${P}/organizations/teams/remove`]:{build:({body:e})=>({teamId:D(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${P}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:D(e,"teamId"),userId:D(e,"userId")}),http:"POST",method:"addTeamMember"},[`${P}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:D(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${P}/organizations/roles/create`]:{build:({body:e})=>({organizationId:D(e,"organizationId"),permission:bt(e),role:D(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:bt(e),roleId:D(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${P}/organizations/roles/remove`]:{build:({body:e})=>({roleId:D(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Jr=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof c)throw i;const l=i,h=typeof l.code=="string"?l.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:h,status:zr[h]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const l=e.getAuthAdmin();if(l===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=l[i.method];if(h===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const p=new URL(a.url),f={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:T=>e.queryParameter(p,T)},R=i.build(f),S=await t(()=>h(R));return Response.json(i.returns==="void"?{ok:!0}:S,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[a,i]of Object.entries(Vr))r[a]=l=>n(l,i);return r},_t="__lunora_admin__:getAuthAuditLog",Rt=e=>typeof e=="string"&&e!==""?e:void 0,Et=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,qr=e=>async(n,r)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=Rt(r.actorId),l=Rt(r.event),h=Et(r.sinceSeq),p=Et(r.limit),f={...i===void 0?{}:{actorId:i},...l===void 0?{}:{event:l},...h===void 0?{}:{sinceSeq:h},...p===void 0?{}:{limit:p}};let R;try{R=await a.read(f)}catch(T){throw T instanceof c?T:(console.error("[lunora] auth audit read failed:",T),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const S={entries:R};return Response.json({result:ke(S)},{headers:{"content-type":"application/json"},status:200})},Yr=(e,t)=>{const n=[],r=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?r.push(a):n.push(a);return{globalTables:r,shardLocalTables:n}},Xr=async(e,t,n,r,a,i,l)=>{if(n!==void 0&&r.length===0)return;const h=await e.orchestrateExport(i,{args:{tables:r},defaultShardKey:l,headers:t,tables:r});for(const p of h.shards)if(!p.error)for(const f of p.rows??[])a(f)},Xt=async(e,t,n,r,a,i)=>{const l=r??e.listSchemaTables?.();r===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:h,shardLocalTables:p}=Yr(e,l);await Xr(t,n,l,p,a,i,e.defaultShardKey??"__root__");const f=e.exportGlobals;if((r===void 0||h.length>0)&&f)for await(const S of f({tables:h}))a(S)},Zr=new TextEncoder,eo=1e3,Zt=10,to=200,St=8,en="lunoraBackupCron",At=24*1048576,Tt=e=>{const t=e.slice(0,Zt).map(r=>Wt(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},no=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const a of e)n.set(a,r),r+=a.byteLength;return n},nt=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let l=0;l<eo;l+=1){const h=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const p of h.objects)rr(p.key)&&p.customMetadata?.[en]===r&&a.push(p.key);if(!h.truncated||h.cursor===void 0)break;i=h.cursor}return{eligible:a.length,stale:a.toSorted((l,h)=>h.localeCompare(l)).slice(n)}},ro=async(e,t,n,r,a)=>{const{stale:i}=await nt(e,t,n,r),l=new Set(a),h=i.filter(m=>l.has(m)),p=h.slice(0,to),f=i.length-p.length,R=a.length-h.length;if(p.length===0)return{deleted:[],failed:[],ignored:R,remaining:f};const S=[],T=[];for(let m=0;m<p.length;m+=St){const _=await Promise.allSettled(p.slice(m,m+St).map(async E=>(await e.delete(Wt(E)),await e.delete(E),E)));for(const[E,g]of _.entries())g.status==="fulfilled"?S.push(g.value):T.push(p[m+E])}return S.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(S.length)}: ${Tt(S)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${Tt(T)}`),{deleted:S,failed:T,ignored:R,remaining:f}},oo=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=Xe(e.backupPrefix??Ze),r=e.backupCron,{eligible:a,stale:i}=r===void 0?{eligible:0,stale:[]}:await nt(t,n,e.backupRetain,r);return{cron:r,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},ao=async(e,t,n,r)=>{const a=e.backupStore,i=e.queryCoordinator;if(!a)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!i)throw new c("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!n||n.length===0)throw new c("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const l={authorization:`Bearer ${n}`,"content-type":"application/json"},h=e.backupTables;let p=0,f=0,R=[];await Xt(e,i,l,h,U=>{const H=Zr.encode(`${JSON.stringify(U)}
2
- `);if(p+=1,f+=H.byteLength,f>At)throw new c(`scheduled backup reached ${String(f)} bytes of NDJSON, past the ${String(At)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});R.push(H)},t);const T=Xe(e.backupPrefix??Ze),m=new Date(r.scheduledTime).toISOString(),_=or(T,m),E=no(R,f);R=[];const g=sr(await crypto.subtle.digest("SHA-256",E));await a.put(_,E,{httpMetadata:{contentType:"application/x-ndjson"},sha256:g});const O={bytes:f,createdAt:m,cron:r.cron,file:_,id:m,rows:p,scheduledTime:r.scheduledTime,sha256:g,...h?{tables:h.join(",")}:{}};await a.put(ar(_),`${JSON.stringify(O,void 0,2)}
3
- `,{customMetadata:{[en]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:U}=await nt(a,T,e.backupRetain,r.cron);if(U.length>0){const H=U.slice(0,Zt),N=U.length-H.length;console.info(`[lunora] backup retention: ${String(U.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${H.join(", ")}${N>0?` (+${String(N)} more)`:""}`)}}catch(U){console.warn(`[lunora] backup ${_} was written, but the retention report failed:`,U)}},so=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=e.backupCron,a=e.backupRetain;if(r===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return ro(n,Xe(e.backupPrefix??Ze),a,r,t)},io="/_lunora/admin/backup/retention",co="/_lunora/admin/backup/prune",uo=e=>{const{options:t,readJsonBody:n,requireAdminOption:r}=e,a=(h,p)=>{r(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${p} requires a \`backupStore\` on the worker`})},i=async h=>(j(h,"GET","Backup-retention"),a(h,"retention preview"),Response.json(await oo(t),{headers:{"cache-control":"no-store"}})),l=async h=>{j(h,"POST","Backup-prune"),a(h,"prune");const{confirm:p}=await n(h);if(!Array.isArray(p)||p.some(f=>typeof f!="string"))throw new c("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await so(t,p),{headers:{"cache-control":"no-store"}})};return{[co]:l,[io]:i}},Ot=500,lo=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const r=e;if(typeof r.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(r.functionPath.startsWith("__lunora_relation__:")||r.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(r.args!==void 0&&(typeof r.args!="object"||r.args===null||Array.isArray(r.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(r.id!==void 0&&typeof r.id!="number")throw new c("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:r.args===void 0?{}:r.args,clientId:typeof r.clientId=="string"?r.clientId:void 0,clientSeq:typeof r.clientSeq=="number"?r.clientSeq:void 0,functionPath:r.functionPath,id:typeof r.id=="number"?r.id:t,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:n}},ho=(e,t)=>{if(e.length>Ot)throw new c(`RPC batch exceeds the ${String(Ot)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,r=new Set;for(const[a,i]of e.entries()){const{entry:l,shardKey:h}=lo(i,a,t);if(r.has(l.id))throw new c(`batch call id ${String(l.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});r.add(l.id);const p=n.get(h)??[];p.push(l),n.set(h,p)}return n},fo="/_lunora/admin/export",po="/_lunora/admin/import",mo="/_lunora/admin/sync",wo="/_lunora/admin/connector/sync",go="/_lunora/admin/apply",yo="/_lunora/admin/export-tap/run",bo=new TextEncoder,_o=async e=>{const n=await le(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(a)}return{tables:r}},je=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,Ro=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:a,knownTables:i,queryCoordinator:l,assertAdmin:h,requireAdminOption:p,resolveForwardContext:f,shardDO:R,streamExportRows:S,streamingImport:T,syncGlobals:m}=e,_=async(N,K)=>{const M=me(N,["POST"]);if(M)return M;const Z=p(N,l,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),C=await _o(N),{headers:G}=await f(N,K),J=new ReadableStream({async pull(q){const ee=Q=>{q.enqueue(bo.encode(`${JSON.stringify(Q)}
4
- `))};try{await S(Z,G,C.tables,ee),q.close()}catch(Q){q.error(Q)}}});return new Response(J,{headers:{"content-type":"application/x-ndjson"},status:200})},E=async(N,K)=>{const M=me(N,["POST"]);if(M)return M;const Z=p(N,l,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),C=await te(N),G=typeof C.cursors=="object"&&C.cursors!==null?C.cursors:{},J=typeof C.limit=="number"?C.limit:void 0,q=typeof C.globalCursor=="number"?C.globalCursor:0,ee=je(C.tables),{headers:Q}=await f(N,K),F=ee??i(),$=await Z.orchestrateCdcSync(R,{cursors:G,defaultShardKey:n,headers:Q,limit:J,tables:F}),he=m?await m({limit:J,sinceSeq:q}):void 0;return Response.json({global:he,shards:$.shards},{status:200})},g=async(N,K)=>{const M=me(N,["POST"]);if(M)return M;const Z=p(N,l,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),C=await te(N),G=lr(C.cursor),J=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,q=je(C.tables),{headers:ee}=await f(N,K),Q=q??i(),F=await Z.orchestrateCdcSync(R,{cursors:G.s,defaultShardKey:n,headers:ee,limit:J,tables:Q}),$=[],he={...G.s};let ce=!1;for(const ae of F.shards)ce=ht($,ae.changes??[],fr(J))||ce,he[ae.shardKey]=ae.cursor;let ge=G.g;if(m){const ae=await m({limit:J,sinceSeq:G.g});ce=ht($,ae.changes,J)||ce,ge=ae.cursor}const Ne=hr({g:ge,s:he,v:1}),De={changes:$,hasMore:ce,nextCursor:Ne};return Response.json(De,{status:200})},O=async(N,K)=>{const M=me(N,["POST"]);if(M)return M;const Z=p(N,l,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),C=await te(N),J=(Array.isArray(C.batches)?C.batches:[]).map($=>$).filter($=>$!==null&&typeof $=="object"&&typeof $.shardKey=="string"&&Array.isArray($.changes)),q=Array.isArray(C.globalChanges)?C.globalChanges:[],{headers:ee}=await f(N,K),Q=await Z.orchestrateApplyCdc(R,{batches:J,headers:ee}),F=q.length>0&&t?await t({changes:q}):0;return Response.json({applied:Q.applied+F,failed:Q.failed,ok:Q.ok},{status:200})},U=async(N,K)=>{const M=me(N,["POST"]);if(M)return M;h(N);const{headers:Z}=await f(N,K),C=await T(N,Z);return Response.json(C,{headers:{"content-type":"application/json"},status:C.failed.length>0?207:200})},H=async(N,K)=>{const M=me(N,["POST"]);if(M)return M;const Z=p(N,l,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(a===void 0||Object.keys(a).length===0||r===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const C=await te(N),G=typeof C.sink=="string"?C.sink:void 0,J=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,q=je(C.tables);if(G===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const ee=a[G];if(ee===void 0)throw new c(`Export-tap sink "${G}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:Q}=await f(N,K),F=q??i(),$=await ur({coordinator:Z,cursorStore:r,defaultShardKey:n,headers:Q,limit:J,shardDO:R,sink:ee,tables:F});return Response.json($,{headers:{"content-type":"application/json"},status:200})};return{[go]:O,[wo]:g,[fo]:_,[yo]:H,[po]:U,[mo]:E}},Eo=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const r=n;return typeof r.table!="string"||r.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!r.doc||typeof r.doc!="object"||Array.isArray(r.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:r.table},ok:!1}:{doc:r.doc,ok:!0,table:r.table}},So=(e,t,n,r,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:r}},Ao=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],a=[],i=new Map;let l=0,h=0;const p=e.body.getReader(),f=new TextDecoder;let R="",S=0;const T=m=>{h+=1;const _=m.trim();if(_.length===0)return;l+=1;const E=Eo(_,h);if(!E.ok){r.push(E.error);return}const{doc:g,table:O}=E,U=t.resolveTableSharding?.(O);if(U?.mode.kind==="global"){a.push({doc:g,line:h,table:O});return}const H=So(g,O,U,n,h);if(!H.ok){r.push(H.error);return}const N=i.get(H.shardKey);N?N.rows.push({doc:g,table:O}):i.set(H.shardKey,{rows:[{doc:g,table:O}],shardKey:H.shardKey,startLine:h})};for(;;){const{done:m,value:_}=await p.read();if(m)break;if(_&&(S+=_.byteLength,S>Ft))throw await p.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});R+=f.decode(_,{stream:!0});let E=R.indexOf(`
5
- `);for(;E!==-1;){const g=R.slice(0,E);R=R.slice(E+1),T(g),E=R.indexOf(`
6
- `)}}return R.length>0&&T(R),{errors:r,globalRows:a,perShard:i,received:l}},To=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),vt=(e,t)=>{for(const[n,r]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+r;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},Oo=async(e,t,n,r)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:l,perShard:h,received:p}=await Ao(e,t,a),f={conflicts:0,errors:i,failed:[],inserted:{}},R=[];if(t.resolveTableSharding===void 0&&h.size>0&&R.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const S=t.queryCoordinator;if(!S)throw new c("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const T=await S.orchestrateImport(r,{batches:[...h.values()],headers:n});vt(f,T),f.failed.push(...To(T.shards))}if(l.length>0)if(t.importGlobals){const S=l[0]?.line??1,T=await t.importGlobals({rows:l,startLine:S});vt(f,T)}else for(const S of l)f.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:S.line,message:`row targets global table "${S.table}" but no \`importGlobals\` is configured`,table:S.table});return{conflicts:f.conflicts,errors:f.errors,failed:f.failed,inserted:f.inserted,received:p,...R.length>0?{warnings:R}:{}}},Ke=e=>typeof e=="object"&&e!==null?e:{},Fe=e=>typeof e.kind=="string"?e.kind:"unknown",vo=(e,t)=>{let n=Ke(t),r=!1;Fe(n)==="optional"&&(r=!0,n=Ke(n._meta?.inner));const a=Fe(n),i=n._meta??{},l={kind:a,name:e,optional:r};if(a==="id"&&typeof i.tableName=="string"&&(l.table=i.tableName),a==="array"){const h=Fe(Ke(i.inner));h!=="unknown"&&(l.element=h)}return l},ko=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>vo(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),Io="/_lunora/admin/functions",Po="/_lunora/admin/cron-jobs",No="/_lunora/admin/openapi",Do="/_lunora/admin/openrpc",Uo="/_lunora/admin/global/tables",Co="/_lunora/admin/global/table",Bo="/_lunora/admin/global/facet",kt=e=>{if(e===void 0||e==="")return;let t;try{t=Ve(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:a,value:i}=r;return[{column:a,value:i}]});return n.length===0?void 0:n},xo=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:{}}),Ho=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"}),Lo=e=>{const{assertAdmin:t,options:n,parsePaging:r,queryParameter:a,requireAdminOption:i}=e,l=m=>{j(m,"GET","Functions");const _=i(m,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),E=Object.entries(_).flatMap(([g,O])=>O.visibility==="internal"||O.kind==="stream"?[]:[{args:ko(O.args),kind:O.kind,path:g}]).toSorted((g,O)=>g.path.localeCompare(O.path));return Response.json({functions:E},{headers:{"content-type":"application/json"},status:200})},h=m=>{j(m,"GET","Cron-jobs");const _=i(m,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),E=Object.entries(_).flatMap(([g,O])=>O.map(U=>({args:U.args,cron:g,functionPath:U.functionPath,name:U.name,shardKey:U.shardKey,workflow:U.workflow}))).toSorted((g,O)=>g.name.localeCompare(O.name));return Response.json({jobs:E},{headers:{"content-type":"application/json"},status:200})},p=m=>(j(m,"GET","OpenAPI"),t(m),Response.json(n.openApiSpec??xo,{headers:{"content-type":"application/json"},status:200})),f=m=>(j(m,"GET","OpenRPC"),t(m),Response.json(n.openRpcSpec??Ho,{headers:{"content-type":"application/json"},status:200})),R=async m=>{j(m,"GET","Global-tables");const _=i(m,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await _.listTables(),{headers:{"content-type":"application/json"},status:200})},S=async m=>{j(m,"GET","Global-table");const _=i(m,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),E=new URL(m.url),g=a(E,"table");if(g===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const O=await _.readTablePage({...r(m),filters:kt(a(E,"filters")),table:g});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},T=async m=>{j(m,"GET","Global-facet");const _=i(m,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),E=new URL(m.url),g=a(E,"table"),O=a(E,"column");if(g===void 0||O===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const U=a(E,"limit"),H=U===void 0?void 0:Number(U),N=await _.facetColumn({column:O,filters:kt(a(E,"filters")),limit:H!==void 0&&Number.isFinite(H)?H:void 0,table:g});return Response.json(N,{headers:{"content-type":"application/json"},status:200})};return{[Po]:h,[Io]:l,[Bo]:T,[Co]:S,[Uo]:R,[No]:p,[Do]:f}},Mo="/_lunora/admin/kv/namespaces",$o="/_lunora/admin/kv/keys",tn="/_lunora/admin/kv/value",nn=32*1048576,It=60,jo=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=_=>n(_,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=_=>Response.json(_,{headers:{"content-type":"application/json"},status:200}),i=(_,E)=>{const g=new URL(_.url),O=g.searchParams.get("namespace")??"",U=g.searchParams.get("key")??"";if(O==="")throw new c(`KV-value ${E} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(U==="")throw new c(`KV-value ${E} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:U,namespace:O}},l=async(_,E)=>{if(!(await _.listNamespaces()).some(O=>O.binding===E))throw new c(`Unknown KV namespace binding \`${E}\``,{code:"NOT_FOUND",status:404})},h=async _=>(j(_,"GET","KV-namespaces"),a({namespaces:await r(_).listNamespaces()})),p=async _=>{j(_,"GET","KV-keys");const E=r(_),g=new URL(_.url),O=g.searchParams.get("namespace")??"";if(O==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const U=g.searchParams.get("prefix")??void 0,H=g.searchParams.get("cursor")??void 0,N=g.searchParams.get("limit"),K=N===null?void 0:Number.parseInt(N,10);if(K!==void 0&&(!Number.isInteger(K)||K<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const M=K===void 0?void 0:Math.min(K,1e3);return await l(E,O),a(await E.listKeys({cursor:H,limit:M,namespace:O,prefix:U}))},T={DELETE:async _=>{const E=r(_),g=i(_,"DELETE");return await l(E,g.namespace),await E.deleteKey(g),a({deleted:!0})},GET:async _=>{const E=r(_),g=i(_,"GET");return await l(E,g.namespace),a(await E.getValue(g))},PUT:async _=>{const E=r(_),g=await t(_,nn);if(typeof g.namespace!="string"||g.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof g.key!="string"||g.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof g.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(g.expirationTtl!==void 0&&(typeof g.expirationTtl!="number"||!Number.isInteger(g.expirationTtl)||g.expirationTtl<It))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const O=Math.floor(Date.now()/1e3)+It;if(g.expiration!==void 0&&(typeof g.expiration!="number"||!Number.isInteger(g.expiration)||g.expiration<O))throw new c("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await l(E,g.namespace),await E.putValue({expiration:g.expiration,expirationTtl:g.expirationTtl,key:g.key,metadata:g.metadata,namespace:g.namespace,value:g.value}),a({ok:!0})}},m=_=>{const E=T[_.method];if(!E)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return E(_)};return{[Mo]:h,[$o]:p,[tn]:m}},Ko="/_lunora/migrate",Fo="/_lunora/admin/pitr",Go="/_lunora/admin/rank",Qo="/_lunora/admin/rankpage",Wo="/_lunora/admin/shard-traffic",zo=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Vo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Jo=async e=>{const n=await le(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!zo.has(n.functionPath))throw new c("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},qo=async e=>{const n=await le(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new c("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new c("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new c("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new c("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},Yo=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new c('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Xo=e=>{if(typeof e.table!="string"||e.table.length===0)throw new c("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new c("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new c("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new c("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new c("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Zo=async e=>{const n=await le(e,"Rank page")??{};Xo(n);const r=Yo(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:r,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},ea=async e=>{const n=await le(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},ta=async e=>{const n=await te(e);if(typeof n.functionPath!="string"||!Vo.has(n.functionPath))throw new c("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new c("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},na=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:r,queryCoordinator:a,resolveForwardContext:i,shardDO:l}=e,h=(m,_)=>{if(m.method!=="POST")throw new c(`${_} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(m))throw new c("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new c(`${_} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},p=async(m,_)=>{const E=h(m,"Migration"),g=await Jo(m),{headers:O}=await i(m,_),U=await E.orchestrateMigration(l,{args:g.args,defaultShardKey:t,functionPath:g.functionPath,headers:O,table:g.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},f=async(m,_)=>{const E=h(m,"Rank"),g=await qo(m),{headers:O}=await i(m,_),U=await E.orchestrateRank(l,{headers:O,index:g.index,partitionKey:g.partitionKey,rowId:g.rowId,sortValues:g.sortValues,table:g.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},R=async(m,_)=>{const E=h(m,"Rank page"),g=await Zo(m),{headers:O}=await i(m,_),U=await E.orchestrateRankPage(l,{...g,headers:O});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},S=async(m,_)=>{const E=h(m,"Shard-traffic"),g=await ea(m),{headers:O}=await i(m,_),U=await E.orchestrateShardTraffic(l,{headers:O,table:g.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},T=async(m,_)=>{if(j(m,"POST","PITR"),!r(m))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const E=await ta(m),{headers:g}=await i(m,_),O=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:E.args,functionPath:E.functionPath}),headers:g,method:"POST"});return n(l,E.shardKey??t,O)};return{[Ko]:p,[Fo]:T,[Go]:f,[Qo]:R,[Wo]:S}},ra=1,oa=0,aa=32,sa=512,ia=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,ca=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>sa)return;const n=t.split(",");if(!(n.length>aa)){for(const r of n)if(!ia.test(r.trim()))return;return t}},da=e=>{const t=Vn(e.headers.get("traceparent"));if(t===void 0)return;const n=ca(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},ua=(e,t={})=>{const n=da(e),r=t.trustInbound===!0?n:void 0,a=Ie(8),i=r?.traceId??Ie(16),l=br(t.sampling,r===void 0?a:i),h=l.isTraced&&(r===void 0||r.sampled);return{decision:l,ignoredUpstream:n!==void 0&&r===void 0,trace:{sampled:h,spanId:a,traceFlags:h?ra:oa,traceId:i,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState}}}},la=(e,t)=>{t.traceparent=Kt(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},ha=(e,t)=>{let n;return()=>{if(n===void 0){const r=Xn(e),a=t===void 0?void 0:t.cf;n=Jn(Yn(r),qn(r,a))}return n}},fa="/_lunora/admin/scheduled",pa="/_lunora/admin/scheduled/status",ma="/_lunora/admin/scheduled/ws",wa="/_lunora/admin/scheduled/cancel",ga="/_lunora/admin/scheduled/dead",ya="/_lunora/admin/scheduled/dead/retry",ba="/_lunora/admin/scheduled/dead/cancel",_a="/_lunora/admin/scheduled/pool/release",Ra=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:r,schedulerInstanceName:a}=e,i=(f,R)=>S=>{if(S.method!=="GET")throw new c(`${R} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(S.url).searchParams.get("cursor"),m=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return r(S).fetch(new Request(`https://scheduler.internal${f}${m}`,{method:"GET"}))},l=(f,R,S=R)=>async T=>{if(T.method!=="POST")throw new c(`${S} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const m=r(T),_=await le(T,R);if(typeof _?.id!="string"||_.id==="")throw new c(`${R} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return m.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:_.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async f=>{if(f.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const R=r(f),S=await le(f,"Scheduled pool-release");if(typeof S?.pool!="string"||S.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const T=typeof S.id=="string"&&S.id!==""?S.id:void 0;return R.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(T===void 0?{pool:S.pool}:{id:T,pool:S.pool}),headers:{"content-type":"application/json"},method:"POST"}))},p=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(f))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const R=n();return we(R,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[wa]:l("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[ba]:l("/dead/cancel","Scheduled dead-letter action"),[ga]:i("/dead","Scheduled dead-letter"),[ya]:l("/dead/retry","Scheduled dead-letter action"),[fa]:i("/list","Scheduled-list"),[_a]:h,[pa]:i("/status","Scheduler-status"),[ma]:p}},Ea=(e,...t)=>{let n=e.cf;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return typeof n=="string"?n:void 0},Pt={mtls:e=>Ea(e,"tlsClientAuth","certVerified")==="SUCCESS"},Sa=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(Pt,e)?Pt[e]:void 0)??(()=>!1),Aa=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},Ta="/_lunora/admin/vector/indexes",Oa="/_lunora/admin/vector/query",va=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=async i=>{j(i,"GET","Vector-indexes");const l=n(i,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 i=>{j(i,"POST","Vector-query");const l=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(l.queryIndex===void 0)throw new c("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const p=await t(i);if(typeof p.name!="string"||p.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof p.text!="string"||p.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(p.topK!==void 0&&(typeof p.topK!="number"||!Number.isInteger(p.topK)||p.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const f=await l.queryIndex({name:p.name,text:p.text,topK:p.topK});return Response.json(f,{headers:{"content-type":"application/json"},status:200})};return{[Ta]:r,[Oa]:a}},ka="/_lunora/admin/workflows/instances",Ia="/_lunora/admin/workflows/instance",Pa="/_lunora/admin/workflows/status",Na={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Da=e=>e!==null&&Object.hasOwn(Na,e)?e:void 0,Nt=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const r=Number(n);return Number.isInteger(r)&&r>0?r:void 0},Ge=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new c(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},Dt=()=>{throw new c("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Ua=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,r=async(l,h,p)=>{j(l,"GET","Workflows instances"),t(l);const f=n(h);if(!f)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const R=Ge(p,"name"),S=Da(p.searchParams.get("status"));return Response.json(await f.listInstances({page:Nt(p,"page"),perPage:Nt(p,"perPage"),status:S,workflowName:R}))},a=async(l,h,p)=>{j(l,"GET","Workflows instance"),t(l);const f=n(h);return f?Response.json(await f.getInstance({instanceId:Ge(p,"id"),workflowName:Ge(p,"name")})):Dt()},i=async(l,h)=>{j(l,"POST","Workflows status"),t(l);const p=n(h);if(!p)return Dt();const f=await l.json().catch(()=>{});if(typeof f?.name!="string"||f.name===""||typeof f.id!="string"||f.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:R}=f;if(R!=="pause"&&R!=="resume"&&R!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await p.setInstanceStatus({action:R,instanceId:f.id,workflowName:f.name}))};return{[Ia]:a,[ka]:r,[Pa]:i}},Ca={[tn]:nn,[dr]:cr},Ut="/_lunora/rpc",Ba="/_lunora/rpc-batch",xa="/_lunora/ws",be=(e,t,n)=>({resourceAttributes:ha(e,t),...n===void 0?{}:{waitUntil:n}}),Qe=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Ct=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),We=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let r;try{r=new URL(e.url)}catch{return{method:t,userAgent:n}}const a=r.port===""?void 0:Number(r.port);return{host:r.hostname,method:t,path:r.pathname,port:Number.isNaN(a)?void 0:a,scheme:r.protocol.replace(":",""),userAgent:n}},Bt="/_lunora/voice/",Ha="/_lunora/scheduler/dispatch",La="/_lunora/admin/cron-jobs/run",Ma="/_lunora/admin/ws-token",$a="/_lunora/admin/",Pe="/_lunora/",ja="/_lunora/migrate",Ka="/_lunora/status",Fa=e=>e.startsWith($a)||e===ja,Ga="__lunora_relation__:",Se=e=>{if(e.startsWith(Ga))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Ae=async e=>await e===!0,Qa=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},xt="/api/auth",Wa="__lunora_admin__:recordAuthEvent",za="__lunora_admin__:listPushSubscriptions",Va=["/sign-in","/sign-up","/callback"],Ja=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const r=e.slice(n.length);return Va.some(a=>r===a||r.startsWith(`${a}/`))},qa=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},Te=(e,t,n,r)=>{const a=jn(n),i=a?n.code:"INTERNAL_SERVER_ERROR",l=a?n.status:500,h=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:h,status:l},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},Ya=e=>{const{exp:t,expiresAtMs:n}=e;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},Ht=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Xa=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},Ye=new WeakMap,Za=async(e,t,n,r,a=Ye.get(e))=>{const i={"content-type":"application/json"},l=e.headers.get("authorization"),h=e.headers.get("cookie"),p=e.headers.get("x-d1-bookmark"),f=e.headers.get("x-lunora-mutation-id"),R=e.headers.get("x-lunora-client-id"),S=e.headers.get("x-lunora-client-seq");l&&(i.authorization=l),h&&(i.cookie=h),p&&(i["x-d1-bookmark"]=p),f&&(i["x-lunora-mutation-id"]=f),R&&(i["x-lunora-client-id"]=R),S&&(i["x-lunora-client-seq"]=S);const T=nr(e.headers,r);if(T&&(i["x-lunora-client-ip"]=T),!n)return{claims:null,headers:i,identity:null,userId:null};const m=await n(e,t,a);if(!m||typeof m.userId!="string"||m.userId.length===0)return{claims:null,headers:i,identity:null,userId:null};i["x-lunora-userid"]=Wn(m.userId);const _=Ya(m);_!==void 0&&(i["x-lunora-identity-exp"]=String(_));const{userId:E,...g}=m,O=Object.keys(g).length>0?g:null;return O&&(i["x-lunora-identity"]=zn(O)),{claims:O,headers:i,identity:m,userId:E}},es=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),ts=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new c("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new c("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new c("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!es.has(n.kind))throw new c("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new c("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new c("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},ns=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},ze=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new c("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new c(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},rs=async e=>{const t=await Qt(e);let n;try{n=JSON.parse(t)}catch{throw new c("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new c("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const r=n;if(r.args!==void 0&&Gt(r.args,"RPC"),r.shardKey!==void 0&&typeof r.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,i=ts(a.fanOut),l=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const h=l.table;if(typeof h=="string"&&h!==i.table)throw new c("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});l.table=i.table}return{args:l,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},Oe=new Map,os=5e3,as=4096,ss=async(e,t)=>{const n=Date.now(),r=Oe.get(t);if(r!==void 0&&r.expiresMs>n)return r.relayCount;r!==void 0&&Oe.delete(t);let a=0;try{const i=await we(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const h=(await i.json()).relayCount;typeof h=="number"&&h>0&&(a=Math.floor(h))}}catch{a=0}return jt(Oe,as),Oe.set(t,{expiresMs:n+os,relayCount:a}),a},Lt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},ve=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),is=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],cs=(e,t)=>{for(const n of is){e.delete(n);const r=t[n];r!==void 0&&e.set(n,r)}},Mt=(e,t)=>{const n=new Headers(e.headers),r=[...n.keys()];for(const a of r)a.startsWith("x-lunora-")&&n.delete(a);return cs(n,t),n},ds=async(e,t,n)=>e.length===0||n.length===0?!1:et(await Jt(e,t),n),$t=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...a]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:et(t,a.join(" ").trim())},us=async(e,t,n)=>{if(!t||t.length===0)return!1;const r=new URL(e.url).searchParams.get("token");return r===null?!1:await Wr(t,r)?!0:n?!1:et(t,r)},ls=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return wr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return Le(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return Le(`queue:${e}`,!0);if(typeof n.connectionString=="string")return Le(`hyperdrive:${e}`,!0)},hs=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(Pe))throw new c(`route "${t}" is under the reserved ${Pe} prefix, which the framework owns. App routes registered there shadow the internal endpoint AND its admin gate — pick a path outside the prefix.`,{code:"MISCONFIGURED",status:500})},fs=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new c("`x402Charge` requires `functions`: paid (.x402) procedures are read from the function registry, so without it every paid procedure would dispatch FREE. Build the worker with `defineApp()` (which supplies the registry) or pass `functions` explicitly.",{code:"MISCONFIGURED",status:500})},rn=e=>{fs(e);const t=Sa(e.trustInboundTraceContext),n=Aa(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",a=gr(e.resolveIdentity,e.identity),i=pt(e.shardDO,e.jurisdiction),l=e.schedulerDO===void 0?void 0:pt(e.schedulerDO,e.jurisdiction);let h=!1;const p=o=>{if(o===void 0||e.jurisdiction===void 0)return o;h||(h=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},f=async(o,s,u,d=e.shardRegion?.(s))=>we(o,s,p(d)).fetch(u);let R;const S=()=>e.adminToken??R;let T;const m=()=>e.requireEphemeralWsToken??T??!0;let _;const E=o=>{const s=o??{};if(_??=Lt(o,e.shardDO),T===void 0&&e.requireEphemeralWsToken===void 0){const d=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof d=="string"&&d.length>0&&(T=Fr(d,!0))}if(R!==void 0||e.adminToken!==void 0)return;const u=s.LUNORA_ADMIN_TOKEN;typeof u=="string"&&u.length>0&&(R=u)},g=new WeakSet,O=o=>$t(o,S())||g.has(o),U=async o=>{if(!(e.adminGate===void 0||g.has(o)))try{await Ae(e.adminGate(o,Ye.get(o)))&&g.add(o)}catch{}},H=async(o,s,u,d)=>{const w=await Za(o,s,u,e.trustedClientIpHeader,d);return e.functions!==void 0&&(w.headers[ut]=dt),w},N=async(o,s)=>{const u=await H(o,s,e.resolveIdentity);if(g.has(o)&&u.headers.authorization===void 0){const d=S();d!==void 0&&(u.headers.authorization=`Bearer ${d}`)}return u};let K=!1,M=!1;const Z=()=>{M||(M=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},C=o=>{if(!e.allowUnauthenticatedShardAccess){const s=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${o} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}K||(K=!0,console.warn([`[lunora] SECURITY: serving ${o} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},G=async(o,s)=>{if(s.includes(Je)||s.includes(qe))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(e.authorizeShard){if(!await Ae(e.authorizeShard({identity:o,shardKey:s})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==r&&C("shard")},J=na({defaultShard:r,forwardToShard:f,isAdmin:O,queryCoordinator:e.queryCoordinator,resolveForwardContext:N,shardDO:i}),q=async(o,s,u,d,w,b)=>{Se(o);const v={"content-type":"application/json",[ut]:dt,"x-lunora-system":"1"};return w?.userId!==void 0&&w.userId.length>0&&(v["x-lunora-userid"]=w.userId),w?.identity!==void 0&&w.identity.length>0&&(v["x-lunora-identity"]=w.identity),d!==void 0&&d.length>0&&(v["x-lunora-mutation-id"]=d),b!==void 0&&b.length>0&&(v.traceparent=b),f(i,u,ve(o,s,v))},ee=async(o,s,u,d,w)=>{const b=u?.[o];if(!b||typeof b.create!="function")throw new c(`${d} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(Sr(s))throw new c(`${d} params ${Ar}`,{code:"BAD_REQUEST",status:400});try{await b.create(w===void 0?{params:s}:{id:w,params:s})}catch(v){if(!vr(v))throw v}},Q=async(o,s,u)=>{if(o.workflow){await ee(o.workflow,o.args??{},s,`cron job "${o.name}"`);return}if(o.functionPath===void 0)throw new c(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const d=await q(o.functionPath,o.args??{},o.shardKey??r,void 0,void 0,u);if(!d.ok)throw new c(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(d.status)}`,{code:"CRON_JOB_FAILED",status:500})},F=o=>{if(!O(o))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},$=(o,s,u)=>{if(F(o),s===void 0)throw new c(u.message,{code:u.code,status:400});return s},he=async(o,s,u,d,w)=>{const b=e.cronJobs?.[o];if(!b)return 0;for(const v of b)try{await Q(v,s,w)}catch(k){u.push(d(k))}return b.length},ce=async(o,s)=>{if(F(o),j(o,"POST","cron-jobs run"),!e.cronJobs)throw new c("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const u=await te(o),d=typeof u.name=="string"?u.name:"";if(d==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const w=Object.values(e.cronJobs).flat().find(b=>b.name===d);if(!w)throw new c(`no cron job named "${d}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await Q(w,s),Response.json({name:d,ran:!0},{status:200})},ge=async o=>{const s=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!s||!l||typeof o.id!="string")return;const u=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await we(l,u).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Ne=async(o,s)=>{j(o,"POST","Scheduler dispatch");const u=await Qt(o),d=s??{},w=typeof d.LUNORA_SCHEDULER_SECRET=="string"?d.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof d.LUNORA_ADMIN_TOKEN=="string"?d.LUNORA_ADMIN_TOKEN:void 0),v=o.headers.get("x-lunora-scheduler-signature");let k=!1;if(v&&w?k=await ds(w,u,v):b&&(k=$t(o,b)),!k)throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let I;try{I=JSON.parse(u)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const y=I??{},A=y.args??{},B=typeof y.id=="string"&&y.id.length>0?y.id:void 0;if(typeof y.workflow=="string"&&y.workflow.length>0)return await ee(y.workflow,A,s,"scheduled workflow",B),await ge(y),Response.json({ok:!0},{status:200});if(typeof y.functionPath!="string"||y.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const x=typeof y.shardKey=="string"&&y.shardKey.length>0?y.shardKey:r,W=Qa(o),L=await q(y.functionPath,A,x,B,W,o.headers.get("traceparent")??void 0);return await ge(y),L},De=qr({assertAdmin:F,getReader:()=>e.authAuditReader}),ae=async(o,s)=>{F(o);const u=e.notifySubscriptionStore;if(u===void 0)return Response.json({result:ke({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const d=s?.kind,w=s?.userId,b=s?.limit,v=d==="fcm"||d==="web-push"?d:void 0,k=typeof w=="string"&&w!==""?w:void 0,I=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,y=I>0?Math.min(I,1e3):1e3,B=(await u.list({kind:v,limit:y,userId:k})).filter(x=>v!==void 0&&x.kind!==v?!1:k===void 0||(x.userId??null)===k).map(({keys:x,token:W,...L})=>L);return Response.json({result:ke({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},on=async(o,s)=>{if(!s.fanOut&&!(s.functionPath!==_t&&s.functionPath!==za))return await U(o),s.functionPath===_t?De(o,s.args??{}):ae(o,s.args)},an=Ro({applyGlobals:e.applyGlobals,assertAdmin:F,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:r,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:$,resolveForwardContext:N,shardDO:i,streamExportRows:(o,s,u,d)=>Xt(e,o,s,u,d,i),streamingImport:(o,s)=>Oo(o,e,s,i),syncGlobals:e.syncGlobals}),Ue=(o,s)=>{const u=o.searchParams.get(s);return u===null||u===""?void 0:u},Ce=o=>{const s=new URL(o.url),u=s.searchParams.get("limit"),d=s.searchParams.get("offset"),w=u===null?void 0:Number.parseInt(u,10),b=d===null?void 0:Number.parseInt(d,10);return{limit:w!==void 0&&Number.isFinite(w)&&w>=0?w:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},rt=()=>{if(l===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return l},sn=Ra({checkWsAdmin:async o=>O(o)||us(o,S(),m()),requireSchedulerNamespace:rt,resolveSchedulerStub:o=>(F(o),we(rt(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),cn=Ua({assertAdmin:F,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),dn=ir({assertAdmin:F,parsePaging:Ce,queryParameter:Ue,readBodyBytes:tr,requireAdminOption:$,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),un=uo({options:e,readJsonBody:te,requireAdminOption:$}),ln=va({readJsonBody:te,requireAdminOption:$,vectorIntrospector:e.vectorIntrospector}),hn=jo({kvIntrospector:e.kvIntrospector,readJsonBody:te,requireAdminOption:$}),fn=yr({logArchive:e.logArchive,readJsonBody:te,requireAdminOption:$}),pn=Lo({assertAdmin:F,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ce,queryParameter:Ue,requireAdminOption:$}),mn=o=>{const s=[],u=i??o?.SHARD;if(u!==void 0&&s.push(mr("durable-object:default",u,r)),e.health?.disableBindingProbes!==!0)for(const[d,w]of Object.entries(o??{})){const b=ls(d,w);b!==void 0&&s.push(b)}for(const d of e.health?.probes??[])s.push(d);return s},wn=pr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:O,resolveProbes:mn}),gn=o=>{const s=y=>"args"in y?{...y,args:Ve(y.args)}:y,u=e.schedulerInstanceName??"default",d=()=>we(o,u),w=async(y,A)=>{const B=await d().fetch(new Request(`https://scheduler.internal${y}`,A));if(!B.ok)throw new c(`ctx.scheduler: SchedulerDO ${y} failed (${String(B.status)}): ${await B.text()}`,{code:"INTERNAL",status:500});return await B.json()},b=async(y,A)=>await w(y,{body:JSON.stringify(A),headers:{"content-type":"application/json"},method:"POST"}),v=y=>{const A=y;if(A==null)throw new c("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof A.binding=="string"&&A.binding.length>0)return{workflow:A.binding};if(typeof A.__lunoraRef=="string")return{functionPath:A.__lunoraRef};throw new c("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},k=async()=>(await Tr(async A=>w(A===void 0?"/list":`/list?cursor=${encodeURIComponent(A)}`,{method:"GET"}))).map(A=>s(A)),I=async(y,A,B={})=>{const x=v(A),{id:W}=await b("/schedule",{args:Zn("ctx.scheduler",String(x.functionPath??x.workflow),B),scheduledFor:y,...x});return W};return{cancel:async y=>await b("/cancel",{id:y}),get:async y=>{const A=await w(`/get?id=${encodeURIComponent(y)}`,{method:"GET"});return A.record===void 0?null:s(A.record)},list:k,runAfter:async(y,A,B)=>{if(!Number.isFinite(y)||y<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await I(Date.now()+y,A,B)},runAt:async(y,A,B)=>{if(!Number.isFinite(y))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await I(y,A,B)}}},yn=async(o,s,u)=>{const{claims:d,headers:w,userId:b}=await H(o,s,a),v=be(s,o,y=>u.waitUntil?.(y)),k=y=>async(A,B={})=>{const x=A.__lunoraRef;if(typeof x!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Se(x);const W=await Re(o,x,ke(B),y,{...w,"x-lunora-system":"1"},v),L=await W.json();if(L.error)throw new c(L.error.message??"shard RPC failed",{code:L.error.code??"INTERNAL",status:W.status});return Ve(L.result)},I=k(r);return{auth:{getIdentity:()=>Promise.resolve(d),userId:b},cache:u.cache,fetch:globalThis.fetch.bind(globalThis),forShard:y=>{const A=k(y);return{runAction:A,runMutation:A,runQuery:A}},runAction:I,runMutation:I,runQuery:I,...l===void 0?{}:{scheduler:gn(l)},...u.waitUntil===void 0?{}:{waitUntil:u.waitUntil.bind(u)},...e.storage===void 0?{}:{storage:Er(e.storage(s))}}},bn=async(o,s,u)=>{if(!e.httpRouter)return;const d=await yn(o,s,u);try{return await e.httpRouter.fetch(o,{...s,__lunoraCtx:d},u)}catch(w){return console.error("[lunora] httpRouter (SSR) handler threw:",w),new Response("Internal Server Error",{status:500})}},_n=async(o,s,u)=>{if(o.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const d=wt(o,se);if(d)return d;const w=u.searchParams.get("shard")??r,{headers:b,identity:v}=await H(o,s,a);await G(v,w);const k=Mt(o,b),I=Lt(s,e.shardDO);if(I!==void 0){k.set("x-lunora-shard-binding",I);const y=await ss(i,w);if(y>0){const A=Lr(w,Math.floor(Math.random()*y));return f(i,A,new Request(o,{headers:k}),gt(o))}}return f(i,w,new Request(o,{headers:k}))},Rn=async(o,s,u)=>{const{voiceAgents:d}=e;if(d===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const w=wt(o,se);if(w)return w;let b;try{b=decodeURIComponent(u.pathname.slice(Bt.length))}catch{return new Response("Unknown voice agent",{status:404})}const v=Object.hasOwn(d,b)?d[b]:void 0;if(v===void 0)return new Response("Unknown voice agent",{status:404});const k=u.searchParams.get("threadKey");if(k===null||k.length===0)return new Response("Missing threadKey",{status:400});const{headers:I,identity:y}=await H(o,s,a);if(e.authorizeShard){if(!await Ae(e.authorizeShard({identity:y,shardKey:k})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else C("shard");const A=Mt(o,I);return f(v,k,new Request(o,{headers:A}))},En=async(o,s,u)=>{if(e.authorizeFanOut){if(!await Ae(e.authorizeFanOut(u,o.table,s)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new c("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});C("fan-out")},_e=async(o,s)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await En(o.fanOut,o.functionPath,s);return}await G(s,o.shardKey??r)}},Sn=(o,s,u)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){Z();return}if(e.functions[s]?.kind!=="query"||u.includes(qe)||u.includes(Je))return;const d=gt(o);return d===void 0?void 0:{name:Mr(u,d),region:d}},An=async(o,s,u,d,w)=>{const b=Sn(o,s,d);if(b!==void 0){const v={...w,"x-lunora-replica-read":"1",..._===void 0?{}:{"x-lunora-shard-binding":_}},k=$r(o.headers.get("x-lunora-min-seq"));k!==void 0&&(v["x-lunora-min-seq"]=String(k));const I=await f(i,b.name,ve(s,u,v),b.region);if(I.status!==421)return I}return f(i,d,ve(s,u,w))},Re=async(o,s,u,d,w,b)=>{const v=Date.now(),{observability:k,sampling:I}=e,y=We(o),{decision:A,ignoredUpstream:B,trace:x}=ua(o,{...I===void 0?{}:{sampling:I},trustInbound:t(o)});B&&n();const W={...w,"x-lunora-sample-errors":A.keepErrors?"1":"0"};la(x,W);try{const L=await An(o,s,u,d,W);ie(k,{...y,...Ct(x),durationMs:Date.now()-v,functionPath:s,ok:L.ok,shardKey:d,...L.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(L.status)}`,status:L.status}}},b,void 0,{isTraced:x.sampled,keepErrors:A.keepErrors});const ne=new Response(L.body,{headers:L.headers,status:L.status,statusText:L.statusText});return ne.headers.set("x-lunora-shard-key",d),ne}catch(L){throw ie(k,{...y,...Ct(x),...Te(s,Date.now()-v,L,{shardKey:d})},b,void 0,{isTraced:x.sampled,keepErrors:A.keepErrors}),L}},Tn=o=>{if(o.fanOut&&o.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(o.fanOut||Se(o.functionPath),o.fanOut&&!e.queryCoordinator)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},On=async(o,s,u)=>{j(o,"POST","RPC");const d=await rs(o);ns(s,d),Tn(d);const w=await on(o,d);if(w!==void 0)return w;const{headers:b,identity:v}=await H(o,s,a);await _e(d,v);const k=ze(d,e);{const I=Date.now(),{observability:y}=e,A=We(o),B=be(s,o,u&&(L=>u.waitUntil?.(L)));if(d.fanOut){const L=e.queryCoordinator;if(!L)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ne=await L.fanOut(i,{args:d.args??{},fanOut:d.fanOut,functionPath:d.functionPath,headers:b});return ie(y,{durationMs:Date.now()-I,fanOut:{failed:ne.failed,shards:ne.ok+ne.failed,table:d.fanOut.table},functionPath:d.functionPath,...A,ok:!0},B),Response.json(ne,{headers:{"content-type":"application/json"},status:200})}catch(ne){throw ie(y,{...Te(d.functionPath,Date.now()-I,ne,{fanOut:{table:d.fanOut.table}}),...A},B),ne}}const x=d.shardKey??r,W=()=>Re(o,d.functionPath,d.args??{},x,b,B);return k&&e.x402Charge?e.x402Charge(o,{functionPath:d.functionPath,price:k.price},W,Qe(u)):W()}},vn=async(o,s,u)=>{j(o,"POST","RPC batch");const d=await te(o),{calls:w}=d;if(!Array.isArray(w))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:b,identity:v}=await H(o,s,a),k=ho(w,r);for(const z of k.values())for(const V of z)if(e.functions?.[V.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${V.functionPath}" cannot be called in a batch; dispatch it individually over ${Ut}`,{code:"BAD_REQUEST",status:400});await Promise.all([...k.entries()].flatMap(([z,V])=>V.map(oe=>_e({args:oe.args,functionPath:oe.functionPath,shardKey:z},v))));const{observability:I}=e,y=be(s,o,u&&(z=>u.waitUntil?.(z))),A=We(o),B=[],x=[],W=(z,V,oe,de)=>({body:{error:{code:oe,message:de}},id:z.id,status:V}),L=(z,V,oe,de,fe)=>{for(const Y of z)ie(I,fe(Y),y),B.push(W(Y,V,oe,de))},ne=(z,V,oe,de,fe)=>{for(const Y of z){const pe=de.get(Y.id)??fe,ye=pe<400;ie(I,{durationMs:oe,functionPath:Y.functionPath,...A,ok:ye,shardKey:V,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},y)}};await Promise.all([...k.entries()].map(async([z,V])=>{const oe=new Headers(b);oe.set("content-type","application/json");const de=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:V}),headers:oe,method:"POST"}),fe=Date.now();let Y;try{Y=await f(i,z,de)}catch(X){const He=Date.now()-fe,{body:ct}=Kn(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});L(V,502,ct.code,ct.message,$n=>({...Te($n.functionPath,He,X,{shardKey:z}),...A}));return}const pe=Date.now()-fe,ye=Y.headers.get("x-d1-bookmark");ye&&x.push(ye);let Be;try{Be=await Y.json()}catch{const X=`shard batch returned a non-JSON response (${String(Y.status)})`;L(V,Y.status,"SHARD_ERROR",X,He=>({durationMs:pe,error:{code:"SHARD_ERROR",message:X,status:Y.status},functionPath:He.functionPath,...A,ok:!1,shardKey:z}));return}const xe=Array.isArray(Be.results)?Be.results:[],Ln=new Map(xe.map(X=>[X.id,X.status??Y.status])),Mn=new Set(xe.map(X=>X.id));ne(V,z,pe,Ln,Y.status),B.push(...xe);for(const X of V)Mn.has(X.id)||B.push(W(X,Y.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const st={"content-type":"application/json"},[it]=x;return x.length===1&&it!==void 0&&(st["x-d1-bookmark"]=it),Response.json({results:B},{headers:st,status:200})},kn=async(o,s,u,d={},w={})=>{try{const b=u.__lunoraRef;if(typeof b!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Se(b);const{headers:v,identity:k}=await H(o,s,a,w.context),I={args:d,functionPath:b,shardKey:w.shardKey};await _e(I,k);const y=w.shardKey??r,A=be(s,o,w.waitUntil),B=()=>Re(o,b,d,y,v,A),x=ze(I,e);return x&&e.x402Charge?await e.x402Charge(o,{functionPath:b,price:x.price},B,Qe(w.waitUntil?{waitUntil:w.waitUntil}:w.context)):await B()}catch(b){return lt(b)}},ot=async(o,s,u)=>{const{observability:d}=e,w=Date.now(),b=Ie(16),v=Ie(8),k=Ht(s),I=Kt(b,v,!0);try{const y=await u(I);return ie(d,{durationMs:Date.now()-w,functionPath:o,ok:!0,spanId:v,traceId:b},k),y}catch(y){throw ie(d,{...Te(o,Date.now()-w,y,{}),spanId:v,traceId:b},k),y}finally{ft(d,k)}},In=async(o,s,u,d)=>{E(s);const w=[],b=A=>A instanceof Error?A:new Error(String(A)),v=e.crons?.[o.cron];if(v)try{await v(o,s,u)}catch(A){w.push(b(A))}const k=await he(o.cron,s,w,b,d),I=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron;if(I)try{await ao(e,i,S(),o)}catch(A){w.push(b(A))}if(!v&&k===0&&!I){const A=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${o.cron}") fired but no cron handler is registered for that expression. Registered: ${A.length===0?"(none)":A.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[y]=w;if(w.length===1&&y)throw y;if(w.length>1)throw new AggregateError(w,`scheduled("${o.cron}") had ${String(w.length)} failure(s)`)},Pn=async(o,s)=>{try{const u=o??{},d=e.adminToken??(typeof u.LUNORA_ADMIN_TOKEN=="string"?u.LUNORA_ADMIN_TOKEN:void 0);if(!d||d.length===0)return;await f(i,r,ve(Wa,{outcome:s},{authorization:`Bearer ${d}`,"content-type":"application/json"}))}catch{}},Nn=async(o,s,u,d)=>{if(!e.authHandler)return;const w=await e.authHandler(o);if(!w)return;const b=e.authBasePath??xt;return Ja(u.pathname,b)&&d.waitUntil?.(Pn(s,w.status>=400?"fail":"ok")),w},Dn=async({args:o,env:s,functionPath:u,request:d,shardKey:w,waitUntil:b})=>{Gt(o,"REST");const v={functionPath:u,...w===void 0?{}:{shardKey:w}},{headers:k,identity:I}=await H(d,s,a);await _e(v,I);const y=w??r,A=be(s,d,b),B=()=>Re(d,u,o,y,k,A),x=ze(v,e);return x&&e.x402Charge?e.x402Charge(d,{functionPath:u,price:x.price},B,Qe({waitUntil:b})):B()},Un=er({functions:e.functions??{},invoke:Dn,readJsonBody:te,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ee=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0;hs(Ee);const Cn={[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"}}),[xa]:(o,s,u)=>_n(o,s,u),[Ut]:(o,s,u,d)=>On(o,s,d),[Ba]:(o,s,u,d)=>vn(o,s,d),[Ha]:(o,s)=>Ne(o,s),[La]:(o,s)=>ce(o,s),[Ma]:async o=>{j(o,"POST","ws-token"),F(o);const s=S();if(s===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const u=await Qr(s);return Response.json(u,{headers:{"cache-control":"no-store"}})},...J,...an,...sn,...cn,...dn,...un,...ln,...hn,...fn,...pn,...wn,...Un,...Jr({assertAdmin:F,getAuthAdmin:()=>e.authAdmin,parsePaging:Ce,queryParameter:Ue,readJsonBody:te})};let se=mt(e.security),at=!1;const Bn=o=>{at||(at=!0,se=mt(e.security,o??{}))},xn=async(o,s)=>{Fa(s)&&await U(o)},Hn=async(o,s,u)=>{Ye.set(o,u);const d=new URL(o.url);if((d.pathname.startsWith(Pe)||e.authHandler!==void 0&&qa(d.pathname,e.authBasePath??xt))&&(o.method==="POST"||o.method==="PUT")){const I=Number(o.headers.get("content-length")??""),y=Ca[d.pathname]??Ft;if(Number.isFinite(I)&&I>y)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const b=await Nn(o,s,d,u);if(b)return b;if(Ee){const I=`${o.method} ${d.pathname}`,y=Ee[I]??Ee[d.pathname];if(y)return y(o,s,u)}const v=Cn[d.pathname];if(v)return await xn(o,d.pathname),v(o,s,d,u);if(e.voiceAgents!==void 0&&d.pathname.startsWith(Bt))return Rn(o,s,d);if(d.pathname.startsWith(Pe))return new Response("Not found",{status:404});const k=await bn(o,s,u);return k||new Response("Not found",{status:404})};return{async fetch(o,s,u){e.passThroughOnException&&u.passThroughOnException?.(),Bn(s),E(s);const d=_r(o,se);if(d)return d;const w=Rr(o,se);if(w)return Me(w,o,se);try{const b=await Hn(o,s,u);return Me(b,o,se)}catch(b){return Me(lt(b),o,se)}finally{ft(e.observability,Ht(u))}},async queue(o,s,u){await ot(`queue:${Xa(o)}`,u,async d=>{await e.queue?.(o,s,u,{traceparent:d})})},async scheduled(o,s,u){await ot(`cron:${o.cron}`,u,async d=>{await In(o,s,u,d)})},serverQuery:kn}},ps=e=>rn(e),ms=e=>typeof e=="function"?{fetch:e}:e,ws=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,gs=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},$s=(e,t)=>{const n=ms(e),{email:r,queue:a,scheduled:i}=gs(e),l=p=>{const R={...ps({...p,httpRouter:n})};return i!==void 0&&!ws(p)&&(R.scheduled=async(S,T,m)=>{await i(S,T,m)}),a!==void 0&&p.queue===void 0&&(R.queue=async(S,T,m)=>{await a(S,T,m)}),r!==void 0&&(R.email=async(S,T,m)=>{await r(S,T,m)}),R};if(typeof t!="function")return l(t);const h=t;return{fetch:(p,f,R)=>l(h(f)).fetch(p,f,R),queue:(p,f,R)=>l(h(f)).queue?.(p,f,R)??Promise.resolve(),scheduled:(p,f,R)=>l(h(f)).scheduled(p,f,R),serverQuery:(p,f,R,S,T)=>l(h(f)).serverQuery(p,f,R,S,T),...r===void 0?{}:{email:(p,f,R)=>l(h(f)).email?.(p,f,R)??Promise.resolve()}}},ys=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new c("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},js=(e={})=>(t,n,r)=>rn(ys(e,n)).fetch(t,n,r??Fn),Ks=e=>e;export{_t as GET_AUTH_AUDIT_LOG_OP,Fn as NOOP_EXECUTION_CONTEXT,Qs as composeIdentityResolvers,ps as composeWorker,js as createLunoraHandler,rn as createWorker,Ks as defineRpcEnvelope,ss as probeRelayCount,ys as resolveLunoraOptions,Ws as routeIdentityResolvers,$s as withFrameworkWorker};