@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.
@@ -0,0 +1,378 @@
1
+ /** An alias in `static attributes` or `define`: `title: { aliasOf: "name" }` reads as "title is an alias of name". */
2
+ interface AttributeAlias {
3
+ readonly aliasOf: string;
4
+ }
5
+ /** The aliases among a Model's declared attributes `O`, each typed as the attribute it names in `S`. */
6
+ type AliasSpecs<S, O> = { -readonly [K in keyof O as O[K] extends {
7
+ aliasOf: keyof S;
8
+ } ? K : never]: O[K] extends {
9
+ aliasOf: infer T extends keyof S;
10
+ } ? S[T] : never; };
11
+ /** `define`'s attributes `A`, with each alias typed as the attribute it names; `A` itself without one. */
12
+ type DefinedSpecs<A> = [AliasNames<A>] extends [never] ? A : WithoutAliases<A> & AliasSpecs<WithoutAliases<A>, A>;
13
+ /** The names of the aliases among `A`. */
14
+ type AliasNames<A> = { [K in keyof A]: A[K] extends {
15
+ aliasOf: string;
16
+ } ? K : never; }[keyof A];
17
+ /** The declared attributes `O` without their aliases. */
18
+ type WithoutAliases<O> = { [K in keyof O as O[K] extends {
19
+ aliasOf: string;
20
+ } ? never : K]: O[K]; };
21
+ /**
22
+ * A type an app defines: what its values are, and how each is kept as a value of the built-in
23
+ * type it's stored as. Made by `defineType`.
24
+ */
25
+ interface CustomType<T = unknown, S extends AttributeType = AttributeType> {
26
+ /** The built-in type its values are stored as: `"integer"` for money kept as cents. */
27
+ readonly storedAs: S;
28
+ /**
29
+ * An assigned value or a condition's as the type's value. It throws for one it can't hold:
30
+ * assigning that value throws `TypeError`, with this error as its `cause`, and a condition
31
+ * matches nothing. Never called with `null`.
32
+ */
33
+ cast(input: unknown): T;
34
+ /** A value as the stored type's value: `money.cents`. Never called with `null`. */
35
+ serialize(value: T): BuiltInValue<S>;
36
+ /** A stored type's value, read as the stored type reads a cell, as the type's value. */
37
+ deserialize(stored: BuiltInValue<S>): T;
38
+ }
39
+ /** Any custom type, whatever its values: what a spec takes. */
40
+ type AnyCustomType = CustomType<any, AttributeType>;
41
+ /**
42
+ * Defines an attribute type, used in a spec as a type name is: `price: money`, or
43
+ * `{ type: money, null: false }`. Its values are kept as `storedAs` keeps its own, so they're
44
+ * read strictly, compared and ordered as that type's are.
45
+ */
46
+ declare function defineType<T, S extends AttributeType>(type: CustomType<T, S>): CustomType<T, S>;
47
+ /** A length of time: `{ minutes: 15 }`, `{ days: 1, hours: 12 }`. */
48
+ interface Duration {
49
+ readonly seconds?: number;
50
+ readonly minutes?: number;
51
+ readonly hours?: number;
52
+ readonly days?: number;
53
+ }
54
+ /**
55
+ * What hashes a secure password and verifies it against a digest: the default, or an app's own
56
+ * (bcrypt, to read digests another app made).
57
+ */
58
+ interface PasswordAlgorithm {
59
+ /** A digest of `password`, salted, that `verify` can check it against. */
60
+ hash(password: string): Promise<string>;
61
+ /** Whether `password` is the one `digest` was made from. */
62
+ verify(password: string, digest: string): Promise<boolean>;
63
+ /** The most bytes a password may be, in UTF-8; without it, any length. */
64
+ readonly maxBytes?: number;
65
+ }
66
+ /** `securePassword`'s options: the algorithm that hashes the password, and its validations. */
67
+ interface SecurePasswordOptions {
68
+ /** What hashes the password and verifies it: PBKDF2-SHA256 unless given. */
69
+ readonly algorithm?: PasswordAlgorithm;
70
+ /** `false` leaves out the validations a secure password adds. */
71
+ readonly validations?: boolean;
72
+ /**
73
+ * Its reset token (`passwordResetToken()`), which lasts 15 minutes unless `expiresIn` says
74
+ * otherwise, and stops finding its record once the password changes; `false` leaves it out.
75
+ */
76
+ readonly resetToken?: boolean | {
77
+ readonly expiresIn?: Duration;
78
+ };
79
+ }
80
+ /** A secure password in `static attributes` or `define`: `password: { securePassword: true }`. */
81
+ interface SecurePasswordDeclaration {
82
+ readonly securePassword: true | SecurePasswordOptions;
83
+ }
84
+ /** The spec a secure password's own attribute gets: a virtual string that says it's one, with its options. */
85
+ type PasswordSpec<D> = {
86
+ type: "string";
87
+ virtual: true;
88
+ securePassword: D extends {
89
+ securePassword: infer P;
90
+ } ? P : true;
91
+ };
92
+ /** The spec of its confirmation and its challenge: virtual strings. */
93
+ type CompanionSpec = {
94
+ type: "string";
95
+ virtual: true;
96
+ };
97
+ /** The names among `O` that declare a secure password. */
98
+ type DeclaredNames<O> = { [K in keyof O]: O[K] extends SecurePasswordDeclaration ? K & string : never; }[keyof O];
99
+ /**
100
+ * The attributes the secure passwords among the declared attributes `O` add: each one, its
101
+ * confirmation and its challenge, virtual strings.
102
+ */
103
+ type SecurePasswordSpecs<O> = { -readonly [K in DeclaredNames<O>]: PasswordSpec<O[K]>; } & { -readonly [K in DeclaredNames<O> as `${K}Confirmation` | `${K}Challenge`]: CompanionSpec; };
104
+ /** The declared attributes `O`, each secure password in it replaced by the attributes it adds. */
105
+ type WithSecurePasswords<O> = [DeclaredNames<O>] extends [never] ? O : { [K in keyof O as K extends DeclaredNames<O> ? never : K]: O[K]; } & SecurePasswordSpecs<O>;
106
+ /** The names among the attribute specs `A` that are secure passwords. */
107
+ type PasswordNames<A> = { [K in keyof A]: A[K] extends {
108
+ securePassword: true | object;
109
+ } ? K & string : never; }[keyof A];
110
+ /**
111
+ * What `authenticateBy` takes for a Model whose attribute specs are `S` and attributes `A`: any of
112
+ * its attributes, or `never` for a Model without a secure password, so calling it is a compile
113
+ * error.
114
+ */
115
+ type AuthenticateByAttributes<S, A> = [PasswordNames<S>] extends [never] ? never : Partial<A>;
116
+ /** Checks a password against its digest: the record, or `false` when it isn't the one. */
117
+ type Authenticate = <R>(this: R, password: string) => Promise<R | false>;
118
+ /** The names among the attribute specs `A` that are secure passwords with a reset token. */
119
+ type ResettableNames<A> = { [K in keyof A]: A[K] extends {
120
+ securePassword: {
121
+ resetToken: false;
122
+ };
123
+ } ? never : A[K] extends {
124
+ securePassword: true | object;
125
+ } ? K & string : never; }[keyof A];
126
+ /**
127
+ * What the secure passwords among the specs `A` add to a record: `authenticatePassword` for
128
+ * `password`, `authenticateRecoveryPassword` for `recoveryPassword`, and `authenticate`, for
129
+ * `password` alone; and each reset token's, `passwordResetToken()` (#517).
130
+ */
131
+ type SecurePasswordMethods<A> = { [K in PasswordNames<A> as `authenticate${Capitalize<K>}`]: Authenticate; } & ("password" extends PasswordNames<A> ? {
132
+ authenticate: Authenticate;
133
+ } : {}) & { [K in ResettableNames<A> as `${K}ResetToken`]: () => Promise<string>; };
134
+ /**
135
+ * What `findByPasswordResetToken` takes for a Model whose attribute specs are `S`: a token, or
136
+ * `never` for a Model whose `password` has no reset token, so calling it is a compile error.
137
+ */
138
+ type PasswordResetTokenArgument<S> = "password" extends ResettableNames<S> ? unknown : never;
139
+ /** `secureToken`'s options: how long the token is, a prefix, and when it's generated. */
140
+ interface SecureTokenOptions {
141
+ /** Its characters, after any prefix: 24 unless given, and at least 24. */
142
+ readonly length?: number;
143
+ /** Text before the token: `true` for the column's name and `_` (`auth_token_…`), or its own. */
144
+ readonly prefix?: true | string;
145
+ /** When a new record without one gets it: as it's built (the default), or as it's created. */
146
+ readonly on?: "initialize" | "create";
147
+ }
148
+ /**
149
+ * A random base58 token of `length` characters (24 unless given), from `crypto.getRandomValues`,
150
+ * each character equally likely. Nothing checks it's unique: a unique index does that.
151
+ */
152
+ declare function generateSecureToken(length?: number): string;
153
+ /** The names among the attribute specs `A` that are secure tokens. */
154
+ type TokenNames<A> = { [K in keyof A]: A[K] extends {
155
+ secureToken: true | object;
156
+ } ? K & string : never; }[keyof A];
157
+ /**
158
+ * What the secure tokens among the specs `A` add to a record: `regenerateAuthToken()`, resolving
159
+ * to `false` when the record is invalid or a callback aborts, and its `OrThrow`.
160
+ */
161
+ type SecureTokenMethods<A> = { [K in TokenNames<A> as `regenerate${Capitalize<K>}`]: () => Promise<boolean>; } & { [K in TokenNames<A> as `regenerate${Capitalize<K>}OrThrow`]: () => Promise<true>; };
162
+ /**
163
+ * An enum's values: its names, each stored as itself (a `string` attribute's only), or each name
164
+ * with the value it's stored as (`{ draft: 0, published: 1 }`).
165
+ */
166
+ type EnumValues = readonly string[] | {
167
+ readonly [name: string]: string | number;
168
+ };
169
+ /** A `string` attribute's enum: names stored as themselves, or each with the text it's stored as. */
170
+ type TextEnum = readonly string[] | {
171
+ readonly [name: string]: string;
172
+ };
173
+ /** An `integer` attribute's enum: each name with the integer it's stored as. */
174
+ type IntegerEnum = {
175
+ readonly [name: string]: number;
176
+ };
177
+ /** The names an enum's values give its attribute: `"draft" | "published"`. */
178
+ type EnumNames<E> = E extends readonly (infer N extends string)[] ? N : keyof E & string;
179
+ /** An enum's names, each with the value it's stored as, as `enumValues` gives them. */
180
+ type EnumMapping<E> = E extends readonly string[] ? { readonly [N in E[number]]: N; } : Readonly<E>;
181
+ /** A datetime held in an `INTEGER` column as seconds or milliseconds since 1970. */
182
+ declare const epochStorages: readonly ["unixSeconds", "unixMilliseconds"];
183
+ type EpochStorage = (typeof epochStorages)[number];
184
+ type AttributeType = "string" | "integer" | "real" | "decimal" | "boolean" | "datetime" | "date" | "time" | "json" | "binary";
185
+ /** An attribute's spec written out: its type, and optionally nullability, column and default. */
186
+ interface SpecObject {
187
+ /** A built-in type's name, or a type `defineType` made (#20). */
188
+ type: AttributeType | AnyCustomType;
189
+ null?: boolean;
190
+ column?: string;
191
+ /** A `datetime` held as a Unix epoch integer, as Drizzle's timestamp modes write it (#73). */
192
+ storage?: EpochStorage;
193
+ /** A decimal's most digits in all, as `NUMERIC(10, 2)`'s 10; without a scale, its scale is 0 (#398). */
194
+ precision?: number;
195
+ /** A decimal's digits after the point, as `NUMERIC(10, 2)`'s 2: a cast value is rounded to them (#398). */
196
+ scale?: number;
197
+ /** Evaluated at `build()`, e.g. `() => new Date()`. */
198
+ default?: () => unknown;
199
+ /**
200
+ * Made by the Model's `generateId` when not given, where a default would run: an
201
+ * app-generated key (#99). Generated ids are strings, so only a string attribute has one.
202
+ */
203
+ generateId?: boolean;
204
+ /** Its only values, by name, and what each is stored as (#340). */
205
+ enum?: EnumValues;
206
+ /** A word before each enum name in its methods' names: the attribute's name for `true` (#340). */
207
+ prefix?: boolean | string;
208
+ /** A word after each enum name in its methods' names: the attribute's name for `true` (#340). */
209
+ suffix?: boolean | string;
210
+ /** `false` to give the Model no scope for each enum name (#340). */
211
+ scopes?: boolean;
212
+ /** `false` to give records no predicate or `saveAs…` setter for each enum name (#340). */
213
+ instanceMethods?: boolean;
214
+ /**
215
+ * Validates an enum's value instead of refusing an unknown one when it's assigned: a
216
+ * record holding another value, or null unless `allowNull`, is invalid.
217
+ */
218
+ validate?: EnumValidation;
219
+ /**
220
+ * An attribute that isn't a column (#356): cast and tracked like one, never read from a row or
221
+ * written to one, and refused in queries.
222
+ */
223
+ virtual?: boolean;
224
+ /**
225
+ * A virtual password kept as its digest, in the column of the attribute named for it with
226
+ * `Digest` (#355): `true`, or its options.
227
+ */
228
+ securePassword?: true | SecurePasswordOptions;
229
+ /**
230
+ * A random token, generated for a new record that has none, and regenerated by
231
+ * `regenerate…()` (#355): `true`, or its options. Only a string has one.
232
+ */
233
+ secureToken?: boolean | SecureTokenOptions;
234
+ /**
235
+ * Written when a record is created, and refused once it's persisted (#358): assigning it a value
236
+ * other than the one it holds throws `ReadonlyAttribute`.
237
+ */
238
+ readonly?: boolean;
239
+ }
240
+ /** How an enum's value is validated: `true`, or `{ allowNull: true }` to let it be null. */
241
+ type EnumValidation = boolean | {
242
+ readonly allowNull?: boolean;
243
+ };
244
+ /** Where a string attribute's value comes from when it isn't given: a default or `generateId`, never both. */
245
+ type ValueSource = {
246
+ default?: () => unknown;
247
+ generateId?: false;
248
+ } | {
249
+ default?: never;
250
+ generateId: true;
251
+ };
252
+ /** An attribute that isn't an enum: no type but a string or an integer has one (#340). */
253
+ type NoEnum = {
254
+ enum?: never;
255
+ prefix?: never;
256
+ suffix?: never;
257
+ scopes?: never;
258
+ instanceMethods?: never;
259
+ validate?: never;
260
+ };
261
+ /** An attribute that isn't a decimal: only a decimal has a precision and a scale (#398). */
262
+ type NoDigits = {
263
+ precision?: never;
264
+ scale?: never;
265
+ };
266
+ /** An attribute that isn't a string: only a string has a secure token (#355). */
267
+ type NoToken = {
268
+ secureToken?: never;
269
+ };
270
+ /** A string's secure token, which `regenerate…()` changes, so it's never read-only (#358). */
271
+ type TokenOrReadonly = {
272
+ secureToken?: boolean | SecureTokenOptions;
273
+ readonly?: false;
274
+ } | {
275
+ secureToken?: false;
276
+ readonly: true;
277
+ };
278
+ /** The spec's keys that only some types have, each written by the type's own branch below. */
279
+ type PerTypeKeys = "type" | "generateId" | "storage" | "enum" | "precision" | "scale" | "secureToken";
280
+ type AttributeSpec = AttributeType | AnyCustomType | (SpecObjectByType & Placement);
281
+ /** A column, or a virtual attribute, which has none (#356). */
282
+ type Placement = {
283
+ virtual?: false;
284
+ } | {
285
+ virtual: true;
286
+ column?: never;
287
+ readonly?: never;
288
+ };
289
+ /** A spec written out, by its type: the keys each type may have. */
290
+ type SpecObjectByType = (Omit<SpecObject, "default" | PerTypeKeys> & {
291
+ type: "string";
292
+ storage?: never;
293
+ enum?: TextEnum;
294
+ } & TokenOrReadonly & ValueSource & NoDigits) | (Omit<SpecObject, PerTypeKeys> & NoDigits & NoToken & {
295
+ type: "integer";
296
+ generateId?: false;
297
+ storage?: never;
298
+ enum?: IntegerEnum;
299
+ }) | (Omit<SpecObject, PerTypeKeys> & NoEnum & NoDigits & NoToken & {
300
+ type: Exclude<AttributeType, "string" | "integer" | "datetime" | "decimal">;
301
+ generateId?: false;
302
+ storage?: never;
303
+ }) | (Omit<SpecObject, PerTypeKeys> & NoEnum & NoToken & {
304
+ type: "decimal";
305
+ generateId?: false;
306
+ storage?: never;
307
+ precision?: number;
308
+ scale?: number;
309
+ }) | (Omit<SpecObject, Exclude<PerTypeKeys, "storage">> & NoEnum & NoDigits & NoToken & {
310
+ type: "datetime";
311
+ generateId?: false;
312
+ }) | (Omit<SpecObject, PerTypeKeys> & NoEnum & NoDigits & NoToken & {
313
+ type: AnyCustomType;
314
+ generateId?: false;
315
+ storage?: never;
316
+ });
317
+ type AttributeSpecs = Record<string, AttributeSpec>;
318
+ /** What `define` takes: attribute specs, aliases of them (#509), and secure passwords (#355). */
319
+ type DeclaredAttributes = Record<string, AttributeSpec | AttributeAlias | SecurePasswordDeclaration>;
320
+ /**
321
+ * `A`, with any key a spec doesn't have typed `never`, so a misspelled one (`nul: false`) is a
322
+ * compile error: a generic parameter skips TypeScript's own check for unknown keys (#102).
323
+ */
324
+ type ExactSpecs<A> = { [K in keyof A]: A[K] extends AnyCustomType ? A[K] : A[K] extends {
325
+ aliasOf: string;
326
+ } ? A[K] & Record<Exclude<keyof A[K], "aliasOf">, never> : A[K] extends {
327
+ securePassword: unknown;
328
+ type?: never;
329
+ } ? A[K] & ExactSecurePassword<A[K]["securePassword"]> & Record<Exclude<keyof A[K], "securePassword">, never> : A[K] extends object ? A[K] & Record<Exclude<keyof A[K], keyof SpecObject>, never> : A[K]; };
330
+ /** A secure password's `securePassword`, with any option it doesn't have typed `never` (#355). */
331
+ type ExactSecurePassword<P> = {
332
+ securePassword: P extends true ? true : P & Record<Exclude<keyof P, keyof SecurePasswordOptions>, never>;
333
+ };
334
+ /** An attribute's resolved metadata. */
335
+ interface AttributeDefinition {
336
+ /** Its built-in type: for a custom type, the type it's stored as. */
337
+ type: AttributeType;
338
+ /** The type `defineType` made, whose values it holds, kept as `type`'s (#20). */
339
+ customType?: AnyCustomType;
340
+ column: string;
341
+ default?: () => unknown;
342
+ generateId?: true;
343
+ storage?: EpochStorage;
344
+ precision?: number;
345
+ scale?: number;
346
+ enum?: EnumValues;
347
+ prefix?: boolean | string;
348
+ suffix?: boolean | string;
349
+ scopes?: boolean;
350
+ instanceMethods?: boolean;
351
+ validate?: EnumValidation;
352
+ /** Not a column: never read or written, and refused in queries (#356). */
353
+ virtual?: true;
354
+ /** A secure password, kept as its digest (#355). */
355
+ securePassword?: true | SecurePasswordOptions;
356
+ /** A secure token, generated for a new record (#355). */
357
+ secureToken?: true | SecureTokenOptions;
358
+ /** Written on create, and not changed once persisted (#358). */
359
+ readonly?: true;
360
+ }
361
+ /** The JavaScript value an attribute of a built-in type holds: a `Date` for a `datetime`. */
362
+ type BuiltInValue<T extends AttributeType> = T extends "string" ? string : T extends "integer" | "real" ? number : T extends "boolean" ? boolean : T extends "datetime" ? Date : T extends "binary" ? Uint8Array : T extends "decimal" | "date" | "time" ? string : unknown;
363
+ /** A type's JavaScript value: a built-in type's, or a custom type's own (#20). */
364
+ type ValueOf<T> = T extends AttributeType ? BuiltInValue<T> : T extends CustomType<infer V, AttributeType> ? V : never;
365
+ /** A spec's value, not null: an enum's names (#340), or its type's JavaScript value. */
366
+ type SpecValue<S> = S extends {
367
+ enum: infer E extends EnumValues;
368
+ } ? EnumNames<E> : S extends {
369
+ type: infer T;
370
+ } ? ValueOf<T> : never;
371
+ type AttributeValue<S> = S extends AttributeType | AnyCustomType ? ValueOf<S> | null : S extends {
372
+ type: unknown;
373
+ null: false;
374
+ } ? SpecValue<S> : S extends {
375
+ type: unknown;
376
+ } ? SpecValue<S> | null : never;
377
+ type AttributeProperties<A extends AttributeSpecs> = { -readonly [K in keyof A]: AttributeValue<A[K]>; };
378
+ export { defineType as A, SecurePasswordOptions as C, Duration as D, PasswordAlgorithm as E, AttributeAlias as M, DefinedSpecs as N, AnyCustomType as O, WithoutAliases as P, SecurePasswordMethods as S, WithSecurePasswords as T, SecureTokenOptions as _, AttributeType as a, PasswordResetTokenArgument as b, SpecObject as c, EnumMapping as d, EnumNames as f, SecureTokenMethods as g, TextEnum as h, AttributeSpecs as i, AliasSpecs as j, CustomType as k, ValueSource as l, IntegerEnum as m, AttributeProperties as n, DeclaredAttributes as o, EnumValues as p, AttributeSpec as r, ExactSpecs as s, AttributeDefinition as t, EpochStorage as u, generateSecureToken as v, SecurePasswordSpecs as w, SecurePasswordDeclaration as x, AuthenticateByAttributes as y };
@@ -1,6 +1,6 @@
1
- import { i as attributeName, n as castDefault, s as listed, t as storageOverride, u as parseJsonc } from "./storage-override-BFC-GSR0.mjs";
2
- import { a as migrationSql, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, s as indexName, t as generatedSchema } from "./for-adapters-CgEQfuyD.mjs";
3
- import { E as underscore } from "./epoch-storage-C7186hd1.mjs";
1
+ import { i as attributeName, n as castDefault, s as listed, t as storageOverride, u as parseJsonc } from "./storage-override-B7WTiA_U.mjs";
2
+ import { a as migrationSql, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, s as indexName, t as generatedSchema } from "./for-adapters-DSVRZL3n.mjs";
3
+ import { D as underscore } from "./identifiers-BP6aRwew.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
6
6
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
@@ -479,7 +479,10 @@ function typeOfDeclared(column, declared, where) {
479
479
  function unmatchedNote(declared, where) {
480
480
  return `${where}: ${declared === "" ? "has no declared type" : `is declared ${declared}`}, so it's read as a string; a number in it fails when the record loads, so override it in its Model with the type it holds`;
481
481
  }
482
- /** A column declared exactly TEXT or INTEGER, refined by its name (Rails' conventions). */
482
+ /**
483
+ * A column declared exactly TEXT or INTEGER, refined by its name: `created_at` a datetime,
484
+ * `is_active` a boolean, and so on.
485
+ */
483
486
  function refinedByName(column, type, where) {
484
487
  if (type === "string" && column.name.endsWith("_at")) return { type: "datetime" };
485
488
  const prefix = /^(is|has)_/.exec(column.name)?.[1];
@@ -612,9 +615,9 @@ function applied(migrations) {
612
615
  */
613
616
  function ownTables(all, migrationsTable) {
614
617
  const virtual = [...all].filter(([, sql]) => /^CREATE\s+VIRTUAL\s+TABLE/i.test(sql)).map(([name]) => name);
615
- const shadow = (name) => virtual.some((table) => name === table || name.startsWith(`${table}_`));
616
- const internal = (name) => name.startsWith("sqlite_") || name.startsWith("_cf_") || name === migrationsTable;
617
- return [...all].filter(([name]) => !internal(name) && !shadow(name));
618
+ const isVirtualOrShadow = (name) => virtual.some((table) => name === table || name.startsWith(`${table}_`));
619
+ const isInternal = (name) => name.startsWith("sqlite_") || name.startsWith("_cf_") || name === migrationsTable;
620
+ return [...all].filter(([name]) => !isInternal(name) && !isVirtualOrShadow(name));
618
621
  }
619
622
  /** The columns `json_valid` checks in a table's definition: `CHECK (json_valid(settings))`. */
620
623
  function jsonChecked(definition) {
@@ -1,6 +1,6 @@
1
- import { i as attributeName, n as castDefault, p as byVersion, r as isCastDefaultType, u as parseJsonc } from "./storage-override-BFC-GSR0.mjs";
2
- import { a as migrationSql, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, t as generatedSchema } from "./for-adapters-CgEQfuyD.mjs";
3
- import { E as underscore } from "./epoch-storage-C7186hd1.mjs";
1
+ import { i as attributeName, n as castDefault, p as byVersion, r as isCastDefaultType, u as parseJsonc } from "./storage-override-B7WTiA_U.mjs";
2
+ import { a as migrationSql, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, t as generatedSchema } from "./for-adapters-DSVRZL3n.mjs";
3
+ import { D as underscore } from "./identifiers-BP6aRwew.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import { existsSync, readFileSync, readdirSync } from "node:fs";
6
6
  import { basename, dirname, join } from "node:path";
@@ -106,7 +106,7 @@ function hyperdriveIn(dir) {
106
106
  };
107
107
  }
108
108
  // cli/adapters/postgresql/init.ts
109
- /** The local database a project's folder suggests, named as Rails names it: `shop_development`. */
109
+ /** The local database a project's folder suggests: `shop_development`. */
110
110
  function guessedUrl(dir) {
111
111
  return `postgres://localhost:5432/${basename(dir).toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "") || "app"}_development`;
112
112
  }
@@ -283,13 +283,13 @@ function dollarEnd(sql, index) {
283
283
  return end < 0 ? sql.length : end + tag.length;
284
284
  }
285
285
  /** Whether a string starting at `index` is an escape string (`E'…'`). */
286
- const escapeString = (sql, index) => /[eE]/.test(sql[index - 1] ?? "") && !/\w/.test(sql[index - 2] ?? "");
286
+ const isEscapeString = (sql, index) => /[eE]/.test(sql[index - 1] ?? "") && !/\w/.test(sql[index - 2] ?? "");
287
287
  /** Where the quoted or commented text starting at `index` ends, or `index` when none starts there. */
288
288
  function skipped(sql, index) {
289
289
  if (sql.startsWith("--", index)) return lineEnd(sql, index);
290
290
  if (sql.startsWith("/*", index)) return blockEnd(sql, index);
291
291
  const char = sql[index];
292
- if (char === "'") return quoteEnd(sql, index, escapeString(sql, index));
292
+ if (char === "'") return quoteEnd(sql, index, isEscapeString(sql, index));
293
293
  if (char === "\"") return quoteEnd(sql, index, false);
294
294
  return char === "$" ? dollarEnd(sql, index) : index;
295
295
  }
@@ -364,7 +364,7 @@ function migrationFiles(dir) {
364
364
  sql
365
365
  }))) ?? files;
366
366
  }
367
- /** One lock per database and schema: a run while another holds it is refused, as Rails refuses it. */
367
+ /** One lock per database and schema: a run while another holds it is refused. */
368
368
  const lock = `hashtext('active-record migrate ' || current_database() || '.' || current_schema())`;
369
369
  /** The versions already applied, once the table that records them is there. */
370
370
  async function appliedVersions(client) {
@@ -1,4 +1,4 @@
1
- import { C as QueryEvent$1, D as SchemaAdapter, O as AnyDatabase, w as QueryListener$1 } from "./validations-DFLjJ203.mjs";
1
+ import { C as QueryEvent$1, D as SchemaAdapter, O as AnyDatabase, w as QueryListener$1 } from "./validations-C2-HKi1V.mjs";
2
2
  import pg from "pg";
3
3
  /** The Postgres database a generated schema's Models query: `adapter: postgresql({ binding: "HYPERDRIVE" })`. */
4
4
  export declare function postgresql({ binding }: {
@@ -1,7 +1,7 @@
1
- import { a as databaseExecutor, i as AnyDatabase, l as DatabaseExecutor } from "./batch-D3nP3g83.mjs";
2
- import { n as onlyRequested, t as workersEnv } from "./for-adapters-l4rNitkK.mjs";
3
- import { z as NoDatabase } from "./epoch-storage-C7186hd1.mjs";
4
- import { O as boundValue } from "./generated-model-FB7oT7V1.mjs";
1
+ import { a as databaseExecutor, i as AnyDatabase, l as workersEnv, u as DatabaseExecutor } from "./batch-DpMoy3-7.mjs";
2
+ import { t as onlyRequested } from "./for-adapters-unqbZQM7.mjs";
3
+ import { V as NoDatabase } from "./identifiers-BP6aRwew.mjs";
4
+ import { w as boundValue } from "./generated-model-CKIciUat.mjs";
5
5
  import pg from "pg";
6
6
  // src/adapters/postgresql/connect-timeout.ts
7
7
  /** The limit when the connection string sets none, in milliseconds. */
@@ -256,6 +256,17 @@ function withoutRefusedValue(error) {
256
256
  if (stack !== void 0) error.stack = stack.replace(message, filtered);
257
257
  }
258
258
  const enumRefusal = "invalid input value for enum ";
259
+ /**
260
+ * The value the dialect's stale guard refuses (#357): the library's marker, naming the stale
261
+ * record's write, not a value of the user's, so it's kept, in any language Postgres writes in.
262
+ */
263
+ const staleGuardMarker = /^active-record stale record [0-9a-f-]{36}$/;
264
+ /** Whether the refused value, from the message's first quote to its last, is the guard's marker. */
265
+ function isStaleGuardRefusal(message) {
266
+ const start = message.indexOf("\"");
267
+ const end = message.lastIndexOf("\"");
268
+ return start !== -1 && end > start && staleGuardMarker.test(message.slice(start + 1, end));
269
+ }
259
270
  /** Where the quoted identifier opening at `at` ends, past its closing quote; its own quotes are doubled. -1 if it never closes. */
260
271
  function quotedEnd(message, at) {
261
272
  let next = at + 1;
@@ -283,6 +294,7 @@ function enumNameEnd(message) {
283
294
  * not matched with a pattern that could backtrack, since the value is the user's.
284
295
  */
285
296
  function refusedValueFiltered(message) {
297
+ if (isStaleGuardRefusal(message)) return message;
286
298
  if (message.startsWith(enumRefusal)) {
287
299
  const end = enumNameEnd(message);
288
300
  if (end !== -1 && message.startsWith(": \"", end) && message.endsWith("\"")) return `${message.slice(0, end)}: "[FILTERED]"`;
@@ -535,6 +547,18 @@ const pgAdapter = {
535
547
  return `CASE WHEN ${key} ~ ${literal("^\\s*[+-]?[0-9]+\\s*$")} THEN CAST(${key} AS NUMERIC) END`;
536
548
  },
537
549
  /**
550
+ * The write returns a row if it changed one, and the statement casts the marker to an integer
551
+ * when it returned none, which fails the transaction with the marker in its message (#357).
552
+ * The cast is of the CASE, which reads the write's rows, so it can't be made before it runs.
553
+ */
554
+ staleGuard(write, marker) {
555
+ return [{
556
+ sql: `WITH locked AS (${write.sql} RETURNING 1) SELECT CAST(CASE WHEN NOT EXISTS (SELECT FROM locked) THEN CAST( AS TEXT) END AS INTEGER) AS stale`,
557
+ params: [...write.params, marker],
558
+ model: write.model
559
+ }];
560
+ },
561
+ /**
538
562
  * The removal returns a row for each row it removed, which the counters' UPDATEs count, and the
539
563
  * statement selects how many as `removed`: a COUNT sent before it could miss a row another
540
564
  * request commits in between, on a snapshot of its own (#61).
@@ -1,5 +1,5 @@
1
- import { n as Model, o as readyModel, s as isReservedScopeName } from "./batch-D3nP3g83.mjs";
2
- import { $ as modelNameOf, et as ownValueSetter, ot as ancestors, st as staticBelow } from "./generated-model-FB7oT7V1.mjs";
1
+ import { n as Model, o as readyModel, s as isReservedScopeName } from "./batch-DpMoy3-7.mjs";
2
+ import { Mt as staticBelow, Tt as ownValueSetter, jt as ancestors, wt as modelNameOf } from "./generated-model-CKIciUat.mjs";
3
3
  // src/define-schema.ts
4
4
  const listed = /* @__PURE__ */ new Set();
5
5
  /**
@@ -1,4 +1,4 @@
1
- import { E as underscore, T as camelize, g as reservedWords, l as uncastable, o as castValue, t as epochStorages } from "./epoch-storage-C7186hd1.mjs";
1
+ import { D as underscore, T as camelize, c as castValue, d as uncastable, n as reservedWords, r as epochStorages } from "./identifiers-BP6aRwew.mjs";
2
2
  import { existsSync, readFileSync, readdirSync } from "node:fs";
3
3
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
4
4
  // cli/project/paths.ts