@forestfuture/active-record 0.0.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/d1.d.mts ADDED
@@ -0,0 +1,68 @@
1
+ import { i as AnyDatabase, lt as QueryEvent$1, r as SchemaAdapter, ut as QueryListener$1 } from "./adapter-AGKp6wfO.mjs";
2
+ import { r as ActiveRecordError } from "./index-CyCJuM96.mjs";
3
+ //#region src/adapters/d1/adapter.d.ts
4
+ /** The D1 database a generated schema's Models query: `adapter: d1({ binding: "DB" })`. */
5
+ export declare function d1({ binding }: {
6
+ binding: string;
7
+ }): SchemaAdapter;
8
+ //#endregion
9
+ //#region src/adapters/d1/database.d.ts
10
+ /** What `onQuery` hears about a statement: its Model, SQL, bound values, timing, and D1's `meta`. */
11
+ type QueryEvent = QueryEvent$1<D1Meta>;
12
+ /** Hears each statement's `QueryEvent`, with D1's `meta`. */
13
+ type QueryListener = QueryListener$1<D1Meta>;
14
+ interface ConnectOptions {
15
+ /** Called once for every statement sent to D1, with D1's `meta`. */
16
+ onQuery?: QueryListener;
17
+ /**
18
+ * Sends every query through one D1 Session, so the request reads its own writes even when
19
+ * reads are served by replicas: `"first-primary"`, `"first-unconstrained"`, or a bookmark
20
+ * from an earlier request's `db.bookmark()`.
21
+ */
22
+ session?: D1SessionConstraint | (D1SessionBookmark & {});
23
+ }
24
+ /**
25
+ * A per-request wrapper around a D1 binding; every query goes through it. `db.batch` uses D1's
26
+ * `batch()`. There's no interactive `transaction()`, because D1 can't hold one open across awaits.
27
+ */
28
+ export declare class Database extends AnyDatabase {
29
+ #private;
30
+ constructor(binding: D1Database, options?: ConnectOptions);
31
+ /**
32
+ * The Session's latest bookmark (null before its first query). Pass it to the next request's
33
+ * `connect(env.DB, { session: bookmark })` to read at least as new as this request wrote.
34
+ */
35
+ bookmark(): D1SessionBookmark | null;
36
+ }
37
+ export declare function connect(binding: D1Database, options?: ConnectOptions): Database;
38
+ //#endregion
39
+ //#region src/adapters/d1/errors.d.ts
40
+ /** `bookmark()` was called on a Database opened without a `session`. */
41
+ export declare class NoSession extends ActiveRecordError {
42
+ name: string;
43
+ }
44
+ //#endregion
45
+ //#region src/adapters/d1/with-session.d.ts
46
+ /** How `withSession` opens the request's Database, and where its bookmark travels. */
47
+ type SessionOptions = Omit<ConnectOptions, "session"> & {
48
+ /** Where a request with no bookmark starts its Session: `"first-unconstrained"` unless set. */
49
+ start?: D1SessionConstraint;
50
+ } & ({
51
+ /** The cookie the bookmark travels in: `"d1-bookmark"` unless set. */
52
+ cookie?: string;
53
+ header?: never;
54
+ } | {
55
+ cookie?: never;
56
+ /** The header the bookmark travels in, on the request and the response, instead of a cookie. */
57
+ header: string;
58
+ });
59
+ type Handler = (db: Database) => Response | Promise<Response>;
60
+ /**
61
+ * Runs `fn` with a Database whose Session starts from the request's bookmark, so the request
62
+ * reads at least as new as the user's last write, from any replica, and sets the Session's
63
+ * latest bookmark on the response it returns. An error from `fn` reaches the caller unchanged.
64
+ */
65
+ export declare function withSession(request: Request, binding: D1Database, fn: Handler): Promise<Response>;
66
+ export declare function withSession(request: Request, binding: D1Database, options: SessionOptions, fn: Handler): Promise<Response>;
67
+ //#endregion
68
+ export type { ConnectOptions, QueryEvent, QueryListener, SessionOptions };
package/dist/d1.mjs ADDED
Binary file
@@ -0,0 +1,112 @@
1
+ //#region src/naming.ts
2
+ /**
3
+ * Converts a camelCase attribute name to its snake_case column name, treating
4
+ * a run of capitals as one word (Rails' `underscore`): `htmlURL` → `html_url`,
5
+ * `userID` → `user_id`, `sha256Hash` → `sha256_hash`.
6
+ */
7
+ function underscore(name) {
8
+ return name.replace(/(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z\d])(?=[A-Z][a-z])/g, "_").toLowerCase();
9
+ }
10
+ /** A snake_case name as a camelCase attribute: `api_key` → `apiKey`. */
11
+ function camelize(name) {
12
+ return name.replace(/_([a-z\d])/g, (_, letter) => letter.toUpperCase());
13
+ }
14
+ //#endregion
15
+ //#region src/inflections.ts
16
+ /** Words whose plural no rule makes: singular, then plural. */
17
+ const IRREGULARS = [
18
+ ["person", "people"],
19
+ ["man", "men"],
20
+ ["child", "children"],
21
+ ["sex", "sexes"],
22
+ ["move", "moves"],
23
+ ["zombie", "zombies"]
24
+ ];
25
+ /** Plural rules in Rails' order of definition. The last one that matches wins, as in Rails. */
26
+ const PLURALS = [
27
+ [/$/, "s"],
28
+ [/s$/i, "s"],
29
+ [/^(ax|test)is$/i, "$1es"],
30
+ [/(octop|vir)us$/i, "$1i"],
31
+ [/(octop|vir)i$/i, "$1i"],
32
+ [/(alias|status)$/i, "$1es"],
33
+ [/(bu)s$/i, "$1ses"],
34
+ [/(buffal|tomat)o$/i, "$1oes"],
35
+ [/([ti])um$/i, "$1a"],
36
+ [/([ti])a$/i, "$1a"],
37
+ [/sis$/i, "ses"],
38
+ [/(?:([^f])fe|([lr])f)$/i, "$1$2ves"],
39
+ [/(hive)$/i, "$1s"],
40
+ [/([^aeiouy]|qu)y$/i, "$1ies"],
41
+ [/(x|ch|ss|sh)$/i, "$1es"],
42
+ [/(matr|vert|ind)(?:ix|ex)$/i, "$1ices"],
43
+ [/^(m|l)ouse$/i, "$1ice"],
44
+ [/^(m|l)ice$/i, "$1ice"],
45
+ [/^(ox)$/i, "$1en"],
46
+ [/^(oxen)$/i, "$1"],
47
+ [/(quiz)$/i, "$1zes"],
48
+ ...IRREGULARS.flatMap(([singular, plural]) => irregular(singular, plural, plural))
49
+ ];
50
+ /** Singular rules, likewise in Rails' order. */
51
+ const SINGULARS = [
52
+ [/s$/i, ""],
53
+ [/(ss)$/i, "$1"],
54
+ [/(n)ews$/i, "$1ews"],
55
+ [/([ti])a$/i, "$1um"],
56
+ [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, "$1sis"],
57
+ [/(^analy)(sis|ses)$/i, "$1sis"],
58
+ [/([^f])ves$/i, "$1fe"],
59
+ [/(hive)s$/i, "$1"],
60
+ [/(tive)s$/i, "$1"],
61
+ [/([lr])ves$/i, "$1f"],
62
+ [/([^aeiouy]|qu)ies$/i, "$1y"],
63
+ [/(s)eries$/i, "$1eries"],
64
+ [/(m)ovies$/i, "$1ovie"],
65
+ [/(x|ch|ss|sh)es$/i, "$1"],
66
+ [/^(m|l)ice$/i, "$1ouse"],
67
+ [/(bus)(es)?$/i, "$1"],
68
+ [/(o)es$/i, "$1"],
69
+ [/(shoe)s$/i, "$1"],
70
+ [/(cris|test)(is|es)$/i, "$1is"],
71
+ [/^(a)x[ie]s$/i, "$1xis"],
72
+ [/(octop|vir)(us|i)$/i, "$1us"],
73
+ [/(alias|status)(es)?$/i, "$1"],
74
+ [/^(ox)en/i, "$1"],
75
+ [/(vert|ind)ices$/i, "$1ex"],
76
+ [/(matr)ices$/i, "$1ix"],
77
+ [/(quiz)zes$/i, "$1"],
78
+ [/(database)s$/i, "$1"],
79
+ ...IRREGULARS.flatMap(([singular, plural]) => irregular(singular, plural, singular))
80
+ ];
81
+ /** Words with no plural, matched as the last word (Rails' `\b<word>\z`). */
82
+ const UNCOUNTABLE = /\b(?:equipment|information|rice|money|species|series|fish|sheep|jeans|police)$/i;
83
+ /**
84
+ * Rails' `irregular`: rules turning either form into `into` (the plural for plural rules, the
85
+ * singular for singular ones), keeping the first letter's case.
86
+ */
87
+ function irregular(singular, plural, into) {
88
+ 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)}`]];
89
+ }
90
+ /** Applies the last rule that matches, as Rails does; uncountable words stay as they are. */
91
+ function inflect(word, rules) {
92
+ if (word === "" || UNCOUNTABLE.test(word)) return word;
93
+ for (let index = rules.length - 1; index >= 0; index--) {
94
+ const [pattern, replacement] = rules[index];
95
+ if (pattern.test(word)) return word.replace(pattern, replacement);
96
+ }
97
+ return word;
98
+ }
99
+ /** Rails' `pluralize`: `category` → `categories`, `person` → `people`, `sheep` → `sheep`. */
100
+ function pluralize(word) {
101
+ return inflect(word, PLURALS);
102
+ }
103
+ /** Rails' `singularize`: `categories` → `category`, `people` → `person`, `line_items` → `line_item`. */
104
+ function singularize(word) {
105
+ return inflect(word, SINGULARS);
106
+ }
107
+ //#endregion
108
+ //#region src/epoch-storage.ts
109
+ /** A datetime held in an `INTEGER` column as seconds or milliseconds since 1970. */
110
+ const epochStorages = ["unixSeconds", "unixMilliseconds"];
111
+ //#endregion
112
+ export { underscore as a, camelize as i, pluralize as n, singularize as r, epochStorages as t };
@@ -0,0 +1,240 @@
1
+ import { a as underscore, n as pluralize } from "./epoch-storage-o2aoOH7H.mjs";
2
+ import { d as byName, i as exportName } from "./storage-override-CpbkdIqE.mjs";
3
+ //#region cli/generate/migration-plan.ts
4
+ /** What to do, read from a migration's name: `create_products`, `add_sku_to_products`, …; else empty. */
5
+ function migrationPlan(name) {
6
+ const words = underscore(name);
7
+ const create = /^create_(\w+)$/.exec(words);
8
+ if (create) return {
9
+ kind: "create",
10
+ table: pluralize(create[1])
11
+ };
12
+ const add = /^add_\w+?_to_(\w+)$/.exec(words);
13
+ if (add) return {
14
+ kind: "add",
15
+ table: pluralize(add[1])
16
+ };
17
+ const remove = /^remove_\w+?_from_(\w+)$/.exec(words);
18
+ return remove ? {
19
+ kind: "remove",
20
+ table: pluralize(remove[1])
21
+ } : { kind: "empty" };
22
+ }
23
+ /** The index the generators name a column's index by: `index_products_on_sku`. */
24
+ function indexName(table, column) {
25
+ return `index_${table}_on_${column}`;
26
+ }
27
+ //#endregion
28
+ //#region cli/generate/migration-sql.ts
29
+ /** A name as SQL: quoted only when the database reserves it, so migrations stay readable. */
30
+ function quotedName(dialect, name) {
31
+ return dialect.reserved.has(name) ? `"${name}"` : name;
32
+ }
33
+ /** A default as a SQL literal: `TRUE`, `1.5`, `'it''s'`. */
34
+ function literal(value) {
35
+ if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
36
+ return typeof value === "number" ? String(value) : `'${value.replaceAll("'", "''")}'`;
37
+ }
38
+ /** A column's definition, as `CREATE TABLE` and `ADD COLUMN` write it. */
39
+ function definition(column, { dialect, keys }, notNull) {
40
+ const name = quotedName(dialect, column.name);
41
+ if (column.type === "references") {
42
+ const type = (keys.get(column.references) ?? dialect.guessedKeyType).toUpperCase();
43
+ const target = quotedName(dialect, column.references);
44
+ return `${name} ${type}${notNull ? " NOT NULL" : ""} REFERENCES ${target} (id)`;
45
+ }
46
+ const parts = [name, dialect.types[column.type]];
47
+ if (notNull) parts.push("NOT NULL");
48
+ if (column.default !== void 0) parts.push(`DEFAULT ${literal(column.default)}`);
49
+ const check = dialect.check?.(column, name);
50
+ if (check !== void 0) parts.push(check);
51
+ return parts.join(" ");
52
+ }
53
+ /** `CREATE [UNIQUE] INDEX` for each indexed column. */
54
+ function indexes(dialect, table, columns) {
55
+ return columns.filter((column) => column.index !== "none").map((column) => {
56
+ const unique = column.index === "unique" ? "UNIQUE " : "";
57
+ const on = `${quotedName(dialect, table)} (${quotedName(dialect, column.name)})`;
58
+ return `CREATE ${unique}INDEX ${indexName(table, column.name)} ON ${on};\n`;
59
+ }).join("");
60
+ }
61
+ /** `CREATE TABLE`, with its key, columns, timestamps and indexes. */
62
+ function createTable(table, change, writing) {
63
+ const { dialect } = writing;
64
+ const lines = [dialect.key(change.options.integerId === true)];
65
+ for (const column of change.columns) lines.push(definition(column, writing, column.notNull));
66
+ if (change.options.timestamps !== false) {
67
+ const type = dialect.timestampType;
68
+ lines.push(`created_at ${type} NOT NULL`, `updated_at ${type} NOT NULL`);
69
+ }
70
+ const body = lines.join(",\n ");
71
+ return `CREATE TABLE ${quotedName(dialect, table)} (\n ${body}\n);\n${indexes(dialect, table, change.columns)}`;
72
+ }
73
+ /** `ADD COLUMN` for each column; a reference added later can be null, as Rails' `add_reference`. */
74
+ function addColumns(table, columns, writing) {
75
+ const { dialect } = writing;
76
+ for (const column of columns) {
77
+ const error = dialect.addRefusal?.(table, column);
78
+ if (error !== void 0) return {
79
+ ok: false,
80
+ error
81
+ };
82
+ }
83
+ return {
84
+ ok: true,
85
+ sql: columns.map((column) => {
86
+ const notNull = column.type !== "references" && column.notNull;
87
+ return `ALTER TABLE ${quotedName(dialect, table)} ADD COLUMN ${definition(column, writing, notNull)};\n`;
88
+ }).join("") + indexes(dialect, table, columns)
89
+ };
90
+ }
91
+ /** The SQL for the migration the change names, or why it can't be written. */
92
+ function migrationFor(change, writing) {
93
+ const { name, columns } = change;
94
+ const plan = migrationPlan(name);
95
+ if (plan.kind === "empty") return columns.length > 0 ? {
96
+ ok: false,
97
+ error: `${name}: columns only go with Create…, Add…To… or Remove…From… migrations`
98
+ } : {
99
+ ok: true,
100
+ sql: "-- Write the migration's SQL here.\n"
101
+ };
102
+ if (columns.length === 0 && plan.kind !== "create") return {
103
+ ok: false,
104
+ error: `${name}: name the columns to ${plan.kind} (sku:string)`
105
+ };
106
+ if (plan.kind === "create") return {
107
+ ok: true,
108
+ sql: createTable(plan.table, change, writing)
109
+ };
110
+ if (plan.kind === "add") return addColumns(plan.table, columns, writing);
111
+ return {
112
+ ok: true,
113
+ sql: columns.map((column) => writing.dialect.dropColumn(plan.table, column.name)).join("")
114
+ };
115
+ }
116
+ /** Notes for references to tables the migrations don't make yet: their key type is a guess. */
117
+ function referenceNotes(change, dialect) {
118
+ if (migrationPlan(change.name).kind === "remove") return [];
119
+ return change.columns.filter((column) => column.type === "references" && !change.keys.has(column.references)).map((column) => `${column.references} isn't in the migrations yet, so ${column.name} is ${dialect.guessedKeyType}`);
120
+ }
121
+ /**
122
+ * A migration's SQL in the dialect given: a table created, columns added or removed, or an empty
123
+ * migration, as its name says (`CreateProducts`, `AddSkuToProducts`, …), with a note for each key
124
+ * type it guessed.
125
+ */
126
+ function migrationSql(change, dialect) {
127
+ const result = migrationFor(change, {
128
+ dialect,
129
+ keys: change.keys
130
+ });
131
+ if (!result.ok) return result;
132
+ const notes = referenceNotes(change, dialect);
133
+ return notes.length === 0 ? result : {
134
+ ...result,
135
+ notes
136
+ };
137
+ }
138
+ //#endregion
139
+ //#region cli/schema/tables.ts
140
+ const noFindings = () => ({
141
+ errors: [],
142
+ notes: [],
143
+ textDates: []
144
+ });
145
+ function merge(into, from) {
146
+ into.errors.push(...from.errors);
147
+ into.notes.push(...from.notes);
148
+ into.textDates.push(...from.textDates);
149
+ }
150
+ /** A table's attributes, in column order, with what their columns turn up. */
151
+ function attributesOf(columns, convert) {
152
+ const attributes = {};
153
+ const found = noFindings();
154
+ const columnOf = /* @__PURE__ */ new Map();
155
+ for (const column of columns) {
156
+ const converted = convert(column);
157
+ if (!converted.ok) {
158
+ found.errors.push(converted.error);
159
+ continue;
160
+ }
161
+ const { attribute, spec, note, textDate } = converted;
162
+ const taken = columnOf.get(attribute);
163
+ if (taken !== void 0) found.errors.push(`${column.table}: columns ${taken} and ${column.name} would both be the attribute ${attribute}; rename one`);
164
+ columnOf.set(attribute, column.name);
165
+ attributes[attribute] = spec;
166
+ if (note !== void 0) found.notes.push(note);
167
+ if (textDate) found.textDates.push(`${column.table}.${column.name}`);
168
+ }
169
+ return {
170
+ attributes,
171
+ ...found
172
+ };
173
+ }
174
+ /** One table's schema, or the errors that stop it from being generated. */
175
+ function tableSchema(table, reading) {
176
+ const { name, columns, lastChangedBy, keyType } = table;
177
+ const keys = columns.filter((column) => column.primaryKey).map((column) => column.name);
178
+ if (keys.length !== 1) {
179
+ const error = keys.length === 0 ? reading.missingKey(name) : `${name}: a composite primary key (${keys.join(", ")}) isn't supported; give the table a single key`;
180
+ return {
181
+ ...noFindings(),
182
+ errors: [error]
183
+ };
184
+ }
185
+ const { attributes, ...found } = attributesOf(columns, reading.convert);
186
+ const generated = {
187
+ name,
188
+ exportName: exportName(name),
189
+ primaryKey: keys[0],
190
+ lastChangedBy
191
+ };
192
+ const withKeyType = keyType === void 0 ? {} : { keyType };
193
+ return {
194
+ table: {
195
+ ...generated,
196
+ attributes,
197
+ ...withKeyType
198
+ },
199
+ ...found
200
+ };
201
+ }
202
+ /** Tables whose names become the same export (`line_items`, `line-items` → `lineItems`). */
203
+ function exportCollisions(names) {
204
+ const seen = /* @__PURE__ */ new Map();
205
+ const errors = [];
206
+ for (const name of names) {
207
+ const as = exportName(name);
208
+ const other = seen.get(as);
209
+ if (other !== void 0) errors.push(`${other} and ${name} would both be exported as ${as}; rename one of the tables`);
210
+ seen.set(as, name);
211
+ }
212
+ return errors;
213
+ }
214
+ /**
215
+ * The generated schema's tables, from the tables an adapter read, in alphabetical order (so the
216
+ * result only changes with the schema), or every error that stops them.
217
+ */
218
+ function generatedSchema(read, reading) {
219
+ const sorted = [...read].sort((a, b) => byName(a.name, b.name));
220
+ const found = noFindings();
221
+ found.errors.push(...exportCollisions(sorted.map((table) => table.name)));
222
+ const tables = [];
223
+ for (const table of sorted) {
224
+ const result = tableSchema(table, reading);
225
+ merge(found, result);
226
+ if (result.table !== void 0) tables.push(result.table);
227
+ }
228
+ const { errors, notes, textDates } = found;
229
+ return errors.length > 0 ? {
230
+ ok: false,
231
+ errors
232
+ } : {
233
+ ok: true,
234
+ tables,
235
+ notes,
236
+ textDates
237
+ };
238
+ }
239
+ //#endregion
240
+ export { migrationPlan as a, indexName as i, migrationSql as n, quotedName as r, generatedSchema as t };
@@ -0,0 +1,33 @@
1
+ import { ct as NoDatabase } from "./generated-model-Cnt0Ot9q.mjs";
2
+ //#region src/request-database.ts
3
+ /**
4
+ * The request's database for a query on `binding` outside a Worker, or a `NoDatabase` saying what
5
+ * to do. `connect` is how the adapter's docs open one, such as `connect(env.DB)`.
6
+ */
7
+ function onlyRequested(requested, binding, connect) {
8
+ if (requested.length === 1) return requested[0];
9
+ const reason = requested.length > 1 ? "withDatabase was given several, and outside a Worker a binding can't tell which" : binding === void 0 ? "its Model's base class holds no generated schema, which names its binding" : `the binding ${binding} is only there inside a Worker`;
10
+ throw new NoDatabase(`No database for this query: ${reason}. Wrap the code in withDatabase(${connect}, …), or use db.model(Model)`);
11
+ }
12
+ //#endregion
13
+ //#region src/workers-env.ts
14
+ /** Whether importing `cloudflare:workers` failed because this isn't a Worker (Node, scripts). */
15
+ function isOutsideWorker(error) {
16
+ const { code, message } = error;
17
+ return code === "ERR_UNSUPPORTED_ESM_URL_SCHEME" || code === "ERR_MODULE_NOT_FOUND" || /cloudflare:workers/.test(String(message));
18
+ }
19
+ /**
20
+ * The Worker's `env`, from `load`, or undefined outside a Worker (Node, scripts). An adapter
21
+ * passes `() => import("cloudflare:workers")` from its own module, with that literal specifier:
22
+ * Wrangler only bundles those, and a test that mocks the module with the adapter inlined reaches it.
23
+ */
24
+ async function workersEnv(load) {
25
+ try {
26
+ return (await load()).env;
27
+ } catch (error) {
28
+ if (isOutsideWorker(error)) return void 0;
29
+ throw error;
30
+ }
31
+ }
32
+ //#endregion
33
+ export { onlyRequested as n, workersEnv as t };
@@ -0,0 +1,21 @@
1
+ import { i as AnyDatabase } from "./adapter-AGKp6wfO.mjs";
2
+ //#region src/request-database.d.ts
3
+ /**
4
+ * The request's database for a query on `binding` outside a Worker, or a `NoDatabase` saying what
5
+ * to do. `connect` is how the adapter's docs open one, such as `connect(env.DB)`.
6
+ */
7
+ declare function onlyRequested(requested: readonly AnyDatabase[], binding: string | undefined, connect: string): AnyDatabase;
8
+ //#endregion
9
+ //#region src/workers-env.d.ts
10
+ /** A Worker's `env`: its bindings and variables, by name. */
11
+ type WorkersEnv = Record<string, unknown>;
12
+ /**
13
+ * The Worker's `env`, from `load`, or undefined outside a Worker (Node, scripts). An adapter
14
+ * passes `() => import("cloudflare:workers")` from its own module, with that literal specifier:
15
+ * Wrangler only bundles those, and a test that mocks the module with the adapter inlined reaches it.
16
+ */
17
+ declare function workersEnv(load: () => Promise<{
18
+ env: unknown;
19
+ }>): Promise<WorkersEnv | undefined>;
20
+ //#endregion
21
+ export { workersEnv as n, onlyRequested as r, WorkersEnv as t };