@open-mercato/shared 0.10.1-develop.8165.1.3de4ce96a8 → 0.10.1-develop.8180.1.c6789f43f3

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.
@@ -1,9 +1,10 @@
1
+ const UNIQUE_VIOLATION_MESSAGE = /duplicate key value violates unique constraint/i;
1
2
  function isUniqueViolation(err) {
2
- if (!err || typeof err !== "object") return false;
3
- const code = err.code;
4
- if (code === "23505") return true;
5
- const message = err.message;
6
- return typeof message === "string" && /duplicate key value|unique constraint/i.test(message);
3
+ return pgErrorCandidates(err).some((candidate) => {
4
+ if (candidate.code === "23505") return true;
5
+ if (candidate.name === "UniqueConstraintViolationException") return true;
6
+ return typeof candidate.message === "string" && UNIQUE_VIOLATION_MESSAGE.test(candidate.message);
7
+ });
7
8
  }
8
9
  const FOREIGN_KEY_VIOLATION_MESSAGE = /violates foreign key constraint(?: "([^"]+)")?/i;
9
10
  const MAX_ERROR_CHAIN_DEPTH = 4;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/db/pg-errors.ts"],
4
- "sourcesContent": ["/**\n * Detect a Postgres unique-constraint violation (SQLSTATE 23505) regardless of\n * the ORM/driver layer that surfaces it. Shared across modules so duplicate-insert\n * handling stays consistent platform-wide.\n */\nexport function isUniqueViolation(err: unknown): boolean {\n if (!err || typeof err !== 'object') return false\n const code = (err as { code?: string }).code\n if (code === '23505') return true // Postgres unique_violation\n const message = (err as { message?: string }).message\n return typeof message === 'string' && /duplicate key value|unique constraint/i.test(message)\n}\n\nconst FOREIGN_KEY_VIOLATION_MESSAGE = /violates foreign key constraint(?: \"([^\"]+)\")?/i\n\nconst MAX_ERROR_CHAIN_DEPTH = 4\n\n/**\n * MikroORM wraps driver errors and copies the pg fields onto the wrapper, but\n * the original error may also sit behind `cause` (Node) or `previous`\n * (MikroORM), possibly re-wrapped by a transaction helper. Walk that chain,\n * breadth-first with a small depth cap, so a check works on any layer.\n */\nfunction pgErrorCandidates(err: unknown): Array<Record<string, unknown>> {\n const found: Array<Record<string, unknown>> = []\n const seen = new Set<unknown>()\n let layer: unknown[] = [err]\n for (let depth = 0; depth < MAX_ERROR_CHAIN_DEPTH && layer.length > 0; depth += 1) {\n const next: unknown[] = []\n for (const candidate of layer) {\n if (!candidate || typeof candidate !== 'object' || seen.has(candidate)) continue\n seen.add(candidate)\n const record = candidate as Record<string, unknown>\n found.push(record)\n next.push(record.cause, record.previous)\n }\n layer = next\n }\n return found\n}\n\n/**\n * Detect a Postgres foreign-key violation (SQLSTATE 23503): the row is still\n * referenced by a dependent table, or the payload references a parent that\n * does not exist. Looks through MikroORM's driver-error wrapping.\n */\nexport function isForeignKeyViolation(err: unknown): boolean {\n return pgErrorCandidates(err).some((candidate) => {\n if (candidate.code === '23503') return true // Postgres foreign_key_violation\n return typeof candidate.message === 'string' && FOREIGN_KEY_VIOLATION_MESSAGE.test(candidate.message)\n })\n}\n\n/**\n * Name of the constraint behind a foreign-key violation, read from the pg\n * `constraint` field on any layer of the wrapper chain, or parsed out of the\n * quoted constraint in the driver message when the field is missing.\n */\nexport function getForeignKeyViolationConstraint(err: unknown): string | null {\n for (const candidate of pgErrorCandidates(err)) {\n if (typeof candidate.constraint === 'string' && candidate.constraint.length > 0) return candidate.constraint\n }\n for (const candidate of pgErrorCandidates(err)) {\n if (typeof candidate.message !== 'string') continue\n const match = FOREIGN_KEY_VIOLATION_MESSAGE.exec(candidate.message)\n if (match?.[1]) return match[1]\n }\n return null\n}\n\n/**\n * A Postgres SQLSTATE is always exactly 5 characters from `[0-9A-Z]`, and every\n * class in the standard SQLSTATE table carries at least one digit. Node system\n * errors (`ECONNREFUSED`), Node internal errors (`ERR_INVALID_ARG_TYPE`), and the\n * five-letter Node errno codes (`EPIPE`, `EPERM`, `EBUSY`) would otherwise be\n * misread as a SQLSTATE, since they also populate a string `code` field; the\n * digit requirement rules those out without excluding any real SQLSTATE.\n */\nconst SQLSTATE_PATTERN = /^(?=.*[0-9])[0-9A-Z]{5}$/\n\n/**\n * The Postgres SQLSTATE behind an error, read from the pg `code` field on any\n * layer of the driver-error wrapper chain (see `pgErrorCandidates`). Returns\n * `null` when no layer carries a `code` matching the SQLSTATE shape, which\n * also covers non-Postgres errors whose `code` is a Node error code.\n */\nexport function readPgSqlState(err: unknown): string | null {\n for (const candidate of pgErrorCandidates(err)) {\n if (typeof candidate.code === 'string' && SQLSTATE_PATTERN.test(candidate.code)) return candidate.code\n }\n return null\n}\n\n/**\n * Postgres SQLSTATEs for transient connection / availability failures \u2014 the\n * database (or its connection pool) is temporarily unreachable and the request\n * can succeed on retry. Deliberately scoped to connection/availability codes;\n * query-level conflicts (deadlock 40P01, serialization 40001, lock_not_available\n * 55P03) are NOT included because they do not mean \"service unavailable\".\n */\nconst TRANSIENT_CONNECTION_SQLSTATES = new Set([\n '53300', // too_many_connections\n '53400', // configuration_limit_exceeded\n '57P01', // admin_shutdown\n '57P02', // crash_shutdown\n '57P03', // cannot_connect_now (db starting up)\n '08000', // connection_exception\n '08001', // sqlclient_unable_to_establish_sqlconnection\n '08003', // connection_does_not_exist\n '08006', // connection_failure\n])\n\n/**\n * Postgres-driver / connection-pool messages that describe a transient DB\n * connection failure when the SQLSTATE is dropped by the ORM wrapper. These are\n * intentionally DB-specific phrases only. Bare socket codes (ECONNREFUSED,\n * ETIMEDOUT, \u2026) are deliberately NOT matched: they can originate from any\n * outbound socket (HTTP, cache, queue), so keying off them would falsely\n * attribute unrelated failures to the database.\n */\nconst TRANSIENT_DB_MESSAGE_PATTERNS = [\n /too many clients already/i,\n /unable to acquire a connection/i,\n /timeout acquiring a connection/i,\n /connection terminated/i,\n /the database system is (starting up|shutting down|in recovery)/i,\n]\n\n/**\n * Detect a transient Postgres connection / availability failure (pool exhaustion,\n * `max_connections` reached, DB restarting) via its SQLSTATE or a DB-specific\n * driver message. Gates retryable 503 responses so callers do not report a\n * temporary infrastructure blip as an auth failure (401) or an unexpected server\n * error (500). Scoped to unambiguous DB signals so generic socket errors from\n * non-DB calls are never misclassified.\n */\nexport function isTransientDbError(err: unknown): boolean {\n if (!err || typeof err !== 'object') {\n return false\n }\n const code = (err as { code?: string }).code\n if (typeof code === 'string' && TRANSIENT_CONNECTION_SQLSTATES.has(code)) {\n return true\n }\n const message = (err as { message?: string }).message\n if (typeof message === 'string' && TRANSIENT_DB_MESSAGE_PATTERNS.some((pattern) => pattern.test(message))) {\n return true\n }\n return false\n}\n\n/**\n * SQLSTATEs that end a lock transaction early but say nothing about the data it\n * would have written, so the work can be retried: lock_not_available (55P03,\n * raised by `DB_LOCK_TIMEOUT_MS`), query_canceled (57014, raised by the opt-in\n * `DB_STATEMENT_TIMEOUT_MS`) and idle_in_transaction_session_timeout (25P03).\n */\nconst TRANSIENT_LOCK_SQLSTATES = new Set(['55P03', '57014', '25P03'])\n\n/**\n * Driver messages for a connection that never arrived or was lost mid-transaction:\n * the pg-pool acquire timeout (`connectionTimeoutMillis`) and node-postgres's\n * error for a client whose connection already failed.\n */\nconst TRANSIENT_LOCK_MESSAGE_PATTERNS = [\n /timeout exceeded when trying to connect/i,\n /client has encountered a connection error and is not queryable/i,\n]\n\n/**\n * @internal Detect a transient failure of a short lock transaction: everything\n * `isTransientDbError` matches, plus lock, statement and idle-in-transaction\n * timeouts, the pg-pool acquire timeout and node-postgres's \"not queryable\"\n * error. Checks every layer of the driver-error wrapper chain (`cause` /\n * `previous`, see `pgErrorCandidates`). `isTransientDbError` keeps its narrower\n * scope because its callers answer 503 \"service unavailable\".\n */\nexport function isTransientLockDbError(err: unknown): boolean {\n return pgErrorCandidates(err).some((candidate) => {\n if (isTransientDbError(candidate)) return true\n if (typeof candidate.code === 'string' && TRANSIENT_LOCK_SQLSTATES.has(candidate.code)) return true\n const message = candidate.message\n return typeof message === 'string' && TRANSIENT_LOCK_MESSAGE_PATTERNS.some((pattern) => pattern.test(message))\n })\n}\n"],
5
- "mappings": "AAKO,SAAS,kBAAkB,KAAuB;AACvD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QAAQ,KAAK,OAAO,CAAC;AAAA,EAC/G,CAAC;AACH;",
4
+ "sourcesContent": ["const UNIQUE_VIOLATION_MESSAGE = /duplicate key value violates unique constraint/i\n\n/**\n * Detect a Postgres unique-constraint violation (SQLSTATE 23505) regardless of\n * the ORM/driver layer that surfaces it. Shared across modules so duplicate-insert\n * handling stays consistent platform-wide. Callers answer 409 on a match, so only\n * DB signals count: the SQLSTATE, MikroORM's exception name, or the exact\n * Postgres message for drivers that drop both \u2014 never an arbitrary error that\n * merely mentions a \"unique constraint\".\n */\nexport function isUniqueViolation(err: unknown): boolean {\n return pgErrorCandidates(err).some((candidate) => {\n if (candidate.code === '23505') return true // Postgres unique_violation\n if (candidate.name === 'UniqueConstraintViolationException') return true\n return typeof candidate.message === 'string' && UNIQUE_VIOLATION_MESSAGE.test(candidate.message)\n })\n}\n\nconst FOREIGN_KEY_VIOLATION_MESSAGE = /violates foreign key constraint(?: \"([^\"]+)\")?/i\n\nconst MAX_ERROR_CHAIN_DEPTH = 4\n\n/**\n * MikroORM wraps driver errors and copies the pg fields onto the wrapper, but\n * the original error may also sit behind `cause` (Node) or `previous`\n * (MikroORM), possibly re-wrapped by a transaction helper. Walk that chain,\n * breadth-first with a small depth cap, so a check works on any layer.\n */\nfunction pgErrorCandidates(err: unknown): Array<Record<string, unknown>> {\n const found: Array<Record<string, unknown>> = []\n const seen = new Set<unknown>()\n let layer: unknown[] = [err]\n for (let depth = 0; depth < MAX_ERROR_CHAIN_DEPTH && layer.length > 0; depth += 1) {\n const next: unknown[] = []\n for (const candidate of layer) {\n if (!candidate || typeof candidate !== 'object' || seen.has(candidate)) continue\n seen.add(candidate)\n const record = candidate as Record<string, unknown>\n found.push(record)\n next.push(record.cause, record.previous)\n }\n layer = next\n }\n return found\n}\n\n/**\n * Detect a Postgres foreign-key violation (SQLSTATE 23503): the row is still\n * referenced by a dependent table, or the payload references a parent that\n * does not exist. Looks through MikroORM's driver-error wrapping.\n */\nexport function isForeignKeyViolation(err: unknown): boolean {\n return pgErrorCandidates(err).some((candidate) => {\n if (candidate.code === '23503') return true // Postgres foreign_key_violation\n return typeof candidate.message === 'string' && FOREIGN_KEY_VIOLATION_MESSAGE.test(candidate.message)\n })\n}\n\n/**\n * Name of the constraint behind a foreign-key violation, read from the pg\n * `constraint` field on any layer of the wrapper chain, or parsed out of the\n * quoted constraint in the driver message when the field is missing.\n */\nexport function getForeignKeyViolationConstraint(err: unknown): string | null {\n for (const candidate of pgErrorCandidates(err)) {\n if (typeof candidate.constraint === 'string' && candidate.constraint.length > 0) return candidate.constraint\n }\n for (const candidate of pgErrorCandidates(err)) {\n if (typeof candidate.message !== 'string') continue\n const match = FOREIGN_KEY_VIOLATION_MESSAGE.exec(candidate.message)\n if (match?.[1]) return match[1]\n }\n return null\n}\n\n/**\n * A Postgres SQLSTATE is always exactly 5 characters from `[0-9A-Z]`, and every\n * class in the standard SQLSTATE table carries at least one digit. Node system\n * errors (`ECONNREFUSED`), Node internal errors (`ERR_INVALID_ARG_TYPE`), and the\n * five-letter Node errno codes (`EPIPE`, `EPERM`, `EBUSY`) would otherwise be\n * misread as a SQLSTATE, since they also populate a string `code` field; the\n * digit requirement rules those out without excluding any real SQLSTATE.\n */\nconst SQLSTATE_PATTERN = /^(?=.*[0-9])[0-9A-Z]{5}$/\n\n/**\n * The Postgres SQLSTATE behind an error, read from the pg `code` field on any\n * layer of the driver-error wrapper chain (see `pgErrorCandidates`). Returns\n * `null` when no layer carries a `code` matching the SQLSTATE shape, which\n * also covers non-Postgres errors whose `code` is a Node error code.\n */\nexport function readPgSqlState(err: unknown): string | null {\n for (const candidate of pgErrorCandidates(err)) {\n if (typeof candidate.code === 'string' && SQLSTATE_PATTERN.test(candidate.code)) return candidate.code\n }\n return null\n}\n\n/**\n * Postgres SQLSTATEs for transient connection / availability failures \u2014 the\n * database (or its connection pool) is temporarily unreachable and the request\n * can succeed on retry. Deliberately scoped to connection/availability codes;\n * query-level conflicts (deadlock 40P01, serialization 40001, lock_not_available\n * 55P03) are NOT included because they do not mean \"service unavailable\".\n */\nconst TRANSIENT_CONNECTION_SQLSTATES = new Set([\n '53300', // too_many_connections\n '53400', // configuration_limit_exceeded\n '57P01', // admin_shutdown\n '57P02', // crash_shutdown\n '57P03', // cannot_connect_now (db starting up)\n '08000', // connection_exception\n '08001', // sqlclient_unable_to_establish_sqlconnection\n '08003', // connection_does_not_exist\n '08006', // connection_failure\n])\n\n/**\n * Postgres-driver / connection-pool messages that describe a transient DB\n * connection failure when the SQLSTATE is dropped by the ORM wrapper. These are\n * intentionally DB-specific phrases only. Bare socket codes (ECONNREFUSED,\n * ETIMEDOUT, \u2026) are deliberately NOT matched: they can originate from any\n * outbound socket (HTTP, cache, queue), so keying off them would falsely\n * attribute unrelated failures to the database.\n */\nconst TRANSIENT_DB_MESSAGE_PATTERNS = [\n /too many clients already/i,\n /unable to acquire a connection/i,\n /timeout acquiring a connection/i,\n /connection terminated/i,\n /the database system is (starting up|shutting down|in recovery)/i,\n]\n\n/**\n * Detect a transient Postgres connection / availability failure (pool exhaustion,\n * `max_connections` reached, DB restarting) via its SQLSTATE or a DB-specific\n * driver message. Gates retryable 503 responses so callers do not report a\n * temporary infrastructure blip as an auth failure (401) or an unexpected server\n * error (500). Scoped to unambiguous DB signals so generic socket errors from\n * non-DB calls are never misclassified.\n */\nexport function isTransientDbError(err: unknown): boolean {\n if (!err || typeof err !== 'object') {\n return false\n }\n const code = (err as { code?: string }).code\n if (typeof code === 'string' && TRANSIENT_CONNECTION_SQLSTATES.has(code)) {\n return true\n }\n const message = (err as { message?: string }).message\n if (typeof message === 'string' && TRANSIENT_DB_MESSAGE_PATTERNS.some((pattern) => pattern.test(message))) {\n return true\n }\n return false\n}\n\n/**\n * SQLSTATEs that end a lock transaction early but say nothing about the data it\n * would have written, so the work can be retried: lock_not_available (55P03,\n * raised by `DB_LOCK_TIMEOUT_MS`), query_canceled (57014, raised by the opt-in\n * `DB_STATEMENT_TIMEOUT_MS`) and idle_in_transaction_session_timeout (25P03).\n */\nconst TRANSIENT_LOCK_SQLSTATES = new Set(['55P03', '57014', '25P03'])\n\n/**\n * Driver messages for a connection that never arrived or was lost mid-transaction:\n * the pg-pool acquire timeout (`connectionTimeoutMillis`) and node-postgres's\n * error for a client whose connection already failed.\n */\nconst TRANSIENT_LOCK_MESSAGE_PATTERNS = [\n /timeout exceeded when trying to connect/i,\n /client has encountered a connection error and is not queryable/i,\n]\n\n/**\n * @internal Detect a transient failure of a short lock transaction: everything\n * `isTransientDbError` matches, plus lock, statement and idle-in-transaction\n * timeouts, the pg-pool acquire timeout and node-postgres's \"not queryable\"\n * error. Checks every layer of the driver-error wrapper chain (`cause` /\n * `previous`, see `pgErrorCandidates`). `isTransientDbError` keeps its narrower\n * scope because its callers answer 503 \"service unavailable\".\n */\nexport function isTransientLockDbError(err: unknown): boolean {\n return pgErrorCandidates(err).some((candidate) => {\n if (isTransientDbError(candidate)) return true\n if (typeof candidate.code === 'string' && TRANSIENT_LOCK_SQLSTATES.has(candidate.code)) return true\n const message = candidate.message\n return typeof message === 'string' && TRANSIENT_LOCK_MESSAGE_PATTERNS.some((pattern) => pattern.test(message))\n })\n}\n"],
5
+ "mappings": "AAAA,MAAM,2BAA2B;AAU1B,SAAS,kBAAkB,KAAuB;AACvD,SAAO,kBAAkB,GAAG,EAAE,KAAK,CAAC,cAAc;AAChD,QAAI,UAAU,SAAS,QAAS,QAAO;AACvC,QAAI,UAAU,SAAS,qCAAsC,QAAO;AACpE,WAAO,OAAO,UAAU,YAAY,YAAY,yBAAyB,KAAK,UAAU,OAAO;AAAA,EACjG,CAAC;AACH;AAEA,MAAM,gCAAgC;AAEtC,MAAM,wBAAwB;AAQ9B,SAAS,kBAAkB,KAA8C;AACvE,QAAM,QAAwC,CAAC;AAC/C,QAAM,OAAO,oBAAI,IAAa;AAC9B,MAAI,QAAmB,CAAC,GAAG;AAC3B,WAAS,QAAQ,GAAG,QAAQ,yBAAyB,MAAM,SAAS,GAAG,SAAS,GAAG;AACjF,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gC;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAUO,SAAS,mBAAmB,KAAuB;AACxD,MAAI,CAAC,OAAO,OAAO,QAAQ,UAAU;AACnC,WAAO;AAAA,EACT;AACA,QAAM,OAAQ,IAA0B;AACxC,MAAI,OAAO,SAAS,YAAY,+BAA+B,IAAI,IAAI,GAAG;AACxE,WAAO;AAAA,EACT;AACA,QAAM,UAAW,IAA6B;AAC9C,MAAI,OAAO,YAAY,YAAY,8BAA8B,KAAK,CAAC,YAAY,QAAQ,KAAK,OAAO,CAAC,GAAG;AACzG,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAQA,MAAM,2BAA2B,oBAAI,IAAI,CAAC,SAAS,SAAS,OAAO,CAAC;AAOpE,MAAM,kCAAkC;AAAA,EACtC;AAAA,EACA;AACF;AAUO,SAAS,uBAAuB,KAAuB;AAC5D,SAAO,kBAAkB,GAAG,EAAE,KAAK,CAAC,cAAc;AAChD,QAAI,mBAAmB,SAAS,EAAG,QAAO;AAC1C,QAAI,OAAO,UAAU,SAAS,YAAY,yBAAyB,IAAI,UAAU,IAAI,EAAG,QAAO;AAC/F,UAAM,UAAU,UAAU;AAC1B,WAAO,OAAO,YAAY,YAAY,gCAAgC,KAAK,CAAC,YAAY,QAAQ,KAAK,OAAO,CAAC;AAAA,EAC/G,CAAC;AACH;",
6
6
  "names": []
7
7
  }
@@ -1,4 +1,4 @@
1
- const APP_VERSION = "0.10.1-develop.8165.1.3de4ce96a8";
1
+ const APP_VERSION = "0.10.1-develop.8180.1.c6789f43f3";
2
2
  const appVersion = APP_VERSION;
3
3
  export {
4
4
  APP_VERSION,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/version.ts"],
4
- "sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.10.1-develop.8165.1.3de4ce96a8';\nexport const appVersion = APP_VERSION;\n"],
4
+ "sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.10.1-develop.8180.1.c6789f43f3';\nexport const appVersion = APP_VERSION;\n"],
5
5
  "mappings": "AACO,MAAM,cAAc;AACpB,MAAM,aAAa;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/shared",
3
- "version": "0.10.1-develop.8165.1.3de4ce96a8",
3
+ "version": "0.10.1-develop.8180.1.c6789f43f3",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -130,7 +130,7 @@
130
130
  "@mikro-orm/core": "^7.1.14",
131
131
  "@mikro-orm/decorators": "^7.1.14",
132
132
  "@mikro-orm/postgresql": "^7.1.14",
133
- "@open-mercato/cache": "0.10.1-develop.8165.1.3de4ce96a8",
133
+ "@open-mercato/cache": "0.10.1-develop.8180.1.c6789f43f3",
134
134
  "@types/html-to-text": "^9.0.4",
135
135
  "@types/sanitize-html": "^2.16.1",
136
136
  "dotenv": "^17.4.2",
@@ -114,6 +114,33 @@ describe('isTransientLockDbError', () => {
114
114
  })
115
115
  })
116
116
 
117
+ describe('isUniqueViolation', () => {
118
+ it('matches the 23505 SQLSTATE and the MikroORM exception name', () => {
119
+ expect(isUniqueViolation({ code: '23505' })).toBe(true)
120
+ expect(isUniqueViolation({ name: 'UniqueConstraintViolationException', message: 'insert failed' })).toBe(true)
121
+ })
122
+
123
+ it('matches a violation wrapped behind cause or previous', () => {
124
+ expect(isUniqueViolation(new Error('flush failed', { cause: { code: '23505' } }))).toBe(true)
125
+ expect(isUniqueViolation({ message: 'transaction failed', previous: { name: 'UniqueConstraintViolationException' } })).toBe(true)
126
+ })
127
+
128
+ it('falls back to the exact Postgres message when the driver drops the code', () => {
129
+ expect(isUniqueViolation(new Error('duplicate key value violates unique constraint "rules_rule_id_unique"'))).toBe(true)
130
+ })
131
+
132
+ it('is false for a non-DB error that only mentions a unique constraint', () => {
133
+ expect(isUniqueViolation(new Error('Field "slug" has no unique constraint configured'))).toBe(false)
134
+ expect(isUniqueViolation(new Error('duplicate key value in payload'))).toBe(false)
135
+ })
136
+
137
+ it('is false for other SQLSTATEs and non-objects', () => {
138
+ expect(isUniqueViolation({ code: '23503', message: 'violates foreign key constraint' })).toBe(false)
139
+ expect(isUniqueViolation('duplicate key value violates unique constraint')).toBe(false)
140
+ expect(isUniqueViolation(null)).toBe(false)
141
+ })
142
+ })
143
+
117
144
  describe('isForeignKeyViolation', () => {
118
145
  it('is true for the foreign_key_violation SQLSTATE', () => {
119
146
  expect(isForeignKeyViolation({ code: '23503' })).toBe(true)
@@ -1,14 +1,19 @@
1
+ const UNIQUE_VIOLATION_MESSAGE = /duplicate key value violates unique constraint/i
2
+
1
3
  /**
2
4
  * Detect a Postgres unique-constraint violation (SQLSTATE 23505) regardless of
3
5
  * the ORM/driver layer that surfaces it. Shared across modules so duplicate-insert
4
- * handling stays consistent platform-wide.
6
+ * handling stays consistent platform-wide. Callers answer 409 on a match, so only
7
+ * DB signals count: the SQLSTATE, MikroORM's exception name, or the exact
8
+ * Postgres message for drivers that drop both — never an arbitrary error that
9
+ * merely mentions a "unique constraint".
5
10
  */
6
11
  export function isUniqueViolation(err: unknown): boolean {
7
- if (!err || typeof err !== 'object') return false
8
- const code = (err as { code?: string }).code
9
- if (code === '23505') return true // Postgres unique_violation
10
- const message = (err as { message?: string }).message
11
- return typeof message === 'string' && /duplicate key value|unique constraint/i.test(message)
12
+ return pgErrorCandidates(err).some((candidate) => {
13
+ if (candidate.code === '23505') return true // Postgres unique_violation
14
+ if (candidate.name === 'UniqueConstraintViolationException') return true
15
+ return typeof candidate.message === 'string' && UNIQUE_VIOLATION_MESSAGE.test(candidate.message)
16
+ })
12
17
  }
13
18
 
14
19
  const FOREIGN_KEY_VIOLATION_MESSAGE = /violates foreign key constraint(?: "([^"]+)")?/i
@@ -0,0 +1,97 @@
1
+ // Compile-time-only guard for the code-definition types (#7183). Never imported at
2
+ // runtime: `yarn typecheck` (`tsc --noEmit`) is the only gate that can catch a
3
+ // regression here, because this repo's Jest transform runs with
4
+ // `isolatedModules: true` and therefore skips type diagnostics.
5
+ //
6
+ // It sits outside `__tests__` because `packages/shared/tsconfig.json` excludes that
7
+ // directory from `tsc --noEmit`, and it is a `.tsx` for the same mutation-gate reason
8
+ // as `lib/i18n/config.typecheck.tsx`.
9
+ //
10
+ // What it protects: every step type and every `userTaskConfig` key the workflows
11
+ // engine validates must compile in `defineWorkflow` without a cast. The engine side
12
+ // of the contract (drift against `userTaskConfigSchema` / `workflowStepTypeSchema`)
13
+ // is guarded in `packages/core/src/modules/workflows/data/code-definition-types.typecheck.tsx`.
14
+ import { defineWorkflow } from './builder'
15
+ import type { CodeStepDefinition, WorkflowStepType } from './types'
16
+
17
+ type UserTaskConfig = NonNullable<CodeStepDefinition['userTaskConfig']>
18
+
19
+ // 1. Every engine-supported user-task key, in one USER_TASK step, plus the
20
+ // condition-wait and branching step types, compiles in the builder.
21
+ const everyEngineFeature = defineWorkflow({
22
+ workflowId: 'shared.typecheck-engine-parity',
23
+ workflowName: 'Engine parity',
24
+ steps: [
25
+ { stepId: 'start', stepName: 'Start', stepType: 'START' },
26
+ {
27
+ stepId: 'review',
28
+ stepName: 'Review',
29
+ stepType: 'USER_TASK',
30
+ userTaskConfig: {
31
+ formSchema: { fields: [{ name: 'approved', type: 'boolean' }] },
32
+ assignedTo: 'user-1',
33
+ assignedToRoles: ['reviewer'],
34
+ assigneeKind: 'user',
35
+ formKey: 'sales.review',
36
+ allowedActions: ['complete', 'cancel'],
37
+ assignmentRule: 'rule-1',
38
+ slaDuration: 'P1D',
39
+ escalationRules: [{ trigger: 'sla_breach', action: 'notify', notifyUsers: ['user-2'] }],
40
+ instructions: { en: 'Review {{context.orderId}}', pl: 'Sprawdź {{context.orderId}}' },
41
+ entityBindings: [{ entityType: 'sales:order', idPath: 'context.orderId', label: 'Order' }],
42
+ priority: 'high',
43
+ deadline: { duration: 'P2D' },
44
+ reminders: [{ offset: 'PT4H' }],
45
+ onBreach: { action: 'route', transitionId: 'review_to_end' },
46
+ decisions: [
47
+ { id: 'approve', label: 'Approve', transitionId: 'review_to_wait', style: 'primary' },
48
+ { id: 'reject', label: { en: 'Reject' }, transitionId: 'review_to_end', style: 'destructive' },
49
+ ],
50
+ editablePrefilled: ['approved'],
51
+ },
52
+ },
53
+ {
54
+ stepId: 'wait',
55
+ stepName: 'Wait for payment',
56
+ stepType: 'WAIT_FOR_CONDITION',
57
+ config: {
58
+ condition: { operator: 'AND', rules: [{ field: 'payment.status', operator: '==', value: 'captured' }] },
59
+ timeout: 'P1D',
60
+ onTimeout: 'FAIL',
61
+ },
62
+ },
63
+ { stepId: 'branch', stepName: 'Branch', stepType: 'IF_ELSE' },
64
+ { stepId: 'route', stepName: 'Route', stepType: 'SWITCH' },
65
+ { stepId: 'end', stepName: 'End', stepType: 'END' },
66
+ ] as const,
67
+ transitions: [
68
+ { transitionId: 'start_to_review', fromStepId: 'start', toStepId: 'review', trigger: 'auto' },
69
+ { transitionId: 'review_to_wait', fromStepId: 'review', toStepId: 'wait', trigger: 'manual' },
70
+ { transitionId: 'review_to_end', fromStepId: 'review', toStepId: 'end', trigger: 'manual' },
71
+ { transitionId: 'wait_to_end', fromStepId: 'wait', toStepId: 'end', trigger: 'auto' },
72
+ ],
73
+ })
74
+
75
+ // 2. The new step types are members of the exported union.
76
+ const newStepTypes: WorkflowStepType[] = ['WAIT_FOR_CONDITION', 'IF_ELSE', 'SWITCH']
77
+
78
+ // 3. Pre-existing keys keep their original (wide) types — nothing was narrowed.
79
+ type MutuallyAssignable<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false
80
+ const formSchemaStaysWide: MutuallyAssignable<UserTaskConfig['formSchema'], Record<string, unknown> | undefined> = true
81
+ const assignedToStaysWide: MutuallyAssignable<UserTaskConfig['assignedTo'], string | string[] | undefined> = true
82
+
83
+ // 4. The new keys are still checked, not `unknown`.
84
+ // @ts-expect-error 'urgent' is not an engine priority
85
+ const badPriority: UserTaskConfig = { priority: 'urgent' }
86
+ // @ts-expect-error a decision must name the transition it routes to
87
+ const decisionWithoutRoute: UserTaskConfig = { decisions: [{ id: 'approve', label: 'Approve' }] }
88
+ // @ts-expect-error 'WAIT_FOR_EVENT' is not an engine step type
89
+ const unknownStepType: WorkflowStepType = 'WAIT_FOR_EVENT'
90
+
91
+ void everyEngineFeature
92
+ void newStepTypes
93
+ void formSchemaStaysWide
94
+ void assignedToStaysWide
95
+ void badPriority
96
+ void decisionWithoutRoute
97
+ void unknownStepType
@@ -4,6 +4,12 @@
4
4
  * These types are used by the builder API, generator extension, and in-memory registry.
5
5
  * They mirror the JSONB shape stored in workflow_definitions.definition but add
6
6
  * generic type safety for step ID references in transitions.
7
+ *
8
+ * The engine's zod schemas (`@open-mercato/core/modules/workflows/data/validators`)
9
+ * are the source of truth. This package cannot import them, so the step-type union
10
+ * and `userTaskConfig` are mirrored by hand and guarded against drift by
11
+ * `code-definition-types.typecheck.tsx` and `code-definition-types-parity.test.ts`
12
+ * in the core workflows module.
7
13
  */
8
14
 
9
15
  // ============================================================================
@@ -20,6 +26,9 @@ export type WorkflowStepType =
20
26
  | 'SUB_WORKFLOW'
21
27
  | 'WAIT_FOR_SIGNAL'
22
28
  | 'WAIT_FOR_TIMER'
29
+ | 'WAIT_FOR_CONDITION'
30
+ | 'IF_ELSE'
31
+ | 'SWITCH'
23
32
 
24
33
  export type TransitionTrigger = 'auto' | 'manual' | 'signal' | 'timer'
25
34
 
@@ -76,6 +85,35 @@ export interface CodeStepDefinition<TStepId extends string = string> {
76
85
  escalateTo?: string
77
86
  notifyUsers?: string[]
78
87
  }>
88
+ assignedToRoles?: string[]
89
+ assigneeKind?: 'user' | 'customer'
90
+ formKey?: string
91
+ allowedActions?: string[]
92
+ instructions?: string | Record<string, string>
93
+ entityBindings?: Array<{
94
+ entityType: string
95
+ idPath: string
96
+ label?: string | Record<string, string>
97
+ }>
98
+ priority?: 'low' | 'medium' | 'high' | 'extreme'
99
+ deadline?: {
100
+ duration: string
101
+ }
102
+ reminders?: Array<{
103
+ offset: string
104
+ }>
105
+ onBreach?: {
106
+ action: 'notify' | 'reassign' | 'route'
107
+ reassignTo?: string
108
+ transitionId?: string
109
+ }
110
+ decisions?: Array<{
111
+ id: string
112
+ label: string | Record<string, string>
113
+ transitionId: string
114
+ style?: 'primary' | 'secondary' | 'destructive'
115
+ }>
116
+ editablePrefilled?: string[]
79
117
  }
80
118
  subWorkflowConfig?: {
81
119
  subWorkflowId: string