@supatype/types 0.1.6 → 0.1.7
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/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +10 -8
- package/.turbo/turbo-typecheck.log +2 -2
- package/dist/index.d.ts +432 -26
- package/dist/index.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +524 -70
- package/tests/modifier-unwrap.test.ts +41 -0
- package/tests/primitives.test.ts +52 -85
- package/tests/relation-cycles.test.ts +50 -0
- package/tsconfig.test.json +26 -0
- package/tsconfig.tsbuildinfo +1 -1
package/.turbo/turbo-build.log
CHANGED
package/.turbo/turbo-test.log
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
|
|
2
|
-
> @supatype/types@0.1.
|
|
2
|
+
> @supatype/types@0.1.7 test /home/runner/work/supatype/supatype/packages/types
|
|
3
3
|
> vitest run
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
[1m[46m RUN [49m[22m [36mv4.0.18 [39m[90m/home/runner/work/supatype/supatype/packages/types[39m
|
|
7
7
|
|
|
8
|
-
[32m✓[39m tests/
|
|
9
|
-
[32m✓[39m tests/
|
|
10
|
-
[32m✓[39m tests/
|
|
8
|
+
[32m✓[39m tests/relation-cycles.test.ts [2m([22m[2m2 tests[22m[2m)[22m[32m 27[2mms[22m[39m
|
|
9
|
+
[32m✓[39m tests/optional-model-spread.test.ts [2m([22m[2m5 tests[22m[2m)[22m[32m 37[2mms[22m[39m
|
|
10
|
+
[32m✓[39m tests/primitives.test.ts [2m([22m[2m15 tests[22m[2m)[22m[32m 40[2mms[22m[39m
|
|
11
|
+
[32m✓[39m tests/modifier-unwrap.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 12[2mms[22m[39m
|
|
12
|
+
[32m✓[39m tests/primitives.test.js [2m([22m[2m3 tests[22m[2m)[22m[32m 17[2mms[22m[39m
|
|
11
13
|
|
|
12
|
-
[2m Test Files [22m [1m[
|
|
13
|
-
[2m Tests [22m [1m[
|
|
14
|
-
[2m Start at [22m
|
|
15
|
-
[2m Duration [22m
|
|
14
|
+
[2m Test Files [22m [1m[32m5 passed[39m[22m[90m (5)[39m
|
|
15
|
+
[2m Tests [22m [1m[32m29 passed[39m[22m[90m (29)[39m
|
|
16
|
+
[2m Start at [22m 21:55:08
|
|
17
|
+
[2m Duration [22m 2.38s[2m (transform 627ms, setup 0ms, import 1.13s, tests 133ms, environment 1ms)[22m
|
|
16
18
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
|
|
2
|
-
> @supatype/types@0.1.
|
|
3
|
-
> tsc --project tsconfig.json --noEmit
|
|
2
|
+
> @supatype/types@0.1.7 typecheck /home/runner/work/supatype/supatype/packages/types
|
|
3
|
+
> tsc --project tsconfig.json --noEmit && tsc --project tsconfig.test.json
|
|
4
4
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,17 +1,49 @@
|
|
|
1
1
|
import type { SerializedEditorState } from "./lexical.js";
|
|
2
2
|
declare const SUPATYPE_TYPE: unique symbol;
|
|
3
3
|
declare const SUPATYPE_MODEL: unique symbol;
|
|
4
|
-
|
|
4
|
+
/**
|
|
5
|
+
* A value type wearing a compile-time label.
|
|
6
|
+
*
|
|
7
|
+
* Named for what it does rather than the community's "branded types" idiom, which reads as content
|
|
8
|
+
* vocabulary in a package that also exports `Block`, `Blocks` and `Localized`.
|
|
9
|
+
*
|
|
10
|
+
* The phantom property is **optional**, which is what keeps values usable: `id.toUpperCase()` works and
|
|
11
|
+
* a plain string can be assigned to a `UUID`. It also means the label is not reliably *detectable* — any
|
|
12
|
+
* type structurally satisfies a tag whose only property is optional — so this is for things that are
|
|
13
|
+
* values (`UUID`, an access rule, the model marker) and never for field declarations. Declarations use
|
|
14
|
+
* a required discriminator instead; see `Modifier`.
|
|
15
|
+
*
|
|
16
|
+
* Two differently-tagged types do repel each other (`Email` is not a `UUID`), but only because
|
|
17
|
+
* `exactOptionalPropertyTypes` is on. Erased at runtime: no value ever carries the property.
|
|
18
|
+
*/
|
|
19
|
+
type Tagged<TShape, TTag extends string> = TShape & {
|
|
5
20
|
readonly [SUPATYPE_TYPE]?: {
|
|
6
21
|
readonly tag: TTag;
|
|
7
22
|
};
|
|
8
23
|
};
|
|
9
|
-
type Primitive<TName extends string, TShape> =
|
|
10
|
-
|
|
11
|
-
|
|
24
|
+
type Primitive<TName extends string, TShape> = Tagged<TShape, `primitive:${TName}`>;
|
|
25
|
+
/**
|
|
26
|
+
* A field *declaration* wrapper — `Optional<string>`, `Unique<Slug>`, `Localized<RichText>`.
|
|
27
|
+
*
|
|
28
|
+
* **Nominal, with a required discriminator**, unlike `Tagged`. Nobody ever holds a value of type
|
|
29
|
+
* `Optional<string>`: you declare a field with it and read the row shape `Model<>` derives, so this does
|
|
30
|
+
* not need to be assignable to its own inner type — and making it so was the cause of three defects.
|
|
31
|
+
*
|
|
32
|
+
* As an intersection carrying an optional tag, every type satisfied `Modifier<Name, infer _>`: a plain
|
|
33
|
+
* `string` reported as `Optional`, so unwrapping never reached a fixed point (`TS2589` on reading any
|
|
34
|
+
* optional field), `Optional<FileAsset<B>>` collapsed to `never`, and stacked modifiers lost their tag
|
|
35
|
+
* to an intersection so only structural matching could see the outer one. A required property is
|
|
36
|
+
* exactly what the relation types already use (`__relationKind`), which is why relation detection was
|
|
37
|
+
* never broken.
|
|
38
|
+
*/
|
|
39
|
+
type Modifier<TName extends string, TInner> = {
|
|
40
|
+
readonly __modifier: TName;
|
|
41
|
+
readonly __inner: TInner;
|
|
42
|
+
};
|
|
43
|
+
type Relation<TName extends string, TInner> = Tagged<TInner, `relation:${TName}`>;
|
|
12
44
|
type Access<TName extends string, TShape = {
|
|
13
45
|
readonly kind: TName;
|
|
14
|
-
}> =
|
|
46
|
+
}> = Tagged<TShape, `access:${TName}`>;
|
|
15
47
|
export type UUID = Primitive<"UUID", string>;
|
|
16
48
|
export type Email = Primitive<"Email", string>;
|
|
17
49
|
export type URL = Primitive<"URL", string>;
|
|
@@ -45,6 +77,7 @@ export type Geo = Primitive<"Geo", {
|
|
|
45
77
|
type: "point" | "polygon" | "linestring";
|
|
46
78
|
coordinates: unknown;
|
|
47
79
|
}>;
|
|
80
|
+
/** Source text with the language it is written in. Stored as `JSONB`. */
|
|
48
81
|
export type Code<Lang extends string = string> = Primitive<"Code", {
|
|
49
82
|
lang: Lang;
|
|
50
83
|
source: string;
|
|
@@ -56,8 +89,16 @@ export type GeoPoint = Primitive<"GeoPoint", {
|
|
|
56
89
|
lat: number;
|
|
57
90
|
lng: number;
|
|
58
91
|
}>;
|
|
92
|
+
/**
|
|
93
|
+
* An amount in minor units with the currency it is denominated in. Stored as `JSONB`.
|
|
94
|
+
*
|
|
95
|
+
* `amount` is a **string**, like {@link Money} and {@link Decimal}, because the value crosses the
|
|
96
|
+
* wire as JSON: `bigint` cannot be serialised (`JSON.stringify(1n)` throws) and `number` loses
|
|
97
|
+
* integers past 2^53. Use {@link Money} or {@link Decimal} instead when you want a numeric column
|
|
98
|
+
* to sum and index — this type keeps the currency with the amount, which a scalar column cannot.
|
|
99
|
+
*/
|
|
59
100
|
export type Currency<Code extends string = string> = Primitive<"Currency", {
|
|
60
|
-
amount:
|
|
101
|
+
amount: string;
|
|
61
102
|
code: Code;
|
|
62
103
|
}>;
|
|
63
104
|
/** Link target for {@link Button}. */
|
|
@@ -230,12 +271,42 @@ export type WithTimestamps<T extends Record<string, unknown>> = T & Timestamps;
|
|
|
230
271
|
export type WithSoftDelete<T extends Record<string, unknown>> = T & SoftDelete;
|
|
231
272
|
export type WithPublishable<T extends Record<string, unknown>> = T & Publishable;
|
|
232
273
|
export type OnDelete = "cascade" | "setNull" | "restrict" | "noAction";
|
|
274
|
+
export type OnUpdate = OnDelete;
|
|
275
|
+
/**
|
|
276
|
+
* Options on a relation field.
|
|
277
|
+
*
|
|
278
|
+
* Only what the extractor reads. `inverse` used to be declared here and was honoured by nothing,
|
|
279
|
+
* which is worse than absent: it type-checked, so a schema could name an inverse relation and get
|
|
280
|
+
* silence. The inverse side is declared as its own `HasMany<…>` / `HasOne<…>` field instead.
|
|
281
|
+
*/
|
|
233
282
|
export type RelationOptions = {
|
|
283
|
+
/** `NOT NULL` on the foreign key column. */
|
|
234
284
|
required?: boolean;
|
|
235
285
|
onDelete?: OnDelete;
|
|
236
|
-
|
|
286
|
+
onUpdate?: OnUpdate;
|
|
287
|
+
/** `ManyToMany` only — the junction table's name, instead of one derived from the two models. */
|
|
288
|
+
through?: string;
|
|
237
289
|
};
|
|
238
|
-
|
|
290
|
+
/**
|
|
291
|
+
* The target model, held behind a property so that resolving a relation field does not resolve the
|
|
292
|
+
* model it points at.
|
|
293
|
+
*
|
|
294
|
+
* Two models that name each other — a `HasOne` and its `RelatedTo`, or a `RelatedTo` both ways —
|
|
295
|
+
* used to fail with `TS2589: Type instantiation is excessively deep`. `Model<F>` spreads `F` through
|
|
296
|
+
* a mapped type that probes every field (`[V] extends [Modifier<"Optional", …>]`), and probing
|
|
297
|
+
* `RelatedTo<Post>` = `Post & …` meant expanding `Post`, which was still being defined. The
|
|
298
|
+
* collection relations escaped it: `Comment[]` is decidable without expanding `Comment`, so
|
|
299
|
+
* `HasMany` and `ManyToMany` are left as they were and only the one-ish relations defer here.
|
|
300
|
+
*
|
|
301
|
+
* Nothing needs a relation field's value type — the target's *identity* carries the relation, the
|
|
302
|
+
* generated client types carry the row shapes, and the CLI reads these declarations as syntax
|
|
303
|
+
* rather than resolving them. So the target moves into a phantom property, where TypeScript leaves
|
|
304
|
+
* it alone until something asks.
|
|
305
|
+
*/
|
|
306
|
+
export interface RelationTarget<T> {
|
|
307
|
+
readonly __relationTarget?: T;
|
|
308
|
+
}
|
|
309
|
+
export type RelatedTo<T, TOptions extends RelationOptions = {}> = Relation<"RelatedTo", RelationTarget<T>> & {
|
|
239
310
|
readonly __relationOptions?: TOptions;
|
|
240
311
|
readonly __relationKind: "relatedTo";
|
|
241
312
|
};
|
|
@@ -243,7 +314,7 @@ export type HasMany<T, TOptions extends RelationOptions = {}> = Relation<"HasMan
|
|
|
243
314
|
readonly __relationOptions?: TOptions;
|
|
244
315
|
readonly __relationKind: "hasMany";
|
|
245
316
|
};
|
|
246
|
-
export type HasOne<T, TOptions extends RelationOptions = {}> = Relation<"HasOne", T | null> & {
|
|
317
|
+
export type HasOne<T, TOptions extends RelationOptions = {}> = Relation<"HasOne", RelationTarget<T> | null> & {
|
|
247
318
|
readonly __relationOptions?: TOptions;
|
|
248
319
|
readonly __relationKind: "hasOne";
|
|
249
320
|
};
|
|
@@ -305,6 +376,186 @@ export type Role<R extends string = string> = Access<"Role", {
|
|
|
305
376
|
readonly kind: "Role";
|
|
306
377
|
readonly role: R;
|
|
307
378
|
}>;
|
|
379
|
+
/**
|
|
380
|
+
* OR-composition: access is granted when **any** listed rule matches.
|
|
381
|
+
*
|
|
382
|
+
* Without this, rules are a closed set of single shapes and the commonest real
|
|
383
|
+
* requirement — "an admin, or the owner" — cannot be written at all. Every rule
|
|
384
|
+
* is combinable, including nested `Any`.
|
|
385
|
+
*
|
|
386
|
+
* ```typescript
|
|
387
|
+
* access: { update: Any<[Role<"admin">, Owner<"author_id">]> }
|
|
388
|
+
* ```
|
|
389
|
+
*
|
|
390
|
+
* Compiles to the rules joined with `OR`. An empty list is rejected at extract
|
|
391
|
+
* time rather than compiling to a policy that grants nothing.
|
|
392
|
+
*/
|
|
393
|
+
export type Any<TRules extends readonly unknown[]> = Access<"Any", {
|
|
394
|
+
readonly kind: "Any";
|
|
395
|
+
readonly rules: TRules;
|
|
396
|
+
}>;
|
|
397
|
+
/** AND-composition: access needs **every** listed rule to match. */
|
|
398
|
+
export type All<TRules extends readonly unknown[]> = Access<"All", {
|
|
399
|
+
readonly kind: "All";
|
|
400
|
+
readonly rules: TRules;
|
|
401
|
+
}>;
|
|
402
|
+
/** Negation. `Not<Role<"banned">>` grants access to everyone but that role. */
|
|
403
|
+
export type Not<TRule> = Access<"Not", {
|
|
404
|
+
readonly kind: "Not";
|
|
405
|
+
readonly rule: TRule;
|
|
406
|
+
}>;
|
|
407
|
+
/** The signed-in user's id. Compiles to `auth.uid()`, evaluated once per query. */
|
|
408
|
+
export type AuthUid = Access<"AuthUid", {
|
|
409
|
+
readonly kind: "AuthUid";
|
|
410
|
+
}>;
|
|
411
|
+
/** The caller's role. Compiles to `auth.role()`, evaluated once per query. */
|
|
412
|
+
export type AuthRole = Access<"AuthRole", {
|
|
413
|
+
readonly kind: "AuthRole";
|
|
414
|
+
}>;
|
|
415
|
+
/**
|
|
416
|
+
* A nested JWT claim, by dotted path: `Claim<"app_metadata.tier">`.
|
|
417
|
+
*
|
|
418
|
+
* This is the developer's own namespace — whatever your application puts in its
|
|
419
|
+
* tokens. A missing claim is SQL NULL, so comparing against one that is absent
|
|
420
|
+
* denies rather than erroring.
|
|
421
|
+
*/
|
|
422
|
+
export type Claim<TPath extends string> = Access<"Claim", {
|
|
423
|
+
readonly kind: "Claim";
|
|
424
|
+
readonly path: TPath;
|
|
425
|
+
}>;
|
|
426
|
+
/** A constant. Bare strings in a comparison mean *columns*, so literals are explicit. */
|
|
427
|
+
export type Literal<TValue extends string | number | boolean> = Access<"Literal", {
|
|
428
|
+
readonly kind: "Literal";
|
|
429
|
+
readonly value: TValue;
|
|
430
|
+
}>;
|
|
431
|
+
/** Transaction start time (`now()`). */
|
|
432
|
+
export type Now = Access<"Now", {
|
|
433
|
+
readonly kind: "Now";
|
|
434
|
+
}>;
|
|
435
|
+
/** Units for {@link Ago} / {@link FromNow}. Plural only — Postgres accepts both. */
|
|
436
|
+
export type TimeUnit = "seconds" | "minutes" | "hours" | "days" | "weeks" | "months" | "years";
|
|
437
|
+
/** Granularity for {@link StartOf}. */
|
|
438
|
+
export type TruncUnit = "day" | "week" | "month" | "year";
|
|
439
|
+
/**
|
|
440
|
+
* The start of the current day, week, month or year — `date_trunc(unit, now())`.
|
|
441
|
+
*
|
|
442
|
+
* `Gte<"created_at", StartOf<"week">>` is "created since Monday".
|
|
443
|
+
*/
|
|
444
|
+
export type StartOf<TUnit extends TruncUnit> = Access<"StartOf", {
|
|
445
|
+
readonly kind: "StartOf";
|
|
446
|
+
readonly unit: TUnit;
|
|
447
|
+
}>;
|
|
448
|
+
/**
|
|
449
|
+
* A duration before now: `Ago<30, "days">` is `now() - INTERVAL '30 days'`.
|
|
450
|
+
*
|
|
451
|
+
* Two arguments rather than one `"30 days"` string, for two reasons. A template
|
|
452
|
+
* literal `` `${number} ${TimeUnit}` `` accepts `"-5 days"`, `"0.5 days"` and
|
|
453
|
+
* `"1e3 days"` — the last is not valid interval syntax, so it type-checks and fails
|
|
454
|
+
* at push. And TypeScript cannot enumerate `${number}`, so a template literal offers
|
|
455
|
+
* **no autocomplete**; this form completes the unit properly.
|
|
456
|
+
*
|
|
457
|
+
* The amount must be a positive integer — for the other direction use
|
|
458
|
+
* {@link FromNow}, which reads correctly rather than relying on a double negative.
|
|
459
|
+
*/
|
|
460
|
+
export type Ago<TAmount extends number, TUnit extends TimeUnit> = Access<"Ago", {
|
|
461
|
+
readonly kind: "Ago";
|
|
462
|
+
readonly amount: TAmount;
|
|
463
|
+
readonly unit: TUnit;
|
|
464
|
+
}>;
|
|
465
|
+
/** A duration after now: `FromNow<7, "days">` is `now() + INTERVAL '7 days'`. */
|
|
466
|
+
export type FromNow<TAmount extends number, TUnit extends TimeUnit> = Access<"FromNow", {
|
|
467
|
+
readonly kind: "FromNow";
|
|
468
|
+
readonly amount: TAmount;
|
|
469
|
+
readonly unit: TUnit;
|
|
470
|
+
}>;
|
|
471
|
+
type Comparison<TName extends string, TLeft, TRight> = Access<TName, {
|
|
472
|
+
readonly kind: TName;
|
|
473
|
+
readonly left: TLeft;
|
|
474
|
+
readonly right: TRight;
|
|
475
|
+
}>;
|
|
476
|
+
/**
|
|
477
|
+
* `Eq<"author_id", AuthUid>` — the row's `author_id` equals the caller.
|
|
478
|
+
*
|
|
479
|
+
* A bare string on either side is a column name; use `Literal<…>` for a constant,
|
|
480
|
+
* so `Eq<"status", Literal<"published">>` cannot be confused with a comparison
|
|
481
|
+
* between two columns.
|
|
482
|
+
*/
|
|
483
|
+
export type Eq<TLeft, TRight> = Comparison<"Eq", TLeft, TRight>;
|
|
484
|
+
export type Neq<TLeft, TRight> = Comparison<"Neq", TLeft, TRight>;
|
|
485
|
+
export type Gt<TLeft, TRight> = Comparison<"Gt", TLeft, TRight>;
|
|
486
|
+
export type Gte<TLeft, TRight> = Comparison<"Gte", TLeft, TRight>;
|
|
487
|
+
export type Lt<TLeft, TRight> = Comparison<"Lt", TLeft, TRight>;
|
|
488
|
+
export type Lte<TLeft, TRight> = Comparison<"Lte", TLeft, TRight>;
|
|
489
|
+
export type Like<TLeft, TRight> = Comparison<"Like", TLeft, TRight>;
|
|
490
|
+
/**
|
|
491
|
+
* `IsNull<"deleted_at">` / `NotNull<"published_at">`.
|
|
492
|
+
*
|
|
493
|
+
* Separate from `Eq`, because SQL null comparison is not equality: `col = NULL`
|
|
494
|
+
* is null, never true, so writing it that way would deny everything silently.
|
|
495
|
+
*/
|
|
496
|
+
export type IsNull<TOperand> = Access<"IsNull", {
|
|
497
|
+
readonly kind: "IsNull";
|
|
498
|
+
readonly operand: TOperand;
|
|
499
|
+
}>;
|
|
500
|
+
export type NotNull<TOperand> = Access<"NotNull", {
|
|
501
|
+
readonly kind: "NotNull";
|
|
502
|
+
readonly operand: TOperand;
|
|
503
|
+
}>;
|
|
504
|
+
/**
|
|
505
|
+
* Rows of another table, narrowed by a rule: the source for a membership test.
|
|
506
|
+
*
|
|
507
|
+
* ```typescript
|
|
508
|
+
* type MySites = Rows<"user_sites", "site_id", Eq<"user_id", AuthUid>>
|
|
509
|
+
* ```
|
|
510
|
+
*
|
|
511
|
+
* The `Where` rule is evaluated against `user_sites`, not against the model the
|
|
512
|
+
* access rule is attached to — it is what makes this *the caller's* sites rather
|
|
513
|
+
* than every row in the join table.
|
|
514
|
+
*
|
|
515
|
+
* Because the join column is named here, the engine emits the index for it. The
|
|
516
|
+
* classic RLS performance trap is a membership subquery scanning an unindexed join
|
|
517
|
+
* table once per row tested; naming it makes that generated infrastructure.
|
|
518
|
+
*/
|
|
519
|
+
export type Rows<TTable extends string, TColumn extends string, TWhere = never> = Access<"Rows", {
|
|
520
|
+
readonly kind: "Rows";
|
|
521
|
+
readonly table: TTable;
|
|
522
|
+
readonly column: TColumn;
|
|
523
|
+
readonly where: TWhere;
|
|
524
|
+
}>;
|
|
525
|
+
/** A fixed set, for `In<"status", Values<["draft", "review"]>>`. */
|
|
526
|
+
export type Values<TItems extends readonly (string | number | boolean)[]> = Access<"Values", {
|
|
527
|
+
readonly kind: "Values";
|
|
528
|
+
readonly values: TItems;
|
|
529
|
+
}>;
|
|
530
|
+
/**
|
|
531
|
+
* `In<"site_id", MySites>` — the row's column appears in the source set.
|
|
532
|
+
*
|
|
533
|
+
* Compiles to a semi-join (`EXISTS`), not `IN (SELECT …)`, so the planner stops at
|
|
534
|
+
* the first match per row instead of materialising the set. Sources are `Rows<>`,
|
|
535
|
+
* `Claim<>` (a claim holding an array) or `Values<>`.
|
|
536
|
+
*/
|
|
537
|
+
export type In<TColumn extends string, TSource> = Access<"In", {
|
|
538
|
+
readonly kind: "In";
|
|
539
|
+
readonly column: TColumn;
|
|
540
|
+
readonly source: TSource;
|
|
541
|
+
}>;
|
|
542
|
+
/**
|
|
543
|
+
* The source set is non-empty, independent of any column.
|
|
544
|
+
*
|
|
545
|
+
* `In<>` asks "is this row's value in the set", which is a different question.
|
|
546
|
+
* Guarding on `Exists<>` is what makes "an editor *who has sites* may see their
|
|
547
|
+
* sites or unassigned rows" mean what it says — without it, an editor with no sites
|
|
548
|
+
* still matches the unassigned branch:
|
|
549
|
+
*
|
|
550
|
+
* ```typescript
|
|
551
|
+
* type MySites = Rows<"user_sites", "site_id", Eq<"user_id", AuthUid>>
|
|
552
|
+
* All<[Role<"editor">, Exists<MySites>, Any<[In<"site_id", MySites>, IsNull<"site_id">]>]>
|
|
553
|
+
* ```
|
|
554
|
+
*/
|
|
555
|
+
export type Exists<TSource> = Access<"Exists", {
|
|
556
|
+
readonly kind: "Exists";
|
|
557
|
+
readonly source: TSource;
|
|
558
|
+
}>;
|
|
308
559
|
type BoundOwnerForFields<TFields extends Record<string, unknown>> = Access<"Owner", {
|
|
309
560
|
readonly kind: "Owner";
|
|
310
561
|
readonly key: OwnerEligibleFieldKeys<TFields>;
|
|
@@ -314,31 +565,90 @@ type BoundOwnerFromForFields<TFields extends Record<string, unknown>> = Access<"
|
|
|
314
565
|
readonly kind: "OwnerFrom";
|
|
315
566
|
readonly relation: RelationFieldKeys<TFields>;
|
|
316
567
|
}>;
|
|
317
|
-
/**
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
568
|
+
/**
|
|
569
|
+
* The composable half of the DSL — every shape that takes other rules or operands
|
|
570
|
+
* as arguments.
|
|
571
|
+
*
|
|
572
|
+
* Written with `unknown` arguments rather than a recursive constraint. TypeScript
|
|
573
|
+
* cannot thread the model's field names down through a tuple of nested rules
|
|
574
|
+
* without instantiation-depth failures on the deeper compositions, so a column
|
|
575
|
+
* named inside a composition is checked by Postgres when the policy is created,
|
|
576
|
+
* not by the editor. The named shapes below stay bound to the model's fields, so
|
|
577
|
+
* the common `Owner<…>` typo is still caught where it always was.
|
|
578
|
+
*/
|
|
579
|
+
type ComposedAccessRule = Any<readonly unknown[]> | All<readonly unknown[]> | Not<unknown> | Eq<unknown, unknown> | Neq<unknown, unknown> | Gt<unknown, unknown> | Gte<unknown, unknown> | Lt<unknown, unknown> | Lte<unknown, unknown> | Like<unknown, unknown> | IsNull<unknown> | NotNull<unknown> | In<string, unknown> | Exists<unknown>;
|
|
580
|
+
/**
|
|
581
|
+
* Any rule that may stand as an access predicate for a model.
|
|
582
|
+
*
|
|
583
|
+
* The named shapes stay bound to `TFields` so `Owner<"athor_id">` is still a typo
|
|
584
|
+
* the editor catches; the composed shapes are open, per the note above.
|
|
585
|
+
*/
|
|
586
|
+
export type AccessRuleFor<TFields extends Record<string, unknown>> = Public | Private | LoggedIn | Owner<OwnerEligibleFieldKeys<TFields>> | OwnerFrom<RelationFieldKeys<TFields>> | BoundOwnerForFields<TFields> | BoundOwnerFromForFields<TFields> | Role<string> | ComposedAccessRule;
|
|
587
|
+
/**
|
|
588
|
+
* `update` as a plain rule, or split into its two halves.
|
|
589
|
+
*
|
|
590
|
+
* `using` picks which existing rows may be modified, `check` constrains what they
|
|
591
|
+
* may become. Unambiguous against a bare rule because every rule carries a `kind`
|
|
592
|
+
* and this object does not.
|
|
593
|
+
*/
|
|
594
|
+
type UpdateAccessFor<TFields extends Record<string, unknown>> = AccessRuleFor<TFields> | {
|
|
595
|
+
readonly using: AccessRuleFor<TFields>;
|
|
596
|
+
readonly check?: AccessRuleFor<TFields>;
|
|
597
|
+
};
|
|
598
|
+
/**
|
|
599
|
+
* Whether a field's key is optional on the row — `Optional` anywhere in the stack, not just outermost.
|
|
600
|
+
*
|
|
601
|
+
* `Unique<Optional<string>>` is as nullable as `Optional<Unique<string>>`. The old structural check
|
|
602
|
+
* could only see the outer wrapper, so which one you wrote decided whether the key was optional.
|
|
603
|
+
*/
|
|
604
|
+
type HasOptionalModifier<V> = V extends {
|
|
605
|
+
readonly __modifier: infer TName extends string;
|
|
606
|
+
readonly __inner: infer TInner;
|
|
607
|
+
} ? TName extends "Optional" ? true : HasOptionalModifier<TInner> : false;
|
|
324
608
|
type ImageAssetLocalizedOption<V> = V extends ImageAsset<infer _B, infer O> ? (O extends {
|
|
325
609
|
localized: true;
|
|
326
610
|
} ? true : false) : false;
|
|
327
611
|
type FileAssetLocalizedOption<V> = V extends FileAsset<infer _B, infer O> ? (O extends {
|
|
328
612
|
localized: true;
|
|
329
613
|
} ? true : false) : false;
|
|
330
|
-
/**
|
|
331
|
-
|
|
614
|
+
/**
|
|
615
|
+
* Apply default localization to copy-like fields (used by {@link LocalizedModel}).
|
|
616
|
+
*
|
|
617
|
+
* Walks *through* any modifier and rebuilds it around the localized inner, so `Unique<string>` becomes
|
|
618
|
+
* `Unique<Localized<string>>`. It used to reach the `V extends string` branch for such a field — a
|
|
619
|
+
* modifier was structurally its own inner type — and return a bare `Localized<string>`, silently
|
|
620
|
+
* dropping the `Unique`.
|
|
621
|
+
*/
|
|
622
|
+
type ApplyAutoLocalizedField<V> = V extends {
|
|
623
|
+
readonly __modifier: infer TName extends string;
|
|
624
|
+
readonly __inner: infer TInner;
|
|
625
|
+
} ? TName extends "NotLocalized" ? TInner : TName extends "Localized" ? V : {
|
|
626
|
+
readonly __modifier: TName;
|
|
627
|
+
readonly __inner: ApplyAutoLocalizedField<TInner>;
|
|
628
|
+
} : V extends string ? Localized<string> : V extends RichText ? Localized<RichText> : V extends Markdown ? Localized<Markdown> : V extends Button ? Localized<Button> : ImageAssetLocalizedOption<V> extends true ? Localized<V> : FileAssetLocalizedOption<V> extends true ? Localized<V> : V;
|
|
332
629
|
type ApplyAutoLocalizedFields<TFields extends Record<string, unknown>> = {
|
|
333
630
|
[K in keyof TFields]: ApplyAutoLocalizedField<TFields[K]>;
|
|
334
631
|
};
|
|
335
|
-
/**
|
|
336
|
-
|
|
632
|
+
/**
|
|
633
|
+
* The value a declared field reads as on the row: every modifier peeled off, whatever it is.
|
|
634
|
+
*
|
|
635
|
+
* Unbounded and still terminating, because each step removes one wrapper — `__inner` is strictly
|
|
636
|
+
* smaller than the type it came from. The previous version needed a depth cap to escape a recursion
|
|
637
|
+
* that could not converge, and a cap that runs out returns a half-unwrapped type rather than an error.
|
|
638
|
+
*
|
|
639
|
+
* Every modifier, not the three that used to be special-cased: a declaration is no longer structurally
|
|
640
|
+
* its own inner type, so `Unique<Slug>` would otherwise surface on the row as the wrapper object rather
|
|
641
|
+
* than as a string. `Localized<T>` needs no case of its own — its inner already *is* the locale record.
|
|
642
|
+
*/
|
|
643
|
+
type UnwrapModelFieldType<V> = V extends {
|
|
644
|
+
readonly __modifier: string;
|
|
645
|
+
readonly __inner: infer TInner;
|
|
646
|
+
} ? UnwrapModelFieldType<TInner> : V;
|
|
337
647
|
/** Row shape from `TFields`: `Optional<…>` → `key?: Inner` (`Inner` includes `null`). */
|
|
338
648
|
export type SpreadOptionalModelFields<TFields extends Record<string, unknown>> = keyof TFields extends never ? {} : {
|
|
339
|
-
[K in keyof TFields as
|
|
649
|
+
[K in keyof TFields as HasOptionalModifier<TFields[K]> extends true ? never : K]: UnwrapModelFieldType<TFields[K]>;
|
|
340
650
|
} & {
|
|
341
|
-
[K in keyof TFields as
|
|
651
|
+
[K in keyof TFields as HasOptionalModifier<TFields[K]> extends true ? K extends keyof TFields & (string | number) ? K : never : never]?: UnwrapModelFieldType<TFields[K]>;
|
|
342
652
|
};
|
|
343
653
|
export type ModelIndex = {
|
|
344
654
|
name?: string;
|
|
@@ -347,10 +657,58 @@ export type ModelIndex = {
|
|
|
347
657
|
};
|
|
348
658
|
export type ModelMeta<TFields extends Record<string, unknown>> = {
|
|
349
659
|
access?: {
|
|
350
|
-
read?:
|
|
351
|
-
create?:
|
|
352
|
-
update?:
|
|
353
|
-
delete?:
|
|
660
|
+
read?: AccessRuleFor<TFields>;
|
|
661
|
+
create?: AccessRuleFor<TFields>;
|
|
662
|
+
update?: UpdateAccessFor<TFields>;
|
|
663
|
+
delete?: AccessRuleFor<TFields>;
|
|
664
|
+
/**
|
|
665
|
+
* Per-column rules, narrowing the table rules for one field.
|
|
666
|
+
*
|
|
667
|
+
* ```typescript
|
|
668
|
+
* access: {
|
|
669
|
+
* read: Public,
|
|
670
|
+
* fields: { salary: { read: Owner<"user_id">, write: Role<"admin"> } },
|
|
671
|
+
* }
|
|
672
|
+
* ```
|
|
673
|
+
*
|
|
674
|
+
* The **full rule language** applies, row-dependent rules included. A caller who
|
|
675
|
+
* may not read the column gets `null` rather than a 403, because `SELECT *` names
|
|
676
|
+
* every column and a revoked one would take the whole table down with it. Column
|
|
677
|
+
* privileges are layered underneath for writes only, as defence in depth.
|
|
678
|
+
*
|
|
679
|
+
* Enforced one of two ways, chosen from what the database can do: the
|
|
680
|
+
* `supatype_mask` extension rewrites every reference to the column in the planner,
|
|
681
|
+
* and where the extension cannot be loaded — most managed Postgres — the same
|
|
682
|
+
* expression is carried by generated views in an `api` schema instead.
|
|
683
|
+
*
|
|
684
|
+
* A `write` rule is compiled conjoined with the field's `read` rule, so write
|
|
685
|
+
* without read is unrepresentable — otherwise a caller could round-trip away a
|
|
686
|
+
* value they were never shown.
|
|
687
|
+
*
|
|
688
|
+
* **`INSERT` cannot evaluate a row-dependent write rule**: there is no row
|
|
689
|
+
* yet, so the column falls back to its default instead of accepting the
|
|
690
|
+
* submitted value. Use an identity-only rule (`Role<>`, `LoggedIn`,
|
|
691
|
+
* `Claim<>`) for a column that must be settable at creation time.
|
|
692
|
+
*
|
|
693
|
+
* Relations are named by their column (`author_id`), because that is what the
|
|
694
|
+
* restriction applies to — `author` is not a column at all.
|
|
695
|
+
*
|
|
696
|
+
* Neither tier half-enforces: a push never applies a schema whose restrictions do
|
|
697
|
+
* not exist. They differ in one place — under the view tier an aggregate over a
|
|
698
|
+
* masked column returns the sum of the rows the caller may read, where the
|
|
699
|
+
* extension raises an error. Unreachable through the API, since PostgREST ships
|
|
700
|
+
* with aggregates disabled.
|
|
701
|
+
*
|
|
702
|
+
* A column restricted from nearly everyone and queried often is still better off
|
|
703
|
+
* in its own table — masking costs a predicate call per row and cannot use the
|
|
704
|
+
* column's index.
|
|
705
|
+
*/
|
|
706
|
+
fields?: {
|
|
707
|
+
readonly [K in (keyof TFields & string) | RelationOwnerKeys<TFields>]?: {
|
|
708
|
+
readonly read?: AccessRuleFor<TFields>;
|
|
709
|
+
readonly write?: AccessRuleFor<TFields>;
|
|
710
|
+
};
|
|
711
|
+
};
|
|
354
712
|
};
|
|
355
713
|
tableName?: string;
|
|
356
714
|
searchable?: readonly string[];
|
|
@@ -364,6 +722,54 @@ export type ModelMeta<TFields extends Record<string, unknown>> = {
|
|
|
364
722
|
softDelete?: boolean;
|
|
365
723
|
/** When true, copy-like fields default to localized (same as {@link LocalizedModel}). */
|
|
366
724
|
autoLocalize?: true;
|
|
725
|
+
/**
|
|
726
|
+
* Lifecycle hooks — an **edge function** run by the API at a write boundary.
|
|
727
|
+
*
|
|
728
|
+
* ```typescript
|
|
729
|
+
* hooks: {
|
|
730
|
+
* beforeChange: "moderate-post",
|
|
731
|
+
* afterChange: { function: "index-post", timeout: 5000 },
|
|
732
|
+
* }
|
|
733
|
+
* ```
|
|
734
|
+
*
|
|
735
|
+
* The value names a function directory under your project's `functions/`, and the name is
|
|
736
|
+
* checked when you push — a hook that silently never fires because of a typo is the failure
|
|
737
|
+
* this feature must not have. `supatype push` also generates a typed handler signature per
|
|
738
|
+
* hooked model, so `row` is the model's real column set rather than `unknown`.
|
|
739
|
+
*
|
|
740
|
+
* **A hook is not a security boundary.** It fires for writes through the API; direct SQL,
|
|
741
|
+
* seeds, migrations and anything holding `service_role` bypass it. Invariants belong in
|
|
742
|
+
* {@link ModelMeta.access}, a `CHECK`, or a generated column — all of which apply to every
|
|
743
|
+
* writer. A hook is for the work that is genuinely application logic: enrichment,
|
|
744
|
+
* notification, indexing, a validation the database cannot express.
|
|
745
|
+
*
|
|
746
|
+
* `beforeChange` and `beforeDelete` are called before the write reaches Postgres and can
|
|
747
|
+
* reject it (any `4xx` from the function) or replace its body. `afterChange` and
|
|
748
|
+
* `afterDelete` run once the write has succeeded and cannot change it.
|
|
749
|
+
*/
|
|
750
|
+
hooks?: {
|
|
751
|
+
readonly beforeChange?: ModelHook;
|
|
752
|
+
readonly afterChange?: ModelHook;
|
|
753
|
+
readonly beforeDelete?: ModelHook;
|
|
754
|
+
readonly afterDelete?: ModelHook;
|
|
755
|
+
};
|
|
756
|
+
};
|
|
757
|
+
/** A hook: a function name, or that name with per-hook options. */
|
|
758
|
+
export type ModelHook = string | ModelHookOptions;
|
|
759
|
+
export type ModelHookOptions = {
|
|
760
|
+
/** Function directory under the project's `functions/`. */
|
|
761
|
+
readonly function: string;
|
|
762
|
+
/** Milliseconds before the hook is abandoned. Default 2000. */
|
|
763
|
+
readonly timeout?: number;
|
|
764
|
+
/**
|
|
765
|
+
* What it means when the hook **does not answer** — a timeout, a connection failure, a `5xx`,
|
|
766
|
+
* or a body that cannot be parsed. A `4xx` is not this: that is the hook working correctly and
|
|
767
|
+
* saying no, and it reaches the caller as the status the hook chose.
|
|
768
|
+
*
|
|
769
|
+
* Defaults to `"reject"` before a write (a validation hook that stopped running must not let
|
|
770
|
+
* writes through) and `"log"` after one (the write already happened; there is nothing to fail).
|
|
771
|
+
*/
|
|
772
|
+
readonly onUnavailable?: "reject" | "log";
|
|
367
773
|
};
|
|
368
774
|
/** Shorthand for singleton globals — `Model<Fields, GlobalMeta<Fields>>`. */
|
|
369
775
|
export type GlobalMeta<TFields extends Record<string, unknown>> = ModelMeta<TFields> & {
|