@cullet/erp-core 1.1.0 → 1.2.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 (101) hide show
  1. package/KIT_CONTEXT.md +1 -67
  2. package/dist/application/index.d.ts +1 -1
  3. package/dist/application/index.js +2 -1
  4. package/dist/domain/index.d.ts +3 -0
  5. package/dist/domain/index.js +3 -0
  6. package/dist/domain-event-contracts.d.ts +27 -0
  7. package/dist/domain-event-contracts.js +22 -0
  8. package/dist/domain-event-contracts.js.map +1 -0
  9. package/dist/domain-exception.d.ts +7 -0
  10. package/dist/domain-exception.js +12 -0
  11. package/dist/domain-exception.js.map +1 -0
  12. package/dist/errors/index.js +1 -1
  13. package/dist/exceptions/index.d.ts +5 -0
  14. package/dist/exceptions/index.js +7 -0
  15. package/dist/gate-engine-registry.d.ts +2 -1
  16. package/dist/gate-engine-registry.js +2 -1
  17. package/dist/gate-engine-registry.js.map +1 -1
  18. package/dist/gate-types.d.ts +3 -139
  19. package/dist/gate-v1-payload.schema.js +2 -116
  20. package/dist/gate-v1-payload.schema.js.map +1 -1
  21. package/dist/immutable.d.ts +6 -0
  22. package/dist/immutable.js +54 -0
  23. package/dist/immutable.js.map +1 -0
  24. package/dist/index.d.ts +15 -160
  25. package/dist/index.js +19 -176
  26. package/dist/index.js.map +1 -1
  27. package/dist/invalid-state-transition-exception.js +30 -0
  28. package/dist/invalid-state-transition-exception.js.map +1 -0
  29. package/dist/invariant-violation-exception.js +11 -0
  30. package/dist/invariant-violation-exception.js.map +1 -0
  31. package/dist/not-found-error.js +1 -1
  32. package/dist/outcome.d.ts +140 -0
  33. package/dist/outcome.js +1 -1
  34. package/dist/parse-gate-payload.d.ts +2 -1
  35. package/dist/path.d.ts +2 -1
  36. package/dist/plugin.d.ts +85 -0
  37. package/dist/plugin.js +74 -0
  38. package/dist/plugin.js.map +1 -0
  39. package/dist/plugins/index.d.ts +2 -0
  40. package/dist/plugins/index.js +2 -0
  41. package/dist/policies/engines/index.d.ts +1 -1
  42. package/dist/policies/engines/v1/gate/index.d.ts +2 -1
  43. package/dist/policies/engines/v1/gate/index.js +2 -1
  44. package/dist/policies/engines/v1/gate/index.js.map +1 -1
  45. package/dist/policies/index.d.ts +2 -1
  46. package/dist/policies/index.js +2 -1
  47. package/dist/policy-service.d.ts +2 -1
  48. package/dist/policy-service.js +6 -3
  49. package/dist/policy-service.js.map +1 -1
  50. package/dist/result/index.d.ts +2 -0
  51. package/dist/result/index.js +3 -0
  52. package/dist/result.js +118 -0
  53. package/dist/result.js.map +1 -0
  54. package/dist/ruleset-registry.js +42 -0
  55. package/dist/ruleset-registry.js.map +1 -0
  56. package/dist/rulesets/index.d.ts +2 -0
  57. package/dist/rulesets/index.js +2 -0
  58. package/dist/temporal-guards.js +2 -17
  59. package/dist/temporal-guards.js.map +1 -1
  60. package/dist/temporal-use-case.d.ts +4 -9
  61. package/dist/temporal-use-case.js +6 -140
  62. package/dist/temporal-use-case.js.map +1 -1
  63. package/dist/unexpected-error.js +179 -0
  64. package/dist/unexpected-error.js.map +1 -0
  65. package/dist/use-case.js +91 -0
  66. package/dist/use-case.js.map +1 -0
  67. package/dist/uuid-identifier.d.ts +230 -0
  68. package/dist/uuid-identifier.js +60 -0
  69. package/dist/uuid-identifier.js.map +1 -0
  70. package/dist/validation-code.d.ts +23 -0
  71. package/dist/validation-code.js +1 -177
  72. package/dist/validation-code.js.map +1 -1
  73. package/dist/validation-error.d.ts +1 -21
  74. package/dist/validation-error.js +1 -1
  75. package/dist/validation-exception.d.ts +50 -0
  76. package/dist/validation-exception.js +8 -2
  77. package/dist/validation-exception.js.map +1 -1
  78. package/dist/value-object-ruleset.contracts.d.ts +36 -0
  79. package/dist/value-object.js +191 -0
  80. package/dist/value-object.js.map +1 -0
  81. package/dist/version.d.ts +10 -0
  82. package/dist/versioning/index.d.ts +3 -0
  83. package/dist/versioning/index.js +3 -0
  84. package/meta.json +17 -3
  85. package/package.json +33 -4
  86. package/src/core/domain/rulesets/index.ts +7 -0
  87. package/src/core/domain/uuid-identifier.ts +72 -0
  88. package/src/core/domain/value-object.ts +37 -5
  89. package/src/core/exceptions/index.ts +13 -0
  90. package/src/core/index.ts +14 -2
  91. package/src/core/plugins/index.ts +7 -0
  92. package/src/core/plugins/plugin.ts +99 -0
  93. package/src/core/plugins/types.ts +53 -0
  94. package/src/core/versioning/index.ts +14 -0
  95. package/src/domain/index.ts +7 -0
  96. package/src/exceptions/index.ts +1 -0
  97. package/src/plugins/index.ts +1 -0
  98. package/src/result/index.ts +2 -0
  99. package/src/rulesets/index.ts +1 -0
  100. package/src/version.ts +1 -1
  101. package/src/versioning/index.ts +1 -0
package/dist/index.js CHANGED
@@ -1,194 +1,37 @@
1
- import { a as ErrorCodes, i as assertJsonSafeMetadata, n as UnexpectedError, o as serializationErrorCode, r as AppError } from "./validation-code.js";
1
+ import { a as serializationErrorCode, i as ErrorCodes, n as AppError, r as assertJsonSafeMetadata, t as UnexpectedError } from "./unexpected-error.js";
2
2
  import { C as translateUniqueViolationToDuplicate, S as UniqueConstraintViolationError, T as AuthenticationError, _ as IdempotencyPayloadMismatchError, a as evaluateTemporalWindow, b as ConflictError, c as SerializationInError, d as safePreview, f as LegacyIncompatibleError, g as IdempotencyKeyMissingError, h as IdempotencyInProgressError, i as TemporalError, l as SerializationMessages, m as IdempotencyError, n as ExpiredError, o as SerializationCodes, p as IntegrationError, r as NotYetValidError, s as SerializationError, t as ValidationError, u as SerializationOutError, v as IdempotencyReplayNotSupportedError, w as AuthorizationError, x as DuplicateError, y as AlreadyExistsError } from "./validation-error.js";
3
3
  import { n as BusinessRuleViolationError, t as NotFoundError } from "./not-found-error.js";
4
4
  import { n as sha256Hex, r as stableStringify, t as payloadHash } from "./hashing.js";
5
+ import { t as ValidationCode } from "./validation-code.js";
5
6
  import { t as ValidationField } from "./validation-field.js";
6
- import { a as Query, c as RequestedBy, d as version$1, i as makeImmutable, l as UseCase, n as assertTemporalContext, o as mapPolicyEvaluationError, r as createTemporalContext, s as Command, t as TemporalUseCase, u as __decorate } from "./temporal-use-case.js";
7
- import { i as InvariantViolationException, n as cloneDate, t as assertValidDate } from "./temporal-guards.js";
8
- import { c as Ok, d as CoreConfig, l as Result, o as PolicyContextPath, s as Err, u as coreConfig } from "./gate-v1-payload.schema.js";
7
+ import { t as DomainException } from "./domain-exception.js";
8
+ import { n as EntityNotFoundException, r as BusinessRuleViolationException, t as InvalidStateTransitionException } from "./invalid-state-transition-exception.js";
9
+ import { t as InvariantViolationException } from "./invariant-violation-exception.js";
10
+ import { n as MultipleValidationException, r as ValidationException, t as InvalidValueException } from "./validation-exception.js";
11
+ import { i as version, r as CONTRACT_VERSION_PROPERTY } from "./immutable.js";
12
+ import { t as UseCase } from "./use-case.js";
13
+ import { a as mapPolicyEvaluationError, i as Query, n as assertTemporalContext, o as Command, r as createTemporalContext, s as RequestedBy, t as TemporalUseCase } from "./temporal-use-case.js";
14
+ import { n as Entity, t as ValueObject } from "./value-object.js";
15
+ import { t as PluginManager } from "./plugin.js";
16
+ import { t as UuidIdentifier } from "./uuid-identifier.js";
17
+ import { t as RulesetRegistry } from "./ruleset-registry.js";
18
+ import { n as createDomainEventEnvelope, t as buildDomainEventContractVersions } from "./domain-event-contracts.js";
19
+ import { c as CoreConfig, o as PolicyContextPath, s as coreConfig } from "./gate-v1-payload.schema.js";
20
+ import { n as Ok, r as Result, t as Err } from "./result.js";
9
21
  import { t as Outcome } from "./outcome.js";
10
22
  import { _ as asPolicyDecisionId, a as ContextSeedValidator, b as asTenantId, c as ContextResolverRegistry, d as PolicyDefinition, f as InMemoryPolicyDefinitionRepository, g as PolicyCatalog, h as PolicyCatalogFactory, i as PolicyAsOfResolver, l as registerNamespacedContextResolversIn, m as PolicyKey, n as PolicyEvaluationErrors, o as contextResolverRegistry, p as PolicyScopeMatcher, r as PolicyResolver, s as registerNamespacedContextResolvers, t as PolicyService, u as PolicyContextBuilder, v as asPolicyDefinitionId, x as PolicyHashing, y as asSchoolId } from "./policy-service.js";
11
23
  import { a as ComputeEvaluatorRegistry, c as ComputePayloadParsers, i as ComputeRegistry, o as ComputeEngineRegistry, r as GatePayloadParsers, s as ComputePayloadParserRegistry, t as GateEngineRegistry } from "./gate-engine-registry.js";
12
24
  //#region src/version.ts
13
- const version = "1.1.0";
14
- //#endregion
15
- //#region src/core/shared/aggregate-version.ts
16
- function assertValidAggregateVersion(aggregateVersion) {
17
- if (!Number.isInteger(aggregateVersion) || aggregateVersion < 0) throw new InvariantViolationException(`aggregateVersion must be a non-negative integer. Received: ${aggregateVersion}`);
18
- }
19
- //#endregion
20
- //#region src/core/domain/entity.ts
21
- var _Entity;
22
- /**
23
- * Base class for domain entities — objects defined by a stable identity rather
24
- * than by their attributes. Two entities are "the same" when their `id`
25
- * matches, even if every other field differs; this is the opposite of a
26
- * {@link ValueObject}, which is defined entirely by its contents.
27
- *
28
- * The class owns the bookkeeping common to every aggregate root: a creation
29
- * timestamp that never changes, a last-modified timestamp, and an
30
- * `aggregateVersion` counter used for optimistic concurrency control. All three
31
- * are validated on construction and the dates are defensively cloned, so an
32
- * entity can never be built into — or leak — an inconsistent temporal state.
33
- *
34
- * @typeParam TIdentifier - The identity type (e.g. a branded string id or a VO).
35
- */
36
- let Entity = class Entity {
37
- static {
38
- _Entity = this;
39
- }
40
- /**
41
- * Reconstitutes an entity from its persisted {@link EntityState}.
42
- *
43
- * Validates the temporal invariants up front so an invalid entity is
44
- * impossible to construct: both dates must be valid, the aggregate version
45
- * must be a non-negative integer, and `updatedAt` may not predate
46
- * `createdAt`. Both dates are cloned on the way in so a later mutation of
47
- * the caller's `Date` objects cannot reach into the entity's internal state.
48
- *
49
- * Declared `protected` because entities are reconstituted through a
50
- * subclass factory, never instantiated directly by application code.
51
- *
52
- * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.
53
- */
54
- constructor(state) {
55
- assertValidDate("createdAt", state.createdAt);
56
- assertValidDate("updatedAt", state.updatedAt);
57
- assertValidAggregateVersion(state.aggregateVersion);
58
- if (state.updatedAt.getTime() < state.createdAt.getTime()) throw new InvariantViolationException("updatedAt cannot be earlier than createdAt");
59
- this._id = state.id;
60
- this._createdAt = cloneDate(state.createdAt);
61
- this._updatedAt = cloneDate(state.updatedAt);
62
- this._aggregateVersion = state.aggregateVersion;
63
- }
64
- /** The entity's stable identity — the basis for equality between entities. */
65
- get id() {
66
- return this._id;
67
- }
68
- /**
69
- * When the entity was first created.
70
- *
71
- * Returns a clone so callers cannot mutate the entity's internal `Date`;
72
- * the value is fixed at construction and never changes thereafter.
73
- */
74
- get createdAt() {
75
- return cloneDate(this._createdAt);
76
- }
77
- /**
78
- * When the entity was last modified.
79
- *
80
- * Returns a clone for the same encapsulation reason as {@link createdAt};
81
- * the underlying value advances only through {@link markAsModified}.
82
- */
83
- get updatedAt() {
84
- return cloneDate(this._updatedAt);
85
- }
86
- /**
87
- * Monotonic counter incremented on every mutation, used for optimistic
88
- * concurrency control: a writer reads this value, and the persistence layer
89
- * rejects the write if the stored version has moved on in the meantime.
90
- */
91
- get aggregateVersion() {
92
- return this._aggregateVersion;
93
- }
94
- /**
95
- * The schema/contract version stamped on this entity type by the
96
- * `@version` decorator — used to detect and migrate state persisted under
97
- * an older shape.
98
- */
99
- get contractVersion() {
100
- return _Entity.CONTRACT_VERSION;
101
- }
102
- /**
103
- * The single seam through which an entity records a mutation: it advances
104
- * `updatedAt` and bumps {@link aggregateVersion} by one. Subclasses must
105
- * call this from every state-changing method so the version counter stays
106
- * an accurate optimistic-lock token.
107
- *
108
- * @param updatedAt - The modification instant; defaults to now. Validated
109
- * and required not to predate `createdAt`, preserving the same invariant
110
- * the constructor enforces.
111
- * @returns The new aggregate version after the increment.
112
- * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.
113
- */
114
- markAsModified(updatedAt = /* @__PURE__ */ new Date()) {
115
- assertValidDate("updatedAt", updatedAt);
116
- if (updatedAt.getTime() < this._createdAt.getTime()) throw new InvariantViolationException("updatedAt cannot be earlier than createdAt");
117
- this._updatedAt = cloneDate(updatedAt);
118
- this._aggregateVersion += 1;
119
- return this._aggregateVersion;
120
- }
121
- };
122
- Entity = _Entity = __decorate([version$1("1.0")], Entity);
123
- //#endregion
124
- //#region src/core/domain/value-object.ts
125
- var _ValueObject;
126
- /**
127
- * Base class for value objects — domain concepts defined entirely by their
128
- * contents, with no identity of their own. Two value objects are
129
- * interchangeable when they hold equal data, which is the opposite of an
130
- * {@link Entity} (compared by id). Money, a CPF, a date range: replacing one
131
- * instance with an equal one changes nothing about the model.
132
- *
133
- * Immutability is the defining guarantee here. The wrapped `value` is
134
- * deep-frozen on construction, so a value object can be shared freely without
135
- * any risk of a consumer mutating shared state. Subclasses seal the instance
136
- * itself with {@link finalize} once their own fields are set.
137
- *
138
- * @typeParam T - The shape of the wrapped data.
139
- * @typeParam P - The primitive form produced by {@link toPrimitive} / {@link toJSON}.
140
- */
141
- let ValueObject = class ValueObject {
142
- static {
143
- _ValueObject = this;
144
- }
145
- /**
146
- * Wraps `value`, deep-freezing it so the value object is immutable from the
147
- * moment it exists. Declared `protected` because value objects are built
148
- * through a validating subclass factory, never instantiated directly.
149
- */
150
- constructor(value) {
151
- this.value = makeImmutable(value);
152
- }
153
- /**
154
- * The schema/contract version stamped on this value-object type by the
155
- * `@version` decorator — used to detect state persisted under an older shape.
156
- */
157
- get contractVersion() {
158
- return _ValueObject.CONTRACT_VERSION;
159
- }
160
- /**
161
- * Freezes the instance shell, blocking reassignment of any own field.
162
- *
163
- * `value` is already deep-frozen by the constructor, so the wrapped data is
164
- * immutable regardless. The instance itself is NOT frozen automatically
165
- * because a subclass may still need to assign its own fields after
166
- * `super(value)` runs. Call `finalize()` at the very end of the subclass
167
- * constructor (after all fields are set) to make the whole value object
168
- * immutable.
169
- */
170
- finalize() {
171
- Object.freeze(this);
172
- }
173
- /**
174
- * Hook for `JSON.stringify`. Delegates to {@link toPrimitive} so a value
175
- * object serializes to its primitive form rather than exposing the internal
176
- * `value` wrapper.
177
- */
178
- toJSON() {
179
- return this.toPrimitive();
180
- }
181
- };
182
- ValueObject = _ValueObject = __decorate([version$1("1.0")], ValueObject);
25
+ const version$1 = "1.2.0";
183
26
  //#endregion
184
27
  //#region src/index.ts
185
28
  const ERP_CORE_NAME = "erp-core";
186
- const ERP_CORE_VERSION = version;
29
+ const ERP_CORE_VERSION = version$1;
187
30
  const erpCoreRelease = {
188
31
  name: ERP_CORE_NAME,
189
32
  version: ERP_CORE_VERSION
190
33
  };
191
34
  //#endregion
192
- export { AlreadyExistsError, AppError, AuthenticationError, AuthorizationError, BusinessRuleViolationError, Command, ComputeEngineRegistry, ComputeEvaluatorRegistry, ComputePayloadParserRegistry, ComputePayloadParsers, ComputeRegistry, ConflictError, ContextResolverRegistry, ContextSeedValidator, CoreConfig, SerializationInError as DeserializationError, SerializationInError, DuplicateError, ERP_CORE_NAME, ERP_CORE_VERSION, Entity, Err, ErrorCodes, ExpiredError, GateEngineRegistry, GatePayloadParsers, IdempotencyError, IdempotencyInProgressError, IdempotencyKeyMissingError, IdempotencyPayloadMismatchError, IdempotencyReplayNotSupportedError, InMemoryPolicyDefinitionRepository, IntegrationError, LegacyIncompatibleError, NotFoundError, NotYetValidError, Ok, Outcome, PolicyAsOfResolver, PolicyCatalog, PolicyCatalogFactory, PolicyContextBuilder, PolicyContextPath, PolicyDefinition, PolicyEvaluationErrors, PolicyHashing, PolicyKey, PolicyResolver, PolicyScopeMatcher, PolicyService, Query, RequestedBy, Result, SerializationCodes, SerializationError, SerializationMessages, SerializationOutError, TemporalError, TemporalUseCase, UnexpectedError, UniqueConstraintViolationError, UseCase, ValidationError, ValidationField, ValueObject, asPolicyDecisionId, asPolicyDefinitionId, asSchoolId, asTenantId, assertJsonSafeMetadata, assertTemporalContext, contextResolverRegistry, coreConfig, createTemporalContext, erpCoreRelease, evaluateTemporalWindow, mapPolicyEvaluationError, payloadHash, registerNamespacedContextResolvers, registerNamespacedContextResolversIn, safePreview, serializationErrorCode, sha256Hex, stableStringify, translateUniqueViolationToDuplicate };
35
+ export { AlreadyExistsError, AppError, AuthenticationError, AuthorizationError, BusinessRuleViolationError, BusinessRuleViolationException, CONTRACT_VERSION_PROPERTY, Command, ComputeEngineRegistry, ComputeEvaluatorRegistry, ComputePayloadParserRegistry, ComputePayloadParsers, ComputeRegistry, ConflictError, ContextResolverRegistry, ContextSeedValidator, CoreConfig, SerializationInError as DeserializationError, SerializationInError, DomainException, DuplicateError, ERP_CORE_NAME, ERP_CORE_VERSION, Entity, EntityNotFoundException, Err, ErrorCodes, ExpiredError, GateEngineRegistry, GatePayloadParsers, IdempotencyError, IdempotencyInProgressError, IdempotencyKeyMissingError, IdempotencyPayloadMismatchError, IdempotencyReplayNotSupportedError, InMemoryPolicyDefinitionRepository, IntegrationError, InvalidStateTransitionException, InvalidValueException, InvariantViolationException, LegacyIncompatibleError, MultipleValidationException, NotFoundError, NotYetValidError, Ok, Outcome, PluginManager, PolicyAsOfResolver, PolicyCatalog, PolicyCatalogFactory, PolicyContextBuilder, PolicyContextPath, PolicyDefinition, PolicyEvaluationErrors, PolicyHashing, PolicyKey, PolicyResolver, PolicyScopeMatcher, PolicyService, Query, RequestedBy, Result, RulesetRegistry, SerializationCodes, SerializationError, SerializationMessages, SerializationOutError, TemporalError, TemporalUseCase, UnexpectedError, UniqueConstraintViolationError, UseCase, UuidIdentifier, ValidationCode, ValidationError, ValidationException, ValidationField, ValueObject, asPolicyDecisionId, asPolicyDefinitionId, asSchoolId, asTenantId, assertJsonSafeMetadata, assertTemporalContext, buildDomainEventContractVersions, contextResolverRegistry, coreConfig, createDomainEventEnvelope, createTemporalContext, erpCoreRelease, evaluateTemporalWindow, mapPolicyEvaluationError, payloadHash, registerNamespacedContextResolvers, registerNamespacedContextResolversIn, safePreview, serializationErrorCode, sha256Hex, stableStringify, translateUniqueViolationToDuplicate, version };
193
36
 
194
37
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["version","version"],"sources":["../src/version.ts","../src/core/shared/aggregate-version.ts","../src/core/domain/entity.ts","../src/core/domain/value-object.ts","../src/index.ts"],"sourcesContent":["// Versao do kit, sincronizada com package.json por scripts/sync-kit-version.mjs.\n// Nao edite a mao: rode `npm run sync-kit-version` (ou e regenerado no release).\n//\n// Mantemos a versao aqui, dentro de src/, para que a copia full-control seja\n// auto-contida: ao copiar so o conteudo de src/, o entry nao depende de um\n// `../package.json` que deixaria de existir no projeto consumidor.\nexport const version = \"1.1.0\";\n","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 { type DeepReadonly, makeImmutable } from \"../shared/immutable.js\";\nimport { type ContractVersion, version } from \"../versioning/version.js\";\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 /** 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, subclasses implement equality over the wrapped data\n * (typically the primitive form), so two independently constructed instances\n * holding the same data are considered equal.\n */\n public abstract equals(other: this): boolean;\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 };\n","import { version } from \"./version.js\";\n\nexport * from \"./core/index.js\";\n\nexport const ERP_CORE_NAME = \"erp-core\";\nexport const ERP_CORE_VERSION = version;\n\nexport const erpCoreRelease = {\n name: ERP_CORE_NAME,\n version: ERP_CORE_VERSION,\n} as const;\n"],"mappings":";;;;;;;;;;;;AAMA,MAAa,UAAU;;;ACJvB,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;+BA7GCA,UAAQ,KAAK,CAAA,GAAA,MAAA;;;;;;;;;;;;;;;;;;;AChBd,IAAA,cAAA,MACe,YAAkB;;;;;;;;;CAW7B,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;AAeJ;yCA5DCC,UAAQ,KAAK,CAAA,GAAA,WAAA;;;ACdd,MAAa,gBAAgB;AAC7B,MAAa,mBAAmB;AAEhC,MAAa,iBAAiB;CAC1B,MAAM;CACN,SAAS;AACb"}
1
+ {"version":3,"file":"index.js","names":["version","version"],"sources":["../src/version.ts","../src/index.ts"],"sourcesContent":["// Versao do kit, sincronizada com package.json por scripts/sync-kit-version.mjs.\n// Nao edite a mao: rode `npm run sync-kit-version` (ou e regenerado no release).\n//\n// Mantemos a versao aqui, dentro de src/, para que a copia full-control seja\n// auto-contida: ao copiar so o conteudo de src/, o entry nao depende de um\n// `../package.json` que deixaria de existir no projeto consumidor.\nexport const version = \"1.2.0\";\n","import { version } from \"./version.js\";\n\nexport * from \"./core/index.js\";\n\nexport const ERP_CORE_NAME = \"erp-core\";\nexport const ERP_CORE_VERSION = version;\n\nexport const erpCoreRelease = {\n name: ERP_CORE_NAME,\n version: ERP_CORE_VERSION,\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAaA,YAAU;;;ACFvB,MAAa,gBAAgB;AAC7B,MAAa,mBAAmBC;AAEhC,MAAa,iBAAiB;CAC1B,MAAM;CACN,SAAS;AACb"}
@@ -0,0 +1,30 @@
1
+ import { t as DomainException } from "./domain-exception.js";
2
+ //#region src/core/exceptions/business-rule-violation-exception.ts
3
+ var BusinessRuleViolationException = class extends DomainException {
4
+ constructor(rule, message) {
5
+ super(message);
6
+ this.rule = rule;
7
+ }
8
+ };
9
+ //#endregion
10
+ //#region src/core/exceptions/entity-not-found-exception.ts
11
+ var EntityNotFoundException = class extends DomainException {
12
+ constructor(entityName, identifier) {
13
+ super(`${entityName} with identifier ${identifier} was not found.`);
14
+ this.entityName = entityName;
15
+ this.identifier = identifier;
16
+ }
17
+ };
18
+ //#endregion
19
+ //#region src/core/exceptions/invalid-state-transition-exception.ts
20
+ var InvalidStateTransitionException = class extends DomainException {
21
+ constructor(from, to, message) {
22
+ super(message);
23
+ this.from = from;
24
+ this.to = to;
25
+ }
26
+ };
27
+ //#endregion
28
+ export { EntityNotFoundException as n, BusinessRuleViolationException as r, InvalidStateTransitionException as t };
29
+
30
+ //# sourceMappingURL=invalid-state-transition-exception.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invalid-state-transition-exception.js","names":[],"sources":["../src/core/exceptions/business-rule-violation-exception.ts","../src/core/exceptions/entity-not-found-exception.ts","../src/core/exceptions/invalid-state-transition-exception.ts"],"sourcesContent":["import { DomainException } from \"./domain-exception.js\";\n\nclass BusinessRuleViolationException extends DomainException {\n constructor(\n public readonly rule: string,\n message: string,\n ) {\n super(message);\n }\n}\n\nexport { BusinessRuleViolationException };\n","import { DomainException } from \"./domain-exception.js\";\n\nclass EntityNotFoundException extends DomainException {\n constructor(\n public readonly entityName: string,\n public readonly identifier: string,\n ) {\n super(`${entityName} with identifier ${identifier} was not found.`);\n }\n}\n\nexport { EntityNotFoundException };\n","import { DomainException } from \"./domain-exception.js\";\n\nclass InvalidStateTransitionException<\n TState extends string = string,\n> extends DomainException {\n constructor(\n public readonly from: TState,\n public readonly to: TState,\n message: string,\n ) {\n super(message);\n }\n}\n\nexport { InvalidStateTransitionException };\n"],"mappings":";;AAEA,IAAM,iCAAN,cAA6C,gBAAgB;CACzD,YACI,MACA,SACF;EACE,MAAM,OAAO;EAHG,KAAA,OAAA;CAIpB;AACJ;;;ACPA,IAAM,0BAAN,cAAsC,gBAAgB;CAClD,YACI,YACA,YACF;EACE,MAAM,GAAG,WAAW,mBAAmB,WAAW,gBAAgB;EAHlD,KAAA,aAAA;EACA,KAAA,aAAA;CAGpB;AACJ;;;ACPA,IAAM,kCAAN,cAEU,gBAAgB;CACtB,YACI,MACA,IACA,SACF;EACE,MAAM,OAAO;EAJG,KAAA,OAAA;EACA,KAAA,KAAA;CAIpB;AACJ"}
@@ -0,0 +1,11 @@
1
+ import { t as DomainException } from "./domain-exception.js";
2
+ //#region src/core/exceptions/invariant-violation-exception.ts
3
+ var InvariantViolationException = class extends DomainException {
4
+ constructor(message) {
5
+ super(message);
6
+ }
7
+ };
8
+ //#endregion
9
+ export { InvariantViolationException as t };
10
+
11
+ //# sourceMappingURL=invariant-violation-exception.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invariant-violation-exception.js","names":[],"sources":["../src/core/exceptions/invariant-violation-exception.ts"],"sourcesContent":["import { DomainException } from \"./domain-exception.js\";\n\nclass InvariantViolationException extends DomainException {\n constructor(message: string) {\n super(message);\n }\n}\n\nexport { InvariantViolationException };\n"],"mappings":";;AAEA,IAAM,8BAAN,cAA0C,gBAAgB;CACtD,YAAY,SAAiB;EACzB,MAAM,OAAO;CACjB;AACJ"}
@@ -1,4 +1,4 @@
1
- import { a as ErrorCodes, r as AppError } from "./validation-code.js";
1
+ import { i as ErrorCodes, n as AppError } from "./unexpected-error.js";
2
2
  //#region src/core/errors/business-rule-violation-error.ts
3
3
  var BusinessRuleViolationError = class extends AppError {
4
4
  constructor(rule, message, detail, options) {
@@ -0,0 +1,140 @@
1
+ //#region src/core/result/result.d.ts
2
+ /**
3
+ * Represents the outcome of an operation that may succeed or fail.
4
+ * Useful for avoiding excessive exceptions and making error flows explicit.
5
+ */
6
+ declare abstract class Result<T, E> {
7
+ protected constructor();
8
+ /**
9
+ * Creates a success result containing a value.
10
+ */
11
+ static ok<T>(value: T): Result<T, never>;
12
+ /**
13
+ * Creates an error result containing an error object.
14
+ */
15
+ static err<E>(error: E): Result<never, E>;
16
+ /**
17
+ * Returns true when this is a success result.
18
+ */
19
+ abstract isOk(): this is Ok<T>;
20
+ /**
21
+ * Returns true when this is an error result.
22
+ */
23
+ abstract isErr(): this is Err<E>;
24
+ /**
25
+ * Runs a handler based on the result state (similar to pattern matching).
26
+ */
27
+ abstract match<R>(handlers: {
28
+ ok: (value: T) => R;
29
+ err: (error: E) => R;
30
+ }): R;
31
+ /**
32
+ * Returns the value when this is success, or null when this is an error.
33
+ */
34
+ getOrNull(): T | null;
35
+ /**
36
+ * Returns the error when this is a failure, or null when this is a success.
37
+ */
38
+ errorOrNull(): E | null;
39
+ /**
40
+ * Returns the value when this is a success, or throws the error when this is a failure.
41
+ */
42
+ getOrThrow(): T;
43
+ /**
44
+ * Transforms the success value using the provided function. Keeps the error when this is a failure.
45
+ */
46
+ map<R>(transform: (value: T) => R): Result<R, E>;
47
+ /**
48
+ * Transforms the error using the provided function. Keeps the value when this is a success.
49
+ */
50
+ mapError<F>(transform: (error: E) => F): Result<T, F>;
51
+ /**
52
+ * Chains another operation that returns a Result when this result is a success.
53
+ */
54
+ flatMap<R>(transform: (value: T) => Result<R, E>): Result<R, E>;
55
+ }
56
+ /**
57
+ * Success variant of Result.
58
+ */
59
+ declare class Ok<T> extends Result<T, never> {
60
+ readonly value: T;
61
+ constructor(value: T);
62
+ isOk(): this is Ok<T>;
63
+ isErr(): this is Err<never>;
64
+ match<R>(handlers: {
65
+ ok: (value: T) => R;
66
+ err: (error: never) => R;
67
+ }): R;
68
+ }
69
+ /**
70
+ * Error variant of Result.
71
+ */
72
+ declare class Err<E> extends Result<never, E> {
73
+ readonly error: E;
74
+ constructor(error: E);
75
+ isOk(): this is Ok<never>;
76
+ isErr(): this is Err<E>;
77
+ match<R>(handlers: {
78
+ ok: (value: never) => R;
79
+ err: (error: E) => R;
80
+ }): R;
81
+ }
82
+ //#endregion
83
+ //#region src/core/result/outcome.d.ts
84
+ /**
85
+ * Outcome — Business decision abstraction.
86
+ *
87
+ * Represents the semantic result of a domain decision, policy evaluation,
88
+ * or business rule. NOT for technical success/failure — use Result for that.
89
+ *
90
+ * Mental model:
91
+ * "What was the business decision?"
92
+ * NOT "Did the operation succeed?"
93
+ *
94
+ * The status axis represents valid business outcomes (APPROVED, REJECTED,
95
+ * ALLOW, DENY, NO_OP, etc.), never technical Ok/Err.
96
+ *
97
+ * @typeParam S - Union of valid status literals for this outcome
98
+ * @typeParam D - Shape of the decision data carried by this outcome
99
+ */
100
+ declare class Outcome<S extends string, D = undefined> {
101
+ readonly status: S;
102
+ readonly data: D;
103
+ readonly reason: string | undefined;
104
+ readonly metadata: Readonly<Record<string, unknown>>;
105
+ private constructor();
106
+ static of<S extends string, D = undefined>(status: S, data: D, reason?: string, metadata?: Record<string, unknown>): Outcome<S, D>;
107
+ static approved<D = undefined>(data: D, reason?: string): Outcome<"APPROVED", D>;
108
+ static rejected<D = undefined>(data: D, reason: string): Outcome<"REJECTED", D>;
109
+ static noOp<D = undefined>(data: D, reason?: string): Outcome<"NO_OP", D>;
110
+ static deferred<D = undefined>(data: D, reason: string): Outcome<"DEFERRED", D>;
111
+ static requiresReview<D = undefined>(data: D, reason: string): Outcome<"REQUIRES_REVIEW", D>;
112
+ /**
113
+ * Narrows this Outcome to a specific status.
114
+ *
115
+ * @example
116
+ * if (outcome.is('DENY')) {
117
+ * outcome.data.violations // TS knows status is 'DENY'
118
+ * }
119
+ */
120
+ is<T extends S>(status: T): this is Outcome<T, D>;
121
+ /**
122
+ * Exhaustive pattern match over all possible statuses.
123
+ * TypeScript enforces that every status has a handler.
124
+ *
125
+ * @example
126
+ * outcome.match({
127
+ * ALLOW: (o) => handleAllow(o.data),
128
+ * DENY: (o) => handleDeny(o.data.violations),
129
+ * })
130
+ */
131
+ match<THandlers extends { [K in S]: (outcome: Outcome<K, D>) => unknown }>(handlers: THandlers): ReturnType<THandlers[S]>;
132
+ withMetadata(extra: Record<string, unknown>): Outcome<S, D>;
133
+ withReason(reason: string): Outcome<S, D>;
134
+ toString(): string;
135
+ }
136
+ /** Common business outcome statuses. Extend per domain as needed. */
137
+ type CommonOutcomeStatus = "APPROVED" | "REJECTED" | "NO_OP" | "DEFERRED" | "REQUIRES_REVIEW";
138
+ //#endregion
139
+ export { Result as a, Ok as i, Outcome as n, Err as r, CommonOutcomeStatus as t };
140
+ //# sourceMappingURL=outcome.d.ts.map
package/dist/outcome.js CHANGED
@@ -1,4 +1,4 @@
1
- import { i as InvariantViolationException } from "./temporal-guards.js";
1
+ import { t as InvariantViolationException } from "./invariant-violation-exception.js";
2
2
  //#region src/core/result/outcome.ts
3
3
  /**
4
4
  * Outcome — Business decision abstraction.
@@ -1,4 +1,5 @@
1
- import { I as Result, d as GatePayloadV1, s as PolicyContext, u as GatePayload } from "./gate-types.js";
1
+ import { a as Result } from "./outcome.js";
2
+ import { d as GatePayloadV1, s as PolicyContext, u as GatePayload } from "./gate-types.js";
2
3
  import { a as ComputeOutcome, c as VersionedComputeEngine, i as ComputeEvaluatorRegistration, l as ComputePayload, p as ComputePayloadV1, r as ComputeEvaluator } from "./gate-engine-registry.js";
3
4
 
4
5
  //#region src/core/policies/engines/compute-evaluator-registry.d.ts
package/dist/path.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { I as Result, g as CoreConfig } from "./gate-types.js";
1
+ import { a as Result } from "./outcome.js";
2
+ import { m as CoreConfig } from "./gate-types.js";
2
3
  import { D as PolicyDefinition, N as PolicyCatalog, P as PolicyCatalogEntryProps, S as PolicyDefinitionRepository, T as FindCandidatesParams, m as ContextResolverRegistry, y as ContextValueResolver } from "./policy-service.js";
3
4
  import { i as ComputeEvaluatorRegistration } from "./gate-engine-registry.js";
4
5
 
@@ -0,0 +1,85 @@
1
+ //#region src/core/plugins/types.d.ts
2
+ /**
3
+ * Common shape every plugin shares, regardless of the contract it implements.
4
+ * Carries the metadata the {@link PluginManager} uses to identify, order and
5
+ * toggle plugins.
6
+ */
7
+ interface BasePlugin {
8
+ /** Unique identifier, used for logs / debugging and for enable/disable. */
9
+ readonly name: string;
10
+ /** Weight; the highest priority wins (default = 0). */
11
+ readonly priority?: number;
12
+ /** Shortcut to disable a plugin without removing it. */
13
+ enabled?: boolean;
14
+ }
15
+ /**
16
+ * A plugin contract is a record whose values are the methods plugins may
17
+ * implement for a given extension point.
18
+ *
19
+ * `any` here is intentional: it is the only way to express the constraint
20
+ * "a record whose values are arbitrary functions". Using `unknown` for the
21
+ * parameters breaks assignment of concrete contracts by contravariance —
22
+ * TypeScript rejects functions with specific parameters as a subtype of
23
+ * `(...args: unknown[]) => unknown`.
24
+ */
25
+ type PluginContract = Record<string, (...args: any[]) => any>;
26
+ /**
27
+ * Reducer used in `pipeline` mode to combine the result of each plugin into a
28
+ * single accumulated value.
29
+ */
30
+ type PipelineReducer<R, P extends PluginContract> = (accumulated: R, current: R, plugin: P & BasePlugin, index: number) => R;
31
+ /** Options accepted by {@link PluginManager.invoke}. */
32
+ interface InvokeOptions<P extends PluginContract, K extends keyof P> {
33
+ /**
34
+ * `'first'` → returns the first enabled plugin with the highest priority.
35
+ * `'pipeline'` → runs every enabled plugin, combining results via `reducer`.
36
+ * default = `'first'`.
37
+ */
38
+ mode?: "first" | "pipeline";
39
+ /** Executed when no plugin is enabled for the method. */
40
+ fallback: P[K];
41
+ /** Reducer used only when `mode = "pipeline"`. */
42
+ reducer?: PipelineReducer<ReturnType<P[K]>, P>;
43
+ }
44
+ //#endregion
45
+ //#region src/core/plugins/plugin.d.ts
46
+ /**
47
+ * Registry that holds a set of plugins implementing a shared {@link PluginContract}
48
+ * and resolves which of them answer a given extension point.
49
+ *
50
+ * Plugins are kept sorted by priority (descending). For a given method,
51
+ * {@link invoke} either delegates to the highest-priority enabled plugin
52
+ * (`'first'`) or folds every enabled plugin into a single value (`'pipeline'`).
53
+ * When no plugin is enabled, the supplied `fallback` runs instead, so the host
54
+ * always has defined behaviour even with an empty registry.
55
+ *
56
+ * @typeParam P - The plugin contract this manager coordinates.
57
+ */
58
+ declare class PluginManager<P extends PluginContract> {
59
+ /** Internal list, kept sorted by priority (desc). */
60
+ private plugins;
61
+ /** Registers one or more plugins and re-sorts by priority. */
62
+ register(...plugins: (P & BasePlugin)[]): void;
63
+ /** Removes a previously registered plugin by name. */
64
+ unregister(name: string): void;
65
+ /** Enables a registered plugin by name. */
66
+ enable(name: string): void;
67
+ /** Disables a registered plugin by name (without removing it). */
68
+ disable(name: string): void;
69
+ /** Lists enabled plugins only, already in priority order. */
70
+ list(): readonly (P & BasePlugin)[];
71
+ /**
72
+ * Resolves `method` against the registered plugins.
73
+ *
74
+ * In `'first'` mode the highest-priority enabled plugin that implements
75
+ * `method` answers. In `'pipeline'` mode every enabled plugin runs and the
76
+ * results are folded with `reducer` (defaults to "keep the last result").
77
+ * When no enabled plugin implements `method`, `fallback` is called.
78
+ */
79
+ invoke<K extends keyof P>(method: K, args: Parameters<P[K]>, opts: InvokeOptions<P, K>): ReturnType<P[K]>;
80
+ /** Re-sorts the internal list by priority (desc; default priority = 0). */
81
+ private reorder;
82
+ }
83
+ //#endregion
84
+ export { PluginContract as a, PipelineReducer as i, BasePlugin as n, InvokeOptions as r, PluginManager as t };
85
+ //# sourceMappingURL=plugin.d.ts.map
package/dist/plugin.js ADDED
@@ -0,0 +1,74 @@
1
+ //#region src/core/plugins/plugin.ts
2
+ /**
3
+ * Registry that holds a set of plugins implementing a shared {@link PluginContract}
4
+ * and resolves which of them answer a given extension point.
5
+ *
6
+ * Plugins are kept sorted by priority (descending). For a given method,
7
+ * {@link invoke} either delegates to the highest-priority enabled plugin
8
+ * (`'first'`) or folds every enabled plugin into a single value (`'pipeline'`).
9
+ * When no plugin is enabled, the supplied `fallback` runs instead, so the host
10
+ * always has defined behaviour even with an empty registry.
11
+ *
12
+ * @typeParam P - The plugin contract this manager coordinates.
13
+ */
14
+ var PluginManager = class {
15
+ constructor() {
16
+ this.plugins = [];
17
+ }
18
+ /** Registers one or more plugins and re-sorts by priority. */
19
+ register(...plugins) {
20
+ this.plugins.push(...plugins);
21
+ this.reorder();
22
+ }
23
+ /** Removes a previously registered plugin by name. */
24
+ unregister(name) {
25
+ this.plugins = this.plugins.filter((p) => p.name !== name);
26
+ }
27
+ /** Enables a registered plugin by name. */
28
+ enable(name) {
29
+ const plugin = this.plugins.find((p) => p.name === name);
30
+ if (plugin) plugin.enabled = true;
31
+ }
32
+ /** Disables a registered plugin by name (without removing it). */
33
+ disable(name) {
34
+ const plugin = this.plugins.find((p) => p.name === name);
35
+ if (plugin) plugin.enabled = false;
36
+ }
37
+ /** Lists enabled plugins only, already in priority order. */
38
+ list() {
39
+ return this.plugins.filter((p) => p.enabled !== false);
40
+ }
41
+ /**
42
+ * Resolves `method` against the registered plugins.
43
+ *
44
+ * In `'first'` mode the highest-priority enabled plugin that implements
45
+ * `method` answers. In `'pipeline'` mode every enabled plugin runs and the
46
+ * results are folded with `reducer` (defaults to "keep the last result").
47
+ * When no enabled plugin implements `method`, `fallback` is called.
48
+ */
49
+ invoke(method, args, opts) {
50
+ const { mode = "first", fallback, reducer } = opts;
51
+ const enabled = this.list().filter((p) => method in p);
52
+ if (enabled.length === 0) return fallback(...args);
53
+ if (mode === "first") {
54
+ const fn = enabled[0][method];
55
+ return fn(...args);
56
+ }
57
+ const defaultReducer = (_, curr) => curr;
58
+ const red = reducer ?? defaultReducer;
59
+ let acc = enabled[0][method](...args);
60
+ enabled.slice(1).forEach((plugin, idx) => {
61
+ const res = plugin[method](...args);
62
+ acc = red(acc, res, plugin, idx + 1);
63
+ });
64
+ return acc;
65
+ }
66
+ /** Re-sorts the internal list by priority (desc; default priority = 0). */
67
+ reorder() {
68
+ this.plugins.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
69
+ }
70
+ };
71
+ //#endregion
72
+ export { PluginManager as t };
73
+
74
+ //# sourceMappingURL=plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.js","names":[],"sources":["../src/core/plugins/plugin.ts"],"sourcesContent":["import {\n type BasePlugin,\n type InvokeOptions,\n type PipelineReducer,\n type PluginContract,\n} from \"./types.js\";\n\n/**\n * Registry that holds a set of plugins implementing a shared {@link PluginContract}\n * and resolves which of them answer a given extension point.\n *\n * Plugins are kept sorted by priority (descending). For a given method,\n * {@link invoke} either delegates to the highest-priority enabled plugin\n * (`'first'`) or folds every enabled plugin into a single value (`'pipeline'`).\n * When no plugin is enabled, the supplied `fallback` runs instead, so the host\n * always has defined behaviour even with an empty registry.\n *\n * @typeParam P - The plugin contract this manager coordinates.\n */\nclass PluginManager<P extends PluginContract> {\n /** Internal list, kept sorted by priority (desc). */\n private plugins: (P & BasePlugin)[] = [];\n\n /** Registers one or more plugins and re-sorts by priority. */\n public register(...plugins: (P & BasePlugin)[]): void {\n this.plugins.push(...plugins);\n this.reorder();\n }\n\n /** Removes a previously registered plugin by name. */\n public unregister(name: string): void {\n this.plugins = this.plugins.filter((p) => p.name !== name);\n }\n\n /** Enables a registered plugin by name. */\n public enable(name: string): void {\n const plugin = this.plugins.find((p) => p.name === name);\n if (plugin) plugin.enabled = true;\n }\n\n /** Disables a registered plugin by name (without removing it). */\n public disable(name: string): void {\n const plugin = this.plugins.find((p) => p.name === name);\n if (plugin) plugin.enabled = false;\n }\n\n /** Lists enabled plugins only, already in priority order. */\n public list(): readonly (P & BasePlugin)[] {\n return this.plugins.filter((p) => p.enabled !== false);\n }\n\n /**\n * Resolves `method` against the registered plugins.\n *\n * In `'first'` mode the highest-priority enabled plugin that implements\n * `method` answers. In `'pipeline'` mode every enabled plugin runs and the\n * results are folded with `reducer` (defaults to \"keep the last result\").\n * When no enabled plugin implements `method`, `fallback` is called.\n */\n public invoke<K extends keyof P>(\n method: K,\n args: Parameters<P[K]>,\n opts: InvokeOptions<P, K>,\n ): ReturnType<P[K]> {\n const { mode = \"first\", fallback, reducer } = opts;\n const enabled = this.list().filter((p) => method in p) as Array<\n P & BasePlugin\n >;\n\n if (enabled.length === 0) {\n return (fallback as P[K])(...args);\n }\n\n if (mode === \"first\") {\n const fn = enabled[0][method] as P[K];\n return fn(...args);\n }\n\n const defaultReducer: PipelineReducer<ReturnType<P[K]>, P> = (\n _,\n curr,\n ) => curr;\n const red = reducer ?? defaultReducer;\n\n let acc: ReturnType<P[K]> = enabled[0][method]!(...args);\n enabled.slice(1).forEach((plugin, idx) => {\n const res = plugin[method]!(...args);\n acc = red(acc, res, plugin, idx + 1);\n });\n return acc;\n }\n\n /** Re-sorts the internal list by priority (desc; default priority = 0). */\n private reorder(): void {\n this.plugins.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));\n }\n}\n\nexport { PluginManager };\n"],"mappings":";;;;;;;;;;;;;AAmBA,IAAM,gBAAN,MAA8C;;iBAEJ,CAAC;;;CAGvC,SAAgB,GAAG,SAAmC;EAClD,KAAK,QAAQ,KAAK,GAAG,OAAO;EAC5B,KAAK,QAAQ;CACjB;;CAGA,WAAkB,MAAoB;EAClC,KAAK,UAAU,KAAK,QAAQ,QAAQ,MAAM,EAAE,SAAS,IAAI;CAC7D;;CAGA,OAAc,MAAoB;EAC9B,MAAM,SAAS,KAAK,QAAQ,MAAM,MAAM,EAAE,SAAS,IAAI;EACvD,IAAI,QAAQ,OAAO,UAAU;CACjC;;CAGA,QAAe,MAAoB;EAC/B,MAAM,SAAS,KAAK,QAAQ,MAAM,MAAM,EAAE,SAAS,IAAI;EACvD,IAAI,QAAQ,OAAO,UAAU;CACjC;;CAGA,OAA2C;EACvC,OAAO,KAAK,QAAQ,QAAQ,MAAM,EAAE,YAAY,KAAK;CACzD;;;;;;;;;CAUA,OACI,QACA,MACA,MACgB;EAChB,MAAM,EAAE,OAAO,SAAS,UAAU,YAAY;EAC9C,MAAM,UAAU,KAAK,KAAK,EAAE,QAAQ,MAAM,UAAU,CAAC;EAIrD,IAAI,QAAQ,WAAW,GACnB,OAAQ,SAAkB,GAAG,IAAI;EAGrC,IAAI,SAAS,SAAS;GAClB,MAAM,KAAK,QAAQ,GAAG;GACtB,OAAO,GAAG,GAAG,IAAI;EACrB;EAEA,MAAM,kBACF,GACA,SACC;EACL,MAAM,MAAM,WAAW;EAEvB,IAAI,MAAwB,QAAQ,GAAG,QAAS,GAAG,IAAI;EACvD,QAAQ,MAAM,CAAC,EAAE,SAAS,QAAQ,QAAQ;GACtC,MAAM,MAAM,OAAO,QAAS,GAAG,IAAI;GACnC,MAAM,IAAI,KAAK,KAAK,QAAQ,MAAM,CAAC;EACvC,CAAC;EACD,OAAO;CACX;;CAGA,UAAwB;EACpB,KAAK,QAAQ,MAAM,GAAG,OAAO,EAAE,YAAY,MAAM,EAAE,YAAY,EAAE;CACrE;AACJ"}