@lunora/server 1.0.0-alpha.95 → 1.0.0-alpha.97

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/README.md CHANGED
@@ -116,7 +116,7 @@ The dev server and CLI automatically bump `compatibility_date` to the minimum re
116
116
  **Set cache headers declaratively** on an `httpRoute`:
117
117
 
118
118
  ```ts
119
- import { httpRoute } from "./_generated/server";
119
+ import { httpRoute, v } from "@lunora/server";
120
120
 
121
121
  export const getProduct = httpRoute
122
122
  .get("/api/products/:id")
package/dist/index.d.mts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Validator, Infer, v, Id, ValidatorMap, InferValidatorMap, ColumnValidator } from '@lunora/values';
2
2
  export { type ColumnValidator, type GeoPoint, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
3
3
  import { ArgsValidator, InferArgs, RegisteredAction, ExposeConfig, X402ProcedureConfig, ActionCtx, MutationCtx, RegisteredMutation, QueryCtx, RegisteredQuery, DurableStreamOptions, RegisteredStream, FunctionKind, TableDefinition, RegisteredFunction, VectorIndexDefinition, Schema, AggregateOp, GlobalBackend, RelationDefinition, OnDeleteAction, SearchLanguage, SearchStrategy, ExternalSourceDefinition, TriggerBuilder, TriggerDefinition, VectorEmbedder, VectorMetric, DurableObjectJurisdiction, AggregateIndexDefinition, RankIndexDefinition, Secrets, LifecycleEvent, ShardInitEvent, RegisteredLifecycleHook } from "./types.mjs";
4
- export { type AnyApi, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type IndexDefinition, type IndexRangeBuilder, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationStorage, type PaginationOptions, type PaginationResult, type RankSortKey, type ReadOnlyStorage, type RestCacheConfig, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type SearchFilterBuilder, type SearchIndexDefinition, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerCtx, type TriggerDatabase, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorMatch, type VectorMatches, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } from "./types.mjs";
4
+ export { type AnyApi, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type IndexDefinition, type IndexRangeBuilder, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationStorage, type PaginationOptions, type PaginationResult, type RankSortKey, type ReadOnlyStorage, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type SearchFilterBuilder, type SearchIndexDefinition, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerCtx, type TriggerDatabase, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorMatch, type VectorMatches, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } from "./types.mjs";
5
5
  import { LunoraError } from '@lunora/errors';
6
6
  export { LunoraError, type LunoraErrorCode } from '@lunora/errors';
7
7
  import { Context, Hono } from 'hono';
@@ -40,6 +40,26 @@ type Middleware<ContextIn, ContextOut> = (options: {
40
40
  ctx: ContextIn;
41
41
  next: MiddlewareNext<ContextIn>;
42
42
  }) => ContextOut | Promise<ContextOut>;
43
+ /**
44
+ * The context a `.use(...)` step actually receives: the procedure context plus
45
+ * `args`, the call's arguments as declared by `.input(...)` up to this point in
46
+ * the chain.
47
+ *
48
+ * A middleware that gates on the payload — a CAPTCHA token, a signup email —
49
+ * has nowhere else to read it from: the procedure context carries the resolved
50
+ * identity, not the request body. `args` is surfaced only AFTER the validators
51
+ * have run, and as a frozen shallow copy, so a middleware cannot rewrite what
52
+ * the handler is then handed.
53
+ *
54
+ * This is a PROCEDURE-builder surface. `httpAction` / `httpRoute` have no
55
+ * `.use()` chain at all (`HttpActionCtx` is not a builder context) — an HTTP
56
+ * handler reads its own `request` / `searchParams` / `body` and calls the
57
+ * underlying helper (`verifyTurnstile(...)`, `assertEmailAllowed(...)`) inline,
58
+ * or mounts a hono middleware.
59
+ */
60
+ type MiddlewareContext<Context, Args extends ArgsValidator> = Context & {
61
+ readonly args: Readonly<InferArgs<Args>>;
62
+ };
43
63
  /** Options accepted by `initLunora.dataModel<DM>().create(...)`. Reserved for transformer/error-formatter wiring. */
44
64
  type CreateOptions = Record<never, never>;
45
65
  /**
@@ -108,7 +128,7 @@ interface QueryBuilder<Context, Args extends ArgsValidator, Output = undefined>
108
128
  ctx: Context;
109
129
  signal: AbortSignal;
110
130
  }) => AsyncGenerator<R, void, void> | AsyncIterable<R>, options?: StreamOptions) => RegisteredStream<Args, R> : never;
111
- use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => QueryBuilder<ContextOut, Args, Output>;
131
+ use: <ContextOut>(middleware: Middleware<MiddlewareContext<Context, Args>, ContextOut>) => QueryBuilder<ContextOut, Args, Output>;
112
132
  /**
113
133
  * Mark this query as paid. The origin worker answers an unpaid client RPC
114
134
  * with HTTP 402, verifies + settles the x402 payment, then dispatches. `price`
@@ -149,7 +169,7 @@ interface MutationBuilder<Context, Args extends ArgsValidator, Output = undefine
149
169
  ctx: Context;
150
170
  }) => Output | Promise<Output>) => RegisteredMutation<Args, Output>;
151
171
  output: <V extends Validator>(validator: V) => MutationBuilder<Context, Args, Infer<V>>;
152
- use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => MutationBuilder<ContextOut, Args, Output>;
172
+ use: <ContextOut>(middleware: Middleware<MiddlewareContext<Context, Args>, ContextOut>) => MutationBuilder<ContextOut, Args, Output>;
153
173
  /**
154
174
  * Mark this mutation as paid. The origin worker answers an unpaid client RPC
155
175
  * with HTTP 402, verifies + settles the x402 payment, then dispatches. `price`
@@ -190,7 +210,7 @@ interface ActionBuilder<Context, Args extends ArgsValidator, Output = undefined>
190
210
  */
191
211
  meta: (value: Record<string, unknown>) => ActionBuilder<Context, Args, Output>;
192
212
  output: <V extends Validator>(validator: V) => ActionBuilder<Context, Args, Infer<V>>;
193
- use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => ActionBuilder<ContextOut, Args, Output>;
213
+ use: <ContextOut>(middleware: Middleware<MiddlewareContext<Context, Args>, ContextOut>) => ActionBuilder<ContextOut, Args, Output>;
194
214
  /**
195
215
  * Mark this action as paid. The origin worker answers an unpaid client RPC
196
216
  * with HTTP 402, verifies + settles the x402 payment, then dispatches. `price`
@@ -237,7 +257,7 @@ interface InternalQueryBuilder<Context, Args extends ArgsValidator, Output = und
237
257
  ctx: Context;
238
258
  signal: AbortSignal;
239
259
  }) => AsyncGenerator<R, void, void> | AsyncIterable<R>, options?: StreamOptions) => RegisteredStream<Args, R>;
240
- use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => InternalQueryBuilder<ContextOut, Args, Output>;
260
+ use: <ContextOut>(middleware: Middleware<MiddlewareContext<Context, Args>, ContextOut>) => InternalQueryBuilder<ContextOut, Args, Output>;
241
261
  }
242
262
  interface InternalMutationBuilder<Context, Args extends ArgsValidator, Output = undefined> {
243
263
  readonly __lunoraProcedure: "mutation";
@@ -265,7 +285,7 @@ interface InternalMutationBuilder<Context, Args extends ArgsValidator, Output =
265
285
  ctx: Context;
266
286
  }) => Output | Promise<Output>) => RegisteredMutation<Args, Output>;
267
287
  output: <V extends Validator>(validator: V) => InternalMutationBuilder<Context, Args, Infer<V>>;
268
- use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => InternalMutationBuilder<ContextOut, Args, Output>;
288
+ use: <ContextOut>(middleware: Middleware<MiddlewareContext<Context, Args>, ContextOut>) => InternalMutationBuilder<ContextOut, Args, Output>;
269
289
  }
270
290
  interface InternalActionBuilder<Context, Args extends ArgsValidator, Output = undefined> {
271
291
  readonly __lunoraProcedure: "action";
@@ -293,7 +313,7 @@ interface InternalActionBuilder<Context, Args extends ArgsValidator, Output = un
293
313
  */
294
314
  meta: (value: Record<string, unknown>) => InternalActionBuilder<Context, Args, Output>;
295
315
  output: <V extends Validator>(validator: V) => InternalActionBuilder<Context, Args, Infer<V>>;
296
- use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => InternalActionBuilder<ContextOut, Args, Output>;
316
+ use: <ContextOut>(middleware: Middleware<MiddlewareContext<Context, Args>, ContextOut>) => InternalActionBuilder<ContextOut, Args, Output>;
297
317
  }
298
318
  /** The public root builders plus their `internal*` counterparts, returned by `.create()`. */
299
319
  interface LunoraBuilders {
@@ -3116,4 +3136,4 @@ interface StorageContextIn {
3116
3136
  }
3117
3137
  declare const storageRules: <Context extends StorageContextIn = StorageContextIn>(rules: ReadonlyArray<StorageRule<Context>>, options?: StorageRulesOptions) => Middleware<Context, Context>;
3118
3138
  declare const VERSION = "0.0.0";
3119
- 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 DefineStorageRuleInput, 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 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 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 MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, 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 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 RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput, withDeferredDeletes };
3139
+ 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 DefineStorageRuleInput, 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 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 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 MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, 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 RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput, withDeferredDeletes };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Validator, Infer, v, Id, ValidatorMap, InferValidatorMap, ColumnValidator } from '@lunora/values';
2
2
  export { type ColumnValidator, type GeoPoint, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
3
3
  import { ArgsValidator, InferArgs, RegisteredAction, ExposeConfig, X402ProcedureConfig, ActionCtx, MutationCtx, RegisteredMutation, QueryCtx, RegisteredQuery, DurableStreamOptions, RegisteredStream, FunctionKind, TableDefinition, RegisteredFunction, VectorIndexDefinition, Schema, AggregateOp, GlobalBackend, RelationDefinition, OnDeleteAction, SearchLanguage, SearchStrategy, ExternalSourceDefinition, TriggerBuilder, TriggerDefinition, VectorEmbedder, VectorMetric, DurableObjectJurisdiction, AggregateIndexDefinition, RankIndexDefinition, Secrets, LifecycleEvent, ShardInitEvent, RegisteredLifecycleHook } from "./types.js";
4
- export { type AnyApi, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type IndexDefinition, type IndexRangeBuilder, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationStorage, type PaginationOptions, type PaginationResult, type RankSortKey, type ReadOnlyStorage, type RestCacheConfig, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type SearchFilterBuilder, type SearchIndexDefinition, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerCtx, type TriggerDatabase, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorMatch, type VectorMatches, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } from "./types.js";
4
+ export { type AnyApi, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type IndexDefinition, type IndexRangeBuilder, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationStorage, type PaginationOptions, type PaginationResult, type RankSortKey, type ReadOnlyStorage, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type SearchFilterBuilder, type SearchIndexDefinition, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerCtx, type TriggerDatabase, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorMatch, type VectorMatches, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } from "./types.js";
5
5
  import { LunoraError } from '@lunora/errors';
6
6
  export { LunoraError, type LunoraErrorCode } from '@lunora/errors';
7
7
  import { Context, Hono } from 'hono';
@@ -40,6 +40,26 @@ type Middleware<ContextIn, ContextOut> = (options: {
40
40
  ctx: ContextIn;
41
41
  next: MiddlewareNext<ContextIn>;
42
42
  }) => ContextOut | Promise<ContextOut>;
43
+ /**
44
+ * The context a `.use(...)` step actually receives: the procedure context plus
45
+ * `args`, the call's arguments as declared by `.input(...)` up to this point in
46
+ * the chain.
47
+ *
48
+ * A middleware that gates on the payload — a CAPTCHA token, a signup email —
49
+ * has nowhere else to read it from: the procedure context carries the resolved
50
+ * identity, not the request body. `args` is surfaced only AFTER the validators
51
+ * have run, and as a frozen shallow copy, so a middleware cannot rewrite what
52
+ * the handler is then handed.
53
+ *
54
+ * This is a PROCEDURE-builder surface. `httpAction` / `httpRoute` have no
55
+ * `.use()` chain at all (`HttpActionCtx` is not a builder context) — an HTTP
56
+ * handler reads its own `request` / `searchParams` / `body` and calls the
57
+ * underlying helper (`verifyTurnstile(...)`, `assertEmailAllowed(...)`) inline,
58
+ * or mounts a hono middleware.
59
+ */
60
+ type MiddlewareContext<Context, Args extends ArgsValidator> = Context & {
61
+ readonly args: Readonly<InferArgs<Args>>;
62
+ };
43
63
  /** Options accepted by `initLunora.dataModel<DM>().create(...)`. Reserved for transformer/error-formatter wiring. */
44
64
  type CreateOptions = Record<never, never>;
45
65
  /**
@@ -108,7 +128,7 @@ interface QueryBuilder<Context, Args extends ArgsValidator, Output = undefined>
108
128
  ctx: Context;
109
129
  signal: AbortSignal;
110
130
  }) => AsyncGenerator<R, void, void> | AsyncIterable<R>, options?: StreamOptions) => RegisteredStream<Args, R> : never;
111
- use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => QueryBuilder<ContextOut, Args, Output>;
131
+ use: <ContextOut>(middleware: Middleware<MiddlewareContext<Context, Args>, ContextOut>) => QueryBuilder<ContextOut, Args, Output>;
112
132
  /**
113
133
  * Mark this query as paid. The origin worker answers an unpaid client RPC
114
134
  * with HTTP 402, verifies + settles the x402 payment, then dispatches. `price`
@@ -149,7 +169,7 @@ interface MutationBuilder<Context, Args extends ArgsValidator, Output = undefine
149
169
  ctx: Context;
150
170
  }) => Output | Promise<Output>) => RegisteredMutation<Args, Output>;
151
171
  output: <V extends Validator>(validator: V) => MutationBuilder<Context, Args, Infer<V>>;
152
- use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => MutationBuilder<ContextOut, Args, Output>;
172
+ use: <ContextOut>(middleware: Middleware<MiddlewareContext<Context, Args>, ContextOut>) => MutationBuilder<ContextOut, Args, Output>;
153
173
  /**
154
174
  * Mark this mutation as paid. The origin worker answers an unpaid client RPC
155
175
  * with HTTP 402, verifies + settles the x402 payment, then dispatches. `price`
@@ -190,7 +210,7 @@ interface ActionBuilder<Context, Args extends ArgsValidator, Output = undefined>
190
210
  */
191
211
  meta: (value: Record<string, unknown>) => ActionBuilder<Context, Args, Output>;
192
212
  output: <V extends Validator>(validator: V) => ActionBuilder<Context, Args, Infer<V>>;
193
- use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => ActionBuilder<ContextOut, Args, Output>;
213
+ use: <ContextOut>(middleware: Middleware<MiddlewareContext<Context, Args>, ContextOut>) => ActionBuilder<ContextOut, Args, Output>;
194
214
  /**
195
215
  * Mark this action as paid. The origin worker answers an unpaid client RPC
196
216
  * with HTTP 402, verifies + settles the x402 payment, then dispatches. `price`
@@ -237,7 +257,7 @@ interface InternalQueryBuilder<Context, Args extends ArgsValidator, Output = und
237
257
  ctx: Context;
238
258
  signal: AbortSignal;
239
259
  }) => AsyncGenerator<R, void, void> | AsyncIterable<R>, options?: StreamOptions) => RegisteredStream<Args, R>;
240
- use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => InternalQueryBuilder<ContextOut, Args, Output>;
260
+ use: <ContextOut>(middleware: Middleware<MiddlewareContext<Context, Args>, ContextOut>) => InternalQueryBuilder<ContextOut, Args, Output>;
241
261
  }
242
262
  interface InternalMutationBuilder<Context, Args extends ArgsValidator, Output = undefined> {
243
263
  readonly __lunoraProcedure: "mutation";
@@ -265,7 +285,7 @@ interface InternalMutationBuilder<Context, Args extends ArgsValidator, Output =
265
285
  ctx: Context;
266
286
  }) => Output | Promise<Output>) => RegisteredMutation<Args, Output>;
267
287
  output: <V extends Validator>(validator: V) => InternalMutationBuilder<Context, Args, Infer<V>>;
268
- use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => InternalMutationBuilder<ContextOut, Args, Output>;
288
+ use: <ContextOut>(middleware: Middleware<MiddlewareContext<Context, Args>, ContextOut>) => InternalMutationBuilder<ContextOut, Args, Output>;
269
289
  }
270
290
  interface InternalActionBuilder<Context, Args extends ArgsValidator, Output = undefined> {
271
291
  readonly __lunoraProcedure: "action";
@@ -293,7 +313,7 @@ interface InternalActionBuilder<Context, Args extends ArgsValidator, Output = un
293
313
  */
294
314
  meta: (value: Record<string, unknown>) => InternalActionBuilder<Context, Args, Output>;
295
315
  output: <V extends Validator>(validator: V) => InternalActionBuilder<Context, Args, Infer<V>>;
296
- use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => InternalActionBuilder<ContextOut, Args, Output>;
316
+ use: <ContextOut>(middleware: Middleware<MiddlewareContext<Context, Args>, ContextOut>) => InternalActionBuilder<ContextOut, Args, Output>;
297
317
  }
298
318
  /** The public root builders plus their `internal*` counterparts, returned by `.create()`. */
299
319
  interface LunoraBuilders {
@@ -3116,4 +3136,4 @@ interface StorageContextIn {
3116
3136
  }
3117
3137
  declare const storageRules: <Context extends StorageContextIn = StorageContextIn>(rules: ReadonlyArray<StorageRule<Context>>, options?: StorageRulesOptions) => Middleware<Context, Context>;
3118
3138
  declare const VERSION = "0.0.0";
3119
- 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 DefineStorageRuleInput, 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 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 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 MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, 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 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 RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput, withDeferredDeletes };
3139
+ 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 DefineStorageRuleInput, 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 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 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 MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, 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 RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput, withDeferredDeletes };
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 a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-DZ4b4IoT.mjs";import{initLunora as m}from"./packem_shared/initLunora-D8WltggT.mjs";import{createSecrets as p}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{flushDeferredDeletes as c,withDeferredDeletes as l}from"./packem_shared/flushDeferredDeletes-DEJXlhop.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as u,DOCUMENT_HISTORY_TABLE as S,defineDocumentHistory as T,documentHistoryExtension as h}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-B5mE3zak.mjs";import{LunoraEnvError as g,defineEnv as R,redactSecrets as _}from"./packem_shared/LunoraEnvError-CXbrsFI8.mjs";import{bindOrm as L,bindTableFacade as C}from"./packem_shared/bindOrm-ChQydkdL.mjs";import{httpAction as y,httpRoute as M,httpRouter as P,isSafeHeaderValue as b,serveStorageObject as F}from"./packem_shared/httpAction-B8X6jXen.mjs";import{defineIdentity as H}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as U,onDisconnect as k,onShardInit as v}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as V,DEFAULT_MAX_LIMIT as w,clampLimit as j,defineListArgs as W}from"./packem_shared/DEFAULT_LIMIT-DC-M6faS.mjs";import{defineMigration as J}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineMutator as Q}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as q,d as z,a as G,b as Z,e as $,f as ee,g as oe,h as re,i as te,j as ne,k as ie,m as ae}from"./packem_shared/plugin-yKCbHnlj.mjs";import{PRESENCE_DEFAULT_TTL_MS as se,PRESENCE_TABLE as me,definePresence as de,presenceExtension as pe}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-DSTJZMfc.mjs";import{protectPublic as ce}from"./packem_shared/protectPublic-Csf6ObbJ.mjs";import{onQueryChange as Ee}from"./packem_shared/onQueryChange-pRK6Dh3g.mjs";import{defineShape as Se}from"./packem_shared/defineShape-BWgwFuMT.mjs";import{anyApi as he}from"./types.mjs";import{LunoraError as ge}from"@lunora/errors";import{cronJobs as _e}from"@lunora/scheduler";import{ValidationError as Le,v as Ce}from"@lunora/values";import{allowAll as ye,deny as Me,isDeny as Pe,toWhereInput as be}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as Oe}from"./packem_shared/asBucketStorage-BthCnWop.mjs";import{buildMaskRegistry as Ne}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{buildRlsReadRegistry as ke,composeShapeReadWhere as ve}from"./packem_shared/buildRlsReadRegistry-CIGmNx0b.mjs";import{createPolicyDsl as Ve,definePermission as we,definePolicies as je,definePolicy as We,defineRole as Ye}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as Ke,defineStorageRules as Qe}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as qe}from"./packem_shared/mask-pIhIWBcr.mjs";import{r as Ge}from"./packem_shared/middleware-Cz5s6CH-.mjs";import{storageRules as $e}from"./packem_shared/storageRules-DHvF6Fjq.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,V as DEFAULT_LIMIT,w as DEFAULT_MAX_LIMIT,u as DOCUMENT_HISTORY_REDACTED_FIELDS,S as DOCUMENT_HISTORY_TABLE,g as LunoraEnvError,ge as LunoraError,se as PRESENCE_DEFAULT_TTL_MS,me as PRESENCE_TABLE,e as VERSION,Le as ValidationError,i as actionCacheExtension,ye as allowAll,he as anyApi,Oe as asBucketStorage,L as bindOrm,C as bindTableFacade,Ne as buildMaskRegistry,ke as buildRlsReadRegistry,a as cacheKeyFor,j as clampLimit,q as composePluginMiddleware,ve as composeShapeReadWhere,Ve as createPolicyDsl,p as createSecrets,_e as cronJobs,f as defineActionCache,z as defineAggregateIndex,G as defineComponent,T as defineDocumentHistory,R as defineEnv,H as defineIdentity,W as defineListArgs,J as defineMigration,Q as defineMutator,we as definePermission,Z as definePlugin,je as definePolicies,We as definePolicy,de as definePresence,$ as defineRankIndex,Ye as defineRole,ee as defineSchema,oe as defineSchemaExtension,Se as defineShape,Ke as defineStorageRule,Qe as defineStorageRules,re as defineTable,te as defineVectorIndex,Me as deny,h as documentHistoryExtension,c as flushDeferredDeletes,y as httpAction,M as httpRoute,P as httpRouter,ne as indexFieldsFromSchema,m as initLunora,ie as installPlugins,Pe as isDeny,b as isSafeHeaderValue,qe as mask,ae as mergeSchemaExtension,U as onConnect,k as onDisconnect,Ee as onQueryChange,v as onShardInit,pe as presenceExtension,ce as protectPublic,_ as redactSecrets,Ge as rls,F as serveStorageObject,$e as storageRules,be as toWhereInput,Ce as v,l as withDeferredDeletes};
1
+ import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-OuQ-AJjz.mjs";import{initLunora as m}from"./packem_shared/initLunora-D5TSiy5j.mjs";import{createSecrets as p}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{flushDeferredDeletes as c,withDeferredDeletes as l}from"./packem_shared/flushDeferredDeletes-DEJXlhop.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as u,DOCUMENT_HISTORY_TABLE as S,defineDocumentHistory as T,documentHistoryExtension as h}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-wgfbacHx.mjs";import{LunoraEnvError as g,defineEnv as R,redactSecrets as _}from"./packem_shared/LunoraEnvError-CXbrsFI8.mjs";import{bindOrm as L,bindTableFacade as C}from"./packem_shared/bindOrm-ChQydkdL.mjs";import{httpAction as y,httpRoute as M,httpRouter as P,isSafeHeaderValue as b,serveStorageObject as F}from"./packem_shared/httpAction-B8X6jXen.mjs";import{defineIdentity as H}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as U,onDisconnect as k,onShardInit as v}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as V,DEFAULT_MAX_LIMIT as w,clampLimit as j,defineListArgs as W}from"./packem_shared/DEFAULT_LIMIT-DC-M6faS.mjs";import{defineMigration as J}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineMutator as Q}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as q,d as z,a as G,b as Z,e as $,f as ee,g as oe,h as re,i as te,j as ne,k as ie,m as ae}from"./packem_shared/plugin-yKCbHnlj.mjs";import{PRESENCE_DEFAULT_TTL_MS as se,PRESENCE_TABLE as me,definePresence as de,presenceExtension as pe}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-lsooaSaF.mjs";import{protectPublic as ce}from"./packem_shared/protectPublic-Csf6ObbJ.mjs";import{onQueryChange as Ee}from"./packem_shared/onQueryChange-pRK6Dh3g.mjs";import{defineShape as Se}from"./packem_shared/defineShape-BWgwFuMT.mjs";import{anyApi as he}from"./types.mjs";import{LunoraError as ge}from"@lunora/errors";import{cronJobs as _e}from"@lunora/scheduler";import{ValidationError as Le,v as Ce}from"@lunora/values";import{allowAll as ye,deny as Me,isDeny as Pe,toWhereInput as be}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as Oe}from"./packem_shared/asBucketStorage-BthCnWop.mjs";import{buildMaskRegistry as Ne}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{buildRlsReadRegistry as ke,composeShapeReadWhere as ve}from"./packem_shared/buildRlsReadRegistry-CIGmNx0b.mjs";import{createPolicyDsl as Ve,definePermission as we,definePolicies as je,definePolicy as We,defineRole as Ye}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as Ke,defineStorageRules as Qe}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as qe}from"./packem_shared/mask-pIhIWBcr.mjs";import{r as Ge}from"./packem_shared/middleware-Cz5s6CH-.mjs";import{storageRules as $e}from"./packem_shared/storageRules-DHvF6Fjq.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,V as DEFAULT_LIMIT,w as DEFAULT_MAX_LIMIT,u as DOCUMENT_HISTORY_REDACTED_FIELDS,S as DOCUMENT_HISTORY_TABLE,g as LunoraEnvError,ge as LunoraError,se as PRESENCE_DEFAULT_TTL_MS,me as PRESENCE_TABLE,e as VERSION,Le as ValidationError,i as actionCacheExtension,ye as allowAll,he as anyApi,Oe as asBucketStorage,L as bindOrm,C as bindTableFacade,Ne as buildMaskRegistry,ke as buildRlsReadRegistry,a as cacheKeyFor,j as clampLimit,q as composePluginMiddleware,ve as composeShapeReadWhere,Ve as createPolicyDsl,p as createSecrets,_e as cronJobs,f as defineActionCache,z as defineAggregateIndex,G as defineComponent,T as defineDocumentHistory,R as defineEnv,H as defineIdentity,W as defineListArgs,J as defineMigration,Q as defineMutator,we as definePermission,Z as definePlugin,je as definePolicies,We as definePolicy,de as definePresence,$ as defineRankIndex,Ye as defineRole,ee as defineSchema,oe as defineSchemaExtension,Se as defineShape,Ke as defineStorageRule,Qe as defineStorageRules,re as defineTable,te as defineVectorIndex,Me as deny,h as documentHistoryExtension,c as flushDeferredDeletes,y as httpAction,M as httpRoute,P as httpRouter,ne as indexFieldsFromSchema,m as initLunora,ie as installPlugins,Pe as isDeny,b as isSafeHeaderValue,qe as mask,ae as mergeSchemaExtension,U as onConnect,k as onDisconnect,Ee as onQueryChange,v as onShardInit,pe as presenceExtension,ce as protectPublic,_ as redactSecrets,Ge as rls,F as serveStorageObject,$e as storageRules,be as toWhereInput,Ce as v,l as withDeferredDeletes};
@@ -1 +1 @@
1
- import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{e as f,d as U}from"./wire-codec-hZHn-Ooo.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-D8WltggT.mjs";import{g as k,h as q,a as B}from"./plugin-yKCbHnlj.mjs";const P=i=>D(f(i)),R=3600*1e3,H=512*1024,V=8,b=64,K=64,W=256,$=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=i=>i===void 0?"":P(i),x=async(i,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${i}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},G=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:J}=F.dataModel().create(),te=(i={})=>{const m=i.ttlMs!==void 0&&Number.isFinite(i.ttlMs)?Math.max(1,Math.floor(i.ttlMs)):R,A=i.maxValueBytes!==void 0&&Number.isFinite(i.maxValueBytes)?Math.max(1,Math.floor(i.maxValueBytes)):H,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(V)).filter(r=>r.expiresAt<=t);await Promise.all(n.map(async r=>e.db.delete(r._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),N=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),I=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(S(n)&&N.has(n.code))return;throw n}},M=async(e,t,a,n)=>{const r=T(a),s=await x(t,r),l=Date.now(),o=await C(e,s);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(f({v:p})),E=Date.now(),O=E+m;return new TextEncoder().encode(w).length<=A?await I(e,o,{expiresAt:O,key:s,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},L=async(e,t,a)=>{const n=await x(t,T(a)),r=await e.db.query(c).withIndex("byKey",s=>s.eq("key",n)).take(b);await Promise.all(r.map(async s=>e.db.delete(s._id)))},_=async(e,t,a,n)=>{if(n>=K)return{complete:!1,deleted:a};const r=await e.db.query(c).withIndex("byName",s=>s.eq("name",t)).take(b);return r.length===0?{complete:!0,deleted:a}:(await Promise.all(r.map(async s=>e.db.delete(s._id))),_(e,t,a+r.length,n+1))},g=async(e,t)=>_(e,t,0,0),v=J.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min($,Math.max(1,Math.floor(e.limit))):W,s=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(s.map(async l=>t.db.delete(l._id))),{deleted:s.length}});return{...B(u,{extension:G,functions:{purgeExpired:v}}),invalidate:L,invalidateAll:g,wrap:M}};export{R as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,G as actionCacheExtension,x as cacheKeyFor,te as defineActionCache};
1
+ import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{e as f,d as U}from"./wire-codec-uveYSVra.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-D5TSiy5j.mjs";import{g as k,h as q,a as B}from"./plugin-yKCbHnlj.mjs";const P=i=>D(f(i)),R=3600*1e3,H=512*1024,V=8,b=64,K=64,W=256,$=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=i=>i===void 0?"":P(i),x=async(i,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${i}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},G=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:J}=F.dataModel().create(),te=(i={})=>{const m=i.ttlMs!==void 0&&Number.isFinite(i.ttlMs)?Math.max(1,Math.floor(i.ttlMs)):R,A=i.maxValueBytes!==void 0&&Number.isFinite(i.maxValueBytes)?Math.max(1,Math.floor(i.maxValueBytes)):H,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(V)).filter(r=>r.expiresAt<=t);await Promise.all(n.map(async r=>e.db.delete(r._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),N=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),I=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(S(n)&&N.has(n.code))return;throw n}},M=async(e,t,a,n)=>{const r=T(a),s=await x(t,r),l=Date.now(),o=await C(e,s);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(f({v:p})),E=Date.now(),O=E+m;return new TextEncoder().encode(w).length<=A?await I(e,o,{expiresAt:O,key:s,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},L=async(e,t,a)=>{const n=await x(t,T(a)),r=await e.db.query(c).withIndex("byKey",s=>s.eq("key",n)).take(b);await Promise.all(r.map(async s=>e.db.delete(s._id)))},_=async(e,t,a,n)=>{if(n>=K)return{complete:!1,deleted:a};const r=await e.db.query(c).withIndex("byName",s=>s.eq("name",t)).take(b);return r.length===0?{complete:!0,deleted:a}:(await Promise.all(r.map(async s=>e.db.delete(s._id))),_(e,t,a+r.length,n+1))},g=async(e,t)=>_(e,t,0,0),v=J.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min($,Math.max(1,Math.floor(e.limit))):W,s=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(s.map(async l=>t.db.delete(l._id))),{deleted:s.length}});return{...B(u,{extension:G,functions:{purgeExpired:v}}),invalidate:L,invalidateAll:g,wrap:M}};export{R as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,G as actionCacheExtension,x as cacheKeyFor,te as defineActionCache};
@@ -1 +1 @@
1
- import{v as r}from"@lunora/values";import{d as A,e as h}from"./wire-codec-hZHn-Ooo.mjs";import{initLunora as v}from"./initLunora-D8WltggT.mjs";import{g as x,h as R,a as U}from"./plugin-yKCbHnlj.mjs";const H=2160*60*60*1e3,q=64*1024,E=200,C=64,F=512,y=16,L=["_commitSeq","seq"],B=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],p="documentHistory",I="versions",l=`${p}_${I}`,P=x(p,{tables:{[I]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:j}=v.dataModel().create(),X=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):q,D=new Set([...B,...d.redact??[]]);let b=0;const M=()=>(b+=1,b),m=(e,t=0)=>{if(Array.isArray(e))return t>=y?void 0:e.map(o=>m(o,t+1));if(typeof e!="object"||e===null||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(t>=y))return Object.fromEntries(Object.entries(e).filter(([o])=>!D.has(o)).map(([o,i])=>[o,m(i,t+1)]))},f=e=>{if(e===void 0)return;const t=JSON.stringify(h(m(e)));return new TextEncoder().encode(t).length>_?void 0:t},u=async(e,t)=>{const o=f(t.doc),i=f(t.previous),n=t.doc!==void 0&&o===void 0||t.previous!==void 0&&i===void 0;await e.db.insert(l,{documentId:t.documentId,op:t.op,recordedAt:Date.now(),seq:M(),tableName:t.tableName,...n?{truncated:!0}:{},...o===void 0?{}:{doc:o},...i===void 0?{}:{previous:i}})},S=e=>({documentHistoryDelete:e.afterDelete(async(t,o)=>u(t,{documentId:o.id,op:"delete",previous:o.previous,tableName:o.table})),documentHistoryInsert:e.afterInsert(async(t,o)=>u(t,{doc:o.doc,documentId:o.id,op:"insert",tableName:o.table})),documentHistoryUpdate:e.afterUpdate(async(t,o)=>u(t,{doc:o.doc,documentId:o.id,op:"update",previous:o.previous,tableName:o.table}))}),N=j.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:t})=>{const o=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):E,i=await t.db.query(l).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(o);return i.sort((n,a)=>{for(const c of L){const s=(a[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:A(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:A(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:t})=>{const o=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let a=0;a<C&&n<i;a+=1){const c=await t.db.query(l).withIndex("byRecordedAt",s=>s.lt("recordedAt",o)).order("asc").take(Math.min(E,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>t.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(p,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:S}};export{B as DOCUMENT_HISTORY_REDACTED_FIELDS,l as DOCUMENT_HISTORY_TABLE,X as defineDocumentHistory,P as documentHistoryExtension};
1
+ import{v as r}from"@lunora/values";import{d as A,e as h}from"./wire-codec-uveYSVra.mjs";import{initLunora as v}from"./initLunora-D5TSiy5j.mjs";import{g as x,h as R,a as U}from"./plugin-yKCbHnlj.mjs";const H=2160*60*60*1e3,q=64*1024,E=200,C=64,F=512,y=16,L=["_commitSeq","seq"],B=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],p="documentHistory",I="versions",l=`${p}_${I}`,P=x(p,{tables:{[I]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:j}=v.dataModel().create(),X=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):q,D=new Set([...B,...d.redact??[]]);let b=0;const M=()=>(b+=1,b),m=(e,t=0)=>{if(Array.isArray(e))return t>=y?void 0:e.map(o=>m(o,t+1));if(typeof e!="object"||e===null||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(t>=y))return Object.fromEntries(Object.entries(e).filter(([o])=>!D.has(o)).map(([o,i])=>[o,m(i,t+1)]))},f=e=>{if(e===void 0)return;const t=JSON.stringify(h(m(e)));return new TextEncoder().encode(t).length>_?void 0:t},u=async(e,t)=>{const o=f(t.doc),i=f(t.previous),n=t.doc!==void 0&&o===void 0||t.previous!==void 0&&i===void 0;await e.db.insert(l,{documentId:t.documentId,op:t.op,recordedAt:Date.now(),seq:M(),tableName:t.tableName,...n?{truncated:!0}:{},...o===void 0?{}:{doc:o},...i===void 0?{}:{previous:i}})},S=e=>({documentHistoryDelete:e.afterDelete(async(t,o)=>u(t,{documentId:o.id,op:"delete",previous:o.previous,tableName:o.table})),documentHistoryInsert:e.afterInsert(async(t,o)=>u(t,{doc:o.doc,documentId:o.id,op:"insert",tableName:o.table})),documentHistoryUpdate:e.afterUpdate(async(t,o)=>u(t,{doc:o.doc,documentId:o.id,op:"update",previous:o.previous,tableName:o.table}))}),N=j.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:t})=>{const o=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):E,i=await t.db.query(l).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(o);return i.sort((n,a)=>{for(const c of L){const s=(a[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:A(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:A(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:t})=>{const o=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let a=0;a<C&&n<i;a+=1){const c=await t.db.query(l).withIndex("byRecordedAt",s=>s.lt("recordedAt",o)).order("asc").take(Math.min(E,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>t.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(p,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:S}};export{B as DOCUMENT_HISTORY_REDACTED_FIELDS,l as DOCUMENT_HISTORY_TABLE,X as defineDocumentHistory,P as documentHistoryExtension};
@@ -1 +1 @@
1
- import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-D8WltggT.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-yKCbHnlj.mjs";const D=3e4,g=1024,P=8,p=4096,w="presence",h="present",l=`${w}_${h}`,N=v(w,{tables:{[h]:A({data:t.optional(t.record(t.string(),t.any())),lastSeen:t.number(),roomId:t.string(),sessionId:t.string(),userId:t.optional(t.string())}).index("byRoomSession",["roomId","sessionId"]).index("byRoom",["roomId"]).index("byRoomLastSeen",["roomId","lastSeen"])}}),{mutation:E,query:B}=M.dataModel().create(),G=(u={})=>{const m=u.ttlMs??D,f=Math.max(0,Math.min(u.disconnectGraceMs??0,m)),S=u.maxSessions,y=S!==void 0&&Number.isFinite(S)?Math.max(1,Math.floor(S)):g,_=E.input({data:t.optional(t.record(t.string(),t.any())),roomId:t.string(),sessionId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now(),d=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>p)throw new b("BAD_REQUEST",`presence data exceeds the ${String(p)}-byte limit`);const e=await s.db.query(l).withIndex("byRoomSession",i=>i.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==d)throw new b("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const a={lastSeen:r,roomId:o.roomId,sessionId:o.sessionId,...o.data===void 0?{}:{data:o.data},...d===void 0?{}:{userId:d}};await(e?s.db.patch(e._id,a):s.db.insert(l,a));const I=r-m-Math.max(f,m),c=(await s.db.query(l).withIndex("byRoomLastSeen",i=>i.eq("roomId",o.roomId)).order("asc").take(P)).filter(i=>i.lastSeen<=I);return await Promise.all(c.map(i=>s.db.delete(i._id))),{lastSeen:r}}),x=B.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const r=Date.now()-m,e=(await s.db.query(l).withIndex("byRoomLastSeen",n=>n.eq("roomId",o.roomId)).order("desc").take(y)).filter(n=>n.lastSeen>r),a=new Set,I=[];for(const n of e){const c=n.userId;if(c!==void 0){if(a.has(c))continue;a.add(c)}const i={lastSeen:n.lastSeen,roomId:n.roomId};c!==void 0&&(i.userId=c),n.data!==void 0&&(i.data=n.data),I.push(i)}return I}),R={...E.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now()-m,d=await s.db.query(l).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=r).collect();return await Promise.all(d.map(e=>s.db.delete(e._id))),{deleted:d.length}}),visibility:"internal"},q=T(async(o,s)=>{const r=s.context?.roomId,d=s.context?.sessionId;if(typeof r!="string"||typeof d!="string")return;const e=await o.db.query(l).withIndex("byRoomSession",n=>n.eq("roomId",r).eq("sessionId",d)).first();if(!e)return;const a=s.userId??void 0;if((e.userId??void 0)!==a)return;if(f===0){await o.db.delete(e._id);return}const I=Math.min(e.lastSeen,Date.now()+f-m);await o.db.patch(e._id,{lastSeen:I})});return L(w,{extension:N,functions:{disconnect:q,heartbeat:_,listPresent:x,sweep:R}})};export{D as PRESENCE_DEFAULT_TTL_MS,l as PRESENCE_TABLE,G as definePresence,N as presenceExtension};
1
+ import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-D5TSiy5j.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-yKCbHnlj.mjs";const D=3e4,g=1024,P=8,p=4096,w="presence",h="present",l=`${w}_${h}`,N=v(w,{tables:{[h]:A({data:t.optional(t.record(t.string(),t.any())),lastSeen:t.number(),roomId:t.string(),sessionId:t.string(),userId:t.optional(t.string())}).index("byRoomSession",["roomId","sessionId"]).index("byRoom",["roomId"]).index("byRoomLastSeen",["roomId","lastSeen"])}}),{mutation:E,query:B}=M.dataModel().create(),G=(u={})=>{const m=u.ttlMs??D,f=Math.max(0,Math.min(u.disconnectGraceMs??0,m)),S=u.maxSessions,y=S!==void 0&&Number.isFinite(S)?Math.max(1,Math.floor(S)):g,_=E.input({data:t.optional(t.record(t.string(),t.any())),roomId:t.string(),sessionId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now(),d=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>p)throw new b("BAD_REQUEST",`presence data exceeds the ${String(p)}-byte limit`);const e=await s.db.query(l).withIndex("byRoomSession",i=>i.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==d)throw new b("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const a={lastSeen:r,roomId:o.roomId,sessionId:o.sessionId,...o.data===void 0?{}:{data:o.data},...d===void 0?{}:{userId:d}};await(e?s.db.patch(e._id,a):s.db.insert(l,a));const I=r-m-Math.max(f,m),c=(await s.db.query(l).withIndex("byRoomLastSeen",i=>i.eq("roomId",o.roomId)).order("asc").take(P)).filter(i=>i.lastSeen<=I);return await Promise.all(c.map(i=>s.db.delete(i._id))),{lastSeen:r}}),x=B.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const r=Date.now()-m,e=(await s.db.query(l).withIndex("byRoomLastSeen",n=>n.eq("roomId",o.roomId)).order("desc").take(y)).filter(n=>n.lastSeen>r),a=new Set,I=[];for(const n of e){const c=n.userId;if(c!==void 0){if(a.has(c))continue;a.add(c)}const i={lastSeen:n.lastSeen,roomId:n.roomId};c!==void 0&&(i.userId=c),n.data!==void 0&&(i.data=n.data),I.push(i)}return I}),R={...E.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now()-m,d=await s.db.query(l).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=r).collect();return await Promise.all(d.map(e=>s.db.delete(e._id))),{deleted:d.length}}),visibility:"internal"},q=T(async(o,s)=>{const r=s.context?.roomId,d=s.context?.sessionId;if(typeof r!="string"||typeof d!="string")return;const e=await o.db.query(l).withIndex("byRoomSession",n=>n.eq("roomId",r).eq("sessionId",d)).first();if(!e)return;const a=s.userId??void 0;if((e.userId??void 0)!==a)return;if(f===0){await o.db.delete(e._id);return}const I=Math.min(e.lastSeen,Date.now()+f-m);await o.db.patch(e._id,{lastSeen:I})});return L(w,{extension:N,functions:{disconnect:q,heartbeat:_,listPresent:x,sweep:R}})};export{D as PRESENCE_DEFAULT_TTL_MS,l as PRESENCE_TABLE,G as definePresence,N as presenceExtension};
@@ -0,0 +1 @@
1
+ import{a as j}from"./apply-output-C5wZ5EAL.mjs";import{v as i}from"./functions-B2-H4PQT.mjs";import{unionMaskColumns as w}from"./buildMaskRegistry-DpWMtalG.mjs";import{r as C}from"./policy-tag-V0lqFzgS.mjs";import{r as b}from"./run-middleware-CuM-Chm3.mjs";const h=(e,r,o,n)=>n===0&&r===void 0||typeof e!="object"||e===null?e:Object.assign(Object.create(Object.getPrototypeOf(e)),e,{args:Object.freeze({...o}),...r===void 0?{}:{meta:r}}),y=(e,r)=>b(e,r,o=>o),M=(e,r,o,n,t)=>async(s,c)=>{const d=i(e,c),m=await y(r,h(s,t,d,r.length)),l=await o({args:d,ctx:m});return n?j(n,l):l},O=(e,r,o,n)=>(t,s,c)=>{const d=i(e,s);return(async function*(){const l=await y(r,h(t,n,d,r.length)),f=o({args:d,ctx:l,signal:c})[Symbol.asyncIterator]();try{for(;;){if(c.aborted)return;const p=await f.next();if(p.done||c.aborted)return;yield p.value}}finally{await f.return?.()}})()},g=e=>{const r=e.flatMap(o=>C(o));return r.length>0?{tags:r}:void 0},x=e=>{for(const r of["add","clear","delete","set"])typeof e[r]=="function"&&Object.defineProperty(e,r,{configurable:!1,enumerable:!1,value:()=>{throw new TypeError(`Cannot mutate a frozen .meta() declaration (${e.constructor.name}.${r})`)},writable:!1})},u=(e,r)=>{if(e===null||typeof e!="object"||r.has(e))return e;if(r.add(e),e instanceof Map){for(const[o,n]of e)u(o,r),u(n,r);x(e)}else if(e instanceof Set){for(const o of e)u(o,r);x(e)}for(const o of Object.values(e))u(o,r);return Object.freeze(e),e},z=e=>u(structuredClone(e),new WeakSet),a=(e,r,o)=>({__lunoraProcedure:e,...o?{__lunoraVisibility:o}:{},input:n=>a(e,{...r,args:{...r.args,...n}},o),[e]:n=>{const t=g(r.middlewares),s=w(r.middlewares);return{args:r.args,...r.expose?{expose:r.expose}:{},handler:M(r.args,r.middlewares,n,r.output,r.meta),kind:e,...s?{maskedTables:s}:{},...t?{rls:t}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}},meta:n=>a(e,{...r,meta:z({...r.meta,...n})},o),output:n=>a(e,{...r,output:n},o),...e==="query"?{stream:(n,t)=>{const s=g(r.middlewares),c=w(r.middlewares),d=t?.durable===!0?{}:t?.durable;return{args:r.args,...d?{durable:d}:{},...r.expose?{expose:r.expose}:{},handler:O(r.args,r.middlewares,n,r.meta),kind:"stream",...c?{maskedTables:c}:{},...s?{rls:s}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}}}:{},use:n=>a(e,{...r,middlewares:[...r.middlewares,n]},o),...o?{}:{expose:n=>a(e,{...r,expose:n},o)},...o?{}:{x402:n=>a(e,{...r,x402:n},o)}}),H={dataModel:()=>({create:e=>({action:a("action",{args:{},middlewares:[]}),internalAction:a("action",{args:{},middlewares:[]},"internal"),internalMutation:a("mutation",{args:{},middlewares:[]},"internal"),internalQuery:a("query",{args:{},middlewares:[]},"internal"),mutation:a("mutation",{args:{},middlewares:[]}),query:a("query",{args:{},middlewares:[]})})})};export{H as initLunora};
@@ -1 +1 @@
1
- const A=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},E=e=>{const t=atob(e),f=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)f[o]=t.codePointAt(o)??0;return f},i="$lunora.wire$";const d="__proto__",m={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},w={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},p=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},u=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===void 0)return[i,"undefined"];if(e===null)return null;const f=typeof e;if(f==="bigint")return[i,"bigint",e.toString()];if(f==="number"){const r=e;return Number.isNaN(r)?[i,"nan"]:r===1/0?[i,"inf"]:r===-1/0?[i,"-inf"]:r}if(f!=="object")return e;if(e instanceof Date)return[i,"date",u(e.getTime(),t+1)];if(e instanceof Error){const r=e,n={};for(const a of Object.keys(r))r[a]!==void 0&&(n[a]=u(r[a],t+1));const c=[i,"error",r.name,r.message,n];return r.cause!==void 0&&c.push(u(r.cause,t+1)),c}if(e instanceof URL)return[i,"url",e.href];if(e instanceof Map)return[i,"map",[...e.entries()].map(([r,n])=>[u(r,t+1),u(n,t+1)])];if(e instanceof Set)return[i,"set",[...e].map(r=>u(r,t+1))];if(e instanceof ArrayBuffer)return[i,"bytes",A(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,n=r.constructor.name,c=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[i,"bytes",A(c)]:[i,"bytes",A(c),n]}if(Array.isArray(e)){const r=e.map(n=>u(n,t+1));return r.length>0&&r[0]===i?[i,"arr",r]:r}if(!p(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const o=e,s={};for(const r of Object.keys(o)){const n=o[r];if(n===void 0)continue;const c=u(n,t+1);r===d?Object.defineProperty(s,r,{configurable:!0,enumerable:!0,value:c,writable:!0}):s[r]=c}return s},y=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===i)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>y(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>1024||!/^-?\d+$/.test(r))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(r)}case"date":return new Date(y(e[2],t+1));case"map":return new Map(e[2].map(([r,n])=>[y(r,t+1),y(n,t+1)]));case"set":return new Set(e[2].map(r=>y(r,t+1)));case"url":return new URL(e[2]);case"error":{const r=e[2],n=e[3],c=(Object.hasOwn(w,r)?w[r]:void 0)??Error,a=new c(n);a.name!==r&&Object.defineProperty(a,"name",{configurable:!0,value:r,writable:!0});const g=y(e[4],t+1);for(const b of Object.keys(g))b===d?Object.defineProperty(a,b,{configurable:!0,enumerable:!0,value:g[b],writable:!0}):a[b]=g[b];return e.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:y(e[5],t+1),writable:!0}),a}case"bytes":{const r=E(e[2]),n=e[3]??"Uint8Array";if(n==="ArrayBuffer")return r.buffer.byteLength===r.byteLength?r.buffer:r.slice().buffer;const c=Object.hasOwn(m,n)?m[n]:void 0;return c?new c(r.slice().buffer):r}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>y(r,t+1))}return e.map(s=>y(s,t+1))}const f=e,o={};for(const s of Object.keys(f)){const r=y(f[s],t+1);s===d?Object.defineProperty(o,s,{configurable:!0,enumerable:!0,value:r,writable:!0}):o[s]=r}return o};export{y as d,u as e};
1
+ const A=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},p=e=>{const t=atob(e),f=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)f[o]=t.codePointAt(o)??0;return f},i="$lunora.wire$";const d="__proto__",m={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},w={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},E=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},u=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===void 0)return[i,"undefined"];if(e===null)return null;const f=typeof e;if(f==="bigint")return[i,"bigint",e.toString()];if(f==="number"){const r=e;return Number.isNaN(r)?[i,"nan"]:r===1/0?[i,"inf"]:r===-1/0?[i,"-inf"]:r}if(f!=="object")return e;if(e instanceof Date)return[i,"date",u(e.getTime(),t+1)];if(e instanceof Error){const r=e,n={};for(const a of Object.keys(r))r[a]!==void 0&&(n[a]=u(r[a],t+1));const c=[i,"error",r.name,r.message,n];return r.cause!==void 0&&c.push(u(r.cause,t+1)),c}if(e instanceof URL)return[i,"url",e.href];if(e instanceof Map)return[i,"map",[...e.entries()].map(([r,n])=>[u(r,t+1),u(n,t+1)])];if(e instanceof Set)return[i,"set",[...e].map(r=>u(r,t+1))];if(e instanceof ArrayBuffer)return[i,"bytes",A(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,n=r.constructor.name,c=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[i,"bytes",A(c)]:[i,"bytes",A(c),n]}if(Array.isArray(e)){const r=e.map(n=>u(n,t+1));return r.length>0&&r[0]===i?[i,"arr",r]:r}if(!E(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const o=e,s={};for(const r of Object.keys(o)){const n=o[r];if(n===void 0)continue;const c=u(n,t+1);r===d?Object.defineProperty(s,r,{configurable:!0,enumerable:!0,value:c,writable:!0}):s[r]=c}return s},y=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===i)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>y(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>1024||!/^-?\d+$/.test(r))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(r)}case"date":return new Date(y(e[2],t+1));case"map":{const r=e[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(n[0],t+1),y(n[1],t+1)]}))}case"set":return new Set(e[2].map(r=>y(r,t+1)));case"url":return new URL(e[2]);case"error":{const r=e[2],n=e[3],c=(Object.hasOwn(w,r)?w[r]:void 0)??Error,a=new c(n);a.name!==r&&Object.defineProperty(a,"name",{configurable:!0,value:r,writable:!0});const g=y(e[4],t+1);for(const b of Object.keys(g))b===d?Object.defineProperty(a,b,{configurable:!0,enumerable:!0,value:g[b],writable:!0}):a[b]=g[b];return e.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:y(e[5],t+1),writable:!0}),a}case"bytes":{const r=p(e[2]),n=e[3]??"Uint8Array";if(n==="ArrayBuffer")return r.buffer.byteLength===r.byteLength?r.buffer:r.slice().buffer;const c=Object.hasOwn(m,n)?m[n]:void 0;return c?new c(r.slice().buffer):r}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>y(r,t+1))}return e.map(s=>y(s,t+1))}const f=e,o={};for(const s of Object.keys(f)){const r=y(f[s],t+1);s===d?Object.defineProperty(o,s,{configurable:!0,enumerable:!0,value:r,writable:!0}):o[s]=r}return o};export{y as d,u as e};
package/dist/types.d.mts CHANGED
@@ -786,14 +786,26 @@ interface ScheduledFunctionDoc {
786
786
  attempts?: number;
787
787
  /** When the job was enqueued (epoch ms). */
788
788
  enqueuedAt: number;
789
- /** Fully-qualified path of the function to invoke. */
790
- functionPath: string;
789
+ /**
790
+ * Fully-qualified `ns:fn` path of the function to invoke. Absent when the job
791
+ * targets a durable workflow/agent instead — exactly one of `functionPath` /
792
+ * {@link ScheduledFunctionDoc.workflow} is set on any given row.
793
+ */
794
+ functionPath?: string;
791
795
  /** The job's id (the `_scheduled_functions` row id). */
792
796
  id: string;
797
+ /** Logical workpool the job is concurrency-gated by, when any. */
798
+ pool?: string;
793
799
  /** When the job is scheduled to fire (epoch ms). */
794
800
  scheduledFor: number;
795
801
  /** Routing hint forwarded so dispatch lands on the right shard. */
796
802
  shardKey?: string;
803
+ /**
804
+ * The `WORKFLOW_*`/`AGENT_*` binding a fresh durable instance is started from
805
+ * on fire (the {@link ScheduledFunctionDoc.args} become its `params`). Set
806
+ * instead of {@link ScheduledFunctionDoc.functionPath}.
807
+ */
808
+ workflow?: string;
797
809
  }
798
810
  /** Maps each system table name to the document shape its reads return. */
799
811
  interface SystemDocMap {
@@ -1226,22 +1238,51 @@ interface AuthState {
1226
1238
  }
1227
1239
  /**
1228
1240
  * A pending scheduled invocation as surfaced by {@link Scheduler.list} /
1229
- * {@link Scheduler.get}. A clean public mirror of `@lunora/scheduler`'s internal
1230
- * `ScheduleRecord` re-declared here so the public ctx surface carries no
1231
- * dependency on the scheduler package's internal types.
1232
- */
1241
+ * {@link Scheduler.get}. A clean public mirror of `@lunora/scheduler`'s
1242
+ * `ScheduleRecord`, re-declared so the public ctx surface names its own type
1243
+ * rather than re-exporting the scheduler's. It must stay field-for-field
1244
+ * identical: `__tests__/scheduler-mirror.test.ts` asserts mutual assignability
1245
+ * against the real `ScheduleRecord` and fails `lint:types` if either side moves.
1246
+ */
1247
+ interface RetryPolicy {
1248
+ /** Backoff growth across attempts. Default `"exponential"`. */
1249
+ backoff?: "exponential" | "linear";
1250
+ /** Base delay in milliseconds for the first retry. Default `30_000`. */
1251
+ baseMs?: number;
1252
+ /** Maximum number of dispatch attempts before dead-lettering. Default `5`. */
1253
+ maxAttempts?: number;
1254
+ /** Optional ceiling clamping the computed backoff delay. */
1255
+ maxMs?: number;
1256
+ }
1233
1257
  interface ScheduledJob {
1234
1258
  args: Record<string, unknown>;
1235
1259
  /** Number of dispatch attempts already made (absent until the first retry). */
1236
1260
  attempts?: number;
1237
1261
  /** When the job was enqueued (epoch ms). */
1238
1262
  enqueuedAt: number;
1239
- functionPath: string;
1263
+ /**
1264
+ * The `ns:fn` path of the function to dispatch on fire. Absent when the job
1265
+ * targets a durable workflow/agent instead — see {@link ScheduledJob.workflow}.
1266
+ * Exactly one of `functionPath` / `workflow` is set.
1267
+ */
1268
+ functionPath?: string;
1240
1269
  id: string;
1270
+ /** Scheduler/workpool instance the job was enqueued through. Absent for the default instance. */
1271
+ instanceName?: string;
1272
+ /** Logical workpool the job is concurrency-gated by. Absent for plain `runAfter`/`runAt` jobs. */
1273
+ pool?: string;
1274
+ /** Per-job retry policy; absent means the scheduler's built-in defaults. */
1275
+ retry?: RetryPolicy;
1241
1276
  /** When the job is scheduled to fire (epoch ms). */
1242
1277
  scheduledFor: number;
1243
1278
  /** Routing hint forwarded so dispatch lands on the right shard. */
1244
1279
  shardKey?: string;
1280
+ /**
1281
+ * The `WORKFLOW_*`/`AGENT_*` binding name a fresh durable instance is started
1282
+ * from on fire (the {@link ScheduledJob.args} become its `params`). Set
1283
+ * instead of {@link ScheduledJob.functionPath}.
1284
+ */
1285
+ workflow?: string;
1245
1286
  }
1246
1287
  /**
1247
1288
  * A schedulable durable-workflow reference — the generated `workflows.<name>` /
@@ -2328,4 +2369,4 @@ interface ActionCtx {
2328
2369
  */
2329
2370
  type AnyApi = Record<string, Record<string, RegisteredFunction<ArgsValidator, unknown, FunctionKind>>>;
2330
2371
  declare const anyApi: AnyApi;
2331
- export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationDefinition, type RestCacheConfig, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
2372
+ export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationDefinition, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
package/dist/types.d.ts CHANGED
@@ -786,14 +786,26 @@ interface ScheduledFunctionDoc {
786
786
  attempts?: number;
787
787
  /** When the job was enqueued (epoch ms). */
788
788
  enqueuedAt: number;
789
- /** Fully-qualified path of the function to invoke. */
790
- functionPath: string;
789
+ /**
790
+ * Fully-qualified `ns:fn` path of the function to invoke. Absent when the job
791
+ * targets a durable workflow/agent instead — exactly one of `functionPath` /
792
+ * {@link ScheduledFunctionDoc.workflow} is set on any given row.
793
+ */
794
+ functionPath?: string;
791
795
  /** The job's id (the `_scheduled_functions` row id). */
792
796
  id: string;
797
+ /** Logical workpool the job is concurrency-gated by, when any. */
798
+ pool?: string;
793
799
  /** When the job is scheduled to fire (epoch ms). */
794
800
  scheduledFor: number;
795
801
  /** Routing hint forwarded so dispatch lands on the right shard. */
796
802
  shardKey?: string;
803
+ /**
804
+ * The `WORKFLOW_*`/`AGENT_*` binding a fresh durable instance is started from
805
+ * on fire (the {@link ScheduledFunctionDoc.args} become its `params`). Set
806
+ * instead of {@link ScheduledFunctionDoc.functionPath}.
807
+ */
808
+ workflow?: string;
797
809
  }
798
810
  /** Maps each system table name to the document shape its reads return. */
799
811
  interface SystemDocMap {
@@ -1226,22 +1238,51 @@ interface AuthState {
1226
1238
  }
1227
1239
  /**
1228
1240
  * A pending scheduled invocation as surfaced by {@link Scheduler.list} /
1229
- * {@link Scheduler.get}. A clean public mirror of `@lunora/scheduler`'s internal
1230
- * `ScheduleRecord` re-declared here so the public ctx surface carries no
1231
- * dependency on the scheduler package's internal types.
1232
- */
1241
+ * {@link Scheduler.get}. A clean public mirror of `@lunora/scheduler`'s
1242
+ * `ScheduleRecord`, re-declared so the public ctx surface names its own type
1243
+ * rather than re-exporting the scheduler's. It must stay field-for-field
1244
+ * identical: `__tests__/scheduler-mirror.test.ts` asserts mutual assignability
1245
+ * against the real `ScheduleRecord` and fails `lint:types` if either side moves.
1246
+ */
1247
+ interface RetryPolicy {
1248
+ /** Backoff growth across attempts. Default `"exponential"`. */
1249
+ backoff?: "exponential" | "linear";
1250
+ /** Base delay in milliseconds for the first retry. Default `30_000`. */
1251
+ baseMs?: number;
1252
+ /** Maximum number of dispatch attempts before dead-lettering. Default `5`. */
1253
+ maxAttempts?: number;
1254
+ /** Optional ceiling clamping the computed backoff delay. */
1255
+ maxMs?: number;
1256
+ }
1233
1257
  interface ScheduledJob {
1234
1258
  args: Record<string, unknown>;
1235
1259
  /** Number of dispatch attempts already made (absent until the first retry). */
1236
1260
  attempts?: number;
1237
1261
  /** When the job was enqueued (epoch ms). */
1238
1262
  enqueuedAt: number;
1239
- functionPath: string;
1263
+ /**
1264
+ * The `ns:fn` path of the function to dispatch on fire. Absent when the job
1265
+ * targets a durable workflow/agent instead — see {@link ScheduledJob.workflow}.
1266
+ * Exactly one of `functionPath` / `workflow` is set.
1267
+ */
1268
+ functionPath?: string;
1240
1269
  id: string;
1270
+ /** Scheduler/workpool instance the job was enqueued through. Absent for the default instance. */
1271
+ instanceName?: string;
1272
+ /** Logical workpool the job is concurrency-gated by. Absent for plain `runAfter`/`runAt` jobs. */
1273
+ pool?: string;
1274
+ /** Per-job retry policy; absent means the scheduler's built-in defaults. */
1275
+ retry?: RetryPolicy;
1241
1276
  /** When the job is scheduled to fire (epoch ms). */
1242
1277
  scheduledFor: number;
1243
1278
  /** Routing hint forwarded so dispatch lands on the right shard. */
1244
1279
  shardKey?: string;
1280
+ /**
1281
+ * The `WORKFLOW_*`/`AGENT_*` binding name a fresh durable instance is started
1282
+ * from on fire (the {@link ScheduledJob.args} become its `params`). Set
1283
+ * instead of {@link ScheduledJob.functionPath}.
1284
+ */
1285
+ workflow?: string;
1245
1286
  }
1246
1287
  /**
1247
1288
  * A schedulable durable-workflow reference — the generated `workflows.<name>` /
@@ -2328,4 +2369,4 @@ interface ActionCtx {
2328
2369
  */
2329
2370
  type AnyApi = Record<string, Record<string, RegisteredFunction<ArgsValidator, unknown, FunctionKind>>>;
2330
2371
  declare const anyApi: AnyApi;
2331
- export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationDefinition, type RestCacheConfig, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
2372
+ export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationDefinition, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/server",
3
- "version": "1.0.0-alpha.95",
3
+ "version": "1.0.0-alpha.97",
4
4
  "description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
5
5
  "keywords": [
6
6
  "backend",
@@ -66,9 +66,9 @@
66
66
  "access": "public"
67
67
  },
68
68
  "dependencies": {
69
- "@lunora/errors": "1.0.0-alpha.26",
70
- "@lunora/scheduler": "1.0.0-alpha.45",
71
- "@lunora/values": "1.0.0-alpha.34",
69
+ "@lunora/errors": "1.0.0-alpha.27",
70
+ "@lunora/scheduler": "1.0.0-alpha.47",
71
+ "@lunora/values": "1.0.0-alpha.35",
72
72
  "drizzle-orm": "^0.45.2",
73
73
  "hono": "^4.13.1"
74
74
  },
@@ -1 +0,0 @@
1
- import{a as h}from"./apply-output-C5wZ5EAL.mjs";import{v as i}from"./functions-B2-H4PQT.mjs";import{unionMaskColumns as w}from"./buildMaskRegistry-DpWMtalG.mjs";import{r as j}from"./policy-tag-V0lqFzgS.mjs";import{r as b}from"./run-middleware-CuM-Chm3.mjs";const y=(e,r)=>r===void 0||typeof e!="object"||e===null?e:Object.assign(Object.create(Object.getPrototypeOf(e)),e,{meta:r}),M=(e,r)=>b(e,r,o=>o),C=(e,r,o,n,t)=>async(s,d)=>{const c=i(e,d),l=await M(r,y(s,t)),m=await o({args:c,ctx:l});return n?h(n,m):m},O=(e,r,o,n)=>(t,s,d)=>{const c=i(e,s);return(async function*(){const m=await M(r,y(t,n)),f=o({args:c,ctx:m,signal:d})[Symbol.asyncIterator]();try{for(;;){if(d.aborted)return;const p=await f.next();if(p.done||d.aborted)return;yield p.value}}finally{await f.return?.()}})()},g=e=>{const r=e.flatMap(o=>j(o));return r.length>0?{tags:r}:void 0},x=e=>{for(const r of["add","clear","delete","set"])typeof e[r]=="function"&&Object.defineProperty(e,r,{configurable:!1,enumerable:!1,value:()=>{throw new TypeError(`Cannot mutate a frozen .meta() declaration (${e.constructor.name}.${r})`)},writable:!1})},u=(e,r)=>{if(e===null||typeof e!="object"||r.has(e))return e;if(r.add(e),e instanceof Map){for(const[o,n]of e)u(o,r),u(n,r);x(e)}else if(e instanceof Set){for(const o of e)u(o,r);x(e)}for(const o of Object.values(e))u(o,r);return Object.freeze(e),e},_=e=>u(structuredClone(e),new WeakSet),a=(e,r,o)=>({__lunoraProcedure:e,...o?{__lunoraVisibility:o}:{},input:n=>a(e,{...r,args:{...r.args,...n}},o),[e]:n=>{const t=g(r.middlewares),s=w(r.middlewares);return{args:r.args,...r.expose?{expose:r.expose}:{},handler:C(r.args,r.middlewares,n,r.output,r.meta),kind:e,...s?{maskedTables:s}:{},...t?{rls:t}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}},meta:n=>a(e,{...r,meta:_({...r.meta,...n})},o),output:n=>a(e,{...r,output:n},o),...e==="query"?{stream:(n,t)=>{const s=g(r.middlewares),d=w(r.middlewares),c=t?.durable===!0?{}:t?.durable;return{args:r.args,...c?{durable:c}:{},...r.expose?{expose:r.expose}:{},handler:O(r.args,r.middlewares,n,r.meta),kind:"stream",...d?{maskedTables:d}:{},...s?{rls:s}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}}}:{},use:n=>a(e,{...r,middlewares:[...r.middlewares,n]},o),...o?{}:{expose:n=>a(e,{...r,expose:n},o)},...o?{}:{x402:n=>a(e,{...r,x402:n},o)}}),H={dataModel:()=>({create:e=>({action:a("action",{args:{},middlewares:[]}),internalAction:a("action",{args:{},middlewares:[]},"internal"),internalMutation:a("mutation",{args:{},middlewares:[]},"internal"),internalQuery:a("query",{args:{},middlewares:[]},"internal"),mutation:a("mutation",{args:{},middlewares:[]}),query:a("query",{args:{},middlewares:[]})})})};export{H as initLunora};