@cullet/erp-core 1.4.0 → 2.0.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/KIT_CONTEXT.md +7 -1
- package/dist/abac/index.d.cts +2 -2
- package/dist/abac/index.d.ts +2 -2
- package/dist/aggregate-version.cjs +14 -0
- package/dist/aggregate-version.cjs.map +1 -0
- package/dist/aggregate-version.js +9 -0
- package/dist/aggregate-version.js.map +1 -0
- package/dist/app-error.cjs +21 -6
- package/dist/app-error.cjs.map +1 -1
- package/dist/app-error.js +21 -6
- package/dist/app-error.js.map +1 -1
- package/dist/application/index.cjs +8 -4
- package/dist/application/index.d.cts +2 -2
- package/dist/application/index.d.ts +2 -2
- package/dist/application/index.js +1 -2
- package/dist/authorization-error.cjs +67 -17
- package/dist/authorization-error.cjs.map +1 -1
- package/dist/authorization-error.d.cts +6 -2
- package/dist/authorization-error.d.ts +6 -2
- package/dist/authorization-error.js +50 -18
- package/dist/authorization-error.js.map +1 -1
- package/dist/authorizer.port.d.cts +18 -3
- package/dist/authorizer.port.d.ts +18 -3
- package/dist/composite-authorizer.d.cts +63 -10
- package/dist/composite-authorizer.d.ts +63 -10
- package/dist/condition-evaluator.cjs +117 -172
- package/dist/condition-evaluator.cjs.map +1 -1
- package/dist/condition-evaluator.js +118 -167
- package/dist/condition-evaluator.js.map +1 -1
- package/dist/core-config.d.cts +53 -6
- package/dist/core-config.d.ts +53 -6
- package/dist/decorate.cjs +14 -0
- package/dist/decorate.js +9 -0
- package/dist/domain/index.cjs +107 -2
- package/dist/domain/index.cjs.map +1 -0
- package/dist/domain/index.d.cts +25 -1
- package/dist/domain/index.d.ts +25 -1
- package/dist/domain/index.js +99 -3
- package/dist/domain/index.js.map +1 -0
- package/dist/domain-event-contracts.cjs +12 -8
- package/dist/domain-event-contracts.cjs.map +1 -1
- package/dist/domain-event-contracts.d.cts +29 -4
- package/dist/domain-event-contracts.d.ts +29 -4
- package/dist/domain-event-contracts.js +11 -7
- package/dist/domain-event-contracts.js.map +1 -1
- package/dist/domain-exception.cjs +2 -1
- package/dist/domain-exception.cjs.map +1 -1
- package/dist/domain-exception.js +2 -1
- package/dist/domain-exception.js.map +1 -1
- package/dist/errors/index.cjs +3 -2
- package/dist/errors/index.d.cts +1 -1
- package/dist/errors/index.d.ts +1 -1
- package/dist/errors/index.js +3 -2
- package/dist/exceptions/index.cjs +2 -2
- package/dist/exceptions/index.d.cts +1 -2
- package/dist/exceptions/index.d.ts +1 -2
- package/dist/exceptions/index.js +2 -2
- package/dist/gate-engine-registry.cjs.map +1 -1
- package/dist/gate-engine-registry.d.cts +1 -1
- package/dist/gate-engine-registry.d.ts +1 -1
- package/dist/gate-engine-registry.js.map +1 -1
- package/dist/gate-v1-payload.schema.cjs +11 -6
- package/dist/gate-v1-payload.schema.cjs.map +1 -1
- package/dist/gate-v1-payload.schema.js +11 -6
- package/dist/gate-v1-payload.schema.js.map +1 -1
- package/dist/hashing.cjs +2 -44
- package/dist/hashing.cjs.map +1 -1
- package/dist/hashing.js +3 -39
- package/dist/hashing.js.map +1 -1
- package/dist/immutable.cjs +25 -12
- package/dist/immutable.cjs.map +1 -1
- package/dist/immutable.js +24 -11
- package/dist/immutable.js.map +1 -1
- package/dist/index.cjs +15 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -10
- package/dist/index.d.ts +9 -10
- package/dist/index.js +8 -9
- package/dist/index.js.map +1 -1
- package/dist/invalid-state-transition-exception.cjs +6 -6
- package/dist/invalid-state-transition-exception.cjs.map +1 -1
- package/dist/invalid-state-transition-exception.js +6 -6
- package/dist/invalid-state-transition-exception.js.map +1 -1
- package/dist/invariant-violation-exception.cjs +2 -2
- package/dist/invariant-violation-exception.cjs.map +1 -1
- package/dist/invariant-violation-exception.js +2 -2
- package/dist/invariant-violation-exception.js.map +1 -1
- package/dist/not-found-error.cjs +6 -4
- package/dist/not-found-error.cjs.map +1 -1
- package/dist/not-found-error.js +6 -4
- package/dist/not-found-error.js.map +1 -1
- package/dist/outcome.cjs +5 -5
- package/dist/outcome.cjs.map +1 -1
- package/dist/outcome.js +5 -5
- package/dist/outcome.js.map +1 -1
- package/dist/parse-gate-payload.d.cts +1 -1
- package/dist/parse-gate-payload.d.ts +1 -1
- package/dist/path.d.cts +2 -2
- package/dist/path.d.ts +2 -2
- package/dist/plugin.cjs +23 -13
- package/dist/plugin.cjs.map +1 -1
- package/dist/plugin.d.cts +22 -8
- package/dist/plugin.d.ts +22 -8
- package/dist/plugin.js +23 -13
- package/dist/plugin.js.map +1 -1
- package/dist/policies/engines/index.d.cts +1 -1
- package/dist/policies/engines/index.d.ts +1 -1
- package/dist/policies/engines/v1/gate/index.d.cts +3 -13
- package/dist/policies/engines/v1/gate/index.d.ts +3 -13
- package/dist/policies/index.d.cts +1 -1
- package/dist/policies/index.d.ts +1 -1
- package/dist/policy-bridge.cjs +30 -2
- package/dist/policy-bridge.cjs.map +1 -1
- package/dist/policy-bridge.d.cts +18 -0
- package/dist/policy-bridge.d.ts +18 -0
- package/dist/policy-bridge.js +30 -2
- package/dist/policy-bridge.js.map +1 -1
- package/dist/policy-service.cjs +41 -46
- package/dist/policy-service.cjs.map +1 -1
- package/dist/policy-service.d.cts +72 -9
- package/dist/policy-service.d.ts +72 -9
- package/dist/policy-service.js +43 -48
- package/dist/policy-service.js.map +1 -1
- package/dist/requested-by.cjs +4 -4
- package/dist/requested-by.cjs.map +1 -1
- package/dist/requested-by.js +2 -2
- package/dist/requested-by.js.map +1 -1
- package/dist/result.cjs +29 -1
- package/dist/result.cjs.map +1 -1
- package/dist/result.d.cts +12 -0
- package/dist/result.d.ts +12 -0
- package/dist/result.js +29 -1
- package/dist/result.js.map +1 -1
- package/dist/rule.cjs +94 -24
- package/dist/rule.cjs.map +1 -1
- package/dist/rule.js +94 -24
- package/dist/rule.js.map +1 -1
- package/dist/ruleset-registry.cjs +19 -0
- package/dist/ruleset-registry.cjs.map +1 -1
- package/dist/ruleset-registry.js +19 -0
- package/dist/ruleset-registry.js.map +1 -1
- package/dist/stable-stringify.cjs +87 -0
- package/dist/stable-stringify.cjs.map +1 -0
- package/dist/stable-stringify.js +76 -0
- package/dist/stable-stringify.js.map +1 -0
- package/dist/temporal-snapshot.d.cts +87 -0
- package/dist/temporal-snapshot.d.ts +87 -0
- package/dist/temporal-use-case.cjs +174 -16
- package/dist/temporal-use-case.cjs.map +1 -1
- package/dist/temporal-use-case.d.cts +82 -44
- package/dist/temporal-use-case.d.ts +82 -44
- package/dist/temporal-use-case.js +167 -15
- package/dist/temporal-use-case.js.map +1 -1
- package/dist/unexpected-error.cjs +4 -2
- package/dist/unexpected-error.cjs.map +1 -1
- package/dist/unexpected-error.js +4 -2
- package/dist/unexpected-error.js.map +1 -1
- package/dist/uuid-identifier.cjs +141 -8
- package/dist/uuid-identifier.cjs.map +1 -1
- package/dist/uuid-identifier.d.cts +26 -7
- package/dist/uuid-identifier.d.ts +26 -7
- package/dist/uuid-identifier.js +135 -8
- package/dist/uuid-identifier.js.map +1 -1
- package/dist/uuid.cjs +23 -0
- package/dist/uuid.cjs.map +1 -0
- package/dist/uuid.js +18 -0
- package/dist/uuid.js.map +1 -0
- package/dist/validation-code.cjs +9 -0
- package/dist/validation-code.cjs.map +1 -1
- package/dist/validation-code.d.cts +3 -0
- package/dist/validation-code.d.ts +3 -0
- package/dist/validation-code.js +9 -0
- package/dist/validation-code.js.map +1 -1
- package/dist/validation-error.cjs +42 -67
- package/dist/validation-error.cjs.map +1 -1
- package/dist/validation-error.d.cts +29 -8
- package/dist/validation-error.d.ts +29 -8
- package/dist/validation-error.js +41 -66
- package/dist/validation-error.js.map +1 -1
- package/dist/validation-exception.cjs +17 -6
- package/dist/validation-exception.cjs.map +1 -1
- package/dist/validation-exception.d.cts +33 -9
- package/dist/validation-exception.d.ts +33 -9
- package/dist/validation-exception.js +17 -6
- package/dist/validation-exception.js.map +1 -1
- package/dist/validation-field.cjs +3 -0
- package/dist/validation-field.cjs.map +1 -1
- package/dist/validation-field.d.cts +1 -0
- package/dist/validation-field.d.ts +1 -0
- package/dist/validation-field.js +3 -0
- package/dist/validation-field.js.map +1 -1
- package/dist/value-object-ruleset.contracts.d.cts +10 -0
- package/dist/value-object-ruleset.contracts.d.ts +10 -0
- package/dist/value-object.cjs +23 -4
- package/dist/value-object.cjs.map +1 -1
- package/dist/value-object.d.cts +25 -1
- package/dist/value-object.d.ts +25 -1
- package/dist/value-object.js +23 -4
- package/dist/value-object.js.map +1 -1
- package/dist/version.d.cts +27 -0
- package/dist/version.d.ts +27 -0
- package/dist/versioning/index.d.cts +2 -2
- package/dist/versioning/index.d.ts +2 -2
- package/meta.json +5 -2
- package/package.json +1 -1
- package/src/core/abac/authorizer.ts +60 -10
- package/src/core/abac/domain/policy-set.ts +52 -5
- package/src/core/abac/domain/rule.ts +28 -16
- package/src/core/abac/index.ts +7 -1
- package/src/core/application/commands/command.ts +14 -1
- package/src/core/application/commands/requested-by.ts +13 -5
- package/src/core/application/index.ts +2 -1
- package/src/core/application/policy-error-mapper.ts +6 -0
- package/src/core/application/ports/index.ts +7 -0
- package/src/core/application/ports/temporal-repository.port.ts +35 -2
- package/src/core/application/queries/index.ts +1 -1
- package/src/core/application/queries/query.ts +25 -3
- package/src/core/application/temporal/temporal-use-case.ts +31 -4
- package/src/core/application/use-case.ts +45 -8
- package/src/core/config/core-config.ts +46 -25
- package/src/core/config/index.ts +1 -0
- package/src/core/config/policy-reporter.ts +32 -1
- package/src/core/domain/entity.ts +51 -8
- package/src/core/domain/rulesets/entity-ruleset.contracts.ts +0 -2
- package/src/core/domain/rulesets/ruleset-registry.ts +24 -0
- package/src/core/domain/rulesets/value-object-ruleset.contracts.ts +1 -7
- package/src/core/domain/temporal/half-open-interval.ts +34 -0
- package/src/core/domain/temporal/temporal-snapshot.ts +13 -2
- package/src/core/domain/temporal/transaction-time.ts +19 -15
- package/src/core/domain/temporal/valid-time.ts +20 -15
- package/src/core/domain/uuid-identifier.ts +6 -11
- package/src/core/domain/value-object.ts +29 -3
- package/src/core/errors/authentication-error.ts +5 -31
- package/src/core/errors/authorization-error.ts +12 -20
- package/src/core/errors/business-rule-violation-error.ts +4 -1
- package/src/core/errors/idempotency-error.ts +5 -2
- package/src/core/errors/index.ts +4 -0
- package/src/core/errors/integration-error.ts +4 -24
- package/src/core/errors/legacy-incompatible-error.ts +1 -0
- package/src/core/errors/not-found-error.ts +4 -1
- package/src/core/errors/temporal-error.ts +22 -20
- package/src/core/errors/unexpected-error.ts +5 -1
- package/src/core/errors/utils/factory-helpers.ts +70 -0
- package/src/core/errors/utils/index.ts +5 -0
- package/src/core/errors/utils/json-safe.ts +35 -12
- package/src/core/errors/validation-error.ts +4 -1
- package/src/core/exceptions/business-rule-violation-exception.ts +2 -1
- package/src/core/exceptions/domain-exception.ts +9 -1
- package/src/core/exceptions/entity-not-found-exception.ts +5 -1
- package/src/core/exceptions/invalid-state-transition-exception.ts +5 -2
- package/src/core/exceptions/invariant-violation-exception.ts +2 -2
- package/src/core/exceptions/validation-code.ts +14 -0
- package/src/core/exceptions/validation-exception.ts +44 -5
- package/src/core/exceptions/validation-field.ts +11 -1
- package/src/core/plugins/plugin.ts +25 -15
- package/src/core/plugins/types.ts +4 -2
- package/src/core/policies/asof/asof.ts +12 -0
- package/src/core/policies/catalog/policy-catalog-entry.ts +3 -1
- package/src/core/policies/catalog/policy-catalog.ts +5 -1
- package/src/core/policies/context/context-builder.ts +20 -0
- package/src/core/policies/context/context-resolver.ts +5 -0
- package/src/core/policies/context/context-seed.ts +11 -0
- package/src/core/policies/defs/in-memory-policy-definition-repo.ts +0 -2
- package/src/core/policies/engines/parse-gate-payload.ts +9 -0
- package/src/core/policies/engines/v1/condition-date-operands.ts +112 -0
- package/src/core/policies/engines/v1/condition-evaluator.ts +120 -291
- package/src/core/policies/engines/v1/condition-schema.ts +23 -19
- package/src/core/policies/engines/v1/condition-types.ts +18 -11
- package/src/core/policies/index.ts +4 -6
- package/src/core/policies/service/policy-service.ts +46 -35
- package/src/core/policies/utils/hash.ts +5 -69
- package/src/core/policies/utils/result.ts +1 -1
- package/src/core/rbac/access-request.ts +12 -2
- package/src/core/rbac/authorizer.ts +8 -1
- package/src/core/rbac/domain/role.ts +20 -0
- package/src/core/rbac/domain/scope.ts +6 -1
- package/src/core/result/index.ts +5 -0
- package/src/core/result/outcome.ts +5 -7
- package/src/core/result/result.ts +34 -1
- package/src/core/shared/hashing.ts +6 -57
- package/src/core/shared/immutable.ts +22 -4
- package/src/core/shared/stable-stringify.ts +144 -0
- package/src/core/shared/uuid.ts +16 -0
- package/src/core/versioning/domain-event-contracts.ts +43 -15
- package/src/core/versioning/index.ts +1 -0
- package/src/core/versioning/version.ts +30 -1
- package/src/domain/index.ts +5 -0
- package/src/examples/rulesets/entity/order-creation-rules-v1.ts +1 -1
- package/src/examples/rulesets/entity/order-invariants-v1.ts +2 -4
- package/src/examples/rulesets/entity/order-invariants-v2.ts +2 -4
- package/src/examples/rulesets/value-object/cpf-rules-v1.ts +2 -4
- package/src/examples/rulesets/value-object/cpf-rules-v2.ts +2 -4
- package/src/examples/rulesets/value-object/person-name-rules-v1.ts +2 -4
- package/src/examples/rulesets/value-object/person-name-rules-v2.ts +2 -4
- package/src/result/index.ts +7 -2
- package/src/version.ts +1 -1
- package/dist/domain-exception.d.cts +0 -7
- package/dist/domain-exception.d.ts +0 -7
- package/dist/entity.cjs +0 -126
- package/dist/entity.cjs.map +0 -1
- package/dist/entity.js +0 -115
- package/dist/entity.js.map +0 -1
- package/dist/use-case.cjs +0 -96
- package/dist/use-case.cjs.map +0 -1
- package/dist/use-case.js +0 -91
- package/dist/use-case.js.map +0 -1
|
@@ -1,8 +1,128 @@
|
|
|
1
|
+
import { t as AppError } from "./app-error.js";
|
|
1
2
|
import { n as BusinessRuleViolationError, t as NotFoundError } from "./not-found-error.js";
|
|
2
|
-
import { t as UnexpectedError } from "./unexpected-error.js";
|
|
3
|
-
import { i as version, n as __decorate, t as makeImmutable } from "./immutable.js";
|
|
4
|
-
import { t as UseCase } from "./use-case.js";
|
|
5
3
|
import { t as assertValidDate } from "./temporal-guards.js";
|
|
4
|
+
import { t as UnexpectedError } from "./unexpected-error.js";
|
|
5
|
+
import { i as version, n as makeImmutable } from "./immutable.js";
|
|
6
|
+
import { t as __decorate } from "./decorate.js";
|
|
7
|
+
//#region src/core/application/use-case.ts
|
|
8
|
+
const EXECUTION_COUNTER = "use_case.executions";
|
|
9
|
+
const DURATION_HISTOGRAM = "use_case.duration_ms";
|
|
10
|
+
let UseCase = class UseCase {
|
|
11
|
+
get contractVersion() {
|
|
12
|
+
return this.constructor.CONTRACT_VERSION;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Runs the use case.
|
|
16
|
+
*
|
|
17
|
+
* `run()` is the single seam every use case crosses, so it is where
|
|
18
|
+
* cross-cutting instrumentation lives. When {@link observability} exposes
|
|
19
|
+
* any adapter, the call to `execute()` is wrapped with tracing, metrics and
|
|
20
|
+
* failure logging; otherwise it delegates directly with no overhead.
|
|
21
|
+
*
|
|
22
|
+
* Observability is strictly side-effecting: a misbehaving adapter never
|
|
23
|
+
* changes the business result nor masks a thrown error — its own failures
|
|
24
|
+
* are swallowed.
|
|
25
|
+
*/
|
|
26
|
+
async run(input) {
|
|
27
|
+
const observability = this.observability();
|
|
28
|
+
if (!observability.logger && !observability.metrics && !observability.tracer) return await this.execute(input);
|
|
29
|
+
return await this.runInstrumented(input, observability);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Adapters used to instrument {@link run}. Override to opt a use case into
|
|
33
|
+
* tracing/metrics/logging. Returns an empty object by default, which keeps
|
|
34
|
+
* the plain delegating behavior.
|
|
35
|
+
*/
|
|
36
|
+
observability() {
|
|
37
|
+
return {};
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Stable identity used for span names and metric labels. Defaults to the
|
|
41
|
+
* runtime class name; override when bundling/minification would otherwise
|
|
42
|
+
* erase a meaningful name.
|
|
43
|
+
*/
|
|
44
|
+
get useCaseName() {
|
|
45
|
+
return this.constructor.name;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Extra attributes stamped onto the span and every metric emitted for this
|
|
49
|
+
* execution. Override to attach stable, **low-cardinality** dimensions
|
|
50
|
+
* (e.g. `Command` adds `requested_by.kind`). Keep values bounded — they
|
|
51
|
+
* become metric label values, so a user id or free-form string here would
|
|
52
|
+
* explode the metric's cardinality. Defaults to none.
|
|
53
|
+
*/
|
|
54
|
+
spanAttributes(_input) {
|
|
55
|
+
return {};
|
|
56
|
+
}
|
|
57
|
+
async runInstrumented(input, observability) {
|
|
58
|
+
const { logger, metrics, tracer } = observability;
|
|
59
|
+
const name = this.useCaseName;
|
|
60
|
+
const attributes = safely(() => this.spanAttributes(input)) ?? {};
|
|
61
|
+
const span = safely(() => tracer?.startSpan(name, {
|
|
62
|
+
"use_case.name": name,
|
|
63
|
+
...attributes
|
|
64
|
+
}));
|
|
65
|
+
const startedAt = performance.now();
|
|
66
|
+
let outcome = "exception";
|
|
67
|
+
try {
|
|
68
|
+
const output = await this.execute(input);
|
|
69
|
+
outcome = output.isOk() ? "ok" : "error";
|
|
70
|
+
if (outcome === "error") {
|
|
71
|
+
const code = businessErrorCode(output);
|
|
72
|
+
safely(() => logger?.warn(`${name} returned a business error`, {
|
|
73
|
+
useCase: name,
|
|
74
|
+
...code ? { code } : {}
|
|
75
|
+
}));
|
|
76
|
+
}
|
|
77
|
+
safely(() => span?.setAttribute("use_case.outcome", outcome));
|
|
78
|
+
safely(() => metrics?.counter(EXECUTION_COUNTER, 1, {
|
|
79
|
+
useCase: name,
|
|
80
|
+
outcome,
|
|
81
|
+
...attributes
|
|
82
|
+
}));
|
|
83
|
+
return output;
|
|
84
|
+
} catch (error) {
|
|
85
|
+
safely(() => logger?.error(`${name} threw an unexpected error`, { useCase: name }));
|
|
86
|
+
safely(() => span?.setAttribute("use_case.outcome", "exception"));
|
|
87
|
+
safely(() => span?.recordException(error));
|
|
88
|
+
safely(() => metrics?.counter(EXECUTION_COUNTER, 1, {
|
|
89
|
+
useCase: name,
|
|
90
|
+
outcome: "exception",
|
|
91
|
+
...attributes
|
|
92
|
+
}));
|
|
93
|
+
throw error;
|
|
94
|
+
} finally {
|
|
95
|
+
safely(() => metrics?.histogram(DURATION_HISTOGRAM, performance.now() - startedAt, {
|
|
96
|
+
useCase: name,
|
|
97
|
+
outcome,
|
|
98
|
+
...attributes
|
|
99
|
+
}));
|
|
100
|
+
safely(() => span?.end());
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
UseCase = __decorate([version("1.0")], UseCase);
|
|
105
|
+
/**
|
|
106
|
+
* Pulls the stable `code` off a business-error `Result` for logging. Returns
|
|
107
|
+
* `undefined` when the error is not an {@link AppError} — the code is safe to
|
|
108
|
+
* log (it's the public contract), unlike the message which may carry PII.
|
|
109
|
+
*/
|
|
110
|
+
function businessErrorCode(output) {
|
|
111
|
+
const error = output.errorOrNull();
|
|
112
|
+
return error instanceof AppError ? error.code : void 0;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Invokes an observability side effect, isolating any adapter failure so it
|
|
116
|
+
* cannot alter the use case outcome.
|
|
117
|
+
*/
|
|
118
|
+
function safely(effect) {
|
|
119
|
+
try {
|
|
120
|
+
return effect();
|
|
121
|
+
} catch {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
//#endregion
|
|
6
126
|
//#region src/core/application/commands/command.ts
|
|
7
127
|
/**
|
|
8
128
|
* Base for use cases that **mutate state** (writes), following CQS.
|
|
@@ -14,7 +134,17 @@ import { t as assertValidDate } from "./temporal-guards.js";
|
|
|
14
134
|
* The Command/Query distinction is semantic: the type declares the intent
|
|
15
135
|
* before any implementation exists, guiding code review and API contracts.
|
|
16
136
|
*/
|
|
17
|
-
let Command = class Command extends UseCase {
|
|
137
|
+
let Command = class Command extends UseCase {
|
|
138
|
+
/**
|
|
139
|
+
* Surfaces the actor's *kind* (`"user"` / `"system"`) on the span and
|
|
140
|
+
* metrics so a write can be sliced by origin. Only the low-cardinality
|
|
141
|
+
* `kind` is emitted — never the raw id, which would blow up label
|
|
142
|
+
* cardinality and could leak a user identifier into metrics.
|
|
143
|
+
*/
|
|
144
|
+
spanAttributes(input) {
|
|
145
|
+
return { "requested_by.kind": input.requestedBy.kind };
|
|
146
|
+
}
|
|
147
|
+
};
|
|
18
148
|
Command = __decorate([version("1.0")], Command);
|
|
19
149
|
//#endregion
|
|
20
150
|
//#region src/core/application/policy-error-mapper.ts
|
|
@@ -36,11 +166,14 @@ function mapPolicyEvaluationError(err) {
|
|
|
36
166
|
policyKind: err.policyKind,
|
|
37
167
|
payloadSchemaVersion: err.payloadSchemaVersion
|
|
38
168
|
}, { cause: err.cause });
|
|
39
|
-
case "ENGINE_FAILURE": return new UnexpectedError(err.message, err.cause, {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
169
|
+
case "ENGINE_FAILURE": return new UnexpectedError(err.message, err.cause, {
|
|
170
|
+
publicMessage: "Policy evaluation failed unexpectedly.",
|
|
171
|
+
metadata: {
|
|
172
|
+
policyKey: err.policyKey,
|
|
173
|
+
engine: err.engine,
|
|
174
|
+
engineVersion: err.engineVersion
|
|
175
|
+
}
|
|
176
|
+
});
|
|
44
177
|
}
|
|
45
178
|
}
|
|
46
179
|
//#endregion
|
|
@@ -59,6 +192,11 @@ function mapPolicyEvaluationError(err) {
|
|
|
59
192
|
* and safe to call multiple times with the same input.
|
|
60
193
|
*/
|
|
61
194
|
let Query = class Query extends UseCase {
|
|
195
|
+
/**
|
|
196
|
+
* Declares how infrastructure should cache this query's result. Public so
|
|
197
|
+
* a caching adapter can actually read it off the instance; overrides must
|
|
198
|
+
* stay public.
|
|
199
|
+
*/
|
|
62
200
|
cacheStrategy() {
|
|
63
201
|
return { kind: "NO_CACHE" };
|
|
64
202
|
}
|
|
@@ -84,21 +222,35 @@ function createTemporalContext(input = {}) {
|
|
|
84
222
|
}
|
|
85
223
|
//#endregion
|
|
86
224
|
//#region src/core/application/temporal/temporal-use-case.ts
|
|
87
|
-
|
|
225
|
+
let TemporalUseCase = class TemporalUseCase extends UseCase {
|
|
88
226
|
resolveTemporalContext(input) {
|
|
89
227
|
return createTemporalContext(input.temporalContext);
|
|
90
228
|
}
|
|
229
|
+
/**
|
|
230
|
+
* Enriches a policy `ContextSeed` with `fields.now`, taken from the
|
|
231
|
+
* context's `requestedAt` (wall-clock time of the request).
|
|
232
|
+
*
|
|
233
|
+
* NOTE: this injects **only** `now` (from `requestedAt`) — it does *not*
|
|
234
|
+
* propagate `temporalContext.asOf`. Policy evaluation derives its own
|
|
235
|
+
* `asOf` from whichever seed field the policy's `asOfSource` points at
|
|
236
|
+
* (via `fields.now` by default). So a retroactive use case (an `asOf` in
|
|
237
|
+
* the past) will still evaluate policies at the *current* time unless the
|
|
238
|
+
* author maps `temporalContext.asOf` onto that seed field explicitly. Do
|
|
239
|
+
* that mapping in the use case when back-dated evaluation is intended.
|
|
240
|
+
*/
|
|
91
241
|
buildPolicySeed(seed, temporalContext) {
|
|
242
|
+
const fields = Object.freeze({
|
|
243
|
+
...seed.fields,
|
|
244
|
+
now: new Date(temporalContext.requestedAt.getTime())
|
|
245
|
+
});
|
|
92
246
|
return Object.freeze({
|
|
93
247
|
...seed,
|
|
94
|
-
fields
|
|
95
|
-
...seed.fields,
|
|
96
|
-
now: new Date(temporalContext.requestedAt.getTime())
|
|
97
|
-
}
|
|
248
|
+
fields
|
|
98
249
|
});
|
|
99
250
|
}
|
|
100
251
|
};
|
|
252
|
+
TemporalUseCase = __decorate([version("1.0")], TemporalUseCase);
|
|
101
253
|
//#endregion
|
|
102
|
-
export { mapPolicyEvaluationError as a, Query as i, assertTemporalContext as n, Command as o, createTemporalContext as r, TemporalUseCase as t };
|
|
254
|
+
export { mapPolicyEvaluationError as a, Query as i, assertTemporalContext as n, Command as o, createTemporalContext as r, UseCase as s, TemporalUseCase as t };
|
|
103
255
|
|
|
104
256
|
//# sourceMappingURL=temporal-use-case.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"temporal-use-case.js","names":[],"sources":["../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 { 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":";;;;;;;;;;;;;;;;AAoBA,IAAA,UAAA,MACe,gBAGL,QAAuB,CAAC;sBAJjC,QAAQ,KAAK,CAAA,GAAA,OAAA;;;ACZd,SAAgB,yBAAyB,KAAsC;CAC3E,QAAQ,IAAI,MAAZ;EACI,KAAK,mBACD,OAAO,IAAI,2BACP,UAAU,IAAI,MAAM,YAAY,KAChC,IAAI,SACJ;GAAE,WAAW,IAAI;GAAW,OAAO,IAAI;EAAM,GAC7C,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,sBACD,OAAO,IAAI,2BACP,sBACA,IAAI,SACJ,EAAE,cAAc,IAAI,aAAa,GACjC,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,oBACD,OAAO,IAAI,cACP,UACA,EAAE,WAAW,IAAI,UAAU,GAC3B,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,+BACD,OAAO,IAAI,cACP,oBACA;GACI,WAAW,IAAI;GACf,gBAAgB,IAAI;GACpB,MAAM,IAAI,KAAK,YAAY;EAC/B,GACA,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,4BACD,OAAO,IAAI,cACP,iBACA;GACI,WAAW,IAAI;GACf,YAAY,IAAI;GAChB,sBAAsB,IAAI;EAC9B,GACA,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,kBACD,OAAO,IAAI,gBAAgB,IAAI,SAAS,IAAI,OAAO,EAC/C,UAAU;GACN,WAAW,IAAI;GACf,QAAQ,IAAI;GACZ,eAAe,IAAI;EACvB,EACJ,CAAC;CACT;AACJ;;;;;;;;;;;;;;;;ACnBA,IAAA,QAAA,MACe,cAIL,QAAsC;CAC5C,gBAAyC;EACrC,OAAO,EAAE,MAAM,WAAW;CAC9B;AACJ;oBATC,QAAQ,KAAK,CAAA,GAAA,KAAA;;;AC3Bd,SAAS,sBACL,iBACA,YAAoB,mBAChB;CACJ,gBAAgB,GAAG,UAAU,QAAQ,gBAAgB,IAAI;CACzD,gBAAgB,GAAG,UAAU,eAAe,gBAAgB,WAAW;AAC3E;AAEA,SAAS,sBACL,QAAoC,CAAC,GACtB;CACf,MAAM,cAAc,MAAM,+BAAe,IAAI,KAAK;CAClD,MAAM,OAAO,MAAM,QAAQ;CAE3B,sBAAsB;EAAE;EAAM;CAAY,CAAC;CAE3C,OAAO,cAAc;EACjB;EACA;CACJ,CAAC;AACL;;;ACNA,IAAe,kBAAf,cAGU,QAA8C;CACpD,uBACI,OACe;EACf,OAAO,sBAAsB,MAAM,eAAe;CACtD;CAEA,gBACI,MACA,iBAC8B;EAC9B,OAAO,OAAO,OAAO;GACjB,GAAG;GACH,QAAQ;IACJ,GAAG,KAAK;IACR,KAAK,IAAI,KAAK,gBAAgB,YAAY,QAAQ,CAAC;GACvD;EACJ,CAAC;CACL;AACJ"}
|
|
1
|
+
{"version":3,"file":"temporal-use-case.js","names":[],"sources":["../src/core/application/use-case.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 { type ContractVersion, version } from \"../versioning/version.js\";\nimport { AppError } from \"../errors/index.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 { TraceAttributeValue, 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 (this.constructor as typeof 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 /**\n * Extra attributes stamped onto the span and every metric emitted for this\n * execution. Override to attach stable, **low-cardinality** dimensions\n * (e.g. `Command` adds `requested_by.kind`). Keep values bounded — they\n * become metric label values, so a user id or free-form string here would\n * explode the metric's cardinality. Defaults to none.\n */\n protected spanAttributes(\n _input: Input,\n ): Readonly<Record<string, TraceAttributeValue>> {\n return {};\n }\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 attributes = safely(() => this.spanAttributes(input)) ?? {};\n const span = safely(() =>\n tracer?.startSpan(name, { \"use_case.name\": name, ...attributes }),\n );\n const startedAt = performance.now();\n // Declared here (not inside `try`) so the `finally` histogram can label\n // duration by outcome; defaults to \"exception\" and is overwritten once\n // execute() returns without throwing.\n let outcome: ExecutionOutcome = \"exception\";\n\n try {\n const output = await this.execute(input);\n outcome = output.isOk() ? \"ok\" : \"error\";\n\n if (outcome === \"error\") {\n const code = businessErrorCode(output);\n safely(() =>\n logger?.warn(`${name} returned a business error`, {\n useCase: name,\n ...(code ? { code } : {}),\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 ...attributes,\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 ...attributes,\n }),\n );\n\n throw error;\n } finally {\n safely(() =>\n metrics?.histogram(\n DURATION_HISTOGRAM,\n performance.now() - startedAt,\n { useCase: name, outcome, ...attributes },\n ),\n );\n safely(() => span?.end());\n }\n }\n}\n\n/**\n * Pulls the stable `code` off a business-error `Result` for logging. Returns\n * `undefined` when the error is not an {@link AppError} — the code is safe to\n * log (it's the public contract), unlike the message which may carry PII.\n */\nfunction businessErrorCode(\n output: Result<unknown, unknown>,\n): string | undefined {\n const error = output.errorOrNull();\n return error instanceof AppError ? error.code : undefined;\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","import { UseCase } from \"../use-case.js\";\nimport { version } from \"../../versioning/version.js\";\nimport type { TraceAttributeValue } from \"../ports/tracer.port.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 /**\n * Surfaces the actor's *kind* (`\"user\"` / `\"system\"`) on the span and\n * metrics so a write can be sliced by origin. Only the low-cardinality\n * `kind` is emitted — never the raw id, which would blow up label\n * cardinality and could leak a user identifier into metrics.\n */\n protected override spanAttributes(\n input: Input,\n ): Readonly<Record<string, TraceAttributeValue>> {\n return { \"requested_by.kind\": input.requestedBy.kind };\n }\n}\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 // `engine`/`engineVersion` are internal detail kept in `metadata`\n // for logs. `publicMessage` gives the HTTP boundary a safe string\n // to expose so it never has to serialize this metadata to a client\n // on a 500. (Whether the boundary leaks `metadata` is still its\n // call — this only hands it the non-leaking alternative.)\n return new UnexpectedError(err.message, err.cause, {\n publicMessage: \"Policy evaluation failed unexpectedly.\",\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 (offset-based).\n * Use as `Output` when the query returns a collection with pagination metadata.\n * For cursor/keyset pagination, model your own `Output` type instead.\n */\ninterface Page<T> {\n readonly items: readonly T[];\n /** Total rows across all pages, ignoring `page`/`pageSize`. */\n readonly total: number;\n /** 1-based page number (the first page is `1`, not `0`). */\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 *\n * These are pure descriptors: the type cannot enforce that a duration is finite\n * and positive, so the caching adapter must validate `ttlMs` /\n * `staleWhileRevalidateMs` (`> 0`, finite) before honoring the strategy.\n */\ntype CacheStrategy =\n | { readonly kind: \"NO_CACHE\" }\n | { readonly kind: \"TIME_TO_LIVE\"; readonly ttlMs: number }\n | {\n readonly kind: \"STALE_WHILE_REVALIDATE\";\n /** How long the entry is served fresh. */\n readonly ttlMs: number;\n /**\n * How long *after* `ttlMs` a stale entry may still be served while a\n * background refresh runs. SWR needs both windows; a single TTL is\n * ambiguous and each adapter would guess the second one.\n */\n readonly staleWhileRevalidateMs: number;\n };\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 /**\n * Declares how infrastructure should cache this query's result. Public so\n * a caching adapter can actually read it off the instance; overrides must\n * stay public.\n */\n public 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 { version } from \"../../versioning/version.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\n/**\n * Marker mixed into a temporal use case's `Input`.\n *\n * The consumer's `Input` must not re-declare `temporalContext` with an\n * incompatible type: `TemporalUseCase` intersects the two, and a clashing\n * declaration collapses the field to `never` (surfacing only as a confusing\n * error at the call site, not here).\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\n@version(\"1.0\")\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 /**\n * Enriches a policy `ContextSeed` with `fields.now`, taken from the\n * context's `requestedAt` (wall-clock time of the request).\n *\n * NOTE: this injects **only** `now` (from `requestedAt`) — it does *not*\n * propagate `temporalContext.asOf`. Policy evaluation derives its own\n * `asOf` from whichever seed field the policy's `asOfSource` points at\n * (via `fields.now` by default). So a retroactive use case (an `asOf` in\n * the past) will still evaluate policies at the *current* time unless the\n * author maps `temporalContext.asOf` onto that seed field explicitly. Do\n * that mapping in the use case when back-dated evaluation is intended.\n */\n protected buildPolicySeed<TSeed extends ContextSeed>(\n seed: TSeed,\n temporalContext: TemporalContext,\n ): TemporalizedContextSeed<TSeed> {\n // ponytail: shallow-freeze the two objects we create (outer + fields);\n // nested `fields` values belong to the caller's seed — not ours to\n // deep-freeze (would freeze shared refs) or structuredClone (would\n // flatten any class instances the seed carries).\n const fields = Object.freeze({\n ...seed.fields,\n now: new Date(temporalContext.requestedAt.getTime()),\n });\n return Object.freeze({\n ...seed,\n fields,\n }) as TemporalizedContextSeed<TSeed>;\n }\n}\n\nexport type { TemporalizedContextSeed, TemporalUseCaseInput };\nexport { TemporalUseCase };\n"],"mappings":";;;;;;;AAwBA,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;AAI3B,IAAA,UAAA,MACe,QAGb;CAGE,IAAW,kBAAmC;EAC1C,OAAQ,KAAK,YAA+B;CAChD;;;;;;;;;;;;;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;;;;;;;;CAWA,eACI,QAC6C;EAC7C,OAAO,CAAC;CACZ;CAEA,MAAc,gBACV,OACA,eACe;EACf,MAAM,EAAE,QAAQ,SAAS,WAAW;EACpC,MAAM,OAAO,KAAK;EAClB,MAAM,aAAa,aAAa,KAAK,eAAe,KAAK,CAAC,KAAK,CAAC;EAChE,MAAM,OAAO,aACT,QAAQ,UAAU,MAAM;GAAE,iBAAiB;GAAM,GAAG;EAAW,CAAC,CACpE;EACA,MAAM,YAAY,YAAY,IAAI;EAIlC,IAAI,UAA4B;EAEhC,IAAI;GACA,MAAM,SAAS,MAAM,KAAK,QAAQ,KAAK;GACvC,UAAU,OAAO,KAAK,IAAI,OAAO;GAEjC,IAAI,YAAY,SAAS;IACrB,MAAM,OAAO,kBAAkB,MAAM;IACrC,aACI,QAAQ,KAAK,GAAG,KAAK,6BAA6B;KAC9C,SAAS;KACT,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;IAC3B,CAAC,CACL;GACJ;GACA,aAAa,MAAM,aAAa,oBAAoB,OAAO,CAAC;GAC5D,aACI,SAAS,QAAQ,mBAAmB,GAAG;IACnC,SAAS;IACT;IACA,GAAG;GACP,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;IACT,GAAG;GACP,CAAC,CACL;GAEA,MAAM;EACV,UAAU;GACN,aACI,SAAS,UACL,oBACA,YAAY,IAAI,IAAI,WACpB;IAAE,SAAS;IAAM;IAAS,GAAG;GAAW,CAC5C,CACJ;GACA,aAAa,MAAM,IAAI,CAAC;EAC5B;CACJ;AACJ;sBAxIC,QAAQ,KAAK,CAAA,GAAA,OAAA;;;;;;AA+Id,SAAS,kBACL,QACkB;CAClB,MAAM,QAAQ,OAAO,YAAY;CACjC,OAAO,iBAAiB,WAAW,MAAM,OAAO,KAAA;AACpD;;;;;AAMA,SAAS,OAAU,QAAgC;CAC/C,IAAI;EACA,OAAO,OAAO;CAClB,QAAQ;EACJ;CACJ;AACJ;;;;;;;;;;;;;ACxKA,IAAA,UAAA,MACe,gBAGL,QAAuB;;;;;;;CAO7B,eACI,OAC6C;EAC7C,OAAO,EAAE,qBAAqB,MAAM,YAAY,KAAK;CACzD;AACJ;sBAhBC,QAAQ,KAAK,CAAA,GAAA,OAAA;;;ACbd,SAAgB,yBAAyB,KAAsC;CAC3E,QAAQ,IAAI,MAAZ;EACI,KAAK,mBACD,OAAO,IAAI,2BACP,UAAU,IAAI,MAAM,YAAY,KAChC,IAAI,SACJ;GAAE,WAAW,IAAI;GAAW,OAAO,IAAI;EAAM,GAC7C,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,sBACD,OAAO,IAAI,2BACP,sBACA,IAAI,SACJ,EAAE,cAAc,IAAI,aAAa,GACjC,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,oBACD,OAAO,IAAI,cACP,UACA,EAAE,WAAW,IAAI,UAAU,GAC3B,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,+BACD,OAAO,IAAI,cACP,oBACA;GACI,WAAW,IAAI;GACf,gBAAgB,IAAI;GACpB,MAAM,IAAI,KAAK,YAAY;EAC/B,GACA,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,4BACD,OAAO,IAAI,cACP,iBACA;GACI,WAAW,IAAI;GACf,YAAY,IAAI;GAChB,sBAAsB,IAAI;EAC9B,GACA,EAAE,OAAO,IAAI,MAAM,CACvB;EACJ,KAAK,kBAMD,OAAO,IAAI,gBAAgB,IAAI,SAAS,IAAI,OAAO;GAC/C,eAAe;GACf,UAAU;IACN,WAAW,IAAI;IACf,QAAQ,IAAI;IACZ,eAAe,IAAI;GACvB;EACJ,CAAC;CACT;AACJ;;;;;;;;;;;;;;;;ACRA,IAAA,QAAA,MACe,cAIL,QAAsC;;;;;;CAM5C,gBAAsC;EAClC,OAAO,EAAE,MAAM,WAAW;CAC9B;AACJ;oBAdC,QAAQ,KAAK,CAAA,GAAA,KAAA;;;AC5Cd,SAAS,sBACL,iBACA,YAAoB,mBAChB;CACJ,gBAAgB,GAAG,UAAU,QAAQ,gBAAgB,IAAI;CACzD,gBAAgB,GAAG,UAAU,eAAe,gBAAgB,WAAW;AAC3E;AAEA,SAAS,sBACL,QAAoC,CAAC,GACtB;CACf,MAAM,cAAc,MAAM,+BAAe,IAAI,KAAK;CAClD,MAAM,OAAO,MAAM,QAAQ;CAE3B,sBAAsB;EAAE;EAAM;CAAY,CAAC;CAE3C,OAAO,cAAc;EACjB;EACA;CACJ,CAAC;AACL;;;ACGA,IAAA,kBAAA,MACe,wBAGL,QAA8C;CACpD,uBACI,OACe;EACf,OAAO,sBAAsB,MAAM,eAAe;CACtD;;;;;;;;;;;;;CAcA,gBACI,MACA,iBAC8B;EAK9B,MAAM,SAAS,OAAO,OAAO;GACzB,GAAG,KAAK;GACR,KAAK,IAAI,KAAK,gBAAgB,YAAY,QAAQ,CAAC;EACvD,CAAC;EACD,OAAO,OAAO,OAAO;GACjB,GAAG;GACH;EACJ,CAAC;CACL;AACJ;8BAxCC,QAAQ,KAAK,CAAA,GAAA,eAAA"}
|
|
@@ -3,9 +3,11 @@ const require_app_error = require("./app-error.cjs");
|
|
|
3
3
|
var UnexpectedError = class extends require_app_error.AppError {
|
|
4
4
|
constructor(message = "Unexpected error", cause, options) {
|
|
5
5
|
super(message, require_app_error.ErrorCodes.unexpected, {
|
|
6
|
-
|
|
7
|
-
...options
|
|
6
|
+
severity: "critical",
|
|
7
|
+
...options,
|
|
8
|
+
cause
|
|
8
9
|
});
|
|
10
|
+
Object.freeze(this);
|
|
9
11
|
}
|
|
10
12
|
};
|
|
11
13
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unexpected-error.cjs","names":["AppError","ErrorCodes"],"sources":["../src/core/errors/unexpected-error.ts"],"sourcesContent":["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
|
|
1
|
+
{"version":3,"file":"unexpected-error.cjs","names":["AppError","ErrorCodes"],"sources":["../src/core/errors/unexpected-error.ts"],"sourcesContent":["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 // The error you most want alerted on defaults to \"critical\" — a caller\n // can still lower it via options.severity.\n super(message, ErrorCodes.unexpected, {\n severity: \"critical\",\n ...options,\n cause,\n });\n Object.freeze(this);\n }\n}\n\nexport { UnexpectedError };\n"],"mappings":";;AAQA,IAAM,kBAAN,cAA8BA,kBAAAA,SAAS;CACnC,YACI,UAAU,oBACV,OACA,SACF;EAGE,MAAM,SAASC,kBAAAA,WAAW,YAAY;GAClC,UAAU;GACV,GAAG;GACH;EACJ,CAAC;EACD,OAAO,OAAO,IAAI;CACtB;AACJ"}
|
package/dist/unexpected-error.js
CHANGED
|
@@ -3,9 +3,11 @@ import { r as ErrorCodes, t as AppError } from "./app-error.js";
|
|
|
3
3
|
var UnexpectedError = class extends AppError {
|
|
4
4
|
constructor(message = "Unexpected error", cause, options) {
|
|
5
5
|
super(message, ErrorCodes.unexpected, {
|
|
6
|
-
|
|
7
|
-
...options
|
|
6
|
+
severity: "critical",
|
|
7
|
+
...options,
|
|
8
|
+
cause
|
|
8
9
|
});
|
|
10
|
+
Object.freeze(this);
|
|
9
11
|
}
|
|
10
12
|
};
|
|
11
13
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unexpected-error.js","names":[],"sources":["../src/core/errors/unexpected-error.ts"],"sourcesContent":["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
|
|
1
|
+
{"version":3,"file":"unexpected-error.js","names":[],"sources":["../src/core/errors/unexpected-error.ts"],"sourcesContent":["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 // The error you most want alerted on defaults to \"critical\" — a caller\n // can still lower it via options.severity.\n super(message, ErrorCodes.unexpected, {\n severity: \"critical\",\n ...options,\n cause,\n });\n Object.freeze(this);\n }\n}\n\nexport { UnexpectedError };\n"],"mappings":";;AAQA,IAAM,kBAAN,cAA8B,SAAS;CACnC,YACI,UAAU,oBACV,OACA,SACF;EAGE,MAAM,SAAS,WAAW,YAAY;GAClC,UAAU;GACV,GAAG;GACH;EACJ,CAAC;EACD,OAAO,OAAO,IAAI;CACtB;AACJ"}
|
package/dist/uuid-identifier.cjs
CHANGED
|
@@ -1,11 +1,136 @@
|
|
|
1
|
+
const require_invariant_violation_exception = require("./invariant-violation-exception.cjs");
|
|
2
|
+
const require_temporal_guards = require("./temporal-guards.cjs");
|
|
3
|
+
const require_immutable = require("./immutable.cjs");
|
|
4
|
+
const require_decorate = require("./decorate.cjs");
|
|
5
|
+
const require_uuid = require("./uuid.cjs");
|
|
6
|
+
const require_aggregate_version = require("./aggregate-version.cjs");
|
|
1
7
|
const require_value_object = require("./value-object.cjs");
|
|
2
|
-
//#region src/core/domain/
|
|
8
|
+
//#region src/core/domain/entity.ts
|
|
3
9
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
10
|
+
* Base class for domain entities — objects defined by a stable identity rather
|
|
11
|
+
* than by their attributes. Two entities are "the same" when their `id`
|
|
12
|
+
* matches, even if every other field differs; this is the opposite of a
|
|
13
|
+
* {@link ValueObject}, which is defined entirely by its contents.
|
|
14
|
+
*
|
|
15
|
+
* The class owns the bookkeeping common to every aggregate root: a creation
|
|
16
|
+
* timestamp that never changes, a last-modified timestamp, and an
|
|
17
|
+
* `aggregateVersion` counter used for optimistic concurrency control. All three
|
|
18
|
+
* are validated on construction and the dates are defensively cloned, so an
|
|
19
|
+
* entity can never be built into — or leak — an inconsistent temporal state.
|
|
20
|
+
*
|
|
21
|
+
* @typeParam TIdentifier - The identity type (e.g. a branded string id or a VO).
|
|
7
22
|
*/
|
|
8
|
-
|
|
23
|
+
let Entity = class Entity {
|
|
24
|
+
/**
|
|
25
|
+
* Reconstitutes an entity from its persisted {@link EntityState}.
|
|
26
|
+
*
|
|
27
|
+
* Validates the temporal invariants up front so an invalid entity is
|
|
28
|
+
* impossible to construct: both dates must be valid, the aggregate version
|
|
29
|
+
* must be a non-negative integer, and `updatedAt` may not predate
|
|
30
|
+
* `createdAt`. Both dates are cloned on the way in so a later mutation of
|
|
31
|
+
* the caller's `Date` objects cannot reach into the entity's internal state.
|
|
32
|
+
*
|
|
33
|
+
* Declared `protected` because entities are reconstituted through a
|
|
34
|
+
* subclass factory, never instantiated directly by application code.
|
|
35
|
+
*
|
|
36
|
+
* @throws {InvariantViolationException} When `id` is absent, or when
|
|
37
|
+
* `updatedAt` is earlier than `createdAt`.
|
|
38
|
+
*/
|
|
39
|
+
constructor(state) {
|
|
40
|
+
if (state.id == null) throw new require_invariant_violation_exception.InvariantViolationException("id is required: an entity cannot exist without an identity");
|
|
41
|
+
require_temporal_guards.assertValidDate("createdAt", state.createdAt);
|
|
42
|
+
require_temporal_guards.assertValidDate("updatedAt", state.updatedAt);
|
|
43
|
+
require_aggregate_version.assertValidAggregateVersion(state.aggregateVersion);
|
|
44
|
+
if (state.updatedAt.getTime() < state.createdAt.getTime()) throw new require_invariant_violation_exception.InvariantViolationException("updatedAt cannot be earlier than createdAt");
|
|
45
|
+
this._id = state.id;
|
|
46
|
+
this._createdAt = require_temporal_guards.cloneDate(state.createdAt);
|
|
47
|
+
this._updatedAt = require_temporal_guards.cloneDate(state.updatedAt);
|
|
48
|
+
this._aggregateVersion = state.aggregateVersion;
|
|
49
|
+
}
|
|
50
|
+
/** The entity's stable identity — the basis for equality between entities. */
|
|
51
|
+
get id() {
|
|
52
|
+
return this._id;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* When the entity was first created.
|
|
56
|
+
*
|
|
57
|
+
* Returns a clone so callers cannot mutate the entity's internal `Date`;
|
|
58
|
+
* the value is fixed at construction and never changes thereafter.
|
|
59
|
+
*/
|
|
60
|
+
get createdAt() {
|
|
61
|
+
return require_temporal_guards.cloneDate(this._createdAt);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* When the entity was last modified.
|
|
65
|
+
*
|
|
66
|
+
* Returns a clone for the same encapsulation reason as {@link createdAt};
|
|
67
|
+
* the underlying value advances only through {@link markAsModified}.
|
|
68
|
+
*/
|
|
69
|
+
get updatedAt() {
|
|
70
|
+
return require_temporal_guards.cloneDate(this._updatedAt);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Monotonic counter incremented on every mutation, used for optimistic
|
|
74
|
+
* concurrency control: a writer reads this value, and the persistence layer
|
|
75
|
+
* rejects the write if the stored version has moved on in the meantime.
|
|
76
|
+
*/
|
|
77
|
+
get aggregateVersion() {
|
|
78
|
+
return this._aggregateVersion;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* The schema/contract version stamped on this entity type by the
|
|
82
|
+
* `@version` decorator — used to detect and migrate state persisted under
|
|
83
|
+
* an older shape.
|
|
84
|
+
*/
|
|
85
|
+
get contractVersion() {
|
|
86
|
+
return this.constructor.CONTRACT_VERSION;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The single seam through which an entity records a mutation: it advances
|
|
90
|
+
* `updatedAt` and bumps {@link aggregateVersion} by one. Subclasses must
|
|
91
|
+
* call this from every state-changing method so the version counter stays
|
|
92
|
+
* an accurate optimistic-lock token.
|
|
93
|
+
*
|
|
94
|
+
* `updatedAt` is monotonic: each call must be at or after the current
|
|
95
|
+
* `updatedAt` (equal is fine — two mutations can share a millisecond).
|
|
96
|
+
* Without this, the version counter would advance while the timestamp
|
|
97
|
+
* walked backwards, corrupting any audit trail or ordering that reads
|
|
98
|
+
* `updatedAt`. A caller replaying out-of-order events must sort them first.
|
|
99
|
+
*
|
|
100
|
+
* @param updatedAt - The modification instant; defaults to now.
|
|
101
|
+
* @returns The new aggregate version after the increment.
|
|
102
|
+
* @throws {InvariantViolationException} When `updatedAt` is earlier than
|
|
103
|
+
* the current `updatedAt`.
|
|
104
|
+
*/
|
|
105
|
+
markAsModified(updatedAt = /* @__PURE__ */ new Date()) {
|
|
106
|
+
require_temporal_guards.assertValidDate("updatedAt", updatedAt);
|
|
107
|
+
if (updatedAt.getTime() < this._updatedAt.getTime()) throw new require_invariant_violation_exception.InvariantViolationException("updatedAt cannot move backwards: it must be at or after the current updatedAt");
|
|
108
|
+
this._updatedAt = require_temporal_guards.cloneDate(updatedAt);
|
|
109
|
+
this._aggregateVersion += 1;
|
|
110
|
+
return this._aggregateVersion;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Identity-based equality — the semantics that define an entity. Two
|
|
114
|
+
* entities are equal when they are the same concrete class and their ids
|
|
115
|
+
* match, regardless of any other field.
|
|
116
|
+
*
|
|
117
|
+
* The class check keeps a `CustomerId`-bearing entity from equalling an
|
|
118
|
+
* unrelated entity that happens to reuse the same raw id. Value-object ids
|
|
119
|
+
* are compared through their own `equals`, so two independently
|
|
120
|
+
* reconstituted id instances still match; primitive ids use `===`.
|
|
121
|
+
*/
|
|
122
|
+
equals(other) {
|
|
123
|
+
if (other == null) return false;
|
|
124
|
+
if (other === this) return true;
|
|
125
|
+
if (other.constructor !== this.constructor) return false;
|
|
126
|
+
const id = this._id;
|
|
127
|
+
if (id instanceof require_value_object.ValueObject) return id.equals(other._id);
|
|
128
|
+
return this._id === other._id;
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
Entity = require_decorate.__decorate([require_immutable.version("1.0")], Entity);
|
|
132
|
+
//#endregion
|
|
133
|
+
//#region src/core/domain/uuid-identifier.ts
|
|
9
134
|
/**
|
|
10
135
|
* Base class for UUID-backed identity value objects.
|
|
11
136
|
*
|
|
@@ -47,14 +172,22 @@ var UuidIdentifier = class extends require_value_object.ValueObject {
|
|
|
47
172
|
return this.value;
|
|
48
173
|
}
|
|
49
174
|
/**
|
|
50
|
-
* Whether `candidate` is a canonical UUID (versions 1–
|
|
51
|
-
*
|
|
175
|
+
* Whether `candidate` is a canonical UUID (versions 1–8, including the
|
|
176
|
+
* time-ordered v7; nil and max UUIDs are rejected as sentinels). The single
|
|
177
|
+
* source of truth for the format — see `shared/uuid.ts`; concrete
|
|
178
|
+
* identifiers call this from `create`.
|
|
52
179
|
*/
|
|
53
180
|
static isValid(candidate) {
|
|
54
|
-
return UUID_PATTERN.test(candidate);
|
|
181
|
+
return require_uuid.UUID_PATTERN.test(candidate);
|
|
55
182
|
}
|
|
56
183
|
};
|
|
57
184
|
//#endregion
|
|
185
|
+
Object.defineProperty(exports, "Entity", {
|
|
186
|
+
enumerable: true,
|
|
187
|
+
get: function() {
|
|
188
|
+
return Entity;
|
|
189
|
+
}
|
|
190
|
+
});
|
|
58
191
|
Object.defineProperty(exports, "UuidIdentifier", {
|
|
59
192
|
enumerable: true,
|
|
60
193
|
get: function() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uuid-identifier.cjs","names":["ValueObject"],"sources":["../src/core/domain/uuid-identifier.ts"],"sourcesContent":["import { ValueObject } from \"./value-object.js\";\n\n/**\n * Canonical RFC-4122 UUID (versions 1–5), matched case-insensitively. Declared\n * once here so the dozens of typed identifiers a domain accumulates never have\n * to re-state the pattern.\n */\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n/**\n * Base class for UUID-backed identity value objects.\n *\n * A domain typically has many of these — `OrderId`, `CustomerId`, `InvoiceId` —\n * all wrapping the same `string` shape. Two problems follow: the UUID format\n * check gets copy-pasted into every one, and because the wrapped shape is\n * identical, TypeScript's structural typing would happily accept an `OrderId`\n * where a `CustomerId` is expected. `UuidIdentifier` solves both: the format\n * lives here once ({@link isValid}), and the `TBrand` phantom tag makes each\n * subtype nominally distinct so the ids cannot be swapped for one another.\n *\n * It deliberately does not impose a factory. Identifiers vary in how they\n * report an invalid value (their own exception type, their own message), so a\n * concrete id adds a validating `create` that calls {@link isValid} plus a\n * `reconstitute` that trusts an already-persisted value:\n *\n * ```ts\n * class OrderId extends UuidIdentifier<\"OrderId\"> {\n * private constructor(value: string) { super(value); }\n * static create(raw: string): OrderId {\n * if (!UuidIdentifier.isValid(raw)) throw new InvalidOrderIdError(raw);\n * return new OrderId(raw);\n * }\n * static reconstitute(value: string): OrderId { return new OrderId(value); }\n * }\n * ```\n *\n * @typeParam TBrand - A unique string literal that nominally tags the subtype.\n */\nabstract class UuidIdentifier<\n TBrand extends string = string,\n> extends ValueObject<string, string> {\n /**\n * Phantom brand. Never assigned at runtime (`declare`), it exists only so\n * two identifiers with different brands are not interchangeable at the type\n * level despite sharing the same `string` value.\n */\n protected declare readonly __brand: TBrand;\n\n protected constructor(value: string) {\n super(value);\n }\n\n public toPrimitive(): string {\n return this.value;\n }\n\n /** The wrapped UUID string — convenient for logging and interpolation. */\n public toString(): string {\n return this.value;\n }\n\n /**\n * Whether `candidate` is a canonical UUID (versions 1–5). The single source\n * of truth for the format; concrete identifiers call this from `create`.\n */\n public static isValid(candidate: string): boolean {\n return UUID_PATTERN.test(candidate);\n }\n}\n\nexport { UuidIdentifier };\n"],"mappings":";;;;;;;AAOA,MAAM,eACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BJ,IAAe,iBAAf,cAEUA,qBAAAA,YAA4B;CAQlC,YAAsB,OAAe;EACjC,MAAM,KAAK;CACf;CAEA,cAA6B;EACzB,OAAO,KAAK;CAChB;;CAGA,WAA0B;EACtB,OAAO,KAAK;CAChB;;;;;CAMA,OAAc,QAAQ,WAA4B;EAC9C,OAAO,aAAa,KAAK,SAAS;CACtC;AACJ"}
|
|
1
|
+
{"version":3,"file":"uuid-identifier.cjs","names":["InvariantViolationException","cloneDate","ValueObject","version","ValueObject","UUID_PATTERN"],"sources":["../src/core/domain/entity.ts","../src/core/domain/uuid-identifier.ts"],"sourcesContent":["import { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\nimport { assertValidAggregateVersion } from \"../shared/aggregate-version.js\";\nimport { assertValidDate, cloneDate } from \"../shared/temporal-guards.js\";\nimport { type ContractVersion, version } from \"../versioning/version.js\";\n\nimport { ValueObject } from \"./value-object.js\";\n\n/**\n * The minimal persisted shape needed to reconstitute an {@link Entity}.\n *\n * This is the contract between storage and the domain: a repository maps a row\n * (or document) onto these four fields and hands them to a subclass constructor.\n * `aggregateVersion` travels with the state so optimistic-concurrency checks\n * survive a round-trip through the database.\n */\ninterface EntityState<TIdentifier> {\n readonly id: TIdentifier;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n readonly aggregateVersion: number;\n}\n\n/**\n * Base class for domain entities — objects defined by a stable identity rather\n * than by their attributes. Two entities are \"the same\" when their `id`\n * matches, even if every other field differs; this is the opposite of a\n * {@link ValueObject}, which is defined entirely by its contents.\n *\n * The class owns the bookkeeping common to every aggregate root: a creation\n * timestamp that never changes, a last-modified timestamp, and an\n * `aggregateVersion` counter used for optimistic concurrency control. All three\n * are validated on construction and the dates are defensively cloned, so an\n * entity can never be built into — or leak — an inconsistent temporal state.\n *\n * @typeParam TIdentifier - The identity type (e.g. a branded string id or a VO).\n */\n@version(\"1.0\")\nabstract class Entity<TIdentifier> {\n declare public static readonly CONTRACT_VERSION: ContractVersion;\n\n private readonly _id: TIdentifier;\n private readonly _createdAt: Date;\n private _updatedAt: Date;\n private _aggregateVersion: number;\n\n /**\n * Reconstitutes an entity from its persisted {@link EntityState}.\n *\n * Validates the temporal invariants up front so an invalid entity is\n * impossible to construct: both dates must be valid, the aggregate version\n * must be a non-negative integer, and `updatedAt` may not predate\n * `createdAt`. Both dates are cloned on the way in so a later mutation of\n * the caller's `Date` objects cannot reach into the entity's internal state.\n *\n * Declared `protected` because entities are reconstituted through a\n * subclass factory, never instantiated directly by application code.\n *\n * @throws {InvariantViolationException} When `id` is absent, or when\n * `updatedAt` is earlier than `createdAt`.\n */\n protected constructor(state: EntityState<TIdentifier>) {\n if (state.id == null) {\n throw new InvariantViolationException(\n \"id is required: an entity cannot exist without an identity\",\n );\n }\n\n assertValidDate(\"createdAt\", state.createdAt);\n assertValidDate(\"updatedAt\", state.updatedAt);\n assertValidAggregateVersion(state.aggregateVersion);\n\n if (state.updatedAt.getTime() < state.createdAt.getTime()) {\n throw new InvariantViolationException(\n \"updatedAt cannot be earlier than createdAt\",\n );\n }\n\n this._id = state.id;\n this._createdAt = cloneDate(state.createdAt);\n this._updatedAt = cloneDate(state.updatedAt);\n this._aggregateVersion = state.aggregateVersion;\n }\n\n /** The entity's stable identity — the basis for equality between entities. */\n public get id(): TIdentifier {\n return this._id;\n }\n\n /**\n * When the entity was first created.\n *\n * Returns a clone so callers cannot mutate the entity's internal `Date`;\n * the value is fixed at construction and never changes thereafter.\n */\n public get createdAt(): Date {\n return cloneDate(this._createdAt);\n }\n\n /**\n * When the entity was last modified.\n *\n * Returns a clone for the same encapsulation reason as {@link createdAt};\n * the underlying value advances only through {@link markAsModified}.\n */\n public get updatedAt(): Date {\n return cloneDate(this._updatedAt);\n }\n\n /**\n * Monotonic counter incremented on every mutation, used for optimistic\n * concurrency control: a writer reads this value, and the persistence layer\n * rejects the write if the stored version has moved on in the meantime.\n */\n public get aggregateVersion(): number {\n return this._aggregateVersion;\n }\n\n /**\n * The schema/contract version stamped on this entity type by the\n * `@version` decorator — used to detect and migrate state persisted under\n * an older shape.\n */\n public get contractVersion(): ContractVersion {\n return (this.constructor as typeof Entity).CONTRACT_VERSION;\n }\n\n /**\n * The single seam through which an entity records a mutation: it advances\n * `updatedAt` and bumps {@link aggregateVersion} by one. Subclasses must\n * call this from every state-changing method so the version counter stays\n * an accurate optimistic-lock token.\n *\n * `updatedAt` is monotonic: each call must be at or after the current\n * `updatedAt` (equal is fine — two mutations can share a millisecond).\n * Without this, the version counter would advance while the timestamp\n * walked backwards, corrupting any audit trail or ordering that reads\n * `updatedAt`. A caller replaying out-of-order events must sort them first.\n *\n * @param updatedAt - The modification instant; defaults to now.\n * @returns The new aggregate version after the increment.\n * @throws {InvariantViolationException} When `updatedAt` is earlier than\n * the current `updatedAt`.\n */\n protected markAsModified(updatedAt: Date = new Date()): number {\n assertValidDate(\"updatedAt\", updatedAt);\n\n if (updatedAt.getTime() < this._updatedAt.getTime()) {\n throw new InvariantViolationException(\n \"updatedAt cannot move backwards: it must be at or after the current updatedAt\",\n );\n }\n\n this._updatedAt = cloneDate(updatedAt);\n this._aggregateVersion += 1;\n\n return this._aggregateVersion;\n }\n\n /**\n * Identity-based equality — the semantics that define an entity. Two\n * entities are equal when they are the same concrete class and their ids\n * match, regardless of any other field.\n *\n * The class check keeps a `CustomerId`-bearing entity from equalling an\n * unrelated entity that happens to reuse the same raw id. Value-object ids\n * are compared through their own `equals`, so two independently\n * reconstituted id instances still match; primitive ids use `===`.\n */\n public equals(other: Entity<TIdentifier> | null | undefined): boolean {\n if (other == null) {\n return false;\n }\n if (other === this) {\n return true;\n }\n if (other.constructor !== this.constructor) {\n return false;\n }\n\n const id: unknown = this._id;\n if (id instanceof ValueObject) {\n return id.equals(other._id as typeof id);\n }\n\n return this._id === other._id;\n }\n}\n\nexport { Entity, type EntityState };\n","import { UUID_PATTERN } from \"../shared/uuid.js\";\nimport { ValueObject } from \"./value-object.js\";\n\n/**\n * Base class for UUID-backed identity value objects.\n *\n * A domain typically has many of these — `OrderId`, `CustomerId`, `InvoiceId` —\n * all wrapping the same `string` shape. Two problems follow: the UUID format\n * check gets copy-pasted into every one, and because the wrapped shape is\n * identical, TypeScript's structural typing would happily accept an `OrderId`\n * where a `CustomerId` is expected. `UuidIdentifier` solves both: the format\n * lives here once ({@link isValid}), and the `TBrand` phantom tag makes each\n * subtype nominally distinct so the ids cannot be swapped for one another.\n *\n * It deliberately does not impose a factory. Identifiers vary in how they\n * report an invalid value (their own exception type, their own message), so a\n * concrete id adds a validating `create` that calls {@link isValid} plus a\n * `reconstitute` that trusts an already-persisted value:\n *\n * ```ts\n * class OrderId extends UuidIdentifier<\"OrderId\"> {\n * private constructor(value: string) { super(value); }\n * static create(raw: string): OrderId {\n * if (!UuidIdentifier.isValid(raw)) throw new InvalidOrderIdError(raw);\n * return new OrderId(raw);\n * }\n * static reconstitute(value: string): OrderId { return new OrderId(value); }\n * }\n * ```\n *\n * @typeParam TBrand - A unique string literal that nominally tags the subtype.\n */\nabstract class UuidIdentifier<\n TBrand extends string = string,\n> extends ValueObject<string, string> {\n /**\n * Phantom brand. Never assigned at runtime (`declare`), it exists only so\n * two identifiers with different brands are not interchangeable at the type\n * level despite sharing the same `string` value.\n */\n declare protected readonly __brand: TBrand;\n\n protected constructor(value: string) {\n super(value);\n }\n\n public toPrimitive(): string {\n return this.value;\n }\n\n /** The wrapped UUID string — convenient for logging and interpolation. */\n public toString(): string {\n return this.value;\n }\n\n /**\n * Whether `candidate` is a canonical UUID (versions 1–8, including the\n * time-ordered v7; nil and max UUIDs are rejected as sentinels). The single\n * source of truth for the format — see `shared/uuid.ts`; concrete\n * identifiers call this from `create`.\n */\n public static isValid(candidate: string): boolean {\n return UUID_PATTERN.test(candidate);\n }\n}\n\nexport { UuidIdentifier };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAA,SAAA,MACe,OAAoB;;;;;;;;;;;;;;;;CAuB/B,YAAsB,OAAiC;EACnD,IAAI,MAAM,MAAM,MACZ,MAAM,IAAIA,sCAAAA,4BACN,4DACJ;EAGJ,wBAAA,gBAAgB,aAAa,MAAM,SAAS;EAC5C,wBAAA,gBAAgB,aAAa,MAAM,SAAS;EAC5C,0BAAA,4BAA4B,MAAM,gBAAgB;EAElD,IAAI,MAAM,UAAU,QAAQ,IAAI,MAAM,UAAU,QAAQ,GACpD,MAAM,IAAIA,sCAAAA,4BACN,4CACJ;EAGJ,KAAK,MAAM,MAAM;EACjB,KAAK,aAAaC,wBAAAA,UAAU,MAAM,SAAS;EAC3C,KAAK,aAAaA,wBAAAA,UAAU,MAAM,SAAS;EAC3C,KAAK,oBAAoB,MAAM;CACnC;;CAGA,IAAW,KAAkB;EACzB,OAAO,KAAK;CAChB;;;;;;;CAQA,IAAW,YAAkB;EACzB,OAAOA,wBAAAA,UAAU,KAAK,UAAU;CACpC;;;;;;;CAQA,IAAW,YAAkB;EACzB,OAAOA,wBAAAA,UAAU,KAAK,UAAU;CACpC;;;;;;CAOA,IAAW,mBAA2B;EAClC,OAAO,KAAK;CAChB;;;;;;CAOA,IAAW,kBAAmC;EAC1C,OAAQ,KAAK,YAA8B;CAC/C;;;;;;;;;;;;;;;;;;CAmBA,eAAyB,4BAAkB,IAAI,KAAK,GAAW;EAC3D,wBAAA,gBAAgB,aAAa,SAAS;EAEtC,IAAI,UAAU,QAAQ,IAAI,KAAK,WAAW,QAAQ,GAC9C,MAAM,IAAID,sCAAAA,4BACN,+EACJ;EAGJ,KAAK,aAAaC,wBAAAA,UAAU,SAAS;EACrC,KAAK,qBAAqB;EAE1B,OAAO,KAAK;CAChB;;;;;;;;;;;CAYA,OAAc,OAAwD;EAClE,IAAI,SAAS,MACT,OAAO;EAEX,IAAI,UAAU,MACV,OAAO;EAEX,IAAI,MAAM,gBAAgB,KAAK,aAC3B,OAAO;EAGX,MAAM,KAAc,KAAK;EACzB,IAAI,cAAcC,qBAAAA,aACd,OAAO,GAAG,OAAO,MAAM,GAAgB;EAG3C,OAAO,KAAK,QAAQ,MAAM;CAC9B;AACJ;sCAtJCC,kBAAAA,QAAQ,KAAK,CAAA,GAAA,MAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACJd,IAAe,iBAAf,cAEUC,qBAAAA,YAA4B;CAQlC,YAAsB,OAAe;EACjC,MAAM,KAAK;CACf;CAEA,cAA6B;EACzB,OAAO,KAAK;CAChB;;CAGA,WAA0B;EACtB,OAAO,KAAK;CAChB;;;;;;;CAQA,OAAc,QAAQ,WAA4B;EAC9C,OAAOC,aAAAA,aAAa,KAAK,SAAS;CACtC;AACJ"}
|
|
@@ -49,7 +49,8 @@ declare abstract class Entity<TIdentifier> {
|
|
|
49
49
|
* Declared `protected` because entities are reconstituted through a
|
|
50
50
|
* subclass factory, never instantiated directly by application code.
|
|
51
51
|
*
|
|
52
|
-
* @throws {InvariantViolationException} When `
|
|
52
|
+
* @throws {InvariantViolationException} When `id` is absent, or when
|
|
53
|
+
* `updatedAt` is earlier than `createdAt`.
|
|
53
54
|
*/
|
|
54
55
|
protected constructor(state: EntityState<TIdentifier>);
|
|
55
56
|
/** The entity's stable identity — the basis for equality between entities. */
|
|
@@ -86,13 +87,29 @@ declare abstract class Entity<TIdentifier> {
|
|
|
86
87
|
* call this from every state-changing method so the version counter stays
|
|
87
88
|
* an accurate optimistic-lock token.
|
|
88
89
|
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
*
|
|
90
|
+
* `updatedAt` is monotonic: each call must be at or after the current
|
|
91
|
+
* `updatedAt` (equal is fine — two mutations can share a millisecond).
|
|
92
|
+
* Without this, the version counter would advance while the timestamp
|
|
93
|
+
* walked backwards, corrupting any audit trail or ordering that reads
|
|
94
|
+
* `updatedAt`. A caller replaying out-of-order events must sort them first.
|
|
95
|
+
*
|
|
96
|
+
* @param updatedAt - The modification instant; defaults to now.
|
|
92
97
|
* @returns The new aggregate version after the increment.
|
|
93
|
-
* @throws {InvariantViolationException} When `updatedAt` is earlier than
|
|
98
|
+
* @throws {InvariantViolationException} When `updatedAt` is earlier than
|
|
99
|
+
* the current `updatedAt`.
|
|
94
100
|
*/
|
|
95
101
|
protected markAsModified(updatedAt?: Date): number;
|
|
102
|
+
/**
|
|
103
|
+
* Identity-based equality — the semantics that define an entity. Two
|
|
104
|
+
* entities are equal when they are the same concrete class and their ids
|
|
105
|
+
* match, regardless of any other field.
|
|
106
|
+
*
|
|
107
|
+
* The class check keeps a `CustomerId`-bearing entity from equalling an
|
|
108
|
+
* unrelated entity that happens to reuse the same raw id. Value-object ids
|
|
109
|
+
* are compared through their own `equals`, so two independently
|
|
110
|
+
* reconstituted id instances still match; primitive ids use `===`.
|
|
111
|
+
*/
|
|
112
|
+
equals(other: Entity<TIdentifier> | null | undefined): boolean;
|
|
96
113
|
}
|
|
97
114
|
//#endregion
|
|
98
115
|
//#region src/core/domain/uuid-identifier.d.ts
|
|
@@ -137,8 +154,10 @@ declare abstract class UuidIdentifier<TBrand extends string = string> extends Va
|
|
|
137
154
|
/** The wrapped UUID string — convenient for logging and interpolation. */
|
|
138
155
|
toString(): string;
|
|
139
156
|
/**
|
|
140
|
-
* Whether `candidate` is a canonical UUID (versions 1–
|
|
141
|
-
*
|
|
157
|
+
* Whether `candidate` is a canonical UUID (versions 1–8, including the
|
|
158
|
+
* time-ordered v7; nil and max UUIDs are rejected as sentinels). The single
|
|
159
|
+
* source of truth for the format — see `shared/uuid.ts`; concrete
|
|
160
|
+
* identifiers call this from `create`.
|
|
142
161
|
*/
|
|
143
162
|
static isValid(candidate: string): boolean;
|
|
144
163
|
}
|