@lunora/server 1.0.0-alpha.6 → 1.0.0-alpha.60

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.
Files changed (73) hide show
  1. package/LICENSE.md +219 -0
  2. package/README.md +50 -0
  3. package/dist/data-model.d.mts +252 -156
  4. package/dist/data-model.d.ts +252 -156
  5. package/dist/data-model.mjs +0 -1
  6. package/dist/drizzle.mjs +1 -1
  7. package/dist/index.d.mts +1795 -977
  8. package/dist/index.d.ts +1795 -977
  9. package/dist/index.mjs +1 -25
  10. package/dist/otel.d.mts +543 -0
  11. package/dist/otel.d.ts +543 -0
  12. package/dist/otel.mjs +1 -0
  13. package/dist/packem_shared/DEFAULT_LIMIT-yHJ5O96W.mjs +1 -0
  14. package/dist/packem_shared/LunoraEnvError-CgpI2Mm_.mjs +3 -0
  15. package/dist/packem_shared/LunoraError-LVhdU0Lo.mjs +1 -0
  16. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-DmnVChTY.mjs +1 -0
  17. package/dist/packem_shared/allowAll-BnyNbJZT.mjs +1 -0
  18. package/dist/packem_shared/asBucketStorage-BthCnWop.mjs +1 -0
  19. package/dist/packem_shared/bindOrm-Bp9hsM2q.mjs +1 -0
  20. package/dist/packem_shared/buildMaskRegistry-BCIzKxdK.mjs +1 -0
  21. package/dist/packem_shared/buildRlsReadRegistry-CA-aUi7I.mjs +1 -0
  22. package/dist/packem_shared/composePluginMiddleware-B9NyOR1k.mjs +1 -0
  23. package/dist/packem_shared/context-identity-GunnA6La.mjs +1 -0
  24. package/dist/packem_shared/createPolicyDsl-sV1swpkD.mjs +1 -0
  25. package/dist/packem_shared/createSecrets-CgVPiW2C.mjs +1 -0
  26. package/dist/packem_shared/defineAggregateIndex-C3CMy5jn.mjs +1 -0
  27. package/dist/packem_shared/defineIdentity-B7gfAgxx.mjs +1 -0
  28. package/dist/packem_shared/defineMigration-Bfpwxv2f.mjs +1 -0
  29. package/dist/packem_shared/defineMutator-BgpQ-xUo.mjs +1 -0
  30. package/dist/packem_shared/defineShape-Ds8uNqzX.mjs +1 -0
  31. package/dist/packem_shared/defineStorageRule-BDu01PUn.mjs +1 -0
  32. package/dist/packem_shared/functions-CDC08CWY.mjs +1 -0
  33. package/dist/packem_shared/httpAction-C14NuF3V.mjs +4 -0
  34. package/dist/packem_shared/initLunora-DXCOVntr.mjs +1 -0
  35. package/dist/packem_shared/mask-DF7mtxQe.mjs +1 -0
  36. package/dist/packem_shared/onConnect-CEtRmUpJ.mjs +1 -0
  37. package/dist/packem_shared/optional-writer-override-CXXO30sZ.mjs +1 -0
  38. package/dist/packem_shared/plugin-CDBMGCeQ.mjs +1 -0
  39. package/dist/packem_shared/policy-tag-Dprt9JWo.mjs +1 -0
  40. package/dist/packem_shared/protectPublic-BhKewPqm.mjs +1 -0
  41. package/dist/packem_shared/rls-tRDkICWZ.mjs +1 -0
  42. package/dist/packem_shared/run-middleware-BeEEqmdE.mjs +1 -0
  43. package/dist/packem_shared/storageRules-BptPZbi8.mjs +1 -0
  44. package/dist/packem_shared/types.d-C4CMJK8x.d.mts +141 -0
  45. package/dist/packem_shared/types.d-DdYF8E18.d.ts +141 -0
  46. package/dist/rls/testing.d.mts +31 -31
  47. package/dist/rls/testing.d.ts +31 -31
  48. package/dist/rls/testing.mjs +1 -49
  49. package/dist/types.d.mts +1438 -475
  50. package/dist/types.d.ts +1438 -475
  51. package/dist/types.mjs +1 -31
  52. package/package.json +17 -4
  53. package/dist/packem_shared/LunoraEnvError-DjFkpkSP.mjs +0 -187
  54. package/dist/packem_shared/LunoraError-DhggBJZF.mjs +0 -51
  55. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-BgBQsqQ-.mjs +0 -114
  56. package/dist/packem_shared/asBucketStorage-Cnxd9y2q.mjs +0 -11
  57. package/dist/packem_shared/bindOrm-Ce57S3N9.mjs +0 -128
  58. package/dist/packem_shared/composePluginMiddleware-Ck5_TUO8.mjs +0 -100
  59. package/dist/packem_shared/createPolicyDsl-De67zPDS.mjs +0 -29
  60. package/dist/packem_shared/createSecrets-TsIP9lOa.mjs +0 -55
  61. package/dist/packem_shared/defineAggregateIndex-C2gT1GzM.mjs +0 -252
  62. package/dist/packem_shared/defineMigration-CAJLr6fx.mjs +0 -8
  63. package/dist/packem_shared/defineStorageRule-qu0mpilX.mjs +0 -20
  64. package/dist/packem_shared/httpAction-B7FYUEgr.mjs +0 -340
  65. package/dist/packem_shared/initLunora-CATvPsVt.mjs +0 -86
  66. package/dist/packem_shared/mask-eCUYOwhd.mjs +0 -211
  67. package/dist/packem_shared/onConnect-CIPXKPyw.mjs +0 -13
  68. package/dist/packem_shared/protectPublic-BjFkQ_Or.mjs +0 -15
  69. package/dist/packem_shared/rls-Bi9HiyDC.mjs +0 -567
  70. package/dist/packem_shared/run-middleware-CYQOuoV6.mjs +0 -18
  71. package/dist/packem_shared/storageRules-4a30FSpI.mjs +0 -88
  72. package/dist/packem_shared/types.d-BDY0FYHK.d.ts +0 -135
  73. package/dist/packem_shared/types.d-DmvyEMD6.d.mts +0 -135
package/dist/index.d.mts CHANGED
@@ -1,37 +1,41 @@
1
- import { Validator, Infer, v } from '@lunora/values';
2
- export { type ColumnValidator, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
3
- import { ArgsValidator, InferArgs, RegisteredAction, ActionCtx, MutationCtx, RegisteredMutation, QueryCtx, RegisteredQuery, RegisteredStream, FunctionKind, Secrets, LifecycleEvent, RegisteredLifecycleHook, TableDefinition, RegisteredFunction, VectorIndexDefinition, Schema, AggregateOp, DurableObjectJurisdiction, RelationDefinition, GlobalBackend, OnDeleteAction, TriggerBuilder, TriggerDefinition, VectorEmbedder, VectorMetric, AggregateIndexDefinition, RankIndexDefinition } from "./types.mjs";
4
- export { type AnyApi, type AuthState, type DatabaseReader, type DatabaseWriter, type FunctionVisibility, type IndexDefinition, type IndexRangeBuilder, type LifecycleEventKind, type LunoraLogger, type PaginationOptions, type PaginationResult, type RankSortKey, type ReadOnlyStorage, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type SearchFilterBuilder, type SearchIndexDefinition, type ShardMode, type Storage, type StorageMetadata, 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 VectorMatch, type VectorMatches, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } from "./types.mjs";
1
+ import { Validator, Infer, ValidatorMap, InferValidatorMap, ColumnValidator, v } from '@lunora/values';
2
+ export { type ColumnValidator, type GeoPoint, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
3
+ import { ArgsValidator, InferArgs, RegisteredAction, ExposeConfig, X402ProcedureConfig, ActionCtx, MutationCtx, RegisteredMutation, QueryCtx, RegisteredQuery, RegisteredStream, FunctionKind, Secrets, LifecycleEvent, RegisteredLifecycleHook, TableDefinition, RegisteredFunction, VectorIndexDefinition, Schema, AggregateOp, DurableObjectJurisdiction, RelationDefinition, GlobalBackend, OnDeleteAction, SearchLanguage, SearchStrategy, ExternalSourceDefinition, TriggerBuilder, TriggerDefinition, VectorEmbedder, VectorMetric, AggregateIndexDefinition, RankIndexDefinition } 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 PaginationOptions, type PaginationResult, type RankSortKey, type ReadOnlyStorage, type RestCacheConfig, 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 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 WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } from "./types.mjs";
5
+ import { LunoraError as LunoraError$1, LunoraErrorCode } from '@lunora/errors';
6
+ export type { LunoraErrorCode } from '@lunora/errors';
5
7
  import { Context, Hono } from 'hono';
6
- import { b as Permission, R as Role, T as TypedDefinePolicyInput, a as Policy, D as DefinePolicyInput, W as WhereInput, c as RlsOptions } from "./packem_shared/types.d-DmvyEMD6.mjs";
7
- export type { d as PolicyContext, e as PolicyDecision, f as PolicyDecisionOf, P as PolicyOperation } from "./packem_shared/types.d-DmvyEMD6.mjs";
8
+ import { WhereOperators, QueryArgs as QueryArgs$2 } from "./data-model.mjs";
9
+ import { b as Permission, R as Role, T as TypedDefinePolicyInput, a as Policy, D as DefinePolicyInput, W as WhereInput, c as RlsOptions } from "./packem_shared/types.d-C4CMJK8x.mjs";
10
+ export type { d as PolicyContext, e as PolicyDecision, f as PolicyDecisionOf, P as PolicyOperation } from "./packem_shared/types.d-C4CMJK8x.mjs";
8
11
  export { type CronJob, type CronJobsBuilder, type CronScheduleKind, type DailySchedule, type IntervalSchedule, type MonthlySchedule, type WeeklySchedule, cronJobs } from '@lunora/scheduler';
9
- import "./data-model.mjs";
10
- /**
11
- * Make any `config.storage` result bucket-aware so `ctx.storage.bucket(name)`
12
- * always resolves. A `createBucketStorage(...)` result already carries
13
- * `.bucket` / `.bucketName` and is returned as-is; a single `createStorage(...)`
14
- * (or the no-storage stub) is tagged as the `"default"` bucket, where
15
- * `.bucket(name)` is the identity — single-bucket apps address one binding under
16
- * every name.
17
- *
18
- * This is the runtime counterpart the generated `_generated/shard.ts` imports to
19
- * wrap `ctx.storage`; it lives here (the single source) rather than being stamped
20
- * inline into every generated file, so the bucket-tagging behaviour has one home
21
- * alongside the storage ctx types. The input is genuinely heterogeneous (a thunk
22
- * result cast through `unknown`), so the signature is `unknown → unknown`; the
23
- * generated caller casts the result to its storage type.
24
- */
12
+ /**
13
+ * Make any resolved storage capability bucket-aware so `ctx.storage.bucket(name)`
14
+ * always resolves. A `createBucketStorage(...)` result already carries
15
+ * `.bucket` / `.bucketName` and is returned as-is; a single `createStorage(...)`
16
+ * (or the no-storage stub) is tagged as the `"default"` bucket, where
17
+ * `.bucket(name)` is the identity single-bucket apps address one binding under
18
+ * every name.
19
+ *
20
+ * Lives here rather than in `@lunora/server` because two packages need it and
21
+ * neither may depend on the other: `@lunora/server` re-exports it as the runtime
22
+ * counterpart `_generated/shard.ts` imports, and `@lunora/runtime` uses it to
23
+ * build `ctx.storage` for an HTTP action from the worker's own R2 bindings.
24
+ * Inlined into each `dist` by the bundler, so no dependency edge is created.
25
+ *
26
+ * The input is genuinely heterogeneous (a thunk result cast through `unknown`),
27
+ * so the signature is `unknown → unknown`; callers cast the result.
28
+ */
25
29
  declare const asBucketStorage: (raw: unknown) => unknown;
26
30
  /** Builder discriminator. Codegen reads this kind. */
27
31
  type TerminalKind = FunctionKind;
28
32
  /** Initial (empty) accumulated args for a fresh builder. */
29
33
  type EmptyArgs = Record<never, never>;
30
34
  /**
31
- * `next()` advances the middleware chain. Called with no argument it forwards
32
- * the current context unchanged; called with `{ ctx }` it shallow-merges the
33
- * extension, and the result type reflects the widened context.
34
- */
35
+ * `next()` advances the middleware chain. Called with no argument it forwards
36
+ * the current context unchanged; called with `{ ctx }` it shallow-merges the
37
+ * extension, and the result type reflects the widened context.
38
+ */
35
39
  interface MiddlewareNext<ContextIn> {
36
40
  (): Promise<ContextIn>;
37
41
  <Extension extends Record<string, unknown>>(options: {
@@ -39,10 +43,10 @@ interface MiddlewareNext<ContextIn> {
39
43
  }): Promise<ContextIn & Extension>;
40
44
  }
41
45
  /**
42
- * A middleware receives the current context and a `next` continuation. Its
43
- * return type becomes the builder's new context, so `return next({ ctx })`
44
- * propagates the extension into every downstream `.use()` and the handler.
45
- */
46
+ * A middleware receives the current context and a `next` continuation. Its
47
+ * return type becomes the builder's new context, so `return next({ ctx })`
48
+ * propagates the extension into every downstream `.use()` and the handler.
49
+ */
46
50
  type Middleware<ContextIn, ContextOut> = (options: {
47
51
  ctx: ContextIn;
48
52
  next: MiddlewareNext<ContextIn>;
@@ -50,17 +54,35 @@ type Middleware<ContextIn, ContextOut> = (options: {
50
54
  /** Options accepted by `initLunora.dataModel&lt;DM>().create(...)`. Reserved for transformer/error-formatter wiring. */
51
55
  type CreateOptions = Record<never, never>;
52
56
  /**
53
- * `Output` carries the type declared by `.output(validator)`. It defaults to
54
- * the `undefined` sentinel meaning "not declared": in that state the terminal
55
- * stays generic over the handler's own return type. Once `.output()` sets it to
56
- * a concrete type, the terminal requires the handler to return that type and
57
- * the registration is typed to it (the runtime parses the result through the
58
- * validator). `[Output] extends [undefined]` is wrapped in a tuple so a union
59
- * `Output` doesn't distribute and so the test is for the exact sentinel.
60
- */
57
+ * `Output` carries the type declared by `.output(validator)`. It defaults to
58
+ * the `undefined` sentinel meaning "not declared": in that state the terminal
59
+ * stays generic over the handler's own return type. Once `.output()` sets it to
60
+ * a concrete type, the terminal requires the handler to return that type and
61
+ * the registration is typed to it (the runtime parses the result through the
62
+ * validator). `[Output] extends [undefined]` is wrapped in a tuple so a union
63
+ * `Output` doesn't distribute and so the test is for the exact sentinel.
64
+ */
61
65
  interface QueryBuilder<Context, Args extends ArgsValidator, Output = undefined> {
62
66
  readonly __lunoraProcedure: "query";
67
+ /**
68
+ * Publish this query on the opt-in public REST surface (plan 167) — the
69
+ * runtime mints `GET /_lunora/rest/&lt;namespace>/&lt;fn>` (and `POST`), dispatching
70
+ * THROUGH the procedure so `ctx.auth` / RLS / validators are enforced, and the
71
+ * generated OpenAPI describes it. Default-closed: omit to keep it RPC-only.
72
+ */
73
+ expose: (config: ExposeConfig) => QueryBuilder<Context, Args, Output>;
63
74
  input: <A extends ArgsValidator>(validators: A) => QueryBuilder<Context, A & Args, Output>;
75
+ /**
76
+ * Attach static, per-procedure metadata. Merges across calls, is readable
77
+ * from middleware as `ctx.meta`, and is stamped onto the registration as
78
+ * `fn.meta` so codegen and other tooling can enumerate it.
79
+ *
80
+ * The point is policy that is DATA rather than a call: `.meta({ rateLimit:
81
+ * "pins/create" })` can be walked to generate a rate-limit registry or docs,
82
+ * where the same policy expressed only as `.use(rateLimit("pins/create"))`
83
+ * can only be executed. Mirrors tRPC's `.meta()`.
84
+ */
85
+ meta: (value: Record<string, unknown>) => QueryBuilder<Context, Args, Output>;
64
86
  output: <V extends Validator>(validator: V) => QueryBuilder<Context, Args, Infer<V>>;
65
87
  query: [Output] extends [undefined] ? <R>(handler: (options: {
66
88
  args: InferArgs<Args>;
@@ -70,23 +92,48 @@ interface QueryBuilder<Context, Args extends ArgsValidator, Output = undefined>
70
92
  ctx: Context;
71
93
  }) => Output | Promise<Output>) => RegisteredQuery<Args, Output>;
72
94
  /**
73
- * Terminal: declare this procedure as a streaming query. The handler is an
74
- * async generator (or any function returning an `AsyncIterable&lt;R>`) that
75
- * yields one chunk per server-pushed frame. The third `signal` argument is
76
- * tripped when the client cancels — break out of the loop or check
77
- * `signal.aborted` between yields. `.output()` does not apply: per-chunk
78
- * validation is opt-in via the handler itself.
79
- */
95
+ * Terminal: declare this procedure as a streaming query. The handler is an
96
+ * async generator (or any function returning an `AsyncIterable&lt;R>`) that
97
+ * yields one chunk per server-pushed frame. The third `signal` argument is
98
+ * tripped when the client cancels — break out of the loop or check
99
+ * `signal.aborted` between yields. `.output()` does not apply: per-chunk
100
+ * validation is opt-in via the handler itself.
101
+ */
80
102
  stream: <R>(handler: (options: {
81
103
  args: InferArgs<Args>;
82
104
  ctx: Context;
83
105
  signal: AbortSignal;
84
106
  }) => AsyncGenerator<R, void, void> | AsyncIterable<R>) => RegisteredStream<Args, R>;
85
107
  use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => QueryBuilder<ContextOut, Args, Output>;
108
+ /**
109
+ * Mark this query as paid. The origin worker answers an unpaid client RPC
110
+ * with HTTP 402, verifies + settles the x402 payment, then dispatches. `price`
111
+ * is USD (a number of dollars or a `"0.01"`/`"$0.01"` string); the network,
112
+ * recipient, and facilitator come from the worker-level x402 charge config.
113
+ */
114
+ x402: (config: X402ProcedureConfig) => QueryBuilder<Context, Args, Output>;
86
115
  }
87
116
  interface MutationBuilder<Context, Args extends ArgsValidator, Output = undefined> {
88
117
  readonly __lunoraProcedure: "mutation";
118
+ /**
119
+ * Publish this mutation on the opt-in public REST surface (plan 167) — the
120
+ * runtime mints `POST /_lunora/rest/&lt;namespace>/&lt;fn>`, dispatching THROUGH the
121
+ * procedure so `ctx.auth` / RLS / validators are enforced, and the generated
122
+ * OpenAPI describes it. Default-closed: omit to keep it RPC-only.
123
+ */
124
+ expose: (config: ExposeConfig) => MutationBuilder<Context, Args, Output>;
89
125
  input: <A extends ArgsValidator>(validators: A) => MutationBuilder<Context, A & Args, Output>;
126
+ /**
127
+ * Attach static, per-procedure metadata. Merges across calls, is readable
128
+ * from middleware as `ctx.meta`, and is stamped onto the registration as
129
+ * `fn.meta` so codegen and other tooling can enumerate it.
130
+ *
131
+ * The point is policy that is DATA rather than a call: `.meta({ rateLimit:
132
+ * "pins/create" })` can be walked to generate a rate-limit registry or docs,
133
+ * where the same policy expressed only as `.use(rateLimit("pins/create"))`
134
+ * can only be executed. Mirrors tRPC's `.meta()`.
135
+ */
136
+ meta: (value: Record<string, unknown>) => MutationBuilder<Context, Args, Output>;
90
137
  mutation: [Output] extends [undefined] ? <R>(handler: (options: {
91
138
  args: InferArgs<Args>;
92
139
  ctx: Context;
@@ -96,6 +143,13 @@ interface MutationBuilder<Context, Args extends ArgsValidator, Output = undefine
96
143
  }) => Output | Promise<Output>) => RegisteredMutation<Args, Output>;
97
144
  output: <V extends Validator>(validator: V) => MutationBuilder<Context, Args, Infer<V>>;
98
145
  use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => MutationBuilder<ContextOut, Args, Output>;
146
+ /**
147
+ * Mark this mutation as paid. The origin worker answers an unpaid client RPC
148
+ * with HTTP 402, verifies + settles the x402 payment, then dispatches. `price`
149
+ * is USD (a number of dollars or a `"0.01"`/`"$0.01"` string); the network,
150
+ * recipient, and facilitator come from the worker-level x402 charge config.
151
+ */
152
+ x402: (config: X402ProcedureConfig) => MutationBuilder<Context, Args, Output>;
99
153
  }
100
154
  interface ActionBuilder<Context, Args extends ArgsValidator, Output = undefined> {
101
155
  readonly __lunoraProcedure: "action";
@@ -106,20 +160,56 @@ interface ActionBuilder<Context, Args extends ArgsValidator, Output = undefined>
106
160
  args: InferArgs<Args>;
107
161
  ctx: Context;
108
162
  }) => Output | Promise<Output>) => RegisteredAction<Args, Output>;
163
+ /**
164
+ * Publish this action on the opt-in public REST surface (plan 167) — the
165
+ * runtime mints `POST /_lunora/rest/&lt;namespace>/&lt;fn>`, dispatching THROUGH the
166
+ * procedure so `ctx.auth` / RLS / validators are enforced, and the generated
167
+ * OpenAPI describes it. Default-closed: omit to keep it RPC-only.
168
+ */
169
+ expose: (config: ExposeConfig) => ActionBuilder<Context, Args, Output>;
109
170
  input: <A extends ArgsValidator>(validators: A) => ActionBuilder<Context, A & Args, Output>;
171
+ /**
172
+ * Attach static, per-procedure metadata. Merges across calls, is readable
173
+ * from middleware as `ctx.meta`, and is stamped onto the registration as
174
+ * `fn.meta` so codegen and other tooling can enumerate it.
175
+ *
176
+ * The point is policy that is DATA rather than a call: `.meta({ rateLimit:
177
+ * "pins/create" })` can be walked to generate a rate-limit registry or docs,
178
+ * where the same policy expressed only as `.use(rateLimit("pins/create"))`
179
+ * can only be executed. Mirrors tRPC's `.meta()`.
180
+ */
181
+ meta: (value: Record<string, unknown>) => ActionBuilder<Context, Args, Output>;
110
182
  output: <V extends Validator>(validator: V) => ActionBuilder<Context, Args, Infer<V>>;
111
183
  use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => ActionBuilder<ContextOut, Args, Output>;
112
- }
113
- /**
114
- * Internal builder variants. Identical to their public counterparts but carry
115
- * the `__lunoraVisibility: "internal"` brand codegen keys off to route the
116
- * registration into the `internal` object (and keep it off `api`). `input`/`use`
117
- * return the internal builder type so the brand survives the whole chain.
118
- */
184
+ /**
185
+ * Mark this action as paid. The origin worker answers an unpaid client RPC
186
+ * with HTTP 402, verifies + settles the x402 payment, then dispatches. `price`
187
+ * is USD (a number of dollars or a `"0.01"`/`"$0.01"` string); the network,
188
+ * recipient, and facilitator come from the worker-level x402 charge config.
189
+ */
190
+ x402: (config: X402ProcedureConfig) => ActionBuilder<Context, Args, Output>;
191
+ }
192
+ /**
193
+ * Internal builder variants. Identical to their public counterparts but carry
194
+ * the `__lunoraVisibility: "internal"` brand codegen keys off to route the
195
+ * registration into the `internal` object (and keep it off `api`). `input`/`use`
196
+ * return the internal builder type so the brand survives the whole chain.
197
+ */
119
198
  interface InternalQueryBuilder<Context, Args extends ArgsValidator, Output = undefined> {
120
199
  readonly __lunoraProcedure: "query";
121
200
  readonly __lunoraVisibility: "internal";
122
201
  input: <A extends ArgsValidator>(validators: A) => InternalQueryBuilder<Context, A & Args, Output>;
202
+ /**
203
+ * Attach static, per-procedure metadata. Merges across calls, is readable
204
+ * from middleware as `ctx.meta`, and is stamped onto the registration as
205
+ * `fn.meta` so codegen and other tooling can enumerate it.
206
+ *
207
+ * The point is policy that is DATA rather than a call: `.meta({ rateLimit:
208
+ * "pins/create" })` can be walked to generate a rate-limit registry or docs,
209
+ * where the same policy expressed only as `.use(rateLimit("pins/create"))`
210
+ * can only be executed. Mirrors tRPC's `.meta()`.
211
+ */
212
+ meta: (value: Record<string, unknown>) => InternalQueryBuilder<Context, Args, Output>;
123
213
  output: <V extends Validator>(validator: V) => InternalQueryBuilder<Context, Args, Infer<V>>;
124
214
  query: [Output] extends [undefined] ? <R>(handler: (options: {
125
215
  args: InferArgs<Args>;
@@ -140,6 +230,17 @@ interface InternalMutationBuilder<Context, Args extends ArgsValidator, Output =
140
230
  readonly __lunoraProcedure: "mutation";
141
231
  readonly __lunoraVisibility: "internal";
142
232
  input: <A extends ArgsValidator>(validators: A) => InternalMutationBuilder<Context, A & Args, Output>;
233
+ /**
234
+ * Attach static, per-procedure metadata. Merges across calls, is readable
235
+ * from middleware as `ctx.meta`, and is stamped onto the registration as
236
+ * `fn.meta` so codegen and other tooling can enumerate it.
237
+ *
238
+ * The point is policy that is DATA rather than a call: `.meta({ rateLimit:
239
+ * "pins/create" })` can be walked to generate a rate-limit registry or docs,
240
+ * where the same policy expressed only as `.use(rateLimit("pins/create"))`
241
+ * can only be executed. Mirrors tRPC's `.meta()`.
242
+ */
243
+ meta: (value: Record<string, unknown>) => InternalMutationBuilder<Context, Args, Output>;
143
244
  mutation: [Output] extends [undefined] ? <R>(handler: (options: {
144
245
  args: InferArgs<Args>;
145
246
  ctx: Context;
@@ -161,6 +262,17 @@ interface InternalActionBuilder<Context, Args extends ArgsValidator, Output = un
161
262
  ctx: Context;
162
263
  }) => Output | Promise<Output>) => RegisteredAction<Args, Output>;
163
264
  input: <A extends ArgsValidator>(validators: A) => InternalActionBuilder<Context, A & Args, Output>;
265
+ /**
266
+ * Attach static, per-procedure metadata. Merges across calls, is readable
267
+ * from middleware as `ctx.meta`, and is stamped onto the registration as
268
+ * `fn.meta` so codegen and other tooling can enumerate it.
269
+ *
270
+ * The point is policy that is DATA rather than a call: `.meta({ rateLimit:
271
+ * "pins/create" })` can be walked to generate a rate-limit registry or docs,
272
+ * where the same policy expressed only as `.use(rateLimit("pins/create"))`
273
+ * can only be executed. Mirrors tRPC's `.meta()`.
274
+ */
275
+ meta: (value: Record<string, unknown>) => InternalActionBuilder<Context, Args, Output>;
164
276
  output: <V extends Validator>(validator: V) => InternalActionBuilder<Context, Args, Infer<V>>;
165
277
  use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => InternalActionBuilder<ContextOut, Args, Output>;
166
278
  }
@@ -179,38 +291,38 @@ interface DataModelInit<DataModel> {
179
291
  create: (options?: CreateOptions) => LunoraBuilders;
180
292
  }
181
293
  /**
182
- * Entry point for the procedure builder. `dataModel&lt;DM>()` binds the generated
183
- * `DataModel` (phantom for now), and `.create()` yields the public root builders
184
- * plus their `internal*` counterparts.
185
- */
294
+ * Entry point for the procedure builder. `dataModel&lt;DM>()` binds the generated
295
+ * `DataModel` (phantom for now), and `.create()` yields the public root builders
296
+ * plus their `internal*` counterparts.
297
+ */
186
298
  declare const initLunora: {
187
299
  dataModel: <DataModel>() => DataModelInit<DataModel>;
188
300
  };
189
301
  /**
190
- * Build the `ctx.secrets` reader from the worker `env`. `get(name)` resolves
191
- * `env[name].get()` — the `secrets_store_secrets[]` binding of that name. An
192
- * absent or non-Secrets-Store binding throws a directed error pointing at the
193
- * wrangler config; the lookup is lazy, so an unused secret never resolves.
194
- */
302
+ * Build the `ctx.secrets` reader from the worker `env`. `get(name)` resolves
303
+ * `env[name].get()` — the `secrets_store_secrets[]` binding of that name. An
304
+ * absent or non-Secrets-Store binding throws a directed error pointing at the
305
+ * wrangler config; the lookup is lazy, so an unused secret never resolves.
306
+ */
195
307
  declare const createSecrets: (env: Record<string, unknown>) => Secrets;
196
308
  /**
197
- * Redact secrets from a free-form message. Masks, in order: any quoted value
198
- * whose contents look like a credential (so a value surfaced as `received string
199
- * "sk_live_…"` is masked even though the surrounding text is not a token); a
200
- * `scheme://user:password@host` URL credential (the password segment); any
201
- * known-prefix credential token wherever it appears, at any length; any value
202
- * following a secret-named key in `KEY=value` / `KEY: value` form; and any
203
- * remaining bare high-entropy ≥24-char token run anywhere in the message.
204
- *
205
- * This is BEST-EFFORT defense-in-depth, NOT a guarantee: a short, prefix-less
206
- * secret under a non-secret-named key (and embedded credentials in shapes not
207
- * enumerated here) can still slip through. Treat it as a backstop — prefer
208
- * structured logging that never serializes raw env/secret fields in the first
209
- * place over relying on post-hoc scrubbing of untrusted data.
210
- *
211
- * Exported because it is independently useful — call it before logging anything
212
- * derived from `env`, request bodies, or thrown errors.
213
- */
309
+ * Redact secrets from a free-form message. Masks, in order: any quoted value
310
+ * whose contents look like a credential (so a value surfaced as `received string
311
+ * "sk_live_…"` is masked even though the surrounding text is not a token); a
312
+ * `scheme://user:password@host` URL credential (the password segment); any
313
+ * known-prefix credential token wherever it appears, at any length; any value
314
+ * following a secret-named key in `KEY=value` / `KEY: value` form; and any
315
+ * remaining bare high-entropy ≥24-char token run anywhere in the message.
316
+ *
317
+ * This is BEST-EFFORT defense-in-depth, NOT a guarantee: a short, prefix-less
318
+ * secret under a non-secret-named key (and embedded credentials in shapes not
319
+ * enumerated here) can still slip through. Treat it as a backstop — prefer
320
+ * structured logging that never serializes raw env/secret fields in the first
321
+ * place over relying on post-hoc scrubbing of untrusted data.
322
+ *
323
+ * Exported because it is independently useful — call it before logging anything
324
+ * derived from `env`, request bodies, or thrown errors.
325
+ */
214
326
  declare const redactSecrets: (message: string) => string;
215
327
  /** One key's validation failure, secrets already redacted out of `message`. */
216
328
  interface EnvKeyFailure {
@@ -220,32 +332,31 @@ interface EnvKeyFailure {
220
332
  message: string;
221
333
  }
222
334
  /**
223
- * Thrown when one or more env keys are missing or fail validation. Carries the
224
- * structured list of `failures` (each with the offending `key`) so callers can
225
- * react programmatically; `message` is the joined, secret-redacted summary.
226
- *
227
- * Named export only (no default) per the repo export convention.
228
- */
229
- declare class LunoraEnvError extends Error {
230
- override readonly name = "LunoraEnvError";
335
+ * Thrown when one or more env keys are missing or fail validation. Carries the
336
+ * structured list of `failures` (each with the offending `key`) so callers can
337
+ * react programmatically; `message` is the joined, secret-redacted summary.
338
+ *
339
+ * Named export only (no default) per the repo export convention.
340
+ */
341
+ declare class LunoraEnvError extends LunoraError$1 {
231
342
  readonly failures: ReadonlyArray<EnvKeyFailure>;
232
343
  constructor(failures: ReadonlyArray<EnvKeyFailure>);
233
344
  }
234
345
  /** A record of `v.*` validators describing the expected env shape. */
235
346
  type EnvShape = Record<string, Validator>;
236
347
  /**
237
- * The typed output of {@link defineEnv}. Optional validators (`v.optional(...)`)
238
- * become optional keys; everything else is required. Mirrors how `InferArgs`
239
- * derives an args object from a validator map.
240
- */
241
- type InferEnv<S extends EnvShape> = { [K in keyof S as undefined extends Infer<S[K]> ? K : never]?: Infer<S[K]> } & { [K in keyof S as undefined extends Infer<S[K]> ? never : K]: Infer<S[K]> };
242
- /**
243
- * The accessor returned by {@link defineEnv}. A typed view over an `env` object
244
- * plus a `.parse(env)` escape hatch that validates every key eagerly.
245
- *
246
- * Call the accessor with the worker's `env` to get the typed, lazily-validated
247
- * proxy: `const config = defineEnv({ … }); const { PORT } = config(env);`.
248
- */
348
+ * The typed output of {@link defineEnv}. Optional validators (`v.optional(...)`)
349
+ * become optional keys; everything else is required. Mirrors how `InferArgs`
350
+ * derives an args object from a validator map.
351
+ */
352
+ type InferEnv<S extends EnvShape> = { [K in keyof S as undefined extends Infer<S[K]> ? K : never]?: Infer<S[K]>; } & { [K in keyof S as undefined extends Infer<S[K]> ? never : K]: Infer<S[K]>; };
353
+ /**
354
+ * The accessor returned by {@link defineEnv}. A typed view over an `env` object
355
+ * plus a `.parse(env)` escape hatch that validates every key eagerly.
356
+ *
357
+ * Call the accessor with the worker's `env` to get the typed, lazily-validated
358
+ * proxy: `const config = defineEnv({ … }); const { PORT } = config(env);`.
359
+ */
249
360
  interface EnvAccessor<S extends EnvShape> {
250
361
  /** Validate every key eagerly and return the typed, plain (non-proxy) object. Use for fail-fast-at-boot. */
251
362
  parse: (env: unknown) => InferEnv<S>;
@@ -253,91 +364,40 @@ interface EnvAccessor<S extends EnvShape> {
253
364
  (env: unknown): InferEnv<S>;
254
365
  }
255
366
  /**
256
- * Define a typed, validated accessor over a Worker's `env`. Pass a record of
257
- * `v.*` validators; receive an accessor that validates lazily per key (cached
258
- * per `env` identity) and infers its output type from the validators.
259
- *
260
- * ```ts
261
- * import { defineEnv, v } from "@lunora/server";
262
- *
263
- * const config = defineEnv({
264
- * STRIPE_KEY: v.string(),
265
- * PORT: v.optional(v.number()),
266
- * });
267
- *
268
- * export default {
269
- * fetch(request, env) {
270
- * const { STRIPE_KEY, PORT } = config(env); // STRIPE_KEY: string, PORT?: number
271
- * // …
272
- * },
273
- * };
274
- * ```
275
- *
276
- * Throws {@link LunoraEnvError} (secrets redacted) when a key is missing or
277
- * invalid — lazily on first access of that key, or eagerly via `config.parse(env)`.
278
- */
367
+ * Define a typed, validated accessor over a Worker's `env`. Pass a record of
368
+ * `v.*` validators; receive an accessor that validates lazily per key (cached
369
+ * per `env` identity) and infers its output type from the validators.
370
+ *
371
+ * ```ts
372
+ * import { defineEnv, v } from "@lunora/server";
373
+ *
374
+ * const config = defineEnv({
375
+ * STRIPE_KEY: v.string(),
376
+ * PORT: v.optional(v.number()),
377
+ * });
378
+ *
379
+ * export default {
380
+ * fetch(request, env) {
381
+ * const { STRIPE_KEY, PORT } = config(env); // STRIPE_KEY: string, PORT?: number
382
+ * // …
383
+ * },
384
+ * };
385
+ * ```
386
+ *
387
+ * Throws {@link LunoraEnvError} (secrets redacted) when a key is missing or
388
+ * invalid — lazily on first access of that key, or eagerly via `config.parse(env)`.
389
+ */
279
390
  declare const defineEnv: <S extends EnvShape>(shape: S) => EnvAccessor<S>;
391
+ declare class LunoraError extends LunoraError$1 {
392
+ constructor(code: LunoraErrorCode, message?: string, data?: unknown);
393
+ }
280
394
  /**
281
- * Canonical error type for Lunora procedures and middleware.
282
- *
283
- * The runtime's structural error mapper keys off `name === "LunoraError"` plus
284
- * the numeric `status`, so throwing one of these from a handler or middleware
285
- * yields the right RPC/HTTP status without any further wiring. `code` carries
286
- * the machine-readable reason for clients.
287
- */
288
- declare const CODE_STATUS: {
289
- readonly BAD_REQUEST: 400;
290
- readonly CONFLICT: 409;
291
- /**
292
- * `count()` invoked against a table whose context carries an active RLS
293
- * policy. The operation itself is unsupported in an RLS-restricted reader
294
- * (kitcn's documented constraint) — the request is well-formed and the
295
- * caller is authorized, so this is a 422 (semantic conflict) rather than a
296
- * 403 (policy denial).
297
- */
298
- readonly COUNT_RLS_UNSUPPORTED: 422;
299
- readonly FORBIDDEN: 403;
300
- readonly INTERNAL_SERVER_ERROR: 500;
301
- /**
302
- * An analytical reduction (`aggregate` / `groupBy`) was invoked over a
303
- * column that the procedure's `mask()` middleware redacts. A masked column
304
- * can't be summed, averaged, or grouped without leaking the very values the
305
- * mask hides (a group key *is* the raw value; an aggregate is computed from
306
- * it), so the operation fails closed. The request is well-formed and the
307
- * caller is authorized — this is a 422 (semantic conflict), mirroring
308
- * `COUNT_RLS_UNSUPPORTED`.
309
- */
310
- readonly MASK_UNSUPPORTED: 422;
311
- readonly NOT_FOUND: 404;
312
- readonly NOT_IMPLEMENTED: 501;
313
- /**
314
- * A write policy's `when` returned a relation-crossing predicate
315
- * (`some`/`none`/`every`/`is`/`isNot`). The in-memory write-policy evaluator
316
- * has no child fetcher and cannot resolve a relation node, so the policy is
317
- * unsupported as written. Relation predicates are valid in *read* policies
318
- * and query `where` clauses (the pre-resolver handles them there). The
319
- * request is well-formed; this is a 422 (semantic conflict), mirroring the
320
- * sibling `*_UNSUPPORTED` codes.
321
- */
322
- readonly RELATION_PREDICATE_UNSUPPORTED: 422;
323
- readonly TOO_MANY_REQUESTS: 429;
324
- readonly UNAUTHORIZED: 401;
325
- readonly UNPROCESSABLE: 422;
326
- };
327
- type LunoraErrorCode = keyof typeof CODE_STATUS;
328
- declare class LunoraError extends Error {
329
- override readonly name = "LunoraError";
330
- readonly code: LunoraErrorCode;
331
- readonly status: number;
332
- constructor(code: LunoraErrorCode, message?: string);
333
- }
334
- /**
335
- * Minimal structural writer the facade binds over. Declared with **method**
336
- * syntax (not arrow properties) so a more-specifically-typed writer — both
337
- * `@lunora/do`'s `DatabaseWriterLike` and the RLS middleware's wrapped writer —
338
- * stays assignable under bivariant parameter checking. That is the whole reason
339
- * the shared helper can serve both callers, hence the rule exemption.
340
- */
395
+ * Minimal structural writer the facade binds over. Declared with **method**
396
+ * syntax (not arrow properties) so a more-specifically-typed writer — both
397
+ * `@lunora/do`'s `DatabaseWriterLike` and the RLS middleware's wrapped writer
398
+ * stays assignable under bivariant parameter checking. That is the whole reason
399
+ * the shared helper can serve both callers, hence the rule exemption.
400
+ */
341
401
  interface FacadeWriterLike {
342
402
  aggregate(tableName: string, options: unknown): Promise<unknown>;
343
403
  count(tableName: string, where?: unknown): Promise<number>;
@@ -349,6 +409,11 @@ interface FacadeWriterLike {
349
409
  }, expectedTable?: string): Promise<{
350
410
  deleted: number;
351
411
  }>;
412
+ deleteWhere?(tableName: string, where: Record<string, unknown>, options?: {
413
+ limit?: number;
414
+ }): Promise<{
415
+ deleted: number;
416
+ }>;
352
417
  findFirst(tableName: string, args?: unknown): Promise<unknown>;
353
418
  findFirstOrThrow(tableName: string, args?: unknown): Promise<unknown>;
354
419
  findMany(tableName: string, args?: unknown): Promise<unknown>;
@@ -357,15 +422,27 @@ interface FacadeWriterLike {
357
422
  insert(tableName: string, document: Record<string, unknown>): Promise<string>;
358
423
  insertMany?(tableName: string, documents: ReadonlyArray<Record<string, unknown>>, options?: {
359
424
  limit?: number;
360
- }): Promise<string[]>;
425
+ skipDuplicates?: boolean;
426
+ }): Promise<(string | null)[]>;
361
427
  patch(id: string, patch: Record<string, unknown>, expectedTable?: string): Promise<void>;
362
428
  patchMany?(patches: ReadonlyArray<{
363
429
  id: string;
364
430
  patch: Record<string, unknown>;
365
431
  }>, options?: {
366
432
  limit?: number;
367
- }, expectedTable?: string): Promise<void>;
433
+ }, expectedTable?: string): Promise<{
434
+ patched: number;
435
+ }>;
436
+ patchWhere?(tableName: string, args: {
437
+ patch: Record<string, unknown>;
438
+ where: Record<string, unknown>;
439
+ }, options?: {
440
+ limit?: number;
441
+ }): Promise<{
442
+ patched: number;
443
+ }>;
368
444
  query(tableName: string): {
445
+ withGeoIndex(indexName: string, build: (q: unknown) => unknown): unknown;
369
446
  withSearchIndex(indexName: string, search: (q: unknown) => unknown): unknown;
370
447
  };
371
448
  rank(tableName: string, indexName: string, options: unknown): Promise<unknown>;
@@ -378,11 +455,19 @@ interface FacadeEntry {
378
455
  aggregate: (options: unknown) => Promise<unknown>;
379
456
  count: (where?: unknown) => Promise<number>;
380
457
  delete: (id: string) => Promise<void>;
381
- deleteMany: (ids: ReadonlyArray<string>, options?: {
382
- limit?: number;
383
- }) => Promise<{
384
- deleted: number;
385
- }>;
458
+ deleteMany: {
459
+ (ids: ReadonlyArray<string>, options?: {
460
+ limit?: number;
461
+ }): Promise<{
462
+ deleted: number;
463
+ }>;
464
+ (args: {
465
+ limit?: number;
466
+ where: Record<string, unknown>;
467
+ }): Promise<{
468
+ deleted: number;
469
+ }>;
470
+ };
386
471
  /** `true` when at least one row matches `where` (or any row exists when omitted). Honors RLS like `findFirst`. */
387
472
  exists: (where?: unknown) => Promise<boolean>;
388
473
  findFirst: (args?: unknown) => Promise<unknown>;
@@ -393,16 +478,34 @@ interface FacadeEntry {
393
478
  /** Physically remove a row (and physically cascade), bypassing `.softDelete()`. */
394
479
  hardDelete: (id: string) => Promise<void>;
395
480
  insert: (document: Record<string, unknown>, options?: FacadeInsertOptions) => Promise<null | string>;
481
+ /**
482
+ * Insert many documents into this table in one call. With
483
+ * `{ skipDuplicates: true }`, UNIQUE breaches resolve to `null` for that row
484
+ * instead of failing the batch. The typed facade narrows the return to
485
+ * `Id&lt;T>[]` when skipDuplicates is not requested.
486
+ */
396
487
  insertMany: (documents: ReadonlyArray<Record<string, unknown>>, options?: {
397
488
  limit?: number;
398
- }) => Promise<string[]>;
489
+ skipDuplicates?: boolean;
490
+ }) => Promise<(string | null)[]>;
399
491
  patch: (id: string, patch: Record<string, unknown>) => Promise<void>;
400
- patchMany: (patches: ReadonlyArray<{
401
- id: string;
402
- values: Record<string, unknown>;
403
- }>, options?: {
404
- limit?: number;
405
- }) => Promise<void>;
492
+ patchMany: {
493
+ (patches: ReadonlyArray<{
494
+ id: string;
495
+ values: Record<string, unknown>;
496
+ }>, options?: {
497
+ limit?: number;
498
+ }): Promise<{
499
+ patched: number;
500
+ }>;
501
+ (args: {
502
+ limit?: number;
503
+ values: Record<string, unknown>;
504
+ where: Record<string, unknown>;
505
+ }): Promise<{
506
+ patched: number;
507
+ }>;
508
+ };
406
509
  rank: (indexName: string, options: unknown) => Promise<unknown>;
407
510
  rankPage: (indexName: string, options?: unknown) => Promise<unknown>;
408
511
  replace: (id: string, document: Record<string, unknown>) => Promise<void>;
@@ -412,15 +515,16 @@ interface FacadeEntry {
412
515
  upsert: (args: UpsertArgs) => Promise<UpsertResult>;
413
516
  /** Sequential `upsert` over many rows sharing one `target`; returns one result per input row in order. */
414
517
  upsertMany: (args: UpsertManyArgs) => Promise<UpsertResult[]>;
518
+ withGeoIndex: (indexName: string, build: (q: unknown) => unknown) => unknown;
415
519
  withSearchIndex: (indexName: string, search: (q: unknown) => unknown) => unknown;
416
520
  }
417
521
  /** Options accepted by the per-table `insert` accessor. */
418
522
  interface FacadeInsertOptions {
419
523
  /**
420
- * When `true`, a UNIQUE-constraint breach is swallowed: the insert becomes a
421
- * silent no-op and resolves to `null` instead of throwing a `CONFLICT`. Any
422
- * other error still propagates. Mirrors better-drizzle's `create({ skipDuplicates })`.
423
- */
524
+ * When `true`, a UNIQUE-constraint breach is swallowed: the insert becomes a
525
+ * silent no-op and resolves to `null` instead of throwing a `CONFLICT`. Any
526
+ * other error still propagates. Mirrors better-drizzle's `create({ skipDuplicates })`.
527
+ */
424
528
  skipDuplicates?: boolean;
425
529
  }
426
530
  /** The conflict target for `upsert`/`upsertMany`: one field name or a tuple of them. */
@@ -448,17 +552,17 @@ interface UpsertManyArgs {
448
552
  target: UpsertTarget;
449
553
  }
450
554
  /**
451
- * Bind a structural writer to one table, producing its `ctx.db` table accessor.
452
- *
453
- * The by-id accessors (`get`/`delete`/`patch`/`replace`) forward the bound
454
- * `tableName` as `expectedTable` so the underlying writer scopes its id lookup
455
- * to this table. Without it, a branded `Id&lt;"posts">` carrying another table's
456
- * id would resolve cross-table (the writer probes every table by id), letting
457
- * `ctx.db.posts.get(foreignId)` read — or `.delete`/`.patch`/`.replace`
458
- * mutate — a row in an unrelated table (IDOR). Writers that ignore the second
459
- * argument keep their previous global behaviour; the scoping is opt-in via this
460
- * forwarded name.
461
- */
555
+ * Bind a structural writer to one table, producing its `ctx.db` table accessor.
556
+ *
557
+ * The by-id accessors (`get`/`delete`/`patch`/`replace`) forward the bound
558
+ * `tableName` as `expectedTable` so the underlying writer scopes its id lookup
559
+ * to this table. Without it, a branded `Id&lt;"posts">` carrying another table's
560
+ * id would resolve cross-table (the writer probes every table by id), letting
561
+ * `ctx.db.posts.get(foreignId)` read — or `.delete`/`.patch`/`.replace`
562
+ * mutate — a row in an unrelated table (IDOR). Writers that ignore the second
563
+ * argument keep their previous global behaviour; the scoping is opt-in via this
564
+ * forwarded name.
565
+ */
462
566
  declare const bindTableFacade: (writer: FacadeWriterLike, tableName: string) => FacadeEntry;
463
567
  /** The kitcn-style `ctx.orm` namespace over a per-table facade map. */
464
568
  interface OrmLike {
@@ -479,21 +583,40 @@ declare const bindOrm: (facade: Record<string, FacadeEntry>) => OrmLike;
479
583
  /** HTTP verbs the typed {@link httpRoute} builder can bind to. */
480
584
  type HttpMethod = "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT";
481
585
  /**
482
- * Context handed to an HTTP action handler. A narrower view of {@link ActionContext}:
483
- * HTTP actions run in the worker (the "action runtime"), separate from the
484
- * transactional store, so there is no direct `db` / `vectors` / `scheduler` /
485
- * `storage` surface — reach the data layer through `runQuery` / `runMutation` /
486
- * `runAction`, which forward to the owning shard.
487
- */
488
- type HttpActionCtx = Pick<ActionCtx, "auth" | "fetch" | "runAction" | "runMutation" | "runQuery">;
586
+ * Context handed to an HTTP action handler. A narrower view of {@link ActionContext}:
587
+ * HTTP actions run in the worker (the "action runtime"), separate from the
588
+ * transactional store, so there is no direct `db` / `vectors` surface reach the
589
+ * data layer through `runQuery` / `runMutation` / `runAction`, which forward to
590
+ * the owning shard. `db`'s absence is principled: an HTTP handler is not
591
+ * transactional.
592
+ *
593
+ * `scheduler` and `storage` ARE present, because neither needs the shard — the
594
+ * scheduler talks to the scheduler DO, and R2 is a worker binding an HTTP
595
+ * handler can reach where an action does. Both are optional: each exists only
596
+ * when the app declared the matching capability (`.scheduler(...)` /
597
+ * `.storage(...)`) on the generated app builder.
598
+ *
599
+ * Omitting them was costly out of proportion to the gap. Without `scheduler`,
600
+ * "receive webhook → enqueue the real work → return 200" — the shape HTTP
601
+ * actions exist for — forced a hop through a mutation plus a closed allow-list
602
+ * of target strings, because a function reference cannot cross the RPC boundary
603
+ * and a free-form target on an unauthenticated endpoint is a "call any internal
604
+ * function" primitive. Without `storage`, any helper the ctx was threaded into
605
+ * had to be typed for its storage-touching branch, so a handler was barred from
606
+ * the helper even on the branches that never went near storage.
607
+ */
608
+ type HttpActionCtx = Pick<ActionCtx, "auth" | "cache" | "fetch" | "runAction" | "runMutation" | "runQuery"> & {
609
+ readonly scheduler?: ActionCtx["scheduler"];
610
+ readonly storage?: ActionCtx["storage"];
611
+ };
489
612
  /** A raw handler wrapped by {@link httpAction}. Receives the raw request, returns the raw response. */
490
613
  type HttpActionHandler = (context: HttpActionCtx, request: Request) => Promise<Response> | Response;
491
614
  /**
492
- * The hono {@link https://hono.dev | Hono} environment used by {@link httpRouter}.
493
- * The runtime injects the per-request {@link HttpActionCtx} on the private
494
- * `__lunoraCtx` binding; the router's lifting middleware promotes it to
495
- * `c.var.lunora` so handlers can read it as a typed variable.
496
- */
615
+ * The hono {@link https://hono.dev | Hono} environment used by {@link httpRouter}.
616
+ * The runtime injects the per-request {@link HttpActionCtx} on the private
617
+ * `__lunoraCtx` binding; the router's lifting middleware promotes it to
618
+ * `c.var.lunora` so handlers can read it as a typed variable.
619
+ */
497
620
  interface LunoraHttpEnv {
498
621
  Bindings: Record<string, unknown> & {
499
622
  __lunoraCtx?: HttpActionCtx;
@@ -507,31 +630,31 @@ type LunoraHttpApp = Hono<LunoraHttpEnv>;
507
630
  /** A compiled route handler: a hono handler that resolves to a raw {@link Response}. */
508
631
  type LunoraRouteHandler = (c: Context<LunoraHttpEnv>) => Promise<Response>;
509
632
  /**
510
- * Wrap a `(ctx, request) => Response` handler as a hono handler. The raw escape
511
- * hatch — mount it with `app.all(path, httpAction(fn))`. `ctx` is the
512
- * runtime-injected {@link HttpActionCtx} lifted into `c.var.lunora` by
513
- * {@link httpRouter}; `request` is the underlying `c.req.raw`.
514
- */
633
+ * Wrap a `(ctx, request) => Response` handler as a hono handler. The raw escape
634
+ * hatch — mount it with `app.all(path, httpAction(fn))`. `ctx` is the
635
+ * runtime-injected {@link HttpActionCtx} lifted into `c.var.lunora` by
636
+ * {@link httpRouter}; `request` is the underlying `c.req.raw`.
637
+ */
515
638
  declare const httpAction: (handler: HttpActionHandler) => LunoraRouteHandler;
516
639
  /**
517
- * Create the hono app for HTTP actions. Pre-wired with a middleware that lifts
518
- * the runtime-injected `c.env.__lunoraCtx` into `c.var.lunora`, so both
519
- * {@link httpAction} and the typed {@link httpRoute} builder can read the action
520
- * context. The full hono surface is available — plugins, path params, `.route`:
521
- *
522
- * ```ts
523
- * const app = httpRouter();
524
- * app.use("*", cors());
525
- * app.post("/webhook", httpAction(onWebhook));
526
- * app.get("/users/:id", getUser);
527
- * export default createWorker({ httpRouter: app, ... });
528
- * ```
529
- *
530
- * The lifting middleware throws if the context is absent. `createWorker` injects
531
- * it on every request the router sees, so this only trips when the app is run
532
- * outside the runtime — a misconfiguration we surface loudly rather than let
533
- * `c.var.lunora` be silently `undefined` despite its non-optional type.
534
- */
640
+ * Create the hono app for HTTP actions. Pre-wired with a middleware that lifts
641
+ * the runtime-injected `c.env.__lunoraCtx` into `c.var.lunora`, so both
642
+ * {@link httpAction} and the typed {@link httpRoute} builder can read the action
643
+ * context. The full hono surface is available — plugins, path params, `.route`:
644
+ *
645
+ * ```ts
646
+ * const app = httpRouter();
647
+ * app.use("*", cors());
648
+ * app.post("/webhook", httpAction(onWebhook));
649
+ * app.get("/users/:id", getUser);
650
+ * export default createWorker({ httpRouter: app, ... });
651
+ * ```
652
+ *
653
+ * The lifting middleware throws if the context is absent. `createWorker` injects
654
+ * it on every request the router sees, so this only trips when the app is run
655
+ * outside the runtime — a misconfiguration we surface loudly rather than let
656
+ * `c.var.lunora` be silently `undefined` despite its non-optional type.
657
+ */
535
658
  declare const httpRouter: () => LunoraHttpApp;
536
659
  /** The `{ ctx, searchParams, body, params }` a typed route handler receives. */
537
660
  interface HttpRouteHandlerOptions<SearchParams extends ArgsValidator, Body extends ArgsValidator, Params extends ArgsValidator> {
@@ -541,11 +664,12 @@ interface HttpRouteHandlerOptions<SearchParams extends ArgsValidator, Body exten
541
664
  searchParams: InferArgs<SearchParams>;
542
665
  }
543
666
  /**
544
- * The `{ ctx, searchParams, params, request, signal }` a streaming HTTP
545
- * handler receives. There is no parsed `body` — streams are typically GET, and
546
- * the raw `request` is exposed if a handler needs to read the body itself.
547
- * `signal` is tripped when the client disconnects.
548
- */
667
+ * The `{ ctx, searchParams, params, request, signal }` a streaming HTTP
668
+ * handler receives. There is no parsed `body` — streams are typically GET, and
669
+ * the raw `request` is exposed if a handler needs to read the body itself.
670
+ * `signal` is tripped when the client disconnects.
671
+ * @experimental Part of the HTTP-SSE stream surface; reconnect/POST-body design questions are still open.
672
+ */
549
673
  interface HttpStreamHandlerOptions<SearchParams extends ArgsValidator, Params extends ArgsValidator> {
550
674
  ctx: HttpActionCtx;
551
675
  params: InferArgs<Params>;
@@ -554,35 +678,51 @@ interface HttpStreamHandlerOptions<SearchParams extends ArgsValidator, Params ex
554
678
  signal: AbortSignal;
555
679
  }
556
680
  /**
557
- * A typed REST route under construction. `.searchParams()` / `.body()` /
558
- * `.params()` accumulate validator maps (later calls merge, a colliding key
559
- * wins) that decode the URL query, JSON body, and hono path params into the
560
- * handler's typed `searchParams` / `body` / `params`. Like the procedure
561
- * builder, `.output(validator)` defaults to the `undefined` sentinel — while
562
- * unset the handler is generic over its own return; once set the handler must
563
- * return that type and the result is parsed through the validator before
564
- * serialization. `[Output] extends [undefined]` is tuple-wrapped so a union
565
- * `Output` doesn't distribute and the test is for the exact sentinel.
566
- *
567
- * The terminal `.handler()` yields a {@link LunoraRouteHandler} — mount it
568
- * directly with `app.get(path, route)`.
569
- */
681
+ * A typed REST route under construction. `.searchParams()` / `.body()` /
682
+ * `.params()` accumulate validator maps (later calls merge, a colliding key
683
+ * wins) that decode the URL query, JSON body, and hono path params into the
684
+ * handler's typed `searchParams` / `body` / `params`. Like the procedure
685
+ * builder, `.output(validator)` defaults to the `undefined` sentinel — while
686
+ * unset the handler is generic over its own return; once set the handler must
687
+ * return that type and the result is parsed through the validator before
688
+ * serialization. `[Output] extends [undefined]` is tuple-wrapped so a union
689
+ * `Output` doesn't distribute and the test is for the exact sentinel.
690
+ *
691
+ * The terminal `.handler()` yields a {@link LunoraRouteHandler} — mount it
692
+ * directly with `app.get(path, route)`.
693
+ */
570
694
  interface HttpRouteBuilder<SearchParams extends ArgsValidator, Body extends ArgsValidator, Params extends ArgsValidator, Output = undefined> {
571
695
  body: <B extends ArgsValidator>(validators: B) => HttpRouteBuilder<SearchParams, B & Body, Params, Output>;
696
+ /**
697
+ * Attach a `Cache-Control` header to the response. Only meaningful when
698
+ * Workers Cache is enabled in `wrangler.jsonc` (`"cache": { "enabled": true }`).
699
+ */
700
+ cacheControl: (value: string) => HttpRouteBuilder<SearchParams, Body, Params, Output>;
701
+ /**
702
+ * Attach a `Cache-Tag` header to the response for tag-based purging via
703
+ * `ctx.cache.purge({ tags: [...] })`.
704
+ */
705
+ cacheTag: (value: string) => HttpRouteBuilder<SearchParams, Body, Params, Output>;
572
706
  handler: [Output] extends [undefined] ? <R>(handler: (options: HttpRouteHandlerOptions<SearchParams, Body, Params>) => Promise<R> | R) => LunoraRouteHandler : (handler: (options: HttpRouteHandlerOptions<SearchParams, Body, Params>) => Output | Promise<Output>) => LunoraRouteHandler;
573
707
  output: <V extends Validator>(validator: V) => HttpRouteBuilder<SearchParams, Body, Params, Infer<V>>;
574
708
  params: <P extends ArgsValidator>(validators: P) => HttpRouteBuilder<SearchParams, Body, P & Params, Output>;
575
709
  searchParams: <S extends ArgsValidator>(validators: S) => HttpRouteBuilder<S & SearchParams, Body, Params, Output>;
576
710
  /**
577
- * Terminal: declare this route as a streaming Server-Sent Events endpoint.
578
- * The handler is an async generator (or any function returning an
579
- * `AsyncIterable&lt;R>`) that yields one chunk per SSE `data:` frame; on
580
- * iterator completion the route writes a final `event: complete` frame; on
581
- * throw, an `event: error` frame is written with `{code, message}` before
582
- * the stream closes. The chunks are JSON-encoded; `R` is inferred from the
583
- * handler's yielded type.
584
- */
711
+ * Terminal: declare this route as a streaming Server-Sent Events endpoint.
712
+ * The handler is an async generator (or any function returning an
713
+ * `AsyncIterable&lt;R>`) that yields one chunk per SSE `data:` frame; on
714
+ * iterator completion the route writes a final `event: complete` frame; on
715
+ * throw, an `event: error` frame is written with `{code, message}` before
716
+ * the stream closes. The chunks are JSON-encoded; `R` is inferred from the
717
+ * handler's yielded type.
718
+ * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
719
+ */
585
720
  stream: <R>(handler: (options: HttpStreamHandlerOptions<SearchParams, Params>) => AsyncGenerator<R, void, void> | AsyncIterable<R>) => LunoraRouteHandler;
721
+ /**
722
+ * Attach a `Vary` header to the response so Cloudflare stores separate
723
+ * cached variants per distinct value of the listed request headers.
724
+ */
725
+ vary: (value: string) => HttpRouteBuilder<SearchParams, Body, Params, Output>;
586
726
  }
587
727
  /** Opens a fresh {@link HttpRouteBuilder}. The `path` documents intent; hono owns the actual routing at mount. */
588
728
  type HttpRouteFactory = (path: string) => HttpRouteBuilder<EmptyArgs, EmptyArgs, EmptyArgs>;
@@ -597,33 +737,33 @@ interface HttpRoute {
597
737
  put: HttpRouteFactory;
598
738
  }
599
739
  /**
600
- * Typed REST route builder. Compiles down to a {@link LunoraRouteHandler}, so a
601
- * typed route and a hand-written {@link httpAction} are interchangeable when
602
- * mounted on {@link httpRouter}:
603
- *
604
- * ```ts
605
- * export const listTodos = httpRoute
606
- * .get("/api/todos")
607
- * .searchParams({ limit: v.number(), q: v.optional(v.string()) })
608
- * .output(v.array(v.object({ id: v.string(), text: v.string() })))
609
- * .handler(async ({ ctx, searchParams }) => ctx.runQuery(api.todos.list, searchParams));
610
- *
611
- * export const getTodo = httpRoute
612
- * .get("/api/todos/:id")
613
- * .params({ id: v.string() })
614
- * .handler(async ({ ctx, params }) => ctx.runQuery(api.todos.get, params));
615
- *
616
- * const app = httpRouter();
617
- * app.get("/api/todos", listTodos);
618
- * app.get("/api/todos/:id", getTodo);
619
- * ```
620
- */
740
+ * Typed REST route builder. Compiles down to a {@link LunoraRouteHandler}, so a
741
+ * typed route and a hand-written {@link httpAction} are interchangeable when
742
+ * mounted on {@link httpRouter}:
743
+ *
744
+ * ```ts
745
+ * export const listTodos = httpRoute
746
+ * .get("/api/todos")
747
+ * .searchParams({ limit: v.number(), q: v.optional(v.string()) })
748
+ * .output(v.array(v.object({ id: v.string(), text: v.string() })))
749
+ * .handler(async ({ ctx, searchParams }) => ctx.runQuery(api.todos.list, searchParams));
750
+ *
751
+ * export const getTodo = httpRoute
752
+ * .get("/api/todos/:id")
753
+ * .params({ id: v.string() })
754
+ * .handler(async ({ ctx, params }) => ctx.runQuery(api.todos.get, params));
755
+ *
756
+ * const app = httpRouter();
757
+ * app.get("/api/todos", listTodos);
758
+ * app.get("/api/todos/:id", getTodo);
759
+ * ```
760
+ */
621
761
  declare const httpRoute: HttpRoute;
622
762
  /**
623
- * Structural view of an R2 object body, as returned by `@lunora/storage`'s
624
- * `download()`. Re-declared here (not imported) so `@lunora/server` takes no
625
- * runtime dependency on `@lunora/storage`; the real binding satisfies the shape.
626
- */
763
+ * Structural view of an R2 object body, as returned by `@lunora/storage`'s
764
+ * `download()`. Re-declared here (not imported) so `@lunora/server` takes no
765
+ * runtime dependency on `@lunora/storage`; the real binding satisfies the shape.
766
+ */
627
767
  interface StorageObjectBody {
628
768
  /** The object body stream (`null` for a zero-byte object). */
629
769
  body: ReadableStream | null;
@@ -654,325 +794,302 @@ interface ContextWithStorage {
654
794
  storage: StorageDownloader;
655
795
  }
656
796
  /**
657
- * Stream a stored object as an HTTP {@link Response} from an `httpAction`
658
- * handler, with correct `Content-Type`, `ETag`, and `Accept-Ranges: bytes`.
659
- * Honors a single-range `Range` request **206 Partial Content** with
660
- * `Content-Range` + `Content-Length`; otherwise **200**. A missing object is a
661
- * **404**; an out-of-bounds range is a **416** with a `Content-Range` of
662
- * `bytes` star-slash-size.
663
- *
664
- * A range request re-issues the `download()` with the resolved `{ offset, length }`
665
- * window so R2 streams only those bytes back to the Worker — the slice is never
666
- * buffered in the isolate. The first `download()` is used only for the object's
667
- * size + metadata (its body is left unread and cancelled). For very large
668
- * objects a signed URL (`ctx.storage.getSignedUrl`) is still cheaper since the
669
- * client then ranges against R2/CDN directly with no Worker hop.
670
- */
797
+ * True when `value` is safe to use as an HTTP header field-value: no CR, LF, or
798
+ * NUL. Guards against response-header injection / `Headers`-construction throws
799
+ * when reflecting attacker-influenced object metadata (e.g. a stored
800
+ * `Content-Type`). Exported (see the `export {}` at the file end) so an `httpAction`
801
+ * handler can guard a request-derived header value before writing it the fix the
802
+ * `http_action_response_header_injection` advisor lint points to.
803
+ */
804
+ declare const isSafeHeaderValue: (value: string) => boolean;
805
+ /**
806
+ * Stream a stored object as an HTTP {@link Response} from an `httpAction`
807
+ * handler, with correct `Content-Type`, `ETag`, and `Accept-Ranges: bytes`.
808
+ * Honors a single-range `Range` request **206 Partial Content** with
809
+ * `Content-Range` + `Content-Length`; otherwise **200**. A missing object is a
810
+ * **404**; an out-of-bounds range is a **416** with a `Content-Range` of
811
+ * `bytes` star-slash-size.
812
+ *
813
+ * A range request re-issues the `download()` with the resolved `{ offset, length }`
814
+ * window so R2 streams only those bytes back to the Worker — the slice is never
815
+ * buffered in the isolate. The first `download()` is used only for the object's
816
+ * size + metadata (its body is left unread and cancelled). For very large
817
+ * objects a signed URL (`ctx.storage.getSignedUrl`) is still cheaper since the
818
+ * client then ranges against R2/CDN directly with no Worker hop.
819
+ */
671
820
  declare const serveStorageObject: (context: ContextWithStorage, key: string, request: Request) => Promise<Response>;
821
+ /**
822
+ * What the worker does with a resolver's identity when it fails contract
823
+ * validation (a forged / malformed claim set arriving from an untrusted token).
824
+ * `"anonymous"` (default, safe) treats the request as anonymous, so the bad
825
+ * identity never reaches a policy as a valid identity (`ctx.auth.userId`
826
+ * becomes `undefined`). `"reject"` fails the request closed (a `401`) — use
827
+ * when a malformed credential should be a hard error, not a silent downgrade.
828
+ */
829
+ type IdentityRejectMode = "anonymous" | "reject";
830
+ /** Options for {@link defineIdentity}. */
831
+ interface DefineIdentityOptions {
832
+ /**
833
+ * How to handle a resolver identity that violates the contract at the trust
834
+ * boundary. Defaults to `"anonymous"` (a forged claim set is downgraded to
835
+ * anonymous rather than flowing in as an unchecked cast).
836
+ */
837
+ readonly onInvalid?: IdentityRejectMode;
838
+ }
839
+ /** Result of validating a candidate identity against the contract. */
840
+ type IdentityValidation = {
841
+ ok: true;
842
+ } | {
843
+ error: string;
844
+ ok: false;
845
+ };
846
+ /**
847
+ * A declared identity claim contract. Carries the codegen discovery brand, the
848
+ * declared claim validators, the reject policy, and a runtime `validate`. The
849
+ * `TClaims` type parameter is the inferred claim shape (always extending
850
+ * `{ userId: string }`); it is phantom (no runtime field) and exists so
851
+ * `@lunora/codegen` and {@link InferIdentity} can recover the type.
852
+ */
853
+ interface IdentityContract<TClaims extends {
854
+ userId: string;
855
+ } = {
856
+ userId: string;
857
+ }> {
858
+ /**
859
+ * Phantom carrier for the inferred claim type. Never populated at runtime
860
+ * (`undefined`); present only so the type flows to codegen / {@link InferIdentity}.
861
+ */
862
+ readonly __claimType?: TClaims;
863
+ readonly __lunoraIdentity: true;
864
+ /** The declared claim validators (a `@lunora/values` validator map). */
865
+ readonly claims: ValidatorMap;
866
+ /** Reject policy applied at the trust boundary. See {@link IdentityRejectMode}. */
867
+ readonly onInvalid: IdentityRejectMode;
868
+ /**
869
+ * Validate a resolver's returned identity against the declared claims. On
870
+ * success the caller keeps the original identity untouched (so undeclared
871
+ * claims are forwarded verbatim, preserving today's behaviour); on failure
872
+ * the worker applies the `onInvalid` policy.
873
+ */
874
+ validate: (identity: Record<string, unknown>) => IdentityValidation;
875
+ }
876
+ /** Recover the declared claim type from a {@link defineIdentity} contract. */
877
+ type InferIdentity<T> = T extends IdentityContract<infer TClaims> ? TClaims : never;
878
+ /**
879
+ * Declare the identity claim contract. `claims` is a `@lunora/values` validator
880
+ * map whose inferred type must extend `{ userId: string }` — if it does not
881
+ * (e.g. `userId` is missing or not a required string), the argument type
882
+ * collapses to `never` and the call fails to typecheck.
883
+ * @example
884
+ * export const identity = defineIdentity({ userId: v.string(), tenantId: v.optional(v.string()), scopes: v.optional(v.array(v.string())) });
885
+ */
886
+ declare const defineIdentity: <A extends ValidatorMap>(claims: InferValidatorMap<A> extends {
887
+ userId: string;
888
+ } ? A : never, options?: DefineIdentityOptions) => IdentityContract<InferValidatorMap<A> & {
889
+ userId: string;
890
+ }>;
672
891
  /** Handler for a connection-lifecycle hook. */
673
892
  type LifecycleHandler = (context: MutationCtx, event: LifecycleEvent) => Promise<void> | void;
674
893
  /** Register a hook that fires once when a client's WebSocket connects. */
675
894
  declare const onConnect: (handler: LifecycleHandler) => RegisteredLifecycleHook;
676
895
  /** Register a hook that fires once when a client's WebSocket disconnects. */
677
896
  declare const onDisconnect: (handler: LifecycleHandler) => RegisteredLifecycleHook;
678
- /**
679
- * Context handed to a {@link MaskFn} (and to {@link MaskOptions.bypass}). The
680
- * `auth` shape mirrors RLS's `PolicyContext.auth` one-for-one same identity
681
- * resolver, same `can(...)` permission check — so an author can branch a mask
682
- * on the caller's role/permission. `row` is the full pre-mask row the column
683
- * belongs to; `column` is the column currently being masked. Both are absent
684
- * when the context is used for the procedure-wide `bypass` check (no specific
685
- * cell is in play yet).
686
- */
687
- interface MaskContext<Context = unknown> {
688
- readonly auth: {
689
- /** `true` when any of the request's `roles` grants `permission` (see {@link MaskOptions.roles}). Fails closed for unregistered roles. */
690
- readonly can: (permission: Permission | string) => boolean;
691
- readonly identity?: Record<string, unknown> | null;
692
- readonly roles: ReadonlyArray<string>;
693
- readonly userId: null | string;
694
- };
695
- /** The column currently being masked. Present only inside a per-cell {@link MaskFn}. */
696
- readonly column?: string;
697
- readonly ctx: Context;
698
- /** The full pre-mask row the masked cell belongs to. Present only inside a per-cell {@link MaskFn}. */
699
- readonly row?: Record<string, unknown>;
700
- }
701
- /**
702
- * A custom masking function. Receives the raw cell value and the
703
- * {@link MaskContext}, returns the value to surface. Use it for partial masks
704
- * (`maskMiddle(phone)`), role-aware reveals (`ctx.auth.can(...) ? value : null`),
705
- * or format-preserving tokens. A function that **throws** fails closed — the
706
- * cell is redacted to `null`, never leaked raw.
707
- */
708
- type MaskFn<Context = unknown> = (value: unknown, context: MaskContext<Context>) => unknown;
709
- /**
710
- * How a column is masked:
711
- *
712
- * - `"redact"` — drop the value to `null`. The simplest, safest strategy, and
713
- * the right choice for any value that must actually be kept secret.
714
- * - `"hash"` — replace with a stable token (unsalted 32-bit FNV-1a hex) so the
715
- * same input always yields the same token (joinable/groupable client-side).
716
- * **This is NOT a confidentiality control.** It is a non-cryptographic,
717
- * unsalted, deterministic, narrow (~2^32) digest: low-entropy values (emails,
718
- * phone numbers, SSNs) are brute-force-recoverable by the very caller you are
719
- * masking from, and identical values always produce identical tokens across
720
- * rows/columns/tenants (enabling correlation). Use `"hash"` ONLY when you want a
721
- * stable pseudonym for grouping/joining and leaking the value is acceptable —
722
- * never to hide sensitive PII. For PII that must stay hidden, use `"redact"`.
723
- * - a {@link MaskFn} — author-defined transform (partial mask, role-aware reveal).
724
- */
725
- type MaskStrategy<Context = unknown> = "hash" | "redact" | MaskFn<Context>;
726
- /** Per-column strategy map for one table: `{ email: "redact", phone: maskMiddle }`. */
727
- type MaskColumns<Context = unknown> = Record<string, MaskStrategy<Context>>;
728
- /**
729
- * The mask declaration passed to `mask(...)`: a table → column → strategy map.
730
- * Deliberately a plain object literal so the codegen feeder can statically read
731
- * which columns a procedure masks (powering the `mask_uncovered_pii_column`
732
- * advisor lint), exactly as the RLS feeder reads policy tables.
733
- */
734
- type MaskPolicies<Context = unknown> = Record<string, MaskColumns<Context>>;
735
- /**
736
- * Options for `mask(policies, options)`.
737
- *
738
- * - `roles` registers the role→permission grants that back `ctx.auth.can(...)`
739
- * inside a {@link MaskFn} — identical to `rls(policies, { roles })`. A role
740
- * not listed grants no permissions (fails closed for unknown roles).
741
- * - `bypass` is a procedure-wide escape hatch: when it returns `true` the whole
742
- * mask is skipped (the caller sees raw values). Use it for a privileged
743
- * viewer — `bypass: ({ auth }) => auth.can("pii:view")`. Prefer this over
744
- * branching every column when an entire class of caller should see clear data.
745
- */
746
- interface MaskOptions<Context = unknown> {
747
- readonly bypass?: (context: MaskContext<Context>) => boolean;
748
- readonly roles?: ReadonlyArray<Role>;
749
- }
750
- interface QueryPage$1 {
751
- continueCursor: null | string;
752
- isDone: boolean;
753
- page: Record<string, unknown>[];
754
- }
755
- interface QueryArgs$1 {
756
- baseWhere?: unknown;
757
- cursor?: null | string;
897
+ /** Default `limit` when the caller doesn't ask for one. */
898
+ declare const DEFAULT_LIMIT = 25;
899
+ /** Default ceiling on `limit`, so one request can't ask for an unbounded page. */
900
+ declare const DEFAULT_MAX_LIMIT = 100;
901
+ /**
902
+ * Per-field predicate accepted for a declared filter column. An alias of the
903
+ * `ctx.db` `where` DSL's own operator type rather than a copy, so the two cannot
904
+ * drift as operators are added.
905
+ */
906
+ type ListFilterOperators<T> = WhereOperators<T>;
907
+ /**
908
+ * The filter allow-list a caller may declare: a subset of the document's own
909
+ * columns, each with a validator for that column's type. Constraining the KEYS to
910
+ * `keyof Doc` is what turns a typo'd or renamed column into a compile error
911
+ * instead of a predicate that silently never matches.
912
+ */
913
+ type ListFilterShape<TDocument> = { [K in keyof TDocument & string]?: Validator<TDocument[K]>; };
914
+ /** The `where` argument: each declared filter column, optionally, as a bare value or an operator object. */
915
+ type ListWhere<F> = { [K in keyof F]?: Infer<NonNullable<F[K]>> | ListFilterOperators<Infer<NonNullable<F[K]>>>; };
916
+ /** One `orderBy` entry. `direction` defaults to `"asc"`. */
917
+ interface ListOrderByEntry<O extends string> {
918
+ direction?: "asc" | "desc";
919
+ field: O;
920
+ }
921
+ /** The decoded arguments a {@link defineListArgs} endpoint receives. */
922
+ interface ListArgsValue<F, O extends string> {
923
+ cursor?: null | number | string;
758
924
  limit?: number;
759
- where?: unknown;
760
- with?: Record<string, unknown>;
761
- }
762
- interface AggregateArgs$1 {
763
- field?: string;
764
- op: string;
765
- }
766
- interface GroupByArgs$1 {
767
- agg?: {
768
- field?: string;
769
- op: string;
770
- };
771
- by: ReadonlyArray<string>;
925
+ orderBy?: ListOrderByEntry<O>[];
926
+ where?: ListWhere<F>;
772
927
  }
773
- interface TableReaderLike$1 {
774
- collect: () => Promise<Record<string, unknown>[]>;
775
- filter: (predicate: (document: Record<string, unknown>) => boolean) => TableReaderLike$1;
776
- first: () => Promise<Record<string, unknown> | null>;
777
- order: (direction: "asc" | "desc") => TableReaderLike$1;
778
- paginate: (options: {
779
- cursor?: null | string;
780
- numItems: number;
781
- }) => Promise<QueryPage$1>;
782
- take: (limit: number) => Promise<Record<string, unknown>[]>;
783
- unique: () => Promise<Record<string, unknown> | null>;
784
- withIndex: (indexName: string, range?: (q: unknown) => unknown) => TableReaderLike$1;
785
- withSearchIndex: (indexName: string, search: (q: unknown) => unknown) => TableReaderLike$1;
786
- }
787
- /**
788
- * Structural projection of the runtime ORM writer — the same subset
789
- * `../rls/middleware` mirrors, so the wrapper is interchangeable between
790
- * `@lunora/do`'s and `@lunora/d1`'s `DatabaseWriterLike` without an
791
- * inter-package dependency. `rankBefore` is optional (the D1 twin omits it).
792
- */
793
- interface MaskDatabase {
794
- aggregate: (tableName: string, options: AggregateArgs$1) => Promise<null | number>;
795
- count: (tableName: string, whereOrArgs?: unknown) => Promise<number>;
796
- delete: (id: string, expectedTable?: string) => Promise<void>;
797
- deleteMany: (ids: ReadonlyArray<string>, options?: {
798
- limit?: number;
799
- }) => Promise<{
800
- deleted: number;
801
- }>;
802
- findFirst: (tableName: string, args?: QueryArgs$1) => Promise<Record<string, unknown> | null>;
803
- findFirstOrThrow: (tableName: string, args?: QueryArgs$1) => Promise<Record<string, unknown>>;
804
- findMany: (tableName: string, args?: QueryArgs$1) => Promise<QueryPage$1>;
805
- get: (id: string, expectedTable?: string) => Promise<Record<string, unknown> | null>;
806
- groupBy: (tableName: string, options: GroupByArgs$1) => Promise<ReadonlyArray<{
807
- key: Record<string, unknown>;
808
- value: null | number;
809
- }>>;
810
- insert: (tableName: string, document: Record<string, unknown>) => Promise<string>;
811
- insertMany: (tableName: string, documents: ReadonlyArray<Record<string, unknown>>, options?: {
812
- limit?: number;
813
- }) => Promise<string[]>;
814
- lookupById?: (id: string, expectedTable?: string) => Promise<null | {
815
- row: Record<string, unknown>;
816
- tableName: string;
817
- }>;
818
- patch: (id: string, patch: Record<string, unknown>, expectedTable?: string) => Promise<void>;
819
- patchMany: (patches: ReadonlyArray<{
820
- id: string;
821
- patch: Record<string, unknown>;
822
- }>, options?: {
823
- limit?: number;
824
- }) => Promise<void>;
825
- query: (tableName: string) => TableReaderLike$1;
826
- rank: (tableName: string, indexName: string, options: unknown) => Promise<null | {
827
- position: number;
828
- total: number;
829
- }>;
830
- rankBefore?: (tableName: string, indexName: string, options: unknown) => Promise<{
831
- before: number;
832
- total: number;
833
- }>;
834
- rankPage: (tableName: string, indexName: string, options?: unknown) => Promise<QueryPage$1>;
835
- replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
928
+ interface DefineListArgsConfig<F, O extends string> {
929
+ /** `limit` applied when the caller omits one. Defaults to 25. */
930
+ readonly defaultLimit?: number;
931
+ /**
932
+ * Allow-list of filterable columns. Publish only columns an index can serve;
933
+ * anything absent here is unreachable from the client.
934
+ */
935
+ readonly filter: F;
936
+ /** Ceiling on `in` / `notIn` array length — one bound parameter each. Defaults to 100. */
937
+ readonly maxInValues?: number;
938
+ /** Ceiling on `limit`; a larger request is clamped down, not rejected. Defaults to 100. */
939
+ readonly maxLimit?: number;
940
+ /** Ceiling on how many `orderBy` entries a request may ask for. Defaults to 8. */
941
+ readonly maxOrderBy?: number;
942
+ /** Allow-list of sortable columns. Pass `[]` to fix the order server-side. */
943
+ readonly orderBy: ReadonlyArray<O>;
944
+ }
945
+ /** The validator map handed to `.input()`. Typed precisely so `args` infers end-to-end. */
946
+ interface ListArgsValidators<F, O extends string> {
947
+ cursor: ColumnValidator<null | number | string | undefined, null | number | string | undefined>;
948
+ limit: ColumnValidator<number | undefined, number | undefined>;
949
+ orderBy: ColumnValidator<ListOrderByEntry<O>[] | undefined, ListOrderByEntry<O>[] | undefined>;
950
+ where: ColumnValidator<ListWhere<F> | undefined, ListWhere<F> | undefined>;
951
+ }
952
+ interface ListArgsSpec<TDocument, F, O extends string> {
953
+ /** Spread into `.input(...)` — `{ cursor, limit, orderBy, where }`. */
954
+ readonly args: ListArgsValidators<F, O>;
955
+ /**
956
+ * Translate the decoded arguments into the `findMany` options object:
957
+ * `limit` clamped into `[1, maxLimit]`, `orderBy` reshaped from
958
+ * `{ field, direction }[]` into `ctx.db`'s `{ column: direction }[]`.
959
+ *
960
+ * Returns `QueryArgs&lt;Doc>` bound to the table, not free — so a mismatch
961
+ * between what this helper declares and what the table actually holds is a
962
+ * compile error at the `findMany` call site.
963
+ */
964
+ readonly toQueryArgs: (args: ListArgsValue<F, O>) => QueryArgs$2<TDocument>;
965
+ }
966
+ /** Clamp a caller-supplied `limit` into `[1, maxLimit]`; a non-finite value falls back to `fallback`. */
967
+ declare const clampLimit: (limit: number | undefined, fallback: number, maxLimit: number) => number;
968
+ /**
969
+ * Declare the filter / sort / page arguments for a list endpoint, plus the
970
+ * translation into `ctx.db.&lt;table>.findMany(...)` options. See the module docs
971
+ * for the shape and the reasoning behind it.
972
+ *
973
+ * Curried on the document type: `defineListArgs&lt;Doc&lt;"messages">>()({ })`. The
974
+ * extra `()` buys the thing that matters — with `Doc` bound, `filter` keys and
975
+ * `orderBy` entries are checked against the table's real columns, so a typo or a
976
+ * column renamed out from under the endpoint is a COMPILE error instead of a
977
+ * predicate that silently matches nothing. TypeScript has no partial type-argument
978
+ * inference, so binding `Doc` explicitly while still inferring `F` and `O` from
979
+ * the config requires the second call.
980
+ */
981
+ declare const defineListArgs: <TDocument>() => <F extends ListFilterShape<TDocument>, O extends keyof TDocument & string>(config: DefineListArgsConfig<F, O>) => ListArgsSpec<TDocument, F, O>;
982
+ /**
983
+ * Structural mirrors of `@lunora/shard-engine`'s rank-page-row shapes
984
+ * (`RankPageRowKey` / `RankPageRow` / `ShardRankPageResult`) — the return type
985
+ * of the writer's `rankPageRows` seam, the cross-shard companion to
986
+ * `rankPage`.
987
+ *
988
+ * Shared by `../rls/middleware` and `../mask/middleware`: both wrap
989
+ * `rankPageRows` structurally (no `@lunora/shard-engine` import, mirroring how
990
+ * every other method on their `DatabaseWriterLike`/`MaskDatabase` projections
991
+ * is hand-mirrored rather than imported) and both need the exact same result
992
+ * shape to type their overrides. A single copy here means the two wrappers
993
+ * can't drift out of lockstep with each other — see AGENTS.md's platform
994
+ * parity note on `ShardSqlExec` and the canonical binding `*Like` projections
995
+ * shipping wrong for exactly this reason (two hand-maintained mirrors of one
996
+ * upstream type).
997
+ */
998
+ /** Structural mirror of `@lunora/shard-engine`'s `RankPageRowKey`. */
999
+ interface RankPageRowKeyLike {
1000
+ partitionKey: string;
1001
+ rowId: string;
1002
+ sortValues: ReadonlyArray<unknown>;
836
1003
  }
837
- /** Roles list source on the context. Tolerant of older auth states (mirrors RLS's `AuthLike`). */
838
- type AuthLike$1 = {
839
- getIdentity?: () => Promise<Record<string, unknown> | null>;
840
- roles?: ReadonlyArray<string>;
841
- userId?: null | string;
842
- };
843
- interface MaskContextIn {
844
- auth?: AuthLike$1;
845
- db: MaskDatabase;
1004
+ /** Structural mirror of `@lunora/shard-engine`'s `RankPageRow`. */
1005
+ interface RankPageRowLike {
1006
+ doc: Record<string, unknown>;
1007
+ key: RankPageRowKeyLike;
846
1008
  }
847
- /**
848
- * Procedure-builder middleware. Apply per-request via `.use(mask(policies))`.
849
- * Closes over the policy map at builder-construction time; resolves identity +
850
- * the `bypass` decision per call against the live ctx.
851
- *
852
- * IMPORTANT: a mask is in scope only for procedures whose builder chain
853
- * includes this middleware — opt-in, never global (the same invariant as RLS).
854
- */
855
- declare const mask: <Context extends MaskContextIn = MaskContextIn>(policies: MaskPolicies<Context>, options?: MaskOptions<Context>) => Middleware<Context, Context>;
856
- /**
857
- * Online data-migration authoring API.
858
- *
859
- * `defineMigration` declares a per-document backfill over one table: `up`
860
- * transforms every existing row, `down` (optional) reverses it. Unlike the D1
861
- * SQL schema migrations in `@lunora/d1`, these run *inside each shard's*
862
- * Durable Object against live documents, in keyset batches, and are resumable —
863
- * the per-shard runner in `@lunora/do` tracks progress in a reserved
864
- * `__lunora_migrations` table so an interrupted run picks up where it stopped.
865
- *
866
- * The returned object carries a `__lunoraMigration` brand so codegen can
867
- * discover declarations through the type checker (mirroring the procedure
868
- * builder's `__lunoraProcedure` brand) and emit them into a `LUNORA_MIGRATIONS`
869
- * registry the DO and CLI look migrations up by id.
870
- */
871
- /** A document handed to a migration transform: the stored row including `_id`/`_creationTime`. */
872
- type MigrationDocument = Record<string, unknown>;
873
- /**
874
- * Transform applied to one document. Return a new document to rewrite the row,
875
- * or `undefined` to leave it untouched (skipped, not counted as changed). The
876
- * runner always preserves the original `_id` and `_creationTime`, so the
877
- * returned document neither needs to nor should change row identity.
878
- */
879
- type MigrationTransform = (document: MigrationDocument) => MigrationDocument | undefined | void;
880
- interface MigrationDefinition {
881
- /** Rows fetched and rewritten per batch. Defaults to the runner's batch size when omitted. */
882
- readonly batchSize?: number;
883
- /** Optional reverse transform, applied by `migrate down`. */
884
- readonly down?: MigrationTransform;
885
- /** Stable, unique identifier — the key per-shard run-state is tracked under. */
886
- readonly id: string;
887
- /** Table whose documents this migration iterates. */
888
- readonly table: string;
889
- /** Forward transform, applied to every row by `migrate up`. */
890
- readonly up: MigrationTransform;
891
- }
892
- /** A {@link MigrationDefinition} plus the codegen discovery marker. */
893
- interface RegisteredMigration extends MigrationDefinition {
894
- readonly __lunoraMigration: true;
1009
+ /** Structural mirror of `@lunora/shard-engine`'s `ShardRankPageResult` — the `rankPageRows` return shape. */
1010
+ interface ShardRankPageResultLike {
1011
+ directions: ReadonlyArray<"asc" | "desc">;
1012
+ hasMore: boolean;
1013
+ rows: ReadonlyArray<RankPageRowLike>;
895
1014
  }
896
- /** Declare an online data migration. See the module docs for runtime semantics. */
897
- declare const defineMigration: (definition: MigrationDefinition) => RegisteredMigration;
898
1015
  /**
899
- * The prefixed tables a single plugin `P` contributes, or an empty map when it
900
- * ships no schema extension. Mirrors {@link PrefixedTables} at the plugin level
901
- * so {@link InstalledTables} can fold a tuple of plugins.
902
- */
1016
+ * The prefixed tables a single plugin `P` contributes, or an empty map when it
1017
+ * ships no schema extension. Mirrors {@link PrefixedTables} at the plugin level
1018
+ * so {@link InstalledTables} can fold a tuple of plugins.
1019
+ */
903
1020
  type ExtensionTablesOf<P> = P extends {
904
1021
  readonly extension: SchemaExtension<infer X> & {
905
1022
  readonly key: infer K;
906
1023
  };
907
1024
  } ? K extends string ? PrefixedTables<X, K> : Record<never, never> : Record<never, never>;
908
1025
  /**
909
- * Fold a tuple of plugins onto a base table map `T`, accumulating each plugin's
910
- * auto-prefixed extension tables left-to-right — the type-level mirror of
911
- * {@link installPlugins} applying `mergeSchemaExtension` for each plugin in turn.
912
- */
1026
+ * Fold a tuple of plugins onto a base table map `T`, accumulating each plugin's
1027
+ * auto-prefixed extension tables left-to-right — the type-level mirror of
1028
+ * {@link installPlugins} applying `mergeSchemaExtension` for each plugin in turn.
1029
+ */
913
1030
  type InstalledTables<T extends Record<string, TableDefinition>, Plugins extends ReadonlyArray<unknown>> = Plugins extends readonly [infer Head, ...infer Rest] ? InstalledTables<ExtensionTablesOf<Head> & T, Rest> : T;
914
1031
  /**
915
- * Union every plugin's `ContextOut` in a tuple — the type-level mirror of the
916
- * `ctx.api.&lt;key>` additions {@link composePluginMiddleware} accumulates as each
917
- * plugin middleware runs. Independent of the incoming context, which the builder
918
- * infers at the `.use(...)` site.
919
- */
1032
+ * Union every plugin's `ContextOut` in a tuple — the type-level mirror of the
1033
+ * `ctx.api.&lt;key>` additions {@link composePluginMiddleware} accumulates as each
1034
+ * plugin middleware runs. Independent of the incoming context, which the builder
1035
+ * infers at the `.use(...)` site.
1036
+ */
920
1037
  type ComposedOut<Plugins extends ReadonlyArray<unknown>> = Plugins extends readonly [infer Head, ...infer Rest] ? ComposedOut<Rest> & (Head extends Plugin<any, any, infer Out> ? Out : unknown) : unknown;
921
1038
  /**
922
- * Schema fragment a plugin contributes. Same shape as the `tables` map
923
- * passed to `defineSchema`. Optional `vectorIndexes` mirror the top-level
924
- * `defineSchema` argument so a plugin can ship vector decls alongside its
925
- * tables.
926
- */
1039
+ * Schema fragment a plugin contributes. Same shape as the `tables` map
1040
+ * passed to `defineSchema`. Optional `vectorIndexes` mirror the top-level
1041
+ * `defineSchema` argument so a plugin can ship vector decls alongside its
1042
+ * tables.
1043
+ */
927
1044
  interface SchemaExtension<T extends Record<string, TableDefinition> = Record<string, TableDefinition>> {
928
1045
  /** Stable key identifying the plugin that owns this extension. */
929
1046
  readonly key: string;
930
1047
  /**
931
- * Extension tables, keyed by **bare** name (e.g. `buckets`). At merge time
932
- * each is auto-prefixed with `key` (`ratelimit_buckets`) so it can't
933
- * collide with an app table; do **not** namespace manually.
934
- */
1048
+ * Extension tables, keyed by **bare** name (e.g. `buckets`). At merge time
1049
+ * each is auto-prefixed with `key` (`ratelimit_buckets`) so it can't
1050
+ * collide with an app table; do **not** namespace manually.
1051
+ */
935
1052
  readonly tables: T;
936
1053
  /**
937
- * Optional standalone vector indexes the plugin ships, keyed by index
938
- * name. Merged into the host schema's `vectorIndexes`; a key collision
939
- * with the base schema is a hard error (same policy as tables).
940
- */
1054
+ * Optional standalone vector indexes the plugin ships, keyed by index
1055
+ * name. Merged into the host schema's `vectorIndexes`; a key collision
1056
+ * with the base schema is a hard error (same policy as tables).
1057
+ */
941
1058
  readonly vectorIndexes?: Record<string, VectorIndexDefinition>;
942
1059
  }
943
1060
  /**
944
- * Build a {@link SchemaExtension}. The `key` is a runtime tag (used for
945
- * error messages on collision) and a type-level brand.
946
- */
1061
+ * Build a {@link SchemaExtension}. The `key` is a runtime tag (used for
1062
+ * error messages on collision) and a type-level brand.
1063
+ */
947
1064
  declare const defineSchemaExtension: <T extends Record<string, TableDefinition>>(key: string, options: {
948
1065
  tables: T;
949
1066
  vectorIndexes?: Record<string, VectorIndexDefinition>;
950
1067
  }) => SchemaExtension<T>;
951
1068
  /**
952
- * A plugin packages an optional schema extension and optional middleware.
953
- * Both are independently usable: an app can install only the schema (e.g.
954
- * for plugins that ship background workers but no per-request behavior)
955
- * or only the middleware (plugins that augment ctx without persistent
956
- * state).
957
- */
1069
+ * A plugin packages an optional schema extension and optional middleware.
1070
+ * Both are independently usable: an app can install only the schema (e.g.
1071
+ * for plugins that ship background workers but no per-request behavior)
1072
+ * or only the middleware (plugins that augment ctx without persistent
1073
+ * state).
1074
+ */
958
1075
  interface Plugin<TExtension extends Record<string, TableDefinition> = Record<string, TableDefinition>, TContextIn = unknown, TContextOut = TContextIn> {
959
1076
  /**
960
- * Optional schema extension. Apps install via
961
- * `defineSchema(...).extend(plugin.extension)`.
962
- */
1077
+ * Optional schema extension. Apps install via
1078
+ * `defineSchema(...).extend(plugin.extension)`.
1079
+ */
963
1080
  readonly extension?: SchemaExtension<TExtension>;
964
1081
  /** Stable key identifying the plugin. Matches `extension.key` when set. */
965
1082
  readonly key: string;
966
1083
  /**
967
- * Optional middleware. Users attach with `c.query.use(plugin.middleware)`.
968
- * The middleware can extend `ctx`; convention is to attach helpers under
969
- * `ctx.api.&lt;key>`, e.g.
970
- *
971
- * ```ts
972
- * middleware: ({ ctx, next }) =>
973
- * next({ ctx: { api: { ...ctx.api, ratelimit: api } } })
974
- * ```
975
- */
1084
+ * Optional middleware. Users attach with `c.query.use(plugin.middleware)`.
1085
+ * The middleware can extend `ctx`; convention is to attach helpers under
1086
+ * `ctx.api.&lt;key>`, e.g.
1087
+ *
1088
+ * ```ts
1089
+ * middleware: ({ ctx, next }) =>
1090
+ * next({ ctx: { api: { ...ctx.api, ratelimit: api } } })
1091
+ * ```
1092
+ */
976
1093
  readonly middleware?: Middleware<TContextIn, TContextOut>;
977
1094
  }
978
1095
  /** Options to {@link definePlugin}. */
@@ -981,35 +1098,51 @@ interface DefinePluginOptions<TExtension extends Record<string, TableDefinition>
981
1098
  middleware?: Middleware<TContextIn, TContextOut>;
982
1099
  }
983
1100
  /**
984
- * Package a schema extension + middleware as a reusable plugin. Either
985
- * field is optional `definePlugin("foo", {})` is valid but degenerate.
986
- */
987
- declare const definePlugin: <TExtension extends Record<string, TableDefinition>, TContextIn = unknown, TContextOut = TContextIn>(key: string, options: DefinePluginOptions<TExtension, TContextIn, TContextOut>) => Plugin<TExtension, TContextIn, TContextOut>;
988
- /**
989
- * Bundle of registered functions a {@link Component} ships. Keys are the
990
- * function's local name (e.g. `check`, `reset`); the registered function
991
- * value carries its own kind / args / handler.
992
- *
993
- * Users re-export from their own lunora module so codegen picks them up:
994
- *
995
- * ```ts
996
- * // lunora/ratelimit.ts
997
- * import { ratelimit } from "@vendor/ratelimit-component";
998
- * export const { check, reset } = ratelimit.functions;
999
- * // Emits as `ratelimit:check` / `ratelimit:reset` in the generated `api`.
1000
- * ```
1001
- *
1002
- * Codegen follows the re-export back to the bundled `query/mutation/action`
1003
- * call (property access or destructuring both work), so the functions land in
1004
- * the generated `api` under the re-exporting file's namespace.
1005
- */
1101
+ * Call signatures for {@link definePlugin}. When `extension` is supplied the
1102
+ * returned plugin's `extension` is typed as PRESENT (not `?`), so the
1103
+ * canonical install pattern `defineSchema(...).extend(plugin.extension)`
1104
+ * typechecks without a non-null assertion the shape every scaffold template
1105
+ * ships. The bare-options signature keeps `extension` optional for plugins
1106
+ * that carry only middleware.
1107
+ */
1108
+ interface DefinePluginFunction {
1109
+ <TExtension extends Record<string, TableDefinition>, TContextIn = unknown, TContextOut = TContextIn>(key: string, options: DefinePluginOptions<TExtension, TContextIn, TContextOut> & {
1110
+ extension: SchemaExtension<TExtension>;
1111
+ }): Plugin<TExtension, TContextIn, TContextOut> & {
1112
+ readonly extension: SchemaExtension<TExtension>;
1113
+ };
1114
+ <TExtension extends Record<string, TableDefinition>, TContextIn = unknown, TContextOut = TContextIn>(key: string, options: DefinePluginOptions<TExtension, TContextIn, TContextOut>): Plugin<TExtension, TContextIn, TContextOut>;
1115
+ }
1116
+ /**
1117
+ * Package a schema extension + middleware as a reusable plugin. Either
1118
+ * field is optional — `definePlugin("foo", {})` is valid but degenerate.
1119
+ */
1120
+ declare const definePlugin: DefinePluginFunction;
1121
+ /**
1122
+ * Bundle of registered functions a {@link Component} ships. Keys are the
1123
+ * function's local name (e.g. `check`, `reset`); the registered function
1124
+ * value carries its own kind / args / handler.
1125
+ *
1126
+ * Users re-export from their own lunora module so codegen picks them up:
1127
+ *
1128
+ * ```ts
1129
+ * // lunora/ratelimit.ts
1130
+ * import { ratelimit } from "@vendor/ratelimit-component";
1131
+ * export const { check, reset } = ratelimit.functions;
1132
+ * // Emits as `ratelimit:check` / `ratelimit:reset` in the generated `api`.
1133
+ * ```
1134
+ *
1135
+ * Codegen follows the re-export back to the bundled `query/mutation/action`
1136
+ * call (property access or destructuring both work), so the functions land in
1137
+ * the generated `api` under the re-exporting file's namespace.
1138
+ */
1006
1139
  type ComponentFunctions = Readonly<Record<string, RegisteredFunction<any, any, FunctionKind>>>;
1007
1140
  /**
1008
- * Component = {@link Plugin} with a bundle of registered functions. The
1009
- * extension + middleware + functions are independent: a component can ship
1010
- * functions without a schema (e.g. a stateless utility), or a schema
1011
- * without functions (e.g. shared table definitions), and any combination.
1012
- */
1141
+ * Component = {@link Plugin} with a bundle of registered functions. The
1142
+ * extension + middleware + functions are independent: a component can ship
1143
+ * functions without a schema (e.g. a stateless utility), or a schema
1144
+ * without functions (e.g. shared table definitions), and any combination.
1145
+ */
1013
1146
  interface Component<TExtension extends Record<string, TableDefinition> = Record<string, TableDefinition>, TContextIn = unknown, TContextOut = TContextIn, F extends ComponentFunctions = ComponentFunctions> extends Plugin<TExtension, TContextIn, TContextOut> {
1014
1147
  readonly functions: F;
1015
1148
  }
@@ -1018,81 +1151,91 @@ interface DefineComponentOptions<TExtension extends Record<string, TableDefiniti
1018
1151
  functions?: F;
1019
1152
  }
1020
1153
  /**
1021
- * Convenience wrapper around {@link definePlugin} that also bundles a set
1022
- * of registered functions. The resulting `component.functions` object is a
1023
- * record of `name → registered query/mutation/action`; consumers
1024
- * re-export entries so codegen discovers them as user functions:
1025
- *
1026
- * ```ts
1027
- * export const ratelimit = defineComponent("ratelimit", {
1028
- * // Bare `buckets` merges in as `ratelimit_buckets`.
1029
- * extension: defineSchemaExtension("ratelimit", { tables: { buckets } }),
1030
- * middleware: ({ ctx, next }) => next({ ctx: { ...ctx, ratelimit: api(ctx) } }),
1031
- * functions: {
1032
- * check: query.input({ key: v.string() }).query(async ({ ctx, args }) => ...),
1033
- * reset: mutation.input({ key: v.string() }).mutation(async ({ ctx, args }) => ...),
1034
- * },
1035
- * });
1036
- * ```
1037
- *
1038
- * Re-exporting an entry (by property access or destructuring) is enough for
1039
- * codegen to discover it in the host app's namespace — the discovery resolver
1040
- * chases the re-export back to the bundled registration call.
1041
- */
1154
+ * Convenience wrapper around {@link definePlugin} that also bundles a set
1155
+ * of registered functions. The resulting `component.functions` object is a
1156
+ * record of `name → registered query/mutation/action`; consumers
1157
+ * re-export entries so codegen discovers them as user functions:
1158
+ *
1159
+ * ```ts
1160
+ * export const ratelimit = defineComponent("ratelimit", {
1161
+ * // Bare `buckets` merges in as `ratelimit_buckets`.
1162
+ * extension: defineSchemaExtension("ratelimit", { tables: { buckets } }),
1163
+ * middleware: ({ ctx, next }) => next({ ctx: { ...ctx, ratelimit: api(ctx) } }),
1164
+ * functions: {
1165
+ * check: query.input({ key: v.string() }).query(async ({ ctx, args }) => ...),
1166
+ * reset: mutation.input({ key: v.string() }).mutation(async ({ ctx, args }) => ...),
1167
+ * },
1168
+ * });
1169
+ * ```
1170
+ *
1171
+ * Re-exporting an entry (by property access or destructuring) is enough for
1172
+ * codegen to discover it in the host app's namespace — the discovery resolver
1173
+ * chases the re-export back to the bundled registration call.
1174
+ */
1042
1175
  declare const defineComponent: <TExtension extends Record<string, TableDefinition>, TContextIn = unknown, TContextOut = TContextIn, F extends ComponentFunctions = ComponentFunctions>(key: string, options: DefineComponentOptions<TExtension, TContextIn, TContextOut, F>) => Component<TExtension, TContextIn, TContextOut, F>;
1043
1176
  /**
1044
- * Map every key `K` of an extension's table map `X` to its auto-prefixed name
1045
- * `${Key}_${K}`. Mirrors the runtime prefixing in {@link mergeSchemaExtension}
1046
- * so the typed `.extend(...)` chain reflects the real merged table names.
1047
- */
1048
- type PrefixedTables<X extends Record<string, TableDefinition>, Key extends string> = { [K in keyof X as K extends string ? `${Key}_${K}` : K]: X[K] };
1049
- /**
1050
- * Merge a {@link SchemaExtension} into an existing schema. Returns a new
1051
- * schema object — never mutates the input.
1052
- *
1053
- * Extension tables are auto-namespaced: each bare table name is prefixed with
1054
- * the extension `key` (`buckets` → `ratelimit_buckets`), Convex-Components
1055
- * style, and every intra-extension reference (relation targets, aggregate /
1056
- * rank index `on`, standalone vector index `table`) is rewritten to match.
1057
- * References to base/app tables are left untouched.
1058
- *
1059
- * Because each extension lives in its own `key` namespace, app↔component
1060
- * collisions are impossible. The only remaining hard error is two extensions
1061
- * sharing the same `key` and producing the same prefixed table (or vector
1062
- * index) name — silent shadow would let one plugin hijack another's data.
1063
- */
1177
+ * Map every key `K` of an extension's table map `X` to its auto-prefixed name
1178
+ * `${Key}_${K}`. Mirrors the runtime prefixing in {@link mergeSchemaExtension}
1179
+ * so the typed `.extend(...)` chain reflects the real merged table names.
1180
+ */
1181
+ type PrefixedTables<X extends Record<string, TableDefinition>, Key extends string> = { [K in keyof X as K extends string ? `${Key}_${K}` : K]: X[K]; };
1182
+ /**
1183
+ * Merge a {@link SchemaExtension} into an existing schema. Returns a new
1184
+ * schema object — never mutates the input.
1185
+ *
1186
+ * Extension tables are auto-namespaced: each bare table name is prefixed with
1187
+ * the extension `key` (`buckets` → `ratelimit_buckets`), Convex-Components
1188
+ * style, and every intra-extension reference (relation targets, aggregate /
1189
+ * rank index `on`, standalone vector index `table`) is rewritten to match.
1190
+ * References to base/app tables are left untouched.
1191
+ *
1192
+ * Because each extension lives in its own `key` namespace, app↔component
1193
+ * collisions are impossible. The only remaining hard error is two extensions
1194
+ * sharing the same `key` and producing the same prefixed table (or vector
1195
+ * index) name — silent shadow would let one plugin hijack another's data.
1196
+ *
1197
+ * Re-runs {@link validateIndexFields} against the merged table set before
1198
+ * returning: `defineSchema` only validates the tables it was called with, so
1199
+ * without this an extension-contributed index with a typo'd/out-of-shape
1200
+ * field (or a duplicate name within one kind) would never be checked at all.
1201
+ * Re-validating the whole merged set (base + prefixed extension tables) is
1202
+ * cheap and idempotent for the base tables, which already passed this same
1203
+ * check when the base schema was built. Both callers of this function —
1204
+ * `withExtend.extend()` (`./schema`) and `installPlugins` (below) — get the
1205
+ * re-validation for free from this single call site (plan 258 §4/§9 Q3).
1206
+ */
1064
1207
  declare const mergeSchemaExtension: <T extends Record<string, TableDefinition>, X extends Record<string, TableDefinition>, Key extends string = string>(base: Schema<T>, extension: SchemaExtension<X> & {
1065
1208
  readonly key: Key;
1066
1209
  }) => Schema<PrefixedTables<X, Key> & T>;
1067
1210
  /**
1068
- * Install several plugins' schema extensions in one call — the one-shot
1069
- * counterpart to chaining `defineSchema(...).extend(a).extend(b)`. Plugins
1070
- * without an `extension` (middleware-only) are skipped; tables from those that
1071
- * do are auto-prefixed and reference-rewritten exactly as
1072
- * {@link mergeSchemaExtension} does for a single `.extend(...)`.
1073
- *
1074
- * ```ts
1075
- * const schema = installPlugins(defineSchema({ todos }), [ratelimit, audit]);
1076
- * // → todos + ratelimit_* + audit_*
1077
- * ```
1078
- *
1079
- * Pair it with {@link composePluginMiddleware} to attach every plugin's
1080
- * middleware in a single `.use(...)`, so installing N plugins is two calls
1081
- * rather than N `.extend(...)` + N `.use(...)`.
1082
- */
1211
+ * Install several plugins' schema extensions in one call — the one-shot
1212
+ * counterpart to chaining `defineSchema(...).extend(a).extend(b)`. Plugins
1213
+ * without an `extension` (middleware-only) are skipped; tables from those that
1214
+ * do are auto-prefixed and reference-rewritten exactly as
1215
+ * {@link mergeSchemaExtension} does for a single `.extend(...)`.
1216
+ *
1217
+ * ```ts
1218
+ * const schema = installPlugins(defineSchema({ todos }), [ratelimit, audit]);
1219
+ * // → todos + ratelimit_* + audit_*
1220
+ * ```
1221
+ *
1222
+ * Pair it with {@link composePluginMiddleware} to attach every plugin's
1223
+ * middleware in a single `.use(...)`, so installing N plugins is two calls
1224
+ * rather than N `.extend(...)` + N `.use(...)`.
1225
+ */
1083
1226
  declare const installPlugins: <T extends Record<string, TableDefinition>, const Plugins extends ReadonlyArray<Plugin<any, any, any>>>(base: Schema<T>, plugins: Plugins) => Schema<InstalledTables<T, Plugins>>;
1084
1227
  /**
1085
- * Compose every plugin's middleware into a single middleware you attach with one
1086
- * `.use(...)`. Plugins without middleware (schema-only) are skipped; the rest run
1087
- * in array order, each seeing the context the previous one widened, so the final
1088
- * `next({ ctx })` the builder receives carries every plugin's `ctx.api.&lt;key>`
1089
- * additions. Equivalent to `.use(a.middleware).use(b.middleware)…` but as one
1090
- * value, the middleware sibling of {@link installPlugins}.
1091
- *
1092
- * `ContextIn` is left free so the builder infers it from the context at the
1093
- * `.use(...)` site; the result type widens it by the union of the plugins'
1094
- * outputs.
1095
- */
1228
+ * Compose every plugin's middleware into a single middleware you attach with one
1229
+ * `.use(...)`. Plugins without middleware (schema-only) are skipped; the rest run
1230
+ * in array order, each seeing the context the previous one widened, so the final
1231
+ * `next({ ctx })` the builder receives carries every plugin's `ctx.api.&lt;key>`
1232
+ * additions. Equivalent to `.use(a.middleware).use(b.middleware)…` but as one
1233
+ * value, the middleware sibling of {@link installPlugins}.
1234
+ *
1235
+ * `ContextIn` is left free so the builder infers it from the context at the
1236
+ * `.use(...)` site; the result type widens it by the union of the plugins'
1237
+ * outputs.
1238
+ */
1096
1239
  declare const composePluginMiddleware: <ContextIn = unknown, const Plugins extends ReadonlyArray<Plugin<any, any, any>> = ReadonlyArray<Plugin<any, any, any>>>(plugins: Plugins) => Middleware<ContextIn, ComposedOut<Plugins> & ContextIn>;
1097
1240
  /** Options for `.vectorize(field, opts)` (DSL Shape A). */
1098
1241
  interface VectorizeOptions<Shape extends Record<string, Validator> = Record<string, Validator>> {
@@ -1129,10 +1272,10 @@ interface RelationBuilder {
1129
1272
  }) => OneRelation<Target>;
1130
1273
  }
1131
1274
  /**
1132
- * Options for the inline `.aggregateIndex(name, opts)` builder. `op` defaults to
1133
- * `count` so `aggregateIndex("byUser", { by: ["userId"] })` is a single-line
1134
- * `COUNT(*) GROUP BY userId` accelerator.
1135
- */
1275
+ * Options for the inline `.aggregateIndex(name, opts)` builder. `op` defaults to
1276
+ * `count` so `aggregateIndex("byUser", { by: ["userId"] })` is a single-line
1277
+ * `COUNT(*) GROUP BY userId` accelerator.
1278
+ */
1136
1279
  interface InlineAggregateIndexOptions<Shape extends Record<string, Validator> = Record<string, Validator>> {
1137
1280
  /** Group keys; counter rows are one per distinct tuple. Omitted = single-row aggregate over the whole table. */
1138
1281
  by?: ReadonlyArray<keyof Shape & string>;
@@ -1144,11 +1287,11 @@ interface InlineAggregateIndexOptions<Shape extends Record<string, Validator> =
1144
1287
  where?: Record<string, unknown>;
1145
1288
  }
1146
1289
  /**
1147
- * Options for the inline `.rankIndex(name, opts)` builder. `sortBy` is required;
1148
- * accepts either an array of `{ field, direction }` keys, or the shorthand
1149
- * `["field"]` (asc) / `{ field: "desc" }` map entries. `partitionBy` scopes the
1150
- * rank — omitted ⇒ one global rank over the whole table.
1151
- */
1290
+ * Options for the inline `.rankIndex(name, opts)` builder. `sortBy` is required;
1291
+ * accepts either an array of `{ field, direction }` keys, or the shorthand
1292
+ * `["field"]` (asc) / `{ field: "desc" }` map entries. `partitionBy` scopes the
1293
+ * rank — omitted ⇒ one global rank over the whole table.
1294
+ */
1152
1295
  interface InlineRankIndexOptions<Shape extends Record<string, Validator> = Record<string, Validator>> {
1153
1296
  /** Columns that scope each ranking; omitted ⇒ one global rank. */
1154
1297
  partitionBy?: ReadonlyArray<keyof Shape & string>;
@@ -1164,66 +1307,127 @@ interface TableBuilder<Shape extends Record<string, Validator> = Record<string,
1164
1307
  /** Declare an aggregate (counter/sum/…) maintained by triggers for O(1) reads. */
1165
1308
  aggregateIndex: (name: string, options?: InlineAggregateIndexOptions<Shape>) => TableBuilder<Shape>;
1166
1309
  /**
1167
- * Mark this table as written outside Lunora's discoverable insert path —
1168
- * by an adapter, a migration, or framework middleware (e.g. `@lunora/auth`'s
1169
- * better-auth tables, `@lunora/ratelimit`'s store). Advisor insert-path lints
1170
- * (`table_without_insert`) then skip it instead of flagging the absent
1171
- * `ctx.db.insert(...)`.
1172
- */
1310
+ * Mark this table as written outside Lunora's discoverable insert path —
1311
+ * by an adapter, a migration, or framework middleware (e.g. `@lunora/auth`'s
1312
+ * better-auth tables, `@lunora/ratelimit`'s store). Advisor insert-path lints
1313
+ * (`table_without_insert`) then skip it instead of flagging the absent
1314
+ * `ctx.db.insert(...)`.
1315
+ */
1173
1316
  externallyManaged: () => TableBuilder<Shape>;
1174
1317
  /**
1175
- * Mark this table as global (cross-shard). Backed by **D1** by default;
1176
- * pass `{ backend: "hyperdrive" }` to store it in a Postgres/MySQL database
1177
- * via Cloudflare Hyperdrive (PlanetScale, Neon, …) instead. Either way the
1178
- * table stays reactive live queries re-run on write.
1179
- */
1318
+ * Declare a geospatial index over a `v.geoPoint()` column. The runtime keeps
1319
+ * a geohash companion so `withGeoIndex(name, q => q.near(point, radius))` and
1320
+ * `.within(bbox)` resolve as a geohash-prefix range scan + Haversine
1321
+ * refine/sort. `options.precision` tunes the geohash length (default 9).
1322
+ */
1323
+ geoIndex: (name: string, options: {
1324
+ field: keyof Shape & string;
1325
+ precision?: number;
1326
+ }) => TableBuilder<Shape>;
1327
+ /**
1328
+ * Mark this table as global (cross-shard). Backed by **D1** by default;
1329
+ * pass `{ backend: "hyperdrive" }` to store it in a Postgres/MySQL database
1330
+ * via Cloudflare Hyperdrive (PlanetScale, Neon, …) instead. Either way the
1331
+ * table stays reactive — live queries re-run on write.
1332
+ */
1180
1333
  global: (options?: {
1181
1334
  backend?: GlobalBackend;
1182
1335
  }) => TableBuilder<Shape>;
1183
1336
  /** Add a secondary index. */
1184
- index: (name: string, fields: ReadonlyArray<string>, options?: {
1337
+ index: (name: string, fields: ReadonlyArray<(keyof Shape & string) | (typeof SYSTEM_INDEX_FIELDS)[number]>, options?: {
1185
1338
  unique?: boolean;
1186
1339
  }) => TableBuilder<Shape>;
1187
1340
  /**
1188
- * Opt this table OUT of secure-by-default RLS. Under a schema marked
1189
- * `.rls("required")`, every table is protected (the write path denies raw,
1190
- * non-RLS `ctx.db` access); calling `.public()` exempts this one table so a
1191
- * plain `query`/`mutation` may read/write it without an RLS policy. No effect
1192
- * when the schema does not require RLS.
1193
- */
1341
+ * Name the column holding the owning user's id, so "only the owner sees these
1342
+ * rows" is declared once here rather than restated in every shape.
1343
+ *
1344
+ * A `defineShape({ table, owner: true })` over this table derives its predicate
1345
+ * from the field: the subscriber's verified `ctx.auth.userId` must match, and an
1346
+ * anonymous subscriber is denied. Pairs naturally with `.shardBy(field)` on the
1347
+ * same column — the shard key routes the storage, `ownedBy` states who the rows
1348
+ * belong to — but the two are independent and either can be used alone.
1349
+ *
1350
+ * This is a *shape* declaration, not an RLS policy: it narrows what a shape
1351
+ * replicates. Guarding procedure reads/writes is still `rls(...)`'s job.
1352
+ */
1353
+ ownedBy: (field: keyof Shape & string) => TableBuilder<Shape>;
1354
+ /**
1355
+ * Opt this table OUT of secure-by-default RLS. Under a schema marked
1356
+ * `.rls("required")`, every table is protected (the write path denies raw,
1357
+ * non-RLS `ctx.db` access); calling `.public()` exempts this one table so a
1358
+ * plain `query`/`mutation` may read/write it without an RLS policy. No effect
1359
+ * when the schema does not require RLS.
1360
+ */
1194
1361
  public: () => TableBuilder<Shape>;
1195
1362
  /**
1196
- * Declare a rank index (sorted companion table, btree-backed) for
1197
- * `rank(row)` / `rankPage()` reads in O(log n). See {@link RankIndexDefinition}.
1198
- */
1363
+ * Declare a rank index (sorted companion table, btree-backed) for
1364
+ * `rank(row)` / `rankPage()` reads in O(log n). See {@link RankIndexDefinition}.
1365
+ */
1199
1366
  rankIndex: (name: string, options: InlineRankIndexOptions<Shape>) => TableBuilder<Shape>;
1200
1367
  /** Declare relations to other tables, loaded via `findMany({ with })`. */
1201
1368
  relations: (build: (r: RelationBuilder) => Record<string, RelationDefinition>) => TableBuilder<Shape>;
1202
- /** Add a search index over a field with optional filter fields. */
1369
+ /**
1370
+ * Add a full-text search index over `field`, queried with
1371
+ * `.withSearchIndex(name, q => q.search(field, term))`. `field` may be a
1372
+ * dot-separated path into a nested object (`"properties.name"`).
1373
+ * `filterFields` (at most 16) lists the columns `.eq()` may narrow by inside
1374
+ * the search. `language` selects the text analysis (accent folding always,
1375
+ * plus that language's stopwords). `staged: true` skips the migration-time
1376
+ * backfill on a large existing table. `strategy: "native"` uses the engine's
1377
+ * own full-text index where it has one (Postgres) — faster on large corpora,
1378
+ * at the cost of the engine ranking rather than the shared scorer.
1379
+ */
1203
1380
  searchIndex: (name: string, options: {
1204
1381
  field: string;
1205
1382
  filterFields?: ReadonlyArray<string>;
1383
+ language?: SearchLanguage;
1384
+ staged?: boolean;
1385
+ strategy?: SearchStrategy;
1206
1386
  }) => TableBuilder<Shape>;
1207
1387
  /** Route storage by the named field — one DO per distinct value. */
1208
1388
  shardBy: (field: keyof Shape & string) => TableBuilder<Shape>;
1209
1389
  /**
1210
- * Turn on soft delete. Adds a nullable timestamp column (`options.field`,
1211
- * default `deletedAt`) and changes `ctx.db.&lt;table>.delete()` to **set** it
1212
- * instead of removing the row; `onDelete: "cascade"` children are recursively
1213
- * soft-deleted too. **List reads** (`findMany`/`findFirst`/`query()`/`count`/
1214
- * `aggregate`/relation loads) then hide soft-deleted rows unless they pass
1215
- * `includeDeleted: true`; by-id `get`/`patch`/`replace` and the new
1216
- * `restore()` still address the row directly. `hardDelete()` physically
1217
- * removes it (cascading as a real delete). Note: `includeDeleted` is a read
1218
- * scope, not access control — anyone who can run the read can set it; a unique
1219
- * index still rejects a new row that collides with a soft-deleted one (the row
1220
- * physically persists).
1221
- */
1390
+ * Turn on soft delete. Adds a nullable timestamp column (`options.field`,
1391
+ * default `deletedAt`) and changes `ctx.db.&lt;table>.delete()` to **set** it
1392
+ * instead of removing the row; `onDelete: "cascade"` children are recursively
1393
+ * soft-deleted too. **List reads** (`findMany`/`findFirst`/`query()`/`count`/
1394
+ * `aggregate`/relation loads) then hide soft-deleted rows unless they pass
1395
+ * `includeDeleted: true`; by-id `get`/`patch`/`replace` and the new
1396
+ * `restore()` still address the row directly. `hardDelete()` physically
1397
+ * removes it (cascading as a real delete). Note: `includeDeleted` is a read
1398
+ * scope, not access control — anyone who can run the read can set it; a unique
1399
+ * index still rejects a new row that collides with a soft-deleted one (the row
1400
+ * physically persists).
1401
+ */
1222
1402
  softDelete: (options?: {
1223
1403
  field?: string;
1224
1404
  }) => TableBuilder<Shape>;
1405
+ /**
1406
+ * Materialize this table from an external Postgres/MySQL behind Cloudflare
1407
+ * Hyperdrive (plan 077). A system-driven poll loop reads the tenant slice
1408
+ * (`query`, with params bound from `tenantBy`) and lands it in the DO's SQLite,
1409
+ * after which `defineShape` carries it to clients unchanged. Implies
1410
+ * `.externallyManaged()` (rows come from the ingest loop, not user mutations).
1411
+ *
1412
+ * Orthogonal to `.shardBy()` — combine them for per-tenant DOs. **Under
1413
+ * `.shardBy()` `tenantBy` is mandatory** (the tenant-isolation boundary); the
1414
+ * `external_source_unscoped` advisor lint fails the build when it is absent, and
1415
+ * `external_source_on_global` rejects combining `.source()` with `.global()`.
1416
+ */
1417
+ source: (definition: ExternalSourceDefinition) => TableBuilder<Shape>;
1225
1418
  /** Declare named lifecycle triggers fired inline within the write path. */
1226
1419
  triggers: (build: (t: TriggerBuilder<Shape>) => Record<string, TriggerDefinition>) => TableBuilder<Shape>;
1420
+ /**
1421
+ * Declare a table-level TTL: a DO alarm-driven sweep auto-deletes rows whose
1422
+ * expiry has passed (or soft-deletes them when the table also
1423
+ * `.softDelete()`s). `field` is an epoch-millisecond column; without
1424
+ * `options.after` its value is the absolute expiry instant, with `after` the
1425
+ * row expires `after` ms past `field` (`field + after`). Coarse, cheap,
1426
+ * table-level — for per-row schedules use `@lunora/scheduler`.
1427
+ */
1428
+ ttl: (field: keyof Shape & string, options?: {
1429
+ after?: number;
1430
+ }) => TableBuilder<Shape>;
1227
1431
  /** Declare a vector index over a single text field on this table. */
1228
1432
  vectorize: (field: keyof Shape & string, options: VectorizeOptions<Shape>) => TableBuilder<Shape>;
1229
1433
  }
@@ -1241,22 +1445,22 @@ interface VectorIndexOptions {
1241
1445
  };
1242
1446
  }
1243
1447
  /**
1244
- * Build a table definition. Returned object is both the table definition (for
1245
- * `defineSchema`) and a fluent builder for indexes + sharding metadata.
1246
- */
1448
+ * Build a table definition. Returned object is both the table definition (for
1449
+ * `defineSchema`) and a fluent builder for indexes + sharding metadata.
1450
+ */
1247
1451
  declare const defineTable: <Shape extends Record<string, Validator>>(inputShape: Shape) => TableBuilder<Shape>;
1248
1452
  /**
1249
- * Declare a standalone vector index (DSL Shape B). Pass the returned value in
1250
- * the `vectorIndexes` map of {@link defineSchema} when the source is derived
1251
- * from multiple fields or a computation rather than a single column.
1252
- */
1453
+ * Declare a standalone vector index (DSL Shape B). Pass the returned value in
1454
+ * the `vectorIndexes` map of {@link defineSchema} when the source is derived
1455
+ * from multiple fields or a computation rather than a single column.
1456
+ */
1253
1457
  declare const defineVectorIndex: (options: VectorIndexOptions) => VectorIndexDefinition;
1254
1458
  /**
1255
- * Options for the standalone `defineAggregateIndex(name, opts)` helper (DSL
1256
- * Shape B). Unlike the inline `.aggregateIndex(...)` builder, this form takes
1257
- * the owning table explicitly via `on` — handy when a single counter wants to
1258
- * live next to the schema map rather than inside a table chain.
1259
- */
1459
+ * Options for the standalone `defineAggregateIndex(name, opts)` helper (DSL
1460
+ * Shape B). Unlike the inline `.aggregateIndex(...)` builder, this form takes
1461
+ * the owning table explicitly via `on` — handy when a single counter wants to
1462
+ * live next to the schema map rather than inside a table chain.
1463
+ */
1260
1464
  interface AggregateIndexOptions {
1261
1465
  by?: ReadonlyArray<string>;
1262
1466
  field?: string;
@@ -1265,17 +1469,17 @@ interface AggregateIndexOptions {
1265
1469
  where?: Record<string, unknown>;
1266
1470
  }
1267
1471
  /**
1268
- * Declare a standalone aggregate index. Pass the returned value to
1269
- * `defineSchema(tables, vectorIndexes, aggregateIndexes)` keyed by index name —
1270
- * the schema attaches it to `tables[on].aggregateIndexes` so runtime consumers
1271
- * (DO + D1) read every index uniformly off the table definition.
1272
- */
1472
+ * Declare a standalone aggregate index. Pass the returned value to
1473
+ * `defineSchema(tables, vectorIndexes, aggregateIndexes)` keyed by index name —
1474
+ * the schema attaches it to `tables[on].aggregateIndexes` so runtime consumers
1475
+ * (DO + D1) read every index uniformly off the table definition.
1476
+ */
1273
1477
  declare const defineAggregateIndex: (name: string, options: AggregateIndexOptions) => AggregateIndexDefinition;
1274
1478
  /**
1275
- * Options for the standalone `defineRankIndex(name, opts)` helper (DSL Shape B).
1276
- * Mirrors the inline `.rankIndex(...)` builder but takes the owning table via
1277
- * `table` so it can sit next to the schema map.
1278
- */
1479
+ * Options for the standalone `defineRankIndex(name, opts)` helper (DSL Shape B).
1480
+ * Mirrors the inline `.rankIndex(...)` builder but takes the owning table via
1481
+ * `table` so it can sit next to the schema map.
1482
+ */
1279
1483
  interface RankIndexOptions {
1280
1484
  partitionBy?: ReadonlyArray<string>;
1281
1485
  sortBy: ReadonlyArray<{
@@ -1286,84 +1490,493 @@ interface RankIndexOptions {
1286
1490
  where?: Record<string, unknown>;
1287
1491
  }
1288
1492
  /**
1289
- * Declare a standalone rank index. Pass the returned value to
1290
- * `defineSchema(tables, vectorIndexes, aggregateIndexes, rankIndexes)` keyed
1291
- * by index name — the schema attaches it to `tables[on].rankIndexes`.
1292
- */
1493
+ * Declare a standalone rank index. Pass the returned value to
1494
+ * `defineSchema(tables, vectorIndexes, aggregateIndexes, rankIndexes)` keyed
1495
+ * by index name — the schema attaches it to `tables[on].rankIndexes`.
1496
+ */
1293
1497
  declare const defineRankIndex: (name: string, options: RankIndexOptions) => RankIndexDefinition;
1294
1498
  /**
1295
- * Build the application schema. The first argument is the table map; the
1296
- * optional second argument registers standalone `defineVectorIndex(...)`
1297
- * declarations (DSL Shape B) keyed by index name. The optional third argument
1298
- * registers standalone `defineAggregateIndex(...)` declarations (DSL Shape B);
1299
- * the optional fourth argument registers standalone `defineRankIndex(...)`
1300
- * declarations. Both are folded into the matching `tables[on].*Indexes` array
1301
- * so runtime backends read every index uniformly off the table definition.
1302
- */
1303
- /**
1304
- * Schema with an in-place `.extend(plugin.extension)` method. Used so apps
1305
- * can compose plugin schemas: `defineSchema({...}).extend(authPlugin.extension)`.
1306
- *
1307
- * `extend` is non-mutating — returns a fresh `ExtendableSchema` containing
1308
- * the merged tables. Extension tables are auto-namespaced by the extension
1309
- * `key` (`buckets` → `ratelimit_buckets`), so the merged type carries the
1310
- * prefixed names via {@link PrefixedTables}. Chains:
1311
- * `defineSchema(...).extend(a).extend(b)` is the typed equivalent of merging
1312
- * `a`'s prefixed tables then `b`'s.
1313
- */
1499
+ * Build the application schema. The first argument is the table map; the
1500
+ * optional second argument registers standalone `defineVectorIndex(...)`
1501
+ * declarations (DSL Shape B) keyed by index name. The optional third argument
1502
+ * registers standalone `defineAggregateIndex(...)` declarations (DSL Shape B);
1503
+ * the optional fourth argument registers standalone `defineRankIndex(...)`
1504
+ * declarations. Both are folded into the matching `tables[on].*Indexes` array
1505
+ * so runtime backends read every index uniformly off the table definition.
1506
+ */
1507
+ /**
1508
+ * Schema with an in-place `.extend(plugin.extension)` method. Used so apps
1509
+ * can compose plugin schemas: `defineSchema({...}).extend(authPlugin.extension)`.
1510
+ *
1511
+ * `extend` is non-mutating — returns a fresh `ExtendableSchema` containing
1512
+ * the merged tables. Extension tables are auto-namespaced by the extension
1513
+ * `key` (`buckets` → `ratelimit_buckets`), so the merged type carries the
1514
+ * prefixed names via {@link PrefixedTables}. Chains:
1515
+ * `defineSchema(...).extend(a).extend(b)` is the typed equivalent of merging
1516
+ * `a`'s prefixed tables then `b`'s.
1517
+ */
1314
1518
  type ExtendableSchema<T extends Record<string, TableDefinition>> = {
1315
1519
  extend: <X extends Record<string, TableDefinition>, Key extends string>(extension: SchemaExtension<X> & {
1316
1520
  readonly key: Key;
1317
1521
  }) => ExtendableSchema<PrefixedTables<X, Key> & T>;
1318
1522
  /**
1319
- * Pin every Durable Object the app reaches — shards, fan-out, subscriptions,
1320
- * the scheduler, and `ctx.containers` — to a Cloudflare data-residency
1321
- * jurisdiction (`"eu"`, `"us"`, `"fedramp"`). Codegen reads this off the
1322
- * schema and emits it into the generated worker's `createWorker({ jurisdiction })`
1323
- * (and `ctx.scheduler` / `ctx.containers`). Non-mutating: returns a fresh
1324
- * `ExtendableSchema`, so it composes with `.rls(...)` / `.extend(...)` in any order.
1325
- *
1326
- * ⚠️ **Set this once, before your first deploy — changing or removing it
1327
- * strands data.** A Durable Object name maps to a *different* ID in each
1328
- * jurisdiction, so toggling this on an existing app makes every shard, scheduler
1329
- * job, and session DO resolve to a NEW, empty DO; the previous data stays in the
1330
- * old jurisdiction's DOs and is no longer reachable. There is no in-place
1331
- * migration — you would have to export from the old jurisdiction and import
1332
- * into the new one.
1333
- *
1334
- * Note: this pins **DO-backed** state only. D1-backed state — `.global()`
1335
- * tables and `@lunora/auth` sessions alike — is governed by D1's own location
1336
- * settings, not this option.
1337
- * @see https://developers.cloudflare.com/durable-objects/reference/data-location/
1338
- */
1523
+ * Pin every Durable Object the app reaches — shards, fan-out, subscriptions,
1524
+ * the scheduler, and `ctx.containers` — to a Cloudflare data-residency
1525
+ * jurisdiction (`"eu"`, `"us"`, `"fedramp"`). Codegen reads this off the
1526
+ * schema and emits it into the generated worker's `createWorker({ jurisdiction })`
1527
+ * (and `ctx.scheduler` / `ctx.containers`). Non-mutating: returns a fresh
1528
+ * `ExtendableSchema`, so it composes with `.rls(...)` / `.extend(...)` in any order.
1529
+ *
1530
+ * ⚠️ **Set this once, before your first deploy — changing or removing it
1531
+ * strands data.** A Durable Object name maps to a *different* ID in each
1532
+ * jurisdiction, so toggling this on an existing app makes every shard, scheduler
1533
+ * job, and session DO resolve to a NEW, empty DO; the previous data stays in the
1534
+ * old jurisdiction's DOs and is no longer reachable. There is no in-place
1535
+ * migration — you would have to export from the old jurisdiction and import
1536
+ * into the new one.
1537
+ *
1538
+ * Note: this pins **DO-backed** state only. D1-backed state — `.global()`
1539
+ * tables and `@lunora/auth` sessions alike — is governed by D1's own location
1540
+ * settings, not this option.
1541
+ * @see https://developers.cloudflare.com/durable-objects/reference/data-location/
1542
+ */
1339
1543
  jurisdiction: (jurisdiction: DurableObjectJurisdiction) => ExtendableSchema<T>;
1340
1544
  /**
1341
- * Turn on secure-by-default RLS for the whole schema. Every table is then
1342
- * protected — the DO/D1 write path denies raw, non-RLS `ctx.db` access, so a
1343
- * procedure that forgets `.use(rls(...))` fails closed. Opt a table out with
1344
- * `.public()`. Non-mutating: returns a fresh `ExtendableSchema` carrying the
1345
- * mode, so `.rls("required")` composes with `.extend(...)` either order.
1346
- */
1545
+ * Turn on secure-by-default RLS for the whole schema. Every table is then
1546
+ * protected — the DO/D1 write path denies raw, non-RLS `ctx.db` access, so a
1547
+ * procedure that forgets `.use(rls(...))` fails closed. Opt a table out with
1548
+ * `.public()`. Non-mutating: returns a fresh `ExtendableSchema` carrying the
1549
+ * mode, so `.rls("required")` composes with `.extend(...)` either order.
1550
+ */
1347
1551
  rls: (mode: "required") => ExtendableSchema<T>;
1348
1552
  } & Schema<T>;
1553
+ /**
1554
+ * Columns every row carries implicitly (never part of a table's declared
1555
+ * `shape`), so `.index()` may legitimately name them. The single source for
1556
+ * both the compile-time allow-list (`TableBuilder["index"]`'s `fields` type,
1557
+ * via `(typeof SYSTEM_INDEX_FIELDS)[number]`) and the runtime cross-check
1558
+ * below (via `SYSTEM_INDEX_FIELDS_SET`) — declared once so the two can't
1559
+ * drift apart.
1560
+ */
1561
+ declare const SYSTEM_INDEX_FIELDS: readonly ["_creationTime", "_id"];
1562
+ /**
1563
+ * Per-table, per-KIND index→declared-fields map: for each table, each index
1564
+ * KIND (`index` | `rank` | `geo`) that has at least one declared index maps
1565
+ * to a name→fields record for that kind only. Distilled by
1566
+ * {@link indexFieldsFromSchema}; this is the shape `mask()`'s
1567
+ * `MaskOptions.indexFields` expects (see `./mask/types`), so a table not
1568
+ * present here (no declared indexes of any kind) is simply absent from the
1569
+ * map rather than mapped to `{}`, and a kind with no declared indexes on a
1570
+ * table that HAS other kinds is simply absent from that table's entry.
1571
+ *
1572
+ * Kept per kind (rather than one flat name→fields record) because the engine
1573
+ * resolves `withIndex`/`withGeoIndex`/rank reads in THREE separate
1574
+ * namespaces (`tableDefinition.indexes` / `.geoIndexes` / `.rankIndexes` —
1575
+ * see `@lunora/shard-engine`'s `ctx-db.ts`), so the same name can legally and
1576
+ * unambiguously denote a different index per kind. A flat map would let one
1577
+ * kind's fields silently shadow another's for a colliding name, producing a
1578
+ * wrong-namespace answer from the mask guard (checking the wrong index's
1579
+ * fields) instead of the documented fail-open (missing lookup) — see plan 258.
1580
+ */
1581
+ type IndexFieldsByTable = Readonly<Record<string, {
1582
+ readonly geo?: Readonly<Record<string, ReadonlyArray<string>>>;
1583
+ readonly index?: Readonly<Record<string, ReadonlyArray<string>>>;
1584
+ readonly rank?: Readonly<Record<string, ReadonlyArray<string>>>;
1585
+ }>>;
1586
+ declare const indexFieldsFromSchema: (schema: Schema) => IndexFieldsByTable;
1349
1587
  declare const defineSchema: <T extends Record<string, TableDefinition>>(tables: T, vectorIndexes?: Record<string, VectorIndexDefinition>, aggregateIndexes?: Record<string, AggregateIndexDefinition>, rankIndexes?: Record<string, RankIndexDefinition>) => ExtendableSchema<T>;
1588
+ /**
1589
+ * Context handed to a {@link MaskFn} (and to {@link MaskOptions.bypass}). The
1590
+ * `auth` shape mirrors RLS's `PolicyContext.auth` one-for-one — same identity
1591
+ * resolver, same `can(...)` permission check — so an author can branch a mask
1592
+ * on the caller's role/permission. `row` is the full pre-mask row the column
1593
+ * belongs to; `column` is the column currently being masked. Both are absent
1594
+ * when the context is used for the procedure-wide `bypass` check (no specific
1595
+ * cell is in play yet).
1596
+ */
1597
+ interface MaskContext<Context = unknown> {
1598
+ readonly auth: {
1599
+ /** `true` when any of the request's `roles` grants `permission` (see {@link MaskOptions.roles}). Fails closed for unregistered roles. */
1600
+ readonly can: (permission: Permission | string) => boolean;
1601
+ readonly identity?: Record<string, unknown> | null;
1602
+ readonly roles: ReadonlyArray<string>;
1603
+ readonly userId: null | string;
1604
+ };
1605
+ /** The column currently being masked. Present only inside a per-cell {@link MaskFn}. */
1606
+ readonly column?: string;
1607
+ readonly ctx: Context;
1608
+ /** The full pre-mask row the masked cell belongs to. Present only inside a per-cell {@link MaskFn}. */
1609
+ readonly row?: Record<string, unknown>;
1610
+ }
1611
+ /**
1612
+ * A custom masking function. Receives the raw cell value and the
1613
+ * {@link MaskContext}, returns the value to surface. Use it for partial masks
1614
+ * (`maskMiddle(phone)`), role-aware reveals (`ctx.auth.can(...) ? value : null`),
1615
+ * or format-preserving tokens. A function that **throws** fails closed — the
1616
+ * cell is redacted to `null`, never leaked raw.
1617
+ */
1618
+ type MaskFn<Context = unknown> = (value: unknown, context: MaskContext<Context>) => unknown;
1619
+ /**
1620
+ * How a column is masked:
1621
+ *
1622
+ * - `"redact"` — drop the value to `null`. The simplest, safest strategy, and
1623
+ * the right choice for any value that must actually be kept secret.
1624
+ * - `"hash"` — replace with a stable token (unsalted 32-bit FNV-1a hex) so the
1625
+ * same input always yields the same token (joinable/groupable client-side).
1626
+ * **This is NOT a confidentiality control.** It is a non-cryptographic,
1627
+ * unsalted, deterministic, narrow (~2^32) digest: low-entropy values (emails,
1628
+ * phone numbers, SSNs) are brute-force-recoverable by the very caller you are
1629
+ * masking from, and identical values always produce identical tokens across
1630
+ * rows/columns/tenants (enabling correlation). Use `"hash"` ONLY when you want a
1631
+ * stable pseudonym for grouping/joining and leaking the value is acceptable —
1632
+ * never to hide sensitive PII. For PII that must stay hidden, use `"redact"`.
1633
+ * - a {@link MaskFn} — author-defined transform (partial mask, role-aware reveal).
1634
+ */
1635
+ type MaskStrategy<Context = unknown> = "hash" | "redact" | MaskFn<Context>;
1636
+ /** Per-column strategy map for one table: `{ email: "redact", phone: maskMiddle }`. */
1637
+ type MaskColumns<Context = unknown> = Record<string, MaskStrategy<Context>>;
1638
+ /**
1639
+ * The mask declaration passed to `mask(...)`: a table → column → strategy map.
1640
+ * Deliberately a plain object literal so the codegen feeder can statically read
1641
+ * which columns a procedure masks (powering the `mask_uncovered_pii_column`
1642
+ * advisor lint), exactly as the RLS feeder reads policy tables.
1643
+ */
1644
+ type MaskPolicies<Context = unknown> = Record<string, MaskColumns<Context>>;
1645
+ /**
1646
+ * Options for `mask(policies, options)`.
1647
+ *
1648
+ * - `roles` registers the role→permission grants that back `ctx.auth.can(...)`
1649
+ * inside a {@link MaskFn} — identical to `rls(policies, { roles })`. A role
1650
+ * not listed grants no permissions (fails closed for unknown roles).
1651
+ * - `bypass` is a procedure-wide escape hatch: when it returns `true` the whole
1652
+ * mask is skipped (the caller sees raw values). Use it for a privileged
1653
+ * viewer — `bypass: ({ auth }) => auth.can("pii:view")`. Prefer this over
1654
+ * branching every column when an entire class of caller should see clear data.
1655
+ * - `indexFields` closes the bare-index-scan / rank / geo position oracle (see
1656
+ * the `mask/middleware` module docblock's "Residual read-position oracles" section).
1657
+ */
1658
+ interface MaskOptions<Context = unknown> {
1659
+ readonly bypass?: (context: MaskContext<Context>) => boolean;
1660
+ /**
1661
+ * Per-table, per-KIND index→declared-fields map (regular index `fields`
1662
+ * under `index`; rank index `sortBy` ∪ `partitionBy` under `rank`; geo
1663
+ * index `field` under `geo`). Supplied to close the bare-index-scan /
1664
+ * rank / geo position oracle: a `withIndex(name)` with no range callback,
1665
+ * a `rank`/`rankPage`/`rankBefore` read, or a `withGeoIndex` read, over an
1666
+ * index whose DECLARED fields (for that read's own kind) intersect a
1667
+ * masked column, is rejected. Kept per kind — rather than one flat
1668
+ * name→fields map — because the engine resolves `withIndex` /
1669
+ * `withGeoIndex` / rank reads in three separate namespaces, so the same
1670
+ * index name can legally denote a different index per kind; a flat map
1671
+ * would let one kind's fields shadow another's for a colliding name.
1672
+ * OPTIONAL and additive — omit it and behaviour is unchanged (the oracle
1673
+ * stays open, exactly as before this option existed). Build it with
1674
+ * `indexFieldsFromSchema` (exported from `@lunora/server`):
1675
+ * `mask(policies, { indexFields: indexFieldsFromSchema(schema) })`.
1676
+ */
1677
+ readonly indexFields?: IndexFieldsByTable;
1678
+ readonly roles?: ReadonlyArray<Role>;
1679
+ }
1680
+ interface QueryPage$1 {
1681
+ continueCursor: null | string;
1682
+ isDone: boolean;
1683
+ page: Record<string, unknown>[];
1684
+ }
1685
+ interface QueryArgs$1 {
1686
+ baseWhere?: unknown;
1687
+ cursor?: null | string;
1688
+ limit?: number;
1689
+ orderBy?: ReadonlyArray<Record<string, unknown>>;
1690
+ where?: unknown;
1691
+ with?: Record<string, unknown>;
1692
+ }
1693
+ interface AggregateArgs$1 {
1694
+ field?: string;
1695
+ op: string;
1696
+ where?: unknown;
1697
+ }
1698
+ interface GroupByArgs$1 {
1699
+ agg?: {
1700
+ field?: string;
1701
+ op: string;
1702
+ };
1703
+ by: ReadonlyArray<string>;
1704
+ where?: unknown;
1705
+ }
1706
+ /** One row of a `.collectWithScores()` result — mirrors `@lunora/shard-engine`'s `ScoredDocument`. */
1707
+ type ScoredDocument = GeoScoredDocument | SearchScoredDocument;
1708
+ /** A `.withGeoIndex()` row — mirrors `@lunora/shard-engine`'s `GeoScoredDocument`. */
1709
+ interface GeoScoredDocument {
1710
+ distanceMeters: null | number;
1711
+ document: Record<string, unknown>;
1712
+ score?: never;
1713
+ }
1714
+ /** A `.withSearchIndex()` row — mirrors `@lunora/shard-engine`'s `SearchScoredDocument`. */
1715
+ interface SearchScoredDocument {
1716
+ distanceMeters?: never;
1717
+ document: Record<string, unknown>;
1718
+ score: number;
1719
+ }
1720
+ interface TableReaderLike$1 {
1721
+ [Symbol.asyncIterator]: () => AsyncIterator<Record<string, unknown>>;
1722
+ collect: () => Promise<Record<string, unknown>[]>;
1723
+ collectWithScores: () => Promise<ScoredDocument[]>;
1724
+ filter: (predicate: (document: Record<string, unknown>) => boolean) => TableReaderLike$1;
1725
+ first: () => Promise<Record<string, unknown> | null>;
1726
+ order: (direction: "asc" | "desc") => TableReaderLike$1;
1727
+ paginate: (options: {
1728
+ cursor?: null | string;
1729
+ numItems: number;
1730
+ }) => Promise<QueryPage$1>;
1731
+ take: (limit: number) => Promise<Record<string, unknown>[]>;
1732
+ unique: () => Promise<Record<string, unknown> | null>;
1733
+ withGeoIndex: (indexName: string, build: (q: unknown) => unknown) => TableReaderLike$1;
1734
+ withIndex: (indexName: string, range?: (q: unknown) => unknown) => TableReaderLike$1;
1735
+ withSearchIndex: (indexName: string, search: (q: unknown) => unknown) => TableReaderLike$1;
1736
+ }
1737
+ /**
1738
+ * Structural projection of the runtime ORM writer — the same subset
1739
+ * `../rls/middleware` mirrors, so the wrapper is interchangeable between
1740
+ * `@lunora/do`'s and `@lunora/d1`'s `DatabaseWriterLike` without an
1741
+ * inter-package dependency. `rankBefore` is optional (the D1 twin omits it).
1742
+ */
1743
+ interface MaskDatabase {
1744
+ aggregate: (tableName: string, options: AggregateArgs$1) => Promise<null | number>;
1745
+ count: (tableName: string, whereOrArgs?: unknown) => Promise<number>;
1746
+ delete: (id: string, expectedTable?: string) => Promise<void>;
1747
+ deleteMany: (ids: ReadonlyArray<string>, options?: {
1748
+ limit?: number;
1749
+ }) => Promise<{
1750
+ deleted: number;
1751
+ }>;
1752
+ deleteWhere?: (tableName: string, where: Record<string, unknown>, options?: {
1753
+ limit?: number;
1754
+ }) => Promise<{
1755
+ deleted: number;
1756
+ }>;
1757
+ findFirst: (tableName: string, args?: QueryArgs$1) => Promise<Record<string, unknown> | null>;
1758
+ findFirstOrThrow: (tableName: string, args?: QueryArgs$1) => Promise<Record<string, unknown>>;
1759
+ findMany: (tableName: string, args?: QueryArgs$1) => Promise<QueryPage$1>;
1760
+ get: (id: string, expectedTable?: string) => Promise<Record<string, unknown> | null>;
1761
+ groupBy: (tableName: string, options: GroupByArgs$1) => Promise<ReadonlyArray<{
1762
+ key: Record<string, unknown>;
1763
+ value: null | number;
1764
+ }>>;
1765
+ insert: (tableName: string, document: Record<string, unknown>) => Promise<string>;
1766
+ insertMany: (tableName: string, documents: ReadonlyArray<Record<string, unknown>>, options?: {
1767
+ limit?: number;
1768
+ skipDuplicates?: boolean;
1769
+ }) => Promise<(string | null)[]>;
1770
+ lookupById?: (id: string, expectedTable?: string) => Promise<null | {
1771
+ row: Record<string, unknown>;
1772
+ tableName: string;
1773
+ }>;
1774
+ patch: (id: string, patch: Record<string, unknown>, expectedTable?: string) => Promise<void>;
1775
+ patchMany: (patches: ReadonlyArray<{
1776
+ id: string;
1777
+ patch: Record<string, unknown>;
1778
+ }>, options?: {
1779
+ limit?: number;
1780
+ }) => Promise<{
1781
+ patched: number;
1782
+ }>;
1783
+ patchWhere?: (tableName: string, args: {
1784
+ patch: Record<string, unknown>;
1785
+ where: Record<string, unknown>;
1786
+ }, options?: {
1787
+ limit?: number;
1788
+ }) => Promise<{
1789
+ patched: number;
1790
+ }>;
1791
+ query: (tableName: string) => TableReaderLike$1;
1792
+ rank: (tableName: string, indexName: string, options: unknown) => Promise<null | {
1793
+ position: number;
1794
+ total: number;
1795
+ }>;
1796
+ rankBefore?: (tableName: string, indexName: string, options: unknown) => Promise<{
1797
+ before: number;
1798
+ total: number;
1799
+ }>;
1800
+ rankPage: (tableName: string, indexName: string, options?: unknown) => Promise<QueryPage$1>;
1801
+ /** Cross-shard companion to `rankPage`, gated the same way `rankPage` is masked below. */
1802
+ rankPageRows?: (tableName: string, indexName: string, options?: unknown) => Promise<ShardRankPageResultLike>;
1803
+ replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
1804
+ }
1805
+ /** Roles list source on the context. Tolerant of older auth states (mirrors RLS's `AuthLike`). */
1806
+ type AuthLike$1 = {
1807
+ getIdentity?: () => Promise<Record<string, unknown> | null>;
1808
+ roles?: ReadonlyArray<string>;
1809
+ userId?: null | string;
1810
+ };
1811
+ interface MaskContextIn {
1812
+ auth?: AuthLike$1;
1813
+ db: MaskDatabase;
1814
+ }
1815
+ /**
1816
+ * Procedure-builder middleware. Apply per-request via `.use(mask(policies))`.
1817
+ * Closes over the policy map at builder-construction time; resolves identity +
1818
+ * the `bypass` decision per call against the live ctx.
1819
+ *
1820
+ * IMPORTANT: a mask is in scope only for procedures whose builder chain
1821
+ * includes this middleware — opt-in, never global (the same invariant as RLS).
1822
+ */
1823
+ declare const mask: <Context extends MaskContextIn = MaskContextIn>(policies: MaskPolicies<Context>, options?: MaskOptions<Context>) => Middleware<Context, Context>;
1824
+ /** Project-wide masked-column registry: every table any registered function masks, unioned. */
1825
+ type MaskRegistry = ReadonlyMap<string, ReadonlySet<string>>;
1826
+ /**
1827
+ * Build the project-wide masked-column registry from the registered functions
1828
+ * (pass `Object.values(LUNORA_FUNCTIONS)`) — the mask-column twin of
1829
+ * `buildRlsReadRegistry`. Unions every function's `.use(mask(...))` columns
1830
+ * per table: a column masked by ANY registered function counts as masked in
1831
+ * the registry — there is no "which procedure would this shape have gone
1832
+ * through" question to narrow by, so the union is the only safe answer.
1833
+ */
1834
+ declare const buildMaskRegistry: (functions: Iterable<unknown>) => MaskRegistry;
1835
+ /** A document handed to a migration transform: the stored row including `_id`/`_creationTime`. */
1836
+ type MigrationDocument = Record<string, unknown>;
1837
+ /**
1838
+ * The read surface a transform reaches through its `ctx`.
1839
+ *
1840
+ * Read-only by design: the runner accounts for exactly one rewrite per row read,
1841
+ * and a transform writing directly would make that count describe something
1842
+ * other than what happened. Scoped to the shard the runner is walking.
1843
+ */
1844
+ interface MigrationReader {
1845
+ count: (table: string, where?: Record<string, unknown>) => Promise<number>;
1846
+ findFirst: (table: string, args?: Record<string, unknown>) => Promise<MigrationDocument | null>;
1847
+ findMany: (table: string, args?: Record<string, unknown>) => Promise<{
1848
+ isDone: boolean;
1849
+ page: MigrationDocument[];
1850
+ }>;
1851
+ get: (id: string, expectedTable?: string) => Promise<MigrationDocument | null>;
1852
+ }
1853
+ /** The context handed to a transform alongside the row. */
1854
+ interface MigrationCtx {
1855
+ db: MigrationReader;
1856
+ }
1857
+ /**
1858
+ * Transform applied to one document. Return a new document to rewrite the row,
1859
+ * or `undefined` to leave it untouched (skipped, not counted as changed). The
1860
+ * runner always preserves the original `_id` and `_creationTime`, so the
1861
+ * returned document neither needs to nor should change row identity.
1862
+ *
1863
+ * The second parameter carries a shard-scoped reader. Without it a transform
1864
+ * could only rewrite the row it was handed — enough for a backfill whose new
1865
+ * value is a pure function of the old row (`displayName = name ?? "Anonymous"`),
1866
+ * but not for the shape people actually write: read the parent, copy a field
1867
+ * down onto its children.
1868
+ *
1869
+ * May return a promise, since a cross-table read is asynchronous.
1870
+ *
1871
+ * **A shard key cannot be backfilled this way, even with a reader.** A row whose
1872
+ * shard-key field is unset does not belong to any shard, so a shard-scoped query
1873
+ * will not enumerate it; and writing the key would have to MOVE the row to a
1874
+ * different Durable Object, which a per-shard runner cannot do. Re-keying is an
1875
+ * export → transform → import, not a migration.
1876
+ */
1877
+ type MigrationTransform = (document: MigrationDocument, ctx: MigrationCtx) => MigrationDocument | Promise<MigrationDocument | undefined | void> | undefined | void;
1878
+ interface MigrationDefinition {
1879
+ /** Rows fetched and rewritten per batch. Defaults to the runner's batch size when omitted. */
1880
+ readonly batchSize?: number;
1881
+ /** Optional reverse transform, applied by `migrate down`. */
1882
+ readonly down?: MigrationTransform;
1883
+ /** Stable, unique identifier — the key per-shard run-state is tracked under. */
1884
+ readonly id: string;
1885
+ /** Table whose documents this migration iterates. */
1886
+ readonly table: string;
1887
+ /** Forward transform, applied to every row by `migrate up`. */
1888
+ readonly up: MigrationTransform;
1889
+ }
1890
+ /** A {@link MigrationDefinition} plus the codegen discovery marker. */
1891
+ interface RegisteredMigration extends MigrationDefinition {
1892
+ readonly __lunoraMigration: true;
1893
+ }
1894
+ /** Declare an online data migration. See the module docs for runtime semantics. */
1895
+ declare const defineMigration: (definition: MigrationDefinition) => RegisteredMigration;
1896
+ /**
1897
+ * A mutator declaration. `server` is authoritative; `client` is the optimistic
1898
+ * twin (optional — omit it to let the optimistic write fall through to the
1899
+ * server round-trip with no local preview). Both receive the same validated
1900
+ * `args`.
1901
+ */
1902
+ interface MutatorDefinition<Args extends ValidatorMap = ValidatorMap, ServerContext = MutationCtx, ClientTx = unknown, R = unknown> {
1903
+ /**
1904
+ * Validator for the mutator's arguments. Validated on the DO before `server`
1905
+ * runs and (when present) on the client before `client` runs, so both impls
1906
+ * see the same parsed shape. Omit for a parameterless mutator.
1907
+ */
1908
+ readonly args?: Args;
1909
+ /**
1910
+ * Optimistic client implementation. Runs in a TanStack DB transaction
1911
+ * against the local collections; its writes are applied immediately and
1912
+ * automatically rolled back / rebased as the authoritative result syncs
1913
+ * back. Pure and side-effect-free beyond the local store. Omit to skip the
1914
+ * local preview.
1915
+ */
1916
+ readonly client?: (tx: ClientTx, args: InferValidatorMap<Args>) => Promise<void> | void;
1917
+ /**
1918
+ * Owner-scope the write: names the column carrying the row owner (e.g.
1919
+ * `owner: "userId"`). Before `server` runs, the mutator requires a verified
1920
+ * identity, rejects a client-supplied owner that disagrees with it, and sets
1921
+ * the column to the verified value — so the impl reads `args[owner]` without
1922
+ * trusting the client and never repeats the check by hand.
1923
+ *
1924
+ * This replaces the "every mutator opens with `assertOwner(ctx, args.userId)`"
1925
+ * pattern, and is the write-side counterpart to an `owner`-scoped
1926
+ * {@link import("./shapes").ShapeDefinition}. Unlike a shape it takes the column
1927
+ * NAME rather than `true`: a shape is bound to one `table`, so the table's
1928
+ * `.ownedBy(field)` resolves unambiguously, whereas one mutator may write
1929
+ * several tables and has no single owning table to read it from.
1930
+ *
1931
+ * Declare the column `v.optional(...)` to leave it off the wire entirely; it is
1932
+ * injected either way.
1933
+ */
1934
+ readonly owner?: string;
1935
+ /**
1936
+ * Authoritative server implementation. Runs inside the shard DO with a full
1937
+ * {@link MutationContext} (`ctx.db` writer); its writes append to `__cdc_log`
1938
+ * and poke back to subscribers. This is the source of truth — the client
1939
+ * impl is only a prediction of it.
1940
+ */
1941
+ readonly server: (context: ServerContext, args: InferValidatorMap<Args>) => Promise<R> | R;
1942
+ }
1943
+ /**
1944
+ * A {@link MutatorDefinition} plus the codegen discovery marker and a
1945
+ * dispatch-shaped `handler` (validates `args`, then runs `server`) so the DO
1946
+ * invokes a mutator exactly like a registered procedure.
1947
+ */
1948
+ interface RegisteredMutator<Args extends ValidatorMap = ValidatorMap, ServerContext = MutationCtx, ClientTx = unknown, R = unknown> extends MutatorDefinition<Args, ServerContext, ClientTx, R> {
1949
+ readonly __lunoraMutator: true;
1950
+ /** Validate `rawArgs`, then run the authoritative `server` impl. Used by the DO push path. */
1951
+ readonly handler: (context: ServerContext, rawArgs: Record<string, unknown>) => Promise<R>;
1952
+ /**
1953
+ * Marks the dispatch kind so codegen can register the mutator in the same
1954
+ * `LUNORA_FUNCTIONS` table queries/mutations use — the DO's `handleRpc`
1955
+ * reads `kind === "mutation"` to wrap the authoritative `server` impl in the
1956
+ * shard's BEGIN/COMMIT span (all-or-nothing writes), exactly like an
1957
+ * ordinary `mutation`.
1958
+ */
1959
+ readonly kind: "mutation";
1960
+ }
1961
+ /** Declare a custom mutator. See the module docs for runtime semantics. */
1962
+ declare const defineMutator: <Args extends ValidatorMap = ValidatorMap, ServerContext = MutationCtx, ClientTx = unknown, R = unknown>(definition: MutatorDefinition<Args, ServerContext, ClientTx, R>) => RegisteredMutator<Args, ServerContext, ClientTx, R>;
1350
1963
  /** Default time-to-live for a presence row: a heartbeat keeps a member "present" for this long. */
1351
1964
  declare const DEFAULT_TTL_MS = 3e4;
1352
1965
  declare const PRESENCE_BARE_TABLE = "present";
1353
1966
  /**
1354
- * The prefixed table name the extension produces at merge time. The handlers
1355
- * read/write this name directly so they always agree with the merged schema.
1356
- */
1967
+ * The prefixed table name the extension produces at merge time. The handlers
1968
+ * read/write this name directly so they always agree with the merged schema.
1969
+ */
1357
1970
  declare const PRESENCE_TABLE: "presence_present";
1358
1971
  /**
1359
- * A single present member as returned by `listPresent`.
1360
- *
1361
- * Note: the raw client-chosen `sessionId` is deliberately NOT surfaced. It is a
1362
- * connection secret — disclosing every member's `sessionId` would let any
1363
- * subscriber enumerate them and target the heartbeat / disconnect write paths.
1364
- * A "who's here" UI needs only `userId` + awareness `data`; the caller already
1365
- * knows its own session id locally (the `usePresence` hook returns it).
1366
- */
1972
+ * A single present member as returned by `listPresent`.
1973
+ *
1974
+ * Note: the raw client-chosen `sessionId` is deliberately NOT surfaced. It is a
1975
+ * connection secret — disclosing every member's `sessionId` would let any
1976
+ * subscriber enumerate them and target the heartbeat / disconnect write paths.
1977
+ * A "who's here" UI needs only `userId` + awareness `data`; the caller already
1978
+ * knows its own session id locally (the `usePresence` hook returns it).
1979
+ */
1367
1980
  interface PresenceMember {
1368
1981
  /** Opaque awareness blob (selection, cursor, name, color…). */
1369
1982
  data?: Record<string, unknown>;
@@ -1377,41 +1990,41 @@ interface PresenceMember {
1377
1990
  /** Options for {@link definePresence}. */
1378
1991
  interface DefinePresenceOptions {
1379
1992
  /**
1380
- * Grace window (ms) before a gracefully-closed session is dropped from the
1381
- * present list. When `0` (the default), `onDisconnect` hard-deletes the
1382
- * session's row the instant its socket closes. When `> 0`, the row is
1383
- * instead aged so the read-time TTL filter hides it `disconnectGraceMs`
1384
- * from now — a reconnect with the same `sessionId` within the window
1385
- * re-heartbeats and restores full presence with no visible flicker (the
1386
- * AnyCable `presence_ttl` behaviour). Clamped to `ttlMs`.
1387
- */
1993
+ * Grace window (ms) before a gracefully-closed session is dropped from the
1994
+ * present list. When `0` (the default), `onDisconnect` hard-deletes the
1995
+ * session's row the instant its socket closes. When `> 0`, the row is
1996
+ * instead aged so the read-time TTL filter hides it `disconnectGraceMs`
1997
+ * from now — a reconnect with the same `sessionId` within the window
1998
+ * re-heartbeats and restores full presence with no visible flicker (the
1999
+ * AnyCable `presence_ttl` behaviour). Clamped to `ttlMs`.
2000
+ */
1388
2001
  disconnectGraceMs?: number;
1389
2002
  /**
1390
- * How long (ms) a heartbeat keeps a member present. `listPresent` excludes
1391
- * rows whose `lastSeen` is older than `now - ttlMs`. Defaults to 30s.
1392
- */
2003
+ * How long (ms) a heartbeat keeps a member present. `listPresent` excludes
2004
+ * rows whose `lastSeen` is older than `now - ttlMs`. Defaults to 30s.
2005
+ */
1393
2006
  ttlMs?: number;
1394
2007
  }
1395
2008
  /** The registered functions a presence component ships. */
1396
2009
  interface PresenceFunctions {
1397
2010
  /**
1398
- * Connection-lifecycle hook: the instant a client's WebSocket drops, hard-
1399
- * delete its presence row so it disappears from `listPresent` with no TTL
1400
- * lag. Targets the row by the `{ roomId, sessionId }` the client passed as
1401
- * the connection `context`, and only deletes it when the disconnecting
1402
- * VERIFIED identity owns the row (so a forged context can't evict another
1403
- * member). The TTL filter + `sweep` remain the fallback for ungraceful drops
1404
- * where no `context` was recorded.
1405
- */
2011
+ * Connection-lifecycle hook: the instant a client's WebSocket drops, hard-
2012
+ * delete its presence row so it disappears from `listPresent` with no TTL
2013
+ * lag. Targets the row by the `{ roomId, sessionId }` the client passed as
2014
+ * the connection `context`, and only deletes it when the disconnecting
2015
+ * VERIFIED identity owns the row (so a forged context can't evict another
2016
+ * member). The TTL filter + `sweep` remain the fallback for ungraceful drops
2017
+ * where no `context` was recorded.
2018
+ */
1406
2019
  disconnect: RegisteredLifecycleHook;
1407
2020
  /**
1408
- * Upsert the caller's presence row for `roomId` and stamp `lastSeen = now`.
1409
- * Keyed by `(roomId, sessionId)` — re-heartbeats patch the existing row so
1410
- * subscribers receive a single-row delta, not a churn of insert/delete. A
1411
- * heartbeat may only patch a row owned by the same identity (an existing row
1412
- * held by a different `userId` is refused with `FORBIDDEN`), so a client
1413
- * can't overwrite another member's awareness data via a guessed `sessionId`.
1414
- */
2021
+ * Upsert the caller's presence row for `roomId` and stamp `lastSeen = now`.
2022
+ * Keyed by `(roomId, sessionId)` — re-heartbeats patch the existing row so
2023
+ * subscribers receive a single-row delta, not a churn of insert/delete. A
2024
+ * heartbeat may only patch a row owned by the same identity (an existing row
2025
+ * held by a different `userId` is refused with `FORBIDDEN`), so a client
2026
+ * can't overwrite another member's awareness data via a guessed `sessionId`.
2027
+ */
1415
2028
  heartbeat: RegisteredMutation<{
1416
2029
  data: ReturnType<typeof v.optional>;
1417
2030
  roomId: ReturnType<typeof v.string>;
@@ -1420,17 +2033,17 @@ interface PresenceFunctions {
1420
2033
  lastSeen: number;
1421
2034
  }>;
1422
2035
  /**
1423
- * Live query returning the non-expired members of `roomId`, newest heartbeat
1424
- * first. Subscribe to it for a reactive "who's here" list.
1425
- */
2036
+ * Live query returning the non-expired members of `roomId`, newest heartbeat
2037
+ * first. Subscribe to it for a reactive "who's here" list.
2038
+ */
1426
2039
  listPresent: RegisteredQuery<{
1427
2040
  roomId: ReturnType<typeof v.string>;
1428
2041
  }, PresenceMember[]>;
1429
2042
  /**
1430
- * Internal mutation that hard-deletes every expired row for `roomId`. Stale
1431
- * rows already vanish from `listPresent` via the read-time TTL filter; this
1432
- * only reclaims storage. Schedule it (cron / `runAfter`) if you care.
1433
- */
2043
+ * Internal mutation that hard-deletes every expired row for `roomId`. Stale
2044
+ * rows already vanish from `listPresent` via the read-time TTL filter; this
2045
+ * only reclaims storage. Schedule it (cron / `runAfter`) if you care.
2046
+ */
1434
2047
  sweep: RegisteredMutation<{
1435
2048
  roomId: ReturnType<typeof v.string>;
1436
2049
  }, {
@@ -1444,114 +2057,114 @@ type PresenceComponent = Component<{
1444
2057
  functions: PresenceFunctions;
1445
2058
  };
1446
2059
  /**
1447
- * The presence schema extension: a single `present` table, auto-namespaced to
1448
- * `presence_present` at merge time, indexed by `(roomId, sessionId)` for the
1449
- * heartbeat upsert and by `roomId` for `listPresent`.
1450
- */
2060
+ * The presence schema extension: a single `present` table, auto-namespaced to
2061
+ * `presence_present` at merge time, indexed by `(roomId, sessionId)` for the
2062
+ * heartbeat upsert and by `roomId` for `listPresent`.
2063
+ */
1451
2064
  declare const presenceExtension: SchemaExtension<{
1452
2065
  [PRESENCE_BARE_TABLE]: ReturnType<typeof defineTable>;
1453
2066
  }>;
1454
2067
  declare const definePresence: (options?: DefinePresenceOptions) => PresenceComponent;
1455
2068
  /**
1456
- * The middlewares `protectPublic` chains, in the order they run. Every field is
1457
- * optional, so a bundle can be just a rate limit, just a captcha, or any mix —
1458
- * pass the already-constructed middlewares (e.g. `rateLimit(limiter, "signup")`
1459
- * from `@lunora/ratelimit`, `verifyTurnstileMiddleware({...})` from
1460
- * `@lunora/auth`). They are accepted as values rather than imported here so
1461
- * `@lunora/server` keeps no dependency on those packages (which depend on it).
1462
- */
2069
+ * The middlewares `protectPublic` chains, in the order they run. Every field is
2070
+ * optional, so a bundle can be just a rate limit, just a captcha, or any mix —
2071
+ * pass the already-constructed middlewares (e.g. `rateLimit(limiter, "signup")`
2072
+ * from `@lunora/ratelimit`, `verifyTurnstileMiddleware({...})` from
2073
+ * `@lunora/auth`). They are accepted as values rather than imported here so
2074
+ * `@lunora/server` keeps no dependency on those packages (which depend on it).
2075
+ */
1463
2076
  interface ProtectPublicOptions<Context> {
1464
2077
  /**
1465
- * A CAPTCHA / bot check, run after the rate limit. Placed second on purpose:
1466
- * an obvious flood is cheaper to reject with the in-memory limiter than with
1467
- * a Turnstile siteverify round-trip.
1468
- */
2078
+ * A CAPTCHA / bot check, run after the rate limit. Placed second on purpose:
2079
+ * an obvious flood is cheaper to reject with the in-memory limiter than with
2080
+ * a Turnstile siteverify round-trip.
2081
+ */
1469
2082
  captcha?: Middleware<Context, Context>;
1470
2083
  /**
1471
- * A rate limit, run first. Cheapest gate, so it sheds obvious abuse before
1472
- * any network-bound check below it runs.
1473
- */
2084
+ * A rate limit, run first. Cheapest gate, so it sheds obvious abuse before
2085
+ * any network-bound check below it runs.
2086
+ */
1474
2087
  rateLimit?: Middleware<Context, Context>;
1475
2088
  /** Extra middlewares appended after `rateLimit` and `captcha`, in order. */
1476
2089
  use?: ReadonlyArray<Middleware<Context, Context>>;
1477
2090
  }
1478
2091
  /**
1479
- * Compose the recommended public-procedure protections into a single
1480
- * `.use()`-able middleware. It is thin sugar over middleware composition — no
1481
- * new enforcement engine — chaining (in order) a rate limit, a CAPTCHA check,
1482
- * and any extra middlewares so a public mutation that creates users, sends
1483
- * mail, or consumes credits is guarded in one attachment:
1484
- *
1485
- * ```ts
1486
- * export const signUp = mutation
1487
- * .use(protectPublic({
1488
- * rateLimit: rateLimit(limiter, "signup"),
1489
- * captcha: verifyTurnstileMiddleware({ secret: env.TURNSTILE_SECRET_KEY, token: (c) => c.args.captchaToken }),
1490
- * }))
1491
- * .handler(async (ctx, args) => { ... });
1492
- * ```
1493
- *
1494
- * The bundle is context-preserving — each inner middleware leaves the context
1495
- * unchanged — so it slots into any `.use()` chain without reshaping the
1496
- * procedure context. Omitted fields are skipped; an empty bundle is a
1497
- * transparent pass-through.
1498
- */
2092
+ * Compose the recommended public-procedure protections into a single
2093
+ * `.use()`-able middleware. It is thin sugar over middleware composition — no
2094
+ * new enforcement engine — chaining (in order) a rate limit, a CAPTCHA check,
2095
+ * and any extra middlewares so a public mutation that creates users, sends
2096
+ * mail, or consumes credits is guarded in one attachment:
2097
+ *
2098
+ * ```ts
2099
+ * export const signUp = mutation
2100
+ * .use(protectPublic({
2101
+ * rateLimit: rateLimit(limiter, "signup"),
2102
+ * captcha: verifyTurnstileMiddleware({ secret: env.TURNSTILE_SECRET_KEY, token: (c) => c.args.captchaToken }),
2103
+ * }))
2104
+ * .handler(async (ctx, args) => { ... });
2105
+ * ```
2106
+ *
2107
+ * The bundle is context-preserving — each inner middleware leaves the context
2108
+ * unchanged — so it slots into any `.use()` chain without reshaping the
2109
+ * procedure context. Omitted fields are skipped; an empty bundle is a
2110
+ * transparent pass-through.
2111
+ */
1499
2112
  declare const protectPublic: <Context>(options: ProtectPublicOptions<Context>) => Middleware<Context, Context>;
1500
2113
  declare const definePolicy: <Context = unknown>(input: DefinePolicyInput<Context>) => Policy<Context>;
1501
2114
  /**
1502
- * Build a project-bound, relation-aware `definePolicy` typed against the
1503
- * generated `DataModel` (`DM`) + `Relations` (`REL`) maps. Codegen emits a
1504
- * `createPolicyDsl&lt;DataModel, Relations>()` binding into `_generated/server.ts`,
1505
- * so importing `definePolicy` from the generated module constrains `table` to a
1506
- * real table name and type-checks the `when` predicate — including Prisma-style
1507
- * relation predicates (`is`/`some`/…) the `@lunora/do` pre-resolver now resolves
1508
- * on reads. The runtime is byte-for-byte the untyped {@link definePolicy}; only
1509
- * the compile-time surface narrows, so a policy authored either way is
1510
- * discovered identically by the `rls()` chain.
1511
- */
1512
- declare const createPolicyDsl: <DM, REL extends Record<keyof DM, object>>() => <T extends keyof DM, Context = unknown>(input: TypedDefinePolicyInput<DM, REL, T, Context>) => Policy<Context>;
1513
- /**
1514
- * Declare a named permission a policy can check with `ctx.auth.can(...)`. Grant
1515
- * it to a role through `defineRole`'s `permissions`, register those roles with
1516
- * the middleware via `rls(policies, { roles })`, then check it in a policy with
1517
- * `when: ({ auth }) => auth.can(permission)`. See the `./index` JSDoc for a
1518
- * worked example.
1519
- */
2115
+ * Build a project-bound, relation-aware `definePolicy` typed against the
2116
+ * generated `DataModel` (`DM`) + `Relations` (`REL`) maps. Codegen emits a
2117
+ * `createPolicyDsl&lt;DataModel, Relations>()` binding into `_generated/server.ts`,
2118
+ * so importing `definePolicy` from the generated module constrains `table` to a
2119
+ * real table name and type-checks the `when` predicate — including Prisma-style
2120
+ * relation predicates (`is`/`some`/…) the `@lunora/do` pre-resolver now resolves
2121
+ * on reads. The runtime is byte-for-byte the untyped {@link definePolicy}; only
2122
+ * the compile-time surface narrows, so a policy authored either way is
2123
+ * discovered identically by the `rls()` chain.
2124
+ */
2125
+ declare const createPolicyDsl: <DM, REL extends Record<keyof DM, object>, Identity = Record<string, unknown>>() => <T extends keyof DM, Context = unknown>(input: TypedDefinePolicyInput<DM, REL, T, Context, Identity>) => Policy<Context>;
2126
+ /**
2127
+ * Declare a named permission a policy can check with `ctx.auth.can(...)`. Grant
2128
+ * it to a role through `defineRole`'s `permissions`, register those roles with
2129
+ * the middleware via `rls(policies, { roles })`, then check it in a policy with
2130
+ * `when: ({ auth }) => auth.can(permission)`. See the `./index` JSDoc for a
2131
+ * worked example.
2132
+ */
1520
2133
  declare const definePermission: (name: string, options?: Omit<Permission, "name">) => Permission;
1521
2134
  /**
1522
- * Collect a list of policies into the structure the `rls()` middleware
1523
- * consumes. Multiple read policies on the same table OR together (any one
1524
- * matching reveals the row); multiple write policies for the same `(table,
1525
- * op)` AND together (every one must allow). The middleware keeps them in order
1526
- * and decides — see `./middleware`.
1527
- *
1528
- * Validates against an **accidentally duplicated policy** — the same
1529
- * `(table, on)` registered with the *same* decision function (a copy-paste, or
1530
- * the same policy object spread in twice). Because multiple DISTINCT policies
1531
- * per `(table, on)` are intentional, the check keys on the `when` reference too:
1532
- * only a reference-identical `when` for the same `(table, on)` is a real
1533
- * duplicate. Throws at module load so the misconfiguration surfaces immediately
1534
- * rather than as a silently double-evaluated predicate at request time.
1535
- */
2135
+ * Collect a list of policies into the structure the `rls()` middleware
2136
+ * consumes. Multiple read policies on the same table OR together (any one
2137
+ * matching reveals the row); multiple write policies for the same `(table,
2138
+ * op)` AND together (every one must allow). The middleware keeps them in order
2139
+ * and decides — see `./middleware`.
2140
+ *
2141
+ * Validates against an **accidentally duplicated policy** — the same
2142
+ * `(table, on)` registered with the *same* decision function (a copy-paste, or
2143
+ * the same policy object spread in twice). Because multiple DISTINCT policies
2144
+ * per `(table, on)` are intentional, the check keys on the `when` reference too:
2145
+ * only a reference-identical `when` for the same `(table, on)` is a real
2146
+ * duplicate. Throws at module load so the misconfiguration surfaces immediately
2147
+ * rather than as a silently double-evaluated predicate at request time.
2148
+ */
1536
2149
  declare const definePolicies: <Context = unknown>(policies: ReadonlyArray<Policy<Context>>) => ReadonlyArray<Policy<Context>>;
1537
2150
  declare const defineRole: (name: string, options?: Omit<Role, "name">) => Role;
1538
2151
  /**
1539
- * Structural mirror of `@lunora/do`'s `QueryArgs` and `CountArgs`. The
1540
- * runtime ORM in `@lunora/do`/`@lunora/d1` reads `baseWhere` /
1541
- * `restrictsCounts` straight off these option objects, so as long as the
1542
- * fields here stay name-compatible the wrapper is portable across the two
1543
- * dialects without an inter-package dependency.
1544
- */
2152
+ * Structural mirror of `@lunora/do`'s `QueryArgs` and `CountArgs`. The
2153
+ * runtime ORM in `@lunora/do`/`@lunora/d1` reads `baseWhere` /
2154
+ * `restrictsCounts` straight off these option objects, so as long as the
2155
+ * fields here stay name-compatible the wrapper is portable across the two
2156
+ * dialects without an inter-package dependency.
2157
+ */
1545
2158
  interface QueryArgs {
1546
2159
  baseWhere?: WhereInput;
1547
2160
  cursor?: null | string;
1548
2161
  limit?: number;
1549
2162
  orderBy?: ReadonlyArray<unknown>;
1550
2163
  /**
1551
- * Per-target-table read filter the RLS wrapper attaches so a `with` relation
1552
- * is policy-filtered on its own hop (see `@lunora/do`'s `QueryArgs`). Mirrors
1553
- * the top-level read: `(table) => readBase(table).baseWhere`.
1554
- */
2164
+ * Per-target-table read filter the RLS wrapper attaches so a `with` relation
2165
+ * is policy-filtered on its own hop (see `@lunora/do`'s `QueryArgs`). Mirrors
2166
+ * the top-level read: `(table) => readBase(table).baseWhere`.
2167
+ */
1555
2168
  relationBaseWhere?: (table: string) => undefined | WhereInput;
1556
2169
  restrictsCounts?: boolean;
1557
2170
  where?: WhereInput;
@@ -1620,41 +2233,54 @@ interface TableReaderLike {
1620
2233
  numItems: number;
1621
2234
  }) => Promise<QueryPage>;
1622
2235
  take: (limit: number) => Promise<Record<string, unknown>[]>;
2236
+ withGeoIndex: (indexName: string, build: (q: unknown) => unknown) => TableReaderLike;
1623
2237
  withIndex: (indexName: string, range?: (q: unknown) => unknown) => TableReaderLike;
1624
2238
  withSearchIndex: (indexName: string, search: (q: unknown) => unknown) => TableReaderLike;
1625
2239
  }
1626
2240
  /**
1627
- * Structural projection of the runtime ORM writer. The wrapper relies only
1628
- * on these fields, so it's interchangeable between `@lunora/do`'s
1629
- * `DatabaseWriterLike` and `@lunora/d1`'s `DatabaseWriterLike`.
1630
- */
2241
+ * Structural projection of the runtime ORM writer. The wrapper relies only
2242
+ * on these fields, so it's interchangeable between `@lunora/do`'s
2243
+ * `DatabaseWriterLike` and `@lunora/d1`'s `DatabaseWriterLike`.
2244
+ */
1631
2245
  interface DatabaseWriterLike {
1632
2246
  /**
1633
- * Reduce matching rows to a scalar. The RLS wrapper AND-merges the read
1634
- * `baseWhere` into `options` so the reduction only sees policy-visible rows
1635
- * (safe: an aggregate scoped to `where` never reveals a hidden row — see
1636
- * `@lunora/do`'s `RestrictableQueryOptions`). Required: the only writer ever
1637
- * wrapped is `@lunora/do`'s `createShardCtxDb`, which always implements it.
1638
- */
2247
+ * Reduce matching rows to a scalar. The RLS wrapper AND-merges the read
2248
+ * `baseWhere` into `options` so the reduction only sees policy-visible rows
2249
+ * (safe: an aggregate scoped to `where` never reveals a hidden row — see
2250
+ * `@lunora/do`'s `RestrictableQueryOptions`). Required: the only writer ever
2251
+ * wrapped is `@lunora/do`'s `createShardCtxDb`, which always implements it.
2252
+ */
1639
2253
  aggregate: (tableName: string, options: AggregateArgs) => Promise<null | number>;
1640
2254
  count: (tableName: string, whereOrArgs?: CountArgs | WhereInput) => Promise<number>;
1641
2255
  delete: (id: string, expectedTable?: string, options?: {
1642
2256
  hard?: boolean;
1643
2257
  }) => Promise<void>;
2258
+ /** Uncapped, chunked erase of a whole table. The RLS wrapper gates each row like a single delete. */
2259
+ deleteAll?: (tableName: string, options?: {
2260
+ chunkSize?: number;
2261
+ hard?: boolean;
2262
+ }) => Promise<{
2263
+ deleted: number;
2264
+ }>;
1644
2265
  deleteMany: (ids: ReadonlyArray<string>, options?: {
1645
2266
  limit?: number;
1646
2267
  }, expectedTable?: string) => Promise<{
1647
2268
  deleted: number;
1648
2269
  }>;
2270
+ deleteWhere?: (tableName: string, where: WhereInput, options?: {
2271
+ limit?: number;
2272
+ }) => Promise<{
2273
+ deleted: number;
2274
+ }>;
1649
2275
  findFirst: (tableName: string, args?: QueryArgs) => Promise<Record<string, unknown> | null>;
1650
2276
  findFirstOrThrow: (tableName: string, args?: QueryArgs) => Promise<Record<string, unknown>>;
1651
2277
  findMany: (tableName: string, args?: QueryArgs) => Promise<QueryPage>;
1652
2278
  get: (id: string, expectedTable?: string) => Promise<Record<string, unknown> | null>;
1653
2279
  /**
1654
- * Group + reduce. Same `baseWhere` injection as `aggregate`: the per-group
1655
- * reduction is scoped to policy-visible rows, so a group count tallies only
1656
- * rows the caller may read. Required for the same reason as `aggregate`.
1657
- */
2280
+ * Group + reduce. Same `baseWhere` injection as `aggregate`: the per-group
2281
+ * reduction is scoped to policy-visible rows, so a group count tallies only
2282
+ * rows the caller may read. Required for the same reason as `aggregate`.
2283
+ */
1658
2284
  groupBy: (tableName: string, options: GroupByArgs) => Promise<ReadonlyArray<{
1659
2285
  key: Record<string, unknown>;
1660
2286
  value: null | number;
@@ -1662,19 +2288,20 @@ interface DatabaseWriterLike {
1662
2288
  insert: (tableName: string, document: Record<string, unknown>) => Promise<string>;
1663
2289
  insertMany: (tableName: string, documents: ReadonlyArray<Record<string, unknown>>, options?: {
1664
2290
  limit?: number;
1665
- }) => Promise<string[]>;
2291
+ skipDuplicates?: boolean;
2292
+ }) => Promise<(string | null)[]>;
1666
2293
  insertManyUnsafe: (tableName: string, documents: ReadonlyArray<Record<string, unknown>>, options?: {
1667
2294
  allowExplicitId?: boolean;
1668
2295
  limit?: number;
1669
2296
  }) => Promise<string[]>;
1670
2297
  /**
1671
- * Optional table-aware lookup. The underlying writer (e.g. `@lunora/do`)
1672
- * already knows the owning table of an id internally, so it can return
1673
- * `{ row, tableName }` in a single round-trip. When present, the RLS wrapper
1674
- * uses it to collapse the per-call membership-probe fan-out (1 `get` + N
1675
- * `findFirst` across every policy table) down to one lookup. Writers that
1676
- * don't implement it fall back to the probe path.
1677
- */
2298
+ * Optional table-aware lookup. The underlying writer (e.g. `@lunora/do`)
2299
+ * already knows the owning table of an id internally, so it can return
2300
+ * `{ row, tableName }` in a single round-trip. When present, the RLS wrapper
2301
+ * uses it to collapse the per-call membership-probe fan-out (1 `get` + N
2302
+ * `findFirst` across every policy table) down to one lookup. Writers that
2303
+ * don't implement it fall back to the probe path.
2304
+ */
1678
2305
  lookupById?: (id: string, expectedTable?: string) => Promise<null | {
1679
2306
  row: Record<string, unknown>;
1680
2307
  tableName: string;
@@ -1685,14 +2312,24 @@ interface DatabaseWriterLike {
1685
2312
  patch: Record<string, unknown>;
1686
2313
  }>, options?: {
1687
2314
  limit?: number;
1688
- }, expectedTable?: string) => Promise<void>;
2315
+ }, expectedTable?: string) => Promise<{
2316
+ patched: number;
2317
+ }>;
2318
+ patchWhere?: (tableName: string, args: {
2319
+ patch: Record<string, unknown>;
2320
+ where: WhereInput;
2321
+ }, options?: {
2322
+ limit?: number;
2323
+ }) => Promise<{
2324
+ patched: number;
2325
+ }>;
1689
2326
  query: (tableName: string) => TableReaderLike;
1690
2327
  /**
1691
- * Rank a row within its partition. A position is a count-of-rows-before, so
1692
- * — exactly like `count()` — it can't be trusted in an RLS-restricted
1693
- * reader: the wrapper fails it closed with `COUNT_RLS_UNSUPPORTED`. Required
1694
- * for the same reason as `aggregate`.
1695
- */
2328
+ * Rank a row within its partition. A position is a count-of-rows-before, so
2329
+ * — exactly like `count()` — it can't be trusted in an RLS-restricted
2330
+ * reader: the wrapper fails it closed with `COUNT_RLS_UNSUPPORTED`. Required
2331
+ * for the same reason as `aggregate`.
2332
+ */
1696
2333
  rank: (tableName: string, indexName: string, options: RankArgs) => Promise<null | {
1697
2334
  position: number;
1698
2335
  total: number;
@@ -1703,24 +2340,43 @@ interface DatabaseWriterLike {
1703
2340
  total: number;
1704
2341
  }>;
1705
2342
  /**
1706
- * Sorted pagination over a rank companion. The companion stores only the
1707
- * partition + sort keys + id, so an arbitrary read `baseWhere` can't be
1708
- * enforced against it (and re-filtering the fetched rows would break page
1709
- * sizing). RLS therefore fails it closed rather than leak hidden rows.
1710
- * Required for the same reason as `aggregate`.
1711
- */
2343
+ * Sorted pagination over a rank companion. The companion stores only the
2344
+ * partition + sort keys + id, so an arbitrary read `baseWhere` can't be
2345
+ * enforced against it (and re-filtering the fetched rows would break page
2346
+ * sizing). RLS therefore fails it closed rather than leak hidden rows.
2347
+ * Required for the same reason as `aggregate`.
2348
+ */
1712
2349
  rankPage: (tableName: string, indexName: string, options?: RankPageArgs) => Promise<QueryPage>;
2350
+ /**
2351
+ * Cross-shard companion to `rankPage`: same ranked slice, but each row
2352
+ * keeps its rank-key tuple for the query coordinator's k-way merge. Same
2353
+ * count-of-partition RLS hazard as `rankPage` — failed closed under a read
2354
+ * policy for the identical reason (see `rankPage` above).
2355
+ */
2356
+ rankPageRows?: (tableName: string, indexName: string, options?: RankPageArgs) => Promise<ShardRankPageResultLike>;
1713
2357
  replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
1714
2358
  restore?: (id: string, expectedTable?: string) => Promise<void>;
2359
+ /**
2360
+ * Whole-shard erase. The RLS wrapper deliberately **fails this closed** rather
2361
+ * than wrapping it — see the wrapper's `wipeShard`.
2362
+ */
2363
+ wipeShard?: (options?: {
2364
+ chunkSize?: number;
2365
+ exclude?: ReadonlyArray<string>;
2366
+ tables?: ReadonlyArray<string>;
2367
+ }) => Promise<{
2368
+ deleted: number;
2369
+ tables: Record<string, number>;
2370
+ }>;
1715
2371
  }
1716
2372
  /**
1717
- * What a procedure's `ctx.db` must structurally satisfy for the middleware
1718
- * to wrap it. We deliberately mirror `@lunora/do`'s `DatabaseWriterLike`
1719
- * rather than `@lunora/server`'s nominal `DatabaseWriter`/`DatabaseReader`:
1720
- * the runtime adapter that flows in is the `DatabaseWriterLike`-shaped one,
1721
- * and structural matching keeps this module free of an `@lunora/do`-typed
1722
- * `ctx`.
1723
- */
2373
+ * What a procedure's `ctx.db` must structurally satisfy for the middleware
2374
+ * to wrap it. We deliberately mirror `@lunora/do`'s `DatabaseWriterLike`
2375
+ * rather than `@lunora/server`'s nominal `DatabaseWriter`/`DatabaseReader`:
2376
+ * the runtime adapter that flows in is the `DatabaseWriterLike`-shaped one,
2377
+ * and structural matching keeps this module free of an `@lunora/do`-typed
2378
+ * `ctx`.
2379
+ */
1724
2380
  type RlsDatabase = DatabaseWriterLike;
1725
2381
  /** Roles list source on the context. Tolerant of older auth states. */
1726
2382
  type AuthLike = {
@@ -1735,21 +2391,183 @@ interface RlsContextIn {
1735
2391
  }
1736
2392
  declare const rls: <Context extends RlsContextIn = RlsContextIn>(policies: ReadonlyArray<Policy<Context>>, options?: RlsOptions) => Middleware<Context, Context>;
1737
2393
  /**
1738
- * Operations a storage rule can gate. `read` covers `download` / `getMetadata`
1739
- * / `getSignedUrl` / `getUrl`; `write` covers `store` / `generateUploadUrl`;
1740
- * `delete` is `delete`; `list` is a prefix listing (governed via the file
1741
- * browser / admin path, not `ctx.storage` which has no `list`).
1742
- */
2394
+ * A predicate matching **no** rows the deny decision.
2395
+ *
2396
+ * `{ OR: [] }` is a disjunction over zero branches, which the where-compiler
2397
+ * folds to a constant false. Use it (never a bare `{}`) for the unauthorized
2398
+ * branch of a shape or policy predicate:
2399
+ *
2400
+ * ```ts
2401
+ * where: (ctx, { userId }) => (ctx.auth.userId === userId ? { userId } : deny())
2402
+ * ```
2403
+ *
2404
+ * A fresh object per call, so a caller can safely spread or extend the result.
2405
+ */
2406
+ declare const deny: () => WhereInput;
2407
+ /**
2408
+ * A predicate matching **every** row — no restriction beyond whatever it is
2409
+ * AND-composed with. The honest spelling of "this branch adds no filter", where a
2410
+ * bare `{}` reads like an oversight.
2411
+ */
2412
+ declare const allowAll: () => WhereInput;
2413
+ /**
2414
+ * `true` when `where` is the vacuously-false deny predicate — i.e. an `OR` over
2415
+ * zero branches, carrying no other constraint. Used by the runtime to short-circuit
2416
+ * a denied read instead of compiling and running SQL that provably matches nothing.
2417
+ */
2418
+ declare const isDeny: (where: WhereInput) => boolean;
2419
+ /**
2420
+ * Normalize a boolean-or-predicate decision to a {@link WhereInput}.
2421
+ *
2422
+ * The authoring surfaces accept `true`/`false` as sugar — they read far better
2423
+ * than the sentinel objects in an ownership check — and every consumer downstream
2424
+ * wants a plain predicate. `undefined` means "no opinion" and maps to
2425
+ * {@link allowAll}, matching the RLS `PolicyDecision` contract.
2426
+ */
2427
+ declare const toWhereInput: (decision: WhereInput | boolean | undefined) => WhereInput;
2428
+ /**
2429
+ * One `rls()` tag's read policies for a table, paired with the role→permission
2430
+ * grants of that SAME middleware. Keeping the role map per-group is what lets a
2431
+ * policy's `auth.can(...)` resolve against its own middleware's roles — never a
2432
+ * permission registered on a different `rls()` step.
2433
+ */
2434
+ interface ScopedReadPolicies {
2435
+ readonly policies: ReadonlyArray<Policy>;
2436
+ readonly rolePermissions: ReadonlyMap<string, ReadonlySet<string>>;
2437
+ }
2438
+ /** Table-indexed read-policy groups, each scoped to the roles of the rls() middleware that declared it. */
2439
+ interface RlsReadRegistry {
2440
+ readonly byTable: ReadonlyMap<string, ReadonlyArray<ScopedReadPolicies>>;
2441
+ }
2442
+ /** The trusted, server-resolved facts a shape's RLS evaluation runs under. */
2443
+ interface ShapeReadWhereRequest {
2444
+ /** The shape ctx (the procedure context a policy `when` reads as `ctx`). */
2445
+ readonly ctx: unknown;
2446
+ /** Resolved identity claims (the socket's verified identity), or `null` when anonymous. */
2447
+ readonly identity: Record<string, unknown> | null;
2448
+ /** `true` when the schema is `.rls("required")` — gates the fail-closed branch. */
2449
+ readonly rlsRequired: boolean;
2450
+ /** Role labels the request carries (drives `auth.can(...)`). */
2451
+ readonly roles: ReadonlyArray<string>;
2452
+ /** The shape's own predicate (`where(ctx, args)`). */
2453
+ readonly shapeWhere: WhereInput;
2454
+ /** Logical table the shape replicates. */
2455
+ readonly table: string;
2456
+ /** `true` when the table is `.public()` (exempt from `.rls("required")` denial). */
2457
+ readonly tablePublic: boolean;
2458
+ /** Verified user id, or `null` when anonymous. */
2459
+ readonly userId: null | string;
2460
+ }
2461
+ /**
2462
+ * Build the read-policy registry from the registered functions (pass
2463
+ * `Object.values(LUNORA_FUNCTIONS)`). Only `on: "read"` policies are collected,
2464
+ * grouped per `rls()` middleware so each group keeps its own role→permission map
2465
+ * (a `(table, when)` pair is de-duplicated within a tag). A tag reused across
2466
+ * several procedures (a shared `const guard = rls(...)`) is folded once. This
2467
+ * mirrors the request-time `rls()` path exactly: a policy's `auth.can(...)`
2468
+ * resolves against the roles of the middleware that declared it, never a union.
2469
+ */
2470
+ declare const buildRlsReadRegistry: (functions: Iterable<unknown>) => RlsReadRegistry;
2471
+ /**
2472
+ * Compute the effective `where` a shape replicates: the table's RLS read
2473
+ * base-where AND the shape's own predicate. Returns the shape predicate
2474
+ * unchanged for a table with no read policy (a `.public()` or non-RLS table),
2475
+ * and the FALSE sentinel (replicate nothing) when a `.rls("required")` schema
2476
+ * exposes a protected, policy-less table.
2477
+ */
2478
+ declare const composeShapeReadWhere: (registry: RlsReadRegistry, request: ShapeReadWhereRequest) => WhereInput;
2479
+ /**
2480
+ * A shape declaration. `where` receives the trusted procedure context and the
2481
+ * validated client args and returns the same {@link WhereInput} shape the RLS
2482
+ * DSL uses, so the DO can AND-merge it with the table's read base-where via the
2483
+ * existing where-compiler (zero second predicate implementation).
2484
+ */
2485
+ interface ShapeDefinition<Args extends ValidatorMap = ValidatorMap, Context = QueryCtx> {
2486
+ /**
2487
+ * Validator for the client-supplied shape parameters. Validated on the DO
2488
+ * before `where` runs, so a malformed `args` envelope is rejected at the
2489
+ * subscription boundary rather than silently widening the partition. Omit
2490
+ * for a parameterless shape.
2491
+ */
2492
+ readonly args?: Args;
2493
+ /**
2494
+ * Project the replicated rows to these columns (the system columns `_id` and
2495
+ * `_creationTime` are always included). Omit to replicate every column. An
2496
+ * empty array is rejected — it would replicate no data, which is never the
2497
+ * intent.
2498
+ */
2499
+ readonly columns?: ReadonlyArray<string>;
2500
+ /**
2501
+ * Restrict this shape to rows the **subscriber owns**, without writing the
2502
+ * predicate by hand.
2503
+ *
2504
+ * `true` uses the owning column declared by `.ownedBy(field)` on the table;
2505
+ * `"field"` names the owning column here instead (for a table that has no
2506
+ * `.ownedBy()`, or a shape that scopes by a different column).
2507
+ *
2508
+ * The derived predicate is `{ [field]: ctx.auth.userId }`, AND-composed with
2509
+ * the shape's own `where` when both are present, and an anonymous subscriber is denied
2510
+ * outright. Because the value comes from the socket's verified identity rather
2511
+ * than from `args`, a client cannot ask for another user's partition at all —
2512
+ * strictly safer than accepting a `userId` arg and comparing it.
2513
+ *
2514
+ * This is the primitive for the "every shape repeats the same ownership check"
2515
+ * pattern: with it, an owner-scoped shape needs no `where` at all.
2516
+ */
2517
+ readonly owner?: string | true;
2518
+ /** Logical table this shape replicates a partition of. */
2519
+ readonly table: string;
2520
+ /**
2521
+ * Predicate selecting the rows this shape replicates. AND-composed with the
2522
+ * table's RLS read base-where on the DO. Runs server-side with a trusted
2523
+ * `ctx` (identity/auth the client can't forge) and the validated client
2524
+ * `args`; returns a {@link WhereInput} using the same operator set as the
2525
+ * SQL compiler (`eq`/`in`/`lt`/… + `AND`/`OR`/`NOT`).
2526
+ *
2527
+ * `true`/`false` are accepted as sugar for "no further restriction" / "deny" —
2528
+ * `false` compiles to the vacuously-false predicate, so a denial branch can
2529
+ * never be mistyped as the everything-matches `{}`. Optional when `owner` is
2530
+ * set; otherwise required.
2531
+ */
2532
+ readonly where?: (context: Context, args: InferValidatorMap<Args>) => WhereInput | boolean;
2533
+ }
2534
+ /** A {@link ShapeDefinition} plus the codegen discovery marker and a dispatch-shaped `compileWhere`. */
2535
+ interface RegisteredShape<Args extends ValidatorMap = ValidatorMap, Context = QueryCtx> extends ShapeDefinition<Args, Context> {
2536
+ readonly __lunoraShape: true;
2537
+ /**
2538
+ * Validate `rawArgs`, then evaluate the shape's predicate under the trusted
2539
+ * `ctx` and return its {@link WhereInput}. Used by the generated DO's
2540
+ * `resolveShape` override: `ctx` is erased to `unknown` at this dispatch
2541
+ * boundary (the DO builds it from the socket's verified identity and hands it
2542
+ * back as the concrete {@link QueryContext} the predicate expects), exactly like
2543
+ * `RegisteredLunoraFunction.handler` erases its context.
2544
+ *
2545
+ * `options.ownerField` carries the table's `.ownedBy(field)` column, which only
2546
+ * the caller (the DO, holding the schema) can look up — it is what resolves an
2547
+ * `owner: true` shape. Omitted for an `owner: "field"` or plain `where` shape.
2548
+ */
2549
+ readonly compileWhere: (context: unknown, rawArgs: Record<string, unknown>, options?: {
2550
+ ownerField?: string;
2551
+ }) => WhereInput;
2552
+ }
2553
+ /** Declare a replication shape. See the module docs for runtime semantics. */
2554
+ declare const defineShape: <Args extends ValidatorMap = ValidatorMap, Context = QueryCtx>(definition: ShapeDefinition<Args, Context>) => RegisteredShape<Args, Context>;
2555
+ /**
2556
+ * Operations a storage rule can gate. `read` covers `download` / `getMetadata`
2557
+ * / `getSignedUrl` / `getUrl`; `write` covers `store` / `generateUploadUrl`;
2558
+ * `delete` is `delete`; `list` is a prefix listing (governed via the file
2559
+ * browser / admin path, not `ctx.storage` which has no `list`).
2560
+ */
1743
2561
  type StorageOperation = "delete" | "list" | "read" | "write";
1744
2562
  /** A rule's decision. `true` allows, `false` denies, `undefined` opts this rule out. */
1745
2563
  type StorageRuleDecision = boolean | undefined;
1746
2564
  /**
1747
- * Context handed to a storage rule. `auth` mirrors RLS's `PolicyContext.auth`
1748
- * (the per-request userId / roles / identity and the `can(permission)` helper),
1749
- * so a rule reads `({ auth, key }) => key.startsWith(`user/${auth.userId}/`)`.
1750
- * `key` is the object key the operation targets (for `list`, the listing
1751
- * prefix). `ctx` is the full procedure context the middleware closed over.
1752
- */
2565
+ * Context handed to a storage rule. `auth` mirrors RLS's `PolicyContext.auth`
2566
+ * (the per-request userId / roles / identity and the `can(permission)` helper),
2567
+ * so a rule reads `({ auth, key }) => key.startsWith(`user/${auth.userId}/`)`.
2568
+ * `key` is the object key the operation targets (for `list`, the listing
2569
+ * prefix). `ctx` is the full procedure context the middleware closed over.
2570
+ */
1753
2571
  interface StorageRuleContext<Context = unknown> {
1754
2572
  readonly auth: {
1755
2573
  readonly can: (permission: Permission | string) => boolean;
@@ -1764,11 +2582,11 @@ interface StorageRuleContext<Context = unknown> {
1764
2582
  /** A registered storage rule as stored in the rule table. */
1765
2583
  interface StorageRule<Context = unknown> {
1766
2584
  /**
1767
- * Logical bucket the rule governs — matched against the accessor's bucket
1768
- * (`ctx.storage.bucketName`, or the bucket selected via `ctx.storage.bucket(name)`).
1769
- * A rule only applies to operations on its own bucket. The unnamed bucket is
1770
- * `"default"`. Also surfaced in the studio's access-rules view.
1771
- */
2585
+ * Logical bucket the rule governs — matched against the accessor's bucket
2586
+ * (`ctx.storage.bucketName`, or the bucket selected via `ctx.storage.bucket(name)`).
2587
+ * A rule only applies to operations on its own bucket. The unnamed bucket is
2588
+ * `"default"`. Also surfaced in the studio's access-rules view.
2589
+ */
1772
2590
  readonly bucket: string;
1773
2591
  readonly on: StorageOperation;
1774
2592
  /** Optional key-prefix scope; the rule only governs keys under it. Absent ⇒ the whole bucket. */
@@ -1783,27 +2601,27 @@ interface DefineStorageRuleInput<Context = unknown> {
1783
2601
  when: (context: StorageRuleContext<Context>) => StorageRuleDecision;
1784
2602
  }
1785
2603
  /**
1786
- * Options for the `storageRules(rules, options)` middleware. `roles` registers
1787
- * the role→permission grants that back `ctx.auth.can(...)`, exactly as RLS's
1788
- * `RlsOptions.roles` does — fail-closed for unlisted roles.
1789
- */
2604
+ * Options for the `storageRules(rules, options)` middleware. `roles` registers
2605
+ * the role→permission grants that back `ctx.auth.can(...)`, exactly as RLS's
2606
+ * `RlsOptions.roles` does — fail-closed for unlisted roles.
2607
+ */
1790
2608
  interface StorageRulesOptions {
1791
2609
  readonly roles?: ReadonlyArray<Role>;
1792
2610
  }
1793
2611
  declare const defineStorageRule: <Context = unknown>(input: DefineStorageRuleInput<Context>) => StorageRule<Context>;
1794
2612
  /**
1795
- * Collect a list of storage rules into the structure the `storageRules()`
1796
- * middleware consumes. Multiple rules for the same `(bucket, on)` OR together —
1797
- * any one allowing grants the operation (each rule grants a slice of the
1798
- * keyspace).
1799
- *
1800
- * Validates against an **accidentally duplicated rule** — the same
1801
- * `(bucket, on, prefix)` registered with the *same* decision function (a
1802
- * copy-paste, or the same rule object spread in twice). Because multiple
1803
- * DISTINCT rules per `(bucket, on)` are intentional, the check keys on the
1804
- * `when` reference too. Throws at module load so the misconfiguration surfaces
1805
- * immediately rather than as a silently double-evaluated predicate.
1806
- */
2613
+ * Collect a list of storage rules into the structure the `storageRules()`
2614
+ * middleware consumes. Multiple rules for the same `(bucket, on)` OR together —
2615
+ * any one allowing grants the operation (each rule grants a slice of the
2616
+ * keyspace).
2617
+ *
2618
+ * Validates against an **accidentally duplicated rule** — the same
2619
+ * `(bucket, on, prefix)` registered with the *same* decision function (a
2620
+ * copy-paste, or the same rule object spread in twice). Because multiple
2621
+ * DISTINCT rules per `(bucket, on)` are intentional, the check keys on the
2622
+ * `when` reference too. Throws at module load so the misconfiguration surfaces
2623
+ * immediately rather than as a silently double-evaluated predicate.
2624
+ */
1807
2625
  declare const defineStorageRules: <Context = unknown>(rules: ReadonlyArray<StorageRule<Context>>) => ReadonlyArray<StorageRule<Context>>;
1808
2626
  /** The minimal `ctx.auth` shape the middleware reads — a structural subset that the full AuthState satisfies. Tolerant of older auth states (mirrors RLS's `AuthLike`). */
1809
2627
  type StorageAuthLike = {
@@ -1817,4 +2635,4 @@ interface StorageContextIn {
1817
2635
  }
1818
2636
  declare const storageRules: <Context extends StorageContextIn = StorageContextIn>(rules: ReadonlyArray<StorageRule<Context>>, options?: StorageRulesOptions) => Middleware<Context, Context>;
1819
2637
  declare const VERSION = "0.0.0";
1820
- export { type ActionBuilder, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, type DataModelInit, type DefineComponentOptions, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DurableObjectJurisdiction, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, 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 InferArgs, type InferEnv, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type LunoraBuilders, LunoraEnvError, LunoraError, type LunoraErrorCode, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskStrategy, type Middleware, type MiddlewareNext, type MigrationDefinition, type MigrationDocument, type MigrationTransform, type MutationBuilder, type MutationCtx, 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 RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type Role, type Schema, type SchemaExtension, 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, asBucketStorage, bindOrm, bindTableFacade, composePluginMiddleware, createPolicyDsl, createSecrets, defineAggregateIndex, defineComponent, defineEnv, defineMigration, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, httpAction, httpRoute, httpRouter, initLunora, installPlugins, mask, mergeSchemaExtension, onConnect, onDisconnect, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules };
2638
+ export { type ActionBuilder, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, type DataModelInit, type DefineComponentOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DurableObjectJurisdiction, 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, LunoraError, 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 RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeReadWhereRequest, 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, allowAll, asBucketStorage, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineAggregateIndex, defineComponent, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput };