tina4-nodejs 3.13.151 → 3.13.152

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.
@@ -10377,8 +10377,8 @@ var init_ssoIdentity = __esm({
10377
10377
  });
10378
10378
 
10379
10379
  // ../core/src/authGate.ts
10380
- function enforceRouteAuth(req2, res, match, isDevAdmin) {
10381
- if (!(match.secure === true && match.noAuth !== true && !isDevAdmin)) {
10380
+ function enforceRouteAuth(req2, res, match) {
10381
+ if (!(match.secure === true && match.noAuth !== true)) {
10382
10382
  return false;
10383
10383
  }
10384
10384
  const authHeader = req2.headers.authorization ?? "";
@@ -14116,26 +14116,31 @@ function parseFlags(args, booleanFlags) {
14116
14116
  const positional = [];
14117
14117
  let i = 0;
14118
14118
  while (i < args.length) {
14119
- const arg = args[i];
14120
- if (arg.startsWith("--")) {
14121
- const key = arg.slice(2);
14122
- if (booleanFlags?.has(key)) {
14123
- flags[key] = true;
14124
- i += 1;
14125
- } else if (i + 1 < args.length && !args[i + 1].startsWith("--")) {
14126
- flags[key] = args[i + 1];
14127
- i += 2;
14128
- } else {
14129
- flags[key] = true;
14130
- i += 1;
14131
- }
14119
+ if (args[i].startsWith("--")) {
14120
+ i += readFlag(args, i, flags, booleanFlags);
14132
14121
  } else {
14133
- positional.push(arg);
14122
+ positional.push(args[i]);
14134
14123
  i += 1;
14135
14124
  }
14136
14125
  }
14137
14126
  return { flags, positional };
14138
14127
  }
14128
+ function readFlag(args, i, flags, booleanFlags) {
14129
+ const arg = args[i];
14130
+ const eq = arg.indexOf("=");
14131
+ if (eq !== -1) {
14132
+ flags[arg.slice(2, eq)] = arg.slice(eq + 1);
14133
+ return 1;
14134
+ }
14135
+ const key = arg.slice(2);
14136
+ const next = args[i + 1];
14137
+ if (!booleanFlags?.has(key) && next !== void 0 && !next.startsWith("--")) {
14138
+ flags[key] = next;
14139
+ return 2;
14140
+ }
14141
+ flags[key] = true;
14142
+ return 1;
14143
+ }
14139
14144
  var init_util = __esm({
14140
14145
  "../cli/src/util.ts"() {
14141
14146
  "use strict";
@@ -14148,6 +14153,7 @@ __export(generate_exports, {
14148
14153
  DEFAULT_FIELDS: () => DEFAULT_FIELDS,
14149
14154
  GENERATORS: () => GENERATORS,
14150
14155
  RESOLUTION_ENVELOPE_VERSION: () => RESOLUTION_ENVELOPE_VERSION,
14156
+ RESOLUTION_FLAGS: () => RESOLUTION_FLAGS,
14151
14157
  SQL_RESERVED_TABLE_NAMES: () => SQL_RESERVED_TABLE_NAMES,
14152
14158
  aiFill: () => aiFill,
14153
14159
  currentResolution: () => currentResolution,
@@ -14464,6 +14470,10 @@ async function generate(what, name, extraArgs = []) {
14464
14470
  extraArgs = [name, ...extraArgs];
14465
14471
  name = "";
14466
14472
  }
14473
+ if (GENERATORS[what] && !noNameGenerators.has(what) && name.startsWith("-")) {
14474
+ console.log(`Invalid ${what} name: '${name}' - names can't start with '-'.`);
14475
+ process.exit(1);
14476
+ }
14467
14477
  if (!noNameGenerators.has(what) && !name) {
14468
14478
  console.error(` Usage: tina4nodejs generate ${what} <name> [options]`);
14469
14479
  process.exit(1);
@@ -14780,7 +14790,7 @@ function generateCrud(name, flags) {
14780
14790
  if (!__resolution.jsonMode) console.log(`
14781
14791
  Generating CRUD for ${name}...
14782
14792
  `);
14783
- generateModel(name, flags, false);
14793
+ if (!flags["skip-model"]) generateModel(name, flags, false);
14784
14794
  generateCrudAdminRoute(name, table2, isPublic);
14785
14795
  if (!flags["no-templates"]) copyCrudTemplates();
14786
14796
  generateCrudGateTest(name, table2, isPublic);
@@ -16090,7 +16100,7 @@ for (const stmt of statements(downSql)) db.execute(stmt);
16090
16100
  assert("DOWN drops the ${table2} table", db.tableExists("${table2}") === false);`;
16091
16101
  writeTest(`${table2}_migration`, standaloneTest(doc, body));
16092
16102
  }
16093
- var FIELD_TYPE_MAP, SQL_RESERVED_TABLE_NAMES, RESOLUTION_ENVELOPE_VERSION, __resolution, TINA4_EDIT_MARKER, DEFAULT_FIELDS, GENERATORS, GENERATOR_LIST, NEXT_STEPS;
16103
+ var FIELD_TYPE_MAP, SQL_RESERVED_TABLE_NAMES, RESOLUTION_ENVELOPE_VERSION, __resolution, TINA4_EDIT_MARKER, DEFAULT_FIELDS, GENERATORS, RESOLUTION_FLAGS, GENERATOR_LIST, NEXT_STEPS;
16094
16104
  var init_generate = __esm({
16095
16105
  "../cli/src/commands/generate.ts"() {
16096
16106
  "use strict";
@@ -16203,22 +16213,23 @@ var init_generate = __esm({
16203
16213
  TINA4_EDIT_MARKER = /^\s*(?:\/\/|--|\{#|#)\s*tina4:edit\s+(.+?)(?:\s*#\})?\s*$/;
16204
16214
  DEFAULT_FIELDS = [["name", "string"]];
16205
16215
  GENERATORS = {
16206
- model: { handler: generateModel, usage: '<Name> [--fields "name:string,price:float"] [--table-name <name>]', summary: "ORM model + matching migration" },
16207
- route: { handler: generateRoute, usage: "<name> [--model Name] [--public]", summary: "CRUD route file, secure by default (--public opens writes)" },
16208
- crud: { handler: generateCrud, usage: '<Name> [--fields "..."] [--public] [--no-templates]', summary: "Model + migration + AutoCrud-backed admin page (toCrud) + editable crud/ templates + gate test" },
16209
- migration: { handler: (n, f) => generateMigration(n, f, void 0, void 0, !f["no-test"]), usage: "<description>", summary: "Timestamped migration file (UP/DOWN)" },
16210
- middleware: { handler: generateMiddleware, usage: "<Name>", summary: "Middleware with before/after hooks" },
16211
- test: { handler: generateTest, usage: "<name> [--model Name]", summary: "Test file" },
16212
- form: { handler: generateForm, usage: '<Name> [--fields "..."]', summary: "Form template with inputs matching model fields" },
16213
- view: { handler: generateView, usage: '<Name> [--fields "..."]', summary: "List + detail view templates" },
16214
- auth: { handler: (_n, f) => generateAuth(f), usage: "", summary: "Login/register routes (public) + User model + templates" },
16215
- service: { handler: generateService, usage: '<Name> [--every 5m | --cron "..."]', summary: "Scheduled ServiceRunner task (src/services/)" },
16216
- queue: { handler: generateQueue, usage: "<topic>", summary: "Producer + consumer daemon worker (src/services/)" },
16217
- validator: { handler: generateValidator, usage: "<Name>", summary: "Request-body Validator (src/validators/)" },
16218
- seeder: { handler: generateSeeder, usage: "<Model>", summary: "FakeData + seedOrm seeder (src/seeds/)" },
16219
- websocket: { handler: generateWebsocket, usage: "<path>", summary: "websocket() handler (src/routes/)" },
16220
- listener: { handler: generateListener, usage: "<event>", summary: "Events.on(event) listener (src/listeners/)" }
16221
- };
16216
+ model: { handler: generateModel, flags: { fields: true, "table-name": true, "no-migration": false }, usage: '<Name> [--fields "name:string,price:float"] [--table-name <name>]', summary: "ORM model + matching migration" },
16217
+ route: { handler: generateRoute, flags: { model: true, public: false, "table-name": true }, usage: "<name> [--model Name] [--public]", summary: "CRUD route file, secure by default (--public opens writes)" },
16218
+ crud: { handler: generateCrud, flags: { fields: true, "table-name": true, public: false, "no-templates": false, "no-migration": false, "skip-model": false }, usage: '<Name> [--fields "..."] [--public] [--no-templates] [--skip-model]', summary: "Model + migration + AutoCrud-backed admin page (toCrud) + editable crud/ templates + gate test" },
16219
+ migration: { handler: (n, f) => generateMigration(n, f, void 0, void 0, !f["no-test"]), flags: { fields: true, "table-name": true, "no-test": false }, usage: "<description>", summary: "Timestamped migration file (UP/DOWN)" },
16220
+ middleware: { handler: generateMiddleware, flags: {}, usage: "<Name>", summary: "Middleware with before/after hooks" },
16221
+ test: { handler: generateTest, flags: { model: true, public: false, "secure-writes": false }, usage: "<name> [--model Name]", summary: "Test file" },
16222
+ form: { handler: generateForm, flags: { fields: true, "table-name": true }, usage: '<Name> [--fields "..."]', summary: "Form template with inputs matching model fields" },
16223
+ view: { handler: generateView, flags: { fields: true, "table-name": true }, usage: '<Name> [--fields "..."]', summary: "List + detail view templates" },
16224
+ auth: { handler: (_n, f) => generateAuth(f), flags: {}, usage: "", summary: "Login/register routes (public) + User model + templates" },
16225
+ service: { handler: generateService, flags: { every: true, cron: true }, usage: '<Name> [--every 5m | --cron "..."]', summary: "Scheduled ServiceRunner task (src/services/)" },
16226
+ queue: { handler: generateQueue, flags: {}, usage: "<topic>", summary: "Producer + consumer daemon worker (src/services/)" },
16227
+ validator: { handler: generateValidator, flags: {}, usage: "<Name>", summary: "Request-body Validator (src/validators/)" },
16228
+ seeder: { handler: generateSeeder, flags: { "table-name": true }, usage: "<Model>", summary: "FakeData + seedOrm seeder (src/seeds/)" },
16229
+ websocket: { handler: generateWebsocket, flags: {}, usage: "<path>", summary: "websocket() handler (src/routes/)" },
16230
+ listener: { handler: generateListener, flags: {}, usage: "<event>", summary: "Events.on(event) listener (src/listeners/)" }
16231
+ };
16232
+ RESOLUTION_FLAGS = { json: false, "dry-run": false };
16222
16233
  GENERATOR_LIST = Object.keys(GENERATORS).join(", ");
16223
16234
  NEXT_STEPS = {
16224
16235
  model: ({ name, table: table2 }) => [
@@ -26033,7 +26044,8 @@ var init_devAdmin = __esm({
26033
26044
  router.addRoute({
26034
26045
  method: route.method,
26035
26046
  pattern: route.pattern,
26036
- handler: route.handler
26047
+ handler: route.handler,
26048
+ noAuth: true
26037
26049
  });
26038
26050
  }
26039
26051
  if (mcpEnabled()) {
@@ -26057,7 +26069,8 @@ var init_devAdmin = __esm({
26057
26069
  router.addRoute({
26058
26070
  method: route.method,
26059
26071
  pattern: route.pattern,
26060
- handler: route.handler
26072
+ handler: route.handler,
26073
+ noAuth: true
26061
26074
  });
26062
26075
  }
26063
26076
  getDefaultDevServer();
@@ -29324,7 +29337,7 @@ async function runMatchedRoute(ctx) {
29324
29337
  const { req: req2, res, match, postMatchMiddleware } = ctx;
29325
29338
  req2.params = match.params;
29326
29339
  if (await runGlobalMiddlewarePass(postMatchMiddleware, req2, res)) return;
29327
- if (enforceRouteAuth(req2, res, match, ctx.pathname.startsWith("/__dev"))) return;
29340
+ if (enforceRouteAuth(req2, res, match)) return;
29328
29341
  const routeMiddlewareClasses = (match.middlewares ?? []).filter(isMiddlewareClass);
29329
29342
  let handlerSkipped = false;
29330
29343
  if (match.middlewares && match.middlewares.length > 0) {
@@ -39814,6 +39827,9 @@ var init_postgres = __esm({
39814
39827
  await withConnectTimeout(
39815
39828
  () => {
39816
39829
  this.client = typeof this.config === "string" ? new Client({ connectionString: this.config, ...timeoutOption }) : new Client({ ...this.config, ...timeoutOption });
39830
+ this.client.on("error", () => {
39831
+ this.connectionIsDead = true;
39832
+ });
39817
39833
  return this.client.connect();
39818
39834
  },
39819
39835
  budgetMs,
@@ -39837,6 +39853,52 @@ var init_postgres = __esm({
39837
39853
  throw new Error("PostgreSQL adapter not connected. Call connect() first.");
39838
39854
  }
39839
39855
  }
39856
+ // ── Reconnect after a dropped link (parity with the Python master, #236/#242) ──
39857
+ // pg's Client does not reconnect itself: once the server drops the link it must
39858
+ // be rebuilt. A statement that hits a dropped link reconnects and retries once
39859
+ // when nothing uncommitted went down with it; inside an explicit transaction the
39860
+ // error surfaces. A reconnect that itself fails leaves the link dead (not null-
39861
+ // guarded away), so the NEXT statement retries and recovers once a server returns.
39862
+ connectionIsDead = false;
39863
+ isConnectionError(e) {
39864
+ const msg = e instanceof Error ? e.message : String(e);
39865
+ return /connection terminated|terminating connection|server closed the connection|encountered a connection error|connection closed|not queryable|ECONNRESET|EPIPE|socket hang up/i.test(msg);
39866
+ }
39867
+ async reconnect() {
39868
+ void Promise.resolve(this.client?.end()).catch(() => {
39869
+ });
39870
+ this.client = null;
39871
+ this.connectionIsDead = false;
39872
+ await this.connect();
39873
+ }
39874
+ async ensureLiveConnection() {
39875
+ if (!this._inTransaction && (this.client === null || this.connectionIsDead)) {
39876
+ await this.reconnect();
39877
+ }
39878
+ }
39879
+ async runQuery(sql, params) {
39880
+ await this.ensureLiveConnection();
39881
+ this.ensureConnected();
39882
+ try {
39883
+ return await this.client.query(sql, params);
39884
+ } catch (e) {
39885
+ if (!this.isConnectionError(e)) throw e;
39886
+ this.connectionIsDead = true;
39887
+ if (this._inTransaction) throw e;
39888
+ await this.reconnect();
39889
+ return await this.client.query(sql, params);
39890
+ }
39891
+ }
39892
+ // Transaction control (BEGIN/COMMIT/ROLLBACK) runs RAW - no reconnect, no
39893
+ // pre-heal. A failed BEGIN/COMMIT/ROLLBACK must surface so the connection-pool
39894
+ // layer can discard the connection and restore capacity; reconnecting or
39895
+ // retrying here would mask that failure (databasePoolIsolation contract).
39896
+ // Dropped-link recovery stays on the DATA path (runQuery): the next data
39897
+ // statement heals the link.
39898
+ async rawQuery(sql) {
39899
+ this.ensureConnected();
39900
+ await this.client.query(sql);
39901
+ }
39840
39902
  /** Convert ? placeholders to $1, $2, ... for pg. */
39841
39903
  /** Ensure bytea columns are Buffer (already the case with pg). No-op guard. */
39842
39904
  decodeBlobs(row) {
@@ -39886,7 +39948,6 @@ var init_postgres = __esm({
39886
39948
  return null;
39887
39949
  }
39888
39950
  execute(sql, params) {
39889
- this.ensureConnected();
39890
39951
  const convertedSql = this.convertPlaceholders(sql);
39891
39952
  throw new Error("Use executeAsync() for PostgreSQL \u2014 async adapter requires async methods.");
39892
39953
  }
@@ -39921,9 +39982,8 @@ var init_postgres = __esm({
39921
39982
  }
39922
39983
  /** Async execute for real usage. */
39923
39984
  async executeAsync(sql, params) {
39924
- this.ensureConnected();
39925
39985
  const convertedSql = this.bindable(sql, params);
39926
- const result = await this.client.query(convertedSql, params);
39986
+ const result = await this.runQuery(convertedSql, params);
39927
39987
  if (result.rows?.[0]?.id !== void 0) {
39928
39988
  this._lastInsertId = this.normalizeId(result.rows[0].id);
39929
39989
  }
@@ -39934,9 +39994,8 @@ var init_postgres = __esm({
39934
39994
  }
39935
39995
  /** Async query for real usage. */
39936
39996
  async queryAsync(sql, params) {
39937
- this.ensureConnected();
39938
39997
  const convertedSql = this.bindable(sql, params);
39939
- const result = await this.client.query(convertedSql, params);
39998
+ const result = await this.runQuery(convertedSql, params);
39940
39999
  return result.rows.map((row) => this.decodeBlobs(row));
39941
40000
  }
39942
40001
  fetch(sql, params, limit, skip) {
@@ -39964,7 +40023,6 @@ var init_postgres = __esm({
39964
40023
  throw new Error("Use insertAsync() for PostgreSQL.");
39965
40024
  }
39966
40025
  async insertAsync(table2, data) {
39967
- this.ensureConnected();
39968
40026
  if (Array.isArray(data)) {
39969
40027
  const batch = buildInsertRows(ANSI_DIALECT, table2, data);
39970
40028
  if (!batch) return { success: true, affectedRows: 0 };
@@ -39978,7 +40036,7 @@ var init_postgres = __esm({
39978
40036
  }
39979
40037
  const { sql, values } = buildInsertRow(POSTGRES_DIALECT, table2, data, " RETURNING *");
39980
40038
  try {
39981
- const result = await this.client.query(sql, values);
40039
+ const result = await this.runQuery(sql, values);
39982
40040
  const insertedRow = result.rows[0];
39983
40041
  const id = this.normalizeId(insertedRow?.id);
39984
40042
  if (id !== null) this._lastInsertId = id;
@@ -39995,13 +40053,12 @@ var init_postgres = __esm({
39995
40053
  throw new Error("Use updateAsync() for PostgreSQL.");
39996
40054
  }
39997
40055
  async updateAsync(table2, data, filter, params) {
39998
- this.ensureConnected();
39999
40056
  const { sql, values } = buildUpdate(POSTGRES_DIALECT, table2, data, filter, params, {
40000
40057
  startAt: 1,
40001
40058
  convertFragment: (fragment, startAt) => this.convertPlaceholders(fragment, startAt)
40002
40059
  });
40003
40060
  try {
40004
- const result = await this.client.query(sql, values);
40061
+ const result = await this.runQuery(sql, values);
40005
40062
  return { success: true, affectedRows: result.rowCount ?? 0 };
40006
40063
  } catch (e) {
40007
40064
  return { success: false, affectedRows: 0, error: e.message };
@@ -40011,13 +40068,12 @@ var init_postgres = __esm({
40011
40068
  throw new Error("Use deleteAsync() for PostgreSQL.");
40012
40069
  }
40013
40070
  async deleteAsync(table2, filter, params) {
40014
- this.ensureConnected();
40015
40071
  const { sql, values } = buildDelete(POSTGRES_DIALECT, table2, filter, params, {
40016
40072
  startAt: 1,
40017
40073
  convertFragment: (fragment) => this.bindable(fragment, params)
40018
40074
  });
40019
40075
  try {
40020
- const result = await this.client.query(sql, values);
40076
+ const result = await this.runQuery(sql, values);
40021
40077
  return { success: true, affectedRows: result.rowCount ?? 0 };
40022
40078
  } catch (e) {
40023
40079
  return { success: false, affectedRows: 0, error: e.message };
@@ -40027,22 +40083,28 @@ var init_postgres = __esm({
40027
40083
  throw new Error("Use startTransactionAsync() for PostgreSQL.");
40028
40084
  }
40029
40085
  async startTransactionAsync() {
40030
- await this.executeAsync("BEGIN");
40086
+ await this.rawQuery("BEGIN");
40031
40087
  this._inTransaction = true;
40032
40088
  }
40033
40089
  commit() {
40034
40090
  throw new Error("Use commitAsync() for PostgreSQL.");
40035
40091
  }
40036
40092
  async commitAsync() {
40037
- await this.executeAsync("COMMIT");
40038
- this._inTransaction = false;
40093
+ try {
40094
+ await this.rawQuery("COMMIT");
40095
+ } finally {
40096
+ this._inTransaction = false;
40097
+ }
40039
40098
  }
40040
40099
  rollback() {
40041
40100
  throw new Error("Use rollbackAsync() for PostgreSQL.");
40042
40101
  }
40043
40102
  async rollbackAsync() {
40044
- await this.executeAsync("ROLLBACK");
40045
- this._inTransaction = false;
40103
+ try {
40104
+ await this.rawQuery("ROLLBACK");
40105
+ } finally {
40106
+ this._inTransaction = false;
40107
+ }
40046
40108
  }
40047
40109
  getTables() {
40048
40110
  throw new Error("Use tablesAsync() for PostgreSQL.");
@@ -48712,6 +48774,12 @@ import { dirname as dirname16, isAbsolute as isAbsolute6, join as join32 } from
48712
48774
  function iso(d) {
48713
48775
  return d.toISOString();
48714
48776
  }
48777
+ function setOwn(obj, key, value) {
48778
+ Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true });
48779
+ }
48780
+ function getOwn(obj, key) {
48781
+ return Object.hasOwn(obj, key) ? obj[key] : void 0;
48782
+ }
48715
48783
  function encodeValue(value) {
48716
48784
  if (value instanceof ObjectId) return value.toString();
48717
48785
  if (value instanceof Date) return iso(value);
@@ -48719,7 +48787,7 @@ function encodeValue(value) {
48719
48787
  if (value !== null && typeof value === "object") {
48720
48788
  const out = {};
48721
48789
  for (const [k, v] of Object.entries(value)) {
48722
- out[k] = encodeValue(v);
48790
+ setOwn(out, k, encodeValue(v));
48723
48791
  }
48724
48792
  return out;
48725
48793
  }
@@ -48738,7 +48806,7 @@ function decodeValue(value) {
48738
48806
  if (value !== null && typeof value === "object") {
48739
48807
  const out = {};
48740
48808
  for (const [k, v] of Object.entries(value)) {
48741
- out[k] = decodeValue(v);
48809
+ setOwn(out, k, decodeValue(v));
48742
48810
  }
48743
48811
  return out;
48744
48812
  }
@@ -48884,31 +48952,32 @@ function project(doc, projection) {
48884
48952
  const exclude = new Set(Object.entries(projection).filter(([, v]) => !v).map(([k]) => k));
48885
48953
  if (include.size > 0) {
48886
48954
  const out2 = {};
48887
- for (const k of include) if (k in doc) out2[k] = doc[k];
48955
+ for (const k of include) if (Object.hasOwn(doc, k)) setOwn(out2, k, doc[k]);
48888
48956
  const idVal = projection._id;
48889
48957
  if ((idVal === void 0 || idVal) && "_id" in doc) out2._id = doc._id;
48890
48958
  return out2;
48891
48959
  }
48892
48960
  const out = {};
48893
- for (const [k, v] of Object.entries(doc)) if (!exclude.has(k)) out[k] = v;
48961
+ for (const [k, v] of Object.entries(doc)) if (!exclude.has(k)) setOwn(out, k, v);
48894
48962
  return out;
48895
48963
  }
48896
48964
  function setPath(doc, dotted, value) {
48897
48965
  const parts = dotted.split(".");
48898
48966
  let node = doc;
48899
48967
  for (const p of parts.slice(0, -1)) {
48900
- if (node[p] === void 0 || node[p] === null || typeof node[p] !== "object") {
48901
- node[p] = {};
48968
+ const child = getOwn(node, p);
48969
+ if (child === void 0 || child === null || typeof child !== "object") {
48970
+ setOwn(node, p, {});
48902
48971
  }
48903
48972
  node = node[p];
48904
48973
  }
48905
- node[parts[parts.length - 1]] = value;
48974
+ setOwn(node, parts[parts.length - 1], value);
48906
48975
  }
48907
48976
  function unsetPath(doc, dotted) {
48908
48977
  const parts = dotted.split(".");
48909
48978
  let node = doc;
48910
48979
  for (const p of parts.slice(0, -1)) {
48911
- const next = node[p];
48980
+ const next = getOwn(node, p);
48912
48981
  if (next === null || typeof next !== "object") return;
48913
48982
  node = next;
48914
48983
  }
@@ -136,6 +136,11 @@ export class PostgresAdapter implements DatabaseAdapter {
136
136
  this.client = typeof this.config === "string"
137
137
  ? new Client({ connectionString: this.config, ...timeoutOption })
138
138
  : new Client({ ...this.config, ...timeoutOption });
139
+ // pg emits an async 'error' event when the server drops the link
140
+ // (failover, idle reap, pg_terminate_backend). With no listener Node
141
+ // throws it as an uncaught exception and crashes the process, so absorb
142
+ // it and mark the link dead - the next statement rebuilds it (#236/#242).
143
+ (this.client as unknown as NodeJS.EventEmitter).on("error", () => { this.connectionIsDead = true; });
139
144
  return this.client!.connect();
140
145
  },
141
146
  budgetMs,
@@ -158,6 +163,59 @@ export class PostgresAdapter implements DatabaseAdapter {
158
163
  }
159
164
  }
160
165
 
166
+ // ── Reconnect after a dropped link (parity with the Python master, #236/#242) ──
167
+ // pg's Client does not reconnect itself: once the server drops the link it must
168
+ // be rebuilt. A statement that hits a dropped link reconnects and retries once
169
+ // when nothing uncommitted went down with it; inside an explicit transaction the
170
+ // error surfaces. A reconnect that itself fails leaves the link dead (not null-
171
+ // guarded away), so the NEXT statement retries and recovers once a server returns.
172
+ private connectionIsDead = false;
173
+
174
+ private isConnectionError(e: unknown): boolean {
175
+ const msg = e instanceof Error ? e.message : String(e);
176
+ return /connection terminated|terminating connection|server closed the connection|encountered a connection error|connection closed|not queryable|ECONNRESET|EPIPE|socket hang up/i.test(msg);
177
+ }
178
+
179
+ private async reconnect(): Promise<void> {
180
+ // end() on a dropped socket can HANG, so fire-and-forget it (the same
181
+ // pattern connect() uses for its own timeout cleanup) rather than await it.
182
+ void Promise.resolve(this.client?.end()).catch(() => { /* already gone */ });
183
+ this.client = null;
184
+ this.connectionIsDead = false;
185
+ await this.connect(); // rebuilds this.client from the stored config
186
+ }
187
+
188
+ private async ensureLiveConnection(): Promise<void> {
189
+ if (!this._inTransaction && (this.client === null || this.connectionIsDead)) {
190
+ await this.reconnect();
191
+ }
192
+ }
193
+
194
+ private async runQuery(sql: string, params?: unknown[]): Promise<import("pg").QueryResult> {
195
+ await this.ensureLiveConnection();
196
+ this.ensureConnected();
197
+ try {
198
+ return await this.client!.query(sql, params);
199
+ } catch (e) {
200
+ if (!this.isConnectionError(e)) throw e; // a genuine SQL error
201
+ this.connectionIsDead = true; // a later statement rebuilds the link
202
+ if (this._inTransaction) throw e; // the caller owns the open transaction
203
+ await this.reconnect(); // nothing uncommitted: heal and retry once
204
+ return await this.client!.query(sql, params);
205
+ }
206
+ }
207
+
208
+ // Transaction control (BEGIN/COMMIT/ROLLBACK) runs RAW - no reconnect, no
209
+ // pre-heal. A failed BEGIN/COMMIT/ROLLBACK must surface so the connection-pool
210
+ // layer can discard the connection and restore capacity; reconnecting or
211
+ // retrying here would mask that failure (databasePoolIsolation contract).
212
+ // Dropped-link recovery stays on the DATA path (runQuery): the next data
213
+ // statement heals the link.
214
+ private async rawQuery(sql: string): Promise<void> {
215
+ this.ensureConnected();
216
+ await this.client!.query(sql);
217
+ }
218
+
161
219
  /** Convert ? placeholders to $1, $2, ... for pg. */
162
220
  /** Ensure bytea columns are Buffer (already the case with pg). No-op guard. */
163
221
  private decodeBlobs<T>(row: T): T {
@@ -212,7 +270,6 @@ export class PostgresAdapter implements DatabaseAdapter {
212
270
  }
213
271
 
214
272
  execute(sql: string, params?: unknown[]): unknown {
215
- this.ensureConnected();
216
273
  const convertedSql = this.convertPlaceholders(sql);
217
274
  // pg client methods are async — we store a promise-based wrapper
218
275
  // Since the interface is sync, we provide executeAsync for real usage
@@ -255,9 +312,8 @@ export class PostgresAdapter implements DatabaseAdapter {
255
312
 
256
313
  /** Async execute for real usage. */
257
314
  async executeAsync(sql: string, params?: unknown[]): Promise<unknown> {
258
- this.ensureConnected();
259
315
  const convertedSql = this.bindable(sql, params);
260
- const result = await this.client!.query(convertedSql, params);
316
+ const result = await this.runQuery(convertedSql, params);
261
317
  if (result.rows?.[0]?.id !== undefined) {
262
318
  this._lastInsertId = this.normalizeId(result.rows[0].id);
263
319
  }
@@ -270,9 +326,8 @@ export class PostgresAdapter implements DatabaseAdapter {
270
326
 
271
327
  /** Async query for real usage. */
272
328
  async queryAsync<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<T[]> {
273
- this.ensureConnected();
274
329
  const convertedSql = this.bindable(sql, params);
275
- const result = await this.client!.query(convertedSql, params);
330
+ const result = await this.runQuery(convertedSql, params);
276
331
  return (result.rows as T[]).map(row => this.decodeBlobs(row));
277
332
  }
278
333
 
@@ -308,7 +363,6 @@ export class PostgresAdapter implements DatabaseAdapter {
308
363
  }
309
364
 
310
365
  async insertAsync(table: string, data: Record<string, unknown> | Record<string, unknown>[]): Promise<DatabaseResult> {
311
- this.ensureConnected();
312
366
  // A list of dicts is a batch insert — build one parameterised INSERT and run
313
367
  // it once per row via executeManyAsync (ONE connection, wrapped in a single
314
368
  // transaction). Database.insert / the docs advertise `data: object | object[]`;
@@ -331,7 +385,7 @@ export class PostgresAdapter implements DatabaseAdapter {
331
385
  const { sql, values } = buildInsertRow(POSTGRES_DIALECT, table, data, " RETURNING *");
332
386
 
333
387
  try {
334
- const result = await this.client!.query(sql, values);
388
+ const result = await this.runQuery(sql, values);
335
389
  const insertedRow = result.rows[0];
336
390
  const id = this.normalizeId(insertedRow?.id);
337
391
  if (id !== null) this._lastInsertId = id;
@@ -350,7 +404,6 @@ export class PostgresAdapter implements DatabaseAdapter {
350
404
  }
351
405
 
352
406
  async updateAsync(table: string, data: Record<string, unknown>, filter: Record<string, unknown> | string, params?: unknown[]): Promise<DatabaseResult> {
353
- this.ensureConnected();
354
407
  // The composer numbers the SET markers from $1 and continues the WHERE
355
408
  // markers past them; a raw string filter's `?` are rewritten to $N via
356
409
  // convertPlaceholders (identity would leave `?`, which pg rejects).
@@ -360,7 +413,7 @@ export class PostgresAdapter implements DatabaseAdapter {
360
413
  });
361
414
 
362
415
  try {
363
- const result = await this.client!.query(sql, values);
416
+ const result = await this.runQuery(sql, values);
364
417
  return { success: true, affectedRows: result.rowCount ?? 0 };
365
418
  } catch (e) {
366
419
  return { success: false, affectedRows: 0, error: (e as Error).message };
@@ -372,7 +425,6 @@ export class PostgresAdapter implements DatabaseAdapter {
372
425
  }
373
426
 
374
427
  async deleteAsync(table: string, filter: Record<string, unknown> | string, params?: unknown[]): Promise<DatabaseResult> {
375
- this.ensureConnected();
376
428
  // bindable() rewrites a raw fragment's `?` to $N only when params are bound
377
429
  // (truncate() passes "1 = 1" with none — no rewrite, no error). A hash filter
378
430
  // numbers its `$N` from 1.
@@ -382,7 +434,7 @@ export class PostgresAdapter implements DatabaseAdapter {
382
434
  });
383
435
 
384
436
  try {
385
- const result = await this.client!.query(sql, values);
437
+ const result = await this.runQuery(sql, values);
386
438
  return { success: true, affectedRows: result.rowCount ?? 0 };
387
439
  } catch (e) {
388
440
  return { success: false, affectedRows: 0, error: (e as Error).message };
@@ -394,7 +446,7 @@ export class PostgresAdapter implements DatabaseAdapter {
394
446
  }
395
447
 
396
448
  async startTransactionAsync(): Promise<void> {
397
- await this.executeAsync("BEGIN");
449
+ await this.rawQuery("BEGIN");
398
450
  // Mark the connection as inside an explicit transaction so executeManyAsync's
399
451
  // owns-guard (owns = !_inTransaction) joins THIS transaction instead of
400
452
  // opening its own inner BEGIN/COMMIT (which would commit this outer
@@ -408,10 +460,14 @@ export class PostgresAdapter implements DatabaseAdapter {
408
460
  }
409
461
 
410
462
  async commitAsync(): Promise<void> {
411
- await this.executeAsync("COMMIT");
412
- // Transaction closed — clear the flag so subsequent standalone batches own
413
- // their own transaction again (parity with Python master commit()).
414
- this._inTransaction = false;
463
+ // The transaction ends whether or not COMMIT succeeds, so clear the flag in
464
+ // finally - a COMMIT that fails on a dropped link would otherwise leave
465
+ // _inTransaction set and wedge every later reconnect (#244).
466
+ try {
467
+ await this.rawQuery("COMMIT");
468
+ } finally {
469
+ this._inTransaction = false;
470
+ }
415
471
  }
416
472
 
417
473
  rollback(): void {
@@ -419,9 +475,13 @@ export class PostgresAdapter implements DatabaseAdapter {
419
475
  }
420
476
 
421
477
  async rollbackAsync(): Promise<void> {
422
- await this.executeAsync("ROLLBACK");
423
- // Transaction closed — clear the flag (parity with Python master rollback()).
424
- this._inTransaction = false;
478
+ // Clear the flag even if ROLLBACK fails on a dropped link - the transaction
479
+ // is over either way, and leaving it set would wedge every later reconnect (#244).
480
+ try {
481
+ await this.rawQuery("ROLLBACK");
482
+ } finally {
483
+ this._inTransaction = false;
484
+ }
425
485
  }
426
486
 
427
487
  getTables(): string[] {