@lunora/do 1.0.0-alpha.38 → 1.0.0-alpha.39

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
@@ -2257,6 +2257,13 @@ interface MetricEvent {
2257
2257
  name: string;
2258
2258
  /** Shard key for single-shard calls; absent for the unnamed root DO. */
2259
2259
  shardKey?: string;
2260
+ /**
2261
+ * Trace id of the dispatch that recorded this measurement, when it ran inside
2262
+ * one — the measurement's **exemplar**, letting a consumer jump from a metric
2263
+ * point to a trace that produced it (OpenTelemetry's exemplar model). Stamped
2264
+ * by the shard from the current request's trace context, not by the caller.
2265
+ */
2266
+ traceId?: string;
2260
2267
  /** Wall-clock millis when the measurement was recorded. */
2261
2268
  ts: number;
2262
2269
  /**
@@ -2274,6 +2281,21 @@ interface MetricEvent {
2274
2281
  * (32-hex trace, 16-hex span), so a `SpanEvent` composes into an OTLP span with
2275
2282
  * no reformatting.
2276
2283
  */
2284
+ /**
2285
+ * Handle the enclosing `ctx.trace` span hands its body, so the body can attach
2286
+ * attributes only known *after* it resolves — an AI call's token usage or dollar
2287
+ * cost, a downstream response's status, a computed row count. The start
2288
+ * attributes passed to `ctx.trace(name, fn, attributes)` are snapshotted before
2289
+ * the body runs (so a mid-span mutation can't rewrite them); anything set through
2290
+ * this handle is merged over that snapshot at record time, with the post-hoc
2291
+ * value winning on a key clash.
2292
+ */
2293
+ interface SpanHandle {
2294
+ /** Set one attribute on the enclosing span (merged at record time; post-hoc wins on key clash). */
2295
+ setAttribute: (key: string, value: LogFields[string]) => void;
2296
+ /** Merge attributes onto the enclosing span (post-hoc wins on key clash). */
2297
+ setAttributes: (fields: LogFields) => void;
2298
+ }
2277
2299
  interface SpanEvent {
2278
2300
  /**
2279
2301
  * Structured attributes the caller attached, already normalized to a fresh
@@ -2339,8 +2361,12 @@ interface SpanEvent {
2339
2361
  * `LunoraTracer`). Declared here rather than imported so `@lunora/do` takes no
2340
2362
  * dependency on `@lunora/server`; a cross-package assignability guard in
2341
2363
  * `@lunora/testing` fails the build if the two drift apart.
2364
+ *
2365
+ * The body's second argument is the enclosing span's {@link SpanHandle}, through
2366
+ * which it can attach attributes only known *after* it resolves (post-hoc). It is
2367
+ * a trailing parameter, so a `(trace) => …` body that ignores it still conforms.
2342
2368
  */
2343
- type ContextTracer = <T>(name: string, function_: (trace: ContextTracer) => Promise<T> | T, attributes?: LogFields) => Promise<T>;
2369
+ type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, attributes?: LogFields) => Promise<T>;
2344
2370
  /** Structural shape of the `ctx.metrics` recorder (see the server `LunoraMetrics`). */
2345
2371
  interface ContextMetrics {
2346
2372
  count: (name: string, value?: number, attributes?: LogFields) => void;
@@ -2814,6 +2840,7 @@ declare const ADMIN_FUNCTIONS: {
2814
2840
  readonly getFanoutMetrics: "__lunora_admin__:getFanoutMetrics";
2815
2841
  readonly getFunctionStats: "__lunora_admin__:getFunctionStats";
2816
2842
  readonly getIssues: "__lunora_admin__:getIssues";
2843
+ readonly getMetricHistory: "__lunora_admin__:getMetricHistory";
2817
2844
  readonly getMetricSeries: "__lunora_admin__:getMetricSeries";
2818
2845
  readonly listSubscriptions: "__lunora_admin__:listSubscriptions";
2819
2846
  readonly listTableIndexes: "__lunora_admin__:listTableIndexes";
@@ -3118,7 +3145,12 @@ interface StudioFeaturesResult {
3118
3145
  kv: boolean;
3119
3146
  /** `@lunora/mail` is imported by a `lunora/` source or a declared dependency. */
3120
3147
  mail: boolean;
3121
- /** `@lunora/payment` is used (import or `ctx.payments`) or a declared dependency. */
3148
+ /**
3149
+ * `@lunora/payment` is used (import or `ctx.payments`), or the app declares the store's
3150
+ * `subscriptions`/`events` tables that the Payments panel reads. Unlike the other flags this
3151
+ * has no declared-dependency arm: the panel queries those tables directly, so a bare dependency
3152
+ * (e.g. reusing the package's pure webhook helpers) must not show a page that would then error.
3153
+ */
3122
3154
  payments: boolean;
3123
3155
  /** `@lunora/queue` / `ctx.queues` is used, the app declares queues, or it is a declared dependency. */
3124
3156
  queues: boolean;
@@ -7206,4 +7238,4 @@ interface WhereSqlStrategy {
7206
7238
  * `undefined` when the input imposes no constraint (empty `where`).
7207
7239
  */
7208
7240
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
7209
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type AuthMetrics, type AuthMetricsBucket, type BroadcastDelta, CDC_LOG_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type Clock, type ColumnMeta, type ColumnMetaLike, ConflictError, type ContextMetrics, type ContextTracer, type CountArgs, CountRlsUnsupportedError, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_MAX_RELATION_KEYS, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FieldOperators, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionMetricBucket, type FunctionMetricIndexHit, type FunctionStatsResult, GEO_DEFAULT_PRECISION, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type HibernatableWebSocket, type IdGenerator, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexRangeBuilderLike, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, type LogSink, MAIL_RETENTION, MAIL_TABLE, MAX_SQL_ROWS, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MetricsDeps, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByInput, type OrderKey, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type QueryArgs, type QueryPage, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadHook, type ReadTablePageOptions, type RecordAuthEventInput, type RecordFunctionMetricInput, type RecordMailInput, type RelationDefinitionLike, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkDeleteArgs, type RunShardBulkDeleteResult, type RunShardExportArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, type RunTriggersOptions, SCAN_DEP, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SelectMatchingIdsOptions, type ServerDefaultContextLike, SessionDO, type SessionRecord, type SettingEntry, type SettingKind, type SettingsResult, type ShapeSubscriptionQuery, ShardDO, type ShardDOOptions, type ShardDOState, type ShardRankPageResult, ShardRegistryDO, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionEnvelope, type SubscriptionOutcome, type SubscriptionQuery, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TelemetrySink, type TraceAnchor, type TracerDeps, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, aggregateSqlFunction, aggregateTableName, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, backfillAggregateIndexes, backfillRankIndexes, boundingBoxGeohashes, buildFtsMatch, buildSecurityAudit, buildSeekWhere, clearCapturedMail, coerceAggregateNumber, compileWhereSql, containsRelationPredicate, coveringGeohashes, createDependencyTracker, createMetrics, createShardCtxDb, createSystemReader, createTracer, decodeCursor, depKey, diffExternalSource, dispatchRootSpan, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, foldAggregateTally, ftsTableName, guardWriter, hasTrigger, haversineMeters, importShardRows, isRelationPredicate, isSoftDeleted, isSourceDue, liftSourceId, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeWhere, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, pullExternalSourceIncrementalTick, pullExternalSourceTick, rankTableName, reactiveCacheKey, readAggregateValue, readAuthMetrics, readBookmark, readCapturedMail, readCdcChanges, readExternalSourceBaseline, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetrics, readFunctionMetricsTotals, readMigrationStatus, readTablePage, recordAuthEvent, recordCapturedMail, recordFunctionMetric, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, runDataMigration, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runTriggers, scoreDocument, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stableWireKey, stringifySearchText, subscriptionListDeltas, throwingScheduler, tokenizeSearch, trimCdcChanges, validateImportRow };
7241
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type AuthMetrics, type AuthMetricsBucket, type BroadcastDelta, CDC_LOG_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type Clock, type ColumnMeta, type ColumnMetaLike, ConflictError, type ContextMetrics, type ContextTracer, type CountArgs, CountRlsUnsupportedError, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_MAX_RELATION_KEYS, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FieldOperators, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionMetricBucket, type FunctionMetricIndexHit, type FunctionStatsResult, GEO_DEFAULT_PRECISION, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type HibernatableWebSocket, type IdGenerator, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexRangeBuilderLike, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, type LogSink, MAIL_RETENTION, MAIL_TABLE, MAX_SQL_ROWS, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MetricsDeps, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByInput, type OrderKey, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type QueryArgs, type QueryPage, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadHook, type ReadTablePageOptions, type RecordAuthEventInput, type RecordFunctionMetricInput, type RecordMailInput, type RelationDefinitionLike, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkDeleteArgs, type RunShardBulkDeleteResult, type RunShardExportArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, type RunTriggersOptions, SCAN_DEP, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SelectMatchingIdsOptions, type ServerDefaultContextLike, SessionDO, type SessionRecord, type SettingEntry, type SettingKind, type SettingsResult, type ShapeSubscriptionQuery, ShardDO, type ShardDOOptions, type ShardDOState, type ShardRankPageResult, ShardRegistryDO, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SpanHandle, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionEnvelope, type SubscriptionOutcome, type SubscriptionQuery, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TelemetrySink, type TraceAnchor, type TracerDeps, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, aggregateSqlFunction, aggregateTableName, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, backfillAggregateIndexes, backfillRankIndexes, boundingBoxGeohashes, buildFtsMatch, buildSecurityAudit, buildSeekWhere, clearCapturedMail, coerceAggregateNumber, compileWhereSql, containsRelationPredicate, coveringGeohashes, createDependencyTracker, createMetrics, createShardCtxDb, createSystemReader, createTracer, decodeCursor, depKey, diffExternalSource, dispatchRootSpan, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, foldAggregateTally, ftsTableName, guardWriter, hasTrigger, haversineMeters, importShardRows, isRelationPredicate, isSoftDeleted, isSourceDue, liftSourceId, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeWhere, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, pullExternalSourceIncrementalTick, pullExternalSourceTick, rankTableName, reactiveCacheKey, readAggregateValue, readAuthMetrics, readBookmark, readCapturedMail, readCdcChanges, readExternalSourceBaseline, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetrics, readFunctionMetricsTotals, readMigrationStatus, readTablePage, recordAuthEvent, recordCapturedMail, recordFunctionMetric, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, runDataMigration, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runTriggers, scoreDocument, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stableWireKey, stringifySearchText, subscriptionListDeltas, throwingScheduler, tokenizeSearch, trimCdcChanges, validateImportRow };
package/dist/index.d.ts CHANGED
@@ -2257,6 +2257,13 @@ interface MetricEvent {
2257
2257
  name: string;
2258
2258
  /** Shard key for single-shard calls; absent for the unnamed root DO. */
2259
2259
  shardKey?: string;
2260
+ /**
2261
+ * Trace id of the dispatch that recorded this measurement, when it ran inside
2262
+ * one — the measurement's **exemplar**, letting a consumer jump from a metric
2263
+ * point to a trace that produced it (OpenTelemetry's exemplar model). Stamped
2264
+ * by the shard from the current request's trace context, not by the caller.
2265
+ */
2266
+ traceId?: string;
2260
2267
  /** Wall-clock millis when the measurement was recorded. */
2261
2268
  ts: number;
2262
2269
  /**
@@ -2274,6 +2281,21 @@ interface MetricEvent {
2274
2281
  * (32-hex trace, 16-hex span), so a `SpanEvent` composes into an OTLP span with
2275
2282
  * no reformatting.
2276
2283
  */
2284
+ /**
2285
+ * Handle the enclosing `ctx.trace` span hands its body, so the body can attach
2286
+ * attributes only known *after* it resolves — an AI call's token usage or dollar
2287
+ * cost, a downstream response's status, a computed row count. The start
2288
+ * attributes passed to `ctx.trace(name, fn, attributes)` are snapshotted before
2289
+ * the body runs (so a mid-span mutation can't rewrite them); anything set through
2290
+ * this handle is merged over that snapshot at record time, with the post-hoc
2291
+ * value winning on a key clash.
2292
+ */
2293
+ interface SpanHandle {
2294
+ /** Set one attribute on the enclosing span (merged at record time; post-hoc wins on key clash). */
2295
+ setAttribute: (key: string, value: LogFields[string]) => void;
2296
+ /** Merge attributes onto the enclosing span (post-hoc wins on key clash). */
2297
+ setAttributes: (fields: LogFields) => void;
2298
+ }
2277
2299
  interface SpanEvent {
2278
2300
  /**
2279
2301
  * Structured attributes the caller attached, already normalized to a fresh
@@ -2339,8 +2361,12 @@ interface SpanEvent {
2339
2361
  * `LunoraTracer`). Declared here rather than imported so `@lunora/do` takes no
2340
2362
  * dependency on `@lunora/server`; a cross-package assignability guard in
2341
2363
  * `@lunora/testing` fails the build if the two drift apart.
2364
+ *
2365
+ * The body's second argument is the enclosing span's {@link SpanHandle}, through
2366
+ * which it can attach attributes only known *after* it resolves (post-hoc). It is
2367
+ * a trailing parameter, so a `(trace) => …` body that ignores it still conforms.
2342
2368
  */
2343
- type ContextTracer = <T>(name: string, function_: (trace: ContextTracer) => Promise<T> | T, attributes?: LogFields) => Promise<T>;
2369
+ type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, attributes?: LogFields) => Promise<T>;
2344
2370
  /** Structural shape of the `ctx.metrics` recorder (see the server `LunoraMetrics`). */
2345
2371
  interface ContextMetrics {
2346
2372
  count: (name: string, value?: number, attributes?: LogFields) => void;
@@ -2814,6 +2840,7 @@ declare const ADMIN_FUNCTIONS: {
2814
2840
  readonly getFanoutMetrics: "__lunora_admin__:getFanoutMetrics";
2815
2841
  readonly getFunctionStats: "__lunora_admin__:getFunctionStats";
2816
2842
  readonly getIssues: "__lunora_admin__:getIssues";
2843
+ readonly getMetricHistory: "__lunora_admin__:getMetricHistory";
2817
2844
  readonly getMetricSeries: "__lunora_admin__:getMetricSeries";
2818
2845
  readonly listSubscriptions: "__lunora_admin__:listSubscriptions";
2819
2846
  readonly listTableIndexes: "__lunora_admin__:listTableIndexes";
@@ -3118,7 +3145,12 @@ interface StudioFeaturesResult {
3118
3145
  kv: boolean;
3119
3146
  /** `@lunora/mail` is imported by a `lunora/` source or a declared dependency. */
3120
3147
  mail: boolean;
3121
- /** `@lunora/payment` is used (import or `ctx.payments`) or a declared dependency. */
3148
+ /**
3149
+ * `@lunora/payment` is used (import or `ctx.payments`), or the app declares the store's
3150
+ * `subscriptions`/`events` tables that the Payments panel reads. Unlike the other flags this
3151
+ * has no declared-dependency arm: the panel queries those tables directly, so a bare dependency
3152
+ * (e.g. reusing the package's pure webhook helpers) must not show a page that would then error.
3153
+ */
3122
3154
  payments: boolean;
3123
3155
  /** `@lunora/queue` / `ctx.queues` is used, the app declares queues, or it is a declared dependency. */
3124
3156
  queues: boolean;
@@ -7206,4 +7238,4 @@ interface WhereSqlStrategy {
7206
7238
  * `undefined` when the input imposes no constraint (empty `where`).
7207
7239
  */
7208
7240
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
7209
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type AuthMetrics, type AuthMetricsBucket, type BroadcastDelta, CDC_LOG_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type Clock, type ColumnMeta, type ColumnMetaLike, ConflictError, type ContextMetrics, type ContextTracer, type CountArgs, CountRlsUnsupportedError, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_MAX_RELATION_KEYS, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FieldOperators, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionMetricBucket, type FunctionMetricIndexHit, type FunctionStatsResult, GEO_DEFAULT_PRECISION, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type HibernatableWebSocket, type IdGenerator, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexRangeBuilderLike, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, type LogSink, MAIL_RETENTION, MAIL_TABLE, MAX_SQL_ROWS, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MetricsDeps, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByInput, type OrderKey, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type QueryArgs, type QueryPage, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadHook, type ReadTablePageOptions, type RecordAuthEventInput, type RecordFunctionMetricInput, type RecordMailInput, type RelationDefinitionLike, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkDeleteArgs, type RunShardBulkDeleteResult, type RunShardExportArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, type RunTriggersOptions, SCAN_DEP, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SelectMatchingIdsOptions, type ServerDefaultContextLike, SessionDO, type SessionRecord, type SettingEntry, type SettingKind, type SettingsResult, type ShapeSubscriptionQuery, ShardDO, type ShardDOOptions, type ShardDOState, type ShardRankPageResult, ShardRegistryDO, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionEnvelope, type SubscriptionOutcome, type SubscriptionQuery, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TelemetrySink, type TraceAnchor, type TracerDeps, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, aggregateSqlFunction, aggregateTableName, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, backfillAggregateIndexes, backfillRankIndexes, boundingBoxGeohashes, buildFtsMatch, buildSecurityAudit, buildSeekWhere, clearCapturedMail, coerceAggregateNumber, compileWhereSql, containsRelationPredicate, coveringGeohashes, createDependencyTracker, createMetrics, createShardCtxDb, createSystemReader, createTracer, decodeCursor, depKey, diffExternalSource, dispatchRootSpan, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, foldAggregateTally, ftsTableName, guardWriter, hasTrigger, haversineMeters, importShardRows, isRelationPredicate, isSoftDeleted, isSourceDue, liftSourceId, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeWhere, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, pullExternalSourceIncrementalTick, pullExternalSourceTick, rankTableName, reactiveCacheKey, readAggregateValue, readAuthMetrics, readBookmark, readCapturedMail, readCdcChanges, readExternalSourceBaseline, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetrics, readFunctionMetricsTotals, readMigrationStatus, readTablePage, recordAuthEvent, recordCapturedMail, recordFunctionMetric, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, runDataMigration, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runTriggers, scoreDocument, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stableWireKey, stringifySearchText, subscriptionListDeltas, throwingScheduler, tokenizeSearch, trimCdcChanges, validateImportRow };
7241
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type AuthMetrics, type AuthMetricsBucket, type BroadcastDelta, CDC_LOG_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type Clock, type ColumnMeta, type ColumnMetaLike, ConflictError, type ContextMetrics, type ContextTracer, type CountArgs, CountRlsUnsupportedError, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_MAX_RELATION_KEYS, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FieldOperators, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionMetricBucket, type FunctionMetricIndexHit, type FunctionStatsResult, GEO_DEFAULT_PRECISION, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type HibernatableWebSocket, type IdGenerator, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexRangeBuilderLike, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, type LogSink, MAIL_RETENTION, MAIL_TABLE, MAX_SQL_ROWS, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MetricsDeps, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByInput, type OrderKey, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type QueryArgs, type QueryPage, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadHook, type ReadTablePageOptions, type RecordAuthEventInput, type RecordFunctionMetricInput, type RecordMailInput, type RelationDefinitionLike, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkDeleteArgs, type RunShardBulkDeleteResult, type RunShardExportArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, type RunTriggersOptions, SCAN_DEP, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SelectMatchingIdsOptions, type ServerDefaultContextLike, SessionDO, type SessionRecord, type SettingEntry, type SettingKind, type SettingsResult, type ShapeSubscriptionQuery, ShardDO, type ShardDOOptions, type ShardDOState, type ShardRankPageResult, ShardRegistryDO, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SpanHandle, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionEnvelope, type SubscriptionOutcome, type SubscriptionQuery, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TelemetrySink, type TraceAnchor, type TracerDeps, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, aggregateSqlFunction, aggregateTableName, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, backfillAggregateIndexes, backfillRankIndexes, boundingBoxGeohashes, buildFtsMatch, buildSecurityAudit, buildSeekWhere, clearCapturedMail, coerceAggregateNumber, compileWhereSql, containsRelationPredicate, coveringGeohashes, createDependencyTracker, createMetrics, createShardCtxDb, createSystemReader, createTracer, decodeCursor, depKey, diffExternalSource, dispatchRootSpan, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, foldAggregateTally, ftsTableName, guardWriter, hasTrigger, haversineMeters, importShardRows, isRelationPredicate, isSoftDeleted, isSourceDue, liftSourceId, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeWhere, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, pullExternalSourceIncrementalTick, pullExternalSourceTick, rankTableName, reactiveCacheKey, readAggregateValue, readAuthMetrics, readBookmark, readCapturedMail, readCdcChanges, readExternalSourceBaseline, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetrics, readFunctionMetricsTotals, readMigrationStatus, readTablePage, recordAuthEvent, recordCapturedMail, recordFunctionMetric, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, runDataMigration, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runTriggers, scoreDocument, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, serveRelationFanout, softDeleteScope, sortColumnName, stableStringify, stableWireKey, stringifySearchText, subscriptionListDeltas, throwingScheduler, tokenizeSearch, trimCdcChanges, validateImportRow };
package/dist/index.mjs CHANGED
@@ -3,7 +3,7 @@ export { AGGREGATE_SQL_FUNCTION, aggregateSqlFunction, matchesStaticWhere, norma
3
3
  export { aggregateTableName, coerceAggregateNumber, encodeAggregateKey, foldAggregateTally, readAggregateValue } from './packem_shared/aggregateTableName-CxNqY1Sl.mjs';
4
4
  export { CountRlsUnsupportedError, mergeWhere, planAggregateLookup, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy } from './packem_shared/CountRlsUnsupportedError-BGxj0pgS.mjs';
5
5
  export { AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, ensureAuthMetricsTables, readAuthMetrics, recordAuthEvent } from './packem_shared/AUTH_METRICS_BUCKETS_TABLE-CiHHYeJi.mjs';
6
- export { c as createMetrics, a as createTracer, d as dispatchRootSpan } from './packem_shared/context-telemetry-DWfYDxCS.mjs';
6
+ export { c as createMetrics, a as createTracer, d as dispatchRootSpan } from './packem_shared/context-telemetry-CqcOObBl.mjs';
7
7
  export { NotUniqueError, assertValidClientId, createShardCtxDb, normalizeIdStructurally } from './packem_shared/NotUniqueError-DbtlWwcG.mjs';
8
8
  export { DATA_MIGRATION_STATE_TABLE, readMigrationStatus, runDataMigration } from './packem_shared/DATA_MIGRATION_STATE_TABLE-CYwBpyTr.mjs';
9
9
  export { SCAN_DEP, createDependencyTracker, depKey } from './packem_shared/SCAN_DEP-DLJF8dsj.mjs';
@@ -13,7 +13,7 @@ export { materializeExternalRows, materializeExternalRowsIncremental, readExtern
13
13
  export { isSoftDeleted, isSourceDue, liftSourceId, pullExternalSourceIncrementalTick, pullExternalSourceTick } from './packem_shared/isSoftDeleted-CFJmhjFP.mjs';
14
14
  export { FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, ensureFunctionMetricsTables, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetrics, readFunctionMetricsTotals, recordFunctionMetric } from './packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-UDNVD7FS.mjs';
15
15
  export { GEO_DEFAULT_PRECISION, boundingBoxGeohashes, coveringGeohashes, encodeGeohash, haversineMeters, pointInBoundingBox } from './packem_shared/GEO_DEFAULT_PRECISION-BWnsNmpP.mjs';
16
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, FLAGS_FUNCTION_PREFIX, RELATION_FUNCTION_PREFIX, facetColumn, listTables, readTablePage, selectMatchingIds } from './packem_shared/ADMIN_FUNCTIONS-DVk02KpP.mjs';
16
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, FLAGS_FUNCTION_PREFIX, RELATION_FUNCTION_PREFIX, facetColumn, listTables, readTablePage, selectMatchingIds } from './packem_shared/ADMIN_FUNCTIONS-CnZkbXH_.mjs';
17
17
  export { LogBuffer } from './packem_shared/LogBuffer-B_Ezju_N.mjs';
18
18
  export { MAIL_RETENTION, MAIL_TABLE, clearCapturedMail, ensureMailTable, readCapturedMail, recordCapturedMail } from './packem_shared/MAIL_RETENTION-CPpgl-dX.mjs';
19
19
  export { default as NotFoundError } from './packem_shared/NotFoundError-C70b9hLw.mjs';
@@ -21,14 +21,14 @@ export { armRestore, readBookmark } from './packem_shared/armRestore-4Px61hHS.mj
21
21
  export { applySelect, buildSeekWhere, decodeCursor, encodeCursor, normalizeOrderKeys, softDeleteScope } from './packem_shared/applySelect-WQY8m62C.mjs';
22
22
  export { RANK_TIEBREAK, encodePartitionKey, matchesRankStaticWhere, rankTableName, resolveRankPartition, sortColumnName } from './packem_shared/RANK_TIEBREAK-CXhdcA1o.mjs';
23
23
  export { ReactiveCache, reactiveCacheKey } from './packem_shared/ReactiveCache-DnSvbjil.mjs';
24
- export { serveRelationFanout } from './packem_shared/serveRelationFanout-FdrPflv1.mjs';
24
+ export { serveRelationFanout } from './packem_shared/serveRelationFanout-k7HTh3CC.mjs';
25
25
  export { DEFAULT_MAX_RELATION_KEYS, assertFlatPredicate, assertShapeShardable, containsRelationPredicate, isRelationPredicate, resolveRelationPredicates } from './packem_shared/DEFAULT_MAX_RELATION_KEYS-BEan1CRD.mjs';
26
26
  export { applyOnDelete, fanOutScalarCounts, resolveWith, runRowValidators } from './packem_shared/applyOnDelete-BXSq3S70.mjs';
27
27
  export { RLS_UNWRAP_SYMBOL, RlsRequiredError, guardWriter } from './packem_shared/RLS_UNWRAP_SYMBOL-DTvHvRzY.mjs';
28
28
  export { buildFtsMatch, ftsTableName, scoreDocument, stringifySearchText, tokenizeSearch } from './packem_shared/buildFtsMatch-BLEMawrp.mjs';
29
29
  export { M as MIN_ADMIN_TOKEN_LENGTH, a as MIN_AUTH_SECRET_LENGTH, b as buildSecurityAudit } from './packem_shared/security-audit-CucgBice.mjs';
30
30
  export { SESSION_DO_TTL_DEFAULT, SessionDO } from './packem_shared/SESSION_DO_TTL_DEFAULT-BnSKgVO4.mjs';
31
- export { ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, ShardDO } from './packem_shared/ROOT_DO_SIZE_WARN_BYTES-FAG0bOO5.mjs';
31
+ export { ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, ShardDO } from './packem_shared/ROOT_DO_SIZE_WARN_BYTES-CJGwzfoT.mjs';
32
32
  export { SHARD_REGISTRY_DO_NAME, ShardRegistryDO } from './packem_shared/SHARD_REGISTRY_DO_NAME-D99roc-r.mjs';
33
33
  export { MAX_SQL_ROWS, assertReadonly, runReadonlySql } from './packem_shared/MAX_SQL_ROWS-iFAA8FbD.mjs';
34
34
  export { createSystemReader } from './packem_shared/createSystemReader-D12eNH13.mjs';
@@ -25,6 +25,7 @@ const ADMIN_FUNCTIONS = {
25
25
  getFanoutMetrics: "__lunora_admin__:getFanoutMetrics",
26
26
  getFunctionStats: "__lunora_admin__:getFunctionStats",
27
27
  getIssues: "__lunora_admin__:getIssues",
28
+ getMetricHistory: "__lunora_admin__:getMetricHistory",
28
29
  getMetricSeries: "__lunora_admin__:getMetricSeries",
29
30
  listSubscriptions: "__lunora_admin__:listSubscriptions",
30
31
  listTableIndexes: "__lunora_admin__:listTableIndexes",
@@ -5,11 +5,11 @@ import { j as jsonResponse } from './json-response-BdbtpOhm.mjs';
5
5
  import { e as encodeWire, d as decodeWire } from './wire-codec-CzQc1pvf.mjs';
6
6
  import { parseExportShardArgs, parseImportShardArgs } from './exportShardRows-Dy3oFZ26.mjs';
7
7
  import { recordAuthEvent, readAuthMetrics } from './AUTH_METRICS_BUCKETS_TABLE-CiHHYeJi.mjs';
8
- import { n as normalizeLogFields, r as resolveTraceAnchor, a as createTracer, c as createMetrics, d as dispatchRootSpan } from './context-telemetry-DWfYDxCS.mjs';
8
+ import { n as normalizeLogFields, r as resolveTraceAnchor, a as createTracer, c as createMetrics, d as dispatchRootSpan } from './context-telemetry-CqcOObBl.mjs';
9
9
  import { DATA_MIGRATION_STATE_TABLE, readMigrationStatus } from './DATA_MIGRATION_STATE_TABLE-CYwBpyTr.mjs';
10
10
  import { SCAN_DEP, createDependencyTracker, tableFromDepKey } from './SCAN_DEP-DLJF8dsj.mjs';
11
11
  import { readFunctionMetricsTotals, readFunctionMetricIndexHits, recordFunctionMetric, mergeScanAttribution, readFunctionMetrics, readFunctionMetricBuckets } from './FUNCTION_METRICS_BUCKETS_TABLE-UDNVD7FS.mjs';
12
- import { createFanoutCounters, ADMIN_FUNCTION_PREFIX, RELATION_FUNCTION_PREFIX, selectMatchingIds, ADMIN_FUNCTIONS, findStorageReferences, listTables, summarizeSubscriptions, summarizeFanoutTopics, readTablePage, facetColumn, FLAGS_FUNCTION_PREFIX, recordFanoutPass, MAX_PAGE_SIZE } from './ADMIN_FUNCTIONS-DVk02KpP.mjs';
12
+ import { createFanoutCounters, ADMIN_FUNCTION_PREFIX, RELATION_FUNCTION_PREFIX, selectMatchingIds, ADMIN_FUNCTIONS, findStorageReferences, listTables, summarizeSubscriptions, summarizeFanoutTopics, readTablePage, facetColumn, FLAGS_FUNCTION_PREFIX, recordFanoutPass, MAX_PAGE_SIZE } from './ADMIN_FUNCTIONS-CnZkbXH_.mjs';
13
13
  import { LogBuffer } from './LogBuffer-B_Ezju_N.mjs';
14
14
  import { recordCapturedMail, clearCapturedMail, readCapturedMail, MAIL_TABLE } from './MAIL_RETENTION-CPpgl-dX.mjs';
15
15
  import { stableStringify } from './stableStringify-mC40mZts.mjs';
@@ -94,12 +94,12 @@ const verifyWsAdminToken = async (secret, token, now = Date.now()) => {
94
94
 
95
95
  const AUDIT_LOG_TABLE = "__lunora_audit__";
96
96
  const AUDIT_LOG_RETENTION = 1e3;
97
- const runSql$4 = (sql, query, ...params) => {
97
+ const runSql$5 = (sql, query, ...params) => {
98
98
  const runner = sql.exec;
99
99
  return runner.call(sql, query, ...params);
100
100
  };
101
101
  const ensureAuditTable = (sql) => {
102
- runSql$4(
102
+ runSql$5(
103
103
  sql,
104
104
  `CREATE TABLE IF NOT EXISTS "${AUDIT_LOG_TABLE}" (
105
105
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -113,7 +113,7 @@ const ensureAuditTable = (sql) => {
113
113
  };
114
114
  const appendAuditEntry = (sql, entry) => {
115
115
  ensureAuditTable(sql);
116
- runSql$4(
116
+ runSql$5(
117
117
  sql,
118
118
  `INSERT INTO "${AUDIT_LOG_TABLE}" (ts, op, "table", id, detail) VALUES (?, ?, ?, ?, ?)`,
119
119
  entry.ts,
@@ -125,13 +125,13 @@ const appendAuditEntry = (sql, entry) => {
125
125
  // eslint-disable-next-line unicorn/no-null -- SQL NULL is the correct value for an op with no associated table/id/detail.
126
126
  entry.detail === void 0 ? null : JSON.stringify(entry.detail)
127
127
  );
128
- runSql$4(sql, `DELETE FROM "${AUDIT_LOG_TABLE}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${AUDIT_LOG_TABLE}")`, AUDIT_LOG_RETENTION);
128
+ runSql$5(sql, `DELETE FROM "${AUDIT_LOG_TABLE}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${AUDIT_LOG_TABLE}")`, AUDIT_LOG_RETENTION);
129
129
  };
130
130
  const readAuditLog = (sql, options = {}) => {
131
131
  ensureAuditTable(sql);
132
132
  const sinceSeq = options.sinceSeq ?? 0;
133
133
  const limit = Math.max(1, Math.min(options.limit ?? AUDIT_LOG_RETENTION, 1e4));
134
- const rows = runSql$4(
134
+ const rows = runSql$5(
135
135
  sql,
136
136
  `SELECT seq, ts, op, "table", id, detail FROM "${AUDIT_LOG_TABLE}" WHERE seq > ? ORDER BY seq DESC LIMIT ?`,
137
137
  sinceSeq,
@@ -188,14 +188,14 @@ const ISSUE_STATE_TABLE = "__lunora_issue_state__";
188
188
  const HASH_QUERY_BATCH = 100;
189
189
  const ISSUE_STATUSES = ["ignored", "open", "resolved"];
190
190
  const ISSUE_SEVERITIES = ["critical", "high", "low", "medium"];
191
- const runSql$3 = (sql, query, ...parameters) => {
191
+ const runSql$4 = (sql, query, ...parameters) => {
192
192
  const runner = sql.exec;
193
193
  return runner.call(sql, query, ...parameters);
194
194
  };
195
195
  const SQL_NULL = null;
196
196
  const orNull$1 = (value) => value ?? SQL_NULL;
197
197
  const ensureIssueStateTable = (sql) => {
198
- runSql$3(
198
+ runSql$4(
199
199
  sql,
200
200
  `CREATE TABLE IF NOT EXISTS "${ISSUE_STATE_TABLE}" (
201
201
  hash TEXT PRIMARY KEY,
@@ -226,7 +226,7 @@ const readIssueStates = (sql, hashes) => {
226
226
  for (let start = 0; start < hashes.length; start += HASH_QUERY_BATCH) {
227
227
  const batch = hashes.slice(start, start + HASH_QUERY_BATCH);
228
228
  const placeholders = batch.map(() => "?").join(", ");
229
- const rows = runSql$3(
229
+ const rows = runSql$4(
230
230
  sql,
231
231
  `SELECT hash, status, assignee, severity, updated_at, updated_by FROM "${ISSUE_STATE_TABLE}" WHERE hash IN (${placeholders})`,
232
232
  ...batch
@@ -245,7 +245,7 @@ const upsertIssueState = (sql, hash, patch, updatedAt, updatedBy) => {
245
245
  const severity = orNull$1(patch.severity);
246
246
  const clearSeverity = patch.severity === null ? 1 : 0;
247
247
  const actor = orNull$1(updatedBy);
248
- runSql$3(
248
+ runSql$4(
249
249
  sql,
250
250
  `INSERT INTO "${ISSUE_STATE_TABLE}" (hash, status, assignee, severity, updated_at, updated_by)
251
251
  VALUES (?, COALESCE(?, 'open'), ?, ?, ?, ?)
@@ -269,7 +269,7 @@ const upsertIssueState = (sql, hash, patch, updatedAt, updatedBy) => {
269
269
  updatedAt,
270
270
  actor
271
271
  );
272
- const [row] = runSql$3(
272
+ const [row] = runSql$4(
273
273
  sql,
274
274
  `SELECT hash, status, assignee, severity, updated_at, updated_by FROM "${ISSUE_STATE_TABLE}" WHERE hash = ?`,
275
275
  hash
@@ -278,7 +278,7 @@ const upsertIssueState = (sql, hash, patch, updatedAt, updatedBy) => {
278
278
  };
279
279
 
280
280
  const DEFAULT_CAPACITY$1 = 256;
281
- const seriesKey = (event) => `${event.kind}\0${event.name}\0${stableStringify(event.attributes ?? {})}`;
281
+ const metricSeriesKey = (event) => `${event.kind}${event.name}${stableStringify(event.attributes ?? {})}`;
282
282
  class MetricBuffer {
283
283
  capacity;
284
284
  series = /* @__PURE__ */ new Map();
@@ -305,7 +305,7 @@ class MetricBuffer {
305
305
  }
306
306
  /** Fold one measurement into its series, creating or updating the aggregate. */
307
307
  push(event) {
308
- const key = seriesKey(event);
308
+ const key = metricSeriesKey(event);
309
309
  const existing = this.series.get(key);
310
310
  if (existing === void 0) {
311
311
  if (this.series.size >= this.capacity) {
@@ -317,6 +317,7 @@ class MetricBuffer {
317
317
  this.series.set(key, {
318
318
  ...event.attributes === void 0 ? {} : { attributes: event.attributes },
319
319
  count: 1,
320
+ ...event.traceId === void 0 ? {} : { exemplarTraceId: event.traceId },
320
321
  firstTs: event.ts,
321
322
  functionPath: event.functionPath,
322
323
  kind: event.kind,
@@ -338,10 +339,152 @@ class MetricBuffer {
338
339
  existing.last = event.value;
339
340
  existing.lastTs = event.ts;
340
341
  existing.functionPath = event.functionPath;
342
+ if (event.traceId !== void 0) {
343
+ existing.exemplarTraceId = event.traceId;
344
+ }
341
345
  this.series.set(key, existing);
342
346
  }
343
347
  }
344
348
 
349
+ const METRIC_HISTORY_TABLE = "__lunora_metric_history";
350
+ const METRIC_HISTORY_BUCKET_MS = 6e4;
351
+ const METRIC_HISTORY_BUCKET_RETENTION = 1440;
352
+ const METRIC_HISTORY_MAX_SERIES = 1e3;
353
+ const METRIC_HISTORY_READ_LIMIT = 5e3;
354
+ const runSql$3 = (sql, query, ...parameters) => {
355
+ const runner = sql.exec;
356
+ return runner.call(sql, query, ...parameters);
357
+ };
358
+ const bucketFloor = (ts) => Math.floor(ts / METRIC_HISTORY_BUCKET_MS) * METRIC_HISTORY_BUCKET_MS;
359
+ const ensureMetricHistoryTable = (sql) => {
360
+ runSql$3(
361
+ sql,
362
+ `CREATE TABLE IF NOT EXISTS "${METRIC_HISTORY_TABLE}" (
363
+ series_key TEXT NOT NULL,
364
+ bucket_ms INTEGER NOT NULL,
365
+ name TEXT NOT NULL,
366
+ kind TEXT NOT NULL,
367
+ attrs TEXT NOT NULL DEFAULT '{}',
368
+ function_path TEXT NOT NULL DEFAULT '',
369
+ shard_key TEXT,
370
+ count INTEGER NOT NULL DEFAULT 0,
371
+ sum REAL NOT NULL DEFAULT 0,
372
+ min REAL NOT NULL DEFAULT 0,
373
+ max REAL NOT NULL DEFAULT 0,
374
+ last REAL NOT NULL DEFAULT 0,
375
+ last_ts REAL NOT NULL DEFAULT 0,
376
+ exemplar_trace TEXT,
377
+ PRIMARY KEY (series_key, bucket_ms)
378
+ )`
379
+ );
380
+ };
381
+ const recordMetricHistory = (sql, event, exemplarTraceId) => {
382
+ ensureMetricHistoryTable(sql);
383
+ const key = metricSeriesKey(event);
384
+ const bucket = bucketFloor(event.ts);
385
+ const bucketExists = runSql$3(sql, `SELECT 1 AS c FROM "${METRIC_HISTORY_TABLE}" WHERE series_key = ? AND bucket_ms = ? LIMIT 1`, key, bucket).toArray().length > 0;
386
+ if (!bucketExists) {
387
+ const seriesTracked = runSql$3(sql, `SELECT 1 AS c FROM "${METRIC_HISTORY_TABLE}" WHERE series_key = ? LIMIT 1`, key).toArray().length > 0;
388
+ if (!seriesTracked) {
389
+ const seriesCountRow = runSql$3(sql, `SELECT COUNT(DISTINCT series_key) AS n FROM "${METRIC_HISTORY_TABLE}"`).one();
390
+ if (seriesCountRow.n >= METRIC_HISTORY_MAX_SERIES) {
391
+ return;
392
+ }
393
+ }
394
+ }
395
+ const exemplar = exemplarTraceId ?? null;
396
+ runSql$3(
397
+ sql,
398
+ `INSERT INTO "${METRIC_HISTORY_TABLE}"
399
+ (series_key, bucket_ms, name, kind, attrs, function_path, shard_key, count, sum, min, max, last, last_ts, exemplar_trace)
400
+ VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?)
401
+ ON CONFLICT(series_key, bucket_ms) DO UPDATE SET
402
+ count = count + 1,
403
+ sum = sum + excluded.sum,
404
+ min = MIN(min, excluded.min),
405
+ max = MAX(max, excluded.max),
406
+ last = excluded.last,
407
+ last_ts = excluded.last_ts,
408
+ exemplar_trace = CASE WHEN excluded.exemplar_trace IS NULL THEN exemplar_trace ELSE excluded.exemplar_trace END`,
409
+ key,
410
+ bucket,
411
+ event.name,
412
+ event.kind,
413
+ stableStringify(event.attributes ?? {}),
414
+ event.functionPath,
415
+ // eslint-disable-next-line unicorn/no-null -- SQL NULL for the unnamed root DO's absent shard key.
416
+ event.shardKey ?? null,
417
+ event.value,
418
+ event.value,
419
+ event.value,
420
+ event.value,
421
+ event.ts,
422
+ exemplar
423
+ );
424
+ if (!bucketExists) {
425
+ runSql$3(
426
+ sql,
427
+ `DELETE FROM "${METRIC_HISTORY_TABLE}"
428
+ WHERE series_key = ?
429
+ AND bucket_ms <= (
430
+ SELECT MAX(bucket_ms) - ? FROM "${METRIC_HISTORY_TABLE}" WHERE series_key = ?
431
+ )`,
432
+ key,
433
+ METRIC_HISTORY_BUCKET_RETENTION * METRIC_HISTORY_BUCKET_MS,
434
+ key
435
+ );
436
+ }
437
+ };
438
+ const parseAttributes = (raw) => {
439
+ if (raw === "" || raw === "{}") {
440
+ return void 0;
441
+ }
442
+ try {
443
+ const parsed = JSON.parse(raw);
444
+ return parsed !== null && typeof parsed === "object" ? parsed : void 0;
445
+ } catch {
446
+ return void 0;
447
+ }
448
+ };
449
+ const readMetricHistory = (sql, options = {}) => {
450
+ ensureMetricHistoryTable(sql);
451
+ const rows = options.sinceMs === void 0 ? runSql$3(sql, `SELECT * FROM "${METRIC_HISTORY_TABLE}" ORDER BY bucket_ms DESC LIMIT ?`, METRIC_HISTORY_READ_LIMIT).toArray() : runSql$3(
452
+ sql,
453
+ `SELECT * FROM "${METRIC_HISTORY_TABLE}" WHERE bucket_ms >= ? ORDER BY bucket_ms DESC LIMIT ?`,
454
+ options.sinceMs,
455
+ METRIC_HISTORY_READ_LIMIT
456
+ ).toArray();
457
+ const bySeries = /* @__PURE__ */ new Map();
458
+ for (const row of rows) {
459
+ let series = bySeries.get(row.series_key);
460
+ if (series === void 0) {
461
+ const attributes = parseAttributes(row.attrs);
462
+ series = {
463
+ ...attributes === void 0 ? {} : { attributes },
464
+ functionPath: row.function_path,
465
+ kind: row.kind,
466
+ name: row.name,
467
+ points: [],
468
+ ...row.shard_key === null ? {} : { shardKey: row.shard_key }
469
+ };
470
+ bySeries.set(row.series_key, series);
471
+ }
472
+ series.points.push({
473
+ bucketMs: row.bucket_ms,
474
+ count: row.count,
475
+ ...row.exemplar_trace === null ? {} : { exemplarTraceId: row.exemplar_trace },
476
+ last: row.last,
477
+ max: row.max,
478
+ min: row.min,
479
+ sum: row.sum
480
+ });
481
+ }
482
+ for (const series of bySeries.values()) {
483
+ series.points.sort((a, b) => a.bucketMs - b.bucketMs);
484
+ }
485
+ return { series: [...bySeries.values()] };
486
+ };
487
+
345
488
  const QUERY_METRICS_TABLE = "__lunora_metrics_queries";
346
489
  const QUERY_METRICS_MAX_SQL_LEN = 512;
347
490
  const QUERY_METRICS_MAX_STATEMENTS = 500;
@@ -4658,15 +4801,23 @@ class ShardDO {
4658
4801
  * cross-instance aggregation is still the sink's job.
4659
4802
  */
4660
4803
  recordMetric(event, sink) {
4661
- try {
4662
- this.metricSeries.push(event);
4663
- } catch {
4664
- }
4665
- if (sink?.onMetric) {
4804
+ const exemplarTraceId = this.currentRequestTrace?.traceId;
4805
+ const stamped = exemplarTraceId === void 0 ? event : { ...event, traceId: exemplarTraceId };
4806
+ const bestEffort = (run) => {
4666
4807
  try {
4667
- sink.onMetric(event, { waitUntil: this.state.waitUntil?.bind(this.state) });
4808
+ run();
4668
4809
  } catch {
4669
4810
  }
4811
+ };
4812
+ bestEffort(() => {
4813
+ this.metricSeries.push(stamped);
4814
+ });
4815
+ const rawSql = this.state.storage.sql;
4816
+ bestEffort(() => {
4817
+ recordMetricHistory(rawSql, stamped, exemplarTraceId);
4818
+ });
4819
+ if (sink?.onMetric) {
4820
+ bestEffort(() => sink.onMetric?.(stamped, { waitUntil: this.state.waitUntil?.bind(this.state) }));
4670
4821
  }
4671
4822
  }
4672
4823
  /**
@@ -5872,6 +6023,9 @@ class ShardDO {
5872
6023
  if (functionPath === ADMIN_FUNCTIONS.getMetricSeries) {
5873
6024
  return { series: this.metricSeries.entries() };
5874
6025
  }
6026
+ if (functionPath === ADMIN_FUNCTIONS.getMetricHistory) {
6027
+ return readMetricHistory(this.sql);
6028
+ }
5875
6029
  if (functionPath === ADMIN_FUNCTIONS.getSettings) {
5876
6030
  return buildSettings(this.env);
5877
6031
  }
@@ -69,10 +69,19 @@ const createTracer = (deps) => {
69
69
  const spanId = otlpRandomHex(8);
70
70
  const startTs = Date.now();
71
71
  const normalized = normalizeLogFields(attributes);
72
+ const collected = {};
73
+ const spanHandle = {
74
+ setAttribute: (key, value) => {
75
+ Object.assign(collected, normalizeLogFields({ [key]: value }));
76
+ },
77
+ setAttributes: (fields) => {
78
+ Object.assign(collected, normalizeLogFields(fields));
79
+ }
80
+ };
72
81
  let ok = true;
73
82
  let error;
74
83
  try {
75
- return await function_(tracerFor(spanId));
84
+ return await function_(tracerFor(spanId), spanHandle);
76
85
  } catch (error_) {
77
86
  ok = false;
78
87
  error = {
@@ -84,8 +93,9 @@ const createTracer = (deps) => {
84
93
  throw error_;
85
94
  } finally {
86
95
  try {
96
+ const merged = { ...normalized, ...collected };
87
97
  record({
88
- ...normalized === void 0 ? {} : { attributes: normalized },
98
+ ...Object.keys(merged).length === 0 ? {} : { attributes: merged },
89
99
  durationMs: Date.now() - startTs,
90
100
  ...error === void 0 ? {} : { error },
91
101
  functionPath,
@@ -1 +1 @@
1
- export { c as createMetrics, a as createTracer, d as dispatchRootSpan } from './context-telemetry-DWfYDxCS.mjs';
1
+ export { c as createMetrics, a as createTracer, d as dispatchRootSpan } from './context-telemetry-CqcOObBl.mjs';
@@ -1,5 +1,5 @@
1
1
  import { LunoraError } from '@lunora/errors';
2
- import { RELATION_FUNCTION_PREFIX } from './ADMIN_FUNCTIONS-DVk02KpP.mjs';
2
+ import { RELATION_FUNCTION_PREFIX } from './ADMIN_FUNCTIONS-CnZkbXH_.mjs';
3
3
 
4
4
  const serveRelationFanout = async (schema, database, functionPath, args) => {
5
5
  const table = typeof args["table"] === "string" ? args["table"] : "";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/do",
3
- "version": "1.0.0-alpha.38",
3
+ "version": "1.0.0-alpha.39",
4
4
  "description": "Lunora Durable Objects: ShardDO (SQLite, OCC, hibernated WebSocket subscriptions) and SessionDO",
5
5
  "keywords": [
6
6
  "cloudflare",