@lunora/runtime 1.0.0-alpha.57 → 1.0.0-alpha.59
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 +158 -18
- package/dist/index.d.ts +158 -18
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/BACKUP_KEY_PREFIX-DhFUE3VL.mjs +1 -0
- package/dist/packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-K0uZPIUj.mjs +1 -0
- package/dist/packem_shared/composeWorker-y5QruLqo.mjs +6 -0
- package/package.json +4 -4
- package/dist/packem_shared/composeWorker-DxXwbTng.mjs +0 -6
package/dist/index.d.mts
CHANGED
|
@@ -4,6 +4,78 @@ 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
|
+
/** The snapshot key a sidecar describes — the inverse of {@link backupManifestKey}. */
|
|
48
|
+
declare const backupObjectKeyOfManifest: (manifestKey: string) => string;
|
|
49
|
+
/**
|
|
50
|
+
* What every snapshot records about itself, whichever writer took it.
|
|
51
|
+
*
|
|
52
|
+
* `id` is the ISO timestamp the snapshot was taken at and the handle `restore`
|
|
53
|
+
* resolves; `file` is where it lives at its own destination (a file name in a
|
|
54
|
+
* directory, an object key in a bucket).
|
|
55
|
+
*/
|
|
56
|
+
interface BackupManifestEntry {
|
|
57
|
+
/** Byte length of the snapshot as stored. */
|
|
58
|
+
bytes: number;
|
|
59
|
+
createdAt: string;
|
|
60
|
+
file: string;
|
|
61
|
+
id: string;
|
|
62
|
+
rows: number;
|
|
63
|
+
/**
|
|
64
|
+
* Lowercase-hex SHA-256 of the snapshot. Optional only because snapshots
|
|
65
|
+
* taken before checksums existed have none — `restore --verify` refuses
|
|
66
|
+
* those rather than reporting an unverified restore as a verified one.
|
|
67
|
+
*/
|
|
68
|
+
sha256?: string;
|
|
69
|
+
/** The `--tables` / `backupTables` allowlist, when the snapshot is a subset. */
|
|
70
|
+
tables?: string;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Is this a backup manifest? The shape check both sides need: the reader, to
|
|
74
|
+
* skip an unrelated object under the prefix, and retention, to decide whether
|
|
75
|
+
* something is safe to delete. The side that deletes must not be the side
|
|
76
|
+
* without a guard.
|
|
77
|
+
*/
|
|
78
|
+
declare const isBackupManifestEntry: (value: unknown) => value is BackupManifestEntry;
|
|
7
79
|
/**
|
|
8
80
|
* Turn-key incremental-sync source helpers for warehouse connectors
|
|
9
81
|
* (Fivetran custom functions, Airbyte incremental sources).
|
|
@@ -2606,6 +2678,40 @@ type TraceTrustSignal = "mtls";
|
|
|
2606
2678
|
* can reach the worker.
|
|
2607
2679
|
*/
|
|
2608
2680
|
type TrustInboundTraceContext = boolean | TraceTrustSignal | ((request: Request) => boolean);
|
|
2681
|
+
/** What a prune did. Keys are sidecar keys; each names a snapshot at the same key without the suffix. */
|
|
2682
|
+
interface PrunedBackups {
|
|
2683
|
+
/** Removed, snapshot and sidecar both. */
|
|
2684
|
+
deleted: string[];
|
|
2685
|
+
/** Attempted and not removed. The snapshot may already be gone — the sidecar survives, so the next run retries. */
|
|
2686
|
+
failed: string[];
|
|
2687
|
+
/** Confirmed keys retention no longer owns: already pruned, or no longer eligible. */
|
|
2688
|
+
ignored: number;
|
|
2689
|
+
/** Still past the window afterwards — they appeared after the preview, or the run stopped at its cap. Run again. */
|
|
2690
|
+
remaining: number;
|
|
2691
|
+
}
|
|
2692
|
+
/** What retention would delete on the next run, and the configuration that decides it. */
|
|
2693
|
+
interface BackupRetentionPreview {
|
|
2694
|
+
/** The trigger retention belongs to. `undefined` when no scheduled backup is configured. */
|
|
2695
|
+
cron?: string;
|
|
2696
|
+
/**
|
|
2697
|
+
* Snapshots this cron owns — legacy sidecars and other writers' are not
|
|
2698
|
+
* counted, because retention never touches them. `0` when there is no
|
|
2699
|
+
* window (`keep === 0`): with nothing to select against, the bucket is not
|
|
2700
|
+
* listed at all.
|
|
2701
|
+
*/
|
|
2702
|
+
eligible: number;
|
|
2703
|
+
/** `backupRetain`; `0` when unset, which is what makes the selection empty. */
|
|
2704
|
+
keep: number;
|
|
2705
|
+
prefix: string;
|
|
2706
|
+
/** Sidecar keys, newest-first. Each names a snapshot at the same key without the suffix. */
|
|
2707
|
+
wouldDelete: string[];
|
|
2708
|
+
}
|
|
2709
|
+
/** A snapshot the scheduled backup took: the shared fields plus which trigger produced it. */
|
|
2710
|
+
interface BackupManifest extends BackupManifestEntry {
|
|
2711
|
+
cron: string;
|
|
2712
|
+
scheduledTime: number;
|
|
2713
|
+
sha256: string;
|
|
2714
|
+
}
|
|
2609
2715
|
/**
|
|
2610
2716
|
* Wire-format RPC envelope. Posted to `POST /_lunora/rpc`.
|
|
2611
2717
|
*
|
|
@@ -2917,6 +3023,26 @@ type StorageUploadFunction = (key: string, body: ArrayBuffer, options?: {
|
|
|
2917
3023
|
etag?: string;
|
|
2918
3024
|
key: string;
|
|
2919
3025
|
};
|
|
3026
|
+
/**
|
|
3027
|
+
* Reads one object's bytes back out of a storage bucket. Structurally the part
|
|
3028
|
+
* of `@lunora/storage`'s `Storage["download"]` the admin endpoint needs — the
|
|
3029
|
+
* body stream plus enough metadata to set the response headers. `null` means
|
|
3030
|
+
* "no such object", which the route turns into a 404.
|
|
3031
|
+
*
|
|
3032
|
+
* This is the read half of {@link StorageUploadFunction}: `lunora backup
|
|
3033
|
+
* restore --bucket` pulls a snapshot back through it under the same admin
|
|
3034
|
+
* bearer that wrote it, so restoring from a bucket does not depend on signed
|
|
3035
|
+
* URLs (which need a signing secret the deployment may not have configured).
|
|
3036
|
+
*/
|
|
3037
|
+
type StorageDownloadFunction = (key: string, options?: {
|
|
3038
|
+
bucket?: string;
|
|
3039
|
+
}) => Promise<{
|
|
3040
|
+
body: ReadableStream | null;
|
|
3041
|
+
httpMetadata?: {
|
|
3042
|
+
contentType?: string;
|
|
3043
|
+
};
|
|
3044
|
+
size?: number;
|
|
3045
|
+
} | null>;
|
|
2920
3046
|
/**
|
|
2921
3047
|
* Mints a (signed or public) URL for one object so the admin file browser can
|
|
2922
3048
|
* offer a "copy URL" action. The optional `expiresInSeconds` lets the caller pick
|
|
@@ -3094,40 +3220,34 @@ interface CronJobInfo {
|
|
|
3094
3220
|
*/
|
|
3095
3221
|
interface BackupStore {
|
|
3096
3222
|
delete: (key: string) => Promise<unknown>;
|
|
3223
|
+
/**
|
|
3224
|
+
* List objects under a prefix. `include: ["customMetadata"]` is how
|
|
3225
|
+
* retention tells its own snapshots from an operator's without a request
|
|
3226
|
+
* per object — R2 returns custom metadata on a listing only when asked, and
|
|
3227
|
+
* may return fewer than `limit` results when it is, which the cursor loop
|
|
3228
|
+
* already handles.
|
|
3229
|
+
*/
|
|
3097
3230
|
list: (options?: {
|
|
3098
3231
|
cursor?: string;
|
|
3232
|
+
include?: ("customMetadata" | "httpMetadata")[];
|
|
3099
3233
|
limit?: number;
|
|
3100
3234
|
prefix?: string;
|
|
3101
3235
|
}) => Promise<{
|
|
3102
3236
|
cursor?: string;
|
|
3103
3237
|
objects: ReadonlyArray<{
|
|
3238
|
+
customMetadata?: Record<string, string>;
|
|
3104
3239
|
key: string;
|
|
3105
3240
|
}>;
|
|
3106
3241
|
truncated?: boolean;
|
|
3107
3242
|
}>;
|
|
3108
|
-
put: (key: string, body: ArrayBuffer | Blob | null | ReadableStream | string, options?: {
|
|
3243
|
+
put: (key: string, body: ArrayBuffer | ArrayBufferView | Blob | null | ReadableStream | string, options?: {
|
|
3109
3244
|
customMetadata?: Record<string, string>;
|
|
3110
3245
|
httpMetadata?: {
|
|
3111
3246
|
contentType?: string;
|
|
3112
3247
|
};
|
|
3248
|
+
sha256?: ArrayBuffer | string;
|
|
3113
3249
|
}) => Promise<unknown>;
|
|
3114
3250
|
}
|
|
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
3251
|
/**
|
|
3132
3252
|
* Health / readiness probe configuration (plan 177). Everything is optional; the
|
|
3133
3253
|
* runtime always registers its default binding probes, so the endpoints work
|
|
@@ -3722,6 +3842,17 @@ interface WorkerOptions {
|
|
|
3722
3842
|
* `STORAGE_DELETE_NOT_CONFIGURED` — the studio surfaces a clear inline error.
|
|
3723
3843
|
*/
|
|
3724
3844
|
storageDelete?: StorageDeleteFunction;
|
|
3845
|
+
/**
|
|
3846
|
+
* Reads one object back, backing the admin-gated
|
|
3847
|
+
* `GET /_lunora/admin/storage/object` endpoint that `lunora backup restore
|
|
3848
|
+
* --bucket` pulls snapshots through. Wrap the storage call — the generated
|
|
3849
|
+
* app worker emits
|
|
3850
|
+
* `(key, opts) => pick(opts?.bucket).download(key)` — rather than passing
|
|
3851
|
+
* `createStorage(...).download` itself, whose second parameter is a byte
|
|
3852
|
+
* range, not a bucket. Omit it and the endpoint responds
|
|
3853
|
+
* `STORAGE_DOWNLOAD_NOT_CONFIGURED`.
|
|
3854
|
+
*/
|
|
3855
|
+
storageDownload?: StorageDownloadFunction;
|
|
3725
3856
|
/**
|
|
3726
3857
|
* Storage lister backing the admin-gated `GET /_lunora/admin/storage`
|
|
3727
3858
|
* endpoint the studio's file browser calls. The structural shape matches
|
|
@@ -4691,5 +4822,14 @@ interface ShardClient {
|
|
|
4691
4822
|
* See the module docs for the privilege model and the authorization caveat.
|
|
4692
4823
|
*/
|
|
4693
4824
|
declare const createShardClient: (namespace: ShardNamespaceLike, options?: ShardClientOptions) => ShardClient;
|
|
4825
|
+
/**
|
|
4826
|
+
* Body budget for an object upload, declared by this route the way the KV value
|
|
4827
|
+
* PUT declares its own (`KV_VALUE_MAX_BODY_BYTES`). The shared 1 MiB default is
|
|
4828
|
+
* a JSON-request cap; a blob migration (`lunora import --with-storage`) moves
|
|
4829
|
+
* real files, and a 1 MiB ceiling would push nearly every photo onto the
|
|
4830
|
+
* signed-URL fallback. 32 MiB is what the isolate can buffer and digest
|
|
4831
|
+
* comfortably inside the Workers memory limit.
|
|
4832
|
+
*/
|
|
4833
|
+
declare const STORAGE_UPLOAD_MAX_BODY_BYTES: number;
|
|
4694
4834
|
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 };
|
|
4835
|
+
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 BackupRetentionPreview, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS, DEFAULT_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 PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
|
package/dist/index.d.ts
CHANGED
|
@@ -4,6 +4,78 @@ 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
|
+
/** The snapshot key a sidecar describes — the inverse of {@link backupManifestKey}. */
|
|
48
|
+
declare const backupObjectKeyOfManifest: (manifestKey: string) => string;
|
|
49
|
+
/**
|
|
50
|
+
* What every snapshot records about itself, whichever writer took it.
|
|
51
|
+
*
|
|
52
|
+
* `id` is the ISO timestamp the snapshot was taken at and the handle `restore`
|
|
53
|
+
* resolves; `file` is where it lives at its own destination (a file name in a
|
|
54
|
+
* directory, an object key in a bucket).
|
|
55
|
+
*/
|
|
56
|
+
interface BackupManifestEntry {
|
|
57
|
+
/** Byte length of the snapshot as stored. */
|
|
58
|
+
bytes: number;
|
|
59
|
+
createdAt: string;
|
|
60
|
+
file: string;
|
|
61
|
+
id: string;
|
|
62
|
+
rows: number;
|
|
63
|
+
/**
|
|
64
|
+
* Lowercase-hex SHA-256 of the snapshot. Optional only because snapshots
|
|
65
|
+
* taken before checksums existed have none — `restore --verify` refuses
|
|
66
|
+
* those rather than reporting an unverified restore as a verified one.
|
|
67
|
+
*/
|
|
68
|
+
sha256?: string;
|
|
69
|
+
/** The `--tables` / `backupTables` allowlist, when the snapshot is a subset. */
|
|
70
|
+
tables?: string;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Is this a backup manifest? The shape check both sides need: the reader, to
|
|
74
|
+
* skip an unrelated object under the prefix, and retention, to decide whether
|
|
75
|
+
* something is safe to delete. The side that deletes must not be the side
|
|
76
|
+
* without a guard.
|
|
77
|
+
*/
|
|
78
|
+
declare const isBackupManifestEntry: (value: unknown) => value is BackupManifestEntry;
|
|
7
79
|
/**
|
|
8
80
|
* Turn-key incremental-sync source helpers for warehouse connectors
|
|
9
81
|
* (Fivetran custom functions, Airbyte incremental sources).
|
|
@@ -2606,6 +2678,40 @@ type TraceTrustSignal = "mtls";
|
|
|
2606
2678
|
* can reach the worker.
|
|
2607
2679
|
*/
|
|
2608
2680
|
type TrustInboundTraceContext = boolean | TraceTrustSignal | ((request: Request) => boolean);
|
|
2681
|
+
/** What a prune did. Keys are sidecar keys; each names a snapshot at the same key without the suffix. */
|
|
2682
|
+
interface PrunedBackups {
|
|
2683
|
+
/** Removed, snapshot and sidecar both. */
|
|
2684
|
+
deleted: string[];
|
|
2685
|
+
/** Attempted and not removed. The snapshot may already be gone — the sidecar survives, so the next run retries. */
|
|
2686
|
+
failed: string[];
|
|
2687
|
+
/** Confirmed keys retention no longer owns: already pruned, or no longer eligible. */
|
|
2688
|
+
ignored: number;
|
|
2689
|
+
/** Still past the window afterwards — they appeared after the preview, or the run stopped at its cap. Run again. */
|
|
2690
|
+
remaining: number;
|
|
2691
|
+
}
|
|
2692
|
+
/** What retention would delete on the next run, and the configuration that decides it. */
|
|
2693
|
+
interface BackupRetentionPreview {
|
|
2694
|
+
/** The trigger retention belongs to. `undefined` when no scheduled backup is configured. */
|
|
2695
|
+
cron?: string;
|
|
2696
|
+
/**
|
|
2697
|
+
* Snapshots this cron owns — legacy sidecars and other writers' are not
|
|
2698
|
+
* counted, because retention never touches them. `0` when there is no
|
|
2699
|
+
* window (`keep === 0`): with nothing to select against, the bucket is not
|
|
2700
|
+
* listed at all.
|
|
2701
|
+
*/
|
|
2702
|
+
eligible: number;
|
|
2703
|
+
/** `backupRetain`; `0` when unset, which is what makes the selection empty. */
|
|
2704
|
+
keep: number;
|
|
2705
|
+
prefix: string;
|
|
2706
|
+
/** Sidecar keys, newest-first. Each names a snapshot at the same key without the suffix. */
|
|
2707
|
+
wouldDelete: string[];
|
|
2708
|
+
}
|
|
2709
|
+
/** A snapshot the scheduled backup took: the shared fields plus which trigger produced it. */
|
|
2710
|
+
interface BackupManifest extends BackupManifestEntry {
|
|
2711
|
+
cron: string;
|
|
2712
|
+
scheduledTime: number;
|
|
2713
|
+
sha256: string;
|
|
2714
|
+
}
|
|
2609
2715
|
/**
|
|
2610
2716
|
* Wire-format RPC envelope. Posted to `POST /_lunora/rpc`.
|
|
2611
2717
|
*
|
|
@@ -2917,6 +3023,26 @@ type StorageUploadFunction = (key: string, body: ArrayBuffer, options?: {
|
|
|
2917
3023
|
etag?: string;
|
|
2918
3024
|
key: string;
|
|
2919
3025
|
};
|
|
3026
|
+
/**
|
|
3027
|
+
* Reads one object's bytes back out of a storage bucket. Structurally the part
|
|
3028
|
+
* of `@lunora/storage`'s `Storage["download"]` the admin endpoint needs — the
|
|
3029
|
+
* body stream plus enough metadata to set the response headers. `null` means
|
|
3030
|
+
* "no such object", which the route turns into a 404.
|
|
3031
|
+
*
|
|
3032
|
+
* This is the read half of {@link StorageUploadFunction}: `lunora backup
|
|
3033
|
+
* restore --bucket` pulls a snapshot back through it under the same admin
|
|
3034
|
+
* bearer that wrote it, so restoring from a bucket does not depend on signed
|
|
3035
|
+
* URLs (which need a signing secret the deployment may not have configured).
|
|
3036
|
+
*/
|
|
3037
|
+
type StorageDownloadFunction = (key: string, options?: {
|
|
3038
|
+
bucket?: string;
|
|
3039
|
+
}) => Promise<{
|
|
3040
|
+
body: ReadableStream | null;
|
|
3041
|
+
httpMetadata?: {
|
|
3042
|
+
contentType?: string;
|
|
3043
|
+
};
|
|
3044
|
+
size?: number;
|
|
3045
|
+
} | null>;
|
|
2920
3046
|
/**
|
|
2921
3047
|
* Mints a (signed or public) URL for one object so the admin file browser can
|
|
2922
3048
|
* offer a "copy URL" action. The optional `expiresInSeconds` lets the caller pick
|
|
@@ -3094,40 +3220,34 @@ interface CronJobInfo {
|
|
|
3094
3220
|
*/
|
|
3095
3221
|
interface BackupStore {
|
|
3096
3222
|
delete: (key: string) => Promise<unknown>;
|
|
3223
|
+
/**
|
|
3224
|
+
* List objects under a prefix. `include: ["customMetadata"]` is how
|
|
3225
|
+
* retention tells its own snapshots from an operator's without a request
|
|
3226
|
+
* per object — R2 returns custom metadata on a listing only when asked, and
|
|
3227
|
+
* may return fewer than `limit` results when it is, which the cursor loop
|
|
3228
|
+
* already handles.
|
|
3229
|
+
*/
|
|
3097
3230
|
list: (options?: {
|
|
3098
3231
|
cursor?: string;
|
|
3232
|
+
include?: ("customMetadata" | "httpMetadata")[];
|
|
3099
3233
|
limit?: number;
|
|
3100
3234
|
prefix?: string;
|
|
3101
3235
|
}) => Promise<{
|
|
3102
3236
|
cursor?: string;
|
|
3103
3237
|
objects: ReadonlyArray<{
|
|
3238
|
+
customMetadata?: Record<string, string>;
|
|
3104
3239
|
key: string;
|
|
3105
3240
|
}>;
|
|
3106
3241
|
truncated?: boolean;
|
|
3107
3242
|
}>;
|
|
3108
|
-
put: (key: string, body: ArrayBuffer | Blob | null | ReadableStream | string, options?: {
|
|
3243
|
+
put: (key: string, body: ArrayBuffer | ArrayBufferView | Blob | null | ReadableStream | string, options?: {
|
|
3109
3244
|
customMetadata?: Record<string, string>;
|
|
3110
3245
|
httpMetadata?: {
|
|
3111
3246
|
contentType?: string;
|
|
3112
3247
|
};
|
|
3248
|
+
sha256?: ArrayBuffer | string;
|
|
3113
3249
|
}) => Promise<unknown>;
|
|
3114
3250
|
}
|
|
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
3251
|
/**
|
|
3132
3252
|
* Health / readiness probe configuration (plan 177). Everything is optional; the
|
|
3133
3253
|
* runtime always registers its default binding probes, so the endpoints work
|
|
@@ -3722,6 +3842,17 @@ interface WorkerOptions {
|
|
|
3722
3842
|
* `STORAGE_DELETE_NOT_CONFIGURED` — the studio surfaces a clear inline error.
|
|
3723
3843
|
*/
|
|
3724
3844
|
storageDelete?: StorageDeleteFunction;
|
|
3845
|
+
/**
|
|
3846
|
+
* Reads one object back, backing the admin-gated
|
|
3847
|
+
* `GET /_lunora/admin/storage/object` endpoint that `lunora backup restore
|
|
3848
|
+
* --bucket` pulls snapshots through. Wrap the storage call — the generated
|
|
3849
|
+
* app worker emits
|
|
3850
|
+
* `(key, opts) => pick(opts?.bucket).download(key)` — rather than passing
|
|
3851
|
+
* `createStorage(...).download` itself, whose second parameter is a byte
|
|
3852
|
+
* range, not a bucket. Omit it and the endpoint responds
|
|
3853
|
+
* `STORAGE_DOWNLOAD_NOT_CONFIGURED`.
|
|
3854
|
+
*/
|
|
3855
|
+
storageDownload?: StorageDownloadFunction;
|
|
3725
3856
|
/**
|
|
3726
3857
|
* Storage lister backing the admin-gated `GET /_lunora/admin/storage`
|
|
3727
3858
|
* endpoint the studio's file browser calls. The structural shape matches
|
|
@@ -4691,5 +4822,14 @@ interface ShardClient {
|
|
|
4691
4822
|
* See the module docs for the privilege model and the authorization caveat.
|
|
4692
4823
|
*/
|
|
4693
4824
|
declare const createShardClient: (namespace: ShardNamespaceLike, options?: ShardClientOptions) => ShardClient;
|
|
4825
|
+
/**
|
|
4826
|
+
* Body budget for an object upload, declared by this route the way the KV value
|
|
4827
|
+
* PUT declares its own (`KV_VALUE_MAX_BODY_BYTES`). The shared 1 MiB default is
|
|
4828
|
+
* a JSON-request cap; a blob migration (`lunora import --with-storage`) moves
|
|
4829
|
+
* real files, and a 1 MiB ceiling would push nearly every photo onto the
|
|
4830
|
+
* signed-URL fallback. 32 MiB is what the isolate can buffer and digest
|
|
4831
|
+
* comfortably inside the Workers memory limit.
|
|
4832
|
+
*/
|
|
4833
|
+
declare const STORAGE_UPLOAD_MAX_BODY_BYTES: number;
|
|
4694
4834
|
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 };
|
|
4835
|
+
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 BackupRetentionPreview, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS, DEFAULT_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 PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as m}from"./packem_shared/BACKUP_KEY_PREFIX-DhFUE3VL.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-DTk8e2f9.mjs";import{composeWorker as S,createLunoraHandler as x,createWorker as _,defineRpcEnvelope as d,resolveLunoraOptions as l,withFrameworkWorker as u}from"./packem_shared/composeWorker-y5QruLqo.mjs";import{createCrossShardRelationCapabilities as k}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 g,toErrorResponse as b}from"./packem_shared/LunoraError-ByasbDmd.mjs";import{createKvCursorStore as H,createMemoryCursorStore as I,defineExportSink as P,r2Sink as v,runExportTap as D,sanitizeChange as F,webhookExportSink as M}from"./packem_shared/createKvCursorStore-C24tEuYk.mjs";import{HEALTH_PATH as G,HEALTH_READY_PATH as K,buildHealthRoutes as N,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-BuLCcWNS.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-CX3xEPYw.mjs";import{e as J,a as Z}from"./packem_shared/observability-DWlkDJJw.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-iIRy11I9.mjs";import{D as pe,a as me,c as ce}from"./packem_shared/pipeline-log-reader-FF1V32O2.mjs";import{createQueryCoordinator as Ee,createStaticShardRegistry as Re,mergeStrategyForAggregate as Se}from"./packem_shared/createQueryCoordinator-BkPfcxUG.mjs";import{applyJurisdiction as _e,resolveShard as de}from"./packem_shared/applyJurisdiction-Dsm_m5zW.mjs";import{R as ue,d as ye,o as ke}from"./packem_shared/rest-cache-5unAzdFN.mjs";import{g as Ae,E as Ce,U as Le,p as Te,y as ge}from"./packem_shared/rest-routes-BqldHiaH.mjs";import{decorateResponse as he,enforceOrigin as He,handleCorsPreflight as Ie,resolveSecurity as Pe}from"./packem_shared/decorateResponse-DBIWsRSZ.mjs";import{createShardClient as De}from"./packem_shared/createShardClient-BYYzDbMc.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Me}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-K0uZPIUj.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ge}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 Ye,routeIdentityResolvers as we}from"./packem_shared/composeIdentityResolvers-DwE0Jbww.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,me as DEFAULT_LOG_LIMIT,A as DEFAULT_REGISTRY_CACHE_TTL_MS,G as HEALTH_PATH,K as HEALTH_READY_PATH,Ge as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,g as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,C as SHARD_REGISTRY_DO_NAME,Me as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,_e as applyJurisdiction,ue as applyRestCache,Ae as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,N as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ye as composeIdentityResolvers,S as composeWorker,oe as consoleSink,k as createCrossShardRelationCapabilities,L as createDynamicShardRegistry,H as createKvCursorStore,x as createLunoraHandler,I as createMemoryCursorStore,ce as createPipelineLogReader,Ee as createQueryCoordinator,Le as createRestRateLimit,De as createShardClient,Re as createStaticShardRegistry,_ as createWorker,B as d1Probe,he as decorateResponse,P as defineExportSink,d as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,He as enforceOrigin,Ie as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,Se as mergeStrategyForAggregate,m as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,v as r2Sink,Te as readShardKey,ye as requestCarriesCredentials,j as resolveLogArchiveFromEnv,l as resolveLunoraOptions,Pe as resolveSecurity,de as resolveShard,ke as restCacheHeaders,ge as restSurfaceFromRegistry,we as routeIdentityResolvers,D as runExportTap,F as sanitizeChange,se as sentrySink,f as toAirbyteMessages,b as toErrorResponse,E as toFivetranResponse,M as webhookExportSink,ie as webhookSink,u 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 yr,toErrorBody as br}from"@lunora/errors";import{d as At}from"./evict-oldest-C2XU6HBR.mjs";import{NOOP_EXECUTION_CONTEXT as _r}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{f as Rr,u as Er}from"./identity-header-pdXOyDU4.mjs";import{O as Ae,m as Sr,A as Or,R as Tr,d as Ar,i as kr,s as vr}from"./otlp-resource-B-ByO9qo.mjs";import{h as X,f as be,i as kt,E as Ir,w as vt,e as It,b as Dr}from"./rest-routes-BqldHiaH.mjs";import{LunoraError as i,toErrorResponse as Xe}from"./LunoraError-ByasbDmd.mjs";import{r as x,t as we}from"./method-guard-rzvo19pa.mjs";import{normalizeBackupPrefix as Fe,BACKUP_KEY_PREFIX as Ge,isBackupManifestKey as Pr,backupObjectKeyOfManifest as Dt,backupObjectKey as Ur,backupManifestKey as Nr}from"./BACKUP_KEY_PREFIX-DhFUE3VL.mjs";import{toHex as qr,STORAGE_UPLOAD_MAX_BODY_BYTES as Cr,STORAGE_PATH as $r,buildStorageAdminRoutes as Br}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-K0uZPIUj.mjs";import{runExportTap as xr}from"./createKvCursorStore-C24tEuYk.mjs";import{buildHealthRoutes as jr,durableObjectProbe as Kr,d1Probe as Lr,presenceProbe as Ne}from"./HEALTH_PATH-BuLCcWNS.mjs";import{wrapResolverWithContract as Fr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as rs,routeIdentityResolvers as ns}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as Gr}from"./LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{o as Qr,f as Ze,a as ce}from"./observability-DWlkDJJw.mjs";import{resolveShard as ge,applyJurisdiction as et}from"./applyJurisdiction-Dsm_m5zW.mjs";import{resolveSecurity as tt,handleCorsPreflight as Mr,enforceOrigin as zr,decorateResponse as qe,enforceWebSocketOrigin as rt}from"./decorateResponse-DBIWsRSZ.mjs";const Wr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const r={...t,bucketName:"default"};return r.bucket=()=>r,r},Pt="__lunoraBranch",Jr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Pt),Hr=`may not contain the reserved workflow branch-marker key ("${Pt}")`,Qe=(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 s=o<e.length?e.charCodeAt(o):0,l=o<t.length?t.charCodeAt(o):0;n|=s^l}return n===0},Me=new TextEncoder,Vr=Array.from({length:32},(e,t)=>t);new RegExp(`[${Vr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Yr=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Xr=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},Zr=64,Ce=new Map,Ut=async e=>{const t=Ce.get(e);if(t)return t;At(Ce,Zr);const r=crypto.subtle.importKey("raw",Me.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ce.set(e,r),r},Nt=async(e,t)=>{const r=await Ut(e),n=await crypto.subtle.sign("HMAC",r,Me.encode(t));return Yr(new Uint8Array(n))},en=async(e,t,r)=>{const n=await Ut(e);return crypto.subtle.verify("HMAC",n,r,Me.encode(t))},tn="::relay::",rn=(e,t)=>`${e}${tn}${String(t)}`,nn=new Set(["1","enabled","on","true","yes"]),an=new Set(["0","disabled","false","no","off"]),on=(e,t)=>{const r=(e??"").trim().toLowerCase();return nn.has(r)?!0:an.has(r)?!1:t},qt="v1",sn=6e4,cn=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??sn),n=`${qt}.${String(r)}`,o=await Nt(e,n);return{expiresAtMs:r,token:`${n}.${o}`}},un=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,s,l]=n;if(o!==qt||l.length===0)return!1;const u=Number(s);if(!Number.isFinite(u)||u<=r)return!1;let f;try{f=Xr(l)}catch{return!1}return en(e,`${o}.${s}`,f)},I="/_lunora/admin/auth",dn={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 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},Ct=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,$e=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},nt=e=>{const t=Ct(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new i("`role` is required",{code:"BAD_REQUEST",status:400});return t},at=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(s=>typeof s=="string")&&(r[n]=o);return r},ln={[`${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:$e(e,"data"),email:P(e,"email"),name:P(e,"name"),password:te(e,"password"),role:Ct(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 i("`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:nt(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:$e(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:$e(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:nt(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:at(e),role:P(e,"role")}),http:"POST",method:"createOrgRole"},[`${I}/organizations/roles/update`]:{build:({body:e})=>({permission:at(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"}},hn=e=>{const t=async o=>{try{return await o()}catch(s){if(s instanceof i)throw s;const l=s,u=typeof l.code=="string"?l.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",s),new i("auth admin operation failed",{code:u,status:dn[u]??500})}},r=async(o,s)=>{if(e.assertAdmin(o),o.method!==s.http)throw new i(`Auth admin endpoint requires ${s.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const l=e.getAuthAdmin();if(l===void 0)throw new i("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const u=l[s.method];if(u===void 0)throw new i(`auth admin does not support \`${s.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(o.url),y={body:s.http==="POST"?await e.readJsonBody(o):{},paging:e.parsePaging(o),query:_=>e.queryParameter(f,_)},E=s.build(y),w=await t(()=>u(E));return Response.json(s.returns==="void"?{ok:!0}:w,{headers:{"content-type":"application/json"},status:200})},n={};for(const[o,s]of Object.entries(ln))n[o]=l=>r(l,s);return n},pn="__lunora_admin__:getAuthAuditLog",ot=e=>typeof e=="string"&&e!==""?e:void 0,st=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,fn=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=ot(r.actorId),s=ot(r.event),l=st(r.sinceSeq),u=st(r.limit),f={...o===void 0?{}:{actorId:o},...s===void 0?{}:{event:s},...l===void 0?{}:{sinceSeq:l},...u===void 0?{}:{limit:u}};let y;try{y=await n.read(f)}catch(w){throw w instanceof i?w:(console.error("[lunora] auth audit read failed:",w),new i("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const E={entries:y};return Response.json(E,{headers:{"content-type":"application/json"},status:200})},mn=(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}},wn=async(e,t,r,n,o,s)=>{if(r!==void 0&&n.length===0)return;const l=await e.orchestrateExport(s,{args:{tables:n},headers:t,tables:n});for(const u of l.shards)if(!u.error)for(const f of u.rows??[])o(f)},$t=async(e,t,r,n,o,s)=>{const{globalTables:l,shardLocalTables:u}=mn(e,n);await wn(t,r,n,u,o,s);const f=e.exportGlobals;if((n===void 0||l.length>0)&&f)for await(const y of f({tables:l}))o(y)},gn=new TextEncoder,yn=1e3,Bt=10,bn=200,it=8,xt="lunoraBackupCron",ct=24*1048576,ut=e=>{const t=e.slice(0,Bt).map(n=>Dt(n)),r=e.length-t.length;return`${t.join(", ")}${r>0?` (+${String(r)} more)`:""}`},_n=(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},ze=async(e,t,r,n)=>{if(r===void 0||!Number.isInteger(r)||r<=0)return{eligible:0,stale:[]};const o=[];let s;for(let l=0;l<yn;l+=1){const u=await e.list({cursor:s,include:["customMetadata"],prefix:t});for(const f of u.objects)Pr(f.key)&&f.customMetadata?.[xt]===n&&o.push(f.key);if(!u.truncated||u.cursor===void 0)break;s=u.cursor}return{eligible:o.length,stale:o.toSorted((l,u)=>u.localeCompare(l)).slice(r)}},Rn=async(e,t,r,n,o)=>{const{stale:s}=await ze(e,t,r,n),l=new Set(o),u=s.filter(h=>l.has(h)),f=u.slice(0,bn),y=s.length-f.length,E=o.length-u.length;if(f.length===0)return{deleted:[],failed:[],ignored:E,remaining:y};const w=[],_=[];for(let h=0;h<f.length;h+=it){const S=await Promise.allSettled(f.slice(h,h+it).map(async R=>(await e.delete(Dt(R)),await e.delete(R),R)));for(const[R,T]of S.entries())T.status==="fulfilled"?w.push(T.value):_.push(f[h+R])}return w.length>0&&console.info(`[lunora] backup prune kept the newest ${String(r)} and deleted ${String(w.length)}: ${ut(w)}`),_.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(_.length)}: ${ut(_)}`),{deleted:w,failed:_,ignored:E,remaining:y}},En=async e=>{const t=e.backupStore;if(!t)throw new i("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=Fe(e.backupPrefix??Ge),n=e.backupCron,{eligible:o,stale:s}=n===void 0?{eligible:0,stale:[]}:await ze(t,r,e.backupRetain,n);return{cron:n,eligible:o,keep:e.backupRetain??0,prefix:r,wouldDelete:s}},Sn=async(e,t,r,n)=>{const o=e.backupStore,s=e.queryCoordinator;if(!o)throw new i("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!s)throw new i("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!r||r.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 l={authorization:`Bearer ${r}`,"content-type":"application/json"},u=e.backupTables;let f=0,y=0,E=[];await $t(e,s,l,u,A=>{const U=gn.encode(`${JSON.stringify(A)}
|
|
2
|
+
`);if(f+=1,y+=U.byteLength,y>ct)throw new i(`scheduled backup reached ${String(y)} 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 w=Fe(e.backupPrefix??Ge),_=new Date(n.scheduledTime).toISOString(),h=Ur(w,_),S=_n(E,y);E=[];const R=qr(await crypto.subtle.digest("SHA-256",S));await o.put(h,S,{httpMetadata:{contentType:"application/x-ndjson"},sha256:R});const T={bytes:y,createdAt:_,cron:n.cron,file:h,id:_,rows:f,scheduledTime:n.scheduledTime,sha256:R,...u?{tables:u.join(",")}:{}};await o.put(Nr(h),`${JSON.stringify(T,void 0,2)}
|
|
3
|
+
`,{customMetadata:{[xt]:n.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:A}=await ze(o,w,e.backupRetain,n.cron);if(A.length>0){const U=A.slice(0,Bt),v=A.length-U.length;console.info(`[lunora] backup retention: ${String(A.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${U.join(", ")}${v>0?` (+${String(v)} more)`:""}`)}}catch(A){console.warn(`[lunora] backup ${h} was written, but the retention report failed:`,A)}},On=async(e,t)=>{const r=e.backupStore;if(!r)throw new i("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=e.backupCron,o=e.backupRetain;if(n===void 0||o===void 0||!Number.isInteger(o)||o<=0)throw new i("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return Rn(r,Fe(e.backupPrefix??Ge),o,n,t)},Tn="/_lunora/admin/backup/retention",An="/_lunora/admin/backup/prune",kn=e=>{const{options:t,readJsonBody:r,requireAdminOption:n}=e,o=(u,f)=>{n(u,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},s=async u=>(x(u,"GET","Backup-retention"),o(u,"retention preview"),Response.json(await En(t),{headers:{"cache-control":"no-store"}})),l=async u=>{x(u,"POST","Backup-prune"),o(u,"prune");const{confirm:f}=await r(u);if(!Array.isArray(f)||f.some(y=>typeof y!="string"))throw new i("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await On(t,f),{headers:{"cache-control":"no-store"}})};return{[An]:l,[Tn]:s}},dt=500,vn=(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}},In=(e,t)=>{if(e.length>dt)throw new i(`RPC batch exceeds the ${String(dt)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,o]of e.entries()){const{entry:s,shardKey:l}=vn(o,n,t),u=r.get(l)??[];u.push(s),r.set(l,u)}return r},Dn=new TextEncoder,Pn=e=>{const t=JSON.stringify(e),r=Dn.encode(t);let n="";for(const o of r)n+=String.fromCodePoint(o);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Un=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 u=0;u<r.length;u+=1)n[u]=r.codePointAt(u)??0;const o=JSON.parse(new TextDecoder().decode(n)),s=o.s&&typeof o.s=="object"?o.s:{},l={};for(const[u,f]of Object.entries(s))typeof f=="number"&&Number.isFinite(f)&&(l[u]=f);return{g:typeof o.g=="number"&&Number.isFinite(o.g)?o.g:0,s:l,v:1}}catch{return t}},Nn=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}},lt=(e,t,r)=>{for(const n of t)e.push(Nn(n));return r!==void 0&&t.length>=r},qn="/_lunora/admin/export",Cn="/_lunora/admin/import",$n="/_lunora/admin/sync",Bn="/_lunora/admin/connector/sync",xn="/_lunora/admin/apply",jn="/_lunora/admin/export-tap/run",Kn=new TextEncoder,Ln=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}},Be=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,Fn=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:o,queryCoordinator:s,assertAdmin:l,requireAdminOption:u,resolveForwardContext:f,shardDO:y,streamExportRows:E,streamingImport:w,syncGlobals:_}=e,h=async(v,L)=>{const j=we(v,["POST"]);if(j)return j;const V=u(v,s,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),N=await Ln(v),{headers:G}=await f(v,L),Q=new ReadableStream({async pull($){const K=Y=>{$.enqueue(Kn.encode(`${JSON.stringify(Y)}
|
|
4
|
+
`))};try{await E(V,G,N.tables,K),$.close()}catch(Y){$.error(Y)}}});return new Response(Q,{headers:{"content-type":"application/x-ndjson"},status:200})},S=async(v,L)=>{const j=we(v,["POST"]);if(j)return j;const V=u(v,s,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),N=await X(v),G=typeof N.cursors=="object"&&N.cursors!==null?N.cursors:{},Q=typeof N.limit=="number"?N.limit:void 0,$=typeof N.globalCursor=="number"?N.globalCursor:0,K=Be(N.tables),{headers:Y}=await f(v,L),J=K??o(),ne=await V.orchestrateCdcSync(y,{cursors:G,headers:Y,limit:Q,tables:J}),he=_?await _({limit:Q,sinceSeq:$}):void 0;return Response.json({global:he,shards:ne.shards},{status:200})},R=async(v,L)=>{const j=we(v,["POST"]);if(j)return j;const V=u(v,s,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),N=await X(v),G=Un(N.cursor),Q=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,$=Be(N.tables),{headers:K}=await f(v,L),Y=$??o(),J=await V.orchestrateCdcSync(y,{cursors:G.s,headers:K,limit:Q,tables:Y}),ne=[],he={...G.s};let ae=!1;for(const se of J.shards)ae=lt(ne,se.changes??[],Q)||ae,he[se.shardKey]=se.cursor;let pe=G.g;if(_){const se=await _({limit:Q,sinceSeq:G.g});ae=lt(ne,se.changes,Q)||ae,pe=se.cursor}const _e=Pn({g:pe,s:he,v:1}),ke={changes:ne,hasMore:ae,nextCursor:_e};return Response.json(ke,{status:200})},T=async(v,L)=>{const j=we(v,["POST"]);if(j)return j;const V=u(v,s,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),N=await X(v),G=(Array.isArray(N.batches)?N.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),Q=Array.isArray(N.globalChanges)?N.globalChanges:[],{headers:$}=await f(v,L),K=await V.orchestrateApplyCdc(y,{batches:G,headers:$}),Y=Q.length>0&&t?await t({changes:Q}):0;return Response.json({applied:K.applied+Y,failed:K.failed,ok:K.ok},{status:200})},A=async(v,L)=>{const j=we(v,["POST"]);if(j)return j;l(v);const{headers:V}=await f(v,L),N=await w(v,V);return Response.json(N,{headers:{"content-type":"application/json"},status:200})},U=async(v,L)=>{const j=we(v,["POST"]);if(j)return j;const V=u(v,s,{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 N=await X(v),G=typeof N.sink=="string"?N.sink:void 0,Q=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,$=Be(N.tables);if(G===void 0)throw new i("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const K=n[G];if(K===void 0)throw new i(`Export-tap sink "${G}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:Y}=await f(v,L),J=$??o(),ne=await xr({coordinator:V,cursorStore:r,headers:Y,limit:Q,shardDO:y,sink:K,tables:J});return Response.json(ne,{headers:{"content-type":"application/json"},status:200})};return{[xn]:T,[Bn]:R,[qn]:h,[jn]:U,[Cn]:A,[$n]:S}},Gn=(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}},Qn=(e,t,r,n,o)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const s=e[r.mode.field];return s==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 s=="string"?s:JSON.stringify(s)}}return{ok:!0,shardKey:n}},Mn=async(e,t,r)=>{if(!e.body)throw new i("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],o=[],s=new Map;let l=0,u=0;const f=e.body.getReader(),y=new TextDecoder;let E="",w=0;const _=h=>{u+=1;const S=h.trim();if(S.length===0)return;l+=1;const R=Gn(S,u);if(!R.ok){n.push(R.error);return}const{doc:T,table:A}=R,U=t.resolveTableSharding?.(A);if(U?.mode.kind==="global"){o.push({doc:T,line:u,table:A});return}const v=Qn(T,A,U,r,u);if(!v.ok){n.push(v.error);return}const L=s.get(v.shardKey);L?L.rows.push({doc:T,table:A}):s.set(v.shardKey,{rows:[{doc:T,table:A}],shardKey:v.shardKey,startLine:u})};for(;;){const{done:h,value:S}=await f.read();if(h)break;if(S&&(w+=S.byteLength,w>kt))throw await f.cancel().catch(()=>{}),new i("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=y.decode(S,{stream:!0});let R=E.indexOf(`
|
|
5
|
+
`);for(;R!==-1;){const T=E.slice(0,R);E=E.slice(R+1),_(T),R=E.indexOf(`
|
|
6
|
+
`)}}return E.length>0&&_(E),{errors:n,globalRows:o,perShard:s,received:l}},ht=(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},zn=async(e,t,r,n)=>{const o=t.defaultShardKey??"__root__",{errors:s,globalRows:l,perShard:u,received:f}=await Mn(e,t,o),y={conflicts:0,errors:s,inserted:{}},E=[];if(t.resolveTableSharding===void 0&&u.size>0&&E.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),u.size>0){const w=t.queryCoordinator;if(!w)throw new i("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const _=await w.orchestrateImport(n,{batches:[...u.values()],headers:r});ht(y,_)}if(l.length>0)if(t.importGlobals){const w=l[0]?.line??1,_=await t.importGlobals({rows:l,startLine:w});ht(y,_)}else for(const w of l)y.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:w.line,message:`row targets global table "${w.table}" but no \`importGlobals\` is configured`,table:w.table});return{conflicts:y.conflicts,errors:y.errors,inserted:y.inserted,received:f,...E.length>0?{warnings:E}:{}}},xe=e=>typeof e=="object"&&e!==null?e:{},je=e=>typeof e.kind=="string"?e.kind:"unknown",Wn=(e,t)=>{let r=xe(t),n=!1;je(r)==="optional"&&(n=!0,r=xe(r._meta?.inner));const o=je(r),s=r._meta??{},l={kind:o,name:e,optional:n};if(o==="id"&&typeof s.tableName=="string"&&(l.table=s.tableName),o==="array"){const u=je(xe(s.inner));u!=="unknown"&&(l.element=u)}return l},Jn=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>Wn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),Hn="/_lunora/admin/functions",Vn="/_lunora/admin/cron-jobs",Yn="/_lunora/admin/openapi",Xn="/_lunora/admin/openrpc",Zn="/_lunora/admin/global/tables",ea="/_lunora/admin/global/table",ta="/_lunora/admin/global/facet",pt=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:s}=n;return[{column:o,value:s}]});return r.length===0?void 0:r},ra=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:{}}),na=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"}),aa=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:o,requireAdminOption:s}=e,l=h=>{x(h,"GET","Functions");const S=s(h,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),R=Object.entries(S).flatMap(([T,A])=>A.visibility==="internal"||A.kind==="stream"?[]:[{args:Jn(A.args),kind:A.kind,path:T}]).toSorted((T,A)=>T.path.localeCompare(A.path));return Response.json({functions:R},{headers:{"content-type":"application/json"},status:200})},u=h=>{x(h,"GET","Cron-jobs");const S=s(h,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),R=Object.entries(S).flatMap(([T,A])=>A.map(U=>({args:U.args,cron:T,functionPath:U.functionPath,name:U.name,shardKey:U.shardKey,workflow:U.workflow}))).toSorted((T,A)=>T.name.localeCompare(A.name));return Response.json({jobs:R},{headers:{"content-type":"application/json"},status:200})},f=h=>(x(h,"GET","OpenAPI"),t(h),Response.json(r.openApiSpec??ra,{headers:{"content-type":"application/json"},status:200})),y=h=>(x(h,"GET","OpenRPC"),t(h),Response.json(r.openRpcSpec??na,{headers:{"content-type":"application/json"},status:200})),E=async h=>{x(h,"GET","Global-tables");const S=s(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})},w=async h=>{x(h,"GET","Global-table");const S=s(h,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(h.url),T=o(R,"table");if(T===void 0)throw new i("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const A=await S.readTablePage({...n(h),filters:pt(o(R,"filters")),table:T});return Response.json(A,{headers:{"content-type":"application/json"},status:200})},_=async h=>{x(h,"GET","Global-facet");const S=s(h,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(h.url),T=o(R,"table"),A=o(R,"column");if(T===void 0||A===void 0)throw new i("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const U=o(R,"limit"),v=U===void 0?void 0:Number(U),L=await S.facetColumn({column:A,filters:pt(o(R,"filters")),limit:v!==void 0&&Number.isFinite(v)?v:void 0,table:T});return Response.json(L,{headers:{"content-type":"application/json"},status:200})};return{[Vn]:u,[Hn]:l,[ta]:_,[ea]:w,[Zn]:E,[Yn]:f,[Xn]:y}},oa="/_lunora/admin/kv/namespaces",sa="/_lunora/admin/kv/keys",jt="/_lunora/admin/kv/value",Kt=32*1048576,ft=60,ia=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=w=>r(w,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),o=w=>Response.json(w,{headers:{"content-type":"application/json"},status:200}),s=(w,_)=>{const h=new URL(w.url),S=h.searchParams.get("namespace")??"",R=h.searchParams.get("key")??"";if(S==="")throw new i(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(R==="")throw new i(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:R,namespace:S}},l=async(w,_)=>{if(!(await w.listNamespaces()).some(h=>h.binding===_))throw new i(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},u=async w=>(x(w,"GET","KV-namespaces"),o({namespaces:await n(w).listNamespaces()})),f=async w=>{x(w,"GET","KV-keys");const _=n(w),h=new URL(w.url),S=h.searchParams.get("namespace")??"";if(S==="")throw new i("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const R=h.searchParams.get("prefix")??void 0,T=h.searchParams.get("cursor")??void 0,A=h.searchParams.get("limit"),U=A===null?void 0:Number.parseInt(A,10);if(U!==void 0&&(!Number.isInteger(U)||U<1))throw new i("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const v=U===void 0?void 0:Math.min(U,1e3);return await l(_,S),o(await _.listKeys({cursor:T,limit:v,namespace:S,prefix:R}))},y={DELETE:async w=>{const _=n(w),h=s(w,"DELETE");return await l(_,h.namespace),await _.deleteKey(h),o({deleted:!0})},GET:async w=>{const _=n(w),h=s(w,"GET");return await l(_,h.namespace),o(await _.getValue(h))},PUT:async w=>{const _=n(w),h=await t(w,Kt);if(typeof h.namespace!="string"||h.namespace==="")throw new i("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof h.key!="string"||h.key==="")throw new i("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof h.value!="string")throw new i("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<ft))throw new i("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const S=Math.floor(Date.now()/1e3)+ft;if(h.expiration!==void 0&&(typeof h.expiration!="number"||!Number.isInteger(h.expiration)||h.expiration<S))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 l(_,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=w=>{const _=y[w.method];if(!_)throw new i("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(w)};return{[oa]:u,[sa]:f,[jt]:E}},ca="/_lunora/migrate",ua="/_lunora/admin/pitr",da="/_lunora/admin/rank",la="/_lunora/admin/rankpage",ha="/_lunora/admin/shard-traffic",pa=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),fa=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),ma=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"||!pa.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}},wa=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}},ga=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}},ya=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})},ba=async e=>{const t=await be(e,"Rank page")??{};ya(t);const r=ga(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}},_a=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}},Ra=async e=>{const t=await X(e);if(typeof t.functionPath!="string"||!fa.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}},Ea=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:o,resolveForwardContext:s,shardDO:l}=e,u=(h,S)=>{if(h.method!=="POST")throw new i(`${S} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!n(h))throw new i("Admin auth required",{code:"FORBIDDEN",status:403});if(!o)throw new i(`${S} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return o},f=async(h,S)=>{const R=u(h,"Migration"),T=await ma(h),{headers:A}=await s(h,S),U=await R.orchestrateMigration(l,{args:T.args,functionPath:T.functionPath,headers:A,table:T.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},y=async(h,S)=>{const R=u(h,"Rank"),T=await wa(h),{headers:A}=await s(h,S),U=await R.orchestrateRank(l,{headers:A,index:T.index,partitionKey:T.partitionKey,rowId:T.rowId,sortValues:T.sortValues,table:T.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},E=async(h,S)=>{const R=u(h,"Rank page"),T=await ba(h),{headers:A}=await s(h,S),U=await R.orchestrateRankPage(l,{...T,headers:A});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},w=async(h,S)=>{const R=u(h,"Shard-traffic"),T=await _a(h),{headers:A}=await s(h,S),U=await R.orchestrateShardTraffic(l,{headers:A,table:T.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},_=async(h,S)=>{if(x(h,"POST","PITR"),!n(h))throw new i("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const R=await Ra(h),{headers:T}=await s(h,S),A=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:R.args,functionPath:R.functionPath}),headers:T,method:"POST"});return r(l,R.shardKey??t,A)};return{[ca]:f,[ua]:_,[da]:y,[la]:E,[ha]:w}},Sa=1,Oa=0,Ta=32,Aa=512,ka=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,va=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Aa)return;const r=t.split(",");if(!(r.length>Ta)){for(const n of r)if(!ka.test(n.trim()))return;return t}},Ia=e=>{const t=Or(e.headers.get("traceparent"));if(t===void 0)return;const r=va(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},Da=(e,t={})=>{const r=Ia(e),n=t.trustInbound===!0?r:void 0,o=Ae(8),s=n?.traceId??Ae(16),l=Qr(t.sampling,n===void 0?o:s),u=l.isTraced&&(n===void 0||n.sampled);return{decision:l,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:u,spanId:o,traceFlags:u?Sa:Oa,traceId:s,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},Pa=(e,t)=>{t.traceparent=Sr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Ua=(e,t)=>{let r;return()=>{if(r===void 0){const n=vr(e),o=t===void 0?void 0:t.cf;r=Tr(kr(n),Ar(n,o))}return r}},Na="/_lunora/admin/scheduled",qa="/_lunora/admin/scheduled/status",Ca="/_lunora/admin/scheduled/ws",$a="/_lunora/admin/scheduled/cancel",Ba="/_lunora/admin/scheduled/dead",xa="/_lunora/admin/scheduled/dead/retry",ja="/_lunora/admin/scheduled/dead/cancel",Ka=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:o}=e,s=(f,y)=>E=>{if(E.method!=="GET")throw new i(`${y} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return n(E).fetch(new Request(`https://scheduler.internal${f}`,{method:"GET"}))},l=(f,y,E=y)=>async w=>{if(w.method!=="POST")throw new i(`${E} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const _=n(w),h=await w.json().catch(()=>{});if(typeof h?.id!="string"||h.id==="")throw new i(`${y} 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"}))},u=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new i("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(f))throw new i("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const y=r();return ge(y,o).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[$a]:l("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[ja]:l("/dead/cancel","Scheduled dead-letter action"),[Ba]:s("/dead","Scheduled dead-letter"),[xa]:l("/dead/retry","Scheduled dead-letter action"),[Na]:s("/list","Scheduled-list"),[qa]:s("/status","Scheduler-status"),[Ca]:u}},La=(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},mt={mtls:e=>La(e,"tlsClientAuth","certVerified")==="SUCCESS"},Fa=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(mt,e)?mt[e]:void 0)??(()=>!1),Ga=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.'))}},Qa="/_lunora/admin/vector/indexes",Ma="/_lunora/admin/vector/query",za=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async s=>{x(s,"GET","Vector-indexes");const l=r(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await l.listIndexes()},{headers:{"content-type":"application/json"},status:200})},o=async s=>{x(s,"POST","Vector-query");const l=r(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(l.queryIndex===void 0)throw new i("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const u=await t(s);if(typeof u.name!="string"||u.name==="")throw new i("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof u.text!="string"||u.text==="")throw new i("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(u.topK!==void 0&&(typeof u.topK!="number"||!Number.isInteger(u.topK)||u.topK<1))throw new i("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const f=await l.queryIndex({name:u.name,text:u.text,topK:u.topK});return Response.json(f,{headers:{"content-type":"application/json"},status:200})};return{[Qa]:n,[Ma]:o}},Wa="/_lunora/admin/workflows/instances",Ja="/_lunora/admin/workflows/instance",Ha="/_lunora/admin/workflows/status",Va={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Ya=e=>e!==null&&Object.hasOwn(Va,e)?e:void 0,wt=(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 i(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},gt=()=>{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})},Xa=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(l,u,f)=>{x(l,"GET","Workflows instances"),t(l);const y=r(u);if(!y)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const E=Ke(f,"name"),w=Ya(f.searchParams.get("status"));return Response.json(await y.listInstances({page:wt(f,"page"),perPage:wt(f,"perPage"),status:w,workflowName:E}))},o=async(l,u,f)=>{x(l,"GET","Workflows instance"),t(l);const y=r(u);return y?Response.json(await y.getInstance({instanceId:Ke(f,"id"),workflowName:Ke(f,"name")})):gt()},s=async(l,u)=>{x(l,"POST","Workflows status"),t(l);const f=r(u);if(!f)return gt();const y=await l.json().catch(()=>{});if(typeof y?.name!="string"||y.name===""||typeof y.id!="string"||y.id==="")throw new i("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:E}=y;if(E!=="pause"&&E!=="resume"&&E!=="terminate")throw new i("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:E,instanceId:y.id,workflowName:y.name}))};return{[Ja]:o,[Wa]:n,[Ha]:s}},Za={[jt]:Kt,[$r]:Cr},yt="/_lunora/rpc",eo="/_lunora/rpc-batch",to="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:Ua(e,t),...r===void 0?{}:{waitUntil:r}}),bt=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},_t=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}},Rt="/_lunora/voice/",ro="/_lunora/scheduler/dispatch",no="/_lunora/admin/cron-jobs/run",ao="/_lunora/admin/ws-token",oo="/_lunora/admin/",so="/_lunora/migrate",io="/_lunora/status",co=e=>e.startsWith(oo)||e===so,uo=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}}},lo="/api/auth",ho="__lunora_admin__:recordAuthEvent",po="__lunora_admin__:listPushSubscriptions",fo=["/sign-in","/sign-up","/callback"],mo=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return fo.some(o=>n===o||n.startsWith(`${o}/`))},Se=(e,t,r,n)=>{const o=yr(r),s=o?r.code:"INTERNAL_SERVER_ERROR",l=o?r.status:500,u=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:s,message:u,status:l},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},wo=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},Et=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,go=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ue=async(e,t,r)=>{const n={"content-type":"application/json"},o=e.headers.get("authorization"),s=e.headers.get("cookie"),l=e.headers.get("x-d1-bookmark"),u=e.headers.get("x-lunora-mutation-id"),f=e.headers.get("x-lunora-client-id"),y=e.headers.get("x-lunora-client-seq");o&&(n.authorization=o),s&&(n.cookie=s),l&&(n["x-d1-bookmark"]=l),u&&(n["x-lunora-mutation-id"]=u),f&&(n["x-lunora-client-id"]=f),y&&(n["x-lunora-client-seq"]=y);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 w=await r(e,t);if(!w||typeof w.userId!="string"||w.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=Rr(w.userId);const _=wo(w);_!==void 0&&(n["x-lunora-identity-exp"]=String(_));const{userId:h,...S}=w,R=Object.keys(S).length>0?S:null;return R&&(n["x-lunora-identity"]=Er(R)),{claims:R,headers:n,identity:w,userId:h}},yo=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),bo=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"||!yo.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},_o=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},St=(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}},Ro=async e=>{const t=await vt(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&&It(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,s=bo(o.fanOut),l=o.args??{};if(s&&o.functionPath.startsWith("__lunora_relation__:")){const u=l.table;if(typeof u=="string"&&u!==s.table)throw new i("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});l.table=s.table}return{args:l,fanOut:s,functionPath:o.functionPath,shardKey:o.shardKey}},oe=async(e,t,r)=>ge(e,t).fetch(r),Oe=new Map,Eo=5e3,So=4096,Oo=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 s=await ge(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(s.ok){const l=(await s.json()).relayCount;typeof l=="number"&&l>0&&(o=Math.floor(l))}}catch{o=0}return At(Oe,So),Oe.set(t,{expiresMs:r+Eo,relayCount:o}),o},To=(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"}),Ao=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],Ot=(e,t)=>{for(const r of Ao){e.delete(r);const n=t[r];n!==void 0&&e.set(r,n)}},ko=async(e,t,r)=>e.length===0||r.length===0?!1:Qe(await Nt(e,t),r),Tt=(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:Qe(t,o.join(" ").trim())},vo=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 un(t,n)?!0:r?!1:Qe(t,n)},Io=(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 Lr(`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)},Lt=e=>{const t=Fa(e.trustInboundTraceContext),r=Ga(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",o=Fr(e.resolveIdentity,e.identity),s=et(e.shardDO,e.jurisdiction),l=e.schedulerDO===void 0?void 0:et(e.schedulerDO,e.jurisdiction);let u;const f=()=>e.adminToken??u;let y;const E=()=>e.requireEphemeralWsToken??y??!0,w=a=>{const c=a??{};if(y===void 0&&e.requireEphemeralWsToken===void 0){const d=c.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof d=="string"&&d.length>0&&(y=on(d,!0))}if(u!==void 0||e.adminToken!==void 0)return;const p=c.LUNORA_ADMIN_TOKEN;typeof p=="string"&&p.length>0&&(u=p)},_=new WeakSet,h=a=>Tt(a,f())||_.has(a),S=async(a,c)=>{const p=await ue(a,c,e.resolveIdentity);if(_.has(a)&&p.headers.authorization===void 0){const d=f();d!==void 0&&(p.headers.authorization=`Bearer ${d}`)}return p};let R=!1;const T=a=>{if(!e.allowUnauthenticatedShardAccess){const c=a==="fan-out"?"authorizeFanOut":"authorizeShard";throw new i(`${a} access is default-denied: configure \`${c}\` 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})}R||(R=!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("")))},A=async(a,c,p=!0)=>{if(e.authorizeShard){if(!await e.authorizeShard(a,c))throw new i("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else p&&c!==n&&T("shard")},U=Ea({defaultShard:n,forwardToShard:oe,isAdmin:h,queryCoordinator:e.queryCoordinator,resolveForwardContext:S,shardDO:s}),v=async(a,c,p,d,m)=>{await A(null,p,!1);const b={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(b["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(b["x-lunora-identity"]=m.identity),d!==void 0&&d.length>0&&(b["x-lunora-mutation-id"]=d),oe(s,p,Te(a,c,b))},L=async(a,c,p,d)=>{const m=p?.[a];if(!m||typeof m.create!="function")throw new i(`${d} targets workflow binding "${a}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(Jr(c))throw new i(`${d} params ${Hr}`,{code:"BAD_REQUEST",status:400});await m.create({params:c})},j=async(a,c)=>{if(a.workflow){await L(a.workflow,a.args??{},c,`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 p=await v(a.functionPath,a.args??{},a.shardKey??n);if(!p.ok)throw new i(`cron job "${a.name}" (${a.functionPath}) failed with shard status ${String(p.status)}`,{code:"CRON_JOB_FAILED",status:500})},V=async(a,c,p,d)=>{const m=e.cronJobs?.[a];if(m)for(const b of m)try{await j(b,c)}catch(D){p.push(d(D))}},N=async(a,c)=>{if(!h(a))throw new i("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(x(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 p=await X(a),d=typeof p.name=="string"?p.name:"";if(d==="")throw new i("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(b=>b.name===d);if(!m)throw new i(`no cron job named "${d}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await j(m,c),Response.json({name:d,ran:!0},{status:200})},G=async a=>{const c=typeof a.pool=="string"&&a.pool.length>0?a.pool:void 0;if(!c||!l||typeof a.id!="string")return;const p=typeof a.instanceName=="string"&&a.instanceName.length>0?a.instanceName:"default";try{await ge(l,p).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:a.id,pool:c}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Q=async(a,c)=>{x(a,"POST","Scheduler dispatch");const p=await vt(a),d=c??{},m=typeof d.LUNORA_SCHEDULER_SECRET=="string"?d.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof d.LUNORA_ADMIN_TOKEN=="string"?d.LUNORA_ADMIN_TOKEN:void 0),D=a.headers.get("x-lunora-scheduler-signature");let g=!1;if(D&&m?g=await ko(m,p,D):b&&(g=Tt(a,b)),!g)throw new i("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let O;try{O=JSON.parse(p)}catch{throw new i("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const k=O??{},q=k.args??{};if(typeof k.workflow=="string"&&k.workflow.length>0)return await L(k.workflow,q,c,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof k.functionPath!="string"||k.functionPath.length===0)throw new i("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const C=typeof k.shardKey=="string"&&k.shardKey.length>0?k.shardKey:n,B=typeof k.id=="string"&&k.id.length>0?k.id:void 0,Z=uo(a),ee=await v(k.functionPath,q,C,B,Z);return await G(k),ee},$=a=>{if(!h(a))throw new i("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},K=(a,c,p)=>{if($(a),c===void 0)throw new i(p.message,{code:p.code,status:400});return c},Y=fn({assertAdmin:$,getReader:()=>e.authAuditReader}),J=async(a,c)=>{$(a);const p=e.notifySubscriptionStore;if(p===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const d=c?.kind,m=c?.userId,b=c?.limit,D=d==="fcm"||d==="web-push"?d:void 0,g=typeof m=="string"&&m!==""?m:void 0,O=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,k=O>0?Math.min(O,1e3):1e3,q=(await p.list({kind:D,limit:k,userId:g})).filter(C=>D!==void 0&&C.kind!==D?!1:g===void 0||(C.userId??null)===g).map(({keys:C,token:B,...Z})=>Z);return Response.json({subscriptions:q},{headers:{"content-type":"application/json"},status:200})},ne=async(a,c)=>{if(!c.fanOut){if(c.functionPath===pn)return Y(a,c.args??{});if(c.functionPath===po)return J(a,c.args)}},he=Fn({applyGlobals:e.applyGlobals,assertAdmin:$,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:K,resolveForwardContext:S,shardDO:s,streamExportRows:(a,c,p,d)=>$t(e,a,c,p,d,s),streamingImport:(a,c)=>zn(a,e,c,s),syncGlobals:e.syncGlobals}),ae=(a,c)=>{const p=a.searchParams.get(c);return p===null||p===""?void 0:p},pe=a=>{const c=new URL(a.url),p=c.searchParams.get("limit"),d=c.searchParams.get("offset"),m=p===null?void 0:Number.parseInt(p,10),b=d===null?void 0:Number.parseInt(d,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},_e=()=>{if(l===void 0)throw new i("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return l},ke=Ka({checkWsAdmin:async a=>h(a)||vo(a,f(),E()),requireSchedulerNamespace:_e,resolveSchedulerStub:a=>($(a),ge(_e(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),se=Xa({assertAdmin:$,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Ft=Br({assertAdmin:$,parsePaging:pe,queryParameter:ae,readBodyBytes:Dr,requireAdminOption:K,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Gt=kn({options:e,readJsonBody:X,requireAdminOption:K}),Qt=za({readJsonBody:X,requireAdminOption:K,vectorIntrospector:e.vectorIntrospector}),Mt=ia({kvIntrospector:e.kvIntrospector,readJsonBody:X,requireAdminOption:K}),zt=Gr({logArchive:e.logArchive,readJsonBody:X,requireAdminOption:K}),Wt=aa({assertAdmin:$,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:ae,requireAdminOption:K}),Jt=a=>{const c=[],p=s??a?.SHARD;if(p!==void 0&&c.push(Kr("durable-object:default",p,n)),e.health?.disableBindingProbes!==!0)for(const[d,m]of Object.entries(a??{})){const b=Io(d,m);b!==void 0&&c.push(b)}for(const d of e.health?.probes??[])c.push(d);return c},Ht=jr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:h,resolveProbes:Jt}),Vt=a=>{const c=e.schedulerInstanceName??"default",p=()=>ge(a,c),d=async(g,O)=>{const k=await p().fetch(new Request(`https://scheduler.internal${g}`,O));if(!k.ok)throw new i(`ctx.scheduler: SchedulerDO ${g} failed (${String(k.status)}): ${await k.text()}`,{code:"INTERNAL",status:500});return await k.json()},m=async(g,O)=>await d(g,{body:JSON.stringify(O),headers:{"content-type":"application/json"},method:"POST"}),b=g=>{const O=g;if(O==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 O.binding=="string"&&O.binding.length>0)return{workflow:O.binding};if(typeof O.__lunoraRef=="string")return{functionPath:O.__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})},D=async(g,O,k={})=>{const{id:q}=await m("/schedule",{args:k,scheduledFor:g,...b(O)});return q};return{cancel:async g=>await m("/cancel",{id:g}),get:async g=>await d(`/get?id=${encodeURIComponent(g)}`,{method:"GET"}),list:async()=>await d("/list",{method:"GET"}),runAfter:async(g,O,k)=>{if(!Number.isFinite(g)||g<0)throw new i("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await D(Date.now()+g,O,k)},runAt:async(g,O,k)=>{if(!Number.isFinite(g))throw new i("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await D(g,O,k)}}},Yt=async(a,c,p)=>{const{claims:d,headers:m,userId:b}=await ue(a,c,o),D=async(g,O={})=>{const k=g.__lunoraRef;if(typeof k!="string")throw new i("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const q=Te(k,O,{...m,"x-lunora-system":"1"}),C=await oe(s,n,q),B=await C.json();if(B.error)throw new i(B.error.message??"shard RPC failed",{code:B.error.code??"INTERNAL",status:C.status});return B.result};return{auth:{getIdentity:()=>Promise.resolve(d),userId:b},cache:p.cache,fetch:globalThis.fetch.bind(globalThis),runAction:D,runMutation:D,runQuery:D,...l===void 0?{}:{scheduler:Vt(l)},...e.storage===void 0?{}:{storage:Wr(e.storage(c))}}},Xt=async(a,c,p)=>{if(!e.httpRouter)return;const d=await Yt(a,c,p);try{return await e.httpRouter.fetch(a,{...c,__lunoraCtx:d},p)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},Zt=async(a,c,p)=>{if(a.headers.get("Upgrade")!=="websocket")throw new i("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const d=rt(a,ie);if(d)return d;const m=p.searchParams.get("shard")??n,{headers:b,identity:D}=await ue(a,c,o);await A(D,m);const g=new Headers(a.headers),O=[...g.keys()];for(const q of O)q.startsWith("x-lunora-")&&g.delete(q);Ot(g,b);const k=To(c,e.shardDO);if(k!==void 0){g.set("x-lunora-shard-binding",k);const q=await Oo(s,m);if(q>0){const C=rn(m,Math.floor(Math.random()*q));return oe(s,C,new Request(a,{headers:g}))}}return oe(s,m,new Request(a,{headers:g}))},er=async(a,c,p)=>{const{voiceAgents:d}=e;if(d===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=rt(a,ie);if(m)return m;let b;try{b=decodeURIComponent(p.pathname.slice(Rt.length))}catch{return new Response("Unknown voice agent",{status:404})}const D=Object.hasOwn(d,b)?d[b]:void 0;if(D===void 0)return new Response("Unknown voice agent",{status:404});const g=p.searchParams.get("threadKey");if(g===null||g.length===0)return new Response("Missing threadKey",{status:400});const{headers:O,identity:k}=await ue(a,c,o);if(e.authorizeShard){if(!await e.authorizeShard(k,g))return new Response("Forbidden",{status:403})}else T("shard");const q=new Headers(a.headers);for(const C of q.keys())C.startsWith("x-lunora-")&&q.delete(C);return Ot(q,O),oe(D,g,new Request(a,{headers:q}))},tr=async(a,c,p)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(p,a.table,c))throw new i("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(c.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});T("fan-out")},Re=async(a,c)=>{if(!(!a.fanOut&&a.functionPath.startsWith("__lunora_admin__:"))){if(a.fanOut){await tr(a.fanOut,a.functionPath,c);return}await A(c,a.shardKey??n)}},ve=async(a,c,p,d,m,b)=>{const D=Date.now(),{observability:g,sampling:O}=e,k=Le(a),{decision:q,ignoredUpstream:C,trace:B}=Da(a,{...O===void 0?{}:{sampling:O},trustInbound:t(a)});C&&r();const Z={...m,"x-lunora-sample-errors":q.keepErrors?"1":"0"};Pa(B,Z);const ee=Te(c,p,Z);try{const F=await oe(s,d,ee);return ce(g,{...k,..._t(B),durationMs:Date.now()-D,functionPath:c,ok:F.ok,shardKey:d,...F.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(F.status)}`,status:F.status}}},b,void 0,{isTraced:B.sampled,keepErrors:q.keepErrors}),F}catch(F){throw ce(g,{...k,..._t(B),...Se(c,Date.now()-D,F,{shardKey:d})},b,void 0,{isTraced:B.sampled,keepErrors:q.keepErrors}),F}},rr=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})},nr=async(a,c,p)=>{x(a,"POST","RPC");const d=await Ro(a);_o(c,d),rr(d);const m=await ne(a,d);if(m!==void 0)return m;const{headers:b,identity:D}=await ue(a,c,o);await Re(d,D);const g=St(d,e);{const O=Date.now(),{observability:k}=e,q=Le(a),C=Ee(c,a,p&&(ee=>p.waitUntil?.(ee)));if(d.fanOut){const ee=e.queryCoordinator;if(!ee)throw new i("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const F=await ee.fanOut(s,{args:d.args??{},fanOut:d.fanOut,functionPath:d.functionPath,headers:b});return ce(k,{durationMs:Date.now()-O,fanOut:{failed:F.failed,shards:F.ok+F.failed,table:d.fanOut.table},functionPath:d.functionPath,...q,ok:!0},C),Response.json(F,{headers:{"content-type":"application/json"},status:200})}catch(F){throw ce(k,{...Se(d.functionPath,Date.now()-O,F,{fanOut:{table:d.fanOut.table}}),...q},C),F}}const B=d.shardKey??n,Z=()=>ve(a,d.functionPath,d.args??{},B,b,C);return g&&e.x402Charge?e.x402Charge(a,{functionPath:d.functionPath,price:g.price},Z,bt(p)):Z()}},ar=async(a,c,p)=>{x(a,"POST","RPC batch");const d=await X(a),{calls:m}=d;if(!Array.isArray(m))throw new i("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:b,identity:D}=await ue(a,c,o),g=In(m,n);for(const M of g.values())for(const z of M)if(e.functions?.[z.functionPath]?.x402)throw new i(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${yt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...g.entries()].flatMap(([M,z])=>z.map(re=>Re({functionPath:re.functionPath,shardKey:M},D))));const{observability:O}=e,k=Ee(c,a,p&&(M=>p.waitUntil?.(M))),q=Le(a),C=[],B=[],Z=(M,z,re,de)=>({body:{error:{code:re,message:de}},id:M.id,status:z}),ee=(M,z,re,de,fe)=>{for(const W of M)ce(O,fe(W),k),C.push(Z(W,z,re,de))},F=(M,z,re,de,fe)=>{for(const W of M){const me=de.get(W.id)??fe,ye=me<400;ce(O,{durationMs:re,functionPath:W.functionPath,...q,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},k)}};await Promise.all([...g.entries()].map(async([M,z])=>{const re=new Headers(b);re.set("content-type","application/json");const de=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(s,M,de)}catch(H){const Ue=Date.now()-fe,{body:Ye}=br(H,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});ee(z,502,Ye.code,Ye.message,gr=>({...Se(gr.functionPath,Ue,H,{shardKey:M}),...q}));return}const me=Date.now()-fe,ye=W.headers.get("x-d1-bookmark");ye&&B.push(ye);let De;try{De=await W.json()}catch{const H=`shard batch returned a non-JSON response (${String(W.status)})`;ee(z,W.status,"SHARD_ERROR",H,Ue=>({durationMs:me,error:{code:"SHARD_ERROR",message:H,status:W.status},functionPath:Ue.functionPath,...q,ok:!1,shardKey:M}));return}const Pe=Array.isArray(De.results)?De.results:[],mr=new Map(Pe.map(H=>[H.id,H.status??W.status])),wr=new Set(Pe.map(H=>H.id));F(z,M,me,mr,W.status),C.push(...Pe);for(const H of z)wr.has(H.id)||C.push(Z(H,W.status,"SHARD_ERROR",`shard batch omitted result for call ${String(H.id)}`))}));const He={"content-type":"application/json"},[Ve]=B;return B.length===1&&Ve!==void 0&&(He["x-d1-bookmark"]=Ve),Response.json({results:C},{headers:He,status:200})},or=async(a,c,p,d={},m={})=>{try{const b=p.__lunoraRef;if(typeof b!="string")throw new i("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:D,identity:g}=await ue(a,c,o);await Re({functionPath:b,shardKey:m.shardKey},g);const O=m.shardKey??n,k=Ee(c,a,m.waitUntil);return await ve(a,b,d,O,D,k)}catch(b){return Xe(b)}},We=async(a,c,p)=>{const{observability:d}=e,m=Date.now(),b=Ae(16),D=Ae(8),g=Et(c);try{const O=await p();return ce(d,{durationMs:Date.now()-m,functionPath:a,ok:!0,spanId:D,traceId:b},g),O}catch(O){throw ce(d,{...Se(a,Date.now()-m,O,{}),spanId:D,traceId:b},g),O}finally{Ze(d,g)}},sr=async(a,c,p)=>{w(c);const d=[],m=g=>g instanceof Error?g:new Error(String(g)),b=e.crons?.[a.cron];if(b)try{await b(a,c,p)}catch(g){d.push(m(g))}if(await V(a.cron,c,d,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===a.cron)try{await Sn(e,s,f(),a)}catch(g){d.push(m(g))}const[D]=d;if(d.length===1&&D)throw D;if(d.length>1)throw new AggregateError(d,`scheduled("${a.cron}") had ${String(d.length)} failure(s)`)},ir=async(a,c)=>{try{const p=a??{},d=e.adminToken??(typeof p.LUNORA_ADMIN_TOKEN=="string"?p.LUNORA_ADMIN_TOKEN:void 0);if(!d||d.length===0)return;await oe(s,n,Te(ho,{outcome:c},{authorization:`Bearer ${d}`,"content-type":"application/json"}))}catch{}},cr=async(a,c,p,d)=>{if(!e.authHandler)return;const m=await e.authHandler(a);if(!m)return;const b=e.authBasePath??lo;return mo(p.pathname,b)&&d.waitUntil?.(ir(c,m.status>=400?"fail":"ok")),m},ur=async({args:a,env:c,functionPath:p,request:d,shardKey:m,waitUntil:b})=>{It(a,"REST");const D={functionPath:p,...m===void 0?{}:{shardKey:m}},{headers:g,identity:O}=await ue(d,c,o);await Re(D,O);const k=m??n,q=Ee(c,d,b),C=()=>ve(d,p,a,k,g,q),B=St(D,e);return B&&e.x402Charge?e.x402Charge(d,{functionPath:p,price:B.price},C,bt({waitUntil:b})):C()},dr=Ir({functions:e.functions??{},invoke:ur,readJsonBody:X,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ie=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,lr={[io]: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"}}),[to]:(a,c,p)=>Zt(a,c,p),[yt]:(a,c,p,d)=>nr(a,c,d),[eo]:(a,c,p,d)=>ar(a,c,d),[ro]:(a,c)=>Q(a,c),[no]:(a,c)=>N(a,c),[ao]:async a=>{x(a,"POST","ws-token"),$(a);const c=f();if(c===void 0)throw new i("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const p=await cn(c);return Response.json(p,{headers:{"cache-control":"no-store"}})},...U,...he,...ke,...se,...Ft,...Gt,...Qt,...Mt,...zt,...Wt,...Ht,...dr,...hn({assertAdmin:$,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:ae,readJsonBody:X})};let ie=tt(e.security),Je=!1;const hr=a=>{Je||(Je=!0,ie=tt(e.security,a??{}))},pr=async(a,c)=>{if(!(e.adminGate===void 0||!co(c)))try{await e.adminGate(a)&&_.add(a)}catch{}},fr=async(a,c,p)=>{const d=new URL(a.url);if(a.method==="POST"||a.method==="PUT"){const g=Number(a.headers.get("content-length")??""),O=Za[d.pathname]??kt;if(Number.isFinite(g)&&g>O)throw new i("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await cr(a,c,d,p);if(m)return m;if(Ie){const g=`${a.method} ${d.pathname}`,O=Ie[g]??Ie[d.pathname];if(O)return O(a,c,p)}const b=lr[d.pathname];return b?(await pr(a,d.pathname),b(a,c,d,p)):e.voiceAgents!==void 0&&d.pathname.startsWith(Rt)?er(a,c,d):await Xt(a,c,p)||new Response("Not found",{status:404})};return{async fetch(a,c,p){e.passThroughOnException&&p.passThroughOnException?.(),hr(c),w(c);const d=Mr(a,ie);if(d)return d;const m=zr(a,ie);if(m)return qe(m,a,ie);try{const b=await fr(a,c,p);return qe(b,a,ie)}catch(b){return qe(Xe(b),a,ie)}finally{Ze(e.observability,Et(p))}},async queue(a,c,p){await We(`queue:${go(a)}`,p,async()=>{await e.queue?.(a,c,p)})},async scheduled(a,c,p){await We(`cron:${a.cron}`,p,async()=>{await sr(a,c,p)})},serverQuery:or}},Do=e=>Lt(e),Po=e=>typeof e=="function"?{fetch:e}:e,Uo=e=>!!(e.crons??e.cronJobs??e.backupCron),Yo=(e,t)=>{const r=Po(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,o=l=>{const u=Do({...l,httpRouter:r});return n!==void 0&&!Uo(l)?{...u,scheduled:async(f,y,E)=>{await n(f,y,E)}}:u};if(typeof t!="function")return o(t);const s=t;return{fetch:(l,u,f)=>o(s(u)).fetch(l,u,f),queue:(l,u,f)=>o(s(u)).queue?.(l,u,f)??Promise.resolve(),scheduled:(l,u,f)=>o(s(u)).scheduled(l,u,f),serverQuery:(l,u,f,y,E)=>o(s(u)).serverQuery(l,u,f,y,E)}},No=(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}},Xo=(e={})=>(t,r,n)=>Lt(No(e,r)).fetch(t,r,n??_r),Zo=e=>e;export{pn as GET_AUTH_AUDIT_LOG_OP,_r as NOOP_EXECUTION_CONTEXT,rs as composeIdentityResolvers,Do as composeWorker,Xo as createLunoraHandler,Lt as createWorker,Zo as defineRpcEnvelope,Oo as probeRelayCount,No as resolveLunoraOptions,ns as routeIdentityResolvers,Yo as withFrameworkWorker};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/runtime",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.59",
|
|
4
4
|
"description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,9 +46,9 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
50
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
51
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
49
|
+
"@lunora/bindings": "1.0.0-alpha.25",
|
|
50
|
+
"@lunora/errors": "1.0.0-alpha.18",
|
|
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};
|