@cullet/erp-core 1.2.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.
- package/dist/app-error.d.cts +108 -0
- package/dist/application/index.cjs +26 -0
- package/dist/application/index.d.cts +2 -0
- package/dist/domain/index.cjs +16 -0
- package/dist/domain/index.d.cts +3 -0
- package/dist/domain-event-contracts.cjs +33 -0
- package/dist/domain-event-contracts.cjs.map +1 -0
- package/dist/domain-event-contracts.d.cts +27 -0
- package/dist/domain-exception.cjs +17 -0
- package/dist/domain-exception.cjs.map +1 -0
- package/dist/domain-exception.d.cts +7 -0
- package/dist/errors/index.cjs +41 -0
- package/dist/errors/index.d.cts +3 -0
- package/dist/exceptions/index.cjs +17 -0
- package/dist/exceptions/index.d.cts +5 -0
- package/dist/exceptions/validation-field.cjs +3 -0
- package/dist/exceptions/validation-field.d.cts +2 -0
- package/dist/gate-engine-registry.cjs +308 -0
- package/dist/gate-engine-registry.cjs.map +1 -0
- package/dist/gate-engine-registry.d.cts +81 -0
- package/dist/gate-types.d.cts +171 -0
- package/dist/gate-v1-payload.schema.cjs +638 -0
- package/dist/gate-v1-payload.schema.cjs.map +1 -0
- package/dist/hashing.cjs +66 -0
- package/dist/hashing.cjs.map +1 -0
- package/dist/immutable.cjs +77 -0
- package/dist/immutable.cjs.map +1 -0
- package/dist/immutable.d.cts +6 -0
- package/dist/index.cjs +163 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +30 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/invalid-state-transition-exception.cjs +47 -0
- package/dist/invalid-state-transition-exception.cjs.map +1 -0
- package/dist/invariant-violation-exception.cjs +16 -0
- package/dist/invariant-violation-exception.cjs.map +1 -0
- package/dist/not-found-error.cjs +65 -0
- package/dist/not-found-error.cjs.map +1 -0
- package/dist/outcome.cjs +97 -0
- package/dist/outcome.cjs.map +1 -0
- package/dist/outcome.d.cts +140 -0
- package/dist/parse-gate-payload.d.cts +62 -0
- package/dist/path.d.cts +90 -0
- package/dist/plugin.cjs +79 -0
- package/dist/plugin.cjs.map +1 -0
- package/dist/plugin.d.cts +85 -0
- package/dist/plugins/index.cjs +3 -0
- package/dist/plugins/index.d.cts +2 -0
- package/dist/policies/engines/index.cjs +10 -0
- package/dist/policies/engines/index.d.cts +4 -0
- package/dist/policies/engines/v1/gate/index.cjs +91 -0
- package/dist/policies/engines/v1/gate/index.cjs.map +1 -0
- package/dist/policies/engines/v1/gate/index.d.cts +121 -0
- package/dist/policies/index.cjs +41 -0
- package/dist/policies/index.d.cts +7 -0
- package/dist/policy-service.cjs +1190 -0
- package/dist/policy-service.cjs.map +1 -0
- package/dist/policy-service.d.cts +559 -0
- package/dist/result/index.cjs +7 -0
- package/dist/result/index.d.cts +2 -0
- package/dist/result.cjs +135 -0
- package/dist/result.cjs.map +1 -0
- package/dist/ruleset-registry.cjs +47 -0
- package/dist/ruleset-registry.cjs.map +1 -0
- package/dist/rulesets/index.cjs +3 -0
- package/dist/rulesets/index.d.cts +2 -0
- package/dist/temporal-guards.cjs +32 -0
- package/dist/temporal-guards.cjs.map +1 -0
- package/dist/temporal-use-case.cjs +191 -0
- package/dist/temporal-use-case.cjs.map +1 -0
- package/dist/temporal-use-case.d.cts +304 -0
- package/dist/unexpected-error.cjs +208 -0
- package/dist/unexpected-error.cjs.map +1 -0
- package/dist/use-case.cjs +96 -0
- package/dist/use-case.cjs.map +1 -0
- package/dist/uuid-identifier.cjs +65 -0
- package/dist/uuid-identifier.cjs.map +1 -0
- package/dist/uuid-identifier.d.cts +230 -0
- package/dist/validation-code.cjs +60 -0
- package/dist/validation-code.cjs.map +1 -0
- package/dist/validation-code.d.cts +23 -0
- package/dist/validation-error.cjs +1020 -0
- package/dist/validation-error.cjs.map +1 -0
- package/dist/validation-error.d.cts +777 -0
- package/dist/validation-exception.cjs +41 -0
- package/dist/validation-exception.cjs.map +1 -0
- package/dist/validation-exception.d.cts +50 -0
- package/dist/validation-field.cjs +28 -0
- package/dist/validation-field.cjs.map +1 -0
- package/dist/validation-field.d.cts +12 -0
- package/dist/value-object-ruleset.contracts.d.cts +36 -0
- package/dist/value-object.cjs +208 -0
- package/dist/value-object.cjs.map +1 -0
- package/dist/version.d.cts +10 -0
- package/dist/versioning/index.cjs +7 -0
- package/dist/versioning/index.d.cts +3 -0
- package/meta.json +3 -2
- package/package.json +147 -28
- package/src/version.ts +1 -1
|
@@ -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
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
//#region src/core/errors/error-codes.ts
|
|
2
|
+
const ErrorCodes = {
|
|
3
|
+
authentication: {
|
|
4
|
+
missingToken: "sec.authn.missing_token",
|
|
5
|
+
invalidToken: "sec.authn.invalid_token",
|
|
6
|
+
expiredToken: "sec.authn.expired_token",
|
|
7
|
+
invalidCredentials: "sec.authn.invalid_credentials"
|
|
8
|
+
},
|
|
9
|
+
authorization: {
|
|
10
|
+
forbidden: "sec.authz.forbidden",
|
|
11
|
+
policyDenied: "sec.authz.policy_denied",
|
|
12
|
+
missingCapability: "sec.authz.missing_capability",
|
|
13
|
+
outOfScope: "sec.authz.out_of_scope"
|
|
14
|
+
},
|
|
15
|
+
businessRuleViolation: "business_rule_violation",
|
|
16
|
+
conflict: {
|
|
17
|
+
alreadyExists: "conf.already_exists",
|
|
18
|
+
duplicate: "conf.duplicate",
|
|
19
|
+
uniqueViolation: "conf.unique_violation"
|
|
20
|
+
},
|
|
21
|
+
idempotency: {
|
|
22
|
+
keyMissing: "idemp.key_missing",
|
|
23
|
+
inProgress: "idemp.in_progress",
|
|
24
|
+
payloadMismatch: "idemp.payload_mismatch",
|
|
25
|
+
replayNotSupported: "idemp.replay_not_supported"
|
|
26
|
+
},
|
|
27
|
+
integration: {
|
|
28
|
+
timeout: "int.timeout",
|
|
29
|
+
unreachable: "int.unreachable",
|
|
30
|
+
badResponse: "int.bad_response"
|
|
31
|
+
},
|
|
32
|
+
legacyIncompatible: "legacy_incompatible",
|
|
33
|
+
notFound: "not_found",
|
|
34
|
+
serialization: {
|
|
35
|
+
deserializePrefix: "ser.des",
|
|
36
|
+
serializePrefix: "ser.ser"
|
|
37
|
+
},
|
|
38
|
+
temporal: {
|
|
39
|
+
expired: "tmp.expired",
|
|
40
|
+
notYetValid: "tmp.not_yet_valid"
|
|
41
|
+
},
|
|
42
|
+
unexpected: "unexpected",
|
|
43
|
+
validation: "validation_error"
|
|
44
|
+
};
|
|
45
|
+
function serializationErrorCode(direction, category) {
|
|
46
|
+
return `${direction === "deserialize" ? ErrorCodes.serialization.deserializePrefix : ErrorCodes.serialization.serializePrefix}.${category}`;
|
|
47
|
+
}
|
|
48
|
+
//#endregion
|
|
49
|
+
//#region src/core/errors/utils/json-safe.ts
|
|
50
|
+
const NON_SERIALIZABLE_PLACEHOLDER = "[NonSerializable]";
|
|
51
|
+
const CIRCULAR_REFERENCE_PLACEHOLDER = "[Circular]";
|
|
52
|
+
function isPlainObject(value) {
|
|
53
|
+
if (value === null || typeof value !== "object") return false;
|
|
54
|
+
const proto = Object.getPrototypeOf(value);
|
|
55
|
+
return proto === Object.prototype || proto === null;
|
|
56
|
+
}
|
|
57
|
+
function sanitizeValue(value, seen) {
|
|
58
|
+
if (value === null) return null;
|
|
59
|
+
const type = typeof value;
|
|
60
|
+
if (type === "string" || type === "number" || type === "boolean") return value;
|
|
61
|
+
if (type === "bigint" || type === "function" || type === "symbol" || value === void 0) return NON_SERIALIZABLE_PLACEHOLDER;
|
|
62
|
+
if (Array.isArray(value)) {
|
|
63
|
+
if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;
|
|
64
|
+
seen.add(value);
|
|
65
|
+
const sanitized = value.map((item) => sanitizeValue(item, seen));
|
|
66
|
+
seen.delete(value);
|
|
67
|
+
return sanitized;
|
|
68
|
+
}
|
|
69
|
+
if (value instanceof Date) return NON_SERIALIZABLE_PLACEHOLDER;
|
|
70
|
+
if (!isPlainObject(value)) return NON_SERIALIZABLE_PLACEHOLDER;
|
|
71
|
+
if (seen.has(value)) return CIRCULAR_REFERENCE_PLACEHOLDER;
|
|
72
|
+
seen.add(value);
|
|
73
|
+
const result = {};
|
|
74
|
+
for (const [key, val] of Object.entries(value)) result[key] = sanitizeValue(val, seen);
|
|
75
|
+
seen.delete(value);
|
|
76
|
+
return result;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Ensures metadata is JSON-serializable.
|
|
80
|
+
*
|
|
81
|
+
* **Allowed:** string, number, boolean, null, arrays, and plain objects.
|
|
82
|
+
*
|
|
83
|
+
* **Converted to placeholder:** Date, BigInt, class instances, functions,
|
|
84
|
+
* symbols, undefined, and circular references (which would otherwise make
|
|
85
|
+
* `JSON.stringify` throw).
|
|
86
|
+
*
|
|
87
|
+
* @throws {TypeError} If `input` is not a plain object at the root level.
|
|
88
|
+
*/
|
|
89
|
+
function assertJsonSafeMetadata(input) {
|
|
90
|
+
if (input === void 0) return {};
|
|
91
|
+
if (!isPlainObject(input)) throw new TypeError("metadata must be a plain object (Record<string, unknown>).");
|
|
92
|
+
return sanitizeValue(input, /* @__PURE__ */ new WeakSet());
|
|
93
|
+
}
|
|
94
|
+
//#endregion
|
|
95
|
+
//#region src/core/errors/app-error.ts
|
|
96
|
+
/**
|
|
97
|
+
* Root of the application/domain error hierarchy. Every error the system raises
|
|
98
|
+
* on purpose extends `AppError`, which gives callers a single `instanceof` to
|
|
99
|
+
* catch and a uniform, serializable shape to log and transport.
|
|
100
|
+
*
|
|
101
|
+
* Beyond the native `Error` message it carries a stable `code` (the contract the
|
|
102
|
+
* outside world matches on), an optional non-leaking `publicMessage`, a
|
|
103
|
+
* severity, JSON-safe `metadata`, and the correlation/request/command ids that
|
|
104
|
+
* stitch an error back to the request that produced it. The metadata is
|
|
105
|
+
* validated as JSON-safe on construction, so a logger can serialize any
|
|
106
|
+
* `AppError` without hitting a circular reference or a non-serializable value.
|
|
107
|
+
*
|
|
108
|
+
* Abstract on purpose: callers should throw a specific subclass (e.g.
|
|
109
|
+
* {@link ValidationError}, {@link NotFoundError}) so the `code` and shape are
|
|
110
|
+
* meaningful, never a bare `AppError`.
|
|
111
|
+
*/
|
|
112
|
+
var AppError = class extends Error {
|
|
113
|
+
/**
|
|
114
|
+
* Builds the common error envelope shared by every subclass.
|
|
115
|
+
*
|
|
116
|
+
* `name` is taken from `new.target` so the thrown instance reports its
|
|
117
|
+
* concrete subclass name (not `"AppError"`), and the prototype is re-pinned
|
|
118
|
+
* via `setPrototypeOf` so `instanceof` keeps working after transpilation to
|
|
119
|
+
* older targets where extending built-ins breaks the chain. `createdAtIso`
|
|
120
|
+
* defaults to now, and `metadata` is validated as JSON-safe so the error is
|
|
121
|
+
* always serializable.
|
|
122
|
+
*
|
|
123
|
+
* Declared `protected`: instantiate a concrete subclass, never `AppError`.
|
|
124
|
+
*
|
|
125
|
+
* @param message - The internal, developer-facing message.
|
|
126
|
+
* @param code - The stable machine-readable code callers match on.
|
|
127
|
+
* @param options - Optional cause, metadata, severity, and correlation ids.
|
|
128
|
+
* @throws When `options.metadata` contains a value that is not JSON-safe.
|
|
129
|
+
*/
|
|
130
|
+
constructor(message, code, options) {
|
|
131
|
+
super(message);
|
|
132
|
+
this.name = new.target.name;
|
|
133
|
+
this.code = code;
|
|
134
|
+
this.cause = options?.cause;
|
|
135
|
+
this.type = options?.type;
|
|
136
|
+
this.severity = options?.severity;
|
|
137
|
+
this.correlationId = options?.correlationId;
|
|
138
|
+
this.requestId = options?.requestId;
|
|
139
|
+
this.commandId = options?.commandId;
|
|
140
|
+
this.createdAtIso = options?.createdAtIso ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
141
|
+
this.publicMessage = options?.publicMessage;
|
|
142
|
+
this.metadata = options?.metadata ? assertJsonSafeMetadata(options.metadata) : void 0;
|
|
143
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Returns a JSON-safe representation of the error.
|
|
147
|
+
* Does NOT include `cause` by default (to avoid leaking internal details).
|
|
148
|
+
*/
|
|
149
|
+
toJSON() {
|
|
150
|
+
const payload = {
|
|
151
|
+
name: this.name,
|
|
152
|
+
code: this.code,
|
|
153
|
+
message: this.message,
|
|
154
|
+
createdAtIso: this.createdAtIso
|
|
155
|
+
};
|
|
156
|
+
if (this.type !== void 0) payload.type = this.type;
|
|
157
|
+
if (this.severity !== void 0) payload.severity = this.severity;
|
|
158
|
+
if (this.publicMessage !== void 0) payload.publicMessage = this.publicMessage;
|
|
159
|
+
if (this.metadata !== void 0) payload.metadata = this.metadata;
|
|
160
|
+
if (this.correlationId !== void 0) payload.correlationId = this.correlationId;
|
|
161
|
+
if (this.requestId !== void 0) payload.requestId = this.requestId;
|
|
162
|
+
if (this.commandId !== void 0) payload.commandId = this.commandId;
|
|
163
|
+
return payload;
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
//#endregion
|
|
167
|
+
//#region src/core/errors/unexpected-error.ts
|
|
168
|
+
var UnexpectedError = class extends AppError {
|
|
169
|
+
constructor(message = "Unexpected error", cause, options) {
|
|
170
|
+
super(message, ErrorCodes.unexpected, {
|
|
171
|
+
cause,
|
|
172
|
+
...options
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
//#endregion
|
|
177
|
+
Object.defineProperty(exports, "AppError", {
|
|
178
|
+
enumerable: true,
|
|
179
|
+
get: function() {
|
|
180
|
+
return AppError;
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
Object.defineProperty(exports, "ErrorCodes", {
|
|
184
|
+
enumerable: true,
|
|
185
|
+
get: function() {
|
|
186
|
+
return ErrorCodes;
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
Object.defineProperty(exports, "UnexpectedError", {
|
|
190
|
+
enumerable: true,
|
|
191
|
+
get: function() {
|
|
192
|
+
return UnexpectedError;
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
Object.defineProperty(exports, "assertJsonSafeMetadata", {
|
|
196
|
+
enumerable: true,
|
|
197
|
+
get: function() {
|
|
198
|
+
return assertJsonSafeMetadata;
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
Object.defineProperty(exports, "serializationErrorCode", {
|
|
202
|
+
enumerable: true,
|
|
203
|
+
get: function() {
|
|
204
|
+
return serializationErrorCode;
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
//# sourceMappingURL=unexpected-error.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"unexpected-error.cjs","names":[],"sources":["../src/core/errors/error-codes.ts","../src/core/errors/utils/json-safe.ts","../src/core/errors/app-error.ts","../src/core/errors/unexpected-error.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 { 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"],"mappings":"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"}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
const require_immutable = require("./immutable.cjs");
|
|
2
|
+
//#region src/core/application/use-case.ts
|
|
3
|
+
var _UseCase;
|
|
4
|
+
const EXECUTION_COUNTER = "use_case.executions";
|
|
5
|
+
const DURATION_HISTOGRAM = "use_case.duration_ms";
|
|
6
|
+
let UseCase = class UseCase {
|
|
7
|
+
static {
|
|
8
|
+
_UseCase = this;
|
|
9
|
+
}
|
|
10
|
+
get contractVersion() {
|
|
11
|
+
return _UseCase.CONTRACT_VERSION;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Runs the use case.
|
|
15
|
+
*
|
|
16
|
+
* `run()` is the single seam every use case crosses, so it is where
|
|
17
|
+
* cross-cutting instrumentation lives. When {@link observability} exposes
|
|
18
|
+
* any adapter, the call to `execute()` is wrapped with tracing, metrics and
|
|
19
|
+
* failure logging; otherwise it delegates directly with no overhead.
|
|
20
|
+
*
|
|
21
|
+
* Observability is strictly side-effecting: a misbehaving adapter never
|
|
22
|
+
* changes the business result nor masks a thrown error — its own failures
|
|
23
|
+
* are swallowed.
|
|
24
|
+
*/
|
|
25
|
+
async run(input) {
|
|
26
|
+
const observability = this.observability();
|
|
27
|
+
if (!observability.logger && !observability.metrics && !observability.tracer) return await this.execute(input);
|
|
28
|
+
return await this.runInstrumented(input, observability);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Adapters used to instrument {@link run}. Override to opt a use case into
|
|
32
|
+
* tracing/metrics/logging. Returns an empty object by default, which keeps
|
|
33
|
+
* the plain delegating behavior.
|
|
34
|
+
*/
|
|
35
|
+
observability() {
|
|
36
|
+
return {};
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Stable identity used for span names and metric labels. Defaults to the
|
|
40
|
+
* runtime class name; override when bundling/minification would otherwise
|
|
41
|
+
* erase a meaningful name.
|
|
42
|
+
*/
|
|
43
|
+
get useCaseName() {
|
|
44
|
+
return this.constructor.name;
|
|
45
|
+
}
|
|
46
|
+
async runInstrumented(input, observability) {
|
|
47
|
+
const { logger, metrics, tracer } = observability;
|
|
48
|
+
const name = this.useCaseName;
|
|
49
|
+
const span = safely(() => tracer?.startSpan(name, { "use_case.name": name }));
|
|
50
|
+
const startedAt = Date.now();
|
|
51
|
+
try {
|
|
52
|
+
const output = await this.execute(input);
|
|
53
|
+
const outcome = output.isOk() ? "ok" : "error";
|
|
54
|
+
if (outcome === "error") safely(() => logger?.warn(`${name} returned a business error`, { useCase: name }));
|
|
55
|
+
safely(() => span?.setAttribute("use_case.outcome", outcome));
|
|
56
|
+
safely(() => metrics?.counter(EXECUTION_COUNTER, 1, {
|
|
57
|
+
useCase: name,
|
|
58
|
+
outcome
|
|
59
|
+
}));
|
|
60
|
+
return output;
|
|
61
|
+
} catch (error) {
|
|
62
|
+
safely(() => logger?.error(`${name} threw an unexpected error`, { useCase: name }));
|
|
63
|
+
safely(() => span?.setAttribute("use_case.outcome", "exception"));
|
|
64
|
+
safely(() => span?.recordException(error));
|
|
65
|
+
safely(() => metrics?.counter(EXECUTION_COUNTER, 1, {
|
|
66
|
+
useCase: name,
|
|
67
|
+
outcome: "exception"
|
|
68
|
+
}));
|
|
69
|
+
throw error;
|
|
70
|
+
} finally {
|
|
71
|
+
safely(() => metrics?.histogram(DURATION_HISTOGRAM, Date.now() - startedAt, { useCase: name }));
|
|
72
|
+
safely(() => span?.end());
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
UseCase = _UseCase = require_immutable.__decorate([require_immutable.version("1.0")], UseCase);
|
|
77
|
+
/**
|
|
78
|
+
* Invokes an observability side effect, isolating any adapter failure so it
|
|
79
|
+
* cannot alter the use case outcome.
|
|
80
|
+
*/
|
|
81
|
+
function safely(effect) {
|
|
82
|
+
try {
|
|
83
|
+
return effect();
|
|
84
|
+
} catch {
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
//#endregion
|
|
89
|
+
Object.defineProperty(exports, "UseCase", {
|
|
90
|
+
enumerable: true,
|
|
91
|
+
get: function() {
|
|
92
|
+
return UseCase;
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
//# sourceMappingURL=use-case.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-case.cjs","names":["version"],"sources":["../src/core/application/use-case.ts"],"sourcesContent":["import { type ContractVersion, version } from \"../versioning/version.js\";\nimport type { Result } from \"../result/result.js\";\n\nimport type { LoggerPort } from \"./ports/logger.port.js\";\nimport type { MetricsPort } from \"./ports/metrics.port.js\";\nimport type { TracerPort } from \"./ports/tracer.port.js\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\n/**\n * Observability adapters a use case may opt into.\n *\n * All fields are optional: a use case that provides none keeps the plain\n * `input → Result` behavior with zero overhead. When provided, {@link UseCase.run}\n * instruments every execution around `execute()` — opening a span, recording\n * duration, counting outcomes, and logging business/unexpected failures.\n */\ninterface UseCaseObservability {\n readonly logger?: LoggerPort;\n readonly metrics?: MetricsPort;\n readonly tracer?: TracerPort;\n}\n\nconst EXECUTION_COUNTER = \"use_case.executions\";\nconst DURATION_HISTOGRAM = \"use_case.duration_ms\";\n\ntype ExecutionOutcome = \"ok\" | \"error\" | \"exception\";\n\n@version(\"1.0\")\nabstract class UseCase<\n Input = void,\n Output extends Result<unknown, unknown> = Result<void, never>,\n> {\n declare public static readonly CONTRACT_VERSION: ContractVersion;\n\n public get contractVersion(): ContractVersion {\n return UseCase.CONTRACT_VERSION;\n }\n\n /**\n * Runs the use case.\n *\n * `run()` is the single seam every use case crosses, so it is where\n * cross-cutting instrumentation lives. When {@link observability} exposes\n * any adapter, the call to `execute()` is wrapped with tracing, metrics and\n * failure logging; otherwise it delegates directly with no overhead.\n *\n * Observability is strictly side-effecting: a misbehaving adapter never\n * changes the business result nor masks a thrown error — its own failures\n * are swallowed.\n */\n public async run(input: Input): Promise<Output> {\n const observability = this.observability();\n if (\n !observability.logger &&\n !observability.metrics &&\n !observability.tracer\n ) {\n return await this.execute(input);\n }\n\n return await this.runInstrumented(input, observability);\n }\n\n /**\n * Adapters used to instrument {@link run}. Override to opt a use case into\n * tracing/metrics/logging. Returns an empty object by default, which keeps\n * the plain delegating behavior.\n */\n protected observability(): UseCaseObservability {\n return {};\n }\n\n /**\n * Stable identity used for span names and metric labels. Defaults to the\n * runtime class name; override when bundling/minification would otherwise\n * erase a meaningful name.\n */\n protected get useCaseName(): string {\n return this.constructor.name;\n }\n\n protected abstract execute(input: Input): MaybePromise<Output>;\n\n private async runInstrumented(\n input: Input,\n observability: UseCaseObservability,\n ): Promise<Output> {\n const { logger, metrics, tracer } = observability;\n const name = this.useCaseName;\n const span = safely(() =>\n tracer?.startSpan(name, { \"use_case.name\": name }),\n );\n const startedAt = Date.now();\n\n try {\n const output = await this.execute(input);\n const outcome: ExecutionOutcome = output.isOk() ? \"ok\" : \"error\";\n\n if (outcome === \"error\") {\n safely(() =>\n logger?.warn(`${name} returned a business error`, {\n useCase: name,\n }),\n );\n }\n safely(() => span?.setAttribute(\"use_case.outcome\", outcome));\n safely(() =>\n metrics?.counter(EXECUTION_COUNTER, 1, {\n useCase: name,\n outcome,\n }),\n );\n\n return output;\n } catch (error) {\n safely(() =>\n logger?.error(`${name} threw an unexpected error`, {\n useCase: name,\n }),\n );\n safely(() => span?.setAttribute(\"use_case.outcome\", \"exception\"));\n safely(() => span?.recordException(error));\n safely(() =>\n metrics?.counter(EXECUTION_COUNTER, 1, {\n useCase: name,\n outcome: \"exception\",\n }),\n );\n\n throw error;\n } finally {\n safely(() =>\n metrics?.histogram(DURATION_HISTOGRAM, Date.now() - startedAt, {\n useCase: name,\n }),\n );\n safely(() => span?.end());\n }\n }\n}\n\n/**\n * Invokes an observability side effect, isolating any adapter failure so it\n * cannot alter the use case outcome.\n */\nfunction safely<R>(effect: () => R): R | undefined {\n try {\n return effect();\n } catch {\n return undefined;\n }\n}\n\nexport { type MaybePromise, UseCase, type UseCaseObservability };\n"],"mappings":";;;AAuBA,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;AAI3B,IAAA,UAAA,MACe,QAGb;;;;CAGE,IAAW,kBAAmC;EAC1C,OAAA,SAAe;CACnB;;;;;;;;;;;;;CAcA,MAAa,IAAI,OAA+B;EAC5C,MAAM,gBAAgB,KAAK,cAAc;EACzC,IACI,CAAC,cAAc,UACf,CAAC,cAAc,WACf,CAAC,cAAc,QAEf,OAAO,MAAM,KAAK,QAAQ,KAAK;EAGnC,OAAO,MAAM,KAAK,gBAAgB,OAAO,aAAa;CAC1D;;;;;;CAOA,gBAAgD;EAC5C,OAAO,CAAC;CACZ;;;;;;CAOA,IAAc,cAAsB;EAChC,OAAO,KAAK,YAAY;CAC5B;CAIA,MAAc,gBACV,OACA,eACe;EACf,MAAM,EAAE,QAAQ,SAAS,WAAW;EACpC,MAAM,OAAO,KAAK;EAClB,MAAM,OAAO,aACT,QAAQ,UAAU,MAAM,EAAE,iBAAiB,KAAK,CAAC,CACrD;EACA,MAAM,YAAY,KAAK,IAAI;EAE3B,IAAI;GACA,MAAM,SAAS,MAAM,KAAK,QAAQ,KAAK;GACvC,MAAM,UAA4B,OAAO,KAAK,IAAI,OAAO;GAEzD,IAAI,YAAY,SACZ,aACI,QAAQ,KAAK,GAAG,KAAK,6BAA6B,EAC9C,SAAS,KACb,CAAC,CACL;GAEJ,aAAa,MAAM,aAAa,oBAAoB,OAAO,CAAC;GAC5D,aACI,SAAS,QAAQ,mBAAmB,GAAG;IACnC,SAAS;IACT;GACJ,CAAC,CACL;GAEA,OAAO;EACX,SAAS,OAAO;GACZ,aACI,QAAQ,MAAM,GAAG,KAAK,6BAA6B,EAC/C,SAAS,KACb,CAAC,CACL;GACA,aAAa,MAAM,aAAa,oBAAoB,WAAW,CAAC;GAChE,aAAa,MAAM,gBAAgB,KAAK,CAAC;GACzC,aACI,SAAS,QAAQ,mBAAmB,GAAG;IACnC,SAAS;IACT,SAAS;GACb,CAAC,CACL;GAEA,MAAM;EACV,UAAU;GACN,aACI,SAAS,UAAU,oBAAoB,KAAK,IAAI,IAAI,WAAW,EAC3D,SAAS,KACb,CAAC,CACL;GACA,aAAa,MAAM,IAAI,CAAC;EAC5B;CACJ;AACJ;mDAhHCA,kBAAAA,QAAQ,KAAK,CAAA,GAAA,OAAA;;;;;AAsHd,SAAS,OAAU,QAAgC;CAC/C,IAAI;EACA,OAAO,OAAO;CAClB,QAAQ;EACJ;CACJ;AACJ"}
|