@forestfuture/active-record 0.0.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +26 -2
- package/dist/adapter-BSvFhTDf.d.mts +1293 -0
- package/dist/adapter.d.mts +2 -0
- package/dist/adapter.mjs +3 -0
- package/dist/batch-DBeYk5wx.mjs +4171 -0
- package/dist/cli.d.mts +197 -0
- package/dist/cli.mjs +3 -0
- package/dist/command.d.mts +1 -0
- package/dist/command.mjs +2157 -0
- package/dist/epoch-storage-o2aoOH7H.mjs +112 -0
- package/dist/generated-model-CfDggoVN.mjs +1853 -0
- package/dist/index.d.mts +143 -0
- package/dist/index.mjs +3 -0
- package/dist/storage-override-BYBYP8Mj.mjs +91 -0
- package/llms-full.txt +4397 -0
- package/package.json +42 -4
- package/skills/active-record/SKILL.md +88 -0
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { $ as ErrorMessages, A as Page, B as Comparison, C as HasOne, D as ScopeMethods, E as Scope, F as Conditions, G as lte, H as gt, I as InsertOptions, J as TableSchemas, K as DatabaseSchema, L as OrderSpec, M as ReturnedRow, N as Statement, O as Scoped, P as WriteResult, Q as ErrorMessage, R as Returning, S as HasManyDependent, T as Relation, U as gte, V as between, W as lt, X as ValidationError, Y as Errors, Z as AttributeErrorMessages, _ as UniquenessOptions, _t as ColumnValue, a as RelationsFor, at as AttributeSpecs, b as BelongsTo, bt as sql, c as BatchResults, d as Model, et as RestrictMessages, f as ModelClass, g as NumericalityOptions, gt as ColumnReference, h as LengthOptions, i as AnyDatabase, it as AttributeSpec, j as PageOptions, k as CountlessPage, l as batch, lt as QueryEvent, m as TableAttributes, mt as QuerySql, ot as AttributeType, p as ScopeStatic, q as TableSchema, rt as AttributeConversions, s as BatchEntry, st as EpochStorage, tt as FilterAttribute, u as RecordStatement, ut as QueryListener, v as ValidationOptions, vt as SafeSql, w as HasOneDependent, x as HasMany, y as AssociationOptions, yt as column, z as UpsertOptions } from "./adapter-BSvFhTDf.mjs";
|
|
2
|
+
//#region src/association-fields.d.ts
|
|
3
|
+
/** This record points at one `target` record through `foreignKey` (its own attribute). */
|
|
4
|
+
export declare function belongsTo<C extends ModelClass>(target: C, options?: Omit<AssociationOptions<C>, "dependent">): BelongsTo<C>;
|
|
5
|
+
/** Many `target` records point at this record through `foreignKey` (theirs). */
|
|
6
|
+
export declare function hasMany<C extends ModelClass>(target: C, options?: AssociationOptions<C> & {
|
|
7
|
+
dependent?: HasManyDependent;
|
|
8
|
+
}): HasMany<C>;
|
|
9
|
+
/** One `target` record points at this record through `foreignKey` (its own). */
|
|
10
|
+
export declare function hasOne<C extends ModelClass>(target: C, options?: AssociationOptions<C> & {
|
|
11
|
+
dependent?: HasOneDependent;
|
|
12
|
+
}): HasOne<C>;
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region src/errors.d.ts
|
|
15
|
+
/** Base class for every error the library throws on purpose. */
|
|
16
|
+
export declare class ActiveRecordError extends Error {
|
|
17
|
+
name: string;
|
|
18
|
+
}
|
|
19
|
+
/** A Model's declaration is invalid, e.g. an association's foreign key isn't an attribute. */
|
|
20
|
+
export declare class InvalidModel extends ActiveRecordError {
|
|
21
|
+
name: string;
|
|
22
|
+
}
|
|
23
|
+
/** A key that isn't a declared attribute of the Model. */
|
|
24
|
+
export declare class UnknownAttribute extends ActiveRecordError {
|
|
25
|
+
name: string;
|
|
26
|
+
}
|
|
27
|
+
/** A record constructed directly (`new User()`) was used for something that needs D1. */
|
|
28
|
+
export declare class NoDatabase extends ActiveRecordError {
|
|
29
|
+
name: string;
|
|
30
|
+
}
|
|
31
|
+
/** No record matched a lookup that requires one (`find`, `findByOrThrow`). */
|
|
32
|
+
export declare class RecordNotFound extends ActiveRecordError {
|
|
33
|
+
name: string;
|
|
34
|
+
}
|
|
35
|
+
/** Reading an attribute that wasn't loaded, e.g. one left out of `select(...)`. */
|
|
36
|
+
export declare class MissingAttribute extends ActiveRecordError {
|
|
37
|
+
name: string;
|
|
38
|
+
}
|
|
39
|
+
/** Destroying a record whose `dependent: "restrictWithException"` association still has records. */
|
|
40
|
+
export declare class DeleteRestriction extends ActiveRecordError {
|
|
41
|
+
name: string;
|
|
42
|
+
}
|
|
43
|
+
/** `last()` can't reverse an order given as an `sql` fragment (Rails' IrreversibleOrderError). */
|
|
44
|
+
export declare class IrreversibleOrder extends ActiveRecordError {
|
|
45
|
+
name: string;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Things that can't be combined: relations in `or`/`merge` (e.g. of different Models),
|
|
49
|
+
* `includes` or a write statement with `distinct()`, or statements of two Databases in a batch.
|
|
50
|
+
*/
|
|
51
|
+
export declare class IncompatibleRelation extends ActiveRecordError {
|
|
52
|
+
name: string;
|
|
53
|
+
}
|
|
54
|
+
/** Using a destroyed record as a live one: `save`, `update`, `destroy` or `reload` after `destroy()`. */
|
|
55
|
+
export declare class RecordDestroyed extends ActiveRecordError {
|
|
56
|
+
name: string;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* D1 rejected a write because of a database constraint. `table`, `columns` and `attributes`
|
|
60
|
+
* are filled in when D1's message names them. `table` is null only for a batch writing to
|
|
61
|
+
* several tables, when D1 doesn't say which one failed. The original D1 error is the `cause`.
|
|
62
|
+
*/
|
|
63
|
+
export declare class ConstraintViolation extends ActiveRecordError {
|
|
64
|
+
name: string;
|
|
65
|
+
readonly table: string | null;
|
|
66
|
+
readonly columns: readonly string[];
|
|
67
|
+
readonly attributes: readonly string[];
|
|
68
|
+
constructor(message: string, details: {
|
|
69
|
+
table: string | null;
|
|
70
|
+
columns: readonly string[];
|
|
71
|
+
attributes: readonly string[];
|
|
72
|
+
cause: unknown;
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
/** A UNIQUE constraint failed, e.g. another request won the race after validation passed. */
|
|
76
|
+
export declare class RecordNotUnique extends ConstraintViolation {
|
|
77
|
+
name: string;
|
|
78
|
+
}
|
|
79
|
+
/** A FOREIGN KEY constraint failed. SQLite's message doesn't name the column. */
|
|
80
|
+
export declare class InvalidForeignKey extends ConstraintViolation {
|
|
81
|
+
name: string;
|
|
82
|
+
}
|
|
83
|
+
/** A NOT NULL constraint failed. */
|
|
84
|
+
export declare class NotNullViolation extends ConstraintViolation {
|
|
85
|
+
name: string;
|
|
86
|
+
}
|
|
87
|
+
/** A CHECK constraint failed. */
|
|
88
|
+
export declare class CheckViolation extends ConstraintViolation {
|
|
89
|
+
name: string;
|
|
90
|
+
}
|
|
91
|
+
/** A `…OrThrow` save was refused because the record is invalid; `record.errors` says why. */
|
|
92
|
+
export declare class RecordInvalid extends ActiveRecordError {
|
|
93
|
+
name: string;
|
|
94
|
+
readonly record: Model;
|
|
95
|
+
constructor(record: Model);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Thrown by a callback to refuse a save or destroy: `throw abort("Account is suspended")`.
|
|
99
|
+
* Only this exact class halts a lifecycle; returning `false` never does.
|
|
100
|
+
*/
|
|
101
|
+
export declare class CallbackAbort extends ActiveRecordError {
|
|
102
|
+
name: string;
|
|
103
|
+
readonly reason: string;
|
|
104
|
+
constructor(reason: string);
|
|
105
|
+
}
|
|
106
|
+
/** Makes the sentinel a pre-write callback throws to refuse: `throw abort("reason")`. */
|
|
107
|
+
export declare function abort(reason?: string): CallbackAbort;
|
|
108
|
+
/** A `…OrThrow` save was refused by a callback's `abort(reason)`. */
|
|
109
|
+
export declare class RecordNotSaved extends ActiveRecordError {
|
|
110
|
+
name: string;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* `abort()` was thrown from an after-write callback (`afterSave`, `afterCreate`, `afterUpdate`,
|
|
114
|
+
* `afterDestroy`). That's a mistake: the save or destroy already succeeded and nothing rolls back.
|
|
115
|
+
*/
|
|
116
|
+
export declare class AbortAfterPersistence extends ActiveRecordError {
|
|
117
|
+
name: string;
|
|
118
|
+
readonly callback: string;
|
|
119
|
+
readonly reason: string;
|
|
120
|
+
constructor(callback: string, lifecycle: "save" | "destroy", abortion: CallbackAbort);
|
|
121
|
+
}
|
|
122
|
+
/** A `destroyOrThrow()` was refused by a `beforeDestroy` callback's `abort(reason)`. */
|
|
123
|
+
export declare class RecordNotDestroyed extends ActiveRecordError {
|
|
124
|
+
name: string;
|
|
125
|
+
}
|
|
126
|
+
/** A name passed to `includes()` or `loaded()` that isn't one of the Model's associations. */
|
|
127
|
+
export declare class UnknownAssociation extends ActiveRecordError {
|
|
128
|
+
name: string;
|
|
129
|
+
}
|
|
130
|
+
/** `record.loaded(name)` for an association that wasn't preloaded or read yet. */
|
|
131
|
+
export declare class AssociationNotLoaded extends ActiveRecordError {
|
|
132
|
+
name: string;
|
|
133
|
+
}
|
|
134
|
+
//#endregion
|
|
135
|
+
//#region src/current-database.d.ts
|
|
136
|
+
/**
|
|
137
|
+
* Runs `fn` with `databases` as the request's own: queries started from a Model inside it (and
|
|
138
|
+
* everything it awaits) use the one on that Model's binding, with its Session and `onQuery`.
|
|
139
|
+
* Usually called once per request, in middleware. Nested calls add to the outer ones.
|
|
140
|
+
*/
|
|
141
|
+
export declare function withDatabase<R>(databases: AnyDatabase | readonly AnyDatabase[], fn: () => R | Promise<R>): Promise<R>;
|
|
142
|
+
//#endregion
|
|
143
|
+
export { type AssociationOptions, type AttributeConversions, type AttributeErrorMessages, type AttributeSpec, type AttributeSpecs, type AttributeType, type BatchEntry, type BatchResults, type BelongsTo, type ColumnReference, type ColumnValue, type Comparison, type Conditions, type CountlessPage, type DatabaseSchema, type EpochStorage, type ErrorMessage, type ErrorMessages, Errors, type FilterAttribute, type HasMany, type HasManyDependent, type HasOne, type HasOneDependent, type InsertOptions, type LengthOptions, Model, type NumericalityOptions, type OrderSpec, type Page, type PageOptions, type QueryEvent, type QueryListener, type QuerySql, type RecordStatement, Relation, type RelationsFor, type RestrictMessages, type ReturnedRow, type Returning, type SafeSql, type Scope, type ScopeMethods, type ScopeStatic, type Scoped, type Statement, type TableAttributes, type TableSchema, type TableSchemas, type UniquenessOptions, type UpsertOptions, type ValidationError, type ValidationOptions, type WriteResult, batch, between, column, gt, gte, lt, lte, sql };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { $ as CallbackAbort, Q as AssociationNotLoaded, X as AbortAfterPersistence, Z as ActiveRecordError, _t as UnknownAttribute, at as InvalidModel, ct as NoDatabase, d as Errors, dt as RecordInvalid, et as CheckViolation, ft as RecordNotDestroyed, gt as UnknownAssociation, ht as RecordNotUnique, it as InvalidForeignKey, lt as NotNullViolation, mt as RecordNotSaved, nt as DeleteRestriction, ot as IrreversibleOrder, pt as RecordNotFound, rt as IncompatibleRelation, st as MissingAttribute, tt as ConstraintViolation, ut as RecordDestroyed, vt as abort } from "./generated-model-CfDggoVN.mjs";
|
|
2
|
+
import { _ as hasOne, c as column, d as gt, f as gte, g as hasMany, h as belongsTo, l as sql, m as lte, n as Model, o as Relation, p as lt, r as withDatabase, t as batch, u as between } from "./batch-DBeYk5wx.mjs";
|
|
3
|
+
export { AbortAfterPersistence, ActiveRecordError, AssociationNotLoaded, CallbackAbort, CheckViolation, ConstraintViolation, DeleteRestriction, Errors, IncompatibleRelation, InvalidForeignKey, InvalidModel, IrreversibleOrder, MissingAttribute, Model, NoDatabase, NotNullViolation, RecordDestroyed, RecordInvalid, RecordNotDestroyed, RecordNotFound, RecordNotSaved, RecordNotUnique, Relation, UnknownAssociation, UnknownAttribute, abort, batch, belongsTo, between, column, gt, gte, hasMany, hasOne, lt, lte, sql, withDatabase };
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { a as underscore, i as camelize, t as epochStorages } from "./epoch-storage-o2aoOH7H.mjs";
|
|
2
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
3
|
+
import { join, relative, sep } from "node:path";
|
|
4
|
+
//#region cli/project/paths.ts
|
|
5
|
+
/** A relative path with forward slashes, as Wrangler names migrations on every system. */
|
|
6
|
+
function slashed(path) {
|
|
7
|
+
return path.split(sep).join("/");
|
|
8
|
+
}
|
|
9
|
+
/** A module path from one file's folder to another file, as an import writes it (`../db/schema`). */
|
|
10
|
+
function importPath(fromDir, to) {
|
|
11
|
+
const path = slashed(relative(fromDir, to)).replace(/\.ts$/, "");
|
|
12
|
+
return path.startsWith(".") ? path : `./${path}`;
|
|
13
|
+
}
|
|
14
|
+
/** A path as printed: relative to the project, with forward slashes. */
|
|
15
|
+
function shown(cwd, path) {
|
|
16
|
+
return slashed(relative(cwd, path)) || ".";
|
|
17
|
+
}
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region cli/project/migrations.ts
|
|
20
|
+
/** Plain character order, the same on every machine (unlike `localeCompare`). */
|
|
21
|
+
function byName(a, b) {
|
|
22
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
23
|
+
}
|
|
24
|
+
/** A database's migrations, in the order Wrangler applies them: by file name. */
|
|
25
|
+
function migrationsOf(target) {
|
|
26
|
+
const { migrationsPattern } = target.database;
|
|
27
|
+
return (migrationsPattern === void 0 ? readdirSync(target.migrationsDir).filter((name) => name.endsWith(".sql")) : process.getBuiltinModule("node:fs").globSync(migrationsPattern, { cwd: target.configDir }).map((path) => slashed(relative(target.migrationsDir, join(target.configDir, path))))).sort(byName).map((name) => ({
|
|
28
|
+
name,
|
|
29
|
+
sql: readFileSync(join(target.migrationsDir, name), "utf8")
|
|
30
|
+
}));
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Whether a database's migrations are in folders (`migrations/0000_init/migration.sql`, as
|
|
34
|
+
* Drizzle writes them) with no `migrations_pattern` in the config to find them.
|
|
35
|
+
*/
|
|
36
|
+
function hasNestedMigrations(target) {
|
|
37
|
+
const dir = target.migrationsDir;
|
|
38
|
+
if (target.database.migrationsPattern !== void 0 || !existsSync(dir)) return false;
|
|
39
|
+
const entries = readdirSync(dir, { withFileTypes: true });
|
|
40
|
+
if (entries.some((entry) => entry.isFile() && entry.name.endsWith(".sql"))) return false;
|
|
41
|
+
return entries.some((entry) => entry.isDirectory() && existsSync(join(dir, entry.name, "migration.sql")));
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
//#region cli/project/names.ts
|
|
45
|
+
/** Whether a name can be written bare: as a `const`, or as an object key without quotes. */
|
|
46
|
+
function isIdentifier(name) {
|
|
47
|
+
return /^[\p{L}_$][\p{L}\p{N}_$]*$/u.test(name);
|
|
48
|
+
}
|
|
49
|
+
/** A column's attribute: camelCase, keeping any leading underscores (`_secret` stays). */
|
|
50
|
+
function attributeName(column) {
|
|
51
|
+
const lead = /^_*/.exec(column)[0];
|
|
52
|
+
return lead + camelize(column.slice(lead.length));
|
|
53
|
+
}
|
|
54
|
+
/** Words JavaScript doesn't allow as a `const` name, and the generated file's own names. */
|
|
55
|
+
const reserved = 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 tables".split(" "));
|
|
56
|
+
/**
|
|
57
|
+
* The `const` a table is exported as: its words in camelCase (`line_items` → `lineItems`),
|
|
58
|
+
* never a reserved word (`default` → `defaultTable`) or starting with a digit (`2fa` →
|
|
59
|
+
* `table2fa`).
|
|
60
|
+
*/
|
|
61
|
+
function exportName(table) {
|
|
62
|
+
const name = table.split(/[^\p{L}\p{N}]+/u).filter(Boolean).map((word, index) => index === 0 ? word : word[0].toUpperCase() + word.slice(1)).join("");
|
|
63
|
+
if (name === "" || /^\p{N}/u.test(name)) return `table${name}`;
|
|
64
|
+
return reserved.has(name) ? `${name}Table` : name;
|
|
65
|
+
}
|
|
66
|
+
/** A class name from any spelling: `line_item`, `lineItem` → `LineItem`. */
|
|
67
|
+
function classify(name) {
|
|
68
|
+
const camel = camelize(underscore(name));
|
|
69
|
+
return camel.charAt(0).toUpperCase() + camel.slice(1);
|
|
70
|
+
}
|
|
71
|
+
/** A Model's module, in kebab-case: `LineItem` → `line-item` (its file is `line-item.ts`). */
|
|
72
|
+
function moduleName(className) {
|
|
73
|
+
return underscore(className).replaceAll("_", "-");
|
|
74
|
+
}
|
|
75
|
+
/** `"A"`, `"A or B"`, `"A, B or C"`. */
|
|
76
|
+
function listed(names) {
|
|
77
|
+
return names.length < 2 ? names.join("") : `${names.slice(0, -1).join(", ")} or ${names.at(-1)}`;
|
|
78
|
+
}
|
|
79
|
+
//#endregion
|
|
80
|
+
//#region cli/schema/storage-override.ts
|
|
81
|
+
/** Drizzle's `mode` for each epoch storage, which a note names for a reader with its schema open. */
|
|
82
|
+
const drizzleModes = {
|
|
83
|
+
unixSeconds: "\"timestamp\"",
|
|
84
|
+
unixMilliseconds: "\"timestamp_ms\""
|
|
85
|
+
};
|
|
86
|
+
/** The override that reads a Unix time as a `Date`, for a note; with Drizzle's modes named if asked. */
|
|
87
|
+
function storageOverride(withDrizzleModes) {
|
|
88
|
+
return `{ type: "datetime", storage: ${epochStorages.map((storage) => withDrizzleModes ? `"${storage}" (${drizzleModes[storage]})` : `"${storage}"`).join(" or ")} }`;
|
|
89
|
+
}
|
|
90
|
+
//#endregion
|
|
91
|
+
export { isIdentifier as a, byName as c, importPath as d, shown as f, exportName as i, hasNestedMigrations as l, attributeName as n, listed as o, slashed as p, classify as r, moduleName as s, storageOverride as t, migrationsOf as u };
|