@forestfuture/active-record 0.6.0 → 0.8.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.
@@ -0,0 +1,46 @@
1
+ import { n as Model, o as readyModel, s as isReservedScopeName } from "./batch-ReqVoCfa.mjs";
2
+ import { $ as modelNameOf, et as ownValueSetter, ot as ancestors, st as staticBelow } from "./generated-model-g5oWsDKE.mjs";
3
+ // src/define-schema.ts
4
+ const listed = /* @__PURE__ */ new Set();
5
+ /**
6
+ * A generated schema, as `schema.ts` declares it: `export const schema = defineSchema({ … })`.
7
+ * A generated Model's attributes are settled when it's first used, so its enum scopes would
8
+ * only appear then; `Post.published()` is often that first use. So each scope the schema lists
9
+ * is a static of every Model now: on a Model it's listed for, reading it readies the Model,
10
+ * which defines the scope on it; on any other, it's `undefined`.
11
+ */
12
+ function defineSchema(schema) {
13
+ for (const names of Object.values(schema.enumScopes ?? {})) for (const name of names) listScope(name);
14
+ return schema;
15
+ }
16
+ function listScope(name) {
17
+ if (listed.has(name) || isReservedScopeName(name) || name in Model) return;
18
+ listed.add(name);
19
+ Object.defineProperty(Model, name, {
20
+ configurable: true,
21
+ get() {
22
+ return enumScopeOf(this, name);
23
+ },
24
+ set: ownValueSetter(name)
25
+ });
26
+ }
27
+ /** The scope `name` of `model`, once it's ready, if its schema lists it; else `undefined`. */
28
+ function enumScopeOf(model, name) {
29
+ if (!isListedFor(model, name)) return void 0;
30
+ readyModel(model);
31
+ return staticBelow(model, Model, name)?.value;
32
+ }
33
+ /**
34
+ * Whether the schema `model`'s base holds lists `name` among the enum scopes of `model`, or of a
35
+ * class it extends: a subclass of a generated Model has its scopes, by the Model's `modelName`.
36
+ */
37
+ function isListedFor(model, name) {
38
+ const holder = ancestors(model).find((each) => Object.hasOwn(each, "schema"));
39
+ const scopes = holder?.schema?.enumScopes;
40
+ if (scopes === void 0) return false;
41
+ return ancestors(model).filter((each) => each !== holder).some((each) => {
42
+ const modelName = modelNameOf(each);
43
+ return Object.hasOwn(scopes, modelName) && scopes[modelName].includes(name);
44
+ });
45
+ }
46
+ export { defineSchema as t };
@@ -0,0 +1,220 @@
1
+ import { E as underscore, T as camelize, g as reservedWords, l as uncastable, o as castValue, t as epochStorages } from "./epoch-storage-CDlQZcBB.mjs";
2
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
3
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
4
+ // cli/project/paths.ts
5
+ /** A relative path with forward slashes, as migrations are named 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
+ // cli/project/migrations.ts
19
+ /** Plain character order, the same on every machine (unlike `localeCompare`). */
20
+ function byName(a, b) {
21
+ return a < b ? -1 : a > b ? 1 : 0;
22
+ }
23
+ /** A migration path's leading number (`0009_x.sql`, `20261108090503_x/migration.sql`), before its first `_`; NaN for none. */
24
+ function leadingNumber(path) {
25
+ return Number.parseInt(path.split("/")[0].split("_")[0], 10);
26
+ }
27
+ /** Two segments of migration paths: by their leading numbers, numbered first, then by name. */
28
+ function bySegment(a, b) {
29
+ const [left, right] = [leadingNumber(a), leadingNumber(b)];
30
+ const [leftNumbered, rightNumbered] = [Number.isFinite(left), Number.isFinite(right)];
31
+ if (leftNumbered && rightNumbered && left !== right) return left - right;
32
+ if (leftNumbered !== rightNumbered) return leftNumbered ? -1 : 1;
33
+ return byName(a, b);
34
+ }
35
+ /**
36
+ * Migrations in the order they're applied, as migration tools order them: folder by folder, by
37
+ * their leading numbers (`9_…` before `10_…`), those without one after them, and by name between
38
+ * equals; a path that's the start of another comes first.
39
+ */
40
+ function byVersion(a, b) {
41
+ const [left, right] = [a.split("/"), b.split("/")];
42
+ for (let index = 0; index < Math.min(left.length, right.length); index++) {
43
+ const order = bySegment(left[index], right[index]);
44
+ if (order !== 0) return order;
45
+ }
46
+ return left.length - right.length;
47
+ }
48
+ /** A database's migrations, in the order they're applied: by version. */
49
+ function migrationsOf(target) {
50
+ const { migrationsPattern } = target.database;
51
+ 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(byVersion).map((name) => ({
52
+ name,
53
+ sql: readFileSync(join(target.migrationsDir, name), "utf8")
54
+ }));
55
+ }
56
+ /**
57
+ * Whether a database's migrations are in folders (`migrations/0000_init/migration.sql`, as
58
+ * Drizzle writes them) with no `migrations_pattern` in the config to find them.
59
+ */
60
+ function hasNestedMigrations(target) {
61
+ const dir = target.migrationsDir;
62
+ if (target.database.migrationsPattern !== void 0 || !existsSync(dir)) return false;
63
+ const entries = readdirSync(dir, { withFileTypes: true });
64
+ if (entries.some((entry) => entry.isFile() && entry.name.endsWith(".sql"))) return false;
65
+ return entries.some((entry) => entry.isDirectory() && existsSync(join(dir, entry.name, "migration.sql")));
66
+ }
67
+ // cli/project/config-file.ts
68
+ /** The project's config file's name, which `--config` replaces. */
69
+ const configFileName = "active-record.jsonc";
70
+ /** JSON with `//` and `/* *\/` comments and trailing commas. */
71
+ function parseJsonc(text) {
72
+ const kept = new KeptText();
73
+ for (let index = 0; index < text.length; index++) {
74
+ const char = text[index];
75
+ const comment = char === "/" ? endOfComment(text, index) : void 0;
76
+ if (char === "\"") {
77
+ const end = endOfString(text, index);
78
+ kept.add(text.slice(index, end));
79
+ index = end - 1;
80
+ } else if (comment !== void 0) index = comment - 1;
81
+ else kept.add(char);
82
+ }
83
+ return JSON.parse(kept.text());
84
+ }
85
+ /** The text JSON.parse reads: what parseJsonc keeps of JSONC, less its trailing commas. */
86
+ var KeptText = class {
87
+ #parts = [];
88
+ /** Where the last comma is, while only whitespace has come after it. */
89
+ #trailingComma = -1;
90
+ /** Keeps a string literal or a character outside one. */
91
+ add(part) {
92
+ if ((part === "}" || part === "]") && this.#trailingComma >= 0) this.#parts[this.#trailingComma] = "";
93
+ if (!/^\s$/.test(part)) this.#trailingComma = part === "," ? this.#parts.length : -1;
94
+ this.#parts.push(part);
95
+ }
96
+ text() {
97
+ return this.#parts.join("");
98
+ }
99
+ };
100
+ /** Just past the comment starting at `start`, keeping a line comment's newline; undefined when none does. */
101
+ function endOfComment(text, start) {
102
+ if (text.startsWith("//", start)) {
103
+ const newline = text.indexOf("\n", start);
104
+ return newline < 0 ? text.length : newline;
105
+ }
106
+ if (!text.startsWith("/*", start)) return void 0;
107
+ const end = text.indexOf("*/", start + 2);
108
+ if (end < 0) throw new SyntaxError("Unterminated /* comment");
109
+ return end + 2;
110
+ }
111
+ /** Just past the string literal starting at `start`. */
112
+ function endOfString(text, start) {
113
+ let index = start + 1;
114
+ while (index < text.length && text[index] !== "\"") index += text[index] === "\\" ? 2 : 1;
115
+ return index + 1;
116
+ }
117
+ /**
118
+ * The project's `active-record.jsonc` in `cwd`, or the file `configPath` names; undefined when
119
+ * there's none, or why it can't be read.
120
+ */
121
+ function readProjectConfig(cwd, configPath) {
122
+ const file = resolve(cwd, configPath ?? "active-record.jsonc");
123
+ if (!existsSync(file)) return configPath === void 0 ? void 0 : `${configPath} isn't there`;
124
+ let settings;
125
+ try {
126
+ settings = parseJsonc(readFileSync(file, "utf8"));
127
+ } catch (error) {
128
+ return `${basename(file)} couldn't be read: ${error.message}`;
129
+ }
130
+ if (typeof settings !== "object" || settings === null || Array.isArray(settings)) return `${basename(file)} isn't an object`;
131
+ return {
132
+ file,
133
+ dir: dirname(file),
134
+ settings
135
+ };
136
+ }
137
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
138
+ /**
139
+ * The databases the project's `active-record.jsonc` (or the file `configPath` names) declares, each
140
+ * entry an object; or why there are none, saying to run `init` when there's no file.
141
+ */
142
+ function projectDatabases(cwd, configPath) {
143
+ const config = readProjectConfig(cwd, configPath);
144
+ if (config === void 0) return `No ${configFileName} here, which names the project's databases and their adapter: run \`npx active-record init\` to write one`;
145
+ if (typeof config === "string") return config;
146
+ const name = basename(config.file);
147
+ const { databases } = config.settings;
148
+ if (!isObject(databases) || Object.keys(databases).length === 0) return `${name} has no databases`;
149
+ const wrong = Object.keys(databases).find((binding) => !isObject(databases[binding]));
150
+ if (wrong !== void 0) return `${name}: databases.${wrong} isn't an object`;
151
+ return {
152
+ file: config.file,
153
+ dir: config.dir,
154
+ databases
155
+ };
156
+ }
157
+ // cli/project/names.ts
158
+ /** A column's attribute: camelCase, keeping any leading underscores (`_secret` stays). */
159
+ function attributeName(column) {
160
+ const lead = /^_*/.exec(column)[0];
161
+ return lead + camelize(column.slice(lead.length));
162
+ }
163
+ /** Words JavaScript doesn't allow as a `const` name, and the generated file's own names. */
164
+ const reserved = /* @__PURE__ */ new Set([...reservedWords, "tables"]);
165
+ /**
166
+ * The `const` a table is exported as: its words in camelCase (`line_items` → `lineItems`),
167
+ * never a reserved word (`default` → `defaultTable`) or starting with a digit (`2fa` →
168
+ * `table2fa`).
169
+ */
170
+ function exportName(table) {
171
+ const name = table.split(/[^\p{L}\p{N}]+/u).filter(Boolean).map((word, index) => index === 0 ? word : word[0].toUpperCase() + word.slice(1)).join("");
172
+ if (name === "" || /^\p{N}/u.test(name)) return `table${name}`;
173
+ return reserved.has(name) ? `${name}Table` : name;
174
+ }
175
+ /** A class name from any spelling: `line_item`, `lineItem` → `LineItem`. */
176
+ function classify(name) {
177
+ const camel = camelize(underscore(name));
178
+ return camel.charAt(0).toUpperCase() + camel.slice(1);
179
+ }
180
+ /** A Model's module, in kebab-case: `LineItem` → `line-item` (its file is `line-item.ts`). */
181
+ function moduleName(className) {
182
+ return underscore(className).replaceAll("_", "-");
183
+ }
184
+ /** `"A"`, `"A or B"`, `"A, B or C"`, or with `"and"`, `"A, B and C"`. */
185
+ function listed(names, last = "or") {
186
+ if (names.length < 2) return names.join("");
187
+ return `${names.slice(0, -1).join(", ")} ${last} ${names.at(-1)}`;
188
+ }
189
+ // cli/schema/cast-default.ts
190
+ const castDefaultTypes = [
191
+ "decimal",
192
+ "date",
193
+ "time"
194
+ ];
195
+ /** Whether a type's literal default is cast as an assigned value is. */
196
+ function isCastDefaultType(type) {
197
+ return castDefaultTypes.includes(type);
198
+ }
199
+ /**
200
+ * A literal default's text as the attribute's value, with a decimal's `digits` (#398) (`1.50` → `"1.5"`, `'09:30'` → `"09:30:00"`),
201
+ * or undefined for text the type can't hold, whose default then stays with the database.
202
+ */
203
+ function castDefault(type, text, digits = {}) {
204
+ const value = castValue({
205
+ type,
206
+ ...digits
207
+ }, text);
208
+ return value === uncastable ? void 0 : { literal: value };
209
+ }
210
+ // cli/schema/storage-override.ts
211
+ /** Drizzle's `mode` for each epoch storage, which a note names for a reader with its schema open. */
212
+ const drizzleModes = {
213
+ unixSeconds: "\"timestamp\"",
214
+ unixMilliseconds: "\"timestamp_ms\""
215
+ };
216
+ /** The override that reads a Unix time as a `Date`, for a note; with Drizzle's modes named if asked. */
217
+ function storageOverride(withDrizzleModes) {
218
+ return `{ type: "datetime", storage: ${epochStorages.map((storage) => withDrizzleModes ? `"${storage}" (${drizzleModes[storage]})` : `"${storage}"`).join(" or ")} }`;
219
+ }
220
+ export { importPath as _, classify as a, moduleName as c, projectDatabases as d, byName as f, migrationsOf as g, leadingNumber as h, attributeName as i, configFileName as l, hasNestedMigrations as m, castDefault as n, exportName as o, byVersion as p, isCastDefaultType as r, listed as s, storageOverride as t, parseJsonc as u, shown as v, slashed as y };