@microsoft/feature-management 1.0.0-preview.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +2 -0
  2. package/dist/commonjs/featureManager.js +71 -0
  3. package/dist/commonjs/featureManager.js.map +1 -0
  4. package/dist/commonjs/featureProvider.js +43 -0
  5. package/dist/commonjs/featureProvider.js.map +1 -0
  6. package/dist/commonjs/filter/TargetingFilter.js +138 -0
  7. package/dist/commonjs/filter/TargetingFilter.js.map +1 -0
  8. package/dist/commonjs/filter/TimeWindowFilter.js +22 -0
  9. package/{dist-esm → dist/commonjs}/filter/TimeWindowFilter.js.map +1 -1
  10. package/dist/commonjs/index.js +13 -0
  11. package/dist/commonjs/index.js.map +1 -0
  12. package/dist/commonjs/model.js +12 -0
  13. package/dist/commonjs/model.js.map +1 -0
  14. package/dist/commonjs/version.js +8 -0
  15. package/dist/commonjs/version.js.map +1 -0
  16. package/{dist-esm → dist/esm}/featureManager.js +18 -9
  17. package/dist/esm/featureManager.js.map +1 -0
  18. package/{dist-esm → dist/esm}/featureProvider.js +9 -6
  19. package/dist/esm/featureProvider.js.map +1 -0
  20. package/{dist-esm → dist/esm}/filter/TargetingFilter.js +47 -15
  21. package/dist/esm/filter/TargetingFilter.js.map +1 -0
  22. package/{dist-esm → dist/esm}/filter/TimeWindowFilter.js +4 -2
  23. package/dist/esm/filter/TimeWindowFilter.js.map +1 -0
  24. package/dist/esm/index.js +4 -0
  25. package/dist/esm/index.js.map +1 -0
  26. package/dist/esm/model.js +9 -0
  27. package/dist/esm/model.js.map +1 -0
  28. package/dist/esm/version.js +6 -0
  29. package/dist/esm/version.js.map +1 -0
  30. package/dist/umd/index.js +276 -0
  31. package/dist/umd/index.js.map +1 -0
  32. package/package.json +14 -19
  33. package/types/index.d.ts +121 -10
  34. package/dist/index.js +0 -234
  35. package/dist/index.js.map +0 -1
  36. package/dist-esm/featureManager.js.map +0 -1
  37. package/dist-esm/featureProvider.js.map +0 -1
  38. package/dist-esm/filter/FeatureFilter.js +0 -4
  39. package/dist-esm/filter/FeatureFilter.js.map +0 -1
  40. package/dist-esm/filter/TargetingFilter.js.map +0 -1
  41. package/dist-esm/gettable.js +0 -6
  42. package/dist-esm/gettable.js.map +0 -1
  43. package/dist-esm/index.js +0 -5
  44. package/dist-esm/index.js.map +0 -1
  45. package/dist-esm/model.js +0 -12
  46. package/dist-esm/model.js.map +0 -1
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # Microsoft Feature Management for JavaScript
2
2
 
3
+ [![feature-management](https://img.shields.io/npm/v/@microsoft/feature-management?label=@microsoft/feature-management)](https://www.npmjs.com/package/@microsoft/feature-management)
4
+
3
5
  Feature Management is a library for enabling/disabling features at runtime.
4
6
  Developers can use feature flags in simple use cases like conditional statement to more advanced scenarios like conditionally adding routes.
5
7
 
@@ -0,0 +1,71 @@
1
+ 'use strict';
2
+
3
+ var TimeWindowFilter = require('./filter/TimeWindowFilter.js');
4
+ var TargetingFilter = require('./filter/TargetingFilter.js');
5
+
6
+ // Copyright (c) Microsoft Corporation.
7
+ // Licensed under the MIT license.
8
+ class FeatureManager {
9
+ #provider;
10
+ #featureFilters = new Map();
11
+ constructor(provider, options) {
12
+ this.#provider = provider;
13
+ const builtinFilters = [new TimeWindowFilter.TimeWindowFilter(), new TargetingFilter.TargetingFilter()];
14
+ // If a custom filter shares a name with an existing filter, the custom filter overrides the existing one.
15
+ for (const filter of [...builtinFilters, ...(options?.customFilters ?? [])]) {
16
+ this.#featureFilters.set(filter.name, filter);
17
+ }
18
+ }
19
+ async listFeatureNames() {
20
+ const features = await this.#provider.getFeatureFlags();
21
+ const featureNameSet = new Set(features.map((feature) => feature.id));
22
+ return Array.from(featureNameSet);
23
+ }
24
+ // If multiple feature flags are found, the first one takes precedence.
25
+ async isEnabled(featureName, context) {
26
+ const featureFlag = await this.#provider.getFeatureFlag(featureName);
27
+ if (featureFlag === undefined) {
28
+ // If the feature is not found, then it is disabled.
29
+ return false;
30
+ }
31
+ // Ensure that the feature flag is in the correct format. Feature providers should validate the feature flags, but we do it here as a safeguard.
32
+ validateFeatureFlagFormat(featureFlag);
33
+ if (featureFlag.enabled !== true) {
34
+ // If the feature is not explicitly enabled, then it is disabled by default.
35
+ return false;
36
+ }
37
+ const clientFilters = featureFlag.conditions?.client_filters;
38
+ if (clientFilters === undefined || clientFilters.length <= 0) {
39
+ // If there are no client filters, then the feature is enabled.
40
+ return true;
41
+ }
42
+ const requirementType = featureFlag.conditions?.requirement_type ?? "Any"; // default to any.
43
+ /**
44
+ * While iterating through the client filters, we short-circuit the evaluation based on the requirement type.
45
+ * - When requirement type is "All", the feature is enabled if all client filters are matched. If any client filter is not matched, the feature is disabled, otherwise it is enabled. `shortCircuitEvaluationResult` is false.
46
+ * - When requirement type is "Any", the feature is enabled if any client filter is matched. If any client filter is matched, the feature is enabled, otherwise it is disabled. `shortCircuitEvaluationResult` is true.
47
+ */
48
+ const shortCircuitEvaluationResult = requirementType === "Any";
49
+ for (const clientFilter of clientFilters) {
50
+ const matchedFeatureFilter = this.#featureFilters.get(clientFilter.name);
51
+ const contextWithFeatureName = { featureName, parameters: clientFilter.parameters };
52
+ if (matchedFeatureFilter === undefined) {
53
+ console.warn(`Feature filter ${clientFilter.name} is not found.`);
54
+ return false;
55
+ }
56
+ if (await matchedFeatureFilter.evaluate(contextWithFeatureName, context) === shortCircuitEvaluationResult) {
57
+ return shortCircuitEvaluationResult;
58
+ }
59
+ }
60
+ // If we get here, then we have not found a client filter that matches the requirement type.
61
+ return !shortCircuitEvaluationResult;
62
+ }
63
+ }
64
+ function validateFeatureFlagFormat(featureFlag) {
65
+ if (featureFlag.enabled !== undefined && typeof featureFlag.enabled !== "boolean") {
66
+ throw new Error(`Feature flag ${featureFlag.id} has an invalid 'enabled' value.`);
67
+ }
68
+ }
69
+
70
+ exports.FeatureManager = FeatureManager;
71
+ //# sourceMappingURL=featureManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"featureManager.js","sources":["../../src/featureManager.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\nimport { TimeWindowFilter } from \"./filter/TimeWindowFilter.js\";\r\nimport { IFeatureFilter } from \"./filter/FeatureFilter.js\";\r\nimport { RequirementType } from \"./model.js\";\r\nimport { IFeatureFlagProvider } from \"./featureProvider.js\";\r\nimport { TargetingFilter } from \"./filter/TargetingFilter.js\";\r\n\r\nexport class FeatureManager {\r\n #provider: IFeatureFlagProvider;\r\n #featureFilters: Map<string, IFeatureFilter> = new Map();\r\n\r\n constructor(provider: IFeatureFlagProvider, options?: FeatureManagerOptions) {\r\n this.#provider = provider;\r\n\r\n const builtinFilters = [new TimeWindowFilter(), new TargetingFilter()];\r\n\r\n // If a custom filter shares a name with an existing filter, the custom filter overrides the existing one.\r\n for (const filter of [...builtinFilters, ...(options?.customFilters ?? [])]) {\r\n this.#featureFilters.set(filter.name, filter);\r\n }\r\n }\r\n\r\n async listFeatureNames(): Promise<string[]> {\r\n const features = await this.#provider.getFeatureFlags();\r\n const featureNameSet = new Set(features.map((feature) => feature.id));\r\n return Array.from(featureNameSet);\r\n }\r\n\r\n // If multiple feature flags are found, the first one takes precedence.\r\n async isEnabled(featureName: string, context?: unknown): Promise<boolean> {\r\n const featureFlag = await this.#provider.getFeatureFlag(featureName);\r\n if (featureFlag === undefined) {\r\n // If the feature is not found, then it is disabled.\r\n return false;\r\n }\r\n\r\n // Ensure that the feature flag is in the correct format. Feature providers should validate the feature flags, but we do it here as a safeguard.\r\n validateFeatureFlagFormat(featureFlag);\r\n\r\n if (featureFlag.enabled !== true) {\r\n // If the feature is not explicitly enabled, then it is disabled by default.\r\n return false;\r\n }\r\n\r\n const clientFilters = featureFlag.conditions?.client_filters;\r\n if (clientFilters === undefined || clientFilters.length <= 0) {\r\n // If there are no client filters, then the feature is enabled.\r\n return true;\r\n }\r\n\r\n const requirementType: RequirementType = featureFlag.conditions?.requirement_type ?? \"Any\"; // default to any.\r\n\r\n /**\r\n * While iterating through the client filters, we short-circuit the evaluation based on the requirement type.\r\n * - When requirement type is \"All\", the feature is enabled if all client filters are matched. If any client filter is not matched, the feature is disabled, otherwise it is enabled. `shortCircuitEvaluationResult` is false.\r\n * - When requirement type is \"Any\", the feature is enabled if any client filter is matched. If any client filter is matched, the feature is enabled, otherwise it is disabled. `shortCircuitEvaluationResult` is true.\r\n */\r\n const shortCircuitEvaluationResult: boolean = requirementType === \"Any\";\r\n\r\n for (const clientFilter of clientFilters) {\r\n const matchedFeatureFilter = this.#featureFilters.get(clientFilter.name);\r\n const contextWithFeatureName = { featureName, parameters: clientFilter.parameters };\r\n if (matchedFeatureFilter === undefined) {\r\n console.warn(`Feature filter ${clientFilter.name} is not found.`);\r\n return false;\r\n }\r\n if (await matchedFeatureFilter.evaluate(contextWithFeatureName, context) === shortCircuitEvaluationResult) {\r\n return shortCircuitEvaluationResult;\r\n }\r\n }\r\n\r\n // If we get here, then we have not found a client filter that matches the requirement type.\r\n return !shortCircuitEvaluationResult;\r\n }\r\n\r\n}\r\n\r\ninterface FeatureManagerOptions {\r\n customFilters?: IFeatureFilter[];\r\n}\r\n\r\nfunction validateFeatureFlagFormat(featureFlag: any): void {\r\n if (featureFlag.enabled !== undefined && typeof featureFlag.enabled !== \"boolean\") {\r\n throw new Error(`Feature flag ${featureFlag.id} has an invalid 'enabled' value.`);\r\n }\r\n}\r\n"],"names":["TimeWindowFilter","TargetingFilter"],"mappings":";;;;;AAAA;AACA;MAQa,cAAc,CAAA;AACvB,IAAA,SAAS,CAAuB;AAChC,IAAA,eAAe,GAAgC,IAAI,GAAG,EAAE,CAAC;IAEzD,WAAY,CAAA,QAA8B,EAAE,OAA+B,EAAA;AACvE,QAAA,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAE1B,MAAM,cAAc,GAAG,CAAC,IAAIA,iCAAgB,EAAE,EAAE,IAAIC,+BAAe,EAAE,CAAC,CAAC;;A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AE;AACtC,YAAA,MAAM,oBAAoB,GAAG,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;YACzE,MAAM,sBAAsB,GAAG,EAAE,WAAW,EAAE,UAAU,EAAE,YAAY,CAAC,UAAU,EAAE,CAAC;AACpF,YAAA,IAAI,oBAAoB,KAAK,SAAS,EAAE;gBACpC,OAAO,CAAC,IAAI,CAAC,CAAA,eAAA,EAAkB,YAAY,CAAC,IAAI,CAAgB,cAAA,CAAA,CAAC,CAAC;AAClE,gBAAA,OAAO,KAAK,CAAC;aAChB;AACD,YAAA,IAAI,MAAM,oBAAoB,CAAC,QAAQ,CAAC,sBAAsB,EAAE,OAAO,CAAC,KAAK,4BAA4B,EAAE;AACvG,gBAAA,OAAO,4BAA4B,CAAC;aACvC;SACJ;;QAGD,OAAO,CAAC,4BAA4B,CAAC;KACxC;AAEJ,CAAA;AAMD,SAAS,yBAAyB,CAAC,WAAgB,EAAA;AAC/C,IAAA,IAAI,WAAW,CAAC,OAAO,KAAK,SAAS,IAAI,OAAO,WAAW,CAAC,OAAO,KAAK,SAAS,EAAE;QAC/E,MAAM,IAAI,KAAK,CAAC,CAAA,aAAA,EAAgB,WAAW,CAAC,EAAE,CAAkC,gCAAA,CAAA,CAAC,CAAC;KACrF;AACL;;;;"}
@@ -0,0 +1,43 @@
1
+ 'use strict';
2
+
3
+ var model = require('./model.js');
4
+
5
+ // Copyright (c) Microsoft Corporation.
6
+ // Licensed under the MIT license.
7
+ /**
8
+ * A feature flag provider that uses a map-like configuration to provide feature flags.
9
+ */
10
+ class ConfigurationMapFeatureFlagProvider {
11
+ #configuration;
12
+ constructor(configuration) {
13
+ this.#configuration = configuration;
14
+ }
15
+ async getFeatureFlag(featureName) {
16
+ const featureConfig = this.#configuration.get(model.FEATURE_MANAGEMENT_KEY);
17
+ return featureConfig?.[model.FEATURE_FLAGS_KEY]?.findLast((feature) => feature.id === featureName);
18
+ }
19
+ async getFeatureFlags() {
20
+ const featureConfig = this.#configuration.get(model.FEATURE_MANAGEMENT_KEY);
21
+ return featureConfig?.[model.FEATURE_FLAGS_KEY] ?? [];
22
+ }
23
+ }
24
+ /**
25
+ * A feature flag provider that uses an object-like configuration to provide feature flags.
26
+ */
27
+ class ConfigurationObjectFeatureFlagProvider {
28
+ #configuration;
29
+ constructor(configuration) {
30
+ this.#configuration = configuration;
31
+ }
32
+ async getFeatureFlag(featureName) {
33
+ const featureFlags = this.#configuration[model.FEATURE_MANAGEMENT_KEY]?.[model.FEATURE_FLAGS_KEY];
34
+ return featureFlags?.findLast((feature) => feature.id === featureName);
35
+ }
36
+ async getFeatureFlags() {
37
+ return this.#configuration[model.FEATURE_MANAGEMENT_KEY]?.[model.FEATURE_FLAGS_KEY] ?? [];
38
+ }
39
+ }
40
+
41
+ exports.ConfigurationMapFeatureFlagProvider = ConfigurationMapFeatureFlagProvider;
42
+ exports.ConfigurationObjectFeatureFlagProvider = ConfigurationObjectFeatureFlagProvider;
43
+ //# sourceMappingURL=featureProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"featureProvider.js","sources":["../../src/featureProvider.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\nimport { IGettable } from \"./gettable.js\";\r\nimport { FeatureFlag, FeatureManagementConfiguration, FEATURE_MANAGEMENT_KEY, FEATURE_FLAGS_KEY } from \"./model.js\";\r\n\r\nexport interface IFeatureFlagProvider {\r\n /**\r\n * Get all feature flags.\r\n */\r\n getFeatureFlags(): Promise<FeatureFlag[]>;\r\n\r\n /**\r\n * Get a feature flag by name.\r\n * @param featureName The name of the feature flag.\r\n */\r\n getFeatureFlag(featureName: string): Promise<FeatureFlag | undefined>;\r\n}\r\n\r\n/**\r\n * A feature flag provider that uses a map-like configuration to provide feature flags.\r\n */\r\nexport class ConfigurationMapFeatureFlagProvider implements IFeatureFlagProvider {\r\n #configuration: IGettable;\r\n\r\n constructor(configuration: IGettable) {\r\n this.#configuration = configuration;\r\n }\r\n async getFeatureFlag(featureName: string): Promise<FeatureFlag | undefined> {\r\n const featureConfig = this.#configuration.get<FeatureManagementConfiguration>(FEATURE_MANAGEMENT_KEY);\r\n return featureConfig?.[FEATURE_FLAGS_KEY]?.findLast((feature) => feature.id === featureName);\r\n }\r\n\r\n async getFeatureFlags(): Promise<FeatureFlag[]> {\r\n const featureConfig = this.#configuration.get<FeatureManagementConfiguration>(FEATURE_MANAGEMENT_KEY);\r\n return featureConfig?.[FEATURE_FLAGS_KEY] ?? [];\r\n }\r\n}\r\n\r\n/**\r\n * A feature flag provider that uses an object-like configuration to provide feature flags.\r\n */\r\nexport class ConfigurationObjectFeatureFlagProvider implements IFeatureFlagProvider {\r\n #configuration: Record<string, unknown>;\r\n\r\n constructor(configuration: Record<string, unknown>) {\r\n this.#configuration = configuration;\r\n }\r\n\r\n async getFeatureFlag(featureName: string): Promise<FeatureFlag | undefined> {\r\n const featureFlags = this.#configuration[FEATURE_MANAGEMENT_KEY]?.[FEATURE_FLAGS_KEY];\r\n return featureFlags?.findLast((feature: FeatureFlag) => feature.id === featureName);\r\n }\r\n\r\n async getFeatureFlags(): Promise<FeatureFlag[]> {\r\n return this.#configuration[FEATURE_MANAGEMENT_KEY]?.[FEATURE_FLAGS_KEY] ?? [];\r\n }\r\n}\r\n"],"names":["FEATURE_MANAGEMENT_KEY","FEATURE_FLAGS_KEY"],"mappings":";;;;AAAA;AACA;AAkBA;;AAEG;MACU,mCAAmC,CAAA;AAC5C,IAAA,cAAc,CAAY;AAE1B,IAAA,WAAA,CAAY,aAAwB,EAAA;AAChC,QAAA,IAAI,CAAC,cAAc,GAAG,aAAa,CAAC;KACvC;IACD,MAAM,cAAc,CAAC,WAAmB,EAAA;QACpC,MAAM,aAAa,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAiCA,4BAAsB,CAAC,CAAC;AACtG,QAAA,OAAO,aAAa,GAAGC,uBAAiB,CAAC,EAAE,QAAQ,CAAC,CAAC,OAAO,KAAK,OAAO,CAAC,EAAE,KAAK,WAAW,CAAC,CAAC;KAChG;AAED,IAAA,MAAM,eAAe,GAAA;QACjB,MAAM,aAAa,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAiCD,4BAAsB,CAAC,CAAC;AACtG,QAAA,OAAO,aAAa,GAAGC,uBAAiB,CAAC,IAAI,EAAE,CAAC;KACnD;AACJ,CAAA;AAED;;AAEG;MACU,sCAAsC,CAAA;AAC/C,IAAA,cAAc,CAA0B;AAExC,IAAA,WAAA,CAAY,aAAsC,EAAA;AAC9C,QAAA,IAAI,CAAC,cAAc,GAAG,aAAa,CAAC;KACvC;IAED,MAAM,cAAc,CAAC,WAAmB,EAAA;AACpC,QAAA,MAAM,YAAY,GAAG,IAAI,CAAC,cAAc,CAACD,4BAAsB,CAAC,GAAGC,uBAAiB,CAAC,CAAC;AACtF,QAAA,OAAO,YAAY,EAAE,QAAQ,CAAC,CAAC,OAAoB,KAAK,OAAO,CAAC,EAAE,KAAK,WAAW,CAAC,CAAC;KACvF;AAED,IAAA,MAAM,eAAe,GAAA;AACjB,QAAA,OAAO,IAAI,CAAC,cAAc,CAACD,4BAAsB,CAAC,GAAGC,uBAAiB,CAAC,IAAI,EAAE,CAAC;KACjF;AACJ;;;;;"}
@@ -0,0 +1,138 @@
1
+ 'use strict';
2
+
3
+ // Copyright (c) Microsoft Corporation.
4
+ // Licensed under the MIT license.
5
+ class TargetingFilter {
6
+ name = "Microsoft.Targeting";
7
+ async evaluate(context, appContext) {
8
+ const { featureName, parameters } = context;
9
+ TargetingFilter.#validateParameters(parameters);
10
+ if (appContext === undefined) {
11
+ throw new Error("The app context is required for targeting filter.");
12
+ }
13
+ if (parameters.Audience.Exclusion !== undefined) {
14
+ // check if the user is in the exclusion list
15
+ if (appContext?.userId !== undefined &&
16
+ parameters.Audience.Exclusion.Users !== undefined &&
17
+ parameters.Audience.Exclusion.Users.includes(appContext.userId)) {
18
+ return false;
19
+ }
20
+ // check if the user is in a group within exclusion list
21
+ if (appContext?.groups !== undefined &&
22
+ parameters.Audience.Exclusion.Groups !== undefined) {
23
+ for (const excludedGroup of parameters.Audience.Exclusion.Groups) {
24
+ if (appContext.groups.includes(excludedGroup)) {
25
+ return false;
26
+ }
27
+ }
28
+ }
29
+ }
30
+ // check if the user is being targeted directly
31
+ if (appContext?.userId !== undefined &&
32
+ parameters.Audience.Users !== undefined &&
33
+ parameters.Audience.Users.includes(appContext.userId)) {
34
+ return true;
35
+ }
36
+ // check if the user is in a group that is being targeted
37
+ if (appContext?.groups !== undefined &&
38
+ parameters.Audience.Groups !== undefined) {
39
+ for (const group of parameters.Audience.Groups) {
40
+ if (appContext.groups.includes(group.Name)) {
41
+ const audienceContextId = constructAudienceContextId(featureName, appContext.userId, group.Name);
42
+ const rolloutPercentage = group.RolloutPercentage;
43
+ if (await TargetingFilter.#isTargeted(audienceContextId, rolloutPercentage)) {
44
+ return true;
45
+ }
46
+ }
47
+ }
48
+ }
49
+ // check if the user is being targeted by a default rollout percentage
50
+ const defaultContextId = constructAudienceContextId(featureName, appContext?.userId);
51
+ return TargetingFilter.#isTargeted(defaultContextId, parameters.Audience.DefaultRolloutPercentage);
52
+ }
53
+ static async #isTargeted(audienceContextId, rolloutPercentage) {
54
+ if (rolloutPercentage === 100) {
55
+ return true;
56
+ }
57
+ // Cryptographic hashing algorithms ensure adequate entropy across hash values.
58
+ const contextMarker = await stringToUint32(audienceContextId);
59
+ const contextPercentage = (contextMarker / 0xFFFFFFFF) * 100;
60
+ return contextPercentage < rolloutPercentage;
61
+ }
62
+ static #validateParameters(parameters) {
63
+ if (parameters.Audience.DefaultRolloutPercentage < 0 || parameters.Audience.DefaultRolloutPercentage > 100) {
64
+ throw new Error("Audience.DefaultRolloutPercentage must be a number between 0 and 100.");
65
+ }
66
+ // validate RolloutPercentage for each group
67
+ if (parameters.Audience.Groups !== undefined) {
68
+ for (const group of parameters.Audience.Groups) {
69
+ if (group.RolloutPercentage < 0 || group.RolloutPercentage > 100) {
70
+ throw new Error(`RolloutPercentage of group ${group.Name} must be a number between 0 and 100.`);
71
+ }
72
+ }
73
+ }
74
+ }
75
+ }
76
+ /**
77
+ * Constructs the context id for the audience.
78
+ * The context id is used to determine if the user is part of the audience for a feature.
79
+ * If groupName is provided, the context id is constructed as follows:
80
+ * userId + "\n" + featureName + "\n" + groupName
81
+ * Otherwise, the context id is constructed as follows:
82
+ * userId + "\n" + featureName
83
+ *
84
+ * @param featureName name of the feature
85
+ * @param userId userId from app context
86
+ * @param groupName group name from app context
87
+ * @returns a string that represents the context id for the audience
88
+ */
89
+ function constructAudienceContextId(featureName, userId, groupName) {
90
+ let contextId = `${userId ?? ""}\n${featureName}`;
91
+ if (groupName !== undefined) {
92
+ contextId += `\n${groupName}`;
93
+ }
94
+ return contextId;
95
+ }
96
+ async function stringToUint32(str) {
97
+ let crypto;
98
+ // Check for browser environment
99
+ if (typeof window !== "undefined" && window.crypto && window.crypto.subtle) {
100
+ crypto = window.crypto;
101
+ }
102
+ // Check for Node.js environment
103
+ else if (typeof global !== "undefined" && global.crypto) {
104
+ crypto = global.crypto;
105
+ }
106
+ // Fallback to native Node.js crypto module
107
+ else {
108
+ try {
109
+ if (typeof module !== "undefined" && module.exports) {
110
+ crypto = require("crypto");
111
+ }
112
+ else {
113
+ crypto = await import('crypto');
114
+ }
115
+ }
116
+ catch (error) {
117
+ console.error("Failed to load the crypto module:", error.message);
118
+ throw error;
119
+ }
120
+ }
121
+ // In the browser, use crypto.subtle.digest
122
+ if (crypto.subtle) {
123
+ const data = new TextEncoder().encode(str);
124
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
125
+ const dataView = new DataView(hashBuffer);
126
+ const uint32 = dataView.getUint32(0, true);
127
+ return uint32;
128
+ }
129
+ // In Node.js, use the crypto module's hash function
130
+ else {
131
+ const hash = crypto.createHash("sha256").update(str).digest();
132
+ const uint32 = hash.readUInt32LE(0);
133
+ return uint32;
134
+ }
135
+ }
136
+
137
+ exports.TargetingFilter = TargetingFilter;
138
+ //# sourceMappingURL=TargetingFilter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TargetingFilter.js","sources":["../../../src/filter/TargetingFilter.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\nimport { IFeatureFilter } from \"./FeatureFilter.js\";\r\n\r\ntype TargetingFilterParameters = {\r\n Audience: {\r\n DefaultRolloutPercentage: number;\r\n Users?: string[];\r\n Groups?: {\r\n Name: string;\r\n RolloutPercentage: number;\r\n }[];\r\n Exclusion?: {\r\n Users?: string[];\r\n Groups?: string[];\r\n };\r\n }\r\n}\r\n\r\ntype TargetingFilterEvaluationContext = {\r\n featureName: string;\r\n parameters: TargetingFilterParameters;\r\n}\r\n\r\ntype TargetingFilterAppContext = {\r\n userId?: string;\r\n groups?: string[];\r\n}\r\n\r\nexport class TargetingFilter implements IFeatureFilter {\r\n name: string = \"Microsoft.Targeting\";\r\n\r\n async evaluate(context: TargetingFilterEvaluationContext, appContext?: TargetingFilterAppContext): Promise<boolean> {\r\n const { featureName, parameters } = context;\r\n TargetingFilter.#validateParameters(parameters);\r\n\r\n if (appContext === undefined) {\r\n throw new Error(\"The app context is required for targeting filter.\");\r\n }\r\n\r\n if (parameters.Audience.Exclusion !== undefined) {\r\n // check if the user is in the exclusion list\r\n if (appContext?.userId !== undefined &&\r\n parameters.Audience.Exclusion.Users !== undefined &&\r\n parameters.Audience.Exclusion.Users.includes(appContext.userId)) {\r\n return false;\r\n }\r\n // check if the user is in a group within exclusion list\r\n if (appContext?.groups !== undefined &&\r\n parameters.Audience.Exclusion.Groups !== undefined) {\r\n for (const excludedGroup of parameters.Audience.Exclusion.Groups) {\r\n if (appContext.groups.includes(excludedGroup)) {\r\n return false;\r\n }\r\n }\r\n }\r\n }\r\n\r\n // check if the user is being targeted directly\r\n if (appContext?.userId !== undefined &&\r\n parameters.Audience.Users !== undefined &&\r\n parameters.Audience.Users.includes(appContext.userId)) {\r\n return true;\r\n }\r\n\r\n // check if the user is in a group that is being targeted\r\n if (appContext?.groups !== undefined &&\r\n parameters.Audience.Groups !== undefined) {\r\n for (const group of parameters.Audience.Groups) {\r\n if (appContext.groups.includes(group.Name)) {\r\n const audienceContextId = constructAudienceContextId(featureName, appContext.userId, group.Name);\r\n const rolloutPercentage = group.RolloutPercentage;\r\n if (await TargetingFilter.#isTargeted(audienceContextId, rolloutPercentage)) {\r\n return true;\r\n }\r\n }\r\n }\r\n }\r\n\r\n // check if the user is being targeted by a default rollout percentage\r\n const defaultContextId = constructAudienceContextId(featureName, appContext?.userId);\r\n return TargetingFilter.#isTargeted(defaultContextId, parameters.Audience.DefaultRolloutPercentage);\r\n }\r\n\r\n static async #isTargeted(audienceContextId: string, rolloutPercentage: number): Promise<boolean> {\r\n if (rolloutPercentage === 100) {\r\n return true;\r\n }\r\n // Cryptographic hashing algorithms ensure adequate entropy across hash values.\r\n const contextMarker = await stringToUint32(audienceContextId);\r\n const contextPercentage = (contextMarker / 0xFFFFFFFF) * 100;\r\n return contextPercentage < rolloutPercentage;\r\n }\r\n\r\n static #validateParameters(parameters: TargetingFilterParameters): void {\r\n if (parameters.Audience.DefaultRolloutPercentage < 0 || parameters.Audience.DefaultRolloutPercentage > 100) {\r\n throw new Error(\"Audience.DefaultRolloutPercentage must be a number between 0 and 100.\");\r\n }\r\n // validate RolloutPercentage for each group\r\n if (parameters.Audience.Groups !== undefined) {\r\n for (const group of parameters.Audience.Groups) {\r\n if (group.RolloutPercentage < 0 || group.RolloutPercentage > 100) {\r\n throw new Error(`RolloutPercentage of group ${group.Name} must be a number between 0 and 100.`);\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Constructs the context id for the audience.\r\n * The context id is used to determine if the user is part of the audience for a feature.\r\n * If groupName is provided, the context id is constructed as follows:\r\n * userId + \"\\n\" + featureName + \"\\n\" + groupName\r\n * Otherwise, the context id is constructed as follows:\r\n * userId + \"\\n\" + featureName\r\n *\r\n * @param featureName name of the feature\r\n * @param userId userId from app context\r\n * @param groupName group name from app context\r\n * @returns a string that represents the context id for the audience\r\n */\r\nfunction constructAudienceContextId(featureName: string, userId: string | undefined, groupName?: string) {\r\n let contextId = `${userId ?? \"\"}\\n${featureName}`;\r\n if (groupName !== undefined) {\r\n contextId += `\\n${groupName}`;\r\n }\r\n return contextId;\r\n}\r\n\r\nasync function stringToUint32(str: string): Promise<number> {\r\n let crypto;\r\n\r\n // Check for browser environment\r\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\r\n crypto = window.crypto;\r\n }\r\n // Check for Node.js environment\r\n else if (typeof global !== \"undefined\" && global.crypto) {\r\n crypto = global.crypto;\r\n }\r\n // Fallback to native Node.js crypto module\r\n else {\r\n try {\r\n if (typeof module !== \"undefined\" && module.exports) {\r\n crypto = require(\"crypto\");\r\n }\r\n else {\r\n crypto = await import(\"crypto\");\r\n }\r\n } catch (error) {\r\n console.error(\"Failed to load the crypto module:\", error.message);\r\n throw error;\r\n }\r\n }\r\n\r\n // In the browser, use crypto.subtle.digest\r\n if (crypto.subtle) {\r\n const data = new TextEncoder().encode(str);\r\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", data);\r\n const dataView = new DataView(hashBuffer);\r\n const uint32 = dataView.getUint32(0, true);\r\n return uint32;\r\n }\r\n // In Node.js, use the crypto module's hash function\r\n else {\r\n const hash = crypto.createHash(\"sha256\").update(str).digest();\r\n const uint32 = hash.readUInt32LE(0);\r\n return uint32;\r\n }\r\n}\r\n"],"names":[],"mappings":";;AAAA;AACA;MA6Ba,eAAe,CAAA;IACxB,IAAI,GAAW,qBAAqB,CAAC;AAErC,IAAA,MAAM,QAAQ,CAAC,OAAyC,EAAE,UAAsC,EAAA;AAC5F,QAAA,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,GAAG,OAAO,CAAC;AAC5C,QAAA,eAAe,CAAC,mBAAmB,CAAC,UAAU,CAAC,CAAC;AAEhD,QAAA,IAAI,UAAU,KAAK,SAAS,EA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AAA,IAAI,MAAM,CAAC,MAAM,EAAE;QACf,MAAM,IAAI,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAC3C,QAAA,MAAM,UAAU,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AAC/D,QAAA,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAAC,UAAU,CAAC,CAAC;QAC1C,MAAM,MAAM,GAAG,QAAQ,CAAC,SAAS,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;AAC3C,QAAA,OAAO,MAAM,CAAC;KACjB;;SAEI;AACD,QAAA,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC;QAC9D,MAAM,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;AACpC,QAAA,OAAO,MAAM,CAAC;KACjB;AACL;;;;"}
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+
3
+ // Copyright (c) Microsoft Corporation.
4
+ // Licensed under the MIT license.
5
+ class TimeWindowFilter {
6
+ name = "Microsoft.TimeWindow";
7
+ evaluate(context) {
8
+ const { featureName, parameters } = context;
9
+ const startTime = parameters.Start !== undefined ? new Date(parameters.Start) : undefined;
10
+ const endTime = parameters.End !== undefined ? new Date(parameters.End) : undefined;
11
+ if (startTime === undefined && endTime === undefined) {
12
+ // If neither start nor end time is specified, then the filter is not applicable.
13
+ console.warn(`The ${this.name} feature filter is not valid for feature ${featureName}. It must specify either 'Start', 'End', or both.`);
14
+ return false;
15
+ }
16
+ const now = new Date();
17
+ return (startTime === undefined || startTime <= now) && (endTime === undefined || now < endTime);
18
+ }
19
+ }
20
+
21
+ exports.TimeWindowFilter = TimeWindowFilter;
22
+ //# sourceMappingURL=TimeWindowFilter.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"TimeWindowFilter.js","sourceRoot":"","sources":["../../src/filter/TimeWindowFilter.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAelC,MAAM,OAAO,gBAAgB;IACzB,IAAI,GAAW,sBAAsB,CAAC;IAEtC,QAAQ,CAAC,OAA0C;QAC/C,MAAM,EAAC,WAAW,EAAE,UAAU,EAAC,GAAG,OAAO,CAAC;QAC1C,MAAM,SAAS,GAAG,UAAU,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC1F,MAAM,OAAO,GAAG,UAAU,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAEpF,IAAI,SAAS,KAAK,SAAS,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;YACnD,iFAAiF;YACjF,OAAO,CAAC,IAAI,CAAC,OAAO,IAAI,CAAC,IAAI,4CAA4C,WAAW,mDAAmD,CAAC,CAAC;YACzI,OAAO,KAAK,CAAC;QACjB,CAAC;QACD,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,OAAO,CAAC,SAAS,KAAK,SAAS,IAAI,SAAS,IAAI,GAAG,CAAC,IAAI,CAAC,OAAO,KAAK,SAAS,IAAI,GAAG,GAAG,OAAO,CAAC,CAAC;IACrG,CAAC;CACJ","sourcesContent":["// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\nimport { IFeatureFilter } from \"./FeatureFilter\";\r\n\r\n// [Start, End)\r\ntype TimeWindowParameters = {\r\n Start?: string;\r\n End?: string;\r\n}\r\n\r\ntype TimeWindowFilterEvaluationContext = {\r\n featureName: string;\r\n parameters: TimeWindowParameters;\r\n}\r\n\r\nexport class TimeWindowFilter implements IFeatureFilter {\r\n name: string = \"Microsoft.TimeWindow\";\r\n\r\n evaluate(context: TimeWindowFilterEvaluationContext): boolean {\r\n const {featureName, parameters} = context;\r\n const startTime = parameters.Start !== undefined ? new Date(parameters.Start) : undefined;\r\n const endTime = parameters.End !== undefined ? new Date(parameters.End) : undefined;\r\n\r\n if (startTime === undefined && endTime === undefined) {\r\n // If neither start nor end time is specified, then the filter is not applicable.\r\n console.warn(`The ${this.name} feature filter is not valid for feature ${featureName}. It must specify either 'Start', 'End', or both.`);\r\n return false;\r\n }\r\n const now = new Date();\r\n return (startTime === undefined || startTime <= now) && (endTime === undefined || now < endTime);\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"TimeWindowFilter.js","sources":["../../../src/filter/TimeWindowFilter.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\nimport { IFeatureFilter } from \"./FeatureFilter.js\";\r\n\r\n// [Start, End)\r\ntype TimeWindowParameters = {\r\n Start?: string;\r\n End?: string;\r\n}\r\n\r\ntype TimeWindowFilterEvaluationContext = {\r\n featureName: string;\r\n parameters: TimeWindowParameters;\r\n}\r\n\r\nexport class TimeWindowFilter implements IFeatureFilter {\r\n name: string = \"Microsoft.TimeWindow\";\r\n\r\n evaluate(context: TimeWindowFilterEvaluationContext): boolean {\r\n const {featureName, parameters} = context;\r\n const startTime = parameters.Start !== undefined ? new Date(parameters.Start) : undefined;\r\n const endTime = parameters.End !== undefined ? new Date(parameters.End) : undefined;\r\n\r\n if (startTime === undefined && endTime === undefined) {\r\n // If neither start nor end time is specified, then the filter is not applicable.\r\n console.warn(`The ${this.name} feature filter is not valid for feature ${featureName}. It must specify either 'Start', 'End', or both.`);\r\n return false;\r\n }\r\n const now = new Date();\r\n return (startTime === undefined || startTime <= now) && (endTime === undefined || now < endTime);\r\n }\r\n}\r\n"],"names":[],"mappings":";;AAAA;AACA;MAea,gBAAgB,CAAA;IACzB,IAAI,GAAW,sBAAsB,CAAC;AAEtC,IAAA,QAAQ,CAAC,OAA0C,EAAA;AAC/C,QAAA,MAAM,EAAC,WAAW,EAAE,UAAU,EAAC,GAAG,OAAO,CAAC;QAC1C,MAAM,SAAS,GAAG,UAAU,CAAC,KAAK,KAAK,SAAS,GAAG,IAAI,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,SAAS,CAAC;QAC1F,MAAM,OAAO,GAAG,UAAU,CAAC,GAAG,KAAK,SAAS,GAAG,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC;QAEpF,IAAI,SAAS,KAAK,SAAS,IAAI,OAAO,KAAK,SAAS,EAAE;;YAElD,OAAO,CAAC,IAAI,CAAC,CAAO,IAAA,EAAA,IAAI,CAAC,IAAI,CAA4C,yCAAA,EAAA,WAAW,CAAmD,iDAAA,CAAA,CAAC,CAAC;AACzI,YAAA,OAAO,KAAK,CAAC;SAChB;AACD,QAAA,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;AACvB,QAAA,OAAO,CAAC,SAAS,KAAK,SAAS,IAAI,SAAS,IAAI,GAAG,MAAM,OAAO,KAAK,SAAS,IAAI,GAAG,GAAG,OAAO,CAAC,CAAC;KACpG;AACJ;;;;"}
@@ -0,0 +1,13 @@
1
+ 'use strict';
2
+
3
+ var featureManager = require('./featureManager.js');
4
+ var featureProvider = require('./featureProvider.js');
5
+ var version = require('./version.js');
6
+
7
+
8
+
9
+ exports.FeatureManager = featureManager.FeatureManager;
10
+ exports.ConfigurationMapFeatureFlagProvider = featureProvider.ConfigurationMapFeatureFlagProvider;
11
+ exports.ConfigurationObjectFeatureFlagProvider = featureProvider.ConfigurationObjectFeatureFlagProvider;
12
+ exports.VERSION = version.VERSION;
13
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;"}
@@ -0,0 +1,12 @@
1
+ 'use strict';
2
+
3
+ // Copyright (c) Microsoft Corporation.
4
+ // Licensed under the MIT license.
5
+ // Feature Management Section fed into feature manager.
6
+ // Converted from https://github.com/Azure/AppConfiguration/blob/main/docs/FeatureManagement/FeatureManagement.v1.0.0.schema.json
7
+ const FEATURE_MANAGEMENT_KEY = "feature_management";
8
+ const FEATURE_FLAGS_KEY = "feature_flags";
9
+
10
+ exports.FEATURE_FLAGS_KEY = FEATURE_FLAGS_KEY;
11
+ exports.FEATURE_MANAGEMENT_KEY = FEATURE_MANAGEMENT_KEY;
12
+ //# sourceMappingURL=model.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.js","sources":["../../src/model.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n// Converted from:\r\n// https://github.com/Azure/AppConfiguration/blob/6e544296a5607f922a423df165f60801717c7800/docs/FeatureManagement/FeatureFlag.v2.0.0.schema.json\r\n\r\n/**\r\n * A feature flag is a named property that can be toggled to enable or disable some feature of an application.\r\n */\r\nexport interface FeatureFlag {\r\n /**\r\n * An ID used to uniquely identify and reference the feature.\r\n */\r\n id: string;\r\n /**\r\n * A description of the feature.\r\n */\r\n description?: string;\r\n /**\r\n * A display name for the feature to use for display rather than the ID.\r\n */\r\n display_name?: string;\r\n /**\r\n * A feature is OFF if enabled is false. If enabled is true, then the feature is ON if there are no conditions (null or empty) or if the conditions are satisfied.\r\n */\r\n enabled?: boolean;\r\n /**\r\n * The declaration of conditions used to dynamically enable the feature.\r\n */\r\n conditions?: FeatureEnablementConditions;\r\n /**\r\n * The list of variants defined for this feature. A variant represents a configuration value of a feature flag that can be a string, a number, a boolean, or a JSON object.\r\n */\r\n variants?: Variant[];\r\n /**\r\n * Determines how variants should be allocated for the feature to various users.\r\n */\r\n allocation?: VariantAllocation;\r\n /**\r\n * The declaration of options used to configure telemetry for this feature.\r\n */\r\n telemetry?: TelemetryOptions\r\n}\r\n\r\n/**\r\n* The declaration of conditions used to dynamically enable the feature\r\n*/\r\ninterface FeatureEnablementConditions {\r\n /**\r\n * Determines whether any or all registered client filters must be evaluated as true for the feature to be considered enabled.\r\n */\r\n requirement_type?: RequirementType;\r\n /**\r\n * Filters that must run on the client and be evaluated as true for the feature to be considered enabled.\r\n */\r\n client_filters?: ClientFilter[];\r\n}\r\n\r\nexport type RequirementType = \"Any\" | \"All\";\r\n\r\ninterface ClientFilter {\r\n /**\r\n * The name used to refer to a client filter.\r\n */\r\n name: string;\r\n /**\r\n * Parameters for a given client filter. A client filter can require any set of parameters of any type.\r\n */\r\n parameters?: Record<string, unknown>;\r\n}\r\n\r\ninterface Variant {\r\n /**\r\n * The name used to refer to a feature variant.\r\n */\r\n name: string;\r\n /**\r\n * The configuration value for this feature variant.\r\n */\r\n configuration_value?: unknown;\r\n /**\r\n * The path to a configuration section used as the configuration value for this feature variant.\r\n */\r\n configuration_reference?: string;\r\n /**\r\n * Overrides the enabled state of the feature if the given variant is assigned. Does not override the state if value is None.\r\n */\r\n status_override?: \"None\" | \"Enabled\" | \"Disabled\";\r\n}\r\n\r\n/**\r\n* Determines how variants should be allocated for the feature to various users.\r\n*/\r\ninterface VariantAllocation {\r\n /**\r\n * Specifies which variant should be used when the feature is considered disabled.\r\n */\r\n default_when_disabled?: string;\r\n /**\r\n * Specifies which variant should be used when the feature is considered enabled and no other allocation rules are applicable.\r\n */\r\n default_when_enabled?: string;\r\n /**\r\n * A list of objects, each containing a variant name and list of users for whom that variant should be used.\r\n */\r\n user?: UserAllocation[];\r\n /**\r\n * A list of objects, each containing a variant name and list of groups for which that variant should be used.\r\n */\r\n group?: GroupAllocation[];\r\n /**\r\n * A list of objects, each containing a variant name and percentage range for which that variant should be used.\r\n */\r\n percentile?: PercentileAllocation[]\r\n /**\r\n * The value percentile calculations are based on. The calculated percentile is consistent across features for a given user if the same nonempty seed is used.\r\n */\r\n seed?: string;\r\n}\r\n\r\ninterface UserAllocation {\r\n /**\r\n * The name of the variant to use if the user allocation matches the current user.\r\n */\r\n variant: string;\r\n /**\r\n * Collection of users where if any match the current user, the variant specified in the user allocation is used.\r\n */\r\n users: string[];\r\n}\r\n\r\ninterface GroupAllocation {\r\n /**\r\n * The name of the variant to use if the group allocation matches a group the current user is in.\r\n */\r\n variant: string;\r\n /**\r\n * Collection of groups where if the current user is in any of these groups, the variant specified in the group allocation is used.\r\n */\r\n groups: string[];\r\n}\r\n\r\ninterface PercentileAllocation {\r\n /**\r\n * The name of the variant to use if the calculated percentile for the current user falls in the provided range.\r\n */\r\n variant: string;\r\n /**\r\n * The lower end of the percentage range for which this variant will be used.\r\n */\r\n from: number;\r\n /**\r\n * The upper end of the percentage range for which this variant will be used.\r\n */\r\n to: number;\r\n}\r\n\r\n/**\r\n* The declaration of options used to configure telemetry for this feature.\r\n*/\r\ninterface TelemetryOptions {\r\n /**\r\n * Indicates if telemetry is enabled.\r\n */\r\n enabled?: boolean;\r\n /**\r\n * A container for metadata that should be bundled with flag telemetry.\r\n */\r\n metadata?: Record<string, string>;\r\n}\r\n\r\n// Feature Management Section fed into feature manager.\r\n// Converted from https://github.com/Azure/AppConfiguration/blob/main/docs/FeatureManagement/FeatureManagement.v1.0.0.schema.json\r\n\r\nexport const FEATURE_MANAGEMENT_KEY = \"feature_management\";\r\nexport const FEATURE_FLAGS_KEY = \"feature_flags\";\r\n\r\nexport interface FeatureManagementConfiguration {\r\n feature_management: FeatureManagement\r\n}\r\n\r\n/**\r\n * Declares feature management configuration.\r\n */\r\nexport interface FeatureManagement {\r\n feature_flags: FeatureFlag[];\r\n}\r\n"],"names":[],"mappings":";;AAAA;AACA;AA0KA;AACA;AAEO,MAAM,sBAAsB,GAAG,qBAAqB;AACpD,MAAM,iBAAiB,GAAG;;;;;"}
@@ -0,0 +1,8 @@
1
+ 'use strict';
2
+
3
+ // Copyright (c) Microsoft Corporation.
4
+ // Licensed under the MIT license.
5
+ const VERSION = "1.0.0";
6
+
7
+ exports.VERSION = VERSION;
8
+ //# sourceMappingURL=version.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version.js","sources":["../../src/version.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport const VERSION = \"1.0.0\";\n"],"names":[],"mappings":";;AAAA;AACA;AAEO,MAAM,OAAO,GAAG;;;;"}
@@ -1,9 +1,9 @@
1
+ import { TimeWindowFilter } from './filter/TimeWindowFilter.js';
2
+ import { TargetingFilter } from './filter/TargetingFilter.js';
3
+
1
4
  // Copyright (c) Microsoft Corporation.
2
5
  // Licensed under the MIT license.
3
- import { TimeWindowFilter } from "./filter/TimeWindowFilter";
4
- import { RequirementType } from "./model";
5
- import { TargetingFilter } from "./filter/TargetingFilter";
6
- export class FeatureManager {
6
+ class FeatureManager {
7
7
  #provider;
8
8
  #featureFilters = new Map();
9
9
  constructor(provider, options) {
@@ -26,8 +26,10 @@ export class FeatureManager {
26
26
  // If the feature is not found, then it is disabled.
27
27
  return false;
28
28
  }
29
- if (featureFlag.enabled === false) {
30
- // If the feature is explicitly disabled, then it is disabled.
29
+ // Ensure that the feature flag is in the correct format. Feature providers should validate the feature flags, but we do it here as a safeguard.
30
+ validateFeatureFlagFormat(featureFlag);
31
+ if (featureFlag.enabled !== true) {
32
+ // If the feature is not explicitly enabled, then it is disabled by default.
31
33
  return false;
32
34
  }
33
35
  const clientFilters = featureFlag.conditions?.client_filters;
@@ -35,13 +37,13 @@ export class FeatureManager {
35
37
  // If there are no client filters, then the feature is enabled.
36
38
  return true;
37
39
  }
38
- const requirementType = featureFlag.conditions?.requirement_type ?? RequirementType.Any; // default to any.
40
+ const requirementType = featureFlag.conditions?.requirement_type ?? "Any"; // default to any.
39
41
  /**
40
42
  * While iterating through the client filters, we short-circuit the evaluation based on the requirement type.
41
43
  * - When requirement type is "All", the feature is enabled if all client filters are matched. If any client filter is not matched, the feature is disabled, otherwise it is enabled. `shortCircuitEvaluationResult` is false.
42
44
  * - When requirement type is "Any", the feature is enabled if any client filter is matched. If any client filter is matched, the feature is enabled, otherwise it is disabled. `shortCircuitEvaluationResult` is true.
43
45
  */
44
- const shortCircuitEvaluationResult = requirementType === RequirementType.Any;
46
+ const shortCircuitEvaluationResult = requirementType === "Any";
45
47
  for (const clientFilter of clientFilters) {
46
48
  const matchedFeatureFilter = this.#featureFilters.get(clientFilter.name);
47
49
  const contextWithFeatureName = { featureName, parameters: clientFilter.parameters };
@@ -57,4 +59,11 @@ export class FeatureManager {
57
59
  return !shortCircuitEvaluationResult;
58
60
  }
59
61
  }
60
- //# sourceMappingURL=featureManager.js.map
62
+ function validateFeatureFlagFormat(featureFlag) {
63
+ if (featureFlag.enabled !== undefined && typeof featureFlag.enabled !== "boolean") {
64
+ throw new Error(`Feature flag ${featureFlag.id} has an invalid 'enabled' value.`);
65
+ }
66
+ }
67
+
68
+ export { FeatureManager };
69
+ //# sourceMappingURL=featureManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"featureManager.js","sources":["../../src/featureManager.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\nimport { TimeWindowFilter } from \"./filter/TimeWindowFilter.js\";\r\nimport { IFeatureFilter } from \"./filter/FeatureFilter.js\";\r\nimport { RequirementType } from \"./model.js\";\r\nimport { IFeatureFlagProvider } from \"./featureProvider.js\";\r\nimport { TargetingFilter } from \"./filter/TargetingFilter.js\";\r\n\r\nexport class FeatureManager {\r\n #provider: IFeatureFlagProvider;\r\n #featureFilters: Map<string, IFeatureFilter> = new Map();\r\n\r\n constructor(provider: IFeatureFlagProvider, options?: FeatureManagerOptions) {\r\n this.#provider = provider;\r\n\r\n const builtinFilters = [new TimeWindowFilter(), new TargetingFilter()];\r\n\r\n // If a custom filter shares a name with an existing filter, the custom filter overrides the existing one.\r\n for (const filter of [...builtinFilters, ...(options?.customFilters ?? [])]) {\r\n this.#featureFilters.set(filter.name, filter);\r\n }\r\n }\r\n\r\n async listFeatureNames(): Promise<string[]> {\r\n const features = await this.#provider.getFeatureFlags();\r\n const featureNameSet = new Set(features.map((feature) => feature.id));\r\n return Array.from(featureNameSet);\r\n }\r\n\r\n // If multiple feature flags are found, the first one takes precedence.\r\n async isEnabled(featureName: string, context?: unknown): Promise<boolean> {\r\n const featureFlag = await this.#provider.getFeatureFlag(featureName);\r\n if (featureFlag === undefined) {\r\n // If the feature is not found, then it is disabled.\r\n return false;\r\n }\r\n\r\n // Ensure that the feature flag is in the correct format. Feature providers should validate the feature flags, but we do it here as a safeguard.\r\n validateFeatureFlagFormat(featureFlag);\r\n\r\n if (featureFlag.enabled !== true) {\r\n // If the feature is not explicitly enabled, then it is disabled by default.\r\n return false;\r\n }\r\n\r\n const clientFilters = featureFlag.conditions?.client_filters;\r\n if (clientFilters === undefined || clientFilters.length <= 0) {\r\n // If there are no client filters, then the feature is enabled.\r\n return true;\r\n }\r\n\r\n const requirementType: RequirementType = featureFlag.conditions?.requirement_type ?? \"Any\"; // default to any.\r\n\r\n /**\r\n * While iterating through the client filters, we short-circuit the evaluation based on the requirement type.\r\n * - When requirement type is \"All\", the feature is enabled if all client filters are matched. If any client filter is not matched, the feature is disabled, otherwise it is enabled. `shortCircuitEvaluationResult` is false.\r\n * - When requirement type is \"Any\", the feature is enabled if any client filter is matched. If any client filter is matched, the feature is enabled, otherwise it is disabled. `shortCircuitEvaluationResult` is true.\r\n */\r\n const shortCircuitEvaluationResult: boolean = requirementType === \"Any\";\r\n\r\n for (const clientFilter of clientFilters) {\r\n const matchedFeatureFilter = this.#featureFilters.get(clientFilter.name);\r\n const contextWithFeatureName = { featureName, parameters: clientFilter.parameters };\r\n if (matchedFeatureFilter === undefined) {\r\n console.warn(`Feature filter ${clientFilter.name} is not found.`);\r\n return false;\r\n }\r\n if (await matchedFeatureFilter.evaluate(contextWithFeatureName, context) === shortCircuitEvaluationResult) {\r\n return shortCircuitEvaluationResult;\r\n }\r\n }\r\n\r\n // If we get here, then we have not found a client filter that matches the requirement type.\r\n return !shortCircuitEvaluationResult;\r\n }\r\n\r\n}\r\n\r\ninterface FeatureManagerOptions {\r\n customFilters?: IFeatureFilter[];\r\n}\r\n\r\nfunction validateFeatureFlagFormat(featureFlag: any): void {\r\n if (featureFlag.enabled !== undefined && typeof featureFlag.enabled !== \"boolean\") {\r\n throw new Error(`Feature flag ${featureFlag.id} has an invalid 'enabled' value.`);\r\n }\r\n}\r\n"],"names":[],"mappings":";;;AAAA;AACA;MAQa,cAAc,CAAA;AACvB,IAAA,SAAS,CAAuB;AAChC,IAAA,eAAe,GAAgC,IAAI,GAAG,EAAE,CAAC;IAEzD,WAAY,CAAA,QAA8B,EAAE,OAA+B,EAAA;AACvE,QAAA,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAE1B,MAAM,cAAc,GAAG,CAAC,IAAI,gBAAgB,EAAE,EAAE,IAAI,eAAe,EAAE,CAAC,CAAC;;AAGvE,QAAA,KAAK,MAAM,MAAM,IAAI,CAAC,GAAG,cAAc,EAAE,IAAI,OAAO,EAAE,aAAa,IAAI,EAAE,CAAC,CAAC,EAAE;YACzE,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;SACjD;KACJ;AAED,IAAA,MAAM,gBAAgB,GAAA;QAClB,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,eAAe,EAAE,CAAC;AACxD,QAAA,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,KAAK,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC;AACtE,QAAA,OAAO,KAAK,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;KACrC;;AAGD,IAAA,MAAM,SAAS,CAAC,WAAmB,EAAE,OAAiB,EAAA;QAClD,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC;AACrE,QAAA,IAAI,WAAW,KAAK,SAAS,EAAE;;AAE3B,YAAA,OAAO,KAAK,CAAC;SAChB;;QAGD,yBAAyB,CAAC,WAAW,CAAC,CAAC;AA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AAkC,gCAAA,CAAA,CAAC,CAAC;KACrF;AACL;;;;"}
@@ -1,17 +1,18 @@
1
+ import { FEATURE_MANAGEMENT_KEY, FEATURE_FLAGS_KEY } from './model.js';
2
+
1
3
  // Copyright (c) Microsoft Corporation.
2
4
  // Licensed under the MIT license.
3
- import { FEATURE_MANAGEMENT_KEY, FEATURE_FLAGS_KEY } from "./model";
4
5
  /**
5
6
  * A feature flag provider that uses a map-like configuration to provide feature flags.
6
7
  */
7
- export class ConfigurationMapFeatureFlagProvider {
8
+ class ConfigurationMapFeatureFlagProvider {
8
9
  #configuration;
9
10
  constructor(configuration) {
10
11
  this.#configuration = configuration;
11
12
  }
12
13
  async getFeatureFlag(featureName) {
13
14
  const featureConfig = this.#configuration.get(FEATURE_MANAGEMENT_KEY);
14
- return featureConfig?.[FEATURE_FLAGS_KEY]?.find((feature) => feature.id === featureName);
15
+ return featureConfig?.[FEATURE_FLAGS_KEY]?.findLast((feature) => feature.id === featureName);
15
16
  }
16
17
  async getFeatureFlags() {
17
18
  const featureConfig = this.#configuration.get(FEATURE_MANAGEMENT_KEY);
@@ -21,17 +22,19 @@ export class ConfigurationMapFeatureFlagProvider {
21
22
  /**
22
23
  * A feature flag provider that uses an object-like configuration to provide feature flags.
23
24
  */
24
- export class ConfigurationObjectFeatureFlagProvider {
25
+ class ConfigurationObjectFeatureFlagProvider {
25
26
  #configuration;
26
27
  constructor(configuration) {
27
28
  this.#configuration = configuration;
28
29
  }
29
30
  async getFeatureFlag(featureName) {
30
31
  const featureFlags = this.#configuration[FEATURE_MANAGEMENT_KEY]?.[FEATURE_FLAGS_KEY];
31
- return featureFlags?.find((feature) => feature.id === featureName);
32
+ return featureFlags?.findLast((feature) => feature.id === featureName);
32
33
  }
33
34
  async getFeatureFlags() {
34
35
  return this.#configuration[FEATURE_MANAGEMENT_KEY]?.[FEATURE_FLAGS_KEY] ?? [];
35
36
  }
36
37
  }
37
- //# sourceMappingURL=featureProvider.js.map
38
+
39
+ export { ConfigurationMapFeatureFlagProvider, ConfigurationObjectFeatureFlagProvider };
40
+ //# sourceMappingURL=featureProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"featureProvider.js","sources":["../../src/featureProvider.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\nimport { IGettable } from \"./gettable.js\";\r\nimport { FeatureFlag, FeatureManagementConfiguration, FEATURE_MANAGEMENT_KEY, FEATURE_FLAGS_KEY } from \"./model.js\";\r\n\r\nexport interface IFeatureFlagProvider {\r\n /**\r\n * Get all feature flags.\r\n */\r\n getFeatureFlags(): Promise<FeatureFlag[]>;\r\n\r\n /**\r\n * Get a feature flag by name.\r\n * @param featureName The name of the feature flag.\r\n */\r\n getFeatureFlag(featureName: string): Promise<FeatureFlag | undefined>;\r\n}\r\n\r\n/**\r\n * A feature flag provider that uses a map-like configuration to provide feature flags.\r\n */\r\nexport class ConfigurationMapFeatureFlagProvider implements IFeatureFlagProvider {\r\n #configuration: IGettable;\r\n\r\n constructor(configuration: IGettable) {\r\n this.#configuration = configuration;\r\n }\r\n async getFeatureFlag(featureName: string): Promise<FeatureFlag | undefined> {\r\n const featureConfig = this.#configuration.get<FeatureManagementConfiguration>(FEATURE_MANAGEMENT_KEY);\r\n return featureConfig?.[FEATURE_FLAGS_KEY]?.findLast((feature) => feature.id === featureName);\r\n }\r\n\r\n async getFeatureFlags(): Promise<FeatureFlag[]> {\r\n const featureConfig = this.#configuration.get<FeatureManagementConfiguration>(FEATURE_MANAGEMENT_KEY);\r\n return featureConfig?.[FEATURE_FLAGS_KEY] ?? [];\r\n }\r\n}\r\n\r\n/**\r\n * A feature flag provider that uses an object-like configuration to provide feature flags.\r\n */\r\nexport class ConfigurationObjectFeatureFlagProvider implements IFeatureFlagProvider {\r\n #configuration: Record<string, unknown>;\r\n\r\n constructor(configuration: Record<string, unknown>) {\r\n this.#configuration = configuration;\r\n }\r\n\r\n async getFeatureFlag(featureName: string): Promise<FeatureFlag | undefined> {\r\n const featureFlags = this.#configuration[FEATURE_MANAGEMENT_KEY]?.[FEATURE_FLAGS_KEY];\r\n return featureFlags?.findLast((feature: FeatureFlag) => feature.id === featureName);\r\n }\r\n\r\n async getFeatureFlags(): Promise<FeatureFlag[]> {\r\n return this.#configuration[FEATURE_MANAGEMENT_KEY]?.[FEATURE_FLAGS_KEY] ?? [];\r\n }\r\n}\r\n"],"names":[],"mappings":";;AAAA;AACA;AAkBA;;AAEG;MACU,mCAAmC,CAAA;AAC5C,IAAA,cAAc,CAAY;AAE1B,IAAA,WAAA,CAAY,aAAwB,EAAA;AAChC,QAAA,IAAI,CAAC,cAAc,GAAG,aAAa,CAAC;KACvC;IACD,MAAM,cAAc,CAAC,WAAmB,EAAA;QACpC,MAAM,aAAa,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAiC,sBAAsB,CAAC,CAAC;AACtG,QAAA,OAAO,aAAa,GAAG,iBAAiB,CAAC,EAAE,QAAQ,CAAC,CAAC,OAAO,KAAK,OAAO,CAAC,EAAE,KAAK,WAAW,CAAC,CAAC;KAChG;AAED,IAAA,MAAM,eAAe,GAAA;QACjB,MAAM,aAAa,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAiC,sBAAsB,CAAC,CAAC;AACtG,QAAA,OAAO,aAAa,GAAG,iBAAiB,CAAC,IAAI,EAAE,CAAC;KACnD;AACJ,CAAA;AAED;;AAEG;MACU,sCAAsC,CAAA;AAC/C,IAAA,cAAc,CAA0B;AAExC,IAAA,WAAA,CAAY,aAAsC,EAAA;AAC9C,QAAA,IAAI,CAAC,cAAc,GAAG,aAAa,CAAC;KACvC;IAED,MAAM,cAAc,CAAC,WAAmB,EAAA;AACpC,QAAA,MAAM,YAAY,GAAG,IAAI,CAAC,cAAc,CAAC,sBAAsB,CAAC,GAAG,iBAAiB,CAAC,CAAC;AACtF,QAAA,OAAO,YAAY,EAAE,QAAQ,CAAC,CAAC,OAAoB,KAAK,OAAO,CAAC,EAAE,KAAK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