@lunora/server 1.0.0-alpha.9 → 1.0.0-alpha.91
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +219 -0
- package/README.md +46 -0
- package/dist/data-model.d.mts +260 -164
- package/dist/data-model.d.ts +260 -164
- package/dist/data-model.mjs +0 -1
- package/dist/drizzle.mjs +1 -1
- package/dist/index.d.mts +2675 -1562
- package/dist/index.d.ts +2675 -1562
- package/dist/index.mjs +1 -28
- package/dist/otel.d.mts +543 -0
- package/dist/otel.d.ts +543 -0
- package/dist/otel.mjs +1 -0
- package/dist/packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-DRJUQGut.mjs +1 -0
- package/dist/packem_shared/DEFAULT_LIMIT-DC-M6faS.mjs +1 -0
- package/dist/packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-KTkC4xOc.mjs +1 -0
- package/dist/packem_shared/LunoraEnvError-_BakoYQ3.mjs +3 -0
- package/dist/packem_shared/LunoraError-DcKdk9Ti.mjs +1 -0
- package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-BpSPSCwL.mjs +1 -0
- package/dist/packem_shared/allowAll-DkRAgItV.mjs +1 -0
- package/dist/packem_shared/apply-output-BG8Bd0Ug.mjs +1 -0
- package/dist/packem_shared/asBucketStorage-BthCnWop.mjs +1 -0
- package/dist/packem_shared/bindOrm-lWdeDi9P.mjs +1 -0
- package/dist/packem_shared/buildMaskRegistry-72SL8fJn.mjs +1 -0
- package/dist/packem_shared/buildRlsReadRegistry-Deq8inqS.mjs +1 -0
- package/dist/packem_shared/composePluginMiddleware-DQHF6mYr.mjs +1 -0
- package/dist/packem_shared/context-identity-B2XYGA0B.mjs +1 -0
- package/dist/packem_shared/createPolicyDsl-DNfByAUX.mjs +1 -0
- package/dist/packem_shared/createSecrets-CyrEddTF.mjs +1 -0
- package/dist/packem_shared/defineAggregateIndex-BtVAy69G.mjs +1 -0
- package/dist/packem_shared/defineIdentity-DwkNKwYa.mjs +1 -0
- package/dist/packem_shared/defineMigration-7GI9Qbtd.mjs +1 -0
- package/dist/packem_shared/defineMutator-DKy8UtbB.mjs +1 -0
- package/dist/packem_shared/defineShape-DYxbNl5W.mjs +1 -0
- package/dist/packem_shared/defineStorageRule-BvxHVq3b.mjs +1 -0
- package/dist/packem_shared/flushDeferredDeletes-DEJXlhop.mjs +1 -0
- package/dist/packem_shared/fnv1a-D6VtE8WR.mjs +1 -0
- package/dist/packem_shared/functions-B2-H4PQT.mjs +1 -0
- package/dist/packem_shared/httpAction-D3b9-YiY.mjs +5 -0
- package/dist/packem_shared/initLunora-B2sfmFJ6.mjs +1 -0
- package/dist/packem_shared/mask-Da7q82ZC.mjs +1 -0
- package/dist/packem_shared/middleware-DEW0yLvU.mjs +1 -0
- package/dist/packem_shared/onConnect-BLRoOpv2.mjs +1 -0
- package/dist/packem_shared/onQueryChange-pRK6Dh3g.mjs +1 -0
- package/dist/packem_shared/plugin-DQcLxTx1.mjs +1 -0
- package/dist/packem_shared/policy-tag-D4RzgQnw.mjs +1 -0
- package/dist/packem_shared/protectPublic-Bo4G9xaV.mjs +1 -0
- package/dist/packem_shared/rls-B3mNGBuc.mjs +1 -0
- package/dist/packem_shared/run-middleware-B-JeGGp9.mjs +1 -0
- package/dist/packem_shared/stable-key-B_BlboiY.mjs +1 -0
- package/dist/packem_shared/storageRules-CyaiZ0av.mjs +1 -0
- package/dist/packem_shared/types.d-B-pIn8rE.d.mts +141 -0
- package/dist/packem_shared/types.d-CdPDEjhz.d.ts +141 -0
- package/dist/packem_shared/wire-codec-hZHn-Ooo.mjs +1 -0
- package/dist/rls/testing.d.mts +31 -31
- package/dist/rls/testing.d.ts +31 -31
- package/dist/rls/testing.mjs +1 -49
- package/dist/types.d.mts +1621 -508
- package/dist/types.d.ts +1621 -508
- package/dist/types.mjs +1 -31
- package/package.json +17 -4
- package/dist/packem_shared/LunoraEnvError-DjFkpkSP.mjs +0 -187
- package/dist/packem_shared/LunoraError-DN7Zhhvu.mjs +0 -54
- package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-D8viLY1S.mjs +0 -114
- package/dist/packem_shared/asBucketStorage-Cnxd9y2q.mjs +0 -11
- package/dist/packem_shared/bindOrm-Ce57S3N9.mjs +0 -128
- package/dist/packem_shared/buildRlsReadRegistry-1jexWrb3.mjs +0 -107
- package/dist/packem_shared/composePluginMiddleware-Ck5_TUO8.mjs +0 -100
- package/dist/packem_shared/createPolicyDsl-De67zPDS.mjs +0 -29
- package/dist/packem_shared/createSecrets-TsIP9lOa.mjs +0 -55
- package/dist/packem_shared/defineAggregateIndex-ZdyU78gh.mjs +0 -291
- package/dist/packem_shared/defineMigration-CAJLr6fx.mjs +0 -8
- package/dist/packem_shared/defineMutator-EIXAWhs9.mjs +0 -11
- package/dist/packem_shared/defineShape-CJ27Wx7o.mjs +0 -17
- package/dist/packem_shared/defineStorageRule-qu0mpilX.mjs +0 -20
- package/dist/packem_shared/functions-Di9FUNkf.mjs +0 -5
- package/dist/packem_shared/httpAction-FLwfsePg.mjs +0 -340
- package/dist/packem_shared/initLunora-lxwHTEV3.mjs +0 -100
- package/dist/packem_shared/mask-BV_jNzsN.mjs +0 -211
- package/dist/packem_shared/onConnect-CIPXKPyw.mjs +0 -13
- package/dist/packem_shared/policy-tag-DvpVH2tv.mjs +0 -13
- package/dist/packem_shared/protectPublic-BjFkQ_Or.mjs +0 -15
- package/dist/packem_shared/rls-2Jhd0uev.mjs +0 -569
- package/dist/packem_shared/run-middleware-CYQOuoV6.mjs +0 -18
- package/dist/packem_shared/storageRules-Cje6Woea.mjs +0 -88
- package/dist/packem_shared/types.d-BDY0FYHK.d.ts +0 -135
- package/dist/packem_shared/types.d-DmvyEMD6.d.mts +0 -135
package/dist/types.d.ts
CHANGED
|
@@ -1,4 +1,68 @@
|
|
|
1
|
-
import { ValidatorMap, InferValidatorMap,
|
|
1
|
+
import { ValidatorMap, InferValidatorMap, Validator, Infer, Id } from '@lunora/values';
|
|
2
|
+
/**
|
|
3
|
+
* The set of languages a `.searchIndex()` can declare, in one place.
|
|
4
|
+
*
|
|
5
|
+
* Three layers need it and none of them can import the others: `@lunora/server`
|
|
6
|
+
* types the option and validates it at schema-build time, and `@lunora/do` maps
|
|
7
|
+
* it onto a stopword list at analysis time — with no dependency edge between
|
|
8
|
+
* them (nor should there be: the schema builder must stay usable without the DO
|
|
9
|
+
* runtime). So it lived in three hand-maintained copies, where adding a
|
|
10
|
+
* language silently produced a schema the builder accepts and the analyzer
|
|
11
|
+
* treats as `"none"` — an index that quietly stops dropping stopwords.
|
|
12
|
+
*
|
|
13
|
+
* The list is the single source: the type is derived from it, so the two cannot
|
|
14
|
+
* drift. `@lunora/do` still owns the stopword *lists*; it keys them by these
|
|
15
|
+
* names, and its own tests assert the two agree.
|
|
16
|
+
*
|
|
17
|
+
* Inlined by the bundler into each `dist` rather than published, so this stays
|
|
18
|
+
* a shared *constant*, not a dependency edge. See the `shared/` section of
|
|
19
|
+
* AGENTS.md.
|
|
20
|
+
*/
|
|
21
|
+
/**
|
|
22
|
+
* Every accepted value, sorted, so an error message can list what *is*
|
|
23
|
+
* accepted without re-sorting. `"none"` is explicit rather than absent: it
|
|
24
|
+
* means "fold, but drop nothing", which is also what an index with no declared
|
|
25
|
+
* language gets.
|
|
26
|
+
*/
|
|
27
|
+
declare const SEARCH_LANGUAGES: readonly ["de", "en", "es", "fr", "it", "nl", "none", "pt"];
|
|
28
|
+
/** A declared analysis language, derived from the list above. */
|
|
29
|
+
type SearchLanguage = (typeof SEARCH_LANGUAGES)[number];
|
|
30
|
+
/**
|
|
31
|
+
* How a search index is stored. `"portable"` promises identical behaviour on
|
|
32
|
+
* every backend; `"native"` opts into the engine's own full-text index where it
|
|
33
|
+
* has one, trading that promise for its speed.
|
|
34
|
+
*
|
|
35
|
+
* Lives beside the languages for the same reason they do: it is declared in
|
|
36
|
+
* `@lunora/server`, acted on in the storage layer, and there is no dependency
|
|
37
|
+
* edge between them — so a third hand-maintained copy is how a typo turns into
|
|
38
|
+
* a silently different *physical layout*.
|
|
39
|
+
*/
|
|
40
|
+
declare const SEARCH_STRATEGIES: readonly ["native", "portable"];
|
|
41
|
+
/** A declared storage strategy, derived from the list above. */
|
|
42
|
+
type SearchStrategy = (typeof SEARCH_STRATEGIES)[number];
|
|
43
|
+
/**
|
|
44
|
+
* Declared HTTP caching for an exposed endpoint (`.expose({ cache })`). Lives
|
|
45
|
+
* here, alongside the path/method contract, for the same reason: the runtime
|
|
46
|
+
* WRITES these headers and the OpenAPI emitter DESCRIBES them, and the two must
|
|
47
|
+
* not be able to disagree. Deriving both from {@link cacheControlValue} /
|
|
48
|
+
* {@link cacheVaryValue} makes "the published spec matches what the runtime
|
|
49
|
+
* actually sends" structural rather than a hand-kept invariant.
|
|
50
|
+
*/
|
|
51
|
+
interface RestCachePolicy {
|
|
52
|
+
/**
|
|
53
|
+
* Extra request headers this app authenticates on, beyond
|
|
54
|
+
* {@link CREDENTIAL_HEADERS}. Declare these whenever `resolveIdentity` reads
|
|
55
|
+
* something else (`x-api-key`, a tenant header, …): they join both the
|
|
56
|
+
* credential check and the emitted `Vary`. Without them, a caller
|
|
57
|
+
* authenticating that way is treated as anonymous.
|
|
58
|
+
*/
|
|
59
|
+
readonly credentialHeaders?: ReadonlyArray<string>;
|
|
60
|
+
readonly maxAge: number;
|
|
61
|
+
readonly scope: "private" | "public";
|
|
62
|
+
readonly staleWhileRevalidate?: number;
|
|
63
|
+
readonly tag?: string;
|
|
64
|
+
readonly vary?: string;
|
|
65
|
+
}
|
|
2
66
|
/** Map of validators describing a function's args record. Alias of `@lunora/values`' shared {@link ValidatorMap}. */
|
|
3
67
|
type ArgsValidator = ValidatorMap;
|
|
4
68
|
/** Infer the args object type from an {@link ArgsValidator}. Alias of `@lunora/values`' shared {@link InferValidatorMap}. */
|
|
@@ -6,12 +70,12 @@ type InferArgs<A extends ArgsValidator> = InferValidatorMap<A>;
|
|
|
6
70
|
/** Storage backend for a `.global()` table: D1 (default) or a Postgres/MySQL database via Cloudflare Hyperdrive (PlanetScale, Neon, …). */
|
|
7
71
|
type GlobalBackend = "d1" | "hyperdrive";
|
|
8
72
|
/**
|
|
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
|
-
*/
|
|
73
|
+
* Cloudflare Durable Object data-residency jurisdiction declared via
|
|
74
|
+
* `defineSchema(...).jurisdiction("…")`. Restricts where every DO the app
|
|
75
|
+
* reaches runs and persists data (GDPR, FedRAMP, US data residency). Widening
|
|
76
|
+
* union — Cloudflare adds values over time.
|
|
77
|
+
* @see https://developers.cloudflare.com/durable-objects/reference/data-location/
|
|
78
|
+
*/
|
|
15
79
|
type DurableObjectJurisdiction = "eu" | "fedramp" | "us";
|
|
16
80
|
/** How a table is routed at runtime. */
|
|
17
81
|
type ShardMode = {
|
|
@@ -28,44 +92,83 @@ type ExternalSourceRefresh = "manual" | {
|
|
|
28
92
|
everyMs: number;
|
|
29
93
|
};
|
|
30
94
|
/**
|
|
31
|
-
* Delete-detection mode for external-source ingest
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
|
|
95
|
+
* Delete-detection mode for external-source ingest (plan 077 / 136).
|
|
96
|
+
*
|
|
97
|
+
* `"full-pull"` (the default) reads the **whole** tenant membership each tick and
|
|
98
|
+
* diffs it, so it observes upstream deletes for free — but costs a full read per tick
|
|
99
|
+
* (the Phase-0 bench put the ceiling at ~10k rows).
|
|
100
|
+
*
|
|
101
|
+
* `"incremental"` pulls **only rows past a durable watermark** (`cursor`), cheap for
|
|
102
|
+
* large low-churn tables above the full-pull cap. Because an absent row then means
|
|
103
|
+
* "unchanged", not "deleted", incremental requires a delete-visibility path: either a
|
|
104
|
+
* `reconcileEveryMs` periodic full-pull sweep, or a `softDeleteColumn` whose
|
|
105
|
+
* tombstones the pull returns. `defineSchema` throws (and the
|
|
106
|
+
* `external_source_incremental_no_delete_path` advisor lint fails the build) when an
|
|
107
|
+
* incremental source declares neither.
|
|
108
|
+
*/
|
|
36
109
|
type ExternalSourceMode = "full-pull" | "incremental";
|
|
37
110
|
/**
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
|
|
111
|
+
* Incremental-ingest cursor (plan 136): the monotonic watermark column plus the
|
|
112
|
+
* watermark-parameterized pull query. `column` names the field in the pulled rows
|
|
113
|
+
* whose max becomes the next watermark (e.g. `"updated_at"`). `query` is a second
|
|
114
|
+
* SQL that returns only rows changed since the watermark — the watermark binds as
|
|
115
|
+
* the parameter AFTER `tenantBy`'s params (e.g. Postgres
|
|
116
|
+
* `... WHERE tenant_id = $1 AND updated_at >= $2 ORDER BY updated_at`). Prefer `>=`
|
|
117
|
+
* with the idempotent upsert apply so rows sharing the boundary timestamp are never
|
|
118
|
+
* skipped (re-pulling them is a no-op).
|
|
119
|
+
*/
|
|
120
|
+
interface ExternalSourceCursor {
|
|
121
|
+
/** The monotonic watermark column in the pulled rows; its max advances the stored watermark. */
|
|
122
|
+
column: string;
|
|
123
|
+
/** The incremental pull SQL. `tenantBy`'s params bind first, then the watermark as the trailing param. */
|
|
124
|
+
query: string;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Config for `.source(...)` (plan 077): declares a table as **materialized from an
|
|
128
|
+
* external Postgres/MySQL behind Cloudflare Hyperdrive**, not written by user
|
|
129
|
+
* mutations. A system-driven poll loop reads the tenant slice and lands it in the
|
|
130
|
+
* DO's SQLite (via the validated CDC writer), after which `defineShape` carries it
|
|
131
|
+
* to clients unchanged. Orthogonal to `shardMode` — a sourced table almost always
|
|
132
|
+
* also `.shardBy()`s, in which case `tenantBy` is the mandatory tenant-isolation
|
|
133
|
+
* boundary (enforced by the `external_source_unscoped` advisor lint).
|
|
134
|
+
*/
|
|
46
135
|
interface ExternalSourceDefinition {
|
|
47
136
|
/** The wrangler Hyperdrive binding name the poll loop reads from. */
|
|
48
137
|
binding: string;
|
|
49
138
|
/** Project the materialized rows to these columns (passed to the membership diff). Omit ⇒ the full mapped document. */
|
|
50
139
|
columns?: ReadonlyArray<string>;
|
|
140
|
+
/** **Required for `mode: "incremental"`**: the watermark column + watermark-parameterized pull query (plan 136). Rejected on a `"full-pull"` source. */
|
|
141
|
+
cursor?: ExternalSourceCursor;
|
|
51
142
|
/** Column whose value becomes the Lunora `_id`. Defaults to `"id"`. */
|
|
52
143
|
idColumn?: string;
|
|
53
144
|
/** Transform an external row into the stored document body. Omit ⇒ every selected column except `idColumn` is copied. */
|
|
54
145
|
map?: (row: Record<string, unknown>) => Record<string, unknown>;
|
|
55
|
-
/** Delete-detection mode.
|
|
146
|
+
/** Delete-detection mode. `"full-pull"` (the default) diffs the whole membership; `"incremental"` pulls past a `cursor` watermark. */
|
|
56
147
|
mode?: ExternalSourceMode;
|
|
57
148
|
/** The full tenant-membership query, with driver-native placeholders (`$1` / `?`). `tenantBy` binds its params. */
|
|
58
149
|
query: string;
|
|
59
|
-
/**
|
|
150
|
+
/**
|
|
151
|
+
* **Incremental delete-visibility (plan 136)**: run a full-pull sweep at most
|
|
152
|
+
* this often (millis) to GC upstream deletes an incremental slice can't see.
|
|
153
|
+
* One of `reconcileEveryMs` / `softDeleteColumn` is required for incremental;
|
|
154
|
+
* rejected on a `"full-pull"` source.
|
|
155
|
+
*/
|
|
60
156
|
reconcileEveryMs?: number;
|
|
61
157
|
/** Poll cadence, or `"manual"`. Omit ⇒ the runtime's size-scaled default. */
|
|
62
158
|
refresh?: ExternalSourceRefresh;
|
|
63
159
|
/**
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
160
|
+
* **Incremental delete-visibility (plan 136)**: the upstream soft-delete
|
|
161
|
+
* tombstone column (e.g. `"deleted_at"`). When set, the incremental pull must
|
|
162
|
+
* return tombstoned rows and the ingest turns each into a local delete — an
|
|
163
|
+
* alternative to `reconcileEveryMs`. Rejected on a `"full-pull"` source.
|
|
164
|
+
*/
|
|
165
|
+
softDeleteColumn?: string;
|
|
166
|
+
/**
|
|
167
|
+
* **Mandatory under `.shardBy()`**: map this DO's shard key → the query's bound
|
|
168
|
+
* params, so a tenant DO can only ever pull its own rows. An unscoped sourced +
|
|
169
|
+
* sharded table replicates the whole multitenant table into every shard — the
|
|
170
|
+
* `external_source_unscoped` advisor lint fails the build when this is absent.
|
|
171
|
+
*/
|
|
69
172
|
tenantBy?: (shardKey: string) => ReadonlyArray<unknown>;
|
|
70
173
|
}
|
|
71
174
|
interface IndexDefinition {
|
|
@@ -74,25 +177,97 @@ interface IndexDefinition {
|
|
|
74
177
|
unique?: boolean;
|
|
75
178
|
}
|
|
76
179
|
interface SearchIndexDefinition {
|
|
180
|
+
/** Indexed text column; a dot-separated path (`"properties.name"`) reads a nested field. */
|
|
77
181
|
field: string;
|
|
182
|
+
/** Columns `.eq()` may narrow by inside the search builder. At most 16. */
|
|
78
183
|
filterFields?: ReadonlyArray<string>;
|
|
184
|
+
/**
|
|
185
|
+
* Text analysis for this index. Accent folding is always applied — it is
|
|
186
|
+
* what makes `café` and `cafe` the same token on every backend, which they
|
|
187
|
+
* otherwise are not. Naming a language additionally drops that language's
|
|
188
|
+
* stopwords from both documents and queries.
|
|
189
|
+
*
|
|
190
|
+
* Analysis is baked into the stored index, so changing this rebuilds it:
|
|
191
|
+
* the runtime records which profile a companion was built with and
|
|
192
|
+
* re-indexes when it no longer matches.
|
|
193
|
+
*/
|
|
194
|
+
language?: SearchLanguage;
|
|
195
|
+
name: string;
|
|
196
|
+
/**
|
|
197
|
+
* Skip the migration-time backfill. By default, creating the index's
|
|
198
|
+
* companion also indexes the rows already in the table, so a search index
|
|
199
|
+
* added to a populated table works immediately. On a very large table that
|
|
200
|
+
* scan is expensive to run inside a deploy: `staged: true` maintains the
|
|
201
|
+
* index on write only and leaves the initial population to an out-of-band
|
|
202
|
+
* run.
|
|
203
|
+
*
|
|
204
|
+
* That run is mandatory, not optional — until it happens, every row written
|
|
205
|
+
* BEFORE the deploy is unsearchable. Drive it against a deployment with
|
|
206
|
+
* `lunora run '__lunora_admin__:backfillSearch' --args '{"maxPages":20}'`,
|
|
207
|
+
* repeating until the response reports `done: true`; progress is durable, so
|
|
208
|
+
* each call resumes where the last stopped.
|
|
209
|
+
*/
|
|
210
|
+
staged?: boolean;
|
|
211
|
+
/**
|
|
212
|
+
* How the index is stored and matched.
|
|
213
|
+
*
|
|
214
|
+
* `"portable"` (default) keeps one implementation on every backend, with
|
|
215
|
+
* identical matching *and* ranking — the invariant the rest of the search
|
|
216
|
+
* docs rest on.
|
|
217
|
+
*
|
|
218
|
+
* `"native"` hands matching to the engine's own full-text index where it has
|
|
219
|
+
* one (Postgres `tsvector` + GIN today; ignored elsewhere). It scales far
|
|
220
|
+
* better on large corpora and common terms, because the portable path
|
|
221
|
+
* aggregates every matching token row before ranking. The trade: the engine
|
|
222
|
+
* ranks, so results are ordered by its formula rather than the shared
|
|
223
|
+
* scorer. Matching still agrees — the vector is built from the same analyzed
|
|
224
|
+
* tokens — but a `.global()` table using it will not return rows in the same
|
|
225
|
+
* order as the sharded twin.
|
|
226
|
+
*/
|
|
227
|
+
strategy?: SearchStrategy;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* A geospatial index declared via `.geoIndex(name, { field })`. The runtime
|
|
231
|
+
* maintains a geohash companion table over the `v.geoPoint()` column `field` so
|
|
232
|
+
* `withGeoIndex(name, q => q.near(point, radius) | q.within(bbox))` resolves a
|
|
233
|
+
* proximity / bounding-box read as a geohash-prefix range scan plus a Haversine
|
|
234
|
+
* refine/sort on the candidate rows.
|
|
235
|
+
*
|
|
236
|
+
* - `field` — the `v.geoPoint()` column whose lat/lng feed the geohash.
|
|
237
|
+
* - `precision` — geohash character length on the companion (default 9, ~4.8 m cells); higher precision narrows each cell.
|
|
238
|
+
*/
|
|
239
|
+
interface GeoIndexDefinition {
|
|
240
|
+
field: string;
|
|
79
241
|
name: string;
|
|
242
|
+
precision?: number;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Declarative table-level TTL declared via `.ttl(field, { after? })`. A DO
|
|
246
|
+
* alarm-driven sweep deletes (or, when the table also `.softDelete()`s,
|
|
247
|
+
* soft-deletes) rows whose expiry timestamp has passed.
|
|
248
|
+
*
|
|
249
|
+
* - `field` — an epoch-millisecond column. Without `after`, its value is the absolute expiry instant; with `after`, `field` is a base timestamp and the row expires `after` milliseconds later (`field + after`).
|
|
250
|
+
* - `after` — optional millisecond offset added to `field` to derive the expiry.
|
|
251
|
+
*/
|
|
252
|
+
interface TtlDefinition {
|
|
253
|
+
after?: number;
|
|
254
|
+
field: string;
|
|
80
255
|
}
|
|
81
256
|
/** Reducer applied by an aggregate index. */
|
|
82
257
|
type AggregateOp = "avg" | "count" | "max" | "min" | "sum";
|
|
83
258
|
/**
|
|
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
|
-
*/
|
|
259
|
+
* Declared aggregate index — the schema-level seam that lets the runtime keep
|
|
260
|
+
* O(1) counters/sums in step with row writes (via the trigger runner) and
|
|
261
|
+
* route matching reads through them.
|
|
262
|
+
*
|
|
263
|
+
* - `on` — the table whose rows feed the aggregate.
|
|
264
|
+
* - `op` — the reducer. `count` is field-less; the others take `field`.
|
|
265
|
+
* - `field` — the column the reducer applies to (required for non-count ops).
|
|
266
|
+
* - `by` — group keys. When all `where` keys in a read participate in `by`, the
|
|
267
|
+
* reader can answer from the counter table without scanning rows.
|
|
268
|
+
* - `where` — optional static predicate baked into the counter (only the rows
|
|
269
|
+
* matching it ever land in the counter).
|
|
270
|
+
*/
|
|
96
271
|
interface AggregateIndexDefinition {
|
|
97
272
|
by?: ReadonlyArray<string>;
|
|
98
273
|
field?: string;
|
|
@@ -102,32 +277,32 @@ interface AggregateIndexDefinition {
|
|
|
102
277
|
where?: Record<string, unknown>;
|
|
103
278
|
}
|
|
104
279
|
/**
|
|
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
|
-
*/
|
|
280
|
+
* One ordering key on a `rankIndex.sortBy`: which column to sort by, and the
|
|
281
|
+
* direction. The runtime breaks ties on the row's `_id` ASC so the order is
|
|
282
|
+
* total and `rank()` always returns a deterministic 1-based position.
|
|
283
|
+
*/
|
|
109
284
|
interface RankSortKey {
|
|
110
285
|
direction: "asc" | "desc";
|
|
111
286
|
field: string;
|
|
112
287
|
}
|
|
113
288
|
/**
|
|
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
|
-
*/
|
|
289
|
+
* Declared rank index — a sorted companion table per `(partition tuple, sortBy)`
|
|
290
|
+
* maintained by triggers, so:
|
|
291
|
+
*
|
|
292
|
+
* - `rank(row)` returns the row's 1-based position within its partition under
|
|
293
|
+
* the declared `sortBy` order, plus the partition's total row count, in
|
|
294
|
+
* O(log n) lookups against the SQLite btree on the companion table.
|
|
295
|
+
* - `rankPage({ where, take, from })` walks the same companion table to return
|
|
296
|
+
* rows in the declared order — a sorted-pagination accelerator.
|
|
297
|
+
*
|
|
298
|
+
* Fields mirror `AggregateIndexDefinition`:
|
|
299
|
+
*
|
|
300
|
+
* - `on` — the source table whose rows feed the rank.
|
|
301
|
+
* - `sortBy` — ordered keys driving the rank. Required.
|
|
302
|
+
* - `partitionBy` — columns that scope each rank context (e.g. `["channelId"]`
|
|
303
|
+
* to rank within a channel). Omitted ⇒ one global rank across the table.
|
|
304
|
+
* - `where` — static predicate baked into the index; only matching rows enter.
|
|
305
|
+
*/
|
|
131
306
|
interface RankIndexDefinition {
|
|
132
307
|
name: string;
|
|
133
308
|
on: string;
|
|
@@ -138,16 +313,16 @@ interface RankIndexDefinition {
|
|
|
138
313
|
/** FK behavior when a referenced parent row is deleted (mirrors SQL `ON DELETE`). */
|
|
139
314
|
type OnDeleteAction = "cascade" | "restrict" | "set null";
|
|
140
315
|
/**
|
|
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
|
-
*/
|
|
316
|
+
* A declared relation between two tables, recorded by `.relations((r) => …)`.
|
|
317
|
+
*
|
|
318
|
+
* - `one` (many-to-one): the FK column `field` lives on **this** table and
|
|
319
|
+
* points at `table`.`references` (default `_id`). Loads a single doc.
|
|
320
|
+
* - `many` (one-to-many): the FK column `field` lives on the **target** table
|
|
321
|
+
* and points back at this table's `references` (default `_id`). Loads an array.
|
|
322
|
+
*
|
|
323
|
+
* `onDelete` is meaningful only on `one`: it is the action applied to the
|
|
324
|
+
* holder rows when the referenced parent row is deleted.
|
|
325
|
+
*/
|
|
151
326
|
interface RelationDefinition {
|
|
152
327
|
field: string;
|
|
153
328
|
kind: "many" | "one";
|
|
@@ -158,15 +333,15 @@ interface RelationDefinition {
|
|
|
158
333
|
/** Distance metric used by a Vectorize index. */
|
|
159
334
|
type VectorMetric = "cosine" | "dot-product" | "euclidean";
|
|
160
335
|
/**
|
|
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
|
-
*/
|
|
336
|
+
* Bring-your-own-embedder: a user-supplied fn turning a source string into a
|
|
337
|
+
* numeric vector. The runtime calls it at upsert/query time so the framework
|
|
338
|
+
* never couples to a single embedding provider.
|
|
339
|
+
*/
|
|
165
340
|
type VectorEmbedder = (input: string) => Promise<ReadonlyArray<number>> | ReadonlyArray<number>;
|
|
166
341
|
/**
|
|
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
|
-
*/
|
|
342
|
+
* Vector index declared inline on a table via `.vectorize(field, opts)`
|
|
343
|
+
* (DSL Shape A). The source is always a single column on the owning table.
|
|
344
|
+
*/
|
|
170
345
|
interface TableVectorIndex {
|
|
171
346
|
dimensions: number;
|
|
172
347
|
embed: VectorEmbedder;
|
|
@@ -177,82 +352,127 @@ interface TableVectorIndex {
|
|
|
177
352
|
}
|
|
178
353
|
interface TableDefinition<Shape extends Record<string, Validator> = Record<string, Validator>> {
|
|
179
354
|
/**
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
355
|
+
* Aggregate indexes declared via `.aggregateIndex(name, opts)`. The runtime
|
|
356
|
+
* maintains a counter row per `by` group via the trigger seam, so reads
|
|
357
|
+
* whose `where` keys all participate in the index's `by` set are answered
|
|
358
|
+
* without scanning the underlying table.
|
|
359
|
+
*/
|
|
185
360
|
aggregateIndexes: ReadonlyArray<AggregateIndexDefinition>;
|
|
186
361
|
/**
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
362
|
+
* Set by `.commitOrdered()` (named `commitOrderedMode`, not `commitOrdered`,
|
|
363
|
+
* so the data field doesn't collide with the fluent `.commitOrdered()`
|
|
364
|
+
* builder method — same convention as `shardBy()`/`shardMode`). When `true`,
|
|
365
|
+
* every write to a row stamps `_commitSeq`: a per-shard integer allocated
|
|
366
|
+
* once per mutation and strictly increasing in commit order. Absent/`false`
|
|
367
|
+
* ⇒ rows carry no `_commitSeq`, as before.
|
|
368
|
+
*/
|
|
369
|
+
commitOrderedMode?: boolean;
|
|
370
|
+
/**
|
|
371
|
+
* Set by `.source(...)` (named `externalSource`, not `source`, so the data
|
|
372
|
+
* field doesn't collide with the fluent `.source()` builder method — same
|
|
373
|
+
* convention as `shardBy()`/`shardMode`). When present, the table is
|
|
374
|
+
* materialized from an external Hyperdrive-backed database by a system poll
|
|
375
|
+
* loop rather than user mutations. Implies `isExternallyManaged`.
|
|
376
|
+
*/
|
|
193
377
|
externalSource?: ExternalSourceDefinition;
|
|
378
|
+
/**
|
|
379
|
+
* Geospatial indexes declared via `.geoIndex(name, { field })`. The runtime
|
|
380
|
+
* maintains a geohash companion over the named `v.geoPoint()` column so
|
|
381
|
+
* `withGeoIndex(name, q => q.near(point, radius) | q.within(bbox))` resolves
|
|
382
|
+
* a proximity/bounding-box read as a geohash-prefix range scan plus a
|
|
383
|
+
* Haversine refine/sort. Empty unless `.geoIndex()` was called.
|
|
384
|
+
*/
|
|
385
|
+
geoIndexes: ReadonlyArray<GeoIndexDefinition>;
|
|
194
386
|
indexes: ReadonlyArray<IndexDefinition>;
|
|
195
387
|
/**
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
388
|
+
* `true` when `.externallyManaged()` was called — the table's rows are
|
|
389
|
+
* written outside Lunora's discoverable insert path (an adapter, a
|
|
390
|
+
* migration, or framework middleware), e.g. `@lunora/auth`'s better-auth
|
|
391
|
+
* tables or `@lunora/ratelimit`'s store. Advisor insert-path lints
|
|
392
|
+
* (`table_without_insert`) skip such tables instead of flagging the absent
|
|
393
|
+
* `ctx.db.insert(...)`.
|
|
394
|
+
*/
|
|
203
395
|
isExternallyManaged?: boolean;
|
|
204
396
|
/**
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
397
|
+
* `true` when `.public()` was called — the table opts OUT of secure-by-default
|
|
398
|
+
* RLS. Under a schema marked `.rls("required")`, every table is protected (the
|
|
399
|
+
* DO/D1 write path denies raw, non-RLS `ctx.db` access) UNLESS it is `isPublic`.
|
|
400
|
+
* Has no effect when the schema does not require RLS.
|
|
401
|
+
*/
|
|
210
402
|
isPublic?: boolean;
|
|
211
403
|
/**
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
404
|
+
* Set by `.memory()` (named `memoryMode`, not `memory`, so the data field
|
|
405
|
+
* doesn't collide with the fluent `.memory()` builder method — same
|
|
406
|
+
* convention as `shardBy()`/`shardMode`). When `true`, the table's rows are
|
|
407
|
+
* cleared every time the Durable Object is reconstructed, and its writes
|
|
408
|
+
* never reach the CDC changelog. Absent/`false` ⇒ an ordinary durable table.
|
|
409
|
+
*/
|
|
410
|
+
memoryMode?: boolean;
|
|
411
|
+
/**
|
|
412
|
+
* Set by `.ownedBy(field)` — the column holding the owning user's id (named
|
|
413
|
+
* `ownerField`, a data field, rather than colliding with the fluent
|
|
414
|
+
* `.ownedBy()` builder method — same convention as `shardBy()`/`shardMode`).
|
|
415
|
+
*
|
|
416
|
+
* A shape over this table with `owner: true` derives its predicate from this
|
|
417
|
+
* field, so "only the owner may replicate these rows" is declared once on the
|
|
418
|
+
* table instead of being restated in every shape's `where`. Absent ⇒ the table
|
|
419
|
+
* has no single owning column and a shape must spell its predicate out.
|
|
420
|
+
*/
|
|
421
|
+
ownerField?: string;
|
|
422
|
+
/**
|
|
423
|
+
* Rank indexes declared via `.rankIndex(name, opts)`. The runtime maintains
|
|
424
|
+
* a sorted companion table per declared rank with a btree on
|
|
425
|
+
* `(partition, sortBy)` so `rank(row)` returns the row's 1-based position
|
|
426
|
+
* within its partition in O(log n), and `rankPage()` walks the index for
|
|
427
|
+
* sorted pagination.
|
|
428
|
+
*/
|
|
218
429
|
rankIndexes: ReadonlyArray<RankIndexDefinition>;
|
|
219
430
|
/**
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
431
|
+
* Declared relations keyed by accessor name; empty unless `.relations()`
|
|
432
|
+
* was called. Named `relationMap` (not `relations`) so the fluent
|
|
433
|
+
* `.relations((r) => …)` builder method doesn't collide with this field.
|
|
434
|
+
*/
|
|
224
435
|
relationMap: Record<string, RelationDefinition>;
|
|
225
436
|
searchIndexes: ReadonlyArray<SearchIndexDefinition>;
|
|
226
437
|
shape: Shape;
|
|
227
438
|
shardMode: ShardMode;
|
|
228
439
|
/**
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
440
|
+
* Set by `.softDelete()` (named `softDeleteMode`, not `softDelete`, so the
|
|
441
|
+
* data field doesn't collide with the fluent `.softDelete()` builder method —
|
|
442
|
+
* same convention as `shardBy()`/`shardMode`). When present, the table carries
|
|
443
|
+
* a nullable timestamp column (`field`, default `deletedAt`):
|
|
444
|
+
* `ctx.db.<table>.delete()` flips it instead of physically removing the row,
|
|
445
|
+
* and **list reads** (`findMany`/`findFirst`/`query()`/`count`/`aggregate`/
|
|
446
|
+
* relation loads) hide rows whose `field` is set unless
|
|
447
|
+
* `includeDeleted: true` is passed. By-id `get`/`patch`/`replace` and
|
|
448
|
+
* `restore` are unaffected. Absent ⇒ deletes are physical, as before.
|
|
449
|
+
*/
|
|
239
450
|
softDeleteMode?: {
|
|
240
451
|
field: string;
|
|
241
452
|
};
|
|
242
453
|
/**
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
454
|
+
* Declared lifecycle triggers keyed by accessor name; empty unless
|
|
455
|
+
* `.triggers()` was called. Named `triggerMap` (not `triggers`) so the
|
|
456
|
+
* fluent `.triggers((t) => …)` builder method doesn't collide with this
|
|
457
|
+
* field — same reasoning as {@link TableDefinition.relationMap}.
|
|
458
|
+
*/
|
|
248
459
|
triggerMap: Record<string, TriggerDefinition>;
|
|
460
|
+
/**
|
|
461
|
+
* Set by `.ttl(field, { after })` — the declarative auto-expiry policy. A DO
|
|
462
|
+
* alarm-driven sweep deletes rows whose expiry timestamp has passed (or
|
|
463
|
+
* soft-deletes them when the table also `.softDelete()`s). Named `ttlPolicy`
|
|
464
|
+
* (a data field) rather than colliding with the fluent `.ttl()` builder
|
|
465
|
+
* method — same convention as `shardBy()`/`shardMode`. Absent ⇒ rows never
|
|
466
|
+
* auto-expire.
|
|
467
|
+
*/
|
|
468
|
+
ttlPolicy?: TtlDefinition;
|
|
249
469
|
vectorIndexes: ReadonlyArray<TableVectorIndex>;
|
|
250
470
|
}
|
|
251
471
|
/**
|
|
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
|
-
*/
|
|
472
|
+
* Standalone vector index declared via `defineVectorIndex(...)` (DSL Shape B).
|
|
473
|
+
* Unlike {@link TableVectorIndex}, the source is a `select` function so it can
|
|
474
|
+
* derive the embedded text from any computation (e.g. `title + body`).
|
|
475
|
+
*/
|
|
256
476
|
interface VectorIndexDefinition {
|
|
257
477
|
readonly dimensions: number;
|
|
258
478
|
readonly embed: VectorEmbedder;
|
|
@@ -264,50 +484,217 @@ interface VectorIndexDefinition {
|
|
|
264
484
|
}
|
|
265
485
|
interface Schema<T extends Record<string, TableDefinition> = Record<string, TableDefinition>> {
|
|
266
486
|
/**
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
487
|
+
* Secure-by-default RLS mode declared via `.rls("required")`. When
|
|
488
|
+
* `"required"`, every table is protected: the DO/D1 write path denies raw
|
|
489
|
+
* (non-RLS-wrapped) `ctx.db` access at runtime, so a procedure that forgets
|
|
490
|
+
* `.use(rls(...))` fails closed instead of silently exposing the table. A
|
|
491
|
+
* table opts out with `.public()` (→ {@link TableDefinition.isPublic}).
|
|
492
|
+
* Absent ⇒ legacy opt-in behavior (RLS only where a policy is applied).
|
|
493
|
+
*/
|
|
274
494
|
readonly rlsMode?: "required";
|
|
275
495
|
readonly tables: T;
|
|
276
496
|
readonly vectorIndexes: Record<string, VectorIndexDefinition>;
|
|
277
497
|
}
|
|
278
498
|
type FunctionKind = "action" | "mutation" | "query" | "stream";
|
|
279
499
|
/**
|
|
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
|
-
*/
|
|
500
|
+
* Call surface a function is exposed on. `public` functions are reachable from
|
|
501
|
+
* clients via the generated `api`; `internal` functions are reachable only
|
|
502
|
+
* server-to-server (`ctx.runQuery`/`runMutation`/`runAction`) and are rejected
|
|
503
|
+
* by the DO's external RPC path. Absence is treated as `public` for
|
|
504
|
+
* back-compat with functions registered before visibility existed.
|
|
505
|
+
*/
|
|
286
506
|
type FunctionVisibility = "internal" | "public";
|
|
507
|
+
/**
|
|
508
|
+
* x402 payment tag attached by the `.x402({ price })` builder modifier. Marks a
|
|
509
|
+
* public procedure as paid: the origin worker answers an unpaid client RPC with
|
|
510
|
+
* HTTP 402, verifies + settles the payment, and only then dispatches to the
|
|
511
|
+
* shard. The runtime reads only `price` from here — the network, recipient, and
|
|
512
|
+
* facilitator live in the worker-level x402 charge config, so `@lunora/runtime`
|
|
513
|
+
* never has to import `@lunora/x402` (and its viem/solana deps).
|
|
514
|
+
*/
|
|
515
|
+
interface X402ProcedureConfig {
|
|
516
|
+
/**
|
|
517
|
+
* USD-denominated price: a number of dollars (`0.01`) or a decimal string
|
|
518
|
+
* (`"0.01"`, or the `"$0.01"` shorthand). Resolved to the network
|
|
519
|
+
* stablecoin's base units (USDC has 6 decimals) at challenge time.
|
|
520
|
+
*/
|
|
521
|
+
readonly price: number | string;
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* HTTP caching for an exposed REST endpoint, declared as
|
|
525
|
+
* `.expose({ rest: true, cache: { scope: "public", maxAge: 60 } })`. The runtime
|
|
526
|
+
* turns this into `Cache-Control` / `Cache-Tag` / `Vary` response headers, and a
|
|
527
|
+
* `cache.tag` is purgeable through `ctx.cache.purge({ tags: [...] })`.
|
|
528
|
+
*
|
|
529
|
+
* This is NOT equivalent to `httpRoute(...).cacheControl()`, which writes whatever
|
|
530
|
+
* value the author passes with no credential downgrade. That is the unguarded
|
|
531
|
+
* escape hatch; this is the guarded surface.
|
|
532
|
+
*
|
|
533
|
+
* Caching a procedure whose result depends on the caller is how a REST cache
|
|
534
|
+
* turns into a data leak, so `scope` is enforced at runtime rather than trusted:
|
|
535
|
+
* a request that carries credentials (an `Authorization` header or any `Cookie`)
|
|
536
|
+
* is ALWAYS answered `private`, even under `scope: "public"` — see
|
|
537
|
+
* {@link https://developer.mozilla.org/docs/Web/HTTP/Headers/Cache-Control MDN}
|
|
538
|
+
* for what `private` forbids. So a per-user response can never be stored in a
|
|
539
|
+
* shared/edge cache, and the worst a mis-declared `scope` can cost is a missed
|
|
540
|
+
* cache hit. `scope: "public"` additionally emits `Vary: authorization, cookie`
|
|
541
|
+
* so an intermediary can't hand a stored anonymous variant to a signed-in caller.
|
|
542
|
+
*
|
|
543
|
+
* Only ever applied to a cacheable exchange: a `GET` (so `query` procedures — a
|
|
544
|
+
* `mutation` / `action` is `POST`-only) that produced a 2xx.
|
|
545
|
+
*/
|
|
546
|
+
type RestCacheConfig = RestCachePolicy;
|
|
547
|
+
/**
|
|
548
|
+
* Opt-in public-surface tag attached by the `.expose({ rest: true })` builder
|
|
549
|
+
* modifier (plan 167). Marks a procedure as deliberately published over the
|
|
550
|
+
* public REST surface: the runtime mints a `/_lunora/rest/<namespace>/<fn>` route
|
|
551
|
+
* that dispatches THROUGH the procedure (so `ctx.auth` / RLS / validators are
|
|
552
|
+
* enforced), and the generated OpenAPI describes it. Everything is default-closed
|
|
553
|
+
* — a procedure without this tag is unreachable over REST.
|
|
554
|
+
*/
|
|
555
|
+
interface ExposeConfig {
|
|
556
|
+
/** Opt this endpoint's responses into HTTP caching. Omit to leave them uncached. */
|
|
557
|
+
readonly cache?: RestCacheConfig;
|
|
558
|
+
/** Publish this procedure over the public REST surface. */
|
|
559
|
+
readonly rest?: boolean;
|
|
560
|
+
}
|
|
287
561
|
interface RegisteredFunction<A extends ArgsValidator, R, Kind extends FunctionKind> {
|
|
288
562
|
readonly args: A;
|
|
563
|
+
/**
|
|
564
|
+
* Set by the `.expose({ rest: true })` builder modifier. Marks the procedure
|
|
565
|
+
* as published on the public REST surface (plan 167). Absent on procedures that
|
|
566
|
+
* are reachable only via typed RPC (the default).
|
|
567
|
+
*/
|
|
568
|
+
readonly expose?: ExposeConfig;
|
|
289
569
|
readonly handler: (context: unknown, args: InferArgs<A>) => Promise<R> | R;
|
|
290
570
|
readonly kind: Kind;
|
|
291
571
|
/**
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
572
|
+
* Set on connection-lifecycle hooks (`onConnect` / `onDisconnect`).
|
|
573
|
+
* Marks the function for the generated `LUNORA_LIFECYCLE_HOOKS` manifest so the
|
|
574
|
+
* DO dispatches it on socket connect/disconnect rather than via a client RPC.
|
|
575
|
+
* Absent on ordinary registrations.
|
|
576
|
+
*/
|
|
297
577
|
readonly lifecycle?: LifecycleEventKind;
|
|
578
|
+
/**
|
|
579
|
+
* Static per-procedure metadata declared with `.meta(...)`. Present so
|
|
580
|
+
* middleware (via `ctx.meta`) and tooling can read the same object; absent
|
|
581
|
+
* when the chain never called `.meta()`.
|
|
582
|
+
*/
|
|
583
|
+
readonly meta?: Readonly<Record<string, unknown>>;
|
|
298
584
|
readonly visibility?: FunctionVisibility;
|
|
585
|
+
/**
|
|
586
|
+
* Set by the `.x402({ price })` builder modifier. Marks the procedure as paid
|
|
587
|
+
* so the origin worker gates it behind an x402 402-challenge before dispatch.
|
|
588
|
+
* Absent on unpaid functions.
|
|
589
|
+
*/
|
|
590
|
+
readonly x402?: X402ProcedureConfig;
|
|
299
591
|
}
|
|
300
592
|
type RegisteredQuery<A extends ArgsValidator, R> = RegisteredFunction<A, R, "query">;
|
|
301
593
|
type RegisteredMutation<A extends ArgsValidator, R> = RegisteredFunction<A, R, "mutation">;
|
|
302
594
|
type RegisteredAction<A extends ArgsValidator, R> = RegisteredFunction<A, R, "action">;
|
|
595
|
+
/**
|
|
596
|
+
* Structural mirror of `@lunora/client`'s `FunctionReference` — the handle the
|
|
597
|
+
* generated `api` / `internal` objects hand you, carrying `<file>:<function>`
|
|
598
|
+
* in `__lunoraRef`. Redeclared here so `@lunora/server` needs no dependency on
|
|
599
|
+
* the client package, exactly as {@link Scheduler} avoids one on
|
|
600
|
+
* `@lunora/scheduler`. `RegisteredFunction` has no `__lunoraRef`, so the two
|
|
601
|
+
* shapes never overlap.
|
|
602
|
+
*/
|
|
603
|
+
interface FunctionHandle<Kind extends "action" | "mutation" | "query" | "stream", Args, Return> {
|
|
604
|
+
/** Phantom marker carrying the type parameters; never present at runtime. */
|
|
605
|
+
readonly __lunoraPhantom?: {
|
|
606
|
+
args: Args;
|
|
607
|
+
kind: Kind;
|
|
608
|
+
returns: Return;
|
|
609
|
+
};
|
|
610
|
+
readonly __lunoraRef: string;
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* `ctx.runQuery` — overloaded, see the note above.
|
|
614
|
+
*
|
|
615
|
+
* A single generic signature over the reference would be nicer (TS will not
|
|
616
|
+
* contextually type a parameter against a multi-signature type, so a hand-built
|
|
617
|
+
* ctx object must annotate its `(reference, args)` explicitly — see
|
|
618
|
+
* `@lunora/testing`'s harness). It does not work: a concrete
|
|
619
|
+
* `RegisteredQuery<{…}, number>` is not assignable to a
|
|
620
|
+
* `RegisteredFunction<ArgsValidator, …>` constraint, because `handler`'s args
|
|
621
|
+
* are in a contravariant position. Two inference sites it is.
|
|
622
|
+
*/
|
|
623
|
+
/**
|
|
624
|
+
* Options for `ctx.runQuery`.
|
|
625
|
+
*
|
|
626
|
+
* Lunora's answer to Convex's `useStaleSnapshot`, and deliberately NOT a port of
|
|
627
|
+
* it. Convex needs that flag because a mutation there validates its whole read
|
|
628
|
+
* set at commit, so merely *reading* a hot append-only table manufactures OCC
|
|
629
|
+
* conflicts. Lunora has no such conflict class: its OCC is a compare-and-swap on
|
|
630
|
+
* the `__doc__` of each row a mutation actually WRITES (see `runGuardedWrite`),
|
|
631
|
+
* so a read costs a mutation nothing and there is nothing for a stale snapshot
|
|
632
|
+
* to relieve.
|
|
633
|
+
*
|
|
634
|
+
* What a read does cost here is REACTIVITY. Every table a live query touches
|
|
635
|
+
* enters its read footprint, and every write to any of those tables re-runs the
|
|
636
|
+
* subscription. A query that reads one hot table — an append-only audit log, a
|
|
637
|
+
* counter, a feed — therefore re-runs on every append even when the append
|
|
638
|
+
* cannot change its result. That is Lunora's version of the pressure Convex is
|
|
639
|
+
* relieving, and {@link RunQueryOptions.untracked} is the release valve.
|
|
640
|
+
*/
|
|
641
|
+
interface RunQueryOptions {
|
|
642
|
+
/**
|
|
643
|
+
* Run the query without recording its reads in the CALLER's read footprint.
|
|
644
|
+
* The subscription therefore does not re-run when the tables that query
|
|
645
|
+
* touched change.
|
|
646
|
+
*
|
|
647
|
+
* The result is exactly as fresh as a tracked call — same SQLite, same
|
|
648
|
+
* instant, no snapshot involved. The only thing given up is the invalidation
|
|
649
|
+
* edge, so use it when the read genuinely should not wake the subscriber
|
|
650
|
+
* (a monotonic counter rendered once, a config row, an audit tail whose
|
|
651
|
+
* growth is irrelevant to the result) — and never for data whose change
|
|
652
|
+
* should reach the client, which is what makes the subscription stale
|
|
653
|
+
* indefinitely rather than merely late.
|
|
654
|
+
*
|
|
655
|
+
* Scoped to the sub-query and nothing else: the untracked call runs on its
|
|
656
|
+
* own context, so a read interleaved on the caller's `ctx.db` while it is in
|
|
657
|
+
* flight still tracks normally. That is why this is an option on
|
|
658
|
+
* `ctx.runQuery` rather than a `ctx.db.untracked(...)` scope — a
|
|
659
|
+
* writer-wide flag would silently swallow a concurrent read's dependency
|
|
660
|
+
* (compare `meterExempt`'s documented interleaving caveat, which is
|
|
661
|
+
* tolerable for a resource meter and would not be here).
|
|
662
|
+
*
|
|
663
|
+
* No effect outside a subscription: a one-shot query records no footprint,
|
|
664
|
+
* so there is nothing to opt out of.
|
|
665
|
+
*/
|
|
666
|
+
untracked?: boolean;
|
|
667
|
+
}
|
|
668
|
+
interface RunQuery {
|
|
669
|
+
<A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args: InferArgs<A>, options?: RunQueryOptions): Promise<R>;
|
|
670
|
+
<Args, R>(reference: FunctionHandle<"query", Args, R>, args: Args, options?: RunQueryOptions): Promise<R>;
|
|
671
|
+
}
|
|
672
|
+
/** `ctx.runMutation` — overloaded for the same reason as {@link RunQuery}. */
|
|
673
|
+
interface RunMutation {
|
|
674
|
+
<A extends ArgsValidator, R>(reference: RegisteredMutation<A, R>, args: InferArgs<A>): Promise<R>;
|
|
675
|
+
<Args, R>(reference: FunctionHandle<"mutation", Args, R>, args: Args): Promise<R>;
|
|
676
|
+
}
|
|
677
|
+
/** `ctx.runAction` — overloaded for the same reason as {@link RunQuery}. */
|
|
678
|
+
interface RunAction {
|
|
679
|
+
<A extends ArgsValidator, R>(reference: RegisteredAction<A, R>, args: InferArgs<A>): Promise<R>;
|
|
680
|
+
<Args, R>(reference: FunctionHandle<"action", Args, R>, args: Args): Promise<R>;
|
|
681
|
+
}
|
|
303
682
|
/** Which side of the WebSocket lifecycle a hook fires on. */
|
|
304
|
-
type LifecycleEventKind = "connect" | "disconnect";
|
|
305
683
|
/**
|
|
306
|
-
*
|
|
307
|
-
*
|
|
308
|
-
*
|
|
309
|
-
*
|
|
310
|
-
|
|
684
|
+
* Which lifecycle moment a hook fires on.
|
|
685
|
+
*
|
|
686
|
+
* `connect`/`disconnect` are per-SOCKET and fire many times over a shard's life.
|
|
687
|
+
* `init` is per-INSTANCE and fires once per cold start, before any handler runs
|
|
688
|
+
* — see {@link ShardInitEvent}. `reactor` is per-WRITE-FLUSH and fires only when
|
|
689
|
+
* a watched read's result changed — see `onQueryChange`.
|
|
690
|
+
*/
|
|
691
|
+
type LifecycleEventKind = "connect" | "disconnect" | "init" | "reactor";
|
|
692
|
+
/**
|
|
693
|
+
* The event a connection-lifecycle hook receives as its second argument. It is
|
|
694
|
+
* the JSON-serializable payload the DO forwards on socket connect/disconnect;
|
|
695
|
+
* the verified caller identity is also reflected on `ctx.auth` (the hook runs
|
|
696
|
+
* under the connecting user via `resolveIdentity`).
|
|
697
|
+
*/
|
|
311
698
|
interface LifecycleEvent {
|
|
312
699
|
/** Stable per-socket id, minted at upgrade and replayed verbatim on disconnect. */
|
|
313
700
|
readonly connectionId: string;
|
|
@@ -319,33 +706,87 @@ interface LifecycleEvent {
|
|
|
319
706
|
readonly userId: string | null;
|
|
320
707
|
}
|
|
321
708
|
/**
|
|
322
|
-
* A registered connection-lifecycle hook — an internal mutation tagged with the
|
|
323
|
-
* lifecycle side it fires on. Produced by `onConnect` / `onDisconnect
|
|
324
|
-
|
|
709
|
+
* A registered connection-lifecycle hook — an internal mutation tagged with the
|
|
710
|
+
* lifecycle side it fires on. Produced by `onConnect` / `onDisconnect` /
|
|
711
|
+
* `onShardInit`.
|
|
712
|
+
*/
|
|
325
713
|
type RegisteredLifecycleHook = RegisteredFunction<Record<string, never>, void, "mutation"> & {
|
|
326
714
|
readonly lifecycle: LifecycleEventKind;
|
|
327
715
|
};
|
|
328
716
|
/**
|
|
329
|
-
*
|
|
330
|
-
*
|
|
331
|
-
*
|
|
332
|
-
*
|
|
333
|
-
*
|
|
334
|
-
*
|
|
335
|
-
|
|
717
|
+
* The event an `onShardInit` hook receives.
|
|
718
|
+
*
|
|
719
|
+
* Deliberately thin, and deliberately NOT a {@link LifecycleEvent}: there is no
|
|
720
|
+
* socket here. An init hook fires because the Durable Object was constructed,
|
|
721
|
+
* not because anyone connected — so there is no `connectionId` to report and no
|
|
722
|
+
* user to attribute it to. The hook runs as a trusted system dispatch with no
|
|
723
|
+
* request identity, exactly like a cron tick; `ctx.auth` is anonymous and RLS
|
|
724
|
+
* does not apply. Derive whatever you need from `shardKey` and the shard's own
|
|
725
|
+
* durable tables, never from an ambient caller — there isn't one.
|
|
726
|
+
*/
|
|
727
|
+
interface ShardInitEvent {
|
|
728
|
+
/** The shard this Durable Object instance serves. */
|
|
729
|
+
readonly shardKey: string;
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* A streaming query registration. Unlike {@link RegisteredFunction} the handler
|
|
733
|
+
* returns an `AsyncIterable<R>` synchronously (it does NOT `Promise<R>`); the
|
|
734
|
+
* runtime drives it frame by frame and forwards each chunk to the caller. The
|
|
735
|
+
* third `signal` argument is wired to the caller's cancel signal so the handler
|
|
736
|
+
* can stop early — break out of the loop or check `signal.aborted` between
|
|
737
|
+
* yields.
|
|
738
|
+
*/
|
|
336
739
|
interface RegisteredStream<A extends ArgsValidator, R> {
|
|
337
740
|
readonly args: A;
|
|
741
|
+
/**
|
|
742
|
+
* Present when the stream was declared `durable`. Chunks are persisted per
|
|
743
|
+
* run before they reach a socket, the producer outlives the socket that
|
|
744
|
+
* opened it, and a reconnecting (or second) client attaches to the same run
|
|
745
|
+
* and replays what it missed. See {@link DurableStreamOptions}.
|
|
746
|
+
*/
|
|
747
|
+
readonly durable?: DurableStreamOptions;
|
|
338
748
|
readonly handler: (context: unknown, args: InferArgs<A>, signal: AbortSignal) => AsyncIterable<R>;
|
|
339
749
|
readonly kind: "stream";
|
|
750
|
+
/** Static per-procedure metadata attached via `.meta()`. See {@link RegisteredFunction.meta}. */
|
|
751
|
+
readonly meta?: Readonly<Record<string, unknown>>;
|
|
340
752
|
readonly visibility?: FunctionVisibility;
|
|
341
753
|
}
|
|
754
|
+
/**
|
|
755
|
+
* Durability settings for a `.stream()` procedure.
|
|
756
|
+
*
|
|
757
|
+
* A run is identified by the socket's verified identity plus the function path
|
|
758
|
+
* and arguments, so two clients of the SAME user calling the same stream with
|
|
759
|
+
* the same arguments observe one producer and one transcript. That identity is
|
|
760
|
+
* the feature: it is what makes a reload resume rather than re-generate, and
|
|
761
|
+
* what lets a second tab watch the same answer. A different identity always gets
|
|
762
|
+
* its own run.
|
|
763
|
+
*
|
|
764
|
+
* Sharing applies to a run still in flight. Once a run finishes, a later caller
|
|
765
|
+
* asking the same question gets a fresh one — a transcript is the record of one
|
|
766
|
+
* execution, not a cached response.
|
|
767
|
+
*
|
|
768
|
+
* **What an attach does not do:** it replays a transcript, it does not re-run the
|
|
769
|
+
* handler — so the procedure's middleware chain (`.use(rls(...))`, rate limits,
|
|
770
|
+
* any custom guard) runs once, for the caller that started the run. That is why
|
|
771
|
+
* the run key is identity-scoped: a guard that has already passed for one user
|
|
772
|
+
* must never be skipped for another.
|
|
773
|
+
*/
|
|
774
|
+
interface DurableStreamOptions {
|
|
775
|
+
/**
|
|
776
|
+
* How long a finished transcript is kept before it is trimmed, in
|
|
777
|
+
* milliseconds. Defaults to 24 hours — long enough to survive a reload and
|
|
778
|
+
* a commute, short enough that a chatty shard doesn't accumulate
|
|
779
|
+
* transcripts forever.
|
|
780
|
+
*/
|
|
781
|
+
readonly ttlMs?: number;
|
|
782
|
+
}
|
|
342
783
|
/** The system tables `ctx.db.system` can read. */
|
|
343
784
|
type SystemTableName = "_scheduled_functions" | "_storage";
|
|
344
785
|
/**
|
|
345
|
-
* A pending scheduled invocation as surfaced by the `_scheduled_functions`
|
|
346
|
-
* system table. Mirrors {@link ScheduledJob} (the `ctx.scheduler` view); the
|
|
347
|
-
* separate name keeps the system-table read surface self-describing.
|
|
348
|
-
*/
|
|
786
|
+
* A pending scheduled invocation as surfaced by the `_scheduled_functions`
|
|
787
|
+
* system table. Mirrors {@link ScheduledJob} (the `ctx.scheduler` view); the
|
|
788
|
+
* separate name keeps the system-table read surface self-describing.
|
|
789
|
+
*/
|
|
349
790
|
interface ScheduledFunctionDoc {
|
|
350
791
|
/** Function arguments the job will be dispatched with. */
|
|
351
792
|
args: Record<string, unknown>;
|
|
@@ -375,55 +816,79 @@ interface SystemQuery<T extends SystemTableName> {
|
|
|
375
816
|
collect: () => Promise<SystemDoc<T>[]>;
|
|
376
817
|
}
|
|
377
818
|
/**
|
|
378
|
-
* Read-only reader over Lunora's system tables (`_scheduled_functions`,
|
|
379
|
-
* `_storage`), exposed as `ctx.db.system`. Mirrors Convex's `ctx.db.system`.
|
|
380
|
-
*
|
|
381
|
-
* **Best-effort and eventually consistent.** Unlike `ctx.db
|
|
382
|
-
* reads the shard's transactional SQLite snapshot — the data behind these tables
|
|
383
|
-
* lives OUTSIDE the shard (scheduled functions in the `SchedulerDO`, storage
|
|
384
|
-
* objects in R2). Every `collect()` / `get()` reaches across to that source.
|
|
385
|
-
*
|
|
386
|
-
* It is **not part of the mutation transaction snapshot** (no OCC guard, no
|
|
387
|
-
* subscription dependency recorded — reading it inside a mutation does not pin
|
|
388
|
-
* it), and results are **eventually consistent** with writes a mutation just
|
|
389
|
-
* made (e.g. a freshly scheduled job may not appear yet).
|
|
390
|
-
*
|
|
391
|
-
* Read-only by design: mutate scheduled jobs via `ctx.scheduler`, storage
|
|
392
|
-
* objects via `ctx.storage`.
|
|
393
|
-
*/
|
|
819
|
+
* Read-only reader over Lunora's system tables (`_scheduled_functions`,
|
|
820
|
+
* `_storage`), exposed as `ctx.db.system`. Mirrors Convex's `ctx.db.system`.
|
|
821
|
+
*
|
|
822
|
+
* **Best-effort and eventually consistent.** Unlike `ctx.db.<table>` — which
|
|
823
|
+
* reads the shard's transactional SQLite snapshot — the data behind these tables
|
|
824
|
+
* lives OUTSIDE the shard (scheduled functions in the `SchedulerDO`, storage
|
|
825
|
+
* objects in R2). Every `collect()` / `get()` reaches across to that source.
|
|
826
|
+
*
|
|
827
|
+
* It is **not part of the mutation transaction snapshot** (no OCC guard, no
|
|
828
|
+
* subscription dependency recorded — reading it inside a mutation does not pin
|
|
829
|
+
* it), and results are **eventually consistent** with writes a mutation just
|
|
830
|
+
* made (e.g. a freshly scheduled job may not appear yet).
|
|
831
|
+
*
|
|
832
|
+
* Read-only by design: mutate scheduled jobs via `ctx.scheduler`, storage
|
|
833
|
+
* objects via `ctx.storage`.
|
|
834
|
+
*/
|
|
394
835
|
interface SystemDatabaseReader {
|
|
395
836
|
/**
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
837
|
+
* Resolve a single system-table row by id, or `null` when absent.
|
|
838
|
+
* (`_scheduled_functions` → job id; `_storage` → object key.)
|
|
839
|
+
*/
|
|
399
840
|
get: <T extends SystemTableName>(table: T, id: string) => Promise<SystemDoc<T> | null>;
|
|
400
841
|
/**
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
842
|
+
* Begin a read over a system table; call `.collect()` to resolve the full
|
|
843
|
+
* list. No filtering, indexing, or pagination — the backing source is remote
|
|
844
|
+
* and the surface stays deliberately minimal.
|
|
845
|
+
*/
|
|
405
846
|
query: <T extends SystemTableName>(table: T) => SystemQuery<T>;
|
|
406
847
|
}
|
|
407
848
|
/**
|
|
408
|
-
* Read-only handle bound to a table. Used by `query`/`mutation`/`action`. The
|
|
409
|
-
* actual SQL implementation lives in `@lunora/do`; these are signatures only.
|
|
410
|
-
*/
|
|
849
|
+
* Read-only handle bound to a table. Used by `query`/`mutation`/`action`. The
|
|
850
|
+
* actual SQL implementation lives in `@lunora/do`; these are signatures only.
|
|
851
|
+
*/
|
|
411
852
|
interface DatabaseReader {
|
|
853
|
+
/**
|
|
854
|
+
* The throwing sibling of {@link DatabaseReader.normalizeId}: brand `id` as an
|
|
855
|
+
* {@link Id} for `tableName`, or throw `BAD_REQUEST` when it is not structurally
|
|
856
|
+
* an id. Pure — it never reads the database, so a valid id for a row that
|
|
857
|
+
* doesn't exist still returns.
|
|
858
|
+
*
|
|
859
|
+
* This is the **parse boundary** for an id that arrived as a plain `string`: a
|
|
860
|
+
* wire payload, a mutator's args, a change plan computed on the client. The
|
|
861
|
+
* alternative is `value as Id<"table">` at every such call site — an assertion,
|
|
862
|
+
* not a check, and one that has to be repeated for every table a helper is
|
|
863
|
+
* generic over:
|
|
864
|
+
*
|
|
865
|
+
* ```ts
|
|
866
|
+
* for (const patch of plan.patches) {
|
|
867
|
+
* await ctx.db.patch(ctx.db.asId("nodes", patch.id), patch.fields);
|
|
868
|
+
* }
|
|
869
|
+
* ```
|
|
870
|
+
*
|
|
871
|
+
* Ids are opaque strings, so the check is exactly `normalizeId`'s: it rejects
|
|
872
|
+
* empty, whitespace-bearing, and NUL-bearing values, not "an id that isn't in
|
|
873
|
+
* this table". Use it to get the brand honestly, and `get()` to learn whether
|
|
874
|
+
* the row exists.
|
|
875
|
+
*/
|
|
876
|
+
asId: <T extends string>(tableName: T, id: string) => Id<T>;
|
|
412
877
|
get: <T extends string>(id: Id<T>) => Promise<Record<string, unknown> | null>;
|
|
413
878
|
/**
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
879
|
+
* Validate an untrusted `id` string against the structural shape of an id
|
|
880
|
+
* for `tableName`, returning the branded {@link Id} when it is well-formed
|
|
881
|
+
* and `null` otherwise. Pure structural validation — it never reads the
|
|
882
|
+
* database, so a structurally valid id for a row that doesn't exist still
|
|
883
|
+
* returns the branded id (mirrors Convex's `db.normalizeId`).
|
|
884
|
+
*/
|
|
420
885
|
normalizeId: <T extends string>(tableName: T, id: string) => Id<T> | null;
|
|
421
886
|
query: (tableName: string) => TableReader;
|
|
422
887
|
/**
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
888
|
+
* Best-effort, read-only reader over Lunora's system tables
|
|
889
|
+
* (`_scheduled_functions`, `_storage`). Eventually consistent and **not**
|
|
890
|
+
* part of the transaction snapshot — see {@link SystemDatabaseReader}.
|
|
891
|
+
*/
|
|
427
892
|
readonly system: SystemDatabaseReader;
|
|
428
893
|
}
|
|
429
894
|
/** Options for {@link TableReader.paginate} — Convex-compatible page request. */
|
|
@@ -431,14 +896,14 @@ interface PaginationOptions {
|
|
|
431
896
|
/** Opaque cursor from the prior page's `continueCursor`; `null`/omitted starts at the first page. */
|
|
432
897
|
cursor?: null | string;
|
|
433
898
|
/**
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
899
|
+
* Optional inclusive upper bound for reactive pagination. When supplied the
|
|
900
|
+
* page covers the fixed half-open range `(cursor, endCursor]` (ignoring
|
|
901
|
+
* `numItems`): every row strictly after `cursor` up to and including the
|
|
902
|
+
* boundary row `endCursor` encodes. The page's `isDone` is `true` and its
|
|
903
|
+
* `continueCursor` echoes `endCursor`, so the next page keeps starting where
|
|
904
|
+
* this one ends even as rows are inserted/deleted inside the range. Omit (or
|
|
905
|
+
* pass `null`) for the legacy "first `numItems` after `cursor`" behaviour.
|
|
906
|
+
*/
|
|
442
907
|
endCursor?: null | string;
|
|
443
908
|
/** Maximum rows to return for this page. */
|
|
444
909
|
numItems: number;
|
|
@@ -451,47 +916,106 @@ interface PaginationResult<T = Record<string, unknown>> {
|
|
|
451
916
|
isDone: boolean;
|
|
452
917
|
page: T[];
|
|
453
918
|
/**
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
919
|
+
* Reactive-pagination only: the midpoint cursor of a bounded
|
|
920
|
+
* `(cursor, endCursor]` page, used by the client to split an over-grown page
|
|
921
|
+
* into two adjacent ranges. Absent on legacy (open-ended) pages.
|
|
922
|
+
*/
|
|
458
923
|
splitCursor?: null | string;
|
|
459
924
|
}
|
|
460
925
|
/**
|
|
461
|
-
* The fluent `ctx.db.query(table)` reader. Generic over the document type
|
|
462
|
-
* `Row` so the generated `ctx.db` can bind it to `Doc
|
|
463
|
-
* every terminal then resolve typed rows — no `as unknown as Doc
|
|
464
|
-
*
|
|
465
|
-
* (
|
|
466
|
-
|
|
467
|
-
|
|
926
|
+
* The fluent `ctx.db.query(table)` reader. Generic over the document type
|
|
927
|
+
* `Row` so the generated `ctx.db` can bind it to `Doc<table>` (the chain and
|
|
928
|
+
* every terminal then resolve typed rows — no `as unknown as Doc<...>` casts),
|
|
929
|
+
* and over the table's declared index names so `.withIndex()` / `.withSearchIndex()`
|
|
930
|
+
* / `.withGeoIndex()` reject a name the table does not declare.
|
|
931
|
+
*
|
|
932
|
+
* All four default to the untyped shape for the base (schema-agnostic)
|
|
933
|
+
* `@lunora/server` reader, which is also the wide `(table: string) => TableReader`
|
|
934
|
+
* overload the generated `ctx.db` intersects in — so a caller holding a runtime
|
|
935
|
+
* string (e.g. `@lunora/ratelimit`'s `createDbStore`) is unaffected.
|
|
936
|
+
*
|
|
937
|
+
* The index-name parameters are what make a stale index name a compile error.
|
|
938
|
+
* They resolve to `never` for a table that declares none of that kind, so the
|
|
939
|
+
* only way to satisfy the call is to declare the index. Before this, a renamed
|
|
940
|
+
* or dropped index left its call sites typechecking, and the query either threw
|
|
941
|
+
* at runtime or silently degraded to a full table scan — the second being the
|
|
942
|
+
* worse outcome, since it stays green in tests and surfaces months later as a
|
|
943
|
+
* latency regression.
|
|
944
|
+
*
|
|
945
|
+
* **Why `with*` are method signatures and everything else is a property.**
|
|
946
|
+
* Narrowing a parameter makes the enclosing type contravariant in it, so as
|
|
947
|
+
* function properties these would make a BOUND reader
|
|
948
|
+
* (`TableReader<Doc, "by_x">`, what `ctx.db.query(t)` returns) unassignable to
|
|
949
|
+
* the unbound `TableReader<Doc>` — quietly breaking every helper factored as
|
|
950
|
+
* `(reader: TableReader<Doc<"users">>) => …`, which is the obvious way to share
|
|
951
|
+
* query logic. A method signature is bivariant in its parameters, which keeps
|
|
952
|
+
* that direction working while the narrow parameter still rejects an undeclared
|
|
953
|
+
* name at the call site. Both directions are pinned in `types.test-d.ts`.
|
|
954
|
+
*/
|
|
955
|
+
interface TableReader<Row = Record<string, unknown>, Indexes extends string = string, SearchIndexes extends string = string, GeoIndexes extends string = string> {
|
|
956
|
+
/**
|
|
957
|
+
* Iterate rows lazily: `for await (const row of ctx.db.query("t").withIndex(…))`.
|
|
958
|
+
*
|
|
959
|
+
* Pages through the result set behind the scenes and yields row by row, so
|
|
960
|
+
* a consumer that stops early stops the reads too. `.collect()` is still the
|
|
961
|
+
* right terminal when you want the whole set; this exists for the cases
|
|
962
|
+
* where you cannot know up front how far you need to read.
|
|
963
|
+
*
|
|
964
|
+
* That is what merged/ordered index streams need. Reimplementing Convex's
|
|
965
|
+
* `convex-helpers/server/stream` in userland previously meant materialising
|
|
966
|
+
* each branch with a bounded `.take(1024)` before merging, so asking a
|
|
967
|
+
* merged stream for ONE row read up to 1,024 rows per branch. The k-way merge itself is application code and stays there — only
|
|
968
|
+
* the laziness had to come from the database layer.
|
|
969
|
+
*
|
|
970
|
+
* Iteration pages through `.paginate()`, so it follows the same order —
|
|
971
|
+
* which is `.collect()`'s order whenever the sort key is unique. Under a
|
|
972
|
+
* TIED sort key (an unindexed read whose rows share `_creationTime`) the
|
|
973
|
+
* two can disagree, because the tie-break is left to SQLite. Read through
|
|
974
|
+
* an index when order matters, exactly as you would for `.paginate()`.
|
|
975
|
+
*/
|
|
976
|
+
[Symbol.asyncIterator]: () => AsyncIterator<Row>;
|
|
468
977
|
collect: () => Promise<Row[]>;
|
|
469
|
-
filter: (predicate: (document: Row) => boolean) => TableReader<Row>;
|
|
978
|
+
filter: (predicate: (document: Row) => boolean) => TableReader<Row, Indexes, SearchIndexes, GeoIndexes>;
|
|
470
979
|
first: () => Promise<Row | null>;
|
|
471
980
|
/**
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
order: (direction: "asc" | "desc") => TableReader<Row>;
|
|
981
|
+
* Set the result order. Orders by the active `.withIndex()` (or by
|
|
982
|
+
* `_creationTime` when none is staged), `"asc"` by default; `"desc"`
|
|
983
|
+
* reverses it. Composes with `.withIndex()`, `.filter()`, and every
|
|
984
|
+
* terminal (`collect`/`first`/`take`/`paginate`/`unique`). Mirrors Convex's
|
|
985
|
+
* `.order("asc" | "desc")`.
|
|
986
|
+
*/
|
|
987
|
+
order: (direction: "asc" | "desc") => TableReader<Row, Indexes, SearchIndexes, GeoIndexes>;
|
|
479
988
|
paginate: (options: PaginationOptions) => Promise<PaginationResult<Row>>;
|
|
480
989
|
take: (limit: number) => Promise<Row[]>;
|
|
481
990
|
/**
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
991
|
+
* Return the single matching document. Returns `null` when nothing matches
|
|
992
|
+
* and throws when more than one row matches. Mirrors Convex's `.unique()`.
|
|
993
|
+
*/
|
|
485
994
|
unique: () => Promise<Row | null>;
|
|
486
|
-
withIndex: (indexName: string, range?: (q: IndexRangeBuilder) => IndexRangeBuilder) => TableReader<Row>;
|
|
487
995
|
/**
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
996
|
+
* Restrict the query to a declared `.geoIndex()`. The builder's
|
|
997
|
+
* `.near(point, radiusMeters)` returns rows within `radiusMeters` of `point`,
|
|
998
|
+
* ordered nearest-first; `.within(bbox)` returns rows inside the
|
|
999
|
+
* latitude/longitude bounding box. Both resolve as a geohash-prefix range
|
|
1000
|
+
* scan over the index's companion followed by a Haversine refine. Pair with
|
|
1001
|
+
* `.take(n)` to cap results (`.paginate()` is not supported on a geo query).
|
|
1002
|
+
*/
|
|
1003
|
+
withGeoIndex(indexName: GeoIndexes, build: (q: GeoFilterBuilder) => GeoFilterBuilder): TableReader<Row, Indexes, SearchIndexes, GeoIndexes>;
|
|
1004
|
+
/**
|
|
1005
|
+
* Restrict the query to a declared `.index()`. `indexName` is constrained to
|
|
1006
|
+
* this table's declared index names (`never` when it declares none), so a
|
|
1007
|
+
* renamed, dropped, or mistyped index is a compile error rather than a
|
|
1008
|
+
* runtime throw or a silent full-table scan.
|
|
1009
|
+
*/
|
|
1010
|
+
withIndex(indexName: Indexes, range?: (q: IndexRangeBuilder) => IndexRangeBuilder): TableReader<Row, Indexes, SearchIndexes, GeoIndexes>;
|
|
1011
|
+
/**
|
|
1012
|
+
* Restrict the query to a declared `.searchIndex()`. The builder's
|
|
1013
|
+
* `.search(field, query)` runs a full-text match against the index's
|
|
1014
|
+
* searchable field; `.eq(field, value)` narrows by a declared filter
|
|
1015
|
+
* field. Results come back ordered by relevance — pair with `.take(n)`
|
|
1016
|
+
* (`.paginate()` is not supported on a search query).
|
|
1017
|
+
*/
|
|
1018
|
+
withSearchIndex(indexName: SearchIndexes, search: (q: SearchFilterBuilder) => SearchFilterBuilder): TableReader<Row, Indexes, SearchIndexes, GeoIndexes>;
|
|
495
1019
|
}
|
|
496
1020
|
interface IndexRangeBuilder {
|
|
497
1021
|
eq: (field: string, value: unknown) => IndexRangeBuilder;
|
|
@@ -507,87 +1031,201 @@ interface SearchFilterBuilder {
|
|
|
507
1031
|
/** Full-text match `query` against the index's searchable `field`. Call exactly once. */
|
|
508
1032
|
search: (field: string, query: string) => SearchFilterBuilder;
|
|
509
1033
|
}
|
|
1034
|
+
/** A latitude/longitude point (WGS84 decimal degrees) accepted by geo queries. */
|
|
1035
|
+
interface GeoPointInput {
|
|
1036
|
+
lat: number;
|
|
1037
|
+
lng: number;
|
|
1038
|
+
}
|
|
1039
|
+
/**
|
|
1040
|
+
* An axis-aligned latitude/longitude bounding box: `sw` is the south-west
|
|
1041
|
+
* (min lat, min lng) corner, `ne` the north-east (max lat, max lng) corner.
|
|
1042
|
+
*/
|
|
1043
|
+
interface GeoBoundingBox {
|
|
1044
|
+
ne: GeoPointInput;
|
|
1045
|
+
sw: GeoPointInput;
|
|
1046
|
+
}
|
|
1047
|
+
/**
|
|
1048
|
+
* Builder passed to {@link TableReader.withGeoIndex}. Call exactly one of
|
|
1049
|
+
* `.near(...)` / `.within(...)` — the two are mutually exclusive proximity vs
|
|
1050
|
+
* bounding-box modes.
|
|
1051
|
+
*/
|
|
1052
|
+
interface GeoFilterBuilder {
|
|
1053
|
+
/** Rows within `radiusMeters` of `point`, resolved nearest-first. Call exactly once. */
|
|
1054
|
+
near: (point: GeoPointInput, radiusMeters: number) => GeoFilterBuilder;
|
|
1055
|
+
/** Rows whose point falls inside the bounding `box`. Call exactly once. */
|
|
1056
|
+
within: (box: GeoBoundingBox) => GeoFilterBuilder;
|
|
1057
|
+
}
|
|
510
1058
|
/**
|
|
511
|
-
* Options shared by the batch-write methods (`insertMany`/`deleteMany`/
|
|
512
|
-
* `patchMany`) — a per-call payload cap. The default cap (500) rejects an
|
|
513
|
-
* oversized call up front so an accidental O(n²) or a payload past the Durable
|
|
514
|
-
* Object request limit fails loudly instead of degrading the mutation. Callers
|
|
515
|
-
* with larger sets should chunk their own loop or raise `limit`.
|
|
516
|
-
*/
|
|
1059
|
+
* Options shared by the batch-write methods (`insertMany`/`deleteMany`/
|
|
1060
|
+
* `patchMany`) — a per-call payload cap. The default cap (500) rejects an
|
|
1061
|
+
* oversized call up front so an accidental O(n²) or a payload past the Durable
|
|
1062
|
+
* Object request limit fails loudly instead of degrading the mutation. Callers
|
|
1063
|
+
* with larger sets should chunk their own loop or raise `limit`.
|
|
1064
|
+
*/
|
|
517
1065
|
interface BatchWriteOptions {
|
|
518
1066
|
/** Reject the call when the batch size exceeds this value (default 500). */
|
|
519
1067
|
limit?: number;
|
|
520
1068
|
}
|
|
1069
|
+
/** Options accepted by {@link DatabaseWriter.insertMany} and the per-table facade. */
|
|
1070
|
+
interface InsertManyOptions extends BatchWriteOptions {
|
|
1071
|
+
/**
|
|
1072
|
+
* When `true`, a UNIQUE-constraint breach for a row resolves to `null`
|
|
1073
|
+
* instead of throwing — the rest of the batch is still inserted. Skipped rows
|
|
1074
|
+
* keep their input-order slot with `null` in the returned array. Mirrors
|
|
1075
|
+
* better-drizzle's `createMany({ skipDuplicates: true })`.
|
|
1076
|
+
*/
|
|
1077
|
+
skipDuplicates?: boolean;
|
|
1078
|
+
}
|
|
521
1079
|
interface DatabaseWriter extends DatabaseReader {
|
|
522
1080
|
delete: <T extends string>(id: Id<T>) => Promise<void>;
|
|
523
1081
|
/**
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
1082
|
+
* Delete EVERY row in `tableName`, chunking internally until the table is
|
|
1083
|
+
* empty — the erasure primitive.
|
|
1084
|
+
*
|
|
1085
|
+
* Unlike `deleteWhere(tableName, {})` there is **no batch cap**: a
|
|
1086
|
+
* `BATCH_LIMIT_EXCEEDED` at row 501 of an account deletion is a bug, not a
|
|
1087
|
+
* safety rail. Rows still go through the single-row delete pipeline, so
|
|
1088
|
+
* triggers, cascades, companions, CDC, and live subscriptions stay correct.
|
|
1089
|
+
*
|
|
1090
|
+
* On a `.softDelete()` table the default flips the marker column; pass
|
|
1091
|
+
* `{ hard: true }` to remove the rows physically (what GDPR erasure means).
|
|
1092
|
+
*/
|
|
1093
|
+
deleteAll: (tableName: string, options?: {
|
|
1094
|
+
chunkSize?: number;
|
|
1095
|
+
hard?: boolean;
|
|
1096
|
+
}) => Promise<{
|
|
1097
|
+
deleted: number;
|
|
1098
|
+
}>;
|
|
1099
|
+
/**
|
|
1100
|
+
* Delete many rows by id in one call. Each id is deleted through the full
|
|
1101
|
+
* single-row pipeline (triggers + per-row RLS). The returned `deleted` is the
|
|
1102
|
+
* number of ids **requested**, not the rows actually removed — an unknown or
|
|
1103
|
+
* duplicated id is a silent no-op.
|
|
1104
|
+
*
|
|
1105
|
+
* **Atomic within a mutation:** the DO wraps a mutation's dispatch in a
|
|
1106
|
+
* BEGIN/COMMIT span, so a mid-batch failure (a later RLS denial or handler
|
|
1107
|
+
* error) rolls back the whole mutation. (In an action there is no transaction
|
|
1108
|
+
* span, so the prior deletes persist; the in-memory test harness mirrors the span.)
|
|
1109
|
+
*/
|
|
534
1110
|
deleteMany: <T extends string>(ids: ReadonlyArray<Id<T>>, options?: BatchWriteOptions) => Promise<{
|
|
535
1111
|
deleted: number;
|
|
536
1112
|
}>;
|
|
537
1113
|
/**
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
1114
|
+
* Delete every row matching `where` in one call. Matching rows are resolved
|
|
1115
|
+
* first, then each row is deleted through the single-row delete pipeline
|
|
1116
|
+
* (triggers, companion sync, CDC, broadcast) so reactive subscriptions and
|
|
1117
|
+
* search/aggregate companions stay correct.
|
|
1118
|
+
*
|
|
1119
|
+
* **Atomic within a mutation:** the DO wraps a mutation's dispatch in a
|
|
1120
|
+
* BEGIN/COMMIT span, so a mid-batch failure rolls back the whole mutation.
|
|
1121
|
+
*/
|
|
1122
|
+
deleteWhere: (tableName: string, where: Record<string, unknown>, options?: BatchWriteOptions) => Promise<{
|
|
1123
|
+
deleted: number;
|
|
1124
|
+
}>;
|
|
1125
|
+
/**
|
|
1126
|
+
* Insert a document, returning its server id.
|
|
1127
|
+
*
|
|
1128
|
+
* Pass `options.clientId` (a UUID) to key the row yourself — for an
|
|
1129
|
+
* optimistic client that needs the persisted row to match the key it
|
|
1130
|
+
* already rendered. It's validated for shape and still subject to the
|
|
1131
|
+
* primary-key uniqueness constraint; omit it and the server mints the id.
|
|
1132
|
+
*/
|
|
545
1133
|
insert: <T extends string>(tableName: T, document: Record<string, unknown>, options?: {
|
|
546
1134
|
clientId?: string;
|
|
547
1135
|
}) => Promise<Id<T>>;
|
|
548
1136
|
/**
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
1137
|
+
* Insert many documents into one table in a single call, returning the
|
|
1138
|
+
* minted ids in input order. Equivalent to a per-row `insert()` loop — each
|
|
1139
|
+
* row gets defaults, validators, triggers, and a per-row RLS check — but the
|
|
1140
|
+
* caller pays one round-trip instead of N.
|
|
1141
|
+
*
|
|
1142
|
+
* Pass `{ skipDuplicates: true }` to turn UNIQUE-constraint breaches into
|
|
1143
|
+
* `null` results for that row instead of failing the whole batch; the rest of
|
|
1144
|
+
* the batch is still inserted and order is preserved.
|
|
1145
|
+
*
|
|
1146
|
+
* **Atomic within a mutation:** the DO wraps a mutation's dispatch in a
|
|
1147
|
+
* BEGIN/COMMIT span, so a mid-batch failure (an invalid or RLS-denied row)
|
|
1148
|
+
* rolls back the whole mutation. (In an action there is no transaction span,
|
|
1149
|
+
* so the prior inserts persist; the in-memory test harness mirrors the span.)
|
|
1150
|
+
*/
|
|
1151
|
+
insertMany: {
|
|
1152
|
+
<T extends string>(tableName: T, documents: ReadonlyArray<Record<string, unknown>>, options: BatchWriteOptions & {
|
|
1153
|
+
skipDuplicates: true;
|
|
1154
|
+
}): Promise<(Id<T> | null)[]>;
|
|
1155
|
+
<T extends string>(tableName: T, documents: ReadonlyArray<Record<string, unknown>>, options?: InsertManyOptions): Promise<Id<T>[]>;
|
|
1156
|
+
};
|
|
1157
|
+
/**
|
|
1158
|
+
* **Trusted** bulk insert: one multi-row `INSERT` that **skips per-row
|
|
1159
|
+
* `.check()` validators and before/after triggers** for throughput on data you
|
|
1160
|
+
* control (seed, migration, admin import). Defaults, ids, and every companion
|
|
1161
|
+
* (search/aggregate/rank/CDC + live subscriptions) are still applied, so reads
|
|
1162
|
+
* stay correct.
|
|
1163
|
+
*
|
|
1164
|
+
* It is **"unsafe" only in that it bypasses the validation/trigger pipeline** —
|
|
1165
|
+
* RLS is **not** bypassed: secure-by-default and the table's insert policy still
|
|
1166
|
+
* apply (the framework ships no RLS-bypassing writer). Pass `allowExplicitId` to
|
|
1167
|
+
* preserve a supplied `_id` (import). Use only for data you trust; prefer
|
|
1168
|
+
* `insertMany` for anything user-supplied.
|
|
1169
|
+
*/
|
|
573
1170
|
insertManyUnsafe: <T extends string>(tableName: T, documents: ReadonlyArray<Record<string, unknown>>, options?: BatchWriteOptions & {
|
|
574
1171
|
allowExplicitId?: boolean;
|
|
575
1172
|
}) => Promise<Id<T>[]>;
|
|
576
1173
|
patch: <T extends string>(id: Id<T>, patch: Record<string, unknown>) => Promise<void>;
|
|
577
1174
|
/**
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
1175
|
+
* Patch many rows by id in one call. Each `{ id, patch }` is applied like a
|
|
1176
|
+
* single `patch()` (per-row triggers + RLS). Returns the number of rows
|
|
1177
|
+
* actually patched.
|
|
1178
|
+
*
|
|
1179
|
+
* **Atomic within a mutation:** the DO wraps a mutation's dispatch in a
|
|
1180
|
+
* BEGIN/COMMIT span, so a mid-batch failure rolls back the whole mutation.
|
|
1181
|
+
* (In an action there is no transaction span, so the prior patches persist;
|
|
1182
|
+
* the in-memory test harness mirrors the span.)
|
|
1183
|
+
*/
|
|
586
1184
|
patchMany: <T extends string>(patches: ReadonlyArray<{
|
|
587
1185
|
id: Id<T>;
|
|
588
1186
|
patch: Record<string, unknown>;
|
|
589
|
-
}>, options?: BatchWriteOptions) => Promise<
|
|
1187
|
+
}>, options?: BatchWriteOptions) => Promise<{
|
|
1188
|
+
patched: number;
|
|
1189
|
+
}>;
|
|
1190
|
+
/**
|
|
1191
|
+
* Patch every row matching `where` with the same `patch` in one call. The
|
|
1192
|
+
* matching rows are resolved first, then each row is updated through the
|
|
1193
|
+
* single-row patch pipeline (OCC, triggers, companion sync, CDC, broadcast)
|
|
1194
|
+
* so reactive subscriptions and search/aggregate companions stay correct.
|
|
1195
|
+
*
|
|
1196
|
+
* **Atomic within a mutation:** the DO wraps a mutation's dispatch in a
|
|
1197
|
+
* BEGIN/COMMIT span, so a mid-batch failure rolls back the whole mutation.
|
|
1198
|
+
*/
|
|
1199
|
+
patchWhere: (tableName: string, args: {
|
|
1200
|
+
patch: Record<string, unknown>;
|
|
1201
|
+
where: Record<string, unknown>;
|
|
1202
|
+
}, options?: BatchWriteOptions) => Promise<{
|
|
1203
|
+
patched: number;
|
|
1204
|
+
}>;
|
|
590
1205
|
replace: <T extends string>(id: Id<T>, document: Record<string, unknown>) => Promise<void>;
|
|
1206
|
+
/**
|
|
1207
|
+
* Erase every shard-local table — the account-deletion / tenant-teardown
|
|
1208
|
+
* primitive. Sweeps the schema's non-`.global()` tables with
|
|
1209
|
+
* {@link DatabaseWriter.deleteAll}`({ hard: true })` and returns the per-table
|
|
1210
|
+
* counts.
|
|
1211
|
+
*
|
|
1212
|
+
* `.global()` tables are skipped by design: their rows live in D1 and are shared
|
|
1213
|
+
* across shards, so "wipe this shard" must not reach them. Restrict the sweep
|
|
1214
|
+
* with `options.tables`, or spare one with `options.exclude` (e.g. an audit log
|
|
1215
|
+
* that must outlive the data).
|
|
1216
|
+
*
|
|
1217
|
+
* ```ts
|
|
1218
|
+
* export const deleteAccount = internalMutation({ handler: async ({ ctx }) => ctx.db.wipeShard() });
|
|
1219
|
+
* ```
|
|
1220
|
+
*/
|
|
1221
|
+
wipeShard: (options?: {
|
|
1222
|
+
chunkSize?: number;
|
|
1223
|
+
exclude?: ReadonlyArray<string>;
|
|
1224
|
+
tables?: ReadonlyArray<string>;
|
|
1225
|
+
}) => Promise<{
|
|
1226
|
+
deleted: number;
|
|
1227
|
+
tables: Record<string, number>;
|
|
1228
|
+
}>;
|
|
591
1229
|
}
|
|
592
1230
|
/** Authenticated identity surfaced into every context. */
|
|
593
1231
|
interface AuthState {
|
|
@@ -595,11 +1233,11 @@ interface AuthState {
|
|
|
595
1233
|
readonly userId: string | null;
|
|
596
1234
|
}
|
|
597
1235
|
/**
|
|
598
|
-
* A pending scheduled invocation as surfaced by {@link Scheduler.list} /
|
|
599
|
-
* {@link Scheduler.get}. A clean public mirror of `@lunora/scheduler`'s internal
|
|
600
|
-
* `ScheduleRecord` — re-declared here so the public ctx surface carries no
|
|
601
|
-
* dependency on the scheduler package's internal types.
|
|
602
|
-
*/
|
|
1236
|
+
* A pending scheduled invocation as surfaced by {@link Scheduler.list} /
|
|
1237
|
+
* {@link Scheduler.get}. A clean public mirror of `@lunora/scheduler`'s internal
|
|
1238
|
+
* `ScheduleRecord` — re-declared here so the public ctx surface carries no
|
|
1239
|
+
* dependency on the scheduler package's internal types.
|
|
1240
|
+
*/
|
|
603
1241
|
interface ScheduledJob {
|
|
604
1242
|
args: Record<string, unknown>;
|
|
605
1243
|
/** Number of dispatch attempts already made (absent until the first retry). */
|
|
@@ -613,6 +1251,21 @@ interface ScheduledJob {
|
|
|
613
1251
|
/** Routing hint forwarded so dispatch lands on the right shard. */
|
|
614
1252
|
shardKey?: string;
|
|
615
1253
|
}
|
|
1254
|
+
/**
|
|
1255
|
+
* A schedulable durable-workflow reference — the generated `workflows.<name>` /
|
|
1256
|
+
* `agents.<name>` object, which carries its `WORKFLOW_*`/`AGENT_*` binding and
|
|
1257
|
+
* stable name. Structural mirror of `@lunora/scheduler`'s `WorkflowReference` so
|
|
1258
|
+
* `ctx.scheduler` can target a workflow/agent without a dependency on
|
|
1259
|
+
* `@lunora/scheduler` / `@lunora/workflow`. A scheduled workflow target starts a
|
|
1260
|
+
* fresh instance on fire (the args become its `params`).
|
|
1261
|
+
*/
|
|
1262
|
+
interface SchedulableWorkflowReference {
|
|
1263
|
+
/** The `WORKFLOW_*`/`AGENT_*` binding name (present on a generated ref). */
|
|
1264
|
+
readonly binding?: string;
|
|
1265
|
+
readonly isLunoraWorkflow: true;
|
|
1266
|
+
/** The workflow/agent export/stable name (present on a generated ref). */
|
|
1267
|
+
readonly name?: string;
|
|
1268
|
+
}
|
|
616
1269
|
interface Scheduler {
|
|
617
1270
|
/** Cancel a pending job by id. `cancelled` is `false` when no such job exists. */
|
|
618
1271
|
cancel: (id: string) => Promise<{
|
|
@@ -622,16 +1275,23 @@ interface Scheduler {
|
|
|
622
1275
|
get: (id: string) => Promise<ScheduledJob | null>;
|
|
623
1276
|
/** List all pending scheduled jobs. */
|
|
624
1277
|
list: () => Promise<ScheduledJob[]>;
|
|
625
|
-
|
|
626
|
-
|
|
1278
|
+
/**
|
|
1279
|
+
* Schedule a one-shot run `delayMs` from now. `target` is a function path
|
|
1280
|
+
* (`"ns:fn"`) dispatched as a one-shot, or a generated `workflows.<name>` /
|
|
1281
|
+
* `agents.<name>` reference which starts a fresh durable instance on fire
|
|
1282
|
+
* (the args become its `params`).
|
|
1283
|
+
*/
|
|
1284
|
+
runAfter: (delayMs: number, target: SchedulableWorkflowReference | string, args?: Record<string, unknown>) => Promise<string>;
|
|
1285
|
+
/** Like {@link Scheduler.runAfter} but fires at an absolute epoch-ms timestamp. */
|
|
1286
|
+
runAt: (timestampMs: number, target: SchedulableWorkflowReference | string, args?: Record<string, unknown>) => Promise<string>;
|
|
627
1287
|
}
|
|
628
1288
|
/**
|
|
629
|
-
* A workflow instance's lifecycle status. Clean public mirror of
|
|
630
|
-
* `@lunora/workflow`'s `WorkflowInstanceStatus` (itself a mirror of Cloudflare's
|
|
631
|
-
* `WorkflowInstanceStatus`) — re-declared here so the ctx surface carries no
|
|
632
|
-
* dependency on the workflow package, exactly as {@link Scheduler} avoids a
|
|
633
|
-
* dependency on `@lunora/scheduler`.
|
|
634
|
-
*/
|
|
1289
|
+
* A workflow instance's lifecycle status. Clean public mirror of
|
|
1290
|
+
* `@lunora/workflow`'s `WorkflowInstanceStatus` (itself a mirror of Cloudflare's
|
|
1291
|
+
* `WorkflowInstanceStatus`) — re-declared here so the ctx surface carries no
|
|
1292
|
+
* dependency on the workflow package, exactly as {@link Scheduler} avoids a
|
|
1293
|
+
* dependency on `@lunora/scheduler`.
|
|
1294
|
+
*/
|
|
635
1295
|
type WorkflowInstanceStatus = "complete" | "errored" | "paused" | "queued" | "running" | "terminated" | "unknown" | "waiting" | "waitingForPause";
|
|
636
1296
|
/** Result of {@link WorkflowInstance.status}. Mirrors `@lunora/workflow`'s `WorkflowStatusResult`. */
|
|
637
1297
|
interface WorkflowStatusResult {
|
|
@@ -654,6 +1314,16 @@ interface WorkflowCreateOptions<Params = Record<string, unknown>> {
|
|
|
654
1314
|
successRetention?: string;
|
|
655
1315
|
};
|
|
656
1316
|
}
|
|
1317
|
+
/**
|
|
1318
|
+
* One declared external event a workflow waits on. Mirrors `@lunora/workflow`'s
|
|
1319
|
+
* `WorkflowEventDefinition` — the value `defineWorkflowEvent` returns, taken by
|
|
1320
|
+
* both {@link WorkflowInstance.sendEvent} and the workflow's `ctx.waitForEvent`.
|
|
1321
|
+
*/
|
|
1322
|
+
interface WorkflowEventDefinition<Payload = unknown> {
|
|
1323
|
+
readonly isLunoraWorkflowEvent: true;
|
|
1324
|
+
readonly payload: Validator<Payload>;
|
|
1325
|
+
readonly type: string;
|
|
1326
|
+
}
|
|
657
1327
|
/** A live handle to a single workflow instance. Mirrors `@lunora/workflow`'s `WorkflowInstanceLike`. */
|
|
658
1328
|
interface WorkflowInstance {
|
|
659
1329
|
readonly id: string;
|
|
@@ -668,9 +1338,9 @@ interface WorkflowInstance {
|
|
|
668
1338
|
terminate: () => Promise<void>;
|
|
669
1339
|
}
|
|
670
1340
|
/**
|
|
671
|
-
* A typed handle to one declared workflow, addressable from `ctx.workflows`.
|
|
672
|
-
* Mirrors `@lunora/workflow`'s `WorkflowHandle`.
|
|
673
|
-
*/
|
|
1341
|
+
* A typed handle to one declared workflow, addressable from `ctx.workflows`.
|
|
1342
|
+
* Mirrors `@lunora/workflow`'s `WorkflowHandle`.
|
|
1343
|
+
*/
|
|
674
1344
|
interface WorkflowHandle<Params = Record<string, unknown>> {
|
|
675
1345
|
/** Start a new instance (optionally with an id + params). */
|
|
676
1346
|
create: (options?: WorkflowCreateOptions<Params>) => Promise<WorkflowInstance>;
|
|
@@ -678,38 +1348,55 @@ interface WorkflowHandle<Params = Record<string, unknown>> {
|
|
|
678
1348
|
createBatch: (batch: ReadonlyArray<WorkflowCreateOptions<Params>>) => Promise<WorkflowInstance[]>;
|
|
679
1349
|
/** Get a handle to an existing instance by id. */
|
|
680
1350
|
get: (id: string) => Promise<WorkflowInstance>;
|
|
1351
|
+
/** Deliver a declared event (`defineWorkflowEvent`) to one instance; the payload is validated before the send. */
|
|
1352
|
+
sendEvent: <Payload>(instanceId: string, event: WorkflowEventDefinition<Payload>, payload: Payload) => Promise<void>;
|
|
681
1353
|
}
|
|
682
1354
|
/**
|
|
683
|
-
* The `ctx.workflows` surface on {@link MutationCtx} / {@link ActionCtx}. Each
|
|
684
|
-
* workflow declared in `lunora/workflows.ts` is reachable by its export name;
|
|
685
|
-
* codegen narrows the `get(name)` overloads to the known workflow names + their
|
|
686
|
-
* inferred param types. Mirrors `@lunora/workflow`'s `Workflows`.
|
|
687
|
-
*/
|
|
1355
|
+
* The `ctx.workflows` surface on {@link MutationCtx} / {@link ActionCtx}. Each
|
|
1356
|
+
* workflow declared in `lunora/workflows.ts` is reachable by its export name;
|
|
1357
|
+
* codegen narrows the `get(name)` overloads to the known workflow names + their
|
|
1358
|
+
* inferred param types. Mirrors `@lunora/workflow`'s `Workflows`.
|
|
1359
|
+
*/
|
|
688
1360
|
interface Workflows {
|
|
689
1361
|
/** Resolve the handle for a declared workflow by export name. */
|
|
690
1362
|
get: <Params = Record<string, unknown>>(name: string) => WorkflowHandle<Params>;
|
|
691
1363
|
}
|
|
692
1364
|
/**
|
|
693
|
-
*
|
|
694
|
-
*
|
|
695
|
-
*
|
|
696
|
-
|
|
697
|
-
|
|
1365
|
+
* Programmatic cache purge surface exposed on {@link ActionCtx}. Actions run
|
|
1366
|
+
* in the Worker (not the DO), so they can reach the Worker's `ctx.cache.purge`.
|
|
1367
|
+
* Queries and mutations do not expose this — they run inside the Durable Object.
|
|
1368
|
+
*/
|
|
1369
|
+
interface CachePurge {
|
|
1370
|
+
/**
|
|
1371
|
+
* Purge cached responses matching the given tags, or everything when
|
|
1372
|
+
* `purgeEverything` is true. Only available in action handlers.
|
|
1373
|
+
*/
|
|
1374
|
+
purge: (options: {
|
|
1375
|
+
purgeEverything?: boolean;
|
|
1376
|
+
tags?: string[];
|
|
1377
|
+
}) => Promise<unknown>;
|
|
1378
|
+
}
|
|
1379
|
+
/**
|
|
1380
|
+
* Structural projection of workers-types' `SecretsStoreSecret` binding — the
|
|
1381
|
+
* per-secret `secrets_store_secrets[]` binding whose `.get()` resolves the
|
|
1382
|
+
* secret value (or throws if it does not exist). Mirrored structurally so the
|
|
1383
|
+
* runtime resolves it without a workerd type dependency.
|
|
1384
|
+
*/
|
|
698
1385
|
interface SecretsStoreSecretLike {
|
|
699
1386
|
get: () => Promise<string>;
|
|
700
1387
|
}
|
|
701
1388
|
/**
|
|
702
|
-
* `ctx.secrets` — read account-level secrets bound via Cloudflare Secrets Store.
|
|
703
|
-
* A core built-in (always present on every context, like `ctx.log`): a binding
|
|
704
|
-
* named in wrangler's `secrets_store_secrets[]` is read by its binding name.
|
|
705
|
-
*
|
|
706
|
-
* ```ts
|
|
707
|
-
* const apiKey = await ctx.secrets.get("STRIPE_KEY");
|
|
708
|
-
* ```
|
|
709
|
-
*
|
|
710
|
-
* The lookup is async (the platform fetches and decrypts on first read);
|
|
711
|
-
* reading an undeclared name throws a directed error naming the bound secrets.
|
|
712
|
-
*/
|
|
1389
|
+
* `ctx.secrets` — read account-level secrets bound via Cloudflare Secrets Store.
|
|
1390
|
+
* A core built-in (always present on every context, like `ctx.log`): a binding
|
|
1391
|
+
* named in wrangler's `secrets_store_secrets[]` is read by its binding name.
|
|
1392
|
+
*
|
|
1393
|
+
* ```ts
|
|
1394
|
+
* const apiKey = await ctx.secrets.get("STRIPE_KEY");
|
|
1395
|
+
* ```
|
|
1396
|
+
*
|
|
1397
|
+
* The lookup is async (the platform fetches and decrypts on first read);
|
|
1398
|
+
* reading an undeclared name throws a directed error naming the bound secrets.
|
|
1399
|
+
*/
|
|
713
1400
|
interface Secrets {
|
|
714
1401
|
/** Resolve a Secrets Store secret by its wrangler binding name. */
|
|
715
1402
|
get: (name: string) => Promise<string>;
|
|
@@ -719,11 +1406,11 @@ type TriggerTiming = "after" | "before";
|
|
|
719
1406
|
/** The CRUD operation a trigger reacts to. `patch` and `replace` both map to `update`. */
|
|
720
1407
|
type TriggerOp = "delete" | "insert" | "update";
|
|
721
1408
|
/**
|
|
722
|
-
* A row as observed by a trigger handler: the table's `Shape` (with the same
|
|
723
|
-
* optionality rules as {@link InferArgs}) plus the system columns every stored
|
|
724
|
-
* doc carries.
|
|
725
|
-
*/
|
|
726
|
-
type TriggerRow<Shape extends Record<string, Validator>> = { [K in keyof Shape as undefined extends Infer<Shape[K]> ? K : never]?: Infer<Shape[K]
|
|
1409
|
+
* A row as observed by a trigger handler: the table's `Shape` (with the same
|
|
1410
|
+
* optionality rules as {@link InferArgs}) plus the system columns every stored
|
|
1411
|
+
* doc carries.
|
|
1412
|
+
*/
|
|
1413
|
+
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]>; } & {
|
|
727
1414
|
readonly _creationTime: number;
|
|
728
1415
|
readonly _id: string;
|
|
729
1416
|
};
|
|
@@ -735,11 +1422,11 @@ interface TriggerInsertEvent<Shape extends Record<string, Validator> = Record<st
|
|
|
735
1422
|
readonly table: string;
|
|
736
1423
|
}
|
|
737
1424
|
/**
|
|
738
|
-
* What an `update` trigger observes: the merged row plus the pre-write row.
|
|
739
|
-
* `previous` is typed as always present (the row must exist to be updated); the
|
|
740
|
-
* runtime supplies it best-effort and only omits it in the unreachable
|
|
741
|
-
* row-vanished-mid-write case.
|
|
742
|
-
*/
|
|
1425
|
+
* What an `update` trigger observes: the merged row plus the pre-write row.
|
|
1426
|
+
* `previous` is typed as always present (the row must exist to be updated); the
|
|
1427
|
+
* runtime supplies it best-effort and only omits it in the unreachable
|
|
1428
|
+
* row-vanished-mid-write case.
|
|
1429
|
+
*/
|
|
743
1430
|
interface TriggerUpdateEvent<Shape extends Record<string, Validator> = Record<string, Validator>> {
|
|
744
1431
|
readonly doc: TriggerRow<Shape>;
|
|
745
1432
|
readonly id: string;
|
|
@@ -748,10 +1435,10 @@ interface TriggerUpdateEvent<Shape extends Record<string, Validator> = Record<st
|
|
|
748
1435
|
readonly table: string;
|
|
749
1436
|
}
|
|
750
1437
|
/**
|
|
751
|
-
* What a `delete` trigger observes: the row about to be (or just) removed.
|
|
752
|
-
* `previous` is typed as always present; the runtime supplies it best-effort
|
|
753
|
-
* and only omits it in the unreachable row-vanished-mid-write case.
|
|
754
|
-
*/
|
|
1438
|
+
* What a `delete` trigger observes: the row about to be (or just) removed.
|
|
1439
|
+
* `previous` is typed as always present; the runtime supplies it best-effort
|
|
1440
|
+
* and only omits it in the unreachable row-vanished-mid-write case.
|
|
1441
|
+
*/
|
|
755
1442
|
interface TriggerDeleteEvent<Shape extends Record<string, Validator> = Record<string, Validator>> {
|
|
756
1443
|
readonly id: string;
|
|
757
1444
|
readonly op: "delete";
|
|
@@ -775,10 +1462,10 @@ interface TriggerQueryArgs {
|
|
|
775
1462
|
with?: Record<string, unknown>;
|
|
776
1463
|
}
|
|
777
1464
|
/**
|
|
778
|
-
* Args accepted by {@link TriggerDatabase.aggregate} — structural mirror of
|
|
779
|
-
* `@lunora/do`'s `AggregateOptions`, kept local so trigger handlers in
|
|
780
|
-
* `@lunora/server` don't take a hard dep on the DO runtime.
|
|
781
|
-
*/
|
|
1465
|
+
* Args accepted by {@link TriggerDatabase.aggregate} — structural mirror of
|
|
1466
|
+
* `@lunora/do`'s `AggregateOptions`, kept local so trigger handlers in
|
|
1467
|
+
* `@lunora/server` don't take a hard dep on the DO runtime.
|
|
1468
|
+
*/
|
|
782
1469
|
interface TriggerAggregateOptions {
|
|
783
1470
|
baseWhere?: Record<string, unknown>;
|
|
784
1471
|
field?: string;
|
|
@@ -823,17 +1510,17 @@ interface TriggerRankPageOptions {
|
|
|
823
1510
|
where?: Record<string, unknown>;
|
|
824
1511
|
}
|
|
825
1512
|
/**
|
|
826
|
-
* Portable, table/id-addressed ORM writer handed to trigger handlers via
|
|
827
|
-
* `ctx.db`. Mirrors `@lunora/do`'s runtime `DatabaseWriterLike` surface — it is
|
|
828
|
-
* **not** the generated per-table `ctx.db
|
|
829
|
-
* from inside `defineTable`, where the full schema isn't known).
|
|
830
|
-
*
|
|
831
|
-
* `aggregate`/`groupBy`/`count`/`rank`/`rankPage` route through the same
|
|
832
|
-
* trigger-maintained counter and rank tables the user-facing reader uses, so
|
|
833
|
-
* a handler's `ctx.db
|
|
834
|
-
* within the same DO transaction (the counter step happens before the trigger
|
|
835
|
-
* fires).
|
|
836
|
-
*/
|
|
1513
|
+
* Portable, table/id-addressed ORM writer handed to trigger handlers via
|
|
1514
|
+
* `ctx.db`. Mirrors `@lunora/do`'s runtime `DatabaseWriterLike` surface — it is
|
|
1515
|
+
* **not** the generated per-table `ctx.db.<table>` facade (which can't be typed
|
|
1516
|
+
* from inside `defineTable`, where the full schema isn't known).
|
|
1517
|
+
*
|
|
1518
|
+
* `aggregate`/`groupBy`/`count`/`rank`/`rankPage` route through the same
|
|
1519
|
+
* trigger-maintained counter and rank tables the user-facing reader uses, so
|
|
1520
|
+
* a handler's `ctx.db.<table>.aggregate(...)` observes the just-staged write
|
|
1521
|
+
* within the same DO transaction (the counter step happens before the trigger
|
|
1522
|
+
* fires).
|
|
1523
|
+
*/
|
|
837
1524
|
interface TriggerDatabase {
|
|
838
1525
|
aggregate: (tableName: string, options: TriggerAggregateOptions) => Promise<null | number>;
|
|
839
1526
|
count: (tableName: string, where?: Record<string, unknown>) => Promise<number>;
|
|
@@ -849,10 +1536,10 @@ interface TriggerDatabase {
|
|
|
849
1536
|
replace: (id: string, document: Record<string, unknown>) => Promise<void>;
|
|
850
1537
|
}
|
|
851
1538
|
/**
|
|
852
|
-
* Handle injected into every trigger handler. `db` is the portable ORM writer;
|
|
853
|
-
* `scheduler` enqueues async / cross-shard follow-up work (cross-shard work is
|
|
854
|
-
* **not** transactional with the firing write).
|
|
855
|
-
*/
|
|
1539
|
+
* Handle injected into every trigger handler. `db` is the portable ORM writer;
|
|
1540
|
+
* `scheduler` enqueues async / cross-shard follow-up work (cross-shard work is
|
|
1541
|
+
* **not** transactional with the firing write).
|
|
1542
|
+
*/
|
|
856
1543
|
interface TriggerCtx {
|
|
857
1544
|
readonly db: TriggerDatabase;
|
|
858
1545
|
readonly scheduler: Scheduler;
|
|
@@ -860,20 +1547,20 @@ interface TriggerCtx {
|
|
|
860
1547
|
/** A user-declared trigger handler. Throwing from a `before*` handler aborts the write. */
|
|
861
1548
|
type TriggerHandler<Event> = (context: TriggerCtx, event: Event) => Promise<void> | void;
|
|
862
1549
|
/**
|
|
863
|
-
* A single declared trigger, as stored in {@link TableDefinition.triggerMap}.
|
|
864
|
-
* The handler's event type is erased to the {@link TriggerEvent} union here; the
|
|
865
|
-
* per-op {@link TriggerBuilder} methods recover the precise event type for
|
|
866
|
-
* authors.
|
|
867
|
-
*/
|
|
1550
|
+
* A single declared trigger, as stored in {@link TableDefinition.triggerMap}.
|
|
1551
|
+
* The handler's event type is erased to the {@link TriggerEvent} union here; the
|
|
1552
|
+
* per-op {@link TriggerBuilder} methods recover the precise event type for
|
|
1553
|
+
* authors.
|
|
1554
|
+
*/
|
|
868
1555
|
interface TriggerDefinition {
|
|
869
1556
|
readonly handler: TriggerHandler<TriggerEvent>;
|
|
870
1557
|
readonly op: TriggerOp;
|
|
871
1558
|
readonly timing: TriggerTiming;
|
|
872
1559
|
}
|
|
873
1560
|
/**
|
|
874
|
-
* The `t` argument passed to `.triggers((t) => …)`. Each method binds a handler
|
|
875
|
-
* to one `timing`+`op` pair, typing the event against the table's `Shape`.
|
|
876
|
-
*/
|
|
1561
|
+
* The `t` argument passed to `.triggers((t) => …)`. Each method binds a handler
|
|
1562
|
+
* to one `timing`+`op` pair, typing the event against the table's `Shape`.
|
|
1563
|
+
*/
|
|
877
1564
|
interface TriggerBuilder<Shape extends Record<string, Validator> = Record<string, Validator>> {
|
|
878
1565
|
afterDelete: (handler: TriggerHandler<TriggerDeleteEvent<Shape>>) => TriggerDefinition;
|
|
879
1566
|
afterInsert: (handler: TriggerHandler<TriggerInsertEvent<Shape>>) => TriggerDefinition;
|
|
@@ -883,11 +1570,11 @@ interface TriggerBuilder<Shape extends Record<string, Validator> = Record<string
|
|
|
883
1570
|
beforeUpdate: (handler: TriggerHandler<TriggerUpdateEvent<Shape>>) => TriggerDefinition;
|
|
884
1571
|
}
|
|
885
1572
|
/**
|
|
886
|
-
* Per-file metadata returned by {@link ReadOnlyStorage.getMetadata}. A clean
|
|
887
|
-
* public mirror of `@lunora/storage`'s `ObjectMetadata` — re-declared here so
|
|
888
|
-
* the ctx surface carries no dependency on the storage package's types. Matches
|
|
889
|
-
* the columns Convex surfaces for `ctx.storage.getMetadata` / `_storage`.
|
|
890
|
-
*/
|
|
1573
|
+
* Per-file metadata returned by {@link ReadOnlyStorage.getMetadata}. A clean
|
|
1574
|
+
* public mirror of `@lunora/storage`'s `ObjectMetadata` — re-declared here so
|
|
1575
|
+
* the ctx surface carries no dependency on the storage package's types. Matches
|
|
1576
|
+
* the columns Convex surfaces for `ctx.storage.getMetadata` / `_storage`.
|
|
1577
|
+
*/
|
|
891
1578
|
interface StorageMetadata {
|
|
892
1579
|
/** The object's `Content-Type`, when recorded. */
|
|
893
1580
|
contentType?: string;
|
|
@@ -903,31 +1590,64 @@ interface StorageMetadata {
|
|
|
903
1590
|
uploaded?: number;
|
|
904
1591
|
}
|
|
905
1592
|
/**
|
|
906
|
-
*
|
|
907
|
-
*
|
|
908
|
-
*
|
|
909
|
-
*
|
|
910
|
-
*
|
|
911
|
-
*
|
|
912
|
-
*
|
|
913
|
-
*
|
|
914
|
-
|
|
1593
|
+
* The body-free object shape returned by {@link ReadOnlyStorage.head} — a clean
|
|
1594
|
+
* public mirror of `@lunora/storage`'s head projection, re-declared here for the
|
|
1595
|
+
* same reason as {@link StorageMetadata}: the ctx surface carries no dependency
|
|
1596
|
+
* on the storage package's types.
|
|
1597
|
+
*
|
|
1598
|
+
* Richer than {@link StorageMetadata} on purpose. `getMetadata` is the tidy
|
|
1599
|
+
* Convex-shaped summary; `head` is what an HTTP layer needs, so it keeps the
|
|
1600
|
+
* validator (`etag`) and the base64 digest RFC 9530 `Repr-Digest` requires, and
|
|
1601
|
+
* leaves `uploaded` as the `Date` the binding reports rather than epoch ms.
|
|
1602
|
+
*/
|
|
1603
|
+
interface StorageObjectHead {
|
|
1604
|
+
/** Custom metadata set at upload time, if any. */
|
|
1605
|
+
customMetadata?: Record<string, string>;
|
|
1606
|
+
/** R2's unquoted etag (the MD5 hex for a single-part upload). */
|
|
1607
|
+
etag?: string;
|
|
1608
|
+
/** The already-quoted form of {@link StorageObjectHead.etag}, when the binding reports one. */
|
|
1609
|
+
httpEtag?: string;
|
|
1610
|
+
/** Recorded HTTP metadata, notably the `Content-Type`. */
|
|
1611
|
+
httpMetadata?: {
|
|
1612
|
+
contentType?: string;
|
|
1613
|
+
};
|
|
1614
|
+
/** The object's key. */
|
|
1615
|
+
key: string;
|
|
1616
|
+
/** Hex-encoded SHA-256 of the body, when R2 carries a checksum. */
|
|
1617
|
+
sha256?: string;
|
|
1618
|
+
/** Base64-encoded SHA-256 of the same checksum — the encoding RFC 9530 digest headers require. */
|
|
1619
|
+
sha256Base64?: string;
|
|
1620
|
+
/** The FULL object size in bytes: R2 reports the object's size, not a returned window's, which is what makes a head enough to resolve a `Range` against. */
|
|
1621
|
+
size: number;
|
|
1622
|
+
/** When the object was last written. */
|
|
1623
|
+
uploaded?: Date;
|
|
1624
|
+
}
|
|
1625
|
+
/**
|
|
1626
|
+
* Read-only projection of `Storage` exposed on `QueryCtx` / `MutationCtx`.
|
|
1627
|
+
*
|
|
1628
|
+
* Queries are pure reads, and mutations run inside a transactional scope —
|
|
1629
|
+
* neither is allowed to perform side-effectful R2 writes (`upload`) or
|
|
1630
|
+
* deletes (`delete`). They can, however, **read** existing objects and
|
|
1631
|
+
* resolve signed URLs (the URL signing itself is HMAC-only — no R2 round
|
|
1632
|
+
* trip), so the read-only surface keeps `download` and `getSignedUrl`. The
|
|
1633
|
+
* full {@link Storage} surface stays on `ActionCtx`.
|
|
1634
|
+
*/
|
|
915
1635
|
interface ReadOnlyStorage<Buckets extends string = string> {
|
|
916
1636
|
/**
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
1637
|
+
* Select a named bucket (declared via `v.storage("name")`). The returned
|
|
1638
|
+
* accessor's operations target that bucket — `ctx.storage.bucket("avatars")
|
|
1639
|
+
* .download(key)`. The bare `ctx.storage` targets the default bucket.
|
|
1640
|
+
*/
|
|
921
1641
|
bucket: (name: Buckets) => ReadOnlyStorage<Buckets>;
|
|
922
1642
|
/** The bucket this accessor's operations target (the default for the bare `ctx.storage`). */
|
|
923
1643
|
readonly bucketName: string;
|
|
924
1644
|
/** Fetch the body of an existing object. Returns `null` when absent. */
|
|
925
1645
|
download: (key: string) => Promise<ReadableStream | null>;
|
|
926
1646
|
/**
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
1647
|
+
* Read a file's metadata (size, content-type, sha256, upload time, custom
|
|
1648
|
+
* metadata) without fetching its body. Returns `null` when the object is
|
|
1649
|
+
* absent. Mirrors Convex's `ctx.storage.getMetadata`.
|
|
1650
|
+
*/
|
|
931
1651
|
getMetadata: (key: string) => Promise<StorageMetadata | null>;
|
|
932
1652
|
/** Resolve a short-lived signed URL for an existing object. */
|
|
933
1653
|
getSignedUrl: (key: string, options?: {
|
|
@@ -935,26 +1655,54 @@ interface ReadOnlyStorage<Buckets extends string = string> {
|
|
|
935
1655
|
}) => Promise<string>;
|
|
936
1656
|
/** Public URL pointing at the configured base for `key`. */
|
|
937
1657
|
getUrl: (key: string) => string;
|
|
1658
|
+
/**
|
|
1659
|
+
* Read an object's metadata with NO body transfer, as the raw object shape —
|
|
1660
|
+
* `etag` and the base64 digest included, which is what an HTTP layer needs to
|
|
1661
|
+
* answer a `Range` request. Returns `null` when the object is absent.
|
|
1662
|
+
*
|
|
1663
|
+
* {@link ReadOnlyStorage.getMetadata} is the tidier summary over the same
|
|
1664
|
+
* read; reach for this one when building a response.
|
|
1665
|
+
*/
|
|
1666
|
+
head: (key: string) => Promise<StorageObjectHead | null>;
|
|
1667
|
+
}
|
|
1668
|
+
/**
|
|
1669
|
+
* `ctx.storage` inside a **mutation**: the read surface, plus the one write a
|
|
1670
|
+
* transactional context can safely express. See `@lunora/server`'s
|
|
1671
|
+
* `deferred-deletes.ts` for why `delete` itself stays action-only.
|
|
1672
|
+
*/
|
|
1673
|
+
interface MutationStorage<Buckets extends string = string> extends ReadOnlyStorage<Buckets> {
|
|
1674
|
+
/** Select a named bucket; deletes queued on it are flushed against that bucket. */
|
|
1675
|
+
bucket: (name: Buckets) => MutationStorage<Buckets>;
|
|
1676
|
+
/**
|
|
1677
|
+
* Queue `key` for deletion once this mutation commits.
|
|
1678
|
+
*
|
|
1679
|
+
* Returns `void`, not a promise: nothing has been attempted yet, so the object
|
|
1680
|
+
* is still there on the next line. A rolled-back mutation never flushes, so
|
|
1681
|
+
* the row deletion and the object cleanup cannot disagree. A failed delete
|
|
1682
|
+
* leaks the object rather than failing a mutation that already succeeded, and
|
|
1683
|
+
* is logged with its key.
|
|
1684
|
+
*/
|
|
1685
|
+
deleteAfterCommit: (key: string) => void;
|
|
938
1686
|
}
|
|
939
1687
|
interface Storage<Buckets extends string = string> extends ReadOnlyStorage<Buckets> {
|
|
940
1688
|
/** Select a named bucket; the returned accessor exposes the full read/write surface. */
|
|
941
1689
|
bucket: (name: Buckets) => Storage<Buckets>;
|
|
942
1690
|
delete: (key: string) => Promise<void>;
|
|
943
1691
|
/**
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
1692
|
+
* Mint a short-lived signed `PUT` URL a client can upload directly to,
|
|
1693
|
+
* optionally pinning the `Content-Type` the uploader must send. Mirrors
|
|
1694
|
+
* Convex's `storage.generateUploadUrl`.
|
|
1695
|
+
*/
|
|
948
1696
|
generateUploadUrl: (key: string, options?: {
|
|
949
1697
|
contentType?: string;
|
|
950
1698
|
expiresInSeconds?: number;
|
|
951
1699
|
}) => Promise<string>;
|
|
952
1700
|
/**
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
1701
|
+
* Upload `body` to `key` from the server, returning the stored object's key
|
|
1702
|
+
* and etag. Mirrors Convex's `storage.store`. Accepts the same guard fields
|
|
1703
|
+
* as `@lunora/storage`'s `UploadOptions` so `maxSize` /
|
|
1704
|
+
* `allowedContentTypes` enforcement isn't lost behind the Convex-style alias.
|
|
1705
|
+
*/
|
|
958
1706
|
store: (key: string, body: ReadableStream | ArrayBuffer | Blob, options?: {
|
|
959
1707
|
allowedContentTypes?: ReadonlyArray<string>;
|
|
960
1708
|
contentType?: string;
|
|
@@ -998,160 +1746,525 @@ interface VectorRecord {
|
|
|
998
1746
|
values: ReadonlyArray<number>;
|
|
999
1747
|
}
|
|
1000
1748
|
/**
|
|
1001
|
-
* Read-only vector surface exposed on {@link QueryCtx}. Mirrors the read half
|
|
1002
|
-
* of `@lunora/bindings/vectors`' `LunoraVectors` so the live adapter is assignable.
|
|
1003
|
-
*/
|
|
1004
|
-
interface VectorSearchReader {
|
|
1005
|
-
getByIds: (indexName:
|
|
1006
|
-
query: (indexName:
|
|
1007
|
-
}
|
|
1008
|
-
/**
|
|
1009
|
-
* Mutating vector surface on {@link MutationCtx} / {@link ActionCtx}. `upsert`
|
|
1010
|
-
* is queued post-commit by default; `upsertNow` forces a synchronous write.
|
|
1011
|
-
* `db.delete` on a vectorized table auto-propagates the matching `deleteByIds`.
|
|
1012
|
-
*/
|
|
1013
|
-
interface VectorSearch extends VectorSearchReader {
|
|
1014
|
-
deleteByIds: (indexName:
|
|
1015
|
-
upsert: (indexName:
|
|
1016
|
-
upsertNow: (indexName:
|
|
1017
|
-
}
|
|
1018
|
-
/**
|
|
1019
|
-
* Structured
|
|
1020
|
-
*
|
|
1021
|
-
* `ObservabilitySink`'s `onLog`
|
|
1022
|
-
*
|
|
1023
|
-
*
|
|
1024
|
-
*
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
*
|
|
1029
|
-
*
|
|
1030
|
-
*
|
|
1031
|
-
*
|
|
1032
|
-
*
|
|
1033
|
-
*
|
|
1034
|
-
* the
|
|
1035
|
-
|
|
1749
|
+
* Read-only vector surface exposed on {@link QueryCtx}. Mirrors the read half
|
|
1750
|
+
* of `@lunora/bindings/vectors`' `LunoraVectors` so the live adapter is assignable.
|
|
1751
|
+
*/
|
|
1752
|
+
interface VectorSearchReader<IndexName extends string = string> {
|
|
1753
|
+
getByIds: (indexName: IndexName, ids: ReadonlyArray<string>) => Promise<ReadonlyArray<VectorRecord>>;
|
|
1754
|
+
query: (indexName: IndexName, input: VectorQueryInput) => Promise<VectorMatches>;
|
|
1755
|
+
}
|
|
1756
|
+
/**
|
|
1757
|
+
* Mutating vector surface on {@link MutationCtx} / {@link ActionCtx}. `upsert`
|
|
1758
|
+
* is queued post-commit by default; `upsertNow` forces a synchronous write.
|
|
1759
|
+
* `db.delete` on a vectorized table auto-propagates the matching `deleteByIds`.
|
|
1760
|
+
*/
|
|
1761
|
+
interface VectorSearch<IndexName extends string = string> extends VectorSearchReader<IndexName> {
|
|
1762
|
+
deleteByIds: (indexName: IndexName, ids: ReadonlyArray<string>) => Promise<void>;
|
|
1763
|
+
upsert: (indexName: IndexName, input: VectorUpsertInput) => Promise<void>;
|
|
1764
|
+
upsertNow: (indexName: IndexName, input: VectorUpsertInput) => Promise<void>;
|
|
1765
|
+
}
|
|
1766
|
+
/**
|
|
1767
|
+
* Structured, filterable key/value fields attached to a log line — the second
|
|
1768
|
+
* argument of a `ctx.log.<level>(message, fields)` call, or the fields bound by
|
|
1769
|
+
* `ctx.log.with(fields)`. They travel to an `ObservabilitySink`'s `onLog` and,
|
|
1770
|
+
* for a network sink, become OTLP log-record attributes a log pipeline (or the
|
|
1771
|
+
* Cloud log viewer) can filter and index on. Primitive values pass through;
|
|
1772
|
+
* objects/arrays are JSON-encoded at the sink boundary.
|
|
1773
|
+
*/
|
|
1774
|
+
type LogFields = Record<string, unknown>;
|
|
1775
|
+
/**
|
|
1776
|
+
* One `ctx.log` severity method. Two call forms:
|
|
1777
|
+
*
|
|
1778
|
+
* - **Structured** — `ctx.log.info("order placed", { orderId, total })`: a message string plus a `fields` object. The fields are indexed as attributes.
|
|
1779
|
+
* - **Console-style** — `ctx.log.info("state", value, other)`: any number of values, joined into the display message exactly like `console.log`.
|
|
1780
|
+
*
|
|
1781
|
+
* The structured form is matched when the second argument is a plain object;
|
|
1782
|
+
* otherwise the call is treated as console-style, so existing `console`-shaped
|
|
1783
|
+
* calls keep working unchanged.
|
|
1784
|
+
*/
|
|
1785
|
+
interface LunoraLogMethod {
|
|
1786
|
+
(message: string, fields?: LogFields): void;
|
|
1787
|
+
(...args: unknown[]): void;
|
|
1788
|
+
}
|
|
1789
|
+
/**
|
|
1790
|
+
* Structured logger on every function `ctx`. Each call emits one attributed log
|
|
1791
|
+
* line — tagged with the function path on the server — that flows to an
|
|
1792
|
+
* `ObservabilitySink`'s `onLog` (where you route it in production) and, in
|
|
1793
|
+
* development, to the dev server terminal via the CLI / Vite plugin formatter.
|
|
1794
|
+
* Mirrors the `console` method names so it's a drop-in for `console.log` inside a
|
|
1795
|
+
* handler, but with attribution, structured fields, and a routable transport.
|
|
1796
|
+
*
|
|
1797
|
+
* Six severities spanning the OpenTelemetry ramp: `trace`, `debug`, `info` (and
|
|
1798
|
+
* its `log` alias), `warn`, `error`, `fatal`.
|
|
1799
|
+
*
|
|
1800
|
+
* Two ways to attach structured {@link LogFields}: pass them per call
|
|
1801
|
+
* (`ctx.log.info(message, fields)`) or bind them once with {@link with} for a
|
|
1802
|
+
* child logger that stamps every line. The rendered `message` and the structured
|
|
1803
|
+
* `fields` reach the dev terminal and the platform's Workers Logs; the raw,
|
|
1804
|
+
* un-rendered console-style arguments are preserved ONLY on the in-process
|
|
1805
|
+
* `onLog` sink (which you opt into and control).
|
|
1806
|
+
*
|
|
1807
|
+
* Attribution follows the dispatched function: a log emitted inside an internal
|
|
1808
|
+
* function invoked via `ctx.runQuery`/`runMutation`/`runAction` is attributed to
|
|
1809
|
+
* the outer request entrypoint, since the composed call reuses its context.
|
|
1810
|
+
*/
|
|
1036
1811
|
interface LunoraLogger {
|
|
1037
|
-
readonly debug:
|
|
1038
|
-
readonly error:
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1812
|
+
readonly debug: LunoraLogMethod;
|
|
1813
|
+
readonly error: LunoraLogMethod;
|
|
1814
|
+
/**
|
|
1815
|
+
* Emit a **structured event** instead of a log line — OpenTelemetry's Events
|
|
1816
|
+
* API, on the wire as `LogRecord.eventName` (plus an `event.name` attribute
|
|
1817
|
+
* for collectors predating that field).
|
|
1818
|
+
*
|
|
1819
|
+
* ```ts
|
|
1820
|
+
* ctx.log.event("checkout.completed", { plan: user.plan, total, currency });
|
|
1821
|
+
* ```
|
|
1822
|
+
*
|
|
1823
|
+
* The difference from `ctx.log.info("checkout completed", { … })` is what a
|
|
1824
|
+
* backend can do with it. A log line's payload is its message: prose, written
|
|
1825
|
+
* for a human, free to be reworded next sprint — so "how many checkouts
|
|
1826
|
+
* completed, by plan, this hour" degrades into a substring search over
|
|
1827
|
+
* English. An event's payload is its `fields` under a **stable name**, which a
|
|
1828
|
+
* collector can index, group, and alert on directly.
|
|
1829
|
+
*
|
|
1830
|
+
* Rule of thumb: `log.*` for narration you'd read while debugging, `event` for
|
|
1831
|
+
* anything you'd ever put on a dashboard. And for facts about the request as a
|
|
1832
|
+
* whole, prefer `ctx.span` — one wide event beats a dozen
|
|
1833
|
+
* events, however well named.
|
|
1834
|
+
*/
|
|
1835
|
+
readonly event: (name: string, fields?: LogFields) => void;
|
|
1836
|
+
readonly fatal: LunoraLogMethod;
|
|
1837
|
+
readonly info: LunoraLogMethod;
|
|
1838
|
+
readonly log: LunoraLogMethod;
|
|
1839
|
+
readonly trace: LunoraLogMethod;
|
|
1840
|
+
readonly warn: LunoraLogMethod;
|
|
1841
|
+
/**
|
|
1842
|
+
* Return a child logger that stamps `fields` onto every line it emits,
|
|
1843
|
+
* merged under any per-call fields (per-call wins on a key clash). Chainable
|
|
1844
|
+
* — `ctx.log.with({ requestId }).with({ step })` accumulates both. Use it to
|
|
1845
|
+
* bind request-scoped context once instead of repeating it per call.
|
|
1846
|
+
*/
|
|
1847
|
+
readonly with: (fields: LogFields) => LunoraLogger;
|
|
1848
|
+
}
|
|
1849
|
+
/**
|
|
1850
|
+
* Handle the enclosing `ctx.trace` span hands its body, so the body can attach
|
|
1851
|
+
* attributes only known *after* it resolves (an AI call's token usage / dollar
|
|
1852
|
+
* cost, a downstream status, a computed count). Declared structurally here to
|
|
1853
|
+
* mirror `shared/span-event.ts`'s `SpanHandle` and `@lunora/do`'s implementation;
|
|
1854
|
+
* a cross-package assignability guard in `@lunora/testing` fails the build if the
|
|
1855
|
+
* three drift apart. Start attributes are snapshotted before the body runs;
|
|
1856
|
+
* handle writes are merged over them at record time, post-hoc winning on a clash.
|
|
1857
|
+
*/
|
|
1858
|
+
/**
|
|
1859
|
+
* One AI **evaluation** verdict — a scorer's `{name, score, label?}` — to attach
|
|
1860
|
+
* to a generation span via {@link SpanHandle.recordEvaluation}. Declared
|
|
1861
|
+
* structurally to mirror `shared/evaluation-attributes.ts`'s `EvaluationInput`
|
|
1862
|
+
* without a dependency edge.
|
|
1863
|
+
*/
|
|
1864
|
+
interface SpanEvaluation {
|
|
1865
|
+
/** Optional categorical label (e.g. `"pass"` / `"fail"`), emitted as `.label`. */
|
|
1866
|
+
label?: string;
|
|
1867
|
+
/** Scorer name — the key's name segment; non-`[A-Za-z0-9._-]` chars become `_`. */
|
|
1868
|
+
name: string;
|
|
1869
|
+
/** Numeric score (typically `[0, 1]`), emitted as `.score`. */
|
|
1870
|
+
score: number;
|
|
1871
|
+
}
|
|
1872
|
+
interface SpanHandle {
|
|
1873
|
+
/**
|
|
1874
|
+
* Record a timestamped event on the enclosing span — a retry, a cache miss, a
|
|
1875
|
+
* state transition. Prefer this over an extra `ctx.log` line for anything that
|
|
1876
|
+
* only makes sense *relative to this span*: it rides the span's own export, so
|
|
1877
|
+
* it costs no additional record and can never be separated from its context.
|
|
1878
|
+
*/
|
|
1879
|
+
addEvent: (name: string, attributes?: LogFields) => void;
|
|
1880
|
+
/**
|
|
1881
|
+
* Link this span to one in another trace — how a queue consumer points back at
|
|
1882
|
+
* the request that enqueued its message without collapsing every producer into
|
|
1883
|
+
* one giant trace.
|
|
1884
|
+
*/
|
|
1885
|
+
addLink: (link: SpanLink) => void;
|
|
1886
|
+
/**
|
|
1887
|
+
* Attach an AI **evaluation** verdict to this (generation) span as the
|
|
1888
|
+
* `gen_ai.evaluation.<name>.score` / `.label` OpenTelemetry attributes, so a
|
|
1889
|
+
* scorer's grade rides the same trace as the generation it graded. Convenience
|
|
1890
|
+
* over {@link SpanHandle.setAttributes} that owns the key format; privacy-safe —
|
|
1891
|
+
* only the name, score, and optional label are emitted. Throws on an empty name
|
|
1892
|
+
* or a non-finite score.
|
|
1893
|
+
*/
|
|
1894
|
+
recordEvaluation: (evaluation: SpanEvaluation) => void;
|
|
1895
|
+
/**
|
|
1896
|
+
* Record a **handled** exception as the OTel-conventional `exception` span
|
|
1897
|
+
* event (`exception.type` / `exception.message` / `exception.stacktrace`),
|
|
1898
|
+
* without marking the span failed.
|
|
1899
|
+
*
|
|
1900
|
+
* For an error you swallowed — a retried request, a fallback that worked. An
|
|
1901
|
+
* error that escapes the span body is recorded automatically and *does* set
|
|
1902
|
+
* the error status, so don't call this for one you're re-throwing.
|
|
1903
|
+
*/
|
|
1904
|
+
recordException: (error: unknown) => void;
|
|
1905
|
+
/** Set one attribute on the enclosing span (merged at record time; post-hoc wins on key clash). */
|
|
1906
|
+
setAttribute: (key: string, value: LogFields[string]) => void;
|
|
1907
|
+
/** Merge attributes onto the enclosing span (post-hoc wins on key clash). */
|
|
1908
|
+
setAttributes: (fields: LogFields) => void;
|
|
1909
|
+
/**
|
|
1910
|
+
* The W3C ids of the span this handle refers to (32-hex trace, 16-hex span).
|
|
1911
|
+
*
|
|
1912
|
+
* On `ctx.span` these are the DISPATCH's ids — the trace the whole request
|
|
1913
|
+
* belongs to. Use it to echo a trace id back to a caller so a user can quote
|
|
1914
|
+
* it in a bug report, to build a `traceparent` for a hand-rolled outbound
|
|
1915
|
+
* call, or to parent a third-party library's spans onto this request.
|
|
1916
|
+
*/
|
|
1917
|
+
spanContext: () => {
|
|
1918
|
+
spanId: string;
|
|
1919
|
+
traceId: string;
|
|
1920
|
+
};
|
|
1921
|
+
}
|
|
1922
|
+
/**
|
|
1923
|
+
* A causal reference to a span in another trace (OTel `Span.links`). Ids are
|
|
1924
|
+
* lowercase hex — 32 chars for `traceId`, 16 for `spanId`.
|
|
1925
|
+
*/
|
|
1926
|
+
interface SpanLink {
|
|
1927
|
+
/** Attributes describing the relationship, e.g. `{ "link.kind": "enqueued_by" }`. */
|
|
1928
|
+
attributes?: LogFields;
|
|
1929
|
+
spanId: string;
|
|
1930
|
+
traceId: string;
|
|
1931
|
+
}
|
|
1932
|
+
/** OTel `SpanKind`. Drives a collector's service map — see {@link SpanOptions.kind}. */
|
|
1933
|
+
type SpanKind = "client" | "consumer" | "internal" | "producer" | "server";
|
|
1934
|
+
/** Options accepted by `ctx.trace(name, fn, options)` beyond a plain attribute bag. */
|
|
1935
|
+
interface SpanOptions {
|
|
1936
|
+
/** Start attributes, snapshotted before the body runs. */
|
|
1937
|
+
attributes?: LogFields;
|
|
1938
|
+
/**
|
|
1939
|
+
* OTel `SpanKind`, default `"internal"`. Set `"client"` for a call OUT to
|
|
1940
|
+
* another service and `"producer"`/`"consumer"` for queue hops: a collector
|
|
1941
|
+
* builds its service map from this, so leaving everything `"internal"` yields
|
|
1942
|
+
* a trace with no topology.
|
|
1943
|
+
*/
|
|
1944
|
+
kind?: SpanKind;
|
|
1945
|
+
/** Links to spans in other traces, known at span start. */
|
|
1946
|
+
links?: SpanLink[];
|
|
1947
|
+
}
|
|
1948
|
+
/**
|
|
1949
|
+
* Span factory on every function `ctx`. Wraps a sub-operation so it becomes its
|
|
1950
|
+
* own **span** nested under the dispatch's RPC span, giving a trace real shape:
|
|
1951
|
+
* without it a slow request is one opaque bar, with it you see which part was
|
|
1952
|
+
* slow.
|
|
1953
|
+
*
|
|
1954
|
+
* ```ts
|
|
1955
|
+
* const charge = await ctx.trace("stripe.charge", () => stripe.charges.create(…), { orderId });
|
|
1956
|
+
* ```
|
|
1957
|
+
*
|
|
1958
|
+
* **Nesting is explicit.** The body receives a tracer bound to its own span;
|
|
1959
|
+
* calling *that* is what makes a child:
|
|
1960
|
+
*
|
|
1961
|
+
* ```ts
|
|
1962
|
+
* await ctx.trace("fulfil", async (trace) => {
|
|
1963
|
+
* // Children of "fulfil" — including under Promise.all, where an ambient
|
|
1964
|
+
* // "currently open span" would mis-record these as nested inside each other.
|
|
1965
|
+
* await Promise.all([trace("reserve.stock", …), trace("email.receipt", …)]);
|
|
1966
|
+
* });
|
|
1967
|
+
* ```
|
|
1968
|
+
*
|
|
1969
|
+
* Calling `ctx.trace` again inside a body (rather than the passed tracer) is not
|
|
1970
|
+
* an error — that span is simply parented to the dispatch instead of to the
|
|
1971
|
+
* enclosing span, which is flatter but never wrong.
|
|
1972
|
+
*
|
|
1973
|
+
* Spans share the dispatch's trace id with its `ctx.log` lines and any container
|
|
1974
|
+
* the handler calls (the same `traceparent` is propagated), so one trace spans
|
|
1975
|
+
* worker, shard, and container.
|
|
1976
|
+
*
|
|
1977
|
+
* The span is recorded when the body settles, and the body's value is returned
|
|
1978
|
+
* unchanged. A throw is recorded as an error span and then **re-thrown** — this
|
|
1979
|
+
* is instrumentation, never flow control. Recording is best-effort: a failing
|
|
1980
|
+
* sink can't turn a working handler into a broken one.
|
|
1981
|
+
*
|
|
1982
|
+
* **Post-hoc attributes.** The body also receives a {@link SpanHandle} as its
|
|
1983
|
+
* second argument. The `attributes` passed here are stamped at span start (and
|
|
1984
|
+
* snapshotted, so a later mutation can't rewrite them); anything the body sets
|
|
1985
|
+
* through the handle — `span.setAttribute(k, v)` / `span.setAttributes({…})` — is
|
|
1986
|
+
* merged over that snapshot when the span is recorded, so a value known only once
|
|
1987
|
+
* the body has resolved (an AI call's token usage / dollar cost, a computed
|
|
1988
|
+
* count) still lands on the span. Post-hoc wins on a key clash. The handle is a
|
|
1989
|
+
* trailing parameter, so every existing `(trace) => …` body keeps working
|
|
1990
|
+
* unchanged.
|
|
1991
|
+
* @param name Span name, e.g. `"stripe.charge"`. Prefer a low-cardinality name
|
|
1992
|
+
* and put the varying part in `attributes` — a name built from an id makes every
|
|
1993
|
+
* span its own group in a collector.
|
|
1994
|
+
* @param fn The body to time, receiving a tracer bound to this span for any
|
|
1995
|
+
* nested spans and the enclosing span's {@link SpanHandle} for post-hoc
|
|
1996
|
+
* attributes. May be sync or async; the result is awaited.
|
|
1997
|
+
* @param attributes Either a plain attribute bag to stamp on the span at start
|
|
1998
|
+
* (normalized like a log line's `fields`), or a {@link SpanOptions} object when
|
|
1999
|
+
* you need `kind` or `links`. It is read as options only when *every* key is one
|
|
2000
|
+
* of `attributes`/`kind`/`links`; `{ attributes: { kind: "premium" } }` is the
|
|
2001
|
+
* explicit form if your own attributes happen to be named that.
|
|
2002
|
+
*/
|
|
2003
|
+
type LunoraTracer = <T>(name: string, function_: (trace: LunoraTracer, span: SpanHandle) => Promise<T> | T, attributes?: LogFields | SpanOptions) => Promise<T>;
|
|
2004
|
+
/**
|
|
2005
|
+
* `ctx.span` — a handle onto **this request's own span**, and with it the
|
|
2006
|
+
* wide-event API.
|
|
2007
|
+
*
|
|
2008
|
+
* ```ts
|
|
2009
|
+
* export const checkout = mutation({ handler: async (ctx, args) => {
|
|
2010
|
+
* ctx.span.setAttributes({ "user.plan": user.plan, "cart.items": cart.length });
|
|
2011
|
+
* const payment = await charge(cart);
|
|
2012
|
+
* ctx.span.setAttributes({ "payment.provider": payment.provider, "payment.total": payment.total });
|
|
2013
|
+
* if (payment.retried) ctx.span.addEvent("payment.retried", { attempts: payment.attempts });
|
|
2014
|
+
* return payment;
|
|
2015
|
+
* }});
|
|
2016
|
+
* ```
|
|
2017
|
+
*
|
|
2018
|
+
* **Why this instead of more log lines.** The usual way to make a handler
|
|
2019
|
+
* observable is to sprinkle `ctx.log.info` through it, which costs one record per
|
|
2020
|
+
* call, scatters one request's facts across a dozen rows, and forces every
|
|
2021
|
+
* question to be answered by correlating them back together. The wide-event
|
|
2022
|
+
* pattern inverts that: accumulate the facts as you learn them, and emit **one**
|
|
2023
|
+
* richly-attributed record per unit of work. Cost is flat — one span per request
|
|
2024
|
+
* no matter how much you attach — and every question ("p99 checkout latency for
|
|
2025
|
+
* pro-plan users with >10 items") becomes a single filter over one table instead
|
|
2026
|
+
* of a join across log lines.
|
|
2027
|
+
*
|
|
2028
|
+
* **This is plain OpenTelemetry, not a Lunora convention.** The attributes land
|
|
2029
|
+
* on the span the dispatch already emits, and are additionally exported as an
|
|
2030
|
+
* OTel Event record named `lunora.dispatch`, correlated by `trace_id`/`span_id`.
|
|
2031
|
+
* Any OTLP backend groups and aggregates them with no special configuration.
|
|
2032
|
+
*
|
|
2033
|
+
* **`span` vs `trace`.** `ctx.trace(name, fn)` creates a NEW child span to time a
|
|
2034
|
+
* sub-operation; `ctx.span` attaches to the one that already exists for the
|
|
2035
|
+
* request. Use `trace` for "how long did this part take", `span` for "what was
|
|
2036
|
+
* true about this request". Inside a `ctx.trace` body, the handle passed as the
|
|
2037
|
+
* body's second argument is that child span's equivalent of this.
|
|
2038
|
+
*
|
|
2039
|
+
* Attributes are normalized exactly like `ctx.log` fields, and recording is
|
|
2040
|
+
* best-effort — a telemetry failure never breaks the handler.
|
|
2041
|
+
*/
|
|
2042
|
+
type LunoraWideEvent = SpanHandle;
|
|
2043
|
+
/**
|
|
2044
|
+
* Application metrics on every function `ctx` — the third signal alongside
|
|
2045
|
+
* `ctx.log` and `ctx.trace`. Each call records one measurement that flows to an
|
|
2046
|
+
* `ObservabilitySink`'s `onMetric`, and from `otlpSink` to a collector's
|
|
2047
|
+
* `/v1/metrics`.
|
|
2048
|
+
*
|
|
2049
|
+
* ```ts
|
|
2050
|
+
* ctx.metrics.count("orders.placed", 1, { plan: user.plan });
|
|
2051
|
+
* ctx.metrics.record("checkout.latency_ms", Date.now() - started);
|
|
2052
|
+
* ctx.metrics.gauge("cart.items", cart.items.length);
|
|
2053
|
+
* ```
|
|
2054
|
+
*
|
|
2055
|
+
* Pick the instrument by the question you want to answer: `count` for "how many"
|
|
2056
|
+
* (summed over time), `gauge` for "how many right now" (replaces the last
|
|
2057
|
+
* reading), `record` for "what's the distribution" (percentiles, not just a
|
|
2058
|
+
* mean).
|
|
2059
|
+
*
|
|
2060
|
+
* `attributes` are the metric's dimensions. Keep them **low-cardinality** — an
|
|
2061
|
+
* attribute valued by user id or order id creates a distinct time series per id,
|
|
2062
|
+
* which is how a metrics backend gets expensive. Put identifiers on a log line or
|
|
2063
|
+
* a span instead.
|
|
2064
|
+
*
|
|
2065
|
+
* No pre-aggregation happens: one call is one exported measurement, with counter
|
|
2066
|
+
* deltas for the collector to sum. In a hot loop, sum locally and record once
|
|
2067
|
+
* rather than calling per iteration.
|
|
2068
|
+
*/
|
|
2069
|
+
interface LunoraMetrics {
|
|
2070
|
+
/**
|
|
2071
|
+
* Add to a monotonic counter (default `1`) — requests served, retries,
|
|
2072
|
+
* bytes sent. The collector sums successive deltas.
|
|
2073
|
+
*/
|
|
2074
|
+
readonly count: (name: string, value?: number, attributes?: LogFields) => void;
|
|
2075
|
+
/**
|
|
2076
|
+
* Report a point-in-time reading that replaces the previous one — queue
|
|
2077
|
+
* depth, cache size, connections open.
|
|
2078
|
+
*/
|
|
2079
|
+
readonly gauge: (name: string, value: number, attributes?: LogFields) => void;
|
|
2080
|
+
/**
|
|
2081
|
+
* Observe one sample of a distribution — latency, payload size. Use this,
|
|
2082
|
+
* not a counter, when percentiles matter.
|
|
2083
|
+
*/
|
|
2084
|
+
readonly record: (name: string, value: number, attributes?: LogFields) => void;
|
|
1042
2085
|
}
|
|
1043
2086
|
interface QueryCtx {
|
|
1044
2087
|
readonly auth: AuthState;
|
|
1045
2088
|
readonly db: DatabaseReader;
|
|
1046
2089
|
/**
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
2090
|
+
* The validated, typed environment. Populated only when the project declares
|
|
2091
|
+
* a `defineEnv(...)` contract in `lunora/env.ts`; codegen then narrows this to
|
|
2092
|
+
* the validated `InferEnv` shape so `ctx.env.STRIPE_KEY` is parsed and
|
|
2093
|
+
* coercion-aware. Absent (optional) without a contract — declare
|
|
2094
|
+
* `lunora/env.ts` to populate and type it.
|
|
2095
|
+
*/
|
|
2096
|
+
readonly env?: Record<string, unknown>;
|
|
2097
|
+
/**
|
|
2098
|
+
* The caller's IP for this request — Cloudflare's trusted `CF-Connecting-IP`,
|
|
2099
|
+
* forwarded server-side (never read from a client header). `undefined` when
|
|
2100
|
+
* unknown: a live-subscription re-run, a server-initiated dispatch, or
|
|
2101
|
+
* non-Cloudflare hosting. A convenient rate-limit key for anonymous traffic.
|
|
2102
|
+
*/
|
|
1052
2103
|
readonly ip?: string;
|
|
1053
2104
|
/** Structured, function-attributed logger; see {@link LunoraLogger}. */
|
|
1054
2105
|
readonly log: LunoraLogger;
|
|
2106
|
+
/** Application counters, gauges, and histograms; see {@link LunoraMetrics}. */
|
|
1055
2107
|
/**
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
2108
|
+
* Static metadata declared on this procedure with `.meta(...)`, merged
|
|
2109
|
+
* across calls. Present so middleware can read the policy it is meant to
|
|
2110
|
+
* enforce (`ctx.meta.rateLimit`, …) instead of having it hard-wired at each
|
|
2111
|
+
* `.use()` site; absent when the procedure never called `.meta()`.
|
|
2112
|
+
*/
|
|
2113
|
+
readonly meta?: Readonly<Record<string, unknown>>;
|
|
2114
|
+
readonly metrics: LunoraMetrics;
|
|
2115
|
+
/**
|
|
2116
|
+
* Wall-clock time (epoch ms) the function began, captured once so the whole
|
|
2117
|
+
* handler sees a single stable value. Query/mutation handlers must be
|
|
2118
|
+
* deterministic — they may be re-run on OCC retry / subscription re-eval — so
|
|
2119
|
+
* read time through `ctx.now` instead of `Date.now()` (the latter is flagged
|
|
2120
|
+
* by the `nondeterministic_query_mutation` advisor). Actions may use `Date.now()`.
|
|
2121
|
+
*/
|
|
1062
2122
|
readonly now: number;
|
|
1063
2123
|
/**
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
readonly runQuery:
|
|
2124
|
+
* Compose a read-only subquery in-process, reusing this query's read
|
|
2125
|
+
* context (same transaction, same `db`). Executes the referenced query's
|
|
2126
|
+
* handler directly — no fresh DO RPC round-trip — so it observes the exact
|
|
2127
|
+
* same snapshot. A query may only call other queries; there is no
|
|
2128
|
+
* `runMutation` on a `QueryCtx` (writes are not allowed from a query).
|
|
2129
|
+
* Mirrors Convex's `ctx.runQuery`.
|
|
2130
|
+
*/
|
|
2131
|
+
readonly runQuery: RunQuery;
|
|
1072
2132
|
/** Read account-level secrets from Cloudflare Secrets Store; see {@link Secrets}. */
|
|
1073
2133
|
readonly secrets: Secrets;
|
|
2134
|
+
/** Attach facts to THIS request's span — the wide event; see {@link LunoraWideEvent}. */
|
|
2135
|
+
readonly span: LunoraWideEvent;
|
|
1074
2136
|
readonly storage: ReadOnlyStorage;
|
|
2137
|
+
/** Wrap a sub-operation in its own nested span; see {@link LunoraTracer}. */
|
|
2138
|
+
readonly trace: LunoraTracer;
|
|
1075
2139
|
readonly vectors: VectorSearchReader;
|
|
1076
2140
|
}
|
|
1077
2141
|
interface MutationCtx {
|
|
1078
2142
|
readonly auth: AuthState;
|
|
1079
2143
|
readonly db: DatabaseWriter;
|
|
1080
2144
|
/**
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
2145
|
+
* The validated, typed environment. Populated only when the project declares
|
|
2146
|
+
* a `defineEnv(...)` contract in `lunora/env.ts`; codegen then narrows this to
|
|
2147
|
+
* the validated `InferEnv` shape so `ctx.env.STRIPE_KEY` is parsed and
|
|
2148
|
+
* coercion-aware. Absent (optional) without a contract — declare
|
|
2149
|
+
* `lunora/env.ts` to populate and type it.
|
|
2150
|
+
*/
|
|
2151
|
+
readonly env?: Record<string, unknown>;
|
|
2152
|
+
/**
|
|
2153
|
+
* The caller's IP for this request — Cloudflare's trusted `CF-Connecting-IP`,
|
|
2154
|
+
* forwarded server-side (never read from a client header). `undefined` when
|
|
2155
|
+
* unknown: a live-subscription re-run, a server-initiated dispatch, or
|
|
2156
|
+
* non-Cloudflare hosting. A convenient rate-limit key for anonymous traffic.
|
|
2157
|
+
*/
|
|
1086
2158
|
readonly ip?: string;
|
|
1087
2159
|
/** Structured, function-attributed logger; see {@link LunoraLogger}. */
|
|
1088
2160
|
readonly log: LunoraLogger;
|
|
2161
|
+
/** Application counters, gauges, and histograms; see {@link LunoraMetrics}. */
|
|
1089
2162
|
/**
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
2163
|
+
* Static metadata declared on this procedure with `.meta(...)`, merged
|
|
2164
|
+
* across calls. Present so middleware can read the policy it is meant to
|
|
2165
|
+
* enforce (`ctx.meta.rateLimit`, …) instead of having it hard-wired at each
|
|
2166
|
+
* `.use()` site; absent when the procedure never called `.meta()`.
|
|
2167
|
+
*/
|
|
2168
|
+
readonly meta?: Readonly<Record<string, unknown>>;
|
|
2169
|
+
readonly metrics: LunoraMetrics;
|
|
2170
|
+
/**
|
|
2171
|
+
* Wall-clock time (epoch ms) the function began, captured once so the whole
|
|
2172
|
+
* handler sees a single stable value. Mutation handlers must be deterministic
|
|
2173
|
+
* — they may be re-run on OCC retry — so read time through `ctx.now` instead
|
|
2174
|
+
* of `Date.now()` (the latter is flagged by the `nondeterministic_query_mutation`
|
|
2175
|
+
* advisor). Actions may use `Date.now()`.
|
|
2176
|
+
*/
|
|
1096
2177
|
readonly now: number;
|
|
1097
2178
|
/**
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
readonly runMutation:
|
|
1106
|
-
/**
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
readonly runQuery:
|
|
2179
|
+
* Compose a submutation in-process, reusing this mutation's `db` writer.
|
|
2180
|
+
* Executes the referenced mutation's handler directly — no fresh DO RPC —
|
|
2181
|
+
* so its writes apply through the same shard invocation as the enclosing
|
|
2182
|
+
* mutation. Note: writes are not wrapped in a SQL transaction, so a partial
|
|
2183
|
+
* failure does not roll back earlier writes (the same as a top-level
|
|
2184
|
+
* mutation). Mirrors Convex's `ctx.runMutation`.
|
|
2185
|
+
*/
|
|
2186
|
+
readonly runMutation: RunMutation;
|
|
2187
|
+
/**
|
|
2188
|
+
* Compose a read-only subquery in-process, reusing this mutation's `db`.
|
|
2189
|
+
* Executes the referenced query's handler directly — no fresh DO RPC — so
|
|
2190
|
+
* it observes this mutation's in-flight writes. Mirrors Convex's
|
|
2191
|
+
* `ctx.runQuery`.
|
|
2192
|
+
*/
|
|
2193
|
+
readonly runQuery: RunQuery;
|
|
1113
2194
|
readonly scheduler: Scheduler;
|
|
1114
2195
|
/** Read account-level secrets from Cloudflare Secrets Store; see {@link Secrets}. */
|
|
1115
2196
|
readonly secrets: Secrets;
|
|
1116
|
-
|
|
2197
|
+
/** Attach facts to THIS request's span — the wide event; see {@link LunoraWideEvent}. */
|
|
2198
|
+
readonly span: LunoraWideEvent;
|
|
2199
|
+
readonly storage: MutationStorage;
|
|
2200
|
+
/** Wrap a sub-operation in its own nested span; see {@link LunoraTracer}. */
|
|
2201
|
+
readonly trace: LunoraTracer;
|
|
1117
2202
|
readonly vectors: VectorSearch;
|
|
1118
2203
|
/** Start / resume / inspect durable workflows; see {@link Workflows}. */
|
|
1119
2204
|
readonly workflows: Workflows;
|
|
1120
2205
|
}
|
|
1121
2206
|
interface ActionCtx {
|
|
1122
2207
|
readonly auth: AuthState;
|
|
2208
|
+
/**
|
|
2209
|
+
* Programmatic Workers Cache purge; see {@link CachePurge}.
|
|
2210
|
+
* **Action-only** — actions run in the Worker, which has a `cache` binding.
|
|
2211
|
+
* Queries and mutations run inside the Durable Object and do not expose this.
|
|
2212
|
+
* Optional at runtime because Workers Cache is only present when enabled.
|
|
2213
|
+
*/
|
|
2214
|
+
readonly cache?: CachePurge;
|
|
1123
2215
|
readonly db: DatabaseWriter;
|
|
2216
|
+
/**
|
|
2217
|
+
* The validated, typed environment. Populated only when the project declares
|
|
2218
|
+
* a `defineEnv(...)` contract in `lunora/env.ts`; codegen then narrows this to
|
|
2219
|
+
* the validated `InferEnv` shape so `ctx.env.STRIPE_KEY` is parsed and
|
|
2220
|
+
* coercion-aware. Absent (optional) without a contract — declare
|
|
2221
|
+
* `lunora/env.ts` to populate and type it.
|
|
2222
|
+
*/
|
|
2223
|
+
readonly env?: Record<string, unknown>;
|
|
1124
2224
|
readonly fetch: typeof globalThis.fetch;
|
|
1125
2225
|
/**
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
2226
|
+
* The caller's IP for this request — Cloudflare's trusted `CF-Connecting-IP`,
|
|
2227
|
+
* forwarded server-side (never read from a client header). `undefined` when
|
|
2228
|
+
* unknown: a live-subscription re-run, a server-initiated dispatch, or
|
|
2229
|
+
* non-Cloudflare hosting. A convenient rate-limit key for anonymous traffic.
|
|
2230
|
+
*/
|
|
1131
2231
|
readonly ip?: string;
|
|
1132
2232
|
/** Structured, function-attributed logger; see {@link LunoraLogger}. */
|
|
1133
2233
|
readonly log: LunoraLogger;
|
|
2234
|
+
/** Application counters, gauges, and histograms; see {@link LunoraMetrics}. */
|
|
2235
|
+
/**
|
|
2236
|
+
* Static metadata declared on this procedure with `.meta(...)`, merged
|
|
2237
|
+
* across calls. Present so middleware can read the policy it is meant to
|
|
2238
|
+
* enforce (`ctx.meta.rateLimit`, …) instead of having it hard-wired at each
|
|
2239
|
+
* `.use()` site; absent when the procedure never called `.meta()`.
|
|
2240
|
+
*/
|
|
2241
|
+
readonly meta?: Readonly<Record<string, unknown>>;
|
|
2242
|
+
readonly metrics: LunoraMetrics;
|
|
1134
2243
|
/**
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
2244
|
+
* Wall-clock time (epoch ms) the action began, captured once for convenience
|
|
2245
|
+
* and parity with query/mutation `ctx.now`. Actions run exactly once, so they
|
|
2246
|
+
* may also use ambient `Date.now()` freely.
|
|
2247
|
+
*/
|
|
1139
2248
|
readonly now: number;
|
|
1140
|
-
readonly runAction:
|
|
1141
|
-
readonly runMutation:
|
|
1142
|
-
readonly runQuery:
|
|
2249
|
+
readonly runAction: RunAction;
|
|
2250
|
+
readonly runMutation: RunMutation;
|
|
2251
|
+
readonly runQuery: RunQuery;
|
|
1143
2252
|
readonly scheduler: Scheduler;
|
|
1144
2253
|
/** Read account-level secrets from Cloudflare Secrets Store; see {@link Secrets}. */
|
|
1145
2254
|
readonly secrets: Secrets;
|
|
2255
|
+
/** Attach facts to THIS request's span — the wide event; see {@link LunoraWideEvent}. */
|
|
2256
|
+
readonly span: LunoraWideEvent;
|
|
1146
2257
|
readonly storage: Storage;
|
|
2258
|
+
/** Wrap a sub-operation in its own nested span; see {@link LunoraTracer}. */
|
|
2259
|
+
readonly trace: LunoraTracer;
|
|
1147
2260
|
readonly vectors: VectorSearch;
|
|
1148
2261
|
/** Start / resume / inspect durable workflows; see {@link Workflows}. */
|
|
1149
2262
|
readonly workflows: Workflows;
|
|
1150
2263
|
}
|
|
1151
2264
|
/**
|
|
1152
|
-
* Stand-in returned by codegen so projects can `import { api } from "./_generated/api"`.
|
|
1153
|
-
* The runtime value is opaque; the types are filled in by generated declarations.
|
|
1154
|
-
*/
|
|
2265
|
+
* Stand-in returned by codegen so projects can `import { api } from "./_generated/api"`.
|
|
2266
|
+
* The runtime value is opaque; the types are filled in by generated declarations.
|
|
2267
|
+
*/
|
|
1155
2268
|
type AnyApi = Record<string, Record<string, RegisteredFunction<ArgsValidator, unknown, FunctionKind>>>;
|
|
1156
2269
|
declare const anyApi: AnyApi;
|
|
1157
|
-
export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, 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, anyApi };
|
|
2270
|
+
export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationDefinition, type RestCacheConfig, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectHead, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
|