@pgpmjs/slice 0.9.0 → 0.10.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
@@ -3,3 +3,4 @@ export * from './slice';
3
3
  export * from './output';
4
4
  export * from './refs';
5
5
  export * from './closure';
6
+ export * from './partition';
@@ -0,0 +1,139 @@
1
+ import { existsSync, readFileSync } from 'fs';
2
+ import { join } from 'path';
3
+ import { parsePlanFile } from '@pgpmjs/ast/files/plan/parser';
4
+ import { buildAstEdges } from './closure';
5
+ import { extractSqlFacts } from './refs';
6
+ import { buildDependencyGraph } from './slice';
7
+ /** The dependency edges of a change: declared plan `requires` + AST-discovered. */
8
+ function dependenciesOf(change, graph, astEdges) {
9
+ const deps = new Set();
10
+ for (const dep of graph.edges.get(change) ?? []) {
11
+ if (graph.nodes.has(dep))
12
+ deps.add(dep);
13
+ }
14
+ for (const dep of astEdges.edges.get(change)?.keys() ?? [])
15
+ deps.add(dep);
16
+ return deps;
17
+ }
18
+ /**
19
+ * Pure partition core: classify every change in the graph as per-tenant or
20
+ * shared by propagating "per-tenant-ness" from the seeds along dependency
21
+ * edges (a change that depends on a per-tenant change is itself per-tenant).
22
+ *
23
+ * Deterministic and I/O-free — the on-disk entry point is
24
+ * {@link partitionModule}.
25
+ */
26
+ export function partitionChanges(input) {
27
+ const { graph, astEdges } = input;
28
+ const warnings = [];
29
+ // dependents[x] = every change that depends on x (reverse of dependenciesOf).
30
+ const dependents = new Map();
31
+ for (const change of graph.nodes.keys()) {
32
+ for (const dep of dependenciesOf(change, graph, astEdges)) {
33
+ (dependents.get(dep) ?? dependents.set(dep, new Set()).get(dep)).add(change);
34
+ }
35
+ }
36
+ // Propagate per-tenant status from the seeds up through their dependents.
37
+ const perTenant = new Set();
38
+ const queue = [];
39
+ for (const seed of input.seeds) {
40
+ if (!graph.nodes.has(seed)) {
41
+ warnings.push({ kind: 'unknown-seed', change: seed, detail: 'seed change is not in the plan' });
42
+ continue;
43
+ }
44
+ if (!perTenant.has(seed)) {
45
+ perTenant.add(seed);
46
+ queue.push(seed);
47
+ }
48
+ }
49
+ while (queue.length > 0) {
50
+ const current = queue.shift();
51
+ for (const dependent of dependents.get(current) ?? []) {
52
+ if (perTenant.has(dependent))
53
+ continue;
54
+ perTenant.add(dependent);
55
+ queue.push(dependent);
56
+ }
57
+ }
58
+ const shared = new Set();
59
+ for (const change of graph.nodes.keys()) {
60
+ if (!perTenant.has(change))
61
+ shared.add(change);
62
+ }
63
+ const sharedDependencies = new Map();
64
+ for (const change of perTenant) {
65
+ const sharedDeps = new Set();
66
+ for (const dep of dependenciesOf(change, graph, astEdges)) {
67
+ if (shared.has(dep))
68
+ sharedDeps.add(dep);
69
+ }
70
+ if (sharedDeps.size > 0)
71
+ sharedDependencies.set(change, sharedDeps);
72
+ }
73
+ // A shared change that runs dynamic SQL could secretly reference per-tenant
74
+ // data the parser can't see — flag it so callers don't share it blindly.
75
+ for (const change of astEdges.dynamicSqlChanges) {
76
+ if (shared.has(change)) {
77
+ warnings.push({
78
+ kind: 'dynamic-sql',
79
+ change,
80
+ detail: 'shared change executes dynamic SQL; hidden references cannot be proven tenant-independent'
81
+ });
82
+ }
83
+ }
84
+ for (const { change, ref } of astEdges.unresolvedReferences) {
85
+ warnings.push({ kind: 'unresolved-reference', change, detail: `references ${ref}, produced by no change in the plan` });
86
+ }
87
+ return { perTenant, shared, sharedDependencies, warnings };
88
+ }
89
+ function objectKey(schema, name) {
90
+ return `${schema ?? ''}\u0000${name}`;
91
+ }
92
+ /**
93
+ * On-disk entry point: parse a module's plan + deploy SQL, resolve the given
94
+ * per-tenant seed *objects* to the changes that create them, and partition the
95
+ * module into shared vs per-tenant changes.
96
+ *
97
+ * `loadModule()` from `plpgsql-parser` must have been awaited first (the SQL
98
+ * fact extraction is synchronous over the WASM parser).
99
+ */
100
+ export function partitionModule(options) {
101
+ const planPath = options.planPath ?? join(options.moduleDir, 'pgpm.plan');
102
+ const parsed = parsePlanFile(planPath);
103
+ if (!parsed.data) {
104
+ const msg = parsed.errors?.map(e => `Line ${e.line}: ${e.message}`).join('\n') || 'Unknown error';
105
+ throw new Error(`Failed to parse plan file: ${msg}`);
106
+ }
107
+ const graph = buildDependencyGraph(parsed.data);
108
+ // Producer index in plan order: first change creating an object wins.
109
+ const producerByObject = new Map();
110
+ for (const change of parsed.data.changes) {
111
+ const deployPath = join(options.moduleDir, 'deploy', `${change.name}.sql`);
112
+ if (!existsSync(deployPath))
113
+ continue;
114
+ const facts = extractSqlFacts(readFileSync(deployPath, 'utf-8'));
115
+ for (const c of facts.creates) {
116
+ const key = objectKey(c.schema, c.name);
117
+ if (!producerByObject.has(key))
118
+ producerByObject.set(key, change.name);
119
+ }
120
+ }
121
+ const seedChanges = [];
122
+ const unresolvedSeeds = [];
123
+ for (const obj of options.seedObjects) {
124
+ const producer = producerByObject.get(objectKey(obj.schema, obj.name));
125
+ if (!producer) {
126
+ unresolvedSeeds.push({
127
+ kind: 'unknown-seed',
128
+ change: obj.schema ? `${obj.schema}.${obj.name}` : obj.name,
129
+ detail: 'no change in the module creates this seed object'
130
+ });
131
+ continue;
132
+ }
133
+ if (!seedChanges.includes(producer))
134
+ seedChanges.push(producer);
135
+ }
136
+ const astEdges = buildAstEdges(graph, options.moduleDir);
137
+ const result = partitionChanges({ graph, astEdges, seeds: seedChanges });
138
+ return { ...result, seedChanges, warnings: [...unresolvedSeeds, ...result.warnings] };
139
+ }
package/index.d.ts CHANGED
@@ -3,3 +3,4 @@ export * from './slice';
3
3
  export * from './output';
4
4
  export * from './refs';
5
5
  export * from './closure';
6
+ export * from './partition';
package/index.js CHANGED
@@ -19,3 +19,4 @@ __exportStar(require("./slice"), exports);
19
19
  __exportStar(require("./output"), exports);
20
20
  __exportStar(require("./refs"), exports);
21
21
  __exportStar(require("./closure"), exports);
22
+ __exportStar(require("./partition"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pgpmjs/slice",
3
- "version": "0.9.0",
3
+ "version": "0.10.1",
4
4
  "author": "Constructive <developers@constructive.io>",
5
5
  "description": "PGPM plan slicing — split a monolithic pgpm plan into packages with pattern strategies and opt-in AST-based dependency closure",
6
6
  "main": "index.js",
@@ -42,10 +42,10 @@
42
42
  "makage": "^0.3.0"
43
43
  },
44
44
  "dependencies": {
45
- "@pgpmjs/ast": "^0.9.0",
46
- "@pgpmjs/transform": "^0.9.0",
45
+ "@pgpmjs/ast": "^0.9.2",
46
+ "@pgpmjs/transform": "^0.11.0",
47
47
  "minimatch": "^10.2.5",
48
48
  "plpgsql-parser": "^18.2.1"
49
49
  },
50
- "gitHead": "72961803894504c1a9308f9c6c349ff7b48bbe14"
50
+ "gitHead": "5ef8341033a8fbd85841b770e996e468dd15333b"
51
51
  }
package/partition.d.ts ADDED
@@ -0,0 +1,74 @@
1
+ import { AstEdges } from './closure';
2
+ import { SqlObjectRef } from './refs';
3
+ import { DependencyGraph } from './types';
4
+ /**
5
+ * A change is *per-tenant* when it must be materialized once per instance
6
+ * (its objects are duplicated across tenants), and *shared* when it can be
7
+ * deployed a single time and reused. The partition is derived purely from the
8
+ * reference graph: any change that (transitively) reaches a per-tenant seed is
9
+ * itself per-tenant; everything else is provably tenant-independent.
10
+ */
11
+ export interface PartitionResult {
12
+ /** Changes that must be transpiled per tenant (a seed, or a dependent of one). */
13
+ perTenant: Set<string>;
14
+ /** Changes safe to deploy once and share across all instances. */
15
+ shared: Set<string>;
16
+ /**
17
+ * For each per-tenant change, the shared changes it depends on. This is the
18
+ * cross-boundary edge set: a per-tenant module `requires` the shared module
19
+ * that owns these changes. Shared changes never depend on per-tenant ones by
20
+ * construction, so the boundary is one-directional.
21
+ */
22
+ sharedDependencies: Map<string, Set<string>>;
23
+ /** Conditions that make the partition potentially unsound (see below). */
24
+ warnings: PartitionWarning[];
25
+ }
26
+ export interface PartitionWarning {
27
+ /**
28
+ * - `dynamic-sql`: a change classified as shared runs `EXECUTE`, so its true
29
+ * references are invisible to the parser — it *might* touch per-tenant data
30
+ * and be unsafe to share. The partition cannot prove otherwise.
31
+ * - `unresolved-reference`: a reference no change in the plan produces (an
32
+ * installed module / extension); informational, not a soundness problem.
33
+ * - `unknown-seed`: a requested seed change is not in the plan.
34
+ */
35
+ kind: 'dynamic-sql' | 'unresolved-reference' | 'unknown-seed';
36
+ change: string;
37
+ detail: string;
38
+ }
39
+ export interface PartitionInput {
40
+ graph: DependencyGraph;
41
+ astEdges: AstEdges;
42
+ /** Change names whose objects are duplicated per tenant. */
43
+ seeds: Iterable<string>;
44
+ }
45
+ /**
46
+ * Pure partition core: classify every change in the graph as per-tenant or
47
+ * shared by propagating "per-tenant-ness" from the seeds along dependency
48
+ * edges (a change that depends on a per-tenant change is itself per-tenant).
49
+ *
50
+ * Deterministic and I/O-free — the on-disk entry point is
51
+ * {@link partitionModule}.
52
+ */
53
+ export declare function partitionChanges(input: PartitionInput): PartitionResult;
54
+ export interface PartitionModuleOptions {
55
+ /** Module root containing `pgpm.plan` and `deploy/`. */
56
+ moduleDir: string;
57
+ /** Objects that are inherently per-tenant (e.g. a tenant-owned table). */
58
+ seedObjects: SqlObjectRef[];
59
+ /** Plan path override (defaults to `<moduleDir>/pgpm.plan`). */
60
+ planPath?: string;
61
+ }
62
+ export interface PartitionModuleResult extends PartitionResult {
63
+ /** The change that produces each seed object, in resolution order. */
64
+ seedChanges: string[];
65
+ }
66
+ /**
67
+ * On-disk entry point: parse a module's plan + deploy SQL, resolve the given
68
+ * per-tenant seed *objects* to the changes that create them, and partition the
69
+ * module into shared vs per-tenant changes.
70
+ *
71
+ * `loadModule()` from `plpgsql-parser` must have been awaited first (the SQL
72
+ * fact extraction is synchronous over the WASM parser).
73
+ */
74
+ export declare function partitionModule(options: PartitionModuleOptions): PartitionModuleResult;
package/partition.js ADDED
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.partitionChanges = partitionChanges;
4
+ exports.partitionModule = partitionModule;
5
+ const fs_1 = require("fs");
6
+ const path_1 = require("path");
7
+ const parser_1 = require("@pgpmjs/ast/files/plan/parser");
8
+ const closure_1 = require("./closure");
9
+ const refs_1 = require("./refs");
10
+ const slice_1 = require("./slice");
11
+ /** The dependency edges of a change: declared plan `requires` + AST-discovered. */
12
+ function dependenciesOf(change, graph, astEdges) {
13
+ const deps = new Set();
14
+ for (const dep of graph.edges.get(change) ?? []) {
15
+ if (graph.nodes.has(dep))
16
+ deps.add(dep);
17
+ }
18
+ for (const dep of astEdges.edges.get(change)?.keys() ?? [])
19
+ deps.add(dep);
20
+ return deps;
21
+ }
22
+ /**
23
+ * Pure partition core: classify every change in the graph as per-tenant or
24
+ * shared by propagating "per-tenant-ness" from the seeds along dependency
25
+ * edges (a change that depends on a per-tenant change is itself per-tenant).
26
+ *
27
+ * Deterministic and I/O-free — the on-disk entry point is
28
+ * {@link partitionModule}.
29
+ */
30
+ function partitionChanges(input) {
31
+ const { graph, astEdges } = input;
32
+ const warnings = [];
33
+ // dependents[x] = every change that depends on x (reverse of dependenciesOf).
34
+ const dependents = new Map();
35
+ for (const change of graph.nodes.keys()) {
36
+ for (const dep of dependenciesOf(change, graph, astEdges)) {
37
+ (dependents.get(dep) ?? dependents.set(dep, new Set()).get(dep)).add(change);
38
+ }
39
+ }
40
+ // Propagate per-tenant status from the seeds up through their dependents.
41
+ const perTenant = new Set();
42
+ const queue = [];
43
+ for (const seed of input.seeds) {
44
+ if (!graph.nodes.has(seed)) {
45
+ warnings.push({ kind: 'unknown-seed', change: seed, detail: 'seed change is not in the plan' });
46
+ continue;
47
+ }
48
+ if (!perTenant.has(seed)) {
49
+ perTenant.add(seed);
50
+ queue.push(seed);
51
+ }
52
+ }
53
+ while (queue.length > 0) {
54
+ const current = queue.shift();
55
+ for (const dependent of dependents.get(current) ?? []) {
56
+ if (perTenant.has(dependent))
57
+ continue;
58
+ perTenant.add(dependent);
59
+ queue.push(dependent);
60
+ }
61
+ }
62
+ const shared = new Set();
63
+ for (const change of graph.nodes.keys()) {
64
+ if (!perTenant.has(change))
65
+ shared.add(change);
66
+ }
67
+ const sharedDependencies = new Map();
68
+ for (const change of perTenant) {
69
+ const sharedDeps = new Set();
70
+ for (const dep of dependenciesOf(change, graph, astEdges)) {
71
+ if (shared.has(dep))
72
+ sharedDeps.add(dep);
73
+ }
74
+ if (sharedDeps.size > 0)
75
+ sharedDependencies.set(change, sharedDeps);
76
+ }
77
+ // A shared change that runs dynamic SQL could secretly reference per-tenant
78
+ // data the parser can't see — flag it so callers don't share it blindly.
79
+ for (const change of astEdges.dynamicSqlChanges) {
80
+ if (shared.has(change)) {
81
+ warnings.push({
82
+ kind: 'dynamic-sql',
83
+ change,
84
+ detail: 'shared change executes dynamic SQL; hidden references cannot be proven tenant-independent'
85
+ });
86
+ }
87
+ }
88
+ for (const { change, ref } of astEdges.unresolvedReferences) {
89
+ warnings.push({ kind: 'unresolved-reference', change, detail: `references ${ref}, produced by no change in the plan` });
90
+ }
91
+ return { perTenant, shared, sharedDependencies, warnings };
92
+ }
93
+ function objectKey(schema, name) {
94
+ return `${schema ?? ''}\u0000${name}`;
95
+ }
96
+ /**
97
+ * On-disk entry point: parse a module's plan + deploy SQL, resolve the given
98
+ * per-tenant seed *objects* to the changes that create them, and partition the
99
+ * module into shared vs per-tenant changes.
100
+ *
101
+ * `loadModule()` from `plpgsql-parser` must have been awaited first (the SQL
102
+ * fact extraction is synchronous over the WASM parser).
103
+ */
104
+ function partitionModule(options) {
105
+ const planPath = options.planPath ?? (0, path_1.join)(options.moduleDir, 'pgpm.plan');
106
+ const parsed = (0, parser_1.parsePlanFile)(planPath);
107
+ if (!parsed.data) {
108
+ const msg = parsed.errors?.map(e => `Line ${e.line}: ${e.message}`).join('\n') || 'Unknown error';
109
+ throw new Error(`Failed to parse plan file: ${msg}`);
110
+ }
111
+ const graph = (0, slice_1.buildDependencyGraph)(parsed.data);
112
+ // Producer index in plan order: first change creating an object wins.
113
+ const producerByObject = new Map();
114
+ for (const change of parsed.data.changes) {
115
+ const deployPath = (0, path_1.join)(options.moduleDir, 'deploy', `${change.name}.sql`);
116
+ if (!(0, fs_1.existsSync)(deployPath))
117
+ continue;
118
+ const facts = (0, refs_1.extractSqlFacts)((0, fs_1.readFileSync)(deployPath, 'utf-8'));
119
+ for (const c of facts.creates) {
120
+ const key = objectKey(c.schema, c.name);
121
+ if (!producerByObject.has(key))
122
+ producerByObject.set(key, change.name);
123
+ }
124
+ }
125
+ const seedChanges = [];
126
+ const unresolvedSeeds = [];
127
+ for (const obj of options.seedObjects) {
128
+ const producer = producerByObject.get(objectKey(obj.schema, obj.name));
129
+ if (!producer) {
130
+ unresolvedSeeds.push({
131
+ kind: 'unknown-seed',
132
+ change: obj.schema ? `${obj.schema}.${obj.name}` : obj.name,
133
+ detail: 'no change in the module creates this seed object'
134
+ });
135
+ continue;
136
+ }
137
+ if (!seedChanges.includes(producer))
138
+ seedChanges.push(producer);
139
+ }
140
+ const astEdges = (0, closure_1.buildAstEdges)(graph, options.moduleDir);
141
+ const result = partitionChanges({ graph, astEdges, seeds: seedChanges });
142
+ return { ...result, seedChanges, warnings: [...unresolvedSeeds, ...result.warnings] };
143
+ }