@cullet/erp-core 1.3.0 → 1.5.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 (197) hide show
  1. package/KIT_CONTEXT.md +11 -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 +201 -0
  8. package/dist/app-error.cjs.map +1 -0
  9. package/dist/app-error.js +178 -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 +579 -0
  26. package/dist/condition-evaluator.cjs.map +1 -0
  27. package/dist/condition-evaluator.js +550 -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 +122 -0
  40. package/dist/entity.cjs.map +1 -0
  41. package/dist/entity.js +111 -0
  42. package/dist/entity.js.map +1 -0
  43. package/dist/errors/index.cjs +10 -7
  44. package/dist/errors/index.d.cts +2 -1
  45. package/dist/errors/index.d.ts +2 -1
  46. package/dist/errors/index.js +6 -3
  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/hashing.cjs +2 -44
  58. package/dist/hashing.cjs.map +1 -1
  59. package/dist/hashing.js +2 -38
  60. package/dist/hashing.js.map +1 -1
  61. package/dist/index.cjs +36 -17
  62. package/dist/index.cjs.map +1 -1
  63. package/dist/index.d.cts +19 -12
  64. package/dist/index.d.ts +19 -12
  65. package/dist/index.js +17 -10
  66. package/dist/index.js.map +1 -1
  67. package/dist/not-found-error.cjs +5 -5
  68. package/dist/not-found-error.cjs.map +1 -1
  69. package/dist/not-found-error.js +1 -1
  70. package/dist/outcome.d.cts +1 -83
  71. package/dist/outcome.d.ts +1 -83
  72. package/dist/parse-gate-payload.d.cts +2 -2
  73. package/dist/parse-gate-payload.d.ts +2 -2
  74. package/dist/path.d.cts +2 -2
  75. package/dist/path.d.ts +2 -2
  76. package/dist/policies/engines/index.d.cts +1 -1
  77. package/dist/policies/engines/index.d.ts +1 -1
  78. package/dist/policies/engines/v1/gate/index.cjs +5 -4
  79. package/dist/policies/engines/v1/gate/index.cjs.map +1 -1
  80. package/dist/policies/engines/v1/gate/index.d.cts +4 -2
  81. package/dist/policies/engines/v1/gate/index.d.ts +4 -2
  82. package/dist/policies/engines/v1/gate/index.js +2 -1
  83. package/dist/policies/engines/v1/gate/index.js.map +1 -1
  84. package/dist/policies/index.cjs +5 -5
  85. package/dist/policies/index.d.cts +3 -2
  86. package/dist/policies/index.d.ts +3 -2
  87. package/dist/policies/index.js +2 -2
  88. package/dist/policy-bridge.cjs +437 -0
  89. package/dist/policy-bridge.cjs.map +1 -0
  90. package/dist/policy-bridge.d.cts +185 -0
  91. package/dist/policy-bridge.d.ts +185 -0
  92. package/dist/policy-bridge.js +396 -0
  93. package/dist/policy-bridge.js.map +1 -0
  94. package/dist/policy-service.cjs +241 -240
  95. package/dist/policy-service.cjs.map +1 -1
  96. package/dist/policy-service.d.cts +2 -2
  97. package/dist/policy-service.d.ts +2 -2
  98. package/dist/policy-service.js +240 -239
  99. package/dist/policy-service.js.map +1 -1
  100. package/dist/rbac/index.cjs +9 -0
  101. package/dist/rbac/index.d.cts +3 -0
  102. package/dist/rbac/index.d.ts +3 -0
  103. package/dist/rbac/index.js +2 -0
  104. package/dist/requested-by.cjs +54 -0
  105. package/dist/requested-by.cjs.map +1 -0
  106. package/dist/requested-by.d.cts +25 -0
  107. package/dist/requested-by.d.ts +25 -0
  108. package/dist/requested-by.js +49 -0
  109. package/dist/requested-by.js.map +1 -0
  110. package/dist/result/index.d.cts +2 -1
  111. package/dist/result/index.d.ts +2 -1
  112. package/dist/result.d.cts +84 -0
  113. package/dist/result.d.ts +84 -0
  114. package/dist/rule.cjs +327 -0
  115. package/dist/rule.cjs.map +1 -0
  116. package/dist/rule.js +298 -0
  117. package/dist/rule.js.map +1 -0
  118. package/dist/stable-stringify.cjs +47 -0
  119. package/dist/stable-stringify.cjs.map +1 -0
  120. package/dist/stable-stringify.js +42 -0
  121. package/dist/stable-stringify.js.map +1 -0
  122. package/dist/temporal-use-case.cjs +6 -53
  123. package/dist/temporal-use-case.cjs.map +1 -1
  124. package/dist/temporal-use-case.d.cts +11 -28
  125. package/dist/temporal-use-case.d.ts +11 -28
  126. package/dist/temporal-use-case.js +7 -48
  127. package/dist/temporal-use-case.js.map +1 -1
  128. package/dist/unexpected-error.cjs +3 -192
  129. package/dist/unexpected-error.cjs.map +1 -1
  130. package/dist/unexpected-error.js +2 -167
  131. package/dist/unexpected-error.js.map +1 -1
  132. package/dist/use-case.cjs +2 -6
  133. package/dist/use-case.cjs.map +1 -1
  134. package/dist/use-case.js +2 -6
  135. package/dist/use-case.js.map +1 -1
  136. package/dist/uuid-identifier.cjs +2 -7
  137. package/dist/uuid-identifier.cjs.map +1 -1
  138. package/dist/uuid-identifier.d.cts +2 -85
  139. package/dist/uuid-identifier.d.ts +2 -85
  140. package/dist/uuid-identifier.js +1 -6
  141. package/dist/uuid-identifier.js.map +1 -1
  142. package/dist/uuid.cjs +18 -0
  143. package/dist/uuid.cjs.map +1 -0
  144. package/dist/uuid.js +13 -0
  145. package/dist/uuid.js.map +1 -0
  146. package/dist/validation-error.cjs +33 -166
  147. package/dist/validation-error.cjs.map +1 -1
  148. package/dist/validation-error.d.cts +12 -103
  149. package/dist/validation-error.d.ts +12 -103
  150. package/dist/validation-error.js +7 -134
  151. package/dist/validation-error.js.map +1 -1
  152. package/dist/value-object.cjs +12 -126
  153. package/dist/value-object.cjs.map +1 -1
  154. package/dist/value-object.d.cts +97 -0
  155. package/dist/value-object.d.ts +97 -0
  156. package/dist/value-object.js +13 -115
  157. package/dist/value-object.js.map +1 -1
  158. package/meta.json +20 -4
  159. package/package.json +27 -1
  160. package/src/abac/index.ts +1 -0
  161. package/src/core/abac/abac-request.ts +29 -0
  162. package/src/core/abac/attributes.ts +39 -0
  163. package/src/core/abac/authorizer.ts +108 -0
  164. package/src/core/abac/combining.ts +63 -0
  165. package/src/core/abac/composite-authorizer.ts +45 -0
  166. package/src/core/abac/domain/policy-set.ts +52 -0
  167. package/src/core/abac/domain/rule.ts +197 -0
  168. package/src/core/abac/index.ts +21 -0
  169. package/src/core/application/commands/requested-by.ts +3 -4
  170. package/src/core/application/ports/abac-authorizer.port.ts +20 -0
  171. package/src/core/application/ports/authorizer.port.ts +22 -0
  172. package/src/core/application/queries/query.ts +6 -1
  173. package/src/core/application/use-case.ts +1 -1
  174. package/src/core/domain/entity.ts +1 -1
  175. package/src/core/domain/uuid-identifier.ts +1 -8
  176. package/src/core/domain/value-object.ts +12 -3
  177. package/src/core/errors/authorization-error.ts +26 -0
  178. package/src/core/errors/error-codes.ts +1 -0
  179. package/src/core/errors/utils/json-safe.ts +20 -11
  180. package/src/core/index.ts +7 -0
  181. package/src/core/policies/engines/v1/condition-evaluator.ts +56 -1
  182. package/src/core/rbac/access-request.ts +32 -0
  183. package/src/core/rbac/authorizer.ts +91 -0
  184. package/src/core/rbac/domain/grant.ts +96 -0
  185. package/src/core/rbac/domain/permission-set.ts +67 -0
  186. package/src/core/rbac/domain/permission.ts +119 -0
  187. package/src/core/rbac/domain/role.ts +101 -0
  188. package/src/core/rbac/domain/scope.ts +84 -0
  189. package/src/core/rbac/index.ts +15 -0
  190. package/src/core/rbac/policy-bridge.ts +44 -0
  191. package/src/core/shared/hashing.ts +1 -55
  192. package/src/core/shared/stable-stringify.ts +57 -0
  193. package/src/core/shared/uuid.ts +11 -0
  194. package/src/examples/application/authorize-cancel-order-abac.example.ts +107 -0
  195. package/src/examples/application/authorize-cancel-order.example.ts +101 -0
  196. package/src/rbac/index.ts +1 -0
  197. package/src/version.ts +1 -1
@@ -0,0 +1,97 @@
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
+ * One exception: nested `Date` instances are cloned but NOT frozen —
30
+ * `Object.freeze` does not block `setTime`/`setFullYear`, so a consumer of
31
+ * `value` can still mutate an inner `Date` in place. Store instants as ISO
32
+ * strings or epoch timestamps in the wrapped state (converting to `Date` only
33
+ * in an accessor) when that guarantee matters.
34
+ *
35
+ * @typeParam T - The shape of the wrapped data.
36
+ * @typeParam P - The primitive form produced by {@link toPrimitive} / {@link toJSON}.
37
+ */
38
+ declare abstract class ValueObject<T, P> {
39
+ static readonly CONTRACT_VERSION: ContractVersion;
40
+ /**
41
+ * Registry of equality plugins shared by every value object. Empty by
42
+ * default — when nothing is registered, {@link equals} falls back to a
43
+ * structural comparison of the wrapped `value`. Hosts register a plugin
44
+ * (e.g. `lodash.isEqual`) once at startup to customise equality globally.
45
+ */
46
+ static readonly plugins: PluginManager<ValueObjectPluginContract>;
47
+ /** The wrapped data, deep-frozen so it can never be mutated after construction. */
48
+ readonly value: DeepReadonly<T>;
49
+ /**
50
+ * Wraps `value`, deep-freezing it so the value object is immutable from the
51
+ * moment it exists. Declared `protected` because value objects are built
52
+ * through a validating subclass factory, never instantiated directly.
53
+ */
54
+ protected constructor(value: T);
55
+ /**
56
+ * The schema/contract version stamped on this value-object type by the
57
+ * `@version` decorator — used to detect state persisted under an older shape.
58
+ */
59
+ get contractVersion(): ContractVersion;
60
+ /**
61
+ * Freezes the instance shell, blocking reassignment of any own field.
62
+ *
63
+ * `value` is already deep-frozen by the constructor, so the wrapped data is
64
+ * immutable regardless. The instance itself is NOT frozen automatically
65
+ * because a subclass may still need to assign its own fields after
66
+ * `super(value)` runs. Call `finalize()` at the very end of the subclass
67
+ * constructor (after all fields are set) to make the whole value object
68
+ * immutable.
69
+ */
70
+ protected finalize(): void;
71
+ /**
72
+ * Hook for `JSON.stringify`. Delegates to {@link toPrimitive} so a value
73
+ * object serializes to its primitive form rather than exposing the internal
74
+ * `value` wrapper.
75
+ */
76
+ toJSON(): P;
77
+ /**
78
+ * Compares this value object with another by content. Because value objects
79
+ * carry no identity, two independently constructed instances holding the
80
+ * same data are considered equal.
81
+ *
82
+ * Delegates to the registered equality {@link plugins}; with no plugin
83
+ * registered it falls back to comparing the serialized wrapped `value`,
84
+ * with object keys sorted so insertion order (e.g. code-built vs
85
+ * JSON-rehydrated) never affects the result.
86
+ * Subclasses may still override for a faster or domain-specific comparison.
87
+ */
88
+ equals(other: this): boolean;
89
+ /**
90
+ * Projects the value object down to a plain, serializable primitive form —
91
+ * the representation suitable for persistence, transport, or comparison.
92
+ */
93
+ abstract toPrimitive(): P;
94
+ }
95
+ //#endregion
96
+ export { ValueObjectPluginContract as n, ValueObject as t };
97
+ //# sourceMappingURL=value-object.d.cts.map
@@ -0,0 +1,97 @@
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
+ * One exception: nested `Date` instances are cloned but NOT frozen —
30
+ * `Object.freeze` does not block `setTime`/`setFullYear`, so a consumer of
31
+ * `value` can still mutate an inner `Date` in place. Store instants as ISO
32
+ * strings or epoch timestamps in the wrapped state (converting to `Date` only
33
+ * in an accessor) when that guarantee matters.
34
+ *
35
+ * @typeParam T - The shape of the wrapped data.
36
+ * @typeParam P - The primitive form produced by {@link toPrimitive} / {@link toJSON}.
37
+ */
38
+ declare abstract class ValueObject<T, P> {
39
+ static readonly CONTRACT_VERSION: ContractVersion;
40
+ /**
41
+ * Registry of equality plugins shared by every value object. Empty by
42
+ * default — when nothing is registered, {@link equals} falls back to a
43
+ * structural comparison of the wrapped `value`. Hosts register a plugin
44
+ * (e.g. `lodash.isEqual`) once at startup to customise equality globally.
45
+ */
46
+ static readonly plugins: PluginManager<ValueObjectPluginContract>;
47
+ /** The wrapped data, deep-frozen so it can never be mutated after construction. */
48
+ readonly value: DeepReadonly<T>;
49
+ /**
50
+ * Wraps `value`, deep-freezing it so the value object is immutable from the
51
+ * moment it exists. Declared `protected` because value objects are built
52
+ * through a validating subclass factory, never instantiated directly.
53
+ */
54
+ protected constructor(value: T);
55
+ /**
56
+ * The schema/contract version stamped on this value-object type by the
57
+ * `@version` decorator — used to detect state persisted under an older shape.
58
+ */
59
+ get contractVersion(): ContractVersion;
60
+ /**
61
+ * Freezes the instance shell, blocking reassignment of any own field.
62
+ *
63
+ * `value` is already deep-frozen by the constructor, so the wrapped data is
64
+ * immutable regardless. The instance itself is NOT frozen automatically
65
+ * because a subclass may still need to assign its own fields after
66
+ * `super(value)` runs. Call `finalize()` at the very end of the subclass
67
+ * constructor (after all fields are set) to make the whole value object
68
+ * immutable.
69
+ */
70
+ protected finalize(): void;
71
+ /**
72
+ * Hook for `JSON.stringify`. Delegates to {@link toPrimitive} so a value
73
+ * object serializes to its primitive form rather than exposing the internal
74
+ * `value` wrapper.
75
+ */
76
+ toJSON(): P;
77
+ /**
78
+ * Compares this value object with another by content. Because value objects
79
+ * carry no identity, two independently constructed instances holding the
80
+ * same data are considered equal.
81
+ *
82
+ * Delegates to the registered equality {@link plugins}; with no plugin
83
+ * registered it falls back to comparing the serialized wrapped `value`,
84
+ * with object keys sorted so insertion order (e.g. code-built vs
85
+ * JSON-rehydrated) never affects the result.
86
+ * Subclasses may still override for a faster or domain-specific comparison.
87
+ */
88
+ equals(other: this): boolean;
89
+ /**
90
+ * Projects the value object down to a plain, serializable primitive form —
91
+ * the representation suitable for persistence, transport, or comparison.
92
+ */
93
+ abstract toPrimitive(): P;
94
+ }
95
+ //#endregion
96
+ export { ValueObjectPluginContract as n, ValueObject as t };
97
+ //# sourceMappingURL=value-object.d.ts.map
@@ -1,116 +1,6 @@
1
- import { t as InvariantViolationException } from "./invariant-violation-exception.js";
1
+ import { t as stableStringify } from "./stable-stringify.js";
2
2
  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
3
  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
4
  //#region src/core/domain/value-object.ts
115
5
  var _ValueObject;
116
6
  /**
@@ -125,6 +15,12 @@ var _ValueObject;
125
15
  * any risk of a consumer mutating shared state. Subclasses seal the instance
126
16
  * itself with {@link finalize} once their own fields are set.
127
17
  *
18
+ * One exception: nested `Date` instances are cloned but NOT frozen —
19
+ * `Object.freeze` does not block `setTime`/`setFullYear`, so a consumer of
20
+ * `value` can still mutate an inner `Date` in place. Store instants as ISO
21
+ * strings or epoch timestamps in the wrapped state (converting to `Date` only
22
+ * in an accessor) when that guarantee matters.
23
+ *
128
24
  * @typeParam T - The shape of the wrapped data.
129
25
  * @typeParam P - The primitive form produced by {@link toPrimitive} / {@link toJSON}.
130
26
  */
@@ -148,7 +44,7 @@ let ValueObject = class ValueObject {
148
44
  * `@version` decorator — used to detect state persisted under an older shape.
149
45
  */
150
46
  get contractVersion() {
151
- return _ValueObject.CONTRACT_VERSION;
47
+ return this.constructor.CONTRACT_VERSION;
152
48
  }
153
49
  /**
154
50
  * Freezes the instance shell, blocking reassignment of any own field.
@@ -177,15 +73,17 @@ let ValueObject = class ValueObject {
177
73
  * same data are considered equal.
178
74
  *
179
75
  * Delegates to the registered equality {@link plugins}; with no plugin
180
- * registered it falls back to comparing the serialized wrapped `value`.
76
+ * registered it falls back to comparing the serialized wrapped `value`,
77
+ * with object keys sorted so insertion order (e.g. code-built vs
78
+ * JSON-rehydrated) never affects the result.
181
79
  * Subclasses may still override for a faster or domain-specific comparison.
182
80
  */
183
81
  equals(other) {
184
- return _ValueObject.plugins.invoke("equals", [this, other], { fallback: (a, b) => JSON.stringify(a.value) === JSON.stringify(b.value) });
82
+ return _ValueObject.plugins.invoke("equals", [this, other], { fallback: (a, b) => stableStringify(a.value) === stableStringify(b.value) });
185
83
  }
186
84
  };
187
85
  ValueObject = _ValueObject = __decorate([version("1.0")], ValueObject);
188
86
  //#endregion
189
- export { Entity as n, assertValidAggregateVersion as r, ValueObject as t };
87
+ export { ValueObject as t };
190
88
 
191
89
  //# 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 { stableStringify } from \"../shared/stable-stringify.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 * One exception: nested `Date` instances are cloned but NOT frozen —\n * `Object.freeze` does not block `setTime`/`setFullYear`, so a consumer of\n * `value` can still mutate an inner `Date` in place. Store instants as ISO\n * strings or epoch timestamps in the wrapped state (converting to `Date` only\n * in an accessor) when that guarantee matters.\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 (this.constructor as typeof 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 * with object keys sorted so insertion order (e.g. code-built vs\n * JSON-rehydrated) never affects the result.\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 stableStringify(a.value) === stableStringify(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":";;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,IAAA,cAAA,MACe,YAAkB;;;;;iBAUzB,IAAI,cAAyC;;;;;;;CAUjD,YAAsB,OAAU;EAC5B,KAAK,QAAQ,cAAc,KAAK;CACpC;;;;;CAMA,IAAW,kBAAmC;EAC1C,OAAQ,KAAK,YAAmC;CACpD;;;;;;;;;;;CAYA,WAA2B;EACvB,OAAO,OAAO,IAAI;CACtB;;;;;;CAOA,SAAmB;EACf,OAAO,KAAK,YAAY;CAC5B;;;;;;;;;;;;CAaA,OAAc,OAAsB;EAChC,OAAA,aAAmB,QAAQ,OAAO,UAAU,CAAC,MAAM,KAAK,GAAG,EACvD,WAAW,GAAG,MACV,gBAAgB,EAAE,KAAK,MAAM,gBAAgB,EAAE,KAAK,EAC5D,CAAC;CACL;AAOJ;yCA/EC,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.5.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,21 @@
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
+ "rbacContextFields",
87
+ "AbacRule",
88
+ "AbacPolicySet",
89
+ "AbacAuthorizer",
90
+ "AbacAuthorizerPort",
91
+ "abacContext",
92
+ "CompositeAuthorizer"
79
93
  ],
80
94
  "changelog": [
81
95
  "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 +105,9 @@
91
105
  "1.0.11 - Document the public API surface with TSDoc.",
92
106
  "1.1.0 - **New: `ResultRepository`, `UseCaseObservability`, and `./application` subpath**",
93
107
  "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."
108
+ "1.3.0 - Add zod-free subpaths for the stable core primitives and a value-object equality plugin system.",
109
+ "1.4.0 - Add a zod-free ABAC module and the `./abac` subpath.",
110
+ "1.5.0 - Add a zod-free ABAC module and the `./abac` subpath."
95
111
  ],
96
112
  "deprecated": false
97
113
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cullet/erp-core",
3
- "version": "1.3.0",
3
+ "version": "1.5.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";
@@ -0,0 +1,29 @@
1
+ import type { RequestedBy } from "../application/commands/requested-by.js";
2
+
3
+ /**
4
+ * The attribute bags an ABAC decision reasons over, grouped by the four standard
5
+ * categories. Each is a flat record; {@link abacContext} nests them under
6
+ * `subject` / `resource` / `action` / `env` so a rule's condition can reference
7
+ * fields like `resource.status` or `env.businessHours`.
8
+ */
9
+ type AbacAttributes = {
10
+ readonly subject?: Record<string, unknown>;
11
+ readonly resource?: Record<string, unknown>;
12
+ readonly action?: Record<string, unknown>;
13
+ readonly environment?: Record<string, unknown>;
14
+ };
15
+
16
+ /**
17
+ * The question put to the {@link AbacAuthorizer}: *do these attributes authorize
18
+ * this action?* Carries the acting {@link RequestedBy} (reused as the subject),
19
+ * an audit-friendly `action` label, an optional type/id resource reference, and
20
+ * the {@link AbacAttributes} the rules evaluate.
21
+ */
22
+ interface AbacRequest {
23
+ readonly actor: RequestedBy;
24
+ readonly action: string;
25
+ readonly resource?: { readonly type: string; readonly id?: string };
26
+ readonly attributes: AbacAttributes;
27
+ }
28
+
29
+ export type { AbacAttributes, AbacRequest };
@@ -0,0 +1,39 @@
1
+ import type { PolicyContext } from "../policies/engines/gate-types.js";
2
+
3
+ import type { AbacRequest } from "./abac-request.js";
4
+
5
+ /**
6
+ * Flattens an {@link AbacRequest} into the nested {@link PolicyContext} the
7
+ * condition evaluator reads (it resolves dotted fields like `resource.status` by
8
+ * walking nested objects). The actor lands as `subject.id`; the four attribute
9
+ * bags nest under `subject` / `resource` / `action` / `env`; a `resource`
10
+ * reference adds `resource.type` / `resource.id`. The actor id and the resource
11
+ * reference win over any same-named keys in the attribute bags.
12
+ *
13
+ * Consumers fold dynamic facts (e.g. RBAC roles/permissions derived from grants,
14
+ * or a computed `ownerIsActor` flag) into `attributes.subject` / `resource` so
15
+ * rules can reference `subject.roles`, `resource.ownerIsActor`, and the like.
16
+ */
17
+ export function abacContext(request: AbacRequest): PolicyContext {
18
+ const attributes = request.attributes;
19
+
20
+ const subject: Record<string, unknown> = {
21
+ ...attributes.subject,
22
+ id: request.actor.raw,
23
+ };
24
+
25
+ const resource: Record<string, unknown> = { ...attributes.resource };
26
+ if (request.resource) {
27
+ resource.type = request.resource.type;
28
+ if (request.resource.id !== undefined) {
29
+ resource.id = request.resource.id;
30
+ }
31
+ }
32
+
33
+ return {
34
+ subject,
35
+ resource,
36
+ action: { ...attributes.action },
37
+ env: { ...attributes.environment },
38
+ };
39
+ }