@lunora/server 1.0.0-alpha.7 → 1.0.0-alpha.71

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