@rebasepro/types 0.30.0 → 0.31.0-canary.g902a0ce

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +16 -18
  2. package/dist/call_context.d.ts +3 -3
  3. package/dist/controllers/client.d.ts +29 -0
  4. package/dist/controllers/data.d.ts +85 -332
  5. package/dist/controllers/data_driver.d.ts +47 -57
  6. package/dist/controllers/index.d.ts +0 -3
  7. package/dist/index.d.ts +1 -0
  8. package/dist/index.es.js +2567 -1151
  9. package/dist/index.es.js.map +1 -1
  10. package/dist/schema/column_options.d.ts +336 -0
  11. package/dist/schema/column_type.d.ts +116 -0
  12. package/dist/schema/columns.d.ts +646 -0
  13. package/dist/schema/compiled.d.ts +114 -0
  14. package/dist/schema/descriptor.d.ts +349 -0
  15. package/dist/schema/hooks.d.ts +164 -0
  16. package/dist/schema/index.d.ts +13 -0
  17. package/dist/schema/infer.d.ts +340 -0
  18. package/dist/schema/json.d.ts +237 -0
  19. package/dist/schema/relations.d.ts +205 -0
  20. package/dist/schema/table.d.ts +304 -0
  21. package/dist/schema/table_options.d.ts +103 -0
  22. package/dist/schema/table_patch.d.ts +338 -0
  23. package/dist/types/auth_adapter.d.ts +12 -6
  24. package/dist/types/auth_hooks.d.ts +65 -0
  25. package/dist/types/backend.d.ts +85 -96
  26. package/dist/types/data_source.d.ts +4 -9
  27. package/dist/types/database_adapter.d.ts +30 -31
  28. package/dist/types/entities.d.ts +0 -162
  29. package/dist/types/filter-operators.d.ts +2 -26
  30. package/dist/types/history.d.ts +6 -9
  31. package/dist/types/index.d.ts +3 -9
  32. package/dist/types/mcp_app_modules.d.ts +0 -2
  33. package/dist/types/policy.d.ts +85 -10
  34. package/dist/types/project_manifest.d.ts +113 -46
  35. package/dist/types/read_query.d.ts +98 -0
  36. package/dist/types/register.d.ts +35 -5
  37. package/dist/types/relations.d.ts +0 -430
  38. package/dist/types/schema_editing.d.ts +54 -2
  39. package/dist/types/schema_version.d.ts +24 -4
  40. package/dist/types/security_rules.d.ts +225 -15
  41. package/dist/types/storage_authorize.d.ts +2 -2
  42. package/dist/types/tenancy.d.ts +3 -3
  43. package/dist/types/ui_preferences.d.ts +228 -0
  44. package/package.json +3 -2
  45. package/dist/controllers/auth_state.d.ts +0 -23
  46. package/dist/controllers/collection_registry.d.ts +0 -67
  47. package/dist/controllers/effective_role.d.ts +0 -4
  48. package/dist/types/admin_block.d.ts +0 -96
  49. package/dist/types/chips.d.ts +0 -16
  50. package/dist/types/collection_contract.d.ts +0 -43
  51. package/dist/types/collection_patch.d.ts +0 -74
  52. package/dist/types/collections.d.ts +0 -783
  53. package/dist/types/component_ref.d.ts +0 -81
  54. package/dist/types/conditions-contract.types.d.ts +0 -14
  55. package/dist/types/entity_callbacks.d.ts +0 -393
  56. package/dist/types/indexes.d.ts +0 -179
  57. package/dist/types/properties.d.ts +0 -1640
@@ -1,81 +0,0 @@
1
- /**
2
- * How a collection points at a UI component without the backend learning about React.
3
- *
4
- * This file is the hinge the BaaS/admin split turns on. `ComponentRef` is named
5
- * by a property's `admin` block (`admin.Field`, `admin.Preview`, `admin.Filter`)
6
- * and imported by `properties.ts`, which must stay in the React-free core
7
- * because every backend subsystem — validation,
8
- * the drizzle schema generator, the OpenAPI generator, the SDK codegen — reads
9
- * property definitions. If `ComponentRef` needed `React.ComponentType`, the whole
10
- * property model would have to move to the admin layer with it.
11
- *
12
- * So the React types are described structurally instead of imported. Every form
13
- * a React component takes is assignable to {@link ComponentLike}:
14
- *
15
- * - a function component is `(props: P) => ReactNode`
16
- * - a class component satisfies the construct signature (`Component` has `render`)
17
- * - `memo` and `forwardRef` return exotic components, which are callable
18
- *
19
- * The cost is that the return type is `unknown` rather than `ReactNode`, so a
20
- * function that returns something React could not render is accepted here.
21
- * `@rebasepro/cms-types` re-exports a `ReactComponentRef<P>` narrowed against
22
- * the real `React.ComponentType` for authoring and for the admin's internals,
23
- * which restores that check where it can be enforced.
24
- */
25
- /**
26
- * Structural stand-in for `React.ComponentType<P>`.
27
- *
28
- * Deliberately not `Function` or `unknown`: those would accept anything and the
29
- * resolver's runtime heuristics ({@link ComponentRef} form 3) would be all that
30
- * stood between a typo and a blank screen.
31
- */
32
- export type ComponentLike<P = any> = ((props: P) => unknown) | (new (props: P, context?: unknown) => {
33
- render(): unknown;
34
- });
35
- /**
36
- * Internal marker for a lazily-loaded component reference.
37
- * Created by the Vite transform plugin when converting string paths
38
- * to deferred `import()` calls. Users should NOT create these manually.
39
- *
40
- * @internal
41
- */
42
- export interface LazyComponentRef<P = unknown> {
43
- readonly __rebaseLazy: true;
44
- readonly load: () => Promise<{
45
- default: ComponentLike<P>;
46
- }>;
47
- }
48
- /**
49
- * A reference to a UI component that can be provided in three forms:
50
- *
51
- * 1. **String path** (recommended for collection configs):
52
- * ```ts
53
- * Field: "../../frontend/src/components/MyField"
54
- * ```
55
- * The Vite plugin transforms this into a `LazyComponentRef` at build time.
56
- * On the backend, the string stays inert and is never evaluated.
57
- *
58
- * 2. **Lazy import function**:
59
- * ```ts
60
- * Field: () => import("../../frontend/src/components/MyField")
61
- * ```
62
- * Standard ES dynamic import. Backend never calls the function.
63
- *
64
- * 3. **Direct component reference** (use only in frontend-only code):
65
- * ```ts
66
- * Field: MyFieldComponent
67
- * ```
68
- * Importing a component at the top level will pull React into the
69
- * backend runtime — only safe in code that the backend never imports.
70
- * `pnpm check:headless` fails on a collection file that does this.
71
- *
72
- * @group Types
73
- */
74
- export type ComponentRef<P = any> = string | LazyComponentRef<P> | (() => Promise<{
75
- default: ComponentLike<P>;
76
- }>) | ComponentLike<P>;
77
- /**
78
- * Type guard: checks if a value is a `LazyComponentRef` produced by the
79
- * Vite transform plugin.
80
- */
81
- export declare function isLazyComponentRef<P = unknown>(ref: unknown): ref is LazyComponentRef<P>;
@@ -1,14 +0,0 @@
1
- /**
2
- * Compile-time assertions about `PropertyConditions`.
3
- *
4
- * A plain module under `src`, imported by nothing, for the reason
5
- * `packages/client/src/query-contract.types.ts` gives: `pnpm typecheck` reads
6
- * `src`, and a type assertion in a jest test is checked by nothing.
7
- *
8
- * A dynamic bound is usually a constant. The evaluator returns a literal
9
- * number as it is, and the docs write `min: 0` — which the type, a JSON Logic
10
- * rule only, refused.
11
- */
12
- import type { PropertyConditions } from "./properties.js";
13
- export declare const literalBounds: PropertyConditions;
14
- export declare const ruleBounds: PropertyConditions;
@@ -1,393 +0,0 @@
1
- import type { CollectionConfig, FilterValues } from "./collections.js";
2
- import type { OrderByTuple } from "./filter-operators.js";
3
- import type { EntityStatus, EntityValues } from "./entities.js";
4
- import type { User } from "../users/index.js";
5
- import type { RebaseCallContext } from "../call_context.js";
6
- import type { LogicalCondition } from "../controllers/data.js";
7
- /**
8
- * Lifecycle callbacks for entity CRUD operations.
9
- *
10
- * Register per-collection on the collection's `callbacks` field, or globally
11
- * via `initializeRebaseBackend({ callbacks })`. Fires on **every** data path — REST API,
12
- * WebSocket / realtime subscriptions, and server-side writes through
13
- * `rebase.dataAsAdmin`.
14
- *
15
- * When both global and per-collection callbacks are registered, execution
16
- * order is: **global → collection → property callbacks**.
17
- *
18
- * @group Models
19
- */
20
- export type CollectionCallbacks<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User> = {
21
- /**
22
- * Callback used after fetching data.
23
- *
24
- * Fires on every read path. Use this for security-critical redaction
25
- * (PII masking, row filtering) — no read path bypasses it.
26
- *
27
- * @param props
28
- */
29
- afterRead?(props: AfterReadProps<M, USER>): Promise<Record<string, unknown>> | Record<string, unknown>;
30
- /**
31
- * Callback used **before** a read is compiled, to narrow which rows it asks
32
- * for.
33
- *
34
- * {@link CollectionCallbacks.afterRead} sees rows that have already been
35
- * fetched, so nothing in userland could influence *which* rows a read
36
- * requests — a tenant scope, a visibility window, a per-role row filter all
37
- * had to be either pushed into every call site or written as an RLS policy.
38
- * This is the hook for that.
39
- *
40
- * Return conditions to **add**. They are AND-ed into the query the caller
41
- * sent, alongside its own `filter`, its `logical` group, the soft-delete
42
- * condition and the relation scope of a nested path.
43
- *
44
- * ### Additive by construction
45
- *
46
- * The return type cannot express a removal, a replacement or an `OR` with
47
- * the caller's own conditions: it is a filter to AND in, and `AND(q, c)` is
48
- * a subset of `q` for every `c`. That is deliberate and it is the reason
49
- * the hook is shaped this way rather than as `(query) => query`. A hook
50
- * handed the parsed query and asked to return one could drop a condition,
51
- * and on an RLS data plane a dropped condition is a widened read — the same
52
- * reasoning that makes `UnknownFilterFieldsMode` in
53
- * `@rebasepro/server-postgres` default to `"error"` rather than to dropping
54
- * what it cannot compile.
55
- *
56
- * For the same reason the returned filter is compiled with unknown fields
57
- * **always** fatal, whatever the process-wide mode is: a scoping condition
58
- * on a renamed column must refuse the request, never run without it.
59
- *
60
- * ### Every read path, no bypass
61
- *
62
- * It fires on the listing, the single get, the count, the aggregate, the
63
- * search, the vector read, the nested-path listing, the realtime refetch
64
- * that builds subscription frames, and on the rows loaded for a relation or
65
- * an `include` — where it is the **target** collection's hook that applies,
66
- * because those are the target's rows. A hook honoured by the listing and
67
- * not by the count is a page that says "1 of 4 results".
68
- *
69
- * Two reads are deliberately not narrowed, and both would be wrong to
70
- * narrow:
71
- *
72
- * - **`checkUniqueField`.** It asks whether a value exists *anywhere* in
73
- * the table. Narrowed, it would answer "unique" for a value a row the
74
- * caller cannot see already holds, and the insert would then fail on the
75
- * constraint instead.
76
- * - **A write's own pre-read** is narrowed, not exempt: an update or delete
77
- * addressed at a row this hook excludes answers "not found", which is the
78
- * same answer the read gives.
79
- *
80
- * ### Postgres only, for now
81
- *
82
- * Implemented by `@rebasepro/server-postgres`. A collection served by
83
- * another engine that declares one is **refused at boot** rather than
84
- * served with the hook silently inert — see `assertBeforeQueryIsPostgresOnly`.
85
- * That is the same treatment a `search` block gets on a non-Postgres
86
- * collection, and for the same reason: a security-shaped hook that does
87
- * nothing is worse than one that is absent.
88
- *
89
- * @example
90
- * ```ts
91
- * callbacks: {
92
- * beforeQuery: ({ context }) => {
93
- * if (context.user?.roles?.includes("admin")) return;
94
- * return { filter: { owner_id: ["==", context.user?.uid ?? null] } };
95
- * }
96
- * }
97
- * ```
98
- *
99
- * @param props
100
- */
101
- beforeQuery?(props: BeforeQueryProps<M, USER>): Promise<QueryNarrowing<M> | void> | QueryNarrowing<M> | void;
102
- /**
103
- * Callback used before saving, you need to return the values that will get
104
- * saved. If you throw an error in this method the process stops, and an
105
- * HTTP error response is returned to the client.
106
- * This runs after schema validation.
107
- *
108
- * @param props
109
- */
110
- beforeSave?(props: BeforeSaveProps<M, USER>): Promise<Partial<EntityValues<M>>> | Partial<EntityValues<M>>;
111
- /**
112
- * Callback used when save is successful.
113
- *
114
- * @param props
115
- */
116
- afterSave?(props: AfterSaveProps<M, USER>): Promise<void> | void;
117
- /**
118
- * Callback used when saving fails
119
- * @param props
120
- */
121
- afterSaveError?(props: AfterSaveErrorProps<M, USER>): Promise<void> | void;
122
- /**
123
- * Callback used before the entity is deleted.
124
- * If you throw an error in this method the process stops, and an
125
- * HTTP error response is returned to the client.
126
- *
127
- * @param props
128
- */
129
- beforeDelete?(props: BeforeDeleteProps<M, USER>): Promise<boolean | void> | boolean | void;
130
- /**
131
- * Callback used after the entity is deleted.
132
- *
133
- * @param props
134
- */
135
- afterDelete?(props: AfterDeleteProps<M, USER>): Promise<void> | void;
136
- };
137
- /**
138
- * Parameters passed to hooks when a entity is fetched
139
- * @group Models
140
- */
141
- export interface AfterReadProps<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User> {
142
- /**
143
- * Collection of the entity
144
- */
145
- collection: CollectionConfig<M>;
146
- /**
147
- * Full path of the admin where this collection is being fetched.
148
- * Might contain unresolved aliases.
149
- */
150
- path: string;
151
- /**
152
- * Fetched row (flat — the table's columns)
153
- */
154
- row: Record<string, unknown>;
155
- /**
156
- * Context of the app status
157
- */
158
- context: RebaseCallContext<USER>;
159
- }
160
- /**
161
- * Which read a {@link CollectionCallbacks.beforeQuery} hook is narrowing.
162
- *
163
- * Named rather than inferred because the four are not interchangeable to a
164
- * hook that logs, measures or short-circuits: `"count"` and `"aggregate"` serve
165
- * a total rather than rows, and `"relation"` is the target collection's own
166
- * hook firing over rows reached from a parent.
167
- *
168
- * @group Models
169
- */
170
- export type ReadOperation = "list" | "get" | "count" | "aggregate" | "relation";
171
- /**
172
- * The parsed read, as a {@link CollectionCallbacks.beforeQuery} hook sees it.
173
- *
174
- * Read-only throughout, and that is the point rather than a courtesy: a hook
175
- * that could edit this object would be able to *widen* the read, which is the
176
- * one thing this hook is built not to permit. Mutating it is a compile error;
177
- * narrowing is what the return value is for.
178
- *
179
- * Fields are present exactly when the caller sent them. An absent `filter` is
180
- * a query with no filter, not an empty one.
181
- *
182
- * @group Models
183
- */
184
- export interface ReadQuery<M extends Record<string, unknown> = Record<string, unknown>> {
185
- /** The caller's own field filter. */
186
- readonly filter?: Readonly<FilterValues<Extract<keyof M, string>>>;
187
- /** The caller's `or(...)` / `and(...)` group, if any. */
188
- readonly logical?: Readonly<LogicalCondition>;
189
- /** The text typed into a search box, if this is a search. */
190
- readonly searchString?: string;
191
- /** Page size, when the caller asked for one. */
192
- readonly limit?: number;
193
- /** Offset pagination, when the caller asked for one. */
194
- readonly offset?: number;
195
- /**
196
- * Sort keys, normalized to tuples — one entry per key, in order of
197
- * significance, whichever of the several authoring forms the caller used.
198
- */
199
- readonly orderBy?: readonly Readonly<OrderByTuple>[];
200
- /** Column projection, when the caller narrowed it with `fields`. */
201
- readonly fields?: readonly string[];
202
- /**
203
- * The parent this read hangs off, for `operation: "relation"` and for a
204
- * nested path like `authors/1/posts`.
205
- *
206
- * A hook that scopes by tenant usually ignores it. A hook that needs to
207
- * know it is looking at *someone's* rows rather than all of them does not.
208
- */
209
- readonly relatedTo?: {
210
- readonly parentSlug: string;
211
- readonly parentId?: string | number;
212
- readonly relationName: string;
213
- };
214
- }
215
- /**
216
- * What a {@link CollectionCallbacks.beforeQuery} hook returns: conditions to
217
- * AND into the read.
218
- *
219
- * Returning nothing (`undefined`, or no `return` at all) adds nothing and
220
- * leaves the compiled SQL byte-identical to what it would have been.
221
- *
222
- * Both fields are the same declarative language a caller's own query uses, so
223
- * a relation path (`author.tenant_id`), a JSON path (`meta->>tier`) and every
224
- * `WhereFilterOp` works here too. There is no raw-SQL member, and that is
225
- * deliberate: raw SQL could be `OR`-ed against the caller's conditions and so
226
- * could widen the read.
227
- *
228
- * @group Models
229
- */
230
- export interface QueryNarrowing<M extends Record<string, unknown> = Record<string, unknown>> {
231
- /**
232
- * A field filter to AND in.
233
- *
234
- * Compiled with unknown fields fatal, always: a scope condition that names
235
- * a column the table does not have refuses the request rather than running
236
- * without it.
237
- */
238
- filter?: FilterValues<Extract<keyof M, string>>;
239
- /**
240
- * An `or(...)` / `and(...)` group to AND in, for a scope that is a
241
- * disjunction — "mine, or shared with me", say.
242
- *
243
- * Still additive: the group is AND-ed into the query as a whole, so an
244
- * `or` inside it can only ever choose between rows the rest of the query
245
- * already admits.
246
- */
247
- logical?: LogicalCondition;
248
- }
249
- /**
250
- * Parameters passed to a {@link CollectionCallbacks.beforeQuery} hook.
251
- *
252
- * @group Models
253
- */
254
- export interface BeforeQueryProps<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User> {
255
- /**
256
- * Collection being read. For `operation: "relation"` this is the
257
- * **target** collection — the one the rows belong to.
258
- */
259
- collection: CollectionConfig<M>;
260
- /**
261
- * Full path being read. Might contain unresolved aliases, and for a nested
262
- * read it is the target collection's own path rather than the nested one —
263
- * the nested parent is on {@link ReadQuery.relatedTo}.
264
- */
265
- path: string;
266
- /** Which read this is. */
267
- operation: ReadOperation;
268
- /** The parsed read, read-only. */
269
- query: ReadQuery<M>;
270
- /**
271
- * Context of the app status.
272
- *
273
- * `context.data` is the caller's own plane, so a lookup made here is
274
- * itself RLS-scoped — and it is a read issued from inside a read, on the
275
- * same connection. Keep it to something cheap and cacheable, or read it
276
- * once per request outside the hook.
277
- */
278
- context: RebaseCallContext<USER>;
279
- }
280
- /**
281
- * Parameters passed to hooks before a entity is saved
282
- * @group Models
283
- */
284
- export type BeforeSaveProps<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User> = Omit<AfterSaveProps<M, USER>, "id"> & {
285
- id?: string | number;
286
- };
287
- /**
288
- * Parameters passed to hooks when a save fails.
289
- *
290
- * `id` is optional because a failed create may never have been assigned one.
291
- * `error` is what the save threw — the reason the hook exists. Documented since
292
- * the callbacks guide first shipped, and until now not on the type or on the
293
- * object: a handler that read `props.error` compiled and logged `undefined`.
294
- *
295
- * @group Models
296
- */
297
- export type AfterSaveErrorProps<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User> = Omit<AfterSaveProps<M, USER>, "id"> & {
298
- id?: string | number;
299
- /**
300
- * Whatever the save threw: a `RebaseApiError` when a `before*` callback
301
- * or a validator refused it, otherwise the driver's error with the
302
- * SQLSTATE in its cause chain. Not narrowed, because a callback may
303
- * throw anything.
304
- */
305
- error: unknown;
306
- };
307
- /**
308
- * Parameters passed to hooks when a entity is saved
309
- * @group Models
310
- */
311
- export interface AfterSaveProps<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User> {
312
- /**
313
- * Resolved collection of the entity
314
- */
315
- collection: CollectionConfig<M>;
316
- /**
317
- * Full path of the admin where this entity is being saved.
318
- * Might contain unresolved aliases.
319
- */
320
- path: string;
321
- /**
322
- * ID of the entity
323
- */
324
- id: string | number;
325
- /**
326
- * Values being saved
327
- */
328
- values: Partial<EntityValues<M>>;
329
- /**
330
- * Previous values
331
- */
332
- previousValues?: Partial<EntityValues<M>>;
333
- /**
334
- * New or existing entity
335
- */
336
- status: EntityStatus;
337
- /**
338
- * Context of the app status
339
- */
340
- context: RebaseCallContext<USER>;
341
- }
342
- /**
343
- * Parameters passed to hooks when a entity is deleted
344
- * @group Models
345
- */
346
- export interface BeforeDeleteProps<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User> {
347
- /**
348
- * collection of the entity being deleted
349
- */
350
- collection: CollectionConfig<M>;
351
- /**
352
- * Path of the parent collection
353
- */
354
- path: string;
355
- /**
356
- * Deleted entity id
357
- */
358
- id: string | number;
359
- /**
360
- * Deleted row (flat — the table's columns)
361
- */
362
- row: Record<string, unknown>;
363
- /**
364
- * Context of the app status
365
- */
366
- context: RebaseCallContext<USER>;
367
- }
368
- /**
369
- * Parameters passed to hooks after a entity is deleted
370
- * @group Models
371
- */
372
- export interface AfterDeleteProps<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User> {
373
- /**
374
- * collection of the entity being deleted
375
- */
376
- collection: CollectionConfig<M>;
377
- /**
378
- * Path of the parent collection
379
- */
380
- path: string;
381
- /**
382
- * Deleted entity id
383
- */
384
- id: string | number;
385
- /**
386
- * Deleted row (flat — the table's columns)
387
- */
388
- row: Record<string, unknown>;
389
- /**
390
- * Context of the app status
391
- */
392
- context: RebaseCallContext<USER>;
393
- }
@@ -1,179 +0,0 @@
1
- /**
2
- * Ordinary indexes, declared on a collection.
3
- *
4
- * Distinct from the two index-shaped things Rebase already builds. A `search`
5
- * block builds a GIN index over a generated `tsvector`, and a `vector`
6
- * property builds an ANN index over an embedding; both are structures the
7
- * *feature* owns and neither is a query the developer wrote. This is the plain
8
- * case — the btree behind a `where` clause — which had no declaration site at
9
- * all, so the only way to have one was to write it by hand, where the next
10
- * `rebase db push` planned it away.
11
- *
12
- * Every form here is core Postgres, deliberately. See {@link CollectionIndex}.
13
- */
14
- /**
15
- * A key column of an index whose access method has no ordering.
16
- *
17
- * `gin` and `brin` reject `ASC`/`DESC`/`NULLS` outright — Postgres answers
18
- * `access method "gin" does not support ASC/DESC options` — so those methods
19
- * take this narrower shape and the combination is unrepresentable rather than
20
- * refused at build time.
21
- */
22
- export interface UnorderedIndexKey<Keys extends string = string> {
23
- /**
24
- * A property key on this collection — never a column name.
25
- *
26
- * Which column that resolves to depends on the property, and the two
27
- * differ in exactly the case an index is most often wanted for: a
28
- * `belongsTo` relation compiles to its resolved `localKey`
29
- * (`primaryCategory` → `primary_category_id`), not to the snake-cased
30
- * property key. Anything else resolves through `columnName`, or the
31
- * snake-case default when it declares none.
32
- *
33
- * Writing the column name here would work for most properties and quietly
34
- * index nothing for a foreign key, which is the one people reach for.
35
- */
36
- prop: Keys | (string & {});
37
- }
38
- /**
39
- * A key column of an index, when its order matters.
40
- *
41
- * `direction` and `nulls` earn their place only when a query's `ORDER BY`
42
- * mixes directions. A lone `DESC` index is redundant with its `ASC` twin —
43
- * Postgres scans a btree backwards just as fast — and declaring both is
44
- * refused.
45
- *
46
- * Writing the Postgres default down explicitly is free: the derived name
47
- * hashes the *effective* order, so adding `direction: "asc"` to a column that
48
- * was already ascending is not a redefinition and rebuilds nothing.
49
- */
50
- export interface IndexKey<Keys extends string = string> extends UnorderedIndexKey<Keys> {
51
- direction?: "asc" | "desc";
52
- /** Postgres's own default: `last` under `asc`, `first` under `desc`. */
53
- nulls?: "first" | "last";
54
- }
55
- /**
56
- * The rows a partial index covers.
57
- *
58
- * Structure rather than a SQL string, and this is the most load-bearing choice
59
- * in the type. A string would be replayed verbatim by Atlas in a scratch
60
- * database, would be the one place a caller reaches for an extension operator
61
- * class or a subquery, could not be checked against the collection's
62
- * properties, and could not be fingerprinted — its own text would have to go
63
- * into the derived name, so reformatting it would rename a live index.
64
- *
65
- * Structure keeps every reference resolvable at build time, keeps literals
66
- * going through the same quoting as the rest of the DDL, and keeps the name
67
- * stable under any rendering change.
68
- *
69
- * There is no `or`. An OR predicate almost always means the index should not
70
- * be partial at all; a caller who genuinely needs one declares two indexes.
71
- */
72
- export type IndexPredicate<Keys extends string = string> = {
73
- prop: Keys | (string & {});
74
- op: "=";
75
- value: string | number | boolean;
76
- } | {
77
- prop: Keys | (string & {});
78
- op: "!=" | "<" | "<=" | ">" | ">=";
79
- value: string | number;
80
- } | {
81
- prop: Keys | (string & {});
82
- op: "is null" | "is not null";
83
- }
84
- /**
85
- * A non-empty list, enforced in the type. An empty `IN` is a predicate
86
- * matching nothing: it builds an index over zero rows and reports success,
87
- * which is the silent-empty-condition shape this codebase has been bitten
88
- * by before.
89
- */
90
- | {
91
- prop: Keys | (string & {});
92
- op: "in";
93
- value: readonly [string | number, ...(string | number)[]];
94
- } | {
95
- and: readonly [IndexPredicate<Keys>, ...IndexPredicate<Keys>[]];
96
- };
97
- interface BaseCollectionIndex<Keys extends string = string> {
98
- /**
99
- * The key columns, in order. This *is* the index's identity.
100
- *
101
- * Postgres can only use a leading subset, so `["ownerId", "createdAt"]`
102
- * serves a query filtering on `ownerId`, and one filtering on both, and
103
- * never one filtering on `createdAt` alone.
104
- *
105
- * Capped at five keys. Postgres allows thirty-two; past four the trailing
106
- * columns are dead weight on every write, and the declaration is usually
107
- * someone hoping a query gets faster by accretion. Payload columns that
108
- * are not searched belong in `include`, which does not count against this.
109
- */
110
- on: readonly [Keys | IndexKey<Keys>, ...(Keys | IndexKey<Keys>)[]];
111
- where?: IndexPredicate<Keys>;
112
- /**
113
- * Why this index exists, in one line. Required, and the only required
114
- * field carrying no SQL.
115
- *
116
- * An index is the only thing a Rebase config can declare that costs money
117
- * forever and whose benefit is invisible from the config. `rebase doctor`
118
- * prints this beside "0 scans in 34 days, 412 MB", which is the one moment
119
- * anyone is in a position to decide whether to delete it. Without it
120
- * nobody can decide, so nobody does, and the table accretes indexes for
121
- * the life of the product.
122
- */
123
- reason: string;
124
- }
125
- /**
126
- * The default. Answers equality, range, `ORDER BY`, and uniqueness.
127
- */
128
- export interface BtreeIndex<Keys extends string = string> extends BaseCollectionIndex<Keys> {
129
- using?: "btree";
130
- /**
131
- * A composite uniqueness guarantee.
132
- *
133
- * Single-column uniqueness is `validation.unique` on the property, and
134
- * declaring it here is refused rather than accepted as a synonym.
135
- * `validation.unique` compiles to an inline `UNIQUE` whose backing index
136
- * Postgres — not Rebase — names `<table>_<column>_key`. That name is in
137
- * every deployed database, appears in no contract file, and no release can
138
- * reach in and rename it.
139
- */
140
- unique?: boolean;
141
- /**
142
- * Payload columns carried in the leaf pages, for index-only scans. Not
143
- * searchable and not ordered — they save a heap fetch at the cost of a
144
- * fatter index. May not overlap `on`.
145
- */
146
- include?: readonly (Keys | (string & {}))[];
147
- }
148
- /**
149
- * Containment over an `array` property or a JSONB `map`, using core operator
150
- * classes only. Trigram and full-text search are `search:`, not this.
151
- */
152
- export interface GinIndex<Keys extends string = string> extends BaseCollectionIndex<Keys> {
153
- using: "gin";
154
- on: readonly [Keys | UnorderedIndexKey<Keys>, ...(Keys | UnorderedIndexKey<Keys>)[]];
155
- }
156
- /**
157
- * A naturally-ordered column on an append-only table — tiny, and useless the
158
- * moment rows arrive out of order.
159
- */
160
- export interface BrinIndex<Keys extends string = string> extends BaseCollectionIndex<Keys> {
161
- using: "brin";
162
- on: readonly [Keys | UnorderedIndexKey<Keys>, ...(Keys | UnorderedIndexKey<Keys>)[]];
163
- }
164
- /**
165
- * An index on a collection's table.
166
- *
167
- * No `gist` and no `hash`: every interesting gist operator class ships in an
168
- * extension, and hash indexes cannot be unique, composite, or ordered.
169
- *
170
- * The restriction to core Postgres is not conservatism, it is what keeps the
171
- * whole model on the Atlas path. `rebase db push` materialises the desired
172
- * state in a bare scratch database to plan against, `--exclude` does not
173
- * suppress that replay, and `CREATE EXTENSION` cannot be put in the file — so
174
- * an index needing `gin_trgm_ops` or `vector_cosine_ops` is refused at build
175
- * time rather than emitted to fail later against a database the author has
176
- * never heard of. Trigram search is `search:`; ANN is a `vector` property.
177
- */
178
- export type CollectionIndex<Keys extends string = string> = BtreeIndex<Keys> | GinIndex<Keys> | BrinIndex<Keys>;
179
- export {};