@cullet/erp-core 1.0.11 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/KIT_CONTEXT.md +1 -0
  2. package/README.md +128 -1
  3. package/dist/app-error.d.ts +108 -0
  4. package/dist/application/index.d.ts +2 -0
  5. package/dist/application/index.js +3 -0
  6. package/dist/domain/index.d.ts +3 -0
  7. package/dist/domain/index.js +3 -0
  8. package/dist/domain-event-contracts.d.ts +27 -0
  9. package/dist/domain-event-contracts.js +22 -0
  10. package/dist/domain-event-contracts.js.map +1 -0
  11. package/dist/domain-exception.d.ts +7 -0
  12. package/dist/domain-exception.js +12 -0
  13. package/dist/domain-exception.js.map +1 -0
  14. package/dist/errors/index.d.ts +2 -1
  15. package/dist/errors/index.js +4 -2
  16. package/dist/exceptions/index.d.ts +5 -0
  17. package/dist/exceptions/index.js +7 -0
  18. package/dist/gate-engine-registry.d.ts +81 -0
  19. package/dist/gate-engine-registry.js +2 -1
  20. package/dist/gate-engine-registry.js.map +1 -1
  21. package/dist/gate-types.d.ts +3 -139
  22. package/dist/gate-v1-payload.schema.js +3 -143
  23. package/dist/gate-v1-payload.schema.js.map +1 -1
  24. package/dist/hashing.js +49 -0
  25. package/dist/hashing.js.map +1 -0
  26. package/dist/immutable.d.ts +6 -0
  27. package/dist/immutable.js +54 -0
  28. package/dist/immutable.js.map +1 -0
  29. package/dist/index.d.ts +21 -200
  30. package/dist/index.js +21 -251
  31. package/dist/index.js.map +1 -1
  32. package/dist/invalid-state-transition-exception.js +30 -0
  33. package/dist/invalid-state-transition-exception.js.map +1 -0
  34. package/dist/invariant-violation-exception.js +11 -0
  35. package/dist/invariant-violation-exception.js.map +1 -0
  36. package/dist/not-found-error.js +54 -0
  37. package/dist/not-found-error.js.map +1 -0
  38. package/dist/outcome.d.ts +140 -0
  39. package/dist/outcome.js +1 -1
  40. package/dist/parse-gate-payload.d.ts +4 -78
  41. package/dist/path.d.ts +90 -0
  42. package/dist/plugin.d.ts +85 -0
  43. package/dist/plugin.js +74 -0
  44. package/dist/plugin.js.map +1 -0
  45. package/dist/plugins/index.d.ts +2 -0
  46. package/dist/plugins/index.js +2 -0
  47. package/dist/policies/engines/index.d.ts +3 -2
  48. package/dist/policies/engines/v1/gate/index.d.ts +2 -1
  49. package/dist/policies/engines/v1/gate/index.js +2 -1
  50. package/dist/policies/engines/v1/gate/index.js.map +1 -1
  51. package/dist/policies/index.d.ts +6 -3
  52. package/dist/policies/index.js +2 -1
  53. package/dist/policy-service.d.ts +4 -86
  54. package/dist/policy-service.js +8 -16
  55. package/dist/policy-service.js.map +1 -1
  56. package/dist/result/index.d.ts +2 -0
  57. package/dist/result/index.js +3 -0
  58. package/dist/result.js +118 -0
  59. package/dist/result.js.map +1 -0
  60. package/dist/ruleset-registry.js +42 -0
  61. package/dist/ruleset-registry.js.map +1 -0
  62. package/dist/rulesets/index.d.ts +2 -0
  63. package/dist/rulesets/index.js +2 -0
  64. package/dist/temporal-guards.js +15 -0
  65. package/dist/temporal-guards.js.map +1 -0
  66. package/dist/temporal-use-case.d.ts +304 -0
  67. package/dist/temporal-use-case.js +150 -0
  68. package/dist/temporal-use-case.js.map +1 -0
  69. package/dist/unexpected-error.js +179 -0
  70. package/dist/unexpected-error.js.map +1 -0
  71. package/dist/use-case.js +91 -0
  72. package/dist/use-case.js.map +1 -0
  73. package/dist/uuid-identifier.d.ts +230 -0
  74. package/dist/uuid-identifier.js +60 -0
  75. package/dist/uuid-identifier.js.map +1 -0
  76. package/dist/validation-code.d.ts +23 -0
  77. package/dist/validation-code.js +1 -223
  78. package/dist/validation-code.js.map +1 -1
  79. package/dist/validation-error.d.ts +3 -128
  80. package/dist/validation-error.js +2 -52
  81. package/dist/validation-error.js.map +1 -1
  82. package/dist/validation-exception.d.ts +50 -0
  83. package/dist/validation-exception.js +24 -0
  84. package/dist/validation-exception.js.map +1 -0
  85. package/dist/value-object-ruleset.contracts.d.ts +36 -0
  86. package/dist/value-object.js +191 -0
  87. package/dist/value-object.js.map +1 -0
  88. package/dist/version.d.ts +10 -0
  89. package/dist/versioning/index.d.ts +3 -0
  90. package/dist/versioning/index.js +3 -0
  91. package/meta.json +18 -3
  92. package/package.json +37 -4
  93. package/src/application/index.ts +1 -0
  94. package/src/core/application/commands/index.ts +1 -0
  95. package/src/core/application/index.ts +12 -3
  96. package/src/core/application/ports/index.ts +2 -2
  97. package/src/core/application/ports/policy-port.ts +13 -3
  98. package/src/core/application/ports/repository.port.ts +37 -1
  99. package/src/core/application/temporal/temporal-use-case.ts +14 -2
  100. package/src/core/application/use-case.ts +133 -2
  101. package/src/core/domain/rulesets/index.ts +7 -0
  102. package/src/core/domain/uuid-identifier.ts +72 -0
  103. package/src/core/domain/value-object.ts +37 -5
  104. package/src/core/exceptions/index.ts +13 -0
  105. package/src/core/index.ts +15 -12
  106. package/src/core/plugins/index.ts +7 -0
  107. package/src/core/plugins/plugin.ts +99 -0
  108. package/src/core/plugins/types.ts +53 -0
  109. package/src/core/versioning/index.ts +14 -0
  110. package/src/domain/index.ts +7 -0
  111. package/src/examples/application/cancel-order.example.ts +124 -0
  112. package/src/examples/application/in-memory-account-repository.example.ts +73 -0
  113. package/src/exceptions/index.ts +1 -0
  114. package/src/plugins/index.ts +1 -0
  115. package/src/result/index.ts +2 -0
  116. package/src/rulesets/index.ts +1 -0
  117. package/src/version.ts +1 -1
  118. package/src/versioning/index.ts +1 -0
@@ -0,0 +1,23 @@
1
+ //#region src/core/exceptions/validation-code.d.ts
2
+ declare class ValidationCode {
3
+ readonly value: string;
4
+ private constructor();
5
+ static of(value: string): ValidationCode;
6
+ static readonly BLANK: ValidationCode;
7
+ static readonly REQUIRED: ValidationCode;
8
+ static readonly INVALID_FORMAT: ValidationCode;
9
+ static readonly INVALID_CHARACTERS: ValidationCode;
10
+ static readonly INVALID_LENGTH: ValidationCode;
11
+ static readonly TOO_SHORT: ValidationCode;
12
+ static readonly TOO_LONG: ValidationCode;
13
+ static readonly OUT_OF_RANGE: ValidationCode;
14
+ static readonly INVALID_CHECKSUM: ValidationCode;
15
+ static readonly INVALID_CHECKING_DIGIT: ValidationCode;
16
+ static readonly ALREADY_EXISTS: ValidationCode;
17
+ static readonly NOT_FOUND: ValidationCode;
18
+ static readonly NOT_ALLOWED: ValidationCode;
19
+ static readonly UNEXPECTED: ValidationCode;
20
+ }
21
+ //#endregion
22
+ export { ValidationCode as t };
23
+ //# sourceMappingURL=validation-code.d.ts.map
@@ -1,225 +1,3 @@
1
- import { createHash } from "node:crypto";
2
- //#region src/core/errors/error-codes.ts
3
- const ErrorCodes = {
4
- authentication: {
5
- missingToken: "sec.authn.missing_token",
6
- invalidToken: "sec.authn.invalid_token",
7
- expiredToken: "sec.authn.expired_token",
8
- invalidCredentials: "sec.authn.invalid_credentials"
9
- },
10
- authorization: {
11
- forbidden: "sec.authz.forbidden",
12
- policyDenied: "sec.authz.policy_denied",
13
- missingCapability: "sec.authz.missing_capability",
14
- outOfScope: "sec.authz.out_of_scope"
15
- },
16
- businessRuleViolation: "business_rule_violation",
17
- conflict: {
18
- alreadyExists: "conf.already_exists",
19
- duplicate: "conf.duplicate",
20
- uniqueViolation: "conf.unique_violation"
21
- },
22
- idempotency: {
23
- keyMissing: "idemp.key_missing",
24
- inProgress: "idemp.in_progress",
25
- payloadMismatch: "idemp.payload_mismatch",
26
- replayNotSupported: "idemp.replay_not_supported"
27
- },
28
- integration: {
29
- timeout: "int.timeout",
30
- unreachable: "int.unreachable",
31
- badResponse: "int.bad_response"
32
- },
33
- legacyIncompatible: "legacy_incompatible",
34
- notFound: "not_found",
35
- serialization: {
36
- deserializePrefix: "ser.des",
37
- serializePrefix: "ser.ser"
38
- },
39
- temporal: {
40
- expired: "tmp.expired",
41
- notYetValid: "tmp.not_yet_valid"
42
- },
43
- unexpected: "unexpected",
44
- validation: "validation_error"
45
- };
46
- function serializationErrorCode(direction, category) {
47
- return `${direction === "deserialize" ? ErrorCodes.serialization.deserializePrefix : ErrorCodes.serialization.serializePrefix}.${category}`;
48
- }
49
- //#endregion
50
- //#region src/core/errors/utils/json-safe.ts
51
- const NON_SERIALIZABLE_PLACEHOLDER = "[NonSerializable]";
52
- const CIRCULAR_REFERENCE_PLACEHOLDER = "[Circular]";
53
- function isPlainObject(value) {
54
- if (value === null || typeof value !== "object") return false;
55
- const proto = Object.getPrototypeOf(value);
56
- return proto === Object.prototype || proto === null;
57
- }
58
- function sanitizeValue(value, seen) {
59
- if (value === null) return null;
60
- const type = typeof value;
61
- if (type === "string" || type === "number" || type === "boolean") return value;
62
- if (type === "bigint" || type === "function" || type === "symbol" || value === void 0) return NON_SERIALIZABLE_PLACEHOLDER;
63
- if (Array.isArray(value)) {
64
- if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;
65
- seen.add(value);
66
- const sanitized = value.map((item) => sanitizeValue(item, seen));
67
- seen.delete(value);
68
- return sanitized;
69
- }
70
- if (value instanceof Date) return NON_SERIALIZABLE_PLACEHOLDER;
71
- if (!isPlainObject(value)) return NON_SERIALIZABLE_PLACEHOLDER;
72
- if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;
73
- seen.add(value);
74
- const result = {};
75
- for (const [key, val] of Object.entries(value)) result[key] = sanitizeValue(val, seen);
76
- seen.delete(value);
77
- return result;
78
- }
79
- /**
80
- * Ensures metadata is JSON-serializable.
81
- *
82
- * **Allowed:** string, number, boolean, null, arrays, and plain objects.
83
- *
84
- * **Converted to placeholder:** Date, BigInt, class instances, functions,
85
- * symbols, undefined, and circular references (which would otherwise make
86
- * `JSON.stringify` throw).
87
- *
88
- * @throws {TypeError} If `input` is not a plain object at the root level.
89
- */
90
- function assertJsonSafeMetadata(input) {
91
- if (input === void 0) return {};
92
- if (!isPlainObject(input)) throw new TypeError("metadata must be a plain object (Record<string, unknown>).");
93
- return sanitizeValue(input, /* @__PURE__ */ new WeakSet());
94
- }
95
- //#endregion
96
- //#region src/core/errors/app-error.ts
97
- /**
98
- * Root of the application/domain error hierarchy. Every error the system raises
99
- * on purpose extends `AppError`, which gives callers a single `instanceof` to
100
- * catch and a uniform, serializable shape to log and transport.
101
- *
102
- * Beyond the native `Error` message it carries a stable `code` (the contract the
103
- * outside world matches on), an optional non-leaking `publicMessage`, a
104
- * severity, JSON-safe `metadata`, and the correlation/request/command ids that
105
- * stitch an error back to the request that produced it. The metadata is
106
- * validated as JSON-safe on construction, so a logger can serialize any
107
- * `AppError` without hitting a circular reference or a non-serializable value.
108
- *
109
- * Abstract on purpose: callers should throw a specific subclass (e.g.
110
- * {@link ValidationError}, {@link NotFoundError}) so the `code` and shape are
111
- * meaningful, never a bare `AppError`.
112
- */
113
- var AppError = class extends Error {
114
- /**
115
- * Builds the common error envelope shared by every subclass.
116
- *
117
- * `name` is taken from `new.target` so the thrown instance reports its
118
- * concrete subclass name (not `"AppError"`), and the prototype is re-pinned
119
- * via `setPrototypeOf` so `instanceof` keeps working after transpilation to
120
- * older targets where extending built-ins breaks the chain. `createdAtIso`
121
- * defaults to now, and `metadata` is validated as JSON-safe so the error is
122
- * always serializable.
123
- *
124
- * Declared `protected`: instantiate a concrete subclass, never `AppError`.
125
- *
126
- * @param message - The internal, developer-facing message.
127
- * @param code - The stable machine-readable code callers match on.
128
- * @param options - Optional cause, metadata, severity, and correlation ids.
129
- * @throws When `options.metadata` contains a value that is not JSON-safe.
130
- */
131
- constructor(message, code, options) {
132
- super(message);
133
- this.name = new.target.name;
134
- this.code = code;
135
- this.cause = options?.cause;
136
- this.type = options?.type;
137
- this.severity = options?.severity;
138
- this.correlationId = options?.correlationId;
139
- this.requestId = options?.requestId;
140
- this.commandId = options?.commandId;
141
- this.createdAtIso = options?.createdAtIso ?? (/* @__PURE__ */ new Date()).toISOString();
142
- this.publicMessage = options?.publicMessage;
143
- this.metadata = options?.metadata ? assertJsonSafeMetadata(options.metadata) : void 0;
144
- Object.setPrototypeOf(this, new.target.prototype);
145
- }
146
- /**
147
- * Returns a JSON-safe representation of the error.
148
- * Does NOT include `cause` by default (to avoid leaking internal details).
149
- */
150
- toJSON() {
151
- const payload = {
152
- name: this.name,
153
- code: this.code,
154
- message: this.message,
155
- createdAtIso: this.createdAtIso
156
- };
157
- if (this.type !== void 0) payload.type = this.type;
158
- if (this.severity !== void 0) payload.severity = this.severity;
159
- if (this.publicMessage !== void 0) payload.publicMessage = this.publicMessage;
160
- if (this.metadata !== void 0) payload.metadata = this.metadata;
161
- if (this.correlationId !== void 0) payload.correlationId = this.correlationId;
162
- if (this.requestId !== void 0) payload.requestId = this.requestId;
163
- if (this.commandId !== void 0) payload.commandId = this.commandId;
164
- return payload;
165
- }
166
- };
167
- //#endregion
168
- //#region src/core/shared/hashing.ts
169
- const CIRCULAR_STRUCTURE_MESSAGE = "Cannot stably stringify a circular structure";
170
- function sha256Hex(value) {
171
- return createHash("sha256").update(value, "utf8").digest("hex");
172
- }
173
- function sortKeysDeep(value, seen) {
174
- if (Array.isArray(value)) {
175
- if (seen.has(value)) throw new TypeError(CIRCULAR_STRUCTURE_MESSAGE);
176
- seen.add(value);
177
- const mapped = value.map((item) => sortKeysDeep(item, seen));
178
- seen.delete(value);
179
- return mapped;
180
- }
181
- if (value instanceof Date) return value;
182
- if (value && typeof value === "object") {
183
- if (seen.has(value)) throw new TypeError(CIRCULAR_STRUCTURE_MESSAGE);
184
- seen.add(value);
185
- const record = value;
186
- const ordered = Object.create(null);
187
- for (const key of Object.keys(record).sort()) ordered[key] = sortKeysDeep(record[key], seen);
188
- seen.delete(value);
189
- return ordered;
190
- }
191
- return value;
192
- }
193
- /**
194
- * Deterministic JSON string with object keys sorted recursively, so key order
195
- * does not affect the output.
196
- *
197
- * Follows `JSON.stringify` semantics for the values it serializes: `undefined`,
198
- * functions and symbols are dropped, non-finite numbers become `null`, `bigint`
199
- * throws, and `Map`/`Set` serialize as `{}`. Distinct payloads can therefore
200
- * collapse to the same string — for collision-resistant hashing use
201
- * `PolicyHashing.canonicalJson` (policies/utils), which rejects those values
202
- * up front.
203
- *
204
- * @throws {TypeError} On circular references (mirroring `JSON.stringify`).
205
- */
206
- function stableStringify(value) {
207
- return JSON.stringify(sortKeysDeep(value, /* @__PURE__ */ new WeakSet()));
208
- }
209
- function payloadHash(value) {
210
- return sha256Hex(stableStringify(value));
211
- }
212
- //#endregion
213
- //#region src/core/errors/unexpected-error.ts
214
- var UnexpectedError = class extends AppError {
215
- constructor(message = "Unexpected error", cause, options) {
216
- super(message, ErrorCodes.unexpected, {
217
- cause,
218
- ...options
219
- });
220
- }
221
- };
222
- //#endregion
223
1
  //#region src/core/exceptions/validation-code.ts
224
2
  var ValidationCode = class ValidationCode {
225
3
  constructor(value) {
@@ -272,6 +50,6 @@ var ValidationCode = class ValidationCode {
272
50
  }
273
51
  };
274
52
  //#endregion
275
- export { stableStringify as a, ErrorCodes as c, sha256Hex as i, serializationErrorCode as l, UnexpectedError as n, AppError as o, payloadHash as r, assertJsonSafeMetadata as s, ValidationCode as t };
53
+ export { ValidationCode as t };
276
54
 
277
55
  //# sourceMappingURL=validation-code.js.map
@@ -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\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,eAAe;EACX,mBAAmB;EACnB,iBAAiB;CACrB;CACA,UAAU;EACN,SAAS;EACT,aAAa;CACjB;CACA,YAAY;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;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/exceptions/validation-code.ts"],"sourcesContent":["// 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":";AAGA,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,46 +1,7 @@
1
+ import { a as JsonSafeRecord, n as AppErrorOptions, r as ErrorSeverity, t as AppError } from "./app-error.js";
2
+ import { t as ValidationCode } from "./validation-code.js";
1
3
  import { t as ValidationField } from "./validation-field.js";
2
4
 
3
- //#region src/core/errors/types.d.ts
4
- type ErrorSeverity = "low" | "medium" | "high" | "critical";
5
- type JsonSafePrimitive = string | number | boolean | null;
6
- type JsonSafeValue = JsonSafePrimitive | JsonSafeValue[] | {
7
- [key: string]: JsonSafeValue;
8
- };
9
- type JsonSafeRecord = Record<string, JsonSafeValue>;
10
- /**
11
- * Options accepted by the AppError constructor.
12
- * Subclasses can extend or pick from this type.
13
- */
14
- type AppErrorOptions = {
15
- /** Original error or exception that caused this error. */
16
- cause?: unknown;
17
- /** Arbitrary key-value metadata (will be sanitized to JSON-safe values). */
18
- metadata?: Record<string, unknown>;
19
- /** Error category/type for grouping (e.g., "authentication", "validation"). */
20
- type?: string;
21
- /** severity level for alerting/logging prioritization. */
22
- severity?: ErrorSeverity;
23
- /**
24
- * Identifies a single execution "story" in the system. All operations
25
- * related to the same logical flow must share the same correlationId.
26
- */
27
- correlationId?: string;
28
- /**
29
- * Identifies a specific technical request attempt (each retry may produce
30
- * a new requestId), even when the correlationId stays the same.
31
- */
32
- requestId?: string;
33
- /**
34
- * Identifies a unique business intent (idempotency key); stays the same
35
- * across technical retries and multiple requests that represent the same intent.
36
- */
37
- commandId?: string;
38
- /** ISO timestamp of when the error was created (defaults to now). */
39
- createdAtIso?: string;
40
- /** Safe message that can be exposed to end users (no internal details). */
41
- publicMessage?: string;
42
- };
43
- //#endregion
44
5
  //#region src/core/errors/error-codes.d.ts
45
6
  declare const ErrorCodes: {
46
7
  readonly authentication: {
@@ -102,71 +63,6 @@ declare function serializationErrorCode(direction: SerializationCodeDirection, c
102
63
  */
103
64
  declare function assertJsonSafeMetadata(input: unknown): JsonSafeRecord;
104
65
  //#endregion
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
- */
122
- declare abstract class AppError extends Error {
123
- readonly code: string;
124
- readonly cause?: unknown;
125
- readonly metadata?: JsonSafeRecord;
126
- readonly type?: string;
127
- readonly severity?: ErrorSeverity;
128
- readonly createdAtIso: string;
129
- readonly publicMessage?: string;
130
- /**
131
- * Identifies a single execution "story" in the system. All operations
132
- * related to the same logical flow must share the same correlationId.
133
- */
134
- readonly correlationId?: string;
135
- /**
136
- * Identifies a specific technical request attempt (each retry may produce
137
- * a new requestId), even when the correlationId stays the same.
138
- */
139
- readonly requestId?: string;
140
- /**
141
- * Marks the business intent / idempotency key; stays the same across
142
- * technical retries and multiple requests that represent the same intent.
143
- */
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
- */
162
- protected constructor(message: string, code: string, options?: AppErrorOptions);
163
- /**
164
- * Returns a JSON-safe representation of the error.
165
- * Does NOT include `cause` by default (to avoid leaking internal details).
166
- */
167
- toJSON(): Record<string, unknown>;
168
- }
169
- //#endregion
170
66
  //#region src/core/errors/authentication-error.d.ts
171
67
  type AuthenticationErrorReason = "missing_token" | "malformed_token" | "invalid_token" | "expired_token" | "revoked_token" | "invalid_credentials" | "session_not_found" | "session_expired" | "unknown";
172
68
  type AuthenticationErrorMetadata = {
@@ -854,27 +750,6 @@ declare class UnexpectedError extends AppError {
854
750
  constructor(message?: string, cause?: unknown, options?: Omit<AppErrorOptions, "cause">);
855
751
  }
856
752
  //#endregion
857
- //#region src/core/exceptions/validation-code.d.ts
858
- declare class ValidationCode {
859
- readonly value: string;
860
- private constructor();
861
- static of(value: string): ValidationCode;
862
- static readonly BLANK: ValidationCode;
863
- static readonly REQUIRED: ValidationCode;
864
- static readonly INVALID_FORMAT: ValidationCode;
865
- static readonly INVALID_CHARACTERS: ValidationCode;
866
- static readonly INVALID_LENGTH: ValidationCode;
867
- static readonly TOO_SHORT: ValidationCode;
868
- static readonly TOO_LONG: ValidationCode;
869
- static readonly OUT_OF_RANGE: ValidationCode;
870
- static readonly INVALID_CHECKSUM: ValidationCode;
871
- static readonly INVALID_CHECKING_DIGIT: ValidationCode;
872
- static readonly ALREADY_EXISTS: ValidationCode;
873
- static readonly NOT_FOUND: ValidationCode;
874
- static readonly NOT_ALLOWED: ValidationCode;
875
- static readonly UNEXPECTED: ValidationCode;
876
- }
877
- //#endregion
878
753
  //#region src/core/errors/validation-error.d.ts
879
754
  /**
880
755
  * Raised when a single input fails a validation rule — the canonical
@@ -898,5 +773,5 @@ declare class ValidationError extends AppError {
898
773
  constructor(field: ValidationField, code: ValidationCode, message: string, options?: AppErrorOptions);
899
774
  }
900
775
  //#endregion
901
- export { ErrorCodes as $, IdempotencyPayloadMismatchError as A, UniqueConstraintViolation as B, IntegrationErrorMetadata as C, IdempotencyFailureKind as D, IdempotencyErrorMetadata as E, AlreadyExistsError as F, AuthorizationErrorMetadata as G, translateUniqueViolationToDuplicate as H, ConflictError as I, AuthenticationError as J, AuthorizationErrorReason as K, ConflictErrorMetadata as L, payloadHash as M, sha256Hex as N, IdempotencyInProgressError as O, stableStringify as P, assertJsonSafeMetadata as Q, ConflictKind as R, IntegrationError as S, IdempotencyError as T, BusinessRuleViolationError as U, UniqueConstraintViolationError as V, AuthorizationError as W, AuthenticationErrorReason as X, AuthenticationErrorMetadata as Y, AppError as Z, SerializationMessages as _, TemporalError as a, JsonSafeValue as at, NotFoundError as b, TemporalPrecision as c, SerializationCodes as d, serializationErrorCode as et, SerializationDirection as f, SerializationInError as g, SerializationFailureCategory as h, NotYetValidError as i, JsonSafeRecord as it, IdempotencyReplayNotSupportedError as j, IdempotencyKeyMissingError as k, evaluateTemporalWindow as l, SerializationErrorMetadata as m, UnexpectedError as n, ErrorSeverity as nt, TemporalErrorMetadata as o, SerializationError as p, AuthorizationRequirement as q, ExpiredError as r, JsonSafePrimitive as rt, TemporalKind as s, ValidationError as t, AppErrorOptions as tt, SerializationBoundary as u, SerializationOutError as v, IntegrationErrorReason as w, LegacyIncompatibleError as x, safePreview as y, DuplicateError as z };
776
+ export { serializationErrorCode as $, IdempotencyPayloadMismatchError as A, UniqueConstraintViolation as B, IntegrationErrorMetadata as C, IdempotencyFailureKind as D, IdempotencyErrorMetadata as E, AlreadyExistsError as F, AuthorizationErrorMetadata as G, translateUniqueViolationToDuplicate as H, ConflictError as I, AuthenticationError as J, AuthorizationErrorReason as K, ConflictErrorMetadata as L, payloadHash as M, sha256Hex as N, IdempotencyInProgressError as O, stableStringify as P, ErrorCodes as Q, ConflictKind as R, IntegrationError as S, IdempotencyError as T, BusinessRuleViolationError as U, UniqueConstraintViolationError as V, AuthorizationError as W, AuthenticationErrorReason as X, AuthenticationErrorMetadata as Y, assertJsonSafeMetadata as Z, SerializationMessages as _, TemporalError as a, NotFoundError as b, TemporalPrecision as c, SerializationCodes as d, SerializationDirection as f, SerializationInError as g, SerializationFailureCategory as h, NotYetValidError as i, IdempotencyReplayNotSupportedError as j, IdempotencyKeyMissingError as k, evaluateTemporalWindow as l, SerializationErrorMetadata as m, UnexpectedError as n, TemporalErrorMetadata as o, SerializationError as p, AuthorizationRequirement as q, ExpiredError as r, TemporalKind as s, ValidationError as t, SerializationBoundary as u, SerializationOutError as v, IntegrationErrorReason as w, LegacyIncompatibleError as x, safePreview as y, DuplicateError as z };
902
777
  //# sourceMappingURL=validation-error.d.ts.map
@@ -1,4 +1,4 @@
1
- import { c as ErrorCodes, l as serializationErrorCode, o as AppError } from "./validation-code.js";
1
+ import { a as serializationErrorCode, i as ErrorCodes, n as AppError } from "./unexpected-error.js";
2
2
  //#region src/core/errors/authentication-error.ts
3
3
  var AuthenticationError = class AuthenticationError extends AppError {
4
4
  constructor(params) {
@@ -206,24 +206,6 @@ function extractMetadataOnly(input) {
206
206
  return metadata;
207
207
  }
208
208
  //#endregion
209
- //#region src/core/errors/business-rule-violation-error.ts
210
- var BusinessRuleViolationError = class extends AppError {
211
- constructor(rule, message, detail, options) {
212
- const baseMetadata = detail ? {
213
- rule,
214
- detail
215
- } : { rule };
216
- const mergedMetadata = options?.metadata ? {
217
- ...baseMetadata,
218
- ...options.metadata
219
- } : baseMetadata;
220
- super(message, ErrorCodes.businessRuleViolation, {
221
- ...options,
222
- metadata: mergedMetadata
223
- });
224
- }
225
- };
226
- //#endregion
227
209
  //#region src/core/errors/conflict-error.ts
228
210
  /**
229
211
  * Base for errors that signal a state conflict — the request collides with data
@@ -678,38 +660,6 @@ var LegacyIncompatibleError = class extends AppError {
678
660
  }
679
661
  };
680
662
  //#endregion
681
- //#region src/core/errors/not-found-error.ts
682
- /**
683
- * Raised when a requested resource does not exist. Maps naturally onto an HTTP
684
- * 404 at the edge, but stays transport-agnostic here.
685
- *
686
- * The `resource` name builds the message (`"<resource> not found"`) and, with
687
- * the optional lookup `criteria`, lands in the metadata so logs show *what* was
688
- * searched for without the caller having to restate it in the message.
689
- */
690
- var NotFoundError = class extends AppError {
691
- /**
692
- * @param resource - Human-readable name of the missing resource (e.g. `"Order"`).
693
- * @param criteria - Optional lookup keys used in the search; recorded in
694
- * metadata to aid debugging. Avoid putting sensitive values here.
695
- * @param options - Optional cause, correlation ids, and extra metadata.
696
- */
697
- constructor(resource, criteria, options) {
698
- const baseMetadata = criteria ? {
699
- resource,
700
- criteria
701
- } : { resource };
702
- const mergedMetadata = options?.metadata ? {
703
- ...baseMetadata,
704
- ...options.metadata
705
- } : baseMetadata;
706
- super(`${resource} not found`, ErrorCodes.notFound, {
707
- ...options,
708
- metadata: mergedMetadata
709
- });
710
- }
711
- };
712
- //#endregion
713
663
  //#region src/core/errors/serialization-error.ts
714
664
  var SerializationError = class extends AppError {
715
665
  constructor(input) {
@@ -916,6 +866,6 @@ var ValidationError = class extends AppError {
916
866
  }
917
867
  };
918
868
  //#endregion
919
- export { UniqueConstraintViolationError as C, AuthenticationError as D, AuthorizationError as E, DuplicateError as S, BusinessRuleViolationError as T, IdempotencyKeyMissingError as _, evaluateTemporalWindow as a, AlreadyExistsError as b, SerializationInError as c, safePreview as d, NotFoundError as f, IdempotencyInProgressError as g, IdempotencyError as h, TemporalError as i, SerializationMessages as l, IntegrationError as m, ExpiredError as n, SerializationCodes as o, LegacyIncompatibleError as p, NotYetValidError as r, SerializationError as s, ValidationError as t, SerializationOutError as u, IdempotencyPayloadMismatchError as v, translateUniqueViolationToDuplicate as w, ConflictError as x, IdempotencyReplayNotSupportedError as y };
869
+ export { translateUniqueViolationToDuplicate as C, UniqueConstraintViolationError as S, AuthenticationError as T, IdempotencyPayloadMismatchError as _, evaluateTemporalWindow as a, ConflictError as b, SerializationInError as c, safePreview as d, LegacyIncompatibleError as f, IdempotencyKeyMissingError as g, IdempotencyInProgressError as h, TemporalError as i, SerializationMessages as l, IdempotencyError as m, ExpiredError as n, SerializationCodes as o, IntegrationError as p, NotYetValidError as r, SerializationError as s, ValidationError as t, SerializationOutError as u, IdempotencyReplayNotSupportedError as v, AuthorizationError as w, DuplicateError as x, AlreadyExistsError as y };
920
870
 
921
871
  //# sourceMappingURL=validation-error.js.map