@neon-pixels/scripts 0.2.0 → 0.4.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,161 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
+ import { join, relative } from "node:path";
4
+ import { parseArgs } from "node:util";
5
+ import { i as parseAllowlist, t as buildTimeOnlyPackages } from "./allowlist-B_zgqKrH.js";
6
+ // src/absent-dependency/detect.ts
7
+ const PACKAGE_NAME_PATTERN = /^(@[A-Za-z0-9~-][A-Za-z0-9._~-]*\/)?[A-Za-z0-9~-][A-Za-z0-9._~-]*$/;
8
+ const SPECIFIER_QUOTES = "[\"'`]";
9
+ function assertPackageName(name) {
10
+ if (!PACKAGE_NAME_PATTERN.test(name)) throw new Error(`"${name}" is not a valid npm package name`);
11
+ }
12
+ function escapeForRegExp(text) {
13
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
14
+ }
15
+ function nodeModulesMarker(name) {
16
+ return `node_modules/${name}/`;
17
+ }
18
+ /** True when a path inside the output is, or is inside, `node_modules/<name>`. */
19
+ function pathContainsPackage(relativePath, name) {
20
+ return `/${relativePath.replaceAll("\\", "/")}/`.includes(`/${nodeModulesMarker(name)}`);
21
+ }
22
+ /** True when the file is a package.json that declares exactly this name. */
23
+ function isPackageManifestFor(relativePath, content, name) {
24
+ if (!/(^|[\\/])package\.json$/.test(relativePath)) return false;
25
+ try {
26
+ const manifest = JSON.parse(content);
27
+ return typeof manifest === "object" && manifest !== null && manifest.name === name;
28
+ } catch {
29
+ return false;
30
+ }
31
+ }
32
+ const specifierPatterns = /* @__PURE__ */ new Map();
33
+ function specifierPatternFor(name) {
34
+ const cached = specifierPatterns.get(name);
35
+ if (cached) return cached;
36
+ const pattern = new RegExp(`(?<![.\\w$])(?:from|import|(?:__)?require)\\s*\\(?\\s*${SPECIFIER_QUOTES}${escapeForRegExp(name)}(?:/[^"'\`]*)?${SPECIFIER_QUOTES}`);
37
+ specifierPatterns.set(name, pattern);
38
+ return pattern;
39
+ }
40
+ /**
41
+ * Finds a bundled or external copy by what bundlers leave in text: the
42
+ * `node_modules/<name>/` path in region comments and source maps, or an
43
+ * import/require of the name or one of its subpaths.
44
+ */
45
+ function contentSignal(content, name) {
46
+ if (content.includes(nodeModulesMarker(name))) return "node_modules reference";
47
+ return specifierPatternFor(name).test(content) ? "import specifier" : null;
48
+ }
49
+ // src/absent-dependency/run.ts
50
+ const DEFAULT_ALLOWLIST_PATH = "audit-allowlist.json";
51
+ const NUL_BYTE = "\0";
52
+ const BINARY_SNIFF_LENGTH = 8e3;
53
+ const LOG_PREFIX = "np-check-absent-dependency:";
54
+ function listOutputOnDisk(directory) {
55
+ return readdirSync(directory, {
56
+ recursive: true,
57
+ withFileTypes: true
58
+ }).map((entry) => {
59
+ const absolute = join(entry.parentPath, entry.name);
60
+ const target = entry.isSymbolicLink() ? statSync(absolute) : entry;
61
+ return {
62
+ path: relative(directory, absolute),
63
+ isFile: target.isFile()
64
+ };
65
+ }).sort((left, right) => left.path.localeCompare(right.path));
66
+ }
67
+ const systemEnvironment = {
68
+ isDirectory: (path) => existsSync(path) && statSync(path).isDirectory(),
69
+ listOutput: listOutputOnDisk,
70
+ readOutputFile: (directory, path) => readFileSync(join(directory, path), "utf-8"),
71
+ readTextFile: (path) => existsSync(path) ? readFileSync(path, "utf-8") : null
72
+ };
73
+ function parseOptions(argv) {
74
+ const { values, positionals } = parseArgs({
75
+ args: argv,
76
+ allowPositionals: true,
77
+ options: {
78
+ allowlist: { type: "string" },
79
+ "from-allowlist": { type: "boolean" }
80
+ }
81
+ });
82
+ const [directory, ...explicitNames] = positionals;
83
+ if (directory === void 0) throw new Error("usage: np-check-absent-dependency <output-dir> [package...] [--from-allowlist] [--allowlist <path>]");
84
+ return {
85
+ directory,
86
+ explicitNames,
87
+ allowlistPath: values.allowlist ?? (values["from-allowlist"] ? DEFAULT_ALLOWLIST_PATH : void 0)
88
+ };
89
+ }
90
+ function readBuildTimeNames(environment, allowlistPath) {
91
+ const content = environment.readTextFile(allowlistPath);
92
+ if (content === null) throw new Error(`allowlist file not found: ${allowlistPath}`);
93
+ return buildTimeOnlyPackages(parseAllowlist(content));
94
+ }
95
+ function resolveNames(environment, explicitNames, allowlistPath) {
96
+ const allowlistNames = allowlistPath === void 0 ? [] : readBuildTimeNames(environment, allowlistPath);
97
+ const names = [.../* @__PURE__ */ new Set([...explicitNames, ...allowlistNames])];
98
+ if (names.length === 0 && allowlistPath === void 0) throw new Error("no package names given: pass names or --from-allowlist");
99
+ names.forEach(assertPackageName);
100
+ return names;
101
+ }
102
+ function isBinary(content) {
103
+ return content.slice(0, BINARY_SNIFF_LENGTH).includes(NUL_BYTE);
104
+ }
105
+ function signalFor(name, entry, content) {
106
+ if (pathContainsPackage(entry.path, name)) return "node_modules path";
107
+ if (content === null) return null;
108
+ if (isPackageManifestFor(entry.path, content, name)) return "package.json name";
109
+ return contentSignal(content, name);
110
+ }
111
+ function readTextContent(entry, readContent) {
112
+ if (!entry.isFile) return null;
113
+ const content = readContent(entry);
114
+ return isBinary(content) ? null : content;
115
+ }
116
+ function findingsForEntry(names, entry, content) {
117
+ return names.flatMap((name) => {
118
+ const signal = signalFor(name, entry, content);
119
+ return signal === null ? [] : [{
120
+ name,
121
+ path: entry.path,
122
+ signal
123
+ }];
124
+ });
125
+ }
126
+ function findDependencies(names, entries, readContent) {
127
+ const found = /* @__PURE__ */ new Map();
128
+ for (const entry of entries) {
129
+ const remaining = names.filter((name) => !found.has(name));
130
+ if (remaining.length === 0) break;
131
+ findingsForEntry(remaining, entry, readTextContent(entry, readContent)).forEach((finding) => found.set(finding.name, finding));
132
+ }
133
+ return [...found.values()];
134
+ }
135
+ function check(argv, environment) {
136
+ const { directory, explicitNames, allowlistPath } = parseOptions(argv);
137
+ if (!environment.isDirectory(directory)) throw new Error(`output directory not found: ${directory}`);
138
+ const names = resolveNames(environment, explicitNames, allowlistPath);
139
+ const entries = environment.listOutput(directory);
140
+ if (!entries.some((entry) => entry.isFile)) throw new Error(`output directory is empty: ${directory}`);
141
+ return {
142
+ names,
143
+ findings: findDependencies(names, entries, (entry) => environment.readOutputFile(directory, entry.path))
144
+ };
145
+ }
146
+ /** Checks a build output for the named packages and returns the exit code. */
147
+ function runAbsentDependencyCheck(argv, environment = systemEnvironment) {
148
+ try {
149
+ const { names, findings } = check(argv, environment);
150
+ for (const finding of findings) console.error(`${LOG_PREFIX} ${finding.name} found in ${finding.path} (${finding.signal})`);
151
+ if (findings.length === 0) console.log(`${LOG_PREFIX} ${names.length} packages checked, none in the output`);
152
+ return findings.length > 0 ? 1 : 0;
153
+ } catch (error) {
154
+ const reason = error instanceof Error ? error.message : String(error);
155
+ console.error(`${LOG_PREFIX} ${reason}`);
156
+ return 1;
157
+ }
158
+ }
159
+ // src/check-absent-dependency.ts
160
+ process.exitCode = runAbsentDependencyCheck(process.argv.slice(2));
161
+ export {};
@@ -0,0 +1,128 @@
1
+ #!/usr/bin/env node
2
+ import { r as prefixedConsole, t as describeError } from "./workflow-command-Bb1eVLow.js";
3
+ import { c as systemFiles, o as readJournal, s as readJournalMigrations, t as readMigrationsOptions } from "./options-C_apa01R.js";
4
+ // src/migrations/drift.ts
5
+ const HASH_PREVIEW_LENGTH = 12;
6
+ function preview(hash) {
7
+ return `${hash.slice(0, HASH_PREVIEW_LENGTH)}...`;
8
+ }
9
+ function findWatermark(recorded) {
10
+ return recorded.reduce((highest, row) => Math.max(highest, Number(row.created_at)), 0);
11
+ }
12
+ function findUnknownHashes(recorded, journalByHash) {
13
+ return recorded.filter((row) => !journalByHash.has(row.hash)).map((row) => ({
14
+ kind: "unknown-hash",
15
+ detail: `Recorded migration ${preview(row.hash)} is not in the journal. A migration file was deleted or its contents were edited after being applied.`
16
+ }));
17
+ }
18
+ function findTimestampDrift(recorded, journalByHash) {
19
+ const watermark = findWatermark(recorded);
20
+ return recorded.flatMap((row) => {
21
+ const entry = journalByHash.get(row.hash);
22
+ if (!entry || entry.folderMillis <= watermark) return [];
23
+ return [{
24
+ kind: "timestamp-drift",
25
+ detail: `Migration ${preview(entry.hash)} is recorded as applied at ${row.created_at} but the journal says ${entry.folderMillis}, above the watermark ${watermark}. The journal was rewritten after this migration ran; drizzle will re-apply already-applied DDL.`
26
+ }];
27
+ });
28
+ }
29
+ function findSilentlySkipped(recorded, journal) {
30
+ const recordedHashes = new Set(recorded.map((row) => row.hash));
31
+ const watermark = findWatermark(recorded);
32
+ return journal.filter((migration) => !recordedHashes.has(migration.hash)).filter((migration) => migration.folderMillis <= watermark).map((migration) => ({
33
+ kind: "silently-skipped",
34
+ detail: `Migration ${preview(migration.hash)} (${migration.folderMillis}) was never applied but sits at or below the watermark ${watermark}. drizzle will never run it.`
35
+ }));
36
+ }
37
+ function findMigrationDrift(recorded, journal) {
38
+ const journalByHash = new Map(journal.map((migration) => [migration.hash, migration]));
39
+ return [
40
+ ...findUnknownHashes(recorded, journalByHash),
41
+ ...findTimestampDrift(recorded, journalByHash),
42
+ ...findSilentlySkipped(recorded, journal)
43
+ ];
44
+ }
45
+ // src/migrations/sql-client.ts
46
+ const REQUEST_TIMEOUT_MS = 3e4;
47
+ function neonEndpoint(connectionString) {
48
+ try {
49
+ return `https://${new URL(connectionString).hostname}/sql`;
50
+ } catch {
51
+ throw new Error("The database URL is not a valid connection string.");
52
+ }
53
+ }
54
+ async function failureMessage(response) {
55
+ const body = await response.json().catch(() => null);
56
+ const detail = typeof body?.message === "string" ? `: ${body.message}` : "";
57
+ return `The database rejected the query (HTTP ${response.status}${detail}).`;
58
+ }
59
+ /** Runs queries over Neon's SQL-over-HTTP endpoint, so no database driver is needed. */
60
+ function createNeonSqlClient(options) {
61
+ const { connectionString, fetchImpl = fetch } = options;
62
+ const endpoint = neonEndpoint(connectionString);
63
+ return { async query(text) {
64
+ const response = await fetchImpl(endpoint, {
65
+ method: "POST",
66
+ headers: {
67
+ "Content-Type": "application/json",
68
+ "Neon-Connection-String": connectionString
69
+ },
70
+ body: JSON.stringify({
71
+ query: text,
72
+ params: []
73
+ }),
74
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
75
+ });
76
+ if (!response.ok) throw new Error(await failureMessage(response));
77
+ const payload = await response.json();
78
+ if (!Array.isArray(payload.rows)) throw new Error("The database returned an unexpected payload.");
79
+ return payload.rows;
80
+ } };
81
+ }
82
+ // src/migrations/drift-run.ts
83
+ const TABLE_EXISTS_QUERY = `select exists (
84
+ select 1 from information_schema.tables
85
+ where table_schema = 'drizzle' and table_name = '__drizzle_migrations'
86
+ ) as exists`;
87
+ const RECORDED_QUERY = "select hash, created_at from drizzle.__drizzle_migrations order by created_at";
88
+ const systemEnvironment = {
89
+ variables: process.env,
90
+ files: systemFiles,
91
+ createSqlClient: (connectionString) => createNeonSqlClient({ connectionString }),
92
+ ...prefixedConsole("np-check-migration-drift")
93
+ };
94
+ async function fetchRecordedMigrations(sql) {
95
+ const [row] = await sql.query(TABLE_EXISTS_QUERY);
96
+ if (!(row?.exists === true || String(row?.exists) === "t")) return null;
97
+ return sql.query(RECORDED_QUERY);
98
+ }
99
+ /** Compares the database's applied migrations with the journal; returns the exit code. */
100
+ async function runCheckMigrationDrift(argv, environment = systemEnvironment) {
101
+ try {
102
+ const options = readMigrationsOptions(argv, environment.variables);
103
+ const connectionString = environment.variables[options.databaseUrlVariable];
104
+ if (!connectionString) throw new Error(`${options.databaseUrlVariable} is required to check migration drift`);
105
+ const entries = readJournal(environment.files, options.migrationsDirectory);
106
+ const journal = readJournalMigrations(environment.files, options.migrationsDirectory, entries);
107
+ const recorded = await fetchRecordedMigrations(environment.createSqlClient(connectionString));
108
+ if (recorded === null) {
109
+ environment.log("No drizzle.__drizzle_migrations table yet, nothing to check.");
110
+ return 0;
111
+ }
112
+ const findings = findMigrationDrift(recorded, journal);
113
+ if (findings.length === 0) {
114
+ environment.log(`Migration bookkeeping is consistent (${recorded.length} applied, ${journal.length} in journal).`);
115
+ return 0;
116
+ }
117
+ environment.error("Migration bookkeeping drift detected:");
118
+ for (const finding of findings) environment.error(` [${finding.kind}] ${finding.detail}`);
119
+ environment.error("Refusing to migrate. Reconcile drizzle.__drizzle_migrations with the journal first.");
120
+ return 1;
121
+ } catch (error) {
122
+ environment.error(describeError(error));
123
+ return 1;
124
+ }
125
+ }
126
+ // src/check-migration-drift.ts
127
+ process.exitCode = await runCheckMigrationDrift(process.argv.slice(2));
128
+ export {};
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env node
2
+ import { join } from "node:path";
3
+ import { r as prefixedConsole, t as describeError } from "./workflow-command-Bb1eVLow.js";
4
+ import { a as parseJsonFile, c as systemFiles, i as metaDirectory, n as journalPath, o as readJournal, r as journalTagPrefix, t as readMigrationsOptions } from "./options-C_apa01R.js";
5
+ // src/migrations/snapshots.ts
6
+ const ROOT_SNAPSHOT_PREV_ID = "00000000-0000-0000-0000-000000000000";
7
+ const SNAPSHOT_FILENAME_PATTERN = /^(\d{4})_snapshot\.json$/;
8
+ function snapshotFilePrefix(filename) {
9
+ return filename.match(SNAPSHOT_FILENAME_PATTERN)?.[1];
10
+ }
11
+ function snapshotFilenameForTag(tag) {
12
+ const prefix = journalTagPrefix(tag);
13
+ return prefix ? `${prefix}_snapshot.json` : void 0;
14
+ }
15
+ function prefixesOf(items, prefixOf) {
16
+ return new Set(items.map(prefixOf).filter((prefix) => prefix !== void 0));
17
+ }
18
+ function findMissingSnapshotTags(journalTags, snapshotFilenames) {
19
+ const existing = prefixesOf(snapshotFilenames, snapshotFilePrefix);
20
+ return journalTags.filter((tag) => {
21
+ const prefix = journalTagPrefix(tag);
22
+ return !prefix || !existing.has(prefix);
23
+ });
24
+ }
25
+ function findOrphanSnapshotFiles(journalTags, snapshotFilenames) {
26
+ const journalPrefixes = prefixesOf(journalTags, journalTagPrefix);
27
+ return snapshotFilenames.filter((filename) => {
28
+ const prefix = snapshotFilePrefix(filename);
29
+ return prefix !== void 0 && !journalPrefixes.has(prefix);
30
+ });
31
+ }
32
+ function findBrokenChainLinks(orderedSnapshots) {
33
+ return orderedSnapshots.flatMap((snapshot, index) => {
34
+ const previous = orderedSnapshots[index - 1];
35
+ const expectedPrevId = previous?.id ?? "00000000-0000-0000-0000-000000000000";
36
+ if (snapshot.prevId === expectedPrevId) return [];
37
+ if (!previous) return [`${snapshot.tag}: prevId "${snapshot.prevId}" is not the root sentinel "${ROOT_SNAPSHOT_PREV_ID}"`];
38
+ return [`${snapshot.tag}: prevId "${snapshot.prevId}" does not match "${previous.tag}"'s id "${previous.id}"`];
39
+ });
40
+ }
41
+ // src/migrations/snapshots-run.ts
42
+ const systemEnvironment = {
43
+ variables: process.env,
44
+ files: systemFiles,
45
+ ...prefixedConsole("np-check-migration-snapshots")
46
+ };
47
+ function describeExpectedSnapshot(tag) {
48
+ const filename = snapshotFilenameForTag(tag);
49
+ return filename ? `expected ${filename}` : "tag has no NNNN_ prefix";
50
+ }
51
+ function loadSnapshotChain(files, metaFolder, journalTags) {
52
+ return journalTags.map((tag) => {
53
+ const filename = snapshotFilenameForTag(tag) ?? "";
54
+ const path = join(metaFolder, filename);
55
+ const snapshot = parseJsonFile(files.readText(path), path) ?? {};
56
+ if (typeof snapshot.id !== "string" || typeof snapshot.prevId !== "string") throw new Error(`${path} is missing a string "id" or "prevId"`);
57
+ return {
58
+ tag,
59
+ id: snapshot.id,
60
+ prevId: snapshot.prevId
61
+ };
62
+ });
63
+ }
64
+ function reportProblems(environment, title, problems, hint) {
65
+ environment.error(title);
66
+ for (const problem of problems) environment.error(` ${problem}`);
67
+ environment.error(hint);
68
+ return 1;
69
+ }
70
+ /** Checks that every journal entry has a correctly chained snapshot; returns the exit code. */
71
+ async function runCheckMigrationSnapshots(argv, environment = systemEnvironment) {
72
+ try {
73
+ const { migrationsDirectory } = readMigrationsOptions(argv, environment.variables);
74
+ const metaFolder = metaDirectory(migrationsDirectory);
75
+ const journalFile = journalPath(migrationsDirectory);
76
+ const journalTags = readJournal(environment.files, migrationsDirectory).map((entry) => entry.tag);
77
+ if (journalTags.length === 0) throw new Error(`${journalFile} has no entries`);
78
+ const filenames = environment.files.listNames(metaFolder);
79
+ const missing = findMissingSnapshotTags(journalTags, filenames);
80
+ if (missing.length > 0) return reportProblems(environment, "Missing migration snapshot file(s):", missing.map((tag) => `${tag} (${describeExpectedSnapshot(tag)})`), `Each entry in ${journalFile} must have a matching <NNNN>_snapshot.json in ${metaFolder}/, or the next \`drizzle-kit generate\` will diff against a stale base schema.`);
81
+ const orphans = findOrphanSnapshotFiles(journalTags, filenames);
82
+ if (orphans.length > 0) return reportProblems(environment, "Snapshot file(s) with no matching journal entry:", orphans, `Each <NNNN>_snapshot.json in ${metaFolder}/ must have a matching entry in ${journalFile}, or \`drizzle-kit generate\` will diff against an orphaned, unreferenced snapshot.`);
83
+ const broken = findBrokenChainLinks(loadSnapshotChain(environment.files, metaFolder, journalTags));
84
+ if (broken.length > 0) return reportProblems(environment, "Broken migration snapshot chain link(s):", broken, "Each snapshot's prevId must match the id of the snapshot before it in journal order, or `drizzle-kit generate` will diff against the wrong base schema.");
85
+ environment.log(`All ${journalTags.length} journal entries have a matching, correctly-chained snapshot file.`);
86
+ return 0;
87
+ } catch (error) {
88
+ environment.error(describeError(error));
89
+ return 1;
90
+ }
91
+ }
92
+ // src/check-migration-snapshots.ts
93
+ process.exitCode = await runCheckMigrationSnapshots(process.argv.slice(2));
94
+ export {};
@@ -28,6 +28,17 @@ function parseDeploy(value) {
28
28
  adminUrl: textOrNull(record["admin_url"])
29
29
  };
30
30
  }
31
+ function parseSite(value) {
32
+ const id = typeof value === "object" && value !== null ? textOrNull(value["id"]) : null;
33
+ if (id === null) throw new NetlifyFatalError("Netlify returned an unexpected payload (expected a site with an id).");
34
+ return id;
35
+ }
36
+ function parsePublishedCommitRef(value) {
37
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new NetlifyFatalError("Netlify returned an unexpected payload (expected a site object).");
38
+ const published = value["published_deploy"];
39
+ if (typeof published !== "object" || published === null) return null;
40
+ return textOrNull(published["commit_ref"]);
41
+ }
31
42
  function parseDeployList(value) {
32
43
  if (!Array.isArray(value)) throw new NetlifyFatalError("Netlify returned an unexpected payload (expected a list of deploys).");
33
44
  return value.map(parseDeploy);
@@ -57,20 +68,19 @@ function createNetlifyClient(options) {
57
68
  return readJson(response);
58
69
  }
59
70
  return {
71
+ async getSiteId() {
72
+ return parseSite(await getJson(`/sites/${encodeURIComponent(siteId)}`));
73
+ },
60
74
  async listProductionDeploys() {
61
75
  const query = `production=true&per_page=${DEPLOYS_PAGE_SIZE}`;
62
76
  return parseDeployList(await getJson(`/sites/${encodeURIComponent(siteId)}/deploys?${query}`));
63
77
  },
78
+ async getPublishedCommitRef() {
79
+ return parsePublishedCommitRef(await getJson(`/sites/${encodeURIComponent(siteId)}`));
80
+ },
64
81
  async getDeploy(deployId) {
65
82
  return parseDeploy(await getJson(`/deploys/${encodeURIComponent(deployId)}`));
66
83
  }
67
84
  };
68
85
  }
69
- // src/workflow-command.ts
70
- function describeError(error) {
71
- return error instanceof Error ? error.message : String(error);
72
- }
73
- function escapeWorkflowCommand(text) {
74
- return text.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
75
- }
76
- export { createNetlifyClient as i, escapeWorkflowCommand as n, NetlifyFatalError as r, describeError as t };
86
+ export { createNetlifyClient as n, NetlifyFatalError as t };
@@ -0,0 +1,82 @@
1
+ import { t as describeError } from "./workflow-command-Bb1eVLow.js";
2
+ import { readFileSync, readdirSync } from "node:fs";
3
+ import { parseArgs } from "node:util";
4
+ import { join } from "node:path";
5
+ import { createHash } from "node:crypto";
6
+ // src/migrations/filesystem.ts
7
+ const systemFiles = {
8
+ readText: (path) => readFileSync(path, "utf8"),
9
+ listNames: (directory) => readdirSync(directory)
10
+ };
11
+ // src/migrations/journal.ts
12
+ const TAG_PREFIX_PATTERN = /^(\d{4})_/;
13
+ function metaDirectory(migrationsDirectory) {
14
+ return join(migrationsDirectory, "meta");
15
+ }
16
+ function journalPath(migrationsDirectory) {
17
+ return join(metaDirectory(migrationsDirectory), "_journal.json");
18
+ }
19
+ /** The "NNNN" out of a journal tag like "0005_add_events_table". */
20
+ function journalTagPrefix(tag) {
21
+ return tag.match(TAG_PREFIX_PATTERN)?.[1];
22
+ }
23
+ function isValidEntry(entry) {
24
+ if (typeof entry !== "object" || entry === null) return false;
25
+ const { tag, idx, when } = entry;
26
+ if (typeof tag !== "string" || !Number.isInteger(idx)) return false;
27
+ return typeof when === "number" && Number.isFinite(when);
28
+ }
29
+ function idxMatchesTagPrefix(entry) {
30
+ const prefix = journalTagPrefix(entry.tag);
31
+ return prefix !== void 0 && Number(prefix) === entry.idx;
32
+ }
33
+ /** JSON.parse that names the file when it is malformed. */
34
+ function parseJsonFile(raw, source) {
35
+ try {
36
+ return JSON.parse(raw);
37
+ } catch (error) {
38
+ throw new Error(`${source} is not valid JSON (${describeError(error)})`, { cause: error });
39
+ }
40
+ }
41
+ function parseJournal(raw, source) {
42
+ const journal = parseJsonFile(raw, source);
43
+ if (!Array.isArray(journal?.entries)) throw new Error(`${source} has no "entries" array`);
44
+ const entries = journal.entries;
45
+ if (!entries.every(isValidEntry)) throw new Error(`${source} has an entry without a string "tag", an integer "idx", or a numeric "when"`);
46
+ if (!entries.every(idxMatchesTagPrefix)) throw new Error(`${source} has an entry whose "idx" does not match its tag's NNNN_ prefix`);
47
+ const indexes = entries.map((entry) => entry.idx);
48
+ if (new Set(indexes).size !== indexes.length) throw new Error(`${source} has duplicate "idx" values`);
49
+ return [...entries].sort((first, second) => first.idx - second.idx);
50
+ }
51
+ function readJournal(files, migrationsDirectory) {
52
+ const path = journalPath(migrationsDirectory);
53
+ return parseJournal(files.readText(path), path);
54
+ }
55
+ /** Hashes each migration file the way drizzle's `readMigrationFiles` does (sha256 of the SQL). */
56
+ function readJournalMigrations(files, migrationsDirectory, entries) {
57
+ return entries.map((entry) => ({
58
+ hash: createHash("sha256").update(files.readText(join(migrationsDirectory, `${entry.tag}.sql`))).digest("hex"),
59
+ folderMillis: entry.when
60
+ }));
61
+ }
62
+ const MIGRATIONS_DIRECTORY_VARIABLE = "MIGRATIONS_DIR";
63
+ /**
64
+ * The migrations directory comes from `--migrations-dir`, then MIGRATIONS_DIR,
65
+ * then the Nuxt convention. The database URL is only ever read from an
66
+ * environment variable (named by `--database-url-variable`), never from argv,
67
+ * so it cannot show up in process listings or logs.
68
+ */
69
+ function readMigrationsOptions(argv, variables) {
70
+ const { values } = parseArgs({
71
+ args: argv,
72
+ options: {
73
+ "migrations-dir": { type: "string" },
74
+ "database-url-variable": { type: "string" }
75
+ }
76
+ });
77
+ return {
78
+ migrationsDirectory: values["migrations-dir"] || variables[MIGRATIONS_DIRECTORY_VARIABLE] || "server/db/migrations",
79
+ databaseUrlVariable: values["database-url-variable"] || "DATABASE_URL"
80
+ };
81
+ }
82
+ export { parseJsonFile as a, systemFiles as c, metaDirectory as i, journalPath as n, readJournal as o, journalTagPrefix as r, readJournalMigrations as s, readMigrationsOptions as t };