@lunora/runtime 1.0.0-alpha.57 → 1.0.0-alpha.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -4,6 +4,76 @@ import { ShardDirectory } from '@lunora/platform';
4
4
  import { R2SqlClient } from '@lunora/bindings/r2sql';
5
5
  import { WorkflowsRestClient } from '@lunora/workflow';
6
6
  import { LunoraError as LunoraError$1, ErrorBody } from '@lunora/errors';
7
+ /**
8
+ * How a snapshot backup is laid out in an object store — the one definition
9
+ * both writers use.
10
+ *
11
+ * Two of them exist: the platform's scheduled backup (`backupCron` /
12
+ * `backupStore`, in `./scheduled-backup`) and `lunora backup create --bucket`
13
+ * in `@lunora/cli`. They deliberately share a bucket so an operator sees one
14
+ * history, which means they must agree on the key, the sidecar suffix, the
15
+ * manifest fields and what an `id` is. Written out twice, those four rules
16
+ * would drift the first time one side changed — this file is what makes
17
+ * "they agree" a type error rather than a comment.
18
+ *
19
+ * Zero dependencies and no I/O, so the CLI can import it without pulling a
20
+ * Worker runtime into its bundle.
21
+ */
22
+ /** Default key prefix backups live under. Both writers default here so one bucket is one history. */
23
+ declare const BACKUP_KEY_PREFIX = "backups/";
24
+ /**
25
+ * A prefix is a key prefix, not a directory, but everyone types it like one.
26
+ * Without this, `--prefix backups` / `backupPrefix: "backups"` yields
27
+ * `backupslunora-backup-…`: a key that works, sorts oddly, and matches nothing
28
+ * the other writer produced. Idempotent, and `""` stays `""` so the same
29
+ * builder can produce a bare file name.
30
+ */
31
+ declare const normalizeBackupPrefix: (prefix: string) => string;
32
+ /**
33
+ * The object key (or file name, with an empty `prefix`) for the snapshot taken
34
+ * at `id`.
35
+ *
36
+ * `id` is the ISO timestamp — `2026-06-01T12:00:00.000Z` — and stays that way
37
+ * in the manifest, because it is what `lunora backup restore <id>` matches on.
38
+ * Only the key swaps `:` and `.` for `-`, since both are awkward in file names
39
+ * and object keys. Conflating the two forms is why `restore` used to be
40
+ * documented with an argument it could never match.
41
+ */
42
+ declare const backupObjectKey: (prefix: string, id: string) => string;
43
+ /** The sidecar key for a snapshot at `objectKey`. */
44
+ declare const backupManifestKey: (objectKey: string) => string;
45
+ /** Is this the sidecar of a snapshot, rather than the snapshot itself? */
46
+ declare const isBackupManifestKey: (key: string) => boolean;
47
+ /**
48
+ * What every snapshot records about itself, whichever writer took it.
49
+ *
50
+ * `id` is the ISO timestamp the snapshot was taken at and the handle `restore`
51
+ * resolves; `file` is where it lives at its own destination (a file name in a
52
+ * directory, an object key in a bucket).
53
+ */
54
+ interface BackupManifestEntry {
55
+ /** Byte length of the snapshot as stored. */
56
+ bytes: number;
57
+ createdAt: string;
58
+ file: string;
59
+ id: string;
60
+ rows: number;
61
+ /**
62
+ * Lowercase-hex SHA-256 of the snapshot. Optional only because snapshots
63
+ * taken before checksums existed have none — `restore --verify` refuses
64
+ * those rather than reporting an unverified restore as a verified one.
65
+ */
66
+ sha256?: string;
67
+ /** The `--tables` / `backupTables` allowlist, when the snapshot is a subset. */
68
+ tables?: string;
69
+ }
70
+ /**
71
+ * Is this a backup manifest? The shape check both sides need: the reader, to
72
+ * skip an unrelated object under the prefix, and retention, to decide whether
73
+ * something is safe to delete. The side that deletes must not be the side
74
+ * without a guard.
75
+ */
76
+ declare const isBackupManifestEntry: (value: unknown) => value is BackupManifestEntry;
7
77
  /**
8
78
  * Turn-key incremental-sync source helpers for warehouse connectors
9
79
  * (Fivetran custom functions, Airbyte incremental sources).
@@ -2606,6 +2676,12 @@ type TraceTrustSignal = "mtls";
2606
2676
  * can reach the worker.
2607
2677
  */
2608
2678
  type TrustInboundTraceContext = boolean | TraceTrustSignal | ((request: Request) => boolean);
2679
+ /** A snapshot the scheduled backup took: the shared fields plus which trigger produced it. */
2680
+ interface BackupManifest extends BackupManifestEntry {
2681
+ cron: string;
2682
+ scheduledTime: number;
2683
+ sha256: string;
2684
+ }
2609
2685
  /**
2610
2686
  * Wire-format RPC envelope. Posted to `POST /_lunora/rpc`.
2611
2687
  *
@@ -2917,6 +2993,26 @@ type StorageUploadFunction = (key: string, body: ArrayBuffer, options?: {
2917
2993
  etag?: string;
2918
2994
  key: string;
2919
2995
  };
2996
+ /**
2997
+ * Reads one object's bytes back out of a storage bucket. Structurally the part
2998
+ * of `@lunora/storage`'s `Storage["download"]` the admin endpoint needs — the
2999
+ * body stream plus enough metadata to set the response headers. `null` means
3000
+ * "no such object", which the route turns into a 404.
3001
+ *
3002
+ * This is the read half of {@link StorageUploadFunction}: `lunora backup
3003
+ * restore --bucket` pulls a snapshot back through it under the same admin
3004
+ * bearer that wrote it, so restoring from a bucket does not depend on signed
3005
+ * URLs (which need a signing secret the deployment may not have configured).
3006
+ */
3007
+ type StorageDownloadFunction = (key: string, options?: {
3008
+ bucket?: string;
3009
+ }) => Promise<{
3010
+ body: ReadableStream | null;
3011
+ httpMetadata?: {
3012
+ contentType?: string;
3013
+ };
3014
+ size?: number;
3015
+ } | null>;
2920
3016
  /**
2921
3017
  * Mints a (signed or public) URL for one object so the admin file browser can
2922
3018
  * offer a "copy URL" action. The optional `expiresInSeconds` lets the caller pick
@@ -3094,40 +3190,34 @@ interface CronJobInfo {
3094
3190
  */
3095
3191
  interface BackupStore {
3096
3192
  delete: (key: string) => Promise<unknown>;
3193
+ /**
3194
+ * List objects under a prefix. `include: ["customMetadata"]` is how
3195
+ * retention tells its own snapshots from an operator's without a request
3196
+ * per object — R2 returns custom metadata on a listing only when asked, and
3197
+ * may return fewer than `limit` results when it is, which the cursor loop
3198
+ * already handles.
3199
+ */
3097
3200
  list: (options?: {
3098
3201
  cursor?: string;
3202
+ include?: ("customMetadata" | "httpMetadata")[];
3099
3203
  limit?: number;
3100
3204
  prefix?: string;
3101
3205
  }) => Promise<{
3102
3206
  cursor?: string;
3103
3207
  objects: ReadonlyArray<{
3208
+ customMetadata?: Record<string, string>;
3104
3209
  key: string;
3105
3210
  }>;
3106
3211
  truncated?: boolean;
3107
3212
  }>;
3108
- put: (key: string, body: ArrayBuffer | Blob | null | ReadableStream | string, options?: {
3213
+ put: (key: string, body: ArrayBuffer | ArrayBufferView | Blob | null | ReadableStream | string, options?: {
3109
3214
  customMetadata?: Record<string, string>;
3110
3215
  httpMetadata?: {
3111
3216
  contentType?: string;
3112
3217
  };
3218
+ sha256?: ArrayBuffer | string;
3113
3219
  }) => Promise<unknown>;
3114
3220
  }
3115
- /**
3116
- * Manifest sidecar written next to each scheduled backup's NDJSON object (at
3117
- * `<file>.manifest.json`). Mirrors the manifest entry the CLI records for local
3118
- * backups so both backup planes describe a snapshot the same way;
3119
- * `cron`/`scheduledTime` additionally record which trigger produced it.
3120
- */
3121
- interface BackupManifest {
3122
- bytes: number;
3123
- createdAt: string;
3124
- cron: string;
3125
- file: string;
3126
- id: string;
3127
- rows: number;
3128
- scheduledTime: number;
3129
- tables?: string;
3130
- }
3131
3221
  /**
3132
3222
  * Health / readiness probe configuration (plan 177). Everything is optional; the
3133
3223
  * runtime always registers its default binding probes, so the endpoints work
@@ -3722,6 +3812,17 @@ interface WorkerOptions {
3722
3812
  * `STORAGE_DELETE_NOT_CONFIGURED` — the studio surfaces a clear inline error.
3723
3813
  */
3724
3814
  storageDelete?: StorageDeleteFunction;
3815
+ /**
3816
+ * Reads one object back, backing the admin-gated
3817
+ * `GET /_lunora/admin/storage/object` endpoint that `lunora backup restore
3818
+ * --bucket` pulls snapshots through. Wrap the storage call — the generated
3819
+ * app worker emits
3820
+ * `(key, opts) => pick(opts?.bucket).download(key)` — rather than passing
3821
+ * `createStorage(...).download` itself, whose second parameter is a byte
3822
+ * range, not a bucket. Omit it and the endpoint responds
3823
+ * `STORAGE_DOWNLOAD_NOT_CONFIGURED`.
3824
+ */
3825
+ storageDownload?: StorageDownloadFunction;
3725
3826
  /**
3726
3827
  * Storage lister backing the admin-gated `GET /_lunora/admin/storage`
3727
3828
  * endpoint the studio's file browser calls. The structural shape matches
@@ -4691,5 +4792,14 @@ interface ShardClient {
4691
4792
  * See the module docs for the privilege model and the authorization caveat.
4692
4793
  */
4693
4794
  declare const createShardClient: (namespace: ShardNamespaceLike, options?: ShardClientOptions) => ShardClient;
4795
+ /**
4796
+ * Body budget for an object upload, declared by this route the way the KV value
4797
+ * PUT declares its own (`KV_VALUE_MAX_BODY_BYTES`). The shared 1 MiB default is
4798
+ * a JSON-request cap; a blob migration (`lunora import --with-storage`) moves
4799
+ * real files, and a 1 MiB ceiling would push nearly every photo onto the
4800
+ * signed-URL fallback. 32 MiB is what the isolate can buffer and digest
4801
+ * comfortably inside the Workers memory limit.
4802
+ */
4803
+ declare const STORAGE_UPLOAD_MAX_BODY_BYTES: number;
4694
4804
  declare const VERSION: string;
4695
- export { 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, type BackupManifest, 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_LOG_LIMIT, 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, 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 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, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, 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, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
4805
+ export { 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 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_LOG_LIMIT, 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, 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 QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
package/dist/index.d.ts CHANGED
@@ -4,6 +4,76 @@ import { ShardDirectory } from '@lunora/platform';
4
4
  import { R2SqlClient } from '@lunora/bindings/r2sql';
5
5
  import { WorkflowsRestClient } from '@lunora/workflow';
6
6
  import { LunoraError as LunoraError$1, ErrorBody } from '@lunora/errors';
7
+ /**
8
+ * How a snapshot backup is laid out in an object store — the one definition
9
+ * both writers use.
10
+ *
11
+ * Two of them exist: the platform's scheduled backup (`backupCron` /
12
+ * `backupStore`, in `./scheduled-backup`) and `lunora backup create --bucket`
13
+ * in `@lunora/cli`. They deliberately share a bucket so an operator sees one
14
+ * history, which means they must agree on the key, the sidecar suffix, the
15
+ * manifest fields and what an `id` is. Written out twice, those four rules
16
+ * would drift the first time one side changed — this file is what makes
17
+ * "they agree" a type error rather than a comment.
18
+ *
19
+ * Zero dependencies and no I/O, so the CLI can import it without pulling a
20
+ * Worker runtime into its bundle.
21
+ */
22
+ /** Default key prefix backups live under. Both writers default here so one bucket is one history. */
23
+ declare const BACKUP_KEY_PREFIX = "backups/";
24
+ /**
25
+ * A prefix is a key prefix, not a directory, but everyone types it like one.
26
+ * Without this, `--prefix backups` / `backupPrefix: "backups"` yields
27
+ * `backupslunora-backup-…`: a key that works, sorts oddly, and matches nothing
28
+ * the other writer produced. Idempotent, and `""` stays `""` so the same
29
+ * builder can produce a bare file name.
30
+ */
31
+ declare const normalizeBackupPrefix: (prefix: string) => string;
32
+ /**
33
+ * The object key (or file name, with an empty `prefix`) for the snapshot taken
34
+ * at `id`.
35
+ *
36
+ * `id` is the ISO timestamp — `2026-06-01T12:00:00.000Z` — and stays that way
37
+ * in the manifest, because it is what `lunora backup restore <id>` matches on.
38
+ * Only the key swaps `:` and `.` for `-`, since both are awkward in file names
39
+ * and object keys. Conflating the two forms is why `restore` used to be
40
+ * documented with an argument it could never match.
41
+ */
42
+ declare const backupObjectKey: (prefix: string, id: string) => string;
43
+ /** The sidecar key for a snapshot at `objectKey`. */
44
+ declare const backupManifestKey: (objectKey: string) => string;
45
+ /** Is this the sidecar of a snapshot, rather than the snapshot itself? */
46
+ declare const isBackupManifestKey: (key: string) => boolean;
47
+ /**
48
+ * What every snapshot records about itself, whichever writer took it.
49
+ *
50
+ * `id` is the ISO timestamp the snapshot was taken at and the handle `restore`
51
+ * resolves; `file` is where it lives at its own destination (a file name in a
52
+ * directory, an object key in a bucket).
53
+ */
54
+ interface BackupManifestEntry {
55
+ /** Byte length of the snapshot as stored. */
56
+ bytes: number;
57
+ createdAt: string;
58
+ file: string;
59
+ id: string;
60
+ rows: number;
61
+ /**
62
+ * Lowercase-hex SHA-256 of the snapshot. Optional only because snapshots
63
+ * taken before checksums existed have none — `restore --verify` refuses
64
+ * those rather than reporting an unverified restore as a verified one.
65
+ */
66
+ sha256?: string;
67
+ /** The `--tables` / `backupTables` allowlist, when the snapshot is a subset. */
68
+ tables?: string;
69
+ }
70
+ /**
71
+ * Is this a backup manifest? The shape check both sides need: the reader, to
72
+ * skip an unrelated object under the prefix, and retention, to decide whether
73
+ * something is safe to delete. The side that deletes must not be the side
74
+ * without a guard.
75
+ */
76
+ declare const isBackupManifestEntry: (value: unknown) => value is BackupManifestEntry;
7
77
  /**
8
78
  * Turn-key incremental-sync source helpers for warehouse connectors
9
79
  * (Fivetran custom functions, Airbyte incremental sources).
@@ -2606,6 +2676,12 @@ type TraceTrustSignal = "mtls";
2606
2676
  * can reach the worker.
2607
2677
  */
2608
2678
  type TrustInboundTraceContext = boolean | TraceTrustSignal | ((request: Request) => boolean);
2679
+ /** A snapshot the scheduled backup took: the shared fields plus which trigger produced it. */
2680
+ interface BackupManifest extends BackupManifestEntry {
2681
+ cron: string;
2682
+ scheduledTime: number;
2683
+ sha256: string;
2684
+ }
2609
2685
  /**
2610
2686
  * Wire-format RPC envelope. Posted to `POST /_lunora/rpc`.
2611
2687
  *
@@ -2917,6 +2993,26 @@ type StorageUploadFunction = (key: string, body: ArrayBuffer, options?: {
2917
2993
  etag?: string;
2918
2994
  key: string;
2919
2995
  };
2996
+ /**
2997
+ * Reads one object's bytes back out of a storage bucket. Structurally the part
2998
+ * of `@lunora/storage`'s `Storage["download"]` the admin endpoint needs — the
2999
+ * body stream plus enough metadata to set the response headers. `null` means
3000
+ * "no such object", which the route turns into a 404.
3001
+ *
3002
+ * This is the read half of {@link StorageUploadFunction}: `lunora backup
3003
+ * restore --bucket` pulls a snapshot back through it under the same admin
3004
+ * bearer that wrote it, so restoring from a bucket does not depend on signed
3005
+ * URLs (which need a signing secret the deployment may not have configured).
3006
+ */
3007
+ type StorageDownloadFunction = (key: string, options?: {
3008
+ bucket?: string;
3009
+ }) => Promise<{
3010
+ body: ReadableStream | null;
3011
+ httpMetadata?: {
3012
+ contentType?: string;
3013
+ };
3014
+ size?: number;
3015
+ } | null>;
2920
3016
  /**
2921
3017
  * Mints a (signed or public) URL for one object so the admin file browser can
2922
3018
  * offer a "copy URL" action. The optional `expiresInSeconds` lets the caller pick
@@ -3094,40 +3190,34 @@ interface CronJobInfo {
3094
3190
  */
3095
3191
  interface BackupStore {
3096
3192
  delete: (key: string) => Promise<unknown>;
3193
+ /**
3194
+ * List objects under a prefix. `include: ["customMetadata"]` is how
3195
+ * retention tells its own snapshots from an operator's without a request
3196
+ * per object — R2 returns custom metadata on a listing only when asked, and
3197
+ * may return fewer than `limit` results when it is, which the cursor loop
3198
+ * already handles.
3199
+ */
3097
3200
  list: (options?: {
3098
3201
  cursor?: string;
3202
+ include?: ("customMetadata" | "httpMetadata")[];
3099
3203
  limit?: number;
3100
3204
  prefix?: string;
3101
3205
  }) => Promise<{
3102
3206
  cursor?: string;
3103
3207
  objects: ReadonlyArray<{
3208
+ customMetadata?: Record<string, string>;
3104
3209
  key: string;
3105
3210
  }>;
3106
3211
  truncated?: boolean;
3107
3212
  }>;
3108
- put: (key: string, body: ArrayBuffer | Blob | null | ReadableStream | string, options?: {
3213
+ put: (key: string, body: ArrayBuffer | ArrayBufferView | Blob | null | ReadableStream | string, options?: {
3109
3214
  customMetadata?: Record<string, string>;
3110
3215
  httpMetadata?: {
3111
3216
  contentType?: string;
3112
3217
  };
3218
+ sha256?: ArrayBuffer | string;
3113
3219
  }) => Promise<unknown>;
3114
3220
  }
3115
- /**
3116
- * Manifest sidecar written next to each scheduled backup's NDJSON object (at
3117
- * `<file>.manifest.json`). Mirrors the manifest entry the CLI records for local
3118
- * backups so both backup planes describe a snapshot the same way;
3119
- * `cron`/`scheduledTime` additionally record which trigger produced it.
3120
- */
3121
- interface BackupManifest {
3122
- bytes: number;
3123
- createdAt: string;
3124
- cron: string;
3125
- file: string;
3126
- id: string;
3127
- rows: number;
3128
- scheduledTime: number;
3129
- tables?: string;
3130
- }
3131
3221
  /**
3132
3222
  * Health / readiness probe configuration (plan 177). Everything is optional; the
3133
3223
  * runtime always registers its default binding probes, so the endpoints work
@@ -3722,6 +3812,17 @@ interface WorkerOptions {
3722
3812
  * `STORAGE_DELETE_NOT_CONFIGURED` — the studio surfaces a clear inline error.
3723
3813
  */
3724
3814
  storageDelete?: StorageDeleteFunction;
3815
+ /**
3816
+ * Reads one object back, backing the admin-gated
3817
+ * `GET /_lunora/admin/storage/object` endpoint that `lunora backup restore
3818
+ * --bucket` pulls snapshots through. Wrap the storage call — the generated
3819
+ * app worker emits
3820
+ * `(key, opts) => pick(opts?.bucket).download(key)` — rather than passing
3821
+ * `createStorage(...).download` itself, whose second parameter is a byte
3822
+ * range, not a bucket. Omit it and the endpoint responds
3823
+ * `STORAGE_DOWNLOAD_NOT_CONFIGURED`.
3824
+ */
3825
+ storageDownload?: StorageDownloadFunction;
3725
3826
  /**
3726
3827
  * Storage lister backing the admin-gated `GET /_lunora/admin/storage`
3727
3828
  * endpoint the studio's file browser calls. The structural shape matches
@@ -4691,5 +4792,14 @@ interface ShardClient {
4691
4792
  * See the module docs for the privilege model and the authorization caveat.
4692
4793
  */
4693
4794
  declare const createShardClient: (namespace: ShardNamespaceLike, options?: ShardClientOptions) => ShardClient;
4795
+ /**
4796
+ * Body budget for an object upload, declared by this route the way the KV value
4797
+ * PUT declares its own (`KV_VALUE_MAX_BODY_BYTES`). The shared 1 MiB default is
4798
+ * a JSON-request cap; a blob migration (`lunora import --with-storage`) moves
4799
+ * real files, and a 1 MiB ceiling would push nearly every photo onto the
4800
+ * signed-URL fallback. 32 MiB is what the isolate can buffer and digest
4801
+ * comfortably inside the Workers memory limit.
4802
+ */
4803
+ declare const STORAGE_UPLOAD_MAX_BODY_BYTES: number;
4694
4804
  declare const VERSION: string;
4695
- export { 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, type BackupManifest, 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_LOG_LIMIT, 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, 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 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, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, 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, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
4805
+ export { 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 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_LOG_LIMIT, 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, 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 QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{toAirbyteMessages as t,toFivetranResponse as a}from"./packem_shared/toAirbyteMessages-DTk8e2f9.mjs";import{composeWorker as i,createLunoraHandler as n,createWorker as p,defineRpcEnvelope as m,resolveLunoraOptions as c,withFrameworkWorker as R}from"./packem_shared/composeWorker-DxXwbTng.mjs";import{createCrossShardRelationCapabilities as S}from"./packem_shared/createCrossShardRelationCapabilities-CQfrCIWR.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as f,SHARD_REGISTRY_DO_NAME as l,createDynamicShardRegistry as x}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-CCDyswsf.mjs";import{LunoraError as y,toErrorResponse as C}from"./packem_shared/LunoraError-ByasbDmd.mjs";import{createKvCursorStore as g,createMemoryCursorStore as u,defineExportSink as T,r2Sink as A,runExportTap as h,sanitizeChange as k,webhookExportSink as O}from"./packem_shared/createKvCursorStore-C24tEuYk.mjs";import{HEALTH_PATH as v,HEALTH_READY_PATH as I,buildHealthRoutes as b,d1Probe as F,durableObjectProbe as P,presenceProbe as D}from"./packem_shared/HEALTH_PATH-BuLCcWNS.mjs";import{LOG_ARCHIVE_PATH as G,resolveLogArchiveFromEnv as U}from"./packem_shared/LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{memoizeIdentity as w,memoizeIdentityPerRequest as z}from"./packem_shared/memoizeIdentity-CX3xEPYw.mjs";import{e as W,a as Y}from"./packem_shared/observability-DWlkDJJw.mjs";import{analyticsEngineSink as K,combineSinks as Q,consoleSink as X,otlpSink as j,pipelineLogSink as J,sentrySink as B,webhookSink as Z}from"./packem_shared/analyticsEngineSink-iIRy11I9.mjs";import{D as ee,a as re,c as oe}from"./packem_shared/pipeline-log-reader-FF1V32O2.mjs";import{createQueryCoordinator as ae,createStaticShardRegistry as se,mergeStrategyForAggregate as ie}from"./packem_shared/createQueryCoordinator-BkPfcxUG.mjs";import{applyJurisdiction as pe,resolveShard as me}from"./packem_shared/applyJurisdiction-Dsm_m5zW.mjs";import{R as Re,d as Ee,o as Se}from"./packem_shared/rest-cache-5unAzdFN.mjs";import{g as fe,E as le,U as xe,p as _e,y as ye}from"./packem_shared/rest-routes-BqldHiaH.mjs";import{decorateResponse as Le,enforceOrigin as ge,handleCorsPreflight as ue,resolveSecurity as Te}from"./packem_shared/decorateResponse-DBIWsRSZ.mjs";import{createShardClient as he}from"./packem_shared/createShardClient-BYYzDbMc.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Oe}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as ve}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as be,routeIdentityResolvers as Fe}from"./packem_shared/composeIdentityResolvers-DwE0Jbww.mjs";const e="0.0.0";export{ee as DEFAULT_LOG_COLUMNS,re as DEFAULT_LOG_LIMIT,f as DEFAULT_REGISTRY_CACHE_TTL_MS,v as HEALTH_PATH,I as HEALTH_READY_PATH,Oe as LOG_ARCHIVE_NOT_CONFIGURED,G as LOG_ARCHIVE_PATH,y as LunoraError,ve as NOOP_EXECUTION_CONTEXT,l as SHARD_REGISTRY_DO_NAME,e as VERSION,K as analyticsEngineSink,pe as applyJurisdiction,Re as applyRestCache,fe as argsFromQuery,b as buildHealthRoutes,le as buildRestRoutes,Q as combineSinks,be as composeIdentityResolvers,i as composeWorker,X as consoleSink,S as createCrossShardRelationCapabilities,x as createDynamicShardRegistry,g as createKvCursorStore,n as createLunoraHandler,u as createMemoryCursorStore,oe as createPipelineLogReader,ae as createQueryCoordinator,xe as createRestRateLimit,he as createShardClient,se as createStaticShardRegistry,p as createWorker,F as d1Probe,Le as decorateResponse,T as defineExportSink,m as defineRpcEnvelope,P as durableObjectProbe,W as emitLogEvent,Y as emitRpcEvent,ge as enforceOrigin,ue as handleCorsPreflight,w as memoizeIdentity,z as memoizeIdentityPerRequest,ie as mergeStrategyForAggregate,j as otlpSink,J as pipelineLogSink,D as presenceProbe,A as r2Sink,_e as readShardKey,Ee as requestCarriesCredentials,U as resolveLogArchiveFromEnv,c as resolveLunoraOptions,Te as resolveSecurity,me as resolveShard,Se as restCacheHeaders,ye as restSurfaceFromRegistry,Fe as routeIdentityResolvers,h as runExportTap,k as sanitizeChange,B as sentrySink,t as toAirbyteMessages,C as toErrorResponse,a as toFivetranResponse,O as webhookExportSink,Z as webhookSink,R as withFrameworkWorker};
1
+ import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,isBackupManifestEntry as i,isBackupManifestKey as n,normalizeBackupPrefix as p}from"./packem_shared/BACKUP_KEY_PREFIX-DhFUE3VL.mjs";import{toAirbyteMessages as c,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-DTk8e2f9.mjs";import{composeWorker as R,createLunoraHandler as S,createWorker as x,defineRpcEnvelope as _,resolveLunoraOptions as d,withFrameworkWorker as l}from"./packem_shared/composeWorker-3QukUt7p.mjs";import{createCrossShardRelationCapabilities as y}from"./packem_shared/createCrossShardRelationCapabilities-CQfrCIWR.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as C,createDynamicShardRegistry as L}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-CCDyswsf.mjs";import{LunoraError as T,toErrorResponse as g}from"./packem_shared/LunoraError-ByasbDmd.mjs";import{createKvCursorStore as b,createMemoryCursorStore as H,defineExportSink as I,r2Sink as P,runExportTap as v,sanitizeChange as D,webhookExportSink as F}from"./packem_shared/createKvCursorStore-C24tEuYk.mjs";import{HEALTH_PATH as U,HEALTH_READY_PATH as G,buildHealthRoutes as N,d1Probe as K,durableObjectProbe as B,presenceProbe as Y}from"./packem_shared/HEALTH_PATH-BuLCcWNS.mjs";import{LOG_ARCHIVE_PATH as z,resolveLogArchiveFromEnv as X}from"./packem_shared/LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as j}from"./packem_shared/memoizeIdentity-CX3xEPYw.mjs";import{e as Q,a as J}from"./packem_shared/observability-DWlkDJJw.mjs";import{analyticsEngineSink as $,combineSinks as ee,consoleSink as re,otlpSink as oe,pipelineLogSink as te,sentrySink as ae,webhookSink as se}from"./packem_shared/analyticsEngineSink-iIRy11I9.mjs";import{D as ne,a as pe,c as me}from"./packem_shared/pipeline-log-reader-FF1V32O2.mjs";import{createQueryCoordinator as Ee,createStaticShardRegistry as fe,mergeStrategyForAggregate as Re}from"./packem_shared/createQueryCoordinator-BkPfcxUG.mjs";import{applyJurisdiction as xe,resolveShard as _e}from"./packem_shared/applyJurisdiction-Dsm_m5zW.mjs";import{R as le,d as ue,o as ye}from"./packem_shared/rest-cache-5unAzdFN.mjs";import{g as Ae,E as Ce,U as Le,p as Oe,y as Te}from"./packem_shared/rest-routes-BqldHiaH.mjs";import{decorateResponse as he,enforceOrigin as be,handleCorsPreflight as He,resolveSecurity as Ie}from"./packem_shared/decorateResponse-DBIWsRSZ.mjs";import{createShardClient as ve}from"./packem_shared/createShardClient-BYYzDbMc.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Fe}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-K0uZPIUj.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ue}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 Be,routeIdentityResolvers as Ye}from"./packem_shared/composeIdentityResolvers-DwE0Jbww.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,ne as DEFAULT_LOG_COLUMNS,pe as DEFAULT_LOG_LIMIT,A as DEFAULT_REGISTRY_CACHE_TTL_MS,U as HEALTH_PATH,G as HEALTH_READY_PATH,Ue as LOG_ARCHIVE_NOT_CONFIGURED,z as LOG_ARCHIVE_PATH,T as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,C as SHARD_REGISTRY_DO_NAME,Fe as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,$ as analyticsEngineSink,xe as applyJurisdiction,le as applyRestCache,Ae as argsFromQuery,a as backupManifestKey,s as backupObjectKey,N as buildHealthRoutes,Ce as buildRestRoutes,ee as combineSinks,Be as composeIdentityResolvers,R as composeWorker,re as consoleSink,y as createCrossShardRelationCapabilities,L as createDynamicShardRegistry,b as createKvCursorStore,S as createLunoraHandler,H as createMemoryCursorStore,me as createPipelineLogReader,Ee as createQueryCoordinator,Le as createRestRateLimit,ve as createShardClient,fe as createStaticShardRegistry,x as createWorker,K as d1Probe,he as decorateResponse,I as defineExportSink,_ as defineRpcEnvelope,B as durableObjectProbe,Q as emitLogEvent,J as emitRpcEvent,be as enforceOrigin,He as handleCorsPreflight,i as isBackupManifestEntry,n as isBackupManifestKey,W as memoizeIdentity,j as memoizeIdentityPerRequest,Re as mergeStrategyForAggregate,p as normalizeBackupPrefix,oe as otlpSink,te as pipelineLogSink,Y as presenceProbe,P as r2Sink,Oe as readShardKey,ue as requestCarriesCredentials,X as resolveLogArchiveFromEnv,d as resolveLunoraOptions,Ie as resolveSecurity,_e as resolveShard,ye as restCacheHeaders,Te as restSurfaceFromRegistry,Ye as routeIdentityResolvers,v as runExportTap,D as sanitizeChange,ae as sentrySink,c as toAirbyteMessages,g as toErrorResponse,E as toFivetranResponse,F as webhookExportSink,se as webhookSink,l as withFrameworkWorker};
@@ -0,0 +1 @@
1
+ const i="backups/",n=e=>e===""||e.endsWith("/")?e:`${e}/`,a=".manifest.json",c=(e,s)=>`${n(e)}lunora-backup-${s.replaceAll(/[.:]/gu,"-")}.ndjson`,p=e=>`${e}${a}`,t=e=>e.endsWith(a),f=e=>e.slice(0,-a.length),o=e=>typeof e=="object"&&e!==null&&typeof e.id=="string"&&typeof e.file=="string";export{i as BACKUP_KEY_PREFIX,p as backupManifestKey,c as backupObjectKey,f as backupObjectKeyOfManifest,o as isBackupManifestEntry,t as isBackupManifestKey,n as normalizeBackupPrefix};
@@ -0,0 +1 @@
1
+ import{LunoraError as g}from"./LunoraError-ByasbDmd.mjs";import{r as _}from"./method-guard-rzvo19pa.mjs";const f="/_lunora/admin/storage",N="/_lunora/admin/storage/object",j="/_lunora/admin/storage/url",P="/_lunora/admin/storage/buckets",C=10080*60,q=32*1048576,v=new Set(["GET","PUT"]),B=S=>{const w=new Uint8Array(S);let E="";for(const o of w)E+=o.toString(16).padStart(2,"0");return E},F=S=>{const{assertAdmin:w,parsePaging:E,queryParameter:o,readBodyBytes:O,requireAdminOption:c,storage:i}=S,l=e=>{const n=o(e,"key");if(n===void 0)throw new g("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return n},R=async e=>{const n=c(e,i.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),t=new URL(e.url),r=await n(o(t,"prefix"),{bucket:o(t,"bucket"),cursor:o(t,"cursor"),...E(e)});return Response.json(r,{headers:{"content-type":"application/json"},status:200})},y=e=>(_(e,"GET","Storage-buckets"),w(e),Response.json({buckets:i.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})),U=async e=>{const n=c(e,i.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),t=new URL(e.url),r=l(t);return await n(r,{bucket:o(t,"bucket")}),Response.json({deleted:!0,key:r},{headers:{"content-type":"application/json"},status:200})},m=async e=>{const n=c(e,i.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),t=new URL(e.url),r=l(t),s=await O(e,q),u=e.headers.get("content-type"),d=u===null||u===""?void 0:u,p=o(t,"expectedSha256"),T=o(t,"expectedSize");let a;if(p!==void 0||T!==void 0){const G=await crypto.subtle.digest("SHA-256",s);a=B(G);const L=T!==void 0&&s.byteLength!==Number(T),D=p!==void 0&&a!==p.toLowerCase();if(L||D)throw new g("Upload failed verification — the body did not match the declared size or SHA-256 checksum, so nothing was written",{code:"STORAGE_CHECKSUM_MISMATCH",status:400})}const h=await n(r,s,{bucket:o(t,"bucket"),contentType:d,sha256:a});return Response.json(a===void 0?h:{...h,sha256:a},{headers:{"content-type":"application/json"},status:200})},A=async e=>{switch(e.method){case"DELETE":return U(e);case"GET":return R(e);case"POST":case"PUT":return m(e);default:throw new g("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},b=async e=>{_(e,"GET","Storage-object");const n=c(e,i.storageDownload,{code:"STORAGE_DOWNLOAD_NOT_CONFIGURED",message:"storage download requires a `storageDownload` function on the worker"}),t=new URL(e.url),r=l(t),s=await n(r,{bucket:o(t,"bucket")});if(!s?.body)throw new g(`No object at key ${r}`,{code:"STORAGE_OBJECT_NOT_FOUND",status:404});return new Response(s.body,{headers:{"content-type":s.httpMetadata?.contentType??"application/octet-stream",...s.size===void 0?{}:{"content-length":String(s.size)}},status:200})},k=async e=>{_(e,"GET","Storage URL");const n=c(e,i.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),t=new URL(e.url),r=l(t),s=Number(o(t,"expiresIn")??""),u=Number.isFinite(s)&&s>0?Math.min(s,C):void 0,d=o(t,"method");if(d!==void 0&&!v.has(d))throw new g("Storage URL `method` must be GET or PUT",{code:"BAD_REQUEST",status:400});const p=d,T=o(t,"contentType"),a=await n(r,{bucket:o(t,"bucket"),contentType:T,expiresInSeconds:u,method:p});return Response.json({key:r,url:a},{headers:{"content-type":"application/json"},status:200})};return{[P]:y,[N]:b,[f]:A,[j]:k}};export{P as STORAGE_BUCKETS_PATH,f as STORAGE_PATH,q as STORAGE_UPLOAD_MAX_BODY_BYTES,j as STORAGE_URL_PATH,F as buildStorageAdminRoutes,B as toHex};
@@ -0,0 +1,6 @@
1
+ import{isLunoraError as ur,toErrorBody as lr}from"@lunora/errors";import{d as Rt}from"./evict-oldest-C2XU6HBR.mjs";import{NOOP_EXECUTION_CONTEXT as hr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{f as pr,u as fr}from"./identity-header-pdXOyDU4.mjs";import{O as Ae,m as mr,A as wr,R as yr,d as gr,i as br,s as _r}from"./otlp-resource-B-ByO9qo.mjs";import{h as Z,f as be,i as Et,E as Rr,w as St,e as Ot,b as Er}from"./rest-routes-BqldHiaH.mjs";import{LunoraError as d,toErrorResponse as Je}from"./LunoraError-ByasbDmd.mjs";import{runExportTap as Sr}from"./createKvCursorStore-C24tEuYk.mjs";import{t as we,r as j}from"./method-guard-rzvo19pa.mjs";import{buildHealthRoutes as Or,durableObjectProbe as Tr,d1Probe as Ar,presenceProbe as Ne}from"./HEALTH_PATH-BuLCcWNS.mjs";import{wrapResolverWithContract as vr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as Mo,routeIdentityResolvers as zo}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as kr}from"./LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{o as Ir,f as Ve,a as de}from"./observability-DWlkDJJw.mjs";import{resolveShard as ye,applyJurisdiction as Ye}from"./applyJurisdiction-Dsm_m5zW.mjs";import{normalizeBackupPrefix as Dr,BACKUP_KEY_PREFIX as Pr,backupObjectKey as Ur,backupManifestKey as Nr,isBackupManifestKey as qr,backupObjectKeyOfManifest as Cr}from"./BACKUP_KEY_PREFIX-DhFUE3VL.mjs";import{toHex as xr,STORAGE_UPLOAD_MAX_BODY_BYTES as Br,STORAGE_PATH as $r,buildStorageAdminRoutes as jr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-K0uZPIUj.mjs";import{resolveSecurity as Xe,handleCorsPreflight as Kr,enforceOrigin as Lr,decorateResponse as qe,enforceWebSocketOrigin as Ze}from"./decorateResponse-DBIWsRSZ.mjs";const Fr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const r={...t,bucketName:"default"};return r.bucket=()=>r,r},Tt="__lunoraBranch",Qr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Tt),Gr=`may not contain the reserved workflow branch-marker key ("${Tt}")`,Fe=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let o=0;o<r;o+=1){const i=o<e.length?e.charCodeAt(o):0,u=o<t.length?t.charCodeAt(o):0;n|=i^u}return n===0},Qe=new TextEncoder,Mr=Array.from({length:32},(e,t)=>t);new RegExp(`[${Mr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const zr=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Wr=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)n[o]=r.codePointAt(o)??0;return n},Hr=64,Ce=new Map,At=async e=>{const t=Ce.get(e);if(t)return t;Rt(Ce,Hr);const r=crypto.subtle.importKey("raw",Qe.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ce.set(e,r),r},vt=async(e,t)=>{const r=await At(e),n=await crypto.subtle.sign("HMAC",r,Qe.encode(t));return zr(new Uint8Array(n))},Jr=async(e,t,r)=>{const n=await At(e);return crypto.subtle.verify("HMAC",n,r,Qe.encode(t))},Vr="::relay::",Yr=(e,t)=>`${e}${Vr}${String(t)}`,Xr=new Set(["1","enabled","on","true","yes"]),Zr=new Set(["0","disabled","false","no","off"]),en=(e,t)=>{const r=(e??"").trim().toLowerCase();return Xr.has(r)?!0:Zr.has(r)?!1:t},kt="v1",tn=6e4,rn=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??tn),n=`${kt}.${String(r)}`,o=await vt(e,n);return{expiresAtMs:r,token:`${n}.${o}`}},nn=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[o,i,u]=n;if(o!==kt||u.length===0)return!1;const l=Number(i);if(!Number.isFinite(l)||l<=r)return!1;let f;try{f=Wr(u)}catch{return!1}return Jr(e,`${o}.${i}`,f)},I="/_lunora/admin/auth",an={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},P=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new d(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new d(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},It=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,xe=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},et=e=>{const t=It(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new d("`role` is required",{code:"BAD_REQUEST",status:400});return t},tt=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 r={};for(const[n,o]of Object.entries(t))Array.isArray(o)&&o.every(i=>typeof i=="string")&&(r[n]=o);return r},on={[`${I}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${I}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${I}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${I}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${I}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${I}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${I}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${I}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${I}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${I}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${I}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${I}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${I}/users/create`]:{build:({body:e})=>({data:xe(e,"data"),email:P(e,"email"),name:P(e,"name"),password:te(e,"password"),role:It(e.role)}),http:"POST",method:"createUser"},[`${I}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:P(e,"userId")}},http:"POST",method:"updateUser"},[`${I}/users/role`]:{build:({body:e})=>({role:et(e),userId:P(e,"userId")}),http:"POST",method:"setRole"},[`${I}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:P(e,"userId")}),http:"POST",method:"banUser"},[`${I}/users/unban`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"unbanUser"},[`${I}/users/password`]:{build:({body:e})=>({newPassword:P(e,"newPassword"),userId:P(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${I}/users/remove`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${I}/users/impersonate`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"impersonateUser"},[`${I}/sessions/revoke`]:{build:({body:e})=>({sessionId:P(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${I}/sessions/revoke-all`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${I}/accounts/unlink`]:{build:({body:e})=>({accountId:P(e,"accountId"),userId:P(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${I}/two-factor/disable`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${I}/passkeys/delete`]:{build:({body:e})=>({passkeyId:P(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${I}/organizations/members/remove`]:{build:({body:e})=>({memberId:P(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${I}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:P(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${I}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:xe(e,"metadata"),name:P(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${I}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:xe(e,"metadata"),name:te(e,"name"),organizationId:P(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${I}/organizations/remove`]:{build:({body:e})=>({organizationId:P(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${I}/organizations/members/add`]:{build:({body:e})=>({organizationId:P(e,"organizationId"),role:te(e,"role"),userId:P(e,"userId")}),http:"POST",method:"addMember"},[`${I}/organizations/members/invite`]:{build:({body:e})=>({email:P(e,"email"),inviterId:te(e,"inviterId"),organizationId:P(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${I}/organizations/members/role`]:{build:({body:e})=>({memberId:P(e,"memberId"),role:et(e)}),http:"POST",method:"updateMemberRole"},[`${I}/organizations/teams/create`]:{build:({body:e})=>({name:P(e,"name"),organizationId:P(e,"organizationId")}),http:"POST",method:"createTeam"},[`${I}/organizations/teams/update`]:{build:({body:e})=>({name:P(e,"name"),teamId:P(e,"teamId")}),http:"POST",method:"updateTeam"},[`${I}/organizations/teams/remove`]:{build:({body:e})=>({teamId:P(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${I}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:P(e,"teamId"),userId:P(e,"userId")}),http:"POST",method:"addTeamMember"},[`${I}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:P(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${I}/organizations/roles/create`]:{build:({body:e})=>({organizationId:P(e,"organizationId"),permission:tt(e),role:P(e,"role")}),http:"POST",method:"createOrgRole"},[`${I}/organizations/roles/update`]:{build:({body:e})=>({permission:tt(e),roleId:P(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${I}/organizations/roles/remove`]:{build:({body:e})=>({roleId:P(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},sn=e=>{const t=async o=>{try{return await o()}catch(i){if(i instanceof d)throw i;const u=i,l=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:l,status:an[l]??500})}},r=async(o,i)=>{if(e.assertAdmin(o),o.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 l=u[i.method];if(l===void 0)throw new d(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(o.url),b={body:i.http==="POST"?await e.readJsonBody(o):{},paging:e.parsePaging(o),query:_=>e.queryParameter(f,_)},E=i.build(b),y=await t(()=>l(E));return Response.json(i.returns==="void"?{ok:!0}:y,{headers:{"content-type":"application/json"},status:200})},n={};for(const[o,i]of Object.entries(on))n[o]=u=>r(u,i);return n},dn="__lunora_admin__:getAuthAuditLog",rt=e=>typeof e=="string"&&e!==""?e:void 0,nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,cn=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new d("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const o=rt(r.actorId),i=rt(r.event),u=nt(r.sinceSeq),l=nt(r.limit),f={...o===void 0?{}:{actorId:o},...i===void 0?{}:{event:i},...u===void 0?{}:{sinceSeq:u},...l===void 0?{}:{limit:l}};let b;try{b=await n.read(f)}catch(y){throw y instanceof d?y:(console.error("[lunora] auth audit read failed:",y),new d("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const E={entries:b};return Response.json(E,{headers:{"content-type":"application/json"},status:200})},at=500,un=(e,t,r)=>{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 n=e;if(typeof n.functionPath!="string")throw new d("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new d("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new d("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},ln=(e,t)=>{if(e.length>at)throw new d(`RPC batch exceeds the ${String(at)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,o]of e.entries()){const{entry:i,shardKey:u}=un(o,n,t),l=r.get(u)??[];l.push(i),r.set(u,l)}return r},hn=new TextEncoder,pn=e=>{const t=JSON.stringify(e),r=hn.encode(t);let n="";for(const o of r)n+=String.fromCodePoint(o);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},fn=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let l=0;l<r.length;l+=1)n[l]=r.codePointAt(l)??0;const o=JSON.parse(new TextDecoder().decode(n)),i=o.s&&typeof o.s=="object"?o.s:{},u={};for(const[l,f]of Object.entries(i))typeof f=="number"&&Number.isFinite(f)&&(u[l]=f);return{g:typeof o.g=="number"&&Number.isFinite(o.g)?o.g:0,s:u,v:1}}catch{return t}},mn=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",o=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(o===void 0?{}:{_id:o}),op:n,table:t}},ot=(e,t,r)=>{for(const n of t)e.push(mn(n));return r!==void 0&&t.length>=r},wn="/_lunora/admin/export",yn="/_lunora/admin/import",gn="/_lunora/admin/sync",bn="/_lunora/admin/connector/sync",_n="/_lunora/admin/apply",Rn="/_lunora/admin/export-tap/run",En=new TextEncoder,Sn=async e=>{const t=await be(e,"Export")??{};if(t.tables===void 0)return{tables:void 0};if(!Array.isArray(t.tables))throw new d("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const n of t.tables){if(typeof n!="string"||n.length===0)throw new d("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(n)}return{tables:r}},Be=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,On=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:o,queryCoordinator:i,assertAdmin:u,requireAdminOption:l,resolveForwardContext:f,shardDO:b,streamExportRows:E,streamingImport:y,syncGlobals:_}=e,h=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const V=l(k,i,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),N=await Sn(k),{headers:Q}=await f(k,K),G=new ReadableStream({async pull(x){const L=Y=>{x.enqueue(En.encode(`${JSON.stringify(Y)}
2
+ `))};try{await E(V,Q,N.tables,L),x.close()}catch(Y){x.error(Y)}}});return new Response(G,{headers:{"content-type":"application/x-ndjson"},status:200})},S=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const V=l(k,i,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),N=await Z(k),Q=typeof N.cursors=="object"&&N.cursors!==null?N.cursors:{},G=typeof N.limit=="number"?N.limit:void 0,x=typeof N.globalCursor=="number"?N.globalCursor:0,L=Be(N.tables),{headers:Y}=await f(k,K),H=L??o(),ne=await V.orchestrateCdcSync(b,{cursors:Q,headers:Y,limit:G,tables:H}),he=_?await _({limit:G,sinceSeq:x}):void 0;return Response.json({global:he,shards:ne.shards},{status:200})},O=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const V=l(k,i,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),N=await Z(k),Q=fn(N.cursor),G=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,x=Be(N.tables),{headers:L}=await f(k,K),Y=x??o(),H=await V.orchestrateCdcSync(b,{cursors:Q.s,headers:L,limit:G,tables:Y}),ne=[],he={...Q.s};let ae=!1;for(const se of H.shards)ae=ot(ne,se.changes??[],G)||ae,he[se.shardKey]=se.cursor;let pe=Q.g;if(_){const se=await _({limit:G,sinceSeq:Q.g});ae=ot(ne,se.changes,G)||ae,pe=se.cursor}const _e=pn({g:pe,s:he,v:1}),ve={changes:ne,hasMore:ae,nextCursor:_e};return Response.json(ve,{status:200})},A=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const V=l(k,i,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),N=await Z(k),Q=(Array.isArray(N.batches)?N.batches:[]).map(H=>H).filter(H=>H!==null&&typeof H=="object"&&typeof H.shardKey=="string"&&Array.isArray(H.changes)),G=Array.isArray(N.globalChanges)?N.globalChanges:[],{headers:x}=await f(k,K),L=await V.orchestrateApplyCdc(b,{batches:Q,headers:x}),Y=G.length>0&&t?await t({changes:G}):0;return Response.json({applied:L.applied+Y,failed:L.failed,ok:L.ok},{status:200})},v=async(k,K)=>{const $=we(k,["POST"]);if($)return $;u(k);const{headers:V}=await f(k,K),N=await y(k,V);return Response.json(N,{headers:{"content-type":"application/json"},status:200})},U=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const V=l(k,i,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new d("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const N=await Z(k),Q=typeof N.sink=="string"?N.sink:void 0,G=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,x=Be(N.tables);if(Q===void 0)throw new d("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const L=n[Q];if(L===void 0)throw new d(`Export-tap sink "${Q}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:Y}=await f(k,K),H=x??o(),ne=await Sr({coordinator:V,cursorStore:r,headers:Y,limit:G,shardDO:b,sink:L,tables:H});return Response.json(ne,{headers:{"content-type":"application/json"},status:200})};return{[_n]:A,[bn]:O,[wn]:h,[Rn]:U,[yn]:v,[gn]:S}},Tn=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const o of t)e.resolveTableSharding?.(o)?.mode.kind==="global"?n.push(o):r.push(o);return{globalTables:n,shardLocalTables:r}},An=async(e,t,r,n,o,i)=>{if(r!==void 0&&n.length===0)return;const u=await e.orchestrateExport(i,{args:{tables:n},headers:t,tables:n});for(const l of u.shards)if(!l.error)for(const f of l.rows??[])o(f)},Dt=async(e,t,r,n,o,i)=>{const{globalTables:u,shardLocalTables:l}=Tn(e,n);await An(t,r,n,l,o,i);const f=e.exportGlobals;if((n===void 0||u.length>0)&&f)for await(const b of f({tables:u}))o(b)},vn=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},kn=(e,t,r,n,o)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const i=e[r.mode.field];return i==null?{error:{code:"BAD_ROW",line:o,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:n}},In=async(e,t,r)=>{if(!e.body)throw new d("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],o=[],i=new Map;let u=0,l=0;const f=e.body.getReader(),b=new TextDecoder;let E="",y=0;const _=h=>{l+=1;const S=h.trim();if(S.length===0)return;u+=1;const O=vn(S,l);if(!O.ok){n.push(O.error);return}const{doc:A,table:v}=O,U=t.resolveTableSharding?.(v);if(U?.mode.kind==="global"){o.push({doc:A,line:l,table:v});return}const k=kn(A,v,U,r,l);if(!k.ok){n.push(k.error);return}const K=i.get(k.shardKey);K?K.rows.push({doc:A,table:v}):i.set(k.shardKey,{rows:[{doc:A,table:v}],shardKey:k.shardKey,startLine:l})};for(;;){const{done:h,value:S}=await f.read();if(h)break;if(S&&(y+=S.byteLength,y>Et))throw await f.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=b.decode(S,{stream:!0});let O=E.indexOf(`
3
+ `);for(;O!==-1;){const A=E.slice(0,O);E=E.slice(O+1),_(A),O=E.indexOf(`
4
+ `)}}return E.length>0&&_(E),{errors:n,globalRows:o,perShard:i,received:u}},st=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},Dn=async(e,t,r,n)=>{const o=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:l,received:f}=await In(e,t,o),b={conflicts:0,errors:i,inserted:{}},E=[];if(t.resolveTableSharding===void 0&&l.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"),l.size>0){const y=t.queryCoordinator;if(!y)throw new d("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const _=await y.orchestrateImport(n,{batches:[...l.values()],headers:r});st(b,_)}if(u.length>0)if(t.importGlobals){const y=u[0]?.line??1,_=await t.importGlobals({rows:u,startLine:y});st(b,_)}else for(const y of u)b.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:y.line,message:`row targets global table "${y.table}" but no \`importGlobals\` is configured`,table:y.table});return{conflicts:b.conflicts,errors:b.errors,inserted:b.inserted,received:f,...E.length>0?{warnings:E}:{}}},$e=e=>typeof e=="object"&&e!==null?e:{},je=e=>typeof e.kind=="string"?e.kind:"unknown",Pn=(e,t)=>{let r=$e(t),n=!1;je(r)==="optional"&&(n=!0,r=$e(r._meta?.inner));const o=je(r),i=r._meta??{},u={kind:o,name:e,optional:n};if(o==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),o==="array"){const l=je($e(i.inner));l!=="unknown"&&(u.element=l)}return u},Un=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>Pn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),Nn="/_lunora/admin/functions",qn="/_lunora/admin/cron-jobs",Cn="/_lunora/admin/openapi",xn="/_lunora/admin/openrpc",Bn="/_lunora/admin/global/tables",$n="/_lunora/admin/global/table",jn="/_lunora/admin/global/facet",it=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:o,value:i}=n;return[{column:o,value:i}]});return r.length===0?void 0:r},Kn=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:{}}),Ln=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"}),Fn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:o,requireAdminOption:i}=e,u=h=>{j(h,"GET","Functions");const S=i(h,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),O=Object.entries(S).flatMap(([A,v])=>v.visibility==="internal"||v.kind==="stream"?[]:[{args:Un(v.args),kind:v.kind,path:A}]).toSorted((A,v)=>A.path.localeCompare(v.path));return Response.json({functions:O},{headers:{"content-type":"application/json"},status:200})},l=h=>{j(h,"GET","Cron-jobs");const S=i(h,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),O=Object.entries(S).flatMap(([A,v])=>v.map(U=>({args:U.args,cron:A,functionPath:U.functionPath,name:U.name,shardKey:U.shardKey,workflow:U.workflow}))).toSorted((A,v)=>A.name.localeCompare(v.name));return Response.json({jobs:O},{headers:{"content-type":"application/json"},status:200})},f=h=>(j(h,"GET","OpenAPI"),t(h),Response.json(r.openApiSpec??Kn,{headers:{"content-type":"application/json"},status:200})),b=h=>(j(h,"GET","OpenRPC"),t(h),Response.json(r.openRpcSpec??Ln,{headers:{"content-type":"application/json"},status:200})),E=async h=>{j(h,"GET","Global-tables");const S=i(h,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await S.listTables(),{headers:{"content-type":"application/json"},status:200})},y=async h=>{j(h,"GET","Global-table");const S=i(h,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),O=new URL(h.url),A=o(O,"table");if(A===void 0)throw new d("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const v=await S.readTablePage({...n(h),filters:it(o(O,"filters")),table:A});return Response.json(v,{headers:{"content-type":"application/json"},status:200})},_=async h=>{j(h,"GET","Global-facet");const S=i(h,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),O=new URL(h.url),A=o(O,"table"),v=o(O,"column");if(A===void 0||v===void 0)throw new d("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const U=o(O,"limit"),k=U===void 0?void 0:Number(U),K=await S.facetColumn({column:v,filters:it(o(O,"filters")),limit:k!==void 0&&Number.isFinite(k)?k:void 0,table:A});return Response.json(K,{headers:{"content-type":"application/json"},status:200})};return{[qn]:l,[Nn]:u,[jn]:_,[$n]:y,[Bn]:E,[Cn]:f,[xn]:b}},Qn="/_lunora/admin/kv/namespaces",Gn="/_lunora/admin/kv/keys",Pt="/_lunora/admin/kv/value",Ut=32*1048576,dt=60,Mn=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=y=>r(y,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),o=y=>Response.json(y,{headers:{"content-type":"application/json"},status:200}),i=(y,_)=>{const h=new URL(y.url),S=h.searchParams.get("namespace")??"",O=h.searchParams.get("key")??"";if(S==="")throw new d(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(O==="")throw new d(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:O,namespace:S}},u=async(y,_)=>{if(!(await y.listNamespaces()).some(h=>h.binding===_))throw new d(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},l=async y=>(j(y,"GET","KV-namespaces"),o({namespaces:await n(y).listNamespaces()})),f=async y=>{j(y,"GET","KV-keys");const _=n(y),h=new URL(y.url),S=h.searchParams.get("namespace")??"";if(S==="")throw new d("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const O=h.searchParams.get("prefix")??void 0,A=h.searchParams.get("cursor")??void 0,v=h.searchParams.get("limit"),U=v===null?void 0:Number.parseInt(v,10);if(U!==void 0&&(!Number.isInteger(U)||U<1))throw new d("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const k=U===void 0?void 0:Math.min(U,1e3);return await u(_,S),o(await _.listKeys({cursor:A,limit:k,namespace:S,prefix:O}))},b={DELETE:async y=>{const _=n(y),h=i(y,"DELETE");return await u(_,h.namespace),await _.deleteKey(h),o({deleted:!0})},GET:async y=>{const _=n(y),h=i(y,"GET");return await u(_,h.namespace),o(await _.getValue(h))},PUT:async y=>{const _=n(y),h=await t(y,Ut);if(typeof h.namespace!="string"||h.namespace==="")throw new d("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof h.key!="string"||h.key==="")throw new d("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof h.value!="string")throw new d("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(h.expirationTtl!==void 0&&(typeof h.expirationTtl!="number"||!Number.isInteger(h.expirationTtl)||h.expirationTtl<dt))throw new d("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const S=Math.floor(Date.now()/1e3)+dt;if(h.expiration!==void 0&&(typeof h.expiration!="number"||!Number.isInteger(h.expiration)||h.expiration<S))throw new d("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(_,h.namespace),await _.putValue({expiration:h.expiration,expirationTtl:h.expirationTtl,key:h.key,metadata:h.metadata,namespace:h.namespace,value:h.value}),o({ok:!0})}},E=y=>{const _=b[y.method];if(!_)throw new d("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(y)};return{[Qn]:l,[Gn]:f,[Pt]:E}},zn="/_lunora/migrate",Wn="/_lunora/admin/pitr",Hn="/_lunora/admin/rank",Jn="/_lunora/admin/rankpage",Vn="/_lunora/admin/shard-traffic",Yn=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Xn=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Zn=async e=>{const t=await be(e,"Migration")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.functionPath!="string"||!Yn.has(t.functionPath))throw new d("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,table:t.table}},ea=async e=>{const t=await be(e,"Rank")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.index!="string"||t.index.length===0)throw new d("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof t.partitionKey!="string")throw new d("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof t.rowId!="string"||t.rowId.length===0)throw new d("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(t.sortValues))throw new d("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:t.sortValues,table:t.table}},ta=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}},ra=e=>{if(typeof e.table!="string"||e.table.length===0)throw new d("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new d("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new d("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new d("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new d("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},na=async e=>{const t=await be(e,"Rank page")??{};ra(t);const r=ta(t.directions);return{cursor:typeof t.cursor=="string"?t.cursor:null,directions:r,index:t.index,partitionKey:typeof t.partitionKey=="string"?t.partitionKey:void 0,table:t.table,take:typeof t.take=="number"?t.take:void 0}},aa=async e=>{const t=await be(e,"Shard-traffic")??{};if(typeof t.table!="string"||t.table.length===0)throw new d("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:t.table}},oa=async e=>{const t=await Z(e);if(typeof t.functionPath!="string"||!Xn.has(t.functionPath))throw new d("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new d("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},sa=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:o,resolveForwardContext:i,shardDO:u}=e,l=(h,S)=>{if(h.method!=="POST")throw new d(`${S} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!n(h))throw new d("Admin auth required",{code:"FORBIDDEN",status:403});if(!o)throw new d(`${S} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return o},f=async(h,S)=>{const O=l(h,"Migration"),A=await Zn(h),{headers:v}=await i(h,S),U=await O.orchestrateMigration(u,{args:A.args,functionPath:A.functionPath,headers:v,table:A.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},b=async(h,S)=>{const O=l(h,"Rank"),A=await ea(h),{headers:v}=await i(h,S),U=await O.orchestrateRank(u,{headers:v,index:A.index,partitionKey:A.partitionKey,rowId:A.rowId,sortValues:A.sortValues,table:A.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},E=async(h,S)=>{const O=l(h,"Rank page"),A=await na(h),{headers:v}=await i(h,S),U=await O.orchestrateRankPage(u,{...A,headers:v});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},y=async(h,S)=>{const O=l(h,"Shard-traffic"),A=await aa(h),{headers:v}=await i(h,S),U=await O.orchestrateShardTraffic(u,{headers:v,table:A.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},_=async(h,S)=>{if(j(h,"POST","PITR"),!n(h))throw new d("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const O=await oa(h),{headers:A}=await i(h,S),v=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:O.args,functionPath:O.functionPath}),headers:A,method:"POST"});return r(u,O.shardKey??t,v)};return{[zn]:f,[Wn]:_,[Hn]:b,[Jn]:E,[Vn]:y}},ia=1,da=0,ca=32,ua=512,la=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,ha=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>ua)return;const r=t.split(",");if(!(r.length>ca)){for(const n of r)if(!la.test(n.trim()))return;return t}},pa=e=>{const t=wr(e.headers.get("traceparent"));if(t===void 0)return;const r=ha(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},fa=(e,t={})=>{const r=pa(e),n=t.trustInbound===!0?r:void 0,o=Ae(8),i=n?.traceId??Ae(16),u=Ir(t.sampling,n===void 0?o:i),l=u.isTraced&&(n===void 0||n.sampled);return{decision:u,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:l,spanId:o,traceFlags:l?ia:da,traceId:i,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},ma=(e,t)=>{t.traceparent=mr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},wa=(e,t)=>{let r;return()=>{if(r===void 0){const n=_r(e),o=t===void 0?void 0:t.cf;r=yr(br(n),gr(n,o))}return r}},ya="/_lunora/admin/scheduled",ga="/_lunora/admin/scheduled/status",ba="/_lunora/admin/scheduled/ws",_a="/_lunora/admin/scheduled/cancel",Ra="/_lunora/admin/scheduled/dead",Ea="/_lunora/admin/scheduled/dead/retry",Sa="/_lunora/admin/scheduled/dead/cancel",Oa=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:o}=e,i=(f,b)=>E=>{if(E.method!=="GET")throw new d(`${b} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return n(E).fetch(new Request(`https://scheduler.internal${f}`,{method:"GET"}))},u=(f,b,E=b)=>async y=>{if(y.method!=="POST")throw new d(`${E} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const _=n(y),h=await y.json().catch(()=>{});if(typeof h?.id!="string"||h.id==="")throw new d(`${b} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return _.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:h.id}),headers:{"content-type":"application/json"},method:"POST"}))},l=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 b=r();return ye(b,o).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[_a]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[Sa]:u("/dead/cancel","Scheduled dead-letter action"),[Ra]:i("/dead","Scheduled dead-letter"),[Ea]:u("/dead/retry","Scheduled dead-letter action"),[ya]:i("/list","Scheduled-list"),[ga]:i("/status","Scheduler-status"),[ba]:l}},Ta=new TextEncoder,Aa=1e3,Nt="lunoraBackupCron",ct=24*1048576,va=(e,t)=>{const r=new Uint8Array(new ArrayBuffer(t));let n=0;for(const o of e)r.set(o,n),n+=o.byteLength;return r},ka=async(e,t,r,n)=>{if(r===void 0||r<=0)return;const o=[];let i;for(let u=0;u<Aa;u+=1){const l=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const f of l.objects)qr(f.key)&&f.customMetadata?.[Nt]===n&&o.push(f.key);if(!l.truncated||l.cursor===void 0)break;i=l.cursor}await Promise.all(o.toSorted((u,l)=>l.localeCompare(u)).slice(r).map(async u=>{await e.delete(Cr(u)),await e.delete(u)}))},Ia=async(e,t,r,n)=>{const o=e.backupStore,i=e.queryCoordinator;if(!o)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(!r||r.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 ${r}`,"content-type":"application/json"},l=e.backupTables;let f=0,b=0,E=[];await Dt(e,i,u,l,v=>{const U=Ta.encode(`${JSON.stringify(v)}
5
+ `);if(f+=1,b+=U.byteLength,b>ct)throw new d(`scheduled backup reached ${String(b)} bytes of NDJSON, past the ${String(ct)}-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(U)},t);const y=Dr(e.backupPrefix??Pr),_=new Date(n.scheduledTime).toISOString(),h=Ur(y,_),S=va(E,b);E=[];const O=xr(await crypto.subtle.digest("SHA-256",S));await o.put(h,S,{httpMetadata:{contentType:"application/x-ndjson"},sha256:O});const A={bytes:b,createdAt:_,cron:n.cron,file:h,id:_,rows:f,scheduledTime:n.scheduledTime,sha256:O,...l?{tables:l.join(",")}:{}};await o.put(Nr(h),`${JSON.stringify(A,void 0,2)}
6
+ `,{customMetadata:{[Nt]:n.cron},httpMetadata:{contentType:"application/json"}});try{await ka(o,y,e.backupRetain,n.cron)}catch(v){console.warn(`[lunora] backup ${h} was written, but retention failed:`,v)}},Da=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},ut={mtls:e=>Da(e,"tlsClientAuth","certVerified")==="SUCCESS"},Pa=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(ut,e)?ut[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.'))}},Na="/_lunora/admin/vector/indexes",qa="/_lunora/admin/vector/query",Ca=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async i=>{j(i,"GET","Vector-indexes");const u=r(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})},o=async i=>{j(i,"POST","Vector-query");const u=r(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 l=await t(i);if(typeof l.name!="string"||l.name==="")throw new d("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof l.text!="string"||l.text==="")throw new d("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(l.topK!==void 0&&(typeof l.topK!="number"||!Number.isInteger(l.topK)||l.topK<1))throw new d("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const f=await u.queryIndex({name:l.name,text:l.text,topK:l.topK});return Response.json(f,{headers:{"content-type":"application/json"},status:200})};return{[Na]:n,[qa]:o}},xa="/_lunora/admin/workflows/instances",Ba="/_lunora/admin/workflows/instance",$a="/_lunora/admin/workflows/status",ja={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Ka=e=>e!==null&&Object.hasOwn(ja,e)?e:void 0,lt=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Ke=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new d(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},ht=()=>{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})},La=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(u,l,f)=>{j(u,"GET","Workflows instances"),t(u);const b=r(l);if(!b)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const E=Ke(f,"name"),y=Ka(f.searchParams.get("status"));return Response.json(await b.listInstances({page:lt(f,"page"),perPage:lt(f,"perPage"),status:y,workflowName:E}))},o=async(u,l,f)=>{j(u,"GET","Workflows instance"),t(u);const b=r(l);return b?Response.json(await b.getInstance({instanceId:Ke(f,"id"),workflowName:Ke(f,"name")})):ht()},i=async(u,l)=>{j(u,"POST","Workflows status"),t(u);const f=r(l);if(!f)return ht();const b=await u.json().catch(()=>{});if(typeof b?.name!="string"||b.name===""||typeof b.id!="string"||b.id==="")throw new d("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:E}=b;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:b.id,workflowName:b.name}))};return{[Ba]:o,[xa]:n,[$a]:i}},Fa={[Pt]:Ut,[$r]:Br},pt="/_lunora/rpc",Qa="/_lunora/rpc-batch",Ga="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:wa(e,t),...r===void 0?{}:{waitUntil:r}}),ft=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},mt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Le=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const o=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(o)?void 0:o,scheme:n.protocol.replace(":",""),userAgent:r}},wt="/_lunora/voice/",Ma="/_lunora/scheduler/dispatch",za="/_lunora/admin/cron-jobs/run",Wa="/_lunora/admin/ws-token",Ha="/_lunora/admin/",Ja="/_lunora/migrate",Va="/_lunora/status",Ya=e=>e.startsWith(Ha)||e===Ja,Xa=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},Za="/api/auth",eo="__lunora_admin__:recordAuthEvent",to="__lunora_admin__:listPushSubscriptions",ro=["/sign-in","/sign-up","/callback"],no=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return ro.some(o=>n===o||n.startsWith(`${o}/`))},Se=(e,t,r,n)=>{const o=ur(r),i=o?r.code:"INTERNAL_SERVER_ERROR",u=o?r.status:500,l=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:i,message:l,status:u},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},ao=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},yt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,oo=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ce=async(e,t,r)=>{const n={"content-type":"application/json"},o=e.headers.get("authorization"),i=e.headers.get("cookie"),u=e.headers.get("x-d1-bookmark"),l=e.headers.get("x-lunora-mutation-id"),f=e.headers.get("x-lunora-client-id"),b=e.headers.get("x-lunora-client-seq");o&&(n.authorization=o),i&&(n.cookie=i),u&&(n["x-d1-bookmark"]=u),l&&(n["x-lunora-mutation-id"]=l),f&&(n["x-lunora-client-id"]=f),b&&(n["x-lunora-client-seq"]=b);const E=e.headers.get("cf-connecting-ip");if(E&&(n["x-lunora-client-ip"]=E),!r)return{claims:null,headers:n,identity:null,userId:null};const y=await r(e,t);if(!y||typeof y.userId!="string"||y.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=pr(y.userId);const _=ao(y);_!==void 0&&(n["x-lunora-identity-exp"]=String(_));const{userId:h,...S}=y,O=Object.keys(S).length>0?S:null;return O&&(n["x-lunora-identity"]=fr(O)),{claims:O,headers:n,identity:y,userId:h}},so=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),io=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 r=t.merge;if(typeof r.kind!="string"||!so.has(r.kind))throw new d("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new d("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new d("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},co=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},gt=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){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 r}},uo=async e=>{const t=await St(e);let r;try{r=JSON.parse(t)}catch{throw new d("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new d("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&Ot(n.args,"RPC"),n.shardKey!==void 0&&typeof n.shardKey!="string")throw new d("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const o=r,i=io(o.fanOut),u=o.args??{};if(i&&o.functionPath.startsWith("__lunora_relation__:")){const l=u.table;if(typeof l=="string"&&l!==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:o.functionPath,shardKey:o.shardKey}},oe=async(e,t,r)=>ye(e,t).fetch(r),Oe=new Map,lo=5e3,ho=4096,po=async(e,t)=>{const r=Date.now(),n=Oe.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&Oe.delete(t);let o=0;try{const i=await ye(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const u=(await i.json()).relayCount;typeof u=="number"&&u>0&&(o=Math.floor(u))}}catch{o=0}return Rt(Oe,ho),Oe.set(t,{expiresMs:r+lo,relayCount:o}),o},fo=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,r])=>r===t)?.[0]},Te=(e,t,r)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:r,method:"POST"}),mo=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],bt=(e,t)=>{for(const r of mo){e.delete(r);const n=t[r];n!==void 0&&e.set(r,n)}},wo=async(e,t,r)=>e.length===0||r.length===0?!1:Fe(await vt(e,t),r),_t=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...o]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:Fe(t,o.join(" ").trim())},yo=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await nn(t,n)?!0:r?!1:Fe(t,n)},go=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return Ar(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Ne(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Ne(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Ne(`hyperdrive:${e}`,!0)},qt=e=>{const t=Pa(e.trustInboundTraceContext),r=Ua(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",o=vr(e.resolveIdentity,e.identity),i=Ye(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:Ye(e.schedulerDO,e.jurisdiction);let l;const f=()=>e.adminToken??l;let b;const E=()=>e.requireEphemeralWsToken??b??!0,y=a=>{const s=a??{};if(b===void 0&&e.requireEphemeralWsToken===void 0){const c=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(b=en(c,!0))}if(l!==void 0||e.adminToken!==void 0)return;const p=s.LUNORA_ADMIN_TOKEN;typeof p=="string"&&p.length>0&&(l=p)},_=new WeakSet,h=a=>_t(a,f())||_.has(a),S=async(a,s)=>{const p=await ce(a,s,e.resolveIdentity);if(_.has(a)&&p.headers.authorization===void 0){const c=f();c!==void 0&&(p.headers.authorization=`Bearer ${c}`)}return p};let O=!1;const A=a=>{if(!e.allowUnauthenticatedShardAccess){const s=a==="fan-out"?"authorizeFanOut":"authorizeShard";throw new d(`${a} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${a} access (relying solely on per-row RLS).`,{code:a==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}O||(O=!0,console.warn([`[lunora] SECURITY: serving ${a} 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("")))},v=async(a,s,p=!0)=>{if(e.authorizeShard){if(!await e.authorizeShard(a,s))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else p&&s!==n&&A("shard")},U=sa({defaultShard:n,forwardToShard:oe,isAdmin:h,queryCoordinator:e.queryCoordinator,resolveForwardContext:S,shardDO:i}),k=async(a,s,p,c,m)=>{await v(null,p,!1);const g={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(g["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(g["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(g["x-lunora-mutation-id"]=c),oe(i,p,Te(a,s,g))},K=async(a,s,p,c)=>{const m=p?.[a];if(!m||typeof m.create!="function")throw new d(`${c} targets workflow binding "${a}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(Qr(s))throw new d(`${c} params ${Gr}`,{code:"BAD_REQUEST",status:400});await m.create({params:s})},$=async(a,s)=>{if(a.workflow){await K(a.workflow,a.args??{},s,`cron job "${a.name}"`);return}if(a.functionPath===void 0)throw new d(`cron job "${a.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const p=await k(a.functionPath,a.args??{},a.shardKey??n);if(!p.ok)throw new d(`cron job "${a.name}" (${a.functionPath}) failed with shard status ${String(p.status)}`,{code:"CRON_JOB_FAILED",status:500})},V=async(a,s,p,c)=>{const m=e.cronJobs?.[a];if(m)for(const g of m)try{await $(g,s)}catch(D){p.push(c(D))}},N=async(a,s)=>{if(!h(a))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(j(a,"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 p=await Z(a),c=typeof p.name=="string"?p.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(g=>g.name===c);if(!m)throw new d(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await $(m,s),Response.json({name:c,ran:!0},{status:200})},Q=async a=>{const s=typeof a.pool=="string"&&a.pool.length>0?a.pool:void 0;if(!s||!u||typeof a.id!="string")return;const p=typeof a.instanceName=="string"&&a.instanceName.length>0?a.instanceName:"default";try{await ye(u,p).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:a.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},G=async(a,s)=>{j(a,"POST","Scheduler dispatch");const p=await St(a),c=s??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,g=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),D=a.headers.get("x-lunora-scheduler-signature");let w=!1;if(D&&m?w=await wo(m,p,D):g&&(w=_t(a,g)),!w)throw new d("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let R;try{R=JSON.parse(p)}catch{throw new d("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const T=R??{},q=T.args??{};if(typeof T.workflow=="string"&&T.workflow.length>0)return await K(T.workflow,q,s,"scheduled workflow"),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 C=typeof T.shardKey=="string"&&T.shardKey.length>0?T.shardKey:n,B=typeof T.id=="string"&&T.id.length>0?T.id:void 0,X=Xa(a),ee=await k(T.functionPath,q,C,B,X);return await Q(T),ee},x=a=>{if(!h(a))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},L=(a,s,p)=>{if(x(a),s===void 0)throw new d(p.message,{code:p.code,status:400});return s},Y=cn({assertAdmin:x,getReader:()=>e.authAuditReader}),H=async(a,s)=>{x(a);const p=e.notifySubscriptionStore;if(p===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const c=s?.kind,m=s?.userId,g=s?.limit,D=c==="fcm"||c==="web-push"?c:void 0,w=typeof m=="string"&&m!==""?m:void 0,R=typeof g=="number"&&Number.isFinite(g)?Math.trunc(g):0,T=R>0?Math.min(R,1e3):1e3,q=(await p.list({kind:D,limit:T,userId:w})).filter(C=>D!==void 0&&C.kind!==D?!1:w===void 0||(C.userId??null)===w).map(({keys:C,token:B,...X})=>X);return Response.json({subscriptions:q},{headers:{"content-type":"application/json"},status:200})},ne=async(a,s)=>{if(!s.fanOut){if(s.functionPath===dn)return Y(a,s.args??{});if(s.functionPath===to)return H(a,s.args)}},he=On({applyGlobals:e.applyGlobals,assertAdmin:x,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:L,resolveForwardContext:S,shardDO:i,streamExportRows:(a,s,p,c)=>Dt(e,a,s,p,c,i),streamingImport:(a,s)=>Dn(a,e,s,i),syncGlobals:e.syncGlobals}),ae=(a,s)=>{const p=a.searchParams.get(s);return p===null||p===""?void 0:p},pe=a=>{const s=new URL(a.url),p=s.searchParams.get("limit"),c=s.searchParams.get("offset"),m=p===null?void 0:Number.parseInt(p,10),g=c===null?void 0:Number.parseInt(c,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:g!==void 0&&Number.isFinite(g)&&g>=0?g:void 0}},_e=()=>{if(u===void 0)throw new d("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},ve=Oa({checkWsAdmin:async a=>h(a)||yo(a,f(),E()),requireSchedulerNamespace:_e,resolveSchedulerStub:a=>(x(a),ye(_e(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),se=La({assertAdmin:x,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Ct=jr({assertAdmin:x,parsePaging:pe,queryParameter:ae,readBodyBytes:Er,requireAdminOption:L,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),xt=Ca({readJsonBody:Z,requireAdminOption:L,vectorIntrospector:e.vectorIntrospector}),Bt=Mn({kvIntrospector:e.kvIntrospector,readJsonBody:Z,requireAdminOption:L}),$t=kr({logArchive:e.logArchive,readJsonBody:Z,requireAdminOption:L}),jt=Fn({assertAdmin:x,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:ae,requireAdminOption:L}),Kt=a=>{const s=[],p=i??a?.SHARD;if(p!==void 0&&s.push(Tr("durable-object:default",p,n)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(a??{})){const g=go(c,m);g!==void 0&&s.push(g)}for(const c of e.health?.probes??[])s.push(c);return s},Lt=Or({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:h,resolveProbes:Kt}),Ft=a=>{const s=e.schedulerInstanceName??"default",p=()=>ye(a,s),c=async(w,R)=>{const T=await p().fetch(new Request(`https://scheduler.internal${w}`,R));if(!T.ok)throw new d(`ctx.scheduler: SchedulerDO ${w} failed (${String(T.status)}): ${await T.text()}`,{code:"INTERNAL",status:500});return await T.json()},m=async(w,R)=>await c(w,{body:JSON.stringify(R),headers:{"content-type":"application/json"},method:"POST"}),g=w=>{const R=w;if(R==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 R.binding=="string"&&R.binding.length>0)return{workflow:R.binding};if(typeof R.__lunoraRef=="string")return{functionPath:R.__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})},D=async(w,R,T={})=>{const{id:q}=await m("/schedule",{args:T,scheduledFor:w,...g(R)});return q};return{cancel:async w=>await m("/cancel",{id:w}),get:async w=>await c(`/get?id=${encodeURIComponent(w)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(w,R,T)=>{if(!Number.isFinite(w)||w<0)throw new d("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await D(Date.now()+w,R,T)},runAt:async(w,R,T)=>{if(!Number.isFinite(w))throw new d("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await D(w,R,T)}}},Qt=async(a,s,p)=>{const{claims:c,headers:m,userId:g}=await ce(a,s,o),D=async(w,R={})=>{const T=w.__lunoraRef;if(typeof T!="string")throw new d("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const q=Te(T,R,{...m,"x-lunora-system":"1"}),C=await oe(i,n,q),B=await C.json();if(B.error)throw new d(B.error.message??"shard RPC failed",{code:B.error.code??"INTERNAL",status:C.status});return B.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:g},cache:p.cache,fetch:globalThis.fetch.bind(globalThis),runAction:D,runMutation:D,runQuery:D,...u===void 0?{}:{scheduler:Ft(u)},...e.storage===void 0?{}:{storage:Fr(e.storage(s))}}},Gt=async(a,s,p)=>{if(!e.httpRouter)return;const c=await Qt(a,s,p);try{return await e.httpRouter.fetch(a,{...s,__lunoraCtx:c},p)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},Mt=async(a,s,p)=>{if(a.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=Ze(a,ie);if(c)return c;const m=p.searchParams.get("shard")??n,{headers:g,identity:D}=await ce(a,s,o);await v(D,m);const w=new Headers(a.headers),R=[...w.keys()];for(const q of R)q.startsWith("x-lunora-")&&w.delete(q);bt(w,g);const T=fo(s,e.shardDO);if(T!==void 0){w.set("x-lunora-shard-binding",T);const q=await po(i,m);if(q>0){const C=Yr(m,Math.floor(Math.random()*q));return oe(i,C,new Request(a,{headers:w}))}}return oe(i,m,new Request(a,{headers:w}))},zt=async(a,s,p)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(a.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=Ze(a,ie);if(m)return m;let g;try{g=decodeURIComponent(p.pathname.slice(wt.length))}catch{return new Response("Unknown voice agent",{status:404})}const D=Object.hasOwn(c,g)?c[g]:void 0;if(D===void 0)return new Response("Unknown voice agent",{status:404});const w=p.searchParams.get("threadKey");if(w===null||w.length===0)return new Response("Missing threadKey",{status:400});const{headers:R,identity:T}=await ce(a,s,o);if(e.authorizeShard){if(!await e.authorizeShard(T,w))return new Response("Forbidden",{status:403})}else A("shard");const q=new Headers(a.headers);for(const C of q.keys())C.startsWith("x-lunora-")&&q.delete(C);return bt(q,R),oe(D,w,new Request(a,{headers:q}))},Wt=async(a,s,p)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(p,a.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});A("fan-out")},Re=async(a,s)=>{if(!(!a.fanOut&&a.functionPath.startsWith("__lunora_admin__:"))){if(a.fanOut){await Wt(a.fanOut,a.functionPath,s);return}await v(s,a.shardKey??n)}},ke=async(a,s,p,c,m,g)=>{const D=Date.now(),{observability:w,sampling:R}=e,T=Le(a),{decision:q,ignoredUpstream:C,trace:B}=fa(a,{...R===void 0?{}:{sampling:R},trustInbound:t(a)});C&&r();const X={...m,"x-lunora-sample-errors":q.keepErrors?"1":"0"};ma(B,X);const ee=Te(s,p,X);try{const F=await oe(i,c,ee);return de(w,{...T,...mt(B),durationMs:Date.now()-D,functionPath:s,ok:F.ok,shardKey:c,...F.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(F.status)}`,status:F.status}}},g,void 0,{isTraced:B.sampled,keepErrors:q.keepErrors}),F}catch(F){throw de(w,{...T,...mt(B),...Se(s,Date.now()-D,F,{shardKey:c})},g,void 0,{isTraced:B.sampled,keepErrors:q.keepErrors}),F}},Ht=a=>{if(a.fanOut&&a.shardKey)throw new d("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!a.fanOut&&a.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(a.fanOut&&!e.queryCoordinator)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Jt=async(a,s,p)=>{j(a,"POST","RPC");const c=await uo(a);co(s,c),Ht(c);const m=await ne(a,c);if(m!==void 0)return m;const{headers:g,identity:D}=await ce(a,s,o);await Re(c,D);const w=gt(c,e);{const R=Date.now(),{observability:T}=e,q=Le(a),C=Ee(s,a,p&&(ee=>p.waitUntil?.(ee)));if(c.fanOut){const ee=e.queryCoordinator;if(!ee)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const F=await ee.fanOut(i,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:g});return de(T,{durationMs:Date.now()-R,fanOut:{failed:F.failed,shards:F.ok+F.failed,table:c.fanOut.table},functionPath:c.functionPath,...q,ok:!0},C),Response.json(F,{headers:{"content-type":"application/json"},status:200})}catch(F){throw de(T,{...Se(c.functionPath,Date.now()-R,F,{fanOut:{table:c.fanOut.table}}),...q},C),F}}const B=c.shardKey??n,X=()=>ke(a,c.functionPath,c.args??{},B,g,C);return w&&e.x402Charge?e.x402Charge(a,{functionPath:c.functionPath,price:w.price},X,ft(p)):X()}},Vt=async(a,s,p)=>{j(a,"POST","RPC batch");const c=await Z(a),{calls:m}=c;if(!Array.isArray(m))throw new d("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:g,identity:D}=await ce(a,s,o),w=ln(m,n);for(const M of w.values())for(const z of M)if(e.functions?.[z.functionPath]?.x402)throw new d(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${pt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...w.entries()].flatMap(([M,z])=>z.map(re=>Re({functionPath:re.functionPath,shardKey:M},D))));const{observability:R}=e,T=Ee(s,a,p&&(M=>p.waitUntil?.(M))),q=Le(a),C=[],B=[],X=(M,z,re,ue)=>({body:{error:{code:re,message:ue}},id:M.id,status:z}),ee=(M,z,re,ue,fe)=>{for(const W of M)de(R,fe(W),T),C.push(X(W,z,re,ue))},F=(M,z,re,ue,fe)=>{for(const W of M){const me=ue.get(W.id)??fe,ge=me<400;de(R,{durationMs:re,functionPath:W.functionPath,...q,ok:ge,shardKey:z,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},T)}};await Promise.all([...w.entries()].map(async([M,z])=>{const re=new Headers(g);re.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:re,method:"POST"}),fe=Date.now();let W;try{W=await oe(i,M,ue)}catch(J){const Ue=Date.now()-fe,{body:He}=lr(J,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});ee(z,502,He.code,He.message,cr=>({...Se(cr.functionPath,Ue,J,{shardKey:M}),...q}));return}const me=Date.now()-fe,ge=W.headers.get("x-d1-bookmark");ge&&B.push(ge);let De;try{De=await W.json()}catch{const J=`shard batch returned a non-JSON response (${String(W.status)})`;ee(z,W.status,"SHARD_ERROR",J,Ue=>({durationMs:me,error:{code:"SHARD_ERROR",message:J,status:W.status},functionPath:Ue.functionPath,...q,ok:!1,shardKey:M}));return}const Pe=Array.isArray(De.results)?De.results:[],ir=new Map(Pe.map(J=>[J.id,J.status??W.status])),dr=new Set(Pe.map(J=>J.id));F(z,M,me,ir,W.status),C.push(...Pe);for(const J of z)dr.has(J.id)||C.push(X(J,W.status,"SHARD_ERROR",`shard batch omitted result for call ${String(J.id)}`))}));const ze={"content-type":"application/json"},[We]=B;return B.length===1&&We!==void 0&&(ze["x-d1-bookmark"]=We),Response.json({results:C},{headers:ze,status:200})},Yt=async(a,s,p,c={},m={})=>{try{const g=p.__lunoraRef;if(typeof g!="string")throw new d("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:D,identity:w}=await ce(a,s,o);await Re({functionPath:g,shardKey:m.shardKey},w);const R=m.shardKey??n,T=Ee(s,a,m.waitUntil);return await ke(a,g,c,R,D,T)}catch(g){return Je(g)}},Ge=async(a,s,p)=>{const{observability:c}=e,m=Date.now(),g=Ae(16),D=Ae(8),w=yt(s);try{const R=await p();return de(c,{durationMs:Date.now()-m,functionPath:a,ok:!0,spanId:D,traceId:g},w),R}catch(R){throw de(c,{...Se(a,Date.now()-m,R,{}),spanId:D,traceId:g},w),R}finally{Ve(c,w)}},Xt=async(a,s,p)=>{y(s);const c=[],m=w=>w instanceof Error?w:new Error(String(w)),g=e.crons?.[a.cron];if(g)try{await g(a,s,p)}catch(w){c.push(m(w))}if(await V(a.cron,s,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===a.cron)try{await Ia(e,i,f(),a)}catch(w){c.push(m(w))}const[D]=c;if(c.length===1&&D)throw D;if(c.length>1)throw new AggregateError(c,`scheduled("${a.cron}") had ${String(c.length)} failure(s)`)},Zt=async(a,s)=>{try{const p=a??{},c=e.adminToken??(typeof p.LUNORA_ADMIN_TOKEN=="string"?p.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await oe(i,n,Te(eo,{outcome:s},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},er=async(a,s,p,c)=>{if(!e.authHandler)return;const m=await e.authHandler(a);if(!m)return;const g=e.authBasePath??Za;return no(p.pathname,g)&&c.waitUntil?.(Zt(s,m.status>=400?"fail":"ok")),m},tr=async({args:a,env:s,functionPath:p,request:c,shardKey:m,waitUntil:g})=>{Ot(a,"REST");const D={functionPath:p,...m===void 0?{}:{shardKey:m}},{headers:w,identity:R}=await ce(c,s,o);await Re(D,R);const T=m??n,q=Ee(s,c,g),C=()=>ke(c,p,a,T,w,q),B=gt(D,e);return B&&e.x402Charge?e.x402Charge(c,{functionPath:p,price:B.price},C,ft({waitUntil:g})):C()},rr=Rr({functions:e.functions??{},invoke:tr,readJsonBody:Z,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ie=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,nr={[Va]:a=>a.method!=="GET"&&a.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Ga]:(a,s,p)=>Mt(a,s,p),[pt]:(a,s,p,c)=>Jt(a,s,c),[Qa]:(a,s,p,c)=>Vt(a,s,c),[Ma]:(a,s)=>G(a,s),[za]:(a,s)=>N(a,s),[Wa]:async a=>{j(a,"POST","ws-token"),x(a);const s=f();if(s===void 0)throw new d("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const p=await rn(s);return Response.json(p,{headers:{"cache-control":"no-store"}})},...U,...he,...ve,...se,...Ct,...xt,...Bt,...$t,...jt,...Lt,...rr,...sn({assertAdmin:x,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:ae,readJsonBody:Z})};let ie=Xe(e.security),Me=!1;const ar=a=>{Me||(Me=!0,ie=Xe(e.security,a??{}))},or=async(a,s)=>{if(!(e.adminGate===void 0||!Ya(s)))try{await e.adminGate(a)&&_.add(a)}catch{}},sr=async(a,s,p)=>{const c=new URL(a.url);if(a.method==="POST"||a.method==="PUT"){const w=Number(a.headers.get("content-length")??""),R=Fa[c.pathname]??Et;if(Number.isFinite(w)&&w>R)throw new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await er(a,s,c,p);if(m)return m;if(Ie){const w=`${a.method} ${c.pathname}`,R=Ie[w]??Ie[c.pathname];if(R)return R(a,s,p)}const g=nr[c.pathname];return g?(await or(a,c.pathname),g(a,s,c,p)):e.voiceAgents!==void 0&&c.pathname.startsWith(wt)?zt(a,s,c):await Gt(a,s,p)||new Response("Not found",{status:404})};return{async fetch(a,s,p){e.passThroughOnException&&p.passThroughOnException?.(),ar(s),y(s);const c=Kr(a,ie);if(c)return c;const m=Lr(a,ie);if(m)return qe(m,a,ie);try{const g=await sr(a,s,p);return qe(g,a,ie)}catch(g){return qe(Je(g),a,ie)}finally{Ve(e.observability,yt(p))}},async queue(a,s,p){await Ge(`queue:${oo(a)}`,p,async()=>{await e.queue?.(a,s,p)})},async scheduled(a,s,p){await Ge(`cron:${a.cron}`,p,async()=>{await Xt(a,s,p)})},serverQuery:Yt}},bo=e=>qt(e),_o=e=>typeof e=="function"?{fetch:e}:e,Ro=e=>!!(e.crons??e.cronJobs??e.backupCron),Ko=(e,t)=>{const r=_o(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,o=u=>{const l=bo({...u,httpRouter:r});return n!==void 0&&!Ro(u)?{...l,scheduled:async(f,b,E)=>{await n(f,b,E)}}:l};if(typeof t!="function")return o(t);const i=t;return{fetch:(u,l,f)=>o(i(l)).fetch(u,l,f),queue:(u,l,f)=>o(i(l)).queue?.(u,l,f)??Promise.resolve(),scheduled:(u,l,f)=>o(i(l)).scheduled(u,l,f),serverQuery:(u,l,f,b,E)=>o(i(l)).serverQuery(u,l,f,b,E)}},Eo=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)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:r}},Lo=(e={})=>(t,r,n)=>qt(Eo(e,r)).fetch(t,r,n??hr),Fo=e=>e;export{dn as GET_AUTH_AUDIT_LOG_OP,hr as NOOP_EXECUTION_CONTEXT,Mo as composeIdentityResolvers,bo as composeWorker,Lo as createLunoraHandler,qt as createWorker,Fo as defineRpcEnvelope,po as probeRelayCount,Eo as resolveLunoraOptions,zo as routeIdentityResolvers,Ko as withFrameworkWorker};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.57",
3
+ "version": "1.0.0-alpha.58",
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.23",
50
- "@lunora/errors": "1.0.0-alpha.16",
51
- "@lunora/platform": "1.0.0-alpha.7"
49
+ "@lunora/bindings": "1.0.0-alpha.24",
50
+ "@lunora/errors": "1.0.0-alpha.17",
51
+ "@lunora/platform": "1.0.0-alpha.8"
52
52
  },
53
53
  "engines": {
54
54
  "node": "^22.15.0 || >=24.11.0"
@@ -1,6 +0,0 @@
1
- import{isLunoraError as pr,toErrorBody as fr}from"@lunora/errors";import{d as Rt}from"./evict-oldest-C2XU6HBR.mjs";import{NOOP_EXECUTION_CONTEXT as mr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{f as wr,u as gr}from"./identity-header-pdXOyDU4.mjs";import{O as Ae,m as yr,A as br,R as _r,d as Rr,i as Er,s as Sr}from"./otlp-resource-B-ByO9qo.mjs";import{h as ee,f as be,i as Et,E as Tr,w as St,e as Tt,b as Or}from"./rest-routes-BqldHiaH.mjs";import{LunoraError as i,toErrorResponse as Je}from"./LunoraError-ByasbDmd.mjs";import{runExportTap as Ar}from"./createKvCursorStore-C24tEuYk.mjs";import{t as we,r as L}from"./method-guard-rzvo19pa.mjs";import{buildHealthRoutes as vr,durableObjectProbe as kr,d1Probe as Ir,presenceProbe as Ne}from"./HEALTH_PATH-BuLCcWNS.mjs";import{wrapResolverWithContract as Dr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as Bo,routeIdentityResolvers as $o}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as Pr}from"./LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{o as Ur,f as Ve,a as ce}from"./observability-DWlkDJJw.mjs";import{resolveShard as ge,applyJurisdiction as Ye}from"./applyJurisdiction-Dsm_m5zW.mjs";import{resolveSecurity as Xe,handleCorsPreflight as Nr,enforceOrigin as qr,decorateResponse as qe,enforceWebSocketOrigin as Ze}from"./decorateResponse-DBIWsRSZ.mjs";const Cr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const r={...t,bucketName:"default"};return r.bucket=()=>r,r},Ot="__lunoraBranch",xr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Ot),jr=`may not contain the reserved workflow branch-marker key ("${Ot}")`,Ge=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let o=0;o<r;o+=1){const d=o<e.length?e.charCodeAt(o):0,u=o<t.length?t.charCodeAt(o):0;n|=d^u}return n===0},Fe=new TextEncoder,Br=Array.from({length:32},(e,t)=>t);new RegExp(`[${Br.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const $r=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Lr=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)n[o]=r.codePointAt(o)??0;return n},Kr=64,Ce=new Map,At=async e=>{const t=Ce.get(e);if(t)return t;Rt(Ce,Kr);const r=crypto.subtle.importKey("raw",Fe.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ce.set(e,r),r},vt=async(e,t)=>{const r=await At(e),n=await crypto.subtle.sign("HMAC",r,Fe.encode(t));return $r(new Uint8Array(n))},Gr=async(e,t,r)=>{const n=await At(e);return crypto.subtle.verify("HMAC",n,r,Fe.encode(t))},Fr="::relay::",Qr=(e,t)=>`${e}${Fr}${String(t)}`,Mr=new Set(["1","enabled","on","true","yes"]),zr=new Set(["0","disabled","false","no","off"]),Wr=(e,t)=>{const r=(e??"").trim().toLowerCase();return Mr.has(r)?!0:zr.has(r)?!1:t},kt="v1",Hr=6e4,Jr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Hr),n=`${kt}.${String(r)}`,o=await vt(e,n);return{expiresAtMs:r,token:`${n}.${o}`}},Vr=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[o,d,u]=n;if(o!==kt||u.length===0)return!1;const h=Number(d);if(!Number.isFinite(h)||h<=r)return!1;let w;try{w=Lr(u)}catch{return!1}return Gr(e,`${o}.${d}`,w)},D="/_lunora/admin/auth",Yr={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},U=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new i(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new i(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},It=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,xe=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},et=e=>{const t=It(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new i("`role` is required",{code:"BAD_REQUEST",status:400});return t},tt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new i("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,o]of Object.entries(t))Array.isArray(o)&&o.every(d=>typeof d=="string")&&(r[n]=o);return r},Xr={[`${D}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${D}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${D}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${D}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${D}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${D}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${D}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${D}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${D}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${D}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${D}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${D}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${D}/users/create`]:{build:({body:e})=>({data:xe(e,"data"),email:U(e,"email"),name:U(e,"name"),password:te(e,"password"),role:It(e.role)}),http:"POST",method:"createUser"},[`${D}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new i("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:U(e,"userId")}},http:"POST",method:"updateUser"},[`${D}/users/role`]:{build:({body:e})=>({role:et(e),userId:U(e,"userId")}),http:"POST",method:"setRole"},[`${D}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:U(e,"userId")}),http:"POST",method:"banUser"},[`${D}/users/unban`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"unbanUser"},[`${D}/users/password`]:{build:({body:e})=>({newPassword:U(e,"newPassword"),userId:U(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${D}/users/remove`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${D}/users/impersonate`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"impersonateUser"},[`${D}/sessions/revoke`]:{build:({body:e})=>({sessionId:U(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${D}/sessions/revoke-all`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${D}/accounts/unlink`]:{build:({body:e})=>({accountId:U(e,"accountId"),userId:U(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${D}/two-factor/disable`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${D}/passkeys/delete`]:{build:({body:e})=>({passkeyId:U(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${D}/organizations/members/remove`]:{build:({body:e})=>({memberId:U(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${D}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:U(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${D}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:xe(e,"metadata"),name:U(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${D}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:xe(e,"metadata"),name:te(e,"name"),organizationId:U(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${D}/organizations/remove`]:{build:({body:e})=>({organizationId:U(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${D}/organizations/members/add`]:{build:({body:e})=>({organizationId:U(e,"organizationId"),role:te(e,"role"),userId:U(e,"userId")}),http:"POST",method:"addMember"},[`${D}/organizations/members/invite`]:{build:({body:e})=>({email:U(e,"email"),inviterId:te(e,"inviterId"),organizationId:U(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${D}/organizations/members/role`]:{build:({body:e})=>({memberId:U(e,"memberId"),role:et(e)}),http:"POST",method:"updateMemberRole"},[`${D}/organizations/teams/create`]:{build:({body:e})=>({name:U(e,"name"),organizationId:U(e,"organizationId")}),http:"POST",method:"createTeam"},[`${D}/organizations/teams/update`]:{build:({body:e})=>({name:U(e,"name"),teamId:U(e,"teamId")}),http:"POST",method:"updateTeam"},[`${D}/organizations/teams/remove`]:{build:({body:e})=>({teamId:U(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${D}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:U(e,"teamId"),userId:U(e,"userId")}),http:"POST",method:"addTeamMember"},[`${D}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:U(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${D}/organizations/roles/create`]:{build:({body:e})=>({organizationId:U(e,"organizationId"),permission:tt(e),role:U(e,"role")}),http:"POST",method:"createOrgRole"},[`${D}/organizations/roles/update`]:{build:({body:e})=>({permission:tt(e),roleId:U(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${D}/organizations/roles/remove`]:{build:({body:e})=>({roleId:U(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Zr=e=>{const t=async o=>{try{return await o()}catch(d){if(d instanceof i)throw d;const u=d,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",d),new i("auth admin operation failed",{code:h,status:Yr[h]??500})}},r=async(o,d)=>{if(e.assertAdmin(o),o.method!==d.http)throw new i(`Auth admin endpoint requires ${d.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new i("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[d.method];if(h===void 0)throw new i(`auth admin does not support \`${d.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const w=new URL(o.url),R={body:d.http==="POST"?await e.readJsonBody(o):{},paging:e.parsePaging(o),query:k=>e.queryParameter(w,k)},I=d.build(R),b=await t(()=>h(I));return Response.json(d.returns==="void"?{ok:!0}:b,{headers:{"content-type":"application/json"},status:200})},n={};for(const[o,d]of Object.entries(Xr))n[o]=u=>r(u,d);return n},en="__lunora_admin__:getAuthAuditLog",rt=e=>typeof e=="string"&&e!==""?e:void 0,nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,tn=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new i("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const o=rt(r.actorId),d=rt(r.event),u=nt(r.sinceSeq),h=nt(r.limit),w={...o===void 0?{}:{actorId:o},...d===void 0?{}:{event:d},...u===void 0?{}:{sinceSeq:u},...h===void 0?{}:{limit:h}};let R;try{R=await n.read(w)}catch(b){throw b instanceof i?b:(console.error("[lunora] auth audit read failed:",b),new i("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const I={entries:R};return Response.json(I,{headers:{"content-type":"application/json"},status:200})},at=500,rn=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new i("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new i("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new i("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new i("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},nn=(e,t)=>{if(e.length>at)throw new i(`RPC batch exceeds the ${String(at)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,o]of e.entries()){const{entry:d,shardKey:u}=rn(o,n,t),h=r.get(u)??[];h.push(d),r.set(u,h)}return r},an=new TextEncoder,on=e=>{const t=JSON.stringify(e),r=an.encode(t);let n="";for(const o of r)n+=String.fromCodePoint(o);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},sn=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let h=0;h<r.length;h+=1)n[h]=r.codePointAt(h)??0;const o=JSON.parse(new TextDecoder().decode(n)),d=o.s&&typeof o.s=="object"?o.s:{},u={};for(const[h,w]of Object.entries(d))typeof w=="number"&&Number.isFinite(w)&&(u[h]=w);return{g:typeof o.g=="number"&&Number.isFinite(o.g)?o.g:0,s:u,v:1}}catch{return t}},cn=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",o=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(o===void 0?{}:{_id:o}),op:n,table:t}},ot=(e,t,r)=>{for(const n of t)e.push(cn(n));return r!==void 0&&t.length>=r},dn="/_lunora/admin/export",un="/_lunora/admin/import",ln="/_lunora/admin/sync",hn="/_lunora/admin/connector/sync",pn="/_lunora/admin/apply",fn="/_lunora/admin/export-tap/run",mn=new TextEncoder,wn=async e=>{const t=await be(e,"Export")??{};if(t.tables===void 0)return{tables:void 0};if(!Array.isArray(t.tables))throw new i("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const n of t.tables){if(typeof n!="string"||n.length===0)throw new i("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(n)}return{tables:r}},je=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,gn=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:o,queryCoordinator:d,assertAdmin:u,requireAdminOption:h,resolveForwardContext:w,shardDO:R,streamExportRows:I,streamingImport:b,syncGlobals:k}=e,p=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),P=await wn(A),{headers:Q}=await w(A,j),M=new ReadableStream({async pull(B){const K=X=>{B.enqueue(mn.encode(`${JSON.stringify(X)}
2
- `))};try{await I(F,Q,P.tables,K),B.close()}catch(X){B.error(X)}}});return new Response(M,{headers:{"content-type":"application/x-ndjson"},status:200})},g=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),P=await ee(A),Q=typeof P.cursors=="object"&&P.cursors!==null?P.cursors:{},M=typeof P.limit=="number"?P.limit:void 0,B=typeof P.globalCursor=="number"?P.globalCursor:0,K=je(P.tables),{headers:X}=await w(A,j),J=K??o(),ne=await F.orchestrateCdcSync(R,{cursors:Q,headers:X,limit:M,tables:J}),he=k?await k({limit:M,sinceSeq:B}):void 0;return Response.json({global:he,shards:ne.shards},{status:200})},E=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),P=await ee(A),Q=sn(P.cursor),M=typeof P.limit=="number"&&P.limit>0?P.limit:void 0,B=je(P.tables),{headers:K}=await w(A,j),X=B??o(),J=await F.orchestrateCdcSync(R,{cursors:Q.s,headers:K,limit:M,tables:X}),ne=[],he={...Q.s};let ae=!1;for(const se of J.shards)ae=ot(ne,se.changes??[],M)||ae,he[se.shardKey]=se.cursor;let pe=Q.g;if(k){const se=await k({limit:M,sinceSeq:Q.g});ae=ot(ne,se.changes,M)||ae,pe=se.cursor}const _e=on({g:pe,s:he,v:1}),ve={changes:ne,hasMore:ae,nextCursor:_e};return Response.json(ve,{status:200})},_=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),P=await ee(A),Q=(Array.isArray(P.batches)?P.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),M=Array.isArray(P.globalChanges)?P.globalChanges:[],{headers:B}=await w(A,j),K=await F.orchestrateApplyCdc(R,{batches:Q,headers:B}),X=M.length>0&&t?await t({changes:M}):0;return Response.json({applied:K.applied+X,failed:K.failed,ok:K.ok},{status:200})},O=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;u(A);const{headers:F}=await w(A,j),P=await b(A,F);return Response.json(P,{headers:{"content-type":"application/json"},status:200})},N=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new i("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const P=await ee(A),Q=typeof P.sink=="string"?P.sink:void 0,M=typeof P.limit=="number"&&P.limit>0?P.limit:void 0,B=je(P.tables);if(Q===void 0)throw new i("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const K=n[Q];if(K===void 0)throw new i(`Export-tap sink "${Q}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:X}=await w(A,j),J=B??o(),ne=await Ar({coordinator:F,cursorStore:r,headers:X,limit:M,shardDO:R,sink:K,tables:J});return Response.json(ne,{headers:{"content-type":"application/json"},status:200})};return{[pn]:_,[hn]:E,[dn]:p,[fn]:N,[un]:O,[ln]:g}},yn=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const o of t)e.resolveTableSharding?.(o)?.mode.kind==="global"?n.push(o):r.push(o);return{globalTables:n,shardLocalTables:r}},bn=async(e,t,r,n,o,d)=>{if(r!==void 0&&n.length===0)return;const u=await e.orchestrateExport(d,{args:{tables:n},headers:t,tables:n});for(const h of u.shards)if(!h.error)for(const w of h.rows??[])o(w)},st=async(e,t,r,n,o,d)=>{const{globalTables:u,shardLocalTables:h}=yn(e,n);await bn(t,r,n,h,o,d);const w=e.exportGlobals;if((n===void 0||u.length>0)&&w)for await(const R of w({tables:u}))o(R)},_n=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},Rn=(e,t,r,n,o)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const d=e[r.mode.field];return d==null?{error:{code:"BAD_ROW",line:o,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof d=="string"?d:JSON.stringify(d)}}return{ok:!0,shardKey:n}},En=async(e,t,r)=>{if(!e.body)throw new i("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],o=[],d=new Map;let u=0,h=0;const w=e.body.getReader(),R=new TextDecoder;let I="",b=0;const k=p=>{h+=1;const g=p.trim();if(g.length===0)return;u+=1;const E=_n(g,h);if(!E.ok){n.push(E.error);return}const{doc:_,table:O}=E,N=t.resolveTableSharding?.(O);if(N?.mode.kind==="global"){o.push({doc:_,line:h,table:O});return}const A=Rn(_,O,N,r,h);if(!A.ok){n.push(A.error);return}const j=d.get(A.shardKey);j?j.rows.push({doc:_,table:O}):d.set(A.shardKey,{rows:[{doc:_,table:O}],shardKey:A.shardKey,startLine:h})};for(;;){const{done:p,value:g}=await w.read();if(p)break;if(g&&(b+=g.byteLength,b>Et))throw await w.cancel().catch(()=>{}),new i("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});I+=R.decode(g,{stream:!0});let E=I.indexOf(`
3
- `);for(;E!==-1;){const _=I.slice(0,E);I=I.slice(E+1),k(_),E=I.indexOf(`
4
- `)}}return I.length>0&&k(I),{errors:n,globalRows:o,perShard:d,received:u}},it=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},Sn=async(e,t,r,n)=>{const o=t.defaultShardKey??"__root__",{errors:d,globalRows:u,perShard:h,received:w}=await En(e,t,o),R={conflicts:0,errors:d,inserted:{}},I=[];if(t.resolveTableSharding===void 0&&h.size>0&&I.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 b=t.queryCoordinator;if(!b)throw new i("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const k=await b.orchestrateImport(n,{batches:[...h.values()],headers:r});it(R,k)}if(u.length>0)if(t.importGlobals){const b=u[0]?.line??1,k=await t.importGlobals({rows:u,startLine:b});it(R,k)}else for(const b of u)R.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:b.line,message:`row targets global table "${b.table}" but no \`importGlobals\` is configured`,table:b.table});return{conflicts:R.conflicts,errors:R.errors,inserted:R.inserted,received:w,...I.length>0?{warnings:I}:{}}},Be=e=>typeof e=="object"&&e!==null?e:{},$e=e=>typeof e.kind=="string"?e.kind:"unknown",Tn=(e,t)=>{let r=Be(t),n=!1;$e(r)==="optional"&&(n=!0,r=Be(r._meta?.inner));const o=$e(r),d=r._meta??{},u={kind:o,name:e,optional:n};if(o==="id"&&typeof d.tableName=="string"&&(u.table=d.tableName),o==="array"){const h=$e(Be(d.inner));h!=="unknown"&&(u.element=h)}return u},On=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>Tn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),An="/_lunora/admin/functions",vn="/_lunora/admin/cron-jobs",kn="/_lunora/admin/openapi",In="/_lunora/admin/openrpc",Dn="/_lunora/admin/global/tables",Pn="/_lunora/admin/global/table",Un="/_lunora/admin/global/facet",ct=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:o,value:d}=n;return[{column:o,value:d}]});return r.length===0?void 0:r},Nn=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:{}}),qn=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"}),Cn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:o,requireAdminOption:d}=e,u=p=>{L(p,"GET","Functions");const g=d(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),E=Object.entries(g).flatMap(([_,O])=>O.visibility==="internal"||O.kind==="stream"?[]:[{args:On(O.args),kind:O.kind,path:_}]).toSorted((_,O)=>_.path.localeCompare(O.path));return Response.json({functions:E},{headers:{"content-type":"application/json"},status:200})},h=p=>{L(p,"GET","Cron-jobs");const g=d(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),E=Object.entries(g).flatMap(([_,O])=>O.map(N=>({args:N.args,cron:_,functionPath:N.functionPath,name:N.name,shardKey:N.shardKey,workflow:N.workflow}))).toSorted((_,O)=>_.name.localeCompare(O.name));return Response.json({jobs:E},{headers:{"content-type":"application/json"},status:200})},w=p=>(L(p,"GET","OpenAPI"),t(p),Response.json(r.openApiSpec??Nn,{headers:{"content-type":"application/json"},status:200})),R=p=>(L(p,"GET","OpenRPC"),t(p),Response.json(r.openRpcSpec??qn,{headers:{"content-type":"application/json"},status:200})),I=async p=>{L(p,"GET","Global-tables");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await g.listTables(),{headers:{"content-type":"application/json"},status:200})},b=async p=>{L(p,"GET","Global-table");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),E=new URL(p.url),_=o(E,"table");if(_===void 0)throw new i("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const O=await g.readTablePage({...n(p),filters:ct(o(E,"filters")),table:_});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},k=async p=>{L(p,"GET","Global-facet");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),E=new URL(p.url),_=o(E,"table"),O=o(E,"column");if(_===void 0||O===void 0)throw new i("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const N=o(E,"limit"),A=N===void 0?void 0:Number(N),j=await g.facetColumn({column:O,filters:ct(o(E,"filters")),limit:A!==void 0&&Number.isFinite(A)?A:void 0,table:_});return Response.json(j,{headers:{"content-type":"application/json"},status:200})};return{[vn]:h,[An]:u,[Un]:k,[Pn]:b,[Dn]:I,[kn]:w,[In]:R}},xn="/_lunora/admin/kv/namespaces",jn="/_lunora/admin/kv/keys",Dt="/_lunora/admin/kv/value",Pt=32*1048576,dt=60,Bn=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=b=>r(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),o=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),d=(b,k)=>{const p=new URL(b.url),g=p.searchParams.get("namespace")??"",E=p.searchParams.get("key")??"";if(g==="")throw new i(`KV-value ${k} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(E==="")throw new i(`KV-value ${k} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:E,namespace:g}},u=async(b,k)=>{if(!(await b.listNamespaces()).some(p=>p.binding===k))throw new i(`Unknown KV namespace binding \`${k}\``,{code:"NOT_FOUND",status:404})},h=async b=>(L(b,"GET","KV-namespaces"),o({namespaces:await n(b).listNamespaces()})),w=async b=>{L(b,"GET","KV-keys");const k=n(b),p=new URL(b.url),g=p.searchParams.get("namespace")??"";if(g==="")throw new i("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const E=p.searchParams.get("prefix")??void 0,_=p.searchParams.get("cursor")??void 0,O=p.searchParams.get("limit"),N=O===null?void 0:Number.parseInt(O,10);if(N!==void 0&&(!Number.isInteger(N)||N<1))throw new i("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const A=N===void 0?void 0:Math.min(N,1e3);return await u(k,g),o(await k.listKeys({cursor:_,limit:A,namespace:g,prefix:E}))},R={DELETE:async b=>{const k=n(b),p=d(b,"DELETE");return await u(k,p.namespace),await k.deleteKey(p),o({deleted:!0})},GET:async b=>{const k=n(b),p=d(b,"GET");return await u(k,p.namespace),o(await k.getValue(p))},PUT:async b=>{const k=n(b),p=await t(b,Pt);if(typeof p.namespace!="string"||p.namespace==="")throw new i("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new i("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new i("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<dt))throw new i("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const g=Math.floor(Date.now()/1e3)+dt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<g))throw new i("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(k,p.namespace),await k.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),o({ok:!0})}},I=b=>{const k=R[b.method];if(!k)throw new i("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return k(b)};return{[xn]:h,[jn]:w,[Dt]:I}},$n="/_lunora/migrate",Ln="/_lunora/admin/pitr",Kn="/_lunora/admin/rank",Gn="/_lunora/admin/rankpage",Fn="/_lunora/admin/shard-traffic",Qn=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Mn=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),zn=async e=>{const t=await be(e,"Migration")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.functionPath!="string"||!Qn.has(t.functionPath))throw new i("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,table:t.table}},Wn=async e=>{const t=await be(e,"Rank")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.index!="string"||t.index.length===0)throw new i("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof t.partitionKey!="string")throw new i("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof t.rowId!="string"||t.rowId.length===0)throw new i("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(t.sortValues))throw new i("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:t.sortValues,table:t.table}},Hn=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new i('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Jn=e=>{if(typeof e.table!="string"||e.table.length===0)throw new i("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new i("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new i("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 i("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 i("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Vn=async e=>{const t=await be(e,"Rank page")??{};Jn(t);const r=Hn(t.directions);return{cursor:typeof t.cursor=="string"?t.cursor:null,directions:r,index:t.index,partitionKey:typeof t.partitionKey=="string"?t.partitionKey:void 0,table:t.table,take:typeof t.take=="number"?t.take:void 0}},Yn=async e=>{const t=await be(e,"Shard-traffic")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:t.table}},Xn=async e=>{const t=await ee(e);if(typeof t.functionPath!="string"||!Mn.has(t.functionPath))throw new i("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new i("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},Zn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:o,resolveForwardContext:d,shardDO:u}=e,h=(p,g)=>{if(p.method!=="POST")throw new i(`${g} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!n(p))throw new i("Admin auth required",{code:"FORBIDDEN",status:403});if(!o)throw new i(`${g} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return o},w=async(p,g)=>{const E=h(p,"Migration"),_=await zn(p),{headers:O}=await d(p,g),N=await E.orchestrateMigration(u,{args:_.args,functionPath:_.functionPath,headers:O,table:_.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},R=async(p,g)=>{const E=h(p,"Rank"),_=await Wn(p),{headers:O}=await d(p,g),N=await E.orchestrateRank(u,{headers:O,index:_.index,partitionKey:_.partitionKey,rowId:_.rowId,sortValues:_.sortValues,table:_.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},I=async(p,g)=>{const E=h(p,"Rank page"),_=await Vn(p),{headers:O}=await d(p,g),N=await E.orchestrateRankPage(u,{..._,headers:O});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},b=async(p,g)=>{const E=h(p,"Shard-traffic"),_=await Yn(p),{headers:O}=await d(p,g),N=await E.orchestrateShardTraffic(u,{headers:O,table:_.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},k=async(p,g)=>{if(L(p,"POST","PITR"),!n(p))throw new i("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const E=await Xn(p),{headers:_}=await d(p,g),O=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:E.args,functionPath:E.functionPath}),headers:_,method:"POST"});return r(u,E.shardKey??t,O)};return{[$n]:w,[Ln]:k,[Kn]:R,[Gn]:I,[Fn]:b}},ea=1,ta=0,ra=32,na=512,aa=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,oa=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>na)return;const r=t.split(",");if(!(r.length>ra)){for(const n of r)if(!aa.test(n.trim()))return;return t}},sa=e=>{const t=br(e.headers.get("traceparent"));if(t===void 0)return;const r=oa(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},ia=(e,t={})=>{const r=sa(e),n=t.trustInbound===!0?r:void 0,o=Ae(8),d=n?.traceId??Ae(16),u=Ur(t.sampling,n===void 0?o:d),h=u.isTraced&&(n===void 0||n.sampled);return{decision:u,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:h,spanId:o,traceFlags:h?ea:ta,traceId:d,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},ca=(e,t)=>{t.traceparent=yr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},da=(e,t)=>{let r;return()=>{if(r===void 0){const n=Sr(e),o=t===void 0?void 0:t.cf;r=_r(Er(n),Rr(n,o))}return r}},ua="/_lunora/admin/scheduled",la="/_lunora/admin/scheduled/status",ha="/_lunora/admin/scheduled/ws",pa="/_lunora/admin/scheduled/cancel",fa="/_lunora/admin/scheduled/dead",ma="/_lunora/admin/scheduled/dead/retry",wa="/_lunora/admin/scheduled/dead/cancel",ga=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:o}=e,d=(w,R)=>I=>{if(I.method!=="GET")throw new i(`${R} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return n(I).fetch(new Request(`https://scheduler.internal${w}`,{method:"GET"}))},u=(w,R,I=R)=>async b=>{if(b.method!=="POST")throw new i(`${I} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const k=n(b),p=await b.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new i(`${R} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return k.fetch(new Request(`https://scheduler.internal${w}`,{body:JSON.stringify({id:p.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async w=>{if(w.headers.get("Upgrade")!=="websocket")throw new i("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(w))throw new i("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const R=r();return ge(R,o).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[pa]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[wa]:u("/dead/cancel","Scheduled dead-letter action"),[fa]:d("/dead","Scheduled dead-letter"),[ma]:u("/dead/retry","Scheduled dead-letter action"),[ua]:d("/list","Scheduled-list"),[la]:d("/status","Scheduler-status"),[ha]:h}},Ut="/_lunora/admin/storage",ya="/_lunora/admin/storage/url",ba="/_lunora/admin/storage/buckets",_a=10080*60,Nt=32*1048576,Ra=new Set(["GET","PUT"]),Ea=e=>{const t=new Uint8Array(e);let r="";for(const n of t)r+=n.toString(16).padStart(2,"0");return r},Sa=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:o,requireAdminOption:d,storage:u}=e,h=g=>{const E=n(g,"key");if(E===void 0)throw new i("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return E},w=async g=>{const E=d(g,u.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),_=new URL(g.url),O=await E(n(_,"prefix"),{bucket:n(_,"bucket"),cursor:n(_,"cursor"),...r(g)});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},R=g=>(L(g,"GET","Storage-buckets"),t(g),Response.json({buckets:u.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})),I=async g=>{const E=d(g,u.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),_=new URL(g.url),O=h(_);return await E(O,{bucket:n(_,"bucket")}),Response.json({deleted:!0,key:O},{headers:{"content-type":"application/json"},status:200})},b=async g=>{const E=d(g,u.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),_=new URL(g.url),O=h(_),N=await o(g,Nt),A=g.headers.get("content-type"),j=A===null||A===""?void 0:A,x=n(_,"expectedSha256"),F=n(_,"expectedSize");let P;if(x!==void 0||F!==void 0){const M=await crypto.subtle.digest("SHA-256",N);P=Ea(M);const B=F!==void 0&&N.byteLength!==Number(F),K=x!==void 0&&P!==x.toLowerCase();if(B||K)throw new i("Upload failed verification — the body did not match the declared size or SHA-256 checksum, so nothing was written",{code:"STORAGE_CHECKSUM_MISMATCH",status:400})}const Q=await E(O,N,{bucket:n(_,"bucket"),contentType:j,sha256:P});return Response.json(P===void 0?Q:{...Q,sha256:P},{headers:{"content-type":"application/json"},status:200})},k=async g=>{switch(g.method){case"DELETE":return I(g);case"GET":return w(g);case"POST":case"PUT":return b(g);default:throw new i("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async g=>{L(g,"GET","Storage URL");const E=d(g,u.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),_=new URL(g.url),O=h(_),N=Number(n(_,"expiresIn")??""),A=Number.isFinite(N)&&N>0?Math.min(N,_a):void 0,j=n(_,"method");if(j!==void 0&&!Ra.has(j))throw new i("Storage URL `method` must be GET or PUT",{code:"BAD_REQUEST",status:400});const x=j,F=n(_,"contentType"),P=await E(O,{bucket:n(_,"bucket"),contentType:F,expiresInSeconds:A,method:x});return Response.json({key:O,url:P},{headers:{"content-type":"application/json"},status:200})};return{[ba]:R,[Ut]:k,[ya]:p}},Ta=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},ut={mtls:e=>Ta(e,"tlsClientAuth","certVerified")==="SUCCESS"},Oa=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(ut,e)?ut[e]:void 0)??(()=>!1),Aa=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},va="/_lunora/admin/vector/indexes",ka="/_lunora/admin/vector/query",Ia=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async d=>{L(d,"GET","Vector-indexes");const u=r(d,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})},o=async d=>{L(d,"POST","Vector-query");const u=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new i("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const h=await t(d);if(typeof h.name!="string"||h.name==="")throw new i("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof h.text!="string"||h.text==="")throw new i("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(h.topK!==void 0&&(typeof h.topK!="number"||!Number.isInteger(h.topK)||h.topK<1))throw new i("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const w=await u.queryIndex({name:h.name,text:h.text,topK:h.topK});return Response.json(w,{headers:{"content-type":"application/json"},status:200})};return{[va]:n,[ka]:o}},Da="/_lunora/admin/workflows/instances",Pa="/_lunora/admin/workflows/instance",Ua="/_lunora/admin/workflows/status",Na={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},qa=e=>e!==null&&Object.hasOwn(Na,e)?e:void 0,lt=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Le=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new i(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},ht=()=>{throw new i("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Ca=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(u,h,w)=>{L(u,"GET","Workflows instances"),t(u);const R=r(h);if(!R)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const I=Le(w,"name"),b=qa(w.searchParams.get("status"));return Response.json(await R.listInstances({page:lt(w,"page"),perPage:lt(w,"perPage"),status:b,workflowName:I}))},o=async(u,h,w)=>{L(u,"GET","Workflows instance"),t(u);const R=r(h);return R?Response.json(await R.getInstance({instanceId:Le(w,"id"),workflowName:Le(w,"name")})):ht()},d=async(u,h)=>{L(u,"POST","Workflows status"),t(u);const w=r(h);if(!w)return ht();const R=await u.json().catch(()=>{});if(typeof R?.name!="string"||R.name===""||typeof R.id!="string"||R.id==="")throw new i("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:I}=R;if(I!=="pause"&&I!=="resume"&&I!=="terminate")throw new i("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await w.setInstanceStatus({action:I,instanceId:R.id,workflowName:R.name}))};return{[Pa]:o,[Da]:n,[Ua]:d}},xa={[Dt]:Pt,[Ut]:Nt},ja=new TextEncoder,pt="/_lunora/rpc",Ba="/_lunora/rpc-batch",$a="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:da(e,t),...r===void 0?{}:{waitUntil:r}}),ft=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},mt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ke=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const o=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(o)?void 0:o,scheme:n.protocol.replace(":",""),userAgent:r}},wt="/_lunora/voice/",La="/_lunora/scheduler/dispatch",Ka="/_lunora/admin/cron-jobs/run",Ga="/_lunora/admin/ws-token",Fa="/_lunora/admin/",Qa="/_lunora/migrate",Ma="/_lunora/status",za=e=>e.startsWith(Fa)||e===Qa,Wa=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},Ha="/api/auth",Ja="__lunora_admin__:recordAuthEvent",Va="__lunora_admin__:listPushSubscriptions",Ya=["/sign-in","/sign-up","/callback"],Xa=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return Ya.some(o=>n===o||n.startsWith(`${o}/`))},Se=(e,t,r,n)=>{const o=pr(r),d=o?r.code:"INTERNAL_SERVER_ERROR",u=o?r.status:500,h=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:d,message:h,status:u},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},Za=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},gt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,eo=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},de=async(e,t,r)=>{const n={"content-type":"application/json"},o=e.headers.get("authorization"),d=e.headers.get("cookie"),u=e.headers.get("x-d1-bookmark"),h=e.headers.get("x-lunora-mutation-id"),w=e.headers.get("x-lunora-client-id"),R=e.headers.get("x-lunora-client-seq");o&&(n.authorization=o),d&&(n.cookie=d),u&&(n["x-d1-bookmark"]=u),h&&(n["x-lunora-mutation-id"]=h),w&&(n["x-lunora-client-id"]=w),R&&(n["x-lunora-client-seq"]=R);const I=e.headers.get("cf-connecting-ip");if(I&&(n["x-lunora-client-ip"]=I),!r)return{claims:null,headers:n,identity:null,userId:null};const b=await r(e,t);if(!b||typeof b.userId!="string"||b.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=wr(b.userId);const k=Za(b);k!==void 0&&(n["x-lunora-identity-exp"]=String(k));const{userId:p,...g}=b,E=Object.keys(g).length>0?g:null;return E&&(n["x-lunora-identity"]=gr(E)),{claims:E,headers:n,identity:b,userId:p}},to=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),ro=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new i("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 i("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new i("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!to.has(r.kind))throw new i("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new i("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new i("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},no=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},yt=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new i("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new i(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},ao=async e=>{const t=await St(e);let r;try{r=JSON.parse(t)}catch{throw new i("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new i("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&Tt(n.args,"RPC"),n.shardKey!==void 0&&typeof n.shardKey!="string")throw new i("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const o=r,d=ro(o.fanOut),u=o.args??{};if(d&&o.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==d.table)throw new i("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=d.table}return{args:u,fanOut:d,functionPath:o.functionPath,shardKey:o.shardKey}},oe=async(e,t,r)=>ge(e,t).fetch(r),Te=new Map,oo=5e3,so=4096,io=async(e,t)=>{const r=Date.now(),n=Te.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&Te.delete(t);let o=0;try{const d=await ge(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(d.ok){const u=(await d.json()).relayCount;typeof u=="number"&&u>0&&(o=Math.floor(u))}}catch{o=0}return Rt(Te,so),Te.set(t,{expiresMs:r+oo,relayCount:o}),o},co=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,r])=>r===t)?.[0]},Oe=(e,t,r)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:r,method:"POST"}),uo=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],bt=(e,t)=>{for(const r of uo){e.delete(r);const n=t[r];n!==void 0&&e.set(r,n)}},lo=async(e,t,r)=>e.length===0||r.length===0?!1:Ge(await vt(e,t),r),_t=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...o]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:Ge(t,o.join(" ").trim())},ho=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await Vr(t,n)?!0:r?!1:Ge(t,n)},po=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return Ir(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Ne(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Ne(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Ne(`hyperdrive:${e}`,!0)},qt=e=>{const t=Oa(e.trustInboundTraceContext),r=Aa(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",o=Dr(e.resolveIdentity,e.identity),d=Ye(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:Ye(e.schedulerDO,e.jurisdiction);let h;const w=()=>e.adminToken??h;let R;const I=()=>e.requireEphemeralWsToken??R??!0,b=a=>{const s=a??{};if(R===void 0&&e.requireEphemeralWsToken===void 0){const c=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(R=Wr(c,!0))}if(h!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(h=l)},k=new WeakSet,p=a=>_t(a,w())||k.has(a),g=async(a,s)=>{const l=await de(a,s,e.resolveIdentity);if(k.has(a)&&l.headers.authorization===void 0){const c=w();c!==void 0&&(l.headers.authorization=`Bearer ${c}`)}return l};let E=!1;const _=a=>{if(!e.allowUnauthenticatedShardAccess){const s=a==="fan-out"?"authorizeFanOut":"authorizeShard";throw new i(`${a} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${a} access (relying solely on per-row RLS).`,{code:a==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}E||(E=!0,console.warn([`[lunora] SECURITY: serving ${a} 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("")))},O=async(a,s,l=!0)=>{if(e.authorizeShard){if(!await e.authorizeShard(a,s))throw new i("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else l&&s!==n&&_("shard")},N=Zn({defaultShard:n,forwardToShard:oe,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:g,shardDO:d}),A=async(a,s,l,c,m)=>{await O(null,l,!1);const y={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(y["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(y["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(y["x-lunora-mutation-id"]=c),oe(d,l,Oe(a,s,y))},j=async(a,s,l,c)=>{const m=l?.[a];if(!m||typeof m.create!="function")throw new i(`${c} targets workflow binding "${a}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(xr(s))throw new i(`${c} params ${jr}`,{code:"BAD_REQUEST",status:400});await m.create({params:s})},x=async(a,s)=>{if(a.workflow){await j(a.workflow,a.args??{},s,`cron job "${a.name}"`);return}if(a.functionPath===void 0)throw new i(`cron job "${a.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const l=await A(a.functionPath,a.args??{},a.shardKey??n);if(!l.ok)throw new i(`cron job "${a.name}" (${a.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},F=async(a,s,l,c)=>{const m=e.cronJobs?.[a];if(m)for(const y of m)try{await x(y,s)}catch(v){l.push(c(v))}},P=async(a,s)=>{if(!p(a))throw new i("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(L(a,"POST","cron-jobs run"),!e.cronJobs)throw new i("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await ee(a),c=typeof l.name=="string"?l.name:"";if(c==="")throw new i("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(y=>y.name===c);if(!m)throw new i(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await x(m,s),Response.json({name:c,ran:!0},{status:200})},Q=async a=>{const s=typeof a.pool=="string"&&a.pool.length>0?a.pool:void 0;if(!s||!u||typeof a.id!="string")return;const l=typeof a.instanceName=="string"&&a.instanceName.length>0?a.instanceName:"default";try{await ge(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:a.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},M=async(a,s)=>{L(a,"POST","Scheduler dispatch");const l=await St(a),c=s??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,y=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),v=a.headers.get("x-lunora-scheduler-signature");let f=!1;if(v&&m?f=await lo(m,l,v):y&&(f=_t(a,y)),!f)throw new i("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let S;try{S=JSON.parse(l)}catch{throw new i("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const T=S??{},q=T.args??{};if(typeof T.workflow=="string"&&T.workflow.length>0)return await j(T.workflow,q,s,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof T.functionPath!="string"||T.functionPath.length===0)throw new i("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const C=typeof T.shardKey=="string"&&T.shardKey.length>0?T.shardKey:n,$=typeof T.id=="string"&&T.id.length>0?T.id:void 0,V=Wa(a),Z=await A(T.functionPath,q,C,$,V);return await Q(T),Z},B=a=>{if(!p(a))throw new i("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},K=(a,s,l)=>{if(B(a),s===void 0)throw new i(l.message,{code:l.code,status:400});return s},X=tn({assertAdmin:B,getReader:()=>e.authAuditReader}),J=async(a,s)=>{B(a);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const c=s?.kind,m=s?.userId,y=s?.limit,v=c==="fcm"||c==="web-push"?c:void 0,f=typeof m=="string"&&m!==""?m:void 0,S=typeof y=="number"&&Number.isFinite(y)?Math.trunc(y):0,T=S>0?Math.min(S,1e3):1e3,q=(await l.list({kind:v,limit:T,userId:f})).filter(C=>v!==void 0&&C.kind!==v?!1:f===void 0||(C.userId??null)===f).map(({keys:C,token:$,...V})=>V);return Response.json({subscriptions:q},{headers:{"content-type":"application/json"},status:200})},ne=async(a,s)=>{if(!s.fanOut){if(s.functionPath===en)return X(a,s.args??{});if(s.functionPath===Va)return J(a,s.args)}},he=gn({applyGlobals:e.applyGlobals,assertAdmin:B,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:K,resolveForwardContext:g,shardDO:d,streamExportRows:(a,s,l,c)=>st(e,a,s,l,c,d),streamingImport:(a,s)=>Sn(a,e,s,d),syncGlobals:e.syncGlobals}),ae=(a,s)=>{const l=a.searchParams.get(s);return l===null||l===""?void 0:l},pe=a=>{const s=new URL(a.url),l=s.searchParams.get("limit"),c=s.searchParams.get("offset"),m=l===null?void 0:Number.parseInt(l,10),y=c===null?void 0:Number.parseInt(c,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:y!==void 0&&Number.isFinite(y)&&y>=0?y:void 0}},_e=()=>{if(u===void 0)throw new i("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},ve=ga({checkWsAdmin:async a=>p(a)||ho(a,w(),I()),requireSchedulerNamespace:_e,resolveSchedulerStub:a=>(B(a),ge(_e(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),se=Ca({assertAdmin:B,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Ct=Sa({assertAdmin:B,parsePaging:pe,queryParameter:ae,readBodyBytes:Or,requireAdminOption:K,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),xt=Ia({readJsonBody:ee,requireAdminOption:K,vectorIntrospector:e.vectorIntrospector}),jt=Bn({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:K}),Bt=Pr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:K}),$t=Cn({assertAdmin:B,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:ae,requireAdminOption:K}),Lt=a=>{const s=[],l=d??a?.SHARD;if(l!==void 0&&s.push(kr("durable-object:default",l,n)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(a??{})){const y=po(c,m);y!==void 0&&s.push(y)}for(const c of e.health?.probes??[])s.push(c);return s},Kt=vr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:Lt}),Gt=a=>{const s=e.schedulerInstanceName??"default",l=()=>ge(a,s),c=async(f,S)=>{const T=await l().fetch(new Request(`https://scheduler.internal${f}`,S));if(!T.ok)throw new i(`ctx.scheduler: SchedulerDO ${f} failed (${String(T.status)}): ${await T.text()}`,{code:"INTERNAL",status:500});return await T.json()},m=async(f,S)=>await c(f,{body:JSON.stringify(S),headers:{"content-type":"application/json"},method:"POST"}),y=f=>{const S=f;if(S==null)throw new i("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 i("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})},v=async(f,S,T={})=>{const{id:q}=await m("/schedule",{args:T,scheduledFor:f,...y(S)});return q};return{cancel:async f=>await m("/cancel",{id:f}),get:async f=>await c(`/get?id=${encodeURIComponent(f)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(f,S,T)=>{if(!Number.isFinite(f)||f<0)throw new i("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await v(Date.now()+f,S,T)},runAt:async(f,S,T)=>{if(!Number.isFinite(f))throw new i("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await v(f,S,T)}}},Ft=async(a,s,l)=>{const{claims:c,headers:m,userId:y}=await de(a,s,o),v=async(f,S={})=>{const T=f.__lunoraRef;if(typeof T!="string")throw new i("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const q=Oe(T,S,{...m,"x-lunora-system":"1"}),C=await oe(d,n,q),$=await C.json();if($.error)throw new i($.error.message??"shard RPC failed",{code:$.error.code??"INTERNAL",status:C.status});return $.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:y},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),runAction:v,runMutation:v,runQuery:v,...u===void 0?{}:{scheduler:Gt(u)},...e.storage===void 0?{}:{storage:Cr(e.storage(s))}}},Qt=async(a,s,l)=>{if(!e.httpRouter)return;const c=await Ft(a,s,l);try{return await e.httpRouter.fetch(a,{...s,__lunoraCtx:c},l)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},Mt=async(a,s,l)=>{if(a.headers.get("Upgrade")!=="websocket")throw new i("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=Ze(a,ie);if(c)return c;const m=l.searchParams.get("shard")??n,{headers:y,identity:v}=await de(a,s,o);await O(v,m);const f=new Headers(a.headers),S=[...f.keys()];for(const q of S)q.startsWith("x-lunora-")&&f.delete(q);bt(f,y);const T=co(s,e.shardDO);if(T!==void 0){f.set("x-lunora-shard-binding",T);const q=await io(d,m);if(q>0){const C=Qr(m,Math.floor(Math.random()*q));return oe(d,C,new Request(a,{headers:f}))}}return oe(d,m,new Request(a,{headers:f}))},zt=async(a,s,l)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(a.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=Ze(a,ie);if(m)return m;let y;try{y=decodeURIComponent(l.pathname.slice(wt.length))}catch{return new Response("Unknown voice agent",{status:404})}const v=Object.hasOwn(c,y)?c[y]:void 0;if(v===void 0)return new Response("Unknown voice agent",{status:404});const f=l.searchParams.get("threadKey");if(f===null||f.length===0)return new Response("Missing threadKey",{status:400});const{headers:S,identity:T}=await de(a,s,o);if(e.authorizeShard){if(!await e.authorizeShard(T,f))return new Response("Forbidden",{status:403})}else _("shard");const q=new Headers(a.headers);for(const C of q.keys())C.startsWith("x-lunora-")&&q.delete(C);return bt(q,S),oe(v,f,new Request(a,{headers:q}))},Wt=async(a,s,l)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(l,a.table,s))throw new i("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new i("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 i("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});_("fan-out")},Re=async(a,s)=>{if(!(!a.fanOut&&a.functionPath.startsWith("__lunora_admin__:"))){if(a.fanOut){await Wt(a.fanOut,a.functionPath,s);return}await O(s,a.shardKey??n)}},ke=async(a,s,l,c,m,y)=>{const v=Date.now(),{observability:f,sampling:S}=e,T=Ke(a),{decision:q,ignoredUpstream:C,trace:$}=ia(a,{...S===void 0?{}:{sampling:S},trustInbound:t(a)});C&&r();const V={...m,"x-lunora-sample-errors":q.keepErrors?"1":"0"};ca($,V);const Z=Oe(s,l,V);try{const G=await oe(d,c,Z);return ce(f,{...T,...mt($),durationMs:Date.now()-v,functionPath:s,ok:G.ok,shardKey:c,...G.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(G.status)}`,status:G.status}}},y,void 0,{isTraced:$.sampled,keepErrors:q.keepErrors}),G}catch(G){throw ce(f,{...T,...mt($),...Se(s,Date.now()-v,G,{shardKey:c})},y,void 0,{isTraced:$.sampled,keepErrors:q.keepErrors}),G}},Ht=a=>{if(a.fanOut&&a.shardKey)throw new i("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!a.fanOut&&a.functionPath.startsWith("__lunora_relation__:"))throw new i("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(a.fanOut&&!e.queryCoordinator)throw new i("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Jt=async(a,s,l)=>{L(a,"POST","RPC");const c=await ao(a);no(s,c),Ht(c);const m=await ne(a,c);if(m!==void 0)return m;const{headers:y,identity:v}=await de(a,s,o);await Re(c,v);const f=yt(c,e);{const S=Date.now(),{observability:T}=e,q=Ke(a),C=Ee(s,a,l&&(Z=>l.waitUntil?.(Z)));if(c.fanOut){const Z=e.queryCoordinator;if(!Z)throw new i("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const G=await Z.fanOut(d,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:y});return ce(T,{durationMs:Date.now()-S,fanOut:{failed:G.failed,shards:G.ok+G.failed,table:c.fanOut.table},functionPath:c.functionPath,...q,ok:!0},C),Response.json(G,{headers:{"content-type":"application/json"},status:200})}catch(G){throw ce(T,{...Se(c.functionPath,Date.now()-S,G,{fanOut:{table:c.fanOut.table}}),...q},C),G}}const $=c.shardKey??n,V=()=>ke(a,c.functionPath,c.args??{},$,y,C);return f&&e.x402Charge?e.x402Charge(a,{functionPath:c.functionPath,price:f.price},V,ft(l)):V()}},Vt=async(a,s,l)=>{L(a,"POST","RPC batch");const c=await ee(a),{calls:m}=c;if(!Array.isArray(m))throw new i("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:y,identity:v}=await de(a,s,o),f=nn(m,n);for(const z of f.values())for(const W of z)if(e.functions?.[W.functionPath]?.x402)throw new i(`paid (\`.x402\`) function "${W.functionPath}" cannot be called in a batch; dispatch it individually over ${pt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...f.entries()].flatMap(([z,W])=>W.map(re=>Re({functionPath:re.functionPath,shardKey:z},v))));const{observability:S}=e,T=Ee(s,a,l&&(z=>l.waitUntil?.(z))),q=Ke(a),C=[],$=[],V=(z,W,re,ue)=>({body:{error:{code:re,message:ue}},id:z.id,status:W}),Z=(z,W,re,ue,fe)=>{for(const H of z)ce(S,fe(H),T),C.push(V(H,W,re,ue))},G=(z,W,re,ue,fe)=>{for(const H of z){const me=ue.get(H.id)??fe,ye=me<400;ce(S,{durationMs:re,functionPath:H.functionPath,...q,ok:ye,shardKey:W,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},T)}};await Promise.all([...f.entries()].map(async([z,W])=>{const re=new Headers(y);re.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:W}),headers:re,method:"POST"}),fe=Date.now();let H;try{H=await oe(d,z,ue)}catch(Y){const Ue=Date.now()-fe,{body:He}=fr(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});Z(W,502,He.code,He.message,hr=>({...Se(hr.functionPath,Ue,Y,{shardKey:z}),...q}));return}const me=Date.now()-fe,ye=H.headers.get("x-d1-bookmark");ye&&$.push(ye);let De;try{De=await H.json()}catch{const Y=`shard batch returned a non-JSON response (${String(H.status)})`;Z(W,H.status,"SHARD_ERROR",Y,Ue=>({durationMs:me,error:{code:"SHARD_ERROR",message:Y,status:H.status},functionPath:Ue.functionPath,...q,ok:!1,shardKey:z}));return}const Pe=Array.isArray(De.results)?De.results:[],ur=new Map(Pe.map(Y=>[Y.id,Y.status??H.status])),lr=new Set(Pe.map(Y=>Y.id));G(W,z,me,ur,H.status),C.push(...Pe);for(const Y of W)lr.has(Y.id)||C.push(V(Y,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const ze={"content-type":"application/json"},[We]=$;return $.length===1&&We!==void 0&&(ze["x-d1-bookmark"]=We),Response.json({results:C},{headers:ze,status:200})},Yt=async(a,s,l,c={},m={})=>{try{const y=l.__lunoraRef;if(typeof y!="string")throw new i("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:v,identity:f}=await de(a,s,o);await Re({functionPath:y,shardKey:m.shardKey},f);const S=m.shardKey??n,T=Ee(s,a,m.waitUntil);return await ke(a,y,c,S,v,T)}catch(y){return Je(y)}},Xt=1e3,Zt=async(a,s)=>{const l=e.backupRetain;if(l===void 0||l<=0)return;const c=[];let m;for(let v=0;v<Xt;v+=1){const f=await a.list({cursor:m,prefix:s});for(const S of f.objects)S.key.endsWith(".manifest.json")&&c.push(S.key);if(!f.truncated||f.cursor===void 0)break;m=f.cursor}const y=c.toSorted((v,f)=>f.localeCompare(v)).slice(l);await Promise.all(y.flatMap(v=>{const f=v.slice(0,-14);return[a.delete(v),a.delete(f)]}))},er=async a=>{const s=e.backupStore,l=e.queryCoordinator;if(!s)throw new i("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!l)throw new i("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const c=w();if(!c||c.length===0)throw new i("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const m={authorization:`Bearer ${c}`,"content-type":"application/json"},y=e.backupTables;let v=0,f=0;const S=[];await st(e,l,m,y,Z=>{const G=`${JSON.stringify(Z)}
5
- `;v+=1,f+=ja.encode(G).byteLength,S.push(G)},d);const T=e.backupPrefix??"backups/",q=new Date(a.scheduledTime).toISOString(),C=`${T}lunora-backup-${q.replaceAll(/[.:]/gu,"-")}.ndjson`,$=`${C}.manifest.json`;await s.put(C,new Blob(S,{type:"application/x-ndjson"}),{httpMetadata:{contentType:"application/x-ndjson"}});const V={bytes:f,createdAt:q,cron:a.cron,file:C,id:q,rows:v,scheduledTime:a.scheduledTime,...y?{tables:y.join(",")}:{}};await s.put($,`${JSON.stringify(V,void 0,2)}
6
- `,{httpMetadata:{contentType:"application/json"}}),await Zt(s,T)},Qe=async(a,s,l)=>{const{observability:c}=e,m=Date.now(),y=Ae(16),v=Ae(8),f=gt(s);try{const S=await l();return ce(c,{durationMs:Date.now()-m,functionPath:a,ok:!0,spanId:v,traceId:y},f),S}catch(S){throw ce(c,{...Se(a,Date.now()-m,S,{}),spanId:v,traceId:y},f),S}finally{Ve(c,f)}},tr=async(a,s,l)=>{b(s);const c=[],m=f=>f instanceof Error?f:new Error(String(f)),y=e.crons?.[a.cron];if(y)try{await y(a,s,l)}catch(f){c.push(m(f))}if(await F(a.cron,s,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===a.cron)try{await er(a)}catch(f){c.push(m(f))}const[v]=c;if(c.length===1&&v)throw v;if(c.length>1)throw new AggregateError(c,`scheduled("${a.cron}") had ${String(c.length)} failure(s)`)},rr=async(a,s)=>{try{const l=a??{},c=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await oe(d,n,Oe(Ja,{outcome:s},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},nr=async(a,s,l,c)=>{if(!e.authHandler)return;const m=await e.authHandler(a);if(!m)return;const y=e.authBasePath??Ha;return Xa(l.pathname,y)&&c.waitUntil?.(rr(s,m.status>=400?"fail":"ok")),m},ar=async({args:a,env:s,functionPath:l,request:c,shardKey:m,waitUntil:y})=>{Tt(a,"REST");const v={functionPath:l,...m===void 0?{}:{shardKey:m}},{headers:f,identity:S}=await de(c,s,o);await Re(v,S);const T=m??n,q=Ee(s,c,y),C=()=>ke(c,l,a,T,f,q),$=yt(v,e);return $&&e.x402Charge?e.x402Charge(c,{functionPath:l,price:$.price},C,ft({waitUntil:y})):C()},or=Tr({functions:e.functions??{},invoke:ar,readJsonBody:ee,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ie=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,sr={[Ma]:a=>a.method!=="GET"&&a.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[$a]:(a,s,l)=>Mt(a,s,l),[pt]:(a,s,l,c)=>Jt(a,s,c),[Ba]:(a,s,l,c)=>Vt(a,s,c),[La]:(a,s)=>M(a,s),[Ka]:(a,s)=>P(a,s),[Ga]:async a=>{L(a,"POST","ws-token"),B(a);const s=w();if(s===void 0)throw new i("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Jr(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...N,...he,...ve,...se,...Ct,...xt,...jt,...Bt,...$t,...Kt,...or,...Zr({assertAdmin:B,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:ae,readJsonBody:ee})};let ie=Xe(e.security),Me=!1;const ir=a=>{Me||(Me=!0,ie=Xe(e.security,a??{}))},cr=async(a,s)=>{if(!(e.adminGate===void 0||!za(s)))try{await e.adminGate(a)&&k.add(a)}catch{}},dr=async(a,s,l)=>{const c=new URL(a.url);if(a.method==="POST"||a.method==="PUT"){const f=Number(a.headers.get("content-length")??""),S=xa[c.pathname]??Et;if(Number.isFinite(f)&&f>S)throw new i("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await nr(a,s,c,l);if(m)return m;if(Ie){const f=`${a.method} ${c.pathname}`,S=Ie[f]??Ie[c.pathname];if(S)return S(a,s,l)}const y=sr[c.pathname];return y?(await cr(a,c.pathname),y(a,s,c,l)):e.voiceAgents!==void 0&&c.pathname.startsWith(wt)?zt(a,s,c):await Qt(a,s,l)||new Response("Not found",{status:404})};return{async fetch(a,s,l){e.passThroughOnException&&l.passThroughOnException?.(),ir(s),b(s);const c=Nr(a,ie);if(c)return c;const m=qr(a,ie);if(m)return qe(m,a,ie);try{const y=await dr(a,s,l);return qe(y,a,ie)}catch(y){return qe(Je(y),a,ie)}finally{Ve(e.observability,gt(l))}},async queue(a,s,l){await Qe(`queue:${eo(a)}`,l,async()=>{await e.queue?.(a,s,l)})},async scheduled(a,s,l){await Qe(`cron:${a.cron}`,l,async()=>{await tr(a,s,l)})},serverQuery:Yt}},fo=e=>qt(e),mo=e=>typeof e=="function"?{fetch:e}:e,wo=e=>!!(e.crons??e.cronJobs??e.backupCron),No=(e,t)=>{const r=mo(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,o=u=>{const h=fo({...u,httpRouter:r});return n!==void 0&&!wo(u)?{...h,scheduled:async(w,R,I)=>{await n(w,R,I)}}:h};if(typeof t!="function")return o(t);const d=t;return{fetch:(u,h,w)=>o(d(h)).fetch(u,h,w),queue:(u,h,w)=>o(d(h)).queue?.(u,h,w)??Promise.resolve(),scheduled:(u,h,w)=>o(d(h)).scheduled(u,h,w),serverQuery:(u,h,w,R,I)=>o(d(h)).serverQuery(u,h,w,R,I)}},go=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new i("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},qo=(e={})=>(t,r,n)=>qt(go(e,r)).fetch(t,r,n??mr),Co=e=>e;export{en as GET_AUTH_AUDIT_LOG_OP,mr as NOOP_EXECUTION_CONTEXT,Bo as composeIdentityResolvers,fo as composeWorker,qo as createLunoraHandler,qt as createWorker,Co as defineRpcEnvelope,io as probeRelayCount,go as resolveLunoraOptions,$o as routeIdentityResolvers,No as withFrameworkWorker};