@cullet/erp-core 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/KIT_CONTEXT.md +5 -3
  2. package/README.md +160 -0
  3. package/dist/abac/index.cjs +7 -0
  4. package/dist/abac/index.d.cts +2 -0
  5. package/dist/abac/index.d.ts +2 -0
  6. package/dist/abac/index.js +2 -0
  7. package/dist/app-error.cjs +193 -0
  8. package/dist/app-error.cjs.map +1 -0
  9. package/dist/app-error.js +170 -0
  10. package/dist/app-error.js.map +1 -0
  11. package/dist/application/index.cjs +2 -1
  12. package/dist/application/index.d.cts +2 -1
  13. package/dist/application/index.d.ts +2 -1
  14. package/dist/application/index.js +2 -1
  15. package/dist/authorization-error.cjs +157 -0
  16. package/dist/authorization-error.cjs.map +1 -0
  17. package/dist/authorization-error.d.cts +113 -0
  18. package/dist/authorization-error.d.ts +113 -0
  19. package/dist/authorization-error.js +152 -0
  20. package/dist/authorization-error.js.map +1 -0
  21. package/dist/authorizer.port.d.cts +130 -0
  22. package/dist/authorizer.port.d.ts +130 -0
  23. package/dist/composite-authorizer.d.cts +216 -0
  24. package/dist/composite-authorizer.d.ts +216 -0
  25. package/dist/condition-evaluator.cjs +565 -0
  26. package/dist/condition-evaluator.cjs.map +1 -0
  27. package/dist/condition-evaluator.js +536 -0
  28. package/dist/condition-evaluator.js.map +1 -0
  29. package/dist/{gate-types.d.ts → core-config.d.cts} +78 -77
  30. package/dist/{gate-types.d.cts → core-config.d.ts} +78 -77
  31. package/dist/domain/index.cjs +2 -1
  32. package/dist/domain/index.d.cts +2 -1
  33. package/dist/domain/index.d.ts +2 -1
  34. package/dist/domain/index.js +2 -1
  35. package/dist/domain-event-contracts.cjs +3 -2
  36. package/dist/domain-event-contracts.cjs.map +1 -1
  37. package/dist/domain-event-contracts.js +2 -1
  38. package/dist/domain-event-contracts.js.map +1 -1
  39. package/dist/entity.cjs +126 -0
  40. package/dist/entity.cjs.map +1 -0
  41. package/dist/entity.js +115 -0
  42. package/dist/entity.js.map +1 -0
  43. package/dist/errors/index.cjs +8 -6
  44. package/dist/errors/index.d.cts +2 -1
  45. package/dist/errors/index.d.ts +2 -1
  46. package/dist/errors/index.js +4 -2
  47. package/dist/gate-engine-registry.cjs +5 -4
  48. package/dist/gate-engine-registry.cjs.map +1 -1
  49. package/dist/gate-engine-registry.d.cts +3 -2
  50. package/dist/gate-engine-registry.d.ts +3 -2
  51. package/dist/gate-engine-registry.js +2 -1
  52. package/dist/gate-engine-registry.js.map +1 -1
  53. package/dist/gate-v1-payload.schema.cjs +0 -562
  54. package/dist/gate-v1-payload.schema.cjs.map +1 -1
  55. package/dist/gate-v1-payload.schema.js +1 -533
  56. package/dist/gate-v1-payload.schema.js.map +1 -1
  57. package/dist/index.cjs +34 -16
  58. package/dist/index.cjs.map +1 -1
  59. package/dist/index.d.cts +19 -12
  60. package/dist/index.d.ts +19 -12
  61. package/dist/index.js +15 -9
  62. package/dist/index.js.map +1 -1
  63. package/dist/not-found-error.cjs +5 -5
  64. package/dist/not-found-error.cjs.map +1 -1
  65. package/dist/not-found-error.js +1 -1
  66. package/dist/outcome.d.cts +1 -83
  67. package/dist/outcome.d.ts +1 -83
  68. package/dist/parse-gate-payload.d.cts +2 -2
  69. package/dist/parse-gate-payload.d.ts +2 -2
  70. package/dist/path.d.cts +2 -2
  71. package/dist/path.d.ts +2 -2
  72. package/dist/policies/engines/index.d.cts +1 -1
  73. package/dist/policies/engines/index.d.ts +1 -1
  74. package/dist/policies/engines/v1/gate/index.cjs +5 -4
  75. package/dist/policies/engines/v1/gate/index.cjs.map +1 -1
  76. package/dist/policies/engines/v1/gate/index.d.cts +2 -2
  77. package/dist/policies/engines/v1/gate/index.d.ts +2 -2
  78. package/dist/policies/engines/v1/gate/index.js +2 -1
  79. package/dist/policies/engines/v1/gate/index.js.map +1 -1
  80. package/dist/policies/index.cjs +5 -5
  81. package/dist/policies/index.d.cts +3 -2
  82. package/dist/policies/index.d.ts +3 -2
  83. package/dist/policies/index.js +2 -2
  84. package/dist/policy-bridge.cjs +437 -0
  85. package/dist/policy-bridge.cjs.map +1 -0
  86. package/dist/policy-bridge.d.cts +185 -0
  87. package/dist/policy-bridge.d.ts +185 -0
  88. package/dist/policy-bridge.js +396 -0
  89. package/dist/policy-bridge.js.map +1 -0
  90. package/dist/policy-service.cjs +239 -239
  91. package/dist/policy-service.cjs.map +1 -1
  92. package/dist/policy-service.d.cts +2 -2
  93. package/dist/policy-service.d.ts +2 -2
  94. package/dist/policy-service.js +239 -239
  95. package/dist/policy-service.js.map +1 -1
  96. package/dist/rbac/index.cjs +9 -0
  97. package/dist/rbac/index.d.cts +3 -0
  98. package/dist/rbac/index.d.ts +3 -0
  99. package/dist/rbac/index.js +2 -0
  100. package/dist/requested-by.cjs +54 -0
  101. package/dist/requested-by.cjs.map +1 -0
  102. package/dist/requested-by.d.cts +25 -0
  103. package/dist/requested-by.d.ts +25 -0
  104. package/dist/requested-by.js +49 -0
  105. package/dist/requested-by.js.map +1 -0
  106. package/dist/result/index.d.cts +2 -1
  107. package/dist/result/index.d.ts +2 -1
  108. package/dist/result.d.cts +84 -0
  109. package/dist/result.d.ts +84 -0
  110. package/dist/rule.cjs +327 -0
  111. package/dist/rule.cjs.map +1 -0
  112. package/dist/rule.js +298 -0
  113. package/dist/rule.js.map +1 -0
  114. package/dist/temporal-use-case.cjs +1 -53
  115. package/dist/temporal-use-case.cjs.map +1 -1
  116. package/dist/temporal-use-case.d.cts +5 -27
  117. package/dist/temporal-use-case.d.ts +5 -27
  118. package/dist/temporal-use-case.js +2 -48
  119. package/dist/temporal-use-case.js.map +1 -1
  120. package/dist/unexpected-error.cjs +3 -192
  121. package/dist/unexpected-error.cjs.map +1 -1
  122. package/dist/unexpected-error.js +2 -167
  123. package/dist/unexpected-error.js.map +1 -1
  124. package/dist/uuid-identifier.d.cts +2 -85
  125. package/dist/uuid-identifier.d.ts +2 -85
  126. package/dist/validation-error.cjs +33 -166
  127. package/dist/validation-error.cjs.map +1 -1
  128. package/dist/validation-error.d.cts +2 -98
  129. package/dist/validation-error.d.ts +2 -98
  130. package/dist/validation-error.js +7 -134
  131. package/dist/validation-error.js.map +1 -1
  132. package/dist/value-object.cjs +0 -123
  133. package/dist/value-object.cjs.map +1 -1
  134. package/dist/value-object.d.cts +89 -0
  135. package/dist/value-object.d.ts +89 -0
  136. package/dist/value-object.js +1 -112
  137. package/dist/value-object.js.map +1 -1
  138. package/meta.json +18 -4
  139. package/package.json +27 -1
  140. package/src/abac/index.ts +1 -0
  141. package/src/core/abac/abac-request.ts +29 -0
  142. package/src/core/abac/attributes.ts +39 -0
  143. package/src/core/abac/authorizer.ts +108 -0
  144. package/src/core/abac/combining.ts +63 -0
  145. package/src/core/abac/composite-authorizer.ts +45 -0
  146. package/src/core/abac/domain/policy-set.ts +52 -0
  147. package/src/core/abac/domain/rule.ts +197 -0
  148. package/src/core/abac/index.ts +21 -0
  149. package/src/core/application/ports/abac-authorizer.port.ts +20 -0
  150. package/src/core/application/ports/authorizer.port.ts +22 -0
  151. package/src/core/errors/authorization-error.ts +26 -0
  152. package/src/core/errors/error-codes.ts +1 -0
  153. package/src/core/index.ts +7 -0
  154. package/src/core/rbac/access-request.ts +32 -0
  155. package/src/core/rbac/authorizer.ts +91 -0
  156. package/src/core/rbac/domain/grant.ts +96 -0
  157. package/src/core/rbac/domain/permission-set.ts +67 -0
  158. package/src/core/rbac/domain/permission.ts +119 -0
  159. package/src/core/rbac/domain/role.ts +101 -0
  160. package/src/core/rbac/domain/scope.ts +84 -0
  161. package/src/core/rbac/index.ts +15 -0
  162. package/src/core/rbac/policy-bridge.ts +44 -0
  163. package/src/examples/application/authorize-cancel-order-abac.example.ts +107 -0
  164. package/src/examples/application/authorize-cancel-order.example.ts +101 -0
  165. package/src/rbac/index.ts +1 -0
  166. package/src/version.ts +1 -1
@@ -1,116 +1,5 @@
1
- const require_invariant_violation_exception = require("./invariant-violation-exception.cjs");
2
1
  const require_immutable = require("./immutable.cjs");
3
- const require_temporal_guards = require("./temporal-guards.cjs");
4
2
  const require_plugin = require("./plugin.cjs");
5
- //#region src/core/shared/aggregate-version.ts
6
- function assertValidAggregateVersion(aggregateVersion) {
7
- if (!Number.isInteger(aggregateVersion) || aggregateVersion < 0) throw new require_invariant_violation_exception.InvariantViolationException(`aggregateVersion must be a non-negative integer. Received: ${aggregateVersion}`);
8
- }
9
- //#endregion
10
- //#region src/core/domain/entity.ts
11
- var _Entity;
12
- /**
13
- * Base class for domain entities — objects defined by a stable identity rather
14
- * than by their attributes. Two entities are "the same" when their `id`
15
- * matches, even if every other field differs; this is the opposite of a
16
- * {@link ValueObject}, which is defined entirely by its contents.
17
- *
18
- * The class owns the bookkeeping common to every aggregate root: a creation
19
- * timestamp that never changes, a last-modified timestamp, and an
20
- * `aggregateVersion` counter used for optimistic concurrency control. All three
21
- * are validated on construction and the dates are defensively cloned, so an
22
- * entity can never be built into — or leak — an inconsistent temporal state.
23
- *
24
- * @typeParam TIdentifier - The identity type (e.g. a branded string id or a VO).
25
- */
26
- let Entity = class Entity {
27
- static {
28
- _Entity = this;
29
- }
30
- /**
31
- * Reconstitutes an entity from its persisted {@link EntityState}.
32
- *
33
- * Validates the temporal invariants up front so an invalid entity is
34
- * impossible to construct: both dates must be valid, the aggregate version
35
- * must be a non-negative integer, and `updatedAt` may not predate
36
- * `createdAt`. Both dates are cloned on the way in so a later mutation of
37
- * the caller's `Date` objects cannot reach into the entity's internal state.
38
- *
39
- * Declared `protected` because entities are reconstituted through a
40
- * subclass factory, never instantiated directly by application code.
41
- *
42
- * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.
43
- */
44
- constructor(state) {
45
- require_temporal_guards.assertValidDate("createdAt", state.createdAt);
46
- require_temporal_guards.assertValidDate("updatedAt", state.updatedAt);
47
- assertValidAggregateVersion(state.aggregateVersion);
48
- if (state.updatedAt.getTime() < state.createdAt.getTime()) throw new require_invariant_violation_exception.InvariantViolationException("updatedAt cannot be earlier than createdAt");
49
- this._id = state.id;
50
- this._createdAt = require_temporal_guards.cloneDate(state.createdAt);
51
- this._updatedAt = require_temporal_guards.cloneDate(state.updatedAt);
52
- this._aggregateVersion = state.aggregateVersion;
53
- }
54
- /** The entity's stable identity — the basis for equality between entities. */
55
- get id() {
56
- return this._id;
57
- }
58
- /**
59
- * When the entity was first created.
60
- *
61
- * Returns a clone so callers cannot mutate the entity's internal `Date`;
62
- * the value is fixed at construction and never changes thereafter.
63
- */
64
- get createdAt() {
65
- return require_temporal_guards.cloneDate(this._createdAt);
66
- }
67
- /**
68
- * When the entity was last modified.
69
- *
70
- * Returns a clone for the same encapsulation reason as {@link createdAt};
71
- * the underlying value advances only through {@link markAsModified}.
72
- */
73
- get updatedAt() {
74
- return require_temporal_guards.cloneDate(this._updatedAt);
75
- }
76
- /**
77
- * Monotonic counter incremented on every mutation, used for optimistic
78
- * concurrency control: a writer reads this value, and the persistence layer
79
- * rejects the write if the stored version has moved on in the meantime.
80
- */
81
- get aggregateVersion() {
82
- return this._aggregateVersion;
83
- }
84
- /**
85
- * The schema/contract version stamped on this entity type by the
86
- * `@version` decorator — used to detect and migrate state persisted under
87
- * an older shape.
88
- */
89
- get contractVersion() {
90
- return _Entity.CONTRACT_VERSION;
91
- }
92
- /**
93
- * The single seam through which an entity records a mutation: it advances
94
- * `updatedAt` and bumps {@link aggregateVersion} by one. Subclasses must
95
- * call this from every state-changing method so the version counter stays
96
- * an accurate optimistic-lock token.
97
- *
98
- * @param updatedAt - The modification instant; defaults to now. Validated
99
- * and required not to predate `createdAt`, preserving the same invariant
100
- * the constructor enforces.
101
- * @returns The new aggregate version after the increment.
102
- * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.
103
- */
104
- markAsModified(updatedAt = /* @__PURE__ */ new Date()) {
105
- require_temporal_guards.assertValidDate("updatedAt", updatedAt);
106
- if (updatedAt.getTime() < this._createdAt.getTime()) throw new require_invariant_violation_exception.InvariantViolationException("updatedAt cannot be earlier than createdAt");
107
- this._updatedAt = require_temporal_guards.cloneDate(updatedAt);
108
- this._aggregateVersion += 1;
109
- return this._aggregateVersion;
110
- }
111
- };
112
- Entity = _Entity = require_immutable.__decorate([require_immutable.version("1.0")], Entity);
113
- //#endregion
114
3
  //#region src/core/domain/value-object.ts
115
4
  var _ValueObject;
116
5
  /**
@@ -186,23 +75,11 @@ let ValueObject = class ValueObject {
186
75
  };
187
76
  ValueObject = _ValueObject = require_immutable.__decorate([require_immutable.version("1.0")], ValueObject);
188
77
  //#endregion
189
- Object.defineProperty(exports, "Entity", {
190
- enumerable: true,
191
- get: function() {
192
- return Entity;
193
- }
194
- });
195
78
  Object.defineProperty(exports, "ValueObject", {
196
79
  enumerable: true,
197
80
  get: function() {
198
81
  return ValueObject;
199
82
  }
200
83
  });
201
- Object.defineProperty(exports, "assertValidAggregateVersion", {
202
- enumerable: true,
203
- get: function() {
204
- return assertValidAggregateVersion;
205
- }
206
- });
207
84
 
208
85
  //# sourceMappingURL=value-object.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"value-object.cjs","names":["InvariantViolationException","InvariantViolationException","cloneDate","version","PluginManager","makeImmutable","version"],"sources":["../src/core/shared/aggregate-version.ts","../src/core/domain/entity.ts","../src/core/domain/value-object.ts"],"sourcesContent":["import { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\n\nfunction assertValidAggregateVersion(aggregateVersion: number): void {\n if (!Number.isInteger(aggregateVersion) || aggregateVersion < 0) {\n throw new InvariantViolationException(\n `aggregateVersion must be a non-negative integer. Received: ${aggregateVersion}`,\n );\n }\n}\n\nexport { assertValidAggregateVersion };\n","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\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 `updatedAt` is earlier than `createdAt`.\n */\n protected constructor(state: EntityState<TIdentifier>) {\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 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 * @param updatedAt - The modification instant; defaults to now. Validated\n * and required not to predate `createdAt`, preserving the same invariant\n * the constructor enforces.\n * @returns The new aggregate version after the increment.\n * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.\n */\n protected markAsModified(updatedAt: Date = new Date()): number {\n assertValidDate(\"updatedAt\", updatedAt);\n\n if (updatedAt.getTime() < this._createdAt.getTime()) {\n throw new InvariantViolationException(\n \"updatedAt cannot be earlier than createdAt\",\n );\n }\n\n this._updatedAt = cloneDate(updatedAt);\n this._aggregateVersion += 1;\n\n return this._aggregateVersion;\n }\n}\n\nexport { Entity, type EntityState };\n","import { PluginManager } from \"../plugins/index.js\";\nimport { type DeepReadonly, makeImmutable } from \"../shared/immutable.js\";\nimport { type ContractVersion, version } from \"../versioning/version.js\";\n\n/**\n * Extension point for value-object equality. A plugin implementing this\n * contract overrides how any two value objects are compared, letting the host\n * application swap in a structural comparator (e.g. `lodash.isEqual` over the\n * wrapped `value`) without every value object having to implement `equals` by\n * hand.\n */\ntype ValueObjectPluginContract = {\n equals: (\n a: ValueObject<unknown, unknown>,\n b: ValueObject<unknown, unknown>,\n ) => boolean;\n};\n\n/**\n * Base class for value objects — domain concepts defined entirely by their\n * contents, with no identity of their own. Two value objects are\n * interchangeable when they hold equal data, which is the opposite of an\n * {@link Entity} (compared by id). Money, a CPF, a date range: replacing one\n * instance with an equal one changes nothing about the model.\n *\n * Immutability is the defining guarantee here. The wrapped `value` is\n * deep-frozen on construction, so a value object can be shared freely without\n * any risk of a consumer mutating shared state. Subclasses seal the instance\n * itself with {@link finalize} once their own fields are set.\n *\n * @typeParam T - The shape of the wrapped data.\n * @typeParam P - The primitive form produced by {@link toPrimitive} / {@link toJSON}.\n */\n@version(\"1.0\")\nabstract class ValueObject<T, P> {\n declare public static readonly CONTRACT_VERSION: ContractVersion;\n\n /**\n * Registry of equality plugins shared by every value object. Empty by\n * default — when nothing is registered, {@link equals} falls back to a\n * structural comparison of the wrapped `value`. Hosts register a plugin\n * (e.g. `lodash.isEqual`) once at startup to customise equality globally.\n */\n public static readonly plugins =\n new PluginManager<ValueObjectPluginContract>();\n\n /** The wrapped data, deep-frozen so it can never be mutated after construction. */\n public readonly value: DeepReadonly<T>;\n\n /**\n * Wraps `value`, deep-freezing it so the value object is immutable from the\n * moment it exists. Declared `protected` because value objects are built\n * through a validating subclass factory, never instantiated directly.\n */\n protected constructor(value: T) {\n this.value = makeImmutable(value);\n }\n\n /**\n * The schema/contract version stamped on this value-object type by the\n * `@version` decorator — used to detect state persisted under an older shape.\n */\n public get contractVersion(): ContractVersion {\n return ValueObject.CONTRACT_VERSION;\n }\n\n /**\n * Freezes the instance shell, blocking reassignment of any own field.\n *\n * `value` is already deep-frozen by the constructor, so the wrapped data is\n * immutable regardless. The instance itself is NOT frozen automatically\n * because a subclass may still need to assign its own fields after\n * `super(value)` runs. Call `finalize()` at the very end of the subclass\n * constructor (after all fields are set) to make the whole value object\n * immutable.\n */\n protected finalize(): void {\n Object.freeze(this);\n }\n\n /**\n * Hook for `JSON.stringify`. Delegates to {@link toPrimitive} so a value\n * object serializes to its primitive form rather than exposing the internal\n * `value` wrapper.\n */\n public toJSON(): P {\n return this.toPrimitive();\n }\n\n /**\n * Compares this value object with another by content. Because value objects\n * carry no identity, two independently constructed instances holding the\n * same data are considered equal.\n *\n * Delegates to the registered equality {@link plugins}; with no plugin\n * registered it falls back to comparing the serialized wrapped `value`.\n * Subclasses may still override for a faster or domain-specific comparison.\n */\n public equals(other: this): boolean {\n return ValueObject.plugins.invoke(\"equals\", [this, other], {\n fallback: (a, b) =>\n JSON.stringify(a.value) === JSON.stringify(b.value),\n });\n }\n\n /**\n * Projects the value object down to a plain, serializable primitive form —\n * the representation suitable for persistence, transport, or comparison.\n */\n public abstract toPrimitive(): P;\n}\n\nexport { type DeepReadonly, ValueObject, type ValueObjectPluginContract };\n"],"mappings":";;;;;AAEA,SAAS,4BAA4B,kBAAgC;CACjE,IAAI,CAAC,OAAO,UAAU,gBAAgB,KAAK,mBAAmB,GAC1D,MAAM,IAAIA,sCAAAA,4BACN,8DAA8D,kBAClE;AAER;;;;;;;;;;;;;;;;;;AC0BA,IAAA,SAAA,MACe,OAAoB;;;;;;;;;;;;;;;;;;CAsB/B,YAAsB,OAAiC;EACnD,wBAAA,gBAAgB,aAAa,MAAM,SAAS;EAC5C,wBAAA,gBAAgB,aAAa,MAAM,SAAS;EAC5C,4BAA4B,MAAM,gBAAgB;EAElD,IAAI,MAAM,UAAU,QAAQ,IAAI,MAAM,UAAU,QAAQ,GACpD,MAAM,IAAIC,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,OAAA,QAAc;CAClB;;;;;;;;;;;;;CAcA,eAAyB,4BAAkB,IAAI,KAAK,GAAW;EAC3D,wBAAA,gBAAgB,aAAa,SAAS;EAEtC,IAAI,UAAU,QAAQ,IAAI,KAAK,WAAW,QAAQ,GAC9C,MAAM,IAAID,sCAAAA,4BACN,4CACJ;EAGJ,KAAK,aAAaC,wBAAAA,UAAU,SAAS;EACrC,KAAK,qBAAqB;EAE1B,OAAO,KAAK;CAChB;AACJ;iDA7GCC,kBAAAA,QAAQ,KAAK,CAAA,GAAA,MAAA;;;;;;;;;;;;;;;;;;;ACDd,IAAA,cAAA,MACe,YAAkB;;;;;iBAUzB,IAAIC,eAAAA,cAAyC;;;;;;;CAUjD,YAAsB,OAAU;EAC5B,KAAK,QAAQC,kBAAAA,cAAc,KAAK;CACpC;;;;;CAMA,IAAW,kBAAmC;EAC1C,OAAA,aAAmB;CACvB;;;;;;;;;;;CAYA,WAA2B;EACvB,OAAO,OAAO,IAAI;CACtB;;;;;;CAOA,SAAmB;EACf,OAAO,KAAK,YAAY;CAC5B;;;;;;;;;;CAWA,OAAc,OAAsB;EAChC,OAAA,aAAmB,QAAQ,OAAO,UAAU,CAAC,MAAM,KAAK,GAAG,EACvD,WAAW,GAAG,MACV,KAAK,UAAU,EAAE,KAAK,MAAM,KAAK,UAAU,EAAE,KAAK,EAC1D,CAAC;CACL;AAOJ;2DA7ECC,kBAAAA,QAAQ,KAAK,CAAA,GAAA,WAAA"}
1
+ {"version":3,"file":"value-object.cjs","names":["PluginManager","makeImmutable","version"],"sources":["../src/core/domain/value-object.ts"],"sourcesContent":["import { PluginManager } from \"../plugins/index.js\";\nimport { type DeepReadonly, makeImmutable } from \"../shared/immutable.js\";\nimport { type ContractVersion, version } from \"../versioning/version.js\";\n\n/**\n * Extension point for value-object equality. A plugin implementing this\n * contract overrides how any two value objects are compared, letting the host\n * application swap in a structural comparator (e.g. `lodash.isEqual` over the\n * wrapped `value`) without every value object having to implement `equals` by\n * hand.\n */\ntype ValueObjectPluginContract = {\n equals: (\n a: ValueObject<unknown, unknown>,\n b: ValueObject<unknown, unknown>,\n ) => boolean;\n};\n\n/**\n * Base class for value objects — domain concepts defined entirely by their\n * contents, with no identity of their own. Two value objects are\n * interchangeable when they hold equal data, which is the opposite of an\n * {@link Entity} (compared by id). Money, a CPF, a date range: replacing one\n * instance with an equal one changes nothing about the model.\n *\n * Immutability is the defining guarantee here. The wrapped `value` is\n * deep-frozen on construction, so a value object can be shared freely without\n * any risk of a consumer mutating shared state. Subclasses seal the instance\n * itself with {@link finalize} once their own fields are set.\n *\n * @typeParam T - The shape of the wrapped data.\n * @typeParam P - The primitive form produced by {@link toPrimitive} / {@link toJSON}.\n */\n@version(\"1.0\")\nabstract class ValueObject<T, P> {\n declare public static readonly CONTRACT_VERSION: ContractVersion;\n\n /**\n * Registry of equality plugins shared by every value object. Empty by\n * default — when nothing is registered, {@link equals} falls back to a\n * structural comparison of the wrapped `value`. Hosts register a plugin\n * (e.g. `lodash.isEqual`) once at startup to customise equality globally.\n */\n public static readonly plugins =\n new PluginManager<ValueObjectPluginContract>();\n\n /** The wrapped data, deep-frozen so it can never be mutated after construction. */\n public readonly value: DeepReadonly<T>;\n\n /**\n * Wraps `value`, deep-freezing it so the value object is immutable from the\n * moment it exists. Declared `protected` because value objects are built\n * through a validating subclass factory, never instantiated directly.\n */\n protected constructor(value: T) {\n this.value = makeImmutable(value);\n }\n\n /**\n * The schema/contract version stamped on this value-object type by the\n * `@version` decorator — used to detect state persisted under an older shape.\n */\n public get contractVersion(): ContractVersion {\n return ValueObject.CONTRACT_VERSION;\n }\n\n /**\n * Freezes the instance shell, blocking reassignment of any own field.\n *\n * `value` is already deep-frozen by the constructor, so the wrapped data is\n * immutable regardless. The instance itself is NOT frozen automatically\n * because a subclass may still need to assign its own fields after\n * `super(value)` runs. Call `finalize()` at the very end of the subclass\n * constructor (after all fields are set) to make the whole value object\n * immutable.\n */\n protected finalize(): void {\n Object.freeze(this);\n }\n\n /**\n * Hook for `JSON.stringify`. Delegates to {@link toPrimitive} so a value\n * object serializes to its primitive form rather than exposing the internal\n * `value` wrapper.\n */\n public toJSON(): P {\n return this.toPrimitive();\n }\n\n /**\n * Compares this value object with another by content. Because value objects\n * carry no identity, two independently constructed instances holding the\n * same data are considered equal.\n *\n * Delegates to the registered equality {@link plugins}; with no plugin\n * registered it falls back to comparing the serialized wrapped `value`.\n * Subclasses may still override for a faster or domain-specific comparison.\n */\n public equals(other: this): boolean {\n return ValueObject.plugins.invoke(\"equals\", [this, other], {\n fallback: (a, b) =>\n JSON.stringify(a.value) === JSON.stringify(b.value),\n });\n }\n\n /**\n * Projects the value object down to a plain, serializable primitive form —\n * the representation suitable for persistence, transport, or comparison.\n */\n public abstract toPrimitive(): P;\n}\n\nexport { type DeepReadonly, ValueObject, type ValueObjectPluginContract };\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiCA,IAAA,cAAA,MACe,YAAkB;;;;;iBAUzB,IAAIA,eAAAA,cAAyC;;;;;;;CAUjD,YAAsB,OAAU;EAC5B,KAAK,QAAQC,kBAAAA,cAAc,KAAK;CACpC;;;;;CAMA,IAAW,kBAAmC;EAC1C,OAAA,aAAmB;CACvB;;;;;;;;;;;CAYA,WAA2B;EACvB,OAAO,OAAO,IAAI;CACtB;;;;;;CAOA,SAAmB;EACf,OAAO,KAAK,YAAY;CAC5B;;;;;;;;;;CAWA,OAAc,OAAsB;EAChC,OAAA,aAAmB,QAAQ,OAAO,UAAU,CAAC,MAAM,KAAK,GAAG,EACvD,WAAW,GAAG,MACV,KAAK,UAAU,EAAE,KAAK,MAAM,KAAK,UAAU,EAAE,KAAK,EAC1D,CAAC;CACL;AAOJ;2DA7ECC,kBAAAA,QAAQ,KAAK,CAAA,GAAA,WAAA"}
@@ -0,0 +1,89 @@
1
+ import { t as PluginManager } from "./plugin.cjs";
2
+ import { t as DeepReadonly } from "./immutable.cjs";
3
+ import { n as ContractVersion } from "./version.cjs";
4
+
5
+ //#region src/core/domain/value-object.d.ts
6
+
7
+ /**
8
+ * Extension point for value-object equality. A plugin implementing this
9
+ * contract overrides how any two value objects are compared, letting the host
10
+ * application swap in a structural comparator (e.g. `lodash.isEqual` over the
11
+ * wrapped `value`) without every value object having to implement `equals` by
12
+ * hand.
13
+ */
14
+ type ValueObjectPluginContract = {
15
+ equals: (a: ValueObject<unknown, unknown>, b: ValueObject<unknown, unknown>) => boolean;
16
+ };
17
+ /**
18
+ * Base class for value objects — domain concepts defined entirely by their
19
+ * contents, with no identity of their own. Two value objects are
20
+ * interchangeable when they hold equal data, which is the opposite of an
21
+ * {@link Entity} (compared by id). Money, a CPF, a date range: replacing one
22
+ * instance with an equal one changes nothing about the model.
23
+ *
24
+ * Immutability is the defining guarantee here. The wrapped `value` is
25
+ * deep-frozen on construction, so a value object can be shared freely without
26
+ * any risk of a consumer mutating shared state. Subclasses seal the instance
27
+ * itself with {@link finalize} once their own fields are set.
28
+ *
29
+ * @typeParam T - The shape of the wrapped data.
30
+ * @typeParam P - The primitive form produced by {@link toPrimitive} / {@link toJSON}.
31
+ */
32
+ declare abstract class ValueObject<T, P> {
33
+ static readonly CONTRACT_VERSION: ContractVersion;
34
+ /**
35
+ * Registry of equality plugins shared by every value object. Empty by
36
+ * default — when nothing is registered, {@link equals} falls back to a
37
+ * structural comparison of the wrapped `value`. Hosts register a plugin
38
+ * (e.g. `lodash.isEqual`) once at startup to customise equality globally.
39
+ */
40
+ static readonly plugins: PluginManager<ValueObjectPluginContract>;
41
+ /** The wrapped data, deep-frozen so it can never be mutated after construction. */
42
+ readonly value: DeepReadonly<T>;
43
+ /**
44
+ * Wraps `value`, deep-freezing it so the value object is immutable from the
45
+ * moment it exists. Declared `protected` because value objects are built
46
+ * through a validating subclass factory, never instantiated directly.
47
+ */
48
+ protected constructor(value: T);
49
+ /**
50
+ * The schema/contract version stamped on this value-object type by the
51
+ * `@version` decorator — used to detect state persisted under an older shape.
52
+ */
53
+ get contractVersion(): ContractVersion;
54
+ /**
55
+ * Freezes the instance shell, blocking reassignment of any own field.
56
+ *
57
+ * `value` is already deep-frozen by the constructor, so the wrapped data is
58
+ * immutable regardless. The instance itself is NOT frozen automatically
59
+ * because a subclass may still need to assign its own fields after
60
+ * `super(value)` runs. Call `finalize()` at the very end of the subclass
61
+ * constructor (after all fields are set) to make the whole value object
62
+ * immutable.
63
+ */
64
+ protected finalize(): void;
65
+ /**
66
+ * Hook for `JSON.stringify`. Delegates to {@link toPrimitive} so a value
67
+ * object serializes to its primitive form rather than exposing the internal
68
+ * `value` wrapper.
69
+ */
70
+ toJSON(): P;
71
+ /**
72
+ * Compares this value object with another by content. Because value objects
73
+ * carry no identity, two independently constructed instances holding the
74
+ * same data are considered equal.
75
+ *
76
+ * Delegates to the registered equality {@link plugins}; with no plugin
77
+ * registered it falls back to comparing the serialized wrapped `value`.
78
+ * Subclasses may still override for a faster or domain-specific comparison.
79
+ */
80
+ equals(other: this): boolean;
81
+ /**
82
+ * Projects the value object down to a plain, serializable primitive form —
83
+ * the representation suitable for persistence, transport, or comparison.
84
+ */
85
+ abstract toPrimitive(): P;
86
+ }
87
+ //#endregion
88
+ export { ValueObjectPluginContract as n, ValueObject as t };
89
+ //# sourceMappingURL=value-object.d.cts.map
@@ -0,0 +1,89 @@
1
+ import { t as PluginManager } from "./plugin.js";
2
+ import { t as DeepReadonly } from "./immutable.js";
3
+ import { n as ContractVersion } from "./version.js";
4
+
5
+ //#region src/core/domain/value-object.d.ts
6
+
7
+ /**
8
+ * Extension point for value-object equality. A plugin implementing this
9
+ * contract overrides how any two value objects are compared, letting the host
10
+ * application swap in a structural comparator (e.g. `lodash.isEqual` over the
11
+ * wrapped `value`) without every value object having to implement `equals` by
12
+ * hand.
13
+ */
14
+ type ValueObjectPluginContract = {
15
+ equals: (a: ValueObject<unknown, unknown>, b: ValueObject<unknown, unknown>) => boolean;
16
+ };
17
+ /**
18
+ * Base class for value objects — domain concepts defined entirely by their
19
+ * contents, with no identity of their own. Two value objects are
20
+ * interchangeable when they hold equal data, which is the opposite of an
21
+ * {@link Entity} (compared by id). Money, a CPF, a date range: replacing one
22
+ * instance with an equal one changes nothing about the model.
23
+ *
24
+ * Immutability is the defining guarantee here. The wrapped `value` is
25
+ * deep-frozen on construction, so a value object can be shared freely without
26
+ * any risk of a consumer mutating shared state. Subclasses seal the instance
27
+ * itself with {@link finalize} once their own fields are set.
28
+ *
29
+ * @typeParam T - The shape of the wrapped data.
30
+ * @typeParam P - The primitive form produced by {@link toPrimitive} / {@link toJSON}.
31
+ */
32
+ declare abstract class ValueObject<T, P> {
33
+ static readonly CONTRACT_VERSION: ContractVersion;
34
+ /**
35
+ * Registry of equality plugins shared by every value object. Empty by
36
+ * default — when nothing is registered, {@link equals} falls back to a
37
+ * structural comparison of the wrapped `value`. Hosts register a plugin
38
+ * (e.g. `lodash.isEqual`) once at startup to customise equality globally.
39
+ */
40
+ static readonly plugins: PluginManager<ValueObjectPluginContract>;
41
+ /** The wrapped data, deep-frozen so it can never be mutated after construction. */
42
+ readonly value: DeepReadonly<T>;
43
+ /**
44
+ * Wraps `value`, deep-freezing it so the value object is immutable from the
45
+ * moment it exists. Declared `protected` because value objects are built
46
+ * through a validating subclass factory, never instantiated directly.
47
+ */
48
+ protected constructor(value: T);
49
+ /**
50
+ * The schema/contract version stamped on this value-object type by the
51
+ * `@version` decorator — used to detect state persisted under an older shape.
52
+ */
53
+ get contractVersion(): ContractVersion;
54
+ /**
55
+ * Freezes the instance shell, blocking reassignment of any own field.
56
+ *
57
+ * `value` is already deep-frozen by the constructor, so the wrapped data is
58
+ * immutable regardless. The instance itself is NOT frozen automatically
59
+ * because a subclass may still need to assign its own fields after
60
+ * `super(value)` runs. Call `finalize()` at the very end of the subclass
61
+ * constructor (after all fields are set) to make the whole value object
62
+ * immutable.
63
+ */
64
+ protected finalize(): void;
65
+ /**
66
+ * Hook for `JSON.stringify`. Delegates to {@link toPrimitive} so a value
67
+ * object serializes to its primitive form rather than exposing the internal
68
+ * `value` wrapper.
69
+ */
70
+ toJSON(): P;
71
+ /**
72
+ * Compares this value object with another by content. Because value objects
73
+ * carry no identity, two independently constructed instances holding the
74
+ * same data are considered equal.
75
+ *
76
+ * Delegates to the registered equality {@link plugins}; with no plugin
77
+ * registered it falls back to comparing the serialized wrapped `value`.
78
+ * Subclasses may still override for a faster or domain-specific comparison.
79
+ */
80
+ equals(other: this): boolean;
81
+ /**
82
+ * Projects the value object down to a plain, serializable primitive form —
83
+ * the representation suitable for persistence, transport, or comparison.
84
+ */
85
+ abstract toPrimitive(): P;
86
+ }
87
+ //#endregion
88
+ export { ValueObjectPluginContract as n, ValueObject as t };
89
+ //# sourceMappingURL=value-object.d.ts.map
@@ -1,116 +1,5 @@
1
- import { t as InvariantViolationException } from "./invariant-violation-exception.js";
2
1
  import { i as version, n as __decorate, t as makeImmutable } from "./immutable.js";
3
- import { n as cloneDate, t as assertValidDate } from "./temporal-guards.js";
4
2
  import { t as PluginManager } from "./plugin.js";
5
- //#region src/core/shared/aggregate-version.ts
6
- function assertValidAggregateVersion(aggregateVersion) {
7
- if (!Number.isInteger(aggregateVersion) || aggregateVersion < 0) throw new InvariantViolationException(`aggregateVersion must be a non-negative integer. Received: ${aggregateVersion}`);
8
- }
9
- //#endregion
10
- //#region src/core/domain/entity.ts
11
- var _Entity;
12
- /**
13
- * Base class for domain entities — objects defined by a stable identity rather
14
- * than by their attributes. Two entities are "the same" when their `id`
15
- * matches, even if every other field differs; this is the opposite of a
16
- * {@link ValueObject}, which is defined entirely by its contents.
17
- *
18
- * The class owns the bookkeeping common to every aggregate root: a creation
19
- * timestamp that never changes, a last-modified timestamp, and an
20
- * `aggregateVersion` counter used for optimistic concurrency control. All three
21
- * are validated on construction and the dates are defensively cloned, so an
22
- * entity can never be built into — or leak — an inconsistent temporal state.
23
- *
24
- * @typeParam TIdentifier - The identity type (e.g. a branded string id or a VO).
25
- */
26
- let Entity = class Entity {
27
- static {
28
- _Entity = this;
29
- }
30
- /**
31
- * Reconstitutes an entity from its persisted {@link EntityState}.
32
- *
33
- * Validates the temporal invariants up front so an invalid entity is
34
- * impossible to construct: both dates must be valid, the aggregate version
35
- * must be a non-negative integer, and `updatedAt` may not predate
36
- * `createdAt`. Both dates are cloned on the way in so a later mutation of
37
- * the caller's `Date` objects cannot reach into the entity's internal state.
38
- *
39
- * Declared `protected` because entities are reconstituted through a
40
- * subclass factory, never instantiated directly by application code.
41
- *
42
- * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.
43
- */
44
- constructor(state) {
45
- assertValidDate("createdAt", state.createdAt);
46
- assertValidDate("updatedAt", state.updatedAt);
47
- assertValidAggregateVersion(state.aggregateVersion);
48
- if (state.updatedAt.getTime() < state.createdAt.getTime()) throw new InvariantViolationException("updatedAt cannot be earlier than createdAt");
49
- this._id = state.id;
50
- this._createdAt = cloneDate(state.createdAt);
51
- this._updatedAt = cloneDate(state.updatedAt);
52
- this._aggregateVersion = state.aggregateVersion;
53
- }
54
- /** The entity's stable identity — the basis for equality between entities. */
55
- get id() {
56
- return this._id;
57
- }
58
- /**
59
- * When the entity was first created.
60
- *
61
- * Returns a clone so callers cannot mutate the entity's internal `Date`;
62
- * the value is fixed at construction and never changes thereafter.
63
- */
64
- get createdAt() {
65
- return cloneDate(this._createdAt);
66
- }
67
- /**
68
- * When the entity was last modified.
69
- *
70
- * Returns a clone for the same encapsulation reason as {@link createdAt};
71
- * the underlying value advances only through {@link markAsModified}.
72
- */
73
- get updatedAt() {
74
- return cloneDate(this._updatedAt);
75
- }
76
- /**
77
- * Monotonic counter incremented on every mutation, used for optimistic
78
- * concurrency control: a writer reads this value, and the persistence layer
79
- * rejects the write if the stored version has moved on in the meantime.
80
- */
81
- get aggregateVersion() {
82
- return this._aggregateVersion;
83
- }
84
- /**
85
- * The schema/contract version stamped on this entity type by the
86
- * `@version` decorator — used to detect and migrate state persisted under
87
- * an older shape.
88
- */
89
- get contractVersion() {
90
- return _Entity.CONTRACT_VERSION;
91
- }
92
- /**
93
- * The single seam through which an entity records a mutation: it advances
94
- * `updatedAt` and bumps {@link aggregateVersion} by one. Subclasses must
95
- * call this from every state-changing method so the version counter stays
96
- * an accurate optimistic-lock token.
97
- *
98
- * @param updatedAt - The modification instant; defaults to now. Validated
99
- * and required not to predate `createdAt`, preserving the same invariant
100
- * the constructor enforces.
101
- * @returns The new aggregate version after the increment.
102
- * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.
103
- */
104
- markAsModified(updatedAt = /* @__PURE__ */ new Date()) {
105
- assertValidDate("updatedAt", updatedAt);
106
- if (updatedAt.getTime() < this._createdAt.getTime()) throw new InvariantViolationException("updatedAt cannot be earlier than createdAt");
107
- this._updatedAt = cloneDate(updatedAt);
108
- this._aggregateVersion += 1;
109
- return this._aggregateVersion;
110
- }
111
- };
112
- Entity = _Entity = __decorate([version("1.0")], Entity);
113
- //#endregion
114
3
  //#region src/core/domain/value-object.ts
115
4
  var _ValueObject;
116
5
  /**
@@ -186,6 +75,6 @@ let ValueObject = class ValueObject {
186
75
  };
187
76
  ValueObject = _ValueObject = __decorate([version("1.0")], ValueObject);
188
77
  //#endregion
189
- export { Entity as n, assertValidAggregateVersion as r, ValueObject as t };
78
+ export { ValueObject as t };
190
79
 
191
80
  //# sourceMappingURL=value-object.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"value-object.js","names":[],"sources":["../src/core/shared/aggregate-version.ts","../src/core/domain/entity.ts","../src/core/domain/value-object.ts"],"sourcesContent":["import { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\n\nfunction assertValidAggregateVersion(aggregateVersion: number): void {\n if (!Number.isInteger(aggregateVersion) || aggregateVersion < 0) {\n throw new InvariantViolationException(\n `aggregateVersion must be a non-negative integer. Received: ${aggregateVersion}`,\n );\n }\n}\n\nexport { assertValidAggregateVersion };\n","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\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 `updatedAt` is earlier than `createdAt`.\n */\n protected constructor(state: EntityState<TIdentifier>) {\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 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 * @param updatedAt - The modification instant; defaults to now. Validated\n * and required not to predate `createdAt`, preserving the same invariant\n * the constructor enforces.\n * @returns The new aggregate version after the increment.\n * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.\n */\n protected markAsModified(updatedAt: Date = new Date()): number {\n assertValidDate(\"updatedAt\", updatedAt);\n\n if (updatedAt.getTime() < this._createdAt.getTime()) {\n throw new InvariantViolationException(\n \"updatedAt cannot be earlier than createdAt\",\n );\n }\n\n this._updatedAt = cloneDate(updatedAt);\n this._aggregateVersion += 1;\n\n return this._aggregateVersion;\n }\n}\n\nexport { Entity, type EntityState };\n","import { PluginManager } from \"../plugins/index.js\";\nimport { type DeepReadonly, makeImmutable } from \"../shared/immutable.js\";\nimport { type ContractVersion, version } from \"../versioning/version.js\";\n\n/**\n * Extension point for value-object equality. A plugin implementing this\n * contract overrides how any two value objects are compared, letting the host\n * application swap in a structural comparator (e.g. `lodash.isEqual` over the\n * wrapped `value`) without every value object having to implement `equals` by\n * hand.\n */\ntype ValueObjectPluginContract = {\n equals: (\n a: ValueObject<unknown, unknown>,\n b: ValueObject<unknown, unknown>,\n ) => boolean;\n};\n\n/**\n * Base class for value objects — domain concepts defined entirely by their\n * contents, with no identity of their own. Two value objects are\n * interchangeable when they hold equal data, which is the opposite of an\n * {@link Entity} (compared by id). Money, a CPF, a date range: replacing one\n * instance with an equal one changes nothing about the model.\n *\n * Immutability is the defining guarantee here. The wrapped `value` is\n * deep-frozen on construction, so a value object can be shared freely without\n * any risk of a consumer mutating shared state. Subclasses seal the instance\n * itself with {@link finalize} once their own fields are set.\n *\n * @typeParam T - The shape of the wrapped data.\n * @typeParam P - The primitive form produced by {@link toPrimitive} / {@link toJSON}.\n */\n@version(\"1.0\")\nabstract class ValueObject<T, P> {\n declare public static readonly CONTRACT_VERSION: ContractVersion;\n\n /**\n * Registry of equality plugins shared by every value object. Empty by\n * default — when nothing is registered, {@link equals} falls back to a\n * structural comparison of the wrapped `value`. Hosts register a plugin\n * (e.g. `lodash.isEqual`) once at startup to customise equality globally.\n */\n public static readonly plugins =\n new PluginManager<ValueObjectPluginContract>();\n\n /** The wrapped data, deep-frozen so it can never be mutated after construction. */\n public readonly value: DeepReadonly<T>;\n\n /**\n * Wraps `value`, deep-freezing it so the value object is immutable from the\n * moment it exists. Declared `protected` because value objects are built\n * through a validating subclass factory, never instantiated directly.\n */\n protected constructor(value: T) {\n this.value = makeImmutable(value);\n }\n\n /**\n * The schema/contract version stamped on this value-object type by the\n * `@version` decorator — used to detect state persisted under an older shape.\n */\n public get contractVersion(): ContractVersion {\n return ValueObject.CONTRACT_VERSION;\n }\n\n /**\n * Freezes the instance shell, blocking reassignment of any own field.\n *\n * `value` is already deep-frozen by the constructor, so the wrapped data is\n * immutable regardless. The instance itself is NOT frozen automatically\n * because a subclass may still need to assign its own fields after\n * `super(value)` runs. Call `finalize()` at the very end of the subclass\n * constructor (after all fields are set) to make the whole value object\n * immutable.\n */\n protected finalize(): void {\n Object.freeze(this);\n }\n\n /**\n * Hook for `JSON.stringify`. Delegates to {@link toPrimitive} so a value\n * object serializes to its primitive form rather than exposing the internal\n * `value` wrapper.\n */\n public toJSON(): P {\n return this.toPrimitive();\n }\n\n /**\n * Compares this value object with another by content. Because value objects\n * carry no identity, two independently constructed instances holding the\n * same data are considered equal.\n *\n * Delegates to the registered equality {@link plugins}; with no plugin\n * registered it falls back to comparing the serialized wrapped `value`.\n * Subclasses may still override for a faster or domain-specific comparison.\n */\n public equals(other: this): boolean {\n return ValueObject.plugins.invoke(\"equals\", [this, other], {\n fallback: (a, b) =>\n JSON.stringify(a.value) === JSON.stringify(b.value),\n });\n }\n\n /**\n * Projects the value object down to a plain, serializable primitive form —\n * the representation suitable for persistence, transport, or comparison.\n */\n public abstract toPrimitive(): P;\n}\n\nexport { type DeepReadonly, ValueObject, type ValueObjectPluginContract };\n"],"mappings":";;;;;AAEA,SAAS,4BAA4B,kBAAgC;CACjE,IAAI,CAAC,OAAO,UAAU,gBAAgB,KAAK,mBAAmB,GAC1D,MAAM,IAAI,4BACN,8DAA8D,kBAClE;AAER;;;;;;;;;;;;;;;;;;AC0BA,IAAA,SAAA,MACe,OAAoB;;;;;;;;;;;;;;;;;;CAsB/B,YAAsB,OAAiC;EACnD,gBAAgB,aAAa,MAAM,SAAS;EAC5C,gBAAgB,aAAa,MAAM,SAAS;EAC5C,4BAA4B,MAAM,gBAAgB;EAElD,IAAI,MAAM,UAAU,QAAQ,IAAI,MAAM,UAAU,QAAQ,GACpD,MAAM,IAAI,4BACN,4CACJ;EAGJ,KAAK,MAAM,MAAM;EACjB,KAAK,aAAa,UAAU,MAAM,SAAS;EAC3C,KAAK,aAAa,UAAU,MAAM,SAAS;EAC3C,KAAK,oBAAoB,MAAM;CACnC;;CAGA,IAAW,KAAkB;EACzB,OAAO,KAAK;CAChB;;;;;;;CAQA,IAAW,YAAkB;EACzB,OAAO,UAAU,KAAK,UAAU;CACpC;;;;;;;CAQA,IAAW,YAAkB;EACzB,OAAO,UAAU,KAAK,UAAU;CACpC;;;;;;CAOA,IAAW,mBAA2B;EAClC,OAAO,KAAK;CAChB;;;;;;CAOA,IAAW,kBAAmC;EAC1C,OAAA,QAAc;CAClB;;;;;;;;;;;;;CAcA,eAAyB,4BAAkB,IAAI,KAAK,GAAW;EAC3D,gBAAgB,aAAa,SAAS;EAEtC,IAAI,UAAU,QAAQ,IAAI,KAAK,WAAW,QAAQ,GAC9C,MAAM,IAAI,4BACN,4CACJ;EAGJ,KAAK,aAAa,UAAU,SAAS;EACrC,KAAK,qBAAqB;EAE1B,OAAO,KAAK;CAChB;AACJ;+BA7GC,QAAQ,KAAK,CAAA,GAAA,MAAA;;;;;;;;;;;;;;;;;;;ACDd,IAAA,cAAA,MACe,YAAkB;;;;;iBAUzB,IAAI,cAAyC;;;;;;;CAUjD,YAAsB,OAAU;EAC5B,KAAK,QAAQ,cAAc,KAAK;CACpC;;;;;CAMA,IAAW,kBAAmC;EAC1C,OAAA,aAAmB;CACvB;;;;;;;;;;;CAYA,WAA2B;EACvB,OAAO,OAAO,IAAI;CACtB;;;;;;CAOA,SAAmB;EACf,OAAO,KAAK,YAAY;CAC5B;;;;;;;;;;CAWA,OAAc,OAAsB;EAChC,OAAA,aAAmB,QAAQ,OAAO,UAAU,CAAC,MAAM,KAAK,GAAG,EACvD,WAAW,GAAG,MACV,KAAK,UAAU,EAAE,KAAK,MAAM,KAAK,UAAU,EAAE,KAAK,EAC1D,CAAC;CACL;AAOJ;yCA7EC,QAAQ,KAAK,CAAA,GAAA,WAAA"}
1
+ {"version":3,"file":"value-object.js","names":[],"sources":["../src/core/domain/value-object.ts"],"sourcesContent":["import { PluginManager } from \"../plugins/index.js\";\nimport { type DeepReadonly, makeImmutable } from \"../shared/immutable.js\";\nimport { type ContractVersion, version } from \"../versioning/version.js\";\n\n/**\n * Extension point for value-object equality. A plugin implementing this\n * contract overrides how any two value objects are compared, letting the host\n * application swap in a structural comparator (e.g. `lodash.isEqual` over the\n * wrapped `value`) without every value object having to implement `equals` by\n * hand.\n */\ntype ValueObjectPluginContract = {\n equals: (\n a: ValueObject<unknown, unknown>,\n b: ValueObject<unknown, unknown>,\n ) => boolean;\n};\n\n/**\n * Base class for value objects — domain concepts defined entirely by their\n * contents, with no identity of their own. Two value objects are\n * interchangeable when they hold equal data, which is the opposite of an\n * {@link Entity} (compared by id). Money, a CPF, a date range: replacing one\n * instance with an equal one changes nothing about the model.\n *\n * Immutability is the defining guarantee here. The wrapped `value` is\n * deep-frozen on construction, so a value object can be shared freely without\n * any risk of a consumer mutating shared state. Subclasses seal the instance\n * itself with {@link finalize} once their own fields are set.\n *\n * @typeParam T - The shape of the wrapped data.\n * @typeParam P - The primitive form produced by {@link toPrimitive} / {@link toJSON}.\n */\n@version(\"1.0\")\nabstract class ValueObject<T, P> {\n declare public static readonly CONTRACT_VERSION: ContractVersion;\n\n /**\n * Registry of equality plugins shared by every value object. Empty by\n * default — when nothing is registered, {@link equals} falls back to a\n * structural comparison of the wrapped `value`. Hosts register a plugin\n * (e.g. `lodash.isEqual`) once at startup to customise equality globally.\n */\n public static readonly plugins =\n new PluginManager<ValueObjectPluginContract>();\n\n /** The wrapped data, deep-frozen so it can never be mutated after construction. */\n public readonly value: DeepReadonly<T>;\n\n /**\n * Wraps `value`, deep-freezing it so the value object is immutable from the\n * moment it exists. Declared `protected` because value objects are built\n * through a validating subclass factory, never instantiated directly.\n */\n protected constructor(value: T) {\n this.value = makeImmutable(value);\n }\n\n /**\n * The schema/contract version stamped on this value-object type by the\n * `@version` decorator — used to detect state persisted under an older shape.\n */\n public get contractVersion(): ContractVersion {\n return ValueObject.CONTRACT_VERSION;\n }\n\n /**\n * Freezes the instance shell, blocking reassignment of any own field.\n *\n * `value` is already deep-frozen by the constructor, so the wrapped data is\n * immutable regardless. The instance itself is NOT frozen automatically\n * because a subclass may still need to assign its own fields after\n * `super(value)` runs. Call `finalize()` at the very end of the subclass\n * constructor (after all fields are set) to make the whole value object\n * immutable.\n */\n protected finalize(): void {\n Object.freeze(this);\n }\n\n /**\n * Hook for `JSON.stringify`. Delegates to {@link toPrimitive} so a value\n * object serializes to its primitive form rather than exposing the internal\n * `value` wrapper.\n */\n public toJSON(): P {\n return this.toPrimitive();\n }\n\n /**\n * Compares this value object with another by content. Because value objects\n * carry no identity, two independently constructed instances holding the\n * same data are considered equal.\n *\n * Delegates to the registered equality {@link plugins}; with no plugin\n * registered it falls back to comparing the serialized wrapped `value`.\n * Subclasses may still override for a faster or domain-specific comparison.\n */\n public equals(other: this): boolean {\n return ValueObject.plugins.invoke(\"equals\", [this, other], {\n fallback: (a, b) =>\n JSON.stringify(a.value) === JSON.stringify(b.value),\n });\n }\n\n /**\n * Projects the value object down to a plain, serializable primitive form —\n * the representation suitable for persistence, transport, or comparison.\n */\n public abstract toPrimitive(): P;\n}\n\nexport { type DeepReadonly, ValueObject, type ValueObjectPluginContract };\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiCA,IAAA,cAAA,MACe,YAAkB;;;;;iBAUzB,IAAI,cAAyC;;;;;;;CAUjD,YAAsB,OAAU;EAC5B,KAAK,QAAQ,cAAc,KAAK;CACpC;;;;;CAMA,IAAW,kBAAmC;EAC1C,OAAA,aAAmB;CACvB;;;;;;;;;;;CAYA,WAA2B;EACvB,OAAO,OAAO,IAAI;CACtB;;;;;;CAOA,SAAmB;EACf,OAAO,KAAK,YAAY;CAC5B;;;;;;;;;;CAWA,OAAc,OAAsB;EAChC,OAAA,aAAmB,QAAQ,OAAO,UAAU,CAAC,MAAM,KAAK,GAAG,EACvD,WAAW,GAAG,MACV,KAAK,UAAU,EAAE,KAAK,MAAM,KAAK,UAAU,EAAE,KAAK,EAC1D,CAAC;CACL;AAOJ;yCA7EC,QAAQ,KAAK,CAAA,GAAA,WAAA"}
package/meta.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": "2",
3
3
  "name": "erp-core",
4
- "version": "1.3.0",
4
+ "version": "1.4.0",
5
5
  "description": "Núcleo arquitetural para ERP em TypeScript — entidades, value objects, erros tipados e policies declaráveis sobre clean architecture.",
6
6
  "compatibility": {
7
7
  "engines": {
@@ -14,7 +14,7 @@
14
14
  "name": "zod",
15
15
  "range": ">=3.22.0 <5",
16
16
  "optional": true,
17
- "notes": "Only required by the `./policies` subpath (gate/compute engines). The domain/result/errors/exceptions/rulesets/versioning/plugins subpaths are zod-free."
17
+ "notes": "Only required by the `./policies` subpath (gate/compute engines). The domain/result/errors/exceptions/rulesets/versioning/plugins/rbac/abac subpaths are zod-free."
18
18
  }
19
19
  ]
20
20
  },
@@ -75,7 +75,20 @@
75
75
  "PolicyDecision",
76
76
  "PolicyResolver",
77
77
  "PolicyService",
78
- "mapPolicyEvaluationError"
78
+ "mapPolicyEvaluationError",
79
+ "Permission",
80
+ "Role",
81
+ "Grant",
82
+ "Scope",
83
+ "PermissionSet",
84
+ "RbacAuthorizer",
85
+ "AuthorizerPort",
86
+ "AbacRule",
87
+ "AbacPolicySet",
88
+ "AbacAuthorizer",
89
+ "AbacAuthorizerPort",
90
+ "abacContext",
91
+ "CompositeAuthorizer"
79
92
  ],
80
93
  "changelog": [
81
94
  "1.0.1 - Corrige os exemplos de consumo nos READMEs dos kits: o import direto usa o nome npm com escopo (`@cullet/<kit>`) e o argumento do `npx cullet fc` é o nome do kit no registry (`erp-core`), não o nome com escopo. Adiciona a nota explicando o que o `fc` faz no `erp-core`.",
@@ -91,7 +104,8 @@
91
104
  "1.0.11 - Document the public API surface with TSDoc.",
92
105
  "1.1.0 - **New: `ResultRepository`, `UseCaseObservability`, and `./application` subpath**",
93
106
  "1.2.0 - Add zod-free subpaths for the stable core primitives and a value-object equality plugin system.",
94
- "1.3.0 - Add zod-free subpaths for the stable core primitives and a value-object equality plugin system."
107
+ "1.3.0 - Add zod-free subpaths for the stable core primitives and a value-object equality plugin system.",
108
+ "1.4.0 - Add a zod-free ABAC module and the `./abac` subpath."
95
109
  ],
96
110
  "deprecated": false
97
111
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cullet/erp-core",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Núcleo arquitetural para ERP em TypeScript — entidades, value objects, erros tipados e policies declaráveis sobre clean architecture.",
5
5
  "type": "module",
6
6
  "repository": {
@@ -13,6 +13,9 @@
13
13
  "types": "./dist/index.d.ts",
14
14
  "typesVersions": {
15
15
  "*": {
16
+ "abac": [
17
+ "./dist/abac/index.d.ts"
18
+ ],
16
19
  "application": [
17
20
  "./dist/application/index.d.ts"
18
21
  ],
@@ -40,6 +43,9 @@
40
43
  "policies/engines/v1/gate": [
41
44
  "./dist/policies/engines/v1/gate/index.d.ts"
42
45
  ],
46
+ "rbac": [
47
+ "./dist/rbac/index.d.ts"
48
+ ],
43
49
  "result": [
44
50
  "./dist/result/index.d.ts"
45
51
  ],
@@ -62,6 +68,16 @@
62
68
  "default": "./dist/index.cjs"
63
69
  }
64
70
  },
71
+ "./abac": {
72
+ "import": {
73
+ "types": "./dist/abac/index.d.ts",
74
+ "default": "./dist/abac/index.js"
75
+ },
76
+ "require": {
77
+ "types": "./dist/abac/index.d.cts",
78
+ "default": "./dist/abac/index.cjs"
79
+ }
80
+ },
65
81
  "./application": {
66
82
  "import": {
67
83
  "types": "./dist/application/index.d.ts",
@@ -152,6 +168,16 @@
152
168
  "default": "./dist/policies/engines/v1/gate/index.cjs"
153
169
  }
154
170
  },
171
+ "./rbac": {
172
+ "import": {
173
+ "types": "./dist/rbac/index.d.ts",
174
+ "default": "./dist/rbac/index.js"
175
+ },
176
+ "require": {
177
+ "types": "./dist/rbac/index.d.cts",
178
+ "default": "./dist/rbac/index.cjs"
179
+ }
180
+ },
155
181
  "./result": {
156
182
  "import": {
157
183
  "types": "./dist/result/index.d.ts",
@@ -0,0 +1 @@
1
+ export * from "../core/abac/index.js";