@lunora/server 1.0.0-alpha.220 → 1.0.0-alpha.221

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.
@@ -1,5 +1,5 @@
1
1
  import { SqlExec } from '@lunora/shard-engine';
2
- import { DatabaseWriter, Schema } from "./types.mjs";
2
+ import { D as DatabaseWriter, S as Schema } from "./packem_shared/types.d-XjrkWPuq.mjs";
3
3
  import '@lunora/values';
4
4
  /** The kind of a registered Lunora function. */
5
5
  type FunctionKind = "action" | "mutation" | "query";
@@ -1,5 +1,5 @@
1
1
  import { SqlExec } from '@lunora/shard-engine';
2
- import { DatabaseWriter, Schema } from "./types.js";
2
+ import { D as DatabaseWriter, S as Schema } from "./packem_shared/types.d-XjrkWPuq.js";
3
3
  import '@lunora/values';
4
4
  /** The kind of a registered Lunora function. */
5
5
  type FunctionKind = "action" | "mutation" | "query";
package/dist/index.d.mts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Validator, Infer, ColumnValidator, v, Id, ValidatorMap, InferValidatorMap } from '@lunora/values';
2
2
  export { type ColumnValidator, type GeoPoint, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
3
- import { ArgsValidator, InferArgs, RegisteredAction, ExposeConfig, X402ProcedureConfig, ActionCtx, MutationCtx, RegisteredMutation, QueryCtx, RegisteredQuery, DurableStreamOptions, RegisteredStream, FunctionKind, TableDefinition, RegisteredFunction, VectorIndexDefinition, Schema, AggregateOp, GlobalBackend, KeyedRelationDefinition, RelationThrough, ThroughRelationDefinition, OnDeleteAction, RelationDefinition, SearchLanguage, SearchStrategy, ExternalSourceDefinition, TriggerBuilder, TriggerDefinition, VectorEmbedder, VectorMetric, DurableObjectJurisdiction, AggregateIndexDefinition, RankIndexDefinition, Secrets, LifecycleEvent, ShardInitEvent, RegisteredLifecycleHook, WhisperEvent } from "./types.mjs";
4
- export type { AuthState, CachePurge, DatabaseReader, DatabaseWriter, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, IndexDefinition, IndexRangeBuilder, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationStorage, PaginationOptions, PaginationResult, PatchIfResult, RankSortKey, ReadOnlyStorage, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, SearchFilterBuilder, SearchIndexDefinition, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableReader, TableVectorIndex, TriggerAggregateOptions, TriggerCtx, TriggerDatabase, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorMatch, VectorMatches, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows } from "./types.mjs";
3
+ import { A as ArgsValidator, I as InferArgs, R as RegisteredAction, E as ExposeConfig, X as X402ProcedureConfig, b as ActionCtx, M as MutationCtx, c as RegisteredMutation, Q as QueryCtx, d as RegisteredQuery, e as DurableStreamOptions, f as RegisteredStream, F as FunctionKind, T as TableDefinition, g as RegisteredFunction, V as VectorIndexDefinition, S as Schema, h as AggregateOp, G as GlobalBackend, K as KeyedRelationDefinition, i as RelationThrough, j as ThroughRelationDefinition, O as OnDeleteAction, k as RelationDefinition, l as SearchLanguage, m as SearchStrategy, n as ExternalSourceDefinition, o as TriggerBuilder, p as TriggerDefinition, q as VectorEmbedder, r as VectorMetric, s as DurableObjectJurisdiction, t as AggregateIndexDefinition, u as RankIndexDefinition, v as Secrets, w as LiveTopicRef, x as LifecycleEvent, y as ShardInitEvent, z as RegisteredLifecycleHook, W as WhisperEvent } from "./packem_shared/types.d-XjrkWPuq.mjs";
4
+ export type { B as AuthState, C as CachePurge, H as DatabaseReader, D as DatabaseWriter, J as FunctionVisibility, N as GeoBoundingBox, P as GeoFilterBuilder, U as GeoIndexDefinition, Y as GeoPointInput, Z as IndexDefinition, _ as IndexRangeBuilder, $ as LifecycleEventKind, a0 as LogFields, a1 as LunoraLogMethod, a2 as LunoraLogger, a3 as LunoraMetrics, L as LunoraTracer, a4 as LunoraWideEvent, a5 as MutationStorage, a6 as PaginationOptions, a7 as PaginationResult, a8 as PatchIfResult, a9 as RankSortKey, aa as ReadOnlyStorage, ab as RelatedDirection, ac as RelatedNode, ad as RelatedOptions, ae as RelatedPage, af as RelatedStart, ag as RelatedStartReference, ah as RestCacheConfig, ai as RetryPolicy, aj as RunQueryOptions, ak as ScheduledFunctionDoc, al as ScheduledJob, am as Scheduler, an as SearchFilterBuilder, ao as SearchIndexDefinition, ap as ShardMode, aq as SpanContextIds, ar as SpanEvaluation, a as SpanHandle, as as SpanIdentity, at as SpanKind, au as SpanLink, av as SpanOptions, aw as Storage, ax as StorageListOptions, ay as StorageListResult, az as StorageMetadata, aA as StorageMultipartUpload, aB as StorageMultipartUploadOptions, aC as StorageObjectBody, aD as StorageObjectHead, aE as StorageRange, aF as StorageUploadBody, aG as StorageUploadOptions, aH as StorageUploadResult, aI as StorageUploadedPart, aJ as SystemDatabaseReader, aK as SystemDoc, aL as SystemQuery, aM as SystemTableName, aN as TableReader, aO as TableVectorIndex, aP as TriggerAggregateOptions, aQ as TriggerCtx, aR as TriggerDatabase, aS as TriggerDeleteEvent, aT as TriggerEvent, aU as TriggerGroupByEntry, aV as TriggerGroupByOptions, aW as TriggerHandler, aX as TriggerInsertEvent, aY as TriggerOp, aZ as TriggerQueryArgs, a_ as TriggerQueryPage, a$ as TriggerRankOptions, b0 as TriggerRankPageOptions, b1 as TriggerRankResult, b2 as TriggerRow, b3 as TriggerTiming, b4 as TriggerUpdateEvent, b5 as TtlDefinition, b6 as VectorMatch, b7 as VectorMatches, b8 as VectorQueryInput, b9 as VectorRecord, ba as VectorSearch, bb as VectorSearchReader, bc as VectorUpsertInput, bd as WorkflowCreateOptions, be as WorkflowEventDefinition, bf as WorkflowHandle, bg as WorkflowInstance, bh as WorkflowInstanceEvent, bi as WorkflowInstanceStatus, bj as WorkflowStatusResult, bk as Workflows } from "./packem_shared/types.d-XjrkWPuq.mjs";
5
5
  import { LunoraError } from '@lunora/errors';
6
6
  export { LunoraError, type LunoraErrorCode } from '@lunora/errors';
7
7
  import { Context, Hono } from 'hono';
@@ -1958,16 +1958,10 @@ type ShardFetch = (shardKey: string | undefined, path: string, init?: ShardFetch
1958
1958
  interface LivePublishOptions {
1959
1959
  /** The shard to publish on. Defaults to the ctx's default shard. */
1960
1960
  shardKey?: string;
1961
- /**
1962
- * The `id` of the `defineLiveStream` whose subscribers see the event. A
1963
- * subscriber follows a topic through the stream that authorized it, so a
1964
- * publish reaches only that stream's subscribers.
1965
- */
1966
- stream: string;
1967
1961
  }
1968
1962
  /**
1969
- * `ctx.live` — publish an arbitrary event to a named topic. The event reaches
1970
- * the SSE subscribers of `options.stream` that followed the topic, and the
1963
+ * `ctx.live` — publish an event to a declared live topic. The event reaches the
1964
+ * SSE subscribers of the stream that declares the topic and followed it, and the
1971
1965
  * WebSocket whisper members that hold a live grant for that stream and topic
1972
1966
  * (see the live-stream docblock).
1973
1967
  *
@@ -1976,14 +1970,16 @@ interface LivePublishOptions {
1976
1970
  */
1977
1971
  interface LivePublisher {
1978
1972
  /**
1979
- * Publish `payload` to `topic` on `options.stream`. Best-effort — a topic
1980
- * with no subscribers is a no-op. Rejects when the shard refuses the publish:
1981
- * a `room:` topic (403), a topic over the control-key bound (400), or a
1973
+ * Publish `payload` to the topic `ref` names, from `_generated/live.ts`
1974
+ * (`live.posts.post({ postId })`). The stream comes from the ref, and the payload
1975
+ * is checked against the validator the topic declares. Best-effort — a topic with
1976
+ * no subscribers is a no-op. Rejects when the shard refuses the publish: a payload
1977
+ * its validator rejects or an undeclared topic (400), a `room:` topic (403), or a
1982
1978
  * payload over the publish cap (413), so a refused publish is not silently
1983
1979
  * dropped. On a target that does not serve live streams it rejects with
1984
1980
  * `LIVE_STREAMS_UNSUPPORTED`.
1985
1981
  */
1986
- publish: (topic: string, payload: unknown, options: LivePublishOptions) => Promise<void>;
1982
+ publish: <Payload>(topic: LiveTopicRef<Payload>, payload: NoInfer<Payload>, options?: LivePublishOptions) => Promise<void>;
1987
1983
  }
1988
1984
  /**
1989
1985
  * The hono {@link https://hono.dev | Hono} environment used by {@link httpRouter}.
@@ -2533,16 +2529,34 @@ declare const clampLimit: (limit: number | undefined, fallback: number, maxLimit
2533
2529
  * the config requires the second call.
2534
2530
  */
2535
2531
  declare const defineListArgs: <TDocument>() => <F extends ListFilterShape<TDocument>, O extends keyof TDocument & string>(config: DefineListArgsConfig<F, O>) => ListArgsSpec<TDocument, F, O>;
2532
+ /** One declared topic: the key that addresses it (string-valued fields, in order) and the payload it carries. */
2533
+ interface LiveTopicDeclaration {
2534
+ /** Absent for a keyless topic, whose wire topic is just its name. Every value is a string on the wire. */
2535
+ key?: Readonly<Record<string, Validator<string>>>;
2536
+ payload: Validator;
2537
+ }
2538
+ /** The `topics` map of a {@link LiveStreamConfig}. */
2539
+ type LiveTopics = Readonly<Record<string, LiveTopicDeclaration>>;
2540
+ /** The key a topic is addressed by, as the validators infer it. A keyless topic has an empty key. */
2541
+ type LiveTopicKey<Topic extends LiveTopicDeclaration> = Topic["key"] extends Readonly<Record<string, Validator>> ? { readonly [Field in keyof Topic["key"]]: Infer<Topic["key"][Field]>; } : Readonly<Record<string, never>>;
2542
+ /** The payload a topic carries, as its validator infers it. */
2543
+ type LiveTopicPayload<Topic extends LiveTopicDeclaration> = Infer<Topic["payload"]>;
2544
+ /** What `onSubscribe` receives: the parsed topic, narrowed by declaration so `key` matches `topic`. */
2545
+ type LiveSubscribeOptions<Topics extends LiveTopics> = { [Name in keyof Topics & string]: {
2546
+ ctx: HttpActionCtx;
2547
+ key: LiveTopicKey<Topics[Name]>;
2548
+ /** The wire topic exactly as the browser sent it. */
2549
+ raw: string;
2550
+ topic: Name;
2551
+ }; }[keyof Topics & string];
2536
2552
  /**
2537
2553
  * Verdict handler for a live-topic subscribe. Return `true` to allow; anything
2538
- * else denies (and a throw denies).
2554
+ * else denies (and a throw denies). It is only called for a topic that parsed
2555
+ * against the stream's declaration.
2539
2556
  */
2540
- type LiveSubscribeHandler = (options: {
2541
- ctx: HttpActionCtx;
2542
- topic: string;
2543
- }) => boolean | Promise<boolean>;
2557
+ type LiveSubscribeHandler<Topics extends LiveTopics = LiveTopics> = (options: LiveSubscribeOptions<Topics>) => boolean | Promise<boolean>;
2544
2558
  /** Config for {@link defineLiveStream}. */
2545
- interface LiveStreamConfig {
2559
+ interface LiveStreamConfig<Topics extends LiveTopics = LiveTopics> {
2546
2560
  /**
2547
2561
  * Opt-in for a public stream. It never skips {@link LiveStreamConfig.onSubscribe}:
2548
2562
  * when a handler is present, the handler decides for every caller and this flag
@@ -2557,10 +2571,16 @@ interface LiveStreamConfig {
2557
2571
  * Per-topic authorization, consulted for every subscribe from every caller.
2558
2572
  * Omitted ⇒ default-deny (unless `allowAnonymousControl` admits anonymous callers).
2559
2573
  */
2560
- onSubscribe?: LiveSubscribeHandler;
2574
+ onSubscribe?: LiveSubscribeHandler<Topics>;
2575
+ /**
2576
+ * The topics this stream carries, by name. A subscribe or publish naming anything
2577
+ * else is refused. A topic with a `key` is addressed as `name:<key values>`; one
2578
+ * without is addressed by its name alone.
2579
+ */
2580
+ topics: Topics;
2561
2581
  }
2562
- /** The two route handlers {@link defineLiveStream} produces. */
2563
- interface LiveStream {
2582
+ /** The two route handlers {@link defineLiveStream} produces, plus the declaration they enforce. */
2583
+ interface LiveStream<Topics extends LiveTopics = LiveTopics> {
2564
2584
  /** Mount with `app.get(stream.connectPath, stream.connect)`. Returns the SSE response. */
2565
2585
  connect: LunoraRouteHandler;
2566
2586
  /** `GET` path for the SSE connection. */
@@ -2570,6 +2590,14 @@ interface LiveStream {
2570
2590
  /** `POST` path for subscribe / unsubscribe control. */
2571
2591
  controlPath: string;
2572
2592
  id: string;
2593
+ readonly topics: Topics;
2594
+ /**
2595
+ * Check a publish against the declaration: the wire `topic` must be a declared
2596
+ * topic in its canonical spelling and `payload` must satisfy its validator.
2597
+ * @returns the payload as the validator parsed it, which is what subscribers must receive
2598
+ * @throws LunoraError `BAD_REQUEST` (400) when either does not
2599
+ */
2600
+ validatePublish: (topic: string, payload: unknown) => unknown;
2573
2601
  }
2574
2602
  /**
2575
2603
  * Define a live topic stream. See the module docblock for the authorization
@@ -2584,7 +2612,7 @@ interface LiveStream {
2584
2612
  * `.deliveryAuthorization(...)`, because the shard answers every `/_lunora/live/*`
2585
2613
  * route with 501 in that mode.
2586
2614
  */
2587
- declare const defineLiveStream: (config: LiveStreamConfig) => LiveStream;
2615
+ declare const defineLiveStream: <const Topics extends LiveTopics>(config: LiveStreamConfig<Topics>) => LiveStream<Topics>;
2588
2616
  /**
2589
2617
  * Structural mirrors of `@lunora/shard-engine`'s rank-page-row shapes
2590
2618
  * (`RankPageRowKey` / `RankPageRow` / `ShardRankPageResult`) — the return type
@@ -4288,7 +4316,7 @@ type RegisteredWhisperAuthorizer = RegisteredFunction<Record<string, never>, boo
4288
4316
  */
4289
4317
  declare const onWhisper: (handler: WhisperAuthorizeHandler) => RegisteredWhisperAuthorizer;
4290
4318
  declare const VERSION = "0.0.0";
4291
- export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineRoomOptions, type DefineStorageRuleInput, type DefineWebSocketOptions, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LivePublishOptions, type LivePublisher, type LiveStream, type LiveStreamConfig, type LiveSubscribeHandler, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type ModuleConfig, type ModuleDefinition, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type PlatformAdminCheck, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredRoom, type RegisteredShape, type RegisteredStream, type RegisteredWebSocket, type RegisteredWhisperAuthorizer, type RelationBuilder, type RelationDefinition, type RelationThrough, type RlsOptions, type RlsReadRegistry, type Role, type RoomJoinHandler, type RoomLeaveHandler, type RoomMessageHandler, type RoomMessageOf, type RoomSocket, type Schema, type SchemaExtension, type ServiceBindingSpec, type ServiceFetcher, type ServiceRpc, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardFetch, type ShardFetchInit, type ShardInitEvent, type ShardInitHandler, type SseEvent, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WebSocketCloseHandler, type WebSocketHandle, type WebSocketMessageHandler, type WebSocketOpenHandler, type WhereInput, type WhisperAuthorizeHandler, type WhisperEvent, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, createServices, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineIdentityGuard, defineListArgs, defineLiveStream, defineMigration, defineModule, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineRoom, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, defineWebSocket, deny, documentHistoryExtension, flushDeferredDeletes,
4319
+ export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineRoomOptions, type DefineStorageRuleInput, type DefineWebSocketOptions, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LivePublishOptions, type LivePublisher, type LiveStream, type LiveStreamConfig, type LiveSubscribeHandler, type LiveSubscribeOptions, type LiveTopicDeclaration, type LiveTopicKey, type LiveTopicPayload, type LiveTopicRef, type LiveTopics, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type ModuleConfig, type ModuleDefinition, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type PlatformAdminCheck, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredRoom, type RegisteredShape, type RegisteredStream, type RegisteredWebSocket, type RegisteredWhisperAuthorizer, type RelationBuilder, type RelationDefinition, type RelationThrough, type RlsOptions, type RlsReadRegistry, type Role, type RoomJoinHandler, type RoomLeaveHandler, type RoomMessageHandler, type RoomMessageOf, type RoomSocket, type Schema, type SchemaExtension, type ServiceBindingSpec, type ServiceFetcher, type ServiceRpc, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardFetch, type ShardFetchInit, type ShardInitEvent, type ShardInitHandler, type SseEvent, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WebSocketCloseHandler, type WebSocketHandle, type WebSocketMessageHandler, type WebSocketOpenHandler, type WhereInput, type WhisperAuthorizeHandler, type WhisperEvent, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, createServices, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineIdentityGuard, defineListArgs, defineLiveStream, defineMigration, defineModule, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineRoom, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, defineWebSocket, deny, documentHistoryExtension, flushDeferredDeletes,
4292
4320
  /**
4293
4321
  * True when `value` is safe to use as an HTTP header field-value: no CR, LF, or
4294
4322
  * NUL. Guards against response-header injection / `Headers`-construction throws
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Validator, Infer, ColumnValidator, v, Id, ValidatorMap, InferValidatorMap } from '@lunora/values';
2
2
  export { type ColumnValidator, type GeoPoint, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
3
- import { ArgsValidator, InferArgs, RegisteredAction, ExposeConfig, X402ProcedureConfig, ActionCtx, MutationCtx, RegisteredMutation, QueryCtx, RegisteredQuery, DurableStreamOptions, RegisteredStream, FunctionKind, TableDefinition, RegisteredFunction, VectorIndexDefinition, Schema, AggregateOp, GlobalBackend, KeyedRelationDefinition, RelationThrough, ThroughRelationDefinition, OnDeleteAction, RelationDefinition, SearchLanguage, SearchStrategy, ExternalSourceDefinition, TriggerBuilder, TriggerDefinition, VectorEmbedder, VectorMetric, DurableObjectJurisdiction, AggregateIndexDefinition, RankIndexDefinition, Secrets, LifecycleEvent, ShardInitEvent, RegisteredLifecycleHook, WhisperEvent } from "./types.js";
4
- export type { AuthState, CachePurge, DatabaseReader, DatabaseWriter, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, IndexDefinition, IndexRangeBuilder, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationStorage, PaginationOptions, PaginationResult, PatchIfResult, RankSortKey, ReadOnlyStorage, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, SearchFilterBuilder, SearchIndexDefinition, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableReader, TableVectorIndex, TriggerAggregateOptions, TriggerCtx, TriggerDatabase, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorMatch, VectorMatches, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows } from "./types.js";
3
+ import { A as ArgsValidator, I as InferArgs, R as RegisteredAction, E as ExposeConfig, X as X402ProcedureConfig, b as ActionCtx, M as MutationCtx, c as RegisteredMutation, Q as QueryCtx, d as RegisteredQuery, e as DurableStreamOptions, f as RegisteredStream, F as FunctionKind, T as TableDefinition, g as RegisteredFunction, V as VectorIndexDefinition, S as Schema, h as AggregateOp, G as GlobalBackend, K as KeyedRelationDefinition, i as RelationThrough, j as ThroughRelationDefinition, O as OnDeleteAction, k as RelationDefinition, l as SearchLanguage, m as SearchStrategy, n as ExternalSourceDefinition, o as TriggerBuilder, p as TriggerDefinition, q as VectorEmbedder, r as VectorMetric, s as DurableObjectJurisdiction, t as AggregateIndexDefinition, u as RankIndexDefinition, v as Secrets, w as LiveTopicRef, x as LifecycleEvent, y as ShardInitEvent, z as RegisteredLifecycleHook, W as WhisperEvent } from "./packem_shared/types.d-XjrkWPuq.js";
4
+ export type { B as AuthState, C as CachePurge, H as DatabaseReader, D as DatabaseWriter, J as FunctionVisibility, N as GeoBoundingBox, P as GeoFilterBuilder, U as GeoIndexDefinition, Y as GeoPointInput, Z as IndexDefinition, _ as IndexRangeBuilder, $ as LifecycleEventKind, a0 as LogFields, a1 as LunoraLogMethod, a2 as LunoraLogger, a3 as LunoraMetrics, L as LunoraTracer, a4 as LunoraWideEvent, a5 as MutationStorage, a6 as PaginationOptions, a7 as PaginationResult, a8 as PatchIfResult, a9 as RankSortKey, aa as ReadOnlyStorage, ab as RelatedDirection, ac as RelatedNode, ad as RelatedOptions, ae as RelatedPage, af as RelatedStart, ag as RelatedStartReference, ah as RestCacheConfig, ai as RetryPolicy, aj as RunQueryOptions, ak as ScheduledFunctionDoc, al as ScheduledJob, am as Scheduler, an as SearchFilterBuilder, ao as SearchIndexDefinition, ap as ShardMode, aq as SpanContextIds, ar as SpanEvaluation, a as SpanHandle, as as SpanIdentity, at as SpanKind, au as SpanLink, av as SpanOptions, aw as Storage, ax as StorageListOptions, ay as StorageListResult, az as StorageMetadata, aA as StorageMultipartUpload, aB as StorageMultipartUploadOptions, aC as StorageObjectBody, aD as StorageObjectHead, aE as StorageRange, aF as StorageUploadBody, aG as StorageUploadOptions, aH as StorageUploadResult, aI as StorageUploadedPart, aJ as SystemDatabaseReader, aK as SystemDoc, aL as SystemQuery, aM as SystemTableName, aN as TableReader, aO as TableVectorIndex, aP as TriggerAggregateOptions, aQ as TriggerCtx, aR as TriggerDatabase, aS as TriggerDeleteEvent, aT as TriggerEvent, aU as TriggerGroupByEntry, aV as TriggerGroupByOptions, aW as TriggerHandler, aX as TriggerInsertEvent, aY as TriggerOp, aZ as TriggerQueryArgs, a_ as TriggerQueryPage, a$ as TriggerRankOptions, b0 as TriggerRankPageOptions, b1 as TriggerRankResult, b2 as TriggerRow, b3 as TriggerTiming, b4 as TriggerUpdateEvent, b5 as TtlDefinition, b6 as VectorMatch, b7 as VectorMatches, b8 as VectorQueryInput, b9 as VectorRecord, ba as VectorSearch, bb as VectorSearchReader, bc as VectorUpsertInput, bd as WorkflowCreateOptions, be as WorkflowEventDefinition, bf as WorkflowHandle, bg as WorkflowInstance, bh as WorkflowInstanceEvent, bi as WorkflowInstanceStatus, bj as WorkflowStatusResult, bk as Workflows } from "./packem_shared/types.d-XjrkWPuq.js";
5
5
  import { LunoraError } from '@lunora/errors';
6
6
  export { LunoraError, type LunoraErrorCode } from '@lunora/errors';
7
7
  import { Context, Hono } from 'hono';
@@ -1958,16 +1958,10 @@ type ShardFetch = (shardKey: string | undefined, path: string, init?: ShardFetch
1958
1958
  interface LivePublishOptions {
1959
1959
  /** The shard to publish on. Defaults to the ctx's default shard. */
1960
1960
  shardKey?: string;
1961
- /**
1962
- * The `id` of the `defineLiveStream` whose subscribers see the event. A
1963
- * subscriber follows a topic through the stream that authorized it, so a
1964
- * publish reaches only that stream's subscribers.
1965
- */
1966
- stream: string;
1967
1961
  }
1968
1962
  /**
1969
- * `ctx.live` — publish an arbitrary event to a named topic. The event reaches
1970
- * the SSE subscribers of `options.stream` that followed the topic, and the
1963
+ * `ctx.live` — publish an event to a declared live topic. The event reaches the
1964
+ * SSE subscribers of the stream that declares the topic and followed it, and the
1971
1965
  * WebSocket whisper members that hold a live grant for that stream and topic
1972
1966
  * (see the live-stream docblock).
1973
1967
  *
@@ -1976,14 +1970,16 @@ interface LivePublishOptions {
1976
1970
  */
1977
1971
  interface LivePublisher {
1978
1972
  /**
1979
- * Publish `payload` to `topic` on `options.stream`. Best-effort — a topic
1980
- * with no subscribers is a no-op. Rejects when the shard refuses the publish:
1981
- * a `room:` topic (403), a topic over the control-key bound (400), or a
1973
+ * Publish `payload` to the topic `ref` names, from `_generated/live.ts`
1974
+ * (`live.posts.post({ postId })`). The stream comes from the ref, and the payload
1975
+ * is checked against the validator the topic declares. Best-effort — a topic with
1976
+ * no subscribers is a no-op. Rejects when the shard refuses the publish: a payload
1977
+ * its validator rejects or an undeclared topic (400), a `room:` topic (403), or a
1982
1978
  * payload over the publish cap (413), so a refused publish is not silently
1983
1979
  * dropped. On a target that does not serve live streams it rejects with
1984
1980
  * `LIVE_STREAMS_UNSUPPORTED`.
1985
1981
  */
1986
- publish: (topic: string, payload: unknown, options: LivePublishOptions) => Promise<void>;
1982
+ publish: <Payload>(topic: LiveTopicRef<Payload>, payload: NoInfer<Payload>, options?: LivePublishOptions) => Promise<void>;
1987
1983
  }
1988
1984
  /**
1989
1985
  * The hono {@link https://hono.dev | Hono} environment used by {@link httpRouter}.
@@ -2533,16 +2529,34 @@ declare const clampLimit: (limit: number | undefined, fallback: number, maxLimit
2533
2529
  * the config requires the second call.
2534
2530
  */
2535
2531
  declare const defineListArgs: <TDocument>() => <F extends ListFilterShape<TDocument>, O extends keyof TDocument & string>(config: DefineListArgsConfig<F, O>) => ListArgsSpec<TDocument, F, O>;
2532
+ /** One declared topic: the key that addresses it (string-valued fields, in order) and the payload it carries. */
2533
+ interface LiveTopicDeclaration {
2534
+ /** Absent for a keyless topic, whose wire topic is just its name. Every value is a string on the wire. */
2535
+ key?: Readonly<Record<string, Validator<string>>>;
2536
+ payload: Validator;
2537
+ }
2538
+ /** The `topics` map of a {@link LiveStreamConfig}. */
2539
+ type LiveTopics = Readonly<Record<string, LiveTopicDeclaration>>;
2540
+ /** The key a topic is addressed by, as the validators infer it. A keyless topic has an empty key. */
2541
+ type LiveTopicKey<Topic extends LiveTopicDeclaration> = Topic["key"] extends Readonly<Record<string, Validator>> ? { readonly [Field in keyof Topic["key"]]: Infer<Topic["key"][Field]>; } : Readonly<Record<string, never>>;
2542
+ /** The payload a topic carries, as its validator infers it. */
2543
+ type LiveTopicPayload<Topic extends LiveTopicDeclaration> = Infer<Topic["payload"]>;
2544
+ /** What `onSubscribe` receives: the parsed topic, narrowed by declaration so `key` matches `topic`. */
2545
+ type LiveSubscribeOptions<Topics extends LiveTopics> = { [Name in keyof Topics & string]: {
2546
+ ctx: HttpActionCtx;
2547
+ key: LiveTopicKey<Topics[Name]>;
2548
+ /** The wire topic exactly as the browser sent it. */
2549
+ raw: string;
2550
+ topic: Name;
2551
+ }; }[keyof Topics & string];
2536
2552
  /**
2537
2553
  * Verdict handler for a live-topic subscribe. Return `true` to allow; anything
2538
- * else denies (and a throw denies).
2554
+ * else denies (and a throw denies). It is only called for a topic that parsed
2555
+ * against the stream's declaration.
2539
2556
  */
2540
- type LiveSubscribeHandler = (options: {
2541
- ctx: HttpActionCtx;
2542
- topic: string;
2543
- }) => boolean | Promise<boolean>;
2557
+ type LiveSubscribeHandler<Topics extends LiveTopics = LiveTopics> = (options: LiveSubscribeOptions<Topics>) => boolean | Promise<boolean>;
2544
2558
  /** Config for {@link defineLiveStream}. */
2545
- interface LiveStreamConfig {
2559
+ interface LiveStreamConfig<Topics extends LiveTopics = LiveTopics> {
2546
2560
  /**
2547
2561
  * Opt-in for a public stream. It never skips {@link LiveStreamConfig.onSubscribe}:
2548
2562
  * when a handler is present, the handler decides for every caller and this flag
@@ -2557,10 +2571,16 @@ interface LiveStreamConfig {
2557
2571
  * Per-topic authorization, consulted for every subscribe from every caller.
2558
2572
  * Omitted ⇒ default-deny (unless `allowAnonymousControl` admits anonymous callers).
2559
2573
  */
2560
- onSubscribe?: LiveSubscribeHandler;
2574
+ onSubscribe?: LiveSubscribeHandler<Topics>;
2575
+ /**
2576
+ * The topics this stream carries, by name. A subscribe or publish naming anything
2577
+ * else is refused. A topic with a `key` is addressed as `name:<key values>`; one
2578
+ * without is addressed by its name alone.
2579
+ */
2580
+ topics: Topics;
2561
2581
  }
2562
- /** The two route handlers {@link defineLiveStream} produces. */
2563
- interface LiveStream {
2582
+ /** The two route handlers {@link defineLiveStream} produces, plus the declaration they enforce. */
2583
+ interface LiveStream<Topics extends LiveTopics = LiveTopics> {
2564
2584
  /** Mount with `app.get(stream.connectPath, stream.connect)`. Returns the SSE response. */
2565
2585
  connect: LunoraRouteHandler;
2566
2586
  /** `GET` path for the SSE connection. */
@@ -2570,6 +2590,14 @@ interface LiveStream {
2570
2590
  /** `POST` path for subscribe / unsubscribe control. */
2571
2591
  controlPath: string;
2572
2592
  id: string;
2593
+ readonly topics: Topics;
2594
+ /**
2595
+ * Check a publish against the declaration: the wire `topic` must be a declared
2596
+ * topic in its canonical spelling and `payload` must satisfy its validator.
2597
+ * @returns the payload as the validator parsed it, which is what subscribers must receive
2598
+ * @throws LunoraError `BAD_REQUEST` (400) when either does not
2599
+ */
2600
+ validatePublish: (topic: string, payload: unknown) => unknown;
2573
2601
  }
2574
2602
  /**
2575
2603
  * Define a live topic stream. See the module docblock for the authorization
@@ -2584,7 +2612,7 @@ interface LiveStream {
2584
2612
  * `.deliveryAuthorization(...)`, because the shard answers every `/_lunora/live/*`
2585
2613
  * route with 501 in that mode.
2586
2614
  */
2587
- declare const defineLiveStream: (config: LiveStreamConfig) => LiveStream;
2615
+ declare const defineLiveStream: <const Topics extends LiveTopics>(config: LiveStreamConfig<Topics>) => LiveStream<Topics>;
2588
2616
  /**
2589
2617
  * Structural mirrors of `@lunora/shard-engine`'s rank-page-row shapes
2590
2618
  * (`RankPageRowKey` / `RankPageRow` / `ShardRankPageResult`) — the return type
@@ -4288,7 +4316,7 @@ type RegisteredWhisperAuthorizer = RegisteredFunction<Record<string, never>, boo
4288
4316
  */
4289
4317
  declare const onWhisper: (handler: WhisperAuthorizeHandler) => RegisteredWhisperAuthorizer;
4290
4318
  declare const VERSION = "0.0.0";
4291
- export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineRoomOptions, type DefineStorageRuleInput, type DefineWebSocketOptions, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LivePublishOptions, type LivePublisher, type LiveStream, type LiveStreamConfig, type LiveSubscribeHandler, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type ModuleConfig, type ModuleDefinition, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type PlatformAdminCheck, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredRoom, type RegisteredShape, type RegisteredStream, type RegisteredWebSocket, type RegisteredWhisperAuthorizer, type RelationBuilder, type RelationDefinition, type RelationThrough, type RlsOptions, type RlsReadRegistry, type Role, type RoomJoinHandler, type RoomLeaveHandler, type RoomMessageHandler, type RoomMessageOf, type RoomSocket, type Schema, type SchemaExtension, type ServiceBindingSpec, type ServiceFetcher, type ServiceRpc, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardFetch, type ShardFetchInit, type ShardInitEvent, type ShardInitHandler, type SseEvent, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WebSocketCloseHandler, type WebSocketHandle, type WebSocketMessageHandler, type WebSocketOpenHandler, type WhereInput, type WhisperAuthorizeHandler, type WhisperEvent, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, createServices, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineIdentityGuard, defineListArgs, defineLiveStream, defineMigration, defineModule, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineRoom, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, defineWebSocket, deny, documentHistoryExtension, flushDeferredDeletes,
4319
+ export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineRoomOptions, type DefineStorageRuleInput, type DefineWebSocketOptions, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LivePublishOptions, type LivePublisher, type LiveStream, type LiveStreamConfig, type LiveSubscribeHandler, type LiveSubscribeOptions, type LiveTopicDeclaration, type LiveTopicKey, type LiveTopicPayload, type LiveTopicRef, type LiveTopics, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type ModuleConfig, type ModuleDefinition, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type PlatformAdminCheck, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredRoom, type RegisteredShape, type RegisteredStream, type RegisteredWebSocket, type RegisteredWhisperAuthorizer, type RelationBuilder, type RelationDefinition, type RelationThrough, type RlsOptions, type RlsReadRegistry, type Role, type RoomJoinHandler, type RoomLeaveHandler, type RoomMessageHandler, type RoomMessageOf, type RoomSocket, type Schema, type SchemaExtension, type ServiceBindingSpec, type ServiceFetcher, type ServiceRpc, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardFetch, type ShardFetchInit, type ShardInitEvent, type ShardInitHandler, type SseEvent, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WebSocketCloseHandler, type WebSocketHandle, type WebSocketMessageHandler, type WebSocketOpenHandler, type WhereInput, type WhisperAuthorizeHandler, type WhisperEvent, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, createServices, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineIdentityGuard, defineListArgs, defineLiveStream, defineMigration, defineModule, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineRoom, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, defineWebSocket, deny, documentHistoryExtension, flushDeferredDeletes,
4292
4320
  /**
4293
4321
  * True when `value` is safe to use as an HTTP header field-value: no CR, LF, or
4294
4322
  * NUL. Guards against response-header injection / `Headers`-construction throws
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-mmP-6BcT.mjs";import{initLunora as d}from"./packem_shared/initLunora-B-7Xs3Qq.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as S,flushDeferredDeletes as u,withDeferredDeletes as h}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-C7QLYr6C.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as A,DOCUMENT_HISTORY_TABLE as I,defineDocumentHistory as L,documentHistoryExtension as _}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-B5Zp-7SI.mjs";import{LunoraEnvError as M,defineEnv as P,redactSecrets as b}from"./packem_shared/LunoraEnvError-bkdMu_-N.mjs";import{bindOrm as F,bindTableFacade as O}from"./packem_shared/bindOrm-9fbLRbOb.mjs";import{httpAction as H,httpRoute as N,httpRouter as k,isSafeHeaderValue as w,lastEventId as U,sseEvent as B}from"./packem_shared/httpAction-D2S7bQzl.mjs";import{serveStorageObject as W}from"./packem_shared/serveStorageObject-aqBFrLyo.mjs";import{defineIdentity as Y}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as J}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as Q,onDisconnect as X,onShardInit as q}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as Z,DEFAULT_MAX_LIMIT as $,clampLimit as ee,defineListArgs as re}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineLiveStream as te}from"./packem_shared/defineLiveStream-BKomK5uG.mjs";import{defineMigration as ie}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as ae}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as de}from"./packem_shared/defineMutator-B4ipDtDR.mjs";import{platformAdmin as pe}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as ce,d as le,a as Ee,b as Se,e as ue,f as he,g as De,h as Te,i as ge,j as Re,k as Ae,m as Ie}from"./packem_shared/plugin-Bm9wIpiI.mjs";import{PRESENCE_DEFAULT_TTL_MS as _e,PRESENCE_TABLE as Ce,definePresence as Me,presenceExtension as Pe}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-DFpy5J8G.mjs";import{protectPublic as ye}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as Oe}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{defineRoom as He}from"./packem_shared/defineRoom-CoGi-xwm.mjs";import{createServices as ke}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Ue}from"./packem_shared/defineShape-CwKm5KLp.mjs";import{defineWebSocket as Ve}from"./packem_shared/defineWebSocket-BHoy6_ox.mjs";import{onWhisper as je}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Ge}from"@lunora/errors";import{cronJobs as Ke}from"@lunora/scheduler";import{ValidationError as Xe,v as qe}from"@lunora/values";import{allowAll as Ze,deny as $e,isDeny as er,toWhereInput as rr}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as tr}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as ir,buildRlsReadRegistry as fr,composeShapeReadWhere as ar}from"./packem_shared/assertShapesDeclareReadPolicies-Bg4Ter7Q.mjs";import{buildMaskRegistry as dr}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as pr,definePermission as xr,definePolicies as cr,definePolicy as lr,defineRole as Er}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as ur,defineStorageRules as hr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as Tr}from"./packem_shared/mask-D-jRCAhy.mjs";import{r as Rr}from"./packem_shared/middleware-3ySZVrpt.mjs";import{storageRules as Ir}from"./packem_shared/storageRules-CBLioxF7.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,Z as DEFAULT_LIMIT,$ as DEFAULT_MAX_LIMIT,A as DOCUMENT_HISTORY_REDACTED_FIELDS,I as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Ge as LunoraError,_e as PRESENCE_DEFAULT_TTL_MS,Ce as PRESENCE_TABLE,e as VERSION,Xe as ValidationError,i as actionCacheExtension,Ze as allowAll,tr as asBucketStorage,ir as assertShapesDeclareReadPolicies,S as beginDeferredDeletes,T as beginDeferredSchedules,F as bindOrm,O as bindTableFacade,dr as buildMaskRegistry,fr as buildRlsReadRegistry,f as cacheKeyFor,ee as clampLimit,ce as composePluginMiddleware,ar as composeShapeReadWhere,pr as createPolicyDsl,l as createSecrets,ke as createServices,Ke as cronJobs,a as defineActionCache,le as defineAggregateIndex,Ee as defineComponent,L as defineDocumentHistory,P as defineEnv,Y as defineIdentity,J as defineIdentityGuard,re as defineListArgs,te as defineLiveStream,ie as defineMigration,ae as defineModule,de as defineMutator,xr as definePermission,Se as definePlugin,cr as definePolicies,lr as definePolicy,Me as definePresence,ue as defineRankIndex,Er as defineRole,He as defineRoom,he as defineSchema,De as defineSchemaExtension,Ue as defineShape,ur as defineStorageRule,hr as defineStorageRules,Te as defineTable,ge as defineVectorIndex,Ve as defineWebSocket,$e as deny,_ as documentHistoryExtension,u as flushDeferredDeletes,H as httpAction,N as httpRoute,k as httpRouter,Re as indexFieldsFromSchema,d as initLunora,Ae as installPlugins,er as isDeny,p as isPerDispatchMiddleware,w as isSafeHeaderValue,U as lastEventId,Tr as mask,Ie as mergeSchemaExtension,Q as onConnect,X as onDisconnect,Oe as onQueryChange,q as onShardInit,je as onWhisper,pe as platformAdmin,Pe as presenceExtension,ye as protectPublic,b as redactSecrets,Rr as rls,W as serveStorageObject,B as sseEvent,Ir as storageRules,x as tagPerDispatchMiddleware,rr as toWhereInput,qe as v,h as withDeferredDeletes,g as withDeferredSchedules};
1
+ import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-mmP-6BcT.mjs";import{initLunora as d}from"./packem_shared/initLunora-B-7Xs3Qq.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as S,flushDeferredDeletes as u,withDeferredDeletes as h}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-C7QLYr6C.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as A,DOCUMENT_HISTORY_TABLE as I,defineDocumentHistory as L,documentHistoryExtension as _}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-B5Zp-7SI.mjs";import{LunoraEnvError as M,defineEnv as P,redactSecrets as b}from"./packem_shared/LunoraEnvError-bkdMu_-N.mjs";import{bindOrm as F,bindTableFacade as O}from"./packem_shared/bindOrm-9fbLRbOb.mjs";import{httpAction as H,httpRoute as N,httpRouter as k,isSafeHeaderValue as w,lastEventId as U,sseEvent as B}from"./packem_shared/httpAction-D2S7bQzl.mjs";import{serveStorageObject as W}from"./packem_shared/serveStorageObject-aqBFrLyo.mjs";import{defineIdentity as Y}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as J}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as Q,onDisconnect as X,onShardInit as q}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as Z,DEFAULT_MAX_LIMIT as $,clampLimit as ee,defineListArgs as re}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineLiveStream as te}from"./packem_shared/defineLiveStream-RmfLZq1a.mjs";import{defineMigration as ie}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as ae}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as de}from"./packem_shared/defineMutator-B4ipDtDR.mjs";import{platformAdmin as pe}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as ce,d as le,a as Ee,b as Se,e as ue,f as he,g as De,h as Te,i as ge,j as Re,k as Ae,m as Ie}from"./packem_shared/plugin-Bm9wIpiI.mjs";import{PRESENCE_DEFAULT_TTL_MS as _e,PRESENCE_TABLE as Ce,definePresence as Me,presenceExtension as Pe}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-DFpy5J8G.mjs";import{protectPublic as ye}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as Oe}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{defineRoom as He}from"./packem_shared/defineRoom-CoGi-xwm.mjs";import{createServices as ke}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Ue}from"./packem_shared/defineShape-CwKm5KLp.mjs";import{defineWebSocket as Ve}from"./packem_shared/defineWebSocket-BHoy6_ox.mjs";import{onWhisper as je}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Ge}from"@lunora/errors";import{cronJobs as Ke}from"@lunora/scheduler";import{ValidationError as Xe,v as qe}from"@lunora/values";import{allowAll as Ze,deny as $e,isDeny as er,toWhereInput as rr}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as tr}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as ir,buildRlsReadRegistry as fr,composeShapeReadWhere as ar}from"./packem_shared/assertShapesDeclareReadPolicies-Bg4Ter7Q.mjs";import{buildMaskRegistry as dr}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as pr,definePermission as xr,definePolicies as cr,definePolicy as lr,defineRole as Er}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as ur,defineStorageRules as hr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as Tr}from"./packem_shared/mask-D-jRCAhy.mjs";import{r as Rr}from"./packem_shared/middleware-3ySZVrpt.mjs";import{storageRules as Ir}from"./packem_shared/storageRules-CBLioxF7.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,Z as DEFAULT_LIMIT,$ as DEFAULT_MAX_LIMIT,A as DOCUMENT_HISTORY_REDACTED_FIELDS,I as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Ge as LunoraError,_e as PRESENCE_DEFAULT_TTL_MS,Ce as PRESENCE_TABLE,e as VERSION,Xe as ValidationError,i as actionCacheExtension,Ze as allowAll,tr as asBucketStorage,ir as assertShapesDeclareReadPolicies,S as beginDeferredDeletes,T as beginDeferredSchedules,F as bindOrm,O as bindTableFacade,dr as buildMaskRegistry,fr as buildRlsReadRegistry,f as cacheKeyFor,ee as clampLimit,ce as composePluginMiddleware,ar as composeShapeReadWhere,pr as createPolicyDsl,l as createSecrets,ke as createServices,Ke as cronJobs,a as defineActionCache,le as defineAggregateIndex,Ee as defineComponent,L as defineDocumentHistory,P as defineEnv,Y as defineIdentity,J as defineIdentityGuard,re as defineListArgs,te as defineLiveStream,ie as defineMigration,ae as defineModule,de as defineMutator,xr as definePermission,Se as definePlugin,cr as definePolicies,lr as definePolicy,Me as definePresence,ue as defineRankIndex,Er as defineRole,He as defineRoom,he as defineSchema,De as defineSchemaExtension,Ue as defineShape,ur as defineStorageRule,hr as defineStorageRules,Te as defineTable,ge as defineVectorIndex,Ve as defineWebSocket,$e as deny,_ as documentHistoryExtension,u as flushDeferredDeletes,H as httpAction,N as httpRoute,k as httpRouter,Re as indexFieldsFromSchema,d as initLunora,Ae as installPlugins,er as isDeny,p as isPerDispatchMiddleware,w as isSafeHeaderValue,U as lastEventId,Tr as mask,Ie as mergeSchemaExtension,Q as onConnect,X as onDisconnect,Oe as onQueryChange,q as onShardInit,je as onWhisper,pe as platformAdmin,Pe as presenceExtension,ye as protectPublic,b as redactSecrets,Rr as rls,W as serveStorageObject,B as sseEvent,Ir as storageRules,x as tagPerDispatchMiddleware,rr as toWhereInput,qe as v,h as withDeferredDeletes,g as withDeferredSchedules};
package/dist/otel.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { SpanHandle, LunoraTracer } from "./types.mjs";
1
+ import { a as SpanHandle, L as LunoraTracer } from "./packem_shared/types.d-XjrkWPuq.mjs";
2
2
  import '@lunora/values';
3
3
  /**
4
4
  * @since 1.0.0
package/dist/otel.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { SpanHandle, LunoraTracer } from "./types.js";
1
+ import { a as SpanHandle, L as LunoraTracer } from "./packem_shared/types.d-XjrkWPuq.js";
2
2
  import '@lunora/values';
3
3
  /**
4
4
  * @since 1.0.0
@@ -0,0 +1 @@
1
+ import{LunoraError as T,isLunoraError as $}from"@lunora/errors";import{isStringValidator as S,parseValidatorMap as b}from"@lunora/values";import{httpAction as m}from"./httpAction-D2S7bQzl.mjs";const L="/_lunora/live/connect",R="/_lunora/live/control",I="room:",P="__lunora_socket__:",k=256,C=e=>`/live/${e}/connect`,j=e=>`/live/${e}/control`,A=/^[A-Za-z]\w*$/u,E=e=>A.test(e),N=e=>`${e}:`.startsWith(I)||`${e}:`.startsWith(P),D=(e,r,n)=>[e,...r.map(a=>{const s=n[a];if(typeof s!="string")throw new TypeError(`live topic "${e}" needs a string key.${a}`);return encodeURIComponent(s)})].join(":"),g=(e,r)=>{if(e.length>k)return;const[n,...a]=e.split(":");if(n===void 0||!Object.hasOwn(r,n))return;const s=r[n];if(a.length!==s.length)return;const d={};try{for(const[l,p]of s.entries())d[p]=decodeURIComponent(a[l]);return D(n,s,d)===e?{key:d,name:n}:void 0}catch{return}},B=async e=>{try{const r=await e.json();return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0}catch{return}},w=e=>Response.json({code:"FORBIDDEN_TOPIC",error:`subscribe to "${e}" was denied`},{status:403}),h=e=>Response.json({code:"BAD_REQUEST",error:e},{status:400}),K=(e,r)=>{for(const[n,a]of Object.entries(r)){if(!E(n))throw new TypeError(`defineLiveStream("${e}"): topic name "${n}" must be a plain identifier (letters, digits and "_", starting with a letter)`);if(N(n))throw new TypeError(`defineLiveStream("${e}"): topic name "${n}" would encode into a reserved topic prefix`);for(const[s,d]of Object.entries(a.key??{})){if(!E(s))throw new TypeError(`defineLiveStream("${e}"): key field "${n}.${s}" must be a plain identifier`);if(!S(d))throw new TypeError(`defineLiveStream("${e}"): key field "${n}.${s}" must be a string validator (v.string(), v.id(), v.literal(…))`)}}},U=(e,r)=>new T("BAD_REQUEST",`publish to "${e}" was refused: ${r instanceof Error?r.message:String(r)}`,{status:400}),H=e=>{K(e.id,e.topics);const r=C(e.id),n=j(e.id),a=Object.fromEntries(Object.entries(e.topics).map(([o,i])=>[o,Object.keys(i.key??{})])),s=o=>{const i=g(o,a),t=i===void 0?void 0:e.topics[i.name];if(!(i===void 0||t===void 0))try{return{declaration:t,key:b(t.key??{},i.key,"key"),name:i.name}}catch{return}},d=(o,i)=>{const t=s(o);if(t===void 0)throw new T("BAD_REQUEST",`"${o}" is not a topic declared by live stream "${e.id}"`,{status:400});const{declaration:c}=t;try{return b({payload:c.payload},{payload:i},"topic").payload}catch(u){throw U(o,u)}},l=async(o,i)=>{const t=s(i);if(t===void 0)return!1;if(!e.onSubscribe)return e.allowAnonymousControl===!0&&o.auth.userId===null;try{return await e.onSubscribe({ctx:o,key:t.key,raw:i,topic:t.name})===!0}catch(c){return console.error("[lunora] live subscribe authorization threw; denying:",c),!1}},p=m(async(o,i)=>{const t=new URL(i.url).searchParams.get("shard")??void 0;return o.fetchShard(t,L,{method:"GET"})}),_=m(async(o,i)=>{const t=await B(i);if(!t)return h("Expected a JSON object body");const{action:c}=t,u=typeof t.topic=="string"?t.topic:void 0;if(u===void 0||u.length===0)return h("topic is required");if(c!=="subscribe"&&c!=="unsubscribe")return h("action must be subscribe or unsubscribe");const y=typeof t.shardKey=="string"?t.shardKey:void 0,O=y===void 0?o:{...o,...o.forShard(y)};if(c==="subscribe"&&!await l(O,u))return w(u);const f=o.fetchShard(y,R,{body:JSON.stringify({...t,stream:e.id}),method:"POST"});if(c!=="subscribe")return f;try{return await f}catch(v){if($(v)&&v.code==="FORBIDDEN_SHARD")return w(u);throw v}});return{connect:p,connectPath:r,control:_,controlPath:n,id:e.id,topics:e.topics,validatePublish:d}};export{H as defineLiveStream};