@forestfuture/active-record 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,6 +19,13 @@ var NoDatabase = class extends ActiveRecordError {
19
19
  var RecordNotFound = class extends ActiveRecordError {
20
20
  name = "RecordNotFound";
21
21
  };
22
+ /**
23
+ * A token a finder that must find a record was given isn't valid (#517): it was changed, signed
24
+ * with another secret, made for another purpose, or has expired.
25
+ */
26
+ var InvalidToken = class extends ActiveRecordError {
27
+ name = "InvalidToken";
28
+ };
22
29
  /** `sole()` or `findSoleBy()` matched more than one record. */
23
30
  var SoleRecordExceeded = class extends ActiveRecordError {
24
31
  name = "SoleRecordExceeded";
@@ -31,7 +38,7 @@ var MissingAttribute = class extends ActiveRecordError {
31
38
  var DeleteRestriction = class extends ActiveRecordError {
32
39
  name = "DeleteRestriction";
33
40
  };
34
- /** `last()` can't reverse an order given as an `sql` fragment (Rails' IrreversibleOrderError). */
41
+ /** `last()` can't reverse an order given as an `sql` fragment. */
35
42
  var IrreversibleOrder = class extends ActiveRecordError {
36
43
  name = "IrreversibleOrder";
37
44
  };
@@ -116,9 +123,23 @@ var RecordNotSaved = class extends ActiveRecordError {
116
123
  name = "RecordNotSaved";
117
124
  };
118
125
  /**
126
+ * A save, destroy or `touch()` of a record whose row another write changed since it was loaded
127
+ * (#357): its `lockVersion` is no longer the row's. Nothing in the write was kept.
128
+ */
129
+ var StaleRecord = class extends ActiveRecordError {
130
+ name = "StaleRecord";
131
+ record;
132
+ action;
133
+ constructor(record, action, options) {
134
+ super(`Attempted to ${action} a stale ${record.constructor.name} record`, options);
135
+ this.record = record;
136
+ this.action = action;
137
+ }
138
+ };
139
+ /**
119
140
  * `abort()` was thrown from an after-write callback (`afterSave`, `afterCreate`, `afterUpdate`,
120
- * `afterDestroy`, `afterTouch`). That's a mistake: the write already succeeded and nothing rolls
121
- * back.
141
+ * `afterDestroy`, `afterTouch`), or from an around callback once its `next()` resolved. That's a
142
+ * mistake: the write already succeeded and nothing rolls back.
122
143
  */
123
144
  var AbortAfterPersistence = class extends ActiveRecordError {
124
145
  name = "AbortAfterPersistence";
@@ -151,7 +172,7 @@ var ReadonlyAssociation = class extends ActiveRecordError {
151
172
  };
152
173
  /**
153
174
  * A polymorphic belongsTo's type that names none of the Models it lists (#60), read from the
154
- * database, as Rails raises when it can't find the class a type names.
175
+ * database.
155
176
  */
156
177
  var UnknownModelName = class extends ActiveRecordError {
157
178
  name = "UnknownModelName";
@@ -163,7 +184,7 @@ var AssociationNotLoaded = class extends ActiveRecordError {
163
184
  // src/naming.ts
164
185
  /**
165
186
  * Converts a camelCase attribute name to its snake_case column name, treating
166
- * a run of capitals as one word (Rails' `underscore`): `htmlURL` → `html_url`,
187
+ * a run of capitals as one word: `htmlURL` → `html_url`,
167
188
  * `userID` → `user_id`, `sha256Hash` → `sha256_hash`.
168
189
  */
169
190
  function underscore(name) {
@@ -173,6 +194,10 @@ function underscore(name) {
173
194
  function camelize(name) {
174
195
  return name.replace(/_([a-z\d])/g, (_, letter) => letter.toUpperCase());
175
196
  }
197
+ /** A name with its first letter capitalized, as a method's name holds it: `authToken` → `AuthToken`. */
198
+ function capitalized(name) {
199
+ return name.charAt(0).toUpperCase() + name.slice(1);
200
+ }
176
201
  // src/inflections.ts
177
202
  /** Words whose plural no rule makes: singular, then plural. */
178
203
  const IRREGULARS = [
@@ -183,7 +208,7 @@ const IRREGULARS = [
183
208
  ["move", "moves"],
184
209
  ["zombie", "zombies"]
185
210
  ];
186
- /** Plural rules in Rails' order of definition. The last one that matches wins, as in Rails. */
211
+ /** Plural rules in order of definition. The last one that matches wins. */
187
212
  const PLURALS = [
188
213
  [/$/, "s"],
189
214
  [/s$/i, "s"],
@@ -208,7 +233,7 @@ const PLURALS = [
208
233
  [/(quiz)$/i, "$1zes"],
209
234
  ...IRREGULARS.flatMap(([singular, plural]) => irregular(singular, plural, plural))
210
235
  ];
211
- /** Singular rules, likewise in Rails' order. */
236
+ /** Singular rules, likewise in order of definition. */
212
237
  const SINGULARS = [
213
238
  [/s$/i, ""],
214
239
  [/(ss)$/i, "$1"],
@@ -239,16 +264,16 @@ const SINGULARS = [
239
264
  [/(database)s$/i, "$1"],
240
265
  ...IRREGULARS.flatMap(([singular, plural]) => irregular(singular, plural, singular))
241
266
  ];
242
- /** Words with no plural, matched as the last word (Rails' `\b<word>\z`). */
267
+ /** Words with no plural, matched as the last word. */
243
268
  const UNCOUNTABLE = /\b(?:equipment|information|rice|money|species|series|fish|sheep|jeans|police)$/i;
244
269
  /**
245
- * Rails' `irregular`: rules turning either form into `into` (the plural for plural rules, the
270
+ * Irregular words: rules turning either form into `into` (the plural for plural rules, the
246
271
  * singular for singular ones), keeping the first letter's case.
247
272
  */
248
273
  function irregular(singular, plural, into) {
249
274
  return [[new RegExp(`(${singular[0]})${singular.slice(1)}$`, "i"), `$1${into.slice(1)}`], [new RegExp(`(${plural[0]})${plural.slice(1)}$`, "i"), `$1${into.slice(1)}`]];
250
275
  }
251
- /** Applies the last rule that matches, as Rails does; uncountable words stay as they are. */
276
+ /** Applies the last rule that matches; uncountable words stay as they are. */
252
277
  function inflect(word, rules) {
253
278
  if (word === "" || UNCOUNTABLE.test(word)) return word;
254
279
  for (let index = rules.length - 1; index >= 0; index--) {
@@ -257,90 +282,14 @@ function inflect(word, rules) {
257
282
  }
258
283
  return word;
259
284
  }
260
- /** Rails' `pluralize`: `category` → `categories`, `person` → `people`, `sheep` → `sheep`. */
285
+ /** A word's plural: `category` → `categories`, `person` → `people`, `sheep` → `sheep`. */
261
286
  function pluralize(word) {
262
287
  return inflect(word, PLURALS);
263
288
  }
264
- /** Rails' `singularize`: `categories` → `category`, `people` → `person`, `line_items` → `line_item`. */
289
+ /** A word's singular: `categories` → `category`, `people` → `person`, `line_items` → `line_item`. */
265
290
  function singularize(word) {
266
291
  return inflect(word, SINGULARS);
267
292
  }
268
- // src/binary-values.ts
269
- /** An assigned value as bytes: a `Uint8Array` (a `Buffer` is one) or an `ArrayBuffer`. */
270
- function castBinary(value) {
271
- if (value instanceof Uint8Array) return value;
272
- return value instanceof ArrayBuffer ? new Uint8Array(value) : uncastable;
273
- }
274
- /**
275
- * A stored cell as a new plain `Uint8Array`: D1 returns a BLOB as an array of numbers, and `pg`
276
- * a `bytea` as a `Buffer`.
277
- */
278
- function readBinary(cell) {
279
- if (cell instanceof Uint8Array) return Uint8Array.from(cell);
280
- return Array.isArray(cell) ? Uint8Array.from(cell) : uncastable;
281
- }
282
- /** Whether two stored cells are the same: bytes by content (#20), anything else by `===`. */
283
- function isSameCell(a, b) {
284
- if (!(a instanceof Uint8Array && b instanceof Uint8Array)) return a === b;
285
- return a.length === b.length && a.every((byte, index) => byte === b[index]);
286
- }
287
- /** The character codes of the hex digits, `0`–`9` then `a`–`f`. */
288
- const digitCodes = new TextEncoder().encode("0123456789abcdef");
289
- const decoder = new TextDecoder();
290
- /**
291
- * Bytes as hex text, two digits each, for SQL that reads bytes from JSON (`unhex`, `\\x…`). The
292
- * digits' character codes are written into one array and decoded once: mapping each byte to a
293
- * string of its own takes many times the memory and time, which a large file can't afford.
294
- */
295
- function hexOf(bytes) {
296
- const text = new Uint8Array(bytes.length * 2);
297
- for (let index = 0; index < bytes.length; index++) {
298
- const byte = bytes[index];
299
- text[index * 2] = digitCodes[byte >> 4];
300
- text[index * 2 + 1] = digitCodes[byte & 15];
301
- }
302
- return decoder.decode(text);
303
- }
304
- // src/calendar-values.ts
305
- /** A day: a four-digit year from 0001 (Postgres has no year 0), a month and a day. */
306
- const dayText = /^(?!0000)(\d{4})-(\d{2})-(\d{2})$/;
307
- /**
308
- * Text naming a day that exists (`"2026-01-02"`), as it is; anything else, a `Date` included
309
- * (its day depends on the time zone), is `uncastable`. Each database returns a day as this text.
310
- */
311
- function castDay(value) {
312
- if (typeof value !== "string") return uncastable;
313
- const match = dayText.exec(value);
314
- if (match === null) return uncastable;
315
- const [, year, month, day] = match.map(Number);
316
- const date = /* @__PURE__ */ new Date(0);
317
- date.setUTCFullYear(year, month - 1, day);
318
- return date.getUTCMonth() === month - 1 && date.getUTCDate() === day ? value : uncastable;
319
- }
320
- /** A time of day: hours and minutes, then optionally seconds and up to six digits of a fraction. */
321
- const timeText = /^([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d)(?:\.(\d{1,6}))?)?$/;
322
- /** The end of a day, which Postgres's `time` holds as `24:00:00`, with no time past it. */
323
- const endOfDay = /^24:00(?::00(?:\.0{1,6})?)?$/;
324
- /**
325
- * Text naming a time of day (`"09:30"`, `"09:30:15.5"`) in its one form, as Postgres writes a
326
- * `time`: seconds always, a fraction without trailing zeros (`"09:30:00"`, `"09:30:15.5"`). The
327
- * end of the day is `"24:00:00"`. Anything else, a `Date` included, is `uncastable`.
328
- */
329
- function castTime(value) {
330
- if (typeof value !== "string") return uncastable;
331
- if (endOfDay.test(value)) return "24:00:00";
332
- const match = timeText.exec(value);
333
- if (match === null) return uncastable;
334
- const [, hours, minutes, seconds = "00", fraction = ""] = match;
335
- const digits = withoutTrailingZeros(fraction);
336
- return `${hours}:${minutes}:${seconds}${digits === "" ? "" : `.${digits}`}`;
337
- }
338
- /** `digits` without the zeros it ends with, found by a loop rather than an unanchored `0+$`. */
339
- function withoutTrailingZeros(digits) {
340
- let end = digits.length;
341
- while (digits[end - 1] === "0") end--;
342
- return digits.slice(0, end);
343
- }
344
293
  // src/enum-values.ts
345
294
  /** Whether `value` is an enum's values: a list of names, or an object of names and stored values. */
346
295
  function isEnumValues(value) {
@@ -389,7 +338,7 @@ function repeatProblem(entries) {
389
338
  }
390
339
  /**
391
340
  * The validations an enum declared `validate: true` adds, before a Model's own: its value must be
392
- * one of its names, and not null unless `allowNull`, as Rails' `validate: true` adds them.
341
+ * one of its names, and not null unless `allowNull`.
393
342
  */
394
343
  function enumValidations(definitions) {
395
344
  return [...definitions].flatMap(([attribute, { enum: values, validate = false }]) => {
@@ -421,6 +370,219 @@ function enumValuesOf(model, attribute) {
421
370
  if (values === void 0) throw new UnknownAttribute(`${model.name} has no enum attribute "${attribute}"`);
422
371
  return mappingOf(values);
423
372
  }
373
+ // src/calendar-values.ts
374
+ /** A day: a four-digit year from 0001 (Postgres has no year 0), a month and a day. */
375
+ const dayText = /^(?!0000)(\d{4})-(\d{2})-(\d{2})$/;
376
+ /**
377
+ * Text naming a day that exists (`"2026-01-02"`), as it is; anything else, a `Date` included
378
+ * (its day depends on the time zone), is `uncastable`. Each database returns a day as this text.
379
+ */
380
+ function castDay(value) {
381
+ if (typeof value !== "string") return uncastable;
382
+ const match = dayText.exec(value);
383
+ if (match === null) return uncastable;
384
+ const [, year, month, day] = match.map(Number);
385
+ const date = /* @__PURE__ */ new Date(0);
386
+ date.setUTCFullYear(year, month - 1, day);
387
+ return date.getUTCMonth() === month - 1 && date.getUTCDate() === day ? value : uncastable;
388
+ }
389
+ /** A time of day: hours and minutes, then optionally seconds and up to six digits of a fraction. */
390
+ const timeText = /^([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d)(?:\.(\d{1,6}))?)?$/;
391
+ /** The end of a day, which Postgres's `time` holds as `24:00:00`, with no time past it. */
392
+ const endOfDay = /^24:00(?::00(?:\.0{1,6})?)?$/;
393
+ /**
394
+ * Text naming a time of day (`"09:30"`, `"09:30:15.5"`) in its one form, as Postgres writes a
395
+ * `time`: seconds always, a fraction without trailing zeros (`"09:30:00"`, `"09:30:15.5"`). The
396
+ * end of the day is `"24:00:00"`. Anything else, a `Date` included, is `uncastable`.
397
+ */
398
+ function castTime(value) {
399
+ if (typeof value !== "string") return uncastable;
400
+ if (endOfDay.test(value)) return "24:00:00";
401
+ const match = timeText.exec(value);
402
+ if (match === null) return uncastable;
403
+ const [, hours, minutes, seconds = "00", fraction = ""] = match;
404
+ const digits = withoutTrailingZeros(fraction);
405
+ return `${hours}:${minutes}:${seconds}${digits === "" ? "" : `.${digits}`}`;
406
+ }
407
+ /** `digits` without the zeros it ends with, found by a loop rather than an unanchored `0+$`. */
408
+ function withoutTrailingZeros(digits) {
409
+ let end = digits.length;
410
+ while (digits[end - 1] === "0") end--;
411
+ return digits.slice(0, end);
412
+ }
413
+ // src/decimal-values.ts
414
+ /**
415
+ * A decimal number: a sign, digits with an optional point (`1.5`, `5.`, `.5`), an optional
416
+ * exponent, and spaces around it. Digits after the point only follow a point, so no run of digits
417
+ * can match two ways (ReDoS).
418
+ */
419
+ const decimalText = /^\s*([+-]?)(?:(\d+)(?:\.(\d*))?|\.(\d+))(?:e([+-]?\d+))?\s*$/i;
420
+ /** The most digits Postgres's `numeric` holds before its point, and after it. */
421
+ const maxWholeDigits = 131072;
422
+ const maxFractionDigits = 16383;
423
+ /**
424
+ * The longest text that can be a decimal: every digit Postgres holds, with room for a sign, a
425
+ * point, an exponent and spaces. Longer text is refused before it's read.
426
+ */
427
+ const maxTextLength = 147519;
428
+ /** The significant digits a number keeps when it's cast to a decimal. */
429
+ const numberPrecision = 16;
430
+ /**
431
+ * An assigned value as a decimal's text: decimal text or a `bigint` as it is, a finite number at
432
+ * 16 significant digits (`0.1 + 0.2` is `"0.3"`); anything else, or a number past what
433
+ * Postgres's `numeric` holds, is `uncastable`.
434
+ */
435
+ function castDecimal(value) {
436
+ if (typeof value === "bigint") return canonical(String(value));
437
+ if (typeof value === "number") return castNumber(value);
438
+ return typeof value === "string" ? canonical(value) : uncastable;
439
+ }
440
+ /**
441
+ * A stored cell as a decimal's text. Postgres returns `numeric` as text; D1 returns a `DECIMAL`
442
+ * cell as a number, since SQLite keeps decimal text as a REAL or an INTEGER, so it reads at 16
443
+ * significant digits, a whole number past a safe integer too.
444
+ */
445
+ function readDecimal(cell) {
446
+ if (typeof cell === "number") return castNumber(cell);
447
+ return typeof cell === "string" ? canonical(cell) : uncastable;
448
+ }
449
+ function castNumber(value) {
450
+ if (!Number.isFinite(value)) return uncastable;
451
+ const decimal = canonical(value.toPrecision(numberPrecision));
452
+ return decimal === uncastable ? canonical(value.toPrecision(17)) : decimal;
453
+ }
454
+ /**
455
+ * Decimal text in its one form: no exponent, no `+`, no leading zeros but one before the point,
456
+ * no trailing zeros after it, and `"0"` for any zero; `uncastable` for anything else.
457
+ */
458
+ function canonical(text) {
459
+ const parts = partsOf(text);
460
+ if (parts === void 0) return uncastable;
461
+ const { negative, digits, point } = parts;
462
+ const first = digits.search(/[1-9]/);
463
+ if (first === -1) return "0";
464
+ const last = lastNonZero(digits) + 1;
465
+ if (point - first > maxWholeDigits || last - point > maxFractionDigits) return uncastable;
466
+ const decimal = (negative ? "-" : "") + placePoint(digits.slice(first, last), point - first);
467
+ return isWithinDouble(decimal) ? decimal : uncastable;
468
+ }
469
+ /**
470
+ * Whether a double holds a non-zero decimal's magnitude: it doesn't overflow to Infinity or
471
+ * underflow to 0. D1 keeps a decimal as a double, and stores one past either end as Infinity,
472
+ * which reads as NULL, or as 0, so every database refuses one alike (#391).
473
+ */
474
+ function isWithinDouble(decimal) {
475
+ const number = Number(decimal);
476
+ return Number.isFinite(number) && number !== 0;
477
+ }
478
+ /** Decimal text's sign, its digits, and how many of them its point follows; undefined if it isn't one. */
479
+ function partsOf(text) {
480
+ if (text.length > maxTextLength) return void 0;
481
+ const match = decimalText.exec(text);
482
+ if (match === null) return void 0;
483
+ const [, sign, whole = "", pointed, unpointed, exponent = "0"] = match;
484
+ return {
485
+ negative: sign === "-",
486
+ digits: whole + (pointed ?? unpointed ?? ""),
487
+ point: whole.length + Number(exponent)
488
+ };
489
+ }
490
+ /**
491
+ * Where `digits`' last non-zero digit is, found by a loop: `/0*$/` tries every place in turn, so
492
+ * on a long run of zeros it takes quadratic time.
493
+ */
494
+ function lastNonZero(digits) {
495
+ let index = digits.length - 1;
496
+ while (digits[index] === "0") index--;
497
+ return index;
498
+ }
499
+ /** Significant `digits` with the point `point` digits after the first, padded with zeros. */
500
+ function placePoint(digits, point) {
501
+ if (point <= 0) return `0.${"0".repeat(-point)}${digits}`;
502
+ if (point >= digits.length) return digits + "0".repeat(point - digits.length);
503
+ return `${digits.slice(0, point)}.${digits.slice(point)}`;
504
+ }
505
+ /**
506
+ * Where decimal `a` falls against decimal `b`, both in their one form: -1, 0 or 1. By sign, then
507
+ * by the digits before the point (more is larger), then digit by digit, which is exact.
508
+ */
509
+ function compareDecimals(a, b) {
510
+ const [signA, signB] = [signOf(a), signOf(b)];
511
+ if (signA !== signB) return Math.sign(signA - signB);
512
+ const order = compareMagnitudes(a.replace("-", ""), b.replace("-", ""));
513
+ return signA < 0 ? -order : order;
514
+ }
515
+ function signOf(decimal) {
516
+ if (decimal === "0") return 0;
517
+ return decimal.startsWith("-") ? -1 : 1;
518
+ }
519
+ function compareMagnitudes(a, b) {
520
+ const [wholeA = "", fractionA = ""] = a.split(".");
521
+ const [wholeB = "", fractionB = ""] = b.split(".");
522
+ if (wholeA.length !== wholeB.length) return Math.sign(wholeA.length - wholeB.length);
523
+ const width = Math.max(fractionA.length, fractionB.length);
524
+ const [left, right] = [wholeA + fractionA.padEnd(width, "0"), wholeB + fractionB.padEnd(width, "0")];
525
+ if (left === right) return 0;
526
+ return left < right ? -1 : 1;
527
+ }
528
+ /**
529
+ * Where a decimal falls against a bound given as a number or decimal text: exactly, as
530
+ * `compareDecimals` does. A bound of `NaN` orders against nothing (NaN), and `±Infinity` beyond
531
+ * every decimal; `undefined` for a bound that isn't a number (text that isn't a decimal).
532
+ */
533
+ function orderDecimal(value, bound) {
534
+ if (typeof bound === "number" && !Number.isFinite(bound)) return Number.isNaN(bound) ? NaN : -Math.sign(bound);
535
+ const decimal = castDecimal(bound);
536
+ return decimal === uncastable ? void 0 : compareDecimals(value, decimal);
537
+ }
538
+ /** The most digits Postgres's `numeric` takes as a precision or a scale. */
539
+ const maxDigits = 1e3;
540
+ /** Whether `value` is a whole number of digits from `least` to 1000. */
541
+ function isDigitCount(value, least) {
542
+ return Number.isSafeInteger(value) && value >= least && value <= maxDigits;
543
+ }
544
+ /**
545
+ * Why a precision and scale can't be a `NUMERIC(p, s)`'s, as the words after "has", or undefined:
546
+ * a precision is 1 to 1000 digits, and a scale 0 to the precision. The spec, the schema readers and
547
+ * the generators all check it here (#398).
548
+ */
549
+ function digitsProblem({ precision, scale }) {
550
+ if (precision !== void 0 && !isDigitCount(precision, 1)) return `a precision of ${precision}; a precision is 1 to 1000 digits`;
551
+ if (scale !== void 0 && !isDigitCount(scale, 0)) return `a scale of ${scale}; a scale is 0 to 1000 digits`;
552
+ if (precision === void 0 || scale === void 0 || scale <= precision) return void 0;
553
+ return `a scale of ${scale}, past its precision of ${precision}; a scale is at most the precision`;
554
+ }
555
+ /**
556
+ * A decimal in its one form, rounded to its scale, half away from zero, as Postgres's `numeric`
557
+ * rounds; `uncastable` when its digits before the point are more than the precision
558
+ * leaves them. A precision without a scale has a scale of 0, as SQL's `NUMERIC(10)` does.
559
+ */
560
+ function limitDecimal(decimal, { precision, scale }) {
561
+ const places = scale ?? (precision === void 0 ? void 0 : 0);
562
+ const rounded = places === void 0 ? decimal : roundDecimal(decimal, places);
563
+ if (precision === void 0 || rounded === uncastable) return rounded;
564
+ const whole = rounded.replace("-", "").split(".")[0];
565
+ return (whole === "0" ? 0 : whole.length) > precision - (places ?? 0) ? uncastable : rounded;
566
+ }
567
+ /**
568
+ * A decimal in its one form, rounded to `places` digits after the point, half away from zero; or
569
+ * `uncastable` when rounding carries it past a double's range.
570
+ */
571
+ function roundDecimal(decimal, places) {
572
+ const negative = decimal.startsWith("-");
573
+ const [whole = "", fraction = ""] = decimal.replace("-", "").split(".");
574
+ if (fraction.length <= places) return decimal;
575
+ const kept = whole + fraction.slice(0, places);
576
+ const digits = fraction[places] >= "5" ? incremented(kept) : kept;
577
+ const point = digits.length - places;
578
+ return canonical(`${negative ? "-" : ""}${digits.slice(0, point)}.${digits.slice(point)}`);
579
+ }
580
+ /** A run of digits plus one in its last place: `"199"` → `"200"`, `"99"` → `"100"`. */
581
+ function incremented(digits) {
582
+ let index = digits.length - 1;
583
+ while (index >= 0 && digits[index] === "9") index--;
584
+ return (index < 0 ? "1" : digits.slice(0, index) + String(Number(digits[index]) + 1)) + "0".repeat(digits.length - 1 - index);
585
+ }
424
586
  // src/conversion.ts
425
587
  /** A value that can't be read as the attribute's type. */
426
588
  const uncastable = Symbol("uncastable");
@@ -570,8 +732,8 @@ function customConverter(type, stored) {
570
732
  }
571
733
  /**
572
734
  * An enum's values are its names (#340). A name is cast as itself, and so is the value it's
573
- * stored as (`1`, or `"1"` from a form), as Rails accepts; anything else is `uncastable`. A stored
574
- * cell of its type that's none of its values reads as null, as Rails reads it, so a row written
735
+ * stored as (`1`, or `"1"` from a form); anything else is `uncastable`. A stored
736
+ * cell of its type that's none of its values reads as null, so a row written
575
737
  * by code that lists a newer value doesn't fail every list it's in; one of another type is
576
738
  * `uncastable`, as for any attribute of that type (#159).
577
739
  */
@@ -595,7 +757,7 @@ function castValue(attribute, value) {
595
757
  /**
596
758
  * A condition's value as the attribute's type, or `uncastable`: as `castValue`, except that a
597
759
  * finite number matches a string attribute as its decimal string (`7` → `"7"`), as `find` does
598
- * for a text key and as Rails does, so a foreign key of another type still finds its target.
760
+ * for a text key, so a foreign key of another type still finds its target.
599
761
  */
600
762
  function castCondition(attribute, value) {
601
763
  return castKey(withoutPrecision(attribute), value);
@@ -803,178 +965,41 @@ function dayOf(day) {
803
965
  function isInvalidDate(value) {
804
966
  return value instanceof Date && Number.isNaN(value.getTime());
805
967
  }
806
- // src/decimal-values.ts
807
- /**
808
- * A decimal number: a sign, digits with an optional point (`1.5`, `5.`, `.5`), an optional
809
- * exponent, and spaces around it. Digits after the point only follow a point, so no run of digits
810
- * can match two ways (ReDoS).
811
- */
812
- const decimalText = /^\s*([+-]?)(?:(\d+)(?:\.(\d*))?|\.(\d+))(?:e([+-]?\d+))?\s*$/i;
813
- /** The most digits Postgres's `numeric` holds before its point, and after it. */
814
- const maxWholeDigits = 131072;
815
- const maxFractionDigits = 16383;
816
- /**
817
- * The longest text that can be a decimal: every digit Postgres holds, with room for a sign, a
818
- * point, an exponent and spaces. Longer text is refused before it's read.
819
- */
820
- const maxTextLength = 147519;
821
- /** A number's significant digits when it's cast, as Rails casts a float to a decimal. */
822
- const numberPrecision = 16;
823
- /**
824
- * An assigned value as a decimal's text: decimal text or a `bigint` as it is, a finite number at
825
- * 16 significant digits (`0.1 + 0.2` is `"0.3"`); anything else, or a number past what
826
- * Postgres's `numeric` holds, is `uncastable`.
827
- */
828
- function castDecimal(value) {
829
- if (typeof value === "bigint") return canonical(String(value));
830
- if (typeof value === "number") return castNumber(value);
831
- return typeof value === "string" ? canonical(value) : uncastable;
832
- }
833
- /**
834
- * A stored cell as a decimal's text. Postgres returns `numeric` as text; D1 returns a `DECIMAL`
835
- * cell as a number, since SQLite keeps decimal text as a REAL or an INTEGER, so it reads at 16
836
- * significant digits, a whole number past a safe integer too, as Rails reads one on SQLite.
837
- */
838
- function readDecimal(cell) {
839
- if (typeof cell === "number") return castNumber(cell);
840
- return typeof cell === "string" ? canonical(cell) : uncastable;
841
- }
842
- function castNumber(value) {
843
- if (!Number.isFinite(value)) return uncastable;
844
- const decimal = canonical(value.toPrecision(numberPrecision));
845
- return decimal === uncastable ? canonical(value.toPrecision(17)) : decimal;
846
- }
847
- /**
848
- * Decimal text in its one form: no exponent, no `+`, no leading zeros but one before the point,
849
- * no trailing zeros after it, and `"0"` for any zero; `uncastable` for anything else.
850
- */
851
- function canonical(text) {
852
- const parts = partsOf(text);
853
- if (parts === void 0) return uncastable;
854
- const { negative, digits, point } = parts;
855
- const first = digits.search(/[1-9]/);
856
- if (first === -1) return "0";
857
- const last = lastNonZero(digits) + 1;
858
- if (point - first > maxWholeDigits || last - point > maxFractionDigits) return uncastable;
859
- const decimal = (negative ? "-" : "") + placePoint(digits.slice(first, last), point - first);
860
- return isWithinDouble(decimal) ? decimal : uncastable;
861
- }
862
- /**
863
- * Whether a double holds a non-zero decimal's magnitude: it doesn't overflow to Infinity or
864
- * underflow to 0. D1 keeps a decimal as a double, and stores one past either end as Infinity,
865
- * which reads as NULL, or as 0, so every database refuses one alike (#391).
866
- */
867
- function isWithinDouble(decimal) {
868
- const number = Number(decimal);
869
- return Number.isFinite(number) && number !== 0;
870
- }
871
- /** Decimal text's sign, its digits, and how many of them its point follows; undefined if it isn't one. */
872
- function partsOf(text) {
873
- if (text.length > maxTextLength) return void 0;
874
- const match = decimalText.exec(text);
875
- if (match === null) return void 0;
876
- const [, sign, whole = "", pointed, unpointed, exponent = "0"] = match;
877
- return {
878
- negative: sign === "-",
879
- digits: whole + (pointed ?? unpointed ?? ""),
880
- point: whole.length + Number(exponent)
881
- };
882
- }
883
- /**
884
- * Where `digits`' last non-zero digit is, found by a loop: `/0*$/` tries every place in turn, so
885
- * on a long run of zeros it takes quadratic time.
886
- */
887
- function lastNonZero(digits) {
888
- let index = digits.length - 1;
889
- while (digits[index] === "0") index--;
890
- return index;
891
- }
892
- /** Significant `digits` with the point `point` digits after the first, padded with zeros. */
893
- function placePoint(digits, point) {
894
- if (point <= 0) return `0.${"0".repeat(-point)}${digits}`;
895
- if (point >= digits.length) return digits + "0".repeat(point - digits.length);
896
- return `${digits.slice(0, point)}.${digits.slice(point)}`;
897
- }
898
- /**
899
- * Where decimal `a` falls against decimal `b`, both in their one form: -1, 0 or 1. By sign, then
900
- * by the digits before the point (more is larger), then digit by digit, which is exact.
901
- */
902
- function compareDecimals(a, b) {
903
- const [signA, signB] = [signOf(a), signOf(b)];
904
- if (signA !== signB) return Math.sign(signA - signB);
905
- const order = compareMagnitudes(a.replace("-", ""), b.replace("-", ""));
906
- return signA < 0 ? -order : order;
907
- }
908
- function signOf(decimal) {
909
- if (decimal === "0") return 0;
910
- return decimal.startsWith("-") ? -1 : 1;
911
- }
912
- function compareMagnitudes(a, b) {
913
- const [wholeA = "", fractionA = ""] = a.split(".");
914
- const [wholeB = "", fractionB = ""] = b.split(".");
915
- if (wholeA.length !== wholeB.length) return Math.sign(wholeA.length - wholeB.length);
916
- const width = Math.max(fractionA.length, fractionB.length);
917
- const [left, right] = [wholeA + fractionA.padEnd(width, "0"), wholeB + fractionB.padEnd(width, "0")];
918
- if (left === right) return 0;
919
- return left < right ? -1 : 1;
920
- }
921
- /**
922
- * Where a decimal falls against a bound given as a number or decimal text: exactly, as
923
- * `compareDecimals` does. A bound of `NaN` orders against nothing (NaN), and `±Infinity` beyond
924
- * every decimal; `undefined` for a bound that isn't a number (text that isn't a decimal).
925
- */
926
- function orderDecimal(value, bound) {
927
- if (typeof bound === "number" && !Number.isFinite(bound)) return Number.isNaN(bound) ? NaN : -Math.sign(bound);
928
- const decimal = castDecimal(bound);
929
- return decimal === uncastable ? void 0 : compareDecimals(value, decimal);
930
- }
931
- /** The most digits Postgres's `numeric` takes as a precision or a scale. */
932
- const maxDigits = 1e3;
933
- /** Whether `value` is a whole number of digits from `least` to 1000. */
934
- function isDigitCount(value, least) {
935
- return Number.isSafeInteger(value) && value >= least && value <= maxDigits;
968
+ // src/binary-values.ts
969
+ /** An assigned value as bytes: a `Uint8Array` (a `Buffer` is one) or an `ArrayBuffer`. */
970
+ function castBinary(value) {
971
+ if (value instanceof Uint8Array) return value;
972
+ return value instanceof ArrayBuffer ? new Uint8Array(value) : uncastable;
936
973
  }
937
974
  /**
938
- * Why a precision and scale can't be a `NUMERIC(p, s)`'s, as the words after "has", or undefined:
939
- * a precision is 1 to 1000 digits, and a scale 0 to the precision. The spec, the schema readers and
940
- * the generators all check it here (#398).
975
+ * A stored cell as a new plain `Uint8Array`: D1 returns a BLOB as an array of numbers, and `pg`
976
+ * a `bytea` as a `Buffer`.
941
977
  */
942
- function digitsProblem({ precision, scale }) {
943
- if (precision !== void 0 && !isDigitCount(precision, 1)) return `a precision of ${precision}; a precision is 1 to 1000 digits`;
944
- if (scale !== void 0 && !isDigitCount(scale, 0)) return `a scale of ${scale}; a scale is 0 to 1000 digits`;
945
- if (precision === void 0 || scale === void 0 || scale <= precision) return void 0;
946
- return `a scale of ${scale}, past its precision of ${precision}; a scale is at most the precision`;
978
+ function readBinary(cell) {
979
+ if (cell instanceof Uint8Array) return Uint8Array.from(cell);
980
+ return Array.isArray(cell) ? Uint8Array.from(cell) : uncastable;
947
981
  }
948
- /**
949
- * A decimal in its one form, rounded to its scale, half away from zero, as Postgres's `numeric`
950
- * and Rails round; `uncastable` when its digits before the point are more than the precision
951
- * leaves them. A precision without a scale has a scale of 0, as SQL's `NUMERIC(10)` does.
952
- */
953
- function limitDecimal(decimal, { precision, scale }) {
954
- const places = scale ?? (precision === void 0 ? void 0 : 0);
955
- const rounded = places === void 0 ? decimal : roundDecimal(decimal, places);
956
- if (precision === void 0 || rounded === uncastable) return rounded;
957
- const whole = rounded.replace("-", "").split(".")[0];
958
- return (whole === "0" ? 0 : whole.length) > precision - (places ?? 0) ? uncastable : rounded;
982
+ /** Whether two stored cells are the same: bytes by content (#20), anything else by `===`. */
983
+ function isSameCell(a, b) {
984
+ if (!(a instanceof Uint8Array && b instanceof Uint8Array)) return a === b;
985
+ return a.length === b.length && a.every((byte, index) => byte === b[index]);
959
986
  }
987
+ /** The character codes of the hex digits, `0`–`9` then `a`–`f`. */
988
+ const digitCodes = new TextEncoder().encode("0123456789abcdef");
989
+ const decoder = new TextDecoder();
960
990
  /**
961
- * A decimal in its one form, rounded to `places` digits after the point, half away from zero; or
962
- * `uncastable` when rounding carries it past a double's range.
991
+ * Bytes as hex text, two digits each, for SQL that reads bytes from JSON (`unhex`, `\\x…`). The
992
+ * digits' character codes are written into one array and decoded once: mapping each byte to a
993
+ * string of its own takes many times the memory and time, which a large file can't afford.
963
994
  */
964
- function roundDecimal(decimal, places) {
965
- const negative = decimal.startsWith("-");
966
- const [whole = "", fraction = ""] = decimal.replace("-", "").split(".");
967
- if (fraction.length <= places) return decimal;
968
- const kept = whole + fraction.slice(0, places);
969
- const digits = fraction[places] >= "5" ? incremented(kept) : kept;
970
- const point = digits.length - places;
971
- return canonical(`${negative ? "-" : ""}${digits.slice(0, point)}.${digits.slice(point)}`);
972
- }
973
- /** A run of digits plus one in its last place: `"199"` → `"200"`, `"99"` → `"100"`. */
974
- function incremented(digits) {
975
- let index = digits.length - 1;
976
- while (index >= 0 && digits[index] === "9") index--;
977
- return (index < 0 ? "1" : digits.slice(0, index) + String(Number(digits[index]) + 1)) + "0".repeat(digits.length - 1 - index);
995
+ function hexOf(bytes) {
996
+ const text = new Uint8Array(bytes.length * 2);
997
+ for (let index = 0; index < bytes.length; index++) {
998
+ const byte = bytes[index];
999
+ text[index * 2] = digitCodes[byte >> 4];
1000
+ text[index * 2 + 1] = digitCodes[byte & 15];
1001
+ }
1002
+ return decoder.decode(text);
978
1003
  }
979
1004
  // src/epoch-storage.ts
980
1005
  /** A datetime held in an `INTEGER` column as seconds or milliseconds since 1970. */
@@ -986,4 +1011,4 @@ function isIdentifier(name) {
986
1011
  }
987
1012
  /** Words JavaScript doesn't allow as a declaration's name in a module (strict mode). */
988
1013
  const reservedWords = new Set("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await arguments eval".split(" "));
989
- export { abort as $, CallbackAbort as A, NotNullViolation as B, pluralize as C, AbortAfterPersistence as D, underscore as E, InvalidForeignKey as F, RecordNotFound as G, RecordDestroyed as H, InvalidModel as I, SoleRecordExceeded as J, RecordNotSaved as K, IrreversibleOrder as L, ConstraintViolation as M, DeleteRestriction as N, ActiveRecordError as O, IncompatibleRelation as P, UnknownModelName as Q, MissingAttribute as R, isSameCell as S, camelize as T, RecordInvalid as U, ReadonlyAssociation as V, RecordNotDestroyed as W, UnknownAssociation as X, StrictValidationFailed as Y, UnknownAttribute as Z, enumValidations as _, orderDecimal as a, listedNames as b, castValue as c, uncastable as d, writeUntypedValue as f, enumProblem as g, enumEntries as h, digitsProblem as i, CheckViolation as j, AssociationNotLoaded as k, isInvalidDate as l, zonelessDateTime as m, reservedWords as n, castCondition as o, writeValue as p, RecordNotUnique as q, epochStorages as r, castKey as s, isIdentifier as t, readValue as u, enumValuesOf as v, singularize as w, hexOf as x, isEnumValues as y, NoDatabase as z };
1014
+ export { UnknownAssociation as $, AssociationNotLoaded as A, MissingAttribute as B, pluralize as C, underscore as D, capitalized as E, IncompatibleRelation as F, RecordInvalid as G, NotNullViolation as H, InvalidForeignKey as I, RecordNotSaved as J, RecordNotDestroyed as K, InvalidModel as L, CheckViolation as M, ConstraintViolation as N, AbortAfterPersistence as O, DeleteRestriction as P, StrictValidationFailed as Q, InvalidToken as R, listedNames as S, camelize as T, ReadonlyAssociation as U, NoDatabase as V, RecordDestroyed as W, SoleRecordExceeded as X, RecordNotUnique as Y, StaleRecord as Z, enumEntries as _, isSameCell as a, enumValuesOf as b, castValue as c, uncastable as d, UnknownAttribute as et, writeUntypedValue as f, orderDecimal as g, digitsProblem as h, hexOf as i, CallbackAbort as j, ActiveRecordError as k, isInvalidDate as l, zonelessDateTime as m, reservedWords as n, abort as nt, castCondition as o, writeValue as p, RecordNotFound as q, epochStorages as r, castKey as s, isIdentifier as t, UnknownModelName as tt, readValue as u, enumProblem as v, singularize as w, isEnumValues as x, enumValidations as y, IrreversibleOrder as z };