@lunora/runtime 1.0.0-alpha.222 → 1.0.0-alpha.223

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -2420,6 +2420,13 @@ interface SpanEvent {
2420
2420
  * per-shard failure count.
2421
2421
  */
2422
2422
  interface ObservabilityEvent {
2423
+ /**
2424
+ * Extra attributes for this dispatch, e.g. derived by an `enrichSink` enricher.
2425
+ * `otlpSink` exports them as span attributes. A reserved attribute of the same name
2426
+ * wins: a key here never replaces a built-in field such as `http.route` or
2427
+ * `lunora.shard_key`, and the colliding key is dropped.
2428
+ */
2429
+ attributes?: LogFields;
2423
2430
  /** Wall-clock duration of the dispatch, in milliseconds. */
2424
2431
  durationMs: number;
2425
2432
  /**
@@ -5074,6 +5081,61 @@ interface MemoizeIdentityOptions {
5074
5081
  * serve one principal's identity to another — see that option's contract.
5075
5082
  */
5076
5083
  declare const memoizeIdentity: (resolver: IdentityResolver, options?: MemoizeIdentityOptions) => IdentityResolver;
5084
+ /** The four signal kinds a sink receives. */
5085
+ type SinkSignalKind = "log" | "metric" | "rpc" | "span";
5086
+ /** Any event a sink receives. Every variant carries `functionPath`. */
5087
+ type SinkEvent = LogEvent | MetricEvent | ObservabilityEvent | SpanEvent;
5088
+ /**
5089
+ * Derives extra attributes for one event. Return `undefined` (or an empty bag)
5090
+ * to add nothing.
5091
+ *
5092
+ * The result is normalized to JSON-safe primitives and redacted the way the signal's
5093
+ * own fields are: `redactArgs` for log lines, and the credential-only `redactCredentials`
5094
+ * for metrics, spans and RPC events, whose ids and URLs the PII rules would erase. It
5095
+ * is merged UNDER the event's own attributes: a key the event already sets keeps its value.
5096
+ *
5097
+ * If the enricher throws, the event is delivered unchanged and the failure is logged
5098
+ * (a bounded number of times per isolate). Enrichment only adds fields and never removes
5099
+ * or reveals anything, so failing open is safe here. Unlike a `postProcessor`, which fails
5100
+ * closed because it is a privacy control.
5101
+ */
5102
+ type SinkEnricher = (event: SinkEvent, signal: SinkSignalKind) => LogFields | undefined;
5103
+ /**
5104
+ * Route signals by `functionPath`, using `*` as the only wildcard (any run of
5105
+ * characters, including `:` and `/`). Matching is case-sensitive.
5106
+ *
5107
+ * - `exclude` always wins over `include`.
5108
+ * - An absent or empty `include` matches every path.
5109
+ *
5110
+ * Platform records use synthetic paths such as `ttl:sweep` or `scheduler:outbox`, and some
5111
+ * are kept only in the shard's local log. Those never reach a sink, so no filter can route
5112
+ * them; only the records a sink actually receives are matched against `include` and `exclude`.
5113
+ */
5114
+ interface SinkRouteOptions {
5115
+ /** Patterns that drop a path, even when `include` matches it. */
5116
+ exclude?: string[];
5117
+ /** Patterns a path must match to pass. Absent or empty passes everything. */
5118
+ include?: string[];
5119
+ }
5120
+ /**
5121
+ * Wrap a sink so every event it receives carries the enricher's attributes: log
5122
+ * lines under `fields`, and metrics, spans and RPC events under `attributes`.
5123
+ *
5124
+ * The result is a fresh object per event, never a mutation, because one event
5125
+ * object fans out to every `combineSinks` child and to the shard's local buffers.
5126
+ * @param sink The sink to deliver enriched events to.
5127
+ * @param enrich Derives the extra attributes for each event.
5128
+ */
5129
+ declare const enrichSink: (sink: ObservabilitySink, enrich: SinkEnricher) => ObservabilitySink;
5130
+ /**
5131
+ * Wrap a sink so it receives only the signals whose `functionPath` passes the
5132
+ * route options. Applies to all four signal kinds, since each carries a path.
5133
+ * A dropped event never reaches the wrapped sink, and no enricher runs for it
5134
+ * when `filterSink` wraps an `enrichSink`.
5135
+ * @param sink The sink to deliver the routed events to.
5136
+ * @param options The include and exclude patterns. See `SinkRouteOptions`.
5137
+ */
5138
+ declare const filterSink: (sink: ObservabilitySink, options: SinkRouteOptions) => ObservabilitySink;
5077
5139
  /** Shared shape for sinks that can be limited to error events only. */
5078
5140
  interface OnlyErrorsOption {
5079
5141
  /** When true, only events with `ok === false` are forwarded. */
@@ -5608,4 +5670,4 @@ export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolve
5608
5670
  * surface — without a name for it, a caller cannot hoist a shared attribute bag
5609
5671
  * into a typed constant.
5610
5672
  */
5611
- type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type QueueForwardBatch, type QueueForwardHandler, type QueueForwardMessage, type QueueForwardResult, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ReportedError, 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 ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StackFrame, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TriggerTrace, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, declareAppJurisdiction, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, normalizeBackupPrefix, otlpSink, parseStackFrames, pipelineLogSink, presenceProbe, r2Sink, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, toAirbyteMessages, toError, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
5673
+ type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type QueueForwardBatch, type QueueForwardHandler, type QueueForwardMessage, type QueueForwardResult, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ReportedError, 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 ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SinkEnricher, type SinkEvent, type SinkRouteOptions, type SinkSignalKind, type SpanEvent, type StackFrame, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TriggerTrace, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, declareAppJurisdiction, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, enrichSink, filterSink, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, normalizeBackupPrefix, otlpSink, parseStackFrames, pipelineLogSink, presenceProbe, r2Sink, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, toAirbyteMessages, toError, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
package/dist/index.d.ts CHANGED
@@ -2420,6 +2420,13 @@ interface SpanEvent {
2420
2420
  * per-shard failure count.
2421
2421
  */
2422
2422
  interface ObservabilityEvent {
2423
+ /**
2424
+ * Extra attributes for this dispatch, e.g. derived by an `enrichSink` enricher.
2425
+ * `otlpSink` exports them as span attributes. A reserved attribute of the same name
2426
+ * wins: a key here never replaces a built-in field such as `http.route` or
2427
+ * `lunora.shard_key`, and the colliding key is dropped.
2428
+ */
2429
+ attributes?: LogFields;
2423
2430
  /** Wall-clock duration of the dispatch, in milliseconds. */
2424
2431
  durationMs: number;
2425
2432
  /**
@@ -5074,6 +5081,61 @@ interface MemoizeIdentityOptions {
5074
5081
  * serve one principal's identity to another — see that option's contract.
5075
5082
  */
5076
5083
  declare const memoizeIdentity: (resolver: IdentityResolver, options?: MemoizeIdentityOptions) => IdentityResolver;
5084
+ /** The four signal kinds a sink receives. */
5085
+ type SinkSignalKind = "log" | "metric" | "rpc" | "span";
5086
+ /** Any event a sink receives. Every variant carries `functionPath`. */
5087
+ type SinkEvent = LogEvent | MetricEvent | ObservabilityEvent | SpanEvent;
5088
+ /**
5089
+ * Derives extra attributes for one event. Return `undefined` (or an empty bag)
5090
+ * to add nothing.
5091
+ *
5092
+ * The result is normalized to JSON-safe primitives and redacted the way the signal's
5093
+ * own fields are: `redactArgs` for log lines, and the credential-only `redactCredentials`
5094
+ * for metrics, spans and RPC events, whose ids and URLs the PII rules would erase. It
5095
+ * is merged UNDER the event's own attributes: a key the event already sets keeps its value.
5096
+ *
5097
+ * If the enricher throws, the event is delivered unchanged and the failure is logged
5098
+ * (a bounded number of times per isolate). Enrichment only adds fields and never removes
5099
+ * or reveals anything, so failing open is safe here. Unlike a `postProcessor`, which fails
5100
+ * closed because it is a privacy control.
5101
+ */
5102
+ type SinkEnricher = (event: SinkEvent, signal: SinkSignalKind) => LogFields | undefined;
5103
+ /**
5104
+ * Route signals by `functionPath`, using `*` as the only wildcard (any run of
5105
+ * characters, including `:` and `/`). Matching is case-sensitive.
5106
+ *
5107
+ * - `exclude` always wins over `include`.
5108
+ * - An absent or empty `include` matches every path.
5109
+ *
5110
+ * Platform records use synthetic paths such as `ttl:sweep` or `scheduler:outbox`, and some
5111
+ * are kept only in the shard's local log. Those never reach a sink, so no filter can route
5112
+ * them; only the records a sink actually receives are matched against `include` and `exclude`.
5113
+ */
5114
+ interface SinkRouteOptions {
5115
+ /** Patterns that drop a path, even when `include` matches it. */
5116
+ exclude?: string[];
5117
+ /** Patterns a path must match to pass. Absent or empty passes everything. */
5118
+ include?: string[];
5119
+ }
5120
+ /**
5121
+ * Wrap a sink so every event it receives carries the enricher's attributes: log
5122
+ * lines under `fields`, and metrics, spans and RPC events under `attributes`.
5123
+ *
5124
+ * The result is a fresh object per event, never a mutation, because one event
5125
+ * object fans out to every `combineSinks` child and to the shard's local buffers.
5126
+ * @param sink The sink to deliver enriched events to.
5127
+ * @param enrich Derives the extra attributes for each event.
5128
+ */
5129
+ declare const enrichSink: (sink: ObservabilitySink, enrich: SinkEnricher) => ObservabilitySink;
5130
+ /**
5131
+ * Wrap a sink so it receives only the signals whose `functionPath` passes the
5132
+ * route options. Applies to all four signal kinds, since each carries a path.
5133
+ * A dropped event never reaches the wrapped sink, and no enricher runs for it
5134
+ * when `filterSink` wraps an `enrichSink`.
5135
+ * @param sink The sink to deliver the routed events to.
5136
+ * @param options The include and exclude patterns. See `SinkRouteOptions`.
5137
+ */
5138
+ declare const filterSink: (sink: ObservabilitySink, options: SinkRouteOptions) => ObservabilitySink;
5077
5139
  /** Shared shape for sinks that can be limited to error events only. */
5078
5140
  interface OnlyErrorsOption {
5079
5141
  /** When true, only events with `ok === false` are forwarded. */
@@ -5608,4 +5670,4 @@ export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolve
5608
5670
  * surface — without a name for it, a caller cannot hoist a shared attribute bag
5609
5671
  * into a typed constant.
5610
5672
  */
5611
- type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type QueueForwardBatch, type QueueForwardHandler, type QueueForwardMessage, type QueueForwardResult, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ReportedError, 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 ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StackFrame, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TriggerTrace, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, declareAppJurisdiction, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, normalizeBackupPrefix, otlpSink, parseStackFrames, pipelineLogSink, presenceProbe, r2Sink, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, toAirbyteMessages, toError, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
5673
+ type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type QueueForwardBatch, type QueueForwardHandler, type QueueForwardMessage, type QueueForwardResult, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ReportedError, 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 ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SinkEnricher, type SinkEvent, type SinkRouteOptions, type SinkSignalKind, type SpanEvent, type StackFrame, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TriggerTrace, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, declareAppJurisdiction, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, enrichSink, filterSink, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, normalizeBackupPrefix, otlpSink, parseStackFrames, pipelineLogSink, presenceProbe, r2Sink, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, toAirbyteMessages, toError, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as R,toFivetranResponse as x}from"./packem_shared/toAirbyteMessages-DY0vsuEn.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as y}from"./packem_shared/composeWorker-B3F3HpUc.mjs";import{createCrossShardRelationCapabilities as O}from"./packem_shared/createCrossShardRelationCapabilities-C8lpyW1a.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-Jrpa-kBx.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-PkZWF-_g.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w as B}from"./packem_shared/export-tap-C2B_SATf.mjs";import{HEALTH_PATH as w,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-B8ndDG3s.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{memoizeIdentity as $,memoizeIdentityPerRequest as ee}from"./packem_shared/memoizeIdentity-BNnHkqeF.mjs";import{e as oe,a as te}from"./packem_shared/observability-9slk__Gi.mjs";import{analyticsEngineSink as se,combineSinks as ie,consoleSink as pe,otlpSink as ne,pipelineLogSink as ce,webhookSink as me}from"./packem_shared/analyticsEngineSink-DN3_R-ab.mjs";import{D as Ee,c as Re}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as Se,createStaticShardRegistry as le}from"./packem_shared/createQueryCoordinator-Bt6xVTQn.mjs";import{applyJurisdiction as ue,resolveShard as _e}from"./packem_shared/applyJurisdiction-DKQE8kOA.mjs";import{a as ye,r as Ce,b as Oe}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as Ae,b as Le,c as Te,r as he}from"./packem_shared/rest-routes-CDQ1F7kI.mjs";import{decorateResponse as Pe,enforceOrigin as ge,handleCorsPreflight as ve,resolveSecurity as Ie}from"./packem_shared/decorateResponse-CdelJSUs.mjs";import{createShardClient as Fe}from"./packem_shared/createShardClient-BlcK9Nok.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ne}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-DiZho96u.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ke}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Be}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as we,routeIdentityResolvers as ze}from"./packem_shared/composeIdentityResolvers-CpdHuDyk.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Ee as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,w as HEALTH_PATH,z as HEALTH_READY_PATH,Ke as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,Be as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ne as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,se as analyticsEngineSink,ue as applyJurisdiction,ye as applyRestCache,Ae as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,Le as buildRestRoutes,ie as combineSinks,we as composeIdentityResolvers,l as composeWorker,pe as consoleSink,O as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,d as createLunoraHandler,M as createMemoryCursorStore,Re as createPipelineLogReader,Se as createQueryCoordinator,Te as createRestRateLimit,Fe as createShardClient,le as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Pe as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,ge as enforceOrigin,ve as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,ne as otlpSink,H as parseStackFrames,ce as pipelineLogSink,W as presenceProbe,G as r2Sink,Ce as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Ie as resolveSecurity,_e as resolveShard,Oe as restCacheHeaders,he as restSurfaceFromRegistry,ze as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,R as toAirbyteMessages,P as toError,I as toErrorResponse,x as toFivetranResponse,B as webhookExportSink,me as webhookSink,y as withFrameworkWorker};
1
+ import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as x,toFivetranResponse as R}from"./packem_shared/toAirbyteMessages-DY0vsuEn.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as b}from"./packem_shared/composeWorker-CTB0-5ke.mjs";import{createCrossShardRelationCapabilities as C}from"./packem_shared/createCrossShardRelationCapabilities-C8lpyW1a.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-Jrpa-kBx.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-PkZWF-_g.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w}from"./packem_shared/export-tap-C2B_SATf.mjs";import{HEALTH_PATH as Y,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-B8ndDG3s.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{memoizeIdentity as $,memoizeIdentityPerRequest as ee}from"./packem_shared/memoizeIdentity-BNnHkqeF.mjs";import{e as oe,a as te}from"./packem_shared/observability-9slk__Gi.mjs";import{enrichSink as se,filterSink as ie}from"./packem_shared/enrichSink-44NOapaE.mjs";import{a as ne,c as ce,b as me,o as fe,p as Ee,w as xe}from"./packem_shared/observability-sinks-lLKqc_rV.mjs";import{D as Se,c as le}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as ue,createStaticShardRegistry as _e}from"./packem_shared/createQueryCoordinator-Bt6xVTQn.mjs";import{applyJurisdiction as be,resolveShard as ye}from"./packem_shared/applyJurisdiction-DKQE8kOA.mjs";import{a as Oe,r as Ae,b as Le}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as he,b as He,c as Pe,r as ge}from"./packem_shared/rest-routes-CDQ1F7kI.mjs";import{decorateResponse as Ie,enforceOrigin as De,handleCorsPreflight as Fe,resolveSecurity as Me}from"./packem_shared/decorateResponse-CdelJSUs.mjs";import{createShardClient as Ge}from"./packem_shared/createShardClient-BlcK9Nok.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ue}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-DiZho96u.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Be}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as ze}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as je,routeIdentityResolvers as Ve}from"./packem_shared/composeIdentityResolvers-CpdHuDyk.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Se as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,Y as HEALTH_PATH,z as HEALTH_READY_PATH,Be as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,ze as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ue as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ne as analyticsEngineSink,be as applyJurisdiction,Oe as applyRestCache,he as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,He as buildRestRoutes,ce as combineSinks,je as composeIdentityResolvers,l as composeWorker,me as consoleSink,C as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,d as createLunoraHandler,M as createMemoryCursorStore,le as createPipelineLogReader,ue as createQueryCoordinator,Pe as createRestRateLimit,Ge as createShardClient,_e as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Ie as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,De as enforceOrigin,se as enrichSink,ie as filterSink,Fe as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,fe as otlpSink,H as parseStackFrames,Ee as pipelineLogSink,W as presenceProbe,G as r2Sink,Ae as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Me as resolveSecurity,ye as resolveShard,Le as restCacheHeaders,ge as restSurfaceFromRegistry,Ve as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,x as toAirbyteMessages,P as toError,I as toErrorResponse,R as toFivetranResponse,w as webhookExportSink,xe as webhookSink,b as withFrameworkWorker};
@@ -0,0 +1 @@
1
+ import"./otlp-resource-Ch_8_U0e.mjs";import{S as a,a as s,c as S,b as e,o as k,p,w as c}from"./observability-sinks-lLKqc_rV.mjs";export{a as SINK_CONFIG_FIELDS,s as analyticsEngineSink,S as combineSinks,e as consoleSink,k as otlpSink,p as pipelineLogSink,c as webhookSink};
@@ -1,4 +1,4 @@
1
- import{isLunoraError as yr,toErrorBody as br}from"@lunora/errors";import{encodeWire as ye,decodeWire as Ze,encodeArgsOrThrow as _r}from"@lunora/wire";import{d as Rt,E as Et,a as Rr,b as Er,W as St}from"./error-detail-C46mdOTW.mjs";import{e as sn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Sr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{i as Tr,e as Ar,a as Or,E as Tt,d as vr}from"./identity-header-pR617HTs.mjs";import{O as cn,a as dn}from"./origin-paywall-B6eOO67m.mjs";import{o as be,b as un,p as Ir,m as Pr,d as kr,a as Dr,r as Nr}from"./otlp-resource-BwFJnvwB.mjs";import{r as Ur,f as At,a as ue,S as Ot}from"./observability-9slk__Gi.mjs";import{t as Cr,f as Br}from"./base64-Bl1_r2k1.mjs";import{d as ne,e as oe,M as ln,b as xr,f as Hr,g as hn,w as Lr,h as fn,t as jr}from"./rest-routes-CDQ1F7kI.mjs";import{LunoraError as c,toErrorResponse as vt}from"./LunoraError-PkZWF-_g.mjs";import{a as M,m as ge}from"./method-guard-8Jo4Q8uS.mjs";import{normalizeBackupPrefix as at,BACKUP_KEY_PREFIX as st,isBackupManifestKey as Mr,backupObjectKeyOfManifest as pn,backupObjectKey as $r,backupManifestKey as Fr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Kr,buildStorageAdminRoutes as Gr,STORAGE_UPLOAD_MAX_BODY_BYTES as Qr,STORAGE_PATH as Wr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-DiZho96u.mjs";import{b as zr,e as Vr,f as It,g as Jr,h as Yr}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as qr,durableObjectProbe as Xr,d1Probe as Zr,presenceProbe as $e}from"./HEALTH_PATH-B8ndDG3s.mjs";import{wrapResolverWithContract as eo}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{composeIdentityResolvers as Qi,routeIdentityResolvers as Wi}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{buildLogArchiveAdminRoutes as to}from"./LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{pruneShardRegistry as no,createQueryCoordinator as ro,createDefaultShardRegistry as oo}from"./createQueryCoordinator-Bt6xVTQn.mjs";import{resolveShard as _e,applyJurisdiction as Fe}from"./applyJurisdiction-DKQE8kOA.mjs";import{resolveSecurity as Pt,handleCorsPreflight as ao,enforceOrigin as so,decorateResponse as Ke,enforceWebSocketOrigin as kt}from"./decorateResponse-CdelJSUs.mjs";const io=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},mn="__lunoraBranch",co=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,mn),uo=`may not contain the reserved workflow branch-marker key ("${mn}")`,lo=async e=>{const t=[];let n;for(;;){const o=await e(n);if(t.push(...Array.isArray(o.records)?o.records:[]),o.truncated!==!0||typeof o.cursor!="string"||o.cursor.length===0)return t;if(o.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=o.cursor}},ho=/already[\s_-]?exists/iu,fo=e=>ho.test(e instanceof Error?e.message:String(e)),po="/_lunora/live/publish",mo="cf-ray",wo="x-lunora-ray-id",go=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,yo=e=>e==null?void 0:go.exec(e.trim())?.[1]?.toLowerCase(),bo=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(bo);const _o=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Ro=-100,Eo=15,So=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&_o.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Eo?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Ro?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},Dt=e=>{const t=e.cf;return t===void 0?void 0:So(t)},et="::relay::",To=(e,t)=>`${e}${et}${String(t)}`,tt="::replica::",Ao=(e,t)=>`${e}${tt}${t}`,Oo=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},wn=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,d=a<t.length?t.charCodeAt(a):0;o|=i^d}return o===0},vo=(e,t,n,o)=>{const a=e.get(t);if(a!==void 0)return a;sn(e,o);const i=n().catch(d=>{throw e.get(t)===i&&e.delete(t),d});return e.set(t,i),i},it=new TextEncoder,Io=Array.from({length:32},(e,t)=>t);new RegExp(`[${Io.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Po=64,ko=new Map,gn=async e=>vo(ko,e,async()=>crypto.subtle.importKey("raw",it.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),Po),yn=async(e,t)=>{const n=await gn(e),o=await crypto.subtle.sign("HMAC",n,it.encode(t));return Cr(new Uint8Array(o))},Do=async(e,t,n)=>{const o=await gn(e);return crypto.subtle.verify("HMAC",o,n,it.encode(t))},No="/_lunora/scheduler/dispatch",Uo="__lunora_relation__:",Co=e=>e.startsWith(Uo),bn=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[o,...a]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:wn(t,a.join(" ").trim())},Bo=async(e,t,n)=>{const o=e.headers.get("x-lunora-scheduler-signature"),{schedulerSecret:a}=n;return o!==null&&o.length>0&&a!==void 0&&a.length>0?wn(await yn(a,t),o):bn(e,n.adminToken)},xo=({forwardedIdentity:e,mutationId:t,traceparent:n})=>{const o={"content-type":"application/json",[dn]:cn,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(o["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(o["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(o["x-lunora-mutation-id"]=t),n!==void 0&&n.length>0&&(o.traceparent=n),o},Ho=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},Lo=(e,t,n)=>e?.[n]??t?.[n],jo=(e,t,n,o)=>{const a=Lo(e,t,n);if(!(typeof a!="object"||a===null))return o.every(i=>typeof a[i]=="function")?a:void 0},_n="v1",Mo=6e4,$o=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Mo),o=`${_n}.${String(n)}`,a=await yn(e,o);return{expiresAtMs:n,token:`${o}.${a}`}},Fo=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[a,i,d]=o;if(a!==_n||d.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let h;try{h=Br(d)}catch{return!1}return Do(e,`${a}.${i}`,h)},U="/_lunora/admin/auth",Ko={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},B=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},me=(e,t)=>{const n=e(t);if(n===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},Rn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},re=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ge=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},Nt=e=>{const t=Rn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},Ut=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[o,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[o]=a);return n},Go={[`${U}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${U}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${U}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${U}/accounts`]:{build:({query:e})=>({userId:me(e,"userId")}),http:"GET",method:"listAccounts"},[`${U}/passkeys`]:{build:({query:e})=>({userId:me(e,"userId")}),http:"GET",method:"listPasskeys"},[`${U}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${U}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listMembers"},[`${U}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${U}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${U}/sign-up-invitations/create`]:{build:({body:e})=>({email:B(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:re(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${U}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:B(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${U}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${U}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listTeams"},[`${U}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:me(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${U}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${U}/users/create`]:{build:({body:e})=>({data:Ge(e,"data"),email:B(e,"email"),name:B(e,"name"),password:re(e,"password"),role:Rn(e.role)}),http:"POST",method:"createUser"},[`${U}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:B(e,"userId")}},http:"POST",method:"updateUser"},[`${U}/users/role`]:{build:({body:e})=>({role:Nt(e),userId:B(e,"userId")}),http:"POST",method:"setRole"},[`${U}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:B(e,"userId")}),http:"POST",method:"banUser"},[`${U}/users/unban`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"unbanUser"},[`${U}/users/password`]:{build:({body:e})=>({newPassword:B(e,"newPassword"),userId:B(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${U}/users/remove`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${U}/users/impersonate`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"impersonateUser"},[`${U}/sessions/revoke`]:{build:({body:e})=>({sessionId:B(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${U}/sessions/revoke-all`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${U}/accounts/unlink`]:{build:({body:e})=>({accountId:B(e,"accountId"),userId:B(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${U}/two-factor/disable`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${U}/passkeys/delete`]:{build:({body:e})=>({passkeyId:B(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${U}/organizations/members/remove`]:{build:({body:e})=>({memberId:B(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${U}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:B(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${U}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:Ge(e,"metadata"),name:B(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${U}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:Ge(e,"metadata"),name:re(e,"name"),organizationId:B(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${U}/organizations/remove`]:{build:({body:e})=>({organizationId:B(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${U}/organizations/members/add`]:{build:({body:e})=>({organizationId:B(e,"organizationId"),role:re(e,"role"),userId:B(e,"userId")}),http:"POST",method:"addMember"},[`${U}/organizations/members/invite`]:{build:({body:e})=>({email:B(e,"email"),inviterId:re(e,"inviterId"),organizationId:B(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${U}/organizations/members/role`]:{build:({body:e})=>({memberId:B(e,"memberId"),role:Nt(e)}),http:"POST",method:"updateMemberRole"},[`${U}/organizations/teams/create`]:{build:({body:e})=>({name:B(e,"name"),organizationId:B(e,"organizationId")}),http:"POST",method:"createTeam"},[`${U}/organizations/teams/update`]:{build:({body:e})=>({name:B(e,"name"),teamId:B(e,"teamId")}),http:"POST",method:"updateTeam"},[`${U}/organizations/teams/remove`]:{build:({body:e})=>({teamId:B(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${U}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:B(e,"teamId"),userId:B(e,"userId")}),http:"POST",method:"addTeamMember"},[`${U}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:B(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${U}/organizations/roles/create`]:{build:({body:e})=>({organizationId:B(e,"organizationId"),permission:Ut(e),role:B(e,"role")}),http:"POST",method:"createOrgRole"},[`${U}/organizations/roles/update`]:{build:({body:e})=>({permission:Ut(e),roleId:B(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${U}/organizations/roles/remove`]:{build:({body:e})=>({roleId:B(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Qo=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof c)throw i;const d=i,f=typeof d.code=="string"?d.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:f,status:Ko[f]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const d=e.getAuthAdmin();if(d===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=d[i.method];if(f===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const h=new URL(a.url),m={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:T=>e.queryParameter(h,T)},g=i.build(m),S=await t(()=>f(g));return Response.json(i.returns==="void"?{ok:!0}:S,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[a,i]of Object.entries(Go))o[a]=d=>n(d,i);return o},Ct="__lunora_admin__:getAuthAuditLog",Bt=e=>typeof e=="string"&&e!==""?e:void 0,xt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Wo=e=>async(n,o)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=Bt(o.actorId),d=Bt(o.event),f=xt(o.sinceSeq),h=xt(o.limit),m={...i===void 0?{}:{actorId:i},...d===void 0?{}:{event:d},...f===void 0?{}:{sinceSeq:f},...h===void 0?{}:{limit:h}};let g;try{g=await a.read(m)}catch(T){throw T instanceof c?T:(console.error("[lunora] auth audit read failed:",T),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const S={entries:g};return Response.json({result:ye(S)},{headers:{"content-type":"application/json"},status:200})},nt="__lunora_admin__:copyAuthToJurisdiction",En="__lunora_admin__:purgeUnpinnedAuth",zo=e=>async(t,n,o)=>{if(n!==nt&&n!==En)return;e.assertAdmin(t);const a=e.getMove();if(a===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===nt?await a.copy({force:o.force===!0}):await a.purge();return Response.json({result:ye(i)},{headers:{"content-type":"application/json"},status:200})},Vo=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?o.push(a):n.push(a);return{globalTables:o,shardLocalTables:n}},Jo=async(e,t,n,o,a,i)=>{if(n!==void 0&&o.length===0)return[];const d=await e.orchestrateExport(a,{args:{tables:o},defaultShardKey:i,headers:t,tables:o}),f=d.shards.filter(h=>h.error);if(f.length>0){const h=f.map(m=>`${m.shardKey}: ${m.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(f.length)} of ${String(d.shards.length)} shard(s) — ${h}`,{code:"EXPORT_SHARD_FAILED",status:502})}return d.shards.flatMap(h=>h.rows??[])},Sn=async(e,t,n,o,a)=>{const i=o??e.listSchemaTables?.();o===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:d,shardLocalTables:f}=Vo(e,i),h=await Jo(t,n,i,f,a,e.defaultShardKey??"__root__"),m=e.exportGlobals,g=o===void 0||d.length>0;return(async function*(){yield*h,g&&m&&(yield*m({tables:d}))})()},Yo=async(e,t,n,o,a,i)=>{for await(const d of await Sn(e,t,n,o,i))a(d)},qo=new TextEncoder,Xo=1e3,Tn=10,Zo=200,Ht=8,An="lunoraBackupCron",Lt=24*1048576,jt=e=>{const t=e.slice(0,Tn).map(o=>pn(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},ea=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const a of e)n.set(a,o),o+=a.byteLength;return n},ct=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let d=0;d<Xo;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)Mr(h.key)&&h.customMetadata?.[An]===o&&a.push(h.key);if(!f.truncated||f.cursor===void 0)break;i=f.cursor}return{eligible:a.length,stale:a.toSorted((d,f)=>f.localeCompare(d)).slice(n)}},ta=async(e,t,n,o,a)=>{const{stale:i}=await ct(e,t,n,o),d=new Set(a),f=i.filter(P=>d.has(P)),h=f.slice(0,Zo),m=i.length-h.length,g=a.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:g,remaining:m};const S=[],T=[];for(let P=0;P<h.length;P+=Ht){const w=await Promise.allSettled(h.slice(P,P+Ht).map(async y=>(await e.delete(pn(y)),await e.delete(y),y)));for(const[y,b]of w.entries())b.status==="fulfilled"?S.push(b.value):T.push(h[P+y])}return S.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(S.length)}: ${jt(S)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${jt(T)}`),{deleted:S,failed:T,ignored:g,remaining:m}},na=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=at(e.backupPrefix??st),o=e.backupCron,{eligible:a,stale:i}=o===void 0?{eligible:0,stale:[]}:await ct(t,n,e.backupRetain,o);return{cron:o,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},ra=async(e,t,n,o,a)=>{const i=e.backupStore;if(!i)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!o||o.length===0)throw new c("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const d={authorization:`Bearer ${o}`,"content-type":"application/json"},f=e.backupTables;let h=0,m=0,g=[];await Yo(e,t,d,f,I=>{const E=qo.encode(`${JSON.stringify(I)}
1
+ import{isLunoraError as yr,toErrorBody as br}from"@lunora/errors";import{encodeWire as ye,decodeWire as Ze,encodeArgsOrThrow as _r}from"@lunora/wire";import{d as Rt,E as Et,a as Rr,b as Er,W as St}from"./error-detail-C46mdOTW.mjs";import{e as sn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Sr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{i as Tr,e as Ar,a as Or,E as Tt,d as vr}from"./identity-header-pR617HTs.mjs";import{O as cn,a as dn}from"./origin-paywall-B6eOO67m.mjs";import{o as be,b as un,p as Ir,m as Pr,d as kr,a as Dr,r as Nr}from"./otlp-resource-Ch_8_U0e.mjs";import{r as Ur,f as At,a as ue,S as Ot}from"./observability-9slk__Gi.mjs";import{t as Cr,f as Br}from"./base64-Bl1_r2k1.mjs";import{d as ne,e as oe,M as ln,b as xr,f as Hr,g as hn,w as Lr,h as fn,t as jr}from"./rest-routes-CDQ1F7kI.mjs";import{LunoraError as c,toErrorResponse as vt}from"./LunoraError-PkZWF-_g.mjs";import{a as M,m as ge}from"./method-guard-8Jo4Q8uS.mjs";import{normalizeBackupPrefix as at,BACKUP_KEY_PREFIX as st,isBackupManifestKey as Mr,backupObjectKeyOfManifest as pn,backupObjectKey as $r,backupManifestKey as Fr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Kr,buildStorageAdminRoutes as Gr,STORAGE_UPLOAD_MAX_BODY_BYTES as Qr,STORAGE_PATH as Wr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-DiZho96u.mjs";import{b as zr,e as Vr,f as It,g as Jr,h as Yr}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as qr,durableObjectProbe as Xr,d1Probe as Zr,presenceProbe as $e}from"./HEALTH_PATH-B8ndDG3s.mjs";import{wrapResolverWithContract as eo}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{composeIdentityResolvers as Qi,routeIdentityResolvers as Wi}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{buildLogArchiveAdminRoutes as to}from"./LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{pruneShardRegistry as no,createQueryCoordinator as ro,createDefaultShardRegistry as oo}from"./createQueryCoordinator-Bt6xVTQn.mjs";import{resolveShard as _e,applyJurisdiction as Fe}from"./applyJurisdiction-DKQE8kOA.mjs";import{resolveSecurity as Pt,handleCorsPreflight as ao,enforceOrigin as so,decorateResponse as Ke,enforceWebSocketOrigin as kt}from"./decorateResponse-CdelJSUs.mjs";const io=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},mn="__lunoraBranch",co=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,mn),uo=`may not contain the reserved workflow branch-marker key ("${mn}")`,lo=async e=>{const t=[];let n;for(;;){const o=await e(n);if(t.push(...Array.isArray(o.records)?o.records:[]),o.truncated!==!0||typeof o.cursor!="string"||o.cursor.length===0)return t;if(o.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=o.cursor}},ho=/already[\s_-]?exists/iu,fo=e=>ho.test(e instanceof Error?e.message:String(e)),po="/_lunora/live/publish",mo="cf-ray",wo="x-lunora-ray-id",go=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,yo=e=>e==null?void 0:go.exec(e.trim())?.[1]?.toLowerCase(),bo=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(bo);const _o=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Ro=-100,Eo=15,So=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&_o.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Eo?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Ro?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},Dt=e=>{const t=e.cf;return t===void 0?void 0:So(t)},et="::relay::",To=(e,t)=>`${e}${et}${String(t)}`,tt="::replica::",Ao=(e,t)=>`${e}${tt}${t}`,Oo=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},wn=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,d=a<t.length?t.charCodeAt(a):0;o|=i^d}return o===0},vo=(e,t,n,o)=>{const a=e.get(t);if(a!==void 0)return a;sn(e,o);const i=n().catch(d=>{throw e.get(t)===i&&e.delete(t),d});return e.set(t,i),i},it=new TextEncoder,Io=Array.from({length:32},(e,t)=>t);new RegExp(`[${Io.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Po=64,ko=new Map,gn=async e=>vo(ko,e,async()=>crypto.subtle.importKey("raw",it.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),Po),yn=async(e,t)=>{const n=await gn(e),o=await crypto.subtle.sign("HMAC",n,it.encode(t));return Cr(new Uint8Array(o))},Do=async(e,t,n)=>{const o=await gn(e);return crypto.subtle.verify("HMAC",o,n,it.encode(t))},No="/_lunora/scheduler/dispatch",Uo="__lunora_relation__:",Co=e=>e.startsWith(Uo),bn=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[o,...a]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:wn(t,a.join(" ").trim())},Bo=async(e,t,n)=>{const o=e.headers.get("x-lunora-scheduler-signature"),{schedulerSecret:a}=n;return o!==null&&o.length>0&&a!==void 0&&a.length>0?wn(await yn(a,t),o):bn(e,n.adminToken)},xo=({forwardedIdentity:e,mutationId:t,traceparent:n})=>{const o={"content-type":"application/json",[dn]:cn,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(o["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(o["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(o["x-lunora-mutation-id"]=t),n!==void 0&&n.length>0&&(o.traceparent=n),o},Ho=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},Lo=(e,t,n)=>e?.[n]??t?.[n],jo=(e,t,n,o)=>{const a=Lo(e,t,n);if(!(typeof a!="object"||a===null))return o.every(i=>typeof a[i]=="function")?a:void 0},_n="v1",Mo=6e4,$o=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Mo),o=`${_n}.${String(n)}`,a=await yn(e,o);return{expiresAtMs:n,token:`${o}.${a}`}},Fo=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[a,i,d]=o;if(a!==_n||d.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let h;try{h=Br(d)}catch{return!1}return Do(e,`${a}.${i}`,h)},U="/_lunora/admin/auth",Ko={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},B=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},me=(e,t)=>{const n=e(t);if(n===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},Rn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},re=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ge=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},Nt=e=>{const t=Rn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},Ut=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[o,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[o]=a);return n},Go={[`${U}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${U}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${U}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${U}/accounts`]:{build:({query:e})=>({userId:me(e,"userId")}),http:"GET",method:"listAccounts"},[`${U}/passkeys`]:{build:({query:e})=>({userId:me(e,"userId")}),http:"GET",method:"listPasskeys"},[`${U}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${U}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listMembers"},[`${U}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${U}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${U}/sign-up-invitations/create`]:{build:({body:e})=>({email:B(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:re(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${U}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:B(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${U}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${U}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listTeams"},[`${U}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:me(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${U}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${U}/users/create`]:{build:({body:e})=>({data:Ge(e,"data"),email:B(e,"email"),name:B(e,"name"),password:re(e,"password"),role:Rn(e.role)}),http:"POST",method:"createUser"},[`${U}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:B(e,"userId")}},http:"POST",method:"updateUser"},[`${U}/users/role`]:{build:({body:e})=>({role:Nt(e),userId:B(e,"userId")}),http:"POST",method:"setRole"},[`${U}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:B(e,"userId")}),http:"POST",method:"banUser"},[`${U}/users/unban`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"unbanUser"},[`${U}/users/password`]:{build:({body:e})=>({newPassword:B(e,"newPassword"),userId:B(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${U}/users/remove`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${U}/users/impersonate`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"impersonateUser"},[`${U}/sessions/revoke`]:{build:({body:e})=>({sessionId:B(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${U}/sessions/revoke-all`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${U}/accounts/unlink`]:{build:({body:e})=>({accountId:B(e,"accountId"),userId:B(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${U}/two-factor/disable`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${U}/passkeys/delete`]:{build:({body:e})=>({passkeyId:B(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${U}/organizations/members/remove`]:{build:({body:e})=>({memberId:B(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${U}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:B(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${U}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:Ge(e,"metadata"),name:B(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${U}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:Ge(e,"metadata"),name:re(e,"name"),organizationId:B(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${U}/organizations/remove`]:{build:({body:e})=>({organizationId:B(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${U}/organizations/members/add`]:{build:({body:e})=>({organizationId:B(e,"organizationId"),role:re(e,"role"),userId:B(e,"userId")}),http:"POST",method:"addMember"},[`${U}/organizations/members/invite`]:{build:({body:e})=>({email:B(e,"email"),inviterId:re(e,"inviterId"),organizationId:B(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${U}/organizations/members/role`]:{build:({body:e})=>({memberId:B(e,"memberId"),role:Nt(e)}),http:"POST",method:"updateMemberRole"},[`${U}/organizations/teams/create`]:{build:({body:e})=>({name:B(e,"name"),organizationId:B(e,"organizationId")}),http:"POST",method:"createTeam"},[`${U}/organizations/teams/update`]:{build:({body:e})=>({name:B(e,"name"),teamId:B(e,"teamId")}),http:"POST",method:"updateTeam"},[`${U}/organizations/teams/remove`]:{build:({body:e})=>({teamId:B(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${U}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:B(e,"teamId"),userId:B(e,"userId")}),http:"POST",method:"addTeamMember"},[`${U}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:B(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${U}/organizations/roles/create`]:{build:({body:e})=>({organizationId:B(e,"organizationId"),permission:Ut(e),role:B(e,"role")}),http:"POST",method:"createOrgRole"},[`${U}/organizations/roles/update`]:{build:({body:e})=>({permission:Ut(e),roleId:B(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${U}/organizations/roles/remove`]:{build:({body:e})=>({roleId:B(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Qo=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof c)throw i;const d=i,f=typeof d.code=="string"?d.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:f,status:Ko[f]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const d=e.getAuthAdmin();if(d===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=d[i.method];if(f===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const h=new URL(a.url),m={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:T=>e.queryParameter(h,T)},g=i.build(m),S=await t(()=>f(g));return Response.json(i.returns==="void"?{ok:!0}:S,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[a,i]of Object.entries(Go))o[a]=d=>n(d,i);return o},Ct="__lunora_admin__:getAuthAuditLog",Bt=e=>typeof e=="string"&&e!==""?e:void 0,xt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Wo=e=>async(n,o)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=Bt(o.actorId),d=Bt(o.event),f=xt(o.sinceSeq),h=xt(o.limit),m={...i===void 0?{}:{actorId:i},...d===void 0?{}:{event:d},...f===void 0?{}:{sinceSeq:f},...h===void 0?{}:{limit:h}};let g;try{g=await a.read(m)}catch(T){throw T instanceof c?T:(console.error("[lunora] auth audit read failed:",T),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const S={entries:g};return Response.json({result:ye(S)},{headers:{"content-type":"application/json"},status:200})},nt="__lunora_admin__:copyAuthToJurisdiction",En="__lunora_admin__:purgeUnpinnedAuth",zo=e=>async(t,n,o)=>{if(n!==nt&&n!==En)return;e.assertAdmin(t);const a=e.getMove();if(a===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===nt?await a.copy({force:o.force===!0}):await a.purge();return Response.json({result:ye(i)},{headers:{"content-type":"application/json"},status:200})},Vo=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?o.push(a):n.push(a);return{globalTables:o,shardLocalTables:n}},Jo=async(e,t,n,o,a,i)=>{if(n!==void 0&&o.length===0)return[];const d=await e.orchestrateExport(a,{args:{tables:o},defaultShardKey:i,headers:t,tables:o}),f=d.shards.filter(h=>h.error);if(f.length>0){const h=f.map(m=>`${m.shardKey}: ${m.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(f.length)} of ${String(d.shards.length)} shard(s) — ${h}`,{code:"EXPORT_SHARD_FAILED",status:502})}return d.shards.flatMap(h=>h.rows??[])},Sn=async(e,t,n,o,a)=>{const i=o??e.listSchemaTables?.();o===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:d,shardLocalTables:f}=Vo(e,i),h=await Jo(t,n,i,f,a,e.defaultShardKey??"__root__"),m=e.exportGlobals,g=o===void 0||d.length>0;return(async function*(){yield*h,g&&m&&(yield*m({tables:d}))})()},Yo=async(e,t,n,o,a,i)=>{for await(const d of await Sn(e,t,n,o,i))a(d)},qo=new TextEncoder,Xo=1e3,Tn=10,Zo=200,Ht=8,An="lunoraBackupCron",Lt=24*1048576,jt=e=>{const t=e.slice(0,Tn).map(o=>pn(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},ea=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const a of e)n.set(a,o),o+=a.byteLength;return n},ct=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let d=0;d<Xo;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)Mr(h.key)&&h.customMetadata?.[An]===o&&a.push(h.key);if(!f.truncated||f.cursor===void 0)break;i=f.cursor}return{eligible:a.length,stale:a.toSorted((d,f)=>f.localeCompare(d)).slice(n)}},ta=async(e,t,n,o,a)=>{const{stale:i}=await ct(e,t,n,o),d=new Set(a),f=i.filter(P=>d.has(P)),h=f.slice(0,Zo),m=i.length-h.length,g=a.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:g,remaining:m};const S=[],T=[];for(let P=0;P<h.length;P+=Ht){const w=await Promise.allSettled(h.slice(P,P+Ht).map(async y=>(await e.delete(pn(y)),await e.delete(y),y)));for(const[y,b]of w.entries())b.status==="fulfilled"?S.push(b.value):T.push(h[P+y])}return S.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(S.length)}: ${jt(S)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${jt(T)}`),{deleted:S,failed:T,ignored:g,remaining:m}},na=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=at(e.backupPrefix??st),o=e.backupCron,{eligible:a,stale:i}=o===void 0?{eligible:0,stale:[]}:await ct(t,n,e.backupRetain,o);return{cron:o,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},ra=async(e,t,n,o,a)=>{const i=e.backupStore;if(!i)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!o||o.length===0)throw new c("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const d={authorization:`Bearer ${o}`,"content-type":"application/json"},f=e.backupTables;let h=0,m=0,g=[];await Yo(e,t,d,f,I=>{const E=qo.encode(`${JSON.stringify(I)}
2
2
  `);if(h+=1,m+=E.byteLength,m>Lt)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Lt)}-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});g.push(E)},n);const T=at(e.backupPrefix??st),P=new Date(a.scheduledTime).toISOString(),w=$r(T,P),y=ea(g,m);g=[];const b=Kr(await crypto.subtle.digest("SHA-256",y));await i.put(w,y,{httpMetadata:{contentType:"application/x-ndjson"},sha256:b});const A={bytes:m,createdAt:P,cron:a.cron,file:w,id:P,rows:h,scheduledTime:a.scheduledTime,sha256:b,...f?{tables:f.join(",")}:{}};await i.put(Fr(w),`${JSON.stringify(A,void 0,2)}
3
3
  `,{customMetadata:{[An]:a.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:I}=await ct(i,T,e.backupRetain,a.cron);if(I.length>0){const E=I.slice(0,Tn),L=I.length-E.length;console.info(`[lunora] backup retention: ${String(I.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${E.join(", ")}${L>0?` (+${String(L)} more)`:""}`)}}catch(I){console.warn(`[lunora] backup ${w} was written, but the retention report failed:`,I)}},oa=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const o=e.backupCron,a=e.backupRetain;if(o===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return ta(n,at(e.backupPrefix??st),a,o,t)},aa="/_lunora/admin/backup/retention",sa="/_lunora/admin/backup/prune",ia=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,a=(f,h)=>{o(f,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${h} requires a \`backupStore\` on the worker`})},i=async f=>(M(f,"GET","Backup-retention"),a(f,"retention preview"),Response.json(await na(t),{headers:{"cache-control":"no-store"}})),d=async f=>{M(f,"POST","Backup-prune"),a(f,"prune");const{confirm:h}=await n(f);if(!Array.isArray(h)||h.some(m=>typeof m!="string"))throw new c("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await oa(t,h),{headers:{"cache-control":"no-store"}})};return{[sa]:d,[aa]:i}},Mt=500,ca=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const o=e;if(typeof o.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(o.functionPath.startsWith("__lunora_relation__:")||o.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(o.args!==void 0&&(typeof o.args!="object"||o.args===null||Array.isArray(o.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(o.id!==void 0&&typeof o.id!="number")throw new c("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:o.args===void 0?{}:o.args,baselineSeq:typeof o.baselineSeq=="number"?o.baselineSeq:void 0,clientId:typeof o.clientId=="string"?o.clientId:void 0,clientSeq:typeof o.clientSeq=="number"?o.clientSeq:void 0,functionPath:o.functionPath,id:typeof o.id=="number"?o.id:t,mutationId:typeof o.mutationId=="string"?o.mutationId:void 0},shardKey:typeof o.shardKey=="string"?o.shardKey:n}},da=(e,t)=>{if(e.length>Mt)throw new c(`RPC batch exceeds the ${String(Mt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,o=new Set;for(const[a,i]of e.entries()){const{entry:d,shardKey:f}=ca(i,a,t);if(o.has(d.id))throw new c(`batch call id ${String(d.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});o.add(d.id);const h=n.get(f)??[];h.push(d),n.set(f,h)}return n},ua="/_lunora/admin/export",la="/_lunora/admin/import",ha="/_lunora/admin/sync",fa="/_lunora/admin/connector/sync",pa="/_lunora/admin/apply",ma="/_lunora/admin/export-tap/run",wa=new TextEncoder,ga=async e=>{const n=await oe(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const o=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});o.push(a)}return{tables:o}},Qe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,ya=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:a,knownTables:i,queryCoordinator:d,assertAdmin:f,resolveForwardContext:h,shardDO:m,prepareExportRows:g,streamingImport:S,syncGlobals:T}=e,P=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await ga(E),{headers:K}=await h(E,L),q=await g(K,C.tables),V=new ReadableStream({async pull(G){try{for await(const J of q)G.enqueue(wa.encode(`${JSON.stringify(J)}
4
4
  `));G.close()}catch(J){G.error(J)}}});return new Response(V,{headers:{"content-type":"application/x-ndjson"},status:200})},w=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await ne(E),K=typeof C.cursors=="object"&&C.cursors!==null?C.cursors:{},q=typeof C.epochs=="object"&&C.epochs!==null?C.epochs:{},V=typeof C.limit=="number"?C.limit:void 0,G=typeof C.globalCursor=="number"?C.globalCursor:0,J=Qe(C.tables),{headers:ae}=await h(E,L),W=J??i(),le=await d.orchestrateCdcSync(m,{cursors:K,defaultShardKey:n,epochs:q,headers:ae,limit:V,tables:W}),se=T?await T({limit:V,sinceSeq:G}):void 0;return Response.json({global:se,shards:le.shards},{status:200})},y=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await ne(E),K=Vr(C.cursor),q=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,V=Qe(C.tables),{headers:G}=await h(E,L),J=V??i(),ae=await d.orchestrateCdcSync(m,{cursors:K.s,defaultShardKey:n,headers:G,limit:q,tables:J}),W=[],le={...K.s};let se=!1;for(const ce of ae.shards)se=It(W,ce.changes??[],Yr(q))||se,le[ce.shardKey]=ce.cursor;let z=K.g;if(T){const ce=await T({limit:q,sinceSeq:K.g});se=It(W,ce.changes,q)||se,z=ce.cursor}const ie=Jr({g:z,s:le,v:1}),xe={changes:W,hasMore:se,nextCursor:ie};return Response.json(xe,{status:200})},b=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await ne(E),q=(Array.isArray(C.batches)?C.batches:[]).map(W=>W).filter(W=>W!==null&&typeof W=="object"&&typeof W.shardKey=="string"&&Array.isArray(W.changes)),V=Array.isArray(C.globalChanges)?C.globalChanges:[],{headers:G}=await h(E,L),J=await d.orchestrateApplyCdc(m,{batches:q,headers:G}),ae=V.length>0&&t?await t({changes:V}):0;return Response.json({applied:J.applied+ae,failed:J.failed,ok:J.ok},{status:200})},A=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const{headers:C}=await h(E,L),K=await S(E,C);return Response.json(K,{headers:{"content-type":"application/json"},status:K.failed.length>0?207:200})},I=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;if(f(E),a===void 0||Object.keys(a).length===0||o===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const C=await ne(E),K=typeof C.sink=="string"?C.sink:void 0,q=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,V=Qe(C.tables);if(K===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const G=a[K];if(G===void 0)throw new c(`Export-tap sink "${K}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:J}=await h(E,L),ae=V??i(),W=await zr({coordinator:d,cursorStore:o,defaultShardKey:n,headers:J,limit:q,shardDO:m,sink:G,tables:ae});return Response.json(W,{headers:{"content-type":"application/json"},status:200})};return{[pa]:b,[fa]:y,[ua]:P,[ma]:I,[la]:A,[ha]:w}},ba=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const o=n;return typeof o.table!="string"||o.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!o.doc||typeof o.doc!="object"||Array.isArray(o.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:o.table},ok:!1}:{doc:o.doc,ok:!0,table:o.table}},_a=(e,t,n,o,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:o}},Ra=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const o=[],a=[],i=new Map;let d=0,f=0;const h=e.body.getReader(),m=new TextDecoder;let g="",S=0;const T=P=>{f+=1;const w=P.trim();if(w.length===0)return;d+=1;const y=ba(w,f);if(!y.ok){o.push(y.error);return}const{doc:b,table:A}=y,I=t.resolveTableSharding?.(A);if(I?.mode.kind==="global"){a.push({doc:b,line:f,table:A});return}const E=_a(b,A,I,n,f);if(!E.ok){o.push(E.error);return}const L=i.get(E.shardKey);L?L.rows.push({doc:b,table:A}):i.set(E.shardKey,{rows:[{doc:b,table:A}],shardKey:E.shardKey,startLine:f})};for(;;){const{done:P,value:w}=await h.read();if(P)break;if(w&&(S+=w.byteLength,S>ln))throw await h.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});g+=m.decode(w,{stream:!0});let y=g.indexOf(`
@@ -0,0 +1 @@
1
+ import{redactArgs as h,redactCredentials as b}from"@lunora/observability";import{S as y,n as O}from"./observability-sinks-lLKqc_rV.mjs";const f=t=>{try{t()}catch{}},u=(t,n)=>{const r={};for(const o of y)t[o]!==void 0&&(r[o]=t[o]);return t.flush&&(r.flush=o=>{f(()=>t.flush?.(o))}),t.onLog&&(r.onLog=(o,e)=>{const c=n.log===void 0?o:n.log(o);c!==void 0&&f(()=>t.onLog?.(c,e))}),t.onMetric&&(r.onMetric=(o,e)=>{const c=n.metric===void 0?o:n.metric(o);c!==void 0&&f(()=>t.onMetric?.(c,e))}),t.onRpc&&(r.onRpc=(o,e)=>{const c=n.rpc===void 0?o:n.rpc(o);c!==void 0&&f(()=>t.onRpc?.(c,e))}),t.onSpan&&(r.onSpan=(o,e)=>{const c=n.span===void 0?o:n.span(o);c!==void 0&&f(()=>t.onSpan?.(c,e))}),r},l=5;let a=0;const S=t=>{if(a>=l)return;a+=1;const n=a===l?" Further enricher failures are silenced until the isolate restarts.":"";try{console.error(`[lunora:observability] enrichSink's enricher threw; delivering the event without its extra attributes.${n}`,t instanceof Error?t.name:typeof t)}catch{}},j=(t,n)=>{if(t instanceof Error)return n({...Object.fromEntries(Object.entries(t)),message:t.message,name:t.name});const r=Reflect.get(t,"toJSON");if(typeof r=="function"){const e=r.call(t);return e!==t?n(e):Object.fromEntries(Object.entries(t).map(([c,s])=>[c,n(s)]))}if(Array.isArray(t))return t.map(e=>n(e));const o=Object.getPrototypeOf(t);return o!==Object.prototype&&o!==null?t:Object.fromEntries(Object.entries(t).map(([e,c])=>[e,n(c)]))},x=()=>({ancestors:new WeakSet,copies:new WeakMap}),g=(t,n=x())=>{if(typeof t=="symbol"||typeof t=="function")return String(t);if(typeof t!="object"||t===null)return t;if(!n.ancestors.has(t)){if(n.copies.has(t))return n.copies.get(t);n.ancestors.add(t);try{const r=j(t,o=>g(o,n));return n.copies.set(t,r),r}finally{n.ancestors.delete(t)}}},d=(t,n,r)=>{try{const o=t(g(n),r),e=o===void 0?void 0:Object.fromEntries(Object.entries(o).filter(([,i])=>i!==void 0)),c=e===void 0?void 0:g(e),s=r==="log"?h(c):b(c);return O(s)}catch(o){S(o);return}},A=(t,n)=>u(t,{log:r=>{const o=d(n,r,"log");return o===void 0?r:{...r,fields:{...o,...r.fields}}},metric:r=>{const o=d(n,r,"metric");return o===void 0?r:{...r,attributes:{...o,...r.attributes}}},rpc:r=>{const o=d(n,r,"rpc");return o===void 0?r:{...r,attributes:{...o,...r.attributes}}},span:r=>{const o=d(n,r,"span");return o===void 0?r:{...r,attributes:{...o,...r.attributes}}}}),m=(t,n)=>{const r=t.split("*");if(r.length===1)return n===t;const o=r[0]??"",e=r.at(-1)??"";if(n.length<o.length+e.length||!n.startsWith(o)||!n.endsWith(e))return!1;const c=n.length-e.length;let s=o.length;for(const i of r.slice(1,-1)){const p=n.indexOf(i,s);if(p===-1||p+i.length>c)return!1;s=p+i.length}return s<=c},E=(t,n)=>n.exclude?.some(r=>m(r,t))?!1:n.include===void 0||n.include.length===0||n.include.some(r=>m(r,t)),L=(t,n)=>{const r=o=>E(o.functionPath,n)?o:void 0;return u(t,{log:r,metric:r,rpc:r,span:r})};export{A as enrichSink,L as filterSink,m as globMatch};
@@ -0,0 +1,4 @@
1
+ import{LunoraError as Z}from"@lunora/errors";import{redactCredentials as Q,redactArgs as N}from"@lunora/observability";import{stableStringify as v}from"@lunora/wire";import{e as c,L as m,c as H,o as j,f as I,O as z,g as rr,h as J,w as tr,i as or,j as sr,m as er}from"./otlp-resource-Ch_8_U0e.mjs";import{t as ar}from"./error-detail-C46mdOTW.mjs";const nr=r=>{if(typeof r=="string")return r;if(r instanceof Error)return String(r);try{return JSON.stringify(r)??String(r)}catch{return String(r)}},R=r=>typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:nr(r),ir=(r,s,t)=>{Object.defineProperty(r,s,{configurable:!0,enumerable:!0,value:t,writable:!0})},Dr=(r,s)=>{if(r===void 0&&s===void 0)return;const t={};if(r!==void 0)for(const[o,e]of Object.entries(r))ir(t,o,R(e));return Object.keys(t).length===0?void 0:t},cr=512,dr=200,ur=r=>{const s=r.maxItems??cr,t=r.maxDelayMs??dr;let o=[],e,i,a;const p=()=>{e!==void 0&&(clearTimeout(e),e=void 0)},g=async()=>{p();const l=o;o=[];const d=a;i=void 0,a=void 0;try{l.length>0&&await r.export(l)}catch{}finally{d?.()}},h=l=>{i===void 0&&(i=new Promise(d=>{a=d}),e=setTimeout(()=>{g()},t)),l?.(i)};return{add:(l,d)=>{for(o.push(l);o.length>s;)o.shift();h(d),o.length>=s&&g()},flush:async l=>{if(o.length===0){p();return}const d=g();return l?.(d),d},get size(){return o.length}}},lr=1,pr=0,fr=new Set(["cloudflare.ray_id","error.type","http.request.method","http.response.status_code","http.route","lunora.error_status","lunora.fanout.failed","lunora.fanout.shards","lunora.fanout.table","lunora.function_path","lunora.ok","lunora.shard_key","server.address","server.port","url.path","url.scheme","user_agent.original"]),mr={errorType:m.errorType,functionPath:m.functionPath,rayId:m.rayId,shardKey:m.shardKey,userId:m.userId},hr=r=>{const s=ar(r);return s===void 0?[]:[c("lunora.error.internal",JSON.stringify(Q(s)))]},G=(r,s,t,o)=>[c("exception.type",r),c("exception.message",s),...t===void 0?[]:[c("exception.stacktrace",t)],...o===void 0?[]:hr(o)],gr=(r,s)=>{const t=[c(m.functionPath,r.functionPath),c(m.ok,r.ok)];if(r.method!==void 0&&t.push(c("http.request.method",r.method)),r.path!==void 0&&t.push(c("url.path",r.path)),t.push(c("http.route",r.functionPath)),r.scheme!==void 0&&t.push(c("url.scheme",r.scheme)),r.host!==void 0&&t.push(c("server.address",r.host)),r.port!==void 0&&t.push(c("server.port",r.port)),r.userAgent!==void 0&&t.push(c("user_agent.original",r.userAgent)),r.shardKey!==void 0&&t.push(c(m.shardKey,r.shardKey)),r.rayId!==void 0&&t.push(c(m.rayId,r.rayId)),t.push(c("http.response.status_code",r.error?.status??200)),r.error&&t.push(c(m.errorType,r.error.code),c("lunora.error_status",r.error.status)),r.fanOut&&t.push(c("lunora.fanout.table",r.fanOut.table),c("lunora.fanout.shards",r.fanOut.shards),c("lunora.fanout.failed",r.fanOut.failed)),r.attributes!==void 0){const e=new Set([...fr,...t.map(a=>a.key)]),i=H(Object.fromEntries(Object.entries(r.attributes).map(([a,p])=>[a,R(p)])));t.push(...i.filter(a=>!e.has(a.key)))}const o={attributes:t,endTimeUnixNano:I(s),kind:z.server,name:r.functionPath,...r.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},spanId:r.spanId??j(8),startTimeUnixNano:I(s-r.durationMs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId??j(16)};return r.traceFlags!==void 0&&(o.flags=r.traceFlags),r.error&&(o.events=[{attributes:G(r.error.code,r.error.message,r.error.stack,r.error.internal),name:"exception",timeUnixNano:I(s)}]),o},x=(r,s)=>{const t=new Map,o=new Set(Object.keys(r).map(e=>mr[e]));for(const[e,i]of Object.entries(s??{}))o.has(e)||t.set(e,c(e,R(i)));return t.set(m.functionPath,c(m.functionPath,r.functionPath)),r.shardKey!==void 0&&t.set(m.shardKey,c(m.shardKey,r.shardKey)),r.userId!==void 0&&t.set(m.userId,c(m.userId,r.userId)),r.rayId!==void 0&&t.set(m.rayId,c(m.rayId,r.rayId)),r.errorType!==void 0&&t.set(m.errorType,c(m.errorType,r.errorType)),[...t.values()]},yr=r=>{const s={attributes:x({errorType:r.error?.type,functionPath:r.functionPath,rayId:r.rayId,shardKey:r.shardKey,userId:r.userId},r.attributes),endTimeUnixNano:I(r.startTs+r.durationMs),flags:r.sampled===!1?pr:lr,kind:z[r.kind??"internal"],name:r.name,parentSpanId:r.parentSpanId,spanId:r.spanId,startTimeUnixNano:I(r.startTs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId},t=o=>H(Object.fromEntries(Object.entries(o??{}).map(([e,i])=>[e,R(i)])));return r.events!==void 0&&r.events.length>0&&(s.events=r.events.map(o=>({attributes:t(o.attributes),name:o.name,timeUnixNano:I(o.ts)}))),r.links!==void 0&&r.links.length>0&&(s.links=r.links.map(o=>({attributes:t(o.attributes),spanId:o.spanId,traceId:o.traceId}))),s},br=r=>{const s=I(r.ts),t=x({functionPath:r.functionPath,shardKey:r.shardKey},r.attributes),o=r.traceId===void 0?void 0:[{asDouble:r.value,timeUnixNano:s,traceId:r.traceId}],e={asDouble:r.value,attributes:t,...o===void 0?{}:{exemplars:o},timeUnixNano:s};return r.kind==="gauge"?{gauge:{dataPoints:[e]},name:r.name}:r.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:t,bucketCounts:["1"],count:"1",...o===void 0?{}:{exemplars:o},explicitBounds:[],max:r.value,min:r.value,sum:r.value,timeUnixNano:s}]},name:r.name}:{name:r.name,sum:{aggregationTemporality:1,dataPoints:[e],isMonotonic:!0}}},kr=r=>{const s={attributes:x({functionPath:r.functionPath,rayId:r.rayId,shardKey:r.shardKey,userId:r.userId},r.fields),body:{stringValue:r.message},severityNumber:rr[r.level],severityText:r.level.toUpperCase(),timeUnixNano:I(r.ts)};if(r.traceId!==void 0&&(s.traceId=r.traceId),r.spanId!==void 0&&(s.spanId=r.spanId),r.error!==void 0){const t=G(r.error.name,r.error.message,r.error.stack,r.error.internal),o=new Set(t.map(e=>e.key));s.attributes=[...s.attributes.filter(e=>!o.has(e.key)),...t]}return r.eventName!==void 0&&(s.eventName=r.eventName,s.attributes=[...s.attributes.filter(t=>t.key!=="event.name"),c("event.name",r.eventName)]),s},Ir=1024,B=5;let _=0;const Sr=(r,s)=>{if(_>=B)return;_+=1;let t;try{t=new URL(r).host}catch{t="<unparseable endpoint>"}const o=_===B?" Further OTLP rejections are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] collector ${t} rejected the export with HTTP ${String(s)}; the batch is DROPPED (there is no retry).${o}`)},Tr=async r=>{const s=new Blob([r]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(s).arrayBuffer()},W=async(r,s,t,o)=>{try{const e=JSON.stringify(s),{byteLength:i}=new TextEncoder().encode(e),a=(i<Ir?fetch(r,{body:e,headers:t,method:"POST"}):Tr(e).then(p=>fetch(r,{body:p,headers:{...t,"content-encoding":"gzip"},method:"POST"}))).then(p=>{p.ok||Sr(r,p.status)},()=>{});o?.(a),await a}catch{}},Pr=(r,s,t,o)=>{W(r,s,t,o?.waitUntil).catch(()=>{})},E=(r,s)=>s===!0&&r.ok,wr=r=>r.kind==="metric"?void 0:r.event.traceId,Or=r=>{const s=Map.groupBy(r,o=>wr(o)),t=s.get(void 0)??[];return s.delete(void 0),{byTrace:s,untraced:t}},C=5,Er=(r,s,t)=>{if(s===void 0)return r;const{byTrace:o,untraced:e}=Or(r),i=[...e];let a=0,p;for(const[g,h]of o){let l;try{l=s({logs:h.filter(d=>d.kind==="log").map(d=>d.event),rpc:h.filter(d=>d.kind==="rpc").map(d=>d.event),spans:h.filter(d=>d.kind==="span").map(d=>d.event),traceId:g})}catch(d){a+=1,a===1&&(p=d),l=!0}l&&i.push(...h)}return a>0&&t(p,a),i},w=(r,s)=>{let t;try{t=s===void 0?r:s(r)}catch{t=void 0}return t??void 0},Lr=r=>{const s=N(r.message);if(r.stack===void 0)return{...r,message:s};const t=`: ${r.message}`,o=r.stack.indexOf(t),i=r.message!==""&&o!==-1&&!r.stack.slice(0,o).includes(`
2
+ `)?r.stack.slice(o+t.length):r.stack.split(`
3
+ `).filter(a=>a.trimStart().startsWith("at ")).map(a=>`
4
+ ${a}`).join("");return{...r,message:s,stack:`${r.name}: ${s}${i}`}},Rr=r=>({...r,...r.error===void 0?{}:{error:Lr(r.error)},...r.fields===void 0?{}:{fields:N(r.fields)},message:N(r.message)}),V=(r,s,t)=>{if(r.kind==="rpc"){const e=w(r.event,s?.rpc);return e===void 0?void 0:{bucket:"spans",encoded:gr(e,r.endMs)}}if(r.kind==="span"){const e=w(r.event,s?.span);return e===void 0?void 0:{bucket:"spans",encoded:yr(e)}}if(r.kind==="log"){const e=w(t?Rr(r.event):r.event,s?.log);return e===void 0?void 0:{bucket:"logs",encoded:kr(e)}}const o=w(r.event,s?.metric);return o===void 0?void 0:{bucket:"metrics",encoded:br(o)}},Ar=["fuseCloudflareTraces","instrumentDatabase","metricHistory","traceFetch"],Fr=(r={})=>{const{onlyErrors:s}=r;return{onLog:t=>{t.level==="error"||t.level==="fatal"?console.error("[lunora:log]",t.functionPath,t.message):console.log("[lunora:log]",t.functionPath,t.message)},onMetric:t=>{console.log("[lunora:metric]",`${t.name}=${String(t.value)}`,t.kind,t.functionPath)},onRpc:t=>{E(t,s)||(t.ok?console.log("[lunora:rpc]",t):console.error("[lunora:rpc]",t))},onSpan:t=>{const o=t.ok?"ok":`error ${t.error?.type??""}`.trim();console.log("[lunora:span]",t.name,`${String(t.durationMs)}ms`,o,t.functionPath)}}},Kr=r=>{const{headers:s,onlyErrors:t,transform:o,transformLog:e,url:i}=r,a=J({"content-type":"application/json"},s),p=(g,h)=>{try{const l=fetch(i,{body:JSON.stringify(g),headers:a,method:"POST"}).catch(()=>{});h?.waitUntil&&h.waitUntil(l)}catch{}};return{onLog:(g,h)=>{const l=w(g,e);l!==void 0&&p(l,h)},onRpc:(g,h)=>{if(E(g,t))return;const l=w(g,o);l!==void 0&&p(l,h)}}},$r=r=>{const{dataset:s,onlyErrors:t}=r;return{onRpc:o=>{if(!E(o,t))try{s.writeDataPoint({blobs:[o.functionPath,o.ok?"ok":"error",o.shardKey??"",o.error?.code??"",o.fanOut?.table??""],doubles:[o.durationMs,o.ok?0:1,o.fanOut?.shards??0,o.fanOut?.failed??0],indexes:[o.functionPath]})}catch{}}}},jr=r=>{const{pipeline:s,serializeFields:t}=r;return{onLog:(o,e)=>{try{const i={functionPath:o.functionPath,level:o.level,message:o.message,ts:o.ts};o.fields&&(i.fields=t===!0?JSON.stringify(o.fields):o.fields);for(const p of["shardKey","userId","traceId","spanId"])o[p]!==void 0&&(i[p]=o[p]);const a=s.send([i]).catch(()=>{});e?.waitUntil&&e.waitUntil(a)}catch{}}}},Br=r=>{const{batch:s,deploymentEnvironment:t,detectResources:o,endpoint:e,headers:i,onlyErrors:a,postProcessor:p,resourceAttributes:g,serviceNamespace:h,serviceVersion:l,tailSampler:d,token:X}=r,M=r.serviceName??"lunora",U=r.redactLogs??!0;if(s!==!1&&s?.maxItems!==void 0&&(!Number.isInteger(s.maxItems)||s.maxItems<1))throw new Z("ENV_INVALID",`otlpSink: \`batch.maxItems\` must be a positive integer, received ${String(s.maxItems)}.`);const D={...l===void 0?{}:{"service.version":l},...h===void 0?{}:{"service.namespace":h},...t===void 0?{}:{"deployment.environment":t},...g},F=new WeakMap,k=u=>{if(o!==!0||u?.resourceAttributes===void 0)return D;const n=F.get(u);if(n!==void 0)return n;const f=er(u.resourceAttributes(),D);return F.set(u,f),f};let S=e;for(;S.endsWith("/");)S=S.slice(0,-1);const K={logs:{url:`${S}/v1/logs`,wrap:sr},metrics:{url:`${S}/v1/metrics`,wrap:or},spans:{url:`${S}/v1/traces`,wrap:tr}},$=J({"content-type":"application/json"},i,X);let A=0;const Y=(u,n)=>{if(A>=C)return;A+=1;const f=A===C?" Further tailSampler failures from this sink are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] tailSampler threw for ${String(n)} trace(s) in this flush window; keeping them (fail-open), so the sampling policy did NOT apply.${f}`,u)},q=async u=>{const n=Er(u,d,Y),f=new Map;for(const y of n){const b=V(y,p,U);if(b===void 0)continue;const L=v(y.resource);let P=f.get(L);P===void 0&&(P={logs:[],metrics:[],resource:y.resource,spans:[]},f.set(L,P)),P[b.bucket].push(b.encoded)}const T=[];for(const[,y]of f)for(const b of["spans","logs","metrics"])if(y[b].length>0){const{url:L,wrap:P}=K[b];T.push(W(L,P(y[b],"@lunora/runtime",M,y.resource),$))}await Promise.all(T)};if(s===!1){const u=(n,f)=>{const T=V(n,p,U);if(T!==void 0){const{url:y,wrap:b}=K[T.bucket];Pr(y,b(T.encoded,"@lunora/runtime",M,n.resource),$,f)}};return{onLog:(n,f)=>{u({event:n,kind:"log",resource:k(f)},f)},onMetric:(n,f)=>{u({event:n,kind:"metric",resource:k(f)},f)},onRpc:(n,f)=>{E(n,a)||u({endMs:Date.now(),event:n,kind:"rpc",resource:k(f)},f)},onSpan:(n,f)=>{u({event:n,kind:"span",resource:k(f)},f)}}}const O=ur({export:q,...s?.maxDelayMs===void 0?{}:{maxDelayMs:s.maxDelayMs},...s?.maxItems===void 0?{}:{maxItems:s.maxItems}});return{flush:u=>{O.flush(u?.waitUntil).catch(()=>{})},onLog:(u,n)=>{O.add({event:u,kind:"log",resource:k(n)},n?.waitUntil)},onMetric:(u,n)=>{O.add({event:u,kind:"metric",resource:k(n)},n?.waitUntil)},onRpc:(u,n)=>{E(u,a)||O.add({endMs:Date.now(),event:u,kind:"rpc",resource:k(n)},n?.waitUntil)},onSpan:(u,n)=>{O.add({event:u,kind:"span",resource:k(n)},n?.waitUntil)}}},Cr=(...r)=>{const s=(o,e)=>{for(const i of r){const a=i[o];if(a)try{a.apply(i,e)}catch{}}},t={};for(const o of r)for(const e of Ar)t[e]===void 0&&o[e]!==void 0&&(t[e]=o[e]);return{...t,flush:o=>{s("flush",[o])},onLog:(o,e)=>{s("onLog",[o,e])},onMetric:(o,e)=>{s("onMetric",[o,e])},onRpc:(o,e)=>{s("onRpc",[o,e])},onSpan:(o,e)=>{s("onSpan",[o,e])}}};export{Ar as S,$r as a,Fr as b,Cr as c,Dr as n,Br as o,jr as p,Kr as w};
@@ -1 +1 @@
1
- const R={debug:5,error:17,fatal:21,info:9,log:9,trace:1,warn:13},N=e=>`${String(Math.round(e))}000000`,A=Array.from({length:256},(e,r)=>r.toString(16).padStart(2,"0")),l=512,O=new Uint8Array(l);let a=l;const m=(e,r,t)=>{let o="";for(let n=0;n<t;n+=1)o+=A[e[r+n]];return o},T=e=>{if(e>l){const t=new Uint8Array(e);return crypto.getRandomValues(t),m(t,0,e)}a+e>l&&(crypto.getRandomValues(O),a=0);const r=m(O,a,e);return a+=e,r},u=/^[0-9a-f]+$/,S=(e,r,t=!0)=>`00-${e}-${r}-${t?"01":"00"}`,I=e=>{if(e==null)return;const r=e.split("-"),[t,o,n,s]=r;if(!(r.length<4||t===void 0||t.length!==2||!u.test(t)||t==="ff"||t==="00"&&r.length!==4||o===void 0||n===void 0||s===void 0||s.length!==2||!u.test(s)||o.length!==32||n.length!==16||!u.test(o)||!u.test(n)||o==="00000000000000000000000000000000"||n==="0000000000000000"))return{parentSpanId:n,sampled:(Number.parseInt(s,16)&1)===1,traceId:o}},_=(e,r)=>typeof r=="boolean"?{key:e,value:{boolValue:r}}:typeof r=="number"?Number.isFinite(r)?Number.isSafeInteger(r)?{key:e,value:{intValue:String(r)}}:{key:e,value:{doubleValue:r}}:{key:e,value:{stringValue:String(r)}}:{key:e,value:{stringValue:r}},b=e=>e===void 0?[]:Object.entries(e).map(([r,t])=>_(r,t)),h=(e,r,t)=>{const o={},n=new Map,s=(c,i)=>{const g=c.toLowerCase(),v=n.get(g);v===void 0?(n.set(g,c),o[c]=i):o[v]=i};for(const[c,i]of Object.entries(e))s(c,i);for(const[c,i]of Object.entries(r??{}))s(c,i);return t!==void 0&&t.length>0&&s("authorization",`Bearer ${t}`),o},f=e=>Array.isArray(e)?e:[e],C={client:3,consumer:5,internal:1,producer:4,server:2},L=Object.freeze({durationMs:"lunora.duration_ms",errorMessage:"error.message",errorType:"error.type",functionPath:"lunora.function_path",ok:"lunora.ok",rayId:"cloudflare.ray_id",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),p=(e,r)=>{const t={"service.name":e};for(const[o,n]of Object.entries(r??{}))t[o]=n;return Object.entries(t).map(([o,n])=>_(o,n))},V=(e,r,t,o)=>({resourceSpans:[{resource:{attributes:p(t,o)},scopeSpans:[{scope:{name:r},spans:f(e)}]}]}),M=(e,r,t,o)=>({resourceLogs:[{resource:{attributes:p(t,o)},scopeLogs:[{logRecords:f(e),scope:{name:r}}]}]}),y=(e,r,t,o)=>({resourceMetrics:[{resource:{attributes:p(t,o)},scopeMetrics:[{metrics:f(e),scope:{name:r}}]}]}),E="CF_VERSION_METADATA",d=(e,r)=>{if(typeof e!="object"||e===null)return;const t=e[r];return typeof t=="string"&&t.length>0?t:void 0},w=e=>r=>{const t=e?.[r];if(typeof t=="string")return t.length>0?t:void 0;if(r===E)return d(t,"tag")??d(t,"id")},D=e=>{const r={},t=e("SERVICE_VERSION")??e("CF_VERSION_METADATA")??e("VERCEL_GIT_COMMIT_SHA")??e("GITHUB_SHA")??e("COMMIT_SHA");t!==void 0&&(r["service.version"]=t);const o=e("DEPLOYMENT_ENVIRONMENT")??e("ENVIRONMENT")??e("NODE_ENV");return o!==void 0&&(r["deployment.environment"]=o),r},x=(e,r)=>{if(!(r!==void 0||e("CLOUDFLARE")!==void 0||e("CF_ACCOUNT_ID")!==void 0))return{};const o={"cloud.provider":"cloudflare"},n=d(r,"colo")??e("CF_COLO")??e("CLOUDFLARE_COLO");return n!==void 0&&(o["cloud.region"]=n),o},F=(...e)=>{const r={};for(const t of e)if(t!==void 0)for(const[o,n]of Object.entries(t))r[o]=n;return r};export{L,C as O,D as a,S as b,N as c,x as d,_ as e,R as f,b as g,h,y as i,M as j,F as m,T as o,I as p,w as r,V as w};
1
+ const R={debug:5,error:17,fatal:21,info:9,log:9,trace:1,warn:13},N=e=>`${String(Math.round(e))}000000`,A=Array.from({length:256},(e,r)=>r.toString(16).padStart(2,"0")),l=512,O=new Uint8Array(l);let a=l;const m=(e,r,t)=>{let o="";for(let n=0;n<t;n+=1)o+=A[e[r+n]];return o},T=e=>{if(e>l){const t=new Uint8Array(e);return crypto.getRandomValues(t),m(t,0,e)}a+e>l&&(crypto.getRandomValues(O),a=0);const r=m(O,a,e);return a+=e,r},u=/^[0-9a-f]+$/,S=(e,r,t=!0)=>`00-${e}-${r}-${t?"01":"00"}`,I=e=>{if(e==null)return;const r=e.split("-"),[t,o,n,s]=r;if(!(r.length<4||t===void 0||t.length!==2||!u.test(t)||t==="ff"||t==="00"&&r.length!==4||o===void 0||n===void 0||s===void 0||s.length!==2||!u.test(s)||o.length!==32||n.length!==16||!u.test(o)||!u.test(n)||o==="00000000000000000000000000000000"||n==="0000000000000000"))return{parentSpanId:n,sampled:(Number.parseInt(s,16)&1)===1,traceId:o}},_=(e,r)=>typeof r=="boolean"?{key:e,value:{boolValue:r}}:typeof r=="number"?Number.isFinite(r)?Number.isSafeInteger(r)?{key:e,value:{intValue:String(r)}}:{key:e,value:{doubleValue:r}}:{key:e,value:{stringValue:String(r)}}:{key:e,value:{stringValue:r}},b=e=>e===void 0?[]:Object.entries(e).map(([r,t])=>_(r,t)),h=(e,r,t)=>{const o={},n=new Map,s=(c,i)=>{const g=c.toLowerCase(),v=n.get(g);v===void 0?(n.set(g,c),o[c]=i):o[v]=i};for(const[c,i]of Object.entries(e))s(c,i);for(const[c,i]of Object.entries(r??{}))s(c,i);return t!==void 0&&t.length>0&&s("authorization",`Bearer ${t}`),o},f=e=>Array.isArray(e)?e:[e],C={client:3,consumer:5,internal:1,producer:4,server:2},L=Object.freeze({durationMs:"lunora.duration_ms",errorMessage:"error.message",errorType:"error.type",functionPath:"lunora.function_path",ok:"lunora.ok",rayId:"cloudflare.ray_id",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),p=(e,r)=>{const t={"service.name":e};for(const[o,n]of Object.entries(r??{}))t[o]=n;return Object.entries(t).map(([o,n])=>_(o,n))},V=(e,r,t,o)=>({resourceSpans:[{resource:{attributes:p(t,o)},scopeSpans:[{scope:{name:r},spans:f(e)}]}]}),M=(e,r,t,o)=>({resourceLogs:[{resource:{attributes:p(t,o)},scopeLogs:[{logRecords:f(e),scope:{name:r}}]}]}),y=(e,r,t,o)=>({resourceMetrics:[{resource:{attributes:p(t,o)},scopeMetrics:[{metrics:f(e),scope:{name:r}}]}]}),E="CF_VERSION_METADATA",d=(e,r)=>{if(typeof e!="object"||e===null)return;const t=e[r];return typeof t=="string"&&t.length>0?t:void 0},w=e=>r=>{const t=e?.[r];if(typeof t=="string")return t.length>0?t:void 0;if(r===E)return d(t,"tag")??d(t,"id")},D=e=>{const r={},t=e("SERVICE_VERSION")??e("CF_VERSION_METADATA")??e("VERCEL_GIT_COMMIT_SHA")??e("GITHUB_SHA")??e("COMMIT_SHA");t!==void 0&&(r["service.version"]=t);const o=e("DEPLOYMENT_ENVIRONMENT")??e("ENVIRONMENT")??e("NODE_ENV");return o!==void 0&&(r["deployment.environment"]=o),r},x=(e,r)=>{if(!(r!==void 0||e("CLOUDFLARE")!==void 0||e("CF_ACCOUNT_ID")!==void 0))return{};const o={"cloud.provider":"cloudflare"},n=d(r,"colo")??e("CF_COLO")??e("CLOUDFLARE_COLO");return n!==void 0&&(o["cloud.region"]=n),o},F=(...e)=>{const r={};for(const t of e)if(t!==void 0)for(const[o,n]of Object.entries(t))r[o]=n;return r};export{L,C as O,D as a,S as b,b as c,x as d,_ as e,N as f,R as g,h,y as i,M as j,F as m,T as o,I as p,w as r,V as w};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.222",
3
+ "version": "1.0.0-alpha.223",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1,4 +0,0 @@
1
- import{LunoraError as q}from"@lunora/errors";import{redactCredentials as Z,redactArgs as x}from"@lunora/observability";import{stableStringify as Q}from"@lunora/wire";import{e as i,L as h,o as K,c as b,O as H,f as v,g as rr,h as V,w as tr,i as or,j as sr,m as er}from"./otlp-resource-BwFJnvwB.mjs";import{t as ar}from"./error-detail-C46mdOTW.mjs";const ir=r=>{if(typeof r=="string")return r;if(r instanceof Error)return String(r);try{return JSON.stringify(r)??String(r)}catch{return String(r)}},z=r=>typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:ir(r),nr=512,cr=200,dr=r=>{const s=r.maxItems??nr,o=r.maxDelayMs??cr;let t=[],e,c,n;const f=()=>{e!==void 0&&(clearTimeout(e),e=void 0)},g=async()=>{f();const l=t;t=[];const d=n;c=void 0,n=void 0;try{l.length>0&&await r.export(l)}catch{}finally{d?.()}},m=l=>{c===void 0&&(c=new Promise(d=>{n=d}),e=setTimeout(()=>{g()},o)),l?.(c)};return{add:(l,d)=>{for(t.push(l);t.length>s;)t.shift();m(d),t.length>=s&&g()},flush:async l=>{if(t.length===0){f();return}const d=g();return l?.(d),d},get size(){return t.length}}},ur=1,lr=0,pr=r=>{const s=ar(r);return s===void 0?[]:[i("lunora.error.internal",JSON.stringify(Z(s)))]},J=(r,s,o,t)=>[i("exception.type",r),i("exception.message",s),...o===void 0?[]:[i("exception.stacktrace",o)],...t===void 0?[]:pr(t)],fr=(r,s)=>{const o=[i(h.functionPath,r.functionPath),i(h.ok,r.ok)];r.method!==void 0&&o.push(i("http.request.method",r.method)),r.path!==void 0&&o.push(i("url.path",r.path)),o.push(i("http.route",r.functionPath)),r.scheme!==void 0&&o.push(i("url.scheme",r.scheme)),r.host!==void 0&&o.push(i("server.address",r.host)),r.port!==void 0&&o.push(i("server.port",r.port)),r.userAgent!==void 0&&o.push(i("user_agent.original",r.userAgent)),r.shardKey!==void 0&&o.push(i(h.shardKey,r.shardKey)),r.rayId!==void 0&&o.push(i(h.rayId,r.rayId)),o.push(i("http.response.status_code",r.error?.status??200)),r.error&&o.push(i(h.errorType,r.error.code),i("lunora.error_status",r.error.status)),r.fanOut&&o.push(i("lunora.fanout.table",r.fanOut.table),i("lunora.fanout.shards",r.fanOut.shards),i("lunora.fanout.failed",r.fanOut.failed));const t={attributes:o,endTimeUnixNano:b(s),kind:H.server,name:r.functionPath,...r.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},spanId:r.spanId??K(8),startTimeUnixNano:b(s-r.durationMs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId??K(16)};return r.traceFlags!==void 0&&(t.flags=r.traceFlags),r.error&&(t.events=[{attributes:J(r.error.code,r.error.message,r.error.stack,r.error.internal),name:"exception",timeUnixNano:b(s)}]),t},N=(r,s)=>{const o=new Map([[h.functionPath,i(h.functionPath,r.functionPath)]]);r.shardKey!==void 0&&o.set(h.shardKey,i(h.shardKey,r.shardKey)),r.userId!==void 0&&o.set(h.userId,i(h.userId,r.userId)),r.rayId!==void 0&&o.set(h.rayId,i(h.rayId,r.rayId)),r.errorType!==void 0&&o.set(h.errorType,i(h.errorType,r.errorType));for(const[t,e]of Object.entries(s??{}))o.set(t,i(t,z(e)));return[...o.values()]},mr=r=>{const s={attributes:N({errorType:r.error?.type,functionPath:r.functionPath,rayId:r.rayId,shardKey:r.shardKey,userId:r.userId},r.attributes),endTimeUnixNano:b(r.startTs+r.durationMs),flags:r.sampled===!1?lr:ur,kind:H[r.kind??"internal"],name:r.name,parentSpanId:r.parentSpanId,spanId:r.spanId,startTimeUnixNano:b(r.startTs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId},o=t=>rr(Object.fromEntries(Object.entries(t??{}).map(([e,c])=>[e,z(c)])));return r.events!==void 0&&r.events.length>0&&(s.events=r.events.map(t=>({attributes:o(t.attributes),name:t.name,timeUnixNano:b(t.ts)}))),r.links!==void 0&&r.links.length>0&&(s.links=r.links.map(t=>({attributes:o(t.attributes),spanId:t.spanId,traceId:t.traceId}))),s},hr=r=>{const s=b(r.ts),o=N({functionPath:r.functionPath,shardKey:r.shardKey},r.attributes),t=r.traceId===void 0?void 0:[{asDouble:r.value,timeUnixNano:s,traceId:r.traceId}],e={asDouble:r.value,attributes:o,...t===void 0?{}:{exemplars:t},timeUnixNano:s};return r.kind==="gauge"?{gauge:{dataPoints:[e]},name:r.name}:r.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:o,bucketCounts:["1"],count:"1",...t===void 0?{}:{exemplars:t},explicitBounds:[],max:r.value,min:r.value,sum:r.value,timeUnixNano:s}]},name:r.name}:{name:r.name,sum:{aggregationTemporality:1,dataPoints:[e],isMonotonic:!0}}},gr=r=>{const s={attributes:N({functionPath:r.functionPath,rayId:r.rayId,shardKey:r.shardKey,userId:r.userId},r.fields),body:{stringValue:r.message},severityNumber:v[r.level],severityText:r.level.toUpperCase(),timeUnixNano:b(r.ts)};if(r.traceId!==void 0&&(s.traceId=r.traceId),r.spanId!==void 0&&(s.spanId=r.spanId),r.error!==void 0){const o=J(r.error.name,r.error.message,r.error.stack,r.error.internal),t=new Set(o.map(e=>e.key));s.attributes=[...s.attributes.filter(e=>!t.has(e.key)),...o]}return r.eventName!==void 0&&(s.eventName=r.eventName,s.attributes.push(i("event.name",r.eventName))),s},yr=1024,j=5;let R=0;const kr=(r,s)=>{if(R>=j)return;R+=1;let o;try{o=new URL(r).host}catch{o="<unparseable endpoint>"}const t=R===j?" Further OTLP rejections are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] collector ${o} rejected the export with HTTP ${String(s)}; the batch is DROPPED (there is no retry).${t}`)},Ir=async r=>{const s=new Blob([r]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(s).arrayBuffer()},G=async(r,s,o,t)=>{try{const e=JSON.stringify(s),{byteLength:c}=new TextEncoder().encode(e),n=(c<yr?fetch(r,{body:e,headers:o,method:"POST"}):Ir(e).then(f=>fetch(r,{body:f,headers:{...o,"content-encoding":"gzip"},method:"POST"}))).then(f=>{f.ok||kr(r,f.status)},()=>{});t?.(n),await n}catch{}},br=(r,s,o,t)=>{G(r,s,o,t?.waitUntil).catch(()=>{})},O=(r,s)=>s===!0&&r.ok,Sr=r=>r.kind==="metric"?void 0:r.event.traceId,Tr=r=>{const s=Map.groupBy(r,t=>Sr(t)),o=s.get(void 0)??[];return s.delete(void 0),{byTrace:s,untraced:o}},B=5,Pr=(r,s,o)=>{if(s===void 0)return r;const{byTrace:t,untraced:e}=Tr(r),c=[...e];let n=0,f;for(const[g,m]of t){let l;try{l=s({logs:m.filter(d=>d.kind==="log").map(d=>d.event),rpc:m.filter(d=>d.kind==="rpc").map(d=>d.event),spans:m.filter(d=>d.kind==="span").map(d=>d.event),traceId:g})}catch(d){n+=1,n===1&&(f=d),l=!0}l&&c.push(...m)}return n>0&&o(f,n),c},w=(r,s)=>{let o;try{o=s===void 0?r:s(r)}catch{o=void 0}return o??void 0},wr=r=>{const s=x(r.message);if(r.stack===void 0)return{...r,message:s};const o=`: ${r.message}`,t=r.stack.indexOf(o),c=r.message!==""&&t!==-1&&!r.stack.slice(0,t).includes(`
2
- `)?r.stack.slice(t+o.length):r.stack.split(`
3
- `).filter(n=>n.trimStart().startsWith("at ")).map(n=>`
4
- ${n}`).join("");return{...r,message:s,stack:`${r.name}: ${s}${c}`}},Lr=r=>({...r,...r.error===void 0?{}:{error:wr(r.error)},...r.fields===void 0?{}:{fields:x(r.fields)},message:x(r.message)}),C=(r,s,o)=>{if(r.kind==="rpc"){const e=w(r.event,s?.rpc);return e===void 0?void 0:{bucket:"spans",encoded:fr(e,r.endMs)}}if(r.kind==="span"){const e=w(r.event,s?.span);return e===void 0?void 0:{bucket:"spans",encoded:mr(e)}}if(r.kind==="log"){const e=w(o?Lr(r.event):r.event,s?.log);return e===void 0?void 0:{bucket:"logs",encoded:gr(e)}}const t=w(r.event,s?.metric);return t===void 0?void 0:{bucket:"metrics",encoded:hr(t)}},Or=["fuseCloudflareTraces","instrumentDatabase","metricHistory","traceFetch"],Mr=(r={})=>{const{onlyErrors:s}=r;return{onLog:o=>{o.level==="error"||o.level==="fatal"?console.error("[lunora:log]",o.functionPath,o.message):console.log("[lunora:log]",o.functionPath,o.message)},onMetric:o=>{console.log("[lunora:metric]",`${o.name}=${String(o.value)}`,o.kind,o.functionPath)},onRpc:o=>{O(o,s)||(o.ok?console.log("[lunora:rpc]",o):console.error("[lunora:rpc]",o))},onSpan:o=>{const t=o.ok?"ok":`error ${o.error?.type??""}`.trim();console.log("[lunora:span]",o.name,`${String(o.durationMs)}ms`,t,o.functionPath)}}},_r=r=>{const{headers:s,onlyErrors:o,transform:t,transformLog:e,url:c}=r,n=V({"content-type":"application/json"},s),f=(g,m)=>{try{const l=fetch(c,{body:JSON.stringify(g),headers:n,method:"POST"}).catch(()=>{});m?.waitUntil&&m.waitUntil(l)}catch{}};return{onLog:(g,m)=>{const l=w(g,e);l!==void 0&&f(l,m)},onRpc:(g,m)=>{if(O(g,o))return;const l=w(g,t);l!==void 0&&f(l,m)}}},Ur=r=>{const{dataset:s,onlyErrors:o}=r;return{onRpc:t=>{if(!O(t,o))try{s.writeDataPoint({blobs:[t.functionPath,t.ok?"ok":"error",t.shardKey??"",t.error?.code??"",t.fanOut?.table??""],doubles:[t.durationMs,t.ok?0:1,t.fanOut?.shards??0,t.fanOut?.failed??0],indexes:[t.functionPath]})}catch{}}}},Dr=r=>{const{pipeline:s,serializeFields:o}=r;return{onLog:(t,e)=>{try{const c={functionPath:t.functionPath,level:t.level,message:t.message,ts:t.ts};t.fields&&(c.fields=o===!0?JSON.stringify(t.fields):t.fields);for(const f of["shardKey","userId","traceId","spanId"])t[f]!==void 0&&(c[f]=t[f]);const n=s.send([c]).catch(()=>{});e?.waitUntil&&e.waitUntil(n)}catch{}}}},Fr=r=>{const{batch:s,deploymentEnvironment:o,detectResources:t,endpoint:e,headers:c,onlyErrors:n,postProcessor:f,resourceAttributes:g,serviceNamespace:m,serviceVersion:l,tailSampler:d,token:W}=r,M=r.serviceName??"lunora",_=r.redactLogs??!0;if(s!==!1&&s?.maxItems!==void 0&&(!Number.isInteger(s.maxItems)||s.maxItems<1))throw new q("ENV_INVALID",`otlpSink: \`batch.maxItems\` must be a positive integer, received ${String(s.maxItems)}.`);const U={...l===void 0?{}:{"service.version":l},...m===void 0?{}:{"service.namespace":m},...o===void 0?{}:{"deployment.environment":o},...g},D=new WeakMap,I=u=>{if(t!==!0||u?.resourceAttributes===void 0)return U;const a=D.get(u);if(a!==void 0)return a;const p=er(u.resourceAttributes(),U);return D.set(u,p),p};let S=e;for(;S.endsWith("/");)S=S.slice(0,-1);const F={logs:{url:`${S}/v1/logs`,wrap:sr},metrics:{url:`${S}/v1/metrics`,wrap:or},spans:{url:`${S}/v1/traces`,wrap:tr}},$=V({"content-type":"application/json"},c,W);let E=0;const X=(u,a)=>{if(E>=B)return;E+=1;const p=E===B?" Further tailSampler failures from this sink are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] tailSampler threw for ${String(a)} trace(s) in this flush window; keeping them (fail-open), so the sampling policy did NOT apply.${p}`,u)},Y=async u=>{const a=Pr(u,d,X),p=new Map;for(const y of a){const k=C(y,f,_);if(k===void 0)continue;const A=Q(y.resource);let P=p.get(A);P===void 0&&(P={logs:[],metrics:[],resource:y.resource,spans:[]},p.set(A,P)),P[k.bucket].push(k.encoded)}const T=[];for(const[,y]of p)for(const k of["spans","logs","metrics"])if(y[k].length>0){const{url:A,wrap:P}=F[k];T.push(G(A,P(y[k],"@lunora/runtime",M,y.resource),$))}await Promise.all(T)};if(s===!1){const u=(a,p)=>{const T=C(a,f,_);if(T!==void 0){const{url:y,wrap:k}=F[T.bucket];br(y,k(T.encoded,"@lunora/runtime",M,a.resource),$,p)}};return{onLog:(a,p)=>{u({event:a,kind:"log",resource:I(p)},p)},onMetric:(a,p)=>{u({event:a,kind:"metric",resource:I(p)},p)},onRpc:(a,p)=>{O(a,n)||u({endMs:Date.now(),event:a,kind:"rpc",resource:I(p)},p)},onSpan:(a,p)=>{u({event:a,kind:"span",resource:I(p)},p)}}}const L=dr({export:Y,...s?.maxDelayMs===void 0?{}:{maxDelayMs:s.maxDelayMs},...s?.maxItems===void 0?{}:{maxItems:s.maxItems}});return{flush:u=>{L.flush(u?.waitUntil).catch(()=>{})},onLog:(u,a)=>{L.add({event:u,kind:"log",resource:I(a)},a?.waitUntil)},onMetric:(u,a)=>{L.add({event:u,kind:"metric",resource:I(a)},a?.waitUntil)},onRpc:(u,a)=>{O(u,n)||L.add({endMs:Date.now(),event:u,kind:"rpc",resource:I(a)},a?.waitUntil)},onSpan:(u,a)=>{L.add({event:u,kind:"span",resource:I(a)},a?.waitUntil)}}},$r=(...r)=>{const s=(t,e)=>{for(const c of r){const n=c[t];if(n)try{n.apply(c,e)}catch{}}},o={};for(const t of r)for(const e of Or)o[e]===void 0&&t[e]!==void 0&&(o[e]=t[e]);return{...o,flush:t=>{s("flush",[t])},onLog:(t,e)=>{s("onLog",[t,e])},onMetric:(t,e)=>{s("onMetric",[t,e])},onRpc:(t,e)=>{s("onRpc",[t,e])},onSpan:(t,e)=>{s("onSpan",[t,e])}}};export{Ur as analyticsEngineSink,$r as combineSinks,Mr as consoleSink,Fr as otlpSink,Dr as pipelineLogSink,_r as webhookSink};