@cullet/erp-core 1.0.9 → 1.0.11
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/dist/index.d.ts +123 -2
- package/dist/index.js +103 -1
- package/dist/index.js.map +1 -1
- package/dist/policy-service.d.ts +99 -0
- package/dist/policy-service.js +73 -0
- package/dist/policy-service.js.map +1 -1
- package/dist/validation-code.js +33 -0
- package/dist/validation-code.js.map +1 -1
- package/dist/validation-error.d.ts +202 -0
- package/dist/validation-error.js +164 -0
- package/dist/validation-error.js.map +1 -1
- package/meta.json +12 -8
- package/package.json +1 -1
- package/src/core/domain/entity.ts +71 -0
- package/src/core/domain/value-object.ts +51 -0
- package/src/core/errors/app-error.ts +33 -0
- package/src/core/errors/authorization-error.ts +43 -0
- package/src/core/errors/conflict-error.ts +69 -0
- package/src/core/errors/integration-error.ts +25 -0
- package/src/core/errors/not-found-error.ts +14 -0
- package/src/core/errors/validation-error.ts +18 -0
- package/src/core/policies/catalog/policy-catalog.ts +36 -0
- package/src/core/policies/resolver/policy-resolver.ts +10 -0
- package/src/core/policies/service/policy-service.ts +53 -0
- package/src/version.ts +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation-code.js","names":[],"sources":["../src/core/errors/error-codes.ts","../src/core/errors/utils/json-safe.ts","../src/core/errors/app-error.ts","../src/core/shared/hashing.ts","../src/core/errors/unexpected-error.ts","../src/core/exceptions/validation-code.ts"],"sourcesContent":["const ErrorCodes = {\n authentication: {\n missingToken: \"sec.authn.missing_token\",\n invalidToken: \"sec.authn.invalid_token\",\n expiredToken: \"sec.authn.expired_token\",\n invalidCredentials: \"sec.authn.invalid_credentials\",\n },\n authorization: {\n forbidden: \"sec.authz.forbidden\",\n policyDenied: \"sec.authz.policy_denied\",\n missingCapability: \"sec.authz.missing_capability\",\n outOfScope: \"sec.authz.out_of_scope\",\n },\n businessRuleViolation: \"business_rule_violation\",\n conflict: {\n alreadyExists: \"conf.already_exists\",\n duplicate: \"conf.duplicate\",\n uniqueViolation: \"conf.unique_violation\",\n },\n idempotency: {\n keyMissing: \"idemp.key_missing\",\n inProgress: \"idemp.in_progress\",\n payloadMismatch: \"idemp.payload_mismatch\",\n replayNotSupported: \"idemp.replay_not_supported\",\n },\n integration: {\n timeout: \"int.timeout\",\n unreachable: \"int.unreachable\",\n badResponse: \"int.bad_response\",\n },\n legacyIncompatible: \"legacy_incompatible\",\n notFound: \"not_found\",\n serialization: {\n deserializePrefix: \"ser.des\",\n serializePrefix: \"ser.ser\",\n },\n temporal: {\n expired: \"tmp.expired\",\n notYetValid: \"tmp.not_yet_valid\",\n },\n unexpected: \"unexpected\",\n validation: \"validation_error\",\n} as const;\n\ntype SerializationCodeDirection = \"deserialize\" | \"serialize\";\n\nfunction serializationErrorCode(\n direction: SerializationCodeDirection,\n category: string,\n): string {\n const prefix =\n direction === \"deserialize\"\n ? ErrorCodes.serialization.deserializePrefix\n : ErrorCodes.serialization.serializePrefix;\n\n return `${prefix}.${category}`;\n}\n\nexport { ErrorCodes, serializationErrorCode };\nexport type { SerializationCodeDirection };\n","// Utilities for ensuring metadata is JSON-serializable.\n\nimport type { JsonSafeRecord, JsonSafeValue } from \"../types.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Constants\n// ─────────────────────────────────────────────────────────────────────────────\n\nconst NON_SERIALIZABLE_PLACEHOLDER = \"[NonSerializable]\";\nconst CIRCULAR_REFERENCE_PLACEHOLDER = \"[Circular]\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Internal helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n// `seen` tracks the ancestors on the current traversal branch (a DFS path), not\n// every object visited. This collapses true circular references to a placeholder\n// while still serializing the same object referenced more than once across\n// sibling branches (a DAG) — matching `JSON.stringify`, which only rejects\n// cycles, not shared references.\nfunction sanitizeValue(value: unknown, seen: WeakSet<object>): JsonSafeValue {\n // Null passthrough\n if (value === null) return null;\n\n const type = typeof value;\n\n // Primitives\n if (type === \"string\" || type === \"number\" || type === \"boolean\") {\n return value as JsonSafeValue;\n }\n\n // Non-serializable primitives\n if (\n type === \"bigint\" ||\n type === \"function\" ||\n type === \"symbol\" ||\n value === undefined\n ) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Arrays (recursive)\n if (Array.isArray(value)) {\n if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;\n seen.add(value);\n const sanitized = value.map((item) => sanitizeValue(item, seen));\n seen.delete(value);\n return sanitized;\n }\n\n // Date → placeholder (could also use .toISOString() if preferred)\n if (value instanceof Date) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Class instances and non-plain objects → placeholder\n if (!isPlainObject(value)) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Plain object (recursive)\n if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;\n seen.add(value);\n const result: Record<string, JsonSafeValue> = {};\n for (const [key, val] of Object.entries(value)) {\n result[key] = sanitizeValue(val, seen);\n }\n seen.delete(value);\n return result;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Public API\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Ensures metadata is JSON-serializable.\n *\n * **Allowed:** string, number, boolean, null, arrays, and plain objects.\n *\n * **Converted to placeholder:** Date, BigInt, class instances, functions,\n * symbols, undefined, and circular references (which would otherwise make\n * `JSON.stringify` throw).\n *\n * @throws {TypeError} If `input` is not a plain object at the root level.\n */\nfunction assertJsonSafeMetadata(input: unknown): JsonSafeRecord {\n if (input === undefined) {\n return {};\n }\n\n if (!isPlainObject(input)) {\n throw new TypeError(\n \"metadata must be a plain object (Record<string, unknown>).\",\n );\n }\n\n return sanitizeValue(input, new WeakSet<object>()) as JsonSafeRecord;\n}\n\nexport {\n assertJsonSafeMetadata,\n CIRCULAR_REFERENCE_PLACEHOLDER,\n NON_SERIALIZABLE_PLACEHOLDER,\n};\n","// Base application error for the domain/application layer.\n// Encapsulates a code, optional cause, and JSON-safe metadata.\n\nimport type {\n AppErrorOptions,\n ErrorSeverity,\n JsonSafeRecord,\n} from \"./types.js\";\nimport { assertJsonSafeMetadata } from \"./utils/index.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// AppError (abstract base class)\n// ─────────────────────────────────────────────────────────────────────────────\n\nabstract class AppError extends Error {\n public readonly code: string;\n public readonly cause?: unknown;\n public readonly metadata?: JsonSafeRecord;\n public readonly type?: string;\n public readonly severity?: ErrorSeverity;\n public readonly createdAtIso: string;\n public readonly publicMessage?: string;\n /**\n * Identifies a single execution \"story\" in the system. All operations\n * related to the same logical flow must share the same correlationId.\n */\n public readonly correlationId?: string;\n /**\n * Identifies a specific technical request attempt (each retry may produce\n * a new requestId), even when the correlationId stays the same.\n */\n public readonly requestId?: string;\n /**\n * Marks the business intent / idempotency key; stays the same across\n * technical retries and multiple requests that represent the same intent.\n */\n public readonly commandId?: string;\n\n protected constructor(\n message: string,\n code: string,\n options?: AppErrorOptions,\n ) {\n super(message);\n\n this.name = new.target.name;\n this.code = code;\n this.cause = options?.cause;\n this.type = options?.type;\n this.severity = options?.severity;\n this.correlationId = options?.correlationId;\n this.requestId = options?.requestId;\n this.commandId = options?.commandId;\n this.createdAtIso = options?.createdAtIso ?? new Date().toISOString();\n this.publicMessage = options?.publicMessage;\n\n this.metadata = options?.metadata\n ? assertJsonSafeMetadata(options.metadata)\n : undefined;\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n /**\n * Returns a JSON-safe representation of the error.\n * Does NOT include `cause` by default (to avoid leaking internal details).\n */\n public toJSON(): Record<string, unknown> {\n const payload: Record<string, unknown> = {\n name: this.name,\n code: this.code,\n message: this.message,\n createdAtIso: this.createdAtIso,\n };\n\n // Optional fields are emitted only when defined, so the serialized\n // shape never carries `undefined`-valued keys (consistent with how the\n // correlation/request/command ids are handled).\n if (this.type !== undefined) payload.type = this.type;\n if (this.severity !== undefined) payload.severity = this.severity;\n if (this.publicMessage !== undefined)\n payload.publicMessage = this.publicMessage;\n if (this.metadata !== undefined) payload.metadata = this.metadata;\n if (this.correlationId !== undefined)\n payload.correlationId = this.correlationId;\n if (this.requestId !== undefined) payload.requestId = this.requestId;\n if (this.commandId !== undefined) payload.commandId = this.commandId;\n\n return payload;\n }\n}\n\nexport { AppError };\n","import { createHash } from \"node:crypto\";\n\nconst CIRCULAR_STRUCTURE_MESSAGE =\n \"Cannot stably stringify a circular structure\";\n\nfunction sha256Hex(value: string): string {\n return createHash(\"sha256\").update(value, \"utf8\").digest(\"hex\");\n}\n\n// `seen` holds the current traversal branch so true cycles are rejected while\n// repeated (acyclic) references are still serialized — matching JSON.stringify.\nfunction sortKeysDeep(value: unknown, seen: WeakSet<object>): unknown {\n if (Array.isArray(value)) {\n if (seen.has(value)) {\n throw new TypeError(CIRCULAR_STRUCTURE_MESSAGE);\n }\n seen.add(value);\n const mapped = value.map((item) => sortKeysDeep(item, seen));\n seen.delete(value);\n return mapped;\n }\n\n if (value instanceof Date) {\n return value;\n }\n\n if (value && typeof value === \"object\") {\n if (seen.has(value)) {\n throw new TypeError(CIRCULAR_STRUCTURE_MESSAGE);\n }\n seen.add(value);\n const record = value as Record<string, unknown>;\n const ordered = Object.create(null) as Record<string, unknown>;\n\n for (const key of Object.keys(record).sort()) {\n ordered[key] = sortKeysDeep(record[key], seen);\n }\n seen.delete(value);\n\n return ordered;\n }\n\n return value;\n}\n\n/**\n * Deterministic JSON string with object keys sorted recursively, so key order\n * does not affect the output.\n *\n * Follows `JSON.stringify` semantics for the values it serializes: `undefined`,\n * functions and symbols are dropped, non-finite numbers become `null`, `bigint`\n * throws, and `Map`/`Set` serialize as `{}`. Distinct payloads can therefore\n * collapse to the same string — for collision-resistant hashing use\n * `PolicyHashing.canonicalJson` (policies/utils), which rejects those values\n * up front.\n *\n * @throws {TypeError} On circular references (mirroring `JSON.stringify`).\n */\nfunction stableStringify(value: unknown): string {\n return JSON.stringify(sortKeysDeep(value, new WeakSet<object>()));\n}\n\nfunction payloadHash(value: unknown): string {\n return sha256Hex(stableStringify(value));\n}\n\nexport { payloadHash, sha256Hex, stableStringify };\n","import { AppError } from \"./app-error.js\";\nimport { ErrorCodes } from \"./error-codes.js\";\nimport type { AppErrorOptions } from \"./types.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// UnexpectedError\n// ─────────────────────────────────────────────────────────────────────────────\n\nclass UnexpectedError extends AppError {\n constructor(\n message = \"Unexpected error\",\n cause?: unknown,\n options?: Omit<AppErrorOptions, \"cause\">,\n ) {\n super(message, ErrorCodes.unexpected, {\n cause,\n ...options,\n });\n }\n}\n\nexport { UnexpectedError };\n","// Object-oriented representation of validation codes (similar to Kotlin inline class).\n// Provides common reusable codes while allowing custom codes via `of`.\n\nclass ValidationCode {\n public readonly value: string;\n\n private constructor(value: string) {\n this.value = value;\n }\n\n // Factory for custom codes\n public static of(value: string): ValidationCode {\n return new ValidationCode(value);\n }\n\n // Common, domain-friendly codes\n public static readonly BLANK = new ValidationCode(\"blank\");\n public static readonly REQUIRED = new ValidationCode(\"required\");\n public static readonly INVALID_FORMAT = new ValidationCode(\n \"invalid_format\",\n );\n public static readonly INVALID_CHARACTERS = new ValidationCode(\n \"invalid_characters\",\n );\n public static readonly INVALID_LENGTH = new ValidationCode(\n \"invalid_length\",\n );\n public static readonly TOO_SHORT = new ValidationCode(\"too_short\");\n public static readonly TOO_LONG = new ValidationCode(\"too_long\");\n public static readonly OUT_OF_RANGE = new ValidationCode(\"out_of_range\");\n public static readonly INVALID_CHECKSUM = new ValidationCode(\n \"invalid_checksum\",\n );\n public static readonly INVALID_CHECKING_DIGIT = new ValidationCode(\n \"invalid_checking_digit\",\n );\n public static readonly ALREADY_EXISTS = new ValidationCode(\n \"already_exists\",\n );\n public static readonly NOT_FOUND = new ValidationCode(\"not_found\");\n public static readonly NOT_ALLOWED = new ValidationCode(\"not_allowed\");\n public static readonly UNEXPECTED = new ValidationCode(\"unexpected\");\n}\n\nexport { ValidationCode };\n"],"mappings":";;AAAA,MAAM,aAAa;CACf,gBAAgB;EACZ,cAAc;EACd,cAAc;EACd,cAAc;EACd,oBAAoB;CACxB;CACA,eAAe;EACX,WAAW;EACX,cAAc;EACd,mBAAmB;EACnB,YAAY;CAChB;CACA,uBAAuB;CACvB,UAAU;EACN,eAAe;EACf,WAAW;EACX,iBAAiB;CACrB;CACA,aAAa;EACT,YAAY;EACZ,YAAY;EACZ,iBAAiB;EACjB,oBAAoB;CACxB;CACA,aAAa;EACT,SAAS;EACT,aAAa;EACb,aAAa;CACjB;CACA,oBAAoB;CACpB,UAAU;CACV,eAAe;EACX,mBAAmB;EACnB,iBAAiB;CACrB;CACA,UAAU;EACN,SAAS;EACT,aAAa;CACjB;CACA,YAAY;CACZ,YAAY;AAChB;AAIA,SAAS,uBACL,WACA,UACM;CAMN,OAAO,GAJH,cAAc,gBACR,WAAW,cAAc,oBACzB,WAAW,cAAc,gBAElB,GAAG;AACxB;;;AChDA,MAAM,+BAA+B;AACrC,MAAM,iCAAiC;AAMvC,SAAS,cAAc,OAAkD;CACrE,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,MAAM,QAAQ,OAAO,eAAe,KAAK;CACzC,OAAO,UAAU,OAAO,aAAa,UAAU;AACnD;AAOA,SAAS,cAAc,OAAgB,MAAsC;CAEzE,IAAI,UAAU,MAAM,OAAO;CAE3B,MAAM,OAAO,OAAO;CAGpB,IAAI,SAAS,YAAY,SAAS,YAAY,SAAS,WACnD,OAAO;CAIX,IACI,SAAS,YACT,SAAS,cACT,SAAS,YACT,UAAU,KAAA,GAEV,OAAO;CAIX,IAAI,MAAM,QAAQ,KAAK,GAAG;EACtB,IAAI,KAAK,IAAI,KAAK,GAAG,OAAO;EAC5B,KAAK,IAAI,KAAK;EACd,MAAM,YAAY,MAAM,KAA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CACzC,OAAO,UAAU,gBAAgB,KAAK,CAAC;AAC3C;;;ACxDA,IAAM,kBAAN,cAA8B,SAAS;CACnC,YACI,UAAU,oBACV,OACA,SACF;EACE,MAAM,SAAS,WAAW,YAAY;GAClC;GACA,GAAG;EACP,CAAC;CACL;AACJ;;;AChBA,IAAM,iBAAN,MAAM,eAAe;CAGjB,YAAoB,OAAe;EAC/B,KAAK,QAAQ;CACjB;CAGA,OAAc,GAAG,OAA+B;EAC5C,OAAO,IAAI,eAAe,KAAK;CACnC;;eAG+B,IAAI,eAAe,OAAO;;;kBACvB,IAAI,eAAe,UAAU;;;wBACvB,IAAI,eACxC,gBACJ;;;4BAC4C,IAAI,eAC5C,oBACJ;;;wBACwC,IAAI,eACxC,gBACJ;;;mBACmC,IAAI,eAAe,WAAW;;;kBAC/B,IAAI,eAAe,UAAU;;;sBACzB,IAAI,eAAe,cAAc;;;0BAC7B,IAAI,eAC1C,kBACJ;;;gCACgD,IAAI,eAChD,wBACJ;;;wBACwC,IAAI,eACxC,gBACJ;;;mBACmC,IAAI,eAAe,WAAW;;;qBAC5B,IAAI,eAAe,aAAa;;;oBACjC,IAAI,eAAe,YAAY;;AACvE"}
|
|
1
|
+
{"version":3,"file":"validation-code.js","names":[],"sources":["../src/core/errors/error-codes.ts","../src/core/errors/utils/json-safe.ts","../src/core/errors/app-error.ts","../src/core/shared/hashing.ts","../src/core/errors/unexpected-error.ts","../src/core/exceptions/validation-code.ts"],"sourcesContent":["const ErrorCodes = {\n authentication: {\n missingToken: \"sec.authn.missing_token\",\n invalidToken: \"sec.authn.invalid_token\",\n expiredToken: \"sec.authn.expired_token\",\n invalidCredentials: \"sec.authn.invalid_credentials\",\n },\n authorization: {\n forbidden: \"sec.authz.forbidden\",\n policyDenied: \"sec.authz.policy_denied\",\n missingCapability: \"sec.authz.missing_capability\",\n outOfScope: \"sec.authz.out_of_scope\",\n },\n businessRuleViolation: \"business_rule_violation\",\n conflict: {\n alreadyExists: \"conf.already_exists\",\n duplicate: \"conf.duplicate\",\n uniqueViolation: \"conf.unique_violation\",\n },\n idempotency: {\n keyMissing: \"idemp.key_missing\",\n inProgress: \"idemp.in_progress\",\n payloadMismatch: \"idemp.payload_mismatch\",\n replayNotSupported: \"idemp.replay_not_supported\",\n },\n integration: {\n timeout: \"int.timeout\",\n unreachable: \"int.unreachable\",\n badResponse: \"int.bad_response\",\n },\n legacyIncompatible: \"legacy_incompatible\",\n notFound: \"not_found\",\n serialization: {\n deserializePrefix: \"ser.des\",\n serializePrefix: \"ser.ser\",\n },\n temporal: {\n expired: \"tmp.expired\",\n notYetValid: \"tmp.not_yet_valid\",\n },\n unexpected: \"unexpected\",\n validation: \"validation_error\",\n} as const;\n\ntype SerializationCodeDirection = \"deserialize\" | \"serialize\";\n\nfunction serializationErrorCode(\n direction: SerializationCodeDirection,\n category: string,\n): string {\n const prefix =\n direction === \"deserialize\"\n ? ErrorCodes.serialization.deserializePrefix\n : ErrorCodes.serialization.serializePrefix;\n\n return `${prefix}.${category}`;\n}\n\nexport { ErrorCodes, serializationErrorCode };\nexport type { SerializationCodeDirection };\n","// Utilities for ensuring metadata is JSON-serializable.\n\nimport type { JsonSafeRecord, JsonSafeValue } from \"../types.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Constants\n// ─────────────────────────────────────────────────────────────────────────────\n\nconst NON_SERIALIZABLE_PLACEHOLDER = \"[NonSerializable]\";\nconst CIRCULAR_REFERENCE_PLACEHOLDER = \"[Circular]\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Internal helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n// `seen` tracks the ancestors on the current traversal branch (a DFS path), not\n// every object visited. This collapses true circular references to a placeholder\n// while still serializing the same object referenced more than once across\n// sibling branches (a DAG) — matching `JSON.stringify`, which only rejects\n// cycles, not shared references.\nfunction sanitizeValue(value: unknown, seen: WeakSet<object>): JsonSafeValue {\n // Null passthrough\n if (value === null) return null;\n\n const type = typeof value;\n\n // Primitives\n if (type === \"string\" || type === \"number\" || type === \"boolean\") {\n return value as JsonSafeValue;\n }\n\n // Non-serializable primitives\n if (\n type === \"bigint\" ||\n type === \"function\" ||\n type === \"symbol\" ||\n value === undefined\n ) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Arrays (recursive)\n if (Array.isArray(value)) {\n if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;\n seen.add(value);\n const sanitized = value.map((item) => sanitizeValue(item, seen));\n seen.delete(value);\n return sanitized;\n }\n\n // Date → placeholder (could also use .toISOString() if preferred)\n if (value instanceof Date) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Class instances and non-plain objects → placeholder\n if (!isPlainObject(value)) {\n return NON_SERIALIZABLE_PLACEHOLDER;\n }\n\n // Plain object (recursive)\n if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;\n seen.add(value);\n const result: Record<string, JsonSafeValue> = {};\n for (const [key, val] of Object.entries(value)) {\n result[key] = sanitizeValue(val, seen);\n }\n seen.delete(value);\n return result;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Public API\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Ensures metadata is JSON-serializable.\n *\n * **Allowed:** string, number, boolean, null, arrays, and plain objects.\n *\n * **Converted to placeholder:** Date, BigInt, class instances, functions,\n * symbols, undefined, and circular references (which would otherwise make\n * `JSON.stringify` throw).\n *\n * @throws {TypeError} If `input` is not a plain object at the root level.\n */\nfunction assertJsonSafeMetadata(input: unknown): JsonSafeRecord {\n if (input === undefined) {\n return {};\n }\n\n if (!isPlainObject(input)) {\n throw new TypeError(\n \"metadata must be a plain object (Record<string, unknown>).\",\n );\n }\n\n return sanitizeValue(input, new WeakSet<object>()) as JsonSafeRecord;\n}\n\nexport {\n assertJsonSafeMetadata,\n CIRCULAR_REFERENCE_PLACEHOLDER,\n NON_SERIALIZABLE_PLACEHOLDER,\n};\n","// Base application error for the domain/application layer.\n// Encapsulates a code, optional cause, and JSON-safe metadata.\n\nimport type {\n AppErrorOptions,\n ErrorSeverity,\n JsonSafeRecord,\n} from \"./types.js\";\nimport { assertJsonSafeMetadata } from \"./utils/index.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// AppError (abstract base class)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Root of the application/domain error hierarchy. Every error the system raises\n * on purpose extends `AppError`, which gives callers a single `instanceof` to\n * catch and a uniform, serializable shape to log and transport.\n *\n * Beyond the native `Error` message it carries a stable `code` (the contract the\n * outside world matches on), an optional non-leaking `publicMessage`, a\n * severity, JSON-safe `metadata`, and the correlation/request/command ids that\n * stitch an error back to the request that produced it. The metadata is\n * validated as JSON-safe on construction, so a logger can serialize any\n * `AppError` without hitting a circular reference or a non-serializable value.\n *\n * Abstract on purpose: callers should throw a specific subclass (e.g.\n * {@link ValidationError}, {@link NotFoundError}) so the `code` and shape are\n * meaningful, never a bare `AppError`.\n */\nabstract class AppError extends Error {\n public readonly code: string;\n public readonly cause?: unknown;\n public readonly metadata?: JsonSafeRecord;\n public readonly type?: string;\n public readonly severity?: ErrorSeverity;\n public readonly createdAtIso: string;\n public readonly publicMessage?: string;\n /**\n * Identifies a single execution \"story\" in the system. All operations\n * related to the same logical flow must share the same correlationId.\n */\n public readonly correlationId?: string;\n /**\n * Identifies a specific technical request attempt (each retry may produce\n * a new requestId), even when the correlationId stays the same.\n */\n public readonly requestId?: string;\n /**\n * Marks the business intent / idempotency key; stays the same across\n * technical retries and multiple requests that represent the same intent.\n */\n public readonly commandId?: string;\n\n /**\n * Builds the common error envelope shared by every subclass.\n *\n * `name` is taken from `new.target` so the thrown instance reports its\n * concrete subclass name (not `\"AppError\"`), and the prototype is re-pinned\n * via `setPrototypeOf` so `instanceof` keeps working after transpilation to\n * older targets where extending built-ins breaks the chain. `createdAtIso`\n * defaults to now, and `metadata` is validated as JSON-safe so the error is\n * always serializable.\n *\n * Declared `protected`: instantiate a concrete subclass, never `AppError`.\n *\n * @param message - The internal, developer-facing message.\n * @param code - The stable machine-readable code callers match on.\n * @param options - Optional cause, metadata, severity, and correlation ids.\n * @throws When `options.metadata` contains a value that is not JSON-safe.\n */\n protected constructor(\n message: string,\n code: string,\n options?: AppErrorOptions,\n ) {\n super(message);\n\n this.name = new.target.name;\n this.code = code;\n this.cause = options?.cause;\n this.type = options?.type;\n this.severity = options?.severity;\n this.correlationId = options?.correlationId;\n this.requestId = options?.requestId;\n this.commandId = options?.commandId;\n this.createdAtIso = options?.createdAtIso ?? new Date().toISOString();\n this.publicMessage = options?.publicMessage;\n\n this.metadata = options?.metadata\n ? assertJsonSafeMetadata(options.metadata)\n : undefined;\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n /**\n * Returns a JSON-safe representation of the error.\n * Does NOT include `cause` by default (to avoid leaking internal details).\n */\n public toJSON(): Record<string, unknown> {\n const payload: Record<string, unknown> = {\n name: this.name,\n code: this.code,\n message: this.message,\n createdAtIso: this.createdAtIso,\n };\n\n // Optional fields are emitted only when defined, so the serialized\n // shape never carries `undefined`-valued keys (consistent with how the\n // correlation/request/command ids are handled).\n if (this.type !== undefined) payload.type = this.type;\n if (this.severity !== undefined) payload.severity = this.severity;\n if (this.publicMessage !== undefined)\n payload.publicMessage = this.publicMessage;\n if (this.metadata !== undefined) payload.metadata = this.metadata;\n if (this.correlationId !== undefined)\n payload.correlationId = this.correlationId;\n if (this.requestId !== undefined) payload.requestId = this.requestId;\n if (this.commandId !== undefined) payload.commandId = this.commandId;\n\n return payload;\n }\n}\n\nexport { AppError };\n","import { createHash } from \"node:crypto\";\n\nconst CIRCULAR_STRUCTURE_MESSAGE =\n \"Cannot stably stringify a circular structure\";\n\nfunction sha256Hex(value: string): string {\n return createHash(\"sha256\").update(value, \"utf8\").digest(\"hex\");\n}\n\n// `seen` holds the current traversal branch so true cycles are rejected while\n// repeated (acyclic) references are still serialized — matching JSON.stringify.\nfunction sortKeysDeep(value: unknown, seen: WeakSet<object>): unknown {\n if (Array.isArray(value)) {\n if (seen.has(value)) {\n throw new TypeError(CIRCULAR_STRUCTURE_MESSAGE);\n }\n seen.add(value);\n const mapped = value.map((item) => sortKeysDeep(item, seen));\n seen.delete(value);\n return mapped;\n }\n\n if (value instanceof Date) {\n return value;\n }\n\n if (value && typeof value === \"object\") {\n if (seen.has(value)) {\n throw new TypeError(CIRCULAR_STRUCTURE_MESSAGE);\n }\n seen.add(value);\n const record = value as Record<string, unknown>;\n const ordered = Object.create(null) as Record<string, unknown>;\n\n for (const key of Object.keys(record).sort()) {\n ordered[key] = sortKeysDeep(record[key], seen);\n }\n seen.delete(value);\n\n return ordered;\n }\n\n return value;\n}\n\n/**\n * Deterministic JSON string with object keys sorted recursively, so key order\n * does not affect the output.\n *\n * Follows `JSON.stringify` semantics for the values it serializes: `undefined`,\n * functions and symbols are dropped, non-finite numbers become `null`, `bigint`\n * throws, and `Map`/`Set` serialize as `{}`. Distinct payloads can therefore\n * collapse to the same string — for collision-resistant hashing use\n * `PolicyHashing.canonicalJson` (policies/utils), which rejects those values\n * up front.\n *\n * @throws {TypeError} On circular references (mirroring `JSON.stringify`).\n */\nfunction stableStringify(value: unknown): string {\n return JSON.stringify(sortKeysDeep(value, new WeakSet<object>()));\n}\n\nfunction payloadHash(value: unknown): string {\n return sha256Hex(stableStringify(value));\n}\n\nexport { payloadHash, sha256Hex, stableStringify };\n","import { AppError } from \"./app-error.js\";\nimport { ErrorCodes } from \"./error-codes.js\";\nimport type { AppErrorOptions } from \"./types.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// UnexpectedError\n// ─────────────────────────────────────────────────────────────────────────────\n\nclass UnexpectedError extends AppError {\n constructor(\n message = \"Unexpected error\",\n cause?: unknown,\n options?: Omit<AppErrorOptions, \"cause\">,\n ) {\n super(message, ErrorCodes.unexpected, {\n cause,\n ...options,\n });\n }\n}\n\nexport { UnexpectedError };\n","// Object-oriented representation of validation codes (similar to Kotlin inline class).\n// Provides common reusable codes while allowing custom codes via `of`.\n\nclass ValidationCode {\n public readonly value: string;\n\n private constructor(value: string) {\n this.value = value;\n }\n\n // Factory for custom codes\n public static of(value: string): ValidationCode {\n return new ValidationCode(value);\n }\n\n // Common, domain-friendly codes\n public static readonly BLANK = new ValidationCode(\"blank\");\n public static readonly REQUIRED = new ValidationCode(\"required\");\n public static readonly INVALID_FORMAT = new ValidationCode(\n \"invalid_format\",\n );\n public static readonly INVALID_CHARACTERS = new ValidationCode(\n \"invalid_characters\",\n );\n public static readonly INVALID_LENGTH = new ValidationCode(\n \"invalid_length\",\n );\n public static readonly TOO_SHORT = new ValidationCode(\"too_short\");\n public static readonly TOO_LONG = new ValidationCode(\"too_long\");\n public static readonly OUT_OF_RANGE = new ValidationCode(\"out_of_range\");\n public static readonly INVALID_CHECKSUM = new ValidationCode(\n \"invalid_checksum\",\n );\n public static readonly INVALID_CHECKING_DIGIT = new ValidationCode(\n \"invalid_checking_digit\",\n );\n public static readonly ALREADY_EXISTS = new ValidationCode(\n \"already_exists\",\n );\n public static readonly NOT_FOUND = new ValidationCode(\"not_found\");\n public static readonly NOT_ALLOWED = new ValidationCode(\"not_allowed\");\n public static readonly UNEXPECTED = new ValidationCode(\"unexpected\");\n}\n\nexport { ValidationCode };\n"],"mappings":";;AAAA,MAAM,aAAa;CACf,gBAAgB;EACZ,cAAc;EACd,cAAc;EACd,cAAc;EACd,oBAAoB;CACxB;CACA,eAAe;EACX,WAAW;EACX,cAAc;EACd,mBAAmB;EACnB,YAAY;CAChB;CACA,uBAAuB;CACvB,UAAU;EACN,eAAe;EACf,WAAW;EACX,iBAAiB;CACrB;CACA,aAAa;EACT,YAAY;EACZ,YAAY;EACZ,iBAAiB;EACjB,oBAAoB;CACxB;CACA,aAAa;EACT,SAAS;EACT,aAAa;EACb,aAAa;CACjB;CACA,oBAAoB;CACpB,UAAU;CACV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J;;;wBACwC,IAAI,eACxC,gBACJ;;;mBACmC,IAAI,eAAe,WAAW;;;kBAC/B,IAAI,eAAe,UAAU;;;sBACzB,IAAI,eAAe,cAAc;;;0BAC7B,IAAI,eAC1C,kBACJ;;;gCACgD,IAAI,eAChD,wBACJ;;;wBACwC,IAAI,eACxC,gBACJ;;;mBACmC,IAAI,eAAe,WAAW;;;qBAC5B,IAAI,eAAe,aAAa;;;oBACjC,IAAI,eAAe,YAAY;;AACvE"}
|
|
@@ -103,6 +103,22 @@ declare function serializationErrorCode(direction: SerializationCodeDirection, c
|
|
|
103
103
|
declare function assertJsonSafeMetadata(input: unknown): JsonSafeRecord;
|
|
104
104
|
//#endregion
|
|
105
105
|
//#region src/core/errors/app-error.d.ts
|
|
106
|
+
/**
|
|
107
|
+
* Root of the application/domain error hierarchy. Every error the system raises
|
|
108
|
+
* on purpose extends `AppError`, which gives callers a single `instanceof` to
|
|
109
|
+
* catch and a uniform, serializable shape to log and transport.
|
|
110
|
+
*
|
|
111
|
+
* Beyond the native `Error` message it carries a stable `code` (the contract the
|
|
112
|
+
* outside world matches on), an optional non-leaking `publicMessage`, a
|
|
113
|
+
* severity, JSON-safe `metadata`, and the correlation/request/command ids that
|
|
114
|
+
* stitch an error back to the request that produced it. The metadata is
|
|
115
|
+
* validated as JSON-safe on construction, so a logger can serialize any
|
|
116
|
+
* `AppError` without hitting a circular reference or a non-serializable value.
|
|
117
|
+
*
|
|
118
|
+
* Abstract on purpose: callers should throw a specific subclass (e.g.
|
|
119
|
+
* {@link ValidationError}, {@link NotFoundError}) so the `code` and shape are
|
|
120
|
+
* meaningful, never a bare `AppError`.
|
|
121
|
+
*/
|
|
106
122
|
declare abstract class AppError extends Error {
|
|
107
123
|
readonly code: string;
|
|
108
124
|
readonly cause?: unknown;
|
|
@@ -126,6 +142,23 @@ declare abstract class AppError extends Error {
|
|
|
126
142
|
* technical retries and multiple requests that represent the same intent.
|
|
127
143
|
*/
|
|
128
144
|
readonly commandId?: string;
|
|
145
|
+
/**
|
|
146
|
+
* Builds the common error envelope shared by every subclass.
|
|
147
|
+
*
|
|
148
|
+
* `name` is taken from `new.target` so the thrown instance reports its
|
|
149
|
+
* concrete subclass name (not `"AppError"`), and the prototype is re-pinned
|
|
150
|
+
* via `setPrototypeOf` so `instanceof` keeps working after transpilation to
|
|
151
|
+
* older targets where extending built-ins breaks the chain. `createdAtIso`
|
|
152
|
+
* defaults to now, and `metadata` is validated as JSON-safe so the error is
|
|
153
|
+
* always serializable.
|
|
154
|
+
*
|
|
155
|
+
* Declared `protected`: instantiate a concrete subclass, never `AppError`.
|
|
156
|
+
*
|
|
157
|
+
* @param message - The internal, developer-facing message.
|
|
158
|
+
* @param code - The stable machine-readable code callers match on.
|
|
159
|
+
* @param options - Optional cause, metadata, severity, and correlation ids.
|
|
160
|
+
* @throws When `options.metadata` contains a value that is not JSON-safe.
|
|
161
|
+
*/
|
|
129
162
|
protected constructor(message: string, code: string, options?: AppErrorOptions);
|
|
130
163
|
/**
|
|
131
164
|
* Returns a JSON-safe representation of the error.
|
|
@@ -196,18 +229,61 @@ type AuthorizationErrorMetadata = {
|
|
|
196
229
|
* Combines metadata fields (except 'reason') with common AppError options.
|
|
197
230
|
*/
|
|
198
231
|
type AuthorizationErrorFactoryOptions = Omit<AuthorizationErrorMetadata, "reason"> & Omit<AppErrorOptions, "metadata">;
|
|
232
|
+
/**
|
|
233
|
+
* Raised when an authenticated actor is not allowed to perform a business
|
|
234
|
+
* action — the "you may not" error, distinct from authentication ("who are
|
|
235
|
+
* you"). Maps to an HTTP 403 at the edge.
|
|
236
|
+
*
|
|
237
|
+
* The discriminating {@link reason} records *why* access was denied (a flat
|
|
238
|
+
* forbid, a missing role/capability, an out-of-scope target, or a policy
|
|
239
|
+
* decision) so the boundary can shape the response without re-deriving it. The
|
|
240
|
+
* metadata is deliberately built around a stable business `action` and a
|
|
241
|
+
* type/id resource reference rather than an HTTP route or full payload, keeping
|
|
242
|
+
* sensitive data out of logs. Instances are frozen. Construct through the
|
|
243
|
+
* static factories, never directly.
|
|
244
|
+
*/
|
|
199
245
|
declare class AuthorizationError extends AppError {
|
|
200
246
|
readonly reason: AuthorizationErrorReason;
|
|
201
247
|
private constructor();
|
|
248
|
+
/**
|
|
249
|
+
* A flat denial with no more specific reason — the actor simply may not
|
|
250
|
+
* perform this action. Reach for a more precise factory
|
|
251
|
+
* ({@link AuthorizationError.missingCapability}, {@link AuthorizationError.outOfScope},
|
|
252
|
+
* {@link AuthorizationError.policyDenied}) when the cause is known.
|
|
253
|
+
*/
|
|
202
254
|
static forbidden(input: AuthorizationErrorFactoryOptions): AuthorizationError;
|
|
255
|
+
/**
|
|
256
|
+
* The action was denied by an evaluated policy. Captures the deciding
|
|
257
|
+
* policy's id, version, and evaluation instant into the metadata (with
|
|
258
|
+
* `decision: "deny"`) so the denial is auditable back to the exact policy
|
|
259
|
+
* that produced it.
|
|
260
|
+
*
|
|
261
|
+
* @param input - Factory options plus the required `policyId`,
|
|
262
|
+
* `policyVersion`, and `evaluatedAtIso` of the deciding policy.
|
|
263
|
+
*/
|
|
203
264
|
static policyDenied(input: AuthorizationErrorFactoryOptions & {
|
|
204
265
|
policyId: string;
|
|
205
266
|
policyVersion: number;
|
|
206
267
|
evaluatedAtIso: string;
|
|
207
268
|
}): AuthorizationError;
|
|
269
|
+
/**
|
|
270
|
+
* The actor lacks a required role or capability. The expected
|
|
271
|
+
* {@link AuthorizationRequirement} is recorded so the boundary can tell the
|
|
272
|
+
* caller precisely what grant is missing.
|
|
273
|
+
*
|
|
274
|
+
* @param input - Factory options plus the `required` role/capability/scope.
|
|
275
|
+
*/
|
|
208
276
|
static missingCapability(input: AuthorizationErrorFactoryOptions & {
|
|
209
277
|
required: AuthorizationRequirement;
|
|
210
278
|
}): AuthorizationError;
|
|
279
|
+
/**
|
|
280
|
+
* The actor may perform the action in general, but not on *this* target —
|
|
281
|
+
* the resource falls outside the actor's permitted scope (e.g. a different
|
|
282
|
+
* school or tenant than the one they are bound to).
|
|
283
|
+
*
|
|
284
|
+
* @param input - Factory options plus the optional `required` scope that the
|
|
285
|
+
* target failed to satisfy.
|
|
286
|
+
*/
|
|
211
287
|
static outOfScope(input: AuthorizationErrorFactoryOptions & {
|
|
212
288
|
required?: AuthorizationRequirement;
|
|
213
289
|
}): AuthorizationError;
|
|
@@ -241,12 +317,28 @@ type ConflictErrorMetadata = {
|
|
|
241
317
|
commandId?: string;
|
|
242
318
|
hint?: string;
|
|
243
319
|
};
|
|
320
|
+
/**
|
|
321
|
+
* Storage-level description of a unique-constraint breach, as reported by a
|
|
322
|
+
* database driver. Used to translate a raw DB error into a domain
|
|
323
|
+
* {@link DuplicateError} via {@link translateUniqueViolationToDuplicate}.
|
|
324
|
+
*/
|
|
244
325
|
type UniqueConstraintViolation = {
|
|
245
326
|
kind: "unique_violation";
|
|
246
327
|
constraintName?: string;
|
|
247
328
|
table?: string;
|
|
248
329
|
columns?: string[];
|
|
249
330
|
};
|
|
331
|
+
/**
|
|
332
|
+
* Base for errors that signal a state conflict — the request collides with data
|
|
333
|
+
* that already exists. Common at an HTTP 409 boundary.
|
|
334
|
+
*
|
|
335
|
+
* The discriminating {@link kind} lets a handler branch on *why* it conflicted
|
|
336
|
+
* (an already-existing record, a domain duplicate, or a raw storage uniqueness
|
|
337
|
+
* breach) without `instanceof` chains. Abstract: construct one of the concrete
|
|
338
|
+
* subclasses through its `detected(...)` factory, which fills in the right code,
|
|
339
|
+
* message, and metadata. Instances are frozen, so a conflict error can be shared
|
|
340
|
+
* and rethrown without risk of tampering.
|
|
341
|
+
*/
|
|
250
342
|
declare abstract class ConflictError extends AppError {
|
|
251
343
|
readonly kind: ConflictKind;
|
|
252
344
|
protected constructor(params: {
|
|
@@ -257,8 +349,21 @@ declare abstract class ConflictError extends AppError {
|
|
|
257
349
|
cause?: unknown;
|
|
258
350
|
} & AppErrorOptions);
|
|
259
351
|
}
|
|
352
|
+
/**
|
|
353
|
+
* The operation cannot proceed because a matching record already exists —
|
|
354
|
+
* e.g. creating something whose natural key is already taken. Construct via
|
|
355
|
+
* {@link AlreadyExistsError.detected}.
|
|
356
|
+
*/
|
|
260
357
|
declare class AlreadyExistsError extends ConflictError {
|
|
261
358
|
private constructor();
|
|
359
|
+
/**
|
|
360
|
+
* Builds an {@link AlreadyExistsError} for a detected collision. `operation`
|
|
361
|
+
* defaults to `"create"` and a generic retry `hint` is supplied when none is
|
|
362
|
+
* given, so the error is actionable even from a minimal call site.
|
|
363
|
+
*
|
|
364
|
+
* @param input - The conflicting entity plus optional non-sensitive context
|
|
365
|
+
* (operation, field, existing id, value hash/preview, correlation ids).
|
|
366
|
+
*/
|
|
262
367
|
static detected(input: {
|
|
263
368
|
entity: string;
|
|
264
369
|
operation?: string;
|
|
@@ -274,8 +379,22 @@ declare class AlreadyExistsError extends ConflictError {
|
|
|
274
379
|
cause?: unknown;
|
|
275
380
|
}): AlreadyExistsError;
|
|
276
381
|
}
|
|
382
|
+
/**
|
|
383
|
+
* A domain-level duplicate: the data being written would duplicate an existing
|
|
384
|
+
* record under the model's own uniqueness rules. Use this when the duplication
|
|
385
|
+
* is recognized in the domain, as opposed to a raw DB constraint
|
|
386
|
+
* ({@link UniqueConstraintViolationError}). Construct via
|
|
387
|
+
* {@link DuplicateError.detected}.
|
|
388
|
+
*/
|
|
277
389
|
declare class DuplicateError extends ConflictError {
|
|
278
390
|
private constructor();
|
|
391
|
+
/**
|
|
392
|
+
* Builds a {@link DuplicateError} for a detected duplicate, defaulting to a
|
|
393
|
+
* "adjust the data so it does not duplicate" hint when none is provided.
|
|
394
|
+
*
|
|
395
|
+
* @param input - The conflicting entity plus optional non-sensitive context
|
|
396
|
+
* (field, constraint name, existing id, value hash/preview, correlation ids).
|
|
397
|
+
*/
|
|
279
398
|
static detected(input: {
|
|
280
399
|
entity: string;
|
|
281
400
|
operation?: string;
|
|
@@ -292,8 +411,23 @@ declare class DuplicateError extends ConflictError {
|
|
|
292
411
|
cause?: unknown;
|
|
293
412
|
}): DuplicateError;
|
|
294
413
|
}
|
|
414
|
+
/**
|
|
415
|
+
* A uniqueness breach surfaced by the storage layer itself (a database unique
|
|
416
|
+
* index), carrying the raw {@link UniqueConstraintViolation} (constraint, table,
|
|
417
|
+
* columns). Keep this distinct from {@link DuplicateError}: this one is the
|
|
418
|
+
* infrastructure signal; translate it into a domain duplicate at the boundary
|
|
419
|
+
* with {@link translateUniqueViolationToDuplicate} when the model should own the
|
|
420
|
+
* message. Construct via {@link UniqueConstraintViolationError.detected}.
|
|
421
|
+
*/
|
|
295
422
|
declare class UniqueConstraintViolationError extends ConflictError {
|
|
296
423
|
private constructor();
|
|
424
|
+
/**
|
|
425
|
+
* Builds a {@link UniqueConstraintViolationError} from the constraint details
|
|
426
|
+
* a driver reports, packaging them into a nested `violation` payload.
|
|
427
|
+
*
|
|
428
|
+
* @param input - The entity plus the offending constraint name, table, and
|
|
429
|
+
* columns, and optional correlation ids.
|
|
430
|
+
*/
|
|
297
431
|
static detected(input: {
|
|
298
432
|
entity: string;
|
|
299
433
|
operation?: string;
|
|
@@ -307,6 +441,17 @@ declare class UniqueConstraintViolationError extends ConflictError {
|
|
|
307
441
|
cause?: unknown;
|
|
308
442
|
}): UniqueConstraintViolationError;
|
|
309
443
|
}
|
|
444
|
+
/**
|
|
445
|
+
* Translates a raw storage {@link UniqueConstraintViolation} into a domain-level
|
|
446
|
+
* {@link DuplicateError}. This is the seam where an infrastructure concern (a DB
|
|
447
|
+
* unique index firing) is re-expressed in the language of the model, so callers
|
|
448
|
+
* upstream catch a `DuplicateError` and never have to know a database was
|
|
449
|
+
* involved.
|
|
450
|
+
*
|
|
451
|
+
* @param input - The entity, the driver-reported `violation`, and optional
|
|
452
|
+
* request context (`ctx`) carrying correlation ids and a clock instant.
|
|
453
|
+
* @returns A {@link DuplicateError} carrying the constraint name as its field hint.
|
|
454
|
+
*/
|
|
310
455
|
declare function translateUniqueViolationToDuplicate(input: {
|
|
311
456
|
entity: string;
|
|
312
457
|
operation?: string;
|
|
@@ -522,11 +667,36 @@ type IntegrationErrorMetadata = {
|
|
|
522
667
|
statusCode?: number;
|
|
523
668
|
responseCode?: string;
|
|
524
669
|
};
|
|
670
|
+
/**
|
|
671
|
+
* Raised when a call to an external provider fails — a timeout, an unreachable
|
|
672
|
+
* endpoint, or a malformed response. This is the boundary error that separates
|
|
673
|
+
* "our code is fine, the outside world misbehaved" from internal faults, which
|
|
674
|
+
* matters for retry and alerting decisions.
|
|
675
|
+
*
|
|
676
|
+
* Every instance records the `provider`, the `operation`, and timing
|
|
677
|
+
* (`startedAtIso` / `durationMs`) so failures are correlatable across services
|
|
678
|
+
* and a slow dependency is visible in the metadata. The discriminating
|
|
679
|
+
* {@link reason} lets callers decide whether a failure is worth retrying.
|
|
680
|
+
* Instances are frozen; construct through the static factories.
|
|
681
|
+
*/
|
|
525
682
|
declare class IntegrationError extends AppError {
|
|
526
683
|
readonly reason: IntegrationErrorReason;
|
|
527
684
|
private constructor();
|
|
685
|
+
/**
|
|
686
|
+
* The provider did not respond within the allotted time. Usually retryable,
|
|
687
|
+
* since a timeout leaves the outcome unknown rather than known-failed.
|
|
688
|
+
*/
|
|
528
689
|
static timeout(options: IntegrationErrorTimeoutOptions): IntegrationError;
|
|
690
|
+
/**
|
|
691
|
+
* The provider could not be reached at all (connection refused, DNS
|
|
692
|
+
* failure, network partition) — the request never landed.
|
|
693
|
+
*/
|
|
529
694
|
static unreachable(options: IntegrationErrorEndpointOptions): IntegrationError;
|
|
695
|
+
/**
|
|
696
|
+
* The provider answered, but with something the system cannot use — an
|
|
697
|
+
* unexpected status, an unparsable body, or a contract mismatch. Unlike a
|
|
698
|
+
* timeout this is a definite failure, so blind retries rarely help.
|
|
699
|
+
*/
|
|
530
700
|
static badResponse(options: IntegrationErrorEndpointOptions): IntegrationError;
|
|
531
701
|
}
|
|
532
702
|
type IntegrationErrorBaseOptions = {
|
|
@@ -556,7 +726,21 @@ declare class LegacyIncompatibleError extends AppError {
|
|
|
556
726
|
}
|
|
557
727
|
//#endregion
|
|
558
728
|
//#region src/core/errors/not-found-error.d.ts
|
|
729
|
+
/**
|
|
730
|
+
* Raised when a requested resource does not exist. Maps naturally onto an HTTP
|
|
731
|
+
* 404 at the edge, but stays transport-agnostic here.
|
|
732
|
+
*
|
|
733
|
+
* The `resource` name builds the message (`"<resource> not found"`) and, with
|
|
734
|
+
* the optional lookup `criteria`, lands in the metadata so logs show *what* was
|
|
735
|
+
* searched for without the caller having to restate it in the message.
|
|
736
|
+
*/
|
|
559
737
|
declare class NotFoundError extends AppError {
|
|
738
|
+
/**
|
|
739
|
+
* @param resource - Human-readable name of the missing resource (e.g. `"Order"`).
|
|
740
|
+
* @param criteria - Optional lookup keys used in the search; recorded in
|
|
741
|
+
* metadata to aid debugging. Avoid putting sensitive values here.
|
|
742
|
+
* @param options - Optional cause, correlation ids, and extra metadata.
|
|
743
|
+
*/
|
|
560
744
|
constructor(resource: string, criteria?: Record<string, unknown>, options?: AppErrorOptions);
|
|
561
745
|
}
|
|
562
746
|
//#endregion
|
|
@@ -692,7 +876,25 @@ declare class ValidationCode {
|
|
|
692
876
|
}
|
|
693
877
|
//#endregion
|
|
694
878
|
//#region src/core/errors/validation-error.d.ts
|
|
879
|
+
/**
|
|
880
|
+
* Raised when a single input fails a validation rule — the canonical
|
|
881
|
+
* "this field is wrong, and here is why" error.
|
|
882
|
+
*
|
|
883
|
+
* It pins the offending `field` and a machine-readable `validationCode` into
|
|
884
|
+
* the metadata (merged ahead of any caller-supplied metadata) so an API layer
|
|
885
|
+
* can map the failure straight onto a form field without parsing the message.
|
|
886
|
+
* The fixed {@link ErrorCodes.validation} code lets callers catch all
|
|
887
|
+
* validation failures uniformly while still distinguishing the specific rule
|
|
888
|
+
* through `validationCode`.
|
|
889
|
+
*/
|
|
695
890
|
declare class ValidationError extends AppError {
|
|
891
|
+
/**
|
|
892
|
+
* @param field - The input that failed validation; surfaced as `metadata.field`.
|
|
893
|
+
* @param code - The specific rule that was violated; surfaced as `metadata.validationCode`.
|
|
894
|
+
* @param message - The developer-facing description of the failure.
|
|
895
|
+
* @param options - Optional cause, correlation ids, and extra metadata
|
|
896
|
+
* (merged over the field/code metadata, never overwriting it by accident).
|
|
897
|
+
*/
|
|
696
898
|
constructor(field: ValidationField, code: ValidationCode, message: string, options?: AppErrorOptions);
|
|
697
899
|
}
|
|
698
900
|
//#endregion
|