@supatype/types 0.3.6 → 0.8.0

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/dist/lexical.d.ts CHANGED
@@ -1,3 +1,9 @@
1
+ /**
2
+ * Lexical's serialized JSON: what a `RichText` column stores and what the editor in Studio and
3
+ * `@supatype/ui` saves. `SerializedLexicalNode` is the loose shape every node shares; the specific
4
+ * interfaces below describe the fields Lexical 0.43 writes for each node type those editors can
5
+ * produce, so renderers and readers work from one definition.
6
+ */
1
7
  export interface SerializedLexicalNode {
2
8
  type: string;
3
9
  version: number;
@@ -7,4 +13,56 @@ export interface SerializedLexicalNode {
7
13
  export interface SerializedEditorState {
8
14
  root: SerializedLexicalNode;
9
15
  }
16
+ /** Block alignment, stored in an element node's `format` (empty when unset). */
17
+ export type ElementFormat = "" | "left" | "start" | "center" | "right" | "end" | "justify";
18
+ /** Fields every element node (root, paragraph, heading, quote, list, listitem, link, code) carries. */
19
+ export interface SerializedElementNode extends SerializedLexicalNode {
20
+ children: SerializedLexicalNode[];
21
+ direction: "ltr" | "rtl" | null;
22
+ format: ElementFormat;
23
+ indent: number;
24
+ }
25
+ /**
26
+ * A run of text. `format` is a bit set: bold 1, italic 2, strikethrough 4, underline 8, code 16,
27
+ * subscript 32, superscript 64, highlight 128, lowercase 256, uppercase 512, capitalize 1024.
28
+ * `tab` and `code-highlight` nodes are text nodes under their own type.
29
+ */
30
+ export interface SerializedTextNode extends SerializedLexicalNode {
31
+ type: "text" | "tab" | "code-highlight";
32
+ text: string;
33
+ format: number;
34
+ detail: number;
35
+ mode: "normal" | "token" | "segmented";
36
+ style: string;
37
+ highlightType?: string | null;
38
+ }
39
+ export interface SerializedHeadingNode extends SerializedElementNode {
40
+ type: "heading";
41
+ tag: "h1" | "h2" | "h3" | "h4" | "h5" | "h6";
42
+ }
43
+ export interface SerializedListNode extends SerializedElementNode {
44
+ type: "list";
45
+ listType: "bullet" | "number" | "check";
46
+ start: number;
47
+ tag: "ul" | "ol";
48
+ }
49
+ /** A list entry. A nested list is a `listitem` whose only child is a `list`. */
50
+ export interface SerializedListItemNode extends SerializedElementNode {
51
+ type: "listitem";
52
+ value: number;
53
+ checked?: boolean;
54
+ }
55
+ /** `link` is set by an editor; `autolink` is detected from typed text and can be unlinked. */
56
+ export interface SerializedLinkNode extends SerializedElementNode {
57
+ type: "link" | "autolink";
58
+ url: string;
59
+ rel: string | null;
60
+ target: string | null;
61
+ title: string | null;
62
+ isUnlinked?: boolean;
63
+ }
64
+ export interface SerializedCodeNode extends SerializedElementNode {
65
+ type: "code";
66
+ language?: string | null;
67
+ }
10
68
  //# sourceMappingURL=lexical.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"lexical.d.ts","sourceRoot":"","sources":["../src/lexical.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAA;IACZ,OAAO,EAAE,MAAM,CAAA;IACf,QAAQ,CAAC,EAAE,qBAAqB,EAAE,CAAA;IAClC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CACvB;AAED,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,qBAAqB,CAAA;CAC5B"}
1
+ {"version":3,"file":"lexical.d.ts","sourceRoot":"","sources":["../src/lexical.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAA;IACZ,OAAO,EAAE,MAAM,CAAA;IACf,QAAQ,CAAC,EAAE,qBAAqB,EAAE,CAAA;IAClC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CACvB;AAED,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,qBAAqB,CAAA;CAC5B;AAED,gFAAgF;AAChF,MAAM,MAAM,aAAa,GAAG,EAAE,GAAG,MAAM,GAAG,OAAO,GAAG,QAAQ,GAAG,OAAO,GAAG,KAAK,GAAG,SAAS,CAAA;AAE1F,uGAAuG;AACvG,MAAM,WAAW,qBAAsB,SAAQ,qBAAqB;IAClE,QAAQ,EAAE,qBAAqB,EAAE,CAAA;IACjC,SAAS,EAAE,KAAK,GAAG,KAAK,GAAG,IAAI,CAAA;IAC/B,MAAM,EAAE,aAAa,CAAA;IACrB,MAAM,EAAE,MAAM,CAAA;CACf;AAED;;;;GAIG;AACH,MAAM,WAAW,kBAAmB,SAAQ,qBAAqB;IAC/D,IAAI,EAAE,MAAM,GAAG,KAAK,GAAG,gBAAgB,CAAA;IACvC,IAAI,EAAE,MAAM,CAAA;IACZ,MAAM,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,MAAM,CAAA;IACd,IAAI,EAAE,QAAQ,GAAG,OAAO,GAAG,WAAW,CAAA;IACtC,KAAK,EAAE,MAAM,CAAA;IACb,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAC9B;AAED,MAAM,WAAW,qBAAsB,SAAQ,qBAAqB;IAClE,IAAI,EAAE,SAAS,CAAA;IACf,GAAG,EAAE,IAAI,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,CAAA;CAC7C;AAED,MAAM,WAAW,kBAAmB,SAAQ,qBAAqB;IAC/D,IAAI,EAAE,MAAM,CAAA;IACZ,QAAQ,EAAE,QAAQ,GAAG,QAAQ,GAAG,OAAO,CAAA;IACvC,KAAK,EAAE,MAAM,CAAA;IACb,GAAG,EAAE,IAAI,GAAG,IAAI,CAAA;CACjB;AAED,gFAAgF;AAChF,MAAM,WAAW,sBAAuB,SAAQ,qBAAqB;IACnE,IAAI,EAAE,UAAU,CAAA;IAChB,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,CAAC,EAAE,OAAO,CAAA;CAClB;AAED,8FAA8F;AAC9F,MAAM,WAAW,kBAAmB,SAAQ,qBAAqB;IAC/D,IAAI,EAAE,MAAM,GAAG,UAAU,CAAA;IACzB,GAAG,EAAE,MAAM,CAAA;IACX,GAAG,EAAE,MAAM,GAAG,IAAI,CAAA;IAClB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;IACrB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,UAAU,CAAC,EAAE,OAAO,CAAA;CACrB;AAED,MAAM,WAAW,kBAAmB,SAAQ,qBAAqB;IAC/D,IAAI,EAAE,MAAM,CAAA;IACZ,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CACzB"}
package/dist/lexical.js CHANGED
@@ -1,2 +1,8 @@
1
+ /**
2
+ * Lexical's serialized JSON: what a `RichText` column stores and what the editor in Studio and
3
+ * `@supatype/ui` saves. `SerializedLexicalNode` is the loose shape every node shares; the specific
4
+ * interfaces below describe the fields Lexical 0.43 writes for each node type those editors can
5
+ * produce, so renderers and readers work from one definition.
6
+ */
1
7
  export {};
2
8
  //# sourceMappingURL=lexical.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"lexical.js","sourceRoot":"","sources":["../src/lexical.ts"],"names":[],"mappings":""}
1
+ {"version":3,"file":"lexical.js","sourceRoot":"","sources":["../src/lexical.ts"],"names":[],"mappings":"AAAA;;;;;GAKG"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supatype/types",
3
- "version": "0.3.6",
3
+ "version": "0.8.0",
4
4
  "license": "MIT",
5
5
  "description": "Pure type primitives for Supatype RFC v2",
6
6
  "type": "module",
@@ -26,7 +26,7 @@
26
26
  "scripts": {
27
27
  "build": "tsc --project tsconfig.json",
28
28
  "dev": "tsc --project tsconfig.json --watch",
29
- "typecheck": "tsc --project tsconfig.json --noEmit && tsc --project tsconfig.test.json",
29
+ "typecheck": "tsc --project tests/tsconfig.json --noEmit",
30
30
  "test": "vitest run",
31
31
  "clean": "rm -rf dist *.tsbuildinfo"
32
32
  }
package/src/index.ts CHANGED
@@ -42,38 +42,80 @@ type Modifier<TName extends string, TInner> = {
42
42
  readonly __inner: TInner
43
43
  }
44
44
  type Relation<TName extends string, TInner> = Tagged<TInner, `relation:${TName}`>
45
+
46
+ /** How an identity column takes values: `always` refuses an explicit one, `by-default` accepts one. */
47
+ export type IdentityMode = "always" | "by-default"
48
+ /**
49
+ * Options every scalar field type takes as its last type argument.
50
+ *
51
+ * `generated` makes it a stored generated column: `GENERATED ALWAYS AS (expression) STORED`, the SQL
52
+ * written over the row's columns by their column names. The database computes it on every write and
53
+ * refuses to have it written, so the generated client types leave it out of inserts and updates.
54
+ *
55
+ * ```typescript
56
+ * total: Float<{ generated: "price * quantity" }>
57
+ * search: TSVector<{ generated: "to_tsvector('english', coalesce(title, ''))" }>
58
+ * ```
59
+ */
60
+ export interface ScalarFieldOptions {
61
+ generated?: string
62
+ }
63
+ /**
64
+ * {@link ScalarFieldOptions}, and for an integer field `identity`: `GENERATED ALWAYS AS IDENTITY`
65
+ * (`"always"`) or `GENERATED BY DEFAULT AS IDENTITY` (`"by-default"`). The database numbers the
66
+ * column from a sequence it owns; an insert leaves it out (and with `"always"` cannot give one).
67
+ *
68
+ * ```typescript
69
+ * id: PrimaryKey<Int<{ identity: "always" }>>
70
+ * ```
71
+ */
72
+ export interface IntegerFieldOptions extends ScalarFieldOptions {
73
+ identity?: IdentityMode
74
+ }
75
+ /**
76
+ * The options a field type was declared with, carried at the type level only. Optional, like
77
+ * {@link Tagged}'s label, so a plain value is still assignable to the field's type; the CLI reads the
78
+ * options from the declaration's syntax.
79
+ */
80
+ type FieldOptions<TOptions> = { readonly __fieldOptions?: TOptions }
45
81
  type Access<TName extends string, TShape = { readonly kind: TName }> = Tagged<TShape, `access:${TName}`>
46
82
 
47
- export type UUID = Primitive<"UUID", string>
48
- export type Email = Primitive<"Email", string>
49
- export type URL = Primitive<"URL", string>
83
+ export type UUID<O extends ScalarFieldOptions = {}> = Primitive<"UUID", string> & FieldOptions<O>
84
+ export type Email<O extends ScalarFieldOptions = {}> = Primitive<"Email", string> & FieldOptions<O>
85
+ export type URL<O extends ScalarFieldOptions = {}> = Primitive<"URL", string> & FieldOptions<O>
50
86
  /**
51
87
  * URL-safe slug stored as text. Optional type argument names the source field used
52
88
  * for auto-generation (DB trigger + Studio). Defaults to `"title"`.
53
89
  */
54
90
  export type Slug<TSource extends string = "title"> = Primitive<`Slug:${TSource}`, string>
55
- export type PhoneNumber = Primitive<"PhoneNumber", string>
56
- export type Markdown = Primitive<"Markdown", string>
57
- export type Color = Primitive<"Color", string>
58
- export type Int = Primitive<"Int", number>
59
- export type SmallInt = Primitive<"SmallInt", number>
60
- export type BigInt = Primitive<"BigInt", bigint>
61
- export type Float = Primitive<"Float", number>
91
+ export type PhoneNumber<O extends ScalarFieldOptions = {}> = Primitive<"PhoneNumber", string> & FieldOptions<O>
92
+ export type Markdown<O extends ScalarFieldOptions = {}> = Primitive<"Markdown", string> & FieldOptions<O>
93
+ export type Color<O extends ScalarFieldOptions = {}> = Primitive<"Color", string> & FieldOptions<O>
94
+ export type Int<O extends IntegerFieldOptions = {}> = Primitive<"Int", number> & FieldOptions<O>
95
+ export type SmallInt<O extends IntegerFieldOptions = {}> = Primitive<"SmallInt", number> & FieldOptions<O>
96
+ export type BigInt<O extends IntegerFieldOptions = {}> = Primitive<"BigInt", bigint> & FieldOptions<O>
97
+ export type Float<O extends ScalarFieldOptions = {}> = Primitive<"Float", number> & FieldOptions<O>
62
98
  export type Decimal<P extends number, S extends number> = Primitive<`Decimal:${P}:${S}`, string>
63
- export type Money = Primitive<"Money", string>
99
+ export type Money<O extends ScalarFieldOptions = {}> = Primitive<"Money", string> & FieldOptions<O>
64
100
  export type Vector<N extends number> = Primitive<`Vector:${N}`, number[]>
65
101
  export type JSON<T> = Primitive<"JSON", T>
66
- export type IPAddress = Primitive<"IPAddress", string>
67
- export type CIDR = Primitive<"CIDR", string>
68
- export type MacAddress = Primitive<"MacAddress", string>
69
- export type Bytea = Primitive<"Bytea", string>
70
- export type XML = Primitive<"XML", string>
71
- export type TSQuery = Primitive<"TSQuery", string>
72
- export type TSVector = Primitive<"TSVector", string>
73
- export type DateOnly = Primitive<"DateOnly", Date>
74
- export type DateTime = Primitive<"DateTime", Date>
75
- export type Timestamp = Primitive<"Timestamp", Date>
76
- export type Geo = Primitive<"Geo", { type: "point" | "polygon" | "linestring"; coordinates: unknown }>
102
+ export type IPAddress<O extends ScalarFieldOptions = {}> = Primitive<"IPAddress", string> & FieldOptions<O>
103
+ export type CIDR<O extends ScalarFieldOptions = {}> = Primitive<"CIDR", string> & FieldOptions<O>
104
+ export type MacAddress<O extends ScalarFieldOptions = {}> = Primitive<"MacAddress", string> & FieldOptions<O>
105
+ export type Bytea<O extends ScalarFieldOptions = {}> = Primitive<"Bytea", string> & FieldOptions<O>
106
+ export type XML<O extends ScalarFieldOptions = {}> = Primitive<"XML", string> & FieldOptions<O>
107
+ export type TSQuery<O extends ScalarFieldOptions = {}> = Primitive<"TSQuery", string> & FieldOptions<O>
108
+ export type TSVector<O extends ScalarFieldOptions = {}> = Primitive<"TSVector", string> & FieldOptions<O>
109
+ export type DateOnly<O extends ScalarFieldOptions = {}> = Primitive<"DateOnly", Date> & FieldOptions<O>
110
+ export type DateTime<O extends ScalarFieldOptions = {}> = Primitive<"DateTime", Date> & FieldOptions<O>
111
+ export type Timestamp<O extends ScalarFieldOptions = {}> = Primitive<"Timestamp", Date> & FieldOptions<O>
112
+ /** A geography shape. */
113
+ export type GeoShape = "point" | "polygon" | "linestring"
114
+ /**
115
+ * A PostGIS `GEOGRAPHY(<shape>, 4326)` column. A bare `Geo` is a point; `Geo<"polygon">` and
116
+ * `Geo<"linestring">` declare the other shapes.
117
+ */
118
+ export type Geo<S extends GeoShape = "point"> = Primitive<"Geo", { type: S; coordinates: unknown }>
77
119
 
78
120
  /** Source text with the language it is written in. Stored as `JSONB`. */
79
121
  export type Code<Lang extends string = string> = Primitive<"Code", { lang: Lang; source: string }>
@@ -111,7 +153,7 @@ export type Button = Primitive<"Button", ButtonValue>
111
153
  * - Lexical document: pass a JSON string literal or use `Default<RichText, '{"root":…}'>`
112
154
  */
113
155
  export type RichText<D extends string = never> = Primitive<
114
- D extends never ? "RichText" : `RichText:${D}`,
156
+ [D] extends [never] ? "RichText" : `RichText:${D}`,
115
157
  SerializedEditorState | string
116
158
  >
117
159
 
@@ -208,11 +250,17 @@ export type LocaleConfig<
208
250
  export type Localized<T> = Modifier<"Localized", Record<string, T>>
209
251
  /** Opt out of {@link LocalizedModel} auto-localization for a copy-like field. */
210
252
  export type NotLocalized<T> = Modifier<"NotLocalized", T>
253
+ /**
254
+ * One kind of entry in a {@link Blocks} field: `TName` is stored under `type` and the fields under
255
+ * `data`, `{ "type": "hero", "data": { "heading": { "en": "Hi" } } }`, which is what Studio's block
256
+ * editor writes. The fields read as a model's row does, so `Localized<string>` is the locale map and
257
+ * `Optional<T>` may be absent or null.
258
+ */
211
259
  export type Block<
212
260
  TName extends string = string,
213
261
  TFields extends Record<string, unknown> = Record<string, unknown>,
214
262
  TMeta extends { label?: string; icon?: string } = {},
215
- > = Primitive<`Block:${TName}`, { type: TName; meta?: TMeta } & TFields>
263
+ > = Primitive<`Block:${TName}`, { type: TName; data: SpreadOptionalModelFields<TFields>; meta?: TMeta }>
216
264
  export type Blocks<TBlock extends Block = Block> = Primitive<"Blocks", TBlock[]>
217
265
 
218
266
  /**
@@ -253,7 +301,28 @@ export type ComputedFrom<
253
301
  TSources extends string | readonly string[] = "title",
254
302
  > = Modifier<"ComputedFrom", TValue>
255
303
  export type PrimaryKey<T> = Modifier<"PrimaryKey", T>
256
- export type AutoIncrement<T extends number | bigint> = Modifier<"AutoIncrement", T>
304
+ /**
305
+ * An identity column: `Identity<number>` is `Int<{ identity: "always" }>`, `Identity<bigint,
306
+ * "by-default">` is `BigInt<{ identity: "by-default" }>`. `Identity<SmallInt>` declares a `SMALLINT`
307
+ * one (at the type level every integer field is a number, so it reads as `Int`).
308
+ */
309
+ export type Identity<
310
+ T extends number | bigint = number,
311
+ M extends IdentityMode = "always",
312
+ > = T extends bigint ? BigInt<{ identity: M }> : Int<{ identity: M }>
313
+ /**
314
+ * A stored generated column of type `T`: `Generated<string, "lower(name)">` is a text column the
315
+ * database computes as `lower(name)`. The same as `T`'s `{ generated }` option, for the types (such as
316
+ * `string`) that take none.
317
+ */
318
+ export type Generated<T, TExpression extends string> = T & FieldOptions<{ generated: TExpression }>
319
+ /**
320
+ * A column the database numbers, which an insert may also give: an identity column generated by
321
+ * default, `Identity<T, "by-default">`. It compiled to `SERIAL` before, and a serial column pushed
322
+ * then satisfies it: every push leaves it exactly as it is. An explicit {@link Identity} on such a
323
+ * column converts it to an identity column.
324
+ */
325
+ export type AutoIncrement<T extends number | bigint = number> = Identity<T, "by-default">
257
326
  /**
258
327
  * Column value is assigned by the database (trigger, `DEFAULT`, sequence, etc.).
259
328
  * Inserts may omit this field; generated client `Insert` types mark it optional.
@@ -411,34 +480,89 @@ export type Public = Access<"Public">
411
480
  export type Private = Access<"Private">
412
481
  export type LoggedIn = Access<"LoggedIn">
413
482
  export type SupatypeAuthUser = Primitive<"SupatypeAuthUser", { readonly system: "supatype:user" }>
414
- export type SupatypeAuthUserId = Primitive<"SupatypeAuthUserId", string>
483
+ /**
484
+ * What deleting a user does to the rows whose {@link SupatypeAuthUserId} field names them.
485
+ *
486
+ * - `"cascade"`: the rows are deleted with the user. Everything the user wrote goes, including
487
+ * content other people rely on, such as their comments in someone else's thread.
488
+ * - `"restrict"`: the user cannot be deleted while they still own a row. Deleting them in Studio is
489
+ * refused until their rows are deleted or handed to someone else.
490
+ * - `"setNull"`: the rows stay and the field becomes NULL, so only an `Optional` field takes it.
491
+ * Under owner rules (`Owner<"user_id">`) a row with no owner matches nobody, so nobody but the
492
+ * service role can edit or delete it afterwards.
493
+ */
494
+ export type AuthUserOnDelete = "cascade" | "restrict" | "setNull"
495
+ /** The options of {@link SupatypeAuthUserId}. */
496
+ export interface AuthUserIdOptions {
497
+ /**
498
+ * Links the field to its user in `auth.users` with a foreign key, and says what deleting the user
499
+ * does to the row. Left out, the field holds a user id with no foreign key.
500
+ */
501
+ onDelete?: AuthUserOnDelete
502
+ }
503
+ /**
504
+ * A user's id from `auth.users`, for an owner column such as `Comment.user_id` or a profile's `id`.
505
+ *
506
+ * It has no foreign key by default: the column holds the id and nothing stops the user being
507
+ * deleted from under it, which is also what lets a project that brings its own auth, or keeps its
508
+ * schema apart from `auth`, use it. A field opts in to a key per field with `onDelete`
509
+ * ({@link AuthUserOnDelete}):
510
+ *
511
+ * ```typescript
512
+ * user_id: SupatypeAuthUserId<{ onDelete: "cascade" }>
513
+ * editor_id: Optional<SupatypeAuthUserId<{ onDelete: "setNull" }>>
514
+ * ```
515
+ *
516
+ * A push with the option needs `auth.users` to exist, and every row's id to name a user in it: it
517
+ * refuses otherwise, and says which rows to fix.
518
+ */
519
+ export type SupatypeAuthUserId<O extends AuthUserIdOptions & OnlyKeysOf<O, AuthUserIdOptions> = {}> =
520
+ Primitive<"SupatypeAuthUserId", string> & FieldOptions<O>
521
+ /** Every key of `T` that `TAllowed` does not have, typed `never`, so an options object takes no others. */
522
+ type OnlyKeysOf<T, TAllowed> = { readonly [K in Exclude<keyof T, keyof TAllowed>]: never }
415
523
  type ModelFieldKeys<TModel> =
416
524
  TModel extends { readonly [SUPATYPE_MODEL]?: { readonly fields: infer TFields } }
417
525
  ? Extract<keyof TFields, string>
418
526
  : never
419
527
  type RelationFieldKeys<TFields extends Record<string, unknown>> = Extract<{
420
528
  [K in keyof TFields]-?: K extends string
421
- ? TFields[K] extends { readonly __relationKind: "relatedTo" }
529
+ ? NonNullable<UnwrapModelFieldType<TFields[K]>> extends { readonly __relationKind: "relatedTo" }
422
530
  ? K
423
531
  : never
424
532
  : never
425
533
  }[keyof TFields], string>
426
534
  type RelationOwnerKeys<TFields extends Record<string, unknown>> = Extract<{
427
535
  [K in keyof TFields]-?: K extends string
428
- ? TFields[K] extends { readonly __relationKind: "relatedTo" }
536
+ ? NonNullable<UnwrapModelFieldType<TFields[K]>> extends { readonly __relationKind: "relatedTo" }
429
537
  ? `${K}_id`
430
538
  : never
431
539
  : never
432
540
  }[keyof TFields], string>
433
- type SelfOwnerKey<TFields extends Record<string, unknown>> =
434
- "id" extends keyof TFields
435
- ? TFields["id"] extends SupatypeAuthUserId
436
- ? "id"
437
- : never
541
+ /** The declared types a row can be owned through: a column that holds a user id. */
542
+ type OwnerColumnTag = "primitive:UUID" | "primitive:SupatypeAuthUserId"
543
+ /**
544
+ * True when a field is declared `UUID` or `SupatypeAuthUserId`.
545
+ *
546
+ * Read from the presence of the tag's key, not by assignability: the tag is optional, so a plain
547
+ * `string` is assignable to `UUID` and would otherwise count as an owner column.
548
+ */
549
+ type IsOwnerColumn<V> = typeof SUPATYPE_TYPE extends keyof V
550
+ ? V extends { readonly [SUPATYPE_TYPE]?: { readonly tag: infer TTag } }
551
+ ? [TTag] extends [OwnerColumnTag]
552
+ ? true
553
+ : false
554
+ : false
555
+ : false
556
+ /** Fields declared `UUID` or `SupatypeAuthUserId`, `id` included, with modifiers (`Optional<UUID>`) unwrapped. */
557
+ type OwnerColumnKeys<TFields extends Record<string, unknown>> = Extract<{
558
+ [K in keyof TFields]-?: IsOwnerColumn<NonNullable<UnwrapModelFieldType<TFields[K]>>> extends true
559
+ ? K
438
560
  : never
561
+ }[keyof TFields], string>
562
+ /** What `Owner<"f">` may name: a UUID or auth-user-id column, or a relation's `<relation>_id` key. */
439
563
  type OwnerEligibleFieldKeys<TFields extends Record<string, unknown>> =
440
- RelationOwnerKeys<TFields> | SelfOwnerKey<TFields>
441
- type ModelRelationFieldKeys<TModel> =
564
+ RelationOwnerKeys<TFields> | OwnerColumnKeys<TFields>
565
+ type ModelOwnerFieldKeys<TModel> =
442
566
  TModel extends { readonly [SUPATYPE_MODEL]?: { readonly fields: infer TFields } }
443
567
  ? TFields extends Record<string, unknown>
444
568
  ? OwnerEligibleFieldKeys<TFields>
@@ -462,7 +586,7 @@ type AnySupatypeModel = {
462
586
  */
463
587
  export type Owner<
464
588
  TModelOrKey extends string | AnySupatypeModel,
465
- TKey extends TModelOrKey extends string ? string : ModelRelationFieldKeys<TModelOrKey> = TModelOrKey extends string
589
+ TKey extends TModelOrKey extends string ? string : ModelOwnerFieldKeys<TModelOrKey> = TModelOrKey extends string
466
590
  ? TModelOrKey
467
591
  : never,
468
592
  > = Access<"Owner", {
@@ -471,7 +595,7 @@ export type Owner<
471
595
  readonly __ownerModel?: TModelOrKey extends string ? never : TModelOrKey
472
596
  }>
473
597
  export type OwnerKey<TModel extends AnySupatypeModel> =
474
- ModelRelationFieldKeys<TModel>
598
+ ModelOwnerFieldKeys<TModel>
475
599
  export type OwnerOf<
476
600
  TModel extends AnySupatypeModel,
477
601
  TKey extends OwnerKey<TModel>,
@@ -770,7 +894,7 @@ export type Exists<TSource> = Access<"Exists", {
770
894
  type BoundOwnerForFields<TFields extends Record<string, unknown>> = Access<"Owner", {
771
895
  readonly kind: "Owner"
772
896
  readonly key: OwnerEligibleFieldKeys<TFields>
773
- readonly __ownerModel?: Model<TFields, any>
897
+ readonly __ownerModel?: Model<TFields, ModelMeta<TFields>>
774
898
  }>
775
899
  type BoundOwnerFromForFields<TFields extends Record<string, unknown>> = Access<"OwnerFrom", {
776
900
  readonly kind: "OwnerFrom"
@@ -938,10 +1062,24 @@ export type SpreadOptionalModelFields<TFields extends Record<string, unknown>> =
938
1062
  : never]?: UnwrapModelFieldType<TFields[K]>
939
1063
  }
940
1064
 
1065
+ /** The Postgres index methods a model index may use. `btree` when omitted. */
1066
+ export type IndexMethod = "btree" | "gin" | "gist" | "hnsw" | "brin"
1067
+
1068
+ /**
1069
+ * How an `hnsw` index on a `Vector` field measures nearness: pgvector's operator classes
1070
+ * `vector_cosine_ops`, `vector_l2_ops` and `vector_ip_ops`. `cosine` when omitted. A query ordered
1071
+ * by another distance does not use the index.
1072
+ */
1073
+ export type VectorDistance = "cosine" | "l2" | "innerProduct"
1074
+
941
1075
  export type ModelIndex = {
942
1076
  name?: string
943
1077
  fields: readonly string[]
944
1078
  unique?: true
1079
+ /** `gist` for `Geo` and `GeoPoint` fields, `hnsw` for `Vector` fields. */
1080
+ using?: IndexMethod
1081
+ /** For an `hnsw` index only. */
1082
+ distance?: VectorDistance
945
1083
  }
946
1084
 
947
1085
  export type ModelMeta<TFields extends Record<string, unknown>> = {
@@ -974,10 +1112,14 @@ export type ModelMeta<TFields extends Record<string, unknown>> = {
974
1112
  * without read is unrepresentable, otherwise a caller could round-trip away a
975
1113
  * value they were never shown.
976
1114
  *
977
- * **`INSERT` cannot evaluate a row-dependent write rule**: there is no row
978
- * yet, so the column falls back to its default instead of accepting the
979
- * submitted value. Use an identity-only rule (`Role<>`, `LoggedIn`,
980
- * `Claim<>`) for a column that must be settable at creation time.
1115
+ * **On `INSERT` a write rule is judged against the row being stored**,
1116
+ * defaults included, as RLS `WITH CHECK` is, so a row-dependent rule
1117
+ * (`Owner<"id">`, `OwnerFrom`, a membership) can pass on create: an
1118
+ * `owner_id DEFAULT auth.uid()` is what it reads. A value the rule allows is
1119
+ * stored; one it refuses fails the insert with `42501`. Sending nothing,
1120
+ * `NULL`, `DEFAULT` or the column default's own value stores the default
1121
+ * without judging the rule. On `UPDATE`, a field the caller cannot read keeps
1122
+ * its stored value, and a real change is judged by the write rule.
981
1123
  *
982
1124
  * Relations are named by their column (`author_id`), because that is what the
983
1125
  * restriction applies to: `author` is not a column at all.
@@ -1033,15 +1175,17 @@ export type ModelMeta<TFields extends Record<string, unknown>> = {
1033
1175
  * }
1034
1176
  * ```
1035
1177
  *
1036
- * The value names a function directory under your project's `functions/`, and the name is
1037
- * checked when you push, a hook that silently never fires because of a typo is the failure
1038
- * this feature must not have. `supatype push` also generates a typed handler signature per
1039
- * hooked model, so `row` is the model's real column set rather than `unknown`.
1178
+ * The value names a hook directory under your project's `hooks/` (create one with
1179
+ * `supatype hooks new <name>`), and the name is checked when you push, a hook that silently
1180
+ * never fires because of a typo is the failure this feature must not have. `supatype push`
1181
+ * also generates a typed handler signature per hooked model, so `row` is the model's real
1182
+ * column set rather than `unknown`.
1040
1183
  *
1041
- * **A hook is not a security boundary.** It fires for writes through the API; direct SQL,
1042
- * seeds, migrations and anything holding `service_role` bypass it. Invariants belong in
1043
- * {@link ModelMeta.access}, a `CHECK`, or a generated column, all of which apply to every
1044
- * writer. A hook is for the work that is genuinely application logic: enrichment,
1184
+ * **A hook is not a security boundary.** It fires for every write through the API, including
1185
+ * one made with the `service_role` key: that key changes what Postgres permits, not whether the
1186
+ * hook runs. Direct SQL, seeds and migrations do not go through the API and bypass it.
1187
+ * Invariants belong in {@link ModelMeta.access}, a `CHECK`, or a generated column, all of which
1188
+ * apply to every writer. A hook is for the work that is genuinely application logic: enrichment,
1045
1189
  * notification, indexing, a validation the database cannot express.
1046
1190
  *
1047
1191
  * `beforeChange` and `beforeDelete` are called before the write reaches Postgres and can
@@ -1255,7 +1399,7 @@ export type Matches<TColumn extends string, TPattern extends string> = Access<"M
1255
1399
  export type ModelHook = string | ModelHookOptions
1256
1400
 
1257
1401
  export type ModelHookOptions = {
1258
- /** Function directory under the project's `functions/`. */
1402
+ /** Hook directory under the project's `hooks/`. */
1259
1403
  readonly function: string
1260
1404
  /** Milliseconds before the hook is abandoned. Default 2000. */
1261
1405
  readonly timeout?: number
package/src/lexical.ts CHANGED
@@ -1,3 +1,10 @@
1
+ /**
2
+ * Lexical's serialized JSON: what a `RichText` column stores and what the editor in Studio and
3
+ * `@supatype/ui` saves. `SerializedLexicalNode` is the loose shape every node shares; the specific
4
+ * interfaces below describe the fields Lexical 0.43 writes for each node type those editors can
5
+ * produce, so renderers and readers work from one definition.
6
+ */
7
+
1
8
  export interface SerializedLexicalNode {
2
9
  type: string
3
10
  version: number
@@ -8,3 +15,63 @@ export interface SerializedLexicalNode {
8
15
  export interface SerializedEditorState {
9
16
  root: SerializedLexicalNode
10
17
  }
18
+
19
+ /** Block alignment, stored in an element node's `format` (empty when unset). */
20
+ export type ElementFormat = "" | "left" | "start" | "center" | "right" | "end" | "justify"
21
+
22
+ /** Fields every element node (root, paragraph, heading, quote, list, listitem, link, code) carries. */
23
+ export interface SerializedElementNode extends SerializedLexicalNode {
24
+ children: SerializedLexicalNode[]
25
+ direction: "ltr" | "rtl" | null
26
+ format: ElementFormat
27
+ indent: number
28
+ }
29
+
30
+ /**
31
+ * A run of text. `format` is a bit set: bold 1, italic 2, strikethrough 4, underline 8, code 16,
32
+ * subscript 32, superscript 64, highlight 128, lowercase 256, uppercase 512, capitalize 1024.
33
+ * `tab` and `code-highlight` nodes are text nodes under their own type.
34
+ */
35
+ export interface SerializedTextNode extends SerializedLexicalNode {
36
+ type: "text" | "tab" | "code-highlight"
37
+ text: string
38
+ format: number
39
+ detail: number
40
+ mode: "normal" | "token" | "segmented"
41
+ style: string
42
+ highlightType?: string | null
43
+ }
44
+
45
+ export interface SerializedHeadingNode extends SerializedElementNode {
46
+ type: "heading"
47
+ tag: "h1" | "h2" | "h3" | "h4" | "h5" | "h6"
48
+ }
49
+
50
+ export interface SerializedListNode extends SerializedElementNode {
51
+ type: "list"
52
+ listType: "bullet" | "number" | "check"
53
+ start: number
54
+ tag: "ul" | "ol"
55
+ }
56
+
57
+ /** A list entry. A nested list is a `listitem` whose only child is a `list`. */
58
+ export interface SerializedListItemNode extends SerializedElementNode {
59
+ type: "listitem"
60
+ value: number
61
+ checked?: boolean
62
+ }
63
+
64
+ /** `link` is set by an editor; `autolink` is detected from typed text and can be unlinked. */
65
+ export interface SerializedLinkNode extends SerializedElementNode {
66
+ type: "link" | "autolink"
67
+ url: string
68
+ rel: string | null
69
+ target: string | null
70
+ title: string | null
71
+ isUnlinked?: boolean
72
+ }
73
+
74
+ export interface SerializedCodeNode extends SerializedElementNode {
75
+ type: "code"
76
+ language?: string | null
77
+ }
@@ -0,0 +1,57 @@
1
+ import { describe, expectTypeOf, it } from "vitest"
2
+ import type {
3
+ AuthUserOnDelete,
4
+ Model,
5
+ Optional,
6
+ Owner,
7
+ RelatedTo,
8
+ SupatypeAuthUser,
9
+ SupatypeAuthUserId,
10
+ UUID,
11
+ } from "../src/index.js"
12
+
13
+ // An auth user id has no foreign key unless the field asks for one: `SupatypeAuthUserId<{ onDelete }>`.
14
+ describe("SupatypeAuthUserId<{ onDelete }>", () => {
15
+ it("takes the three delete behaviours, and nothing else", () => {
16
+ expectTypeOf<AuthUserOnDelete>().toEqualTypeOf<"cascade" | "restrict" | "setNull">()
17
+ expectTypeOf<SupatypeAuthUserId<{ onDelete: "cascade" }>>().toExtend<string>()
18
+ expectTypeOf<SupatypeAuthUserId<{ onDelete: "restrict" }>>().toExtend<string>()
19
+ expectTypeOf<Optional<SupatypeAuthUserId<{ onDelete: "setNull" }>>>().not.toBeNever()
20
+ // Without options it is the field it always was, with no key.
21
+ expectTypeOf<SupatypeAuthUserId>().toEqualTypeOf<SupatypeAuthUserId<{}>>()
22
+ expectTypeOf<string>().toExtend<SupatypeAuthUserId<{ onDelete: "cascade" }>>()
23
+ })
24
+
25
+ it("rejects a behaviour or an option it does not take", () => {
26
+ // @ts-expect-error "noAction" is not one of the delete behaviours
27
+ type NoAction = SupatypeAuthUserId<{ onDelete: "noAction" }>
28
+ // @ts-expect-error the behaviour is spelled setNull, as the schema spells options
29
+ type SnakeCase = SupatypeAuthUserId<{ onDelete: "set_null" }>
30
+ // @ts-expect-error an auth user id takes onDelete alone
31
+ type Generated = SupatypeAuthUserId<{ generated: "gen_random_uuid()" }>
32
+ // @ts-expect-error an auth user id takes onDelete alone, even beside it
33
+ type Extra = SupatypeAuthUserId<{ onDelete: "cascade"; onUpdate: "cascade" }>
34
+ // @ts-expect-error the options are an object
35
+ type Bare = SupatypeAuthUserId<"cascade">
36
+ expectTypeOf<[NoAction, SnakeCase, Generated, Extra, Bare]>().not.toBeNever()
37
+ })
38
+
39
+ it("is still an owner column, and RelatedTo<SupatypeAuthUser> is unchanged", () => {
40
+ type Comment = Model<{
41
+ id: UUID
42
+ user_id: SupatypeAuthUserId<{ onDelete: "cascade" }>
43
+ editor_id: Optional<SupatypeAuthUserId<{ onDelete: "setNull" }>>
44
+ author: RelatedTo<SupatypeAuthUser>
45
+ body: string
46
+ }, {
47
+ access: { update: Owner<"user_id">; delete: Owner<"editor_id"> }
48
+ }>
49
+ expectTypeOf<Comment["user_id"]>().toExtend<string>()
50
+ expectTypeOf<Comment>().toHaveProperty("author")
51
+
52
+ type Profile = Model<{ id: SupatypeAuthUserId<{ onDelete: "cascade" }>; name: string }, {
53
+ access: { update: Owner<"id"> }
54
+ }>
55
+ expectTypeOf<Profile>().toHaveProperty("id")
56
+ })
57
+ })
@@ -10,12 +10,11 @@ describe("BucketStorageAccess", () => {
10
10
  })
11
11
 
12
12
  it("accepts a fully declared bucket", () => {
13
- const crud = {} as {
13
+ expectTypeOf<{
14
14
  read: BucketPublic
15
15
  create: BucketLoggedIn
16
16
  update: BucketOwner
17
17
  delete: BucketOwner
18
- }
19
- expectTypeOf(crud).toExtend<BucketStorageAccess>()
18
+ }>().toExtend<BucketStorageAccess>()
20
19
  })
21
20
  })
@@ -0,0 +1,12 @@
1
+ import { describe, expectTypeOf, it } from "vitest"
2
+ import type { Geo } from "../src/index.js"
3
+
4
+ describe("Geo", () => {
5
+ it("is a point unless a shape is given", () => {
6
+ expectTypeOf<Geo>().toEqualTypeOf<Geo<"point">>()
7
+ })
8
+
9
+ it("carries the shape it was given", () => {
10
+ expectTypeOf<Geo<"polygon">["type"]>().toEqualTypeOf<"polygon">()
11
+ })
12
+ })