@pgpmjs/core 7.20.4 → 7.21.1

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/esm/index.js CHANGED
@@ -2,6 +2,7 @@ export * from './core/class/pgpm';
2
2
  export * from './rebundle';
3
3
  export * from './extensions';
4
4
  export * from './modules/modules';
5
+ export * from './packaging/check';
5
6
  export * from './packaging/package';
6
7
  export * from './packaging/sync-versions';
7
8
  export * from './packaging/transform';
@@ -0,0 +1,207 @@
1
+ import { execSync } from 'child_process';
2
+ import { isAbsolute, relative, resolve as resolvePath } from 'path';
3
+ import { verifyBundle } from '@pgpmjs/bundle';
4
+ import { bundleMatchesModule, readBundleArtifact, resolveBundleArtifactPath, } from '../bundle/artifact';
5
+ import { PgpmPackage } from '../core/class/pgpm';
6
+ /**
7
+ * Verify a single module's committed bundle artifact against its `deploy/`.
8
+ *
9
+ * Cheap by design — read + sha256 only, no SQL parse/deparse and no DDL — so it
10
+ * is safe to run in CI on every push. Returns `null` when the artifact is in
11
+ * sync, or a {@link ModuleDrift} describing the first problem found.
12
+ */
13
+ export function checkModuleArtifact(moduleDir, name) {
14
+ const artifactPath = resolveBundleArtifactPath(moduleDir);
15
+ if (!artifactPath) {
16
+ return {
17
+ name,
18
+ moduleDir,
19
+ reason: 'missing-artifact',
20
+ detail: 'no sql/<name>--<version>.bundle.tar.gz — run `pgpm package`',
21
+ };
22
+ }
23
+ const bundle = readBundleArtifact(moduleDir);
24
+ if (!bundle) {
25
+ return {
26
+ name,
27
+ moduleDir,
28
+ reason: 'unreadable-artifact',
29
+ detail: `could not read ${artifactPath} — re-run \`pgpm package\``,
30
+ };
31
+ }
32
+ const issues = verifyBundle(bundle);
33
+ if (issues.length) {
34
+ return {
35
+ name,
36
+ moduleDir,
37
+ reason: 'integrity',
38
+ detail: `bundle integrity check failed: ${issues.map((i) => i.message).join('; ')}`,
39
+ };
40
+ }
41
+ if (!bundleMatchesModule(moduleDir, bundle)) {
42
+ return {
43
+ name,
44
+ moduleDir,
45
+ reason: 'out-of-sync',
46
+ detail: 'committed bundle does not match deploy/ — run `pgpm package`',
47
+ };
48
+ }
49
+ return null;
50
+ }
51
+ function git(args, cwd) {
52
+ return execSync(`git ${args}`, {
53
+ cwd,
54
+ encoding: 'utf-8',
55
+ stdio: ['ignore', 'pipe', 'ignore'],
56
+ maxBuffer: 64 * 1024 * 1024,
57
+ });
58
+ }
59
+ /**
60
+ * Resolve the git ref to diff against. Explicit `--since` wins; otherwise use
61
+ * the PR base branch when running in GitHub Actions; otherwise `undefined`
62
+ * (working-tree changes only).
63
+ */
64
+ export function resolveBase(since) {
65
+ if (since)
66
+ return since;
67
+ const prBase = process.env.GITHUB_BASE_REF;
68
+ if (prBase && prBase.trim())
69
+ return `origin/${prBase.trim()}`;
70
+ return undefined;
71
+ }
72
+ /**
73
+ * Collect the set of changed files, combining committed changes since `base`
74
+ * (three-dot diff, so it works with branches, refs, and tags) with any
75
+ * uncommitted/untracked changes in the working tree. Returns absolute paths.
76
+ */
77
+ export function changedFiles(cwd, base) {
78
+ const files = new Set();
79
+ const status = git('status --porcelain', cwd);
80
+ for (const rawLine of status.split('\n')) {
81
+ const line = rawLine.trimEnd();
82
+ if (!line)
83
+ continue;
84
+ let p = line.slice(3);
85
+ const arrow = p.indexOf(' -> ');
86
+ if (arrow !== -1)
87
+ p = p.slice(arrow + 4);
88
+ p = p.replace(/^"|"$/g, '');
89
+ if (p)
90
+ files.add(resolvePath(cwd, p));
91
+ }
92
+ if (base) {
93
+ let diff;
94
+ try {
95
+ diff = git(`diff --name-only ${base}...HEAD`, cwd);
96
+ }
97
+ catch (err) {
98
+ throw new Error(`Could not diff against '${base}'. Ensure the ref exists locally ` +
99
+ `(e.g. \`git fetch origin\`). Original error: ${err instanceof Error ? err.message : String(err)}`);
100
+ }
101
+ for (const rawLine of diff.split('\n')) {
102
+ const p = rawLine.trim();
103
+ if (p)
104
+ files.add(resolvePath(cwd, p));
105
+ }
106
+ }
107
+ return [...files];
108
+ }
109
+ /** Enumerate the modules to consider — the whole workspace, or the single module. */
110
+ export function enumerateModules(pkg) {
111
+ const wsPath = pkg.getWorkspacePath();
112
+ if (wsPath) {
113
+ const map = pkg.getModuleMap();
114
+ return Object.entries(map).map(([name, m]) => ({
115
+ name,
116
+ dir: resolvePath(wsPath, m.path),
117
+ }));
118
+ }
119
+ if (pkg.isInModule()) {
120
+ return [{ name: pkg.getModuleName(), dir: pkg.getModulePath() }];
121
+ }
122
+ return [];
123
+ }
124
+ /** Map changed file paths to the owning module (longest matching module dir). */
125
+ export function mapFilesToModules(files, modules) {
126
+ const hit = new Set();
127
+ for (const file of files) {
128
+ let best;
129
+ for (const mod of modules) {
130
+ const rel = relative(mod.dir, file);
131
+ if (rel.startsWith('..') || isAbsolute(rel))
132
+ continue;
133
+ if (!best || mod.dir.length > best.dir.length)
134
+ best = mod;
135
+ }
136
+ if (best)
137
+ hit.add(best.name);
138
+ }
139
+ return [...hit];
140
+ }
141
+ /** Expand a set of module names to include everything that transitively requires them. */
142
+ export function addDependents(names, pkg) {
143
+ const map = pkg.getModuleMap();
144
+ const reverse = new Map();
145
+ for (const [name, m] of Object.entries(map)) {
146
+ for (const req of m.requires ?? []) {
147
+ if (!reverse.has(req))
148
+ reverse.set(req, []);
149
+ reverse.get(req).push(name);
150
+ }
151
+ }
152
+ const queue = [...names];
153
+ while (queue.length) {
154
+ const current = queue.shift();
155
+ for (const dependent of reverse.get(current) ?? []) {
156
+ if (!names.has(dependent)) {
157
+ names.add(dependent);
158
+ queue.push(dependent);
159
+ }
160
+ }
161
+ }
162
+ }
163
+ /**
164
+ * Verify that committed bundle artifacts are in sync with `deploy/` for the
165
+ * modules that changed (per git), failing fast on the first drift by default.
166
+ *
167
+ * This is the engine behind `pgpm package --check`: change detection + workspace
168
+ * mapping + the cheap per-module artifact verification, so CI can gate every PR
169
+ * with a one-liner and only pay for the modules that actually changed.
170
+ */
171
+ export async function checkPackages(options = {}) {
172
+ const cwd = options.cwd ?? process.cwd();
173
+ const failFast = options.failFast ?? true;
174
+ const pkg = new PgpmPackage(cwd);
175
+ const modules = enumerateModules(pkg);
176
+ const byName = new Map(modules.map((m) => [m.name, m]));
177
+ let base;
178
+ let changedModules = [];
179
+ let targetNames;
180
+ if (options.all) {
181
+ targetNames = modules.map((m) => m.name);
182
+ }
183
+ else {
184
+ base = resolveBase(options.since);
185
+ const files = changedFiles(cwd, base);
186
+ changedModules = mapFilesToModules(files, modules);
187
+ const set = new Set(changedModules);
188
+ if (options.dependents && pkg.getWorkspacePath())
189
+ addDependents(set, pkg);
190
+ targetNames = [...set];
191
+ }
192
+ const checked = [];
193
+ const drifted = [];
194
+ for (const name of targetNames) {
195
+ const mod = byName.get(name);
196
+ if (!mod)
197
+ continue;
198
+ checked.push(name);
199
+ const drift = checkModuleArtifact(mod.dir, name);
200
+ if (drift) {
201
+ drifted.push(drift);
202
+ if (failFast)
203
+ break;
204
+ }
205
+ }
206
+ return { targeted: targetNames, checked, drifted, base, changedModules };
207
+ }
package/index.d.ts CHANGED
@@ -2,6 +2,7 @@ export * from './core/class/pgpm';
2
2
  export * from './rebundle';
3
3
  export * from './extensions';
4
4
  export * from './modules/modules';
5
+ export * from './packaging/check';
5
6
  export * from './packaging/package';
6
7
  export * from './packaging/sync-versions';
7
8
  export * from './packaging/transform';
package/index.js CHANGED
@@ -19,6 +19,7 @@ __exportStar(require("./core/class/pgpm"), exports);
19
19
  __exportStar(require("./rebundle"), exports);
20
20
  __exportStar(require("./extensions"), exports);
21
21
  __exportStar(require("./modules/modules"), exports);
22
+ __exportStar(require("./packaging/check"), exports);
22
23
  __exportStar(require("./packaging/package"), exports);
23
24
  __exportStar(require("./packaging/sync-versions"), exports);
24
25
  __exportStar(require("./packaging/transform"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pgpmjs/core",
3
- "version": "7.20.4",
3
+ "version": "7.21.1",
4
4
  "author": "Constructive <developers@constructive.io>",
5
5
  "description": "PGPM Package and Migration Tools",
6
6
  "main": "index.js",
@@ -53,19 +53,19 @@
53
53
  "@pgpmjs/env": "^2.40.2",
54
54
  "@pgpmjs/logger": "^2.23.2",
55
55
  "@pgpmjs/server-utils": "^3.24.2",
56
- "@pgpmjs/slice": "^0.13.4",
57
- "@pgpmjs/transform": "^0.15.3",
56
+ "@pgpmjs/slice": "^0.13.6",
57
+ "@pgpmjs/transform": "^0.17.0",
58
58
  "@pgpmjs/types": "^2.49.2",
59
- "csv-to-pg": "^4.9.2",
59
+ "csv-to-pg": "^4.9.3",
60
60
  "genomic": "^5.6.2",
61
61
  "glob": "^13.0.6",
62
62
  "parse-package-name": "^1.0.0",
63
63
  "pg": "^8.21.0",
64
64
  "pg-cache": "^3.24.2",
65
65
  "pg-env": "^1.27.2",
66
- "pgsql-deparser": "^18.1.1",
67
- "pgsql-parser": "^18.1.1",
66
+ "pgsql-deparser": "^18.2.0",
67
+ "pgsql-parser": "^18.1.2",
68
68
  "yanse": "^0.2.1"
69
69
  },
70
- "gitHead": "90f447482b056a4949134565db2665f21d11aca3"
70
+ "gitHead": "45cd961cf956d2d28e4d09b20db4204982c33593"
71
71
  }
@@ -0,0 +1,91 @@
1
+ import { PgpmPackage } from '../core/class/pgpm';
2
+ /**
3
+ * Why a module's committed bundle artifact no longer describes its `deploy/`.
4
+ *
5
+ * - `missing-artifact` — no `sql/<name>--<version>.bundle.tar.gz` at all.
6
+ * - `unreadable-artifact` — the archive exists but could not be opened/parsed.
7
+ * - `integrity` — the artifact is internally inconsistent (`verifyBundle`).
8
+ * - `out-of-sync` — the artifact is valid but its plan/per-change bytes no
9
+ * longer match the files under `deploy/` (`bundleMatchesModule`).
10
+ */
11
+ export type DriftReason = 'missing-artifact' | 'unreadable-artifact' | 'integrity' | 'out-of-sync';
12
+ export interface ModuleDrift {
13
+ name: string;
14
+ moduleDir: string;
15
+ reason: DriftReason;
16
+ detail: string;
17
+ }
18
+ export interface ModuleRef {
19
+ name: string;
20
+ dir: string;
21
+ }
22
+ export interface PackageCheckOptions {
23
+ cwd?: string;
24
+ /**
25
+ * Git ref/branch/tag to diff `HEAD` against for change detection. When
26
+ * omitted, the check auto-detects the base (`origin/$GITHUB_BASE_REF` in a
27
+ * PR, otherwise it only inspects uncommitted/untracked working-tree changes).
28
+ */
29
+ since?: string;
30
+ /** Check every module in the workspace, skipping git change detection. */
31
+ all?: boolean;
32
+ /**
33
+ * Stop at the first drifted module (default `true`). Set `false` to report
34
+ * every drifted module in one pass.
35
+ */
36
+ failFast?: boolean;
37
+ /**
38
+ * Also re-check modules that (transitively) `require` a changed module.
39
+ * Off by default: a module's packaged SQL/bundle reflects only its own
40
+ * `deploy/` files (`resolveWithPlan`), so a dependency's change does not
41
+ * alter a dependent's artifact. Exposed for completeness/paranoia.
42
+ */
43
+ dependents?: boolean;
44
+ }
45
+ export interface PackageCheckResult {
46
+ /** Module names selected for verification (before fail-fast truncation). */
47
+ targeted: string[];
48
+ /** Module names that were actually verified (fail-fast may stop early). */
49
+ checked: string[];
50
+ /** Modules whose committed artifact no longer matches `deploy/`. */
51
+ drifted: ModuleDrift[];
52
+ /** The git ref used for change detection, if any. */
53
+ base?: string;
54
+ /** Module names detected as directly changed (before dependent expansion). */
55
+ changedModules: string[];
56
+ }
57
+ /**
58
+ * Verify a single module's committed bundle artifact against its `deploy/`.
59
+ *
60
+ * Cheap by design — read + sha256 only, no SQL parse/deparse and no DDL — so it
61
+ * is safe to run in CI on every push. Returns `null` when the artifact is in
62
+ * sync, or a {@link ModuleDrift} describing the first problem found.
63
+ */
64
+ export declare function checkModuleArtifact(moduleDir: string, name: string): ModuleDrift | null;
65
+ /**
66
+ * Resolve the git ref to diff against. Explicit `--since` wins; otherwise use
67
+ * the PR base branch when running in GitHub Actions; otherwise `undefined`
68
+ * (working-tree changes only).
69
+ */
70
+ export declare function resolveBase(since?: string): string | undefined;
71
+ /**
72
+ * Collect the set of changed files, combining committed changes since `base`
73
+ * (three-dot diff, so it works with branches, refs, and tags) with any
74
+ * uncommitted/untracked changes in the working tree. Returns absolute paths.
75
+ */
76
+ export declare function changedFiles(cwd: string, base?: string): string[];
77
+ /** Enumerate the modules to consider — the whole workspace, or the single module. */
78
+ export declare function enumerateModules(pkg: PgpmPackage): ModuleRef[];
79
+ /** Map changed file paths to the owning module (longest matching module dir). */
80
+ export declare function mapFilesToModules(files: string[], modules: ModuleRef[]): string[];
81
+ /** Expand a set of module names to include everything that transitively requires them. */
82
+ export declare function addDependents(names: Set<string>, pkg: PgpmPackage): void;
83
+ /**
84
+ * Verify that committed bundle artifacts are in sync with `deploy/` for the
85
+ * modules that changed (per git), failing fast on the first drift by default.
86
+ *
87
+ * This is the engine behind `pgpm package --check`: change detection + workspace
88
+ * mapping + the cheap per-module artifact verification, so CI can gate every PR
89
+ * with a one-liner and only pay for the modules that actually changed.
90
+ */
91
+ export declare function checkPackages(options?: PackageCheckOptions): Promise<PackageCheckResult>;
@@ -0,0 +1,216 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.checkModuleArtifact = checkModuleArtifact;
4
+ exports.resolveBase = resolveBase;
5
+ exports.changedFiles = changedFiles;
6
+ exports.enumerateModules = enumerateModules;
7
+ exports.mapFilesToModules = mapFilesToModules;
8
+ exports.addDependents = addDependents;
9
+ exports.checkPackages = checkPackages;
10
+ const child_process_1 = require("child_process");
11
+ const path_1 = require("path");
12
+ const bundle_1 = require("@pgpmjs/bundle");
13
+ const artifact_1 = require("../bundle/artifact");
14
+ const pgpm_1 = require("../core/class/pgpm");
15
+ /**
16
+ * Verify a single module's committed bundle artifact against its `deploy/`.
17
+ *
18
+ * Cheap by design — read + sha256 only, no SQL parse/deparse and no DDL — so it
19
+ * is safe to run in CI on every push. Returns `null` when the artifact is in
20
+ * sync, or a {@link ModuleDrift} describing the first problem found.
21
+ */
22
+ function checkModuleArtifact(moduleDir, name) {
23
+ const artifactPath = (0, artifact_1.resolveBundleArtifactPath)(moduleDir);
24
+ if (!artifactPath) {
25
+ return {
26
+ name,
27
+ moduleDir,
28
+ reason: 'missing-artifact',
29
+ detail: 'no sql/<name>--<version>.bundle.tar.gz — run `pgpm package`',
30
+ };
31
+ }
32
+ const bundle = (0, artifact_1.readBundleArtifact)(moduleDir);
33
+ if (!bundle) {
34
+ return {
35
+ name,
36
+ moduleDir,
37
+ reason: 'unreadable-artifact',
38
+ detail: `could not read ${artifactPath} — re-run \`pgpm package\``,
39
+ };
40
+ }
41
+ const issues = (0, bundle_1.verifyBundle)(bundle);
42
+ if (issues.length) {
43
+ return {
44
+ name,
45
+ moduleDir,
46
+ reason: 'integrity',
47
+ detail: `bundle integrity check failed: ${issues.map((i) => i.message).join('; ')}`,
48
+ };
49
+ }
50
+ if (!(0, artifact_1.bundleMatchesModule)(moduleDir, bundle)) {
51
+ return {
52
+ name,
53
+ moduleDir,
54
+ reason: 'out-of-sync',
55
+ detail: 'committed bundle does not match deploy/ — run `pgpm package`',
56
+ };
57
+ }
58
+ return null;
59
+ }
60
+ function git(args, cwd) {
61
+ return (0, child_process_1.execSync)(`git ${args}`, {
62
+ cwd,
63
+ encoding: 'utf-8',
64
+ stdio: ['ignore', 'pipe', 'ignore'],
65
+ maxBuffer: 64 * 1024 * 1024,
66
+ });
67
+ }
68
+ /**
69
+ * Resolve the git ref to diff against. Explicit `--since` wins; otherwise use
70
+ * the PR base branch when running in GitHub Actions; otherwise `undefined`
71
+ * (working-tree changes only).
72
+ */
73
+ function resolveBase(since) {
74
+ if (since)
75
+ return since;
76
+ const prBase = process.env.GITHUB_BASE_REF;
77
+ if (prBase && prBase.trim())
78
+ return `origin/${prBase.trim()}`;
79
+ return undefined;
80
+ }
81
+ /**
82
+ * Collect the set of changed files, combining committed changes since `base`
83
+ * (three-dot diff, so it works with branches, refs, and tags) with any
84
+ * uncommitted/untracked changes in the working tree. Returns absolute paths.
85
+ */
86
+ function changedFiles(cwd, base) {
87
+ const files = new Set();
88
+ const status = git('status --porcelain', cwd);
89
+ for (const rawLine of status.split('\n')) {
90
+ const line = rawLine.trimEnd();
91
+ if (!line)
92
+ continue;
93
+ let p = line.slice(3);
94
+ const arrow = p.indexOf(' -> ');
95
+ if (arrow !== -1)
96
+ p = p.slice(arrow + 4);
97
+ p = p.replace(/^"|"$/g, '');
98
+ if (p)
99
+ files.add((0, path_1.resolve)(cwd, p));
100
+ }
101
+ if (base) {
102
+ let diff;
103
+ try {
104
+ diff = git(`diff --name-only ${base}...HEAD`, cwd);
105
+ }
106
+ catch (err) {
107
+ throw new Error(`Could not diff against '${base}'. Ensure the ref exists locally ` +
108
+ `(e.g. \`git fetch origin\`). Original error: ${err instanceof Error ? err.message : String(err)}`);
109
+ }
110
+ for (const rawLine of diff.split('\n')) {
111
+ const p = rawLine.trim();
112
+ if (p)
113
+ files.add((0, path_1.resolve)(cwd, p));
114
+ }
115
+ }
116
+ return [...files];
117
+ }
118
+ /** Enumerate the modules to consider — the whole workspace, or the single module. */
119
+ function enumerateModules(pkg) {
120
+ const wsPath = pkg.getWorkspacePath();
121
+ if (wsPath) {
122
+ const map = pkg.getModuleMap();
123
+ return Object.entries(map).map(([name, m]) => ({
124
+ name,
125
+ dir: (0, path_1.resolve)(wsPath, m.path),
126
+ }));
127
+ }
128
+ if (pkg.isInModule()) {
129
+ return [{ name: pkg.getModuleName(), dir: pkg.getModulePath() }];
130
+ }
131
+ return [];
132
+ }
133
+ /** Map changed file paths to the owning module (longest matching module dir). */
134
+ function mapFilesToModules(files, modules) {
135
+ const hit = new Set();
136
+ for (const file of files) {
137
+ let best;
138
+ for (const mod of modules) {
139
+ const rel = (0, path_1.relative)(mod.dir, file);
140
+ if (rel.startsWith('..') || (0, path_1.isAbsolute)(rel))
141
+ continue;
142
+ if (!best || mod.dir.length > best.dir.length)
143
+ best = mod;
144
+ }
145
+ if (best)
146
+ hit.add(best.name);
147
+ }
148
+ return [...hit];
149
+ }
150
+ /** Expand a set of module names to include everything that transitively requires them. */
151
+ function addDependents(names, pkg) {
152
+ const map = pkg.getModuleMap();
153
+ const reverse = new Map();
154
+ for (const [name, m] of Object.entries(map)) {
155
+ for (const req of m.requires ?? []) {
156
+ if (!reverse.has(req))
157
+ reverse.set(req, []);
158
+ reverse.get(req).push(name);
159
+ }
160
+ }
161
+ const queue = [...names];
162
+ while (queue.length) {
163
+ const current = queue.shift();
164
+ for (const dependent of reverse.get(current) ?? []) {
165
+ if (!names.has(dependent)) {
166
+ names.add(dependent);
167
+ queue.push(dependent);
168
+ }
169
+ }
170
+ }
171
+ }
172
+ /**
173
+ * Verify that committed bundle artifacts are in sync with `deploy/` for the
174
+ * modules that changed (per git), failing fast on the first drift by default.
175
+ *
176
+ * This is the engine behind `pgpm package --check`: change detection + workspace
177
+ * mapping + the cheap per-module artifact verification, so CI can gate every PR
178
+ * with a one-liner and only pay for the modules that actually changed.
179
+ */
180
+ async function checkPackages(options = {}) {
181
+ const cwd = options.cwd ?? process.cwd();
182
+ const failFast = options.failFast ?? true;
183
+ const pkg = new pgpm_1.PgpmPackage(cwd);
184
+ const modules = enumerateModules(pkg);
185
+ const byName = new Map(modules.map((m) => [m.name, m]));
186
+ let base;
187
+ let changedModules = [];
188
+ let targetNames;
189
+ if (options.all) {
190
+ targetNames = modules.map((m) => m.name);
191
+ }
192
+ else {
193
+ base = resolveBase(options.since);
194
+ const files = changedFiles(cwd, base);
195
+ changedModules = mapFilesToModules(files, modules);
196
+ const set = new Set(changedModules);
197
+ if (options.dependents && pkg.getWorkspacePath())
198
+ addDependents(set, pkg);
199
+ targetNames = [...set];
200
+ }
201
+ const checked = [];
202
+ const drifted = [];
203
+ for (const name of targetNames) {
204
+ const mod = byName.get(name);
205
+ if (!mod)
206
+ continue;
207
+ checked.push(name);
208
+ const drift = checkModuleArtifact(mod.dir, name);
209
+ if (drift) {
210
+ drifted.push(drift);
211
+ if (failFast)
212
+ break;
213
+ }
214
+ }
215
+ return { targeted: targetNames, checked, drifted, base, changedModules };
216
+ }