@lunora/runtime 1.0.0-alpha.84 → 1.0.0-alpha.86
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 +3 -7
- package/dist/index.d.ts +3 -7
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/DEFAULT_LOG_COLUMNS-gYMhXLzO.mjs +1 -0
- package/dist/packem_shared/{LOG_ARCHIVE_PATH-Btzcg6oL.mjs → LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs} +1 -1
- package/dist/packem_shared/argsFromQuery-DUfMEn8Z.mjs +1 -0
- package/dist/packem_shared/composeWorker-DnsDkxiF.mjs +6 -0
- package/dist/packem_shared/{createCrossShardRelationCapabilities-kKGcOgYm.mjs → createCrossShardRelationCapabilities-BYNkv1Ys.mjs} +1 -1
- package/dist/packem_shared/{createKvCursorStore-DI7FWQ1f.mjs → createKvCursorStore-dBxlYrXY.mjs} +1 -1
- package/dist/packem_shared/{createShardClient-0Tz9JwbX.mjs → createShardClient-DoKTlCKb.mjs} +1 -1
- package/dist/packem_shared/{export-tap-CgiuS5w4.mjs → export-tap-CGR3Xd9F.mjs} +1 -1
- package/dist/packem_shared/pipeline-log-reader-C-nuWG_e.mjs +1 -0
- package/dist/packem_shared/{portable-json-DPJbalfn.mjs → portable-json-DpqTEd22.mjs} +1 -1
- package/dist/packem_shared/{rest-routes-Dq17Zntv.mjs → rest-routes-ZZES0ngM.mjs} +1 -1
- package/dist/packem_shared/{toAirbyteMessages-CIjE6Vm1.mjs → toAirbyteMessages-DvYrhqLf.mjs} +1 -1
- package/dist/packem_shared/{wire-codec-BsPOEXGn.mjs → wire-codec-CMVqBlcF.mjs} +1 -1
- package/package.json +4 -4
- package/dist/packem_shared/DEFAULT_LOG_COLUMNS-B8FFcwsX.mjs +0 -1
- package/dist/packem_shared/argsFromQuery-CRa3o4U3.mjs +0 -1
- package/dist/packem_shared/composeWorker-C6smX1pe.mjs +0 -6
- package/dist/packem_shared/pipeline-log-reader-BGrl66P5.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -1920,7 +1920,7 @@ interface PipelineLogQuery {
|
|
|
1920
1920
|
functionPathPrefix?: string;
|
|
1921
1921
|
/** Match only this exact severity. When set, `minLevel` is ignored for the same field. */
|
|
1922
1922
|
level?: ContextLogLevel;
|
|
1923
|
-
/** Max rows to return. Clamped to `[1, 10000]`; defaults to
|
|
1923
|
+
/** Max rows to return. Clamped to `[1, 10000]`; defaults to 500. */
|
|
1924
1924
|
limit?: number;
|
|
1925
1925
|
/** Severity floor: keep every level at or above this in {@link LOG_LEVEL_ORDER} (e.g. `warn` keeps warn, error, fatal). */
|
|
1926
1926
|
minLevel?: ContextLogLevel;
|
|
@@ -1994,8 +1994,6 @@ interface PipelineLogReader {
|
|
|
1994
1994
|
}
|
|
1995
1995
|
/** The written-column contract exposed publicly: canonical field to default physical column name. */
|
|
1996
1996
|
declare const DEFAULT_LOG_COLUMNS: Readonly<Record<PipelineLogField, string>>;
|
|
1997
|
-
/** Default page size when a query omits `limit`. */
|
|
1998
|
-
declare const DEFAULT_LOG_LIMIT: number;
|
|
1999
1997
|
/**
|
|
2000
1998
|
* Build a durable-log reader over one R2 Data Catalog (Iceberg) table.
|
|
2001
1999
|
*
|
|
@@ -2519,8 +2517,6 @@ interface RestRouteDeps {
|
|
|
2519
2517
|
* `shared/rest-surface` helper).
|
|
2520
2518
|
*/
|
|
2521
2519
|
declare const restSurfaceFromRegistry: (functions: RestRegistryLike) => ReturnType<typeof describeRestSurface>;
|
|
2522
|
-
/** Read `shardKey` from `?shardKey=` or the `x-lunora-shard-key` header; `undefined` routes to the default shard. */
|
|
2523
|
-
declare const readShardKey: (url: URL, request: Request) => string | undefined;
|
|
2524
2520
|
/**
|
|
2525
2521
|
* Decode GET args from the query string. Each value is parsed as JSON when it
|
|
2526
2522
|
* looks like a JSON scalar/array/object (so `?limit=10` → number, `?ids=[1,2]` →
|
|
@@ -5060,11 +5056,11 @@ declare const createShardClient: (namespace: ShardNamespaceLike, options?: Shard
|
|
|
5060
5056
|
*/
|
|
5061
5057
|
declare const STORAGE_UPLOAD_MAX_BODY_BYTES: number;
|
|
5062
5058
|
declare const VERSION: string;
|
|
5063
|
-
export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolver, type AirbyteMessage, type AnalyticsEngineDataPointLike, type AnalyticsEngineDatasetLike, type AnalyticsEngineSinkOptions, type AuthAdmin, type AuthCapabilities, type AuthConfigInfo, type AuthImpersonation, type AuthPage, type AuthSession, type AuthUser, type AuthUserFieldSpec, BACKUP_KEY_PREFIX, type BackupManifest, type BackupManifestEntry, type BackupRetentionPreview, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS,
|
|
5059
|
+
export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolver, type AirbyteMessage, type AnalyticsEngineDataPointLike, type AnalyticsEngineDatasetLike, type AnalyticsEngineSinkOptions, type AuthAdmin, type AuthCapabilities, type AuthConfigInfo, type AuthImpersonation, type AuthPage, type AuthSession, type AuthUser, type AuthUserFieldSpec, BACKUP_KEY_PREFIX, type BackupManifest, type BackupManifestEntry, type BackupRetentionPreview, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS, DEFAULT_REGISTRY_CACHE_TTL_MS, type DurableObjectJurisdiction, type DynamicShardRegistry, type DynamicShardRegistryOptions, type ExecutionContextLike, type ExportBatch, type ExportChange, type ExportCursorStore, type ExportFanOutRequest, type ExportFanOutResult, type ExportSink, type ExportTapFailure, type ExportTapResult, type FanOutRequest, type FanOutResult, type FanOutSpec, type FivetranResponse, type FrameworkHostHandler, type FrameworkWorkerOptions, type FrameworkWorkerOptionsInput, type FunctionDescriptor, type FunctionRegistryEntry, type FunctionRegistryLike, type GlobalExportFunction as GlobalExportFn, type GlobalImportFunction as GlobalImportFn, type GlobalIntrospector, type GlobalTableInfo as GlobalTableInfoMeta, type GlobalTablePage as GlobalTablePageMeta, HEALTH_PATH, HEALTH_READY_PATH, type HealthAuthPosture, type HealthBody, type HealthCheckReport, type HealthProbe, type HealthProbeKind, type HealthProbeResult, type HealthRouteDeps, type HttpActionContext, type HttpActionLike, type HttpRouterLike, type IdentityContractLike, type IdentityResolver, type IdentityValidation, type ImportFanOutRequest, type ImportFanOutResult, type KvIntrospector, type KvKeyEntry, type KvKeyListResult, type KvNamespaceSummary, type KvValueResult, LOG_ARCHIVE_NOT_CONFIGURED, LOG_ARCHIVE_PATH, type ListAuthUsersOptions, type LogArchiveConfig, type LogEvent, type LogFields, type LogLevel, LunoraError, type LunoraErrorBody, type LunoraHandlerOptions, type LunoraWorker, type MemoizeIdentityOptions, type MergeStrategy, type MetricEvent, type MetricKind, type MigrationFanOutRequest, type MigrationFanOutResult, NOOP_EXECUTION_CONTEXT, type NotifySubscriptionDevice, type NotifySubscriptionStoreLike, type ObservabilityEvent, type ObservabilitySink, type ObservabilitySinkContext,
|
|
5064
5060
|
/**
|
|
5065
5061
|
* Resource attribute bag used by OTLP exporters. Re-exported from `shared/otlp`
|
|
5066
5062
|
* because {@link OtlpSinkOptions.resourceAttributes} is part of the public
|
|
5067
5063
|
* surface — without a name for it, a caller cannot hoist a shared attribute bag
|
|
5068
5064
|
* into a typed constant.
|
|
5069
5065
|
*/
|
|
5070
|
-
type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink,
|
|
5066
|
+
type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, 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
|
@@ -1920,7 +1920,7 @@ interface PipelineLogQuery {
|
|
|
1920
1920
|
functionPathPrefix?: string;
|
|
1921
1921
|
/** Match only this exact severity. When set, `minLevel` is ignored for the same field. */
|
|
1922
1922
|
level?: ContextLogLevel;
|
|
1923
|
-
/** Max rows to return. Clamped to `[1, 10000]`; defaults to
|
|
1923
|
+
/** Max rows to return. Clamped to `[1, 10000]`; defaults to 500. */
|
|
1924
1924
|
limit?: number;
|
|
1925
1925
|
/** Severity floor: keep every level at or above this in {@link LOG_LEVEL_ORDER} (e.g. `warn` keeps warn, error, fatal). */
|
|
1926
1926
|
minLevel?: ContextLogLevel;
|
|
@@ -1994,8 +1994,6 @@ interface PipelineLogReader {
|
|
|
1994
1994
|
}
|
|
1995
1995
|
/** The written-column contract exposed publicly: canonical field to default physical column name. */
|
|
1996
1996
|
declare const DEFAULT_LOG_COLUMNS: Readonly<Record<PipelineLogField, string>>;
|
|
1997
|
-
/** Default page size when a query omits `limit`. */
|
|
1998
|
-
declare const DEFAULT_LOG_LIMIT: number;
|
|
1999
1997
|
/**
|
|
2000
1998
|
* Build a durable-log reader over one R2 Data Catalog (Iceberg) table.
|
|
2001
1999
|
*
|
|
@@ -2519,8 +2517,6 @@ interface RestRouteDeps {
|
|
|
2519
2517
|
* `shared/rest-surface` helper).
|
|
2520
2518
|
*/
|
|
2521
2519
|
declare const restSurfaceFromRegistry: (functions: RestRegistryLike) => ReturnType<typeof describeRestSurface>;
|
|
2522
|
-
/** Read `shardKey` from `?shardKey=` or the `x-lunora-shard-key` header; `undefined` routes to the default shard. */
|
|
2523
|
-
declare const readShardKey: (url: URL, request: Request) => string | undefined;
|
|
2524
2520
|
/**
|
|
2525
2521
|
* Decode GET args from the query string. Each value is parsed as JSON when it
|
|
2526
2522
|
* looks like a JSON scalar/array/object (so `?limit=10` → number, `?ids=[1,2]` →
|
|
@@ -5060,11 +5056,11 @@ declare const createShardClient: (namespace: ShardNamespaceLike, options?: Shard
|
|
|
5060
5056
|
*/
|
|
5061
5057
|
declare const STORAGE_UPLOAD_MAX_BODY_BYTES: number;
|
|
5062
5058
|
declare const VERSION: string;
|
|
5063
|
-
export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolver, type AirbyteMessage, type AnalyticsEngineDataPointLike, type AnalyticsEngineDatasetLike, type AnalyticsEngineSinkOptions, type AuthAdmin, type AuthCapabilities, type AuthConfigInfo, type AuthImpersonation, type AuthPage, type AuthSession, type AuthUser, type AuthUserFieldSpec, BACKUP_KEY_PREFIX, type BackupManifest, type BackupManifestEntry, type BackupRetentionPreview, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS,
|
|
5059
|
+
export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolver, type AirbyteMessage, type AnalyticsEngineDataPointLike, type AnalyticsEngineDatasetLike, type AnalyticsEngineSinkOptions, type AuthAdmin, type AuthCapabilities, type AuthConfigInfo, type AuthImpersonation, type AuthPage, type AuthSession, type AuthUser, type AuthUserFieldSpec, BACKUP_KEY_PREFIX, type BackupManifest, type BackupManifestEntry, type BackupRetentionPreview, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS, DEFAULT_REGISTRY_CACHE_TTL_MS, type DurableObjectJurisdiction, type DynamicShardRegistry, type DynamicShardRegistryOptions, type ExecutionContextLike, type ExportBatch, type ExportChange, type ExportCursorStore, type ExportFanOutRequest, type ExportFanOutResult, type ExportSink, type ExportTapFailure, type ExportTapResult, type FanOutRequest, type FanOutResult, type FanOutSpec, type FivetranResponse, type FrameworkHostHandler, type FrameworkWorkerOptions, type FrameworkWorkerOptionsInput, type FunctionDescriptor, type FunctionRegistryEntry, type FunctionRegistryLike, type GlobalExportFunction as GlobalExportFn, type GlobalImportFunction as GlobalImportFn, type GlobalIntrospector, type GlobalTableInfo as GlobalTableInfoMeta, type GlobalTablePage as GlobalTablePageMeta, HEALTH_PATH, HEALTH_READY_PATH, type HealthAuthPosture, type HealthBody, type HealthCheckReport, type HealthProbe, type HealthProbeKind, type HealthProbeResult, type HealthRouteDeps, type HttpActionContext, type HttpActionLike, type HttpRouterLike, type IdentityContractLike, type IdentityResolver, type IdentityValidation, type ImportFanOutRequest, type ImportFanOutResult, type KvIntrospector, type KvKeyEntry, type KvKeyListResult, type KvNamespaceSummary, type KvValueResult, LOG_ARCHIVE_NOT_CONFIGURED, LOG_ARCHIVE_PATH, type ListAuthUsersOptions, type LogArchiveConfig, type LogEvent, type LogFields, type LogLevel, LunoraError, type LunoraErrorBody, type LunoraHandlerOptions, type LunoraWorker, type MemoizeIdentityOptions, type MergeStrategy, type MetricEvent, type MetricKind, type MigrationFanOutRequest, type MigrationFanOutResult, NOOP_EXECUTION_CONTEXT, type NotifySubscriptionDevice, type NotifySubscriptionStoreLike, type ObservabilityEvent, type ObservabilitySink, type ObservabilitySinkContext,
|
|
5064
5060
|
/**
|
|
5065
5061
|
* Resource attribute bag used by OTLP exporters. Re-exported from `shared/otlp`
|
|
5066
5062
|
* because {@link OtlpSinkOptions.resourceAttributes} is part of the public
|
|
5067
5063
|
* surface — without a name for it, a caller cannot hoist a shared attribute bag
|
|
5068
5064
|
* into a typed constant.
|
|
5069
5065
|
*/
|
|
5070
|
-
type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink,
|
|
5066
|
+
type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, 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-
|
|
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-DvYrhqLf.mjs";import{composeWorker as x,createLunoraHandler as S,createWorker as l,defineRpcEnvelope as u,resolveLunoraOptions as _,withFrameworkWorker as d}from"./packem_shared/composeWorker-DnsDkxiF.mjs";import{createCrossShardRelationCapabilities as y}from"./packem_shared/createCrossShardRelationCapabilities-BYNkv1Ys.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-CGR3Xd9F.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-jZsuCmSs.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-vDK-rMbs.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-B3sQ6FPW.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-Ctr3eqmp.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-CPSyD1RD.mjs";import{a as ye,b as Ce,c as Oe,r as be}from"./packem_shared/rest-routes-ZZES0ngM.mjs";import{decorateResponse as Le,enforceOrigin as Te,handleCorsPreflight as he,resolveSecurity as He}from"./packem_shared/decorateResponse-BuqVnrmc.mjs";import{createShardClient as ge}from"./packem_shared/createShardClient-DoKTlCKb.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 @@
|
|
|
1
|
+
import{D as r,c as L}from"./pipeline-log-reader-C-nuWG_e.mjs";export{r as DEFAULT_LOG_COLUMNS,L as createPipelineLogReader};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createR2Sql as h}from"@lunora/bindings/r2sql";import{LOG_ARCHIVE_NOT_CONFIGURED as l}from"./LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{L,c as A}from"./pipeline-log-reader-
|
|
1
|
+
import{createR2Sql as h}from"@lunora/bindings/r2sql";import{LOG_ARCHIVE_NOT_CONFIGURED as l}from"./LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{L,c as A}from"./pipeline-log-reader-C-nuWG_e.mjs";import{LunoraError as _}from"./LunoraError-DksAgIpa.mjs";import{a as R}from"./method-guard-BG_vJNTl.mjs";const v="/_lunora/admin/logs/archive",m="LUNORA_LOG_ARCHIVE_TABLE",C="LUNORA_LOG_ARCHIVE_NAMESPACE",V=e=>{if(typeof e!="object"||e===null)return;const o=e,s=o[m];if(typeof s!="string"||s==="")return;const n=o[C];return{table:s,...typeof n=="string"&&n!==""?{namespace:n}:{}}},T=new Set(L),O=e=>typeof e=="string"&&e!==""?e:void 0,S=(e,o)=>{if(e!==void 0){if(typeof e!="string"||!T.has(e))throw new _(`logs archive: invalid \`${o}\` — expected one of ${L.join(", ")}`,{code:"BAD_REQUEST",status:400});return e}},p=(e,o)=>{if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e))throw new _(`logs archive: invalid \`${o}\` — expected a finite number`,{code:"BAD_REQUEST",status:400});return e}},b=e=>{const o={},s=r=>{const t=O(e[r]);t!==void 0&&(o[r]=t)},n=r=>{const t=S(e[r],r);t!==void 0&&(o[r]=t)},i=r=>{const t=p(e[r],r);t!==void 0&&(o[r]=t)};s("functionPath"),s("functionPathPrefix"),s("traceId"),s("shardKey"),s("userId"),n("level"),n("minLevel"),i("sinceTs"),i("untilTs"),i("limit");const c=e.cursor;if(typeof c=="object"&&c!==null){const r=c,t=p(r.ts,"cursor.ts");if(t!==void 0){const a=r.seen;if(a!==void 0&&(!Array.isArray(a)||a.some(d=>typeof d!="string")))throw new _("logs archive: invalid `cursor.seen` — expected an array of strings",{code:"BAD_REQUEST",status:400});const u=a;o.cursor=u===void 0||u.length===0?{ts:t}:{seen:u,ts:t}}}return o},y=e=>{const o=e.R2_SQL_ACCOUNT_ID??e.CLOUDFLARE_ACCOUNT_ID,s=e.R2_SQL_TOKEN,n=e.R2_SQL_BUCKET,i=[];if((o===void 0||o==="")&&i.push("R2_SQL_ACCOUNT_ID"),(s===void 0||s==="")&&i.push("R2_SQL_TOKEN"),(n===void 0||n==="")&&i.push("R2_SQL_BUCKET"),i.length>0)throw new _(`log archive not configured (missing ${i.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET must be set — see the observability docs.`,{code:l,status:400});return{accountId:o,apiToken:s,bucket:n}},B=e=>{const{createReader:o=A,readJsonBody:s,requireAdminOption:n}=e,i=async(c,r)=>{R(c,"POST","Log-archive");const t=n(c,e.logArchive,{code:l,message:"log archive requires a `logArchive` config (an R2 Data Catalog table) on the worker — see the observability docs"}),{accountId:a,apiToken:u,bucket:d}=y(r??{}),g=b(await s(c)),E=h({accountId:a,apiToken:u,bucket:d}),f=await o(E,{columnMap:t.columnMap,namespace:t.namespace,table:t.table}).query(g);return Response.json(f,{headers:{"content-type":"application/json"},status:200})};return{[v]:i}};export{l as LOG_ARCHIVE_NOT_CONFIGURED,v as LOG_ARCHIVE_PATH,B as buildLogArchiveAdminRoutes,V as resolveLogArchiveFromEnv};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./rest-cache-CPSyD1RD.mjs";import{a,b as o,c as i,r as m}from"./rest-routes-ZZES0ngM.mjs";import"./method-guard-BG_vJNTl.mjs";export{a as argsFromQuery,o as buildRestRoutes,i as createRestRateLimit,m as restSurfaceFromRegistry};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{isLunoraError as Dn,toErrorBody as Nn}from"@lunora/errors";import{e as Nt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Un}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as Cn,f as Bn}from"./base64-Bl1_r2k1.mjs";import{e as xn,a as Hn}from"./identity-header-C4Z5pldl.mjs";import{o as Te,b as Ln,p as Mn,m as Kn,d as jn,a as $n,r as Fn}from"./otlp-resource-DeXhb949.mjs";import{e as Qe,d as Gn}from"./wire-codec-CMVqBlcF.mjs";import{d as Z,e as be,M as Ut,b as Qn,f as zn,g as Ct,h as Bt}from"./rest-routes-ZZES0ngM.mjs";import{LunoraError as d,toErrorResponse as ot}from"./LunoraError-DksAgIpa.mjs";import{a as j,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as We,BACKUP_KEY_PREFIX as Ve,isBackupManifestKey as Wn,backupObjectKeyOfManifest as xt,backupObjectKey as Vn,backupManifestKey as Jn}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as qn,buildStorageAdminRoutes as Yn,STORAGE_UPLOAD_MAX_BODY_BYTES as Xn,STORAGE_PATH as Zn}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{b as er,e as tr,f as at,g as nr,h as rr}from"./export-tap-CGR3Xd9F.mjs";import{buildHealthRoutes as or,durableObjectProbe as ar,d1Probe as sr,presenceProbe as Be}from"./HEALTH_PATH-jZsuCmSs.mjs";import{wrapResolverWithContract as ir}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Os,routeIdentityResolvers as vs}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as cr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{r as dr,f as st,a as ie}from"./observability-vDK-rMbs.mjs";import{resolveShard as we,applyJurisdiction as it}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as ct,handleCorsPreflight as ur,enforceOrigin as lr,decorateResponse as xe,enforceWebSocketOrigin as dt}from"./decorateResponse-BuqVnrmc.mjs";const hr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n={...t,bucketName:"default"};return n.bucket=()=>n,n},Ht="__lunoraBranch",fr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Ht),pr=`may not contain the reserved workflow branch-marker key ("${Ht}")`,Je=(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 i=a<e.length?e.charCodeAt(a):0,u=a<t.length?t.charCodeAt(a):0;o|=i^u}return o===0},mr=(e,t,n,o)=>{const a=e.get(t);if(a!==void 0)return a;Nt(e,o);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},qe=new TextEncoder,wr=Array.from({length:32},(e,t)=>t);new RegExp(`[${wr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const gr=64,yr=new Map,Lt=async e=>mr(yr,e,async()=>crypto.subtle.importKey("raw",qe.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),gr),Mt=async(e,t)=>{const n=await Lt(e),o=await crypto.subtle.sign("HMAC",n,qe.encode(t));return Cn(new Uint8Array(o))},br=async(e,t,n)=>{const o=await Lt(e);return crypto.subtle.verify("HMAC",o,n,qe.encode(t))},_r=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(_r);const Rr=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Er=-100,Sr=15,Ar=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Rr.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Sr?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Er?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},ut=e=>{const t=e.cf;return t===void 0?void 0:Ar(t)},Kt="::relay::",Tr=(e,t)=>`${e}${Kt}${String(t)}`,jt="::replica::",Or=(e,t)=>`${e}${jt}${t}`,vr=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},kr=new Set(["1","enabled","on","true","yes"]),Ir=new Set(["0","disabled","false","no","off"]),Pr=(e,t)=>{const n=(e??"").trim().toLowerCase();return kr.has(n)?!0:Ir.has(n)?!1:t},$t="v1",Dr=6e4,Nr=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Dr),o=`${$t}.${String(n)}`,a=await Mt(e,o);return{expiresAtMs:n,token:`${o}.${a}`}},Ur=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,i,u]=o;if(a!==$t||u.length===0)return!1;const h=Number(i);if(!Number.isFinite(h)||h<=n)return!1;let f;try{f=Bn(u)}catch{return!1}return br(e,`${a}.${i}`,f)},P="/_lunora/admin/auth",Cr={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},he=(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},Ft=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,He=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},lt=e=>{const t=Ft(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new d("`role` is required",{code:"BAD_REQUEST",status:400});return t},ht=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(i=>typeof i=="string")&&(n[o]=a);return n},Br={[`${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:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:he(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:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:He(e,"data"),email:N(e,"email"),name:N(e,"name"),password:re(e,"password"),role:Ft(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:lt(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:He(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:He(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:lt(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:ht(e),role:N(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:ht(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(i){if(i instanceof d)throw i;const u=i,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new d("auth admin operation failed",{code:h,status:Cr[h]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new d(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new d("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[i.method];if(h===void 0)throw new d(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(a.url),w={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:v=>e.queryParameter(f,v)},E=i.build(w),O=await t(()=>h(E));return Response.json(i.returns==="void"?{ok:!0}:O,{headers:{"content-type":"application/json"},status:200})},o={};for(const[a,i]of Object.entries(Br))o[a]=u=>n(u,i);return o},Hr="__lunora_admin__:getAuthAuditLog",ft=e=>typeof e=="string"&&e!==""?e:void 0,pt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Lr=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 i=ft(o.actorId),u=ft(o.event),h=pt(o.sinceSeq),f=pt(o.limit),w={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...f===void 0?{}:{limit:f}};let E;try{E=await a.read(w)}catch(v){throw v instanceof d?v:(console.error("[lunora] auth audit read failed:",v),new d("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const O={entries:E};return Response.json({result:Qe(O)},{headers:{"content-type":"application/json"},status:200})},Mr=(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}},Kr=async(e,t,n,o,a,i,u)=>{if(n!==void 0&&o.length===0)return;const h=await e.orchestrateExport(i,{args:{tables:o},defaultShardKey:u,headers:t,tables:o});for(const f of h.shards)if(!f.error)for(const w of f.rows??[])a(w)},Gt=async(e,t,n,o,a,i)=>{const u=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:h,shardLocalTables:f}=Mr(e,u);await Kr(t,n,u,f,a,i,e.defaultShardKey??"__root__");const w=e.exportGlobals;if((o===void 0||h.length>0)&&w)for await(const O of w({tables:h}))a(O)},jr=new TextEncoder,$r=1e3,Qt=10,Fr=200,mt=8,zt="lunoraBackupCron",wt=24*1048576,gt=e=>{const t=e.slice(0,Qt).map(o=>xt(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Gr=(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},Ye=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let u=0;u<$r;u+=1){const h=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const f of h.objects)Wn(f.key)&&f.customMetadata?.[zt]===o&&a.push(f.key);if(!h.truncated||h.cursor===void 0)break;i=h.cursor}return{eligible:a.length,stale:a.toSorted((u,h)=>h.localeCompare(u)).slice(n)}},Qr=async(e,t,n,o,a)=>{const{stale:i}=await Ye(e,t,n,o),u=new Set(a),h=i.filter(g=>u.has(g)),f=h.slice(0,Fr),w=i.length-f.length,E=a.length-h.length;if(f.length===0)return{deleted:[],failed:[],ignored:E,remaining:w};const O=[],v=[];for(let g=0;g<f.length;g+=mt){const b=await Promise.allSettled(f.slice(g,g+mt).map(async _=>(await e.delete(xt(_)),await e.delete(_),_)));for(const[_,p]of b.entries())p.status==="fulfilled"?O.push(p.value):v.push(f[g+_])}return O.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(O.length)}: ${gt(O)}`),v.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(v.length)}: ${gt(v)}`),{deleted:O,failed:v,ignored:E,remaining:w}},zr=async e=>{const t=e.backupStore;if(!t)throw new d("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=We(e.backupPrefix??Ve),o=e.backupCron,{eligible:a,stale:i}=o===void 0?{eligible:0,stale:[]}:await Ye(t,n,e.backupRetain,o);return{cron:o,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},Wr=async(e,t,n,o)=>{const a=e.backupStore,i=e.queryCoordinator;if(!a)throw new d("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!i)throw new d("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!n||n.length===0)throw new d("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const u={authorization:`Bearer ${n}`,"content-type":"application/json"},h=e.backupTables;let f=0,w=0,E=[];await Gt(e,i,u,h,D=>{const M=jr.encode(`${JSON.stringify(D)}
|
|
2
|
+
`);if(f+=1,w+=M.byteLength,w>wt)throw new d(`scheduled backup reached ${String(w)} bytes of NDJSON, past the ${String(wt)}-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(M)},t);const v=We(e.backupPrefix??Ve),g=new Date(o.scheduledTime).toISOString(),b=Vn(v,g),_=Gr(E,w);E=[];const p=qn(await crypto.subtle.digest("SHA-256",_));await a.put(b,_,{httpMetadata:{contentType:"application/x-ndjson"},sha256:p});const A={bytes:w,createdAt:g,cron:o.cron,file:b,id:g,rows:f,scheduledTime:o.scheduledTime,sha256:p,...h?{tables:h.join(",")}:{}};await a.put(Jn(b),`${JSON.stringify(A,void 0,2)}
|
|
3
|
+
`,{customMetadata:{[zt]:o.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:D}=await Ye(a,v,e.backupRetain,o.cron);if(D.length>0){const M=D.slice(0,Qt),I=D.length-M.length;console.info(`[lunora] backup retention: ${String(D.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${M.join(", ")}${I>0?` (+${String(I)} more)`:""}`)}}catch(D){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,D)}},Vr=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 Qr(n,We(e.backupPrefix??Ve),a,o,t)},Jr="/_lunora/admin/backup/retention",qr="/_lunora/admin/backup/prune",Yr=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,a=(h,f)=>{o(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},i=async h=>(j(h,"GET","Backup-retention"),a(h,"retention preview"),Response.json(await zr(t),{headers:{"cache-control":"no-store"}})),u=async h=>{j(h,"POST","Backup-prune"),a(h,"prune");const{confirm:f}=await n(h);if(!Array.isArray(f)||f.some(w=>typeof w!="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 Vr(t,f),{headers:{"cache-control":"no-store"}})};return{[qr]:u,[Jr]:i}},yt=500,Xr=(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});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}},Zr=(e,t)=>{if(e.length>yt)throw new d(`RPC batch exceeds the ${String(yt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map;for(const[o,a]of e.entries()){const{entry:i,shardKey:u}=Xr(a,o,t),h=n.get(u)??[];h.push(i),n.set(u,h)}return n},eo="/_lunora/admin/export",to="/_lunora/admin/import",no="/_lunora/admin/sync",ro="/_lunora/admin/connector/sync",oo="/_lunora/admin/apply",ao="/_lunora/admin/export-tap/run",so=new TextEncoder,io=async e=>{const n=await be(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}},Le=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,co=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:a,knownTables:i,queryCoordinator:u,assertAdmin:h,requireAdminOption:f,resolveForwardContext:w,shardDO:E,streamExportRows:O,streamingImport:v,syncGlobals:g}=e,b=async(I,F)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),U=await io(I),{headers:G}=await w(I,F),Q=new ReadableStream({async pull(J){const K=$=>{J.enqueue(so.encode(`${JSON.stringify($)}
|
|
4
|
+
`))};try{await O(Y,G,U.tables,K),J.close()}catch($){J.error($)}}});return new Response(Q,{headers:{"content-type":"application/x-ndjson"},status:200})},_=async(I,F)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),U=await Z(I),G=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},Q=typeof U.limit=="number"?U.limit:void 0,J=typeof U.globalCursor=="number"?U.globalCursor:0,K=Le(U.tables),{headers:$}=await w(I,F),oe=K??i(),z=await Y.orchestrateCdcSync(E,{cursors:G,defaultShardKey:n,headers:$,limit:Q,tables:oe}),de=g?await g({limit:Q,sinceSeq:J}):void 0;return Response.json({global:de,shards:z.shards},{status:200})},p=async(I,F)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),U=await Z(I),G=tr(U.cursor),Q=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,J=Le(U.tables),{headers:K}=await w(I,F),$=J??i(),oe=await Y.orchestrateCdcSync(E,{cursors:G.s,defaultShardKey:n,headers:K,limit:Q,tables:$}),z=[],de={...G.s};let ue=!1;for(const ae of oe.shards)ue=at(z,ae.changes??[],rr(Q))||ue,de[ae.shardKey]=ae.cursor;let _e=G.g;if(g){const ae=await g({limit:Q,sinceSeq:G.g});ue=at(z,ae.changes,Q)||ue,_e=ae.cursor}const Oe=nr({g:_e,s:de,v:1}),ve={changes:z,hasMore:ue,nextCursor:Oe};return Response.json(ve,{status:200})},A=async(I,F)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),U=await Z(I),Q=(Array.isArray(U.batches)?U.batches:[]).map(z=>z).filter(z=>z!==null&&typeof z=="object"&&typeof z.shardKey=="string"&&Array.isArray(z.changes)),J=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:K}=await w(I,F),$=await Y.orchestrateApplyCdc(E,{batches:Q,headers:K}),oe=J.length>0&&t?await t({changes:J}):0;return Response.json({applied:$.applied+oe,failed:$.failed,ok:$.ok},{status:200})},D=async(I,F)=>{const H=me(I,["POST"]);if(H)return H;h(I);const{headers:Y}=await w(I,F),U=await v(I,Y);return Response.json(U,{headers:{"content-type":"application/json"},status:U.failed.length>0?207:200})},M=async(I,F)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{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 U=await Z(I),G=typeof U.sink=="string"?U.sink:void 0,Q=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,J=Le(U.tables);if(G===void 0)throw new d("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const K=a[G];if(K===void 0)throw new d(`Export-tap sink "${G}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:$}=await w(I,F),oe=J??i(),z=await er({coordinator:Y,cursorStore:o,defaultShardKey:n,headers:$,limit:Q,shardDO:E,sink:K,tables:oe});return Response.json(z,{headers:{"content-type":"application/json"},status:200})};return{[oo]:A,[ro]:p,[eo]:b,[ao]:M,[to]:D,[no]:_}},uo=(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}},lo=(e,t,n,o,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:o}},ho=async(e,t,n)=>{if(!e.body)throw new d("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const o=[],a=[],i=new Map;let u=0,h=0;const f=e.body.getReader(),w=new TextDecoder;let E="",O=0;const v=g=>{h+=1;const b=g.trim();if(b.length===0)return;u+=1;const _=uo(b,h);if(!_.ok){o.push(_.error);return}const{doc:p,table:A}=_,D=t.resolveTableSharding?.(A);if(D?.mode.kind==="global"){a.push({doc:p,line:h,table:A});return}const M=lo(p,A,D,n,h);if(!M.ok){o.push(M.error);return}const I=i.get(M.shardKey);I?I.rows.push({doc:p,table:A}):i.set(M.shardKey,{rows:[{doc:p,table:A}],shardKey:M.shardKey,startLine:h})};for(;;){const{done:g,value:b}=await f.read();if(g)break;if(b&&(O+=b.byteLength,O>Ut))throw await f.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=w.decode(b,{stream:!0});let _=E.indexOf(`
|
|
5
|
+
`);for(;_!==-1;){const p=E.slice(0,_);E=E.slice(_+1),v(p),_=E.indexOf(`
|
|
6
|
+
`)}}return E.length>0&&v(E),{errors:o,globalRows:a,perShard:i,received:u}},fo=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),bt=(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},po=async(e,t,n,o)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:h,received:f}=await ho(e,t,a),w={conflicts:0,errors:i,failed:[],inserted:{}},E=[];if(t.resolveTableSharding===void 0&&h.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"),h.size>0){const O=t.queryCoordinator;if(!O)throw new d("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const v=await O.orchestrateImport(o,{batches:[...h.values()],headers:n});bt(w,v),w.failed.push(...fo(v.shards))}if(u.length>0)if(t.importGlobals){const O=u[0]?.line??1,v=await t.importGlobals({rows:u,startLine:O});bt(w,v)}else for(const O of u)w.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:O.line,message:`row targets global table "${O.table}" but no \`importGlobals\` is configured`,table:O.table});return{conflicts:w.conflicts,errors:w.errors,failed:w.failed,inserted:w.inserted,received:f,...E.length>0?{warnings:E}:{}}},Me=e=>typeof e=="object"&&e!==null?e:{},Ke=e=>typeof e.kind=="string"?e.kind:"unknown",mo=(e,t)=>{let n=Me(t),o=!1;Ke(n)==="optional"&&(o=!0,n=Me(n._meta?.inner));const a=Ke(n),i=n._meta??{},u={kind:a,name:e,optional:o};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const h=Ke(Me(i.inner));h!=="unknown"&&(u.element=h)}return u},wo=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>mo(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),go="/_lunora/admin/functions",yo="/_lunora/admin/cron-jobs",bo="/_lunora/admin/openapi",_o="/_lunora/admin/openrpc",Ro="/_lunora/admin/global/tables",Eo="/_lunora/admin/global/table",So="/_lunora/admin/global/facet",_t=e=>{if(e===void 0||e==="")return;let t;try{t=Gn(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:i}=o;return[{column:a,value:i}]});return n.length===0?void 0:n},Ao=Object.freeze({info:{description:'No OpenAPI spec is configured on this worker. Run `lunora codegen`, then wire the generated module to `createWorker`: `import { openApiSpec } from "./lunora/_generated/openapi"`.',title:"Lunora API",version:"0.0.0"},openapi:"3.1.0",paths:{}}),To=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"}),Oo=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:a,requireAdminOption:i}=e,u=g=>{j(g,"GET","Functions");const b=i(g,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(b).flatMap(([p,A])=>A.visibility==="internal"||A.kind==="stream"?[]:[{args:wo(A.args),kind:A.kind,path:p}]).toSorted((p,A)=>p.path.localeCompare(A.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},h=g=>{j(g,"GET","Cron-jobs");const b=i(g,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(b).flatMap(([p,A])=>A.map(D=>({args:D.args,cron:p,functionPath:D.functionPath,name:D.name,shardKey:D.shardKey,workflow:D.workflow}))).toSorted((p,A)=>p.name.localeCompare(A.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},f=g=>(j(g,"GET","OpenAPI"),t(g),Response.json(n.openApiSpec??Ao,{headers:{"content-type":"application/json"},status:200})),w=g=>(j(g,"GET","OpenRPC"),t(g),Response.json(n.openRpcSpec??To,{headers:{"content-type":"application/json"},status:200})),E=async g=>{j(g,"GET","Global-tables");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await b.listTables(),{headers:{"content-type":"application/json"},status:200})},O=async g=>{j(g,"GET","Global-table");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),p=a(_,"table");if(p===void 0)throw new d("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const A=await b.readTablePage({...o(g),filters:_t(a(_,"filters")),table:p});return Response.json(A,{headers:{"content-type":"application/json"},status:200})},v=async g=>{j(g,"GET","Global-facet");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),p=a(_,"table"),A=a(_,"column");if(p===void 0||A===void 0)throw new d("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const D=a(_,"limit"),M=D===void 0?void 0:Number(D),I=await b.facetColumn({column:A,filters:_t(a(_,"filters")),limit:M!==void 0&&Number.isFinite(M)?M:void 0,table:p});return Response.json(I,{headers:{"content-type":"application/json"},status:200})};return{[yo]:h,[go]:u,[So]:v,[Eo]:O,[Ro]:E,[bo]:f,[_o]:w}},vo="/_lunora/admin/kv/namespaces",ko="/_lunora/admin/kv/keys",Wt="/_lunora/admin/kv/value",Vt=32*1048576,Rt=60,Io=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}),i=(b,_)=>{const p=new URL(b.url),A=p.searchParams.get("namespace")??"",D=p.searchParams.get("key")??"";if(A==="")throw new d(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(D==="")throw new d(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:D,namespace:A}},u=async(b,_)=>{if(!(await b.listNamespaces()).some(A=>A.binding===_))throw new d(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},h=async b=>(j(b,"GET","KV-namespaces"),a({namespaces:await o(b).listNamespaces()})),f=async b=>{j(b,"GET","KV-keys");const _=o(b),p=new URL(b.url),A=p.searchParams.get("namespace")??"";if(A==="")throw new d("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const D=p.searchParams.get("prefix")??void 0,M=p.searchParams.get("cursor")??void 0,I=p.searchParams.get("limit"),F=I===null?void 0:Number.parseInt(I,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 H=F===void 0?void 0:Math.min(F,1e3);return await u(_,A),a(await _.listKeys({cursor:M,limit:H,namespace:A,prefix:D}))},v={DELETE:async b=>{const _=o(b),p=i(b,"DELETE");return await u(_,p.namespace),await _.deleteKey(p),a({deleted:!0})},GET:async b=>{const _=o(b),p=i(b,"GET");return await u(_,p.namespace),a(await _.getValue(p))},PUT:async b=>{const _=o(b),p=await t(b,Vt);if(typeof p.namespace!="string"||p.namespace==="")throw new d("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new d("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new d("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<Rt))throw new d("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const A=Math.floor(Date.now()/1e3)+Rt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<A))throw new d("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(_,p.namespace),await _.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),a({ok:!0})}},g=b=>{const _=v[b.method];if(!_)throw new d("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(b)};return{[vo]:h,[ko]:f,[Wt]:g}},Po="/_lunora/migrate",Do="/_lunora/admin/pitr",No="/_lunora/admin/rank",Uo="/_lunora/admin/rankpage",Co="/_lunora/admin/shard-traffic",Bo=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),xo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Ho=async e=>{const n=await be(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"||!Bo.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}},Lo=async e=>{const n=await be(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}},Mo=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}},Ko=e=>{if(typeof e.table!="string"||e.table.length===0)throw new d("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new d("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new d("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new d("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new d("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},jo=async e=>{const n=await be(e,"Rank page")??{};Ko(n);const o=Mo(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}},$o=async e=>{const n=await be(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}},Fo=async e=>{const n=await Z(e);if(typeof n.functionPath!="string"||!xo.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}},Go=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:a,resolveForwardContext:i,shardDO:u}=e,h=(g,b)=>{if(g.method!=="POST")throw new d(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(g))throw new d("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new d(`${b} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},f=async(g,b)=>{const _=h(g,"Migration"),p=await Ho(g),{headers:A}=await i(g,b),D=await _.orchestrateMigration(u,{args:p.args,defaultShardKey:t,functionPath:p.functionPath,headers:A,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},w=async(g,b)=>{const _=h(g,"Rank"),p=await Lo(g),{headers:A}=await i(g,b),D=await _.orchestrateRank(u,{headers:A,index:p.index,partitionKey:p.partitionKey,rowId:p.rowId,sortValues:p.sortValues,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},E=async(g,b)=>{const _=h(g,"Rank page"),p=await jo(g),{headers:A}=await i(g,b),D=await _.orchestrateRankPage(u,{...p,headers:A});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},O=async(g,b)=>{const _=h(g,"Shard-traffic"),p=await $o(g),{headers:A}=await i(g,b),D=await _.orchestrateShardTraffic(u,{headers:A,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},v=async(g,b)=>{if(j(g,"POST","PITR"),!o(g))throw new d("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const _=await Fo(g),{headers:p}=await i(g,b),A=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:_.args,functionPath:_.functionPath}),headers:p,method:"POST"});return n(u,_.shardKey??t,A)};return{[Po]:f,[Do]:v,[No]:w,[Uo]:E,[Co]:O}},Qo=1,zo=0,Wo=32,Vo=512,Jo=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,qo=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Vo)return;const n=t.split(",");if(!(n.length>Wo)){for(const o of n)if(!Jo.test(o.trim()))return;return t}},Yo=e=>{const t=Mn(e.headers.get("traceparent"));if(t===void 0)return;const n=qo(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},Xo=(e,t={})=>{const n=Yo(e),o=t.trustInbound===!0?n:void 0,a=Te(8),i=o?.traceId??Te(16),u=dr(t.sampling,o===void 0?a:i),h=u.isTraced&&(o===void 0||o.sampled);return{decision:u,ignoredUpstream:n!==void 0&&o===void 0,trace:{sampled:h,spanId:a,traceFlags:h?Qo:zo,traceId:i,...o?.parentSpanId===void 0?{}:{parentSpanId:o.parentSpanId},...o?.traceState===void 0?{}:{traceState:o.traceState}}}},Zo=(e,t)=>{t.traceparent=Ln(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},ea=(e,t)=>{let n;return()=>{if(n===void 0){const o=Fn(e),a=t===void 0?void 0:t.cf;n=Kn($n(o),jn(o,a))}return n}},ta="/_lunora/admin/scheduled",na="/_lunora/admin/scheduled/status",ra="/_lunora/admin/scheduled/ws",oa="/_lunora/admin/scheduled/cancel",aa="/_lunora/admin/scheduled/dead",sa="/_lunora/admin/scheduled/dead/retry",ia="/_lunora/admin/scheduled/dead/cancel",ca=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:a}=e,i=(f,w)=>E=>{if(E.method!=="GET")throw new d(`${w} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return o(E).fetch(new Request(`https://scheduler.internal${f}`,{method:"GET"}))},u=(f,w,E=w)=>async O=>{if(O.method!=="POST")throw new d(`${E} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const v=o(O),g=await O.json().catch(()=>{});if(typeof g?.id!="string"||g.id==="")throw new d(`${w} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return v.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:g.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(f))throw new d("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const w=n();return we(w,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[oa]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[ia]:u("/dead/cancel","Scheduled dead-letter action"),[aa]:i("/dead","Scheduled dead-letter"),[sa]:u("/dead/retry","Scheduled dead-letter action"),[ta]:i("/list","Scheduled-list"),[na]:i("/status","Scheduler-status"),[ra]:h}},da=(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},Et={mtls:e=>da(e,"tlsClientAuth","certVerified")==="SUCCESS"},ua=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(Et,e)?Et[e]:void 0)??(()=>!1),la=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.'))}},ha="/_lunora/admin/vector/indexes",fa="/_lunora/admin/vector/query",pa=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=async i=>{j(i,"GET","Vector-indexes");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async i=>{j(i,"POST","Vector-query");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new d("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const f=await t(i);if(typeof f.name!="string"||f.name==="")throw new d("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof f.text!="string"||f.text==="")throw new d("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(f.topK!==void 0&&(typeof f.topK!="number"||!Number.isInteger(f.topK)||f.topK<1))throw new d("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const w=await u.queryIndex({name:f.name,text:f.text,topK:f.topK});return Response.json(w,{headers:{"content-type":"application/json"},status:200})};return{[ha]:o,[fa]:a}},ma="/_lunora/admin/workflows/instances",wa="/_lunora/admin/workflows/instance",ga="/_lunora/admin/workflows/status",ya={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},ba=e=>e!==null&&Object.hasOwn(ya,e)?e:void 0,St=(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},je=(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},At=()=>{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})},_a=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,o=async(u,h,f)=>{j(u,"GET","Workflows instances"),t(u);const w=n(h);if(!w)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const E=je(f,"name"),O=ba(f.searchParams.get("status"));return Response.json(await w.listInstances({page:St(f,"page"),perPage:St(f,"perPage"),status:O,workflowName:E}))},a=async(u,h,f)=>{j(u,"GET","Workflows instance"),t(u);const w=n(h);return w?Response.json(await w.getInstance({instanceId:je(f,"id"),workflowName:je(f,"name")})):At()},i=async(u,h)=>{j(u,"POST","Workflows status"),t(u);const f=n(h);if(!f)return At();const w=await u.json().catch(()=>{});if(typeof w?.name!="string"||w.name===""||typeof w.id!="string"||w.id==="")throw new d("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:E}=w;if(E!=="pause"&&E!=="resume"&&E!=="terminate")throw new d("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:E,instanceId:w.id,workflowName:w.name}))};return{[wa]:a,[ma]:o,[ga]:i}},Ra={[Wt]:Vt,[Zn]:Xn},Tt="/_lunora/rpc",Ea="/_lunora/rpc-batch",Sa="/_lunora/ws",Ee=(e,t,n)=>({resourceAttributes:ea(e,t),...n===void 0?{}:{waitUntil:n}}),$e=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Ot=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Fe=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}},vt="/_lunora/voice/",Aa="/_lunora/scheduler/dispatch",Ta="/_lunora/admin/cron-jobs/run",Oa="/_lunora/admin/ws-token",va="/_lunora/admin/",ka="/_lunora/migrate",Ia="/_lunora/status",Pa=e=>e.startsWith(va)||e===ka,Da=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}}},Na="/api/auth",Ua="__lunora_admin__:recordAuthEvent",Ca="__lunora_admin__:listPushSubscriptions",Ba=["/sign-in","/sign-up","/callback"],xa=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return Ba.some(a=>o===a||o.startsWith(`${a}/`))},Se=(e,t,n,o)=>{const a=Dn(n),i=a?n.code:"INTERNAL_SERVER_ERROR",u=a?n.status:500,h=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:h,status:u},functionPath:e,ok:!1,...o.fanOut?{fanOut:{failed:0,shards:0,table:o.fanOut.table}}:{},...o.shardKey?{shardKey:o.shardKey}:{}}},Ha=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},kt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,La=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ze=new WeakMap,ce=async(e,t,n,o=ze.get(e))=>{const a={"content-type":"application/json"},i=e.headers.get("authorization"),u=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),f=e.headers.get("x-lunora-mutation-id"),w=e.headers.get("x-lunora-client-id"),E=e.headers.get("x-lunora-client-seq");i&&(a.authorization=i),u&&(a.cookie=u),h&&(a["x-d1-bookmark"]=h),f&&(a["x-lunora-mutation-id"]=f),w&&(a["x-lunora-client-id"]=w),E&&(a["x-lunora-client-seq"]=E);const O=e.headers.get("cf-connecting-ip");if(O&&(a["x-lunora-client-ip"]=O),!n)return{claims:null,headers:a,identity:null,userId:null};const v=await n(e,t,o);if(!v||typeof v.userId!="string"||v.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=xn(v.userId);const g=Ha(v);g!==void 0&&(a["x-lunora-identity-exp"]=String(g));const{userId:b,..._}=v,p=Object.keys(_).length>0?_:null;return p&&(a["x-lunora-identity"]=Hn(p)),{claims:p,headers:a,identity:v,userId:b}},Ma=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Ka=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"||!Ma.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},ja=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},Ge=(e,t)=>{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}},$a=async e=>{const t=await Bt(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&&Ct(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,i=Ka(a.fanOut),u=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==i.table)throw new d("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},Ae=new Map,Fa=5e3,Ga=4096,Qa=async(e,t)=>{const n=Date.now(),o=Ae.get(t);if(o!==void 0&&o.expiresMs>n)return o.relayCount;o!==void 0&&Ae.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 Nt(Ae,Ga),Ae.set(t,{expiresMs:n+Fa,relayCount:a}),a},It=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},ye=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),za=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],Wa=(e,t)=>{for(const n of za){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},Pt=(e,t)=>{const n=new Headers(e.headers),o=[...n.keys()];for(const a of o)a.startsWith("x-lunora-")&&n.delete(a);return Wa(n,t),n},Va=async(e,t,n)=>e.length===0||n.length===0?!1:Je(await Mt(e,t),n),Dt=(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:Je(t,a.join(" ").trim())},Ja=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 Ur(t,o)?!0:n?!1:Je(t,o)},qa=(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 sr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return Be(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return Be(`queue:${e}`,!0);if(typeof n.connectionString=="string")return Be(`hyperdrive:${e}`,!0)},Jt=e=>{const t=ua(e.trustInboundTraceContext),n=la(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",a=ir(e.resolveIdentity,e.identity),i=it(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:it(e.schedulerDO,e.jurisdiction);let h=!1;const f=r=>{if(r===void 0||e.jurisdiction===void 0)return r;h||(h=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},w=async(r,s,l,c=e.shardRegion?.(s))=>we(r,s,f(c)).fetch(l);let E;const O=()=>e.adminToken??E;let v;const g=()=>e.requireEphemeralWsToken??v??!0;let b;const _=r=>{const s=r??{};if(b??=It(r,e.shardDO),v===void 0&&e.requireEphemeralWsToken===void 0){const c=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(v=Pr(c,!0))}if(E!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(E=l)},p=new WeakSet,A=r=>Dt(r,O())||p.has(r),D=async(r,s)=>{const l=await ce(r,s,e.resolveIdentity);if(p.has(r)&&l.headers.authorization===void 0){const c=O();c!==void 0&&(l.headers.authorization=`Bearer ${c}`)}return l};let M=!1,I=!1;const F=()=>{I||(I=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},H=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})}M||(M=!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("")))},Y=async(r,s)=>{if(e.authorizeShard){if(!await e.authorizeShard({identity:r,shardKey:s}))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==o&&H("shard")},U=Go({defaultShard:o,forwardToShard:w,isAdmin:A,queryCoordinator:e.queryCoordinator,resolveForwardContext:D,shardDO:i}),G=async(r,s,l,c,m)=>{const R={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(R["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(R["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(R["x-lunora-mutation-id"]=c),w(i,l,ye(r,s,R))},Q=async(r,s,l,c)=>{const m=l?.[r];if(!m||typeof m.create!="function")throw new d(`${c} targets workflow binding "${r}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(fr(s))throw new d(`${c} params ${pr}`,{code:"BAD_REQUEST",status:400});await m.create({params:s})},J=async(r,s)=>{if(r.workflow){await Q(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 l=await G(r.functionPath,r.args??{},r.shardKey??o);if(!l.ok)throw new d(`cron job "${r.name}" (${r.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},K=r=>{if(!A(r))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},$=(r,s,l)=>{if(K(r),s===void 0)throw new d(l.message,{code:l.code,status:400});return s},oe=async(r,s,l,c)=>{const m=e.cronJobs?.[r];if(m)for(const R of m)try{await J(R,s)}catch(k){l.push(c(k))}},z=async(r,s)=>{if(K(r),j(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 l=await Z(r),c=typeof l.name=="string"?l.name:"";if(c==="")throw new d("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(R=>R.name===c);if(!m)throw new d(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await J(m,s),Response.json({name:c,ran:!0},{status:200})},de=async r=>{const s=typeof r.pool=="string"&&r.pool.length>0?r.pool:void 0;if(!s||!u||typeof r.id!="string")return;const l=typeof r.instanceName=="string"&&r.instanceName.length>0?r.instanceName:"default";try{await we(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:r.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},ue=async(r,s)=>{j(r,"POST","Scheduler dispatch");const l=await Bt(r),c=s??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,R=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),k=r.headers.get("x-lunora-scheduler-signature");let y=!1;if(k&&m?y=await Va(m,l,k):R&&(y=Dt(r,R)),!y)throw new d("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let S;try{S=JSON.parse(l)}catch{throw new d("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const T=S??{},B=T.args??{};if(typeof T.workflow=="string"&&T.workflow.length>0)return await Q(T.workflow,B,s,"scheduled workflow"),await de(T),Response.json({ok:!0},{status:200});if(typeof T.functionPath!="string"||T.functionPath.length===0)throw new d("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const x=typeof T.shardKey=="string"&&T.shardKey.length>0?T.shardKey:o,C=typeof T.id=="string"&&T.id.length>0?T.id:void 0,te=Da(r),L=await G(T.functionPath,B,x,C,te);return await de(T),L},_e=Lr({assertAdmin:K,getReader:()=>e.authAuditReader}),Oe=async(r,s)=>{K(r);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:Qe({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const c=s?.kind,m=s?.userId,R=s?.limit,k=c==="fcm"||c==="web-push"?c:void 0,y=typeof m=="string"&&m!==""?m:void 0,S=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,T=S>0?Math.min(S,1e3):1e3,x=(await l.list({kind:k,limit:T,userId:y})).filter(C=>k!==void 0&&C.kind!==k?!1:y===void 0||(C.userId??null)===y).map(({keys:C,token:te,...L})=>L);return Response.json({result:Qe({subscriptions:x})},{headers:{"content-type":"application/json"},status:200})},ve=async(r,s)=>{if(!s.fanOut){if(s.functionPath===Hr)return _e(r,s.args??{});if(s.functionPath===Ca)return Oe(r,s.args)}},ae=co({applyGlobals:e.applyGlobals,assertAdmin:K,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:o,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:$,resolveForwardContext:D,shardDO:i,streamExportRows:(r,s,l,c)=>Gt(e,r,s,l,c,i),streamingImport:(r,s)=>po(r,e,s,i),syncGlobals:e.syncGlobals}),ke=(r,s)=>{const l=r.searchParams.get(s);return l===null||l===""?void 0:l},Ie=r=>{const s=new URL(r.url),l=s.searchParams.get("limit"),c=s.searchParams.get("offset"),m=l===null?void 0:Number.parseInt(l,10),R=c===null?void 0:Number.parseInt(c,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},Xe=()=>{if(u===void 0)throw new d("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},qt=ca({checkWsAdmin:async r=>A(r)||Ja(r,O(),g()),requireSchedulerNamespace:Xe,resolveSchedulerStub:r=>(K(r),we(Xe(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Yt=_a({assertAdmin:K,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Xt=Yn({assertAdmin:K,parsePaging:Ie,queryParameter:ke,readBodyBytes:zn,requireAdminOption:$,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Zt=Yr({options:e,readJsonBody:Z,requireAdminOption:$}),en=pa({readJsonBody:Z,requireAdminOption:$,vectorIntrospector:e.vectorIntrospector}),tn=Io({kvIntrospector:e.kvIntrospector,readJsonBody:Z,requireAdminOption:$}),nn=cr({logArchive:e.logArchive,readJsonBody:Z,requireAdminOption:$}),rn=Oo({assertAdmin:K,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ie,queryParameter:ke,requireAdminOption:$}),on=r=>{const s=[],l=i??r?.SHARD;if(l!==void 0&&s.push(ar("durable-object:default",l,o)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(r??{})){const R=qa(c,m);R!==void 0&&s.push(R)}for(const c of e.health?.probes??[])s.push(c);return s},an=or({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:A,resolveProbes:on}),sn=r=>{const s=e.schedulerInstanceName??"default",l=()=>we(r,s),c=async(y,S)=>{const T=await l().fetch(new Request(`https://scheduler.internal${y}`,S));if(!T.ok)throw new d(`ctx.scheduler: SchedulerDO ${y} failed (${String(T.status)}): ${await T.text()}`,{code:"INTERNAL",status:500});return await T.json()},m=async(y,S)=>await c(y,{body:JSON.stringify(S),headers:{"content-type":"application/json"},method:"POST"}),R=y=>{const S=y;if(S==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 S.binding=="string"&&S.binding.length>0)return{workflow:S.binding};if(typeof S.__lunoraRef=="string")return{functionPath:S.__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(y,S,T={})=>{const{id:B}=await m("/schedule",{args:T,scheduledFor:y,...R(S)});return B};return{cancel:async y=>await m("/cancel",{id:y}),get:async y=>await c(`/get?id=${encodeURIComponent(y)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(y,S,T)=>{if(!Number.isFinite(y)||y<0)throw new d("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await k(Date.now()+y,S,T)},runAt:async(y,S,T)=>{if(!Number.isFinite(y))throw new d("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await k(y,S,T)}}},cn=async(r,s,l)=>{const{claims:c,headers:m,userId:R}=await ce(r,s,a),k=async(y,S={})=>{const T=y.__lunoraRef;if(typeof T!="string")throw new d("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const B=ye(T,S,{...m,"x-lunora-system":"1"}),x=await w(i,o,B),C=await x.json();if(C.error)throw new d(C.error.message??"shard RPC failed",{code:C.error.code??"INTERNAL",status:x.status});return C.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:R},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),runAction:k,runMutation:k,runQuery:k,...u===void 0?{}:{scheduler:sn(u)},...e.storage===void 0?{}:{storage:hr(e.storage(s))}}},dn=async(r,s,l)=>{if(!e.httpRouter)return;const c=await cn(r,s,l);try{return await e.httpRouter.fetch(r,{...s,__lunoraCtx:c},l)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},un=async(r,s,l)=>{if(r.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=dt(r,se);if(c)return c;const m=l.searchParams.get("shard")??o,{headers:R,identity:k}=await ce(r,s,a);await Y(k,m);const y=Pt(r,R),S=It(s,e.shardDO);if(S!==void 0){y.set("x-lunora-shard-binding",S);const T=await Qa(i,m);if(T>0){const B=Tr(m,Math.floor(Math.random()*T));return w(i,B,new Request(r,{headers:y}),ut(r))}}return w(i,m,new Request(r,{headers:y}))},ln=async(r,s,l)=>{const{voiceAgents:c}=e;if(c===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 m=dt(r,se);if(m)return m;let R;try{R=decodeURIComponent(l.pathname.slice(vt.length))}catch{return new Response("Unknown voice agent",{status:404})}const k=Object.hasOwn(c,R)?c[R]:void 0;if(k===void 0)return new Response("Unknown voice agent",{status:404});const y=l.searchParams.get("threadKey");if(y===null||y.length===0)return new Response("Missing threadKey",{status:400});const{headers:S,identity:T}=await ce(r,s,a);if(e.authorizeShard){if(!await e.authorizeShard({identity:T,shardKey:y}))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else H("shard");const B=Pt(r,S);return w(k,y,new Request(r,{headers:B}))},hn=async(r,s,l)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(l,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});H("fan-out")},Re=async(r,s)=>{if(!(!r.fanOut&&r.functionPath.startsWith("__lunora_admin__:"))){if(r.fanOut){await hn(r.fanOut,r.functionPath,s);return}await Y(s,r.shardKey??o)}},fn=(r,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){F();return}if(e.functions[s]?.kind!=="query"||l.includes(jt)||l.includes(Kt))return;const c=ut(r);return c===void 0?void 0:{name:Or(l,c),region:c}},pn=async(r,s,l,c,m)=>{const R=fn(r,s,c);if(R!==void 0){const k={...m,"x-lunora-replica-read":"1",...b===void 0?{}:{"x-lunora-shard-binding":b}},y=vr(r.headers.get("x-lunora-min-seq"));y!==void 0&&(k["x-lunora-min-seq"]=String(y));const S=await w(i,R.name,ye(s,l,k),R.region);if(S.status!==421)return S}return w(i,c,ye(s,l,m))},Pe=async(r,s,l,c,m,R)=>{const k=Date.now(),{observability:y,sampling:S}=e,T=Fe(r),{decision:B,ignoredUpstream:x,trace:C}=Xo(r,{...S===void 0?{}:{sampling:S},trustInbound:t(r)});x&&n();const te={...m,"x-lunora-sample-errors":B.keepErrors?"1":"0"};Zo(C,te);try{const L=await pn(r,s,l,c,te);ie(y,{...T,...Ot(C),durationMs:Date.now()-k,functionPath:s,ok:L.ok,shardKey:c,...L.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(L.status)}`,status:L.status}}},R,void 0,{isTraced:C.sampled,keepErrors:B.keepErrors});const ee=new Response(L.body,{headers:L.headers,status:L.status,statusText:L.statusText});return ee.headers.set("x-lunora-shard-key",c),ee}catch(L){throw ie(y,{...T,...Ot(C),...Se(s,Date.now()-k,L,{shardKey:c})},R,void 0,{isTraced:C.sampled,keepErrors:B.keepErrors}),L}},mn=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&&r.functionPath.startsWith("__lunora_relation__:"))throw new d("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(r.fanOut&&!e.queryCoordinator)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},wn=async(r,s,l)=>{j(r,"POST","RPC");const c=await $a(r);ja(s,c),mn(c);const m=await ve(r,c);if(m!==void 0)return m;const{headers:R,identity:k}=await ce(r,s,a);await Re(c,k);const y=Ge(c,e);{const S=Date.now(),{observability:T}=e,B=Fe(r),x=Ee(s,r,l&&(L=>l.waitUntil?.(L)));if(c.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 ee=await L.fanOut(i,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:R});return ie(T,{durationMs:Date.now()-S,fanOut:{failed:ee.failed,shards:ee.ok+ee.failed,table:c.fanOut.table},functionPath:c.functionPath,...B,ok:!0},x),Response.json(ee,{headers:{"content-type":"application/json"},status:200})}catch(ee){throw ie(T,{...Se(c.functionPath,Date.now()-S,ee,{fanOut:{table:c.fanOut.table}}),...B},x),ee}}const C=c.shardKey??o,te=()=>Pe(r,c.functionPath,c.args??{},C,R,x);return y&&e.x402Charge?e.x402Charge(r,{functionPath:c.functionPath,price:y.price},te,$e(l)):te()}},gn=async(r,s,l)=>{j(r,"POST","RPC batch");const c=await Z(r),{calls:m}=c;if(!Array.isArray(m))throw new d("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:k}=await ce(r,s,a),y=Zr(m,o);for(const W of y.values())for(const V of W)if(e.functions?.[V.functionPath]?.x402)throw new d(`paid (\`.x402\`) function "${V.functionPath}" cannot be called in a batch; dispatch it individually over ${Tt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...y.entries()].flatMap(([W,V])=>V.map(ne=>Re({args:ne.args,functionPath:ne.functionPath,shardKey:W},k))));const{observability:S}=e,T=Ee(s,r,l&&(W=>l.waitUntil?.(W))),B=Fe(r),x=[],C=[],te=(W,V,ne,le)=>({body:{error:{code:ne,message:le}},id:W.id,status:V}),L=(W,V,ne,le,fe)=>{for(const q of W)ie(S,fe(q),T),x.push(te(q,V,ne,le))},ee=(W,V,ne,le,fe)=>{for(const q of W){const pe=le.get(q.id)??fe,ge=pe<400;ie(S,{durationMs:ne,functionPath:q.functionPath,...B,ok:ge,shardKey:V,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},T)}};await Promise.all([...y.entries()].map(async([W,V])=>{const ne=new Headers(R);ne.set("content-type","application/json");const le=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:V}),headers:ne,method:"POST"}),fe=Date.now();let q;try{q=await w(i,W,le)}catch(X){const Ce=Date.now()-fe,{body:rt}=Nn(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});L(V,502,rt.code,rt.message,Pn=>({...Se(Pn.functionPath,Ce,X,{shardKey:W}),...B}));return}const pe=Date.now()-fe,ge=q.headers.get("x-d1-bookmark");ge&&C.push(ge);let Ne;try{Ne=await q.json()}catch{const X=`shard batch returned a non-JSON response (${String(q.status)})`;L(V,q.status,"SHARD_ERROR",X,Ce=>({durationMs:pe,error:{code:"SHARD_ERROR",message:X,status:q.status},functionPath:Ce.functionPath,...B,ok:!1,shardKey:W}));return}const Ue=Array.isArray(Ne.results)?Ne.results:[],kn=new Map(Ue.map(X=>[X.id,X.status??q.status])),In=new Set(Ue.map(X=>X.id));ee(V,W,pe,kn,q.status),x.push(...Ue);for(const X of V)In.has(X.id)||x.push(te(X,q.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const tt={"content-type":"application/json"},[nt]=C;return C.length===1&&nt!==void 0&&(tt["x-d1-bookmark"]=nt),Response.json({results:x},{headers:tt,status:200})},yn=async(r,s,l,c={},m={})=>{try{const R=l.__lunoraRef;if(typeof R!="string")throw new d("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:k,identity:y}=await ce(r,s,a,m.context),S={args:c,functionPath:R,shardKey:m.shardKey};await Re(S,y);const T=m.shardKey??o,B=Ee(s,r,m.waitUntil),x=()=>Pe(r,R,c,T,k,B),C=Ge(S,e);return C&&e.x402Charge?await e.x402Charge(r,{functionPath:R,price:C.price},x,$e(m.waitUntil?{waitUntil:m.waitUntil}:m.context)):await x()}catch(R){return ot(R)}},Ze=async(r,s,l)=>{const{observability:c}=e,m=Date.now(),R=Te(16),k=Te(8),y=kt(s);try{const S=await l();return ie(c,{durationMs:Date.now()-m,functionPath:r,ok:!0,spanId:k,traceId:R},y),S}catch(S){throw ie(c,{...Se(r,Date.now()-m,S,{}),spanId:k,traceId:R},y),S}finally{st(c,y)}},bn=async(r,s,l)=>{_(s);const c=[],m=y=>y instanceof Error?y:new Error(String(y)),R=e.crons?.[r.cron];if(R)try{await R(r,s,l)}catch(y){c.push(m(y))}if(await oe(r.cron,s,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===r.cron)try{await Wr(e,i,O(),r)}catch(y){c.push(m(y))}const[k]=c;if(c.length===1&&k)throw k;if(c.length>1)throw new AggregateError(c,`scheduled("${r.cron}") had ${String(c.length)} failure(s)`)},_n=async(r,s)=>{try{const l=r??{},c=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await w(i,o,ye(Ua,{outcome:s},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},Rn=async(r,s,l,c)=>{if(!e.authHandler)return;const m=await e.authHandler(r);if(!m)return;const R=e.authBasePath??Na;return xa(l.pathname,R)&&c.waitUntil?.(_n(s,m.status>=400?"fail":"ok")),m},En=async({args:r,env:s,functionPath:l,request:c,shardKey:m,waitUntil:R})=>{Ct(r,"REST");const k={functionPath:l,...m===void 0?{}:{shardKey:m}},{headers:y,identity:S}=await ce(c,s,a);await Re(k,S);const T=m??o,B=Ee(s,c,R),x=()=>Pe(c,l,r,T,y,B),C=Ge(k,e);return C&&e.x402Charge?e.x402Charge(c,{functionPath:l,price:C.price},x,$e({waitUntil:R})):x()},Sn=Qn({functions:e.functions??{},invoke:En,readJsonBody:Z,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),De=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,An={[Ia]: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"}}),[Sa]:(r,s,l)=>un(r,s,l),[Tt]:(r,s,l,c)=>wn(r,s,c),[Ea]:(r,s,l,c)=>gn(r,s,c),[Aa]:(r,s)=>ue(r,s),[Ta]:(r,s)=>z(r,s),[Oa]:async r=>{j(r,"POST","ws-token"),K(r);const s=O();if(s===void 0)throw new d("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Nr(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...U,...ae,...qt,...Yt,...Xt,...Zt,...en,...tn,...nn,...rn,...an,...Sn,...xr({assertAdmin:K,getAuthAdmin:()=>e.authAdmin,parsePaging:Ie,queryParameter:ke,readJsonBody:Z})};let se=ct(e.security),et=!1;const Tn=r=>{et||(et=!0,se=ct(e.security,r??{}))},On=async(r,s)=>{if(!(e.adminGate===void 0||!Pa(s)))try{await e.adminGate(r,ze.get(r))&&p.add(r)}catch{}},vn=async(r,s,l)=>{ze.set(r,l);const c=new URL(r.url);if(r.method==="POST"||r.method==="PUT"){const y=Number(r.headers.get("content-length")??""),S=Ra[c.pathname]??Ut;if(Number.isFinite(y)&&y>S)throw new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await Rn(r,s,c,l);if(m)return m;if(De){const y=`${r.method} ${c.pathname}`,S=De[y]??De[c.pathname];if(S)return S(r,s,l)}const R=An[c.pathname];if(R)return await On(r,c.pathname),R(r,s,c,l);if(e.voiceAgents!==void 0&&c.pathname.startsWith(vt))return ln(r,s,c);const k=await dn(r,s,l);return k||new Response("Not found",{status:404})};return{async fetch(r,s,l){e.passThroughOnException&&l.passThroughOnException?.(),Tn(s),_(s);const c=ur(r,se);if(c)return c;const m=lr(r,se);if(m)return xe(m,r,se);try{const R=await vn(r,s,l);return xe(R,r,se)}catch(R){return xe(ot(R),r,se)}finally{st(e.observability,kt(l))}},async queue(r,s,l){await Ze(`queue:${La(r)}`,l,async()=>{await e.queue?.(r,s,l)})},async scheduled(r,s,l){await Ze(`cron:${r.cron}`,l,async()=>{await bn(r,s,l)})},serverQuery:yn}},Ya=e=>Jt(e),Xa=e=>typeof e=="function"?{fetch:e}:e,Za=e=>!!(e.crons??e.cronJobs??e.backupCron),Rs=(e,t)=>{const n=Xa(e),o=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=u=>{const h=Ya({...u,httpRouter:n});return o!==void 0&&!Za(u)?{...h,scheduled:async(f,w,E)=>{await o(f,w,E)}}:h};if(typeof t!="function")return a(t);const i=t;return{fetch:(u,h,f)=>a(i(h)).fetch(u,h,f),queue:(u,h,f)=>a(i(h)).queue?.(u,h,f)??Promise.resolve(),scheduled:(u,h,f)=>a(i(h)).scheduled(u,h,f),serverQuery:(u,h,f,w,E)=>a(i(h)).serverQuery(u,h,f,w,E)}},es=(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}},Es=(e={})=>(t,n,o)=>Jt(es(e,n)).fetch(t,n,o??Un),Ss=e=>e;export{Hr as GET_AUTH_AUDIT_LOG_OP,Un as NOOP_EXECUTION_CONTEXT,Os as composeIdentityResolvers,Ya as composeWorker,Es as createLunoraHandler,Jt as createWorker,Ss as defineRpcEnvelope,Qa as probeRelayCount,es as resolveLunoraOptions,vs as routeIdentityResolvers,Rs as withFrameworkWorker};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as c,a as u}from"./identity-header-C4Z5pldl.mjs";import{d as f}from"./wire-codec-
|
|
1
|
+
import{e as c,a as u}from"./identity-header-C4Z5pldl.mjs";import{d as f}from"./wire-codec-CMVqBlcF.mjs";import{LunoraError as s}from"./LunoraError-DksAgIpa.mjs";const l="/_lunora/rpc",h=e=>{const a={"content-type":"application/json"};return e.userId!==void 0&&e.userId.length>0&&(a["x-lunora-userid"]=c(e.userId)),e.identity!==void 0&&(a["x-lunora-identity"]=u(e.identity)),a},d=async(e,a,o)=>{const t=await(e.fetch??globalThis.fetch)(new Request(`${e.origin}${l}`,{body:JSON.stringify(a),headers:h(e),method:"POST"}));if(!t.ok)throw new s(`cross-shard relation ${o} failed: worker returned ${String(t.status)}`);const r=await t.json();if(typeof r.failed=="number"&&r.failed>0){const i=(typeof r.ok=="number"?r.ok:0)+r.failed;throw new s(`cross-shard relation ${o} failed on ${String(r.failed)} of ${String(i)} shard(s) — refusing to return a partial result`)}return f(r.data)},_=e=>({crossShardCounter:async(n,t)=>{const r=await d(e,{args:{table:n,where:t},fanOut:{merge:{kind:"sum"},table:n},functionPath:"__lunora_relation__:count"},"count");return typeof r=="number"?r:0},crossShardReader:async(n,t)=>{const r=await d(e,{args:{...t,table:n},fanOut:{merge:{kind:"concat"},table:n},functionPath:"__lunora_relation__:read"},"read");return{continueCursor:null,isDone:!0,page:Array.isArray(r)?r:[]}}});export{_ as createCrossShardRelationCapabilities};
|
package/dist/packem_shared/{createKvCursorStore-DI7FWQ1f.mjs → createKvCursorStore-dBxlYrXY.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as o,a as s,d as t,r as i,b as n,s as p,w as S}from"./export-tap-
|
|
1
|
+
import{c as o,a as s,d as t,r as i,b as n,s as p,w as S}from"./export-tap-CGR3Xd9F.mjs";import"./portable-json-DpqTEd22.mjs";export{o as createKvCursorStore,s as createMemoryCursorStore,t as defineExportSink,i as r2Sink,n as runExportTap,p as sanitizeChange,S as webhookExportSink};
|
package/dist/packem_shared/{createShardClient-0Tz9JwbX.mjs → createShardClient-DoKTlCKb.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as n}from"@lunora/errors";import{e as S,a as w}from"./identity-header-C4Z5pldl.mjs";import{e as g,d as f}from"./wire-codec-
|
|
1
|
+
import{LunoraError as n}from"@lunora/errors";import{e as S,a as w}from"./identity-header-C4Z5pldl.mjs";import{e as g,d as f}from"./wire-codec-CMVqBlcF.mjs";import{applyJurisdiction as p,resolveShard as N}from"./applyJurisdiction-C0ddU7Tg.mjs";const I=e=>{if(typeof e=="string")return e;const t=e?.__lunoraRef;if(typeof t!="string"||t.length===0)throw new n("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return t},x=e=>{const t=new n(e.code,e.message);return e.data!==void 0&&(t.data=f(e.data)),t},$=(e,t={})=>{const l=p(e,t.jurisdiction),m=t.system??!0,c=r=>$(e,{...t,...r});return{as:r=>c({as:r}),asSystem:()=>c({as:void 0}),call:async(r,y,o)=>{const d=I(r),h=o?.shardKey??t.shardKey;if(h===void 0||h.length===0)throw new n("INTERNAL",`createShardClient: no shard key for "${d}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const s={"content-type":"application/json"};m&&(s["x-lunora-system"]="1"),t.as&&(s["x-lunora-userid"]=S(t.as.userId),t.as.claims&&(s["x-lunora-identity"]=w(t.as.claims))),o?.mutationId!==void 0&&o.mutationId.length>0&&(s["x-lunora-mutation-id"]=o.mutationId);const a=await N(l,h).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:g(y??{}),functionPath:d}),headers:s,method:"POST"})),u=a.statusText?` ${a.statusText}`:"";let i;try{i=await a.json()}catch{throw new n("INTERNAL",`createShardClient: shard response for "${d}" was not JSON (status ${String(a.status)}${u})`)}if("error"in i)throw x(i.error);if(!a.ok)throw new n("INTERNAL",`createShardClient: shard call "${d}" failed (status ${String(a.status)}${u})`);return f(i.result)},forShard:r=>c({shardKey:r})}};export{$ as createShardClient};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{f as K,t as j}from"./base64-Bl1_r2k1.mjs";import{t as O}from"./portable-json-
|
|
1
|
+
import{f as K,t as j}from"./base64-Bl1_r2k1.mjs";import{t as O}from"./portable-json-DpqTEd22.mjs";const N=new TextEncoder,q=e=>j(N.encode(JSON.stringify(e))),B=e=>{const r={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return r;try{const t=JSON.parse(new TextDecoder().decode(K(e))),o=t.s&&typeof t.s=="object"?t.s:{},s={};for(const[i,n]of Object.entries(o))typeof n=="number"&&Number.isFinite(n)&&(s[i]=n);return{g:typeof t.g=="number"&&Number.isFinite(t.g)?t.g:0,s,v:1}}catch{return r}},P=e=>{const r=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",o=t==="delete"||t==="insert"||t==="update"?t:"upsert",s=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(s===void 0?{}:{_id:s}),op:o,table:r}},M=e=>Math.max(1,Math.min(e??1e3,1e4)),D=(e,r,t)=>{for(const o of r)e.push(P(o));return t!==void 0&&r.length>=t},R=e=>new Promise(r=>{setTimeout(r,e)}),$=e=>{const r=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",o=t==="delete"||t==="insert"||t==="update"?t:"upsert",s=typeof e.id=="string"?e.id:void 0,i=e.doc&&typeof e.doc=="object"?O(e.doc):void 0,n=typeof e.seq=="number"&&Number.isFinite(e.seq)?e.seq:void 0,c=typeof e.ts=="number"&&Number.isFinite(e.ts)?e.ts:void 0;return{op:o,table:r,...i===void 0?{}:{doc:i},...s===void 0?{}:{id:s},...n===void 0?{}:{seq:n},...c===void 0?{}:{ts:c}}},T=async(e,r,t,o,s,i)=>{let n=0;for(;;)try{await e.deliver(r);return}catch(c){if(n>=t)throw c instanceof Error?c:new Error(String(c));const d=Math.min(o*2**n,s);await i(d),n+=1}},I=async e=>{const{coordinator:r,cursorStore:t,defaultShardKey:o,headers:s,initialBackoffMs:i=100,limit:n,maxBackoffMs:c=5e3,maxRetries:d=3,shardDO:S,sink:p,sleep:k=R,tables:C}=e,h=await t.read(p.name),b=await r.orchestrateCdcSync(S,{cursors:h,defaultShardKey:o,headers:s,limit:n,tables:C}),l={...h},m=[];let v=0,f=!1;for(const a of b.shards){if(a.error){m.push({error:a.error.message,shardKey:a.shardKey}),f=!0;continue}const y=a.changes??[];if(y.length===0){l[a.shardKey]=a.cursor;continue}const g=y.map(u=>$(u)),E={changes:g,cursor:a.cursor,shardKey:a.shardKey,sink:p.name};try{await T(p,E,d,i,c,k),l[a.shardKey]=a.cursor,v+=g.length,y.length>=M(n)&&(f=!0)}catch(u){m.push({error:u instanceof Error?u.message:String(u),shardKey:a.shardKey}),f=!0}}return await t.write(p.name,l),{cursors:l,delivered:v,failures:m,hasMore:f,shards:b.shards.length}},x=e=>{if(typeof e.name!="string"||e.name.length===0)throw new Error("defineExportSink: `name` must be a non-empty string");if(typeof e.deliver!="function")throw new TypeError("defineExportSink: `deliver` must be a function");return{deliver:e.deliver,name:e.name}},w=e=>`${e.map(r=>JSON.stringify(r)).join(`
|
|
2
2
|
`)}
|
|
3
3
|
`,J=e=>{const r=e.fetchImpl??((t,o)=>fetch(t,o));return x({deliver:async t=>{const o=await r(e.url,{body:w(t.changes),headers:{"content-type":"application/x-ndjson","x-lunora-cursor":String(t.cursor),"x-lunora-shard":t.shardKey,"x-lunora-sink":t.sink,...e.headers},method:"POST"});if(!o.ok)throw new Error(`webhook export sink "${e.name}" returned ${String(o.status)}`)},name:e.name})},U=e=>{let r=e.prefix??"cdc";for(;r.endsWith("/");)r=r.slice(0,-1);return x({deliver:async t=>{const o=`${r}/${t.shardKey}/${String(t.cursor)}.ndjson`;await e.bucket.put(o,w(t.changes),{httpMetadata:{contentType:"application/x-ndjson"}})},name:e.name})},z=()=>{const e={};return{read:r=>Promise.resolve({...e[r]}),snapshot:()=>structuredClone(e),write:(r,t)=>(e[r]={...t},Promise.resolve())}},W=(e,r)=>{const t=r?.keyPrefix??"__lunora_source_cursor:export",o=s=>`${t}:${s}`;return{read:async s=>{const i=await e.get(o(s),"json");if(i===null||typeof i!="object")return{};const n={};for(const[c,d]of Object.entries(i))typeof d=="number"&&Number.isFinite(d)&&(n[c]=d);return n},write:async(s,i)=>{await e.put(o(s),JSON.stringify(i))}}};export{z as a,I as b,W as c,x as d,B as e,D as f,q as g,M as h,U as r,$ as s,J as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{raw as n,desc as F,sql as r}from"@lunora/bindings/r2sql";const u=["trace","debug","log","info","warn","error","fatal"],T={fields:"fields",functionPath:"functionPath",level:"level",message:"message",shardKey:"shardKey",spanId:"spanId",traceId:"traceId",ts:"ts",userId:"userId"},N=500,w=1e4,_=e=>e===void 0||!Number.isFinite(e)?N:Math.min(Math.max(Math.floor(e),1),w),D=e=>typeof e=="number"?e:Number(e),L=e=>e==null?"":String(e),U=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},S=e=>{const s=JSON.stringify([e.ts,e.level,e.functionPath,e.message,e.traceId,e.spanId,e.shardKey,e.userId,e.fields]);let t=0,l=0;for(const v of s){const I=v.codePointAt(0)??0;t=(t*31+I)%2147483647,l=(l*131+I)%4294967291}return`${t.toString(36)}.${l.toString(36)}`},y=(e,s,t,l)=>{if(s.sinceTs!==void 0&&e.where(r`${n(t.ts)} >= ${s.sinceTs}`),s.untilTs!==void 0&&e.where(r`${n(t.ts)} <= ${s.untilTs}`),s.level!==void 0)e.where(r`${n(t.level)} = ${s.level}`);else if(s.minLevel!==void 0){const v=u.indexOf(s.minLevel),I=v===-1?[...u]:u.slice(v);e.where(r`${n(t.level)} IN ${I}`)}s.functionPath!==void 0&&e.where(r`${n(t.functionPath)} = ${s.functionPath}`),s.functionPathPrefix!==void 0&&e.where(r`${n(t.functionPath)} LIKE ${`${s.functionPathPrefix}%`}`),s.traceId!==void 0&&e.where(r`${n(t.traceId)} = ${s.traceId}`),s.shardKey!==void 0&&e.where(r`${n(t.shardKey)} = ${s.shardKey}`),s.userId!==void 0&&e.where(r`${n(t.userId)} = ${s.userId}`),l!==void 0&&e.where(r`${n(t.ts)} <= ${l}`)},G=T,J=(e,s)=>{const t={...T,...s.columnMap},l=s.namespace===void 0?s.table:`${s.namespace}.${s.table}`,v=a=>{const c={functionPath:L(a[t.functionPath]),level:L(a[t.level]),message:L(a[t.message]),ts:D(a[t.ts])},o=a[t.fields];o!=null&&(c.fields=U(o));for(const d of["shardKey","userId","traceId","spanId"]){const i=a[t[d]];i!=null&&(c[d]=L(i))}return c},I=async(a,c,o)=>{const d=e.from(l).select(n(t.functionPath),n(t.level),n(t.message),n(t.ts),n(t.fields),n(t.shardKey),n(t.userId),n(t.traceId),n(t.spanId));y(d,a,t,c),d.orderBy(F(n(t.ts))).limit(o);const{rows:i}=await d.run();return i},A=async(a,c,o,d)=>{const i=await I(a,c,d),$=[];for(const P of i){const f=v(P);o!==void 0&&c!==void 0&&f.ts===c&&o.has(S(f))||$.push(f)}return{decoded:$,truncated:i.length>=d}};return{query:async(a={})=>{const c=_(a.limit),{cursor:o}=a,d=o?.ts,i=o?.seen!==void 0&&o.seen.length>0?new Set(o.seen):void 0,$=Math.min(c+1,w),P=3;let f=[],m=!1;for(let h=0;h<P;h+=1){const K=Math.min($*2**h,w),O=await A(a,d,i,K);if(f=O.decoded,m=O.truncated,f.length>c||!m||K>=w)break}const R=f.length>c,g=R?f.slice(0,c):f,M=g.at(-1);if(M===void 0||!(R||m))return{rows:g};const p=M.ts,E=g.filter(h=>h.ts===p).map(h=>S(h)),x=[...d===p&&o?.seen!==void 0?o.seen:[],...E];return{nextCursor:x.length>0?{seen:x,ts:p}:{ts:p},rows:g}}}};export{G as D,u as L,J as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as i}from"./base64-Bl1_r2k1.mjs";import{d as f,i as s}from"./wire-codec-
|
|
1
|
+
import{a as i}from"./base64-Bl1_r2k1.mjs";import{d as f,i as s}from"./wire-codec-CMVqBlcF.mjs";const o=r=>{if(typeof r=="bigint")return r.toString();if(r instanceof ArrayBuffer)return i(new Uint8Array(r));if(ArrayBuffer.isView(r))return i(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));if(Array.isArray(r))return r.map(t=>o(t));if(s(r)){const t={};for(const e of Object.keys(r)){const n=o(r[e]);e==="__proto__"?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}return t}return r},y=r=>o(f(r));export{y as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as S,d as T,e as O,a as P,f as B}from"./rest-cache-CPSyD1RD.mjs";import{LunoraError as l}from"./LunoraError-DksAgIpa.mjs";import{m as D}from"./method-guard-BG_vJNTl.mjs";const w=1048576,p=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),U=async(t,r=w)=>{if(!t.body)return"";const e=t.body.getReader(),a=new TextDecoder;let s=0,i="";for(;;){const{done:o,value:n}=await e.read();if(o)break;if(n){if(s+=n.byteLength,s>r)throw await e.cancel().catch(()=>{}),new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});i+=a.decode(n,{stream:!0})}}return i+=a.decode(),i},W=async(t,r=w)=>{if(!t.body)return new ArrayBuffer(0);const e=t.body.getReader(),a=[];let s=0;for(;;){const{done:n,value:c}=await e.read();if(n)break;if(c){if(s+=c.byteLength,s>r)throw await e.cancel().catch(()=>{}),new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});a.push(c)}}const i=new Uint8Array(s);let o=0;for(const n of a)i.set(n,o),o+=n.byteLength;return i.buffer},j=async(t,r,e=w)=>{try{const a=await U(t,e);return a===""?{}:JSON.parse(a)}catch(a){throw a instanceof l?a:new l(`${r} body must be valid JSON`,{code:"BAD_REQUEST",status:400})}},I=async(t,r=w)=>{const e=await j(t,"Request",r);if(!p(e))throw new l("Request body must be an object",{code:"BAD_REQUEST",status:400});return e},x=(t,r)=>{if(!p(t))throw new l(`${r} \`args\` must be an object`,{code:"BAD_REQUEST",status:400})},R="__lunora_vary",G="x-lunora-edge-cache",C=["x-d1-bookmark","x-lunora-shard-key"],M=()=>{try{return globalThis.caches?.default}catch{return}},L=t=>t.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r!==""),J=(t,r)=>{const e=t.headers.get("vary");return e===null?!0:L(e).every(a=>a!=="*"&&r.includes(a))},Y=(t,r)=>{if(t===void 0||r===null||t.scope!=="public"||S(t.maxAge)<=0)return;const e=()=>r??M(),a=L(T(t)??""),s=o=>{const n=new URL(o.url);return n.searchParams.delete(R),a.length>0&&n.searchParams.set(R,a.map(c=>`${c}=${o.headers.get(c)??""}`).join("\0")),new Request(n.toString(),{method:"GET"})},i=(o,n)=>o.method==="GET"&&O(t,o,n)==="public";return{lookup:async(o,n)=>{const c=e();if(c===void 0||!i(o,n))return;let u;try{u=await c.match(s(o))}catch{return}if(u===void 0)return;const h=new Response(u.body,u);return h.headers.set(G,"hit"),h},store:(o,n,c)=>{const u=e();if(u===void 0||!i(n,c)||o.status!==200||o.headers.has("set-cookie")||o.headers.has("x-payment-response")||!J(o,a))return o;try{const h=new Response(o.clone().body,o);for(const b of C)h.headers.delete(b);const d=Promise.resolve(u.put(s(n),h)).catch(()=>{});c?.waitUntil&&c.waitUntil(d)}catch{}return o}}},H=t=>B(Object.entries(t).map(([r,e])=>({exposure:e.expose,functionPath:r,kind:e.kind}))),K=(t,r)=>{const e=t.searchParams.get("shardKey");if(e!==null&&e!=="")return e;const a=r.headers.get("x-lunora-shard-key");return a===null||a===""?void 0:a},Q=t=>{const r=Object.create(null);for(const[e,a]of t.searchParams.entries())if(!(e==="shardKey"||e===R))try{r[e]=JSON.parse(a)}catch{r[e]=a}return r},X=t=>{const{edgeCache:r,functions:e,invoke:a,rateLimit:s,readJsonBody:i}=t,o={};for(const n of H(e)){const c=n.kind==="query"?["GET","POST"]:["POST"],u=e[n.functionPath].expose?.cache,h=Y(u,r);o[n.path]=async(d,b,F,f)=>{const g=D(d,c);if(g)return g;const v=new URL(d.url);if(s){const m=await s(d,n.functionPath);if(m)return m}const E=await h?.lookup(d,f);if(E)return E;let y;d.method==="GET"?y=Q(v):y=d.body===null?{}:await i(d),x(y,"REST");const A=K(v,d),_=await a({args:y,env:b,functionPath:n.functionPath,request:d,...A===void 0?{}:{shardKey:A},...f?.waitUntil===void 0?{}:{waitUntil:m=>f.waitUntil?.(m)}}),k=P(_,u,d,f);return h?h.store(k,d,f):k}}return o},z=(t,r)=>async(e,a)=>{const s=r.key?r.key(e,a):e.headers.get("cf-connecting-ip")??void 0,i=await t.limit(r.name,s===void 0?{}:{key:s});if(i.ok)return;const o=Math.max(1,Math.ceil(i.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(o)},status:429})};export{w as M,Q as a,X as b,z as c,
|
|
1
|
+
import{c as S,d as T,e as O,a as P,f as B}from"./rest-cache-CPSyD1RD.mjs";import{LunoraError as l}from"./LunoraError-DksAgIpa.mjs";import{m as D}from"./method-guard-BG_vJNTl.mjs";const w=1048576,p=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),U=async(t,r=w)=>{if(!t.body)return"";const e=t.body.getReader(),a=new TextDecoder;let s=0,i="";for(;;){const{done:o,value:n}=await e.read();if(o)break;if(n){if(s+=n.byteLength,s>r)throw await e.cancel().catch(()=>{}),new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});i+=a.decode(n,{stream:!0})}}return i+=a.decode(),i},W=async(t,r=w)=>{if(!t.body)return new ArrayBuffer(0);const e=t.body.getReader(),a=[];let s=0;for(;;){const{done:n,value:c}=await e.read();if(n)break;if(c){if(s+=c.byteLength,s>r)throw await e.cancel().catch(()=>{}),new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});a.push(c)}}const i=new Uint8Array(s);let o=0;for(const n of a)i.set(n,o),o+=n.byteLength;return i.buffer},j=async(t,r,e=w)=>{try{const a=await U(t,e);return a===""?{}:JSON.parse(a)}catch(a){throw a instanceof l?a:new l(`${r} body must be valid JSON`,{code:"BAD_REQUEST",status:400})}},I=async(t,r=w)=>{const e=await j(t,"Request",r);if(!p(e))throw new l("Request body must be an object",{code:"BAD_REQUEST",status:400});return e},x=(t,r)=>{if(!p(t))throw new l(`${r} \`args\` must be an object`,{code:"BAD_REQUEST",status:400})},R="__lunora_vary",G="x-lunora-edge-cache",C=["x-d1-bookmark","x-lunora-shard-key"],M=()=>{try{return globalThis.caches?.default}catch{return}},L=t=>t.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r!==""),J=(t,r)=>{const e=t.headers.get("vary");return e===null?!0:L(e).every(a=>a!=="*"&&r.includes(a))},Y=(t,r)=>{if(t===void 0||r===null||t.scope!=="public"||S(t.maxAge)<=0)return;const e=()=>r??M(),a=L(T(t)??""),s=o=>{const n=new URL(o.url);return n.searchParams.delete(R),a.length>0&&n.searchParams.set(R,a.map(c=>`${c}=${o.headers.get(c)??""}`).join("\0")),new Request(n.toString(),{method:"GET"})},i=(o,n)=>o.method==="GET"&&O(t,o,n)==="public";return{lookup:async(o,n)=>{const c=e();if(c===void 0||!i(o,n))return;let u;try{u=await c.match(s(o))}catch{return}if(u===void 0)return;const h=new Response(u.body,u);return h.headers.set(G,"hit"),h},store:(o,n,c)=>{const u=e();if(u===void 0||!i(n,c)||o.status!==200||o.headers.has("set-cookie")||o.headers.has("x-payment-response")||!J(o,a))return o;try{const h=new Response(o.clone().body,o);for(const b of C)h.headers.delete(b);const d=Promise.resolve(u.put(s(n),h)).catch(()=>{});c?.waitUntil&&c.waitUntil(d)}catch{}return o}}},H=t=>B(Object.entries(t).map(([r,e])=>({exposure:e.expose,functionPath:r,kind:e.kind}))),K=(t,r)=>{const e=t.searchParams.get("shardKey");if(e!==null&&e!=="")return e;const a=r.headers.get("x-lunora-shard-key");return a===null||a===""?void 0:a},Q=t=>{const r=Object.create(null);for(const[e,a]of t.searchParams.entries())if(!(e==="shardKey"||e===R))try{r[e]=JSON.parse(a)}catch{r[e]=a}return r},X=t=>{const{edgeCache:r,functions:e,invoke:a,rateLimit:s,readJsonBody:i}=t,o={};for(const n of H(e)){const c=n.kind==="query"?["GET","POST"]:["POST"],u=e[n.functionPath].expose?.cache,h=Y(u,r);o[n.path]=async(d,b,F,f)=>{const g=D(d,c);if(g)return g;const v=new URL(d.url);if(s){const m=await s(d,n.functionPath);if(m)return m}const E=await h?.lookup(d,f);if(E)return E;let y;d.method==="GET"?y=Q(v):y=d.body===null?{}:await i(d),x(y,"REST");const A=K(v,d),_=await a({args:y,env:b,functionPath:n.functionPath,request:d,...A===void 0?{}:{shardKey:A},...f?.waitUntil===void 0?{}:{waitUntil:m=>f.waitUntil?.(m)}}),k=P(_,u,d,f);return h?h.store(k,d,f):k}}return o},z=(t,r)=>async(e,a)=>{const s=r.key?r.key(e,a):e.headers.get("cf-connecting-ip")??void 0,i=await t.limit(r.name,s===void 0?{}:{key:s});if(i.ok)return;const o=Math.max(1,Math.ceil(i.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(o)},status:429})};export{w as M,Q as a,X as b,z as c,I as d,j as e,W as f,x as g,U as h,H as r};
|
package/dist/packem_shared/{toAirbyteMessages-CIjE6Vm1.mjs → toAirbyteMessages-DvYrhqLf.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as b}from"./portable-json-
|
|
1
|
+
import{t as b}from"./portable-json-DpqTEd22.mjs";const p="_id",f=(t,n=p)=>{const o=Object.create(null),s=Object.create(null),c=Object.create(null),a=Object.create(null),h=e=>typeof n=="string"?n:n[e]??p,l=(e,r)=>{const u=e[r];if(u)return u;const d=[];return e[r]=d,d};for(const e of t.changes){a[e.table]??={primary_key:[h(e.table)]};const r=b(e.doc);e.op==="delete"?l(c,e.table).push(r):e.op==="update"?l(s,e.table).push(r):l(o,e.table).push(r)}return{delete:c,hasMore:t.hasMore,insert:o,schema:a,state:{cursor:t.nextCursor},update:s}},m=(t,n=Date.now())=>{const o=[];for(const s of t.changes){const c=b(s.doc),a=s.op==="delete"?{...c,_lunora_deleted:!0}:c;o.push({record:{data:a,emitted_at:n,stream:s.table},type:"RECORD"})}return o.push({state:{data:{cursor:t.nextCursor}},type:"STATE"}),o};export{m as toAirbyteMessages,f as toFivetranResponse};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as w,b as O}from"./base64-Bl1_r2k1.mjs";const o="$lunora.wire$",m=64,A=1024,d="__proto__",p={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},E={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},
|
|
1
|
+
import{a as w,b as O}from"./base64-Bl1_r2k1.mjs";const o="$lunora.wire$",m=64,A=1024,d="__proto__",p={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},E={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},l=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},a=(e,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(e===void 0)return[o,"undefined"];if(e===null)return null;const y=typeof e;if(y==="bigint")return[o,"bigint",e.toString()];if(y==="number"){const r=e;return Number.isNaN(r)?[o,"nan"]:r===1/0?[o,"inf"]:r===-1/0?[o,"-inf"]:r}if(y!=="object")return e;if(e instanceof Date)return[o,"date",a(e.getTime(),t+1)];if(e instanceof Error){const r=e,n={};for(const c of Object.keys(r))r[c]!==void 0&&(n[c]=a(r[c],t+1));const i=[o,"error",r.name,r.message,n];return r.cause!==void 0&&i.push(a(r.cause,t+1)),i}if(e instanceof URL)return[o,"url",e.href];if(e instanceof Map)return[o,"map",[...e.entries()].map(([r,n])=>[a(r,t+1),a(n,t+1)])];if(e instanceof Set)return[o,"set",[...e].map(r=>a(r,t+1))];if(e instanceof ArrayBuffer)return[o,"bytes",w(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,n=r.constructor.name,i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[o,"bytes",w(i)]:[o,"bytes",w(i),n]}if(Array.isArray(e)){const r=e.map(n=>a(n,t+1));return r.length>0&&r[0]===o?[o,"arr",r]:r}if(!l(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const u=e,s={};for(const r of Object.keys(u)){const n=u[r];if(n===void 0)continue;const i=a(n,t+1);r===d?Object.defineProperty(s,r,{configurable:!0,enumerable:!0,value:i,writable:!0}):s[r]=i}return s},f=(e,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===o)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>f(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>A||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${A} digits)`);return BigInt(r)}case"date":return new Date(f(e[2],t+1));case"map":{const r=e[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[f(n[0],t+1),f(n[1],t+1)]}))}case"set":return new Set(e[2].map(r=>f(r,t+1)));case"url":return new URL(e[2]);case"error":{const r=e[2],n=e[3],i=(Object.hasOwn(E,r)?E[r]:void 0)??Error,c=new i(n);c.name!==r&&Object.defineProperty(c,"name",{configurable:!0,value:r,writable:!0});const g=f(e[4],t+1);for(const b of Object.keys(g))b===d?Object.defineProperty(c,b,{configurable:!0,enumerable:!0,value:g[b],writable:!0}):c[b]=g[b];return e.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:f(e[5],t+1),writable:!0}),c}case"bytes":{const r=O(e[2]),n=e[3]??"Uint8Array";if(n==="ArrayBuffer")return r.buffer.byteLength===r.byteLength?r.buffer:r.slice().buffer;const i=Object.hasOwn(p,n)?p[n]:void 0;return i?new i(r.slice().buffer):r}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>f(r,t+1))}return e.map(s=>f(s,t+1))}const y=e,u={};for(const s of Object.keys(y)){const r=f(y[s],t+1);s===d?Object.defineProperty(u,s,{configurable:!0,enumerable:!0,value:r,writable:!0}):u[s]=r}return u};export{f as d,a as e,l as i};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/runtime",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.86",
|
|
4
4
|
"description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,9 +46,9 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
50
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
51
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
49
|
+
"@lunora/bindings": "1.0.0-alpha.44",
|
|
50
|
+
"@lunora/errors": "1.0.0-alpha.27",
|
|
51
|
+
"@lunora/platform": "1.0.0-alpha.23"
|
|
52
52
|
},
|
|
53
53
|
"peerDependencies": {
|
|
54
54
|
"@lunora/shard-engine": ">=1.0.0-alpha.24 <2.0.0-0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{D as a,a as r,c as _}from"./pipeline-log-reader-BGrl66P5.mjs";export{a as DEFAULT_LOG_COLUMNS,r as DEFAULT_LOG_LIMIT,_ as createPipelineLogReader};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./rest-cache-CPSyD1RD.mjs";import{a as t,b as o,c as i,r as m,d as R}from"./rest-routes-Dq17Zntv.mjs";import"./method-guard-BG_vJNTl.mjs";export{t as argsFromQuery,o as buildRestRoutes,i as createRestRateLimit,m as readShardKey,R as restSurfaceFromRegistry};
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as Dn,toErrorBody as Nn}from"@lunora/errors";import{e as Nt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Un}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as Cn,f as Bn}from"./base64-Bl1_r2k1.mjs";import{e as xn,a as Hn}from"./identity-header-C4Z5pldl.mjs";import{o as Te,b as Ln,p as Mn,m as Kn,d as jn,a as $n,r as Fn}from"./otlp-resource-DeXhb949.mjs";import{e as Qe}from"./wire-codec-BsPOEXGn.mjs";import{e as ee,f as be,M as Ut,b as Gn,g as Qn,h as Ct,i as Bt}from"./rest-routes-Dq17Zntv.mjs";import{LunoraError as d,toErrorResponse as ot}from"./LunoraError-DksAgIpa.mjs";import{a as K,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as We,BACKUP_KEY_PREFIX as Ve,isBackupManifestKey as zn,backupObjectKeyOfManifest as xt,backupObjectKey as Wn,backupManifestKey as Vn}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as qn,buildStorageAdminRoutes as Jn,STORAGE_UPLOAD_MAX_BODY_BYTES as Yn,STORAGE_PATH as Xn}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{b as Zn,e as er,f as at,g as tr,h as nr}from"./export-tap-CgiuS5w4.mjs";import{buildHealthRoutes as rr,durableObjectProbe as or,d1Probe as ar,presenceProbe as Be}from"./HEALTH_PATH-jZsuCmSs.mjs";import{wrapResolverWithContract as sr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as As,routeIdentityResolvers as Ts}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as ir}from"./LOG_ARCHIVE_PATH-Btzcg6oL.mjs";import{r as cr,f as st,a as de}from"./observability-vDK-rMbs.mjs";import{resolveShard as we,applyJurisdiction as it}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as ct,handleCorsPreflight as dr,enforceOrigin as ur,decorateResponse as xe,enforceWebSocketOrigin as dt}from"./decorateResponse-BuqVnrmc.mjs";const lr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n={...t,bucketName:"default"};return n.bucket=()=>n,n},Ht="__lunoraBranch",hr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Ht),fr=`may not contain the reserved workflow branch-marker key ("${Ht}")`,qe=(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 i=a<e.length?e.charCodeAt(a):0,u=a<t.length?t.charCodeAt(a):0;o|=i^u}return o===0},pr=(e,t,n,o)=>{const a=e.get(t);if(a!==void 0)return a;Nt(e,o);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},Je=new TextEncoder,mr=Array.from({length:32},(e,t)=>t);new RegExp(`[${mr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const wr=64,gr=new Map,Lt=async e=>pr(gr,e,async()=>crypto.subtle.importKey("raw",Je.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),wr),Mt=async(e,t)=>{const n=await Lt(e),o=await crypto.subtle.sign("HMAC",n,Je.encode(t));return Cn(new Uint8Array(o))},yr=async(e,t,n)=>{const o=await Lt(e);return crypto.subtle.verify("HMAC",o,n,Je.encode(t))},br=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(br);const _r=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Rr=-100,Er=15,Sr=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&_r.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Er?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Rr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},ut=e=>{const t=e.cf;return t===void 0?void 0:Sr(t)},Kt="::relay::",Ar=(e,t)=>`${e}${Kt}${String(t)}`,jt="::replica::",Tr=(e,t)=>`${e}${jt}${t}`,Or=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},vr=new Set(["1","enabled","on","true","yes"]),kr=new Set(["0","disabled","false","no","off"]),Ir=(e,t)=>{const n=(e??"").trim().toLowerCase();return vr.has(n)?!0:kr.has(n)?!1:t},$t="v1",Pr=6e4,Dr=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Pr),o=`${$t}.${String(n)}`,a=await Mt(e,o);return{expiresAtMs:n,token:`${o}.${a}`}},Nr=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,i,u]=o;if(a!==$t||u.length===0)return!1;const h=Number(i);if(!Number.isFinite(h)||h<=n)return!1;let f;try{f=Bn(u)}catch{return!1}return yr(e,`${a}.${i}`,f)},P="/_lunora/admin/auth",Ur={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},he=(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},Ft=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},ae=(e,t)=>typeof e[t]=="string"?e[t]:void 0,He=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},lt=e=>{const t=Ft(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new d("`role` is required",{code:"BAD_REQUEST",status:400});return t},ht=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(i=>typeof i=="string")&&(n[o]=a);return n},Cr={[`${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:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:he(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:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:He(e,"data"),email:N(e,"email"),name:N(e,"name"),password:ae(e,"password"),role:Ft(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:lt(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:ae(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:ae(e,"logo"),metadata:He(e,"metadata"),name:N(e,"name"),ownerId:ae(e,"ownerId"),slug:ae(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:ae(e,"logo"),metadata:He(e,"metadata"),name:ae(e,"name"),organizationId:N(e,"organizationId"),slug:ae(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:ae(e,"role"),userId:N(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:N(e,"email"),inviterId:ae(e,"inviterId"),organizationId:N(e,"organizationId"),role:ae(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:N(e,"memberId"),role:lt(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:ht(e),role:N(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:ht(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"}},Br=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof d)throw i;const u=i,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new d("auth admin operation failed",{code:h,status:Ur[h]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new d(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new d("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[i.method];if(h===void 0)throw new d(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(a.url),w={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:v=>e.queryParameter(f,v)},E=i.build(w),O=await t(()=>h(E));return Response.json(i.returns==="void"?{ok:!0}:O,{headers:{"content-type":"application/json"},status:200})},o={};for(const[a,i]of Object.entries(Cr))o[a]=u=>n(u,i);return o},xr="__lunora_admin__:getAuthAuditLog",ft=e=>typeof e=="string"&&e!==""?e:void 0,pt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Hr=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 i=ft(o.actorId),u=ft(o.event),h=pt(o.sinceSeq),f=pt(o.limit),w={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...f===void 0?{}:{limit:f}};let E;try{E=await a.read(w)}catch(v){throw v instanceof d?v:(console.error("[lunora] auth audit read failed:",v),new d("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const O={entries:E};return Response.json({result:Qe(O)},{headers:{"content-type":"application/json"},status:200})},Lr=(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}},Mr=async(e,t,n,o,a,i,u)=>{if(n!==void 0&&o.length===0)return;const h=await e.orchestrateExport(i,{args:{tables:o},defaultShardKey:u,headers:t,tables:o});for(const f of h.shards)if(!f.error)for(const w of f.rows??[])a(w)},Gt=async(e,t,n,o,a,i)=>{const u=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:h,shardLocalTables:f}=Lr(e,u);await Mr(t,n,u,f,a,i,e.defaultShardKey??"__root__");const w=e.exportGlobals;if((o===void 0||h.length>0)&&w)for await(const O of w({tables:h}))a(O)},Kr=new TextEncoder,jr=1e3,Qt=10,$r=200,mt=8,zt="lunoraBackupCron",wt=24*1048576,gt=e=>{const t=e.slice(0,Qt).map(o=>xt(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Fr=(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},Ye=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let u=0;u<jr;u+=1){const h=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const f of h.objects)zn(f.key)&&f.customMetadata?.[zt]===o&&a.push(f.key);if(!h.truncated||h.cursor===void 0)break;i=h.cursor}return{eligible:a.length,stale:a.toSorted((u,h)=>h.localeCompare(u)).slice(n)}},Gr=async(e,t,n,o,a)=>{const{stale:i}=await Ye(e,t,n,o),u=new Set(a),h=i.filter(g=>u.has(g)),f=h.slice(0,$r),w=i.length-f.length,E=a.length-h.length;if(f.length===0)return{deleted:[],failed:[],ignored:E,remaining:w};const O=[],v=[];for(let g=0;g<f.length;g+=mt){const b=await Promise.allSettled(f.slice(g,g+mt).map(async _=>(await e.delete(xt(_)),await e.delete(_),_)));for(const[_,p]of b.entries())p.status==="fulfilled"?O.push(p.value):v.push(f[g+_])}return O.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(O.length)}: ${gt(O)}`),v.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(v.length)}: ${gt(v)}`),{deleted:O,failed:v,ignored:E,remaining:w}},Qr=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=We(e.backupPrefix??Ve),o=e.backupCron,{eligible:a,stale:i}=o===void 0?{eligible:0,stale:[]}:await Ye(t,n,e.backupRetain,o);return{cron:o,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},zr=async(e,t,n,o)=>{const a=e.backupStore,i=e.queryCoordinator;if(!a)throw new d("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!i)throw new d("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!n||n.length===0)throw new d("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const u={authorization:`Bearer ${n}`,"content-type":"application/json"},h=e.backupTables;let f=0,w=0,E=[];await Gt(e,i,u,h,D=>{const M=Kr.encode(`${JSON.stringify(D)}
|
|
2
|
-
`);if(f+=1,w+=M.byteLength,w>wt)throw new d(`scheduled backup reached ${String(w)} bytes of NDJSON, past the ${String(wt)}-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(M)},t);const v=We(e.backupPrefix??Ve),g=new Date(o.scheduledTime).toISOString(),b=Wn(v,g),_=Fr(E,w);E=[];const p=qn(await crypto.subtle.digest("SHA-256",_));await a.put(b,_,{httpMetadata:{contentType:"application/x-ndjson"},sha256:p});const A={bytes:w,createdAt:g,cron:o.cron,file:b,id:g,rows:f,scheduledTime:o.scheduledTime,sha256:p,...h?{tables:h.join(",")}:{}};await a.put(Vn(b),`${JSON.stringify(A,void 0,2)}
|
|
3
|
-
`,{customMetadata:{[zt]:o.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:D}=await Ye(a,v,e.backupRetain,o.cron);if(D.length>0){const M=D.slice(0,Qt),I=D.length-M.length;console.info(`[lunora] backup retention: ${String(D.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${M.join(", ")}${I>0?` (+${String(I)} more)`:""}`)}}catch(D){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,D)}},Wr=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 Gr(n,We(e.backupPrefix??Ve),a,o,t)},Vr="/_lunora/admin/backup/retention",qr="/_lunora/admin/backup/prune",Jr=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,a=(h,f)=>{o(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},i=async h=>(K(h,"GET","Backup-retention"),a(h,"retention preview"),Response.json(await Qr(t),{headers:{"cache-control":"no-store"}})),u=async h=>{K(h,"POST","Backup-prune"),a(h,"prune");const{confirm:f}=await n(h);if(!Array.isArray(f)||f.some(w=>typeof w!="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 Wr(t,f),{headers:{"cache-control":"no-store"}})};return{[qr]:u,[Vr]:i}},yt=500,Yr=(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});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}},Xr=(e,t)=>{if(e.length>yt)throw new d(`RPC batch exceeds the ${String(yt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map;for(const[o,a]of e.entries()){const{entry:i,shardKey:u}=Yr(a,o,t),h=n.get(u)??[];h.push(i),n.set(u,h)}return n},Zr="/_lunora/admin/export",eo="/_lunora/admin/import",to="/_lunora/admin/sync",no="/_lunora/admin/connector/sync",ro="/_lunora/admin/apply",oo="/_lunora/admin/export-tap/run",ao=new TextEncoder,so=async e=>{const n=await be(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}},Le=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,io=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:a,knownTables:i,queryCoordinator:u,assertAdmin:h,requireAdminOption:f,resolveForwardContext:w,shardDO:E,streamExportRows:O,streamingImport:v,syncGlobals:g}=e,b=async(I,j)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),U=await so(I),{headers:$}=await w(I,j),F=new ReadableStream({async pull(W){const te=V=>{W.enqueue(ao.encode(`${JSON.stringify(V)}
|
|
4
|
-
`))};try{await O(Y,$,U.tables,te),W.close()}catch(V){W.error(V)}}});return new Response(F,{headers:{"content-type":"application/x-ndjson"},status:200})},_=async(I,j)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),U=await ee(I),$=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},F=typeof U.limit=="number"?U.limit:void 0,W=typeof U.globalCursor=="number"?U.globalCursor:0,te=Le(U.tables),{headers:V}=await w(I,j),se=te??i(),G=await Y.orchestrateCdcSync(E,{cursors:$,defaultShardKey:n,headers:V,limit:F,tables:se}),q=g?await g({limit:F,sinceSeq:W}):void 0;return Response.json({global:q,shards:G.shards},{status:200})},p=async(I,j)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),U=await ee(I),$=er(U.cursor),F=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,W=Le(U.tables),{headers:te}=await w(I,j),V=W??i(),se=await Y.orchestrateCdcSync(E,{cursors:$.s,defaultShardKey:n,headers:te,limit:F,tables:V}),G=[],q={...$.s};let Z=!1;for(const ie of se.shards)Z=at(G,ie.changes??[],nr(F))||Z,q[ie.shardKey]=ie.cursor;let _e=$.g;if(g){const ie=await g({limit:F,sinceSeq:$.g});Z=at(G,ie.changes,F)||Z,_e=ie.cursor}const Oe=tr({g:_e,s:q,v:1}),ve={changes:G,hasMore:Z,nextCursor:Oe};return Response.json(ve,{status:200})},A=async(I,j)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),U=await ee(I),F=(Array.isArray(U.batches)?U.batches:[]).map(G=>G).filter(G=>G!==null&&typeof G=="object"&&typeof G.shardKey=="string"&&Array.isArray(G.changes)),W=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:te}=await w(I,j),V=await Y.orchestrateApplyCdc(E,{batches:F,headers:te}),se=W.length>0&&t?await t({changes:W}):0;return Response.json({applied:V.applied+se,failed:V.failed,ok:V.ok},{status:200})},D=async(I,j)=>{const H=me(I,["POST"]);if(H)return H;h(I);const{headers:Y}=await w(I,j),U=await v(I,Y);return Response.json(U,{headers:{"content-type":"application/json"},status:U.failed.length>0?207:200})},M=async(I,j)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{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 U=await ee(I),$=typeof U.sink=="string"?U.sink:void 0,F=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,W=Le(U.tables);if($===void 0)throw new d("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const te=a[$];if(te===void 0)throw new d(`Export-tap sink "${$}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:V}=await w(I,j),se=W??i(),G=await Zn({coordinator:Y,cursorStore:o,defaultShardKey:n,headers:V,limit:F,shardDO:E,sink:te,tables:se});return Response.json(G,{headers:{"content-type":"application/json"},status:200})};return{[ro]:A,[no]:p,[Zr]:b,[oo]:M,[eo]:D,[to]:_}},co=(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}},uo=(e,t,n,o,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:o}},lo=async(e,t,n)=>{if(!e.body)throw new d("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const o=[],a=[],i=new Map;let u=0,h=0;const f=e.body.getReader(),w=new TextDecoder;let E="",O=0;const v=g=>{h+=1;const b=g.trim();if(b.length===0)return;u+=1;const _=co(b,h);if(!_.ok){o.push(_.error);return}const{doc:p,table:A}=_,D=t.resolveTableSharding?.(A);if(D?.mode.kind==="global"){a.push({doc:p,line:h,table:A});return}const M=uo(p,A,D,n,h);if(!M.ok){o.push(M.error);return}const I=i.get(M.shardKey);I?I.rows.push({doc:p,table:A}):i.set(M.shardKey,{rows:[{doc:p,table:A}],shardKey:M.shardKey,startLine:h})};for(;;){const{done:g,value:b}=await f.read();if(g)break;if(b&&(O+=b.byteLength,O>Ut))throw await f.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=w.decode(b,{stream:!0});let _=E.indexOf(`
|
|
5
|
-
`);for(;_!==-1;){const p=E.slice(0,_);E=E.slice(_+1),v(p),_=E.indexOf(`
|
|
6
|
-
`)}}return E.length>0&&v(E),{errors:o,globalRows:a,perShard:i,received:u}},ho=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),bt=(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},fo=async(e,t,n,o)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:h,received:f}=await lo(e,t,a),w={conflicts:0,errors:i,failed:[],inserted:{}},E=[];if(t.resolveTableSharding===void 0&&h.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"),h.size>0){const O=t.queryCoordinator;if(!O)throw new d("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const v=await O.orchestrateImport(o,{batches:[...h.values()],headers:n});bt(w,v),w.failed.push(...ho(v.shards))}if(u.length>0)if(t.importGlobals){const O=u[0]?.line??1,v=await t.importGlobals({rows:u,startLine:O});bt(w,v)}else for(const O of u)w.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:O.line,message:`row targets global table "${O.table}" but no \`importGlobals\` is configured`,table:O.table});return{conflicts:w.conflicts,errors:w.errors,failed:w.failed,inserted:w.inserted,received:f,...E.length>0?{warnings:E}:{}}},Me=e=>typeof e=="object"&&e!==null?e:{},Ke=e=>typeof e.kind=="string"?e.kind:"unknown",po=(e,t)=>{let n=Me(t),o=!1;Ke(n)==="optional"&&(o=!0,n=Me(n._meta?.inner));const a=Ke(n),i=n._meta??{},u={kind:a,name:e,optional:o};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const h=Ke(Me(i.inner));h!=="unknown"&&(u.element=h)}return u},mo=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>po(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),wo="/_lunora/admin/functions",go="/_lunora/admin/cron-jobs",yo="/_lunora/admin/openapi",bo="/_lunora/admin/openrpc",_o="/_lunora/admin/global/tables",Ro="/_lunora/admin/global/table",Eo="/_lunora/admin/global/facet",_t=e=>{if(e===void 0||e==="")return;let t;try{t=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:i}=o;return[{column:a,value:i}]});return n.length===0?void 0:n},So=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:{}}),Ao=Object.freeze({info:{description:'No OpenRPC spec is configured on this worker. Run `lunora codegen --api-spec openrpc` (or `both`), then wire the generated module to `createWorker`: `import { openRpcSpec } from "./lunora/_generated/openrpc"`.',title:"Lunora RPC",version:"0.0.0"},methods:[],openrpc:"1.3.2"}),To=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:a,requireAdminOption:i}=e,u=g=>{K(g,"GET","Functions");const b=i(g,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(b).flatMap(([p,A])=>A.visibility==="internal"||A.kind==="stream"?[]:[{args:mo(A.args),kind:A.kind,path:p}]).toSorted((p,A)=>p.path.localeCompare(A.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},h=g=>{K(g,"GET","Cron-jobs");const b=i(g,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(b).flatMap(([p,A])=>A.map(D=>({args:D.args,cron:p,functionPath:D.functionPath,name:D.name,shardKey:D.shardKey,workflow:D.workflow}))).toSorted((p,A)=>p.name.localeCompare(A.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},f=g=>(K(g,"GET","OpenAPI"),t(g),Response.json(n.openApiSpec??So,{headers:{"content-type":"application/json"},status:200})),w=g=>(K(g,"GET","OpenRPC"),t(g),Response.json(n.openRpcSpec??Ao,{headers:{"content-type":"application/json"},status:200})),E=async g=>{K(g,"GET","Global-tables");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await b.listTables(),{headers:{"content-type":"application/json"},status:200})},O=async g=>{K(g,"GET","Global-table");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),p=a(_,"table");if(p===void 0)throw new d("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const A=await b.readTablePage({...o(g),filters:_t(a(_,"filters")),table:p});return Response.json(A,{headers:{"content-type":"application/json"},status:200})},v=async g=>{K(g,"GET","Global-facet");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),p=a(_,"table"),A=a(_,"column");if(p===void 0||A===void 0)throw new d("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const D=a(_,"limit"),M=D===void 0?void 0:Number(D),I=await b.facetColumn({column:A,filters:_t(a(_,"filters")),limit:M!==void 0&&Number.isFinite(M)?M:void 0,table:p});return Response.json(I,{headers:{"content-type":"application/json"},status:200})};return{[go]:h,[wo]:u,[Eo]:v,[Ro]:O,[_o]:E,[yo]:f,[bo]:w}},Oo="/_lunora/admin/kv/namespaces",vo="/_lunora/admin/kv/keys",Wt="/_lunora/admin/kv/value",Vt=32*1048576,Rt=60,ko=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}),i=(b,_)=>{const p=new URL(b.url),A=p.searchParams.get("namespace")??"",D=p.searchParams.get("key")??"";if(A==="")throw new d(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(D==="")throw new d(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:D,namespace:A}},u=async(b,_)=>{if(!(await b.listNamespaces()).some(A=>A.binding===_))throw new d(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},h=async b=>(K(b,"GET","KV-namespaces"),a({namespaces:await o(b).listNamespaces()})),f=async b=>{K(b,"GET","KV-keys");const _=o(b),p=new URL(b.url),A=p.searchParams.get("namespace")??"";if(A==="")throw new d("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const D=p.searchParams.get("prefix")??void 0,M=p.searchParams.get("cursor")??void 0,I=p.searchParams.get("limit"),j=I===null?void 0:Number.parseInt(I,10);if(j!==void 0&&(!Number.isInteger(j)||j<1))throw new d("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const H=j===void 0?void 0:Math.min(j,1e3);return await u(_,A),a(await _.listKeys({cursor:M,limit:H,namespace:A,prefix:D}))},v={DELETE:async b=>{const _=o(b),p=i(b,"DELETE");return await u(_,p.namespace),await _.deleteKey(p),a({deleted:!0})},GET:async b=>{const _=o(b),p=i(b,"GET");return await u(_,p.namespace),a(await _.getValue(p))},PUT:async b=>{const _=o(b),p=await t(b,Vt);if(typeof p.namespace!="string"||p.namespace==="")throw new d("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new d("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new d("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<Rt))throw new d("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const A=Math.floor(Date.now()/1e3)+Rt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<A))throw new d("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(_,p.namespace),await _.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),a({ok:!0})}},g=b=>{const _=v[b.method];if(!_)throw new d("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(b)};return{[Oo]:h,[vo]:f,[Wt]:g}},Io="/_lunora/migrate",Po="/_lunora/admin/pitr",Do="/_lunora/admin/rank",No="/_lunora/admin/rankpage",Uo="/_lunora/admin/shard-traffic",Co=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Bo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),xo=async e=>{const n=await be(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"||!Co.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}},Ho=async e=>{const n=await be(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}},Lo=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}},Mo=e=>{if(typeof e.table!="string"||e.table.length===0)throw new d("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new d("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new d("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new d("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new d("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Ko=async e=>{const n=await be(e,"Rank page")??{};Mo(n);const o=Lo(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}},jo=async e=>{const n=await be(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}},$o=async e=>{const n=await ee(e);if(typeof n.functionPath!="string"||!Bo.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}},Fo=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:a,resolveForwardContext:i,shardDO:u}=e,h=(g,b)=>{if(g.method!=="POST")throw new d(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(g))throw new d("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new d(`${b} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},f=async(g,b)=>{const _=h(g,"Migration"),p=await xo(g),{headers:A}=await i(g,b),D=await _.orchestrateMigration(u,{args:p.args,defaultShardKey:t,functionPath:p.functionPath,headers:A,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},w=async(g,b)=>{const _=h(g,"Rank"),p=await Ho(g),{headers:A}=await i(g,b),D=await _.orchestrateRank(u,{headers:A,index:p.index,partitionKey:p.partitionKey,rowId:p.rowId,sortValues:p.sortValues,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},E=async(g,b)=>{const _=h(g,"Rank page"),p=await Ko(g),{headers:A}=await i(g,b),D=await _.orchestrateRankPage(u,{...p,headers:A});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},O=async(g,b)=>{const _=h(g,"Shard-traffic"),p=await jo(g),{headers:A}=await i(g,b),D=await _.orchestrateShardTraffic(u,{headers:A,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},v=async(g,b)=>{if(K(g,"POST","PITR"),!o(g))throw new d("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const _=await $o(g),{headers:p}=await i(g,b),A=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:_.args,functionPath:_.functionPath}),headers:p,method:"POST"});return n(u,_.shardKey??t,A)};return{[Io]:f,[Po]:v,[Do]:w,[No]:E,[Uo]:O}},Go=1,Qo=0,zo=32,Wo=512,Vo=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,qo=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Wo)return;const n=t.split(",");if(!(n.length>zo)){for(const o of n)if(!Vo.test(o.trim()))return;return t}},Jo=e=>{const t=Mn(e.headers.get("traceparent"));if(t===void 0)return;const n=qo(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},Yo=(e,t={})=>{const n=Jo(e),o=t.trustInbound===!0?n:void 0,a=Te(8),i=o?.traceId??Te(16),u=cr(t.sampling,o===void 0?a:i),h=u.isTraced&&(o===void 0||o.sampled);return{decision:u,ignoredUpstream:n!==void 0&&o===void 0,trace:{sampled:h,spanId:a,traceFlags:h?Go:Qo,traceId:i,...o?.parentSpanId===void 0?{}:{parentSpanId:o.parentSpanId},...o?.traceState===void 0?{}:{traceState:o.traceState}}}},Xo=(e,t)=>{t.traceparent=Ln(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Zo=(e,t)=>{let n;return()=>{if(n===void 0){const o=Fn(e),a=t===void 0?void 0:t.cf;n=Kn($n(o),jn(o,a))}return n}},ea="/_lunora/admin/scheduled",ta="/_lunora/admin/scheduled/status",na="/_lunora/admin/scheduled/ws",ra="/_lunora/admin/scheduled/cancel",oa="/_lunora/admin/scheduled/dead",aa="/_lunora/admin/scheduled/dead/retry",sa="/_lunora/admin/scheduled/dead/cancel",ia=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:a}=e,i=(f,w)=>E=>{if(E.method!=="GET")throw new d(`${w} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return o(E).fetch(new Request(`https://scheduler.internal${f}`,{method:"GET"}))},u=(f,w,E=w)=>async O=>{if(O.method!=="POST")throw new d(`${E} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const v=o(O),g=await O.json().catch(()=>{});if(typeof g?.id!="string"||g.id==="")throw new d(`${w} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return v.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:g.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(f))throw new d("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const w=n();return we(w,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ra]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[sa]:u("/dead/cancel","Scheduled dead-letter action"),[oa]:i("/dead","Scheduled dead-letter"),[aa]:u("/dead/retry","Scheduled dead-letter action"),[ea]:i("/list","Scheduled-list"),[ta]:i("/status","Scheduler-status"),[na]:h}},ca=(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},Et={mtls:e=>ca(e,"tlsClientAuth","certVerified")==="SUCCESS"},da=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(Et,e)?Et[e]:void 0)??(()=>!1),ua=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.'))}},la="/_lunora/admin/vector/indexes",ha="/_lunora/admin/vector/query",fa=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=async i=>{K(i,"GET","Vector-indexes");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async i=>{K(i,"POST","Vector-query");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new d("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const f=await t(i);if(typeof f.name!="string"||f.name==="")throw new d("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof f.text!="string"||f.text==="")throw new d("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(f.topK!==void 0&&(typeof f.topK!="number"||!Number.isInteger(f.topK)||f.topK<1))throw new d("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const w=await u.queryIndex({name:f.name,text:f.text,topK:f.topK});return Response.json(w,{headers:{"content-type":"application/json"},status:200})};return{[la]:o,[ha]:a}},pa="/_lunora/admin/workflows/instances",ma="/_lunora/admin/workflows/instance",wa="/_lunora/admin/workflows/status",ga={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},ya=e=>e!==null&&Object.hasOwn(ga,e)?e:void 0,St=(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},je=(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},At=()=>{throw new d("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},ba=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,o=async(u,h,f)=>{K(u,"GET","Workflows instances"),t(u);const w=n(h);if(!w)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const E=je(f,"name"),O=ya(f.searchParams.get("status"));return Response.json(await w.listInstances({page:St(f,"page"),perPage:St(f,"perPage"),status:O,workflowName:E}))},a=async(u,h,f)=>{K(u,"GET","Workflows instance"),t(u);const w=n(h);return w?Response.json(await w.getInstance({instanceId:je(f,"id"),workflowName:je(f,"name")})):At()},i=async(u,h)=>{K(u,"POST","Workflows status"),t(u);const f=n(h);if(!f)return At();const w=await u.json().catch(()=>{});if(typeof w?.name!="string"||w.name===""||typeof w.id!="string"||w.id==="")throw new d("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:E}=w;if(E!=="pause"&&E!=="resume"&&E!=="terminate")throw new d("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:E,instanceId:w.id,workflowName:w.name}))};return{[ma]:a,[pa]:o,[wa]:i}},_a={[Wt]:Vt,[Xn]:Yn},Tt="/_lunora/rpc",Ra="/_lunora/rpc-batch",Ea="/_lunora/ws",Ee=(e,t,n)=>({resourceAttributes:Zo(e,t),...n===void 0?{}:{waitUntil:n}}),$e=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Ot=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Fe=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}},vt="/_lunora/voice/",Sa="/_lunora/scheduler/dispatch",Aa="/_lunora/admin/cron-jobs/run",Ta="/_lunora/admin/ws-token",Oa="/_lunora/admin/",va="/_lunora/migrate",ka="/_lunora/status",Ia=e=>e.startsWith(Oa)||e===va,Pa=e=>{const 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}}},Da="/api/auth",Na="__lunora_admin__:recordAuthEvent",Ua="__lunora_admin__:listPushSubscriptions",Ca=["/sign-in","/sign-up","/callback"],Ba=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return Ca.some(a=>o===a||o.startsWith(`${a}/`))},Se=(e,t,n,o)=>{const a=Dn(n),i=a?n.code:"INTERNAL_SERVER_ERROR",u=a?n.status:500,h=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:h,status:u},functionPath:e,ok:!1,...o.fanOut?{fanOut:{failed:0,shards:0,table:o.fanOut.table}}:{},...o.shardKey?{shardKey:o.shardKey}:{}}},xa=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},kt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Ha=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ze=new WeakMap,ue=async(e,t,n,o=ze.get(e))=>{const a={"content-type":"application/json"},i=e.headers.get("authorization"),u=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),f=e.headers.get("x-lunora-mutation-id"),w=e.headers.get("x-lunora-client-id"),E=e.headers.get("x-lunora-client-seq");i&&(a.authorization=i),u&&(a.cookie=u),h&&(a["x-d1-bookmark"]=h),f&&(a["x-lunora-mutation-id"]=f),w&&(a["x-lunora-client-id"]=w),E&&(a["x-lunora-client-seq"]=E);const O=e.headers.get("cf-connecting-ip");if(O&&(a["x-lunora-client-ip"]=O),!n)return{claims:null,headers:a,identity:null,userId:null};const v=await n(e,t,o);if(!v||typeof v.userId!="string"||v.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=xn(v.userId);const g=xa(v);g!==void 0&&(a["x-lunora-identity-exp"]=String(g));const{userId:b,..._}=v,p=Object.keys(_).length>0?_:null;return p&&(a["x-lunora-identity"]=Hn(p)),{claims:p,headers:a,identity:v,userId:b}},La=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Ma=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new d("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const 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"||!La.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},Ka=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},Ge=(e,t)=>{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}},ja=async e=>{const t=await Bt(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&&Ct(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,i=Ma(a.fanOut),u=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==i.table)throw new d("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},Ae=new Map,$a=5e3,Fa=4096,Ga=async(e,t)=>{const n=Date.now(),o=Ae.get(t);if(o!==void 0&&o.expiresMs>n)return o.relayCount;o!==void 0&&Ae.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 Nt(Ae,Fa),Ae.set(t,{expiresMs:n+$a,relayCount:a}),a},It=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},ye=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),Qa=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],Pt=(e,t)=>{for(const n of Qa){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},za=async(e,t,n)=>e.length===0||n.length===0?!1:qe(await Mt(e,t),n),Dt=(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:qe(t,a.join(" ").trim())},Wa=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 Nr(t,o)?!0:n?!1:qe(t,o)},Va=(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 ar(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return Be(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return Be(`queue:${e}`,!0);if(typeof n.connectionString=="string")return Be(`hyperdrive:${e}`,!0)},qt=e=>{const t=da(e.trustInboundTraceContext),n=ua(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",a=sr(e.resolveIdentity,e.identity),i=it(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:it(e.schedulerDO,e.jurisdiction);let h=!1;const f=r=>{if(r===void 0||e.jurisdiction===void 0)return r;h||(h=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},w=async(r,s,l,c=e.shardRegion?.(s))=>we(r,s,f(c)).fetch(l);let E;const O=()=>e.adminToken??E;let v;const g=()=>e.requireEphemeralWsToken??v??!0;let b;const _=r=>{const s=r??{};if(b??=It(r,e.shardDO),v===void 0&&e.requireEphemeralWsToken===void 0){const c=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(v=Ir(c,!0))}if(E!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(E=l)},p=new WeakSet,A=r=>Dt(r,O())||p.has(r),D=async(r,s)=>{const l=await ue(r,s,e.resolveIdentity);if(p.has(r)&&l.headers.authorization===void 0){const c=O();c!==void 0&&(l.headers.authorization=`Bearer ${c}`)}return l};let M=!1,I=!1;const j=()=>{I||(I=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},H=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})}M||(M=!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("")))},Y=async(r,s)=>{if(e.authorizeShard){if(!await e.authorizeShard({identity:r,shardKey:s}))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==o&&H("shard")},U=Fo({defaultShard:o,forwardToShard:w,isAdmin:A,queryCoordinator:e.queryCoordinator,resolveForwardContext:D,shardDO:i}),$=async(r,s,l,c,m)=>{const R={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(R["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(R["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(R["x-lunora-mutation-id"]=c),w(i,l,ye(r,s,R))},F=async(r,s,l,c)=>{const m=l?.[r];if(!m||typeof m.create!="function")throw new d(`${c} targets workflow binding "${r}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(hr(s))throw new d(`${c} params ${fr}`,{code:"BAD_REQUEST",status:400});await m.create({params:s})},W=async(r,s)=>{if(r.workflow){await F(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 l=await $(r.functionPath,r.args??{},r.shardKey??o);if(!l.ok)throw new d(`cron job "${r.name}" (${r.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},te=async(r,s,l,c)=>{const m=e.cronJobs?.[r];if(m)for(const R of m)try{await W(R,s)}catch(k){l.push(c(k))}},V=async(r,s)=>{if(!A(r))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(K(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 l=await ee(r),c=typeof l.name=="string"?l.name:"";if(c==="")throw new d("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(R=>R.name===c);if(!m)throw new d(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await W(m,s),Response.json({name:c,ran:!0},{status:200})},se=async r=>{const s=typeof r.pool=="string"&&r.pool.length>0?r.pool:void 0;if(!s||!u||typeof r.id!="string")return;const l=typeof r.instanceName=="string"&&r.instanceName.length>0?r.instanceName:"default";try{await we(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:r.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},G=async(r,s)=>{K(r,"POST","Scheduler dispatch");const l=await Bt(r),c=s??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,R=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),k=r.headers.get("x-lunora-scheduler-signature");let y=!1;if(k&&m?y=await za(m,l,k):R&&(y=Dt(r,R)),!y)throw new d("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let S;try{S=JSON.parse(l)}catch{throw new d("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const T=S??{},C=T.args??{};if(typeof T.workflow=="string"&&T.workflow.length>0)return await F(T.workflow,C,s,"scheduled workflow"),await se(T),Response.json({ok:!0},{status:200});if(typeof T.functionPath!="string"||T.functionPath.length===0)throw new d("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const B=typeof T.shardKey=="string"&&T.shardKey.length>0?T.shardKey:o,x=typeof T.id=="string"&&T.id.length>0?T.id:void 0,re=Pa(r),L=await $(T.functionPath,C,B,x,re);return await se(T),L},q=r=>{if(!A(r))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},Z=(r,s,l)=>{if(q(r),s===void 0)throw new d(l.message,{code:l.code,status:400});return s},_e=Hr({assertAdmin:q,getReader:()=>e.authAuditReader}),Oe=async(r,s)=>{q(r);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:Qe({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const c=s?.kind,m=s?.userId,R=s?.limit,k=c==="fcm"||c==="web-push"?c:void 0,y=typeof m=="string"&&m!==""?m:void 0,S=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,T=S>0?Math.min(S,1e3):1e3,B=(await l.list({kind:k,limit:T,userId:y})).filter(x=>k!==void 0&&x.kind!==k?!1:y===void 0||(x.userId??null)===y).map(({keys:x,token:re,...L})=>L);return Response.json({result:Qe({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},ve=async(r,s)=>{if(!s.fanOut){if(s.functionPath===xr)return _e(r,s.args??{});if(s.functionPath===Ua)return Oe(r,s.args)}},ie=io({applyGlobals:e.applyGlobals,assertAdmin:q,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:o,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:Z,resolveForwardContext:D,shardDO:i,streamExportRows:(r,s,l,c)=>Gt(e,r,s,l,c,i),streamingImport:(r,s)=>fo(r,e,s,i),syncGlobals:e.syncGlobals}),ke=(r,s)=>{const l=r.searchParams.get(s);return l===null||l===""?void 0:l},Ie=r=>{const s=new URL(r.url),l=s.searchParams.get("limit"),c=s.searchParams.get("offset"),m=l===null?void 0:Number.parseInt(l,10),R=c===null?void 0:Number.parseInt(c,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},Xe=()=>{if(u===void 0)throw new d("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},Jt=ia({checkWsAdmin:async r=>A(r)||Wa(r,O(),g()),requireSchedulerNamespace:Xe,resolveSchedulerStub:r=>(q(r),we(Xe(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Yt=ba({assertAdmin:q,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Xt=Jn({assertAdmin:q,parsePaging:Ie,queryParameter:ke,readBodyBytes:Qn,requireAdminOption:Z,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Zt=Jr({options:e,readJsonBody:ee,requireAdminOption:Z}),en=fa({readJsonBody:ee,requireAdminOption:Z,vectorIntrospector:e.vectorIntrospector}),tn=ko({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:Z}),nn=ir({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:Z}),rn=To({assertAdmin:q,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ie,queryParameter:ke,requireAdminOption:Z}),on=r=>{const s=[],l=i??r?.SHARD;if(l!==void 0&&s.push(or("durable-object:default",l,o)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(r??{})){const R=Va(c,m);R!==void 0&&s.push(R)}for(const c of e.health?.probes??[])s.push(c);return s},an=rr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:A,resolveProbes:on}),sn=r=>{const s=e.schedulerInstanceName??"default",l=()=>we(r,s),c=async(y,S)=>{const T=await l().fetch(new Request(`https://scheduler.internal${y}`,S));if(!T.ok)throw new d(`ctx.scheduler: SchedulerDO ${y} failed (${String(T.status)}): ${await T.text()}`,{code:"INTERNAL",status:500});return await T.json()},m=async(y,S)=>await c(y,{body:JSON.stringify(S),headers:{"content-type":"application/json"},method:"POST"}),R=y=>{const S=y;if(S==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 S.binding=="string"&&S.binding.length>0)return{workflow:S.binding};if(typeof S.__lunoraRef=="string")return{functionPath:S.__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(y,S,T={})=>{const{id:C}=await m("/schedule",{args:T,scheduledFor:y,...R(S)});return C};return{cancel:async y=>await m("/cancel",{id:y}),get:async y=>await c(`/get?id=${encodeURIComponent(y)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(y,S,T)=>{if(!Number.isFinite(y)||y<0)throw new d("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await k(Date.now()+y,S,T)},runAt:async(y,S,T)=>{if(!Number.isFinite(y))throw new d("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await k(y,S,T)}}},cn=async(r,s,l)=>{const{claims:c,headers:m,userId:R}=await ue(r,s,a),k=async(y,S={})=>{const T=y.__lunoraRef;if(typeof T!="string")throw new d("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const C=ye(T,S,{...m,"x-lunora-system":"1"}),B=await w(i,o,C),x=await B.json();if(x.error)throw new d(x.error.message??"shard RPC failed",{code:x.error.code??"INTERNAL",status:B.status});return x.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:R},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),runAction:k,runMutation:k,runQuery:k,...u===void 0?{}:{scheduler:sn(u)},...e.storage===void 0?{}:{storage:lr(e.storage(s))}}},dn=async(r,s,l)=>{if(!e.httpRouter)return;const c=await cn(r,s,l);try{return await e.httpRouter.fetch(r,{...s,__lunoraCtx:c},l)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},un=async(r,s,l)=>{if(r.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=dt(r,ce);if(c)return c;const m=l.searchParams.get("shard")??o,{headers:R,identity:k}=await ue(r,s,a);await Y(k,m);const y=new Headers(r.headers),S=[...y.keys()];for(const C of S)C.startsWith("x-lunora-")&&y.delete(C);Pt(y,R);const T=It(s,e.shardDO);if(T!==void 0){y.set("x-lunora-shard-binding",T);const C=await Ga(i,m);if(C>0){const B=Ar(m,Math.floor(Math.random()*C));return w(i,B,new Request(r,{headers:y}),ut(r))}}return w(i,m,new Request(r,{headers:y}))},ln=async(r,s,l)=>{const{voiceAgents:c}=e;if(c===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 m=dt(r,ce);if(m)return m;let R;try{R=decodeURIComponent(l.pathname.slice(vt.length))}catch{return new Response("Unknown voice agent",{status:404})}const k=Object.hasOwn(c,R)?c[R]:void 0;if(k===void 0)return new Response("Unknown voice agent",{status:404});const y=l.searchParams.get("threadKey");if(y===null||y.length===0)return new Response("Missing threadKey",{status:400});const{headers:S,identity:T}=await ue(r,s,a);if(e.authorizeShard){if(!await e.authorizeShard({identity:T,shardKey:y}))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else H("shard");const C=new Headers(r.headers);for(const B of C.keys())B.startsWith("x-lunora-")&&C.delete(B);return Pt(C,S),w(k,y,new Request(r,{headers:C}))},hn=async(r,s,l)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(l,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});H("fan-out")},Re=async(r,s)=>{if(!(!r.fanOut&&r.functionPath.startsWith("__lunora_admin__:"))){if(r.fanOut){await hn(r.fanOut,r.functionPath,s);return}await Y(s,r.shardKey??o)}},fn=(r,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){j();return}if(e.functions[s]?.kind!=="query"||l.includes(jt)||l.includes(Kt))return;const c=ut(r);return c===void 0?void 0:{name:Tr(l,c),region:c}},pn=async(r,s,l,c,m)=>{const R=fn(r,s,c);if(R!==void 0){const k={...m,"x-lunora-replica-read":"1",...b===void 0?{}:{"x-lunora-shard-binding":b}},y=Or(r.headers.get("x-lunora-min-seq"));y!==void 0&&(k["x-lunora-min-seq"]=String(y));const S=await w(i,R.name,ye(s,l,k),R.region);if(S.status!==421)return S}return w(i,c,ye(s,l,m))},Pe=async(r,s,l,c,m,R)=>{const k=Date.now(),{observability:y,sampling:S}=e,T=Fe(r),{decision:C,ignoredUpstream:B,trace:x}=Yo(r,{...S===void 0?{}:{sampling:S},trustInbound:t(r)});B&&n();const re={...m,"x-lunora-sample-errors":C.keepErrors?"1":"0"};Xo(x,re);try{const L=await pn(r,s,l,c,re);de(y,{...T,...Ot(x),durationMs:Date.now()-k,functionPath:s,ok:L.ok,shardKey:c,...L.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(L.status)}`,status:L.status}}},R,void 0,{isTraced:x.sampled,keepErrors:C.keepErrors});const ne=new Response(L.body,{headers:L.headers,status:L.status,statusText:L.statusText});return ne.headers.set("x-lunora-shard-key",c),ne}catch(L){throw de(y,{...T,...Ot(x),...Se(s,Date.now()-k,L,{shardKey:c})},R,void 0,{isTraced:x.sampled,keepErrors:C.keepErrors}),L}},mn=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&&r.functionPath.startsWith("__lunora_relation__:"))throw new d("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(r.fanOut&&!e.queryCoordinator)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},wn=async(r,s,l)=>{K(r,"POST","RPC");const c=await ja(r);Ka(s,c),mn(c);const m=await ve(r,c);if(m!==void 0)return m;const{headers:R,identity:k}=await ue(r,s,a);await Re(c,k);const y=Ge(c,e);{const S=Date.now(),{observability:T}=e,C=Fe(r),B=Ee(s,r,l&&(L=>l.waitUntil?.(L)));if(c.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(i,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:R});return de(T,{durationMs:Date.now()-S,fanOut:{failed:ne.failed,shards:ne.ok+ne.failed,table:c.fanOut.table},functionPath:c.functionPath,...C,ok:!0},B),Response.json(ne,{headers:{"content-type":"application/json"},status:200})}catch(ne){throw de(T,{...Se(c.functionPath,Date.now()-S,ne,{fanOut:{table:c.fanOut.table}}),...C},B),ne}}const x=c.shardKey??o,re=()=>Pe(r,c.functionPath,c.args??{},x,R,B);return y&&e.x402Charge?e.x402Charge(r,{functionPath:c.functionPath,price:y.price},re,$e(l)):re()}},gn=async(r,s,l)=>{K(r,"POST","RPC batch");const c=await ee(r),{calls:m}=c;if(!Array.isArray(m))throw new d("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:k}=await ue(r,s,a),y=Xr(m,o);for(const Q of y.values())for(const z of Q)if(e.functions?.[z.functionPath]?.x402)throw new d(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${Tt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...y.entries()].flatMap(([Q,z])=>z.map(oe=>Re({args:oe.args,functionPath:oe.functionPath,shardKey:Q},k))));const{observability:S}=e,T=Ee(s,r,l&&(Q=>l.waitUntil?.(Q))),C=Fe(r),B=[],x=[],re=(Q,z,oe,le)=>({body:{error:{code:oe,message:le}},id:Q.id,status:z}),L=(Q,z,oe,le,fe)=>{for(const J of Q)de(S,fe(J),T),B.push(re(J,z,oe,le))},ne=(Q,z,oe,le,fe)=>{for(const J of Q){const pe=le.get(J.id)??fe,ge=pe<400;de(S,{durationMs:oe,functionPath:J.functionPath,...C,ok:ge,shardKey:z,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},T)}};await Promise.all([...y.entries()].map(async([Q,z])=>{const oe=new Headers(R);oe.set("content-type","application/json");const le=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:oe,method:"POST"}),fe=Date.now();let J;try{J=await w(i,Q,le)}catch(X){const Ce=Date.now()-fe,{body:rt}=Nn(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});L(z,502,rt.code,rt.message,Pn=>({...Se(Pn.functionPath,Ce,X,{shardKey:Q}),...C}));return}const pe=Date.now()-fe,ge=J.headers.get("x-d1-bookmark");ge&&x.push(ge);let Ne;try{Ne=await J.json()}catch{const X=`shard batch returned a non-JSON response (${String(J.status)})`;L(z,J.status,"SHARD_ERROR",X,Ce=>({durationMs:pe,error:{code:"SHARD_ERROR",message:X,status:J.status},functionPath:Ce.functionPath,...C,ok:!1,shardKey:Q}));return}const Ue=Array.isArray(Ne.results)?Ne.results:[],kn=new Map(Ue.map(X=>[X.id,X.status??J.status])),In=new Set(Ue.map(X=>X.id));ne(z,Q,pe,kn,J.status),B.push(...Ue);for(const X of z)In.has(X.id)||B.push(re(X,J.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const tt={"content-type":"application/json"},[nt]=x;return x.length===1&&nt!==void 0&&(tt["x-d1-bookmark"]=nt),Response.json({results:B},{headers:tt,status:200})},yn=async(r,s,l,c={},m={})=>{try{const R=l.__lunoraRef;if(typeof R!="string")throw new d("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:k,identity:y}=await ue(r,s,a,m.context),S={args:c,functionPath:R,shardKey:m.shardKey};await Re(S,y);const T=m.shardKey??o,C=Ee(s,r,m.waitUntil),B=()=>Pe(r,R,c,T,k,C),x=Ge(S,e);return x&&e.x402Charge?await e.x402Charge(r,{functionPath:R,price:x.price},B,$e(m.waitUntil?{waitUntil:m.waitUntil}:m.context)):await B()}catch(R){return ot(R)}},Ze=async(r,s,l)=>{const{observability:c}=e,m=Date.now(),R=Te(16),k=Te(8),y=kt(s);try{const S=await l();return de(c,{durationMs:Date.now()-m,functionPath:r,ok:!0,spanId:k,traceId:R},y),S}catch(S){throw de(c,{...Se(r,Date.now()-m,S,{}),spanId:k,traceId:R},y),S}finally{st(c,y)}},bn=async(r,s,l)=>{_(s);const c=[],m=y=>y instanceof Error?y:new Error(String(y)),R=e.crons?.[r.cron];if(R)try{await R(r,s,l)}catch(y){c.push(m(y))}if(await te(r.cron,s,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===r.cron)try{await zr(e,i,O(),r)}catch(y){c.push(m(y))}const[k]=c;if(c.length===1&&k)throw k;if(c.length>1)throw new AggregateError(c,`scheduled("${r.cron}") had ${String(c.length)} failure(s)`)},_n=async(r,s)=>{try{const l=r??{},c=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await w(i,o,ye(Na,{outcome:s},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},Rn=async(r,s,l,c)=>{if(!e.authHandler)return;const m=await e.authHandler(r);if(!m)return;const R=e.authBasePath??Da;return Ba(l.pathname,R)&&c.waitUntil?.(_n(s,m.status>=400?"fail":"ok")),m},En=async({args:r,env:s,functionPath:l,request:c,shardKey:m,waitUntil:R})=>{Ct(r,"REST");const k={functionPath:l,...m===void 0?{}:{shardKey:m}},{headers:y,identity:S}=await ue(c,s,a);await Re(k,S);const T=m??o,C=Ee(s,c,R),B=()=>Pe(c,l,r,T,y,C),x=Ge(k,e);return x&&e.x402Charge?e.x402Charge(c,{functionPath:l,price:x.price},B,$e({waitUntil:R})):B()},Sn=Gn({functions:e.functions??{},invoke:En,readJsonBody:ee,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),De=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,An={[ka]: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"}}),[Ea]:(r,s,l)=>un(r,s,l),[Tt]:(r,s,l,c)=>wn(r,s,c),[Ra]:(r,s,l,c)=>gn(r,s,c),[Sa]:(r,s)=>G(r,s),[Aa]:(r,s)=>V(r,s),[Ta]:async r=>{K(r,"POST","ws-token"),q(r);const s=O();if(s===void 0)throw new d("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Dr(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...U,...ie,...Jt,...Yt,...Xt,...Zt,...en,...tn,...nn,...rn,...an,...Sn,...Br({assertAdmin:q,getAuthAdmin:()=>e.authAdmin,parsePaging:Ie,queryParameter:ke,readJsonBody:ee})};let ce=ct(e.security),et=!1;const Tn=r=>{et||(et=!0,ce=ct(e.security,r??{}))},On=async(r,s)=>{if(!(e.adminGate===void 0||!Ia(s)))try{await e.adminGate(r,ze.get(r))&&p.add(r)}catch{}},vn=async(r,s,l)=>{ze.set(r,l);const c=new URL(r.url);if(r.method==="POST"||r.method==="PUT"){const y=Number(r.headers.get("content-length")??""),S=_a[c.pathname]??Ut;if(Number.isFinite(y)&&y>S)throw new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await Rn(r,s,c,l);if(m)return m;if(De){const y=`${r.method} ${c.pathname}`,S=De[y]??De[c.pathname];if(S)return S(r,s,l)}const R=An[c.pathname];if(R)return await On(r,c.pathname),R(r,s,c,l);if(e.voiceAgents!==void 0&&c.pathname.startsWith(vt))return ln(r,s,c);const k=await dn(r,s,l);return k||new Response("Not found",{status:404})};return{async fetch(r,s,l){e.passThroughOnException&&l.passThroughOnException?.(),Tn(s),_(s);const c=dr(r,ce);if(c)return c;const m=ur(r,ce);if(m)return xe(m,r,ce);try{const R=await vn(r,s,l);return xe(R,r,ce)}catch(R){return xe(ot(R),r,ce)}finally{st(e.observability,kt(l))}},async queue(r,s,l){await Ze(`queue:${Ha(r)}`,l,async()=>{await e.queue?.(r,s,l)})},async scheduled(r,s,l){await Ze(`cron:${r.cron}`,l,async()=>{await bn(r,s,l)})},serverQuery:yn}},qa=e=>qt(e),Ja=e=>typeof e=="function"?{fetch:e}:e,Ya=e=>!!(e.crons??e.cronJobs??e.backupCron),bs=(e,t)=>{const n=Ja(e),o=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=u=>{const h=qa({...u,httpRouter:n});return o!==void 0&&!Ya(u)?{...h,scheduled:async(f,w,E)=>{await o(f,w,E)}}:h};if(typeof t!="function")return a(t);const i=t;return{fetch:(u,h,f)=>a(i(h)).fetch(u,h,f),queue:(u,h,f)=>a(i(h)).queue?.(u,h,f)??Promise.resolve(),scheduled:(u,h,f)=>a(i(h)).scheduled(u,h,f),serverQuery:(u,h,f,w,E)=>a(i(h)).serverQuery(u,h,f,w,E)}},Xa=(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}},_s=(e={})=>(t,n,o)=>qt(Xa(e,n)).fetch(t,n,o??Un),Rs=e=>e;export{xr as GET_AUTH_AUDIT_LOG_OP,Un as NOOP_EXECUTION_CONTEXT,As as composeIdentityResolvers,qa as composeWorker,_s as createLunoraHandler,qt as createWorker,Rs as defineRpcEnvelope,Ga as probeRelayCount,Xa as resolveLunoraOptions,Ts as routeIdentityResolvers,bs as withFrameworkWorker};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{raw as n,desc as F,sql as r}from"@lunora/bindings/r2sql";const u=["trace","debug","log","info","warn","error","fatal"],S={fields:"fields",functionPath:"functionPath",level:"level",message:"message",shardKey:"shardKey",spanId:"spanId",traceId:"traceId",ts:"ts",userId:"userId"},_=500,w=1e4,N=e=>e===void 0||!Number.isFinite(e)?_:Math.min(Math.max(Math.floor(e),1),w),D=e=>typeof e=="number"?e:Number(e),p=e=>e==null?"":String(e),U=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},K=e=>{const s=JSON.stringify([e.ts,e.level,e.functionPath,e.message,e.traceId,e.spanId,e.shardKey,e.userId,e.fields]);let t=0,l=0;for(const I of s){const v=I.codePointAt(0)??0;t=(t*31+v)%2147483647,l=(l*131+v)%4294967291}return`${t.toString(36)}.${l.toString(36)}`},y=(e,s,t,l)=>{if(s.sinceTs!==void 0&&e.where(r`${n(t.ts)} >= ${s.sinceTs}`),s.untilTs!==void 0&&e.where(r`${n(t.ts)} <= ${s.untilTs}`),s.level!==void 0)e.where(r`${n(t.level)} = ${s.level}`);else if(s.minLevel!==void 0){const I=u.indexOf(s.minLevel),v=I===-1?[...u]:u.slice(I);e.where(r`${n(t.level)} IN ${v}`)}s.functionPath!==void 0&&e.where(r`${n(t.functionPath)} = ${s.functionPath}`),s.functionPathPrefix!==void 0&&e.where(r`${n(t.functionPath)} LIKE ${`${s.functionPathPrefix}%`}`),s.traceId!==void 0&&e.where(r`${n(t.traceId)} = ${s.traceId}`),s.shardKey!==void 0&&e.where(r`${n(t.shardKey)} = ${s.shardKey}`),s.userId!==void 0&&e.where(r`${n(t.userId)} = ${s.userId}`),l!==void 0&&e.where(r`${n(t.ts)} <= ${l}`)},G=S,J=_,k=(e,s)=>{const t={...S,...s.columnMap},l=s.namespace===void 0?s.table:`${s.namespace}.${s.table}`,I=a=>{const c={functionPath:p(a[t.functionPath]),level:p(a[t.level]),message:p(a[t.message]),ts:D(a[t.ts])},o=a[t.fields];o!=null&&(c.fields=U(o));for(const d of["shardKey","userId","traceId","spanId"]){const i=a[t[d]];i!=null&&(c[d]=p(i))}return c},v=async(a,c,o)=>{const d=e.from(l).select(n(t.functionPath),n(t.level),n(t.message),n(t.ts),n(t.fields),n(t.shardKey),n(t.userId),n(t.traceId),n(t.spanId));y(d,a,t,c),d.orderBy(F(n(t.ts))).limit(o);const{rows:i}=await d.run();return i},A=async(a,c,o,d)=>{const i=await v(a,c,d),$=[];for(const P of i){const f=I(P);o!==void 0&&c!==void 0&&f.ts===c&&o.has(K(f))||$.push(f)}return{decoded:$,truncated:i.length>=d}};return{query:async(a={})=>{const c=N(a.limit),{cursor:o}=a,d=o?.ts,i=o?.seen!==void 0&&o.seen.length>0?new Set(o.seen):void 0,$=Math.min(c+1,w),P=3;let f=[],m=!1;for(let h=0;h<P;h+=1){const O=Math.min($*2**h,w),x=await A(a,d,i,O);if(f=x.decoded,m=x.truncated,f.length>c||!m||O>=w)break}const R=f.length>c,L=R?f.slice(0,c):f,M=L.at(-1);if(M===void 0||!(R||m))return{rows:L};const g=M.ts,E=L.filter(h=>h.ts===g).map(h=>K(h)),T=[...d===g&&o?.seen!==void 0?o.seen:[],...E];return{nextCursor:T.length>0?{seen:T,ts:g}:{ts:g},rows:L}}}};export{G as D,u as L,J as a,k as c};
|