@cullet/erp-core 1.1.0 → 1.3.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 (196) hide show
  1. package/KIT_CONTEXT.md +1 -67
  2. package/dist/app-error.d.cts +108 -0
  3. package/dist/application/index.cjs +26 -0
  4. package/dist/application/index.d.cts +2 -0
  5. package/dist/application/index.d.ts +1 -1
  6. package/dist/application/index.js +2 -1
  7. package/dist/domain/index.cjs +16 -0
  8. package/dist/domain/index.d.cts +3 -0
  9. package/dist/domain/index.d.ts +3 -0
  10. package/dist/domain/index.js +3 -0
  11. package/dist/domain-event-contracts.cjs +33 -0
  12. package/dist/domain-event-contracts.cjs.map +1 -0
  13. package/dist/domain-event-contracts.d.cts +27 -0
  14. package/dist/domain-event-contracts.d.ts +27 -0
  15. package/dist/domain-event-contracts.js +22 -0
  16. package/dist/domain-event-contracts.js.map +1 -0
  17. package/dist/domain-exception.cjs +17 -0
  18. package/dist/domain-exception.cjs.map +1 -0
  19. package/dist/domain-exception.d.cts +7 -0
  20. package/dist/domain-exception.d.ts +7 -0
  21. package/dist/domain-exception.js +12 -0
  22. package/dist/domain-exception.js.map +1 -0
  23. package/dist/errors/index.cjs +41 -0
  24. package/dist/errors/index.d.cts +3 -0
  25. package/dist/errors/index.js +1 -1
  26. package/dist/exceptions/index.cjs +17 -0
  27. package/dist/exceptions/index.d.cts +5 -0
  28. package/dist/exceptions/index.d.ts +5 -0
  29. package/dist/exceptions/index.js +7 -0
  30. package/dist/exceptions/validation-field.cjs +3 -0
  31. package/dist/exceptions/validation-field.d.cts +2 -0
  32. package/dist/gate-engine-registry.cjs +308 -0
  33. package/dist/gate-engine-registry.cjs.map +1 -0
  34. package/dist/gate-engine-registry.d.cts +81 -0
  35. package/dist/gate-engine-registry.d.ts +2 -1
  36. package/dist/gate-engine-registry.js +2 -1
  37. package/dist/gate-engine-registry.js.map +1 -1
  38. package/dist/gate-types.d.cts +171 -0
  39. package/dist/gate-types.d.ts +3 -139
  40. package/dist/gate-v1-payload.schema.cjs +638 -0
  41. package/dist/gate-v1-payload.schema.cjs.map +1 -0
  42. package/dist/gate-v1-payload.schema.js +2 -116
  43. package/dist/gate-v1-payload.schema.js.map +1 -1
  44. package/dist/hashing.cjs +66 -0
  45. package/dist/hashing.cjs.map +1 -0
  46. package/dist/immutable.cjs +77 -0
  47. package/dist/immutable.cjs.map +1 -0
  48. package/dist/immutable.d.cts +6 -0
  49. package/dist/immutable.d.ts +6 -0
  50. package/dist/immutable.js +54 -0
  51. package/dist/immutable.js.map +1 -0
  52. package/dist/index.cjs +163 -0
  53. package/dist/index.cjs.map +1 -0
  54. package/dist/index.d.cts +30 -0
  55. package/dist/index.d.ts +15 -160
  56. package/dist/index.js +19 -176
  57. package/dist/index.js.map +1 -1
  58. package/dist/invalid-state-transition-exception.cjs +47 -0
  59. package/dist/invalid-state-transition-exception.cjs.map +1 -0
  60. package/dist/invalid-state-transition-exception.js +30 -0
  61. package/dist/invalid-state-transition-exception.js.map +1 -0
  62. package/dist/invariant-violation-exception.cjs +16 -0
  63. package/dist/invariant-violation-exception.cjs.map +1 -0
  64. package/dist/invariant-violation-exception.js +11 -0
  65. package/dist/invariant-violation-exception.js.map +1 -0
  66. package/dist/not-found-error.cjs +65 -0
  67. package/dist/not-found-error.cjs.map +1 -0
  68. package/dist/not-found-error.js +1 -1
  69. package/dist/outcome.cjs +97 -0
  70. package/dist/outcome.cjs.map +1 -0
  71. package/dist/outcome.d.cts +140 -0
  72. package/dist/outcome.d.ts +140 -0
  73. package/dist/outcome.js +1 -1
  74. package/dist/parse-gate-payload.d.cts +62 -0
  75. package/dist/parse-gate-payload.d.ts +2 -1
  76. package/dist/path.d.cts +90 -0
  77. package/dist/path.d.ts +2 -1
  78. package/dist/plugin.cjs +79 -0
  79. package/dist/plugin.cjs.map +1 -0
  80. package/dist/plugin.d.cts +85 -0
  81. package/dist/plugin.d.ts +85 -0
  82. package/dist/plugin.js +74 -0
  83. package/dist/plugin.js.map +1 -0
  84. package/dist/plugins/index.cjs +3 -0
  85. package/dist/plugins/index.d.cts +2 -0
  86. package/dist/plugins/index.d.ts +2 -0
  87. package/dist/plugins/index.js +2 -0
  88. package/dist/policies/engines/index.cjs +10 -0
  89. package/dist/policies/engines/index.d.cts +4 -0
  90. package/dist/policies/engines/index.d.ts +1 -1
  91. package/dist/policies/engines/v1/gate/index.cjs +91 -0
  92. package/dist/policies/engines/v1/gate/index.cjs.map +1 -0
  93. package/dist/policies/engines/v1/gate/index.d.cts +121 -0
  94. package/dist/policies/engines/v1/gate/index.d.ts +2 -1
  95. package/dist/policies/engines/v1/gate/index.js +2 -1
  96. package/dist/policies/engines/v1/gate/index.js.map +1 -1
  97. package/dist/policies/index.cjs +41 -0
  98. package/dist/policies/index.d.cts +7 -0
  99. package/dist/policies/index.d.ts +2 -1
  100. package/dist/policies/index.js +2 -1
  101. package/dist/policy-service.cjs +1190 -0
  102. package/dist/policy-service.cjs.map +1 -0
  103. package/dist/policy-service.d.cts +559 -0
  104. package/dist/policy-service.d.ts +2 -1
  105. package/dist/policy-service.js +6 -3
  106. package/dist/policy-service.js.map +1 -1
  107. package/dist/result/index.cjs +7 -0
  108. package/dist/result/index.d.cts +2 -0
  109. package/dist/result/index.d.ts +2 -0
  110. package/dist/result/index.js +3 -0
  111. package/dist/result.cjs +135 -0
  112. package/dist/result.cjs.map +1 -0
  113. package/dist/result.js +118 -0
  114. package/dist/result.js.map +1 -0
  115. package/dist/ruleset-registry.cjs +47 -0
  116. package/dist/ruleset-registry.cjs.map +1 -0
  117. package/dist/ruleset-registry.js +42 -0
  118. package/dist/ruleset-registry.js.map +1 -0
  119. package/dist/rulesets/index.cjs +3 -0
  120. package/dist/rulesets/index.d.cts +2 -0
  121. package/dist/rulesets/index.d.ts +2 -0
  122. package/dist/rulesets/index.js +2 -0
  123. package/dist/temporal-guards.cjs +32 -0
  124. package/dist/temporal-guards.cjs.map +1 -0
  125. package/dist/temporal-guards.js +2 -17
  126. package/dist/temporal-guards.js.map +1 -1
  127. package/dist/temporal-use-case.cjs +191 -0
  128. package/dist/temporal-use-case.cjs.map +1 -0
  129. package/dist/temporal-use-case.d.cts +304 -0
  130. package/dist/temporal-use-case.d.ts +4 -9
  131. package/dist/temporal-use-case.js +6 -140
  132. package/dist/temporal-use-case.js.map +1 -1
  133. package/dist/unexpected-error.cjs +208 -0
  134. package/dist/unexpected-error.cjs.map +1 -0
  135. package/dist/unexpected-error.js +179 -0
  136. package/dist/unexpected-error.js.map +1 -0
  137. package/dist/use-case.cjs +96 -0
  138. package/dist/use-case.cjs.map +1 -0
  139. package/dist/use-case.js +91 -0
  140. package/dist/use-case.js.map +1 -0
  141. package/dist/uuid-identifier.cjs +65 -0
  142. package/dist/uuid-identifier.cjs.map +1 -0
  143. package/dist/uuid-identifier.d.cts +230 -0
  144. package/dist/uuid-identifier.d.ts +230 -0
  145. package/dist/uuid-identifier.js +60 -0
  146. package/dist/uuid-identifier.js.map +1 -0
  147. package/dist/validation-code.cjs +60 -0
  148. package/dist/validation-code.cjs.map +1 -0
  149. package/dist/validation-code.d.cts +23 -0
  150. package/dist/validation-code.d.ts +23 -0
  151. package/dist/validation-code.js +1 -177
  152. package/dist/validation-code.js.map +1 -1
  153. package/dist/validation-error.cjs +1020 -0
  154. package/dist/validation-error.cjs.map +1 -0
  155. package/dist/validation-error.d.cts +777 -0
  156. package/dist/validation-error.d.ts +1 -21
  157. package/dist/validation-error.js +1 -1
  158. package/dist/validation-exception.cjs +41 -0
  159. package/dist/validation-exception.cjs.map +1 -0
  160. package/dist/validation-exception.d.cts +50 -0
  161. package/dist/validation-exception.d.ts +50 -0
  162. package/dist/validation-exception.js +8 -2
  163. package/dist/validation-exception.js.map +1 -1
  164. package/dist/validation-field.cjs +28 -0
  165. package/dist/validation-field.cjs.map +1 -0
  166. package/dist/validation-field.d.cts +12 -0
  167. package/dist/value-object-ruleset.contracts.d.cts +36 -0
  168. package/dist/value-object-ruleset.contracts.d.ts +36 -0
  169. package/dist/value-object.cjs +208 -0
  170. package/dist/value-object.cjs.map +1 -0
  171. package/dist/value-object.js +191 -0
  172. package/dist/value-object.js.map +1 -0
  173. package/dist/version.d.cts +10 -0
  174. package/dist/version.d.ts +10 -0
  175. package/dist/versioning/index.cjs +7 -0
  176. package/dist/versioning/index.d.cts +3 -0
  177. package/dist/versioning/index.d.ts +3 -0
  178. package/dist/versioning/index.js +3 -0
  179. package/meta.json +18 -3
  180. package/package.json +165 -17
  181. package/src/core/domain/rulesets/index.ts +7 -0
  182. package/src/core/domain/uuid-identifier.ts +72 -0
  183. package/src/core/domain/value-object.ts +37 -5
  184. package/src/core/exceptions/index.ts +13 -0
  185. package/src/core/index.ts +14 -2
  186. package/src/core/plugins/index.ts +7 -0
  187. package/src/core/plugins/plugin.ts +99 -0
  188. package/src/core/plugins/types.ts +53 -0
  189. package/src/core/versioning/index.ts +14 -0
  190. package/src/domain/index.ts +7 -0
  191. package/src/exceptions/index.ts +1 -0
  192. package/src/plugins/index.ts +1 -0
  193. package/src/result/index.ts +2 -0
  194. package/src/rulesets/index.ts +1 -0
  195. package/src/version.ts +1 -1
  196. package/src/versioning/index.ts +1 -0
@@ -0,0 +1,191 @@
1
+ const require_unexpected_error = require("./unexpected-error.cjs");
2
+ const require_not_found_error = require("./not-found-error.cjs");
3
+ const require_validation_code = require("./validation-code.cjs");
4
+ const require_validation_field = require("./validation-field.cjs");
5
+ const require_validation_exception = require("./validation-exception.cjs");
6
+ const require_immutable = require("./immutable.cjs");
7
+ const require_use_case = require("./use-case.cjs");
8
+ const require_temporal_guards = require("./temporal-guards.cjs");
9
+ //#region src/core/application/commands/requested-by.ts
10
+ const REQUESTED_BY_FIELD = require_validation_field.ValidationField.of("requestedBy");
11
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
12
+ const SYSTEM_IDENTITY_PATTERN = /^system:[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
13
+ var RequestedBy = class RequestedBy {
14
+ constructor(kind, raw) {
15
+ this.kind = kind;
16
+ this.raw = raw;
17
+ Object.freeze(this);
18
+ }
19
+ /** Builds from a human user ID (must be a UUID). */
20
+ static fromUser(userId) {
21
+ if (!UUID_PATTERN.test(userId)) throw new require_validation_exception.InvalidValueException(REQUESTED_BY_FIELD, require_validation_code.ValidationCode.INVALID_FORMAT, `requestedBy: user identity must be a UUID, got "${userId}"`);
22
+ return new RequestedBy("user", userId);
23
+ }
24
+ /**
25
+ * Builds from a system identity.
26
+ * Only accepts the format "system:<job>", where <job> matches [a-z][a-z0-9]*(-[a-z0-9]+)*.
27
+ */
28
+ static fromSystem(systemIdentity) {
29
+ if (!SYSTEM_IDENTITY_PATTERN.test(systemIdentity)) throw new require_validation_exception.InvalidValueException(REQUESTED_BY_FIELD, require_validation_code.ValidationCode.INVALID_FORMAT, `requestedBy: system identity must match "system:<job>" (e.g. "system:late-fee-job"), got "${systemIdentity}"`);
30
+ return new RequestedBy("system", systemIdentity);
31
+ }
32
+ /**
33
+ * Infers the kind from the raw value.
34
+ * Use when the origin (user vs system) is not known at the call-site.
35
+ */
36
+ static parse(raw) {
37
+ if (UUID_PATTERN.test(raw)) return new RequestedBy("user", raw);
38
+ if (SYSTEM_IDENTITY_PATTERN.test(raw)) return new RequestedBy("system", raw);
39
+ throw new require_validation_exception.InvalidValueException(REQUESTED_BY_FIELD, require_validation_code.ValidationCode.INVALID_FORMAT, `requestedBy must be a UUID (user) or "system:<job>" (system), got "${raw}"`);
40
+ }
41
+ get isUser() {
42
+ return this.kind === "user";
43
+ }
44
+ get isSystem() {
45
+ return this.kind === "system";
46
+ }
47
+ toString() {
48
+ return this.raw;
49
+ }
50
+ };
51
+ //#endregion
52
+ //#region src/core/application/commands/command.ts
53
+ /**
54
+ * Base for use cases that **mutate state** (writes), following CQS.
55
+ *
56
+ * - `Input extends CommandInput` ensures every mutation records who triggered it.
57
+ * - `Output extends Result<unknown, unknown>` ensures business errors are
58
+ * explicit values, never thrown exceptions.
59
+ *
60
+ * The Command/Query distinction is semantic: the type declares the intent
61
+ * before any implementation exists, guiding code review and API contracts.
62
+ */
63
+ let Command = class Command extends require_use_case.UseCase {};
64
+ Command = require_immutable.__decorate([require_immutable.version("1.0")], Command);
65
+ //#endregion
66
+ //#region src/core/application/policy-error-mapper.ts
67
+ function mapPolicyEvaluationError(err) {
68
+ switch (err.kind) {
69
+ case "INVALID_CONTEXT": return new require_not_found_error.BusinessRuleViolationError(`policy.${err.stage.toLowerCase()}`, err.message, {
70
+ policyKey: err.policyKey,
71
+ stage: err.stage
72
+ }, { cause: err.cause });
73
+ case "INVALID_POLICY_KEY": return new require_not_found_error.BusinessRuleViolationError("policy.invalid_key", err.message, { rawPolicyKey: err.rawPolicyKey }, { cause: err.cause });
74
+ case "POLICY_NOT_FOUND": return new require_not_found_error.NotFoundError("Policy", { policyKey: err.policyKey }, { cause: err.cause });
75
+ case "POLICY_DEFINITION_NOT_FOUND": return new require_not_found_error.NotFoundError("PolicyDefinition", {
76
+ policyKey: err.policyKey,
77
+ contextVersion: err.contextVersion,
78
+ asOf: err.asOf.toISOString()
79
+ }, { cause: err.cause });
80
+ case "POLICY_VARIANT_NOT_FOUND": return new require_not_found_error.NotFoundError("PolicyVariant", {
81
+ policyKey: err.policyKey,
82
+ policyKind: err.policyKind,
83
+ payloadSchemaVersion: err.payloadSchemaVersion
84
+ }, { cause: err.cause });
85
+ case "ENGINE_FAILURE": return new require_unexpected_error.UnexpectedError(err.message, err.cause, { metadata: {
86
+ policyKey: err.policyKey,
87
+ engine: err.engine,
88
+ engineVersion: err.engineVersion
89
+ } });
90
+ }
91
+ }
92
+ //#endregion
93
+ //#region src/core/application/queries/query.ts
94
+ /**
95
+ * Base for use cases that **only read state**, with no side effects, following CQS.
96
+ *
97
+ * - `Data extends QueryOutput` prevents a query from declaring a `void` or
98
+ * `undefined` success payload, while still allowing primitive projections
99
+ * and `null` when that makes sense for the read. Failures stay explicit in
100
+ * `Result<T, E>`.
101
+ * - Override `cacheStrategy()` to declare how infrastructure should cache the
102
+ * result. By default, no cache is applied.
103
+ *
104
+ * A Query must never mutate persisted data — its execution must be idempotent
105
+ * and safe to call multiple times with the same input.
106
+ */
107
+ let Query = class Query extends require_use_case.UseCase {
108
+ cacheStrategy() {
109
+ return { kind: "NO_CACHE" };
110
+ }
111
+ };
112
+ Query = require_immutable.__decorate([require_immutable.version("1.0")], Query);
113
+ //#endregion
114
+ //#region src/core/application/temporal/temporal-context.ts
115
+ function assertTemporalContext(temporalContext, fieldName = "temporalContext") {
116
+ require_temporal_guards.assertValidDate(`${fieldName}.asOf`, temporalContext.asOf);
117
+ require_temporal_guards.assertValidDate(`${fieldName}.requestedAt`, temporalContext.requestedAt);
118
+ }
119
+ function createTemporalContext(input = {}) {
120
+ const requestedAt = input.requestedAt ?? /* @__PURE__ */ new Date();
121
+ const asOf = input.asOf ?? requestedAt;
122
+ assertTemporalContext({
123
+ asOf,
124
+ requestedAt
125
+ });
126
+ return require_immutable.makeImmutable({
127
+ asOf,
128
+ requestedAt
129
+ });
130
+ }
131
+ //#endregion
132
+ //#region src/core/application/temporal/temporal-use-case.ts
133
+ var TemporalUseCase = class extends require_use_case.UseCase {
134
+ resolveTemporalContext(input) {
135
+ return createTemporalContext(input.temporalContext);
136
+ }
137
+ buildPolicySeed(seed, temporalContext) {
138
+ return Object.freeze({
139
+ ...seed,
140
+ fields: {
141
+ ...seed.fields,
142
+ now: new Date(temporalContext.requestedAt.getTime())
143
+ }
144
+ });
145
+ }
146
+ };
147
+ //#endregion
148
+ Object.defineProperty(exports, "Command", {
149
+ enumerable: true,
150
+ get: function() {
151
+ return Command;
152
+ }
153
+ });
154
+ Object.defineProperty(exports, "Query", {
155
+ enumerable: true,
156
+ get: function() {
157
+ return Query;
158
+ }
159
+ });
160
+ Object.defineProperty(exports, "RequestedBy", {
161
+ enumerable: true,
162
+ get: function() {
163
+ return RequestedBy;
164
+ }
165
+ });
166
+ Object.defineProperty(exports, "TemporalUseCase", {
167
+ enumerable: true,
168
+ get: function() {
169
+ return TemporalUseCase;
170
+ }
171
+ });
172
+ Object.defineProperty(exports, "assertTemporalContext", {
173
+ enumerable: true,
174
+ get: function() {
175
+ return assertTemporalContext;
176
+ }
177
+ });
178
+ Object.defineProperty(exports, "createTemporalContext", {
179
+ enumerable: true,
180
+ get: function() {
181
+ return createTemporalContext;
182
+ }
183
+ });
184
+ Object.defineProperty(exports, "mapPolicyEvaluationError", {
185
+ enumerable: true,
186
+ get: function() {
187
+ return mapPolicyEvaluationError;
188
+ }
189
+ });
190
+
191
+ //# sourceMappingURL=temporal-use-case.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"temporal-use-case.cjs","names":["ValidationField","InvalidValueException","ValidationCode","UseCase","version","BusinessRuleViolationError","NotFoundError","UnexpectedError","UseCase","version","makeImmutable","UseCase"],"sources":["../src/core/application/commands/requested-by.ts","../src/core/application/commands/command.ts","../src/core/application/policy-error-mapper.ts","../src/core/application/queries/query.ts","../src/core/application/temporal/temporal-context.ts","../src/core/application/temporal/temporal-use-case.ts"],"sourcesContent":["import { ValidationCode } from \"../../exceptions/validation-code.js\";\nimport { InvalidValueException } from \"../../exceptions/validation-exception.js\";\nimport { ValidationField } from \"../../exceptions/validation-field.js\";\n\n// Identifies who triggered a Command.\n// Two valid formats:\n// - Human user: UUID v4 (e.g.: \"550e8400-e29b-41d4-a716-446655440000\")\n// - System identity: \"system:<job>\" where <job> is [a-z][a-z0-9]*(-[a-z0-9]+)*\n// (e.g.: \"system:late-fee-job\", \"system:email-sender\")\n//\n// The split between `fromUser` / `fromSystem` / `parse` exists to make intent\n// explicit at the call-site: whoever builds the value knows where it came from.\n\ntype RequestedByKind = \"user\" | \"system\";\n\nconst REQUESTED_BY_FIELD = ValidationField.of(\"requestedBy\");\n\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n// system:<job> where <job> starts with a lowercase letter and may have hyphens between segments\nconst SYSTEM_IDENTITY_PATTERN = /^system:[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\n\nclass RequestedBy {\n readonly kind: RequestedByKind;\n readonly raw: string;\n\n private constructor(kind: RequestedByKind, raw: string) {\n this.kind = kind;\n this.raw = raw;\n Object.freeze(this);\n }\n\n /** Builds from a human user ID (must be a UUID). */\n static fromUser(userId: string): RequestedBy {\n if (!UUID_PATTERN.test(userId)) {\n throw new InvalidValueException(\n REQUESTED_BY_FIELD,\n ValidationCode.INVALID_FORMAT,\n `requestedBy: user identity must be a UUID, got \"${userId}\"`,\n );\n }\n\n return new RequestedBy(\"user\", userId);\n }\n\n /**\n * Builds from a system identity.\n * Only accepts the format \"system:<job>\", where <job> matches [a-z][a-z0-9]*(-[a-z0-9]+)*.\n */\n static fromSystem(systemIdentity: string): RequestedBy {\n if (!SYSTEM_IDENTITY_PATTERN.test(systemIdentity)) {\n throw new InvalidValueException(\n REQUESTED_BY_FIELD,\n ValidationCode.INVALID_FORMAT,\n `requestedBy: system identity must match \"system:<job>\" (e.g. \"system:late-fee-job\"), got \"${systemIdentity}\"`,\n );\n }\n\n return new RequestedBy(\"system\", systemIdentity);\n }\n\n /**\n * Infers the kind from the raw value.\n * Use when the origin (user vs system) is not known at the call-site.\n */\n static parse(raw: string): RequestedBy {\n if (UUID_PATTERN.test(raw)) {\n return new RequestedBy(\"user\", raw);\n }\n\n if (SYSTEM_IDENTITY_PATTERN.test(raw)) {\n return new RequestedBy(\"system\", raw);\n }\n\n throw new InvalidValueException(\n REQUESTED_BY_FIELD,\n ValidationCode.INVALID_FORMAT,\n `requestedBy must be a UUID (user) or \"system:<job>\" (system), got \"${raw}\"`,\n );\n }\n\n get isUser(): boolean {\n return this.kind === \"user\";\n }\n\n get isSystem(): boolean {\n return this.kind === \"system\";\n }\n\n toString(): string {\n return this.raw;\n }\n}\n\nexport type { RequestedByKind };\nexport { RequestedBy };\n","import { UseCase } from \"../use-case.js\";\nimport { version } from \"../../versioning/version.js\";\nimport type { Result } from \"../../result/result.js\";\n\nimport { RequestedBy } from \"./requested-by.js\";\n\ninterface CommandInput {\n readonly requestedBy: RequestedBy;\n}\n\n/**\n * Base for use cases that **mutate state** (writes), following CQS.\n *\n * - `Input extends CommandInput` ensures every mutation records who triggered it.\n * - `Output extends Result<unknown, unknown>` ensures business errors are\n * explicit values, never thrown exceptions.\n *\n * The Command/Query distinction is semantic: the type declares the intent\n * before any implementation exists, guiding code review and API contracts.\n */\n@version(\"1.0\")\nabstract class Command<\n Input extends CommandInput,\n Output extends Result<unknown, unknown> = Result<void, never>,\n> extends UseCase<Input, Output> {}\n\nexport type { CommandInput };\nexport { Command };\n","import {\n type AppError,\n BusinessRuleViolationError,\n NotFoundError,\n UnexpectedError,\n} from \"../errors/index.js\";\nimport type { PolicyEvaluationError } from \"../policies/index.js\";\n\nexport function mapPolicyEvaluationError(err: PolicyEvaluationError): AppError {\n switch (err.kind) {\n case \"INVALID_CONTEXT\":\n return new BusinessRuleViolationError(\n `policy.${err.stage.toLowerCase()}`,\n err.message,\n { policyKey: err.policyKey, stage: err.stage },\n { cause: err.cause },\n );\n case \"INVALID_POLICY_KEY\":\n return new BusinessRuleViolationError(\n \"policy.invalid_key\",\n err.message,\n { rawPolicyKey: err.rawPolicyKey },\n { cause: err.cause },\n );\n case \"POLICY_NOT_FOUND\":\n return new NotFoundError(\n \"Policy\",\n { policyKey: err.policyKey },\n { cause: err.cause },\n );\n case \"POLICY_DEFINITION_NOT_FOUND\":\n return new NotFoundError(\n \"PolicyDefinition\",\n {\n policyKey: err.policyKey,\n contextVersion: err.contextVersion,\n asOf: err.asOf.toISOString(),\n },\n { cause: err.cause },\n );\n case \"POLICY_VARIANT_NOT_FOUND\":\n return new NotFoundError(\n \"PolicyVariant\",\n {\n policyKey: err.policyKey,\n policyKind: err.policyKind,\n payloadSchemaVersion: err.payloadSchemaVersion,\n },\n { cause: err.cause },\n );\n case \"ENGINE_FAILURE\":\n return new UnexpectedError(err.message, err.cause, {\n metadata: {\n policyKey: err.policyKey,\n engine: err.engine,\n engineVersion: err.engineVersion,\n },\n });\n }\n}\n","import { UseCase } from \"../use-case.js\";\nimport { version } from \"../../versioning/version.js\";\nimport type { AppError } from \"../../errors/index.js\";\nimport type { Result } from \"../../result/result.js\";\n\n/**\n * Paginated result of a list query.\n * Use as `Output` when the query returns a collection with pagination metadata.\n */\ninterface Page<T> {\n readonly items: readonly T[];\n readonly total: number;\n readonly page: number;\n readonly pageSize: number;\n}\n\n/**\n * Cache strategy declared by the query type.\n * Infrastructure reads this value to decide whether and how to cache the result.\n */\ntype CacheStrategy =\n | { readonly kind: \"NO_CACHE\" }\n | { readonly kind: \"TIME_TO_LIVE\"; readonly ttlMs: number }\n | { readonly kind: \"STALE_WHILE_REVALIDATE\"; readonly ttlMs: number };\n\ntype QueryOutput = object | string | number | boolean | bigint | symbol | null;\n\n/**\n * Base for use cases that **only read state**, with no side effects, following CQS.\n *\n * - `Data extends QueryOutput` prevents a query from declaring a `void` or\n * `undefined` success payload, while still allowing primitive projections\n * and `null` when that makes sense for the read. Failures stay explicit in\n * `Result<T, E>`.\n * - Override `cacheStrategy()` to declare how infrastructure should cache the\n * result. By default, no cache is applied.\n *\n * A Query must never mutate persisted data — its execution must be idempotent\n * and safe to call multiple times with the same input.\n */\n@version(\"1.0\")\nabstract class Query<\n Input = void,\n Data extends QueryOutput = never,\n Failure = AppError,\n> extends UseCase<Input, Result<Data, Failure>> {\n protected cacheStrategy(): CacheStrategy {\n return { kind: \"NO_CACHE\" };\n }\n}\n\nexport type { CacheStrategy, Page, QueryOutput };\nexport { Query };\n","import { makeImmutable } from \"../../shared/immutable.js\";\nimport { assertValidDate } from \"../../shared/temporal-guards.js\";\n\ninterface TemporalContext {\n readonly asOf: Date;\n readonly requestedAt: Date;\n}\n\ninterface CreateTemporalContextInput {\n readonly asOf?: Date;\n readonly requestedAt?: Date;\n}\n\nfunction assertTemporalContext(\n temporalContext: TemporalContext,\n fieldName: string = \"temporalContext\",\n): void {\n assertValidDate(`${fieldName}.asOf`, temporalContext.asOf);\n assertValidDate(`${fieldName}.requestedAt`, temporalContext.requestedAt);\n}\n\nfunction createTemporalContext(\n input: CreateTemporalContextInput = {},\n): TemporalContext {\n const requestedAt = input.requestedAt ?? new Date();\n const asOf = input.asOf ?? requestedAt;\n\n assertTemporalContext({ asOf, requestedAt });\n\n return makeImmutable({\n asOf,\n requestedAt,\n });\n}\n\nexport {\n assertTemporalContext,\n createTemporalContext,\n type CreateTemporalContextInput,\n type TemporalContext,\n};\n","import { UseCase } from \"../use-case.js\";\nimport type { ContextSeed } from \"../../policies/index.js\";\nimport type { Result } from \"../../result/result.js\";\n\nimport {\n createTemporalContext,\n type TemporalContext,\n} from \"./temporal-context.js\";\n\ninterface TemporalUseCaseInput {\n readonly temporalContext?: TemporalContext;\n}\n\n/**\n * A {@link ContextSeed} after temporal enrichment by\n * {@link TemporalUseCase.buildPolicySeed}: structurally identical to `TSeed`,\n * except `fields.now` is now guaranteed present as a `Date` (injected from the\n * resolved {@link TemporalContext}). Downstream policies can therefore read\n * `seed.fields.now` without a presence/type guard.\n */\ntype TemporalizedContextSeed<TSeed extends ContextSeed> = Omit<\n TSeed,\n \"fields\"\n> & {\n readonly fields: TSeed[\"fields\"] & { readonly now: Date };\n};\n\nabstract class TemporalUseCase<\n Input extends object,\n Output extends Result<unknown, unknown>,\n> extends UseCase<Input & TemporalUseCaseInput, Output> {\n protected resolveTemporalContext(\n input: Input & TemporalUseCaseInput,\n ): TemporalContext {\n return createTemporalContext(input.temporalContext);\n }\n\n protected buildPolicySeed<TSeed extends ContextSeed>(\n seed: TSeed,\n temporalContext: TemporalContext,\n ): TemporalizedContextSeed<TSeed> {\n return Object.freeze({\n ...seed,\n fields: {\n ...seed.fields,\n now: new Date(temporalContext.requestedAt.getTime()),\n },\n }) as TemporalizedContextSeed<TSeed>;\n }\n}\n\nexport type { TemporalizedContextSeed, TemporalUseCaseInput };\nexport { TemporalUseCase };\n"],"mappings":"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"}
@@ -0,0 +1,304 @@
1
+ import { n as ContractVersion } from "./version.cjs";
2
+ import { a as Result } from "./outcome.cjs";
3
+ import { t as AppError } from "./app-error.cjs";
4
+ import { b as ContextSeed, r as PolicyEvaluationResult, s as PolicyEvaluationError, t as EvaluateInput } from "./policy-service.cjs";
5
+ import { t as DeepReadonly } from "./immutable.cjs";
6
+
7
+ //#region src/core/application/ports/logger.port.d.ts
8
+ type LogPayload = Record<string, unknown>;
9
+ interface LoggerPort {
10
+ debug(message: string, payload?: LogPayload): void;
11
+ info(message: string, payload?: LogPayload): void;
12
+ warn(message: string, payload?: LogPayload): void;
13
+ error(message: string, payload?: LogPayload): void;
14
+ }
15
+ //#endregion
16
+ //#region src/core/application/ports/metrics.port.d.ts
17
+ type MetricLabels = Readonly<Record<string, string | number | boolean>>;
18
+ interface MetricsPort {
19
+ counter(name: string, value: number, labels?: MetricLabels): void;
20
+ gauge(name: string, value: number, labels?: MetricLabels): void;
21
+ histogram(name: string, value: number, labels?: MetricLabels): void;
22
+ }
23
+ //#endregion
24
+ //#region src/core/application/ports/tracer.port.d.ts
25
+ type TraceAttributeValue = string | number | boolean;
26
+ interface TraceSpan {
27
+ setAttribute(key: string, value: TraceAttributeValue): void;
28
+ recordException(error: unknown): void;
29
+ end(): void;
30
+ }
31
+ interface TracerPort {
32
+ startSpan(name: string, attributes?: Record<string, TraceAttributeValue>): TraceSpan;
33
+ }
34
+ //#endregion
35
+ //#region src/core/application/use-case.d.ts
36
+ type MaybePromise<T> = T | Promise<T>;
37
+ /**
38
+ * Observability adapters a use case may opt into.
39
+ *
40
+ * All fields are optional: a use case that provides none keeps the plain
41
+ * `input → Result` behavior with zero overhead. When provided, {@link UseCase.run}
42
+ * instruments every execution around `execute()` — opening a span, recording
43
+ * duration, counting outcomes, and logging business/unexpected failures.
44
+ */
45
+ interface UseCaseObservability {
46
+ readonly logger?: LoggerPort;
47
+ readonly metrics?: MetricsPort;
48
+ readonly tracer?: TracerPort;
49
+ }
50
+ declare abstract class UseCase<Input = void, Output extends Result<unknown, unknown> = Result<void, never>> {
51
+ static readonly CONTRACT_VERSION: ContractVersion;
52
+ get contractVersion(): ContractVersion;
53
+ /**
54
+ * Runs the use case.
55
+ *
56
+ * `run()` is the single seam every use case crosses, so it is where
57
+ * cross-cutting instrumentation lives. When {@link observability} exposes
58
+ * any adapter, the call to `execute()` is wrapped with tracing, metrics and
59
+ * failure logging; otherwise it delegates directly with no overhead.
60
+ *
61
+ * Observability is strictly side-effecting: a misbehaving adapter never
62
+ * changes the business result nor masks a thrown error — its own failures
63
+ * are swallowed.
64
+ */
65
+ run(input: Input): Promise<Output>;
66
+ /**
67
+ * Adapters used to instrument {@link run}. Override to opt a use case into
68
+ * tracing/metrics/logging. Returns an empty object by default, which keeps
69
+ * the plain delegating behavior.
70
+ */
71
+ protected observability(): UseCaseObservability;
72
+ /**
73
+ * Stable identity used for span names and metric labels. Defaults to the
74
+ * runtime class name; override when bundling/minification would otherwise
75
+ * erase a meaningful name.
76
+ */
77
+ protected get useCaseName(): string;
78
+ protected abstract execute(input: Input): MaybePromise<Output>;
79
+ private runInstrumented;
80
+ }
81
+ //#endregion
82
+ //#region src/core/application/commands/requested-by.d.ts
83
+ type RequestedByKind = "user" | "system";
84
+ declare class RequestedBy {
85
+ readonly kind: RequestedByKind;
86
+ readonly raw: string;
87
+ private constructor();
88
+ /** Builds from a human user ID (must be a UUID). */
89
+ static fromUser(userId: string): RequestedBy;
90
+ /**
91
+ * Builds from a system identity.
92
+ * Only accepts the format "system:<job>", where <job> matches [a-z][a-z0-9]*(-[a-z0-9]+)*.
93
+ */
94
+ static fromSystem(systemIdentity: string): RequestedBy;
95
+ /**
96
+ * Infers the kind from the raw value.
97
+ * Use when the origin (user vs system) is not known at the call-site.
98
+ */
99
+ static parse(raw: string): RequestedBy;
100
+ get isUser(): boolean;
101
+ get isSystem(): boolean;
102
+ toString(): string;
103
+ }
104
+ //#endregion
105
+ //#region src/core/application/commands/command.d.ts
106
+ interface CommandInput {
107
+ readonly requestedBy: RequestedBy;
108
+ }
109
+ /**
110
+ * Base for use cases that **mutate state** (writes), following CQS.
111
+ *
112
+ * - `Input extends CommandInput` ensures every mutation records who triggered it.
113
+ * - `Output extends Result<unknown, unknown>` ensures business errors are
114
+ * explicit values, never thrown exceptions.
115
+ *
116
+ * The Command/Query distinction is semantic: the type declares the intent
117
+ * before any implementation exists, guiding code review and API contracts.
118
+ */
119
+ declare abstract class Command<Input extends CommandInput, Output extends Result<unknown, unknown> = Result<void, never>> extends UseCase<Input, Output> {}
120
+ //#endregion
121
+ //#region src/core/application/ports/policy-port.d.ts
122
+ type PolicyEvaluationInput = EvaluateInput;
123
+ type PolicyEvaluationOutput = PolicyEvaluationResult;
124
+ /**
125
+ * Failure surfaced by {@link PolicyPort.evaluate}.
126
+ *
127
+ * This is the *post-mapping* boundary: the structured `PolicyEvaluationError`
128
+ * union produced inside the policies module is expected to have already been
129
+ * translated into an {@link AppError} (e.g. via `mapPolicyEvaluationError`)
130
+ * before it reaches a use case. Named distinctly from the policies-layer
131
+ * `PolicyEvaluationError` to avoid a collision on the public surface.
132
+ */
133
+ type PolicyPortError = AppError;
134
+ interface PolicyPort {
135
+ evaluate(input: PolicyEvaluationInput): Promise<Result<PolicyEvaluationOutput, PolicyPortError>>;
136
+ }
137
+ //#endregion
138
+ //#region src/core/application/ports/repository.port.d.ts
139
+ /**
140
+ * Persistence port for an aggregate in the imperative style: absence is
141
+ * modelled as `null`, and failures (missing row on delete, optimistic
142
+ * concurrency conflicts, infrastructure errors) surface as thrown exceptions.
143
+ *
144
+ * Prefer {@link ResultRepository} when you want those persistence outcomes to
145
+ * be explicit, recoverable values rather than exceptions.
146
+ */
147
+ interface Repository<TEntity, TId> {
148
+ findById(id: TId): Promise<TEntity | null>;
149
+ save(entity: TEntity): Promise<void>;
150
+ delete(id: TId): Promise<void>;
151
+ }
152
+ /**
153
+ * `Result`-returning counterpart of {@link Repository}, aligned with the
154
+ * "errors as values" philosophy used by `Command` / `UseCase`.
155
+ *
156
+ * Where {@link Repository} returns `Promise<void>` from `save`/`delete` and
157
+ * relies on thrown exceptions, this variant lets a repository *signal*
158
+ * recoverable persistence outcomes without breaking control flow — for
159
+ * example a `NotFoundError` when updating/deleting a missing aggregate, or a
160
+ * `ConflictError` on an optimistic-concurrency version mismatch. A successful
161
+ * write resolves to `Result.ok(undefined)`.
162
+ *
163
+ * `findById` keeps `null` as the "not present" answer to a lookup (not an
164
+ * error) while still wrapping the call in a `Result` so genuine failures
165
+ * (e.g. a connectivity error) stay in band.
166
+ *
167
+ * `TError` defaults to {@link AppError} to match the rest of the application
168
+ * boundary (see `PolicyPortError`); narrow it per repository when the failure
169
+ * set is known, e.g. `ResultRepository<Order, OrderId, NotFoundError | ConflictError>`.
170
+ */
171
+ interface ResultRepository<TEntity, TId, TError = AppError> {
172
+ findById(id: TId): Promise<Result<TEntity | null, TError>>;
173
+ save(entity: TEntity): Promise<Result<void, TError>>;
174
+ delete(id: TId): Promise<Result<void, TError>>;
175
+ }
176
+ //#endregion
177
+ //#region src/core/domain/temporal/transaction-time.d.ts
178
+ /**
179
+ * Represents transaction time (Transaction Time).
180
+ * Defines when the system learned about or recorded a piece of information.
181
+ * Useful for auditing and reconstructing system state at a specific past moment.
182
+ */
183
+ interface TransactionTime {
184
+ /** When the information was first recorded in the system. */
185
+ readonly recordedAt: Date;
186
+ /** When this information was superseded or invalidated by a newer version. */
187
+ readonly supersededAt?: Date;
188
+ }
189
+ //#endregion
190
+ //#region src/core/domain/temporal/valid-time.d.ts
191
+ /**
192
+ * Represents business time (Valid Time).
193
+ * Defines when a piece of information is considered true or in effect in the real world.
194
+ */
195
+ interface ValidTime {
196
+ /** Start of the validity window (inclusive). */
197
+ readonly from: Date;
198
+ /** End of the validity window (exclusive). When absent, the information is still in effect. */
199
+ readonly to?: Date;
200
+ }
201
+ //#endregion
202
+ //#region src/core/domain/temporal/temporal-snapshot.d.ts
203
+ /**
204
+ * Pairs a domain datum with its time dimensions (Business and Transaction).
205
+ * It is the representation of an entry in the append-only (historical) table.
206
+ */
207
+ interface TemporalSnapshot<T> {
208
+ /** The data or state captured by the snapshot. */
209
+ readonly data: DeepReadonly<T>;
210
+ /** Period during which this datum was valid in the real world. */
211
+ readonly validTime: ValidTime;
212
+ /** Period during which this record was the state known to the system. */
213
+ readonly txTime: TransactionTime;
214
+ }
215
+ //#endregion
216
+ //#region src/core/application/ports/temporal-repository.port.d.ts
217
+ type TemporalHistory<TEntity> = readonly TemporalSnapshot<TEntity>[];
218
+ interface TemporalRepository<TEntity, TId> extends Repository<TEntity, TId> {
219
+ findAsOf(id: TId, asOf: Date): Promise<TEntity | null>;
220
+ findAtTransaction(id: TId, txTime: Date): Promise<TEntity | null>;
221
+ findHistory(id: TId): Promise<TemporalHistory<TEntity>>;
222
+ save(entity: TEntity, validFrom?: Date): Promise<void>;
223
+ }
224
+ //#endregion
225
+ //#region src/core/application/policy-error-mapper.d.ts
226
+ declare function mapPolicyEvaluationError(err: PolicyEvaluationError): AppError;
227
+ //#endregion
228
+ //#region src/core/application/queries/query.d.ts
229
+ /**
230
+ * Paginated result of a list query.
231
+ * Use as `Output` when the query returns a collection with pagination metadata.
232
+ */
233
+ interface Page<T> {
234
+ readonly items: readonly T[];
235
+ readonly total: number;
236
+ readonly page: number;
237
+ readonly pageSize: number;
238
+ }
239
+ /**
240
+ * Cache strategy declared by the query type.
241
+ * Infrastructure reads this value to decide whether and how to cache the result.
242
+ */
243
+ type CacheStrategy = {
244
+ readonly kind: "NO_CACHE";
245
+ } | {
246
+ readonly kind: "TIME_TO_LIVE";
247
+ readonly ttlMs: number;
248
+ } | {
249
+ readonly kind: "STALE_WHILE_REVALIDATE";
250
+ readonly ttlMs: number;
251
+ };
252
+ type QueryOutput = object | string | number | boolean | bigint | symbol | null;
253
+ /**
254
+ * Base for use cases that **only read state**, with no side effects, following CQS.
255
+ *
256
+ * - `Data extends QueryOutput` prevents a query from declaring a `void` or
257
+ * `undefined` success payload, while still allowing primitive projections
258
+ * and `null` when that makes sense for the read. Failures stay explicit in
259
+ * `Result<T, E>`.
260
+ * - Override `cacheStrategy()` to declare how infrastructure should cache the
261
+ * result. By default, no cache is applied.
262
+ *
263
+ * A Query must never mutate persisted data — its execution must be idempotent
264
+ * and safe to call multiple times with the same input.
265
+ */
266
+ declare abstract class Query<Input = void, Data extends QueryOutput = never, Failure = AppError> extends UseCase<Input, Result<Data, Failure>> {
267
+ protected cacheStrategy(): CacheStrategy;
268
+ }
269
+ //#endregion
270
+ //#region src/core/application/temporal/temporal-context.d.ts
271
+ interface TemporalContext {
272
+ readonly asOf: Date;
273
+ readonly requestedAt: Date;
274
+ }
275
+ interface CreateTemporalContextInput {
276
+ readonly asOf?: Date;
277
+ readonly requestedAt?: Date;
278
+ }
279
+ declare function assertTemporalContext(temporalContext: TemporalContext, fieldName?: string): void;
280
+ declare function createTemporalContext(input?: CreateTemporalContextInput): TemporalContext;
281
+ //#endregion
282
+ //#region src/core/application/temporal/temporal-use-case.d.ts
283
+ interface TemporalUseCaseInput {
284
+ readonly temporalContext?: TemporalContext;
285
+ }
286
+ /**
287
+ * A {@link ContextSeed} after temporal enrichment by
288
+ * {@link TemporalUseCase.buildPolicySeed}: structurally identical to `TSeed`,
289
+ * except `fields.now` is now guaranteed present as a `Date` (injected from the
290
+ * resolved {@link TemporalContext}). Downstream policies can therefore read
291
+ * `seed.fields.now` without a presence/type guard.
292
+ */
293
+ type TemporalizedContextSeed<TSeed extends ContextSeed> = Omit<TSeed, "fields"> & {
294
+ readonly fields: TSeed["fields"] & {
295
+ readonly now: Date;
296
+ };
297
+ };
298
+ declare abstract class TemporalUseCase<Input extends object, Output extends Result<unknown, unknown>> extends UseCase<Input & TemporalUseCaseInput, Output> {
299
+ protected resolveTemporalContext(input: Input & TemporalUseCaseInput): TemporalContext;
300
+ protected buildPolicySeed<TSeed extends ContextSeed>(seed: TSeed, temporalContext: TemporalContext): TemporalizedContextSeed<TSeed>;
301
+ }
302
+ //#endregion
303
+ export { MetricLabels as A, RequestedByKind as C, TraceAttributeValue as D, UseCaseObservability as E, LogPayload as M, LoggerPort as N, TraceSpan as O, RequestedBy as S, UseCase as T, PolicyEvaluationOutput as _, TemporalContext as a, Command as b, CacheStrategy as c, mapPolicyEvaluationError as d, TemporalHistory as f, PolicyEvaluationInput as g, ResultRepository as h, CreateTemporalContextInput as i, MetricsPort as j, TracerPort as k, Page as l, Repository as m, TemporalUseCaseInput as n, assertTemporalContext as o, TemporalRepository as p, TemporalizedContextSeed as r, createTemporalContext as s, TemporalUseCase as t, Query as u, PolicyPort as v, MaybePromise as w, CommandInput as x, PolicyPortError as y };
304
+ //# sourceMappingURL=temporal-use-case.d.cts.map
@@ -1,10 +1,9 @@
1
- import { I as Result } from "./gate-types.js";
1
+ import { n as ContractVersion } from "./version.js";
2
+ import { a as Result } from "./outcome.js";
2
3
  import { t as AppError } from "./app-error.js";
3
4
  import { b as ContextSeed, r as PolicyEvaluationResult, s as PolicyEvaluationError, t as EvaluateInput } from "./policy-service.js";
5
+ import { t as DeepReadonly } from "./immutable.js";
4
6
 
5
- //#region src/core/versioning/version.d.ts
6
- type ContractVersion = `${number}.${number}`;
7
- //#endregion
8
7
  //#region src/core/application/ports/logger.port.d.ts
9
8
  type LogPayload = Record<string, unknown>;
10
9
  interface LoggerPort {
@@ -200,10 +199,6 @@ interface ValidTime {
200
199
  readonly to?: Date;
201
200
  }
202
201
  //#endregion
203
- //#region src/core/shared/immutable.d.ts
204
- type PrimitiveValue = bigint | boolean | null | number | string | symbol | undefined;
205
- type DeepReadonly<T> = T extends PrimitiveValue | Date ? T : T extends readonly (infer TItem)[] ? readonly DeepReadonly<TItem>[] : { readonly [TKey in keyof T]: DeepReadonly<T[TKey]> };
206
- //#endregion
207
202
  //#region src/core/domain/temporal/temporal-snapshot.d.ts
208
203
  /**
209
204
  * Pairs a domain datum with its time dimensions (Business and Transaction).
@@ -305,5 +300,5 @@ declare abstract class TemporalUseCase<Input extends object, Output extends Resu
305
300
  protected buildPolicySeed<TSeed extends ContextSeed>(seed: TSeed, temporalContext: TemporalContext): TemporalizedContextSeed<TSeed>;
306
301
  }
307
302
  //#endregion
308
- export { TracerPort as A, RequestedBy as C, UseCaseObservability as D, UseCase as E, ContractVersion as F, MetricsPort as M, LogPayload as N, TraceAttributeValue as O, LoggerPort as P, CommandInput as S, MaybePromise as T, PolicyEvaluationInput as _, TemporalContext as a, PolicyPortError as b, CacheStrategy as c, mapPolicyEvaluationError as d, TemporalHistory as f, ResultRepository as g, Repository as h, CreateTemporalContextInput as i, MetricLabels as j, TraceSpan as k, Page as l, DeepReadonly as m, TemporalUseCaseInput as n, assertTemporalContext as o, TemporalRepository as p, TemporalizedContextSeed as r, createTemporalContext as s, TemporalUseCase as t, Query as u, PolicyEvaluationOutput as v, RequestedByKind as w, Command as x, PolicyPort as y };
303
+ export { MetricLabels as A, RequestedByKind as C, TraceAttributeValue as D, UseCaseObservability as E, LogPayload as M, LoggerPort as N, TraceSpan as O, RequestedBy as S, UseCase as T, PolicyEvaluationOutput as _, TemporalContext as a, Command as b, CacheStrategy as c, mapPolicyEvaluationError as d, TemporalHistory as f, PolicyEvaluationInput as g, ResultRepository as h, CreateTemporalContextInput as i, MetricsPort as j, TracerPort as k, Page as l, Repository as m, TemporalUseCaseInput as n, assertTemporalContext as o, TemporalRepository as p, TemporalizedContextSeed as r, createTemporalContext as s, TemporalUseCase as t, Query as u, PolicyPort as v, MaybePromise as w, CommandInput as x, PolicyPortError as y };
309
304
  //# sourceMappingURL=temporal-use-case.d.ts.map