ts-ioc-container 72.2.0 → 72.3.1

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 (58) hide show
  1. package/README.md +242 -0
  2. package/cjm/container/Container.js +3 -0
  3. package/cjm/container/EmptyContainer.js +3 -0
  4. package/cjm/feature/IFeatureFlags.js +6 -0
  5. package/cjm/index.js +11 -2
  6. package/cjm/token/BindableToken.js +63 -0
  7. package/cjm/token/GroupAliasToken.js +5 -50
  8. package/cjm/token/MultiVariantFeatureToken.js +84 -0
  9. package/cjm/token/SingleAliasToken.js +5 -50
  10. package/cjm/token/SingleToken.js +5 -50
  11. package/cjm/token/ToggleFeatureToken.js +10 -0
  12. package/esm/container/Container.js +3 -0
  13. package/esm/container/EmptyContainer.js +3 -0
  14. package/esm/feature/IFeatureFlags.js +3 -0
  15. package/esm/index.js +4 -0
  16. package/esm/token/BindableToken.js +59 -0
  17. package/esm/token/GroupAliasToken.js +5 -50
  18. package/esm/token/MultiVariantFeatureToken.js +80 -0
  19. package/esm/token/SingleAliasToken.js +5 -50
  20. package/esm/token/SingleToken.js +5 -50
  21. package/esm/token/ToggleFeatureToken.js +6 -0
  22. package/lib/container/Container.ts +4 -0
  23. package/lib/container/EmptyContainer.ts +4 -0
  24. package/lib/container/IContainer.ts +3 -0
  25. package/lib/feature/IFeatureFlags.ts +44 -0
  26. package/lib/index.ts +16 -0
  27. package/lib/registration/IRegistration.ts +12 -5
  28. package/lib/token/BindableToken.ts +137 -0
  29. package/lib/token/GroupAliasToken.ts +10 -69
  30. package/lib/token/MultiVariantFeatureToken.ts +160 -0
  31. package/lib/token/SingleAliasToken.ts +11 -67
  32. package/lib/token/SingleToken.ts +9 -67
  33. package/lib/token/ToggleFeatureToken.ts +27 -0
  34. package/package.json +3 -3
  35. package/typings/container/Container.d.ts +1 -0
  36. package/typings/container/Container.d.ts.map +1 -1
  37. package/typings/container/EmptyContainer.d.ts +1 -0
  38. package/typings/container/EmptyContainer.d.ts.map +1 -1
  39. package/typings/container/IContainer.d.ts +2 -0
  40. package/typings/container/IContainer.d.ts.map +1 -1
  41. package/typings/feature/IFeatureFlags.d.ts +42 -0
  42. package/typings/feature/IFeatureFlags.d.ts.map +1 -0
  43. package/typings/index.d.ts +4 -0
  44. package/typings/index.d.ts.map +1 -1
  45. package/typings/registration/IRegistration.d.ts +12 -5
  46. package/typings/registration/IRegistration.d.ts.map +1 -1
  47. package/typings/token/BindableToken.d.ts +80 -0
  48. package/typings/token/BindableToken.d.ts.map +1 -0
  49. package/typings/token/GroupAliasToken.d.ts +9 -24
  50. package/typings/token/GroupAliasToken.d.ts.map +1 -1
  51. package/typings/token/MultiVariantFeatureToken.d.ts +79 -0
  52. package/typings/token/MultiVariantFeatureToken.d.ts.map +1 -0
  53. package/typings/token/SingleAliasToken.d.ts +10 -22
  54. package/typings/token/SingleAliasToken.d.ts.map +1 -1
  55. package/typings/token/SingleToken.d.ts +8 -22
  56. package/typings/token/SingleToken.d.ts.map +1 -1
  57. package/typings/token/ToggleFeatureToken.d.ts +25 -0
  58. package/typings/token/ToggleFeatureToken.d.ts.map +1 -0
package/README.md CHANGED
@@ -52,7 +52,9 @@ provider pipelines, aliases, and custom injector strategies.
52
52
  - [Registration](#registration) `@register`
53
53
  - [Token](#token) `bindTo`
54
54
  - [Scope](#scope) `scope`
55
+ - [Environment-based registration](#environment-based-registration) `Env`
55
56
  - [Composing decorators](#composing-decorators) `createComposeClassDecorator`
57
+ - [Feature flags](#feature-flags) `MultiVariantFeatureToken` `ToggleFeatureToken`
56
58
  - [Module](#module)
57
59
  - [Hook](#hook) `@hook`
58
60
  - [Hook domains](#hook-domains) `ScopeHook` `InjectorHook` `ProviderHook`
@@ -2795,6 +2797,78 @@ describe('Scopes', function () {
2795
2797
 
2796
2798
  ```
2797
2799
 
2800
+ ### Environment-based registration
2801
+
2802
+ Picking an implementation by deployment environment (`prod` / `dev` / `test`)
2803
+ needs no dedicated API - it is the same `scope()` mechanism as above: tag the
2804
+ container with its env and scope each implementation to the env it belongs to.
2805
+ Multiple registrations share the same key; only the one whose scope rule
2806
+ matches the container's tag registers there.
2807
+
2808
+ ```typescript
2809
+ import { bindTo, Container, register, Registration as R, scope, SingleToken } from 'ts-ioc-container';
2810
+
2811
+ /**
2812
+ * Environment-based Registration
2813
+ *
2814
+ * An app often needs a different implementation per deployment environment -
2815
+ * a real payment gateway in production, a stub in tests, a verbose one in dev.
2816
+ * This is a plain application of `scope()`: tag the container with its env and
2817
+ * scope each implementation to the env tag it belongs to. No dedicated API is
2818
+ * needed - the same `ScopeMatchRule` mechanism used for `request` / `transaction`
2819
+ * scopes applies here too.
2820
+ */
2821
+ type Env = 'prod' | 'dev' | 'test';
2822
+
2823
+ interface IPaymentGateway {
2824
+ charge(amount: number): string;
2825
+ }
2826
+
2827
+ const PaymentGatewayToken = new SingleToken<IPaymentGateway>('IPaymentGateway');
2828
+
2829
+ @register(bindTo(PaymentGatewayToken), scope((c) => c.hasTag('prod')))
2830
+ class StripeGateway implements IPaymentGateway {
2831
+ charge(amount: number): string {
2832
+ return `charged $${amount} via Stripe`;
2833
+ }
2834
+ }
2835
+
2836
+ @register(bindTo(PaymentGatewayToken), scope((c) => c.hasTag('dev')))
2837
+ class LoggingGateway implements IPaymentGateway {
2838
+ charge(amount: number): string {
2839
+ return `[dev] would charge $${amount}`;
2840
+ }
2841
+ }
2842
+
2843
+ @register(bindTo(PaymentGatewayToken), scope((c) => c.hasTag('test')))
2844
+ class FakeGateway implements IPaymentGateway {
2845
+ charge(amount: number): string {
2846
+ return `faked charge of $${amount}`;
2847
+ }
2848
+ }
2849
+
2850
+ const createContainerForEnv = (env: Env) =>
2851
+ new Container({ tags: [env] })
2852
+ .addRegistration(R.fromClass(StripeGateway))
2853
+ .addRegistration(R.fromClass(LoggingGateway))
2854
+ .addRegistration(R.fromClass(FakeGateway));
2855
+
2856
+ describe('Environment-based registration', function () {
2857
+ it('should resolve the implementation whose scope tag matches the container env', function () {
2858
+ expect(PaymentGatewayToken.resolve(createContainerForEnv('prod'))).toBeInstanceOf(StripeGateway);
2859
+ expect(PaymentGatewayToken.resolve(createContainerForEnv('dev'))).toBeInstanceOf(LoggingGateway);
2860
+ expect(PaymentGatewayToken.resolve(createContainerForEnv('test'))).toBeInstanceOf(FakeGateway);
2861
+ });
2862
+
2863
+ it('should behave like the environment it was resolved for', function () {
2864
+ const gateway = PaymentGatewayToken.resolve(createContainerForEnv('test'));
2865
+
2866
+ expect(gateway.charge(10)).toBe('faked charge of $10');
2867
+ });
2868
+ });
2869
+
2870
+ ```
2871
+
2798
2872
  ### Composing decorators
2799
2873
 
2800
2874
  A decorator stack repeated on every class of a layer is worth a name.
@@ -2887,6 +2961,174 @@ describe('composing decorators', () => {
2887
2961
 
2888
2962
  ```
2889
2963
 
2964
+ ### Feature flags
2965
+
2966
+ Feature tokens let a feature flag choose which implementation is injected, so
2967
+ consumers depend on one type and never see the flag. The implementations
2968
+ decide where they belong - each one's own token declares its role:
2969
+
2970
+ - `token.variantOf(Feature, 'blue')` - used while the flag serves the variant `blue` (`getVariant`)
2971
+ - `token.primaryVariantOf(Feature)` - used while the flag is on and no named variant implementation matches
2972
+ - `token.fallbackOf(Feature)` - used otherwise: the flag is off, serves nothing implemented, or its client throws
2973
+
2974
+ **Every flag has a fallback**: resolving a feature without one registered is a
2975
+ `DependencyNotFoundError`, whatever the flag serves. `MultiVariantFeatureToken<T, V>`
2976
+ is the general case; `ToggleFeatureToken<T>` is its on/off case - no named
2977
+ variants, only a primary one (`isEnabled`). Each implementation stays
2978
+ injectable through its own token.
2979
+
2980
+ The flag client comes from `IFeatureFlagsToken` and the context it evaluates
2981
+ for from `IFeatureContextToken`, both resolved from the resolving scope on every
2982
+ resolution - register the context in your `request` scope. A missing client or
2983
+ context is a `DependencyNotFoundError`, never a silent fallback.
2984
+
2985
+ `IFeatureFlags` is shaped after Unleash (`isEnabled(name, context)`,
2986
+ `getVariant(name, context)`), so an Unleash client is registered as is:
2987
+ `R.fromValue(unleash).bindTo(IFeatureFlagsToken)`. Resolution is synchronous;
2988
+ wrap an asynchronous client (e.g. the OpenFeature server SDK) in an adapter
2989
+ that evaluates ahead of time. `Feature.lazy()` defers the evaluation to first use.
2990
+
2991
+ ```typescript
2992
+ import 'reflect-metadata';
2993
+ import {
2994
+ by,
2995
+ Container,
2996
+ type FeatureContext,
2997
+ type FeatureVariant,
2998
+ type IFeatureFlags,
2999
+ IFeatureContextToken,
3000
+ IFeatureFlagsToken,
3001
+ inject,
3002
+ MultiVariantFeatureToken,
3003
+ register,
3004
+ Registration as R,
3005
+ SingleToken,
3006
+ ToggleFeatureToken,
3007
+ } from 'ts-ioc-container';
3008
+
3009
+ /**
3010
+ * Checkout Domain - Feature Flags
3011
+ *
3012
+ * A flag chooses which implementation is injected; the consumer depends on one
3013
+ * type and never sees the flag. The implementations decide where they belong:
3014
+ * each one's own token declares it
3015
+ *
3016
+ * - `.variantOf(feature, name)` - used while the flag serves the variant `name`;
3017
+ * - `.primaryVariantOf(feature)` - used while the flag is on and no named
3018
+ * variant implementation matches (the "on" side of a toggle);
3019
+ * - `.fallbackOf(feature)` - used otherwise. Every flag has one.
3020
+ *
3021
+ * `ToggleFeatureToken` is the on/off case of `MultiVariantFeatureToken`: no
3022
+ * named variants, only a primary one.
3023
+ *
3024
+ * The flag client is any object with `isEnabled(name, context)` and
3025
+ * `getVariant(name, context)` - an Unleash client works as is:
3026
+ * container.addRegistration(R.fromValue(unleash).bindTo(IFeatureFlagsToken));
3027
+ */
3028
+
3029
+ // Toggle: new checkout on / off
3030
+ interface IPaymentGateway {
3031
+ pay(amount: number): string;
3032
+ }
3033
+
3034
+ const PaymentGatewayToken = new ToggleFeatureToken<IPaymentGateway>('new-checkout');
3035
+
3036
+ // Each implementation's own token declares where it belongs
3037
+ @register(new SingleToken<IPaymentGateway>('LegacyGateway').fallbackOf(PaymentGatewayToken))
3038
+ class LegacyGateway implements IPaymentGateway {
3039
+ pay(amount: number) {
3040
+ return `legacy charged ${amount}`;
3041
+ }
3042
+ }
3043
+
3044
+ @register(new SingleToken<IPaymentGateway>('StripeGateway').primaryVariantOf(PaymentGatewayToken))
3045
+ class StripeGateway implements IPaymentGateway {
3046
+ pay(amount: number) {
3047
+ return `stripe charged ${amount}`;
3048
+ }
3049
+ }
3050
+
3051
+ // Multi-variant: A/B/n experiment on the checkout button
3052
+ interface ICheckoutButton {
3053
+ render(): string;
3054
+ }
3055
+
3056
+ const CheckoutButtonToken = new MultiVariantFeatureToken<ICheckoutButton, 'blue' | 'green'>('checkout-button');
3057
+
3058
+ @register(new SingleToken<ICheckoutButton>('GreyButton').fallbackOf(CheckoutButtonToken))
3059
+ class GreyButton implements ICheckoutButton {
3060
+ render() {
3061
+ return 'grey button';
3062
+ }
3063
+ }
3064
+
3065
+ @register(new SingleToken<ICheckoutButton>('BlueButton').variantOf(CheckoutButtonToken, 'blue'))
3066
+ class BlueButton implements ICheckoutButton {
3067
+ render() {
3068
+ return 'blue button';
3069
+ }
3070
+ }
3071
+
3072
+ @register(new SingleToken<ICheckoutButton>('GreenButton').variantOf(CheckoutButtonToken, 'green'))
3073
+ class GreenButton implements ICheckoutButton {
3074
+ render() {
3075
+ return 'green button';
3076
+ }
3077
+ }
3078
+
3079
+ class CheckoutPage {
3080
+ constructor(
3081
+ @inject(by(PaymentGatewayToken)) private readonly gateway: IPaymentGateway,
3082
+ @inject(by(CheckoutButtonToken)) private readonly button: ICheckoutButton,
3083
+ ) {}
3084
+
3085
+ render(amount: number) {
3086
+ return `${this.button.render()}, ${this.gateway.pay(amount)}`;
3087
+ }
3088
+ }
3089
+
3090
+ // Stands in for an Unleash client
3091
+ class InMemoryFlags implements IFeatureFlags {
3092
+ isEnabled(name: string, context?: FeatureContext) {
3093
+ return name === 'new-checkout' && context?.userId === 'beta-tester';
3094
+ }
3095
+
3096
+ getVariant(name: string, context?: FeatureContext): FeatureVariant {
3097
+ const bucket = { 'beta-tester': 'green', 'user-1': 'blue' }[context?.userId ?? ''];
3098
+ return name === 'checkout-button' && bucket
3099
+ ? { name: bucket, enabled: true }
3100
+ : { name: 'disabled', enabled: false };
3101
+ }
3102
+ }
3103
+
3104
+ describe('Feature flags', () => {
3105
+ const app = new Container({ tags: ['application'] })
3106
+ .addRegistration(R.fromValue(new InMemoryFlags()).bindTo(IFeatureFlagsToken))
3107
+ .addRegistration(R.fromClass(LegacyGateway))
3108
+ .addRegistration(R.fromClass(GreyButton))
3109
+ .addRegistration(R.fromClass(StripeGateway))
3110
+ .addRegistration(R.fromClass(BlueButton))
3111
+ .addRegistration(R.fromClass(GreenButton));
3112
+
3113
+ // The context is per request: each request evaluates the flags for its own user
3114
+ const handleRequest = (userId: string) => {
3115
+ const request = app.createScope({ tags: ['request'] });
3116
+ request.addRegistration(R.fromValue({ userId }).bindTo(IFeatureContextToken));
3117
+ return request.resolve(CheckoutPage).render(42);
3118
+ };
3119
+
3120
+ it('serves each user the implementations their flags select', () => {
3121
+ expect(handleRequest('beta-tester')).toBe('green button, stripe charged 42');
3122
+ expect(handleRequest('user-1')).toBe('blue button, legacy charged 42');
3123
+ });
3124
+
3125
+ it('serves the fallbacks to everyone else', () => {
3126
+ expect(handleRequest('regular-user')).toBe('grey button, legacy charged 42');
3127
+ });
3128
+ });
3129
+
3130
+ ```
3131
+
2890
3132
  ## Module
2891
3133
 
2892
3134
  Sometimes you want to encapsulate registration logic in separate module. This is what `IContainerModule` is for.
@@ -129,6 +129,9 @@ class Container {
129
129
  hasRegistration(key) {
130
130
  return this.registrations.some((r) => r.getKeyOrFail() === key) || this.parent.hasRegistration(key);
131
131
  }
132
+ hasAlias(alias) {
133
+ return this.aliases.getKeysByAlias(alias).length > 0 || this.parent.hasAlias(alias);
134
+ }
132
135
  addInstance(instance) {
133
136
  this.instances.add(instance);
134
137
  }
@@ -47,6 +47,9 @@ class EmptyContainer {
47
47
  hasRegistration(key) {
48
48
  return false;
49
49
  }
50
+ hasAlias(alias) {
51
+ return false;
52
+ }
50
53
  removeScope() { }
51
54
  useModule(module) {
52
55
  throw new MethodNotImplementedError_1.MethodNotImplementedError('EmptyContainer.useModule is not implemented');
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.IFeatureContextToken = exports.IFeatureFlagsToken = void 0;
4
+ const SingleToken_1 = require("../token/SingleToken");
5
+ exports.IFeatureFlagsToken = new SingleToken_1.SingleToken('IFeatureFlags');
6
+ exports.IFeatureContextToken = new SingleToken_1.SingleToken('IFeatureContext');
package/cjm/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createHookContextFactory = exports.HookContext = exports.toHookFn = exports.hasHooks = exports.hook = exports.getHooks = exports.ArgumentNotFoundError = exports.TypedEventDisposedError = exports.UnsupportedTokenTypeError = exports.CannonSingletonApplyTwiceError = exports.CannotApplySingletonTwiceError = exports.ProviderDisposedError = exports.ContainerDisposedError = exports.MethodNotImplementedError = exports.DependencyMissingKeyError = exports.ContainerNotFoundError = exports.DependencyNotFoundError = exports.ContainerError = exports.Registration = exports.onResolve = exports.appendArgsFn = exports.appendArgs = exports.decorate = exports.singleton = exports.autoResolve = exports.lazy = exports.scopeAccess = exports.scope = exports.bindTo = exports.register = exports.toRegistrationFn = exports.toProviderFn = exports.toBindToken = exports.registerPipe = exports.isProviderPipe = exports.Provider = exports.ProxyInjector = exports.SimpleInjector = exports.resolveArgs = exports.by = exports.argsFn = exports.args = exports.arg = exports.inject = exports.MetadataInjector = exports.Injector = exports.EmptyContainer = exports.AutoResolveModule = exports.Container = exports.isDependencyKey = void 0;
4
- exports.shallowCache = exports.debounce = exports.throttle = exports.runAtOnce = exports.runInOrder = exports.handleAsyncError = exports.handleError = exports.createComposeMethodDecorator = exports.getMethodTags = exports.addMethodTag = exports.getMethodLabels = exports.addMethodLabel = exports.getMethodMeta = exports.addMethodMeta = exports.createComposeParameterDecorator = exports.getParamTags = exports.addParamTag = exports.getParamLabels = exports.addParamLabel = exports.getParamMeta = exports.addParamMeta = exports.createComposeClassDecorator = exports.getClassTags = exports.addClassTag = exports.getClassLabels = exports.addClassLabel = exports.getClassMeta = exports.addClassMeta = exports.resolveConstructor = exports.GroupInstanceToken = exports.ConstantToken = exports.FunctionToken = exports.SingleToken = exports.ClassToken = exports.toSingleAlias = exports.SingleAliasToken = exports.toGroupAlias = exports.GroupAliasToken = exports.argToToken = exports.toToken = exports.forwardArgs = exports.isInjectionToken = exports.InjectionToken = exports.toTask = exports.HookCollector = exports.oncePerInstance = exports.parallel = exports.sequential = exports.injectProp = exports.createHookExecutionContext = void 0;
5
- exports.isSerializable = exports.Is = exports.unwrapProxy = exports.ProxyRegistry = exports.findOrFail = exports.pipe = exports.select = exports.TypedEvent = exports.getConstructorChain = exports.memoize = exports.once = void 0;
4
+ exports.handleAsyncError = exports.handleError = exports.createComposeMethodDecorator = exports.getMethodTags = exports.addMethodTag = exports.getMethodLabels = exports.addMethodLabel = exports.getMethodMeta = exports.addMethodMeta = exports.createComposeParameterDecorator = exports.getParamTags = exports.addParamTag = exports.getParamLabels = exports.addParamLabel = exports.getParamMeta = exports.addParamMeta = exports.createComposeClassDecorator = exports.getClassTags = exports.addClassTag = exports.getClassLabels = exports.addClassLabel = exports.getClassMeta = exports.addClassMeta = exports.resolveConstructor = exports.IFeatureContextToken = exports.IFeatureFlagsToken = exports.ToggleFeatureToken = exports.MultiVariantFeatureToken = exports.GroupInstanceToken = exports.ConstantToken = exports.FunctionToken = exports.SingleToken = exports.BindableToken = exports.ClassToken = exports.toSingleAlias = exports.SingleAliasToken = exports.toGroupAlias = exports.GroupAliasToken = exports.argToToken = exports.toToken = exports.forwardArgs = exports.isInjectionToken = exports.InjectionToken = exports.toTask = exports.HookCollector = exports.oncePerInstance = exports.parallel = exports.sequential = exports.injectProp = exports.createHookExecutionContext = void 0;
5
+ exports.isSerializable = exports.Is = exports.unwrapProxy = exports.ProxyRegistry = exports.findOrFail = exports.pipe = exports.select = exports.TypedEvent = exports.getConstructorChain = exports.memoize = exports.once = exports.shallowCache = exports.debounce = exports.throttle = exports.runAtOnce = exports.runInOrder = void 0;
6
6
  var IContainer_1 = require("./container/IContainer");
7
7
  Object.defineProperty(exports, "isDependencyKey", { enumerable: true, get: function () { return IContainer_1.isDependencyKey; } });
8
8
  var Container_1 = require("./container/Container");
@@ -103,6 +103,8 @@ Object.defineProperty(exports, "SingleAliasToken", { enumerable: true, get: func
103
103
  Object.defineProperty(exports, "toSingleAlias", { enumerable: true, get: function () { return SingleAliasToken_1.toSingleAlias; } });
104
104
  var ClassToken_1 = require("./token/ClassToken");
105
105
  Object.defineProperty(exports, "ClassToken", { enumerable: true, get: function () { return ClassToken_1.ClassToken; } });
106
+ var BindableToken_1 = require("./token/BindableToken");
107
+ Object.defineProperty(exports, "BindableToken", { enumerable: true, get: function () { return BindableToken_1.BindableToken; } });
106
108
  var SingleToken_1 = require("./token/SingleToken");
107
109
  Object.defineProperty(exports, "SingleToken", { enumerable: true, get: function () { return SingleToken_1.SingleToken; } });
108
110
  var FunctionToken_1 = require("./token/FunctionToken");
@@ -111,6 +113,13 @@ var ConstantToken_1 = require("./token/ConstantToken");
111
113
  Object.defineProperty(exports, "ConstantToken", { enumerable: true, get: function () { return ConstantToken_1.ConstantToken; } });
112
114
  var GroupInstanceToken_1 = require("./token/GroupInstanceToken");
113
115
  Object.defineProperty(exports, "GroupInstanceToken", { enumerable: true, get: function () { return GroupInstanceToken_1.GroupInstanceToken; } });
116
+ var MultiVariantFeatureToken_1 = require("./token/MultiVariantFeatureToken");
117
+ Object.defineProperty(exports, "MultiVariantFeatureToken", { enumerable: true, get: function () { return MultiVariantFeatureToken_1.MultiVariantFeatureToken; } });
118
+ var ToggleFeatureToken_1 = require("./token/ToggleFeatureToken");
119
+ Object.defineProperty(exports, "ToggleFeatureToken", { enumerable: true, get: function () { return ToggleFeatureToken_1.ToggleFeatureToken; } });
120
+ var IFeatureFlags_1 = require("./feature/IFeatureFlags");
121
+ Object.defineProperty(exports, "IFeatureFlagsToken", { enumerable: true, get: function () { return IFeatureFlags_1.IFeatureFlagsToken; } });
122
+ Object.defineProperty(exports, "IFeatureContextToken", { enumerable: true, get: function () { return IFeatureFlags_1.IFeatureContextToken; } });
114
123
  var target_1 = require("./metadata/target");
115
124
  Object.defineProperty(exports, "resolveConstructor", { enumerable: true, get: function () { return target_1.resolveConstructor; } });
116
125
  var class_1 = require("./metadata/class");
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BindableToken = void 0;
4
+ const InjectionToken_1 = require("./InjectionToken");
5
+ class BindableToken extends InjectionToken_1.InjectionToken {
6
+ token;
7
+ getArgsFn;
8
+ isLazyByDefault;
9
+ memberships;
10
+ constructor(token, { getArgsFn = InjectionToken_1.forwardArgs, isLazy = false, tags = [], memberships = [] } = {}) {
11
+ super(tags);
12
+ this.token = token;
13
+ this.getArgsFn = getArgsFn;
14
+ this.isLazyByDefault = isLazy;
15
+ this.memberships = memberships;
16
+ }
17
+ bindTo(r) {
18
+ this.bindKey(r);
19
+ for (const alias of this.memberships) {
20
+ r.bindToAlias(alias);
21
+ }
22
+ }
23
+ variantOf(feature, name) {
24
+ return this.copy({ memberships: [...this.memberships, feature.variantAlias(name)] });
25
+ }
26
+ primaryVariantOf(feature) {
27
+ return this.copy({ memberships: [...this.memberships, feature.primaryAlias()] });
28
+ }
29
+ fallbackOf(feature) {
30
+ return this.copy({ memberships: [...this.memberships, feature.fallbackAlias()] });
31
+ }
32
+ args(...newArgs) {
33
+ const parentFn = this.getArgsFn;
34
+ return this.copy({ getArgsFn: (options) => [...parentFn(options), ...newArgs] });
35
+ }
36
+ argsFn(fn) {
37
+ const parentFn = this.getArgsFn;
38
+ return this.copy({ getArgsFn: (options) => [...parentFn(options), ...fn(options.scope)] });
39
+ }
40
+ lazy() {
41
+ return this.copy({ isLazy: true });
42
+ }
43
+ addTags(...tags) {
44
+ return this.copy({ tags: [...this.getTags(), ...tags] });
45
+ }
46
+ toString() {
47
+ return this.token.toString();
48
+ }
49
+ toResolveOptions(s, { args = [], lazy } = {}) {
50
+ return { args: this.getArgsFn({ scope: s, args }), lazy: this.isLazyByDefault || lazy };
51
+ }
52
+ copy(overrides) {
53
+ const Self = this.constructor;
54
+ return new Self(this.token, {
55
+ getArgsFn: this.getArgsFn,
56
+ isLazy: this.isLazyByDefault,
57
+ tags: this.getTags(),
58
+ memberships: this.memberships,
59
+ ...overrides,
60
+ });
61
+ }
62
+ }
63
+ exports.BindableToken = BindableToken;
@@ -1,62 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.toGroupAlias = exports.GroupAliasToken = void 0;
4
- const InjectionToken_1 = require("./InjectionToken");
5
- class GroupAliasToken extends InjectionToken_1.InjectionToken {
6
- token;
7
- _getArgsFn;
8
- _isLazy;
9
- constructor(token, { getArgsFn = InjectionToken_1.forwardArgs, isLazy = false, tags = [], } = {}) {
10
- super(tags);
11
- this.token = token;
12
- this._getArgsFn = getArgsFn;
13
- this._isLazy = isLazy;
14
- }
4
+ const BindableToken_1 = require("./BindableToken");
5
+ class GroupAliasToken extends BindableToken_1.BindableToken {
15
6
  select(fn) {
16
7
  return (s) => fn(this.resolve(s));
17
8
  }
18
- resolve(s, { args = [], lazy } = {}) {
19
- return s.resolveByAlias(this.token, {
20
- args: this._getArgsFn({ scope: s, args }),
21
- lazy: this._isLazy || lazy,
22
- });
9
+ resolve(s, options) {
10
+ return s.resolveByAlias(this.token, this.toResolveOptions(s, options));
23
11
  }
24
- bindTo(r) {
12
+ bindKey(r) {
25
13
  r.bindToAlias(this.token);
26
14
  }
27
- args(...newArgs) {
28
- const parentFn = this._getArgsFn;
29
- return new GroupAliasToken(this.token, {
30
- getArgsFn: (options) => [...parentFn(options), ...newArgs],
31
- isLazy: this._isLazy,
32
- tags: this.getTags(),
33
- });
34
- }
35
- argsFn(fn) {
36
- const parentFn = this._getArgsFn;
37
- return new GroupAliasToken(this.token, {
38
- getArgsFn: (options) => [...parentFn(options), ...fn(options.scope)],
39
- isLazy: this._isLazy,
40
- tags: this.getTags(),
41
- });
42
- }
43
- lazy() {
44
- return new GroupAliasToken(this.token, {
45
- getArgsFn: this._getArgsFn,
46
- isLazy: true,
47
- tags: this.getTags(),
48
- });
49
- }
50
- addTags(...tags) {
51
- return new GroupAliasToken(this.token, {
52
- getArgsFn: this._getArgsFn,
53
- isLazy: this._isLazy,
54
- tags: [...this.getTags(), ...tags],
55
- });
56
- }
57
- toString() {
58
- return this.token.toString();
59
- }
60
15
  }
61
16
  exports.GroupAliasToken = GroupAliasToken;
62
17
  const toGroupAlias = (token) => new GroupAliasToken(token);
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MultiVariantFeatureToken = void 0;
4
+ const InjectionToken_1 = require("./InjectionToken");
5
+ const ProxyRegistry_1 = require("../utils/ProxyRegistry");
6
+ const DependencyNotFoundError_1 = require("../errors/DependencyNotFoundError");
7
+ const IFeatureFlags_1 = require("../feature/IFeatureFlags");
8
+ class MultiVariantFeatureToken extends InjectionToken_1.InjectionToken {
9
+ flag;
10
+ _getArgsFn;
11
+ _isLazy;
12
+ constructor(flag, { getArgsFn = InjectionToken_1.forwardArgs, isLazy = false, tags = [] } = {}) {
13
+ super(tags);
14
+ this.flag = flag;
15
+ this._getArgsFn = getArgsFn;
16
+ this._isLazy = isLazy;
17
+ }
18
+ variantAlias(name) {
19
+ return `feature:${this.flag}:variant:${name}`;
20
+ }
21
+ primaryAlias() {
22
+ return `feature:${this.flag}:primary`;
23
+ }
24
+ fallbackAlias() {
25
+ return `feature:${this.flag}:fallback`;
26
+ }
27
+ resolve(s, { args = [], lazy } = {}) {
28
+ const resolveSelected = () => s.resolveOneByAlias(this.selectAlias(s), { args: this._getArgsFn({ scope: s, args }) });
29
+ return ProxyRegistry_1.ProxyRegistry.getInstance().toLazyIf(resolveSelected, this._isLazy || lazy);
30
+ }
31
+ args(...newArgs) {
32
+ const parentFn = this._getArgsFn;
33
+ return this.copy({ getArgsFn: (options) => [...parentFn(options), ...newArgs] });
34
+ }
35
+ argsFn(fn) {
36
+ const parentFn = this._getArgsFn;
37
+ return this.copy({ getArgsFn: (options) => [...parentFn(options), ...fn(options.scope)] });
38
+ }
39
+ lazy() {
40
+ return this.copy({ isLazy: true });
41
+ }
42
+ addTags(...tags) {
43
+ return this.copy({ tags: [...this.getTags(), ...tags] });
44
+ }
45
+ toString() {
46
+ return this.flag;
47
+ }
48
+ evaluate(flags, context) {
49
+ const served = flags.getVariant(this.flag, context);
50
+ return served.enabled
51
+ ? { enabled: true, variant: served.name }
52
+ : { enabled: flags.isEnabled(this.flag, context) };
53
+ }
54
+ copy(overrides) {
55
+ const Self = this.constructor;
56
+ return new Self(this.flag, {
57
+ getArgsFn: this._getArgsFn,
58
+ isLazy: this._isLazy,
59
+ tags: this.getTags(),
60
+ ...overrides,
61
+ });
62
+ }
63
+ selectAlias(s) {
64
+ const fallback = this.fallbackAlias();
65
+ if (!s.hasAlias(fallback)) {
66
+ throw new DependencyNotFoundError_1.DependencyNotFoundError(`Feature flag "${this.flag}" has no fallback: a flag always has one. ` +
67
+ `Register it with @register(token.fallbackOf(feature)) in this scope or a parent.`);
68
+ }
69
+ const flags = IFeatureFlags_1.IFeatureFlagsToken.resolve(s);
70
+ const context = IFeatureFlags_1.IFeatureContextToken.resolve(s);
71
+ let served = { enabled: false };
72
+ try {
73
+ served = this.evaluate(flags, context);
74
+ }
75
+ catch {
76
+ }
77
+ const candidates = [
78
+ served.variant === undefined ? undefined : this.variantAlias(served.variant),
79
+ served.enabled ? this.primaryAlias() : undefined,
80
+ ];
81
+ return candidates.find((alias) => alias !== undefined && s.hasAlias(alias)) ?? fallback;
82
+ }
83
+ }
84
+ exports.MultiVariantFeatureToken = MultiVariantFeatureToken;
@@ -1,62 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.toSingleAlias = exports.SingleAliasToken = void 0;
4
- const InjectionToken_1 = require("./InjectionToken");
5
- class SingleAliasToken extends InjectionToken_1.InjectionToken {
6
- token;
7
- _getArgsFn;
8
- _isLazy;
9
- constructor(token, { getArgsFn = InjectionToken_1.forwardArgs, isLazy = false, tags = [], } = {}) {
10
- super(tags);
11
- this.token = token;
12
- this._getArgsFn = getArgsFn;
13
- this._isLazy = isLazy;
14
- }
4
+ const BindableToken_1 = require("./BindableToken");
5
+ class SingleAliasToken extends BindableToken_1.BindableToken {
15
6
  select(fn) {
16
7
  return (s) => fn(this.resolve(s));
17
8
  }
18
- resolve(s, { args = [], lazy } = {}) {
19
- return s.resolveOneByAlias(this.token, {
20
- args: this._getArgsFn({ scope: s, args }),
21
- lazy: this._isLazy || lazy,
22
- });
9
+ resolve(s, options) {
10
+ return s.resolveOneByAlias(this.token, this.toResolveOptions(s, options));
23
11
  }
24
- bindTo(r) {
12
+ bindKey(r) {
25
13
  r.bindToAlias(this.token);
26
14
  }
27
- args(...newArgs) {
28
- const parentFn = this._getArgsFn;
29
- return new SingleAliasToken(this.token, {
30
- getArgsFn: (options) => [...parentFn(options), ...newArgs],
31
- isLazy: this._isLazy,
32
- tags: this.getTags(),
33
- });
34
- }
35
- argsFn(fn) {
36
- const parentFn = this._getArgsFn;
37
- return new SingleAliasToken(this.token, {
38
- getArgsFn: (options) => [...parentFn(options), ...fn(options.scope)],
39
- isLazy: this._isLazy,
40
- tags: this.getTags(),
41
- });
42
- }
43
- lazy() {
44
- return new SingleAliasToken(this.token, {
45
- getArgsFn: this._getArgsFn,
46
- isLazy: true,
47
- tags: this.getTags(),
48
- });
49
- }
50
- addTags(...tags) {
51
- return new SingleAliasToken(this.token, {
52
- getArgsFn: this._getArgsFn,
53
- isLazy: this._isLazy,
54
- tags: [...this.getTags(), ...tags],
55
- });
56
- }
57
- toString() {
58
- return this.token.toString();
59
- }
60
15
  }
61
16
  exports.SingleAliasToken = SingleAliasToken;
62
17
  const toSingleAlias = (token) => new SingleAliasToken(token);
@@ -1,61 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SingleToken = void 0;
4
- const InjectionToken_1 = require("./InjectionToken");
5
- class SingleToken extends InjectionToken_1.InjectionToken {
6
- token;
7
- _getArgsFn;
8
- _isLazy;
9
- constructor(token, { getArgsFn = InjectionToken_1.forwardArgs, isLazy = false, tags = [], } = {}) {
10
- super(tags);
11
- this.token = token;
12
- this._getArgsFn = getArgsFn;
13
- this._isLazy = isLazy;
14
- }
4
+ const BindableToken_1 = require("./BindableToken");
5
+ class SingleToken extends BindableToken_1.BindableToken {
15
6
  select(fn) {
16
7
  return (s) => fn(this.resolve(s));
17
8
  }
18
- resolve(s, { args = [], lazy } = {}) {
19
- return s.resolve(this.token, {
20
- args: this._getArgsFn({ scope: s, args }),
21
- lazy: this._isLazy || lazy,
22
- });
9
+ resolve(s, options) {
10
+ return s.resolve(this.token, this.toResolveOptions(s, options));
23
11
  }
24
- bindTo(r) {
12
+ bindKey(r) {
25
13
  r.bindToKey(this.token);
26
14
  }
27
- args(...newArgs) {
28
- const parentFn = this._getArgsFn;
29
- return new SingleToken(this.token, {
30
- getArgsFn: (options) => [...parentFn(options), ...newArgs],
31
- isLazy: this._isLazy,
32
- tags: this.getTags(),
33
- });
34
- }
35
- argsFn(fn) {
36
- const parentFn = this._getArgsFn;
37
- return new SingleToken(this.token, {
38
- getArgsFn: (options) => [...parentFn(options), ...fn(options.scope)],
39
- isLazy: this._isLazy,
40
- tags: this.getTags(),
41
- });
42
- }
43
- lazy() {
44
- return new SingleToken(this.token, {
45
- getArgsFn: this._getArgsFn,
46
- isLazy: true,
47
- tags: this.getTags(),
48
- });
49
- }
50
- addTags(...tags) {
51
- return new SingleToken(this.token, {
52
- getArgsFn: this._getArgsFn,
53
- isLazy: this._isLazy,
54
- tags: [...this.getTags(), ...tags],
55
- });
56
- }
57
- toString() {
58
- return this.token.toString();
59
- }
60
15
  }
61
16
  exports.SingleToken = SingleToken;