@lunora/server 1.0.0-alpha.23 → 1.0.0-alpha.231

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 (101) hide show
  1. package/LICENSE.md +213 -0
  2. package/README.md +18 -12
  3. package/dist/data-model.d.mts +392 -170
  4. package/dist/data-model.d.ts +392 -170
  5. package/dist/data-model.mjs +0 -1
  6. package/dist/drizzle.mjs +1 -1
  7. package/dist/in-process.d.mts +101 -0
  8. package/dist/in-process.d.ts +101 -0
  9. package/dist/in-process.mjs +1 -0
  10. package/dist/index.d.mts +3831 -1565
  11. package/dist/index.d.ts +3831 -1565
  12. package/dist/index.mjs +1 -29
  13. package/dist/otel.d.mts +554 -0
  14. package/dist/otel.d.ts +554 -0
  15. package/dist/otel.mjs +1 -0
  16. package/dist/packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-9W5_vf8H.mjs +1 -0
  17. package/dist/packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs +1 -0
  18. package/dist/packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-xyn3tFOE.mjs +1 -0
  19. package/dist/packem_shared/LunoraEnvError-bkdMu_-N.mjs +4 -0
  20. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-CKKVL22B.mjs +1 -0
  21. package/dist/packem_shared/allowAll-DkRAgItV.mjs +1 -0
  22. package/dist/packem_shared/apply-output-C5wZ5EAL.mjs +1 -0
  23. package/dist/packem_shared/asBucketStorage-DoGYOjq3.mjs +1 -0
  24. package/dist/packem_shared/assertShapesDeclareReadPolicies-Bg4Ter7Q.mjs +1 -0
  25. package/dist/packem_shared/beginDeferredDeletes-DhwFBbvs.mjs +1 -0
  26. package/dist/packem_shared/beginDeferredSchedules-C7QLYr6C.mjs +1 -0
  27. package/dist/packem_shared/bindOrm-9fbLRbOb.mjs +1 -0
  28. package/dist/packem_shared/buildMaskRegistry-DpWMtalG.mjs +1 -0
  29. package/dist/packem_shared/compose-middleware-BK9FlblN.mjs +1 -0
  30. package/dist/packem_shared/composePluginMiddleware-ZtDIkbvJ.mjs +1 -0
  31. package/dist/packem_shared/context-identity-B2XYGA0B.mjs +1 -0
  32. package/dist/packem_shared/createPolicyDsl-BZa6SqLJ.mjs +1 -0
  33. package/dist/packem_shared/createSecrets-D6rLB42U.mjs +1 -0
  34. package/dist/packem_shared/createServices-IJvoqi0e.mjs +1 -0
  35. package/dist/packem_shared/defineAggregateIndex-DF8NiKHr.mjs +1 -0
  36. package/dist/packem_shared/defineIdentity-DwkNKwYa.mjs +1 -0
  37. package/dist/packem_shared/defineIdentityGuard-Bt8N65Zs.mjs +1 -0
  38. package/dist/packem_shared/defineLiveStream-5DXpg7Jy.mjs +1 -0
  39. package/dist/packem_shared/defineMigration-CXOS0Bvq.mjs +1 -0
  40. package/dist/packem_shared/defineModule-OecXWM3U.mjs +1 -0
  41. package/dist/packem_shared/defineMutator-DlLFSWbO.mjs +1 -0
  42. package/dist/packem_shared/defineRoom-CoGi-xwm.mjs +1 -0
  43. package/dist/packem_shared/defineShape-CULsDRu5.mjs +1 -0
  44. package/dist/packem_shared/defineStorageRule-Dv4nJE0H.mjs +1 -0
  45. package/dist/packem_shared/defineWebSocket-BHoy6_ox.mjs +1 -0
  46. package/dist/packem_shared/fnv1a-D3ueNTWB.mjs +1 -0
  47. package/dist/packem_shared/functions-QFoBUe9t.mjs +1 -0
  48. package/dist/packem_shared/httpAction-DplHzcUa.mjs +6 -0
  49. package/dist/packem_shared/initLunora-DH7k24N0.mjs +1 -0
  50. package/dist/packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs +1 -0
  51. package/dist/packem_shared/mask-D-jRCAhy.mjs +1 -0
  52. package/dist/packem_shared/middleware-3ySZVrpt.mjs +1 -0
  53. package/dist/packem_shared/onConnect-BLRoOpv2.mjs +1 -0
  54. package/dist/packem_shared/onQueryChange-iuLzmyPs.mjs +1 -0
  55. package/dist/packem_shared/onWhisper-CfDbFLQh.mjs +1 -0
  56. package/dist/packem_shared/platformAdmin-kczXQme8.mjs +1 -0
  57. package/dist/packem_shared/plugin-Bm9wIpiI.mjs +1 -0
  58. package/dist/packem_shared/policy-tag-V0lqFzgS.mjs +1 -0
  59. package/dist/packem_shared/protectPublic-Bi5_95aP.mjs +1 -0
  60. package/dist/packem_shared/rls-Dwj6TlY_.mjs +1 -0
  61. package/dist/packem_shared/run-middleware-BefYq7Xd.mjs +1 -0
  62. package/dist/packem_shared/serveStorageObject-B9GbK4qd.mjs +1 -0
  63. package/dist/packem_shared/storageRules-CBLioxF7.mjs +1 -0
  64. package/dist/packem_shared/types.d-B7FLdYUD.d.mts +148 -0
  65. package/dist/packem_shared/types.d-BCtjbIzl.d.ts +148 -0
  66. package/dist/packem_shared/types.d-CCjAj93e.d.mts +2902 -0
  67. package/dist/packem_shared/types.d-CCjAj93e.d.ts +2902 -0
  68. package/dist/rls/testing.d.mts +42 -34
  69. package/dist/rls/testing.d.ts +42 -34
  70. package/dist/rls/testing.mjs +1 -49
  71. package/dist/types.d.mts +2 -1274
  72. package/dist/types.d.ts +2 -1274
  73. package/dist/types.mjs +0 -31
  74. package/package.json +24 -6
  75. package/dist/packem_shared/LunoraEnvError-BGmd1Qs0.mjs +0 -187
  76. package/dist/packem_shared/LunoraError-WbxmrpxR.mjs +0 -9
  77. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-BAD0QPAg.mjs +0 -114
  78. package/dist/packem_shared/asBucketStorage-Cnxd9y2q.mjs +0 -11
  79. package/dist/packem_shared/bindOrm-Bfgl7f-Q.mjs +0 -146
  80. package/dist/packem_shared/buildRlsReadRegistry-D54vUQe4.mjs +0 -107
  81. package/dist/packem_shared/composePluginMiddleware-CcTj1_v2.mjs +0 -103
  82. package/dist/packem_shared/createPolicyDsl-By3QB4he.mjs +0 -32
  83. package/dist/packem_shared/createSecrets-DwaR2rNG.mjs +0 -58
  84. package/dist/packem_shared/defineAggregateIndex-znq4ygKQ.mjs +0 -295
  85. package/dist/packem_shared/defineIdentity-DiX4zM9x.mjs +0 -35
  86. package/dist/packem_shared/defineMigration-Hx01yIht.mjs +0 -10
  87. package/dist/packem_shared/defineMutator-EIXAWhs9.mjs +0 -11
  88. package/dist/packem_shared/defineShape-C5scNOrf.mjs +0 -18
  89. package/dist/packem_shared/defineStorageRule-B5nL4Z1P.mjs +0 -23
  90. package/dist/packem_shared/functions-Di9FUNkf.mjs +0 -5
  91. package/dist/packem_shared/httpAction-DCXoYPIk.mjs +0 -355
  92. package/dist/packem_shared/initLunora-CmMVk4i7.mjs +0 -107
  93. package/dist/packem_shared/mask-DSBtA3qp.mjs +0 -314
  94. package/dist/packem_shared/onConnect-CIPXKPyw.mjs +0 -13
  95. package/dist/packem_shared/policy-tag-DvpVH2tv.mjs +0 -13
  96. package/dist/packem_shared/protectPublic-BlcGpiRc.mjs +0 -15
  97. package/dist/packem_shared/rls-B_ZWgslr.mjs +0 -595
  98. package/dist/packem_shared/run-middleware-I6EiQfxL.mjs +0 -20
  99. package/dist/packem_shared/storageRules-6QxzDOcx.mjs +0 -88
  100. package/dist/packem_shared/types.d-BB3pjV0m.d.mts +0 -141
  101. package/dist/packem_shared/types.d-Cxl6ndhm.d.ts +0 -141
package/dist/types.d.ts CHANGED
@@ -1,1274 +1,2 @@
1
- import { ValidatorMap, InferValidatorMap, Id, Validator, Infer } from '@lunora/values';
2
- /** Map of validators describing a function's args record. Alias of `@lunora/values`' shared {@link ValidatorMap}. */
3
- type ArgsValidator = ValidatorMap;
4
- /** Infer the args object type from an {@link ArgsValidator}. Alias of `@lunora/values`' shared {@link InferValidatorMap}. */
5
- type InferArgs<A extends ArgsValidator> = InferValidatorMap<A>;
6
- /** Storage backend for a `.global()` table: D1 (default) or a Postgres/MySQL database via Cloudflare Hyperdrive (PlanetScale, Neon, …). */
7
- type GlobalBackend = "d1" | "hyperdrive";
8
- /**
9
- * Cloudflare Durable Object data-residency jurisdiction declared via
10
- * `defineSchema(...).jurisdiction("…")`. Restricts where every DO the app
11
- * reaches runs and persists data (GDPR, FedRAMP, US data residency). Widening
12
- * union — Cloudflare adds values over time.
13
- * @see https://developers.cloudflare.com/durable-objects/reference/data-location/
14
- */
15
- type DurableObjectJurisdiction = "eu" | "fedramp" | "us";
16
- /** How a table is routed at runtime. */
17
- type ShardMode = {
18
- backend?: GlobalBackend;
19
- kind: "global";
20
- } | {
21
- field: string;
22
- kind: "shardBy";
23
- } | {
24
- kind: "root";
25
- };
26
- /** Poll cadence for a sourced table — `"manual"` (pull only on an explicit trigger) or a fixed interval. */
27
- type ExternalSourceRefresh = "manual" | {
28
- everyMs: number;
29
- };
30
- /**
31
- * Delete-detection mode for external-source ingest. `"full-pull"` (default) reads
32
- * the whole tenant membership each tick and diffs it, so it observes upstream
33
- * deletes; `"incremental"` pulls only changed rows (cheap) and is blind to deletes
34
- * unless paired with a soft-delete column or a `reconcileEveryMs` full-pull sweep.
35
- */
36
- type ExternalSourceMode = "full-pull" | "incremental";
37
- /**
38
- * Config for `.source(...)` (plan 077): declares a table as **materialized from an
39
- * external Postgres/MySQL behind Cloudflare Hyperdrive**, not written by user
40
- * mutations. A system-driven poll loop reads the tenant slice and lands it in the
41
- * DO's SQLite (via the validated CDC writer), after which `defineShape` carries it
42
- * to clients unchanged. Orthogonal to `shardMode` — a sourced table almost always
43
- * also `.shardBy()`s, in which case `tenantBy` is the mandatory tenant-isolation
44
- * boundary (enforced by the `external_source_unscoped` advisor lint).
45
- */
46
- interface ExternalSourceDefinition {
47
- /** The wrangler Hyperdrive binding name the poll loop reads from. */
48
- binding: string;
49
- /** Project the materialized rows to these columns (passed to the membership diff). Omit ⇒ the full mapped document. */
50
- columns?: ReadonlyArray<string>;
51
- /** Column whose value becomes the Lunora `_id`. Defaults to `"id"`. */
52
- idColumn?: string;
53
- /** Transform an external row into the stored document body. Omit ⇒ every selected column except `idColumn` is copied. */
54
- map?: (row: Record<string, unknown>) => Record<string, unknown>;
55
- /** Delete-detection mode. Defaults to `"full-pull"`. */
56
- mode?: ExternalSourceMode;
57
- /** The full tenant-membership query, with driver-native placeholders (`$1` / `?`). `tenantBy` binds its params. */
58
- query: string;
59
- /** `"incremental"` only: run a full-pull reconcile this often to garbage-collect tombstones the incremental path can't see. */
60
- reconcileEveryMs?: number;
61
- /** Poll cadence, or `"manual"`. Omit ⇒ the runtime's size-scaled default. */
62
- refresh?: ExternalSourceRefresh;
63
- /**
64
- * **Mandatory under `.shardBy()`**: map this DO's shard key → the query's bound
65
- * params, so a tenant DO can only ever pull its own rows. An unscoped sourced +
66
- * sharded table replicates the whole multitenant table into every shard — the
67
- * `external_source_unscoped` advisor lint fails the build when this is absent.
68
- */
69
- tenantBy?: (shardKey: string) => ReadonlyArray<unknown>;
70
- }
71
- interface IndexDefinition {
72
- fields: ReadonlyArray<string>;
73
- name: string;
74
- unique?: boolean;
75
- }
76
- interface SearchIndexDefinition {
77
- field: string;
78
- filterFields?: ReadonlyArray<string>;
79
- name: string;
80
- }
81
- /** Reducer applied by an aggregate index. */
82
- type AggregateOp = "avg" | "count" | "max" | "min" | "sum";
83
- /**
84
- * Declared aggregate index — the schema-level seam that lets the runtime keep
85
- * O(1) counters/sums in step with row writes (via the trigger runner) and
86
- * route matching reads through them.
87
- *
88
- * - `on` — the table whose rows feed the aggregate.
89
- * - `op` — the reducer. `count` is field-less; the others take `field`.
90
- * - `field` — the column the reducer applies to (required for non-count ops).
91
- * - `by` — group keys. When all `where` keys in a read participate in `by`, the
92
- * reader can answer from the counter table without scanning rows.
93
- * - `where` — optional static predicate baked into the counter (only the rows
94
- * matching it ever land in the counter).
95
- */
96
- interface AggregateIndexDefinition {
97
- by?: ReadonlyArray<string>;
98
- field?: string;
99
- name: string;
100
- on: string;
101
- op: AggregateOp;
102
- where?: Record<string, unknown>;
103
- }
104
- /**
105
- * One ordering key on a `rankIndex.sortBy`: which column to sort by, and the
106
- * direction. The runtime breaks ties on the row's `_id` ASC so the order is
107
- * total and `rank()` always returns a deterministic 1-based position.
108
- */
109
- interface RankSortKey {
110
- direction: "asc" | "desc";
111
- field: string;
112
- }
113
- /**
114
- * Declared rank index — a sorted companion table per `(partition tuple, sortBy)`
115
- * maintained by triggers, so:
116
- *
117
- * - `rank(row)` returns the row's 1-based position within its partition under
118
- * the declared `sortBy` order, plus the partition's total row count, in
119
- * O(log n) lookups against the SQLite btree on the companion table.
120
- * - `rankPage({ where, take, from })` walks the same companion table to return
121
- * rows in the declared order — a sorted-pagination accelerator.
122
- *
123
- * Fields mirror `AggregateIndexDefinition`:
124
- *
125
- * - `on` — the source table whose rows feed the rank.
126
- * - `sortBy` — ordered keys driving the rank. Required.
127
- * - `partitionBy` — columns that scope each rank context (e.g. `["channelId"]`
128
- * to rank within a channel). Omitted ⇒ one global rank across the table.
129
- * - `where` — static predicate baked into the index; only matching rows enter.
130
- */
131
- interface RankIndexDefinition {
132
- name: string;
133
- on: string;
134
- partitionBy?: ReadonlyArray<string>;
135
- sortBy: ReadonlyArray<RankSortKey>;
136
- where?: Record<string, unknown>;
137
- }
138
- /** FK behavior when a referenced parent row is deleted (mirrors SQL `ON DELETE`). */
139
- type OnDeleteAction = "cascade" | "restrict" | "set null";
140
- /**
141
- * A declared relation between two tables, recorded by `.relations((r) => …)`.
142
- *
143
- * - `one` (many-to-one): the FK column `field` lives on **this** table and
144
- * points at `table`.`references` (default `_id`). Loads a single doc.
145
- * - `many` (one-to-many): the FK column `field` lives on the **target** table
146
- * and points back at this table's `references` (default `_id`). Loads an array.
147
- *
148
- * `onDelete` is meaningful only on `one`: it is the action applied to the
149
- * holder rows when the referenced parent row is deleted.
150
- */
151
- interface RelationDefinition {
152
- field: string;
153
- kind: "many" | "one";
154
- onDelete?: OnDeleteAction;
155
- references: string;
156
- table: string;
157
- }
158
- /** Distance metric used by a Vectorize index. */
159
- type VectorMetric = "cosine" | "dot-product" | "euclidean";
160
- /**
161
- * Bring-your-own-embedder: a user-supplied fn turning a source string into a
162
- * numeric vector. The runtime calls it at upsert/query time so the framework
163
- * never couples to a single embedding provider.
164
- */
165
- type VectorEmbedder = (input: string) => Promise<ReadonlyArray<number>> | ReadonlyArray<number>;
166
- /**
167
- * Vector index declared inline on a table via `.vectorize(field, opts)`
168
- * (DSL Shape A). The source is always a single column on the owning table.
169
- */
170
- interface TableVectorIndex {
171
- dimensions: number;
172
- embed: VectorEmbedder;
173
- field: string;
174
- metadata?: ReadonlyArray<string>;
175
- metric: VectorMetric;
176
- name: string;
177
- }
178
- interface TableDefinition<Shape extends Record<string, Validator> = Record<string, Validator>> {
179
- /**
180
- * Aggregate indexes declared via `.aggregateIndex(name, opts)`. The runtime
181
- * maintains a counter row per `by` group via the trigger seam, so reads
182
- * whose `where` keys all participate in the index's `by` set are answered
183
- * without scanning the underlying table.
184
- */
185
- aggregateIndexes: ReadonlyArray<AggregateIndexDefinition>;
186
- /**
187
- * Set by `.source(...)` (named `externalSource`, not `source`, so the data
188
- * field doesn't collide with the fluent `.source()` builder method — same
189
- * convention as `shardBy()`/`shardMode`). When present, the table is
190
- * materialized from an external Hyperdrive-backed database by a system poll
191
- * loop rather than user mutations. Implies `isExternallyManaged`.
192
- */
193
- externalSource?: ExternalSourceDefinition;
194
- indexes: ReadonlyArray<IndexDefinition>;
195
- /**
196
- * `true` when `.externallyManaged()` was called — the table's rows are
197
- * written outside Lunora's discoverable insert path (an adapter, a
198
- * migration, or framework middleware), e.g. `@lunora/auth`'s better-auth
199
- * tables or `@lunora/ratelimit`'s store. Advisor insert-path lints
200
- * (`table_without_insert`) skip such tables instead of flagging the absent
201
- * `ctx.db.insert(...)`.
202
- */
203
- isExternallyManaged?: boolean;
204
- /**
205
- * `true` when `.public()` was called — the table opts OUT of secure-by-default
206
- * RLS. Under a schema marked `.rls("required")`, every table is protected (the
207
- * DO/D1 write path denies raw, non-RLS `ctx.db` access) UNLESS it is `isPublic`.
208
- * Has no effect when the schema does not require RLS.
209
- */
210
- isPublic?: boolean;
211
- /**
212
- * Rank indexes declared via `.rankIndex(name, opts)`. The runtime maintains
213
- * a sorted companion table per declared rank with a btree on
214
- * `(partition, sortBy)` so `rank(row)` returns the row's 1-based position
215
- * within its partition in O(log n), and `rankPage()` walks the index for
216
- * sorted pagination.
217
- */
218
- rankIndexes: ReadonlyArray<RankIndexDefinition>;
219
- /**
220
- * Declared relations keyed by accessor name; empty unless `.relations()`
221
- * was called. Named `relationMap` (not `relations`) so the fluent
222
- * `.relations((r) => …)` builder method doesn't collide with this field.
223
- */
224
- relationMap: Record<string, RelationDefinition>;
225
- searchIndexes: ReadonlyArray<SearchIndexDefinition>;
226
- shape: Shape;
227
- shardMode: ShardMode;
228
- /**
229
- * Set by `.softDelete()` (named `softDeleteMode`, not `softDelete`, so the
230
- * data field doesn't collide with the fluent `.softDelete()` builder method —
231
- * same convention as `shardBy()`/`shardMode`). When present, the table carries
232
- * a nullable timestamp column (`field`, default `deletedAt`):
233
- * `ctx.db.&lt;table>.delete()` flips it instead of physically removing the row,
234
- * and **list reads** (`findMany`/`findFirst`/`query()`/`count`/`aggregate`/
235
- * relation loads) hide rows whose `field` is set unless
236
- * `includeDeleted: true` is passed. By-id `get`/`patch`/`replace` and
237
- * `restore` are unaffected. Absent ⇒ deletes are physical, as before.
238
- */
239
- softDeleteMode?: {
240
- field: string;
241
- };
242
- /**
243
- * Declared lifecycle triggers keyed by accessor name; empty unless
244
- * `.triggers()` was called. Named `triggerMap` (not `triggers`) so the
245
- * fluent `.triggers((t) => …)` builder method doesn't collide with this
246
- * field — same reasoning as {@link TableDefinition.relationMap}.
247
- */
248
- triggerMap: Record<string, TriggerDefinition>;
249
- vectorIndexes: ReadonlyArray<TableVectorIndex>;
250
- }
251
- /**
252
- * Standalone vector index declared via `defineVectorIndex(...)` (DSL Shape B).
253
- * Unlike {@link TableVectorIndex}, the source is a `select` function so it can
254
- * derive the embedded text from any computation (e.g. `title + body`).
255
- */
256
- interface VectorIndexDefinition {
257
- readonly dimensions: number;
258
- readonly embed: VectorEmbedder;
259
- readonly kind: "vectorIndex";
260
- readonly metadata?: (row: Record<string, unknown>) => Record<string, unknown>;
261
- readonly metric: VectorMetric;
262
- readonly select: (row: Record<string, unknown>) => string;
263
- readonly table: string;
264
- }
265
- interface Schema<T extends Record<string, TableDefinition> = Record<string, TableDefinition>> {
266
- /**
267
- * Secure-by-default RLS mode declared via `.rls("required")`. When
268
- * `"required"`, every table is protected: the DO/D1 write path denies raw
269
- * (non-RLS-wrapped) `ctx.db` access at runtime, so a procedure that forgets
270
- * `.use(rls(...))` fails closed instead of silently exposing the table. A
271
- * table opts out with `.public()` (→ {@link TableDefinition.isPublic}).
272
- * Absent ⇒ legacy opt-in behavior (RLS only where a policy is applied).
273
- */
274
- readonly rlsMode?: "required";
275
- readonly tables: T;
276
- readonly vectorIndexes: Record<string, VectorIndexDefinition>;
277
- }
278
- type FunctionKind = "action" | "mutation" | "query" | "stream";
279
- /**
280
- * Call surface a function is exposed on. `public` functions are reachable from
281
- * clients via the generated `api`; `internal` functions are reachable only
282
- * server-to-server (`ctx.runQuery`/`runMutation`/`runAction`) and are rejected
283
- * by the DO's external RPC path. Absence is treated as `public` for
284
- * back-compat with functions registered before visibility existed.
285
- */
286
- type FunctionVisibility = "internal" | "public";
287
- /**
288
- * x402 payment tag attached by the `.x402({ price })` builder modifier. Marks a
289
- * public procedure as paid: the origin worker answers an unpaid client RPC with
290
- * HTTP 402, verifies + settles the payment, and only then dispatches to the
291
- * shard. The runtime reads only `price` from here — the network, recipient, and
292
- * facilitator live in the worker-level x402 charge config, so `@lunora/runtime`
293
- * never has to import `@lunora/x402` (and its viem/solana deps).
294
- */
295
- interface X402ProcedureConfig {
296
- /**
297
- * USD-denominated price: a number of dollars (`0.01`) or a decimal string
298
- * (`"0.01"`, or the `"$0.01"` shorthand). Resolved to the network
299
- * stablecoin's base units (USDC has 6 decimals) at challenge time.
300
- */
301
- readonly price: number | string;
302
- }
303
- interface RegisteredFunction<A extends ArgsValidator, R, Kind extends FunctionKind> {
304
- readonly args: A;
305
- readonly handler: (context: unknown, args: InferArgs<A>) => Promise<R> | R;
306
- readonly kind: Kind;
307
- /**
308
- * Set on connection-lifecycle hooks (`onConnect` / `onDisconnect`).
309
- * Marks the function for the generated `LUNORA_LIFECYCLE_HOOKS` manifest so the
310
- * DO dispatches it on socket connect/disconnect rather than via a client RPC.
311
- * Absent on ordinary registrations.
312
- */
313
- readonly lifecycle?: LifecycleEventKind;
314
- readonly visibility?: FunctionVisibility;
315
- /**
316
- * Set by the `.x402({ price })` builder modifier. Marks the procedure as paid
317
- * so the origin worker gates it behind an x402 402-challenge before dispatch.
318
- * Absent on unpaid functions.
319
- */
320
- readonly x402?: X402ProcedureConfig;
321
- }
322
- type RegisteredQuery<A extends ArgsValidator, R> = RegisteredFunction<A, R, "query">;
323
- type RegisteredMutation<A extends ArgsValidator, R> = RegisteredFunction<A, R, "mutation">;
324
- type RegisteredAction<A extends ArgsValidator, R> = RegisteredFunction<A, R, "action">;
325
- /** Which side of the WebSocket lifecycle a hook fires on. */
326
- type LifecycleEventKind = "connect" | "disconnect";
327
- /**
328
- * The event a connection-lifecycle hook receives as its second argument. It is
329
- * the JSON-serializable payload the DO forwards on socket connect/disconnect;
330
- * the verified caller identity is also reflected on `ctx.auth` (the hook runs
331
- * under the connecting user via `resolveIdentity`).
332
- */
333
- interface LifecycleEvent {
334
- /** Stable per-socket id, minted at upgrade and replayed verbatim on disconnect. */
335
- readonly connectionId: string;
336
- /** App-supplied connection context from the client `connect` envelope (e.g. `{ roomId, sessionId }`). */
337
- readonly context?: Record<string, unknown>;
338
- /** The shard this socket is bound to. */
339
- readonly shardKey: string;
340
- /** Verified user id resolved at upgrade, or `null` for an anonymous socket. */
341
- readonly userId: string | null;
342
- }
343
- /**
344
- * A registered connection-lifecycle hook — an internal mutation tagged with the
345
- * lifecycle side it fires on. Produced by `onConnect` / `onDisconnect`.
346
- */
347
- type RegisteredLifecycleHook = RegisteredFunction<Record<string, never>, void, "mutation"> & {
348
- readonly lifecycle: LifecycleEventKind;
349
- };
350
- /**
351
- * A streaming query registration. Unlike {@link RegisteredFunction} the handler
352
- * returns an `AsyncIterable&lt;R>` synchronously (it does NOT `Promise&lt;R>`); the
353
- * runtime drives it frame by frame and forwards each chunk to the caller. The
354
- * third `signal` argument is wired to the caller's cancel signal so the handler
355
- * can stop early — break out of the loop or check `signal.aborted` between
356
- * yields.
357
- */
358
- interface RegisteredStream<A extends ArgsValidator, R> {
359
- readonly args: A;
360
- readonly handler: (context: unknown, args: InferArgs<A>, signal: AbortSignal) => AsyncIterable<R>;
361
- readonly kind: "stream";
362
- readonly visibility?: FunctionVisibility;
363
- }
364
- /** The system tables `ctx.db.system` can read. */
365
- type SystemTableName = "_scheduled_functions" | "_storage";
366
- /**
367
- * A pending scheduled invocation as surfaced by the `_scheduled_functions`
368
- * system table. Mirrors {@link ScheduledJob} (the `ctx.scheduler` view); the
369
- * separate name keeps the system-table read surface self-describing.
370
- */
371
- interface ScheduledFunctionDoc {
372
- /** Function arguments the job will be dispatched with. */
373
- args: Record<string, unknown>;
374
- /** Number of dispatch attempts already made (absent until the first retry). */
375
- attempts?: number;
376
- /** When the job was enqueued (epoch ms). */
377
- enqueuedAt: number;
378
- /** Fully-qualified path of the function to invoke. */
379
- functionPath: string;
380
- /** The job's id (the `_scheduled_functions` row id). */
381
- id: string;
382
- /** When the job is scheduled to fire (epoch ms). */
383
- scheduledFor: number;
384
- /** Routing hint forwarded so dispatch lands on the right shard. */
385
- shardKey?: string;
386
- }
387
- /** Maps each system table name to the document shape its reads return. */
388
- interface SystemDocMap {
389
- _scheduled_functions: ScheduledFunctionDoc;
390
- _storage: StorageMetadata;
391
- }
392
- /** Document type for a given system table name. */
393
- type SystemDoc<T extends SystemTableName> = SystemDocMap[T];
394
- /** Terminal returned by {@link SystemDatabaseReader.query}; only `.collect()` is supported. */
395
- interface SystemQuery<T extends SystemTableName> {
396
- /** Resolve the full list of rows in the backing source. */
397
- collect: () => Promise<SystemDoc<T>[]>;
398
- }
399
- /**
400
- * Read-only reader over Lunora's system tables (`_scheduled_functions`,
401
- * `_storage`), exposed as `ctx.db.system`. Mirrors Convex's `ctx.db.system`.
402
- *
403
- * **Best-effort and eventually consistent.** Unlike `ctx.db.&lt;table>` — which
404
- * reads the shard's transactional SQLite snapshot — the data behind these tables
405
- * lives OUTSIDE the shard (scheduled functions in the `SchedulerDO`, storage
406
- * objects in R2). Every `collect()` / `get()` reaches across to that source.
407
- *
408
- * It is **not part of the mutation transaction snapshot** (no OCC guard, no
409
- * subscription dependency recorded — reading it inside a mutation does not pin
410
- * it), and results are **eventually consistent** with writes a mutation just
411
- * made (e.g. a freshly scheduled job may not appear yet).
412
- *
413
- * Read-only by design: mutate scheduled jobs via `ctx.scheduler`, storage
414
- * objects via `ctx.storage`.
415
- */
416
- interface SystemDatabaseReader {
417
- /**
418
- * Resolve a single system-table row by id, or `null` when absent.
419
- * (`_scheduled_functions` → job id; `_storage` → object key.)
420
- */
421
- get: <T extends SystemTableName>(table: T, id: string) => Promise<SystemDoc<T> | null>;
422
- /**
423
- * Begin a read over a system table; call `.collect()` to resolve the full
424
- * list. No filtering, indexing, or pagination — the backing source is remote
425
- * and the surface stays deliberately minimal.
426
- */
427
- query: <T extends SystemTableName>(table: T) => SystemQuery<T>;
428
- }
429
- /**
430
- * Read-only handle bound to a table. Used by `query`/`mutation`/`action`. The
431
- * actual SQL implementation lives in `@lunora/do`; these are signatures only.
432
- */
433
- interface DatabaseReader {
434
- get: <T extends string>(id: Id<T>) => Promise<Record<string, unknown> | null>;
435
- /**
436
- * Validate an untrusted `id` string against the structural shape of an id
437
- * for `tableName`, returning the branded {@link Id} when it is well-formed
438
- * and `null` otherwise. Pure structural validation — it never reads the
439
- * database, so a structurally valid id for a row that doesn't exist still
440
- * returns the branded id (mirrors Convex's `db.normalizeId`).
441
- */
442
- normalizeId: <T extends string>(tableName: T, id: string) => Id<T> | null;
443
- query: (tableName: string) => TableReader;
444
- /**
445
- * Best-effort, read-only reader over Lunora's system tables
446
- * (`_scheduled_functions`, `_storage`). Eventually consistent and **not**
447
- * part of the transaction snapshot — see {@link SystemDatabaseReader}.
448
- */
449
- readonly system: SystemDatabaseReader;
450
- }
451
- /** Options for {@link TableReader.paginate} — Convex-compatible page request. */
452
- interface PaginationOptions {
453
- /** Opaque cursor from the prior page's `continueCursor`; `null`/omitted starts at the first page. */
454
- cursor?: null | string;
455
- /**
456
- * Optional inclusive upper bound for reactive pagination. When supplied the
457
- * page covers the fixed half-open range `(cursor, endCursor]` (ignoring
458
- * `numItems`): every row strictly after `cursor` up to and including the
459
- * boundary row `endCursor` encodes. The page's `isDone` is `true` and its
460
- * `continueCursor` echoes `endCursor`, so the next page keeps starting where
461
- * this one ends even as rows are inserted/deleted inside the range. Omit (or
462
- * pass `null`) for the legacy "first `numItems` after `cursor`" behaviour.
463
- */
464
- endCursor?: null | string;
465
- /** Maximum rows to return for this page. */
466
- numItems: number;
467
- }
468
- /** One page of a keyset-paginated query. */
469
- interface PaginationResult<T = Record<string, unknown>> {
470
- /** Cursor to pass back for the next page, or `null` once `isDone`. */
471
- continueCursor: null | string;
472
- /** `true` when this page is the last one. */
473
- isDone: boolean;
474
- page: T[];
475
- /**
476
- * Reactive-pagination only: the midpoint cursor of a bounded
477
- * `(cursor, endCursor]` page, used by the client to split an over-grown page
478
- * into two adjacent ranges. Absent on legacy (open-ended) pages.
479
- */
480
- splitCursor?: null | string;
481
- }
482
- /**
483
- * The fluent `ctx.db.query(table)` reader. Generic over the document type
484
- * `Row` so the generated `ctx.db` can bind it to `Doc&lt;table>` (the chain and
485
- * every terminal then resolve typed rows — no `as unknown as Doc&lt;...>` casts).
486
- * Defaults to the untyped `Record&lt;string, unknown>` shape for the base
487
- * (schema-agnostic) `@lunora/server` reader.
488
- */
489
- interface TableReader<Row = Record<string, unknown>> {
490
- collect: () => Promise<Row[]>;
491
- filter: (predicate: (document: Row) => boolean) => TableReader<Row>;
492
- first: () => Promise<Row | null>;
493
- /**
494
- * Set the result order. Orders by the active `.withIndex()` (or by
495
- * `_creationTime` when none is staged), `"asc"` by default; `"desc"`
496
- * reverses it. Composes with `.withIndex()`, `.filter()`, and every
497
- * terminal (`collect`/`first`/`take`/`paginate`/`unique`). Mirrors Convex's
498
- * `.order("asc" | "desc")`.
499
- */
500
- order: (direction: "asc" | "desc") => TableReader<Row>;
501
- paginate: (options: PaginationOptions) => Promise<PaginationResult<Row>>;
502
- take: (limit: number) => Promise<Row[]>;
503
- /**
504
- * Return the single matching document. Returns `null` when nothing matches
505
- * and throws when more than one row matches. Mirrors Convex's `.unique()`.
506
- */
507
- unique: () => Promise<Row | null>;
508
- withIndex: (indexName: string, range?: (q: IndexRangeBuilder) => IndexRangeBuilder) => TableReader<Row>;
509
- /**
510
- * Restrict the query to a declared `.searchIndex()`. The builder's
511
- * `.search(field, query)` runs a full-text match against the index's
512
- * searchable field; `.eq(field, value)` narrows by a declared filter
513
- * field. Results come back ordered by relevance — pair with `.take(n)`
514
- * (`.paginate()` is not supported on a search query).
515
- */
516
- withSearchIndex: (indexName: string, search: (q: SearchFilterBuilder) => SearchFilterBuilder) => TableReader<Row>;
517
- }
518
- interface IndexRangeBuilder {
519
- eq: (field: string, value: unknown) => IndexRangeBuilder;
520
- gt: (field: string, value: unknown) => IndexRangeBuilder;
521
- gte: (field: string, value: unknown) => IndexRangeBuilder;
522
- lt: (field: string, value: unknown) => IndexRangeBuilder;
523
- lte: (field: string, value: unknown) => IndexRangeBuilder;
524
- }
525
- /** Builder passed to {@link TableReader.withSearchIndex}; mirrors Convex's search query. */
526
- interface SearchFilterBuilder {
527
- /** Narrow by a declared filter field (exact match). */
528
- eq: (field: string, value: unknown) => SearchFilterBuilder;
529
- /** Full-text match `query` against the index's searchable `field`. Call exactly once. */
530
- search: (field: string, query: string) => SearchFilterBuilder;
531
- }
532
- /**
533
- * Options shared by the batch-write methods (`insertMany`/`deleteMany`/
534
- * `patchMany`) — a per-call payload cap. The default cap (500) rejects an
535
- * oversized call up front so an accidental O(n²) or a payload past the Durable
536
- * Object request limit fails loudly instead of degrading the mutation. Callers
537
- * with larger sets should chunk their own loop or raise `limit`.
538
- */
539
- interface BatchWriteOptions {
540
- /** Reject the call when the batch size exceeds this value (default 500). */
541
- limit?: number;
542
- }
543
- /** Options accepted by {@link DatabaseWriter.insertMany} and the per-table facade. */
544
- interface InsertManyOptions extends BatchWriteOptions {
545
- /**
546
- * When `true`, a UNIQUE-constraint breach for a row resolves to `null`
547
- * instead of throwing — the rest of the batch is still inserted. Skipped rows
548
- * keep their input-order slot with `null` in the returned array. Mirrors
549
- * better-drizzle's `createMany({ skipDuplicates: true })`.
550
- */
551
- skipDuplicates?: boolean;
552
- }
553
- interface DatabaseWriter extends DatabaseReader {
554
- delete: <T extends string>(id: Id<T>) => Promise<void>;
555
- /**
556
- * Delete many rows by id in one call. Each id is deleted through the full
557
- * single-row pipeline (triggers + per-row RLS). The returned `deleted` is the
558
- * number of ids **requested**, not the rows actually removed — an unknown or
559
- * duplicated id is a silent no-op.
560
- *
561
- * **Atomic within a mutation:** the DO wraps a mutation's dispatch in a
562
- * BEGIN/COMMIT span, so a mid-batch failure (a later RLS denial or handler
563
- * error) rolls back the whole mutation. (In an action there is no transaction
564
- * span, so the prior deletes persist; the in-memory test harness mirrors the span.)
565
- */
566
- deleteMany: <T extends string>(ids: ReadonlyArray<Id<T>>, options?: BatchWriteOptions) => Promise<{
567
- deleted: number;
568
- }>;
569
- /**
570
- * Delete every row matching `where` in one call. Matching rows are resolved
571
- * first, then each row is deleted through the single-row delete pipeline
572
- * (triggers, companion sync, CDC, broadcast) so reactive subscriptions and
573
- * search/aggregate companions stay correct.
574
- *
575
- * **Atomic within a mutation:** the DO wraps a mutation's dispatch in a
576
- * BEGIN/COMMIT span, so a mid-batch failure rolls back the whole mutation.
577
- */
578
- deleteWhere: (tableName: string, where: Record<string, unknown>, options?: BatchWriteOptions) => Promise<{
579
- deleted: number;
580
- }>;
581
- /**
582
- * Insert a document, returning its server id.
583
- *
584
- * Pass `options.clientId` (a UUID) to key the row yourself — for an
585
- * optimistic client that needs the persisted row to match the key it
586
- * already rendered. It's validated for shape and still subject to the
587
- * primary-key uniqueness constraint; omit it and the server mints the id.
588
- */
589
- insert: <T extends string>(tableName: T, document: Record<string, unknown>, options?: {
590
- clientId?: string;
591
- }) => Promise<Id<T>>;
592
- /**
593
- * Insert many documents into one table in a single call, returning the
594
- * minted ids in input order. Equivalent to a per-row `insert()` loop — each
595
- * row gets defaults, validators, triggers, and a per-row RLS check — but the
596
- * caller pays one round-trip instead of N.
597
- *
598
- * Pass `{ skipDuplicates: true }` to turn UNIQUE-constraint breaches into
599
- * `null` results for that row instead of failing the whole batch; the rest of
600
- * the batch is still inserted and order is preserved.
601
- *
602
- * **Atomic within a mutation:** the DO wraps a mutation's dispatch in a
603
- * BEGIN/COMMIT span, so a mid-batch failure (an invalid or RLS-denied row)
604
- * rolls back the whole mutation. (In an action there is no transaction span,
605
- * so the prior inserts persist; the in-memory test harness mirrors the span.)
606
- */
607
- insertMany: {
608
- <T extends string>(tableName: T, documents: ReadonlyArray<Record<string, unknown>>, options: BatchWriteOptions & {
609
- skipDuplicates: true;
610
- }): Promise<(Id<T> | null)[]>;
611
- <T extends string>(tableName: T, documents: ReadonlyArray<Record<string, unknown>>, options?: InsertManyOptions): Promise<Id<T>[]>;
612
- };
613
- /**
614
- * **Trusted** bulk insert: one multi-row `INSERT` that **skips per-row
615
- * `.check()` validators and before/after triggers** for throughput on data you
616
- * control (seed, migration, admin import). Defaults, ids, and every companion
617
- * (search/aggregate/rank/CDC + live subscriptions) are still applied, so reads
618
- * stay correct.
619
- *
620
- * It is **"unsafe" only in that it bypasses the validation/trigger pipeline** —
621
- * RLS is **not** bypassed: secure-by-default and the table's insert policy still
622
- * apply (the framework ships no RLS-bypassing writer). Pass `allowExplicitId` to
623
- * preserve a supplied `_id` (import). Use only for data you trust; prefer
624
- * `insertMany` for anything user-supplied.
625
- */
626
- insertManyUnsafe: <T extends string>(tableName: T, documents: ReadonlyArray<Record<string, unknown>>, options?: BatchWriteOptions & {
627
- allowExplicitId?: boolean;
628
- }) => Promise<Id<T>[]>;
629
- patch: <T extends string>(id: Id<T>, patch: Record<string, unknown>) => Promise<void>;
630
- /**
631
- * Patch many rows by id in one call. Each `{ id, patch }` is applied like a
632
- * single `patch()` (per-row triggers + RLS). Returns the number of rows
633
- * actually patched.
634
- *
635
- * **Atomic within a mutation:** the DO wraps a mutation's dispatch in a
636
- * BEGIN/COMMIT span, so a mid-batch failure rolls back the whole mutation.
637
- * (In an action there is no transaction span, so the prior patches persist;
638
- * the in-memory test harness mirrors the span.)
639
- */
640
- patchMany: <T extends string>(patches: ReadonlyArray<{
641
- id: Id<T>;
642
- patch: Record<string, unknown>;
643
- }>, options?: BatchWriteOptions) => Promise<{
644
- patched: number;
645
- }>;
646
- /**
647
- * Patch every row matching `where` with the same `patch` in one call. The
648
- * matching rows are resolved first, then each row is updated through the
649
- * single-row patch pipeline (OCC, triggers, companion sync, CDC, broadcast)
650
- * so reactive subscriptions and search/aggregate companions stay correct.
651
- *
652
- * **Atomic within a mutation:** the DO wraps a mutation's dispatch in a
653
- * BEGIN/COMMIT span, so a mid-batch failure rolls back the whole mutation.
654
- */
655
- patchWhere: (tableName: string, args: {
656
- patch: Record<string, unknown>;
657
- where: Record<string, unknown>;
658
- }, options?: BatchWriteOptions) => Promise<{
659
- patched: number;
660
- }>;
661
- replace: <T extends string>(id: Id<T>, document: Record<string, unknown>) => Promise<void>;
662
- }
663
- /** Authenticated identity surfaced into every context. */
664
- interface AuthState {
665
- getIdentity: () => Promise<Record<string, unknown> | null>;
666
- readonly userId: string | null;
667
- }
668
- /**
669
- * A pending scheduled invocation as surfaced by {@link Scheduler.list} /
670
- * {@link Scheduler.get}. A clean public mirror of `@lunora/scheduler`'s internal
671
- * `ScheduleRecord` — re-declared here so the public ctx surface carries no
672
- * dependency on the scheduler package's internal types.
673
- */
674
- interface ScheduledJob {
675
- args: Record<string, unknown>;
676
- /** Number of dispatch attempts already made (absent until the first retry). */
677
- attempts?: number;
678
- /** When the job was enqueued (epoch ms). */
679
- enqueuedAt: number;
680
- functionPath: string;
681
- id: string;
682
- /** When the job is scheduled to fire (epoch ms). */
683
- scheduledFor: number;
684
- /** Routing hint forwarded so dispatch lands on the right shard. */
685
- shardKey?: string;
686
- }
687
- interface Scheduler {
688
- /** Cancel a pending job by id. `cancelled` is `false` when no such job exists. */
689
- cancel: (id: string) => Promise<{
690
- cancelled: boolean;
691
- }>;
692
- /** Resolve a single pending job by id, or `null` when absent. */
693
- get: (id: string) => Promise<ScheduledJob | null>;
694
- /** List all pending scheduled jobs. */
695
- list: () => Promise<ScheduledJob[]>;
696
- runAfter: (delayMs: number, functionPath: string, args?: Record<string, unknown>) => Promise<string>;
697
- runAt: (timestampMs: number, functionPath: string, args?: Record<string, unknown>) => Promise<string>;
698
- }
699
- /**
700
- * A workflow instance's lifecycle status. Clean public mirror of
701
- * `@lunora/workflow`'s `WorkflowInstanceStatus` (itself a mirror of Cloudflare's
702
- * `WorkflowInstanceStatus`) — re-declared here so the ctx surface carries no
703
- * dependency on the workflow package, exactly as {@link Scheduler} avoids a
704
- * dependency on `@lunora/scheduler`.
705
- */
706
- type WorkflowInstanceStatus = "complete" | "errored" | "paused" | "queued" | "running" | "terminated" | "unknown" | "waiting" | "waitingForPause";
707
- /** Result of {@link WorkflowInstance.status}. Mirrors `@lunora/workflow`'s `WorkflowStatusResult`. */
708
- interface WorkflowStatusResult {
709
- error?: {
710
- message: string;
711
- name: string;
712
- };
713
- output?: unknown;
714
- status: WorkflowInstanceStatus;
715
- }
716
- /** Options accepted by {@link WorkflowHandle.create}. Mirrors `@lunora/workflow`'s `WorkflowCreateOptions`. */
717
- interface WorkflowCreateOptions<Params = Record<string, unknown>> {
718
- /** Unique-within-the-workflow instance id. Generated by Cloudflare when omitted. */
719
- id?: string;
720
- /** The event payload the instance is triggered with — surfaced as `event.payload`. */
721
- params?: Params;
722
- /** Instance retention policy (defaults to the account maximum). */
723
- retention?: {
724
- errorRetention?: string;
725
- successRetention?: string;
726
- };
727
- }
728
- /** A live handle to a single workflow instance. Mirrors `@lunora/workflow`'s `WorkflowInstanceLike`. */
729
- interface WorkflowInstance {
730
- readonly id: string;
731
- pause: () => Promise<void>;
732
- restart: () => Promise<void>;
733
- resume: () => Promise<void>;
734
- sendEvent: (event: {
735
- payload: unknown;
736
- type: string;
737
- }) => Promise<void>;
738
- status: () => Promise<WorkflowStatusResult>;
739
- terminate: () => Promise<void>;
740
- }
741
- /**
742
- * A typed handle to one declared workflow, addressable from `ctx.workflows`.
743
- * Mirrors `@lunora/workflow`'s `WorkflowHandle`.
744
- */
745
- interface WorkflowHandle<Params = Record<string, unknown>> {
746
- /** Start a new instance (optionally with an id + params). */
747
- create: (options?: WorkflowCreateOptions<Params>) => Promise<WorkflowInstance>;
748
- /** Start many instances in one batched RPC. */
749
- createBatch: (batch: ReadonlyArray<WorkflowCreateOptions<Params>>) => Promise<WorkflowInstance[]>;
750
- /** Get a handle to an existing instance by id. */
751
- get: (id: string) => Promise<WorkflowInstance>;
752
- }
753
- /**
754
- * The `ctx.workflows` surface on {@link MutationCtx} / {@link ActionCtx}. Each
755
- * workflow declared in `lunora/workflows.ts` is reachable by its export name;
756
- * codegen narrows the `get(name)` overloads to the known workflow names + their
757
- * inferred param types. Mirrors `@lunora/workflow`'s `Workflows`.
758
- */
759
- interface Workflows {
760
- /** Resolve the handle for a declared workflow by export name. */
761
- get: <Params = Record<string, unknown>>(name: string) => WorkflowHandle<Params>;
762
- }
763
- /**
764
- * Programmatic cache purge surface exposed on {@link ActionCtx}. Actions run
765
- * in the Worker (not the DO), so they can reach the Worker's `ctx.cache.purge`.
766
- * Queries and mutations do not expose this — they run inside the Durable Object.
767
- */
768
- interface CachePurge {
769
- /**
770
- * Purge cached responses matching the given tags, or everything when
771
- * `purgeEverything` is true. Only available in action handlers.
772
- */
773
- purge: (options: {
774
- purgeEverything?: boolean;
775
- tags?: string[];
776
- }) => Promise<unknown>;
777
- }
778
- /**
779
- * Structural projection of workers-types' `SecretsStoreSecret` binding — the
780
- * per-secret `secrets_store_secrets[]` binding whose `.get()` resolves the
781
- * secret value (or throws if it does not exist). Mirrored structurally so the
782
- * runtime resolves it without a workerd type dependency.
783
- */
784
- interface SecretsStoreSecretLike {
785
- get: () => Promise<string>;
786
- }
787
- /**
788
- * `ctx.secrets` — read account-level secrets bound via Cloudflare Secrets Store.
789
- * A core built-in (always present on every context, like `ctx.log`): a binding
790
- * named in wrangler's `secrets_store_secrets[]` is read by its binding name.
791
- *
792
- * ```ts
793
- * const apiKey = await ctx.secrets.get("STRIPE_KEY");
794
- * ```
795
- *
796
- * The lookup is async (the platform fetches and decrypts on first read);
797
- * reading an undeclared name throws a directed error naming the bound secrets.
798
- */
799
- interface Secrets {
800
- /** Resolve a Secrets Store secret by its wrangler binding name. */
801
- get: (name: string) => Promise<string>;
802
- }
803
- /** Lifecycle phase relative to the SQL write. */
804
- type TriggerTiming = "after" | "before";
805
- /** The CRUD operation a trigger reacts to. `patch` and `replace` both map to `update`. */
806
- type TriggerOp = "delete" | "insert" | "update";
807
- /**
808
- * A row as observed by a trigger handler: the table's `Shape` (with the same
809
- * optionality rules as {@link InferArgs}) plus the system columns every stored
810
- * doc carries.
811
- */
812
- type TriggerRow<Shape extends Record<string, Validator>> = { [K in keyof Shape as undefined extends Infer<Shape[K]> ? K : never]?: Infer<Shape[K]> } & { [K in keyof Shape as undefined extends Infer<Shape[K]> ? never : K]: Infer<Shape[K]> } & {
813
- readonly _creationTime: number;
814
- readonly _id: string;
815
- };
816
- /** What an `insert` trigger observes: the freshly written row. */
817
- interface TriggerInsertEvent<Shape extends Record<string, Validator> = Record<string, Validator>> {
818
- readonly doc: TriggerRow<Shape>;
819
- readonly id: string;
820
- readonly op: "insert";
821
- readonly table: string;
822
- }
823
- /**
824
- * What an `update` trigger observes: the merged row plus the pre-write row.
825
- * `previous` is typed as always present (the row must exist to be updated); the
826
- * runtime supplies it best-effort and only omits it in the unreachable
827
- * row-vanished-mid-write case.
828
- */
829
- interface TriggerUpdateEvent<Shape extends Record<string, Validator> = Record<string, Validator>> {
830
- readonly doc: TriggerRow<Shape>;
831
- readonly id: string;
832
- readonly op: "update";
833
- readonly previous: TriggerRow<Shape>;
834
- readonly table: string;
835
- }
836
- /**
837
- * What a `delete` trigger observes: the row about to be (or just) removed.
838
- * `previous` is typed as always present; the runtime supplies it best-effort
839
- * and only omits it in the unreachable row-vanished-mid-write case.
840
- */
841
- interface TriggerDeleteEvent<Shape extends Record<string, Validator> = Record<string, Validator>> {
842
- readonly id: string;
843
- readonly op: "delete";
844
- readonly previous: TriggerRow<Shape>;
845
- readonly table: string;
846
- }
847
- /** Union of every trigger event, with the table `Shape` erased (as stored in `triggerMap`). */
848
- type TriggerEvent = TriggerDeleteEvent | TriggerInsertEvent | TriggerUpdateEvent;
849
- /** Page returned by {@link TriggerDatabase.findMany}; mirrors `@lunora/do`'s `QueryPage`. */
850
- interface TriggerQueryPage {
851
- continueCursor: null | string;
852
- isDone: boolean;
853
- page: Record<string, unknown>[];
854
- }
855
- /** Args accepted by {@link TriggerDatabase} reads; mirrors `@lunora/do`'s `QueryArgs`. */
856
- interface TriggerQueryArgs {
857
- cursor?: null | string;
858
- limit?: number;
859
- orderBy?: ReadonlyArray<unknown>;
860
- where?: Record<string, unknown>;
861
- with?: Record<string, unknown>;
862
- }
863
- /**
864
- * Args accepted by {@link TriggerDatabase.aggregate} — structural mirror of
865
- * `@lunora/do`'s `AggregateOptions`, kept local so trigger handlers in
866
- * `@lunora/server` don't take a hard dep on the DO runtime.
867
- */
868
- interface TriggerAggregateOptions {
869
- baseWhere?: Record<string, unknown>;
870
- field?: string;
871
- op: AggregateOp;
872
- restrictsCounts?: boolean;
873
- where?: Record<string, unknown>;
874
- }
875
- /** Args accepted by {@link TriggerDatabase.groupBy}. */
876
- interface TriggerGroupByOptions {
877
- agg?: {
878
- field?: string;
879
- op: AggregateOp;
880
- };
881
- baseWhere?: Record<string, unknown>;
882
- by: ReadonlyArray<string>;
883
- restrictsCounts?: boolean;
884
- where?: Record<string, unknown>;
885
- }
886
- /** One entry returned by {@link TriggerDatabase.groupBy}. */
887
- interface TriggerGroupByEntry {
888
- key: Record<string, unknown>;
889
- value: null | number;
890
- }
891
- /** Args accepted by {@link TriggerDatabase.rank}. */
892
- interface TriggerRankOptions {
893
- baseWhere?: Record<string, unknown>;
894
- restrictsCounts?: boolean;
895
- /** Either the row id or the full row document. */
896
- row: Record<string, unknown> | string;
897
- where?: Record<string, unknown>;
898
- }
899
- /** Result of {@link TriggerDatabase.rank} — 1-based position + partition total. */
900
- interface TriggerRankResult {
901
- position: number;
902
- total: number;
903
- }
904
- /** Args accepted by {@link TriggerDatabase.rankPage}. */
905
- interface TriggerRankPageOptions {
906
- baseWhere?: Record<string, unknown>;
907
- cursor?: null | string;
908
- take?: number;
909
- where?: Record<string, unknown>;
910
- }
911
- /**
912
- * Portable, table/id-addressed ORM writer handed to trigger handlers via
913
- * `ctx.db`. Mirrors `@lunora/do`'s runtime `DatabaseWriterLike` surface — it is
914
- * **not** the generated per-table `ctx.db.&lt;table>` facade (which can't be typed
915
- * from inside `defineTable`, where the full schema isn't known).
916
- *
917
- * `aggregate`/`groupBy`/`count`/`rank`/`rankPage` route through the same
918
- * trigger-maintained counter and rank tables the user-facing reader uses, so
919
- * a handler's `ctx.db.&lt;table>.aggregate(...)` observes the just-staged write
920
- * within the same DO transaction (the counter step happens before the trigger
921
- * fires).
922
- */
923
- interface TriggerDatabase {
924
- aggregate: (tableName: string, options: TriggerAggregateOptions) => Promise<null | number>;
925
- count: (tableName: string, where?: Record<string, unknown>) => Promise<number>;
926
- delete: (id: string) => Promise<void>;
927
- findFirst: (tableName: string, args?: TriggerQueryArgs) => Promise<Record<string, unknown> | null>;
928
- findMany: (tableName: string, args?: TriggerQueryArgs) => Promise<TriggerQueryPage>;
929
- get: (id: string) => Promise<Record<string, unknown> | null>;
930
- groupBy: (tableName: string, options: TriggerGroupByOptions) => Promise<ReadonlyArray<TriggerGroupByEntry>>;
931
- insert: (tableName: string, document: Record<string, unknown>) => Promise<string>;
932
- patch: (id: string, patch: Record<string, unknown>) => Promise<void>;
933
- rank: (tableName: string, indexName: string, options: TriggerRankOptions) => Promise<null | TriggerRankResult>;
934
- rankPage: (tableName: string, indexName: string, options?: TriggerRankPageOptions) => Promise<TriggerQueryPage>;
935
- replace: (id: string, document: Record<string, unknown>) => Promise<void>;
936
- }
937
- /**
938
- * Handle injected into every trigger handler. `db` is the portable ORM writer;
939
- * `scheduler` enqueues async / cross-shard follow-up work (cross-shard work is
940
- * **not** transactional with the firing write).
941
- */
942
- interface TriggerCtx {
943
- readonly db: TriggerDatabase;
944
- readonly scheduler: Scheduler;
945
- }
946
- /** A user-declared trigger handler. Throwing from a `before*` handler aborts the write. */
947
- type TriggerHandler<Event> = (context: TriggerCtx, event: Event) => Promise<void> | void;
948
- /**
949
- * A single declared trigger, as stored in {@link TableDefinition.triggerMap}.
950
- * The handler's event type is erased to the {@link TriggerEvent} union here; the
951
- * per-op {@link TriggerBuilder} methods recover the precise event type for
952
- * authors.
953
- */
954
- interface TriggerDefinition {
955
- readonly handler: TriggerHandler<TriggerEvent>;
956
- readonly op: TriggerOp;
957
- readonly timing: TriggerTiming;
958
- }
959
- /**
960
- * The `t` argument passed to `.triggers((t) => …)`. Each method binds a handler
961
- * to one `timing`+`op` pair, typing the event against the table's `Shape`.
962
- */
963
- interface TriggerBuilder<Shape extends Record<string, Validator> = Record<string, Validator>> {
964
- afterDelete: (handler: TriggerHandler<TriggerDeleteEvent<Shape>>) => TriggerDefinition;
965
- afterInsert: (handler: TriggerHandler<TriggerInsertEvent<Shape>>) => TriggerDefinition;
966
- afterUpdate: (handler: TriggerHandler<TriggerUpdateEvent<Shape>>) => TriggerDefinition;
967
- beforeDelete: (handler: TriggerHandler<TriggerDeleteEvent<Shape>>) => TriggerDefinition;
968
- beforeInsert: (handler: TriggerHandler<TriggerInsertEvent<Shape>>) => TriggerDefinition;
969
- beforeUpdate: (handler: TriggerHandler<TriggerUpdateEvent<Shape>>) => TriggerDefinition;
970
- }
971
- /**
972
- * Per-file metadata returned by {@link ReadOnlyStorage.getMetadata}. A clean
973
- * public mirror of `@lunora/storage`'s `ObjectMetadata` — re-declared here so
974
- * the ctx surface carries no dependency on the storage package's types. Matches
975
- * the columns Convex surfaces for `ctx.storage.getMetadata` / `_storage`.
976
- */
977
- interface StorageMetadata {
978
- /** The object's `Content-Type`, when recorded. */
979
- contentType?: string;
980
- /** Custom metadata set at upload time, if any. */
981
- customMetadata?: Record<string, string>;
982
- /** The object's key. */
983
- key: string;
984
- /** Hex-encoded SHA-256 of the body, when R2 carries a checksum. */
985
- sha256?: string;
986
- /** Body length in bytes. */
987
- size: number;
988
- /** When the object was last written (epoch ms), when reported. */
989
- uploaded?: number;
990
- }
991
- /**
992
- * Read-only projection of `Storage` exposed on `QueryCtx` / `MutationCtx`.
993
- *
994
- * Queries are pure reads, and mutations run inside a transactional scope —
995
- * neither is allowed to perform side-effectful R2 writes (`upload`) or
996
- * deletes (`delete`). They can, however, **read** existing objects and
997
- * resolve signed URLs (the URL signing itself is HMAC-only — no R2 round
998
- * trip), so the read-only surface keeps `download` and `getSignedUrl`. The
999
- * full {@link Storage} surface stays on `ActionCtx`.
1000
- */
1001
- interface ReadOnlyStorage<Buckets extends string = string> {
1002
- /**
1003
- * Select a named bucket (declared via `v.storage("name")`). The returned
1004
- * accessor's operations target that bucket — `ctx.storage.bucket("avatars")
1005
- * .download(key)`. The bare `ctx.storage` targets the default bucket.
1006
- */
1007
- bucket: (name: Buckets) => ReadOnlyStorage<Buckets>;
1008
- /** The bucket this accessor's operations target (the default for the bare `ctx.storage`). */
1009
- readonly bucketName: string;
1010
- /** Fetch the body of an existing object. Returns `null` when absent. */
1011
- download: (key: string) => Promise<ReadableStream | null>;
1012
- /**
1013
- * Read a file's metadata (size, content-type, sha256, upload time, custom
1014
- * metadata) without fetching its body. Returns `null` when the object is
1015
- * absent. Mirrors Convex's `ctx.storage.getMetadata`.
1016
- */
1017
- getMetadata: (key: string) => Promise<StorageMetadata | null>;
1018
- /** Resolve a short-lived signed URL for an existing object. */
1019
- getSignedUrl: (key: string, options?: {
1020
- expiresInSeconds?: number;
1021
- }) => Promise<string>;
1022
- /** Public URL pointing at the configured base for `key`. */
1023
- getUrl: (key: string) => string;
1024
- }
1025
- interface Storage<Buckets extends string = string> extends ReadOnlyStorage<Buckets> {
1026
- /** Select a named bucket; the returned accessor exposes the full read/write surface. */
1027
- bucket: (name: Buckets) => Storage<Buckets>;
1028
- delete: (key: string) => Promise<void>;
1029
- /**
1030
- * Mint a short-lived signed `PUT` URL a client can upload directly to,
1031
- * optionally pinning the `Content-Type` the uploader must send. Mirrors
1032
- * Convex's `storage.generateUploadUrl`.
1033
- */
1034
- generateUploadUrl: (key: string, options?: {
1035
- contentType?: string;
1036
- expiresInSeconds?: number;
1037
- }) => Promise<string>;
1038
- /**
1039
- * Upload `body` to `key` from the server, returning the stored object's key
1040
- * and etag. Mirrors Convex's `storage.store`. Accepts the same guard fields
1041
- * as `@lunora/storage`'s `UploadOptions` so `maxSize` /
1042
- * `allowedContentTypes` enforcement isn't lost behind the Convex-style alias.
1043
- */
1044
- store: (key: string, body: ReadableStream | ArrayBuffer | Blob, options?: {
1045
- allowedContentTypes?: ReadonlyArray<string>;
1046
- contentType?: string;
1047
- customMetadata?: Record<string, string>;
1048
- maxSize?: number;
1049
- }) => Promise<{
1050
- etag: string;
1051
- key: string;
1052
- }>;
1053
- }
1054
- interface VectorMatch {
1055
- id: string;
1056
- metadata?: Record<string, unknown>;
1057
- score: number;
1058
- }
1059
- interface VectorMatches {
1060
- count: number;
1061
- matches: ReadonlyArray<VectorMatch>;
1062
- }
1063
- interface VectorQueryInput {
1064
- /** Embedder used when `input` is supplied instead of a precomputed `vector`. */
1065
- embed?: VectorEmbedder;
1066
- filter?: Record<string, unknown>;
1067
- /** Natural-language input embedded via `embed`. Ignored when `vector` is set. */
1068
- input?: string;
1069
- namespace?: string;
1070
- topK?: number;
1071
- /** Precomputed query vector; skips `embed`. */
1072
- vector?: ReadonlyArray<number>;
1073
- }
1074
- interface VectorUpsertInput {
1075
- embed: VectorEmbedder;
1076
- id: string;
1077
- input: string;
1078
- metadata?: Record<string, unknown>;
1079
- namespace?: string;
1080
- }
1081
- interface VectorRecord {
1082
- id: string;
1083
- metadata?: Record<string, unknown>;
1084
- values: ReadonlyArray<number>;
1085
- }
1086
- /**
1087
- * Read-only vector surface exposed on {@link QueryCtx}. Mirrors the read half
1088
- * of `@lunora/bindings/vectors`' `LunoraVectors` so the live adapter is assignable.
1089
- */
1090
- interface VectorSearchReader {
1091
- getByIds: (indexName: string, ids: ReadonlyArray<string>) => Promise<ReadonlyArray<VectorRecord>>;
1092
- query: (indexName: string, input: VectorQueryInput) => Promise<VectorMatches>;
1093
- }
1094
- /**
1095
- * Mutating vector surface on {@link MutationCtx} / {@link ActionCtx}. `upsert`
1096
- * is queued post-commit by default; `upsertNow` forces a synchronous write.
1097
- * `db.delete` on a vectorized table auto-propagates the matching `deleteByIds`.
1098
- */
1099
- interface VectorSearch extends VectorSearchReader {
1100
- deleteByIds: (indexName: string, ids: ReadonlyArray<string>) => Promise<void>;
1101
- upsert: (indexName: string, input: VectorUpsertInput) => Promise<void>;
1102
- upsertNow: (indexName: string, input: VectorUpsertInput) => Promise<void>;
1103
- }
1104
- /**
1105
- * Structured logger on every function `ctx`. Each call emits one attributed log
1106
- * line — tagged with the function path on the server — that flows to an
1107
- * `ObservabilitySink`'s `onLog` (where you route it in production) and, in
1108
- * development, to the dev server terminal via the CLI / Vite plugin formatter.
1109
- * Mirrors the `console` method names so it's a drop-in for `console.log` inside a
1110
- * handler, but with attribution and a routable transport.
1111
- *
1112
- * Accepts any number of values per call, exactly like `console`; objects are
1113
- * rendered into the human-readable message. The raw, un-rendered arguments are
1114
- * preserved ONLY on the in-process `onLog` sink (which you opt into and control);
1115
- * the rendered message — not the structured args — is what reaches the dev
1116
- * terminal and the platform's Workers Logs.
1117
- *
1118
- * Attribution follows the dispatched function: a log emitted inside an internal
1119
- * function invoked via `ctx.runQuery`/`runMutation`/`runAction` is attributed to
1120
- * the outer request entrypoint, since the composed call reuses its context.
1121
- */
1122
- interface LunoraLogger {
1123
- readonly debug: (...args: unknown[]) => void;
1124
- readonly error: (...args: unknown[]) => void;
1125
- readonly info: (...args: unknown[]) => void;
1126
- readonly log: (...args: unknown[]) => void;
1127
- readonly warn: (...args: unknown[]) => void;
1128
- }
1129
- interface QueryCtx {
1130
- readonly auth: AuthState;
1131
- readonly db: DatabaseReader;
1132
- /**
1133
- * The validated, typed environment. Populated only when the project declares
1134
- * a `defineEnv(...)` contract in `lunora/env.ts`; codegen then narrows this to
1135
- * the validated `InferEnv` shape so `ctx.env.STRIPE_KEY` is parsed and
1136
- * coercion-aware. Absent (optional) without a contract — declare
1137
- * `lunora/env.ts` to populate and type it.
1138
- */
1139
- readonly env?: Record<string, unknown>;
1140
- /**
1141
- * The caller's IP for this request — Cloudflare's trusted `CF-Connecting-IP`,
1142
- * forwarded server-side (never read from a client header). `undefined` when
1143
- * unknown: a live-subscription re-run, a server-initiated dispatch, or
1144
- * non-Cloudflare hosting. A convenient rate-limit key for anonymous traffic.
1145
- */
1146
- readonly ip?: string;
1147
- /** Structured, function-attributed logger; see {@link LunoraLogger}. */
1148
- readonly log: LunoraLogger;
1149
- /**
1150
- * Wall-clock time (epoch ms) the function began, captured once so the whole
1151
- * handler sees a single stable value. Query/mutation handlers must be
1152
- * deterministic — they may be re-run on OCC retry / subscription re-eval — so
1153
- * read time through `ctx.now` instead of `Date.now()` (the latter is flagged
1154
- * by the `nondeterministic_query_mutation` advisor). Actions may use `Date.now()`.
1155
- */
1156
- readonly now: number;
1157
- /**
1158
- * Compose a read-only subquery in-process, reusing this query's read
1159
- * context (same transaction, same `db`). Executes the referenced query's
1160
- * handler directly — no fresh DO RPC round-trip — so it observes the exact
1161
- * same snapshot. A query may only call other queries; there is no
1162
- * `runMutation` on a `QueryCtx` (writes are not allowed from a query).
1163
- * Mirrors Convex's `ctx.runQuery`.
1164
- */
1165
- readonly runQuery: <A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args: InferArgs<A>) => Promise<R>;
1166
- /** Read account-level secrets from Cloudflare Secrets Store; see {@link Secrets}. */
1167
- readonly secrets: Secrets;
1168
- readonly storage: ReadOnlyStorage;
1169
- readonly vectors: VectorSearchReader;
1170
- }
1171
- interface MutationCtx {
1172
- readonly auth: AuthState;
1173
- readonly db: DatabaseWriter;
1174
- /**
1175
- * The validated, typed environment. Populated only when the project declares
1176
- * a `defineEnv(...)` contract in `lunora/env.ts`; codegen then narrows this to
1177
- * the validated `InferEnv` shape so `ctx.env.STRIPE_KEY` is parsed and
1178
- * coercion-aware. Absent (optional) without a contract — declare
1179
- * `lunora/env.ts` to populate and type it.
1180
- */
1181
- readonly env?: Record<string, unknown>;
1182
- /**
1183
- * The caller's IP for this request — Cloudflare's trusted `CF-Connecting-IP`,
1184
- * forwarded server-side (never read from a client header). `undefined` when
1185
- * unknown: a live-subscription re-run, a server-initiated dispatch, or
1186
- * non-Cloudflare hosting. A convenient rate-limit key for anonymous traffic.
1187
- */
1188
- readonly ip?: string;
1189
- /** Structured, function-attributed logger; see {@link LunoraLogger}. */
1190
- readonly log: LunoraLogger;
1191
- /**
1192
- * Wall-clock time (epoch ms) the function began, captured once so the whole
1193
- * handler sees a single stable value. Mutation handlers must be deterministic
1194
- * — they may be re-run on OCC retry — so read time through `ctx.now` instead
1195
- * of `Date.now()` (the latter is flagged by the `nondeterministic_query_mutation`
1196
- * advisor). Actions may use `Date.now()`.
1197
- */
1198
- readonly now: number;
1199
- /**
1200
- * Compose a submutation in-process, reusing this mutation's `db` writer.
1201
- * Executes the referenced mutation's handler directly — no fresh DO RPC —
1202
- * so its writes apply through the same shard invocation as the enclosing
1203
- * mutation. Note: writes are not wrapped in a SQL transaction, so a partial
1204
- * failure does not roll back earlier writes (the same as a top-level
1205
- * mutation). Mirrors Convex's `ctx.runMutation`.
1206
- */
1207
- readonly runMutation: <A extends ArgsValidator, R>(reference: RegisteredMutation<A, R>, args: InferArgs<A>) => Promise<R>;
1208
- /**
1209
- * Compose a read-only subquery in-process, reusing this mutation's `db`.
1210
- * Executes the referenced query's handler directly — no fresh DO RPC — so
1211
- * it observes this mutation's in-flight writes. Mirrors Convex's
1212
- * `ctx.runQuery`.
1213
- */
1214
- readonly runQuery: <A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args: InferArgs<A>) => Promise<R>;
1215
- readonly scheduler: Scheduler;
1216
- /** Read account-level secrets from Cloudflare Secrets Store; see {@link Secrets}. */
1217
- readonly secrets: Secrets;
1218
- readonly storage: ReadOnlyStorage;
1219
- readonly vectors: VectorSearch;
1220
- /** Start / resume / inspect durable workflows; see {@link Workflows}. */
1221
- readonly workflows: Workflows;
1222
- }
1223
- interface ActionCtx {
1224
- readonly auth: AuthState;
1225
- /**
1226
- * Programmatic Workers Cache purge; see {@link CachePurge}.
1227
- * **Action-only** — actions run in the Worker, which has a `cache` binding.
1228
- * Queries and mutations run inside the Durable Object and do not expose this.
1229
- * Optional at runtime because Workers Cache is only present when enabled.
1230
- */
1231
- readonly cache?: CachePurge;
1232
- readonly db: DatabaseWriter;
1233
- /**
1234
- * The validated, typed environment. Populated only when the project declares
1235
- * a `defineEnv(...)` contract in `lunora/env.ts`; codegen then narrows this to
1236
- * the validated `InferEnv` shape so `ctx.env.STRIPE_KEY` is parsed and
1237
- * coercion-aware. Absent (optional) without a contract — declare
1238
- * `lunora/env.ts` to populate and type it.
1239
- */
1240
- readonly env?: Record<string, unknown>;
1241
- readonly fetch: typeof globalThis.fetch;
1242
- /**
1243
- * The caller's IP for this request — Cloudflare's trusted `CF-Connecting-IP`,
1244
- * forwarded server-side (never read from a client header). `undefined` when
1245
- * unknown: a live-subscription re-run, a server-initiated dispatch, or
1246
- * non-Cloudflare hosting. A convenient rate-limit key for anonymous traffic.
1247
- */
1248
- readonly ip?: string;
1249
- /** Structured, function-attributed logger; see {@link LunoraLogger}. */
1250
- readonly log: LunoraLogger;
1251
- /**
1252
- * Wall-clock time (epoch ms) the action began, captured once for convenience
1253
- * and parity with query/mutation `ctx.now`. Actions run exactly once, so they
1254
- * may also use ambient `Date.now()` freely.
1255
- */
1256
- readonly now: number;
1257
- readonly runAction: <A extends ArgsValidator, R>(reference: RegisteredAction<A, R>, args: InferArgs<A>) => Promise<R>;
1258
- readonly runMutation: <A extends ArgsValidator, R>(reference: RegisteredMutation<A, R>, args: InferArgs<A>) => Promise<R>;
1259
- readonly runQuery: <A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args: InferArgs<A>) => Promise<R>;
1260
- readonly scheduler: Scheduler;
1261
- /** Read account-level secrets from Cloudflare Secrets Store; see {@link Secrets}. */
1262
- readonly secrets: Secrets;
1263
- readonly storage: Storage;
1264
- readonly vectors: VectorSearch;
1265
- /** Start / resume / inspect durable workflows; see {@link Workflows}. */
1266
- readonly workflows: Workflows;
1267
- }
1268
- /**
1269
- * Stand-in returned by codegen so projects can `import { api } from "./_generated/api"`.
1270
- * The runtime value is opaque; the types are filled in by generated declarations.
1271
- */
1272
- type AnyApi = Record<string, Record<string, RegisteredFunction<ArgsValidator, unknown, FunctionKind>>>;
1273
- declare const anyApi: AnyApi;
1274
- export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LunoraLogger, type MutationCtx, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationDefinition, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type Secrets, type SecretsStoreSecretLike, type ShardMode, type Storage, type StorageMetadata, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
1
+ export type { b as ActionCtx, t as AggregateIndexDefinition, h as AggregateOp, A as ArgsValidator, B as AuthState, C as CachePurge, H as DatabaseReader, D as DatabaseWriter, s as DurableObjectJurisdiction, e as DurableStreamOptions, E as ExposeConfig, bl as ExternalSourceCursor, n as ExternalSourceDefinition, bm as ExternalSourceMode, bn as ExternalSourceRefresh, F as FunctionKind, J as FunctionVisibility, N as GeoBoundingBox, P as GeoFilterBuilder, U as GeoIndexDefinition, Y as GeoPointInput, G as GlobalBackend, Z as IndexDefinition, _ as IndexRangeBuilder, I as InferArgs, K as KeyedRelationDefinition, x as LifecycleEvent, $ as LifecycleEventKind, a0 as LogFields, a1 as LunoraLogMethod, a2 as LunoraLogger, a3 as LunoraMetrics, L as LunoraTracer, a4 as LunoraWideEvent, M as MutationCtx, a5 as MutationStorage, O as OnDeleteAction, a6 as PaginationOptions, a7 as PaginationResult, a8 as PatchIfResult, Q as QueryCtx, u as RankIndexDefinition, a9 as RankSortKey, aa as ReadOnlyStorage, R as RegisteredAction, g as RegisteredFunction, z as RegisteredLifecycleHook, c as RegisteredMutation, d as RegisteredQuery, f as RegisteredStream, ab as RelatedDirection, ac as RelatedNode, ad as RelatedOptions, ae as RelatedPage, af as RelatedStart, ag as RelatedStartReference, k as RelationDefinition, i as RelationThrough, ah as RestCacheConfig, ai as RetryPolicy, aj as RunQueryOptions, ak as ScheduledFunctionDoc, al as ScheduledJob, am as Scheduler, S as Schema, an as SearchFilterBuilder, ao as SearchIndexDefinition, l as SearchLanguage, m as SearchStrategy, v as Secrets, bo as SecretsStoreSecretLike, y as ShardInitEvent, ap as ShardMode, aq as SpanContextIds, ar as SpanEvaluation, a as SpanHandle, as as SpanIdentity, at as SpanKind, au as SpanLink, av as SpanOptions, aw as Storage, ax as StorageListOptions, ay as StorageListResult, az as StorageMetadata, aA as StorageMultipartUpload, aB as StorageMultipartUploadOptions, aC as StorageObjectBody, aD as StorageObjectHead, aE as StorageRange, aF as StorageUploadBody, aG as StorageUploadOptions, aH as StorageUploadResult, aI as StorageUploadedPart, aJ as SystemDatabaseReader, aK as SystemDoc, aL as SystemQuery, aM as SystemTableName, T as TableDefinition, aN as TableReader, aO as TableVectorIndex, j as ThroughRelationDefinition, aP as TriggerAggregateOptions, o as TriggerBuilder, aQ as TriggerCtx, aR as TriggerDatabase, p as TriggerDefinition, aS as TriggerDeleteEvent, aT as TriggerEvent, aU as TriggerGroupByEntry, aV as TriggerGroupByOptions, aW as TriggerHandler, aX as TriggerInsertEvent, aY as TriggerOp, aZ as TriggerQueryArgs, a_ as TriggerQueryPage, a$ as TriggerRankOptions, b0 as TriggerRankPageOptions, b1 as TriggerRankResult, b2 as TriggerRow, b3 as TriggerTiming, b4 as TriggerUpdateEvent, b5 as TtlDefinition, q as VectorEmbedder, V as VectorIndexDefinition, b6 as VectorMatch, b7 as VectorMatches, r as VectorMetric, b8 as VectorQueryInput, b9 as VectorRecord, ba as VectorSearch, bb as VectorSearchReader, bc as VectorUpsertInput, W as WhisperEvent, bd as WorkflowCreateOptions, be as WorkflowEventDefinition, bf as WorkflowHandle, bg as WorkflowInstance, bh as WorkflowInstanceEvent, bi as WorkflowInstanceStatus, bj as WorkflowStatusResult, bk as Workflows, X as X402ProcedureConfig } from "./packem_shared/types.d-CCjAj93e.js";
2
+ import '@lunora/values';