@venizia/ignis-kernel 0.5.0-3 → 0.5.0-4

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 (54) hide show
  1. package/dist/esm/base/applications/boot-sequence.d.ts +2 -3
  2. package/dist/esm/base/applications/boot-sequence.js +2 -17
  3. package/dist/esm/base/applications/boot-sequence.js.map +1 -1
  4. package/dist/esm/base/applications/common/constants.d.ts +3 -6
  5. package/dist/esm/base/applications/common/constants.js +3 -17
  6. package/dist/esm/base/applications/common/constants.js.map +1 -1
  7. package/dist/esm/base/auth/authenticate/common/constants/authentication.d.ts +3 -7
  8. package/dist/esm/base/auth/authenticate/common/constants/authentication.js +3 -11
  9. package/dist/esm/base/auth/authenticate/common/constants/authentication.js.map +1 -1
  10. package/dist/esm/base/auth/authenticate/common/constants/jose.d.ts +6 -15
  11. package/dist/esm/base/auth/authenticate/common/constants/jose.js +6 -25
  12. package/dist/esm/base/auth/authenticate/common/constants/jose.js.map +1 -1
  13. package/dist/esm/base/auth/authorize/common/constants/authorization.d.ts +4 -9
  14. package/dist/esm/base/auth/authorize/common/constants/authorization.js +4 -15
  15. package/dist/esm/base/auth/authorize/common/constants/authorization.js.map +1 -1
  16. package/dist/esm/base/auth/authorize/common/constants/enforcer.d.ts +5 -12
  17. package/dist/esm/base/auth/authorize/common/constants/enforcer.js +5 -26
  18. package/dist/esm/base/auth/authorize/common/constants/enforcer.js.map +1 -1
  19. package/dist/esm/base/controllers/common/constants.d.ts +3 -6
  20. package/dist/esm/base/controllers/common/constants.js +3 -11
  21. package/dist/esm/base/controllers/common/constants.js.map +1 -1
  22. package/dist/esm/base/controllers/factory/controller.js +1 -1
  23. package/dist/esm/base/controllers/factory/controller.js.map +1 -1
  24. package/dist/esm/base/datasources/common/types.d.ts +2 -3
  25. package/dist/esm/base/datasources/common/types.js +2 -5
  26. package/dist/esm/base/datasources/common/types.js.map +1 -1
  27. package/dist/esm/base/events/common/constants.d.ts +2 -3
  28. package/dist/esm/base/events/common/constants.js +2 -5
  29. package/dist/esm/base/events/common/constants.js.map +1 -1
  30. package/dist/esm/base/events/event-bus.js +1 -1
  31. package/dist/esm/base/events/event-bus.js.map +1 -1
  32. package/dist/esm/base/metadata/injectable.js +1 -1
  33. package/dist/esm/base/metadata/injectable.js.map +1 -1
  34. package/dist/esm/base/metadata/model-metadata.js +1 -1
  35. package/dist/esm/base/metadata/model-metadata.js.map +1 -1
  36. package/dist/esm/base/metadata/persistents/datasource.js +1 -1
  37. package/dist/esm/base/metadata/persistents/datasource.js.map +1 -1
  38. package/dist/esm/base/metadata/persistents/repository/validate.js +1 -1
  39. package/dist/esm/base/metadata/persistents/repository/validate.js.map +1 -1
  40. package/dist/esm/base/models/common/constants.d.ts +5 -11
  41. package/dist/esm/base/models/common/constants.js +5 -23
  42. package/dist/esm/base/models/common/constants.js.map +1 -1
  43. package/dist/esm/base/repositories/common/constants.d.ts +7 -18
  44. package/dist/esm/base/repositories/common/constants.js +7 -35
  45. package/dist/esm/base/repositories/common/constants.js.map +1 -1
  46. package/dist/esm/common/statuses/user.d.ts +2 -3
  47. package/dist/esm/common/statuses/user.js +2 -5
  48. package/dist/esm/common/statuses/user.js.map +1 -1
  49. package/dist/esm/helpers/inversion/common/constants.d.ts +3 -6
  50. package/dist/esm/helpers/inversion/common/constants.js +3 -18
  51. package/dist/esm/helpers/inversion/common/constants.js.map +1 -1
  52. package/dist/esm/helpers/inversion/common/types/model.d.ts +1 -1
  53. package/dist/esm/helpers/inversion/common/types/model.js.map +1 -1
  54. package/package.json +3 -3
@@ -1,31 +1,20 @@
1
+ import { ConstClass } from '@venizia/ignis-helpers/common';
1
2
  /** Kinds of enforcer a registration can declare; `casbin` takes `ICasbinEnforcerOptions`, `custom` takes untyped options. */
2
- export class AuthorizationEnforcerTypes {
3
+ export class AuthorizationEnforcerTypes extends ConstClass {
3
4
  static { this.CASBIN = 'casbin'; }
4
5
  static { this.CUSTOM = 'custom'; }
5
- static { this.SCHEME_SET = new Set([this.CASBIN, this.CUSTOM]); }
6
- static isValid(input) {
7
- return this.SCHEME_SET.has(input);
8
- }
9
6
  }
10
7
  /** Cache backends for a Casbin enforcer's per-user policy lines. */
11
- export class CasbinEnforcerCachedDrivers {
8
+ export class CasbinEnforcerCachedDrivers extends ConstClass {
12
9
  static { this.REDIS = 'redis'; }
13
- static { this.SCHEME_SET = new Set([this.REDIS]); }
14
- static isValid(input) {
15
- return this.SCHEME_SET.has(input);
16
- }
17
10
  }
18
11
  /** Where a Casbin enforcer reads its model from: a `file` path or inline `text`. */
19
- export class CasbinEnforcerModelDrivers {
12
+ export class CasbinEnforcerModelDrivers extends ConstClass {
20
13
  static { this.FILE = 'file'; }
21
14
  static { this.TEXT = 'text'; }
22
- static { this.SCHEME_SET = new Set([this.FILE, this.TEXT]); }
23
- static isValid(input) {
24
- return this.SCHEME_SET.has(input);
25
- }
26
15
  }
27
16
  /** Casbin matching functions selectable for the domain match in `ICasbinEnforcerOptions.domainMatching`. */
28
- export class CasbinDomainMatchingFunctions {
17
+ export class CasbinDomainMatchingFunctions extends ConstClass {
29
18
  /** `*` is the only wildcard; exact compare otherwise. Safest for `Merchant_<uuid>` domains. */
30
19
  static { this.KEY_MATCH = 'keyMatch'; }
31
20
  /** Adds URL-path `:param` segment matching. */
@@ -36,16 +25,6 @@ export class CasbinDomainMatchingFunctions {
36
25
  static { this.KEY_MATCH_4 = 'keyMatch4'; }
37
26
  /** Treats the stored/policy value as a full regular expression. */
38
27
  static { this.REGEX_MATCH = 'regexMatch'; }
39
- static { this.SCHEME_SET = new Set([
40
- this.KEY_MATCH,
41
- this.KEY_MATCH_2,
42
- this.KEY_MATCH_3,
43
- this.KEY_MATCH_4,
44
- this.REGEX_MATCH,
45
- ]); }
46
- static isValid(input) {
47
- return this.SCHEME_SET.has(input);
48
- }
49
28
  }
50
29
  /** Relation prefixes the Casbin MODEL declares (`p` + `g`..`g5`), which {@link AuthorizationPolicyVariants} maps onto (many app edge-types -> one rule). Keep in sync with the model's `[role_definition]`. */
51
30
  export class CasbinRuleVariants {
@@ -1 +1 @@
1
- {"version":3,"file":"enforcer.js","sourceRoot":"","sources":["../../../../../../../src/base/auth/authorize/common/constants/enforcer.ts"],"names":[],"mappings":"AAEA,6HAA6H;AAC7H,MAAM,OAAO,0BAA0B;aACrB,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;aAElB,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;IAEjE,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAMH,oEAAoE;AACpE,MAAM,OAAO,2BAA2B;aACtB,UAAK,GAAG,OAAO,CAAC;aAEhB,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;IAEnD,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAMH,oFAAoF;AACpF,MAAM,OAAO,0BAA0B;aACrB,SAAI,GAAG,MAAM,CAAC;aACd,SAAI,GAAG,MAAM,CAAC;aAEd,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IAE7D,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAMH,4GAA4G;AAC5G,MAAM,OAAO,6BAA6B;IACxC,+FAA+F;aAC/E,cAAS,GAAG,UAAU,CAAC;IAEvC,+CAA+C;aAC/B,gBAAW,GAAG,WAAW,CAAC;IAE1C,uCAAuC;aACvB,gBAAW,GAAG,WAAW,CAAC;IAE1C,6DAA6D;aAC7C,gBAAW,GAAG,WAAW,CAAC;IAE1C,mEAAmE;aACnD,gBAAW,GAAG,YAAY,CAAC;aAE3B,eAAU,GAAG,IAAI,GAAG,CAAC;QACnC,IAAI,CAAC,SAAS;QACd,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,WAAW;KACjB,CAAC,CAAC;IAEH,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAMH,+MAA+M;AAC/M,MAAM,OAAO,kBAAkB;IAC7B,8BAA8B;aACd,MAAC,GAAG,GAAG,CAAC;IAExB,4GAA4G;IAE5G,+FAA+F;aAC/E,MAAC,GAAG,GAAG,CAAC;IAExB,uFAAuF;aACvE,OAAE,GAAG,IAAI,CAAC;IAE1B,gEAAgE;aAChD,OAAE,GAAG,IAAI,CAAC;IAE1B,wDAAwD;aACxC,OAAE,GAAG,IAAI,CAAC;IAE1B,sDAAsD;aACtC,OAAE,GAAG,IAAI,CAAC","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\n\n/** Kinds of enforcer a registration can declare; `casbin` takes `ICasbinEnforcerOptions`, `custom` takes untyped options. */\nexport class AuthorizationEnforcerTypes {\n static readonly CASBIN = 'casbin';\n static readonly CUSTOM = 'custom';\n\n static readonly SCHEME_SET = new Set([this.CASBIN, this.CUSTOM]);\n\n static isValid(input: string): boolean {\n return this.SCHEME_SET.has(input);\n }\n}\n\n/** Union of the `AuthorizationEnforcerTypes` values. */\nexport type TAuthorizationEnforcerType = TConstValue<typeof AuthorizationEnforcerTypes>;\n\n/** Cache backends for a Casbin enforcer's per-user policy lines. */\nexport class CasbinEnforcerCachedDrivers {\n static readonly REDIS = 'redis';\n\n static readonly SCHEME_SET = new Set([this.REDIS]);\n\n static isValid(input: string): boolean {\n return this.SCHEME_SET.has(input);\n }\n}\n\n/** Union of the `CasbinEnforcerCachedDrivers` values. */\nexport type TCasbinEnforcerCachedDriver = TConstValue<typeof CasbinEnforcerCachedDrivers>;\n\n/** Where a Casbin enforcer reads its model from: a `file` path or inline `text`. */\nexport class CasbinEnforcerModelDrivers {\n static readonly FILE = 'file';\n static readonly TEXT = 'text';\n\n static readonly SCHEME_SET = new Set([this.FILE, this.TEXT]);\n\n static isValid(input: string): boolean {\n return this.SCHEME_SET.has(input);\n }\n}\n\n/** Union of the `CasbinEnforcerModelDrivers` values. */\nexport type TCasbinEnforcerModelDriver = TConstValue<typeof CasbinEnforcerModelDrivers>;\n\n/** Casbin matching functions selectable for the domain match in `ICasbinEnforcerOptions.domainMatching`. */\nexport class CasbinDomainMatchingFunctions {\n /** `*` is the only wildcard; exact compare otherwise. Safest for `Merchant_<uuid>` domains. */\n static readonly KEY_MATCH = 'keyMatch';\n\n /** Adds URL-path `:param` segment matching. */\n static readonly KEY_MATCH_2 = 'keyMatch2';\n\n /** Adds `{param}` segment matching. */\n static readonly KEY_MATCH_3 = 'keyMatch3';\n\n /** `{param}` matching with repeated-name equality checks. */\n static readonly KEY_MATCH_4 = 'keyMatch4';\n\n /** Treats the stored/policy value as a full regular expression. */\n static readonly REGEX_MATCH = 'regexMatch';\n\n static readonly SCHEME_SET = new Set([\n this.KEY_MATCH,\n this.KEY_MATCH_2,\n this.KEY_MATCH_3,\n this.KEY_MATCH_4,\n this.REGEX_MATCH,\n ]);\n\n static isValid(input: string): boolean {\n return this.SCHEME_SET.has(input);\n }\n}\n\n/** Union of the `CasbinDomainMatchingFunctions` values. */\nexport type TCasbinDomainMatchingFunction = TConstValue<typeof CasbinDomainMatchingFunctions>;\n\n/** Relation prefixes the Casbin MODEL declares (`p` + `g`..`g5`), which {@link AuthorizationPolicyVariants} maps onto (many app edge-types -> one rule). Keep in sync with the model's `[role_definition]`. */\nexport class CasbinRuleVariants {\n /** Permission policy line. */\n static readonly P = 'p';\n\n /** Numbered in request-tuple order (sub -> dom -> obj -> act): g (sub), g2/g3 (dom), g4 (obj), g5 (act). */\n\n /** Grouping #1 - role membership + role inheritance (user→role, role→role). The `sub` axis. */\n static readonly G = 'g';\n\n /** Grouping #2 - user→domain membership (join_domain). The `dom` axis (membership). */\n static readonly G2 = 'g2';\n\n /** Grouping #3 - domain hierarchy. The `dom` axis (nesting). */\n static readonly G3 = 'g3';\n\n /** Grouping #4 - resource hierarchy. The `obj` axis. */\n static readonly G4 = 'g4';\n\n /** Grouping #5 - action hierarchy. The `act` axis. */\n static readonly G5 = 'g5';\n}\n\n/** Union of the `CasbinRuleVariants` values. */\nexport type TCasbinRuleVariant = TConstValue<typeof CasbinRuleVariants>;\n"]}
1
+ {"version":3,"file":"enforcer.js","sourceRoot":"","sources":["../../../../../../../src/base/auth/authorize/common/constants/enforcer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAE3D,6HAA6H;AAC7H,MAAM,OAAO,0BAA2B,SAAQ,UAAU;aACxC,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;;AAMpC,oEAAoE;AACpE,MAAM,OAAO,2BAA4B,SAAQ,UAAU;aACzC,UAAK,GAAG,OAAO,CAAC;;AAMlC,oFAAoF;AACpF,MAAM,OAAO,0BAA2B,SAAQ,UAAU;aACxC,SAAI,GAAG,MAAM,CAAC;aACd,SAAI,GAAG,MAAM,CAAC;;AAMhC,4GAA4G;AAC5G,MAAM,OAAO,6BAA8B,SAAQ,UAAU;IAC3D,+FAA+F;aAC/E,cAAS,GAAG,UAAU,CAAC;IAEvC,+CAA+C;aAC/B,gBAAW,GAAG,WAAW,CAAC;IAE1C,uCAAuC;aACvB,gBAAW,GAAG,WAAW,CAAC;IAE1C,6DAA6D;aAC7C,gBAAW,GAAG,WAAW,CAAC;IAE1C,mEAAmE;aACnD,gBAAW,GAAG,YAAY,CAAC;;AAM7C,+MAA+M;AAC/M,MAAM,OAAO,kBAAkB;IAC7B,8BAA8B;aACd,MAAC,GAAG,GAAG,CAAC;IAExB,4GAA4G;IAE5G,+FAA+F;aAC/E,MAAC,GAAG,GAAG,CAAC;IAExB,uFAAuF;aACvE,OAAE,GAAG,IAAI,CAAC;IAE1B,gEAAgE;aAChD,OAAE,GAAG,IAAI,CAAC;IAE1B,wDAAwD;aACxC,OAAE,GAAG,IAAI,CAAC;IAE1B,sDAAsD;aACtC,OAAE,GAAG,IAAI,CAAC","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\nimport { ConstClass } from '@venizia/ignis-helpers/common';\n\n/** Kinds of enforcer a registration can declare; `casbin` takes `ICasbinEnforcerOptions`, `custom` takes untyped options. */\nexport class AuthorizationEnforcerTypes extends ConstClass {\n static readonly CASBIN = 'casbin';\n static readonly CUSTOM = 'custom';\n}\n\n/** Union of the `AuthorizationEnforcerTypes` values. */\nexport type TAuthorizationEnforcerType = TConstValue<typeof AuthorizationEnforcerTypes>;\n\n/** Cache backends for a Casbin enforcer's per-user policy lines. */\nexport class CasbinEnforcerCachedDrivers extends ConstClass {\n static readonly REDIS = 'redis';\n}\n\n/** Union of the `CasbinEnforcerCachedDrivers` values. */\nexport type TCasbinEnforcerCachedDriver = TConstValue<typeof CasbinEnforcerCachedDrivers>;\n\n/** Where a Casbin enforcer reads its model from: a `file` path or inline `text`. */\nexport class CasbinEnforcerModelDrivers extends ConstClass {\n static readonly FILE = 'file';\n static readonly TEXT = 'text';\n}\n\n/** Union of the `CasbinEnforcerModelDrivers` values. */\nexport type TCasbinEnforcerModelDriver = TConstValue<typeof CasbinEnforcerModelDrivers>;\n\n/** Casbin matching functions selectable for the domain match in `ICasbinEnforcerOptions.domainMatching`. */\nexport class CasbinDomainMatchingFunctions extends ConstClass {\n /** `*` is the only wildcard; exact compare otherwise. Safest for `Merchant_<uuid>` domains. */\n static readonly KEY_MATCH = 'keyMatch';\n\n /** Adds URL-path `:param` segment matching. */\n static readonly KEY_MATCH_2 = 'keyMatch2';\n\n /** Adds `{param}` segment matching. */\n static readonly KEY_MATCH_3 = 'keyMatch3';\n\n /** `{param}` matching with repeated-name equality checks. */\n static readonly KEY_MATCH_4 = 'keyMatch4';\n\n /** Treats the stored/policy value as a full regular expression. */\n static readonly REGEX_MATCH = 'regexMatch';\n}\n\n/** Union of the `CasbinDomainMatchingFunctions` values. */\nexport type TCasbinDomainMatchingFunction = TConstValue<typeof CasbinDomainMatchingFunctions>;\n\n/** Relation prefixes the Casbin MODEL declares (`p` + `g`..`g5`), which {@link AuthorizationPolicyVariants} maps onto (many app edge-types -> one rule). Keep in sync with the model's `[role_definition]`. */\nexport class CasbinRuleVariants {\n /** Permission policy line. */\n static readonly P = 'p';\n\n /** Numbered in request-tuple order (sub -> dom -> obj -> act): g (sub), g2/g3 (dom), g4 (obj), g5 (act). */\n\n /** Grouping #1 - role membership + role inheritance (user→role, role→role). The `sub` axis. */\n static readonly G = 'g';\n\n /** Grouping #2 - user→domain membership (join_domain). The `dom` axis (membership). */\n static readonly G2 = 'g2';\n\n /** Grouping #3 - domain hierarchy. The `dom` axis (nesting). */\n static readonly G3 = 'g3';\n\n /** Grouping #4 - resource hierarchy. The `obj` axis. */\n static readonly G4 = 'g4';\n\n /** Grouping #5 - action hierarchy. The `act` axis. */\n static readonly G5 = 'g5';\n}\n\n/** Union of the `CasbinRuleVariants` values. */\nexport type TCasbinRuleVariant = TConstValue<typeof CasbinRuleVariants>;\n"]}
@@ -1,4 +1,5 @@
1
1
  import type { TConstValue } from '@venizia/ignis-helpers/common';
2
+ import { ConstClass } from '@venizia/ignis-helpers/common';
2
3
  import type { TResponseHeaders } from './types/index.js';
3
4
  /**
4
5
  * Constants with NO zod import, deliberately. The container's controller mixin imports
@@ -13,11 +14,9 @@ export declare class ControllerTransports {
13
14
  /** Union of the `ControllerTransports` values. */
14
15
  export type TControllerTransport = TConstValue<typeof ControllerTransports>;
15
16
  /** Shape of `data` in a `{ count, data }` response, echoed in the `X-Response-Format` header. */
16
- export declare class ResponseFormats {
17
+ export declare class ResponseFormats extends ConstClass {
17
18
  static readonly OBJECT = "object";
18
19
  static readonly ARRAY = "array";
19
- static readonly SCHEME_SET: Set<string>;
20
- static isValid(value: string): boolean;
21
20
  }
22
21
  /** Union of the `ResponseFormats` values. */
23
22
  export type TResponseFormat = TConstValue<typeof ResponseFormats>;
@@ -43,12 +42,10 @@ export declare const commonResponseHeaders: TResponseHeaders;
43
42
  /** OpenAPI response headers of a list route: `commonResponseHeaders` plus `Content-Range` for pagination. */
44
43
  export declare const findResponseHeaders: TResponseHeaders;
45
44
  /** Which decorator-defined routes `registerRoutesFromRegistry` registers: STATIC (no path parameter), PARAM (a path parameter) or ALL. */
46
- export declare class RoutePathScopes {
45
+ export declare class RoutePathScopes extends ConstClass {
47
46
  static readonly STATIC = "static";
48
47
  static readonly PARAM = "param";
49
48
  static readonly ALL = "all";
50
- static readonly SCHEME_SET: Set<string>;
51
- static isValid(value: string): boolean;
52
49
  }
53
50
  /** Valid route path scope values. */
54
51
  export type TRoutePathScope = TConstValue<typeof RoutePathScopes>;
@@ -1,4 +1,4 @@
1
- import { HTTP } from '@venizia/ignis-helpers/common';
1
+ import { HTTP, ConstClass } from '@venizia/ignis-helpers/common';
2
2
  /**
3
3
  * Constants with NO zod import, deliberately. The container's controller mixin imports
4
4
  * `ControllerTransports` from here, so anything this file pulls in reaches every consumer of
@@ -10,13 +10,9 @@ export class ControllerTransports {
10
10
  static { this.GRPC = 'grpc'; }
11
11
  }
12
12
  /** Shape of `data` in a `{ count, data }` response, echoed in the `X-Response-Format` header. */
13
- export class ResponseFormats {
13
+ export class ResponseFormats extends ConstClass {
14
14
  static { this.OBJECT = 'object'; }
15
15
  static { this.ARRAY = 'array'; }
16
- static { this.SCHEME_SET = new Set([this.OBJECT, this.ARRAY]); }
17
- static isValid(value) {
18
- return this.SCHEME_SET.has(value);
19
- }
20
16
  }
21
17
  /** Standard REST API path constants for CRUD controllers. */
22
18
  export class RestPaths {
@@ -59,13 +55,9 @@ export const findResponseHeaders = {
59
55
  },
60
56
  };
61
57
  /** Which decorator-defined routes `registerRoutesFromRegistry` registers: STATIC (no path parameter), PARAM (a path parameter) or ALL. */
62
- export class RoutePathScopes {
58
+ export class RoutePathScopes extends ConstClass {
63
59
  static { this.STATIC = 'static'; }
64
60
  static { this.PARAM = 'param'; }
65
61
  static { this.ALL = 'all'; }
66
- static { this.SCHEME_SET = new Set([this.STATIC, this.PARAM, this.ALL]); }
67
- static isValid(value) {
68
- return this.SCHEME_SET.has(value);
69
- }
70
62
  }
71
63
  //# sourceMappingURL=constants.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/base/controllers/common/constants.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAGrD;;;;GAIG;AAEH,oDAAoD;AACpD,MAAM,OAAO,oBAAoB;aACf,SAAI,GAAG,MAAM,CAAC;aACd,SAAI,GAAG,MAAM,CAAC;;AAMhC,iGAAiG;AACjG,MAAM,OAAO,eAAe;aACV,WAAM,GAAG,QAAQ,CAAC;aAClB,UAAK,GAAG,OAAO,CAAC;aAEhB,eAAU,GAAG,IAAI,GAAG,CAAS,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;IAExE,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAMH,6DAA6D;AAC7D,MAAM,OAAO,SAAS;aACJ,SAAI,GAAG,GAAG,CAAC;aACX,UAAK,GAAG,QAAQ,CAAC;aACjB,aAAQ,GAAG,WAAW,CAAC;aACvB,YAAO,GAAG,UAAU,CAAC;;AAGvC,qEAAqE;AACrE,MAAM,OAAO,UAAU;IACrB,uEAAuE;aACvD,SAAI,GAAG;QACrB,KAAK,EAAE,IAAI;QACX,IAAI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C,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport type { TCrudRoutes, TResponseHeaders } from './types';\n\n/**\n * Constants with NO zod import, deliberately. The container's controller mixin imports\n * `ControllerTransports` from here, so anything this file pulls in reaches every consumer of\n * `Container` - the request schemas live in `schemas.ts` for exactly that reason.\n */\n\n/** Transport protocol constants for controllers. */\nexport class ControllerTransports {\n static readonly REST = 'rest';\n static readonly GRPC = 'grpc';\n}\n\n/** Union of the `ControllerTransports` values. */\nexport type TControllerTransport = TConstValue<typeof ControllerTransports>;\n\n/** Shape of `data` in a `{ count, data }` response, echoed in the `X-Response-Format` header. */\nexport class ResponseFormats {\n static readonly OBJECT = 'object';\n static readonly ARRAY = 'array';\n\n static readonly SCHEME_SET = new Set<string>([this.OBJECT, this.ARRAY]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Union of the `ResponseFormats` values. */\nexport type TResponseFormat = TConstValue<typeof ResponseFormats>;\n\n/** Standard REST API path constants for CRUD controllers. */\nexport class RestPaths {\n static readonly ROOT = '/';\n static readonly COUNT = '/count';\n static readonly FIND_ONE = '/find-one';\n static readonly RESTORE = '/restore';\n}\n\n/** Route groups to spread into the `routes` of a CRUD controller. */\nexport class CrudRoutes {\n /** The four read routes: `count`, `find`, `findById` and `findOne`. */\n static readonly READ = {\n count: true,\n find: true,\n findById: true,\n findOne: true,\n } satisfies TCrudRoutes;\n}\n\n/** OpenAPI response headers every CRUD route documents: the request tracing id, the record count and the response format. */\nexport const commonResponseHeaders: TResponseHeaders = {\n [HTTP.Headers.REQUEST_TRACING_ID]: {\n description: 'Echo of the request tracing ID',\n schema: { type: 'string' },\n },\n [HTTP.Headers.RESPONSE_COUNT_DATA]: {\n description: 'Number of records in response',\n schema: { type: 'string', examples: ['1', '10', '100'] },\n },\n [HTTP.Headers.RESPONSE_FORMAT]: {\n description: 'Response format indicator',\n schema: { type: 'string', examples: ['array', 'object'] },\n },\n};\n\n/** OpenAPI response headers of a list route: `commonResponseHeaders` plus `Content-Range` for pagination. */\nexport const findResponseHeaders: TResponseHeaders = {\n ...commonResponseHeaders,\n [HTTP.Headers.CONTENT_RANGE]: {\n description: 'Content range for pagination (e.g., \"records 0-24/100\")',\n schema: { type: 'string', examples: ['records 0-24/100', 'records 25-49/100'] },\n },\n};\n\n/** Which decorator-defined routes `registerRoutesFromRegistry` registers: STATIC (no path parameter), PARAM (a path parameter) or ALL. */\nexport class RoutePathScopes {\n static readonly STATIC = 'static';\n static readonly PARAM = 'param';\n static readonly ALL = 'all';\n\n static readonly SCHEME_SET = new Set<string>([this.STATIC, this.PARAM, this.ALL]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Valid route path scope values. */\nexport type TRoutePathScope = TConstValue<typeof RoutePathScopes>;\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/base/controllers/common/constants.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAGjE;;;;GAIG;AAEH,oDAAoD;AACpD,MAAM,OAAO,oBAAoB;aACf,SAAI,GAAG,MAAM,CAAC;aACd,SAAI,GAAG,MAAM,CAAC;;AAMhC,iGAAiG;AACjG,MAAM,OAAO,eAAgB,SAAQ,UAAU;aAC7B,WAAM,GAAG,QAAQ,CAAC;aAClB,UAAK,GAAG,OAAO,CAAC;;AAMlC,6DAA6D;AAC7D,MAAM,OAAO,SAAS;aACJ,SAAI,GAAG,GAAG,CAAC;aACX,UAAK,GAAG,QAAQ,CAAC;aACjB,aAAQ,GAAG,WAAW,CAAC;aACvB,YAAO,GAAG,UAAU,CAAC;;AAGvC,qEAAqE;AACrE,MAAM,OAAO,UAAU;IACrB,uEAAuE;aACvD,SAAI,GAAG;QACrB,KAAK,EAAE,IAAI;QACX,IAAI,EAAE,IAAI;QACV,QAAQ,EAAE,IAAI;QACd,OAAO,EAAE,IAAI;KACQ,CAAC;;AAG1B,6HAA6H;AAC7H,MAAM,CAAC,MAAM,qBAAqB,GAAqB;IACrD,CAAC,IAAI,CAAC,OAAO,CAAC,kBAAkB,CAAC,EAAE;QACjC,WAAW,EAAE,gCAAgC;QAC7C,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;KAC3B;IACD,CAAC,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,EAAE;QAClC,WAAW,EAAE,+BAA+B;QAC5C,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,KAAK,CAAC,EAAE;KACzD;IACD,CAAC,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE;QAC9B,WAAW,EAAE,2BAA2B;QACxC,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,QAAQ,CAAC,EAAE;KAC1D;CACF,CAAC;AAEF,6GAA6G;AAC7G,MAAM,CAAC,MAAM,mBAAmB,GAAqB;IACnD,GAAG,qBAAqB;IACxB,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE;QAC5B,WAAW,EAAE,yDAAyD;QACtE,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,kBAAkB,EAAE,mBAAmB,CAAC,EAAE;KAChF;CACF,CAAC;AAEF,0IAA0I;AAC1I,MAAM,OAAO,eAAgB,SAAQ,UAAU;aAC7B,WAAM,GAAG,QAAQ,CAAC;aAClB,UAAK,GAAG,OAAO,CAAC;aAChB,QAAG,GAAG,KAAK,CAAC","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\nimport { HTTP, ConstClass } from '@venizia/ignis-helpers/common';\nimport type { TCrudRoutes, TResponseHeaders } from './types';\n\n/**\n * Constants with NO zod import, deliberately. The container's controller mixin imports\n * `ControllerTransports` from here, so anything this file pulls in reaches every consumer of\n * `Container` - the request schemas live in `schemas.ts` for exactly that reason.\n */\n\n/** Transport protocol constants for controllers. */\nexport class ControllerTransports {\n static readonly REST = 'rest';\n static readonly GRPC = 'grpc';\n}\n\n/** Union of the `ControllerTransports` values. */\nexport type TControllerTransport = TConstValue<typeof ControllerTransports>;\n\n/** Shape of `data` in a `{ count, data }` response, echoed in the `X-Response-Format` header. */\nexport class ResponseFormats extends ConstClass {\n static readonly OBJECT = 'object';\n static readonly ARRAY = 'array';\n}\n\n/** Union of the `ResponseFormats` values. */\nexport type TResponseFormat = TConstValue<typeof ResponseFormats>;\n\n/** Standard REST API path constants for CRUD controllers. */\nexport class RestPaths {\n static readonly ROOT = '/';\n static readonly COUNT = '/count';\n static readonly FIND_ONE = '/find-one';\n static readonly RESTORE = '/restore';\n}\n\n/** Route groups to spread into the `routes` of a CRUD controller. */\nexport class CrudRoutes {\n /** The four read routes: `count`, `find`, `findById` and `findOne`. */\n static readonly READ = {\n count: true,\n find: true,\n findById: true,\n findOne: true,\n } satisfies TCrudRoutes;\n}\n\n/** OpenAPI response headers every CRUD route documents: the request tracing id, the record count and the response format. */\nexport const commonResponseHeaders: TResponseHeaders = {\n [HTTP.Headers.REQUEST_TRACING_ID]: {\n description: 'Echo of the request tracing ID',\n schema: { type: 'string' },\n },\n [HTTP.Headers.RESPONSE_COUNT_DATA]: {\n description: 'Number of records in response',\n schema: { type: 'string', examples: ['1', '10', '100'] },\n },\n [HTTP.Headers.RESPONSE_FORMAT]: {\n description: 'Response format indicator',\n schema: { type: 'string', examples: ['array', 'object'] },\n },\n};\n\n/** OpenAPI response headers of a list route: `commonResponseHeaders` plus `Content-Range` for pagination. */\nexport const findResponseHeaders: TResponseHeaders = {\n ...commonResponseHeaders,\n [HTTP.Headers.CONTENT_RANGE]: {\n description: 'Content range for pagination (e.g., \"records 0-24/100\")',\n schema: { type: 'string', examples: ['records 0-24/100', 'records 25-49/100'] },\n },\n};\n\n/** Which decorator-defined routes `registerRoutesFromRegistry` registers: STATIC (no path parameter), PARAM (a path parameter) or ALL. */\nexport class RoutePathScopes extends ConstClass {\n static readonly STATIC = 'static';\n static readonly PARAM = 'param';\n static readonly ALL = 'all';\n}\n\n/** Valid route path scope values. */\nexport type TRoutePathScope = TConstValue<typeof RoutePathScopes>;\n"]}
@@ -79,7 +79,7 @@ export class CrudControllerFactory extends BaseHelper {
79
79
  create: entityInstance.getSchema({ type: SchemaTypes.CREATE }),
80
80
  update: entityInstance.getSchema({ type: SchemaTypes.UPDATE }),
81
81
  },
82
- serverStampedKeys: [...(settings?.properties?.stamped ?? AuditFields.SCHEME_SET)],
82
+ serverStampedKeys: [...(settings?.properties?.stamped ?? AuditFields.values())],
83
83
  });
84
84
  const controllerClass = class extends PersistableCrudController {
85
85
  constructor(repositoryInstance) {
@@ -1 +1 @@
1
- {"version":3,"file":"controller.js","sourceRoot":"","sources":["../../../../../src/base/controllers/factory/controller.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAG9E,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAE1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEpE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AASnD,OAAO,EAAE,yBAAyB,EAAE,MAAM,QAAQ,CAAC;AACnD,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAEnD,6EAA6E;AAC7E,MAAM,OAAO,qBAAsB,SAAQ,UAAU;IACnD,0GAA0G;aAClF,gBAAW,GAAG;QACpC,QAAQ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CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC/F,MAAM,KAAK,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,cAAc,IAAI,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAE9E,MAAM,QAAQ,CAAC;YACb,OAAO,EAAE;gBACP,gGAAgG,cAAc,cAAc,KAAK,iBAAiB,SAAS,EAAE;gBAC7J,sEAAsE;gBACtE,0HAA0H;aAC3H,CAAC,IAAI,CAAC,KAAK,CAAC;SACd,CAAC,CAAC;IACL,CAAC","sourcesContent":["import type { AbstractRepository } from '@/base/repositories';\nimport { AuthorizationActions } from '@/base/auth/authorize/common/constants';\nimport type { IAuthorizationSpec } from '@/base/auth/authorize/common/types';\nimport type { AbstractEntity } from '@/base/models';\nimport { AuditFields, SchemaTypes } from '@/base/models/common/constants';\nimport type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\nimport { BindingNamespaces } from '@/common/bindings';\nimport { BindingKeys, MetadataRegistry } from '@/helpers/inversion';\nimport type { TClass, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { isClass } from '@venizia/ignis-inversion';\nimport type { Env, Schema } from 'hono';\nimport type {\n ICrudControllerOptions,\n TCrudRepositoryClass,\n TCrudRoutes,\n TRepositoryDataObject,\n TRepositoryPersistObject,\n} from '../common';\nimport { PersistableCrudController } from './crud';\nimport { RouteConfigResolver } from './definition';\n\n/** Factory for generating typed CRUD controllers from entity definitions. */\nexport class CrudControllerFactory extends BaseHelper {\n /** The generated routes that change data: the ones that must never be answered by a `read` permission. */\n private static readonly WRITE_VERBS = [\n 'create',\n 'updateById',\n 'updateBy',\n 'deleteById',\n 'deleteBy',\n 'restoreById',\n 'restoreBy',\n ] as const;\n\n constructor() {\n super({ scope: CrudControllerFactory.name });\n }\n\n /**\n * Injects `repositories.<repositoryName>` into constructor parameter 0 of a factory-generated\n * controller, so a subclass needs no constructor. Recorded as metadata rather than a parameter\n * decorator, which Bun drops in some configurations. A subclass that declares its own `@inject` at\n * index 0 wins, and a sibling subclass keeps the factory's key.\n */\n static registerRepositoryInjection(opts: {\n target: TClass<unknown>;\n factoryName: string;\n repositoryName: string;\n }): void {\n const { target, factoryName, repositoryName } = opts;\n\n if (!repositoryName) {\n throw getError({\n message: `[${factoryName}] Invalid repository name | repository.name must name the repository binding`,\n });\n }\n\n MetadataRegistry.getInstance().setInjectMetadata({\n target,\n index: 0,\n metadata: {\n key: BindingKeys.build<unknown>({\n namespace: BindingNamespaces.REPOSITORY,\n key: repositoryName,\n }),\n index: 0,\n isOptional: false,\n },\n });\n }\n\n static build<\n Repository extends TCrudRepositoryClass,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n TDataObject extends object = TRepositoryDataObject<InstanceType<Repository>>,\n TPersistObject extends object = TRepositoryPersistObject<InstanceType<Repository>>,\n >(opts: ICrudControllerOptions<Repository>) {\n const { repository, authenticate, authorize, routes, isStrict = {} } = opts;\n\n CrudControllerFactory.assertWriteVerbsDeclareAuthorize({\n repositoryName: repository.name,\n authorize,\n routes,\n });\n CrudControllerFactory.assertRestoreRoutesSupported({ repository, routes });\n\n const model = MetadataRegistry.getInstance().getRepositoryBinding({\n target: repository,\n })?.model;\n\n if (!model) {\n throw getError({\n message: `[CrudControllerFactory.build] Cannot resolve the entity | repository: ${repository.name} | declare it with @repository({ model })`,\n });\n }\n\n const entityClass = isClass(model) ? model : model();\n const entityInstance = new entityClass();\n const settings = MetadataRegistry.getInstance().getModelMetadata({\n target: entityClass,\n })?.settings;\n\n const routeDefinitions = RouteConfigResolver.defineControllerRouteConfigs({\n isStrict: isStrict.requestSchema ?? true,\n idType: entityInstance.getIdType(),\n authenticate,\n authorize,\n routes,\n schema: {\n select: entityInstance.getSchema<TAnyObjectSchema>({ type: SchemaTypes.SELECT }),\n create: entityInstance.getSchema<TAnyObjectSchema>({ type: SchemaTypes.CREATE }),\n update: entityInstance.getSchema<TAnyObjectSchema>({ type: SchemaTypes.UPDATE }),\n },\n serverStampedKeys: [...(settings?.properties?.stamped ?? AuditFields.SCHEME_SET)],\n });\n\n const controllerClass = class extends PersistableCrudController<\n AbstractEntity<TAnyObjectSchema>,\n RouteEnv,\n RouteSchema,\n BasePath,\n ConfigurableOptions,\n TDataObject,\n TPersistObject\n > {\n constructor(repositoryInstance: AbstractRepository<TDataObject, TPersistObject>) {\n super({\n scope: new.target.name,\n isStrict: isStrict.path ?? true,\n repository: repositoryInstance,\n definitions: routeDefinitions,\n });\n }\n\n /** The routes of a generated controller come from `routes`; a subclass adds its own here. */\n override binding(): ValueOrPromise<void> {}\n\n /** Registers each listed CRUD route, after `binding()`: a custom static path is never taken by `/{id}`. */\n override bindDefaultRoutes(): ValueOrPromise<void> {\n if (routeDefinitions.COUNT) {\n this.defineRoute({\n configs: routeDefinitions.COUNT,\n handler: async (context) => this.count({ context }),\n });\n }\n\n if (routeDefinitions.FIND) {\n this.defineRoute({\n configs: routeDefinitions.FIND,\n handler: async (context) => this.find({ context }),\n });\n }\n\n if (routeDefinitions.FIND_ONE) {\n this.defineRoute({\n configs: routeDefinitions.FIND_ONE,\n handler: async (context) => this.findOne({ context }),\n });\n }\n\n if (routeDefinitions.FIND_BY_ID) {\n this.defineRoute({\n configs: routeDefinitions.FIND_BY_ID,\n handler: async (context) => this.findById({ context }),\n });\n }\n\n if (routeDefinitions.CREATE) {\n this.defineRoute({\n configs: routeDefinitions.CREATE,\n handler: async (context) => this.create({ context }),\n });\n }\n\n if (routeDefinitions.UPDATE_BY_ID) {\n this.defineRoute({\n configs: routeDefinitions.UPDATE_BY_ID,\n handler: async (context) => this.updateById({ context }),\n });\n }\n\n if (routeDefinitions.UPDATE_BY) {\n this.defineRoute({\n configs: routeDefinitions.UPDATE_BY,\n handler: async (context) => this.updateBy({ context }),\n });\n }\n\n if (routeDefinitions.DELETE_BY_ID) {\n this.defineRoute({\n configs: routeDefinitions.DELETE_BY_ID,\n handler: async (context) => this.deleteById({ context }),\n });\n }\n\n if (routeDefinitions.DELETE_BY) {\n this.defineRoute({\n configs: routeDefinitions.DELETE_BY,\n handler: async (context) => this.deleteBy({ context }),\n });\n }\n\n if (routeDefinitions.RESTORE_BY) {\n this.defineRoute({\n configs: routeDefinitions.RESTORE_BY,\n handler: async (context) => this.restoreBy({ context }),\n });\n }\n\n if (routeDefinitions.RESTORE_BY_ID) {\n this.defineRoute({\n configs: routeDefinitions.RESTORE_BY_ID,\n handler: async (context) => this.restoreById({ context }),\n });\n }\n }\n };\n\n CrudControllerFactory.registerRepositoryInjection({\n target: controllerClass,\n factoryName: 'CrudControllerFactory.build',\n repositoryName: repository.name,\n });\n\n return controllerClass;\n }\n\n /** A restore route needs a repository that has the restore methods; the types already refuse one, this is the backstop for an untyped caller. */\n private static assertRestoreRoutesSupported(opts: {\n repository: TCrudRepositoryClass;\n routes: TCrudRoutes | undefined;\n }): void {\n const { repository, routes } = opts;\n\n const isRestoreListed = routes?.restoreById !== undefined || routes?.restoreBy !== undefined;\n const isRestorable =\n typeof repository.prototype.restoreById === 'function' &&\n typeof repository.prototype.restoreBy === 'function';\n\n if (isRestoreListed && !isRestorable) {\n throw getError({\n message: `[CrudControllerFactory.build] a restore route needs a repository with both restoreById and restoreBy | repository: ${repository.name}`,\n });\n }\n }\n\n private static describeSpec(opts: { spec: IAuthorizationSpec }): string {\n const { spec } = opts;\n\n return `{ action: ${String(spec.action)}, resource: ${String(spec.resource)} }`;\n }\n\n /**\n * Refuses a CRUD controller that lists a write verb which would inherit a controller-level `authorize`\n * that is only a `read` permission: the verb would then answer to anyone who may read.\n *\n * A listed write verb is fine when it declares its own `authorize` (a spec, an array, or `{ skip: true }`) or\n * skips authentication. Only the literal action `read` is detected; a custom action name is the application's own\n * vocabulary. An array counts when every spec in it is `read`, since the specs of one route must all pass.\n */\n static assertWriteVerbsDeclareAuthorize(opts: {\n repositoryName: string;\n authorize: IAuthorizationSpec | IAuthorizationSpec[] | undefined;\n routes: TCrudRoutes | undefined;\n }): void {\n const { repositoryName, authorize, routes } = opts;\n\n if (authorize == null) {\n return;\n }\n\n const specs = Array.isArray(authorize) ? authorize : [authorize];\n const isReadOnlyPermission =\n specs.length > 0 && specs.every((spec) => spec.action === AuthorizationActions.READ);\n\n if (!isReadOnlyPermission) {\n return;\n }\n\n const offending = CrudControllerFactory.WRITE_VERBS.filter((verb) => {\n const route = routes?.[verb];\n\n if (route === undefined) {\n return false;\n }\n\n return route === true || (route.authenticate?.skip !== true && route.authorize == null);\n });\n\n if (offending.length === 0) {\n return;\n }\n\n const inherited = specs.map((spec) => CrudControllerFactory.describeSpec({ spec })).join(', ');\n const verbs = offending.map((verb) => `${repositoryName}.${verb}`).join(', ');\n\n throw getError({\n message: [\n `[CrudControllerFactory.build] Write routes would inherit a read-only authorize | repository: ${repositoryName} | routes: ${verbs} | inherited: ${inherited}`,\n 'Anyone allowed to read could then create, update, delete or restore.',\n 'Fix: declare routes.<verb>.authorize for each of them (a spec, an array or { skip: true }), or leave them out of routes.',\n ].join(' | '),\n });\n }\n}\n"]}
1
+ {"version":3,"file":"controller.js","sourceRoot":"","sources":["../../../../../src/base/controllers/factory/controller.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAG9E,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAE1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEpE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AASnD,OAAO,EAAE,yBAAyB,EAAE,MAAM,QAAQ,CAAC;AACnD,OAAO,EAAE,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;QACT,CAAC;QAED,MAAM,SAAS,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,qBAAqB,CAAC,YAAY,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC/F,MAAM,KAAK,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,cAAc,IAAI,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAE9E,MAAM,QAAQ,CAAC;YACb,OAAO,EAAE;gBACP,gGAAgG,cAAc,cAAc,KAAK,iBAAiB,SAAS,EAAE;gBAC7J,sEAAsE;gBACtE,0HAA0H;aAC3H,CAAC,IAAI,CAAC,KAAK,CAAC;SACd,CAAC,CAAC;IACL,CAAC","sourcesContent":["import type { AbstractRepository } from '@/base/repositories';\nimport { AuthorizationActions } from '@/base/auth/authorize/common/constants';\nimport type { IAuthorizationSpec } from '@/base/auth/authorize/common/types';\nimport type { AbstractEntity } from '@/base/models';\nimport { AuditFields, SchemaTypes } from '@/base/models/common/constants';\nimport type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\nimport { BindingNamespaces } from '@/common/bindings';\nimport { BindingKeys, MetadataRegistry } from '@/helpers/inversion';\nimport type { TClass, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { isClass } from '@venizia/ignis-inversion';\nimport type { Env, Schema } from 'hono';\nimport type {\n ICrudControllerOptions,\n TCrudRepositoryClass,\n TCrudRoutes,\n TRepositoryDataObject,\n TRepositoryPersistObject,\n} from '../common';\nimport { PersistableCrudController } from './crud';\nimport { RouteConfigResolver } from './definition';\n\n/** Factory for generating typed CRUD controllers from entity definitions. */\nexport class CrudControllerFactory extends BaseHelper {\n /** The generated routes that change data: the ones that must never be answered by a `read` permission. */\n private static readonly WRITE_VERBS = [\n 'create',\n 'updateById',\n 'updateBy',\n 'deleteById',\n 'deleteBy',\n 'restoreById',\n 'restoreBy',\n ] as const;\n\n constructor() {\n super({ scope: CrudControllerFactory.name });\n }\n\n /**\n * Injects `repositories.<repositoryName>` into constructor parameter 0 of a factory-generated\n * controller, so a subclass needs no constructor. Recorded as metadata rather than a parameter\n * decorator, which Bun drops in some configurations. A subclass that declares its own `@inject` at\n * index 0 wins, and a sibling subclass keeps the factory's key.\n */\n static registerRepositoryInjection(opts: {\n target: TClass<unknown>;\n factoryName: string;\n repositoryName: string;\n }): void {\n const { target, factoryName, repositoryName } = opts;\n\n if (!repositoryName) {\n throw getError({\n message: `[${factoryName}] Invalid repository name | repository.name must name the repository binding`,\n });\n }\n\n MetadataRegistry.getInstance().setInjectMetadata({\n target,\n index: 0,\n metadata: {\n key: BindingKeys.build<unknown>({\n namespace: BindingNamespaces.REPOSITORY,\n key: repositoryName,\n }),\n index: 0,\n isOptional: false,\n },\n });\n }\n\n static build<\n Repository extends TCrudRepositoryClass,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n TDataObject extends object = TRepositoryDataObject<InstanceType<Repository>>,\n TPersistObject extends object = TRepositoryPersistObject<InstanceType<Repository>>,\n >(opts: ICrudControllerOptions<Repository>) {\n const { repository, authenticate, authorize, routes, isStrict = {} } = opts;\n\n CrudControllerFactory.assertWriteVerbsDeclareAuthorize({\n repositoryName: repository.name,\n authorize,\n routes,\n });\n CrudControllerFactory.assertRestoreRoutesSupported({ repository, routes });\n\n const model = MetadataRegistry.getInstance().getRepositoryBinding({\n target: repository,\n })?.model;\n\n if (!model) {\n throw getError({\n message: `[CrudControllerFactory.build] Cannot resolve the entity | repository: ${repository.name} | declare it with @repository({ model })`,\n });\n }\n\n const entityClass = isClass(model) ? model : model();\n const entityInstance = new entityClass();\n const settings = MetadataRegistry.getInstance().getModelMetadata({\n target: entityClass,\n })?.settings;\n\n const routeDefinitions = RouteConfigResolver.defineControllerRouteConfigs({\n isStrict: isStrict.requestSchema ?? true,\n idType: entityInstance.getIdType(),\n authenticate,\n authorize,\n routes,\n schema: {\n select: entityInstance.getSchema<TAnyObjectSchema>({ type: SchemaTypes.SELECT }),\n create: entityInstance.getSchema<TAnyObjectSchema>({ type: SchemaTypes.CREATE }),\n update: entityInstance.getSchema<TAnyObjectSchema>({ type: SchemaTypes.UPDATE }),\n },\n serverStampedKeys: [...(settings?.properties?.stamped ?? AuditFields.values())],\n });\n\n const controllerClass = class extends PersistableCrudController<\n AbstractEntity<TAnyObjectSchema>,\n RouteEnv,\n RouteSchema,\n BasePath,\n ConfigurableOptions,\n TDataObject,\n TPersistObject\n > {\n constructor(repositoryInstance: AbstractRepository<TDataObject, TPersistObject>) {\n super({\n scope: new.target.name,\n isStrict: isStrict.path ?? true,\n repository: repositoryInstance,\n definitions: routeDefinitions,\n });\n }\n\n /** The routes of a generated controller come from `routes`; a subclass adds its own here. */\n override binding(): ValueOrPromise<void> {}\n\n /** Registers each listed CRUD route, after `binding()`: a custom static path is never taken by `/{id}`. */\n override bindDefaultRoutes(): ValueOrPromise<void> {\n if (routeDefinitions.COUNT) {\n this.defineRoute({\n configs: routeDefinitions.COUNT,\n handler: async (context) => this.count({ context }),\n });\n }\n\n if (routeDefinitions.FIND) {\n this.defineRoute({\n configs: routeDefinitions.FIND,\n handler: async (context) => this.find({ context }),\n });\n }\n\n if (routeDefinitions.FIND_ONE) {\n this.defineRoute({\n configs: routeDefinitions.FIND_ONE,\n handler: async (context) => this.findOne({ context }),\n });\n }\n\n if (routeDefinitions.FIND_BY_ID) {\n this.defineRoute({\n configs: routeDefinitions.FIND_BY_ID,\n handler: async (context) => this.findById({ context }),\n });\n }\n\n if (routeDefinitions.CREATE) {\n this.defineRoute({\n configs: routeDefinitions.CREATE,\n handler: async (context) => this.create({ context }),\n });\n }\n\n if (routeDefinitions.UPDATE_BY_ID) {\n this.defineRoute({\n configs: routeDefinitions.UPDATE_BY_ID,\n handler: async (context) => this.updateById({ context }),\n });\n }\n\n if (routeDefinitions.UPDATE_BY) {\n this.defineRoute({\n configs: routeDefinitions.UPDATE_BY,\n handler: async (context) => this.updateBy({ context }),\n });\n }\n\n if (routeDefinitions.DELETE_BY_ID) {\n this.defineRoute({\n configs: routeDefinitions.DELETE_BY_ID,\n handler: async (context) => this.deleteById({ context }),\n });\n }\n\n if (routeDefinitions.DELETE_BY) {\n this.defineRoute({\n configs: routeDefinitions.DELETE_BY,\n handler: async (context) => this.deleteBy({ context }),\n });\n }\n\n if (routeDefinitions.RESTORE_BY) {\n this.defineRoute({\n configs: routeDefinitions.RESTORE_BY,\n handler: async (context) => this.restoreBy({ context }),\n });\n }\n\n if (routeDefinitions.RESTORE_BY_ID) {\n this.defineRoute({\n configs: routeDefinitions.RESTORE_BY_ID,\n handler: async (context) => this.restoreById({ context }),\n });\n }\n }\n };\n\n CrudControllerFactory.registerRepositoryInjection({\n target: controllerClass,\n factoryName: 'CrudControllerFactory.build',\n repositoryName: repository.name,\n });\n\n return controllerClass;\n }\n\n /** A restore route needs a repository that has the restore methods; the types already refuse one, this is the backstop for an untyped caller. */\n private static assertRestoreRoutesSupported(opts: {\n repository: TCrudRepositoryClass;\n routes: TCrudRoutes | undefined;\n }): void {\n const { repository, routes } = opts;\n\n const isRestoreListed = routes?.restoreById !== undefined || routes?.restoreBy !== undefined;\n const isRestorable =\n typeof repository.prototype.restoreById === 'function' &&\n typeof repository.prototype.restoreBy === 'function';\n\n if (isRestoreListed && !isRestorable) {\n throw getError({\n message: `[CrudControllerFactory.build] a restore route needs a repository with both restoreById and restoreBy | repository: ${repository.name}`,\n });\n }\n }\n\n private static describeSpec(opts: { spec: IAuthorizationSpec }): string {\n const { spec } = opts;\n\n return `{ action: ${String(spec.action)}, resource: ${String(spec.resource)} }`;\n }\n\n /**\n * Refuses a CRUD controller that lists a write verb which would inherit a controller-level `authorize`\n * that is only a `read` permission: the verb would then answer to anyone who may read.\n *\n * A listed write verb is fine when it declares its own `authorize` (a spec, an array, or `{ skip: true }`) or\n * skips authentication. Only the literal action `read` is detected; a custom action name is the application's own\n * vocabulary. An array counts when every spec in it is `read`, since the specs of one route must all pass.\n */\n static assertWriteVerbsDeclareAuthorize(opts: {\n repositoryName: string;\n authorize: IAuthorizationSpec | IAuthorizationSpec[] | undefined;\n routes: TCrudRoutes | undefined;\n }): void {\n const { repositoryName, authorize, routes } = opts;\n\n if (authorize == null) {\n return;\n }\n\n const specs = Array.isArray(authorize) ? authorize : [authorize];\n const isReadOnlyPermission =\n specs.length > 0 && specs.every((spec) => spec.action === AuthorizationActions.READ);\n\n if (!isReadOnlyPermission) {\n return;\n }\n\n const offending = CrudControllerFactory.WRITE_VERBS.filter((verb) => {\n const route = routes?.[verb];\n\n if (route === undefined) {\n return false;\n }\n\n return route === true || (route.authenticate?.skip !== true && route.authorize == null);\n });\n\n if (offending.length === 0) {\n return;\n }\n\n const inherited = specs.map((spec) => CrudControllerFactory.describeSpec({ spec })).join(', ');\n const verbs = offending.map((verb) => `${repositoryName}.${verb}`).join(', ');\n\n throw getError({\n message: [\n `[CrudControllerFactory.build] Write routes would inherit a read-only authorize | repository: ${repositoryName} | routes: ${verbs} | inherited: ${inherited}`,\n 'Anyone allowed to read could then create, update, delete or restore.',\n 'Fix: declare routes.<verb>.authorize for each of them (a spec, an array or { skip: true }), or leave them out of routes.',\n ].join(' | '),\n });\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import type { IConfigurable, TClass, TConstValue, ValueOrPromise } from '@venizia/ignis-helpers/common';
2
+ import { ConstClass } from '@venizia/ignis-helpers/common';
2
3
  /** Names of the supported datasource drivers, split into relational and search sets. `isValid` checks a value against all of them. */
3
4
  export declare class DataSourceDrivers {
4
5
  static readonly NODE_POSTGRES = "node-postgres";
@@ -13,11 +14,9 @@ export declare class DataSourceDrivers {
13
14
  static isValid(value: string): boolean;
14
15
  }
15
16
  /** When a datasource opens: with the application (`start`, the default) or at the first call that needs it (`first-use`). */
16
- export declare class DataSourceOpenModes {
17
+ export declare class DataSourceOpenModes extends ConstClass {
17
18
  static readonly START = "start";
18
19
  static readonly FIRST_USE = "first-use";
19
- static readonly SCHEME_SET: Set<string>;
20
- static isValid(value: string): value is TDataSourceOpenMode;
21
20
  }
22
21
  /** Defaults of the `open` option. */
23
22
  export declare class DataSourceOpenDefaults {
@@ -1,3 +1,4 @@
1
+ import { ConstClass } from '@venizia/ignis-helpers/common';
1
2
  /** Names of the supported datasource drivers, split into relational and search sets. `isValid` checks a value against all of them. */
2
3
  export class DataSourceDrivers {
3
4
  // Relational - PGlite is a Postgres DRIVER (Postgres compiled to WASM), not a separate engine.
@@ -30,13 +31,9 @@ export class DataSourceDrivers {
30
31
  }
31
32
  }
32
33
  /** When a datasource opens: with the application (`start`, the default) or at the first call that needs it (`first-use`). */
33
- export class DataSourceOpenModes {
34
+ export class DataSourceOpenModes extends ConstClass {
34
35
  static { this.START = 'start'; }
35
36
  static { this.FIRST_USE = 'first-use'; }
36
- static { this.SCHEME_SET = new Set([this.START, this.FIRST_USE]); }
37
- static isValid(value) {
38
- return this.SCHEME_SET.has(value);
39
- }
40
37
  }
41
38
  /** Defaults of the `open` option. */
42
39
  export class DataSourceOpenDefaults {
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/base/datasources/common/types.ts"],"names":[],"mappings":"AAOA,sIAAsI;AACtI,MAAM,OAAO,iBAAiB;IAC5B,+FAA+F;aAC/E,kBAAa,GAAG,eAAe,CAAC;aAChC,gBAAW,GAAG,aAAa,CAAC;aAC5B,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;IAElC,SAAS;aACO,cAAS,GAAG,WAAW,CAAC;aACxB,gBAAW,GAAG,aAAa,CAAC;aAE5B,0BAAqB,GAAG,IAAI,GAAG,CAAC;QAC9C,IAAI,CAAC,aAAa;QAClB,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,MAAM;KACZ,CAAC,CAAC;aAEa,sBAAiB,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC;aAEhE,eAAU,GAAG,IAAI,GAAG,CAAC;QACnC,aAAa;QACb,IAAI,CAAC,aAAa;QAClB,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,MAAM;QAEX,SAAS;QACT,IAAI,CAAC,SAAS;QACd,IAAI,CAAC,WAAW;KACjB,CAAC,CAAC;IAEH,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAGH,6HAA6H;AAC7H,MAAM,OAAO,mBAAmB;aACd,UAAK,GAAG,OAAO,CAAC;aAChB,cAAS,GAAG,WAAW,CAAC;aAExB,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IAEnE,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAGH,qCAAqC;AACrC,MAAM,OAAO,sBAAsB;IACjC,qKAAqK;aACrJ,eAAU,GAAG,MAAM,CAAC","sourcesContent":["import type {\n IConfigurable,\n TClass,\n TConstValue,\n ValueOrPromise,\n} from '@venizia/ignis-helpers/common';\n\n/** Names of the supported datasource drivers, split into relational and search sets. `isValid` checks a value against all of them. */\nexport class DataSourceDrivers {\n // Relational - PGlite is a Postgres DRIVER (Postgres compiled to WASM), not a separate engine.\n static readonly NODE_POSTGRES = 'node-postgres';\n static readonly POSTGRES_JS = 'postgres-js';\n static readonly PGLITE = 'pglite';\n static readonly LIBSQL = 'libsql';\n\n // Search\n static readonly TYPESENSE = 'typesense';\n static readonly MEILISEARCH = 'meilisearch';\n\n static readonly RELATIONAL_SCHEME_SET = new Set([\n this.NODE_POSTGRES,\n this.POSTGRES_JS,\n this.PGLITE,\n this.LIBSQL,\n ]);\n\n static readonly SEARCH_SCHEME_SET = new Set([this.TYPESENSE, this.MEILISEARCH]);\n\n static readonly SCHEME_SET = new Set([\n // Relational\n this.NODE_POSTGRES,\n this.POSTGRES_JS,\n this.PGLITE,\n this.LIBSQL,\n\n // Search\n this.TYPESENSE,\n this.MEILISEARCH,\n ]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** When a datasource opens: with the application (`start`, the default) or at the first call that needs it (`first-use`). */\nexport class DataSourceOpenModes {\n static readonly START = 'start';\n static readonly FIRST_USE = 'first-use';\n\n static readonly SCHEME_SET = new Set([this.START, this.FIRST_USE]);\n\n static isValid(value: string): value is TDataSourceOpenMode {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Defaults of the `open` option. */\nexport class DataSourceOpenDefaults {\n /** How long a first use waits for the open before it gives up (ms): a WASM boot on a slow link fits, a `configure()` that waits on itself does not hang for ever. */\n static readonly TIMEOUT_MS = 60_000;\n}\n\n/** One of the {@link DataSourceOpenModes} values. */\nexport type TDataSourceOpenMode = TConstValue<typeof DataSourceOpenModes>;\n\n/** The `open` option of `@datasource`. */\nexport interface IDataSourceOpenOptions {\n /**\n * `start`: `configure()` runs when the application starts, and `listen()` waits for it. `first-use`: the application\n * starts without opening the datasource; the first call that needs it runs `configure()` once, and every call that\n * arrives meanwhile waits for that one open. A failed open rejects every waiting call, leaves nothing half-open, and is\n * tried again by the next call.\n *\n * @default 'start'\n */\n on?: TDataSourceOpenMode;\n\n /**\n * `first-use` only: how long the open may take (ms) before every waiting call is rejected with a named error and the\n * attempt is abandoned. An abandoned `configure()` that finishes later is closed and never published, and the next call\n * waits until it has settled before trying again. `0` waits for ever.\n *\n * @default 60000\n */\n timeoutMs?: number;\n}\n\n/**\n * What `configure()` is given to do its database work while the datasource is opening: the connector, the client and a\n * transaction, through the datasource's own ungated internals. Only `configure()` receives it, so nothing outside can use it\n * and every other caller still waits for the open to finish. Generic over the datasource's connector, client and\n * transaction types, so `opening.getClient()` of a PGlite datasource is a `PGlite`.\n *\n * Inside the open of a datasource that opens on first use, the public `getConnector()`, `getClient()` and\n * `beginTransaction()` are gated (they wait for the open, which waits for `configure()`), and a repository cannot be used:\n * use these handles instead.\n */\nexport interface IDataSourceOpening<\n TConnector = unknown,\n Client = unknown,\n TTransaction extends ITransaction = ITransaction,\n TTransactionOptions extends ITransactionOptions = ITransactionOptions,\n> {\n getConnector(): TConnector;\n getClient(): Client;\n beginTransaction(opts?: TTransactionOptions): Promise<TTransaction>;\n}\n\n// `(string & {})` keeps autocomplete for the known values\n// while still accepting any other engine-driver string.\n/** A driver name: one of `DataSourceDrivers`, or any other string for an unlisted engine. */\nexport type TDataSourceDriver = TConstValue<typeof DataSourceDrivers> | (string & {});\n\n/**\n * A driver CLASS, named by `@datasource({ driver })`. The class reference is what pulls the peer\n * package into a bundle - a name string pulls nothing, and a bare side-effect import may be\n * dropped. Untyped because `IRelationalDriver` lives under `connectors/`, off-limits to `base/`.\n */\nexport type TDataSourceDriverClass = TClass<unknown>;\n\n/** Loose schema record of a datasource; the default `Schema` type argument of `IDataSource`. */\nexport type TAnyDataSourceSchema = Record<string, any>;\n\n/** Engine-neutral datasource contract - the root every connector family implements. */\nexport interface IDataSource<\n Settings extends object = {},\n Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema,\n ConfigurableOptions extends object = {},\n> extends IConfigurable<ConfigurableOptions> {\n name: string;\n settings: Settings;\n schema: Schema;\n\n getSettings(): Settings;\n getSchema(): Schema;\n\n /** Releases what `configure()` opened. `stop()` calls it on every datasource the boot configured. */\n close?(): Promise<void>;\n\n /** The datasource's own `configure()` receives the handles of {@link IDataSourceOpening} as its second argument. */\n configure(opts?: ConfigurableOptions, opening?: IDataSourceOpening): ValueOrPromise<void>;\n\n /** True when the datasource opens on first use (`@datasource({ open: { on: 'first-use' } })`): the boot then calls {@link deferOpen} instead of `configure()`. */\n isOpenDeferred?(): boolean;\n\n /** Records the options `configure()` will get when the datasource opens on first use; nothing is opened. */\n deferOpen?(opts: { options?: ConfigurableOptions }): void;\n\n /** Resolves once the datasource is open: at once when it opens with the application or is already open, else after the one open that the first use starts. */\n ensureOpen?(): Promise<void>;\n}\n\n/**\n * Neutral transaction options - isolation levels are engine vocabulary, so `isolationLevel` stays\n * a loose string here and connectors narrow it in their own `ITransactionOptions` extension.\n */\nexport interface ITransactionOptions {\n isolationLevel?: string;\n}\n\n/** Neutral transaction handle - the minimum shape every connector's transaction satisfies. */\nexport interface ITransaction {\n isActive: boolean;\n commit(): Promise<void>;\n rollback(): Promise<void>;\n}\n\n/** What a datasource supports. `transactions` tells whether it can open transactions. */\nexport interface IDataSourceCapabilities {\n transactions: boolean;\n}\n\n/** Capabilities of a search datasource. Each `search` flag tells whether the engine supports that feature. */\nexport interface ISearchableDataSourceCapabilities extends IDataSourceCapabilities {\n search?: {\n /** Vector / semantic / hybrid search (search engines). */\n vector?: boolean;\n\n /** Batched multi-query search across collections. */\n multi?: boolean;\n\n /** Merged (union) result set across a multi-search. */\n union?: boolean;\n\n /** Synonym sets (multi-way / one-way). */\n synonyms?: boolean;\n };\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/base/datasources/common/types.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAE3D,sIAAsI;AACtI,MAAM,OAAO,iBAAiB;IAC5B,+FAA+F;aAC/E,kBAAa,GAAG,eAAe,CAAC;aAChC,gBAAW,GAAG,aAAa,CAAC;aAC5B,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;IAElC,SAAS;aACO,cAAS,GAAG,WAAW,CAAC;aACxB,gBAAW,GAAG,aAAa,CAAC;aAE5B,0BAAqB,GAAG,IAAI,GAAG,CAAC;QAC9C,IAAI,CAAC,aAAa;QAClB,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,MAAM;KACZ,CAAC,CAAC;aAEa,sBAAiB,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC;aAEhE,eAAU,GAAG,IAAI,GAAG,CAAC;QACnC,aAAa;QACb,IAAI,CAAC,aAAa;QAClB,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,MAAM;QAEX,SAAS;QACT,IAAI,CAAC,SAAS;QACd,IAAI,CAAC,WAAW;KACjB,CAAC,CAAC;IAEH,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAGH,6HAA6H;AAC7H,MAAM,OAAO,mBAAoB,SAAQ,UAAU;aACjC,UAAK,GAAG,OAAO,CAAC;aAChB,cAAS,GAAG,WAAW,CAAC;;AAG1C,qCAAqC;AACrC,MAAM,OAAO,sBAAsB;IACjC,qKAAqK;aACrJ,eAAU,GAAG,MAAM,CAAC","sourcesContent":["import type {\n IConfigurable,\n TClass,\n TConstValue,\n ValueOrPromise,\n} from '@venizia/ignis-helpers/common';\nimport { ConstClass } from '@venizia/ignis-helpers/common';\n\n/** Names of the supported datasource drivers, split into relational and search sets. `isValid` checks a value against all of them. */\nexport class DataSourceDrivers {\n // Relational - PGlite is a Postgres DRIVER (Postgres compiled to WASM), not a separate engine.\n static readonly NODE_POSTGRES = 'node-postgres';\n static readonly POSTGRES_JS = 'postgres-js';\n static readonly PGLITE = 'pglite';\n static readonly LIBSQL = 'libsql';\n\n // Search\n static readonly TYPESENSE = 'typesense';\n static readonly MEILISEARCH = 'meilisearch';\n\n static readonly RELATIONAL_SCHEME_SET = new Set([\n this.NODE_POSTGRES,\n this.POSTGRES_JS,\n this.PGLITE,\n this.LIBSQL,\n ]);\n\n static readonly SEARCH_SCHEME_SET = new Set([this.TYPESENSE, this.MEILISEARCH]);\n\n static readonly SCHEME_SET = new Set([\n // Relational\n this.NODE_POSTGRES,\n this.POSTGRES_JS,\n this.PGLITE,\n this.LIBSQL,\n\n // Search\n this.TYPESENSE,\n this.MEILISEARCH,\n ]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** When a datasource opens: with the application (`start`, the default) or at the first call that needs it (`first-use`). */\nexport class DataSourceOpenModes extends ConstClass {\n static readonly START = 'start';\n static readonly FIRST_USE = 'first-use';\n}\n\n/** Defaults of the `open` option. */\nexport class DataSourceOpenDefaults {\n /** How long a first use waits for the open before it gives up (ms): a WASM boot on a slow link fits, a `configure()` that waits on itself does not hang for ever. */\n static readonly TIMEOUT_MS = 60_000;\n}\n\n/** One of the {@link DataSourceOpenModes} values. */\nexport type TDataSourceOpenMode = TConstValue<typeof DataSourceOpenModes>;\n\n/** The `open` option of `@datasource`. */\nexport interface IDataSourceOpenOptions {\n /**\n * `start`: `configure()` runs when the application starts, and `listen()` waits for it. `first-use`: the application\n * starts without opening the datasource; the first call that needs it runs `configure()` once, and every call that\n * arrives meanwhile waits for that one open. A failed open rejects every waiting call, leaves nothing half-open, and is\n * tried again by the next call.\n *\n * @default 'start'\n */\n on?: TDataSourceOpenMode;\n\n /**\n * `first-use` only: how long the open may take (ms) before every waiting call is rejected with a named error and the\n * attempt is abandoned. An abandoned `configure()` that finishes later is closed and never published, and the next call\n * waits until it has settled before trying again. `0` waits for ever.\n *\n * @default 60000\n */\n timeoutMs?: number;\n}\n\n/**\n * What `configure()` is given to do its database work while the datasource is opening: the connector, the client and a\n * transaction, through the datasource's own ungated internals. Only `configure()` receives it, so nothing outside can use it\n * and every other caller still waits for the open to finish. Generic over the datasource's connector, client and\n * transaction types, so `opening.getClient()` of a PGlite datasource is a `PGlite`.\n *\n * Inside the open of a datasource that opens on first use, the public `getConnector()`, `getClient()` and\n * `beginTransaction()` are gated (they wait for the open, which waits for `configure()`), and a repository cannot be used:\n * use these handles instead.\n */\nexport interface IDataSourceOpening<\n TConnector = unknown,\n Client = unknown,\n TTransaction extends ITransaction = ITransaction,\n TTransactionOptions extends ITransactionOptions = ITransactionOptions,\n> {\n getConnector(): TConnector;\n getClient(): Client;\n beginTransaction(opts?: TTransactionOptions): Promise<TTransaction>;\n}\n\n// `(string & {})` keeps autocomplete for the known values\n// while still accepting any other engine-driver string.\n/** A driver name: one of `DataSourceDrivers`, or any other string for an unlisted engine. */\nexport type TDataSourceDriver = TConstValue<typeof DataSourceDrivers> | (string & {});\n\n/**\n * A driver CLASS, named by `@datasource({ driver })`. The class reference is what pulls the peer\n * package into a bundle - a name string pulls nothing, and a bare side-effect import may be\n * dropped. Untyped because `IRelationalDriver` lives under `connectors/`, off-limits to `base/`.\n */\nexport type TDataSourceDriverClass = TClass<unknown>;\n\n/** Loose schema record of a datasource; the default `Schema` type argument of `IDataSource`. */\nexport type TAnyDataSourceSchema = Record<string, any>;\n\n/** Engine-neutral datasource contract - the root every connector family implements. */\nexport interface IDataSource<\n Settings extends object = {},\n Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema,\n ConfigurableOptions extends object = {},\n> extends IConfigurable<ConfigurableOptions> {\n name: string;\n settings: Settings;\n schema: Schema;\n\n getSettings(): Settings;\n getSchema(): Schema;\n\n /** Releases what `configure()` opened. `stop()` calls it on every datasource the boot configured. */\n close?(): Promise<void>;\n\n /** The datasource's own `configure()` receives the handles of {@link IDataSourceOpening} as its second argument. */\n configure(opts?: ConfigurableOptions, opening?: IDataSourceOpening): ValueOrPromise<void>;\n\n /** True when the datasource opens on first use (`@datasource({ open: { on: 'first-use' } })`): the boot then calls {@link deferOpen} instead of `configure()`. */\n isOpenDeferred?(): boolean;\n\n /** Records the options `configure()` will get when the datasource opens on first use; nothing is opened. */\n deferOpen?(opts: { options?: ConfigurableOptions }): void;\n\n /** Resolves once the datasource is open: at once when it opens with the application or is already open, else after the one open that the first use starts. */\n ensureOpen?(): Promise<void>;\n}\n\n/**\n * Neutral transaction options - isolation levels are engine vocabulary, so `isolationLevel` stays\n * a loose string here and connectors narrow it in their own `ITransactionOptions` extension.\n */\nexport interface ITransactionOptions {\n isolationLevel?: string;\n}\n\n/** Neutral transaction handle - the minimum shape every connector's transaction satisfies. */\nexport interface ITransaction {\n isActive: boolean;\n commit(): Promise<void>;\n rollback(): Promise<void>;\n}\n\n/** What a datasource supports. `transactions` tells whether it can open transactions. */\nexport interface IDataSourceCapabilities {\n transactions: boolean;\n}\n\n/** Capabilities of a search datasource. Each `search` flag tells whether the engine supports that feature. */\nexport interface ISearchableDataSourceCapabilities extends IDataSourceCapabilities {\n search?: {\n /** Vector / semantic / hybrid search (search engines). */\n vector?: boolean;\n\n /** Batched multi-query search across collections. */\n multi?: boolean;\n\n /** Merged (union) result set across a multi-search. */\n union?: boolean;\n\n /** Synonym sets (multi-way / one-way). */\n synonyms?: boolean;\n };\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import type { TConstValue } from '@venizia/ignis-helpers/common';
2
+ import { ConstClass } from '@venizia/ignis-helpers/common';
2
3
  /** Defaults and ceilings of event dispatch retry: the `*_CEILING` and `*_WINDOW_MS` values cap what `register` may ask for. */
3
4
  export declare class EventDispatchRetry {
4
5
  /** Attempts per dispatch when `register` gives no `retry.maxAttempts`. */
@@ -28,13 +29,11 @@ export declare class EventDispatchRetry {
28
29
  * error there rather than a runtime surprise later, inside a `queueMicrotask` where nobody is
29
30
  * watching.
30
31
  */
31
- export declare class EventHandlerTypes {
32
+ export declare class EventHandlerTypes extends ConstClass {
32
33
  /** `handler.key` is resolved from the container on every retry attempt - a rebind reaches an attempt already in flight. */
33
34
  static readonly BINDING_KEY = "binding-key";
34
35
  /** `handler.fn` is invoked directly as a captured closure - there is nothing to rebind, so every attempt in a retry window calls the exact function registered here. */
35
36
  static readonly FUNCTION = "function";
36
- static readonly SCHEME_SET: Set<string>;
37
- static isValid(value: string): value is TEventHandlerType;
38
37
  }
39
38
  /** Union of the `EventHandlerTypes` values. */
40
39
  export type TEventHandlerType = TConstValue<typeof EventHandlerTypes>;
@@ -1,3 +1,4 @@
1
+ import { ConstClass } from '@venizia/ignis-helpers/common';
1
2
  /** Defaults and ceilings of event dispatch retry: the `*_CEILING` and `*_WINDOW_MS` values cap what `register` may ask for. */
2
3
  export class EventDispatchRetry {
3
4
  /** Attempts per dispatch when `register` gives no `retry.maxAttempts`. */
@@ -27,14 +28,10 @@ export class EventDispatchRetry {
27
28
  * error there rather than a runtime surprise later, inside a `queueMicrotask` where nobody is
28
29
  * watching.
29
30
  */
30
- export class EventHandlerTypes {
31
+ export class EventHandlerTypes extends ConstClass {
31
32
  /** `handler.key` is resolved from the container on every retry attempt - a rebind reaches an attempt already in flight. */
32
33
  static { this.BINDING_KEY = 'binding-key'; }
33
34
  /** `handler.fn` is invoked directly as a captured closure - there is nothing to rebind, so every attempt in a retry window calls the exact function registered here. */
34
35
  static { this.FUNCTION = 'function'; }
35
- static { this.SCHEME_SET = new Set([this.BINDING_KEY, this.FUNCTION]); }
36
- static isValid(value) {
37
- return this.SCHEME_SET.has(value);
38
- }
39
36
  }
40
37
  //# sourceMappingURL=constants.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/base/events/common/constants.ts"],"names":[],"mappings":"AAEA,+HAA+H;AAC/H,MAAM,OAAO,kBAAkB;IAC7B,0EAA0E;aAC1D,iBAAY,GAAG,CAAC,CAAC;IAEjC,8EAA8E;aAC9D,kBAAa,GAAG,GAAG,CAAC;IAEpC;;;;;OAKG;aACa,yBAAoB,GAAG,EAAE,CAAC;IAE1C;;;;;;OAMG;aACa,wBAAmB,GAAG,MAAM,CAAC;;AAG/C;;;;;;GAMG;AACH,MAAM,OAAO,iBAAiB;IAC5B,2HAA2H;aAC3G,gBAAW,GAAG,aAAa,CAAC;IAE5C,wKAAwK;aACxJ,aAAQ,GAAG,UAAU,CAAC;aAEtB,eAAU,GAAG,IAAI,GAAG,CAAS,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;IAEhF,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\n\n/** Defaults and ceilings of event dispatch retry: the `*_CEILING` and `*_WINDOW_MS` values cap what `register` may ask for. */\nexport class EventDispatchRetry {\n /** Attempts per dispatch when `register` gives no `retry.maxAttempts`. */\n static readonly MAX_ATTEMPTS = 3;\n\n /** First backoff delay in ms when `register` gives no `retry.baseDelayMs`. */\n static readonly BASE_DELAY_MS = 100;\n\n /**\n * Ceiling on `register`'s `retry.maxAttempts`. Dispatch is fire-and-forget - nobody awaits it - so\n * an attempt count high enough to matter is already high enough to hammer a struggling downstream\n * resource attempt after attempt. Twice the highest count any known consumer has asked for (5)\n * leaves room to tune without permitting an attempt storm.\n */\n static readonly MAX_ATTEMPTS_CEILING = 10;\n\n /**\n * Ceiling, in ms, on the total backoff window `register`'s `retry` can produce (the sum of every\n * inter-attempt delay, computed without jitter since jitter only shrinks it). Matches\n * `RetryUtility`'s own default cap on a SINGLE delay: a dispatch holds a handler's resources - e.g.\n * a database connection - for its entire retry window, so the sum across every attempt gets the\n * same \"unreasonable beyond this\" line the framework already draws for one attempt.\n */\n static readonly MAX_TOTAL_WINDOW_MS = 30_000;\n}\n\n/**\n * Tag for `EventBus.register`'s `handler` union (`TEventHandlerReference`). The tag makes the\n * caller's choice explicit at the call site instead of implicit in whichever field is present, so a\n * mismatched `type`/field pair (`BINDING_KEY` with `fn`, or `FUNCTION` with `key`) is a compile\n * error there rather than a runtime surprise later, inside a `queueMicrotask` where nobody is\n * watching.\n */\nexport class EventHandlerTypes {\n /** `handler.key` is resolved from the container on every retry attempt - a rebind reaches an attempt already in flight. */\n static readonly BINDING_KEY = 'binding-key';\n\n /** `handler.fn` is invoked directly as a captured closure - there is nothing to rebind, so every attempt in a retry window calls the exact function registered here. */\n static readonly FUNCTION = 'function';\n\n static readonly SCHEME_SET = new Set<string>([this.BINDING_KEY, this.FUNCTION]);\n\n static isValid(value: string): value is TEventHandlerType {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Union of the `EventHandlerTypes` values. */\nexport type TEventHandlerType = TConstValue<typeof EventHandlerTypes>;\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/base/events/common/constants.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAE3D,+HAA+H;AAC/H,MAAM,OAAO,kBAAkB;IAC7B,0EAA0E;aAC1D,iBAAY,GAAG,CAAC,CAAC;IAEjC,8EAA8E;aAC9D,kBAAa,GAAG,GAAG,CAAC;IAEpC;;;;;OAKG;aACa,yBAAoB,GAAG,EAAE,CAAC;IAE1C;;;;;;OAMG;aACa,wBAAmB,GAAG,MAAM,CAAC;;AAG/C;;;;;;GAMG;AACH,MAAM,OAAO,iBAAkB,SAAQ,UAAU;IAC/C,2HAA2H;aAC3G,gBAAW,GAAG,aAAa,CAAC;IAE5C,wKAAwK;aACxJ,aAAQ,GAAG,UAAU,CAAC","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\nimport { ConstClass } from '@venizia/ignis-helpers/common';\n\n/** Defaults and ceilings of event dispatch retry: the `*_CEILING` and `*_WINDOW_MS` values cap what `register` may ask for. */\nexport class EventDispatchRetry {\n /** Attempts per dispatch when `register` gives no `retry.maxAttempts`. */\n static readonly MAX_ATTEMPTS = 3;\n\n /** First backoff delay in ms when `register` gives no `retry.baseDelayMs`. */\n static readonly BASE_DELAY_MS = 100;\n\n /**\n * Ceiling on `register`'s `retry.maxAttempts`. Dispatch is fire-and-forget - nobody awaits it - so\n * an attempt count high enough to matter is already high enough to hammer a struggling downstream\n * resource attempt after attempt. Twice the highest count any known consumer has asked for (5)\n * leaves room to tune without permitting an attempt storm.\n */\n static readonly MAX_ATTEMPTS_CEILING = 10;\n\n /**\n * Ceiling, in ms, on the total backoff window `register`'s `retry` can produce (the sum of every\n * inter-attempt delay, computed without jitter since jitter only shrinks it). Matches\n * `RetryUtility`'s own default cap on a SINGLE delay: a dispatch holds a handler's resources - e.g.\n * a database connection - for its entire retry window, so the sum across every attempt gets the\n * same \"unreasonable beyond this\" line the framework already draws for one attempt.\n */\n static readonly MAX_TOTAL_WINDOW_MS = 30_000;\n}\n\n/**\n * Tag for `EventBus.register`'s `handler` union (`TEventHandlerReference`). The tag makes the\n * caller's choice explicit at the call site instead of implicit in whichever field is present, so a\n * mismatched `type`/field pair (`BINDING_KEY` with `fn`, or `FUNCTION` with `key`) is a compile\n * error there rather than a runtime surprise later, inside a `queueMicrotask` where nobody is\n * watching.\n */\nexport class EventHandlerTypes extends ConstClass {\n /** `handler.key` is resolved from the container on every retry attempt - a rebind reaches an attempt already in flight. */\n static readonly BINDING_KEY = 'binding-key';\n\n /** `handler.fn` is invoked directly as a captured closure - there is nothing to rebind, so every attempt in a retry window calls the exact function registered here. */\n static readonly FUNCTION = 'function';\n}\n\n/** Union of the `EventHandlerTypes` values. */\nexport type TEventHandlerType = TConstValue<typeof EventHandlerTypes>;\n"]}
@@ -99,7 +99,7 @@ export class EventBus extends BaseHelper {
99
99
  }
100
100
  default: {
101
101
  throw getError({
102
- message: `[EventBus][register] Unknown handler.type | name: ${name} | Expected one of: ${[...EventHandlerTypes.SCHEME_SET].join(', ')} | Got: ${handler.type}`,
102
+ message: `[EventBus][register] Unknown handler.type | name: ${name} | Expected one of: ${EventHandlerTypes.values().join(', ')} | Got: ${handler.type}`,
103
103
  });
104
104
  }
105
105
  }
@@ -1 +1 @@
1
- {"version":3,"file":"event-bus.js","sourceRoot":"","sources":["../../../../src/base/events/event-bus.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAG9D,OAAO,EACL,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AE,CAAC,CAAC;gBACjC,CAAC;aACF,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,4FAA4F;YAC5F,6EAA6E;YAC7E,IAAI,CAAC,MAAM,CAAC,KAAK,CACf,wGAAwG,EACxG,KAAK,CAAC,IAAI,EACV,KAAK,CAAC,OAAO,EACb,WAAW,EACX,WAAW,EACX,KAAK,CACN,CAAC;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["import { ObjectUtility } from '@venizia/ignis-helpers/common';\nimport type { Container } from '@/helpers/inversion/container';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport {\n BaseHelper,\n getError,\n RetryBackoffStrategies,\n RetryUtility,\n RetryJitterModes,\n} from '@venizia/ignis-helpers/core';\nimport { EventDispatchRetry, EventHandlerTypes } from './common/constants';\nimport type {\n IDomainEvent,\n IEventHandlerRetryOptions,\n TEventHandlerReference,\n} from './common/types';\n\n/** One `register`ed handler, resolved to concrete retry numbers and a ready-to-call invoker -\n * `EventDispatchRetry`'s defaults already applied and `handler`'s shape already resolved, so\n * `dispatch` never has to branch on either. */\ninterface IResolvedEventRegistration {\n // A method signature on purpose: its parameter is bivariant, so a registration holds the invoker of any payload type, which the registry cannot tell apart.\n invokeHandler(opts: { event: IDomainEvent<unknown> }): ValueOrPromise<void>;\n /** For the exhaustion log line only - a binding key or `<function fn.name>`. */\n description: string;\n maxAttempts: number;\n baseDelayMs: number;\n}\n\n/** In-process, fire-and-forget domain event bus. `TPayloadMap` keys the event names, so a wrong name\n * or payload shape is a compile error. Delivery is always async. Retry timing is a property of the\n * handler's own failure mode, not of the event, so `register` may tune it per registration. But\n * nobody awaits a fire-and-forget dispatch, so an unbounded window would let one event hold a\n * handler - and whatever it holds open, e.g. a database connection - for an unbounded time with no\n * one to report it. What the bus guarantees instead: a bounded MAXIMUM time a single dispatch can\n * occupy, enforced as a hard ceiling at `register()` - see `EventDispatchRetry`. Retry makes\n * delivery at-least-once: handlers must be idempotent, see `IEventHandler`. */\nexport class EventBus<TPayloadMap extends object> extends BaseHelper {\n private readonly container: Container;\n\n /** `register` appends, never replaces - two handlers may share an event name, and replacing would\n * drop the first with no way for the caller to notice. */\n private readonly registrationsByName: Map<string, IResolvedEventRegistration[]>;\n\n constructor(opts: { scope?: string; container: Container }) {\n super({ scope: opts.scope ?? EventBus.name });\n this.container = opts.container;\n this.registrationsByName = new Map();\n }\n\n /** The pre-jitter total of every inter-attempt delay `maxAttempts`/`baseDelayMs` would produce -\n * jitter (always on, see `dispatch`) only ever shrinks a delay, so this is a true upper bound. */\n private static computeTotalWindowMs(opts: { maxAttempts: number; baseDelayMs: number }): number {\n const { maxAttempts, baseDelayMs } = opts;\n let totalWindowMs = 0;\n\n for (let attempt = 1; attempt < maxAttempts; attempt++) {\n totalWindowMs += RetryUtility.computeBackoffDelayMs({\n attempt,\n backoff: {\n strategy: RetryBackoffStrategies.EXPONENTIAL,\n initialDelayMs: baseDelayMs,\n jitter: RetryJitterModes.NONE,\n },\n });\n }\n\n return totalWindowMs;\n }\n\n /** Loud rejection, never a silent clamp: a caller who believes a number the bus does not honour is\n * worse off than one who sees the ceiling at boot. */\n private static assertValidRetry(opts: {\n name: string;\n maxAttempts: number;\n baseDelayMs: number;\n }): void {\n const { name, maxAttempts, baseDelayMs } = opts;\n\n if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n throw getError({\n message: `[EventBus][register] retry.maxAttempts must be a positive integer | name: ${name} | Got: ${maxAttempts}`,\n });\n }\n\n if (!Number.isInteger(baseDelayMs) || baseDelayMs < 1) {\n throw getError({\n message: `[EventBus][register] retry.baseDelayMs must be a positive integer | name: ${name} | Got: ${baseDelayMs}`,\n });\n }\n\n if (maxAttempts > EventDispatchRetry.MAX_ATTEMPTS_CEILING) {\n throw getError({\n message: `[EventBus][register] retry.maxAttempts exceeds the ceiling | name: ${name} | Got: ${maxAttempts} | Ceiling: ${EventDispatchRetry.MAX_ATTEMPTS_CEILING} | Lower retry.maxAttempts`,\n });\n }\n\n const totalWindowMs = EventBus.computeTotalWindowMs({ maxAttempts, baseDelayMs });\n\n if (totalWindowMs > EventDispatchRetry.MAX_TOTAL_WINDOW_MS) {\n throw getError({\n message: `[EventBus][register] retry window exceeds the ceiling | name: ${name} | Got: ${totalWindowMs}ms | Ceiling: ${EventDispatchRetry.MAX_TOTAL_WINDOW_MS}ms | Lower retry.maxAttempts or retry.baseDelayMs`,\n });\n }\n }\n\n /**\n * Turns `handler` into a uniform invoker plus a description for the exhaustion log line.\n * `BINDING_KEY` resolves through the container INSIDE the returned closure, so every call re-reads\n * the current binding; `FUNCTION` calls `fn` directly, so the closure IS the resolution - there is\n * nothing left to re-read on a later attempt. The tag (`handler.type`) is what this switches on,\n * not which field happens to be present - see `EventHandlerTypes`' doc.\n */\n private static buildHandlerInvoker<TPayload>(opts: {\n container: Container;\n handler: TEventHandlerReference<TPayload>;\n name: string;\n }): {\n invokeHandler: (opts: { event: IDomainEvent<TPayload> }) => ValueOrPromise<void>;\n description: string;\n } {\n const { container, handler, name } = opts;\n\n if (ObjectUtility.isEmpty({ value: handler })) {\n throw getError({\n message: `[EventBus][register] Invalid handler | name: ${name} | Got: ${handler}`,\n });\n }\n\n switch (handler.type) {\n case EventHandlerTypes.BINDING_KEY: {\n const { key } = handler;\n\n if (ObjectUtility.isEmpty({ value: key })) {\n throw getError({\n message: `[EventBus][register] Invalid handler.key | name: ${name} | Got: ${key}`,\n });\n }\n\n return {\n invokeHandler: ({ event }) => container.get({ key }).handle({ event }),\n description: `binding-key:${key}`,\n };\n }\n\n case EventHandlerTypes.FUNCTION: {\n const { fn } = handler;\n\n if (typeof fn !== 'function') {\n throw getError({\n message: `[EventBus][register] Invalid handler.fn | name: ${name} | Expected a function | Got: ${typeof fn}`,\n });\n }\n\n return {\n invokeHandler: ({ event }) => fn({ event }),\n description: `function:${fn.name || 'anonymous'}`,\n };\n }\n\n default: {\n throw getError({\n message: `[EventBus][register] Unknown handler.type | name: ${name} | Expected one of: ${[...EventHandlerTypes.SCHEME_SET].join(', ')} | Got: ${(handler as { type?: unknown }).type}`,\n });\n }\n }\n }\n\n /**\n * `retry` is optional and per REGISTRATION, not per publish: the right window belongs to the\n * handler's own failure mode, and two handlers on the same event name may each pick their own.\n * Omitting it reproduces today's `EventDispatchRetry` defaults exactly. Both `maxAttempts` and the\n * total backoff window it implies are bounded - see `EventDispatchRetry` - and exceeding either\n * throws here, at boot where a human sees it, rather than being silently clamped at dispatch time.\n */\n register<K extends keyof TPayloadMap & string>(opts: {\n name: K;\n /** A `BINDING_KEY` reference re-resolves through the container on every retry attempt, so a\n * rebind reaches a dispatch already in flight. A `FUNCTION` reference is captured as-is: a\n * rebind has nothing to reach, and every attempt in a long retry window calls the exact `fn`\n * registered here. */\n handler: TEventHandlerReference<TPayloadMap[K]>;\n retry?: IEventHandlerRetryOptions;\n }): void {\n const { name, handler, retry } = opts;\n\n if (ObjectUtility.isEmpty({ value: name })) {\n throw getError({\n message: `[EventBus][register] Invalid registration | name: ${String(name)}`,\n });\n }\n\n const maxAttempts = retry?.maxAttempts ?? EventDispatchRetry.MAX_ATTEMPTS;\n const baseDelayMs = retry?.baseDelayMs ?? EventDispatchRetry.BASE_DELAY_MS;\n EventBus.assertValidRetry({ name, maxAttempts, baseDelayMs });\n\n const { invokeHandler, description } = EventBus.buildHandlerInvoker({\n container: this.container,\n handler,\n name,\n });\n\n const registration: IResolvedEventRegistration = {\n invokeHandler,\n description,\n maxAttempts,\n baseDelayMs,\n };\n\n const existing = this.registrationsByName.get(name);\n\n if (existing) {\n existing.push(registration);\n\n return;\n }\n\n this.registrationsByName.set(name, [registration]);\n }\n\n /**\n * Never blocks and never throws back to the caller: dispatch runs outside this call's flow via\n * `queueMicrotask`, and a handler failure is caught and logged where it happens (`dispatch`),\n * never here.\n */\n publish<K extends keyof TPayloadMap & string>(opts: {\n name: K;\n payload: TPayloadMap[K];\n traceId?: string;\n }): void {\n const { name, payload, traceId } = opts;\n\n const event: IDomainEvent<TPayloadMap[K]> = {\n name,\n payload,\n occurredAt: new Date().toISOString(),\n traceId,\n };\n\n const registrations = this.registrationsByName.get(name);\n\n if (!registrations?.length) {\n // A typo is already a compile error, so at runtime this only means nobody is listening yet -\n // a legitimate state on a fire-and-forget bus, not an incident.\n this.logger.debug('[publish] No handler registered | name: %s | traceId: %s', name, traceId);\n\n return;\n }\n\n for (const registration of registrations) {\n queueMicrotask(() => {\n // `dispatch` catches every failure path itself and never rejects - this `.catch` is an\n // unreachable backstop, kept (and logged) rather than left floating, for the day it isn't.\n this.dispatch({ event, registration }).catch((error: unknown) => {\n this.logger.error(\n '[publish] Unexpected dispatch failure | name: %s | Error: %s',\n event.name,\n error,\n );\n });\n });\n }\n }\n\n /**\n * Attempts/backoff come from the registration (`EventDispatchRetry`'s defaults when omitted),\n * always with full jitter - `RetryJitterModes.FULL` decorrelates a shared-resource pile-up hardest,\n * so many handlers retrying the same lock do not collide on the same instant a second and third\n * time. `invokeHandler` already encodes whether that re-resolves (`BINDING_KEY`) or was captured\n * once (`FUNCTION`) - see `buildHandlerInvoker` - so this method calls it uniformly. A handler that\n * throws synchronously is caught exactly like one that returns a rejected promise: `execution`\n * here is itself `async`, and JS converts a synchronous throw inside an async function body into a\n * rejection of that function's own promise - `RetryUtility.executeWithRetry`'s attempt loop never\n * sees the difference.\n *\n * `RetryUtility.executeWithRetry` is used without its own `logger` - its internal per-attempt/exhaustion\n * logging knows nothing about the event name or `traceId`, so it cannot be the trace anyone\n * relies on. The one line below, logged only on final failure, is.\n */\n private async dispatch(opts: {\n event: IDomainEvent<unknown>;\n registration: IResolvedEventRegistration;\n }): Promise<void> {\n const { event, registration } = opts;\n const { invokeHandler, description, maxAttempts, baseDelayMs } = registration;\n let lastAttempt = 0;\n\n try {\n await RetryUtility.executeWithRetry({\n operation: `EventBus.dispatch:${event.name}`,\n maxAttempts,\n backoff: {\n strategy: RetryBackoffStrategies.EXPONENTIAL,\n initialDelayMs: baseDelayMs,\n jitter: RetryJitterModes.FULL,\n },\n execution: async ({ attempt }) => {\n lastAttempt = attempt;\n await invokeHandler({ event });\n },\n });\n } catch (error) {\n // The only trace this failure leaves: it is caught here and never reaches the publisher, so\n // the event name, traceId and attempt count all have to be on this one line.\n this.logger.error(\n '[dispatch] Handler exhausted retries | name: %s | traceId: %s | attempts: %d | handler: %s | Error: %s',\n event.name,\n event.traceId,\n lastAttempt,\n description,\n error,\n );\n }\n }\n}\n"]}
1
+ {"version":3,"file":"event-bus.js","sourceRoot":"","sources":["../../../../src/base/events/event-bus.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAG9D,OAAO,EACL,UAAU,EACV,QAAQ,EACR,sBAAsB,EACtB,YAAY,EACZ,gBAAgB,GACjB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAmB3E;;;;;;;+EAO+E;AAC/E,MAAM,OAAO,QAAqC,SAAQ,UAAU;IAOlE,YAAY,IAA8C;QACxD,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;QAC9C,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;QAChC,IAAI,CAAC,mBAAmB,GAAG,IAAI,GAAG,EAAE,CAAC;IACvC,CAAC;IAED;sGACkG;IAC1F,MAAM,CAAC,oBAAoB,CAAC,IAAkD;QACpF,MAAM,EAAE,WAAW,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;QAC1C,IAAI,aAAa,GAAG,CAAC,CAAC;QAEtB,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,GAAG,WAAW,EAAE,OAAO,EAAE,EAAE,CAAC;YACvD,aAAa,IAAI,YAAY,CAAC,qBAAqB,CAAC;gBAClD,OAAO;gBACP,OAAO,EAAE;oBACP,QAAQ,EAAE,sBAAsB,CAAC,WAAW;oB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G,CAAC,CAAC;QAEpB,IAAI,CAAC;YACH,MAAM,YAAY,CAAC,gBAAgB,CAAC;gBAClC,SAAS,EAAE,qBAAqB,KAAK,CAAC,IAAI,EAAE;gBAC5C,WAAW;gBACX,OAAO,EAAE;oBACP,QAAQ,EAAE,sBAAsB,CAAC,WAAW;oBAC5C,cAAc,EAAE,WAAW;oBAC3B,MAAM,EAAE,gBAAgB,CAAC,IAAI;iBAC9B;gBACD,SAAS,EAAE,KAAK,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE;oBAC/B,WAAW,GAAG,OAAO,CAAC;oBACtB,MAAM,aAAa,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;gBACjC,CAAC;aACF,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,4FAA4F;YAC5F,6EAA6E;YAC7E,IAAI,CAAC,MAAM,CAAC,KAAK,CACf,wGAAwG,EACxG,KAAK,CAAC,IAAI,EACV,KAAK,CAAC,OAAO,EACb,WAAW,EACX,WAAW,EACX,KAAK,CACN,CAAC;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["import { ObjectUtility } from '@venizia/ignis-helpers/common';\nimport type { Container } from '@/helpers/inversion/container';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport {\n BaseHelper,\n getError,\n RetryBackoffStrategies,\n RetryUtility,\n RetryJitterModes,\n} from '@venizia/ignis-helpers/core';\nimport { EventDispatchRetry, EventHandlerTypes } from './common/constants';\nimport type {\n IDomainEvent,\n IEventHandlerRetryOptions,\n TEventHandlerReference,\n} from './common/types';\n\n/** One `register`ed handler, resolved to concrete retry numbers and a ready-to-call invoker -\n * `EventDispatchRetry`'s defaults already applied and `handler`'s shape already resolved, so\n * `dispatch` never has to branch on either. */\ninterface IResolvedEventRegistration {\n // A method signature on purpose: its parameter is bivariant, so a registration holds the invoker of any payload type, which the registry cannot tell apart.\n invokeHandler(opts: { event: IDomainEvent<unknown> }): ValueOrPromise<void>;\n /** For the exhaustion log line only - a binding key or `<function fn.name>`. */\n description: string;\n maxAttempts: number;\n baseDelayMs: number;\n}\n\n/** In-process, fire-and-forget domain event bus. `TPayloadMap` keys the event names, so a wrong name\n * or payload shape is a compile error. Delivery is always async. Retry timing is a property of the\n * handler's own failure mode, not of the event, so `register` may tune it per registration. But\n * nobody awaits a fire-and-forget dispatch, so an unbounded window would let one event hold a\n * handler - and whatever it holds open, e.g. a database connection - for an unbounded time with no\n * one to report it. What the bus guarantees instead: a bounded MAXIMUM time a single dispatch can\n * occupy, enforced as a hard ceiling at `register()` - see `EventDispatchRetry`. Retry makes\n * delivery at-least-once: handlers must be idempotent, see `IEventHandler`. */\nexport class EventBus<TPayloadMap extends object> extends BaseHelper {\n private readonly container: Container;\n\n /** `register` appends, never replaces - two handlers may share an event name, and replacing would\n * drop the first with no way for the caller to notice. */\n private readonly registrationsByName: Map<string, IResolvedEventRegistration[]>;\n\n constructor(opts: { scope?: string; container: Container }) {\n super({ scope: opts.scope ?? EventBus.name });\n this.container = opts.container;\n this.registrationsByName = new Map();\n }\n\n /** The pre-jitter total of every inter-attempt delay `maxAttempts`/`baseDelayMs` would produce -\n * jitter (always on, see `dispatch`) only ever shrinks a delay, so this is a true upper bound. */\n private static computeTotalWindowMs(opts: { maxAttempts: number; baseDelayMs: number }): number {\n const { maxAttempts, baseDelayMs } = opts;\n let totalWindowMs = 0;\n\n for (let attempt = 1; attempt < maxAttempts; attempt++) {\n totalWindowMs += RetryUtility.computeBackoffDelayMs({\n attempt,\n backoff: {\n strategy: RetryBackoffStrategies.EXPONENTIAL,\n initialDelayMs: baseDelayMs,\n jitter: RetryJitterModes.NONE,\n },\n });\n }\n\n return totalWindowMs;\n }\n\n /** Loud rejection, never a silent clamp: a caller who believes a number the bus does not honour is\n * worse off than one who sees the ceiling at boot. */\n private static assertValidRetry(opts: {\n name: string;\n maxAttempts: number;\n baseDelayMs: number;\n }): void {\n const { name, maxAttempts, baseDelayMs } = opts;\n\n if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n throw getError({\n message: `[EventBus][register] retry.maxAttempts must be a positive integer | name: ${name} | Got: ${maxAttempts}`,\n });\n }\n\n if (!Number.isInteger(baseDelayMs) || baseDelayMs < 1) {\n throw getError({\n message: `[EventBus][register] retry.baseDelayMs must be a positive integer | name: ${name} | Got: ${baseDelayMs}`,\n });\n }\n\n if (maxAttempts > EventDispatchRetry.MAX_ATTEMPTS_CEILING) {\n throw getError({\n message: `[EventBus][register] retry.maxAttempts exceeds the ceiling | name: ${name} | Got: ${maxAttempts} | Ceiling: ${EventDispatchRetry.MAX_ATTEMPTS_CEILING} | Lower retry.maxAttempts`,\n });\n }\n\n const totalWindowMs = EventBus.computeTotalWindowMs({ maxAttempts, baseDelayMs });\n\n if (totalWindowMs > EventDispatchRetry.MAX_TOTAL_WINDOW_MS) {\n throw getError({\n message: `[EventBus][register] retry window exceeds the ceiling | name: ${name} | Got: ${totalWindowMs}ms | Ceiling: ${EventDispatchRetry.MAX_TOTAL_WINDOW_MS}ms | Lower retry.maxAttempts or retry.baseDelayMs`,\n });\n }\n }\n\n /**\n * Turns `handler` into a uniform invoker plus a description for the exhaustion log line.\n * `BINDING_KEY` resolves through the container INSIDE the returned closure, so every call re-reads\n * the current binding; `FUNCTION` calls `fn` directly, so the closure IS the resolution - there is\n * nothing left to re-read on a later attempt. The tag (`handler.type`) is what this switches on,\n * not which field happens to be present - see `EventHandlerTypes`' doc.\n */\n private static buildHandlerInvoker<TPayload>(opts: {\n container: Container;\n handler: TEventHandlerReference<TPayload>;\n name: string;\n }): {\n invokeHandler: (opts: { event: IDomainEvent<TPayload> }) => ValueOrPromise<void>;\n description: string;\n } {\n const { container, handler, name } = opts;\n\n if (ObjectUtility.isEmpty({ value: handler })) {\n throw getError({\n message: `[EventBus][register] Invalid handler | name: ${name} | Got: ${handler}`,\n });\n }\n\n switch (handler.type) {\n case EventHandlerTypes.BINDING_KEY: {\n const { key } = handler;\n\n if (ObjectUtility.isEmpty({ value: key })) {\n throw getError({\n message: `[EventBus][register] Invalid handler.key | name: ${name} | Got: ${key}`,\n });\n }\n\n return {\n invokeHandler: ({ event }) => container.get({ key }).handle({ event }),\n description: `binding-key:${key}`,\n };\n }\n\n case EventHandlerTypes.FUNCTION: {\n const { fn } = handler;\n\n if (typeof fn !== 'function') {\n throw getError({\n message: `[EventBus][register] Invalid handler.fn | name: ${name} | Expected a function | Got: ${typeof fn}`,\n });\n }\n\n return {\n invokeHandler: ({ event }) => fn({ event }),\n description: `function:${fn.name || 'anonymous'}`,\n };\n }\n\n default: {\n throw getError({\n message: `[EventBus][register] Unknown handler.type | name: ${name} | Expected one of: ${EventHandlerTypes.values().join(', ')} | Got: ${(handler as { type?: unknown }).type}`,\n });\n }\n }\n }\n\n /**\n * `retry` is optional and per REGISTRATION, not per publish: the right window belongs to the\n * handler's own failure mode, and two handlers on the same event name may each pick their own.\n * Omitting it reproduces today's `EventDispatchRetry` defaults exactly. Both `maxAttempts` and the\n * total backoff window it implies are bounded - see `EventDispatchRetry` - and exceeding either\n * throws here, at boot where a human sees it, rather than being silently clamped at dispatch time.\n */\n register<K extends keyof TPayloadMap & string>(opts: {\n name: K;\n /** A `BINDING_KEY` reference re-resolves through the container on every retry attempt, so a\n * rebind reaches a dispatch already in flight. A `FUNCTION` reference is captured as-is: a\n * rebind has nothing to reach, and every attempt in a long retry window calls the exact `fn`\n * registered here. */\n handler: TEventHandlerReference<TPayloadMap[K]>;\n retry?: IEventHandlerRetryOptions;\n }): void {\n const { name, handler, retry } = opts;\n\n if (ObjectUtility.isEmpty({ value: name })) {\n throw getError({\n message: `[EventBus][register] Invalid registration | name: ${String(name)}`,\n });\n }\n\n const maxAttempts = retry?.maxAttempts ?? EventDispatchRetry.MAX_ATTEMPTS;\n const baseDelayMs = retry?.baseDelayMs ?? EventDispatchRetry.BASE_DELAY_MS;\n EventBus.assertValidRetry({ name, maxAttempts, baseDelayMs });\n\n const { invokeHandler, description } = EventBus.buildHandlerInvoker({\n container: this.container,\n handler,\n name,\n });\n\n const registration: IResolvedEventRegistration = {\n invokeHandler,\n description,\n maxAttempts,\n baseDelayMs,\n };\n\n const existing = this.registrationsByName.get(name);\n\n if (existing) {\n existing.push(registration);\n\n return;\n }\n\n this.registrationsByName.set(name, [registration]);\n }\n\n /**\n * Never blocks and never throws back to the caller: dispatch runs outside this call's flow via\n * `queueMicrotask`, and a handler failure is caught and logged where it happens (`dispatch`),\n * never here.\n */\n publish<K extends keyof TPayloadMap & string>(opts: {\n name: K;\n payload: TPayloadMap[K];\n traceId?: string;\n }): void {\n const { name, payload, traceId } = opts;\n\n const event: IDomainEvent<TPayloadMap[K]> = {\n name,\n payload,\n occurredAt: new Date().toISOString(),\n traceId,\n };\n\n const registrations = this.registrationsByName.get(name);\n\n if (!registrations?.length) {\n // A typo is already a compile error, so at runtime this only means nobody is listening yet -\n // a legitimate state on a fire-and-forget bus, not an incident.\n this.logger.debug('[publish] No handler registered | name: %s | traceId: %s', name, traceId);\n\n return;\n }\n\n for (const registration of registrations) {\n queueMicrotask(() => {\n // `dispatch` catches every failure path itself and never rejects - this `.catch` is an\n // unreachable backstop, kept (and logged) rather than left floating, for the day it isn't.\n this.dispatch({ event, registration }).catch((error: unknown) => {\n this.logger.error(\n '[publish] Unexpected dispatch failure | name: %s | Error: %s',\n event.name,\n error,\n );\n });\n });\n }\n }\n\n /**\n * Attempts/backoff come from the registration (`EventDispatchRetry`'s defaults when omitted),\n * always with full jitter - `RetryJitterModes.FULL` decorrelates a shared-resource pile-up hardest,\n * so many handlers retrying the same lock do not collide on the same instant a second and third\n * time. `invokeHandler` already encodes whether that re-resolves (`BINDING_KEY`) or was captured\n * once (`FUNCTION`) - see `buildHandlerInvoker` - so this method calls it uniformly. A handler that\n * throws synchronously is caught exactly like one that returns a rejected promise: `execution`\n * here is itself `async`, and JS converts a synchronous throw inside an async function body into a\n * rejection of that function's own promise - `RetryUtility.executeWithRetry`'s attempt loop never\n * sees the difference.\n *\n * `RetryUtility.executeWithRetry` is used without its own `logger` - its internal per-attempt/exhaustion\n * logging knows nothing about the event name or `traceId`, so it cannot be the trace anyone\n * relies on. The one line below, logged only on final failure, is.\n */\n private async dispatch(opts: {\n event: IDomainEvent<unknown>;\n registration: IResolvedEventRegistration;\n }): Promise<void> {\n const { event, registration } = opts;\n const { invokeHandler, description, maxAttempts, baseDelayMs } = registration;\n let lastAttempt = 0;\n\n try {\n await RetryUtility.executeWithRetry({\n operation: `EventBus.dispatch:${event.name}`,\n maxAttempts,\n backoff: {\n strategy: RetryBackoffStrategies.EXPONENTIAL,\n initialDelayMs: baseDelayMs,\n jitter: RetryJitterModes.FULL,\n },\n execution: async ({ attempt }) => {\n lastAttempt = attempt;\n await invokeHandler({ event });\n },\n });\n } catch (error) {\n // The only trace this failure leaves: it is caught here and never reaches the publisher, so\n // the event name, traceId and attempt count all have to be on this one line.\n this.logger.error(\n '[dispatch] Handler exhausted retries | name: %s | traceId: %s | attempts: %d | handler: %s | Error: %s',\n event.name,\n event.traceId,\n lastAttempt,\n description,\n error,\n );\n }\n }\n}\n"]}
@@ -7,7 +7,7 @@ export const injectable = (opts) => {
7
7
  return (target) => {
8
8
  if (!ArtifactTypes.isValid(opts.type)) {
9
9
  throw getError({
10
- message: `[injectable][${target.name}] Invalid artifact type: '${opts.type}' | Expected one of: ${[...ArtifactTypes.SCHEME_SET].join(', ')}`,
10
+ message: `[injectable][${target.name}] Invalid artifact type: '${opts.type}' | Expected one of: ${ArtifactTypes.values().join(', ')}`,
11
11
  });
12
12
  }
13
13
  // At import time, so the failure lands where the binding is written, not at boot.
@@ -1 +1 @@
1
- {"version":3,"file":"injectable.js","sourceRoot":"","sources":["../../../../src/base/metadata/injectable.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAoB,MAAM,qBAAqB,CAAC;AACxF,OAAO,EAAE,mBAAmB,EAAE,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AC,uBAAuB,CAA4B,IAEzD;QACC,MAAM,EAAE,OAAO,EAAE,aAAa,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC5E,MAAM,YAAY,GAAkD,EAAE,CAAC;QAEvE,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;YAC1B,YAAY,CAAC,OAAO,GAAG,OAAO,CAAC;QACjC,CAAC;QAED,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;YAChC,YAAY,CAAC,aAAa,GAAG,aAAa,CAAC;QAC7C,CAAC;QAED,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,YAAY,CAAC,KAAK,GAAG,KAAK,CAAC;QAC7B,CAAC;QAED,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,YAAY,CAAC,KAAK,GAAG,KAAK,CAAC;QAC7B,CAAC;QAED,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,YAAY,CAAC,IAAI,GAAG,IAAI,CAAC;QAC3B,CAAC;QAED,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,YAAY,CAAC,KAAK,GAAG,KAAK,CAAC;QAC7B,CAAC;QAED,OAAO,YAAY,CAAC;IACtB,CAAC;CACF","sourcesContent":["import type {\n IArtifactMetadata,\n IArtifactRegistrationOptions,\n TBindingScope,\n} from '@/helpers/inversion';\nimport { ArtifactNamespaces, BindingNamespaces } from '@/common/bindings';\nimport { ArtifactTypes, MetadataRegistry, type TBindingKey } from '@/helpers/inversion';\nimport { ArtifactBindingKeys } from './artifact-keys';\nimport { getError } from '@venizia/ignis-helpers/core';\n\n/** The root stereotype: marks a class as an artifact the application registers, with its registration defaults. Every other stereotype calls it. */\nexport const injectable = <ApplicationType = unknown>(\n opts: IArtifactMetadata<ApplicationType>,\n): ClassDecorator => {\n return (target) => {\n if (!ArtifactTypes.isValid(opts.type)) {\n throw getError({\n message: `[injectable][${target.name}] Invalid artifact type: '${opts.type}' | Expected one of: ${[...ArtifactTypes.SCHEME_SET].join(', ')}`,\n });\n }\n\n // At import time, so the failure lands where the binding is written, not at boot.\n if (opts.binding) {\n BindingNamespaces.assertArtifactNamespace({\n namespace: opts.binding.namespace,\n artifact: target.name,\n caller: 'injectable',\n });\n }\n\n const registry = MetadataRegistry.getInstance();\n registry.setArtifactMetadata({ target, metadata: opts });\n\n // Discovery happens HERE, at import time. A boot-time filesystem scan cannot see a compiled\n // single-file binary, and a class exists at run time only because something imported it.\n registry.addDiscoveredArtifact({ target });\n\n // The key this class WOULD get; `registerArtifact` overwrites it with the one actually bound.\n registry.setBindingKey({\n target,\n key: ArtifactBindingKeys.resolve({\n target,\n namespace: ArtifactNamespaces.resolve({ type: opts.type }),\n binding: opts.binding,\n }).key,\n isProvisional: true,\n });\n };\n};\n\n/**\n * Class decorator that registers the class as a service artifact; accepts the same registration options as `injectable`.\n *\n * @example\n * ```typescript\n * import { BaseService, service } from '@venizia/ignis';\n *\n * export @service()\n * class MailService extends BaseService {\n * constructor() {\n * super({ scope: MailService.name });\n * }\n * }\n * ```\n */\nexport const service = <ApplicationType = unknown>(\n opts?: IArtifactRegistrationOptions<ApplicationType>,\n): ClassDecorator => {\n return injectable<ApplicationType>({ type: ArtifactTypes.SERVICE, ...opts });\n};\n\n/**\n * Class decorator that registers the class as a component artifact; accepts the same registration options as `injectable`.\n *\n * @example\n * ```typescript\n * import { BaseComponent, component } from '@venizia/ignis';\n *\n * export @component()\n * class AuditComponent extends BaseComponent {\n * constructor() {\n * super({ scope: AuditComponent.name });\n * }\n *\n * override binding(): void {}\n * }\n * ```\n */\nexport const component = <ApplicationType = unknown>(\n opts?: IArtifactRegistrationOptions<ApplicationType>,\n): ClassDecorator => {\n return injectable<ApplicationType>({ type: ArtifactTypes.COMPONENT, ...opts });\n};\n\n/**\n * Class decorator that registers the class as a configuration artifact; `after` orders it behind other configuration classes.\n *\n * @example\n * ```typescript\n * import { BaseConfiguration, configuration } from '@venizia/ignis';\n *\n * export @configuration()\n * class SeedConfiguration extends BaseConfiguration {}\n *\n * export @configuration({ after: [SeedConfiguration] })\n * class IndexConfiguration extends BaseConfiguration {}\n * ```\n */\nexport const configuration = <ApplicationType = unknown>(\n opts?: IArtifactRegistrationOptions<ApplicationType>,\n): ClassDecorator => {\n return injectable<ApplicationType>({ type: ArtifactTypes.CONFIGURATION, ...opts });\n};\n\n/** Marks a component method as the provider of `key`. `registerArtifacts` binds the key to a lazy provider that resolves the component and calls the method; SINGLETON unless `scope` says otherwise. */\nexport const provide = (opts: { key: TBindingKey; scope?: TBindingScope }): MethodDecorator => {\n return (target, propertyKey) => {\n MetadataRegistry.getInstance().addProvideMetadata({\n target: target.constructor,\n metadata: {\n methodName: propertyKey,\n key: opts.key,\n ...(opts.scope ? { scope: opts.scope } : {}),\n },\n });\n };\n};\n\n/** Helpers of the stereotype decorators; the decorators themselves stay functions. */\nexport class InjectableUtility {\n /** The registration defaults a stereotype forwards to `@injectable`, copied field by field so an absent option stays absent. */\n static pickRegistrationOptions<ApplicationType = unknown>(opts: {\n metadata: IArtifactRegistrationOptions<ApplicationType>;\n }): IArtifactRegistrationOptions<ApplicationType> {\n const { binding, allowOverride, scope, order, when, after } = opts.metadata;\n const registration: IArtifactRegistrationOptions<ApplicationType> = {};\n\n if (binding !== undefined) {\n registration.binding = binding;\n }\n\n if (allowOverride !== undefined) {\n registration.allowOverride = allowOverride;\n }\n\n if (scope !== undefined) {\n registration.scope = scope;\n }\n\n if (order !== undefined) {\n registration.order = order;\n }\n\n if (when !== undefined) {\n registration.when = when;\n }\n\n if (after !== undefined) {\n registration.after = after;\n }\n\n return registration;\n }\n}\n"]}
1
+ {"version":3,"file":"injectable.js","sourceRoot":"","sources":["../../../../src/base/metadata/injectable.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAoB,M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iBAAiB;IAC5B,gIAAgI;IAChI,MAAM,CAAC,uBAAuB,CAA4B,IAEzD;QACC,MAAM,EAAE,OAAO,EAAE,aAAa,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC5E,MAAM,YAAY,GAAkD,EAAE,CAAC;QAEvE,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;YAC1B,YAAY,CAAC,OAAO,GAAG,OAAO,CAAC;QACjC,CAAC;QAED,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;YAChC,YAAY,CAAC,aAAa,GAAG,aAAa,CAAC;QAC7C,CAAC;QAED,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,YAAY,CAAC,KAAK,GAAG,KAAK,CAAC;QAC7B,CAAC;QAED,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,YAAY,CAAC,KAAK,GAAG,KAAK,CAAC;QAC7B,CAAC;QAED,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,YAAY,CAAC,IAAI,GAAG,IAAI,CAAC;QAC3B,CAAC;QAED,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,YAAY,CAAC,KAAK,GAAG,KAAK,CAAC;QAC7B,CAAC;QAED,OAAO,YAAY,CAAC;IACtB,CAAC;CACF","sourcesContent":["import type {\n IArtifactMetadata,\n IArtifactRegistrationOptions,\n TBindingScope,\n} from '@/helpers/inversion';\nimport { ArtifactNamespaces, BindingNamespaces } from '@/common/bindings';\nimport { ArtifactTypes, MetadataRegistry, type TBindingKey } from '@/helpers/inversion';\nimport { ArtifactBindingKeys } from './artifact-keys';\nimport { getError } from '@venizia/ignis-helpers/core';\n\n/** The root stereotype: marks a class as an artifact the application registers, with its registration defaults. Every other stereotype calls it. */\nexport const injectable = <ApplicationType = unknown>(\n opts: IArtifactMetadata<ApplicationType>,\n): ClassDecorator => {\n return (target) => {\n if (!ArtifactTypes.isValid(opts.type)) {\n throw getError({\n message: `[injectable][${target.name}] Invalid artifact type: '${opts.type}' | Expected one of: ${ArtifactTypes.values().join(', ')}`,\n });\n }\n\n // At import time, so the failure lands where the binding is written, not at boot.\n if (opts.binding) {\n BindingNamespaces.assertArtifactNamespace({\n namespace: opts.binding.namespace,\n artifact: target.name,\n caller: 'injectable',\n });\n }\n\n const registry = MetadataRegistry.getInstance();\n registry.setArtifactMetadata({ target, metadata: opts });\n\n // Discovery happens HERE, at import time. A boot-time filesystem scan cannot see a compiled\n // single-file binary, and a class exists at run time only because something imported it.\n registry.addDiscoveredArtifact({ target });\n\n // The key this class WOULD get; `registerArtifact` overwrites it with the one actually bound.\n registry.setBindingKey({\n target,\n key: ArtifactBindingKeys.resolve({\n target,\n namespace: ArtifactNamespaces.resolve({ type: opts.type }),\n binding: opts.binding,\n }).key,\n isProvisional: true,\n });\n };\n};\n\n/**\n * Class decorator that registers the class as a service artifact; accepts the same registration options as `injectable`.\n *\n * @example\n * ```typescript\n * import { BaseService, service } from '@venizia/ignis';\n *\n * export @service()\n * class MailService extends BaseService {\n * constructor() {\n * super({ scope: MailService.name });\n * }\n * }\n * ```\n */\nexport const service = <ApplicationType = unknown>(\n opts?: IArtifactRegistrationOptions<ApplicationType>,\n): ClassDecorator => {\n return injectable<ApplicationType>({ type: ArtifactTypes.SERVICE, ...opts });\n};\n\n/**\n * Class decorator that registers the class as a component artifact; accepts the same registration options as `injectable`.\n *\n * @example\n * ```typescript\n * import { BaseComponent, component } from '@venizia/ignis';\n *\n * export @component()\n * class AuditComponent extends BaseComponent {\n * constructor() {\n * super({ scope: AuditComponent.name });\n * }\n *\n * override binding(): void {}\n * }\n * ```\n */\nexport const component = <ApplicationType = unknown>(\n opts?: IArtifactRegistrationOptions<ApplicationType>,\n): ClassDecorator => {\n return injectable<ApplicationType>({ type: ArtifactTypes.COMPONENT, ...opts });\n};\n\n/**\n * Class decorator that registers the class as a configuration artifact; `after` orders it behind other configuration classes.\n *\n * @example\n * ```typescript\n * import { BaseConfiguration, configuration } from '@venizia/ignis';\n *\n * export @configuration()\n * class SeedConfiguration extends BaseConfiguration {}\n *\n * export @configuration({ after: [SeedConfiguration] })\n * class IndexConfiguration extends BaseConfiguration {}\n * ```\n */\nexport const configuration = <ApplicationType = unknown>(\n opts?: IArtifactRegistrationOptions<ApplicationType>,\n): ClassDecorator => {\n return injectable<ApplicationType>({ type: ArtifactTypes.CONFIGURATION, ...opts });\n};\n\n/** Marks a component method as the provider of `key`. `registerArtifacts` binds the key to a lazy provider that resolves the component and calls the method; SINGLETON unless `scope` says otherwise. */\nexport const provide = (opts: { key: TBindingKey; scope?: TBindingScope }): MethodDecorator => {\n return (target, propertyKey) => {\n MetadataRegistry.getInstance().addProvideMetadata({\n target: target.constructor,\n metadata: {\n methodName: propertyKey,\n key: opts.key,\n ...(opts.scope ? { scope: opts.scope } : {}),\n },\n });\n };\n};\n\n/** Helpers of the stereotype decorators; the decorators themselves stay functions. */\nexport class InjectableUtility {\n /** The registration defaults a stereotype forwards to `@injectable`, copied field by field so an absent option stays absent. */\n static pickRegistrationOptions<ApplicationType = unknown>(opts: {\n metadata: IArtifactRegistrationOptions<ApplicationType>;\n }): IArtifactRegistrationOptions<ApplicationType> {\n const { binding, allowOverride, scope, order, when, after } = opts.metadata;\n const registration: IArtifactRegistrationOptions<ApplicationType> = {};\n\n if (binding !== undefined) {\n registration.binding = binding;\n }\n\n if (allowOverride !== undefined) {\n registration.allowOverride = allowOverride;\n }\n\n if (scope !== undefined) {\n registration.scope = scope;\n }\n\n if (order !== undefined) {\n registration.order = order;\n }\n\n if (when !== undefined) {\n registration.when = when;\n }\n\n if (after !== undefined) {\n registration.after = after;\n }\n\n return registration;\n }\n}\n"]}
@@ -14,7 +14,7 @@ export class ModelMetadataUtility {
14
14
  const { type, migration } = metadata;
15
15
  if (type !== undefined && !ModelTypes.isValid(type)) {
16
16
  throw getError({
17
- message: `[model][${model}] Invalid 'type' | Expected one of: ${[...ModelTypes.SCHEME_SET].join(', ')} (or leave it out) | Got: ${String(type)}`,
17
+ message: `[model][${model}] Invalid 'type' | Expected one of: ${ModelTypes.values().join(', ')} (or leave it out) | Got: ${String(type)}`,
18
18
  });
19
19
  }
20
20
  if (migration === undefined) {