@pgxsinkit/server 0.1.32 → 0.1.36

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.
Files changed (52) hide show
  1. package/README.md +12 -0
  2. package/bin/pgxsinkit-generate.mjs +25 -0
  3. package/dist/cli/generate.d.ts +14 -2
  4. package/dist/cli/generate.d.ts.map +1 -1
  5. package/dist/electric-proxy.d.ts +30 -2
  6. package/dist/electric-proxy.d.ts.map +1 -1
  7. package/dist/index.d.ts +56 -9
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +3935 -936
  10. package/dist/index.js.map +40 -25
  11. package/dist/migrations/utilities.d.ts +13 -0
  12. package/dist/migrations/utilities.d.ts.map +1 -0
  13. package/dist/mutations/plpgsql-apply.d.ts +36 -0
  14. package/dist/mutations/plpgsql-apply.d.ts.map +1 -0
  15. package/dist/mutations/route.d.ts +64 -0
  16. package/dist/mutations/route.d.ts.map +1 -0
  17. package/dist/mutations/types.d.ts +4 -0
  18. package/dist/mutations/types.d.ts.map +1 -0
  19. package/dist/operations-log/ddl.d.ts +6 -0
  20. package/dist/operations-log/ddl.d.ts.map +1 -1
  21. package/dist/operations-log/schema.d.ts +2 -32
  22. package/dist/operations-log/schema.d.ts.map +1 -1
  23. package/dist/operations-log/types.d.ts +1 -5
  24. package/dist/operations-log/types.d.ts.map +1 -1
  25. package/dist/operations-log/writer.d.ts.map +1 -1
  26. package/dist/router.d.ts +22 -0
  27. package/dist/router.d.ts.map +1 -0
  28. package/dist/sql-state.d.ts +23 -0
  29. package/dist/sql-state.d.ts.map +1 -0
  30. package/package.json +11 -6
  31. package/skills/deploying/SKILL.md +162 -0
  32. package/src/cli/generate.ts +292 -21
  33. package/src/electric-proxy.ts +274 -42
  34. package/src/index.ts +146 -59
  35. package/src/migrations/utilities.ts +25 -0
  36. package/src/mutations/plpgsql-apply.ts +658 -0
  37. package/src/mutations/route.ts +1176 -0
  38. package/src/mutations/{bulk/types.ts → types.ts} +0 -2
  39. package/src/operations-log/ddl.ts +13 -3
  40. package/src/operations-log/schema.ts +9 -6
  41. package/src/operations-log/types.ts +1 -7
  42. package/src/operations-log/writer.ts +0 -2
  43. package/src/router.ts +109 -0
  44. package/src/sql-state.ts +59 -0
  45. package/dist/mutations/bulk/plpgsql-strategy.d.ts +0 -17
  46. package/dist/mutations/bulk/plpgsql-strategy.d.ts.map +0 -1
  47. package/dist/mutations/bulk/route.d.ts +0 -7
  48. package/dist/mutations/bulk/route.d.ts.map +0 -1
  49. package/dist/mutations/bulk/types.d.ts +0 -5
  50. package/dist/mutations/bulk/types.d.ts.map +0 -1
  51. package/src/mutations/bulk/plpgsql-strategy.ts +0 -370
  52. package/src/mutations/bulk/route.ts +0 -580
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env bun
2
2
  /**
3
3
  * pgxsinkit-generate — Generates a drizzle-kit migration with the
4
- * pgxsinkit_apply_batch_mutations PL/pgSQL function.
4
+ * pgxsinkit_apply_mutations PL/pgSQL function.
5
5
  *
6
6
  * External consumers (e.g. transcrobes) invoke this from their own project:
7
7
  *
@@ -16,18 +16,26 @@
16
16
  */
17
17
 
18
18
  import { spawnSync } from "node:child_process";
19
- import { readdirSync, readFileSync, writeFileSync } from "node:fs";
20
- import { join } from "node:path";
19
+ import { randomUUID } from "node:crypto";
20
+ import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
21
+ import { isAbsolute, join, resolve } from "node:path";
22
+ import { pathToFileURL } from "node:url";
21
23
 
22
24
  import type { SyncTableRegistry } from "@pgxsinkit/contracts";
23
25
 
24
- import { buildPlpgsqlBatchFunctionDdl } from "../mutations/bulk/plpgsql-strategy";
26
+ import { renderPgxsinkitUtilitiesMigration } from "../migrations/utilities";
27
+ import { buildPlpgsqlBatchFunctionDdl, expectedApplyFingerprint } from "../mutations/plpgsql-apply";
25
28
 
26
29
  function parseArgs(argv: string[]) {
30
+ let check = false;
31
+ let utilities = false;
32
+ let functionSchema: string | undefined;
27
33
  let registryPath = "";
28
34
  let projectDir = process.cwd();
29
35
  let migrationName = "sync_artifact";
30
36
  let drizzleConfig = "";
37
+ let outDir: string | undefined;
38
+ let exportName: string | undefined;
31
39
 
32
40
  for (let i = 0; i < argv.length; i++) {
33
41
  const arg = argv[i]!;
@@ -39,25 +47,83 @@ function parseArgs(argv: string[]) {
39
47
  migrationName = argv[++i]!;
40
48
  } else if (arg === "--config" && argv[i + 1]) {
41
49
  drizzleConfig = argv[++i]!;
50
+ } else if (arg === "--out" && argv[i + 1]) {
51
+ outDir = argv[++i]!;
52
+ } else if (arg === "--export" && argv[i + 1]) {
53
+ exportName = argv[++i]!;
54
+ } else if (arg === "--check") {
55
+ check = true;
56
+ } else if (arg === "--utilities") {
57
+ utilities = true;
58
+ } else if (arg === "--function-schema" && argv[i + 1]) {
59
+ functionSchema = argv[++i]!;
42
60
  }
43
61
  }
44
62
 
45
- if (!registryPath) {
63
+ // Utilities mode installs the registry-independent pgxsinkit_clock_us() function, so it needs no
64
+ // --registry; the apply-artifact modes do.
65
+ if (!registryPath && !utilities) {
46
66
  console.error(
47
- "Usage: pgxsinkit-generate --registry <path> [--project-dir .] [--name sync_artifact] [--config drizzle.config.ts]",
67
+ "Usage:\n" +
68
+ " pgxsinkit-generate [--check] --registry <path> [--export registry] [--project-dir .] [--name sync_artifact] [--config drizzle.config.ts] [--out drizzle] [--function-schema schema]\n" +
69
+ " pgxsinkit-generate --utilities [--check] --name <folder> [--project-dir .] [--config drizzle.config.ts] [--out drizzle]",
48
70
  );
49
71
  process.exit(1);
50
72
  }
51
73
 
52
- return { registryPath, projectDir, migrationName, drizzleConfig };
74
+ return {
75
+ check,
76
+ utilities,
77
+ functionSchema,
78
+ registryPath,
79
+ projectDir,
80
+ migrationName,
81
+ drizzleConfig,
82
+ outDir,
83
+ exportName,
84
+ };
53
85
  }
54
86
 
55
- async function importRegistry(registryPath: string, projectDir: string): Promise<SyncTableRegistry> {
56
- // Resolve relative to the project directory (which is cwd when running from project root)
57
- const absProjectDir = join(process.cwd(), projectDir);
58
- const resolved = registryPath.startsWith("/") ? registryPath : join(absProjectDir, registryPath);
59
- const mod = await import(resolved.startsWith("file://") ? resolved : `file://${resolved}`);
60
- return mod.transcrobesSyncRegistry ?? mod.demoSyncRegistry ?? mod.default;
87
+ /** Registry source paths are relative to the invocation directory, not the migration output directory. */
88
+ export function resolveRegistryModulePath(registryPath: string, cwd = process.cwd()): string {
89
+ return isAbsolute(registryPath) ? registryPath : resolve(cwd, registryPath);
90
+ }
91
+
92
+ function isSyncTableRegistry(value: unknown): value is SyncTableRegistry {
93
+ return typeof value === "object" && value !== null && !Array.isArray(value);
94
+ }
95
+
96
+ /** Select a registry from an imported module, with `--export` available for arbitrary names. */
97
+ export function selectRegistryExport(moduleExports: Record<string, unknown>, exportName?: string): SyncTableRegistry {
98
+ const availableExports = Object.keys(moduleExports).sort();
99
+
100
+ if (exportName) {
101
+ const selected = moduleExports[exportName];
102
+ if (isSyncTableRegistry(selected)) {
103
+ return selected;
104
+ }
105
+
106
+ throw new Error(
107
+ `Registry export '${exportName}' was not found or is not an object. Available exports: ${availableExports.join(", ") || "(none)"}`,
108
+ );
109
+ }
110
+
111
+ for (const conventionalName of ["registry", "default", "transcrobesSyncRegistry", "demoSyncRegistry"]) {
112
+ const selected = moduleExports[conventionalName];
113
+ if (isSyncTableRegistry(selected)) {
114
+ return selected;
115
+ }
116
+ }
117
+
118
+ throw new Error(
119
+ `Could not find a registry export. Export it as 'registry' or default, or pass --export <name>. Available exports: ${availableExports.join(", ") || "(none)"}`,
120
+ );
121
+ }
122
+
123
+ async function importRegistry(registryPath: string, exportName?: string): Promise<SyncTableRegistry> {
124
+ const resolved = resolveRegistryModulePath(registryPath);
125
+ const moduleExports = (await import(pathToFileURL(resolved).href)) as Record<string, unknown>;
126
+ return selectRegistryExport(moduleExports, exportName);
61
127
  }
62
128
 
63
129
  function runDrizzleGenerate(projectDir: string, name: string, drizzleConfig?: string): void {
@@ -75,14 +141,49 @@ function runDrizzleGenerate(projectDir: string, name: string, drizzleConfig?: st
75
141
  }
76
142
  }
77
143
 
78
- function findDrizzleDir(projectDir: string): string | null {
144
+ async function readOutFromConfig(configPath: string): Promise<string | undefined> {
145
+ try {
146
+ const mod = (await import(pathToFileURL(configPath).href)) as { default?: { out?: unknown } };
147
+ const out = mod.default?.out;
148
+ return typeof out === "string" ? out : undefined;
149
+ } catch {
150
+ return undefined;
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Resolves where drizzle-kit writes migrations for this project, in precedence order:
156
+ * 1. an explicit `--out` (relative to `--project-dir`),
157
+ * 2. the `out` field of the `--config` drizzle config — so a consumer whose migrations
158
+ * live somewhere non-default (e.g. `infra/board-drizzle`) never has to repeat the path,
159
+ * 3. a probe of the conventional `drizzle` / `infra/drizzle` locations.
160
+ */
161
+ export async function resolveDrizzleOutDir(
162
+ projectDir: string,
163
+ drizzleConfig?: string,
164
+ outFlag?: string,
165
+ ): Promise<string | null> {
79
166
  const cwd = join(process.cwd(), projectDir);
167
+
168
+ if (outFlag) {
169
+ return isAbsolute(outFlag) ? outFlag : join(cwd, outFlag);
170
+ }
171
+
172
+ if (drizzleConfig) {
173
+ const configPath = isAbsolute(drizzleConfig) ? drizzleConfig : join(cwd, drizzleConfig);
174
+ const out = await readOutFromConfig(configPath);
175
+ if (out) {
176
+ return isAbsolute(out) ? out : join(cwd, out);
177
+ }
178
+ }
179
+
80
180
  for (const name of ["drizzle", "infra/drizzle"]) {
81
181
  const full = join(cwd, name);
82
182
  try {
83
183
  if (readdirSync(full).length > 0) return full;
84
184
  } catch {}
85
185
  }
186
+
86
187
  return null;
87
188
  }
88
189
 
@@ -106,11 +207,179 @@ function findNewMigrationFile(drizzleDir: string): string | null {
106
207
  return null;
107
208
  }
108
209
 
210
+ /**
211
+ * `--check` (ADR-0018): the read-only, pre-deploy half of apply-function drift detection. Computes the
212
+ * fingerprint the apply function SHOULD carry for this registry + applier codegen and asserts that a
213
+ * committed migration already embeds it. No drizzle-kit, no writes — safe to run in CI. The server
214
+ * enforces the same fingerprint at startup; this surfaces the drift before a deploy. Generic by design:
215
+ * a consumer points it at their own registry, drizzle config, and (optionally) function schema.
216
+ */
217
+ async function runCheck(
218
+ registry: SyncTableRegistry,
219
+ options: {
220
+ projectDir: string;
221
+ drizzleConfig: string | undefined;
222
+ outDir: string | undefined;
223
+ functionSchema: string | undefined;
224
+ label: string;
225
+ },
226
+ ): Promise<void> {
227
+ const fingerprint = expectedApplyFingerprint(
228
+ registry,
229
+ options.functionSchema ? { functionSchema: options.functionSchema } : {},
230
+ );
231
+
232
+ const drizzleDir = await resolveDrizzleOutDir(options.projectDir, options.drizzleConfig, options.outDir);
233
+ if (!drizzleDir) {
234
+ console.error(
235
+ `[pgxsinkit-generate --check] Could not resolve a drizzle migrations directory in ${options.projectDir}.`,
236
+ );
237
+ process.exit(1);
238
+ }
239
+
240
+ for (const entry of readdirSync(drizzleDir, { withFileTypes: true })) {
241
+ if (!entry.isDirectory()) {
242
+ continue;
243
+ }
244
+ try {
245
+ if (readFileSync(join(drizzleDir, entry.name, "migration.sql"), "utf-8").includes(fingerprint)) {
246
+ console.log(`[pgxsinkit-generate --check] ✓ ${options.label}: a committed migration carries ${fingerprint}`);
247
+ return;
248
+ }
249
+ } catch {}
250
+ }
251
+
252
+ console.error(
253
+ `[pgxsinkit-generate --check] ✗ ${options.label}: no committed migration in ${drizzleDir} carries the ` +
254
+ `current apply-function fingerprint (${fingerprint}).\n` +
255
+ ` The registry or @pgxsinkit/server codegen changed since the sync function migration was generated.\n` +
256
+ ` Regenerate it (drop --check) and commit + apply the new migration before deploying.`,
257
+ );
258
+ process.exit(1);
259
+ }
260
+
261
+ /** The drizzle-kit "no previous migration" root id (an all-zero UUID), used by a chain's first folder. */
262
+ const ZERO_MIGRATION_ID = "00000000-0000-0000-0000-000000000000";
263
+
264
+ /** A committed migration carries the utilities function when its DDL declares this signature. */
265
+ const UTILITIES_SIGNATURE = "CREATE OR REPLACE FUNCTION public.pgxsinkit_clock_us()";
266
+
267
+ /**
268
+ * Writes the utilities migration as a NON-KIT folder (a hand-authored pre-baseline, mirroring the
269
+ * board-prereqs pattern): an empty-`ddl` snapshot rooted at the zero id, so it sorts and applies
270
+ * FIRST. Unlike the artifact path this does NOT invoke `drizzle-kit generate` — that stamps the
271
+ * current time and would sort the folder LAST, after the schema and artifact it must precede — so the
272
+ * caller supplies the full, early-sorting folder name via `--name` (e.g. 20260101000000_pgxsinkit_utilities).
273
+ */
274
+ function writeUtilitiesMigration(drizzleDir: string, folderName: string): string {
275
+ const dir = join(drizzleDir, folderName);
276
+ mkdirSync(dir, { recursive: true });
277
+
278
+ const header =
279
+ "-- Generated by pgxsinkit-generate --utilities\n" +
280
+ "-- Installs the canonical pgxsinkit_clock_us() microsecond clock. MUST be the first folder in the chain.\n\n";
281
+ const migrationFile = join(dir, "migration.sql");
282
+ writeFileSync(migrationFile, header + renderPgxsinkitUtilitiesMigration() + "\n");
283
+
284
+ // The snapshot mirrors a hand-authored pre-baseline (see board-drizzle/*_board_prereqs): the function
285
+ // is not part of drizzle-kit's tracked DDL model, so the snapshot's `ddl` is empty and it roots the
286
+ // chain at the zero id. `version`/`dialect` match the kit's postgres snapshot format.
287
+ const snapshot = {
288
+ id: randomUUID(),
289
+ prevIds: [ZERO_MIGRATION_ID],
290
+ version: "8",
291
+ dialect: "postgres",
292
+ ddl: [] as unknown[],
293
+ renames: [] as unknown[],
294
+ };
295
+ writeFileSync(join(dir, "snapshot.json"), `${JSON.stringify(snapshot, null, 2)}\n`);
296
+
297
+ return migrationFile;
298
+ }
299
+
300
+ /**
301
+ * The utilities counterpart of `--check`: assert a committed migration in the resolved drizzle dir
302
+ * installs the (static, registry-independent) pgxsinkit_clock_us() function. Read-only, no writes.
303
+ */
304
+ function checkUtilities(drizzleDir: string, label: string): void {
305
+ for (const entry of readdirSync(drizzleDir, { withFileTypes: true })) {
306
+ if (!entry.isDirectory()) {
307
+ continue;
308
+ }
309
+ try {
310
+ if (readFileSync(join(drizzleDir, entry.name, "migration.sql"), "utf-8").includes(UTILITIES_SIGNATURE)) {
311
+ console.log(
312
+ `[pgxsinkit-generate --utilities --check] ✓ ${label}: a committed migration installs pgxsinkit_clock_us()`,
313
+ );
314
+ return;
315
+ }
316
+ } catch {}
317
+ }
318
+
319
+ console.error(
320
+ `[pgxsinkit-generate --utilities --check] ✗ ${label}: no committed migration in ${drizzleDir} installs ` +
321
+ `public.pgxsinkit_clock_us().\n` +
322
+ ` The apply function and column DEFAULTs call it — generate the utilities migration (--utilities, drop --check) ` +
323
+ `as the first folder in the chain and commit it.`,
324
+ );
325
+ process.exit(1);
326
+ }
327
+
328
+ async function runUtilities(options: {
329
+ check: boolean;
330
+ projectDir: string;
331
+ drizzleConfig: string | undefined;
332
+ outDir: string | undefined;
333
+ migrationName: string;
334
+ }): Promise<void> {
335
+ const drizzleDir = await resolveDrizzleOutDir(options.projectDir, options.drizzleConfig, options.outDir);
336
+ if (!drizzleDir) {
337
+ console.error(
338
+ `[pgxsinkit-generate --utilities] Could not resolve a drizzle migrations directory in ${options.projectDir}.`,
339
+ );
340
+ process.exit(1);
341
+ }
342
+
343
+ if (options.check) {
344
+ checkUtilities(drizzleDir, options.migrationName);
345
+ return;
346
+ }
347
+
348
+ const migrationFile = writeUtilitiesMigration(drizzleDir, options.migrationName);
349
+ console.log(`Wrote pgxsinkit_clock_us() utilities migration to ${migrationFile}`);
350
+ }
351
+
109
352
  async function main() {
110
- const { registryPath, projectDir, migrationName, drizzleConfig } = parseArgs(process.argv.slice(2));
353
+ const {
354
+ check,
355
+ utilities,
356
+ functionSchema,
357
+ registryPath,
358
+ projectDir,
359
+ migrationName,
360
+ drizzleConfig,
361
+ outDir,
362
+ exportName,
363
+ } = parseArgs(process.argv.slice(2));
364
+
365
+ if (utilities) {
366
+ await runUtilities({ check, projectDir, drizzleConfig, outDir, migrationName });
367
+ return;
368
+ }
111
369
 
112
370
  console.log(`Importing registry from ${registryPath}...`);
113
- const registry = await importRegistry(registryPath, projectDir);
371
+ const registry = await importRegistry(registryPath, exportName);
372
+
373
+ if (check) {
374
+ await runCheck(registry, {
375
+ projectDir,
376
+ drizzleConfig,
377
+ outDir,
378
+ functionSchema,
379
+ label: exportName ?? "(conventional registry)",
380
+ });
381
+ return;
382
+ }
114
383
 
115
384
  console.log(`Generating DDL for ${Object.keys(registry).length} table(s)...`);
116
385
  const ddl = buildPlpgsqlBatchFunctionDdl(registry);
@@ -118,7 +387,7 @@ async function main() {
118
387
  console.log(`Creating empty migration via drizzle-kit generate --custom --name ${migrationName}...`);
119
388
  runDrizzleGenerate(projectDir, migrationName, drizzleConfig);
120
389
 
121
- const drizzleDir = findDrizzleDir(projectDir);
390
+ const drizzleDir = await resolveDrizzleOutDir(projectDir, drizzleConfig, outDir);
122
391
  if (!drizzleDir) {
123
392
  console.error("Could not find drizzle output directory in", projectDir);
124
393
  process.exit(1);
@@ -135,7 +404,9 @@ async function main() {
135
404
  console.log(`Wrote sync function to ${drizzleDir}/.../migration.sql`);
136
405
  }
137
406
 
138
- main().catch((err) => {
139
- console.error(err);
140
- process.exit(1);
141
- });
407
+ if (import.meta.main) {
408
+ main().catch((err) => {
409
+ console.error(err);
410
+ process.exit(1);
411
+ });
412
+ }