@forestfuture/active-record 0.8.2 → 0.9.1

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.
@@ -1,9 +1,9 @@
1
- import { a as AttributeType, c as ValueSource, d as EnumNames, f as EnumValues, g as CustomType, h as AnyCustomType, i as AttributeSpecs, m as TextEnum, n as AttributeProperties, o as ExactSpecs, p as IntegerEnum, s as SpecObject, t as AttributeDefinition, u as EnumMapping } from "./metadata-CzntpYzC.mjs";
1
+ import { D as Duration, M as AttributeAlias, N as DefinedSpecs, O as AnyCustomType, P as WithoutAliases, S as SecurePasswordMethods, T as WithSecurePasswords, _ as SecureTokenOptions, a as AttributeType, b as PasswordResetTokenArgument, c as SpecObject, d as EnumMapping, f as EnumNames, g as SecureTokenMethods, h as TextEnum, i as AttributeSpecs, j as AliasSpecs, k as CustomType, l as ValueSource, m as IntegerEnum, n as AttributeProperties, o as DeclaredAttributes, p as EnumValues, s as ExactSpecs, t as AttributeDefinition, w as SecurePasswordSpecs, x as SecurePasswordDeclaration, y as AuthenticateByAttributes } from "./metadata-nKZ_6DzA.mjs";
2
2
  /** What `comparison` compares: numbers with numbers, strings with strings, Dates by their time. */
3
3
  type Comparable = number | string | Date;
4
4
  /** A bound: a value, or a function of the record being validated (`(event) => event.startsAt`). */
5
5
  type ComparisonBound<R = never> = Comparable | ((record: R) => Comparable | null);
6
- /** The bounds of a `comparison` rule, with Rails' error types as keys. `R` is the record type. */
6
+ /** The bounds of a `comparison` rule, with its error types as keys. `R` is the record type. */
7
7
  interface ComparisonOptions<R = never> {
8
8
  greaterThan?: ComparisonBound<R>;
9
9
  greaterThanOrEqualTo?: ComparisonBound<R>;
@@ -37,7 +37,7 @@ type ScopeStems<A> = { [K in keyof A]: A[K] extends {
37
37
  } ? never : Stems<K, A[K]>; }[keyof A];
38
38
  /**
39
39
  * What the enums of the specs `A` add to a record: a predicate for each name, and a setter that
40
- * assigns it and saves, with its `OrThrow`, as Rails' `published!` updates the record.
40
+ * assigns it and saves, with its `OrThrow`.
41
41
  */
42
42
  type EnumMethods<A> = { [P in `is${RecordStems<A>}`]: () => boolean; } & { [P in `saveAs${RecordStems<A>}`]: () => Promise<boolean>; } & { [P in `saveAs${RecordStems<A>}OrThrow`]: () => Promise<true>; };
43
43
  /** What the enums of the specs `A` add to a Model: a scope for each name, and a `not…` scope. */
@@ -84,7 +84,8 @@ type UnscopedPart = "where" | "order" | "limit" | "offset" | "select" | "distinc
84
84
  declare class Attribute {
85
85
  #private;
86
86
  readonly name: string;
87
- readonly column: string;
87
+ /** Its column; `UnknownAttribute` for a virtual attribute, which has none (#356). */
88
+ get column(): string;
88
89
  /** Whether it's a `string` attribute, which D1 compares as text, not by number. */
89
90
  get isText(): boolean;
90
91
  /** Whether it's a `binary` attribute, whose cells are bytes, which JSON can't hold (#20). */
@@ -98,6 +99,23 @@ declare class Attribute {
98
99
  * unless the attribute is filtered (#83).
99
100
  */
100
101
  cast(value: unknown): unknown;
102
+ /** An assigned value cast, then normalized (#354): what a record keeps for it. */
103
+ assigned(value: unknown): unknown;
104
+ /**
105
+ * An already cast value through each of the attribute's normalizations, in order (#354): null
106
+ * only through those declared `applyToNull`. Each result is cast again, so it's a value of the
107
+ * attribute's type, whatever plain JavaScript returns; a promise is refused.
108
+ */
109
+ normalize(value: unknown): unknown;
110
+ /**
111
+ * A condition's value cast as a condition's, then normalized as an assigned value is (#354), each
112
+ * result cast again as a condition's, so a decimal's precision limits neither. A value that
113
+ * can't be cast is kept as it was given, so it still matches nothing, and an error that names it
114
+ * names what was given; a result that can't be cast throws, as assigning it would.
115
+ */
116
+ normalizedCondition(value: unknown): unknown;
117
+ /** Whether the attribute has a normalization, so its conditions need normalizing (#354). */
118
+ get hasNormalization(): boolean;
101
119
  /**
102
120
  * A key copied from another record or inherited from a condition: cast as a condition's, but
103
121
  * one that can't be cast throws, naming the association it came through.
@@ -118,6 +136,8 @@ declare class Attribute {
118
136
  write(value: unknown): unknown;
119
137
  /** An assigned value cast, then in the form D1 stores. */
120
138
  store(value: unknown): unknown;
139
+ /** An assigned value cast and normalized (#354), then in the form D1 stores. */
140
+ storeNormalized(value: unknown): unknown;
121
141
  /**
122
142
  * A cell D1 returned as the attribute's value. One that isn't (text in a Unix time column, or
123
143
  * past the range of a `Date`; a json cell that isn't JSON) throws `TypeError` naming the
@@ -129,7 +149,7 @@ declare class Attribute {
129
149
  /**
130
150
  * Whether two values are the same as stored (dates by time, json and bytes by content). Each is
131
151
  * cast as a condition's value first, so `isAttributeChanged`'s `from` and `to` compare as
132
- * Rails' do, and one that can't be cast is the same as nothing (#20).
152
+ * conditions do, and one that can't be cast is the same as nothing (#20).
133
153
  */
134
154
  isSame(a: unknown, b: unknown): boolean;
135
155
  /** An assigned value, cast and written, bound hidden from `onQuery` if filtered (#83). */
@@ -187,6 +207,13 @@ interface Dialect {
187
207
  * it matches `linked`'s column as a condition on `linked` would: by text for a text attribute.
188
208
  */
189
209
  linkedKey(key: string, keyAttribute: Attribute, linked: Attribute): string;
210
+ /**
211
+ * A record's write that must change its row (an update or delete by its key and `lockVersion`,
212
+ * #357), followed by a check that fails the whole atomic batch when it changed none, with an
213
+ * error whose message holds `marker`, bound as a value: one statement or several, the write's
214
+ * result first.
215
+ */
216
+ staleGuard(write: CompiledSql, marker: string): CompiledSql[];
190
217
  /**
191
218
  * A bulk removal (a DELETE, or an UPDATE nullifying a key) and the counter caches it changes
192
219
  * (#61), as one statement: `decrements` writes the counters' UPDATEs, given SQL counting the rows
@@ -207,6 +234,18 @@ interface QuerySql {
207
234
  sql: string;
208
235
  params: unknown[];
209
236
  }
237
+ /**
238
+ * What `normalizes` takes for an attribute whose values are `T`: a function given a value of
239
+ * the attribute's type, once it's cast, returning the value to keep. It isn't given `null`
240
+ * unless `applyToNull` is `true`.
241
+ */
242
+ type NormalizeOptions<T> = {
243
+ with: (value: NonNullable<T>) => T;
244
+ applyToNull?: false;
245
+ } | {
246
+ with: (value: T) => T;
247
+ applyToNull: true;
248
+ };
210
249
  /** What Node's `util.inspect` passes a custom inspector; `src/` doesn't import Node's types. */
211
250
  interface InspectOptions {
212
251
  depth?: number | null;
@@ -218,9 +257,61 @@ type Inspect = (value: unknown, options?: InspectOptions) => string;
218
257
  declare const inspectCustom: unique symbol;
219
258
  /** What `inOrderOf` takes after its list: whether to keep only the records with a listed value. */
220
259
  interface InOrderOfOptions {
221
- /** Keep only the records whose value is in the list (the default), as Rails does; `false` keeps every one, those not in it last. */
260
+ /** Keep only the records whose value is in the list (the default); `false` keeps every one, those not in it last. */
222
261
  filter?: boolean;
223
262
  }
263
+ /** What a signed id is for, and how long it lasts: forever unless given. */
264
+ interface SignedIdOptions {
265
+ /** How long it lasts: `{ minutes: 15 }`. Give this or `expiresAt`. */
266
+ readonly expiresIn?: Duration;
267
+ /** When it stops finding its record. */
268
+ readonly expiresAt?: Date;
269
+ /** What it's for (`"login"`): `findSigned` finds its record only given the same. */
270
+ readonly purpose?: string;
271
+ }
272
+ /** What `findSigned` takes: the purpose the signed id was made for. */
273
+ interface FindSignedOptions {
274
+ readonly purpose?: string;
275
+ }
276
+ /** The finders by token every Relation has. */
277
+ declare abstract class TokenFinders<M extends Model> {
278
+ #private;
279
+ abstract findBy(conditions: never): Promise<M | null>;
280
+ /**
281
+ * The record a signed id finds (`await user.signedId()`), if this Model's secret signed it for
282
+ * the same `purpose` and it hasn't expired, and this Relation matches it; or null.
283
+ */
284
+ findSigned(signedId: unknown, options?: FindSignedOptions): Promise<M | null>;
285
+ /** Like `findSigned`, but throws `InvalidToken` for a signed id that isn't valid, and `RecordNotFound` when its record is gone. */
286
+ findSignedOrThrow(signedId: unknown, options?: FindSignedOptions): Promise<M>;
287
+ /**
288
+ * The record a token for `purpose` finds (`await user.generateTokenFor(purpose)`), if this
289
+ * Model's secret signed it, it hasn't expired, the value it depends on is unchanged, and this
290
+ * Relation matches it; or null. `TypeError` for a purpose the Model doesn't declare.
291
+ */
292
+ findByTokenFor(purpose: string, token: unknown): Promise<M | null>;
293
+ /**
294
+ * Like `findByTokenFor`, but throws `InvalidToken` for a token that isn't valid, and
295
+ * `RecordNotFound` when its record is gone or the value it depends on changed.
296
+ */
297
+ findByTokenForOrThrow(purpose: string, token: unknown): Promise<M>;
298
+ }
299
+ /** The questions about how many records every Relation has. */
300
+ declare abstract class CountQuestions<M extends Model> extends TokenFinders<M> {
301
+ /**
302
+ * The number of records: a loaded association's (built records included) without a query;
303
+ * otherwise a `COUNT(*)`, plus an association's unsaved built records.
304
+ */
305
+ size(): Promise<number>;
306
+ /** Whether there are no records: a loaded association answers itself, else `!exists()`. */
307
+ isEmpty(): Promise<boolean>;
308
+ /** Whether there are any records: the opposite of `isEmpty()`. */
309
+ hasAny(): Promise<boolean>;
310
+ /** Whether more than one record matches: one `COUNT` of at most two rows. */
311
+ hasMoreThanOne(): Promise<boolean>;
312
+ /** Whether exactly one record matches: one `COUNT` of at most two rows. */
313
+ hasExactlyOne(): Promise<boolean>;
314
+ }
224
315
  /** A part of a query `unscope` drops by name: `unscope("order")`. */
225
316
  type QueryPart = Exclude<UnscopedPart, object>;
226
317
  /** One attribute's name, or several: what `unscope({ where })` takes. */
@@ -237,15 +328,15 @@ declare class Comparison<T = unknown> {
237
328
  }
238
329
  /** `attribute > value` */
239
330
  declare function gt<T>(value: T): Comparison<T>;
240
- /** `attribute >= value`, like Rails' endless range `value..` */
331
+ /** `attribute >= value`: everything from `value` on. */
241
332
  declare function gte<T>(value: T): Comparison<T>;
242
- /** `attribute < value`, like Rails' beginless range `...value` */
333
+ /** `attribute < value`: everything before `value`. */
243
334
  declare function lt<T>(value: T): Comparison<T>;
244
- /** `attribute <= value`, like Rails' beginless range `..value` */
335
+ /** `attribute <= value`: everything up to `value`, `value` included. */
245
336
  declare function lte<T>(value: T): Comparison<T>;
246
337
  /**
247
- * `attribute BETWEEN start AND end`, both ends included, like Rails' `start..end`. With
248
- * `excludeEnd`, `start <= attribute < end`, like `start...end` (e.g. a window of days).
338
+ * `attribute BETWEEN start AND end`, both ends included. With
339
+ * `excludeEnd`, `start <= attribute < end` (e.g. a window of days).
249
340
  */
250
341
  declare function between<T>(start: T, end: T, options?: {
251
342
  excludeEnd?: boolean;
@@ -285,16 +376,16 @@ type OrderSpec<M> = { [K in keyof AttributesOf<M>]?: OrderDirection | {
285
376
  direction: OrderDirection;
286
377
  nulls?: NullsPlacement;
287
378
  }; };
288
- /** What `user.posts()` has besides its Relation's methods, as Rails' collection proxy does. */
379
+ /** What `user.posts()` has besides its Relation's methods. */
289
380
  interface CollectionMethods<M extends Model> {
290
381
  /**
291
- * Adds records to the association (Rails' `<<`): sets each one's foreign key and saves them
382
+ * Adds records to the association: sets each one's foreign key and saves them
292
383
  * together, resolving to `false`, with nothing written, if one can't be saved.
293
384
  */
294
385
  push(...records: M[]): Promise<boolean>;
295
386
  /**
296
- * Removes records from the association by its `dependent:` strategy, as Rails' collection
297
- * `delete`: destroys them with `"destroy"`, deletes their rows with `"deleteAll"`, and
387
+ * Removes records from the association by its `dependent:` strategy:
388
+ * destroys them with `"destroy"`, deletes their rows with `"deleteAll"`, and
298
389
  * otherwise sets their foreign key to NULL. Resolves to the records.
299
390
  */
300
391
  delete(...records: M[]): Promise<M[]>;
@@ -317,7 +408,7 @@ interface CollectionMethods<M extends Model> {
317
408
  destroyAll(): Promise<M[]>;
318
409
  }
319
410
  /**
320
- * An association's scope, as Rails' `has_many :posts, -> { order(:created_at) }`: it receives
411
+ * An association's scope, such as `(q) => q.order({ createdAt: "asc" })`: it receives
321
412
  * the target's Relation, with its scopes, and returns a narrowed one.
322
413
  */
323
414
  type AssociationScope<C extends ModelClass> = (relation: Scoped<InstanceType<C>, ScopesOf<C>>) => unknown;
@@ -325,7 +416,7 @@ type AssociationScope<C extends ModelClass> = (relation: Scoped<InstanceType<C>,
325
416
  interface AssociationOptions<C extends ModelClass = ModelClass> {
326
417
  /**
327
418
  * The attribute holding the link: on the owner for belongsTo, on the target otherwise.
328
- * Inferred when left out, as Rails does: a belongsTo's name + `Id` (`author` → `authorId`),
419
+ * Inferred when left out: a belongsTo's name + `Id` (`author` → `authorId`),
329
420
  * or for a hasMany/hasOne the owner's `modelName` + `Id` (`User` → `userId`).
330
421
  */
331
422
  foreignKey?: string;
@@ -337,7 +428,7 @@ interface AssociationOptions<C extends ModelClass = ModelClass> {
337
428
  dependent?: Dependent;
338
429
  /**
339
430
  * Saving the owner also saves this association's loaded records that changed, and destroys
340
- * those marked with `markForDestruction()`, as Rails' `autosave: true` does (#37).
431
+ * those marked with `markForDestruction()` (#37).
341
432
  */
342
433
  autosave?: true;
343
434
  /**
@@ -368,14 +459,14 @@ interface ThroughOptions<C extends ModelClass = ModelClass> {
368
459
  * another's join records (#434): destroy them, callbacks included, or delete their rows.
369
460
  */
370
461
  type ThroughDependent = "destroy" | "deleteAll";
371
- /** Rails' `dependent:` strategies for a hasMany. */
462
+ /** What a hasMany's `dependent:` does to its records when the owner is destroyed. */
372
463
  type HasManyDependent = "destroy" | "deleteAll" | "nullify" | "restrictWithException" | "restrictWithError";
373
- /** Rails' `dependent:` strategies for a hasOne: `delete` in place of `deleteAll`. */
464
+ /** What a hasOne's `dependent:` does to its record: `delete` in place of `deleteAll`. */
374
465
  type HasOneDependent = "destroy" | "delete" | "nullify" | "restrictWithException" | "restrictWithError";
375
466
  type Dependent = HasManyDependent | HasOneDependent;
376
467
  /**
377
468
  * `await post.author()`: the owning record, or null. `post.author.set(user)` points the post at
378
- * another record (Rails' `post.author = user`), and `build`/`create` make a new one for it.
469
+ * another record, and `build`/`create` make a new one for it.
379
470
  */
380
471
  interface BelongsTo<C extends ModelClass> {
381
472
  (): Promise<InstanceType<C> | null>;
@@ -396,9 +487,8 @@ interface PolymorphicBelongsTo<C extends ModelClass> {
396
487
  }
397
488
  /**
398
489
  * `await user.profile()`: the one associated record, or null. `await user.profile.set(profile)`
399
- * gives the user another (Rails' `user.profile = profile`), and `build(attrs)` and
400
- * `create(attrs)` make a new one pointing at the user (Rails' `build_profile`). Each replaces the
401
- * old record, removed by `dependent:` when the new one is written.
490
+ * gives the user another, and `build(attrs)` and `create(attrs)` make a new one pointing at the
491
+ * user. Each replaces the old record, removed by `dependent:` when the new one is written.
402
492
  */
403
493
  interface HasOne<C extends ModelClass> {
404
494
  (): Promise<InstanceType<C> | null>;
@@ -424,7 +514,7 @@ type HasManyThrough<C extends ModelClass> = () => Scoped<InstanceType<C>, Scopes
424
514
  type ThroughWrite = "insert" | "insertAll" | "upsert" | "upsertAll";
425
515
  /**
426
516
  * `await mark.note()` for a hasOne through another (#59): its record, or null. `set(note)`
427
- * points the owner's join record at another (#434); as in Rails, it has no `build` or `create`.
517
+ * points the owner's join record at another (#434); it has no `build` or `create`.
428
518
  */
429
519
  interface HasOneThrough<C extends ModelClass> {
430
520
  (): Promise<InstanceType<C> | null>;
@@ -498,8 +588,8 @@ declare class Statement<Row = never> {
498
588
  readonly [rowType]?: Row;
499
589
  }
500
590
  /**
501
- * What a new record is handed to, once its attributes are assigned and before it's saved (Rails'
502
- * block): `create({ email }, (user) => { user.role = "member" })`. Awaited where it's saved.
591
+ * What a new record is handed to, once its attributes are assigned and before it's saved:
592
+ * `create({ email }, (user) => { user.role = "member" })`. Awaited where it's saved.
503
593
  */
504
594
  type Init<M> = (record: M) => void | Promise<void>;
505
595
  /** Two or more of a Model's attributes, as `pluck` and `pick` take them for tuples. */
@@ -643,7 +733,7 @@ type ScopeMethods<M extends Model, S> = { [K in keyof S]: S[K] extends ((this: n
643
733
  /** A Relation of Model records `M` with the Model's scope methods `S`. */
644
734
  type Scoped<M extends Model, S = {}> = [keyof S] extends [never] ? Relation<M, S> : Relation<M, S> & ScopeMethods<M, S>;
645
735
  /** A lazy, immutable description of a query against one Model. */
646
- declare class Relation<M extends Model, S = {}> {
736
+ declare class Relation<M extends Model, S = {}> extends CountQuestions<M> {
647
737
  #private;
648
738
  /** Type-only: the Model's scopes, so chained calls keep their scope methods. */
649
739
  readonly [scopeTypes]?: S;
@@ -656,21 +746,21 @@ declare class Relation<M extends Model, S = {}> {
656
746
  /** Negates the whole condition: `NOT (…)`. Rows where it is NULL are excluded too. */
657
747
  whereNot(conditions: Conditions<M> | SafeSql): Scoped<M, S>;
658
748
  /**
659
- * Replaces the conditions on these attributes with these, as Rails' `rewhere`: those on other
660
- * attributes, and fragments, are kept.
749
+ * Replaces the conditions on these attributes with these: those on other attributes, and
750
+ * fragments, are kept.
661
751
  */
662
752
  rewhere(conditions: Conditions<M>): Scoped<M, S>;
663
753
  /**
664
- * Drops parts of the query, as Rails' `unscope`: `unscope("order", "limit")`, or the conditions
754
+ * Drops parts of the query: `unscope("order", "limit")`, or the conditions
665
755
  * on some attributes, `unscope({ where: "role" })`. A default scope's are dropped too.
666
756
  */
667
757
  unscope(...parts: (QueryPart | {
668
758
  where: AttributeNames<M>;
669
759
  })[]): Scoped<M, S>;
670
- /** Keeps only these parts of the query, as Rails' `only`: `only("where", "order")`. */
760
+ /** Keeps only these parts of the query: `only("where", "order")`. */
671
761
  only(...parts: QueryPart[]): Scoped<M, S>;
672
762
  /**
673
- * Leaves these records out, by primary key, as Rails' `excluding`: `excluding(post)`, or
763
+ * Leaves these records out, by primary key: `excluding(post)`, or
674
764
  * `excluding(posts)`. A record not yet saved leaves nothing out.
675
765
  */
676
766
  excluding(...records: (M | readonly M[])[]): Scoped<M, S>;
@@ -684,7 +774,7 @@ declare class Relation<M extends Model, S = {}> {
684
774
  /**
685
775
  * ANDs `other`'s conditions onto this Relation's. For select, order, limit, offset and
686
776
  * distinct, a clause `other` sets explicitly replaces this one's; one it doesn't set is kept.
687
- * Orders are replaced, not concatenated (a deliberate difference from Rails). `other` may be a
777
+ * Orders are replaced, not concatenated, so a merged order reads as written. `other` may be a
688
778
  * Relation of a Model this one joins once (#24): its conditions apply to the joined table.
689
779
  */
690
780
  merge<T extends Model = M, O = S>(other: Relation<T, O>): Scoped<M, S>;
@@ -693,10 +783,10 @@ declare class Relation<M extends Model, S = {}> {
693
783
  * nulls: "last" } }`), or by an `sql` fragment expression. Repeated calls append.
694
784
  */
695
785
  order(spec: OrderSpec<M> | SafeSql): Scoped<M, S>;
696
- /** Replaces the order so far, as in Rails; `reorder()` removes it. */
786
+ /** Replaces the order so far; `reorder()` removes it. */
697
787
  reorder(spec?: OrderSpec<M> | SafeSql): Scoped<M, S>;
698
788
  /**
699
- * Orders by `attribute`'s place in `values`, then by any order after it, as Rails' `in_order_of`:
789
+ * Orders by `attribute`'s place in `values`, then by any order after it:
700
790
  * `inOrderOf("status", ["open", "paid"])`. Keeps only the records with one of them, unless
701
791
  * `filter: false`, which keeps the rest after them.
702
792
  */
@@ -707,6 +797,12 @@ declare class Relation<M extends Model, S = {}> {
707
797
  select(...attributes: (keyof AttributesOf<M> & string)[]): Scoped<M, S>;
708
798
  /** Removes duplicate rows (of the selected attributes). */
709
799
  distinct(): Scoped<M, S>;
800
+ /**
801
+ * Makes the records this Relation loads read-only (#358): saving or destroying one throws
802
+ * `ReadonlyRecord`. Records it preloads, builds or creates aren't, and its bulk writes ignore it.
803
+ * `readonly(false)` undoes it.
804
+ */
805
+ readonly(flag?: boolean): Scoped<M, S>;
710
806
  /**
711
807
  * Preloads associations for every record this Relation loads, so reading them afterwards
712
808
  * sends no query: `includes("posts", "profile")`, nested `includes({ posts: "comments" })`.
@@ -737,14 +833,14 @@ declare class Relation<M extends Model, S = {}> {
737
833
  * wrote and the `returning` attributes of each (the primary key by default; `false` for none).
738
834
  * Skips validations and callbacks; declared defaults, generated ids, and timestamps apply, and
739
835
  * this Relation's equality conditions are inserted over the given attributes (#470). A
740
- * duplicate throws, unless `onDuplicate: "skip"` (Rails' `insert`). `b.insert` is the same
836
+ * duplicate throws, unless `onDuplicate: "skip"`. `b.insert` is the same
741
837
  * write, for a batch.
742
838
  */
743
839
  insert<const R extends Returning<M> | undefined = undefined>(attributes: Partial<AttributesOf<M>>, options?: InsertOptions<M> & {
744
840
  returning?: R;
745
841
  }): Promise<WriteResult<ReturnedRow<M, R>>>;
746
842
  /**
747
- * Inserts several rows with the same attributes now (Rails' `insert_all!`): in one statement,
843
+ * Inserts several rows with the same attributes now: in one statement,
748
844
  * or several in one atomic batch when they pass the database's cap on one value.
749
845
  */
750
846
  insertAll<const R extends Returning<M> | undefined = undefined>(rows: readonly Partial<AttributesOf<M>>[], options?: InsertOptions<M> & {
@@ -753,26 +849,26 @@ declare class Relation<M extends Model, S = {}> {
753
849
  /**
754
850
  * Inserts a row now, or updates it when it clashes with the unique index on `uniqueBy` (the
755
851
  * primary key by default): every given attribute and every value this Relation writes into the
756
- * row (#475), except the `uniqueBy` ones and `createdAt`, with `updatedAt` set, as Rails'
757
- * `upsert` does. Resolves as `insert` does, returning inserted and updated rows.
852
+ * row (#475), except the `uniqueBy` ones and `createdAt`, with `updatedAt` set.
853
+ * Resolves as `insert` does, returning inserted and updated rows.
758
854
  */
759
855
  upsert<const R extends Returning<M> | undefined = undefined>(attributes: Partial<AttributesOf<M>>, options?: UpsertOptions<M> & {
760
856
  returning?: R;
761
857
  }): Promise<WriteResult<ReturnedRow<M, R>>>;
762
- /** `upsert` for several rows with the same attributes, now (Rails' `upsert_all`). */
858
+ /** `upsert` for several rows with the same attributes, now. */
763
859
  upsertAll<const R extends Returning<M> | undefined = undefined>(rows: readonly Partial<AttributesOf<M>>[], options?: UpsertOptions<M> & {
764
860
  returning?: R;
765
861
  }): Promise<WriteResult<ReturnedRow<M, R>>>;
766
862
  /**
767
863
  * Updates every row this Relation matches, now, setting attribute values or an `sql`
768
864
  * fragment: ``updateAll(sql`${column("views")} = ${column("views")} + 1`)``. Resolves to the
769
- * number of rows updated. Skips validations and callbacks, and leaves `updatedAt` alone, as in
770
- * Rails. A `none()` Relation sends nothing and resolves to 0.
865
+ * number of rows updated. Skips validations and callbacks, and leaves `updatedAt` alone.
866
+ * A `none()` Relation sends nothing and resolves to 0.
771
867
  */
772
868
  updateAll(changes: Partial<AttributesOf<M>> | SafeSql): Promise<number>;
773
869
  /**
774
870
  * Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`) in every row this
775
- * Relation matches, in one statement, as Rails' `touch_all` (#50). Resolves to the number of
871
+ * Relation matches, in one statement (#50). Resolves to the number of
776
872
  * rows; skips what `updateAll` skips.
777
873
  */
778
874
  touchAll(...args: TouchArguments<M>): Promise<number>;
@@ -785,7 +881,7 @@ declare class Relation<M extends Model, S = {}> {
785
881
  /**
786
882
  * Deletes every row this Relation matches, now, resolving to the number of rows. On a hasMany
787
883
  * association itself (`user.posts().deleteAll()`), the rows' foreign key is set to NULL
788
- * instead unless its `dependent:` deletes, as in Rails. A `none()` Relation sends nothing and
884
+ * instead unless its `dependent:` deletes. A `none()` Relation sends nothing and
789
885
  * resolves to 0.
790
886
  */
791
887
  deleteAll(): Promise<number>;
@@ -811,7 +907,7 @@ declare class Relation<M extends Model, S = {}> {
811
907
  /**
812
908
  * The record with this primary key, keeping this Relation's conditions. With several ids,
813
909
  * `find(1, 2)` or `find([1, 2])`, the records in the ids' order (or this Relation's order,
814
- * if it has one), as Rails does; `RecordNotFound` if any is missing.
910
+ * if it has one); `RecordNotFound` if any is missing.
815
911
  */
816
912
  find(id: string | number): Promise<M>;
817
913
  find(ids: readonly (string | number)[]): Promise<M[]>;
@@ -885,19 +981,6 @@ declare class Relation<M extends Model, S = {}> {
885
981
  calculate<K extends OrderedAttribute<M> | SafeSql>(operation: "minimum" | "maximum", attribute: K): Promise<CalculatedValue<M, K, unknown> | null>;
886
982
  /** Groups the rows by attributes or `sql` fragments, for each group's calculations (#345). */
887
983
  group<const G extends GroupTerms<M>>(...terms: G): GroupedRelation<M, G>;
888
- /**
889
- * The number of records, as Rails' `size`: a loaded association's (built records included)
890
- * without a query; otherwise a `COUNT(*)`, plus an association's unsaved built records.
891
- */
892
- size(): Promise<number>;
893
- /** Whether there are no records: a loaded association answers itself, else `!exists()`. */
894
- isEmpty(): Promise<boolean>;
895
- /** Whether there are any records: the opposite of `isEmpty()` (Rails' `any?`). */
896
- hasAny(): Promise<boolean>;
897
- /** Whether more than one record matches, as Rails' `many?`: one `COUNT` of at most two rows. */
898
- hasMoreThanOne(): Promise<boolean>;
899
- /** Whether exactly one record matches, as Rails' `one?`: one `COUNT` of at most two rows. */
900
- hasExactlyOne(): Promise<boolean>;
901
984
  /** Whether any record matches, optionally with extra conditions. */
902
985
  exists(conditions?: Conditions<M> | SafeSql): Promise<boolean>;
903
986
  /** Converted values of one attribute, or tuples of several, in this Relation's order. */
@@ -935,7 +1018,7 @@ declare class Relation<M extends Model, S = {}> {
935
1018
  */
936
1019
  inBatches(options?: IterationOptions): AsyncIterable<Scoped<M, S>>;
937
1020
  /**
938
- * The SQL `toArray()` sends, and its bound values, without sending it (Rails' `to_sql`). Values
1021
+ * The SQL `toArray()` sends, and its bound values, without sending it. Values
939
1022
  * are never inlined into the SQL (ADR-0006), and none are redacted, filtered attributes included.
940
1023
  */
941
1024
  toSql(): QuerySql;
@@ -943,6 +1026,17 @@ declare class Relation<M extends Model, S = {}> {
943
1026
  [inspectCustom](depth: number, options: InspectOptions, inspect: Inspect): string;
944
1027
  toArray(): Promise<M[]>;
945
1028
  }
1029
+ /** What `generatesTokenFor` takes: how long its tokens last, and a value they depend on. */
1030
+ interface TokenForOptions<R> {
1031
+ /** How long a token lasts: `{ days: 1 }`. Forever unless given. */
1032
+ readonly expiresIn?: Duration;
1033
+ /**
1034
+ * A value of the record's that its tokens depend on (`(user) => user.email`): a token finds
1035
+ * its record only while the value is the same as when it was made. Compared as JSON; a
1036
+ * token holds a fingerprint of it, never the value.
1037
+ */
1038
+ readonly dependsOn?: (record: R) => unknown;
1039
+ }
946
1040
  /**
947
1041
  * An around callback: `next` runs the rest of the write, resolving once the record's write is kept
948
1042
  * and its inner callbacks have run.
@@ -972,7 +1066,7 @@ interface SaveOptions {
972
1066
  /** A Model's Relation, as its statics return them: `Product.where(…)` is `Product.all().where(…)`. */
973
1067
  type RelationOf<C extends ModelClass> = Scoped<InstanceType<C>, ScopesOf<C>>;
974
1068
  /** The Relation methods every Model has as statics (besides the overloaded ones). */
975
- declare const relationMethods: readonly ["where", "whereNot", "rewhere", "unscope", "only", "excluding", "none", "or", "order", "reorder", "limit", "offset", "select", "distinct", "includes", "joins", "leftJoins", "createWith", "build", "insert", "insertAll", "upsert", "upsertAll", "updateAll", "touchAll", "deleteAll", "destroyAll", "destroyBy", "deleteBy", "create", "createOrThrow", "findBy", "findByOrThrow", "findSoleBy", "findOrCreateBy", "findOrCreateByOrThrow", "findOrInitializeBy", "createOrFindBy", "createOrFindByOrThrow", "first", "last", "take", "firstOrThrow", "lastOrThrow", "takeOrThrow", "sole", "count", "average", "size", "isEmpty", "hasAny", "hasMoreThanOne", "hasExactlyOne", "exists", "ids", "toArray", "toSql", "findEach", "findInBatches", "inBatches"];
1069
+ declare const relationMethods: readonly ["where", "whereNot", "rewhere", "unscope", "only", "excluding", "none", "or", "order", "reorder", "limit", "offset", "select", "distinct", "readonly", "includes", "joins", "leftJoins", "createWith", "build", "insert", "insertAll", "upsert", "upsertAll", "updateAll", "touchAll", "deleteAll", "destroyAll", "destroyBy", "deleteBy", "create", "createOrThrow", "findBy", "findByOrThrow", "findSoleBy", "findSigned", "findSignedOrThrow", "findByTokenFor", "findByTokenForOrThrow", "findOrCreateBy", "findOrCreateByOrThrow", "findOrInitializeBy", "createOrFindBy", "createOrFindByOrThrow", "first", "last", "take", "firstOrThrow", "lastOrThrow", "takeOrThrow", "sole", "count", "average", "size", "isEmpty", "hasAny", "hasMoreThanOne", "hasExactlyOne", "exists", "ids", "toArray", "toSql", "findEach", "findInBatches", "inBatches"];
976
1070
  /** A Relation method with no overloads, by name. */
977
1071
  type RelationMethod = (typeof relationMethods)[number];
978
1072
  /**
@@ -1001,7 +1095,7 @@ interface OverloadedStatics {
1001
1095
  <C extends QueryableClass, K extends OrderedAttribute<InstanceType<C>> | SafeSql>(this: C, operation: "minimum" | "maximum", attribute: K): Promise<CalculatedValue<InstanceType<C>, K, unknown> | null>;
1002
1096
  };
1003
1097
  paginate: PaginateStatic;
1004
- /** The class's Relation ordered by `attribute`'s place in `values` (#350), as Rails' `in_order_of`. */
1098
+ /** The class's Relation ordered by `attribute`'s place in `values` (#350). */
1005
1099
  inOrderOf: <C extends QueryableClass, K extends keyof AttributesOf<InstanceType<C>> & string>(this: C, attribute: K, values: readonly AttributesOf<InstanceType<C>>[K][], options?: InOrderOfOptions) => RelationOf<C>;
1006
1100
  group: <C extends QueryableClass, const G extends GroupTerms<InstanceType<C>>>(this: C, ...terms: G) => GroupedRelation<InstanceType<C>, G>;
1007
1101
  find: {
@@ -1146,12 +1240,49 @@ interface CommitStatics {
1146
1240
  /** Runs once a destroy is kept, after every after-callback. */
1147
1241
  afterDestroyCommit: CallbackStatic;
1148
1242
  }
1243
+ /** A static that finds a record by `password`'s reset token, typed `never` for a Model without one. */
1244
+ type ResetTokenStatic<Found> = <C extends QueryableClass>(this: C, token: PasswordResetTokenArgument<SpecsOf<InstanceType<C>>>) => Promise<InstanceType<C> | Found>;
1245
+ /** The finders by a secure password's reset token (#517), for `password`. */
1246
+ interface ResetTokenStatics {
1247
+ findByPasswordResetToken: ResetTokenStatic<null>;
1248
+ findByPasswordResetTokenOrThrow: ResetTokenStatic<never>;
1249
+ }
1149
1250
  /**
1150
1251
  * The class Model extends, for its statics' types only: at runtime it's empty, and
1151
1252
  * `defineStatics` puts the statics on Model itself, where scopes look for the names they
1152
1253
  * can't take.
1153
1254
  */
1154
- declare const ModelStatics: (abstract new () => object) & RelationStatics & OverloadedStatics & KeyedWriteStatics & CallbackStatics & AroundStatics & CommitStatics;
1255
+ declare const ModelStatics: (abstract new () => object) & ResetTokenStatics & RelationStatics & OverloadedStatics & KeyedWriteStatics & CallbackStatics & AroundStatics & CommitStatics;
1256
+ /** What a Model's `signingSecret` reads secrets from: the Worker's env, by name. */
1257
+ type SigningEnv = Readonly<Record<string, string | undefined>>;
1258
+ /** What `signingSecret` returns: a secret, or a list of them, newest first; unset ones skipped. */
1259
+ type SigningSecrets = string | readonly (string | undefined)[] | undefined;
1260
+ /** The token methods Model's records have, and the secret their tokens are signed with. */
1261
+ declare abstract class RecordTokens extends ModelStatics {
1262
+ /**
1263
+ * The secret this Model's tokens are signed with, from the Worker's env (or `process.env`
1264
+ * outside a Worker): `SECRET_KEY_BASE` unless overridden, on the app's base class. A list
1265
+ * rotates secrets: the first signs, and every one verifies. Each is at least 32 bytes.
1266
+ */
1267
+ static signingSecret(env: SigningEnv): SigningSecrets;
1268
+ /**
1269
+ * Declares tokens for a purpose, in `static {}`: `this.generatesTokenFor("emailConfirmation", {
1270
+ * expiresIn: { days: 1 }, dependsOn: (user) => user.email })`. A record makes one with
1271
+ * `generateTokenFor(purpose)`, and `findByTokenFor(purpose, token)` finds it again until it
1272
+ * expires or the value it depends on changes. Declaring a purpose again replaces it.
1273
+ */
1274
+ static generatesTokenFor<C extends AbstractModelClass>(this: C, purpose: string, options?: TokenForOptions<InstanceType<C>>): void;
1275
+ /**
1276
+ * A token for `purpose`, which its Model declares with `generatesTokenFor`, for
1277
+ * `findByTokenFor` to find this saved record by. `RecordNotSaved` for a new record.
1278
+ */
1279
+ generateTokenFor(purpose: string): Promise<string>;
1280
+ /**
1281
+ * This saved record's primary key, signed with its Model's secret, for `findSigned` to find it
1282
+ * by: for a purpose, if given, and until it expires, if given. `RecordNotSaved` for a new record.
1283
+ */
1284
+ signedId(options?: SignedIdOptions): Promise<string>;
1285
+ }
1155
1286
  /**
1156
1287
  * The built-in type a spec names: `"integer"` for `"integer"` or `{ type: "integer" }`, and
1157
1288
  * `"custom"` for a custom type, given bare or as `{ type }`.
@@ -1178,7 +1309,7 @@ type BooleanAttributeKey<R> = AttributeKeyOf<R, "boolean">;
1178
1309
  * The record methods that change one attribute, between Model and its statics: Model's records
1179
1310
  * have them, and model.ts stays the record class's own.
1180
1311
  */
1181
- declare abstract class AttributeWrites extends ModelStatics {
1312
+ declare abstract class AttributeWrites extends RecordTokens {
1182
1313
  /** Adds `by` (one by default) to a number attribute, null counting as zero; doesn't save. */
1183
1314
  increment<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number): R;
1184
1315
  /** Takes `by` (one by default) from a number attribute, null counting as zero; doesn't save. */
@@ -1186,39 +1317,39 @@ declare abstract class AttributeWrites extends ModelStatics {
1186
1317
  /** Flips a boolean attribute, null becoming `true`; doesn't save. */
1187
1318
  toggle<R extends Model>(this: R, name: BooleanAttributeKey<R>): R;
1188
1319
  /**
1189
- * Writes these attributes straight to the row, with no validation, callback or `updatedAt`,
1190
- * and leaves the record clean for them, as Rails' `update_columns`. Resolves to whether there
1191
- * was a row to write. A new record is `RecordNotSaved`.
1320
+ * Writes these attributes straight to the row, with no validation, callback or `updatedAt`, and
1321
+ * leaves the record clean for them. Resolves to whether there was a row to write. A new record is
1322
+ * `RecordNotSaved`.
1192
1323
  */
1193
1324
  updateColumns<R extends Model>(this: R, attributes: Partial<AttributesOf<R>>): Promise<boolean>;
1194
1325
  /** `updateColumns` for one attribute. */
1195
1326
  updateColumn<R extends Model, K extends AttributeKey$1<R>>(this: R, name: K, value: AttributesOf<R>[K]): Promise<boolean>;
1196
1327
  /**
1197
1328
  * Adds `by` to a number attribute in the row, as `SET x = COALESCE(x, 0) + by`, so concurrent
1198
- * writes all count, with no validation, callback or `updatedAt`; the record then holds the
1199
- * row's new value. An unsaved change to it is added too, as Rails' `increment!`. With
1200
- * `{ touch }`, the same UPDATE sets `updatedAt` (and any datetime attributes named) to now, and
1201
- * the record holds them (#50). Resolves to whether there was a row to write.
1329
+ * writes all count, with no validation, callback or `updatedAt`; the record then holds the row's
1330
+ * new value. An unsaved change to it is added too. With `{ touch }`, the same UPDATE sets
1331
+ * `updatedAt` (and any datetime attributes named) to now, and the record holds them (#50).
1332
+ * Resolves to whether there was a row to write.
1202
1333
  */
1203
1334
  incrementColumn<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number, { touch }?: CounterOptions<R>): Promise<boolean>;
1204
1335
  /** `incrementColumn`, taking `by` away. */
1205
1336
  decrementColumn<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number, { touch }?: CounterOptions<R>): Promise<boolean>;
1206
1337
  /**
1207
- * Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`), straight to
1208
- * the row, with no validation or save callback, as Rails' `touch`. Resolves to whether there
1209
- * was a row to write. Inside its Model's `noTouching` block, it writes nothing (#496).
1338
+ * Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`), straight to the
1339
+ * row, with no validation or save callback. Resolves to whether there was a row to write. Inside
1340
+ * its Model's `noTouching` block, it writes nothing (#496).
1210
1341
  */
1211
1342
  touch<R extends Model>(this: R, ...args: TouchArguments<R>): Promise<boolean>;
1212
1343
  /**
1213
1344
  * Writes a boolean attribute's flipped value straight to the row, as `updateColumn` does: no
1214
- * validation or callback, unlike Rails' `toggle!`, which runs the save callbacks.
1345
+ * validation or callback. Flip the attribute and `save()` to run the save callbacks.
1215
1346
  */
1216
1347
  toggleColumn<R extends Model>(this: R, name: BooleanAttributeKey<R>): Promise<boolean>;
1217
1348
  }
1218
1349
  /** What `updateCounters` adds to each number attribute: `{ viewCount: 1 }`. */
1219
1350
  type Counters<R> = { [K in NumberAttributeKey<R>]?: number; };
1220
1351
  /**
1221
- * What a counter's write also sets to now (#61), as Rails' `touch:`: `true` for `updatedAt`, or
1352
+ * What a counter's write also sets to now (#61): `true` for `updatedAt`, or
1222
1353
  * a datetime attribute's name, or several, set with `updatedAt`.
1223
1354
  */
1224
1355
  type Touch<R> = true | DatetimeAttributeKey<R> | readonly DatetimeAttributeKey<R>[];
@@ -1429,12 +1560,12 @@ type Permitted<C extends ModelClass, K extends string> = Partial<Pick<Attributes
1429
1560
  interface AttributeConversions<T> {
1430
1561
  /**
1431
1562
  * `input` as the attribute's JavaScript value, as assigning it would: strict, so `TypeError`
1432
- * naming the Model and attribute when it can't be. `null` stays `null`; `undefined` throws.
1563
+ * naming the Model and attribute when it can't be, and normalized (#354). `null` stays `null`; `undefined` throws.
1433
1564
  * Nothing is floored: a `Date` with milliseconds keeps them, whatever the attribute's `storage`.
1434
1565
  */
1435
1566
  readonly cast: (input: unknown) => T;
1436
1567
  /**
1437
- * `input`, cast, as D1 stores it: an ISO string, an integer for a `storage` attribute (seconds
1568
+ * `input`, cast and normalized, as D1 stores it: an ISO string, an integer for a `storage` attribute (seconds
1438
1569
  * are floored), `0` or `1`, JSON text, bytes for a `binary` attribute, or a custom type's value
1439
1570
  * as its stored type keeps it (#20). The value `column(attribute).value(input)` binds inside
1440
1571
  * an `sql` fragment; `undefined` throws as assigning it does.
@@ -1456,6 +1587,11 @@ interface AttributeConversions<T> {
1456
1587
  type FilterAttribute = string | RegExp;
1457
1588
  /** The value D1 binds. */
1458
1589
  declare function boundValue(param: unknown): unknown;
1590
+ /**
1591
+ * `S` as attribute specs: itself, or when it isn't (a spec that's a compile error), widened, so
1592
+ * `define` still gives a class to extend and the error stays on the spec.
1593
+ */
1594
+ type SpecsOrWidened<S> = S extends AttributeSpecs ? S : S & AttributeSpecs;
1459
1595
  /** An override written out: the parts of a spec it may change (not the column), any left out or `undefined` unchanged. */
1460
1596
  type SpecOverride = Partial<Omit<SpecObject, "column">>;
1461
1597
  /** One table in a generated schema: its attributes, and which is the primary key. */
@@ -1470,33 +1606,52 @@ type EnumOptions = Pick<SpecOverride, "prefix" | "suffix" | "scopes" | "instance
1470
1606
  /**
1471
1607
  * A change to a generated attribute: its type alone, or its type, nullability, default and
1472
1608
  * `generateId`, typed so `generateId` goes only with a string, and never with a default (#99); and
1473
- * an enum on a string or an integer, whose stored values are of its type (#340).
1609
+ * an enum on a string or an integer, whose stored values are of its type (#340); and `readonly`
1610
+ * on a column (#358).
1474
1611
  */
1475
- type AttributeOverride = AttributeType | AnyCustomType | (Pick<SpecOverride, "null"> & {
1612
+ type AttributeOverride = AttributeType | AnyCustomType | (Pick<SpecOverride, "null" | "readonly"> & {
1476
1613
  type?: "string";
1477
1614
  storage?: never;
1615
+ virtual?: false;
1478
1616
  /** Or `true`: a generated enum's names, with its methods; `false`: none of it (#64). */
1479
1617
  enum?: TextEnum | boolean;
1480
- } & EnumOptions & ValueSource) | (Pick<SpecOverride, "null" | "default"> & {
1618
+ /** A random token, generated for a new record (#355). */
1619
+ secureToken?: boolean | SecureTokenOptions;
1620
+ } & EnumOptions & ValueSource) | (Pick<SpecOverride, "null" | "default" | "readonly"> & {
1481
1621
  type?: "integer";
1482
1622
  generateId?: false;
1483
1623
  storage?: never;
1624
+ virtual?: false;
1484
1625
  enum: IntegerEnum;
1485
- } & EnumOptions) | (Pick<SpecOverride, "null" | "default"> & {
1626
+ } & EnumOptions) | (Pick<SpecOverride, "null" | "default" | "readonly"> & {
1486
1627
  type: Exclude<AttributeType, "string" | "datetime">;
1487
1628
  generateId?: false;
1488
1629
  storage?: never;
1489
1630
  enum?: never;
1490
- }) | (Pick<SpecOverride, "null" | "default" | "storage"> & {
1631
+ virtual?: false;
1632
+ }) | (Pick<SpecOverride, "null" | "default" | "storage" | "readonly"> & {
1491
1633
  type: "datetime";
1492
1634
  generateId?: false;
1493
1635
  enum?: never;
1494
- }) | (Pick<SpecOverride, "null" | "default"> & {
1636
+ virtual?: false;
1637
+ }) | (Pick<SpecOverride, "null" | "default" | "readonly"> & {
1495
1638
  type: AnyCustomType;
1496
1639
  generateId?: false;
1497
1640
  storage?: never;
1498
1641
  enum?: never;
1499
- });
1642
+ virtual?: false;
1643
+ }) | VirtualAttribute | AttributeAlias | SecurePasswordDeclaration;
1644
+ /**
1645
+ * An attribute that isn't a column (#356): its type, and optionally nullability and a default,
1646
+ * the only keys an attribute with no column has.
1647
+ */
1648
+ type VirtualAttribute = Pick<SpecOverride, "null" | "default"> & {
1649
+ type: AttributeType | AnyCustomType;
1650
+ virtual: true;
1651
+ generateId?: never;
1652
+ storage?: never;
1653
+ enum?: never;
1654
+ };
1500
1655
  /** The type a spec declares, written either way. */
1501
1656
  type TypeOf<S> = S extends AttributeType | AnyCustomType ? S : S extends {
1502
1657
  type: infer T;
@@ -1542,9 +1697,18 @@ type Overridden<S, O> = O extends AttributeType | AnyCustomType ? {
1542
1697
  null: O extends {
1543
1698
  null: infer N extends boolean;
1544
1699
  } ? N : NullOf<S>;
1545
- } & KeptEnumKeys<S, O> & GivenEnumKeys<O> : S;
1546
- /** A table's attributes after its overrides: changed ones merged, ignored ones gone. */
1547
- type OverriddenSpecs<A, O> = { -readonly [K in keyof A as K extends keyof O ? (O[K] extends false ? never : K) : K]: K extends keyof O ? Overridden<A[K], O[K]> : A[K]; };
1700
+ } & KeptEnumKeys<S, O> & GivenEnumKeys<O> & Pick<O, "secureToken" & keyof O> : S;
1701
+ /**
1702
+ * A table's attributes after its overrides: changed ones merged, ignored ones gone, and virtual
1703
+ * ones (#356), aliases (#509) and secure passwords' (#355) added.
1704
+ */
1705
+ type OverriddenSpecs<A, O> = ColumnSpecs<A, WithoutAliases<O>> & AliasSpecs<ColumnSpecs<A, WithoutAliases<O>>, O>;
1706
+ /** A table's attributes after the overrides that aren't aliases. */
1707
+ type ColumnSpecs<A, O> = { -readonly [K in keyof A as K extends keyof O ? (O[K] extends false ? never : K) : K]: K extends keyof O ? Overridden<A[K], O[K]> : A[K]; } & VirtualSpecs<A, O> & SecurePasswordSpecs<O>;
1708
+ /** The virtual attributes an override declares (#356): those not in the table, as declared. */
1709
+ type VirtualSpecs<A, O> = { -readonly [K in keyof O as K extends keyof A ? never : O[K] extends {
1710
+ virtual: true;
1711
+ } ? K : never]: O[K]; };
1548
1712
  /** `S` as attribute specs, without widening it to an index signature (which would type any name). */
1549
1713
  type AsSpecs<S> = S extends AttributeSpecs ? S : never;
1550
1714
  /**
@@ -1569,6 +1733,16 @@ interface DatabaseSchema {
1569
1733
  }
1570
1734
  /** `{ attribute: [before, after] }` */
1571
1735
  type Changes = Record<string, [before: unknown, after: unknown]>;
1736
+ /** The read-only mark Model's records have. */
1737
+ declare abstract class ReadonlyMarks extends AttributeWrites {
1738
+ /**
1739
+ * Marks the record read-only: saving, destroying, touching it or writing its columns throws
1740
+ * `ReadonlyRecord`, sending nothing. It can still be changed in memory and reloaded.
1741
+ */
1742
+ markReadonly<R extends Model>(this: R): R;
1743
+ /** Whether it's read-only: marked by `markReadonly()`, or loaded through a `readonly()` Relation. */
1744
+ isReadonly(this: Model): boolean;
1745
+ }
1572
1746
  /** Type-only brand on a scope static (`static newest = this.scope(…)`); never set at runtime. */
1573
1747
  declare const scopeBrand: unique symbol;
1574
1748
  /**
@@ -1641,15 +1815,15 @@ type AttributesOf<M> = M extends {
1641
1815
  readonly [attributeTypes]?: infer A;
1642
1816
  } ? A : never;
1643
1817
  /**
1644
- * The library's base class, as Rails' `ActiveRecord::Base`: an app's base class extends it, and
1818
+ * The library's base class: an app's base class extends it, and
1645
1819
  * methods, statics, callbacks and scopes declared there are shared by every Model built on it.
1646
1820
  * It has no table, so it's never used as a Model itself.
1647
1821
  */
1648
- declare class Model extends AttributeWrites {
1822
+ declare class Model extends ReadonlyMarks {
1649
1823
  /** The table's name: inferred from `modelName` (`BlogPost` → `blog_posts`) unless set. */
1650
1824
  static table: string;
1651
1825
  /**
1652
- * The Model's name, as Rails' `model_name`: its class name unless set (`static modelName =
1826
+ * The Model's name: its class name unless set (`static modelName =
1653
1827
  * "BlogPost"`), so names inferred from it survive a bundler that renames classes.
1654
1828
  */
1655
1829
  static modelName: string;
@@ -1679,10 +1853,11 @@ declare class Model extends AttributeWrites {
1679
1853
  */
1680
1854
  static onQuery: QueryListener | undefined;
1681
1855
  /**
1682
- * Attributes whose values listeners and errors show as "[FILTERED]", as Rails'
1683
- * `filter_attributes`: an attribute whose snake_case name holds a string entry, lowercased
1684
- * or read in snake_case (`"apiKey"` as `api_key`), or matches a RegExp. Rails' defaults;
1685
- * replace them on the app's base class (#83).
1856
+ * Attributes whose values listeners and errors show as "[FILTERED]": an attribute
1857
+ * whose snake_case name holds a string entry, lowercased or read in snake_case (`"apiKey"` as
1858
+ * `api_key`), or matches a RegExp. The defaults cover common secret and personal names
1859
+ * (`password`, `token`, `email`, …); replace them on the app's base class (#83). A secure
1860
+ * password's attributes and digest, and a secure token, are filtered whatever it says (#355).
1686
1861
  */
1687
1862
  static filterAttributes: readonly FilterAttribute[];
1688
1863
  /**
@@ -1692,7 +1867,7 @@ declare class Model extends AttributeWrites {
1692
1867
  static hiddenAttributes: readonly string[];
1693
1868
  /**
1694
1869
  * Runs `fn` with this Model's records not touched, nor those of the Models extending it
1695
- * (`Model.noTouching` covers every Model), as Rails' `no_touching`: a belongsTo's `touch`
1870
+ * (`Model.noTouching` covers every Model): a belongsTo's `touch`
1696
1871
  * leaves them alone, and their `touch()` writes nothing. Resolves to what `fn` returns.
1697
1872
  */
1698
1873
  static noTouching<R>(fn: () => R | Promise<R>): Promise<R>;
@@ -1716,51 +1891,70 @@ declare class Model extends AttributeWrites {
1716
1891
  * `class Visit extends Model.define({ path: "string" }) {}`. It's built on the class it's
1717
1892
  * called on, so a Model made with `ApplicationRecord.define({...})` shares the app's base.
1718
1893
  */
1719
- static define<B extends BaseClass, const A extends AttributeSpecs>(this: B, specs: A & ExactSpecs<A>): ModelBaseFor<A, B>;
1894
+ static define<B extends BaseClass, const A extends DeclaredAttributes>(this: B, specs: A & ExactSpecs<A>): ModelBaseFor<SpecsOrWidened<DefinedSpecs<WithSecurePasswords<A>>>, B>;
1720
1895
  /**
1721
- * Declares a scope, as Rails' `scope :active, -> { … }`: `static active = this.scope((q) =>
1896
+ * Declares a scope: `static active = this.scope((q) =>
1722
1897
  * q.where({ isActive: true }))`. It's a static (`User.active()`) and a Relation method
1723
1898
  * (`User.where(…).active()`), inherited like any static. Inside it, `q` has every Relation
1724
1899
  * method, but not the Model's other scopes (their types would refer to themselves).
1725
1900
  */
1726
1901
  static scope<C extends AbstractModelClass, A extends unknown[]>(this: C, body: (q: Relation<InstanceType<C>>, ...args: A) => Relation<InstanceType<C>>): ScopeStatic<A>;
1727
1902
  /**
1728
- * All of this Model's records, as Rails' `Product.all`: a Relation on the current database
1903
+ * All of this Model's records: a Relation on the current database
1729
1904
  * (the request's, set with `withDatabase`, or else the binding in its base class's schema).
1730
1905
  */
1731
1906
  static all<C extends QueryableClass>(this: C): Scoped<InstanceType<C>, ScopesOf<C>>;
1732
1907
  /**
1733
1908
  * Only the named attributes of untrusted input (a JSON body, `FormData` or
1734
- * `URLSearchParams`), as Rails' `params.permit`:
1909
+ * `URLSearchParams`):
1735
1910
  * `User.create(User.permit(await request.json(), "email", "name"))`. Every other key is
1736
1911
  * dropped, and each value is cast as assigning it would be.
1737
1912
  */
1738
1913
  static permit<C extends QueryableClass, K extends AttributeKey<InstanceType<C>>>(this: C, input: unknown, ...names: K[]): Permitted<C, K>;
1739
1914
  /**
1740
- * An enum's names, each with the value it's stored as, frozen (#340), as Rails' `Post.statuses`:
1915
+ * The record its other attributes find, if each secure password given is its own (#355):
1916
+ * `User.authenticateBy({ email, password })`, or null. When none is found, the password is
1917
+ * hashed anyway, so how long it takes doesn't say whether one exists. Without a secure
1918
+ * password, or an attribute to find the record by, it throws `TypeError`.
1919
+ */
1920
+ static authenticateBy<C extends QueryableClass>(this: C, attributes: AuthenticateByAttributes<SpecsOf<InstanceType<C>>, AttributesOf<InstanceType<C>>>): Promise<InstanceType<C> | null>;
1921
+ /**
1922
+ * An enum's names, each with the value it's stored as, frozen (#340):
1741
1923
  * `Post.enumValues("status")` is `{ draft: "draft", published: "published" }`.
1742
1924
  */
1743
1925
  static enumValues<C extends QueryableClass, K extends EnumAttributeKey<InstanceType<C>>>(this: C, attribute: K): EnumMapping<EnumOf<InstanceType<C>, K>>;
1744
1926
  /**
1745
- * An attribute's conversions, for SQL d1-record doesn't write, as Rails' `type_for_attribute`:
1927
+ * An attribute's conversions, for SQL the library doesn't write:
1746
1928
  * `Post.typeForAttribute("publishedAt").serialize(date)` is what `publishedAt` stores a `Date`
1747
- * as, whatever its `storage`; `cast` and `deserialize` go the other way.
1929
+ * as, whatever its `storage`; `cast` and `deserialize` go the other way. `cast` and `serialize`
1930
+ * normalize the value, as assigning it does (#354).
1748
1931
  */
1749
1932
  static typeForAttribute<C extends QueryableClass, K extends AttributeKey<InstanceType<C>>>(this: C, name: K): AttributeConversions<AttributesOf<InstanceType<C>>[K]>;
1750
1933
  /**
1751
- * Declares a default scope (#25), as Rails' `default_scope { … }`, in `static {}`:
1934
+ * `value` as assigning it to `name` keeps it: cast, then normalized (#354), so
1935
+ * `Account.normalizeValueFor("email", " Jane@Example.com")` is `"jane@example.com"`.
1936
+ */
1937
+ static normalizeValueFor<C extends QueryableClass, K extends AttributeKey<InstanceType<C>>>(this: C, name: K, value: unknown): AttributesOf<InstanceType<C>>[K];
1938
+ /**
1939
+ * Declares a default scope (#25), in `static {}`:
1752
1940
  * `this.defaultScope((q) => q.where({ deletedAt: null }))`. Every query on the Model, its
1753
1941
  * associations' included, starts from it, and new records take its equality values. Several
1754
1942
  * are applied in order; a subclass adds to its parent's. `unscoped()` leaves them out.
1755
1943
  */
1756
1944
  static defaultScope<C extends AbstractModelClass>(this: C, body: (q: Relation<InstanceType<C>>) => Relation<InstanceType<C>>): void;
1757
1945
  /**
1758
- * All of this Model's records without its default scopes (#25), as Rails' `Product.unscoped`,
1946
+ * All of this Model's records without its default scopes (#25),
1759
1947
  * on the current database. Only a static: a Relation keeps what it has.
1760
1948
  */
1761
1949
  static unscoped<C extends QueryableClass>(this: C): Scoped<InstanceType<C>, ScopesOf<C>>;
1762
1950
  /** Declares a validation, e.g. `this.validates("email", { presence: true })` in `static {}`. */
1763
1951
  static validates<C extends AbstractModelClass>(this: C, attribute: keyof AttributesOf<InstanceType<C>> & string, options: ValidationOptions<InstanceType<C>, ContextOf<C>>): void;
1952
+ /**
1953
+ * Declares a normalization (#354), e.g. `this.normalizes("email", { with: (email) =>
1954
+ * email.trim().toLowerCase() })` in `static {}`: each value assigned to the attribute, once
1955
+ * cast, becomes what `with` returns for it.
1956
+ */
1957
+ static normalizes<C extends AbstractModelClass, K extends AttributeKey<InstanceType<C>>>(this: C, attribute: K, options: NormalizeOptions<AttributesOf<InstanceType<C>>[K]>): void;
1764
1958
  /**
1765
1959
  * Declares that an association's records must be valid too, e.g.
1766
1960
  * `this.validatesAssociated("posts")` in `static {}`: an invalid one adds "is invalid" to the
@@ -1790,8 +1984,7 @@ declare class Model extends AttributeWrites {
1790
1984
  /** Whether the association is loaded: preloaded or already read, for the key held now. */
1791
1985
  isLoaded<K extends AssociationName<this>>(name: K): boolean;
1792
1986
  /**
1793
- * Loads the association again, replacing what's cached, and returns it: Rails'
1794
- * `reload_author`, or `user.posts.reload` for a hasMany.
1987
+ * Loads the association again, replacing what's cached, and returns its record or records.
1795
1988
  */
1796
1989
  reloadAssociation<K extends AssociationName<this>>(name: K): Promise<LoadedValue<this[K]>>;
1797
1990
  /** Why a callback last refused a save or destroy (`abort(reason)`); never copied into `errors`. */
@@ -1812,11 +2005,10 @@ declare class Model extends AttributeWrites {
1812
2005
  changes(): Changes;
1813
2006
  /** The changes the last successful save wrote; use it in after-save callbacks. */
1814
2007
  savedChanges(): Changes;
1815
- /** The attribute's value before its unsaved change, as stored (Rails' `attribute_was`). */
2008
+ /** The attribute's value before its unsaved change, as stored. */
1816
2009
  attributeWas<R extends Model, K extends AttributeKey<R>>(this: R, name: K): AttributesOf<R>[K];
1817
2010
  /**
1818
- * Whether the attribute has an unsaved change, optionally `from` and/or `to` given values
1819
- * (Rails' `attribute_changed?(name, from:, to:)`).
2011
+ * Whether the attribute has an unsaved change, optionally `from` and/or `to` given values.
1820
2012
  */
1821
2013
  isAttributeChanged<R extends Model, K extends AttributeKey<R>>(this: R, name: K, options?: ChangeOptions<AttributesOf<R>[K]>): boolean;
1822
2014
  /** Whether saving now would write a change to the attribute (for before-callbacks). */
@@ -1827,8 +2019,13 @@ declare class Model extends AttributeWrites {
1827
2019
  hasSavedChangeTo<R extends Model, K extends AttributeKey<R>>(this: R, name: K, options?: ChangeOptions<AttributesOf<R>[K]>): boolean;
1828
2020
  /** The attribute's value before the last save (its current stored value, if that didn't change it). */
1829
2021
  attributeBeforeLastSave<R extends Model, K extends AttributeKey<R>>(this: R, name: K): AttributesOf<R>[K];
1830
- /** Undoes unsaved changes to these attributes (all of them by default), as Rails' `restore_attributes`. */
2022
+ /** Undoes unsaved changes to these attributes (all of them by default). */
1831
2023
  restoreAttributes<R extends Model>(this: R, names?: readonly AttributeKey<R>[]): void;
2024
+ /**
2025
+ * Normalizes an attribute's value as assigning it again would (#354): for a value loaded from
2026
+ * a row stored before its normalization was declared, which loading leaves as it was.
2027
+ */
2028
+ normalizeAttribute<R extends Model>(this: R, name: AttributeKey<R>): void;
1832
2029
  /**
1833
2030
  * Inserts a new record or updates a persisted one; `false` if it's invalid, a callback aborted,
1834
2031
  * or a record it destroys refused (#37). `context` validates it in that context (`"signup"`), as
@@ -1859,7 +2056,7 @@ declare class Model extends AttributeWrites {
1859
2056
  reload(): Promise<this>;
1860
2057
  /**
1861
2058
  * Marks the record to be destroyed when its owner is saved, through an association declared
1862
- * `autosave: true`, as Rails' `mark_for_destruction` does. Nothing is written until then, and
2059
+ * `autosave: true`. Nothing is written until then, and
1863
2060
  * `reload()` clears the mark.
1864
2061
  */
1865
2062
  markForDestruction(): void;
@@ -1868,7 +2065,7 @@ declare class Model extends AttributeWrites {
1868
2065
  /** Not yet saved: built, or created but not persisted. */
1869
2066
  isNewRecord(): boolean;
1870
2067
  /**
1871
- * Whether its last save created it, as Rails' `previously_new_record?`: true in a create's
2068
+ * Whether its last save created it: true in a create's
1872
2069
  * after-callbacks and after it, false once it's saved again or destroyed.
1873
2070
  */
1874
2071
  isPreviouslyNewRecord(): boolean;
@@ -1877,7 +2074,7 @@ declare class Model extends AttributeWrites {
1877
2074
  /** Deleted by this instance; a read-only snapshot of the row. */
1878
2075
  isDestroyed(): boolean;
1879
2076
  /**
1880
- * Whether the record has the attribute `name` loaded (Rails' `has_attribute?`): `false` for one
2077
+ * Whether the record has the attribute `name` loaded: `false` for one
1881
2078
  * `select(...)` left out, whose read throws `MissingAttribute`, and for a name the Model doesn't
1882
2079
  * declare. A callback that runs for partial records, such as `afterFind`, checks it first.
1883
2080
  */
@@ -1888,7 +2085,9 @@ declare class Model extends AttributeWrites {
1888
2085
  [inspectCustom](depth: number, options: InspectOptions, inspect: Inspect): string;
1889
2086
  /**
1890
2087
  * The loaded attributes as JSON-ready values (dates as ISO strings), without the Model's
1891
- * `hiddenAttributes`, for `Response.json(record)`.
2088
+ * `hiddenAttributes`, the virtual attributes its `confirmation` rules read, or its secrets: each
2089
+ * secure password, its confirmation, challenge and digest, and each secure token (#355), for
2090
+ * `Response.json(record)`.
1892
2091
  */
1893
2092
  toJSON(): Record<string, unknown>;
1894
2093
  }
@@ -1906,7 +2105,7 @@ type QueryableClass<M extends Model = Model> = ModelClass<M & {
1906
2105
  * What a generated declaration adds to a Model's records: its table's attributes `A`, with the
1907
2106
  * Model's `static attributes` overrides `O` applied, typed, and its enums' methods (#340).
1908
2107
  */
1909
- type TableAttributes<A extends AttributeSpecs, O = {}> = AttributeProperties<AsSpecs<OverriddenSpecs<A, O>>> & EnumMethods<OverriddenSpecs<A, O>> & {
2108
+ type TableAttributes<A extends AttributeSpecs, O = {}> = AttributeProperties<AsSpecs<OverriddenSpecs<A, O>>> & EnumMethods<OverriddenSpecs<A, O>> & SecurePasswordMethods<OverriddenSpecs<A, O>> & SecureTokenMethods<OverriddenSpecs<A, O>> & {
1910
2109
  readonly [attributeSpecs]: OverriddenSpecs<A, O>;
1911
2110
  readonly [attributeTypes]: AttributeProperties<AsSpecs<OverriddenSpecs<A, O>>>;
1912
2111
  };
@@ -1921,7 +2120,7 @@ type BaseClass = abstract new () => Model;
1921
2120
  * The base class `Model.define({...})` makes: records with the attributes `A`, built on `B` (the
1922
2121
  * library's base, or an app's), so they have its methods and statics too.
1923
2122
  */
1924
- type ModelBaseFor<A extends AttributeSpecs, B extends BaseClass = typeof Model> = (new () => InstanceType<B> & AttributeProperties<A> & EnumMethods<A> & {
2123
+ type ModelBaseFor<A extends AttributeSpecs, B extends BaseClass = typeof Model> = (new () => InstanceType<B> & AttributeProperties<A> & EnumMethods<A> & SecurePasswordMethods<A> & SecureTokenMethods<A> & {
1925
2124
  readonly [attributeTypes]: AttributeProperties<A>;
1926
2125
  readonly [attributeSpecs]: A;
1927
2126
  }) & Omit<B, "prototype"> & EnumStatics<A>;
@@ -2040,6 +2239,14 @@ interface ValidationOptions<R = never, X extends string = ValidationContext> {
2040
2239
  acceptance?: boolean | {
2041
2240
  accept: readonly unknown[];
2042
2241
  };
2242
+ /**
2243
+ * The value equals the virtual attribute named after it with `Confirmation`
2244
+ * (`emailConfirmation` for `email`), which must be declared; the failure is on that attribute,
2245
+ * "doesn't match Email". A null confirmation passes. `caseSensitive: false` ignores case.
2246
+ */
2247
+ confirmation?: boolean | {
2248
+ caseSensitive?: boolean;
2249
+ };
2043
2250
  /**
2044
2251
  * No other row has this value (checked in D1 through the record's Database). `scope` adds
2045
2252
  * attributes that must match too; `caseSensitive: false` compares with `lower()` (ASCII only).
@@ -2072,4 +2279,4 @@ interface ValidationOptions<R = never, X extends string = ValidationContext> {
2072
2279
  }
2073
2280
  /** The options of a `validatesAssociated(association, options)` call. */
2074
2281
  type AssociatedValidationOptions<R = never, X extends string = ValidationContext> = Pick<ValidationOptions<R, X>, "message" | "strict" | "if" | "unless" | "on" | "exceptOn">;
2075
- export { ReturnedRow as $, databaseExecutor as A, QuerySql as At, ValidationContext as B, ComparisonBound as Bt, QueryEvent as C, gt as Ct, SchemaAdapter as D, QueryPart as Dt, ConstraintFailure as E, lte as Et, RecordStatement as F, ColumnValue as Ft, Scoped as G, Relation as H, DatetimeAttributeKey as I, SafeSql as It, Page as J, IterationOptions as K, NumberAttributeKey as L, column as Lt, BatchResults as M, valueMark as Mt, batch as N, Attribute as Nt, AnyDatabase as O, InOrderOfOptions as Ot, Batch as P, ColumnReference as Pt, Init as Q, SaveOptions as R, sql$1 as Rt, DatabaseExecutor as S, between as St, Adapter as T, lt as Tt, Scope as U, ValidationContexts as V, ComparisonOptions as Vt, ScopeMethods as W, TouchOptions as X, PageOptions as Y, GroupedRelation as Z, TableSchema as _, InsertOptions as _t, ValidationOptions as a, BelongsTo as at, boundValue as b, UpsertOptions as bt, AttributeErrorMessages as c, HasManyDependent as ct, RestrictMessages as d, HasOneDependent as dt, Statement as et, Model as f, HasOneThrough as ft, DatabaseSchema as g, Conditions as gt, TableAttributes as h, ThroughOptions as ht, UniquenessOptions as i, AssociationOptions as it, BatchEntry as j, Dialect as jt, RelationsFor as k, CompiledSql as kt, ErrorMessage as l, HasManyThrough as lt, ScopeStatic as m, ThroughDependent as mt, LengthOptions as n, Driver as nt, Errors as o, HasMany as ot, ModelClass as p, PolymorphicBelongsTo as pt, CountlessPage as q, NumericalityOptions as r, StatementResult as rt, ValidationError as s, HasManyCollection as st, AssociatedValidationOptions as t, WriteResult as tt, ErrorMessages as u, HasOne as ut, TableSchemas as v, OrderSpec as vt, QueryListener as w, gte as wt, AttributeConversions as x, Comparison as xt, FilterAttribute as y, Returning as yt, ValidationCallbackOptions as z, Comparable as zt };
2282
+ export { TouchOptions as $, databaseExecutor as A, QueryPart as At, SaveOptions as B, ColumnValue as Bt, QueryEvent as C, UpsertOptions as Ct, SchemaAdapter as D, gte as Dt, ConstraintFailure as E, gt as Et, RecordStatement as F, QuerySql as Ft, Relation as G, ComparisonBound as Gt, ValidationContext as H, column as Ht, DatetimeAttributeKey as I, Dialect as It, Scoped as J, Scope as K, ComparisonOptions as Kt, NumberAttributeKey as L, valueMark as Lt, BatchResults as M, SignedIdOptions as Mt, batch as N, InOrderOfOptions as Nt, AnyDatabase as O, lt as Ot, Batch as P, CompiledSql as Pt, PageOptions as Q, SigningEnv as R, Attribute as Rt, DatabaseExecutor as S, Returning as St, Adapter as T, between as Tt, ValidationContexts as U, sql$1 as Ut, ValidationCallbackOptions as V, SafeSql as Vt, TokenForOptions as W, Comparable as Wt, CountlessPage as X, IterationOptions as Y, Page as Z, TableSchema as _, ThroughDependent as _t, ValidationOptions as a, Driver as at, boundValue as b, InsertOptions as bt, AttributeErrorMessages as c, BelongsTo as ct, RestrictMessages as d, HasManyDependent as dt, GroupedRelation as et, Model as f, HasManyThrough as ft, DatabaseSchema as g, PolymorphicBelongsTo as gt, TableAttributes as h, HasOneThrough as ht, UniquenessOptions as i, WriteResult as it, BatchEntry as j, FindSignedOptions as jt, RelationsFor as k, lte as kt, ErrorMessage as l, HasMany as lt, ScopeStatic as m, HasOneDependent as mt, LengthOptions as n, ReturnedRow as nt, Errors as o, StatementResult as ot, ModelClass as p, HasOne as pt, ScopeMethods as q, NumericalityOptions as r, Statement as rt, ValidationError as s, AssociationOptions as st, AssociatedValidationOptions as t, Init as tt, ErrorMessages as u, HasManyCollection as ut, TableSchemas as v, ThroughOptions as vt, QueryListener as w, Comparison as wt, AttributeConversions as x, OrderSpec as xt, FilterAttribute as y, Conditions as yt, SigningSecrets as z, ColumnReference as zt };