@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.
@@ -0,0 +1,187 @@
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 { basename, dirname, join, relative, resolve, sep } from "node:path";
4
+ //#region 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
+ //#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 migration path's leading number (`0009_x.sql`, `20261108090503_x/migration.sql`), before its first `_`; NaN for none. */
25
+ function leadingNumber(path) {
26
+ return Number.parseInt(path.split("/")[0].split("_")[0], 10);
27
+ }
28
+ /** Two segments of migration paths: by their leading numbers, numbered first, then by name. */
29
+ function bySegment(a, b) {
30
+ const [left, right] = [leadingNumber(a), leadingNumber(b)];
31
+ const [leftNumbered, rightNumbered] = [Number.isFinite(left), Number.isFinite(right)];
32
+ if (leftNumbered && rightNumbered && left !== right) return left - right;
33
+ if (leftNumbered !== rightNumbered) return leftNumbered ? -1 : 1;
34
+ return byName(a, b);
35
+ }
36
+ /**
37
+ * Migrations in the order they're applied, as migration tools order them: folder by folder, by
38
+ * their leading numbers (`9_…` before `10_…`), those without one after them, and by name between
39
+ * equals; a path that's the start of another comes first.
40
+ */
41
+ function byVersion(a, b) {
42
+ const [left, right] = [a.split("/"), b.split("/")];
43
+ for (let index = 0; index < Math.min(left.length, right.length); index++) {
44
+ const order = bySegment(left[index], right[index]);
45
+ if (order !== 0) return order;
46
+ }
47
+ return left.length - right.length;
48
+ }
49
+ /** A database's migrations, in the order they're applied: by version. */
50
+ function migrationsOf(target) {
51
+ const { migrationsPattern } = target.database;
52
+ 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) => ({
53
+ name,
54
+ sql: readFileSync(join(target.migrationsDir, name), "utf8")
55
+ }));
56
+ }
57
+ /**
58
+ * Whether a database's migrations are in folders (`migrations/0000_init/migration.sql`, as
59
+ * Drizzle writes them) with no `migrations_pattern` in the config to find them.
60
+ */
61
+ function hasNestedMigrations(target) {
62
+ const dir = target.migrationsDir;
63
+ if (target.database.migrationsPattern !== void 0 || !existsSync(dir)) return false;
64
+ const entries = readdirSync(dir, { withFileTypes: true });
65
+ if (entries.some((entry) => entry.isFile() && entry.name.endsWith(".sql"))) return false;
66
+ return entries.some((entry) => entry.isDirectory() && existsSync(join(dir, entry.name, "migration.sql")));
67
+ }
68
+ //#endregion
69
+ //#region cli/project/config-file.ts
70
+ /** The project's config file's name, which `--config` replaces. */
71
+ const configFileName = "active-record.jsonc";
72
+ /** JSON with `//` and `/* *\/` comments and trailing commas. */
73
+ function parseJsonc(text) {
74
+ let out = "";
75
+ for (let index = 0; index < text.length; index++) {
76
+ const char = text[index];
77
+ if (char === "\"") {
78
+ const end = endOfString(text, index);
79
+ out += text.slice(index, end);
80
+ index = end - 1;
81
+ } else if (text.startsWith("//", index)) {
82
+ index = text.indexOf("\n", index) - 1;
83
+ if (index < 0) break;
84
+ } else if (text.startsWith("/*", index)) {
85
+ const end = text.indexOf("*/", index + 2);
86
+ if (end < 0) throw new SyntaxError("Unterminated /* comment");
87
+ index = end + 1;
88
+ } else out += char;
89
+ }
90
+ return JSON.parse(out.replace(/,(\s*[}\]])/g, "$1"));
91
+ }
92
+ /** Just past the string literal starting at `start`. */
93
+ function endOfString(text, start) {
94
+ let index = start + 1;
95
+ while (index < text.length && text[index] !== "\"") index += text[index] === "\\" ? 2 : 1;
96
+ return index + 1;
97
+ }
98
+ /**
99
+ * The project's `active-record.jsonc` in `cwd`, or the file `configPath` names; undefined when
100
+ * there's none, or why it can't be read.
101
+ */
102
+ function readProjectConfig(cwd, configPath) {
103
+ const file = resolve(cwd, configPath ?? "active-record.jsonc");
104
+ if (!existsSync(file)) return configPath === void 0 ? void 0 : `${configPath} isn't there`;
105
+ let settings;
106
+ try {
107
+ settings = parseJsonc(readFileSync(file, "utf8"));
108
+ } catch (error) {
109
+ return `${basename(file)} couldn't be read: ${error.message}`;
110
+ }
111
+ if (typeof settings !== "object" || settings === null || Array.isArray(settings)) return `${basename(file)} isn't an object`;
112
+ return {
113
+ file,
114
+ dir: dirname(file),
115
+ settings
116
+ };
117
+ }
118
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
119
+ /**
120
+ * The databases the project's `active-record.jsonc` (or the file `configPath` names) declares, each
121
+ * entry an object; or why there are none, saying to run `init` when there's no file.
122
+ */
123
+ function projectDatabases(cwd, configPath) {
124
+ const config = readProjectConfig(cwd, configPath);
125
+ 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`;
126
+ if (typeof config === "string") return config;
127
+ const name = basename(config.file);
128
+ const { databases } = config.settings;
129
+ if (!isObject(databases) || Object.keys(databases).length === 0) return `${name} has no databases`;
130
+ const wrong = Object.keys(databases).find((binding) => !isObject(databases[binding]));
131
+ if (wrong !== void 0) return `${name}: databases.${wrong} isn't an object`;
132
+ return {
133
+ file: config.file,
134
+ dir: config.dir,
135
+ databases
136
+ };
137
+ }
138
+ //#endregion
139
+ //#region cli/project/names.ts
140
+ /** Whether a name can be written bare: as a `const`, or as an object key without quotes. */
141
+ function isIdentifier(name) {
142
+ return /^[\p{L}_$][\p{L}\p{N}_$]*$/u.test(name);
143
+ }
144
+ /** A column's attribute: camelCase, keeping any leading underscores (`_secret` stays). */
145
+ function attributeName(column) {
146
+ const lead = /^_*/.exec(column)[0];
147
+ return lead + camelize(column.slice(lead.length));
148
+ }
149
+ /** Words JavaScript doesn't allow as a `const` name, and the generated file's own names. */
150
+ 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(" "));
151
+ /**
152
+ * The `const` a table is exported as: its words in camelCase (`line_items` → `lineItems`),
153
+ * never a reserved word (`default` → `defaultTable`) or starting with a digit (`2fa` →
154
+ * `table2fa`).
155
+ */
156
+ function exportName(table) {
157
+ const name = table.split(/[^\p{L}\p{N}]+/u).filter(Boolean).map((word, index) => index === 0 ? word : word[0].toUpperCase() + word.slice(1)).join("");
158
+ if (name === "" || /^\p{N}/u.test(name)) return `table${name}`;
159
+ return reserved.has(name) ? `${name}Table` : name;
160
+ }
161
+ /** A class name from any spelling: `line_item`, `lineItem` → `LineItem`. */
162
+ function classify(name) {
163
+ const camel = camelize(underscore(name));
164
+ return camel.charAt(0).toUpperCase() + camel.slice(1);
165
+ }
166
+ /** A Model's module, in kebab-case: `LineItem` → `line-item` (its file is `line-item.ts`). */
167
+ function moduleName(className) {
168
+ return underscore(className).replaceAll("_", "-");
169
+ }
170
+ /** `"A"`, `"A or B"`, `"A, B or C"`, or with `"and"`, `"A, B and C"`. */
171
+ function listed(names, last = "or") {
172
+ if (names.length < 2) return names.join("");
173
+ return `${names.slice(0, -1).join(", ")} ${last} ${names.at(-1)}`;
174
+ }
175
+ //#endregion
176
+ //#region cli/schema/storage-override.ts
177
+ /** Drizzle's `mode` for each epoch storage, which a note names for a reader with its schema open. */
178
+ const drizzleModes = {
179
+ unixSeconds: "\"timestamp\"",
180
+ unixMilliseconds: "\"timestamp_ms\""
181
+ };
182
+ /** The override that reads a Unix time as a `Date`, for a note; with Drizzle's modes named if asked. */
183
+ function storageOverride(withDrizzleModes) {
184
+ return `{ type: "datetime", storage: ${epochStorages.map((storage) => withDrizzleModes ? `"${storage}" (${drizzleModes[storage]})` : `"${storage}"`).join(" or ")} }`;
185
+ }
186
+ //#endregion
187
+ export { shown as _, isIdentifier as a, configFileName as c, byName as d, byVersion as f, importPath as g, migrationsOf as h, exportName as i, parseJsonc as l, leadingNumber as m, attributeName as n, listed as o, hasNestedMigrations as p, classify as r, moduleName as s, storageOverride as t, projectDatabases as u, slashed as v };