/** * Public flag-evaluation API. * * `evaluateFlag(name, ctx)` orchestrates: * * 1. Storage-load (delegated to a {@link FlagLoader} callback — keeps * this package decoupled from `@hivegrid/db`). * 2. Time-window check (`enabledFrom`/`enabledUntil`). * 3. Dependency-resolution — parent flag must itself be enabled. * 4. Targeting-rule evaluation via {@link evaluateRule}. * 5. Variant-selection — sticky bucket over the variants array using * SHA1(userId+flagName), so a user always gets the same variant. * * Returns a structured result `{ enabled, variant?, reason }`. `reason` * is a short tag (e.g. `"disabled"`, `"parent-disabled"`, `"matched"`, * `"no-match"`, `"time-window-future"`) — safe to log / display, never * contains PII pulled from the context. */ import { evaluateRule } from "./targeting/evaluator.js"; import { computeBucket } from "./targeting/percentage.js"; import type { EvaluationContext, TargetingRule } from "./targeting/types.js"; /** * Storage shape returned by {@link FlagLoader}. Matches a subset of the * Prisma `FeatureFlag` row, but typed loosely (`unknown`) for * `rules` / `variants` so the package itself stays Prisma-free. */ export interface StoredFeatureFlag { readonly id: string; readonly name: string; readonly enabled: boolean; readonly rules: unknown; readonly variants: readonly unknown[]; readonly enabledFrom: Date | null; readonly enabledUntil: Date | null; readonly parentFlagId: string | null; } export interface FlagVariant { readonly key: string; /** Optional weight; treated as 1 if missing. Negative coerces to 0. */ readonly weight?: number; readonly value?: unknown; } export type FlagLoader = (name: string) => Promise; export interface EvaluateFlagResult { readonly enabled: boolean; readonly variant?: FlagVariant; readonly reason: | "flag-not-found" | "disabled" | "parent-disabled" | "parent-not-found" | "time-window-future" | "time-window-expired" | "no-match" | "matched"; } export interface EvaluateFlagOptions { readonly load: FlagLoader; /** Cap dependency-chain depth to prevent loops. Default 8. */ readonly maxDepth?: number; } const DEFAULT_MAX_DEPTH = 8; const RESULT_FLAG_NOT_FOUND = Object.freeze({ enabled: false, reason: "flag-not-found" as const }); const RESULT_DISABLED = Object.freeze({ enabled: false, reason: "disabled" as const }); const RESULT_PARENT_DISABLED = Object.freeze({ enabled: false, reason: "parent-disabled" as const }); const RESULT_PARENT_NOT_FOUND = Object.freeze({ enabled: false, reason: "parent-not-found" as const }); const RESULT_TIME_FUTURE = Object.freeze({ enabled: false, reason: "time-window-future" as const }); const RESULT_TIME_EXPIRED = Object.freeze({ enabled: false, reason: "time-window-expired" as const }); const RESULT_NO_MATCH = Object.freeze({ enabled: false, reason: "no-match" as const }); export async function evaluateFlag( name: string, ctx: EvaluationContext, options: EvaluateFlagOptions, ): Promise { const flag = await options.load(name); if (!flag) return RESULT_FLAG_NOT_FOUND; if (!flag.enabled) return RESULT_DISABLED; const now = ctx.now ?? new Date(); if (flag.enabledFrom && now.getTime() < flag.enabledFrom.getTime()) { return RESULT_TIME_FUTURE; } if (flag.enabledUntil && now.getTime() > flag.enabledUntil.getTime()) { return RESULT_TIME_EXPIRED; } // Dependency-resolution: parent must itself be enabled. const parentDecision = await resolveParent(flag, ctx, options, 0); if (parentDecision !== "ok") return parentDecision === "missing" ? RESULT_PARENT_NOT_FOUND : RESULT_PARENT_DISABLED; // Targeting eval. If no rules → flag is on for everyone matching the // boolean `enabled`. If a rules-tree is present, evaluate it. const rule = parseRule(flag.rules); if (rule && !evaluateRule(rule, { ...ctx, flagName: name })) { return RESULT_NO_MATCH; } // Variant-selection — sticky by userId, fall back to tenantId, then // to a stable hash of `name` itself when neither is present (so // anonymous traffic still gets a single deterministic variant). const variant = pickVariant(name, flag.variants, ctx); if (variant) { return { enabled: true, variant, reason: "matched" }; } return { enabled: true, reason: "matched" }; } async function resolveParent( flag: StoredFeatureFlag, ctx: EvaluationContext, options: EvaluateFlagOptions, depth: number, ): Promise<"ok" | "disabled" | "missing"> { if (!flag.parentFlagId) return "ok"; const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH; if (depth >= maxDepth) return "disabled"; // suspect cycle → fail-closed // Parent is looked up by its own row, not by name — we don't know // the parent's name from the FK alone, so we ask the loader to do it. const parent = await loadById(flag.parentFlagId, options); if (!parent) return "missing"; if (!parent.enabled) return "disabled"; const now = ctx.now ?? new Date(); if (parent.enabledFrom && now.getTime() < parent.enabledFrom.getTime()) return "disabled"; if (parent.enabledUntil && now.getTime() > parent.enabledUntil.getTime()) return "disabled"; const parentRule = parseRule(parent.rules); if (parentRule && !evaluateRule(parentRule, { ...ctx, flagName: parent.name })) { return "disabled"; } return resolveParent(parent, ctx, options, depth + 1); } /** * The loader contract is keyed by **name**, not id. We map id→name by * scanning a tiny in-memory cache populated by `load`. For now we * delegate to a wrapper that calls `load` with the id used as the * lookup key — callers that want true id-based loading should pass a * loader that handles both id and name. The default implementation * shipped with this package only matches on `id === arg`. */ async function loadById( id: string, options: EvaluateFlagOptions, ): Promise { // The loader is name-keyed by spec but we re-use the same callback — // the canonical web-app loader (`createPrismaFlagLoader`) accepts // either an id or a name and dedupes via Prisma OR-where. Tests in // evaluate.test.ts assert this contract. return options.load(id); } function parseRule(raw: unknown): TargetingRule | null { if (raw === null || raw === undefined) return null; if (typeof raw !== "object") return null; if (!("type" in (raw as Record))) return null; return raw as TargetingRule; } function pickVariant( flagName: string, variants: readonly unknown[], ctx: EvaluationContext, ): FlagVariant | undefined { if (!variants || variants.length === 0) return undefined; const parsed: FlagVariant[] = []; for (const raw of variants) { if (raw && typeof raw === "object" && "key" in (raw as Record)) { parsed.push(raw as FlagVariant); } } if (parsed.length === 0) return undefined; if (parsed.length === 1) return parsed[0]; const bucketKey = ctx.userId ?? ctx.tenantId ?? flagName; const bucket = computeBucket(bucketKey, `${flagName}:variant`); const totalWeight = parsed.reduce((sum, v) => sum + normalizeWeight(v.weight), 0); if (totalWeight <= 0) { // Even distribution. const idx = bucket % parsed.length; return parsed[idx]; } const target = (bucket / 100) * totalWeight; let cursor = 0; for (const v of parsed) { cursor += normalizeWeight(v.weight); if (target < cursor) return v; } return parsed[parsed.length - 1]; } function normalizeWeight(raw: number | undefined): number { if (raw === undefined || raw === null) return 1; if (!Number.isFinite(raw) || raw < 0) return 0; return raw; } /** * Convenience wrapper — returns just the variant or `null` when the * flag is disabled / has no variants. */ export async function getFeatureFlagVariant( name: string, ctx: EvaluationContext, options: EvaluateFlagOptions, ): Promise { const result = await evaluateFlag(name, ctx, options); if (!result.enabled) return null; return result.variant ?? null; }