@subodh001/pg-safe-migrate 2.0.0 → 2.2.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,115 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { randomUUID } from 'node:crypto';
5
+
6
+ const MAX_SQL_BYTES = 1024 * 1024;
7
+ const MAX_FILES = 100;
8
+ const ALLOWED_VERSIONS = new Set(['14', '15', '16', '17', '18']);
9
+
10
+ function readSql(file) {
11
+ const resolved = path.resolve(file);
12
+ const stat = fs.statSync(resolved);
13
+ if (!stat.isFile() || stat.size > MAX_SQL_BYTES) throw new Error('SQL file must be a regular file <= 1 MiB');
14
+ const sql = fs.readFileSync(resolved, 'utf8');
15
+ if (!sql.trim()) throw new Error(`SQL file is empty: ${resolved}`);
16
+ return { file: resolved, sql };
17
+ }
18
+
19
+ function migrationFiles(dir) {
20
+ const root = path.resolve(dir);
21
+ if (!fs.statSync(root).isDirectory()) throw new Error('migrations-dir must be a directory');
22
+ const files = fs.readdirSync(root, { withFileTypes: true })
23
+ .filter(entry => entry.isFile() && entry.name.toLowerCase().endsWith('.sql'))
24
+ .map(entry => path.join(root, entry.name)).sort();
25
+ if (!files.length || files.length > MAX_FILES) throw new Error('migrations-dir must contain 1-100 top-level .sql files');
26
+ return files.map(readSql);
27
+ }
28
+
29
+ /** Run SQL in a disposable, network-isolated PostgreSQL container.
30
+ * Baseline and target steps are separate. Not a production safety or rollback guarantee.
31
+ */
32
+ export function simulateSqlFile(file, {
33
+ postgresVersion = '16', timeoutSeconds = 60, baseline,
34
+ migrationsDir, verifySql, run = spawnSync
35
+ } = {}) {
36
+ if (!ALLOWED_VERSIONS.has(String(postgresVersion))) throw new Error('Simulation supports PostgreSQL 14-18');
37
+ if (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 10 || timeoutSeconds > 300) throw new Error('timeoutSeconds must be 10-300');
38
+ if (file && migrationsDir) throw new Error('Use either --simulate <file> or --migrations-dir, not both');
39
+ if (!file && !migrationsDir) throw new Error('Provide a SQL file or --migrations-dir');
40
+ const baselineStep = baseline ? readSql(baseline) : null;
41
+ const targets = migrationsDir ? migrationFiles(migrationsDir) : [readSql(file)];
42
+ const verification = verifySql ? readSql(verifySql) : null;
43
+ const name = `pg-safe-sim-${randomUUID().slice(0, 12)}`;
44
+ const image = `postgres:${postgresVersion}`;
45
+ const call = (args, options = {}) => {
46
+ const result = run('docker', args, {
47
+ encoding: 'utf8', timeout: options.timeout ?? 15000,
48
+ input: options.input, maxBuffer: 2 * 1024 * 1024, windowsHide: true
49
+ });
50
+ if (result.error) throw new Error(`Docker ${args[0]} failed: ${result.error.message}`);
51
+ return result;
52
+ };
53
+ let created = false;
54
+ let primaryError;
55
+ try {
56
+ const started = call(['run', '-d', '--name', name, '--network', 'none', '--memory', '512m', '--cpus', '1', '--pids-limit', '128', '--security-opt', 'no-new-privileges', '-e', 'POSTGRES_HOST_AUTH_METHOD=trust', image], { timeout: 120000 });
57
+ if (started.status !== 0) throw new Error(`Docker could not start disposable PostgreSQL: ${(started.stderr || '').trim()}`);
58
+ created = true;
59
+ let ready = false;
60
+ for (let attempt = 0; attempt < 30; attempt++) {
61
+ const result = call(['exec', name, 'pg_isready', '-U', 'postgres'], { timeout: 5000 });
62
+ if (result.status === 0) { ready = true; break; }
63
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1000);
64
+ }
65
+ if (!ready) throw new Error('Disposable PostgreSQL did not become ready within 30 seconds');
66
+ const execute = (step, stage) => {
67
+ const result = call(['exec', '-i', name, 'psql', '-X', '-v', 'ON_ERROR_STOP=1', '-U', 'postgres', '-d', 'postgres', '-f', '-'], { input: step.sql, timeout: timeoutSeconds * 1000 });
68
+ return {
69
+ stage, file: step.file, passed: result.status === 0,
70
+ stdout: (result.stdout || '').slice(-4000), stderr: (result.stderr || '').slice(-4000),
71
+ exitCode: result.status
72
+ };
73
+ };
74
+ const steps = [];
75
+ if (baselineStep) {
76
+ const result = execute(baselineStep, 'baseline');
77
+ steps.push(result);
78
+ if (!result.passed) return summary(result, steps, postgresVersion);
79
+ }
80
+ for (const target of targets) {
81
+ const result = execute(target, 'migration');
82
+ steps.push(result);
83
+ if (!result.passed) return summary(result, steps, postgresVersion);
84
+ }
85
+ if (verification) {
86
+ const result = execute(verification, 'verification');
87
+ steps.push(result);
88
+ if (!result.passed) return summary(result, steps, postgresVersion);
89
+ }
90
+ return summary(steps.at(-1), steps, postgresVersion);
91
+ } catch (error) {
92
+ primaryError = error;
93
+ throw error;
94
+ } finally {
95
+ if (created) {
96
+ try {
97
+ const removed = call(['rm', '-f', name], { timeout: 30000 });
98
+ if (removed.status !== 0) throw new Error((removed.stderr || 'docker rm failed').trim());
99
+ } catch (error) {
100
+ const message = `CRITICAL: Disposable container ${name} could not be removed: ${error.message}`;
101
+ if (primaryError) throw new AggregateError([primaryError, error], message);
102
+ throw new Error(message);
103
+ }
104
+ }
105
+ }
106
+ }
107
+
108
+ function summary(last, steps, postgresVersion) {
109
+ return {
110
+ passed: last.passed, postgresVersion: Number(postgresVersion), isolated: true,
111
+ disposable: true, stage: last.stage, file: last.file,
112
+ stdout: last.stdout, stderr: last.stderr, exitCode: last.exitCode,
113
+ steps, limitation: 'Checks SQL execution against an empty disposable database plus optional baseline; not a downtime, production-data, or rollback guarantee.'
114
+ };
115
+ }
@@ -0,0 +1,23 @@
1
+ import fs from 'node:fs';
2
+
3
+ export function loadTeamPolicy(file) {
4
+ const policy = JSON.parse(fs.readFileSync(file, 'utf8'));
5
+ if (!policy || typeof policy !== 'object' || Array.isArray(policy)) throw new Error('Team policy must be a JSON object');
6
+ const allowed = ['name', 'maxRiskScore', 'maxWarnings', 'blockedRules', 'requireSimulation'];
7
+ for (const key of Object.keys(policy)) if (!allowed.includes(key)) throw new Error(`Unknown team policy key: ${key}`);
8
+ if (policy.maxRiskScore !== undefined && (!Number.isInteger(policy.maxRiskScore) || policy.maxRiskScore < 0 || policy.maxRiskScore > 100)) throw new Error('maxRiskScore must be 0-100');
9
+ if (policy.maxWarnings !== undefined && (!Number.isInteger(policy.maxWarnings) || policy.maxWarnings < 0)) throw new Error('maxWarnings must be >= 0');
10
+ if (policy.blockedRules !== undefined && (!Array.isArray(policy.blockedRules) || policy.blockedRules.some(x => !/^PG\d{3}$/.test(x)))) throw new Error('blockedRules must be an array of PG rule IDs');
11
+ if (policy.requireSimulation !== undefined && typeof policy.requireSimulation !== 'boolean') throw new Error('requireSimulation must be boolean');
12
+ return policy;
13
+ }
14
+
15
+ export function assessTeamPolicy(report, policy) {
16
+ const reasons = [];
17
+ const findings = report.lint.findings;
18
+ if (policy.requireSimulation && !report.execution?.passed) reasons.push('Simulation must pass');
19
+ if (policy.maxRiskScore !== undefined && report.lint.risk.score > policy.maxRiskScore) reasons.push(`Risk score exceeds ${policy.maxRiskScore}`);
20
+ if (policy.maxWarnings !== undefined && findings.filter(f => f.severity === 'warning').length > policy.maxWarnings) reasons.push(`Warnings exceed ${policy.maxWarnings}`);
21
+ for (const f of findings) if (policy.blockedRules?.includes(f.ruleId)) reasons.push(`Blocked rule ${f.ruleId}: ${f.file}`);
22
+ return { name: policy.name ?? 'local-team', passed: reasons.length === 0, reasons: [...new Set(reasons)] };
23
+ }