@burdenoff/be-sdk 2026.1202.6 → 2026.1202.8
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.
- package/dist/feature-flags/index.d.ts +2 -2
- package/dist/feature-flags/index.js +1 -1
- package/dist/{feature-flags-CP1KRgwD.js → feature-flags-o-7MKGg8.js} +73 -9
- package/dist/feature-flags-o-7MKGg8.js.map +1 -0
- package/dist/{index-DM5zS9TT.d.ts → index-DIvauo52.d.ts} +11 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +6 -3
- package/dist/feature-flags-CP1KRgwD.js.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as FeatureFlagProvider, c as
|
|
2
|
-
export { type EvaluationContext, FeatureFlagProvider, type FeatureFlagProviderConfig, type FlagEvaluation, type FlagType, type GatedOperationType, type OperationsFlagGatePluginOptions, type ResolutionDetails, createOperationsFlagGatePlugin };
|
|
1
|
+
import { a as FeatureFlagProvider, c as FeatureFlagProviderConfig, d as ResolutionDetails, i as createOperationsFlagGatePlugin, l as FlagEvaluation, n as GatedOperationType, o as CacheTtlOverride, r as OperationsFlagGatePluginOptions, s as EvaluationContext, u as FlagType } from "../index-DIvauo52.js";
|
|
2
|
+
export { type CacheTtlOverride, type EvaluationContext, FeatureFlagProvider, type FeatureFlagProviderConfig, type FlagEvaluation, type FlagType, type GatedOperationType, type OperationsFlagGatePluginOptions, type ResolutionDetails, createOperationsFlagGatePlugin };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as createOperationsFlagGatePlugin, r as FeatureFlagProvider } from "../feature-flags-
|
|
1
|
+
import { n as createOperationsFlagGatePlugin, r as FeatureFlagProvider } from "../feature-flags-o-7MKGg8.js";
|
|
2
2
|
|
|
3
3
|
export { FeatureFlagProvider, createOperationsFlagGatePlugin };
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
|
@@ -10,7 +10,8 @@ import { GraphQLError, Kind } from "graphql";
|
|
|
10
10
|
*
|
|
11
11
|
* Server-side feature flag provider for backend services.
|
|
12
12
|
* Evaluates flags via the global-tenant-svc GraphQL API through the internal gateway.
|
|
13
|
-
* Supports in-memory caching with configurable TTL
|
|
13
|
+
* Supports in-memory caching with a configurable TTL, and shorter TTLs for
|
|
14
|
+
* chosen key prefixes (`cacheTtlOverrides`).
|
|
14
15
|
*
|
|
15
16
|
* @module feature-flags/provider
|
|
16
17
|
* @category FeatureFlags
|
|
@@ -22,6 +23,8 @@ import { GraphQLError, Kind } from "graphql";
|
|
|
22
23
|
* const provider = new FeatureFlagProvider({
|
|
23
24
|
* gatewayUrl: 'http://global-int-gateway:4000/global/graphql',
|
|
24
25
|
* cacheTtlSeconds: 60,
|
|
26
|
+
* // Kill switches: refetch `fluidgrids.rpa.*` after 10 s, every other key after 60 s.
|
|
27
|
+
* cacheTtlOverrides: [{ prefix: 'fluidgrids.rpa.', ttlSeconds: 10 }],
|
|
25
28
|
* });
|
|
26
29
|
*
|
|
27
30
|
* const isEnabled = await provider.resolveBoolean('calendar.recurring-events', false, {
|
|
@@ -34,6 +37,23 @@ import { GraphQLError, Kind } from "graphql";
|
|
|
34
37
|
* console.log(isEnabled.reason); // 'TARGETING_MATCH', 'DEFAULT', etc.
|
|
35
38
|
* ```
|
|
36
39
|
*/
|
|
40
|
+
/**
|
|
41
|
+
* Keep only usable overrides (non-empty prefix, positive finite TTL) and sort
|
|
42
|
+
* them longest prefix first, so the first match is the most specific one.
|
|
43
|
+
*/
|
|
44
|
+
function normalizeTtlOverrides(overrides) {
|
|
45
|
+
if (!overrides) return [];
|
|
46
|
+
const valid = [];
|
|
47
|
+
for (const override of overrides) {
|
|
48
|
+
if (typeof override.prefix !== "string" || override.prefix.length === 0) continue;
|
|
49
|
+
if (typeof override.ttlSeconds !== "number" || !Number.isFinite(override.ttlSeconds) || override.ttlSeconds <= 0) continue;
|
|
50
|
+
valid.push({
|
|
51
|
+
prefix: override.prefix,
|
|
52
|
+
ttlMs: override.ttlSeconds * 1e3
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
return valid.sort((a, b) => b.prefix.length - a.prefix.length);
|
|
56
|
+
}
|
|
37
57
|
const EVALUATE_QUERY = `
|
|
38
58
|
query EvaluateFeatureFlags($input: EvaluateFeatureFlagsInput!) {
|
|
39
59
|
evaluateFeatureFlags(input: $input) {
|
|
@@ -64,6 +84,13 @@ function readPositiveIntEnv(name, fallback) {
|
|
|
64
84
|
var FeatureFlagProvider = class {
|
|
65
85
|
gatewayUrl;
|
|
66
86
|
cacheTtlMs;
|
|
87
|
+
/** Per-prefix TTLs, longest prefix first (empty when none are configured). */
|
|
88
|
+
ttlOverrides;
|
|
89
|
+
/**
|
|
90
|
+
* The shortest override TTL (`Infinity` when none is configured): the limit
|
|
91
|
+
* for an answer that covers every flag.
|
|
92
|
+
*/
|
|
93
|
+
shortestOverrideTtlMs;
|
|
67
94
|
failureTtlMs;
|
|
68
95
|
requestTimeoutMs;
|
|
69
96
|
serviceToken;
|
|
@@ -74,6 +101,8 @@ var FeatureFlagProvider = class {
|
|
|
74
101
|
constructor(config) {
|
|
75
102
|
this.gatewayUrl = config.gatewayUrl;
|
|
76
103
|
this.cacheTtlMs = (config.cacheTtlSeconds ?? 60) * 1e3;
|
|
104
|
+
this.ttlOverrides = normalizeTtlOverrides(config.cacheTtlOverrides);
|
|
105
|
+
this.shortestOverrideTtlMs = this.ttlOverrides.reduce((shortest, o) => Math.min(shortest, o.ttlMs), Number.POSITIVE_INFINITY);
|
|
77
106
|
this.requestTimeoutMs = config.requestTimeoutMs ?? readPositiveIntEnv("FEATURE_FLAG_REQUEST_TIMEOUT_MS", 3e3);
|
|
78
107
|
this.failureTtlMs = (config.failureTtlSeconds ?? readPositiveIntEnv("FEATURE_FLAG_FAILURE_TTL_SECONDS", 15)) * 1e3;
|
|
79
108
|
this.serviceToken = config.serviceToken;
|
|
@@ -180,7 +209,8 @@ var FeatureFlagProvider = class {
|
|
|
180
209
|
* Returns a map of key -> ResolutionDetails.
|
|
181
210
|
*/
|
|
182
211
|
async evaluateAll(context, keys) {
|
|
183
|
-
const
|
|
212
|
+
const maxAgeMs = keys ? keys.reduce((shortest, key) => Math.min(shortest, this.overrideTtlForKey(key)), Number.POSITIVE_INFINITY) : this.shortestOverrideTtlMs;
|
|
213
|
+
const evaluations = await this.fetchEvaluations(context, keys, maxAgeMs);
|
|
184
214
|
const result = /* @__PURE__ */ new Map();
|
|
185
215
|
for (const [key, evaluation] of evaluations) result.set(key, {
|
|
186
216
|
value: evaluation.value,
|
|
@@ -206,18 +236,39 @@ var FeatureFlagProvider = class {
|
|
|
206
236
|
*/
|
|
207
237
|
async getEvaluation(flagKey, context) {
|
|
208
238
|
try {
|
|
209
|
-
return (await this.fetchEvaluations(context)).get(flagKey) ?? null;
|
|
239
|
+
return (await this.fetchEvaluations(context, void 0, this.overrideTtlForKey(flagKey))).get(flagKey) ?? null;
|
|
210
240
|
} catch {
|
|
211
241
|
return null;
|
|
212
242
|
}
|
|
213
243
|
}
|
|
214
244
|
/**
|
|
215
|
-
*
|
|
245
|
+
* The override TTL for one flag key: the TTL of the longest matching
|
|
246
|
+
* `cacheTtlOverrides` prefix, else `Infinity`, so a key without an override
|
|
247
|
+
* is limited only by the entry's own TTL (success or failure), exactly as
|
|
248
|
+
* before overrides existed.
|
|
216
249
|
*/
|
|
217
|
-
|
|
250
|
+
overrideTtlForKey(flagKey) {
|
|
251
|
+
const override = this.ttlOverrides.find((o) => flagKey.startsWith(o.prefix));
|
|
252
|
+
return override ? override.ttlMs : Number.POSITIVE_INFINITY;
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Fetch flag evaluations — uses cache if available, otherwise calls the API.
|
|
256
|
+
*
|
|
257
|
+
* @param maxAgeMs - The oldest cached entry the caller accepts, from the
|
|
258
|
+
* overrides (`Infinity` when none applies). The entry's own TTL (success
|
|
259
|
+
* or failure) still applies, so this can only shorten it.
|
|
260
|
+
* When an early refresh fails, the entry is served until its own TTL ends
|
|
261
|
+
* (see {@link rememberFailure}).
|
|
262
|
+
*/
|
|
263
|
+
async fetchEvaluations(context, keys, maxAgeMs) {
|
|
218
264
|
const cacheKey = this.buildCacheKey(context);
|
|
219
265
|
const cached = this.cache.get(cacheKey);
|
|
220
|
-
if (cached
|
|
266
|
+
if (cached) {
|
|
267
|
+
const now = Date.now();
|
|
268
|
+
const age = now - cached.storedAt;
|
|
269
|
+
const refreshFailedRecently = cached.retryAfter !== void 0 && now < cached.retryAfter;
|
|
270
|
+
if (age < cached.ttlMs && (age < maxAgeMs || refreshFailedRecently)) return cached.evaluations;
|
|
271
|
+
}
|
|
221
272
|
if (!context?.workspaceId) return /* @__PURE__ */ new Map();
|
|
222
273
|
const bearerToken = this.serviceToken ?? await signServiceJwt(this.serviceName) ?? void 0;
|
|
223
274
|
try {
|
|
@@ -247,7 +298,8 @@ var FeatureFlagProvider = class {
|
|
|
247
298
|
for (const evaluation of json.data.evaluateFeatureFlags.evaluations) evaluations.set(evaluation.key, evaluation);
|
|
248
299
|
this.cache.set(cacheKey, {
|
|
249
300
|
evaluations,
|
|
250
|
-
|
|
301
|
+
storedAt: Date.now(),
|
|
302
|
+
ttlMs: this.cacheTtlMs
|
|
251
303
|
});
|
|
252
304
|
return evaluations;
|
|
253
305
|
} catch {
|
|
@@ -260,10 +312,17 @@ var FeatureFlagProvider = class {
|
|
|
260
312
|
* timeout per window instead of one per flag evaluation.
|
|
261
313
|
*/
|
|
262
314
|
rememberFailure(cacheKey) {
|
|
315
|
+
const current = this.cache.get(cacheKey);
|
|
316
|
+
const now = Date.now();
|
|
317
|
+
if (current && now - current.storedAt < current.ttlMs) {
|
|
318
|
+
current.retryAfter = now + this.failureTtlMs;
|
|
319
|
+
return current.evaluations;
|
|
320
|
+
}
|
|
263
321
|
const evaluations = /* @__PURE__ */ new Map();
|
|
264
322
|
this.cache.set(cacheKey, {
|
|
265
323
|
evaluations,
|
|
266
|
-
|
|
324
|
+
storedAt: Date.now(),
|
|
325
|
+
ttlMs: this.failureTtlMs
|
|
267
326
|
});
|
|
268
327
|
return evaluations;
|
|
269
328
|
}
|
|
@@ -364,11 +423,16 @@ function createOperationsFlagGatePlugin(options) {
|
|
|
364
423
|
const { flagKey, productId } = options;
|
|
365
424
|
const gatedOperations = new Set(options.gatedOperations ?? ["mutation"]);
|
|
366
425
|
const userMessage = options.userMessage ?? "This operation is currently unavailable.";
|
|
426
|
+
if (options.provider && options.cacheTtlOverrides) logger.warn("[OperationsFlagGate] cacheTtlOverrides is ignored because a provider was passed", {
|
|
427
|
+
flagKey,
|
|
428
|
+
productId
|
|
429
|
+
});
|
|
367
430
|
let provider = options.provider ?? null;
|
|
368
431
|
const getProvider = () => {
|
|
369
432
|
if (!provider) provider = new FeatureFlagProvider({
|
|
370
433
|
gatewayUrl: options.gatewayUrl ?? process.env["GLOBAL_PUBLIC_GATEWAY_URL"] ?? process.env["GLOBAL_INT_GATEWAY_URL"] ?? "",
|
|
371
434
|
cacheTtlSeconds: options.cacheTtlSeconds ?? 60,
|
|
435
|
+
...options.cacheTtlOverrides ? { cacheTtlOverrides: options.cacheTtlOverrides } : {},
|
|
372
436
|
defaultActorType: "service"
|
|
373
437
|
});
|
|
374
438
|
return provider;
|
|
@@ -419,4 +483,4 @@ var feature_flags_exports = /* @__PURE__ */ __exportAll({
|
|
|
419
483
|
});
|
|
420
484
|
|
|
421
485
|
export { createOperationsFlagGatePlugin as n, FeatureFlagProvider as r, feature_flags_exports as t };
|
|
422
|
-
//# sourceMappingURL=feature-flags-
|
|
486
|
+
//# sourceMappingURL=feature-flags-o-7MKGg8.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"feature-flags-o-7MKGg8.js","names":[],"sources":["../src/feature-flags/provider.ts","../src/feature-flags/operations-flag-gate.ts","../src/feature-flags/index.ts"],"sourcesContent":["/**\n * Burdenoff Feature Flags Server Provider\n *\n * Server-side feature flag provider for backend services.\n * Evaluates flags via the global-tenant-svc GraphQL API through the internal gateway.\n * Supports in-memory caching with a configurable TTL, and shorter TTLs for\n * chosen key prefixes (`cacheTtlOverrides`).\n *\n * @module feature-flags/provider\n * @category FeatureFlags\n *\n * @example\n * ```typescript\n * import { FeatureFlagProvider } from '@burdenoff/be-sdk/feature-flags';\n *\n * const provider = new FeatureFlagProvider({\n * gatewayUrl: 'http://global-int-gateway:4000/global/graphql',\n * cacheTtlSeconds: 60,\n * // Kill switches: refetch `fluidgrids.rpa.*` after 10 s, every other key after 60 s.\n * cacheTtlOverrides: [{ prefix: 'fluidgrids.rpa.', ttlSeconds: 10 }],\n * });\n *\n * const isEnabled = await provider.resolveBoolean('calendar.recurring-events', false, {\n * actorId: 'user-123',\n * actorType: 'user',\n * workspaceId: 'ws-456',\n * });\n *\n * console.log(isEnabled.value); // true or false\n * console.log(isEnabled.reason); // 'TARGETING_MATCH', 'DEFAULT', etc.\n * ```\n */\n\nimport { ContextManager } from '../context/index.js';\nimport { signServiceJwt } from '../gateway/service-jwt.js';\nimport type {\n CacheTtlOverride,\n EvaluationContext,\n FeatureFlagProviderConfig,\n FlagEvaluation,\n ResolutionDetails,\n} from './types.js';\n\ninterface CacheEntry {\n evaluations: Map<string, FlagEvaluation>;\n /** When the entry was written (`Date.now()`). */\n storedAt: number;\n /** How long the whole entry may be served: the success TTL, or the failure TTL for a failed fetch. */\n ttlMs: number;\n /**\n * Set when an early refresh (asked for by a key with a shorter\n * `cacheTtlOverrides` TTL) failed while this entry was still within its own\n * TTL: until this time the entry keeps being served instead of retrying.\n */\n retryAfter?: number;\n}\n\n/** A validated {@link CacheTtlOverride}, with its TTL in milliseconds. */\ninterface PrefixTtl {\n prefix: string;\n ttlMs: number;\n}\n\n/**\n * Keep only usable overrides (non-empty prefix, positive finite TTL) and sort\n * them longest prefix first, so the first match is the most specific one.\n */\nfunction normalizeTtlOverrides(overrides: readonly CacheTtlOverride[] | undefined): PrefixTtl[] {\n if (!overrides) return [];\n const valid: PrefixTtl[] = [];\n for (const override of overrides) {\n if (typeof override.prefix !== 'string' || override.prefix.length === 0) continue;\n if (typeof override.ttlSeconds !== 'number' || !Number.isFinite(override.ttlSeconds) || override.ttlSeconds <= 0) {\n continue;\n }\n valid.push({ prefix: override.prefix, ttlMs: override.ttlSeconds * 1000 });\n }\n return valid.sort((a, b) => b.prefix.length - a.prefix.length);\n}\n\nconst EVALUATE_QUERY = `\n query EvaluateFeatureFlags($input: EvaluateFeatureFlagsInput!) {\n evaluateFeatureFlags(input: $input) {\n evaluations {\n key\n value\n variant\n reason\n flagType\n errorCode\n }\n }\n }\n`;\n\n/**\n * Burdenoff Feature Flag Server Provider\n *\n * Evaluates feature flags by querying the global-tenant-svc through\n * the internal gateway. Results are cached in-memory per workspace+actor\n * combination with a configurable TTL.\n */\nfunction readPositiveIntEnv(name: string, fallback: number): number {\n const raw = process.env[name];\n if (!raw) return fallback;\n const parsed = parseInt(raw, 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;\n}\n\nexport class FeatureFlagProvider {\n private readonly gatewayUrl: string;\n private readonly cacheTtlMs: number;\n /** Per-prefix TTLs, longest prefix first (empty when none are configured). */\n private readonly ttlOverrides: readonly PrefixTtl[];\n /**\n * The shortest override TTL (`Infinity` when none is configured): the limit\n * for an answer that covers every flag.\n */\n private readonly shortestOverrideTtlMs: number;\n private readonly failureTtlMs: number;\n private readonly requestTimeoutMs: number;\n private readonly serviceToken?: string;\n private readonly serviceName: string;\n private readonly defaultActorType: string;\n\n /** In-memory cache keyed by `${workspaceId}:${actorId}` */\n private readonly cache = new Map<string, CacheEntry>();\n\n constructor(config: FeatureFlagProviderConfig) {\n this.gatewayUrl = config.gatewayUrl;\n this.cacheTtlMs = (config.cacheTtlSeconds ?? 60) * 1000;\n this.ttlOverrides = normalizeTtlOverrides(config.cacheTtlOverrides);\n this.shortestOverrideTtlMs = this.ttlOverrides.reduce(\n (shortest, o) => Math.min(shortest, o.ttlMs),\n Number.POSITIVE_INFINITY\n );\n // Hard per-request ceiling. Without it an unreachable gateway (NSG\n // silent-drop on the cross-environment path) left the fetch hanging for\n // the kernel's ~130s TCP connect timeout — stalling every flag-gated\n // request, and killing services that await a flag at BOOT (their ACA\n // startup probe expired → ActivationFailed).\n this.requestTimeoutMs = config.requestTimeoutMs ?? readPositiveIntEnv('FEATURE_FLAG_REQUEST_TIMEOUT_MS', 3000);\n // Negative cache so a broken gateway costs at most one timeout per\n // window instead of one per evaluation.\n this.failureTtlMs = (config.failureTtlSeconds ?? readPositiveIntEnv('FEATURE_FLAG_FAILURE_TTL_SECONDS', 15)) * 1000;\n this.serviceToken = config.serviceToken;\n this.serviceName = config.serviceName ?? process.env['SERVICE_NAME'] ?? 'burdenoff-be-sdk';\n this.defaultActorType = config.defaultActorType ?? 'service';\n }\n\n // =========================================================================\n // Public Resolution Methods (OpenFeature-compatible interface)\n // =========================================================================\n\n /**\n * Resolve a boolean feature flag\n *\n * @param flagKey - The flag key (e.g. \"calendar.recurring-events\")\n * @param defaultValue - Default value if resolution fails\n * @param context - Evaluation context with actor and workspace info\n * @returns Resolution details with the resolved boolean value\n */\n async resolveBoolean(\n flagKey: string,\n defaultValue: boolean,\n context: EvaluationContext\n ): Promise<ResolutionDetails<boolean>> {\n const evaluation = await this.getEvaluation(flagKey, context);\n if (!evaluation) {\n return {\n value: defaultValue,\n reason: 'DEFAULT',\n flagType: 'BOOLEAN',\n };\n }\n\n return {\n value: Boolean(evaluation.value),\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n };\n }\n\n /**\n * Resolve a string feature flag\n */\n async resolveString(\n flagKey: string,\n defaultValue: string,\n context: EvaluationContext\n ): Promise<ResolutionDetails<string>> {\n const evaluation = await this.getEvaluation(flagKey, context);\n if (!evaluation) {\n return {\n value: defaultValue,\n reason: 'DEFAULT',\n flagType: 'STRING',\n };\n }\n\n return {\n value: String(evaluation.value),\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n };\n }\n\n /**\n * Resolve a number feature flag\n */\n async resolveNumber(\n flagKey: string,\n defaultValue: number,\n context: EvaluationContext\n ): Promise<ResolutionDetails<number>> {\n const evaluation = await this.getEvaluation(flagKey, context);\n if (!evaluation) {\n return {\n value: defaultValue,\n reason: 'DEFAULT',\n flagType: 'NUMBER',\n };\n }\n\n return {\n value: Number(evaluation.value),\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n };\n }\n\n /**\n * Resolve an object (JSON) feature flag\n */\n async resolveObject<T extends Record<string, unknown>>(\n flagKey: string,\n defaultValue: T,\n context: EvaluationContext\n ): Promise<ResolutionDetails<T>> {\n const evaluation = await this.getEvaluation(flagKey, context);\n if (!evaluation) {\n return {\n value: defaultValue,\n reason: 'DEFAULT',\n flagType: 'JSON',\n };\n }\n\n return {\n value: evaluation.value as T,\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n };\n }\n\n // =========================================================================\n // Convenience Methods\n // =========================================================================\n\n /**\n * Quick boolean check — returns just the value.\n * Defaults to `true` (default-allow philosophy) if the flag is not found.\n *\n * @example\n * ```typescript\n * if (await provider.isEnabled('calendar.recurring-events', ctx)) {\n * // Feature is enabled\n * }\n * ```\n */\n async isEnabled(flagKey: string, context?: EvaluationContext): Promise<boolean> {\n const result = await this.resolveBoolean(\n flagKey,\n true,\n context ?? { workspaceId: 'system', actorType: 'service', actorId: 'boot' }\n );\n return result.value;\n }\n\n /**\n * Bulk evaluate multiple flags at once.\n * Returns a map of key -> ResolutionDetails.\n */\n async evaluateAll(context: EvaluationContext, keys?: string[]): Promise<Map<string, ResolutionDetails<unknown>>> {\n // The answer is only as fresh as its shortest-lived key: every flag when\n // no keys are named, else the named keys.\n const maxAgeMs = keys\n ? keys.reduce((shortest, key) => Math.min(shortest, this.overrideTtlForKey(key)), Number.POSITIVE_INFINITY)\n : this.shortestOverrideTtlMs;\n const evaluations = await this.fetchEvaluations(context, keys, maxAgeMs);\n const result = new Map<string, ResolutionDetails<unknown>>();\n\n for (const [key, evaluation] of evaluations) {\n result.set(key, {\n value: evaluation.value,\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n });\n }\n\n return result;\n }\n\n /**\n * Invalidate the cache for a specific workspace+actor combination,\n * or all cache entries if no context is provided.\n */\n invalidateCache(context?: EvaluationContext): void {\n if (context) {\n const cacheKey = this.buildCacheKey(context);\n this.cache.delete(cacheKey);\n } else {\n this.cache.clear();\n }\n }\n\n // =========================================================================\n // Private Methods\n // =========================================================================\n\n /**\n * Get a single flag evaluation, fetching from cache or API\n */\n private async getEvaluation(flagKey: string, context: EvaluationContext | undefined): Promise<FlagEvaluation | null> {\n try {\n const evaluations = await this.fetchEvaluations(context, undefined, this.overrideTtlForKey(flagKey));\n return evaluations.get(flagKey) ?? null;\n } catch {\n return null;\n }\n }\n\n /**\n * The override TTL for one flag key: the TTL of the longest matching\n * `cacheTtlOverrides` prefix, else `Infinity`, so a key without an override\n * is limited only by the entry's own TTL (success or failure), exactly as\n * before overrides existed.\n */\n private overrideTtlForKey(flagKey: string): number {\n const override = this.ttlOverrides.find((o) => flagKey.startsWith(o.prefix));\n return override ? override.ttlMs : Number.POSITIVE_INFINITY;\n }\n\n /**\n * Fetch flag evaluations — uses cache if available, otherwise calls the API.\n *\n * @param maxAgeMs - The oldest cached entry the caller accepts, from the\n * overrides (`Infinity` when none applies). The entry's own TTL (success\n * or failure) still applies, so this can only shorten it.\n * When an early refresh fails, the entry is served until its own TTL ends\n * (see {@link rememberFailure}).\n */\n private async fetchEvaluations(\n context: EvaluationContext | undefined,\n keys: string[] | undefined,\n maxAgeMs: number\n ): Promise<Map<string, FlagEvaluation>> {\n const cacheKey = this.buildCacheKey(context);\n const cached = this.cache.get(cacheKey);\n\n if (cached) {\n const now = Date.now();\n const age = now - cached.storedAt;\n const refreshFailedRecently = cached.retryAfter !== undefined && now < cached.retryAfter;\n if (age < cached.ttlMs && (age < maxAgeMs || refreshFailedRecently)) {\n return cached.evaluations;\n }\n }\n\n // Without a workspace context there's nothing the backend can evaluate\n // against — fall through to caller defaults instead of hitting the API.\n if (!context?.workspaceId) {\n return new Map();\n }\n\n // Cross-layer flag evaluation transits the global PUBLIC gateway, which\n // strips raw actor headers unless the request carries a valid JWT. Use an\n // explicit serviceToken if provided, otherwise mint a short-lived `service`\n // actor JWT (no-op when SERVICE_JWT_SECRET is unset → falls back to header\n // context for same-env/internal-gateway evaluation).\n const bearerToken = this.serviceToken ?? (await signServiceJwt(this.serviceName)) ?? undefined;\n\n // Fetch from API\n try {\n const response = await fetch(this.gatewayUrl, {\n method: 'POST',\n // Bounded: an unreachable gateway must cost milliseconds-to-seconds,\n // never the kernel's TCP connect timeout. On abort the catch below\n // negative-caches and callers fall back to their defaults.\n signal: AbortSignal.timeout(this.requestTimeoutMs),\n headers: {\n 'Content-Type': 'application/json',\n ...(context.actorId && { 'x-actor-id': context.actorId }),\n 'x-actor-type': context.actorType ?? this.defaultActorType,\n 'x-workspace-id': context.workspaceId,\n ...(bearerToken && { Authorization: `Bearer ${bearerToken}` }),\n // Re-present the inbound CF Access service token when the flag check\n // runs against a CF-Access-gated public gateway (alpha). No-op when\n // request context carries no CF creds (local dev, production).\n ...ContextManager.getCfAccessHeaders(),\n },\n body: JSON.stringify({\n query: EVALUATE_QUERY,\n variables: {\n input: {\n workspaceId: context.workspaceId,\n keys: keys ?? null,\n },\n },\n }),\n });\n\n if (!response.ok) {\n // Return empty map on error — default-allow handled by callers\n return this.rememberFailure(cacheKey);\n }\n\n const json = (await response.json()) as {\n data?: {\n evaluateFeatureFlags?: {\n evaluations?: FlagEvaluation[];\n };\n };\n errors?: Array<{ message: string }>;\n };\n\n if (json.errors || !json.data?.evaluateFeatureFlags?.evaluations) {\n return this.rememberFailure(cacheKey);\n }\n\n const evaluations = new Map<string, FlagEvaluation>();\n for (const evaluation of json.data.evaluateFeatureFlags.evaluations) {\n evaluations.set(evaluation.key, evaluation);\n }\n\n // Cache the results\n this.cache.set(cacheKey, {\n evaluations,\n storedAt: Date.now(),\n ttlMs: this.cacheTtlMs,\n });\n\n return evaluations;\n } catch {\n // On network error/timeout, return empty map (default-allow handled by\n // callers) and negative-cache so the next evaluations in the window\n // skip the doomed request entirely.\n return this.rememberFailure(cacheKey);\n }\n }\n\n /**\n * Negative-cache a failed fetch: remember an empty evaluation set for\n * `failureTtlMs` so a broken/unreachable gateway costs at most one request\n * timeout per window instead of one per flag evaluation.\n */\n private rememberFailure(cacheKey: string): Map<string, FlagEvaluation> {\n // The fetch failed while the current entry is still within its own TTL:\n // either an early refresh asked for by a key with a shorter\n // `cacheTtlOverrides` TTL, or a concurrent call already stored a fresh\n // answer. Keep serving that entry, as the provider did before overrides\n // existed, instead of replacing still-valid answers with caller defaults,\n // and wait the failure TTL before the next early refresh.\n const current = this.cache.get(cacheKey);\n const now = Date.now();\n if (current && now - current.storedAt < current.ttlMs) {\n current.retryAfter = now + this.failureTtlMs;\n return current.evaluations;\n }\n\n const evaluations = new Map<string, FlagEvaluation>();\n this.cache.set(cacheKey, {\n evaluations,\n storedAt: Date.now(),\n ttlMs: this.failureTtlMs,\n });\n return evaluations;\n }\n\n /**\n * Build a cache key from the evaluation context.\n *\n * Safe against undefined/null context — callers like isEnabled() may\n * pass no context during service boot (e.g. checking a default-allow\n * feature flag at startup before the first request builds a real\n * actor context). Without the guard, isEnabled(flag) used to throw\n * \"undefined is not an object (evaluating 'context.workspaceId')\"\n * and crash the svc at startServer().\n */\n private buildCacheKey(context: EvaluationContext | undefined): string {\n const ctx = context ?? ({} as EvaluationContext);\n return `${ctx.workspaceId ?? 'system'}:${ctx.actorId ?? 'anonymous'}:${ctx.actorType ?? 'user'}`;\n }\n}\n","/**\n * Operations Feature-Flag Gate Plugin\n *\n * GraphQL-Yoga/envelop plugin factory that short-circuits GraphQL operations\n * when a product's operations feature flag is OFF, returning a clean typed\n * `FEATURE_DISABLED` (HTTP 403) error before any resolver runs.\n *\n * This is the shared, fleet-wide replacement for the per-service inline\n * `operations-feature-flag` / `feature-flag-gate` plugins (movethewheels,\n * manufacturedops, …). By default it gates MUTATIONS only; queries and\n * subscriptions pass through.\n *\n * Default-allow philosophy (matches {@link FeatureFlagProvider.isEnabled}): if\n * there is no workspace context, or the flag service is unreachable / the flag\n * is unknown, the operation is ALLOWED. A flag must be explicitly disabled for\n * the workspace to block traffic.\n *\n * @module feature-flags/operations-flag-gate\n * @category FeatureFlags\n *\n * @example\n * ```typescript\n * import { createOperationsFlagGatePlugin } from '@burdenoff/be-sdk/feature-flags';\n *\n * yogaPlugins: [\n * createOperationsFlagGatePlugin({\n * flagKey: 'movethewheels.operations',\n * productId: 'movethewheels',\n * }),\n * useGraphQLModules(application),\n * ];\n * ```\n */\n\nimport { type DocumentNode, GraphQLError, Kind, type OperationDefinitionNode } from 'graphql';\n\nimport { logger } from '../logger/index.js';\nimport type { YogaPlugin } from '../server/index.js';\nimport { FeatureFlagProvider } from './provider.js';\nimport type { CacheTtlOverride, EvaluationContext } from './types.js';\n\n/** GraphQL operation types that a gate can be configured to short-circuit. */\nexport type GatedOperationType = 'query' | 'mutation' | 'subscription';\n\nexport interface OperationsFlagGatePluginOptions {\n /** Feature flag key that gates the operations (e.g. `'movethewheels.operations'`). */\n flagKey: string;\n /** Product identifier this gate protects. Surfaced in the error extensions + logs. */\n productId: string;\n /**\n * Provider used to evaluate the flag. When omitted, a {@link FeatureFlagProvider}\n * is lazily built from `gatewayUrl` (or `GLOBAL_PUBLIC_GATEWAY_URL` /\n * `GLOBAL_INT_GATEWAY_URL`).\n */\n provider?: FeatureFlagProvider;\n /** Gateway URL for the lazily-built default provider. Ignored when `provider` is set. */\n gatewayUrl?: string;\n /** Cache TTL (seconds) for the lazily-built default provider. Default: 60. */\n cacheTtlSeconds?: number;\n /**\n * Per-prefix cache TTLs for the lazily-built default provider (see\n * {@link CacheTtlOverride}). Ignored when `provider` is set.\n */\n cacheTtlOverrides?: readonly CacheTtlOverride[];\n /** Which operation types to gate. Default: `['mutation']`. */\n gatedOperations?: readonly GatedOperationType[];\n /** Override the user-facing error message shown when the flag is disabled. */\n userMessage?: string;\n}\n\n/** Actor/workspace fields the gate reads off the GraphQL context (either shape). */\ninterface GateContextShape {\n workspace?: { id?: string | null } | null;\n actor?: { id?: string | null; type?: string | null } | null;\n workspaceId?: string | null;\n actorId?: string | null;\n actorType?: string | null;\n}\n\nconst ACTOR_TYPES: readonly string[] = ['user', 'app', 'service', 'super_admin'];\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isDocumentNode(value: unknown): value is DocumentNode {\n return isRecord(value) && Array.isArray((value as { definitions?: unknown }).definitions);\n}\n\n/** Find the operation that will actually execute for this request. */\nfunction findExecutedOperation(document: DocumentNode, operationName?: string | null): OperationDefinitionNode | null {\n const operations = document.definitions.filter(\n (definition): definition is OperationDefinitionNode => definition.kind === Kind.OPERATION_DEFINITION\n );\n\n if (operationName) {\n return operations.find((operation) => operation.name?.value === operationName) ?? null;\n }\n // Unnamed / single-operation request executes the first (only) operation.\n return operations[0] ?? null;\n}\n\nfunction coerceActorType(value: string | null | undefined): EvaluationContext['actorType'] {\n // Cast is sound: only reached after `ACTOR_TYPES.includes(value)` proves the\n // string is one of the known actor-type literals.\n return value && ACTOR_TYPES.includes(value) ? (value as EvaluationContext['actorType']) : undefined;\n}\n\n/**\n * Build the flag {@link EvaluationContext} from the GraphQL context, tolerating\n * both the nested (`workspace.id` / `actor.id`) and flat (`workspaceId` /\n * `actorId`) shapes. Returns `null` when no workspace can be resolved.\n */\nfunction resolveEvaluationContext(contextValue: unknown): EvaluationContext | null {\n // Cast to the fully-optional GateContextShape after the record guard; every\n // field is read defensively with optional chaining below.\n const ctx = (isRecord(contextValue) ? contextValue : {}) as GateContextShape;\n const workspaceId = ctx.workspace?.id ?? ctx.workspaceId ?? undefined;\n if (!workspaceId) {\n return null;\n }\n const actorId = ctx.actor?.id ?? ctx.actorId ?? undefined;\n const actorType = coerceActorType(ctx.actor?.type ?? ctx.actorType);\n return {\n workspaceId,\n ...(actorId ? { actorId } : {}),\n ...(actorType ? { actorType } : {}),\n };\n}\n\n/**\n * Create a GraphQL-Yoga/envelop plugin that gates operations behind a product\n * feature flag. Returns a {@link YogaPlugin} ready to drop into a service's\n * `yogaPlugins` array.\n */\nexport function createOperationsFlagGatePlugin(options: OperationsFlagGatePluginOptions): YogaPlugin {\n const { flagKey, productId } = options;\n const gatedOperations = new Set<string>(options.gatedOperations ?? ['mutation']);\n const userMessage = options.userMessage ?? 'This operation is currently unavailable.';\n\n if (options.provider && options.cacheTtlOverrides) {\n // The option configures only the provider this plugin builds itself.\n logger.warn('[OperationsFlagGate] cacheTtlOverrides is ignored because a provider was passed', {\n flagKey,\n productId,\n });\n }\n\n let provider = options.provider ?? null;\n const getProvider = (): FeatureFlagProvider => {\n if (!provider) {\n provider = new FeatureFlagProvider({\n gatewayUrl:\n options.gatewayUrl ?? process.env['GLOBAL_PUBLIC_GATEWAY_URL'] ?? process.env['GLOBAL_INT_GATEWAY_URL'] ?? '',\n cacheTtlSeconds: options.cacheTtlSeconds ?? 60,\n ...(options.cacheTtlOverrides ? { cacheTtlOverrides: options.cacheTtlOverrides } : {}),\n defaultActorType: 'service',\n });\n }\n return provider;\n };\n\n return {\n async onExecute({\n args,\n }: {\n args: {\n document?: unknown;\n operationName?: string | null;\n variableValues?: Record<string, unknown>;\n contextValue?: unknown;\n };\n }): Promise<void> {\n if (!isDocumentNode(args.document)) {\n return;\n }\n\n const operation = findExecutedOperation(args.document, args.operationName);\n if (!operation || !gatedOperations.has(operation.operation)) {\n return; // Not a gated operation type — allow.\n }\n\n const evaluationContext = resolveEvaluationContext(args.contextValue);\n if (!evaluationContext) {\n // No workspace context to evaluate against → default-allow.\n logger.warn('[OperationsFlagGate] no workspace context — allowing operation', { flagKey, productId });\n return;\n }\n\n let enabled = true;\n try {\n enabled = await getProvider().isEnabled(flagKey, evaluationContext);\n } catch (error) {\n // Never let a flag-service failure block traffic (default-allow).\n logger.warn('[OperationsFlagGate] flag evaluation failed — allowing operation', {\n flagKey,\n productId,\n error: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n\n if (!enabled) {\n logger.warn('[OperationsFlagGate] flag disabled — blocking operation', {\n flagKey,\n productId,\n workspaceId: evaluationContext.workspaceId,\n });\n throw new GraphQLError(userMessage, {\n extensions: {\n code: 'FEATURE_DISABLED',\n flagKey,\n productId,\n http: { status: 403 },\n },\n });\n }\n },\n };\n}\n","/**\n * Feature Flags Module\n *\n * In-house feature flag evaluation for Burdenoff backend services.\n * Compatible with OpenFeature specification concepts.\n *\n * @module feature-flags\n * @category FeatureFlags\n *\n * @example\n * ```typescript\n * import { FeatureFlagProvider } from '@burdenoff/be-sdk/feature-flags';\n *\n * // Create provider (typically done once at service startup)\n * const provider = new FeatureFlagProvider({\n * gatewayUrl: process.env.GLOBAL_INT_GATEWAY_URL || 'http://global-int-gateway:4000/global/graphql',\n * cacheTtlSeconds: 60,\n * });\n *\n * // Check a boolean flag\n * const ctx = { actorId: 'user-123', actorType: 'user' as const, workspaceId: 'ws-456' };\n * const isEnabled = await provider.isEnabled('calendar.recurring-events', ctx);\n *\n * // Resolve with full details\n * const details = await provider.resolveBoolean('calendar.recurring-events', true, ctx);\n * console.log(details.value); // true\n * console.log(details.reason); // 'TARGETING_MATCH'\n * console.log(details.variant); // 'user-opted-in'\n * ```\n */\n\nexport { FeatureFlagProvider } from './provider.js';\nexport type {\n CacheTtlOverride,\n EvaluationContext,\n FeatureFlagProviderConfig,\n FlagEvaluation,\n FlagType,\n ResolutionDetails,\n} from './types.js';\n\nexport { createOperationsFlagGatePlugin } from './operations-flag-gate.js';\nexport type { OperationsFlagGatePluginOptions, GatedOperationType } from './operations-flag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AC,UAAU,SAAS,iBAAiB;EACpE,SAAS,OAAO;GAEd,OAAO,KAAK,oEAAoE;IAC9E;IACA;IACA,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GAC9D,CAAC;GACD;EACF;EAEA,IAAI,CAAC,SAAS;GACZ,OAAO,KAAK,2DAA2D;IACrE;IACA;IACA,aAAa,kBAAkB;GACjC,CAAC;GACD,MAAM,IAAI,aAAa,aAAa,EAClC,YAAY;IACV,MAAM;IACN;IACA;IACA,MAAM,EAAE,QAAQ,IAAI;GACtB,EACF,CAAC;EACH;CACF,EACF;AACF"}
|
|
@@ -21,9 +21,14 @@ interface FlagEvaluation {
|
|
|
21
21
|
flagType: FlagType;
|
|
22
22
|
errorCode: string | null;
|
|
23
23
|
}
|
|
24
|
+
interface CacheTtlOverride {
|
|
25
|
+
prefix: string;
|
|
26
|
+
ttlSeconds: number;
|
|
27
|
+
}
|
|
24
28
|
interface FeatureFlagProviderConfig {
|
|
25
29
|
gatewayUrl: string;
|
|
26
30
|
cacheTtlSeconds?: number;
|
|
31
|
+
cacheTtlOverrides?: readonly CacheTtlOverride[];
|
|
27
32
|
serviceToken?: string;
|
|
28
33
|
serviceName?: string;
|
|
29
34
|
defaultActorType?: 'user' | 'app' | 'service' | 'super_admin';
|
|
@@ -33,6 +38,8 @@ interface FeatureFlagProviderConfig {
|
|
|
33
38
|
declare class FeatureFlagProvider {
|
|
34
39
|
private readonly gatewayUrl;
|
|
35
40
|
private readonly cacheTtlMs;
|
|
41
|
+
private readonly ttlOverrides;
|
|
42
|
+
private readonly shortestOverrideTtlMs;
|
|
36
43
|
private readonly failureTtlMs;
|
|
37
44
|
private readonly requestTimeoutMs;
|
|
38
45
|
private readonly serviceToken?;
|
|
@@ -48,6 +55,7 @@ declare class FeatureFlagProvider {
|
|
|
48
55
|
evaluateAll(context: EvaluationContext, keys?: string[]): Promise<Map<string, ResolutionDetails<unknown>>>;
|
|
49
56
|
invalidateCache(context?: EvaluationContext): void;
|
|
50
57
|
private getEvaluation;
|
|
58
|
+
private overrideTtlForKey;
|
|
51
59
|
private fetchEvaluations;
|
|
52
60
|
private rememberFailure;
|
|
53
61
|
private buildCacheKey;
|
|
@@ -59,11 +67,12 @@ interface OperationsFlagGatePluginOptions {
|
|
|
59
67
|
provider?: FeatureFlagProvider;
|
|
60
68
|
gatewayUrl?: string;
|
|
61
69
|
cacheTtlSeconds?: number;
|
|
70
|
+
cacheTtlOverrides?: readonly CacheTtlOverride[];
|
|
62
71
|
gatedOperations?: readonly GatedOperationType[];
|
|
63
72
|
userMessage?: string;
|
|
64
73
|
}
|
|
65
74
|
declare function createOperationsFlagGatePlugin(options: OperationsFlagGatePluginOptions): YogaPlugin;
|
|
66
75
|
declare namespace index_d_exports {
|
|
67
|
-
export { EvaluationContext, FeatureFlagProvider, FeatureFlagProviderConfig, FlagEvaluation, FlagType, GatedOperationType, OperationsFlagGatePluginOptions, ResolutionDetails, createOperationsFlagGatePlugin };
|
|
76
|
+
export { CacheTtlOverride, EvaluationContext, FeatureFlagProvider, FeatureFlagProviderConfig, FlagEvaluation, FlagType, GatedOperationType, OperationsFlagGatePluginOptions, ResolutionDetails, createOperationsFlagGatePlugin };
|
|
68
77
|
}
|
|
69
|
-
export { FeatureFlagProvider as a,
|
|
78
|
+
export { FeatureFlagProvider as a, FeatureFlagProviderConfig as c, ResolutionDetails as d, createOperationsFlagGatePlugin as i, FlagEvaluation as l, GatedOperationType as n, CacheTtlOverride as o, OperationsFlagGatePluginOptions as r, EvaluationContext as s, index_d_exports as t, FlagType as u };
|
package/dist/index.d.ts
CHANGED
|
@@ -38,7 +38,7 @@ import { a as index_d_exports$14 } from "./index-DMq2xPV7.js";
|
|
|
38
38
|
import { a as index_d_exports$15 } from "./index-Base-sg5.js";
|
|
39
39
|
import { t as index_d_exports$3 } from "./index-BVOL7458.js";
|
|
40
40
|
import { t as index_d_exports$9 } from "./index-XkPephwV.js";
|
|
41
|
-
import { t as index_d_exports$7 } from "./index-
|
|
41
|
+
import { t as index_d_exports$7 } from "./index-DIvauo52.js";
|
|
42
42
|
import { a as index_d_exports$2, c as verifyCaptchaIfEnabled, n as RecaptchaVerifyResult, o as isCaptchaEnabled, s as verifyCaptcha, t as RecaptchaVerifyOptions } from "./index-yBSjMY32.js";
|
|
43
43
|
import { t as index_d_exports$20 } from "./index-DY3dNhMN.js";
|
|
44
44
|
import { B as validateUserFields, C as RbacCoverageOptions, G as validateUsername, H as USERNAME_MIN_LENGTH, I as UserFieldError, J as NameErrorCode, K as NAME_MAX_LENGTH, L as UserFieldKey, M as assertRbacCoverage, R as UserFieldsValidationResult, S as RbacCoverageError, T as RbacCoverageSource, U as UsernameErrorCode, V as USERNAME_MAX_LENGTH, W as UsernameValidationResult, X as lengthInCodePoints, Y as NameValidationResult, Z as validateName, j as analyzeRbacCoverage, q as NAME_MIN_LENGTH, t as index_d_exports$26, w as RbacCoverageReport, z as ValidatedUserFields } from "./index-Bnz5Bqtl.js";
|
package/dist/index.js
CHANGED
|
@@ -41,7 +41,7 @@ import { r as instrumentation_exports } from "./instrumentation-DKHAGCoz.js";
|
|
|
41
41
|
import { a as layer_exports } from "./layer-CEKy6cm8.js";
|
|
42
42
|
import { t as crypto_exports } from "./crypto-DO9fM0FO.js";
|
|
43
43
|
import { t as gateway_exports } from "./gateway-B9p8PD82.js";
|
|
44
|
-
import { t as feature_flags_exports } from "./feature-flags-
|
|
44
|
+
import { t as feature_flags_exports } from "./feature-flags-o-7MKGg8.js";
|
|
45
45
|
import { i as verifyCaptchaIfEnabled, n as isCaptchaEnabled, r as verifyCaptcha, t as captcha_exports } from "./captcha-BT7yh1YS.js";
|
|
46
46
|
import { t as platform_exports } from "./platform-DZwczW7v.js";
|
|
47
47
|
import { C as USERNAME_MIN_LENGTH, D as lengthInCodePoints, E as NAME_MIN_LENGTH, O as validateName, S as USERNAME_MAX_LENGTH, T as NAME_MAX_LENGTH, _ as assertRbacCoverage, g as analyzeRbacCoverage, h as RbacCoverageError, t as validation_exports, w as validateUsername, x as validateUserFields } from "./validation-bwJzOytZ.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@burdenoff/be-sdk",
|
|
3
|
-
"version": "2026.1202.
|
|
3
|
+
"version": "2026.1202.8",
|
|
4
4
|
"description": "Backend SDK for Burdenoff products providing unified access to notifications, RBAC, activity tracking, usage monitoring, and more",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -89,7 +89,7 @@
|
|
|
89
89
|
"test:coverage": "boff coverage-gate --run-tests",
|
|
90
90
|
"test:live-pg": "bunx prisma generate --schema tests/live-pg/rls-transactions/schema.prisma && bun test tests/live-pg",
|
|
91
91
|
"test:ci": "bun run test",
|
|
92
|
-
"audit": "bun audit
|
|
92
|
+
"audit": "bun audit",
|
|
93
93
|
"sanity": "boff sanity",
|
|
94
94
|
"prepublishOnly": "bun run build",
|
|
95
95
|
"pack:tgz": "mkdir -p dist && rm -rf dist/burdenoff-be-sdk.tgz && bun pm pack --filename dist/burdenoff-be-sdk.tgz",
|
|
@@ -240,9 +240,12 @@
|
|
|
240
240
|
"@grpc/grpc-js": "1.14.5",
|
|
241
241
|
"baseline-browser-mapping": "2.11.27",
|
|
242
242
|
"browserslist": "4.29.3",
|
|
243
|
+
"cross-spawn": "7.1.2",
|
|
243
244
|
"deepmerge-ts": "8.0.2",
|
|
244
245
|
"fast-uri": "3.1.9",
|
|
245
|
-
"
|
|
246
|
+
"minimatch": "11.0.9",
|
|
247
|
+
"mysql2": "3.24.5",
|
|
248
|
+
"terser": "5.51.4"
|
|
246
249
|
},
|
|
247
250
|
"resolutions": {
|
|
248
251
|
"graphql": "16.12.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"feature-flags-CP1KRgwD.js","names":[],"sources":["../src/feature-flags/provider.ts","../src/feature-flags/operations-flag-gate.ts","../src/feature-flags/index.ts"],"sourcesContent":["/**\n * Burdenoff Feature Flags Server Provider\n *\n * Server-side feature flag provider for backend services.\n * Evaluates flags via the global-tenant-svc GraphQL API through the internal gateway.\n * Supports in-memory caching with configurable TTL.\n *\n * @module feature-flags/provider\n * @category FeatureFlags\n *\n * @example\n * ```typescript\n * import { FeatureFlagProvider } from '@burdenoff/be-sdk/feature-flags';\n *\n * const provider = new FeatureFlagProvider({\n * gatewayUrl: 'http://global-int-gateway:4000/global/graphql',\n * cacheTtlSeconds: 60,\n * });\n *\n * const isEnabled = await provider.resolveBoolean('calendar.recurring-events', false, {\n * actorId: 'user-123',\n * actorType: 'user',\n * workspaceId: 'ws-456',\n * });\n *\n * console.log(isEnabled.value); // true or false\n * console.log(isEnabled.reason); // 'TARGETING_MATCH', 'DEFAULT', etc.\n * ```\n */\n\nimport { ContextManager } from '../context/index.js';\nimport { signServiceJwt } from '../gateway/service-jwt.js';\nimport type { EvaluationContext, FeatureFlagProviderConfig, FlagEvaluation, ResolutionDetails } from './types.js';\n\ninterface CacheEntry {\n evaluations: Map<string, FlagEvaluation>;\n expiresAt: number;\n}\n\nconst EVALUATE_QUERY = `\n query EvaluateFeatureFlags($input: EvaluateFeatureFlagsInput!) {\n evaluateFeatureFlags(input: $input) {\n evaluations {\n key\n value\n variant\n reason\n flagType\n errorCode\n }\n }\n }\n`;\n\n/**\n * Burdenoff Feature Flag Server Provider\n *\n * Evaluates feature flags by querying the global-tenant-svc through\n * the internal gateway. Results are cached in-memory per workspace+actor\n * combination with a configurable TTL.\n */\nfunction readPositiveIntEnv(name: string, fallback: number): number {\n const raw = process.env[name];\n if (!raw) return fallback;\n const parsed = parseInt(raw, 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;\n}\n\nexport class FeatureFlagProvider {\n private readonly gatewayUrl: string;\n private readonly cacheTtlMs: number;\n private readonly failureTtlMs: number;\n private readonly requestTimeoutMs: number;\n private readonly serviceToken?: string;\n private readonly serviceName: string;\n private readonly defaultActorType: string;\n\n /** In-memory cache keyed by `${workspaceId}:${actorId}` */\n private readonly cache = new Map<string, CacheEntry>();\n\n constructor(config: FeatureFlagProviderConfig) {\n this.gatewayUrl = config.gatewayUrl;\n this.cacheTtlMs = (config.cacheTtlSeconds ?? 60) * 1000;\n // Hard per-request ceiling. Without it an unreachable gateway (NSG\n // silent-drop on the cross-environment path) left the fetch hanging for\n // the kernel's ~130s TCP connect timeout — stalling every flag-gated\n // request, and killing services that await a flag at BOOT (their ACA\n // startup probe expired → ActivationFailed).\n this.requestTimeoutMs = config.requestTimeoutMs ?? readPositiveIntEnv('FEATURE_FLAG_REQUEST_TIMEOUT_MS', 3000);\n // Negative cache so a broken gateway costs at most one timeout per\n // window instead of one per evaluation.\n this.failureTtlMs = (config.failureTtlSeconds ?? readPositiveIntEnv('FEATURE_FLAG_FAILURE_TTL_SECONDS', 15)) * 1000;\n this.serviceToken = config.serviceToken;\n this.serviceName = config.serviceName ?? process.env['SERVICE_NAME'] ?? 'burdenoff-be-sdk';\n this.defaultActorType = config.defaultActorType ?? 'service';\n }\n\n // =========================================================================\n // Public Resolution Methods (OpenFeature-compatible interface)\n // =========================================================================\n\n /**\n * Resolve a boolean feature flag\n *\n * @param flagKey - The flag key (e.g. \"calendar.recurring-events\")\n * @param defaultValue - Default value if resolution fails\n * @param context - Evaluation context with actor and workspace info\n * @returns Resolution details with the resolved boolean value\n */\n async resolveBoolean(\n flagKey: string,\n defaultValue: boolean,\n context: EvaluationContext\n ): Promise<ResolutionDetails<boolean>> {\n const evaluation = await this.getEvaluation(flagKey, context);\n if (!evaluation) {\n return {\n value: defaultValue,\n reason: 'DEFAULT',\n flagType: 'BOOLEAN',\n };\n }\n\n return {\n value: Boolean(evaluation.value),\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n };\n }\n\n /**\n * Resolve a string feature flag\n */\n async resolveString(\n flagKey: string,\n defaultValue: string,\n context: EvaluationContext\n ): Promise<ResolutionDetails<string>> {\n const evaluation = await this.getEvaluation(flagKey, context);\n if (!evaluation) {\n return {\n value: defaultValue,\n reason: 'DEFAULT',\n flagType: 'STRING',\n };\n }\n\n return {\n value: String(evaluation.value),\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n };\n }\n\n /**\n * Resolve a number feature flag\n */\n async resolveNumber(\n flagKey: string,\n defaultValue: number,\n context: EvaluationContext\n ): Promise<ResolutionDetails<number>> {\n const evaluation = await this.getEvaluation(flagKey, context);\n if (!evaluation) {\n return {\n value: defaultValue,\n reason: 'DEFAULT',\n flagType: 'NUMBER',\n };\n }\n\n return {\n value: Number(evaluation.value),\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n };\n }\n\n /**\n * Resolve an object (JSON) feature flag\n */\n async resolveObject<T extends Record<string, unknown>>(\n flagKey: string,\n defaultValue: T,\n context: EvaluationContext\n ): Promise<ResolutionDetails<T>> {\n const evaluation = await this.getEvaluation(flagKey, context);\n if (!evaluation) {\n return {\n value: defaultValue,\n reason: 'DEFAULT',\n flagType: 'JSON',\n };\n }\n\n return {\n value: evaluation.value as T,\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n };\n }\n\n // =========================================================================\n // Convenience Methods\n // =========================================================================\n\n /**\n * Quick boolean check — returns just the value.\n * Defaults to `true` (default-allow philosophy) if the flag is not found.\n *\n * @example\n * ```typescript\n * if (await provider.isEnabled('calendar.recurring-events', ctx)) {\n * // Feature is enabled\n * }\n * ```\n */\n async isEnabled(flagKey: string, context?: EvaluationContext): Promise<boolean> {\n const result = await this.resolveBoolean(\n flagKey,\n true,\n context ?? { workspaceId: 'system', actorType: 'service', actorId: 'boot' }\n );\n return result.value;\n }\n\n /**\n * Bulk evaluate multiple flags at once.\n * Returns a map of key -> ResolutionDetails.\n */\n async evaluateAll(context: EvaluationContext, keys?: string[]): Promise<Map<string, ResolutionDetails<unknown>>> {\n const evaluations = await this.fetchEvaluations(context, keys);\n const result = new Map<string, ResolutionDetails<unknown>>();\n\n for (const [key, evaluation] of evaluations) {\n result.set(key, {\n value: evaluation.value,\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n });\n }\n\n return result;\n }\n\n /**\n * Invalidate the cache for a specific workspace+actor combination,\n * or all cache entries if no context is provided.\n */\n invalidateCache(context?: EvaluationContext): void {\n if (context) {\n const cacheKey = this.buildCacheKey(context);\n this.cache.delete(cacheKey);\n } else {\n this.cache.clear();\n }\n }\n\n // =========================================================================\n // Private Methods\n // =========================================================================\n\n /**\n * Get a single flag evaluation, fetching from cache or API\n */\n private async getEvaluation(flagKey: string, context: EvaluationContext | undefined): Promise<FlagEvaluation | null> {\n try {\n const evaluations = await this.fetchEvaluations(context);\n return evaluations.get(flagKey) ?? null;\n } catch {\n return null;\n }\n }\n\n /**\n * Fetch flag evaluations — uses cache if available, otherwise calls the API\n */\n private async fetchEvaluations(\n context: EvaluationContext | undefined,\n keys?: string[]\n ): Promise<Map<string, FlagEvaluation>> {\n const cacheKey = this.buildCacheKey(context);\n const cached = this.cache.get(cacheKey);\n\n if (cached && cached.expiresAt > Date.now()) {\n return cached.evaluations;\n }\n\n // Without a workspace context there's nothing the backend can evaluate\n // against — fall through to caller defaults instead of hitting the API.\n if (!context?.workspaceId) {\n return new Map();\n }\n\n // Cross-layer flag evaluation transits the global PUBLIC gateway, which\n // strips raw actor headers unless the request carries a valid JWT. Use an\n // explicit serviceToken if provided, otherwise mint a short-lived `service`\n // actor JWT (no-op when SERVICE_JWT_SECRET is unset → falls back to header\n // context for same-env/internal-gateway evaluation).\n const bearerToken = this.serviceToken ?? (await signServiceJwt(this.serviceName)) ?? undefined;\n\n // Fetch from API\n try {\n const response = await fetch(this.gatewayUrl, {\n method: 'POST',\n // Bounded: an unreachable gateway must cost milliseconds-to-seconds,\n // never the kernel's TCP connect timeout. On abort the catch below\n // negative-caches and callers fall back to their defaults.\n signal: AbortSignal.timeout(this.requestTimeoutMs),\n headers: {\n 'Content-Type': 'application/json',\n ...(context.actorId && { 'x-actor-id': context.actorId }),\n 'x-actor-type': context.actorType ?? this.defaultActorType,\n 'x-workspace-id': context.workspaceId,\n ...(bearerToken && { Authorization: `Bearer ${bearerToken}` }),\n // Re-present the inbound CF Access service token when the flag check\n // runs against a CF-Access-gated public gateway (alpha). No-op when\n // request context carries no CF creds (local dev, production).\n ...ContextManager.getCfAccessHeaders(),\n },\n body: JSON.stringify({\n query: EVALUATE_QUERY,\n variables: {\n input: {\n workspaceId: context.workspaceId,\n keys: keys ?? null,\n },\n },\n }),\n });\n\n if (!response.ok) {\n // Return empty map on error — default-allow handled by callers\n return this.rememberFailure(cacheKey);\n }\n\n const json = (await response.json()) as {\n data?: {\n evaluateFeatureFlags?: {\n evaluations?: FlagEvaluation[];\n };\n };\n errors?: Array<{ message: string }>;\n };\n\n if (json.errors || !json.data?.evaluateFeatureFlags?.evaluations) {\n return this.rememberFailure(cacheKey);\n }\n\n const evaluations = new Map<string, FlagEvaluation>();\n for (const evaluation of json.data.evaluateFeatureFlags.evaluations) {\n evaluations.set(evaluation.key, evaluation);\n }\n\n // Cache the results\n this.cache.set(cacheKey, {\n evaluations,\n expiresAt: Date.now() + this.cacheTtlMs,\n });\n\n return evaluations;\n } catch {\n // On network error/timeout, return empty map (default-allow handled by\n // callers) and negative-cache so the next evaluations in the window\n // skip the doomed request entirely.\n return this.rememberFailure(cacheKey);\n }\n }\n\n /**\n * Negative-cache a failed fetch: remember an empty evaluation set for\n * `failureTtlMs` so a broken/unreachable gateway costs at most one request\n * timeout per window instead of one per flag evaluation.\n */\n private rememberFailure(cacheKey: string): Map<string, FlagEvaluation> {\n const evaluations = new Map<string, FlagEvaluation>();\n this.cache.set(cacheKey, {\n evaluations,\n expiresAt: Date.now() + this.failureTtlMs,\n });\n return evaluations;\n }\n\n /**\n * Build a cache key from the evaluation context.\n *\n * Safe against undefined/null context — callers like isEnabled() may\n * pass no context during service boot (e.g. checking a default-allow\n * feature flag at startup before the first request builds a real\n * actor context). Without the guard, isEnabled(flag) used to throw\n * \"undefined is not an object (evaluating 'context.workspaceId')\"\n * and crash the svc at startServer().\n */\n private buildCacheKey(context: EvaluationContext | undefined): string {\n const ctx = context ?? ({} as EvaluationContext);\n return `${ctx.workspaceId ?? 'system'}:${ctx.actorId ?? 'anonymous'}:${ctx.actorType ?? 'user'}`;\n }\n}\n","/**\n * Operations Feature-Flag Gate Plugin\n *\n * GraphQL-Yoga/envelop plugin factory that short-circuits GraphQL operations\n * when a product's operations feature flag is OFF, returning a clean typed\n * `FEATURE_DISABLED` (HTTP 403) error before any resolver runs.\n *\n * This is the shared, fleet-wide replacement for the per-service inline\n * `operations-feature-flag` / `feature-flag-gate` plugins (movethewheels,\n * manufacturedops, …). By default it gates MUTATIONS only; queries and\n * subscriptions pass through.\n *\n * Default-allow philosophy (matches {@link FeatureFlagProvider.isEnabled}): if\n * there is no workspace context, or the flag service is unreachable / the flag\n * is unknown, the operation is ALLOWED. A flag must be explicitly disabled for\n * the workspace to block traffic.\n *\n * @module feature-flags/operations-flag-gate\n * @category FeatureFlags\n *\n * @example\n * ```typescript\n * import { createOperationsFlagGatePlugin } from '@burdenoff/be-sdk/feature-flags';\n *\n * yogaPlugins: [\n * createOperationsFlagGatePlugin({\n * flagKey: 'movethewheels.operations',\n * productId: 'movethewheels',\n * }),\n * useGraphQLModules(application),\n * ];\n * ```\n */\n\nimport { type DocumentNode, GraphQLError, Kind, type OperationDefinitionNode } from 'graphql';\n\nimport { logger } from '../logger/index.js';\nimport type { YogaPlugin } from '../server/index.js';\nimport { FeatureFlagProvider } from './provider.js';\nimport type { EvaluationContext } from './types.js';\n\n/** GraphQL operation types that a gate can be configured to short-circuit. */\nexport type GatedOperationType = 'query' | 'mutation' | 'subscription';\n\nexport interface OperationsFlagGatePluginOptions {\n /** Feature flag key that gates the operations (e.g. `'movethewheels.operations'`). */\n flagKey: string;\n /** Product identifier this gate protects. Surfaced in the error extensions + logs. */\n productId: string;\n /**\n * Provider used to evaluate the flag. When omitted, a {@link FeatureFlagProvider}\n * is lazily built from `gatewayUrl` (or `GLOBAL_PUBLIC_GATEWAY_URL` /\n * `GLOBAL_INT_GATEWAY_URL`).\n */\n provider?: FeatureFlagProvider;\n /** Gateway URL for the lazily-built default provider. Ignored when `provider` is set. */\n gatewayUrl?: string;\n /** Cache TTL (seconds) for the lazily-built default provider. Default: 60. */\n cacheTtlSeconds?: number;\n /** Which operation types to gate. Default: `['mutation']`. */\n gatedOperations?: readonly GatedOperationType[];\n /** Override the user-facing error message shown when the flag is disabled. */\n userMessage?: string;\n}\n\n/** Actor/workspace fields the gate reads off the GraphQL context (either shape). */\ninterface GateContextShape {\n workspace?: { id?: string | null } | null;\n actor?: { id?: string | null; type?: string | null } | null;\n workspaceId?: string | null;\n actorId?: string | null;\n actorType?: string | null;\n}\n\nconst ACTOR_TYPES: readonly string[] = ['user', 'app', 'service', 'super_admin'];\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isDocumentNode(value: unknown): value is DocumentNode {\n return isRecord(value) && Array.isArray((value as { definitions?: unknown }).definitions);\n}\n\n/** Find the operation that will actually execute for this request. */\nfunction findExecutedOperation(document: DocumentNode, operationName?: string | null): OperationDefinitionNode | null {\n const operations = document.definitions.filter(\n (definition): definition is OperationDefinitionNode => definition.kind === Kind.OPERATION_DEFINITION\n );\n\n if (operationName) {\n return operations.find((operation) => operation.name?.value === operationName) ?? null;\n }\n // Unnamed / single-operation request executes the first (only) operation.\n return operations[0] ?? null;\n}\n\nfunction coerceActorType(value: string | null | undefined): EvaluationContext['actorType'] {\n // Cast is sound: only reached after `ACTOR_TYPES.includes(value)` proves the\n // string is one of the known actor-type literals.\n return value && ACTOR_TYPES.includes(value) ? (value as EvaluationContext['actorType']) : undefined;\n}\n\n/**\n * Build the flag {@link EvaluationContext} from the GraphQL context, tolerating\n * both the nested (`workspace.id` / `actor.id`) and flat (`workspaceId` /\n * `actorId`) shapes. Returns `null` when no workspace can be resolved.\n */\nfunction resolveEvaluationContext(contextValue: unknown): EvaluationContext | null {\n // Cast to the fully-optional GateContextShape after the record guard; every\n // field is read defensively with optional chaining below.\n const ctx = (isRecord(contextValue) ? contextValue : {}) as GateContextShape;\n const workspaceId = ctx.workspace?.id ?? ctx.workspaceId ?? undefined;\n if (!workspaceId) {\n return null;\n }\n const actorId = ctx.actor?.id ?? ctx.actorId ?? undefined;\n const actorType = coerceActorType(ctx.actor?.type ?? ctx.actorType);\n return {\n workspaceId,\n ...(actorId ? { actorId } : {}),\n ...(actorType ? { actorType } : {}),\n };\n}\n\n/**\n * Create a GraphQL-Yoga/envelop plugin that gates operations behind a product\n * feature flag. Returns a {@link YogaPlugin} ready to drop into a service's\n * `yogaPlugins` array.\n */\nexport function createOperationsFlagGatePlugin(options: OperationsFlagGatePluginOptions): YogaPlugin {\n const { flagKey, productId } = options;\n const gatedOperations = new Set<string>(options.gatedOperations ?? ['mutation']);\n const userMessage = options.userMessage ?? 'This operation is currently unavailable.';\n\n let provider = options.provider ?? null;\n const getProvider = (): FeatureFlagProvider => {\n if (!provider) {\n provider = new FeatureFlagProvider({\n gatewayUrl:\n options.gatewayUrl ?? process.env['GLOBAL_PUBLIC_GATEWAY_URL'] ?? process.env['GLOBAL_INT_GATEWAY_URL'] ?? '',\n cacheTtlSeconds: options.cacheTtlSeconds ?? 60,\n defaultActorType: 'service',\n });\n }\n return provider;\n };\n\n return {\n async onExecute({\n args,\n }: {\n args: {\n document?: unknown;\n operationName?: string | null;\n variableValues?: Record<string, unknown>;\n contextValue?: unknown;\n };\n }): Promise<void> {\n if (!isDocumentNode(args.document)) {\n return;\n }\n\n const operation = findExecutedOperation(args.document, args.operationName);\n if (!operation || !gatedOperations.has(operation.operation)) {\n return; // Not a gated operation type — allow.\n }\n\n const evaluationContext = resolveEvaluationContext(args.contextValue);\n if (!evaluationContext) {\n // No workspace context to evaluate against → default-allow.\n logger.warn('[OperationsFlagGate] no workspace context — allowing operation', { flagKey, productId });\n return;\n }\n\n let enabled = true;\n try {\n enabled = await getProvider().isEnabled(flagKey, evaluationContext);\n } catch (error) {\n // Never let a flag-service failure block traffic (default-allow).\n logger.warn('[OperationsFlagGate] flag evaluation failed — allowing operation', {\n flagKey,\n productId,\n error: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n\n if (!enabled) {\n logger.warn('[OperationsFlagGate] flag disabled — blocking operation', {\n flagKey,\n productId,\n workspaceId: evaluationContext.workspaceId,\n });\n throw new GraphQLError(userMessage, {\n extensions: {\n code: 'FEATURE_DISABLED',\n flagKey,\n productId,\n http: { status: 403 },\n },\n });\n }\n },\n };\n}\n","/**\n * Feature Flags Module\n *\n * In-house feature flag evaluation for Burdenoff backend services.\n * Compatible with OpenFeature specification concepts.\n *\n * @module feature-flags\n * @category FeatureFlags\n *\n * @example\n * ```typescript\n * import { FeatureFlagProvider } from '@burdenoff/be-sdk/feature-flags';\n *\n * // Create provider (typically done once at service startup)\n * const provider = new FeatureFlagProvider({\n * gatewayUrl: process.env.GLOBAL_INT_GATEWAY_URL || 'http://global-int-gateway:4000/global/graphql',\n * cacheTtlSeconds: 60,\n * });\n *\n * // Check a boolean flag\n * const ctx = { actorId: 'user-123', actorType: 'user' as const, workspaceId: 'ws-456' };\n * const isEnabled = await provider.isEnabled('calendar.recurring-events', ctx);\n *\n * // Resolve with full details\n * const details = await provider.resolveBoolean('calendar.recurring-events', true, ctx);\n * console.log(details.value); // true\n * console.log(details.reason); // 'TARGETING_MATCH'\n * console.log(details.variant); // 'user-opted-in'\n * ```\n */\n\nexport { FeatureFlagProvider } from './provider.js';\nexport type {\n EvaluationContext,\n FeatureFlagProviderConfig,\n FlagEvaluation,\n FlagType,\n ResolutionDetails,\n} from './types.js';\n\nexport { createOperationsFlagGatePlugin } from './operations-flag-gate.js';\nexport type { OperationsFlagGatePluginOptions, GatedOperationType } from './operations-flag-gate.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;AAsBvB,SAAS,mBAAmB,MAAc,UAA0B;CAClE,MAAM,MAAM,QAAQ,IAAI;CACxB,IAAI,CAAC,KAAK,OAAO;CACjB,MAAM,SAAS,SAAS,KAAK,EAAE;CAC/B,OAAO,OAAO,SAAS,MAAM,KAAK,SAAS,IAAI,SAAS;AAC1D;AAEA,IAAa,sBAAb,MAAiC;CAC/B,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;;CAGjB,AAAiB,wBAAQ,IAAI,IAAwB;CAErD,YAAY,QAAmC;EAC7C,KAAK,aAAa,OAAO;EACzB,KAAK,cAAc,OAAO,mBAAmB,MAAM;EAMnD,KAAK,mBAAmB,OAAO,oBAAoB,mBAAmB,mCAAmC,GAAI;EAG7G,KAAK,gBAAgB,OAAO,qBAAqB,mBAAmB,oCAAoC,EAAE,KAAK;EAC/G,KAAK,eAAe,OAAO;EAC3B,KAAK,cAAc,OAAO,eAAe,QAAQ,IAAI,mBAAmB;EACxE,KAAK,mBAAmB,OAAO,oBAAoB;CACrD;;;;;;;;;CAcA,MAAM,eACJ,SACA,cACA,SACqC;EACrC,MAAM,aAAa,MAAM,KAAK,cAAc,SAAS,OAAO;EAC5D,IAAI,CAAC,YACH,OAAO;GACL,OAAO;GACP,QAAQ;GACR,UAAU;EACZ;EAGF,OAAO;GACL,OAAO,QAAQ,WAAW,KAAK;GAC/B,SAAS,WAAW,WAAW;GAC/B,QAAQ,WAAW;GACnB,UAAU,WAAW;GACrB,WAAW,WAAW,aAAa;EACrC;CACF;;;;CAKA,MAAM,cACJ,SACA,cACA,SACoC;EACpC,MAAM,aAAa,MAAM,KAAK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