From 5a6fa18a83390e7b94e62f611bb51e446563b337 Mon Sep 17 00:00:00 2001 From: Dennis Paler Date: Sat, 21 Nov 2026 21:09:27 +0800 Subject: [PATCH 01/38] =?UTF-8?q?feat(core):=20explain()=20=E2=80=94=20eva?= =?UTF-8?q?luation=20reason,=20matched=20rule,=20bucket=20and=20prerequisi?= =?UTF-8?q?te=20trace?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The evaluator becomes generic over a Trace observer. evaluate_variant runs it with NoTrace (empty methods, compiled away); explain() runs the very same function with a recorder. One evaluator, two views — no second copy of the targeting semantics for OpenFeature details, the Python SDK or the evaluation playground to drift from. Reasons follow the OpenFeature vocabulary (DISABLED, TARGETING_MATCH, SPLIT, DEFAULT, STATIC) plus PREREQUISITE_FAILED and ROLLOUT_EXCLUDED. Adds sdks/conformance/vectors/evaluation.json: 28 flags, 86 cases and 6 malformed configurations, with expectations blessed from the core (core/tests/vectors.rs) for every SDK to check itself against. A randomized test checks explain() == evaluate_variant() over 300 generated configurations. --- bench/benches/evaluation.rs | 11 +- core/src/evaluator.rs | 568 +++++++- core/tests/vectors.rs | 158 +++ sdks/conformance/vectors/evaluation.json | 1514 ++++++++++++++++++++++ 4 files changed, 2222 insertions(+), 29 deletions(-) create mode 100644 core/tests/vectors.rs create mode 100644 sdks/conformance/vectors/evaluation.json diff --git a/bench/benches/evaluation.rs b/bench/benches/evaluation.rs index 39b4f987..d9eb6198 100644 --- a/bench/benches/evaluation.rs +++ b/bench/benches/evaluation.rs @@ -20,7 +20,7 @@ //! evaluation, retained bytes per stored flag) is printed as JSON lines, //! measured with a counting global allocator. -use checkgate_core::evaluator::{Flag, UserContext, evaluate, evaluate_variant}; +use checkgate_core::evaluator::{Flag, UserContext, evaluate, evaluate_variant, explain}; use checkgate_core::store::FlagStore; use criterion::{BenchmarkId, Criterion, Throughput, criterion_group}; use serde_json::json; @@ -284,6 +284,15 @@ fn rules(c: &mut Criterion) { g.bench_function("weighted_multivariate", |b| { b.iter(|| evaluate_variant(&store.get_flag(black_box("mv")).unwrap(), &ctx, &store)) }); + // The detailed path (OpenFeature details, the playground): same + // evaluator with a recorder, so its cost over the plain call is the + // price of the explanation alone. + g.bench_function("explain_targeting_10_rules", |b| { + b.iter(|| explain(&store.get_flag(black_box("t10")).unwrap(), &ctx, &store)) + }); + g.bench_function("explain_percentage_rollout", |b| { + b.iter(|| explain(&store.get_flag(black_box("rollout")).unwrap(), &ctx, &store)) + }); // Depth counts flags in the chain: 2 = a flag with one prerequisite. for depth in [2usize, 3, 5] { let s = store_with(1_000); diff --git a/core/src/evaluator.rs b/core/src/evaluator.rs index ac878aad..2530d96d 100644 --- a/core/src/evaluator.rs +++ b/core/src/evaluator.rs @@ -202,11 +202,28 @@ fn disabled_result(flag: &Flag) -> EvalResult { /// weights. Salted independently from the rollout-percentage hash (`:variant` suffix) /// so variant assignment doesn't correlate with which users pass the rollout gate. /// Zero total weight (all-zero or empty) falls back to the first variant. +#[cfg(test)] fn pick_weighted_variant( flag_key: &str, user_key: &str, variants: &[WeightedVariant], ) -> FlagValue { + weighted_variant_index(flag_key, user_key, variants) + .and_then(|i| variants.get(i)) + .map(|v| v.value.clone()) + .unwrap_or(FlagValue::Null) +} + +/// The index of the variant [`pick_weighted_variant`] returns, or `None` when +/// `variants` is empty. +fn weighted_variant_index( + flag_key: &str, + user_key: &str, + variants: &[WeightedVariant], +) -> Option { + if variants.is_empty() { + return None; + } let total: u64 = variants .iter() .map(|v| u64::from(v.weight)) @@ -216,10 +233,7 @@ fn pick_weighted_variant( // type-level guarantee: `u64 % NonZeroU64` cannot divide by zero, so the // remainder below has no panic path at all. let Some(total_weight) = NonZeroU64::new(total) else { - return variants - .first() - .map(|v| v.value.clone()) - .unwrap_or(FlagValue::Null); + return Some(0); }; // Hashes the bytes of `"{flag_key}:{user_key}:variant"` without building @@ -237,17 +251,21 @@ fn pick_weighted_variant( }; let mut cumulative = 0u64; - for variant in variants { + for (index, variant) in variants.iter().enumerate() { cumulative = cumulative.saturating_add(u64::from(variant.weight)); if bucket < cumulative { - return variant.value.clone(); + return Some(index); } } // Unreachable given bucket < total_weight == final cumulative, but guard anyway. - variants - .last() - .map(|v| v.value.clone()) - .unwrap_or(FlagValue::Null) + Some(variants.len().saturating_sub(1)) +} + +/// The user's rollout bucket for `flag`, in `0..100`. A user is inside a +/// rollout of `p` percent when their bucket is below `p`. +fn rollout_bucket(flag_key: &str, user_key: &str) -> u32 { + // Hashes the bytes of `"{flag_key}:{user_key}"` without building that string. + murmurhash3_x86_32_concat(&[flag_key.as_bytes(), b":", user_key.as_bytes()], 0) % 100 } /// Prerequisite chains deeper than this are treated as unsatisfied (fail closed). @@ -268,33 +286,208 @@ const MAX_PREREQUISITE_DEPTH: usize = 10; /// saved before that check, or written by other means. const MAX_PREREQUISITE_EVALUATIONS: u32 = 1_000; +/// Why an evaluation resolved the way it did. The vocabulary follows the +/// [OpenFeature resolution reasons](https://openfeature.dev/specification/types#resolution-reason), +/// plus the two outcomes OpenFeature has no standard word for. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +#[non_exhaustive] +pub enum Reason { + /// The flag is switched off (`is_enabled: false`). + Disabled, + /// A prerequisite was not satisfied, so the flag resolved as disabled. + PrerequisiteFailed, + /// A targeting rule matched (see [`Explanation::rule_index`]). + TargetingMatch, + /// The user's rollout bucket is outside the rollout percentage, so the + /// flag resolved as disabled (see [`Explanation::rollout_bucket`]). + RolloutExcluded, + /// The outcome was decided by hashing the user key: the user passed a + /// partial rollout, or was assigned a weighted variant. + Split, + /// The flag has targeting rules, none matched, and the user got the + /// flag's default value. + Default, + /// The flag has no rules, partial rollout or variants: every user gets + /// the same value. + Static, +} + +/// How one prerequisite of the explained flag was judged. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "snake_case")] +#[non_exhaustive] +pub enum PrerequisiteOutcome { + /// The prerequisite flag resolved as required. + Satisfied, + /// The prerequisite flag resolved, but not as required. + Unsatisfied, + /// No flag with that key exists (fails closed). + NotFound, + /// The depth or evaluation limit was reached before it could be + /// evaluated (fails closed). + LimitExceeded, +} + +/// One prerequisite of the explained flag, in the order they were checked. +/// Checking stops at the first prerequisite that is not satisfied, so later +/// ones are absent. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[non_exhaustive] +pub struct PrerequisiteCheck { + pub flag_key: String, + pub outcome: PrerequisiteOutcome, + /// The value the prerequisite must resolve to; `None` means "enabled". + #[serde(default, skip_serializing_if = "Option::is_none")] + pub required_value: Option, + /// What the prerequisite resolved to; `None` when it was not evaluated. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub result: Option, +} + +/// An evaluation together with the path that produced it: the same result +/// [`evaluate_variant`] returns, from the same code, plus why. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[non_exhaustive] +pub struct Explanation { + pub enabled: bool, + pub value: FlagValue, + pub reason: Reason, + /// Index into `Flag::rules` of the rule that matched. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rule_index: Option, + /// The user's rollout bucket (`0..100`) when a partial rollout + /// (`0 < rollout_percentage < 100`) was checked. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rollout_bucket: Option, + /// Index into `Flag::variants` of the weighted variant assigned. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub variant_index: Option, + /// The flag's own prerequisites as they were checked (not those of + /// prerequisites further down the chain). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub prerequisites: Vec, +} + +impl Explanation { + /// The plain result, as [`evaluate_variant`] returns it. + #[must_use] + pub fn result(&self) -> EvalResult { + EvalResult { + enabled: self.enabled, + value: self.value.clone(), + } + } +} + +/// Observes the decisions one evaluation makes. [`evaluate_variant`] runs with +/// [`NoTrace`], whose empty methods compile away, so the hot path is the same +/// machine code it was before explanations existed; [`explain`] runs the very +/// same function with a recorder. One evaluator, two views of it. +trait Trace { + fn reason(&mut self, _reason: Reason) {} + fn rule(&mut self, _index: usize) {} + fn rollout_bucket(&mut self, _bucket: u32) {} + fn variant(&mut self, _index: usize) {} + /// Only called for the top-level flag's own prerequisites. + fn prerequisite(&mut self, _check: PrerequisiteCheck) {} + /// Whether [`Trace::prerequisite`] does anything; lets the caller skip + /// building the check (it clones values) when nobody records it. + fn records_prerequisites(&self) -> bool { + false + } +} + +struct NoTrace; +impl Trace for NoTrace {} + +#[derive(Default)] +struct Recorder { + reason: Option, + rule_index: Option, + rollout_bucket: Option, + variant_index: Option, + prerequisites: Vec, +} + +impl Trace for Recorder { + fn reason(&mut self, reason: Reason) { + self.reason = Some(reason); + } + fn rule(&mut self, index: usize) { + self.rule_index = Some(index); + } + fn rollout_bucket(&mut self, bucket: u32) { + self.rollout_bucket = Some(bucket); + } + fn variant(&mut self, index: usize) { + self.variant_index = Some(index); + } + fn prerequisite(&mut self, check: PrerequisiteCheck) { + self.prerequisites.push(check); + } + fn records_prerequisites(&self) -> bool { + true + } +} + /// Evaluate a flag and return both the on/off result and the resolved variant value. /// Use this for non-boolean flags (string / integer / JSON variants). `store` is /// used to resolve the flag's prerequisites (if any) — pass the same store the /// flag itself was looked up from. pub fn evaluate_variant(flag: &Flag, user_context: &UserContext, store: &FlagStore) -> EvalResult { let mut budget = MAX_PREREQUISITE_EVALUATIONS; - evaluate_variant_at_depth(flag, user_context, store, 0, &mut budget) + evaluate_variant_at_depth(flag, user_context, store, 0, &mut budget, &mut NoTrace) +} + +/// Evaluate a flag and report why it resolved as it did: the reason, the +/// matched rule, the rollout bucket, the weighted variant and the outcome of +/// each prerequisite. The result is the one [`evaluate_variant`] returns for +/// the same inputs, computed by the same code. Costs more than +/// `evaluate_variant` (it records the path), so use it for debugging and +/// detailed SDK APIs, not as the default evaluation. +#[must_use] +pub fn explain(flag: &Flag, user_context: &UserContext, store: &FlagStore) -> Explanation { + let mut budget = MAX_PREREQUISITE_EVALUATIONS; + let mut recorder = Recorder::default(); + let result = + evaluate_variant_at_depth(flag, user_context, store, 0, &mut budget, &mut recorder); + Explanation { + enabled: result.enabled, + value: result.value, + // Every return path of the evaluator reports a reason; `Disabled` is + // the fail-closed answer should one ever be added without it. + reason: recorder.reason.unwrap_or(Reason::Disabled), + rule_index: recorder.rule_index, + rollout_bucket: recorder.rollout_bucket, + variant_index: recorder.variant_index, + prerequisites: recorder.prerequisites, + } } -fn evaluate_variant_at_depth( +fn evaluate_variant_at_depth( flag: &Flag, user_context: &UserContext, store: &FlagStore, depth: usize, budget: &mut u32, + trace: &mut T, ) -> EvalResult { if !flag.is_enabled { + trace.reason(Reason::Disabled); return disabled_result(flag); } - if !prerequisites_satisfied(flag, user_context, store, depth, budget) { + if !prerequisites_satisfied(flag, user_context, store, depth, budget, trace) { + trace.reason(Reason::PrerequisiteFailed); return disabled_result(flag); } // Targeting rules — first match wins; per-rule variant overrides the flag default. - for rule in &flag.rules { + for (index, rule) in flag.rules.iter().enumerate() { if rule_matches(rule, user_context) { + trace.reason(Reason::TargetingMatch); + trace.rule(index); let value = rule .variant .clone() @@ -308,30 +501,43 @@ fn evaluate_variant_at_depth( } // Rollout bucket check + let mut hashed = false; if let Some(percentage) = flag.rollout_percentage { if percentage == 0 { + trace.reason(Reason::RolloutExcluded); return disabled_result(flag); } if percentage < 100 { - // Hashes the bytes of `"{flag.key}:{user_context.key}"` without - // building that string. - let hash_val = murmurhash3_x86_32_concat( - &[flag.key.as_bytes(), b":", user_context.key.as_bytes()], - 0, - ); - if hash_val % 100 >= percentage { + let bucket = rollout_bucket(&flag.key, &user_context.key); + trace.rollout_bucket(bucket); + if bucket >= percentage { + trace.reason(Reason::RolloutExcluded); return disabled_result(flag); } + hashed = true; } } - let value = if !flag.variants.is_empty() { - pick_weighted_variant(&flag.key, &user_context.key, &flag.variants) + let value = + if let Some(index) = weighted_variant_index(&flag.key, &user_context.key, &flag.variants) { + trace.variant(index); + hashed = true; + flag.variants + .get(index) + .map(|v| v.value.clone()) + .unwrap_or(FlagValue::Null) + } else { + flag.default_value + .clone() + .unwrap_or_else(|| enabled_default(flag)) + }; + trace.reason(if hashed { + Reason::Split + } else if flag.rules.is_empty() { + Reason::Static } else { - flag.default_value - .clone() - .unwrap_or_else(|| enabled_default(flag)) - }; + Reason::Default + }); EvalResult { enabled: true, @@ -345,26 +551,49 @@ fn evaluate_variant_at_depth( /// cycles, e.g. A requires B, B requires A), or a prerequisite reached after the /// evaluation's `MAX_PREREQUISITE_EVALUATIONS` budget is spent, is treated as /// unsatisfied. Stops at the first unsatisfied prerequisite. -fn prerequisites_satisfied( +/// +/// `trace` sees only this flag's own prerequisites; flags further down the +/// chain are evaluated untraced. +fn prerequisites_satisfied( flag: &Flag, user_context: &UserContext, store: &FlagStore, depth: usize, budget: &mut u32, + trace: &mut T, ) -> bool { if flag.prerequisites.is_empty() { return true; } + let record = trace.records_prerequisites(); + let report = |trace: &mut T, + prereq: &Prerequisite, + outcome: PrerequisiteOutcome, + result: Option<&EvalResult>| { + if record { + trace.prerequisite(PrerequisiteCheck { + flag_key: prereq.flag_key.clone(), + outcome, + required_value: prereq.required_value.clone(), + result: result.cloned(), + }); + } + }; if depth >= MAX_PREREQUISITE_DEPTH { + if let Some(first) = flag.prerequisites.first() { + report(trace, first, PrerequisiteOutcome::LimitExceeded, None); + } return false; } for prereq in &flag.prerequisites { let Some(remaining) = budget.checked_sub(1) else { + report(trace, prereq, PrerequisiteOutcome::LimitExceeded, None); return false; }; *budget = remaining; let Some(prereq_flag) = store.get_flag(&prereq.flag_key) else { + report(trace, prereq, PrerequisiteOutcome::NotFound, None); return false; }; let result = evaluate_variant_at_depth( @@ -373,11 +602,18 @@ fn prerequisites_satisfied( store, depth.saturating_add(1), budget, + &mut NoTrace, ); let satisfied = match &prereq.required_value { Some(required) => result.enabled && &result.value == required, None => result.enabled, }; + let outcome = if satisfied { + PrerequisiteOutcome::Satisfied + } else { + PrerequisiteOutcome::Unsatisfied + }; + report(trace, prereq, outcome, Some(&result)); if !satisfied { return false; } @@ -1560,4 +1796,280 @@ mod tests { FlagValue::Json(json) ); } + + // ----------------------------------------------------------------- + // explain(): same result as evaluate_variant, plus the path taken + // ----------------------------------------------------------------- + + fn ctx(key: &str, attrs: &[(&str, &str)]) -> UserContext { + UserContext { + key: key.into(), + attributes: attrs + .iter() + .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) + .collect(), + } + } + + fn rule(attribute: &str, operator: Operator, values: &[&str]) -> TargetingRule { + TargetingRule { + attribute: attribute.into(), + operator, + values: values.iter().map(|v| (*v).to_owned()).collect(), + segment_key: None, + variant: None, + } + } + + #[test] + fn explain_reports_matched_rule_index() { + let flag = bool_flag( + "f", + true, + Some(0), + vec![ + rule("plan", Operator::Equals, &["pro"]), + rule("country", Operator::Equals, &["PH"]), + ], + ); + let e = explain(&flag, &ctx("u", &[("country", "PH")]), &FlagStore::new()); + assert_eq!(e.reason, Reason::TargetingMatch); + assert_eq!(e.rule_index, Some(1)); + assert!(e.enabled); + let e = explain(&flag, &ctx("u", &[]), &FlagStore::new()); + assert_eq!(e.reason, Reason::RolloutExcluded); + assert_eq!(e.rule_index, None); + assert_eq!(e.rollout_bucket, None, "0% is decided without hashing"); + } + + #[test] + fn explain_reports_rollout_bucket_consistently_with_the_gate() { + let flag = bool_flag("gate", true, Some(40), vec![]); + for i in 0..500 { + let e = explain(&flag, &ctx(&format!("user{i}"), &[]), &FlagStore::new()); + let bucket = e.rollout_bucket.expect("partial rollout is hashed"); + assert!(bucket < 100); + assert_eq!(e.enabled, bucket < 40); + assert_eq!( + e.reason, + if e.enabled { + Reason::Split + } else { + Reason::RolloutExcluded + } + ); + } + } + + #[test] + fn explain_reports_static_default_and_variant() { + let store = FlagStore::new(); + let plain = bool_flag("plain", true, None, vec![]); + assert_eq!( + explain(&plain, &ctx("u", &[]), &store).reason, + Reason::Static + ); + let full = bool_flag("full", true, Some(100), vec![]); + assert_eq!( + explain(&full, &ctx("u", &[]), &store).reason, + Reason::Static + ); + let ruled = bool_flag( + "ruled", + true, + None, + vec![rule("a", Operator::Equals, &["b"])], + ); + assert_eq!( + explain(&ruled, &ctx("u", &[]), &store).reason, + Reason::Default + ); + + let mut weighted = bool_flag("w", true, None, vec![]); + weighted.flag_type = FlagType::String; + weighted.variants = vec![ + WeightedVariant { + weight: 1, + value: FlagValue::Str("x".into()), + }, + WeightedVariant { + weight: 1, + value: FlagValue::Str("y".into()), + }, + ]; + let e = explain(&weighted, &ctx("u", &[]), &store); + assert_eq!(e.reason, Reason::Split); + let index = e.variant_index.unwrap(); + assert_eq!(e.value, weighted.variants[index].value); + } + + #[test] + fn explain_reports_prerequisites_and_stops_at_the_first_failure() { + let store = FlagStore::new(); + store.upsert_flag(bool_flag("on", true, None, vec![])); + store.upsert_flag(bool_flag("off", false, None, vec![])); + let mut flag = bool_flag("child", true, None, vec![]); + flag.prerequisites = vec![ + Prerequisite { + flag_key: "on".into(), + required_value: None, + }, + Prerequisite { + flag_key: "off".into(), + required_value: None, + }, + Prerequisite { + flag_key: "never-checked".into(), + required_value: None, + }, + ]; + let e = explain(&flag, &ctx("u", &[]), &store); + assert_eq!(e.reason, Reason::PrerequisiteFailed); + assert!(!e.enabled); + let outcomes: Vec<_> = e + .prerequisites + .iter() + .map(|p| (p.flag_key.as_str(), p.outcome)) + .collect(); + assert_eq!( + outcomes, + vec![ + ("on", PrerequisiteOutcome::Satisfied), + ("off", PrerequisiteOutcome::Unsatisfied) + ] + ); + assert_eq!( + e.prerequisites[1].result, + Some(EvalResult { + enabled: false, + value: FlagValue::Bool(false) + }) + ); + + flag.prerequisites = vec![Prerequisite { + flag_key: "ghost".into(), + required_value: None, + }]; + let e = explain(&flag, &ctx("u", &[]), &store); + assert_eq!(e.prerequisites[0].outcome, PrerequisiteOutcome::NotFound); + assert_eq!(e.prerequisites[0].result, None); + } + + #[test] + fn explain_reports_a_cycle_as_a_failed_prerequisite() { + let store = FlagStore::new(); + let mut a = bool_flag("a", true, None, vec![]); + a.prerequisites = vec![Prerequisite { + flag_key: "b".into(), + required_value: None, + }]; + let mut b = bool_flag("b", true, None, vec![]); + b.prerequisites = vec![Prerequisite { + flag_key: "a".into(), + required_value: None, + }]; + store.upsert_flag(a.clone()); + store.upsert_flag(b); + let e = explain(&a, &ctx("u", &[]), &store); + assert_eq!(e.reason, Reason::PrerequisiteFailed); + // The direct prerequisite was evaluated (and failed further down). + assert_eq!(e.prerequisites[0].outcome, PrerequisiteOutcome::Unsatisfied); + } + + #[test] + fn explanation_serializes_with_the_documented_wire_names() { + let flag = bool_flag("f", true, Some(50), vec![]); + let e = explain(&flag, &ctx("u", &[]), &FlagStore::new()); + let v = serde_json::to_value(&e).unwrap(); + assert!(v["reason"] == "SPLIT" || v["reason"] == "ROLLOUT_EXCLUDED"); + assert!(v["rollout_bucket"].is_u64()); + assert!(v.get("rule_index").is_none(), "absent fields are omitted"); + assert!(v.get("prerequisites").is_none()); + } + + /// A deterministic stream of pseudo-random numbers (no new dependency). + struct Lcg(u64); + impl Lcg { + fn next(&mut self, bound: u64) -> u64 { + self.0 = self + .0 + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + (self.0 >> 33) % bound + } + } + + #[test] + fn explain_agrees_with_evaluate_variant_on_random_configurations() { + let ops = [ + Operator::Equals, + Operator::NotEquals, + Operator::Contains, + Operator::StartsWith, + Operator::EndsWith, + Operator::GreaterThan, + Operator::GreaterThanOrEqual, + Operator::LessThan, + Operator::LessThanOrEqual, + ]; + let words = ["1", "5", "10", "pro", "free", "ph", "x"]; + let mut rng = Lcg(0x5eed); + for round in 0..300 { + let store = FlagStore::new(); + let count = 6; + for i in 0..count { + let mut f = bool_flag(&format!("f{i}"), rng.next(5) != 0, None, vec![]); + f.rollout_percentage = match rng.next(4) { + 0 => None, + 1 => Some(0), + 2 => Some(100), + _ => Some(u32::try_from(rng.next(100)).unwrap()), + }; + for _ in 0..rng.next(3) { + let mut r = rule( + ["a", "b", "c"][usize::try_from(rng.next(3)).unwrap()], + ops[usize::try_from(rng.next(9)).unwrap()].clone(), + &[words[usize::try_from(rng.next(7)).unwrap()]], + ); + if rng.next(2) == 0 { + r.variant = Some(FlagValue::Str("rule".into())); + } + f.rules.push(r); + } + if rng.next(3) == 0 { + f.flag_type = FlagType::String; + f.variants = (0..rng.next(4)) + .map(|w| WeightedVariant { + weight: u32::try_from(rng.next(5)).unwrap(), + value: FlagValue::Str(format!("v{w}")), + }) + .collect(); + } + for _ in 0..rng.next(3) { + f.prerequisites.push(Prerequisite { + flag_key: format!("f{}", rng.next(count + 1)), + required_value: None, + }); + } + store.upsert_flag(f); + } + for u in 0..20 { + let c = ctx( + &format!("r{round}u{u}"), + &[ + ("a", words[usize::try_from(rng.next(7)).unwrap()]), + ("b", words[usize::try_from(rng.next(7)).unwrap()]), + ], + ); + for f in store.list_flags() { + let e = explain(&f, &c, &store); + assert_eq!(e.result(), evaluate_variant(&f, &c, &store)); + assert_eq!(e.rule_index.is_some(), e.reason == Reason::TargetingMatch); + if let Some(i) = e.rule_index { + assert!(rule_matches(&f.rules[i], &c)); + } + } + } + } + } } diff --git a/core/tests/vectors.rs b/core/tests/vectors.rs new file mode 100644 index 00000000..a08039fd --- /dev/null +++ b/core/tests/vectors.rs @@ -0,0 +1,158 @@ +#![allow( + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::indexing_slicing, + clippy::arithmetic_side_effects, + reason = "test code: a panic here is an assertion failure, not a DoS" +)] +//! The shared evaluation vectors (`sdks/conformance/vectors/evaluation.json`). +//! +//! The Rust core is the oracle: this test checks that the file's `expect` +//! entries are what the core computes, and every SDK checks itself against +//! the same file. After a deliberate semantic change, regenerate with +//! `CHECKGATE_BLESS_VECTORS=1 cargo test -p checkgate-core --test vectors` +//! and review the diff: every changed line is a behaviour change users see. + +use checkgate_core::evaluator::{evaluate_variant, explain, Flag, UserContext}; +use checkgate_core::store::FlagStore; +use serde_json::{json, Value}; +use std::path::PathBuf; + +fn vectors_path() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../sdks/conformance/vectors/evaluation.json") +} + +fn store(doc: &Value) -> FlagStore { + let store = FlagStore::new(); + for flag in doc["flags"].as_array().unwrap() { + let parsed: Flag = serde_json::from_value(flag.clone()) + .unwrap_or_else(|e| panic!("vector flag {} must parse: {e}", flag["key"])); + store.upsert_flag(parsed); + } + store +} + +fn context(case: &Value) -> UserContext { + UserContext { + key: case["user"].as_str().unwrap().to_owned(), + attributes: case["attributes"] + .as_object() + .unwrap() + .iter() + .map(|(k, v)| { + ( + k.clone(), + v.as_str() + .expect("vector attributes are strings") + .to_owned(), + ) + }) + .collect(), + } +} + +/// What every SDK must reproduce for one case, or `null` for a missing flag. +fn expected(store: &FlagStore, case: &Value) -> Value { + let Some(flag) = store.get_flag(case["flag"].as_str().unwrap()) else { + return Value::Null; + }; + let ctx = context(case); + let explanation = explain(&flag, &ctx, store); + // The explanation must be the plain evaluation, plus why. + assert_eq!( + explanation.result(), + evaluate_variant(&flag, &ctx, store), + "explain and evaluate_variant disagree on {}", + case["name"] + ); + let mut out = json!({ + "enabled": explanation.enabled, + "value": explanation.value, + "reason": explanation.reason, + }); + let obj = out.as_object_mut().unwrap(); + if let Some(i) = explanation.rule_index { + obj.insert("rule_index".into(), json!(i)); + } + if let Some(b) = explanation.rollout_bucket { + obj.insert("rollout_bucket".into(), json!(b)); + } + if let Some(i) = explanation.variant_index { + obj.insert("variant_index".into(), json!(i)); + } + out +} + +#[test] +fn vectors_match_the_core() { + let raw = std::fs::read_to_string(vectors_path()).expect("vectors file"); + let mut doc: Value = serde_json::from_str(&raw).expect("vectors are JSON"); + let store = store(&doc); + let bless = std::env::var_os("CHECKGATE_BLESS_VECTORS").is_some(); + + let mut mismatches = Vec::new(); + let mut names = std::collections::HashSet::new(); + for case in doc["cases"].as_array_mut().unwrap() { + assert!( + names.insert(case["name"].as_str().unwrap().to_owned()), + "duplicate case name {}", + case["name"] + ); + let want = expected(&store, case); + if bless { + case["expect"] = want; + } else if case.get("expect") != Some(&want) { + mismatches.push(format!( + "{}: file says {}, core computes {want}", + case["name"], + case.get("expect").unwrap_or(&Value::Null) + )); + } + } + + for bad in doc["malformed"].as_array().unwrap() { + let json = bad["json"].as_str().unwrap(); + assert!( + serde_json::from_str::(json).is_err(), + "malformed vector must be rejected: {json}" + ); + } + + if bless { + let mut text = serde_json::to_string_pretty(&doc).unwrap(); + text.push('\n'); + std::fs::write(vectors_path(), text).unwrap(); + return; + } + assert!( + mismatches.is_empty(), + "{} vector(s) disagree with the core (bless after a deliberate change):\n{}", + mismatches.len(), + mismatches.join("\n") + ); +} + +#[test] +fn every_reason_is_covered() { + // A new reason without a vector would let SDKs drift on it unnoticed. + let raw = std::fs::read_to_string(vectors_path()).unwrap(); + let doc: Value = serde_json::from_str(&raw).unwrap(); + let seen: std::collections::HashSet<&str> = doc["cases"] + .as_array() + .unwrap() + .iter() + .filter_map(|c| c["expect"]["reason"].as_str()) + .collect(); + for reason in [ + "DISABLED", + "PREREQUISITE_FAILED", + "TARGETING_MATCH", + "ROLLOUT_EXCLUDED", + "SPLIT", + "DEFAULT", + "STATIC", + ] { + assert!(seen.contains(reason), "no vector produces {reason}"); + } +} diff --git a/sdks/conformance/vectors/evaluation.json b/sdks/conformance/vectors/evaluation.json new file mode 100644 index 00000000..e4da1c9c --- /dev/null +++ b/sdks/conformance/vectors/evaluation.json @@ -0,0 +1,1514 @@ +{ + "about": "Shared evaluation vectors. Inputs are hand-written; `expect` is produced by the Rust core (CHECKGATE_BLESS_VECTORS=1 cargo test -p checkgate-core --test vectors) and checked by every SDK. `expect: null` means the flag does not exist. Attributes are strings only: SDKs differ on non-string values by documented design.", + "cases": [ + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "STATIC", + "value": true + }, + "flag": "static-on", + "name": "static-on/user-1/{}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "DISABLED", + "value": false + }, + "flag": "off", + "name": "off/user-1/{}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "DISABLED", + "value": "off" + }, + "flag": "string-off-custom", + "name": "string-off-custom/user-1/{}", + "user": "user-1" + }, + { + "attributes": { + "plan": "pro" + }, + "expect": { + "enabled": true, + "reason": "TARGETING_MATCH", + "rule_index": 0, + "value": true + }, + "flag": "rules-plan", + "name": "rules-plan/user-1/{\"plan\": \"pro\"}", + "user": "user-1" + }, + { + "attributes": { + "plan": "team" + }, + "expect": { + "enabled": true, + "reason": "TARGETING_MATCH", + "rule_index": 0, + "value": true + }, + "flag": "rules-plan", + "name": "rules-plan/user-1/{\"plan\": \"team\"}", + "user": "user-1" + }, + { + "attributes": { + "plan": "free" + }, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "value": false + }, + "flag": "rules-plan", + "name": "rules-plan/user-1/{\"plan\": \"free\"}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "value": false + }, + "flag": "rules-plan", + "name": "rules-plan/user-1/{}", + "user": "user-1" + }, + { + "attributes": { + "plan": "pro" + }, + "expect": { + "enabled": true, + "reason": "TARGETING_MATCH", + "rule_index": 0, + "value": true + }, + "flag": "rules-plan-default", + "name": "rules-plan-default/user-1/{\"plan\": \"pro\"}", + "user": "user-1" + }, + { + "attributes": { + "plan": "free" + }, + "expect": { + "enabled": true, + "reason": "DEFAULT", + "value": true + }, + "flag": "rules-plan-default", + "name": "rules-plan-default/user-1/{\"plan\": \"free\"}", + "user": "user-1" + }, + { + "attributes": { + "country": "PH" + }, + "expect": { + "enabled": true, + "reason": "TARGETING_MATCH", + "rule_index": 0, + "value": "asia" + }, + "flag": "multi-rule", + "name": "multi-rule/user-1/{\"country\": \"PH\"}", + "user": "user-1" + }, + { + "attributes": { + "country": "US", + "plan": "enterprise" + }, + "expect": { + "enabled": true, + "reason": "TARGETING_MATCH", + "rule_index": 1, + "value": "enterprise" + }, + "flag": "multi-rule", + "name": "multi-rule/user-1/{\"country\": \"US\", \"plan\": \"enterprise\"}", + "user": "user-1" + }, + { + "attributes": { + "country": "SG", + "plan": "enterprise" + }, + "expect": { + "enabled": true, + "reason": "TARGETING_MATCH", + "rule_index": 0, + "value": "asia" + }, + "flag": "multi-rule", + "name": "multi-rule/user-1/{\"country\": \"SG\", \"plan\": \"enterprise\"}", + "user": "user-1" + }, + { + "attributes": { + "country": "US" + }, + "expect": { + "enabled": true, + "reason": "DEFAULT", + "value": "standard" + }, + "flag": "multi-rule", + "name": "multi-rule/user-1/{\"country\": \"US\"}", + "user": "user-1" + }, + { + "attributes": { + "age": "17" + }, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "value": false + }, + "flag": "adults", + "name": "adults/user-1/{\"age\": \"17\"}", + "user": "user-1" + }, + { + "attributes": { + "age": "18" + }, + "expect": { + "enabled": true, + "reason": "TARGETING_MATCH", + "rule_index": 0, + "value": true + }, + "flag": "adults", + "name": "adults/user-1/{\"age\": \"18\"}", + "user": "user-1" + }, + { + "attributes": { + "age": "18.0" + }, + "expect": { + "enabled": true, + "reason": "TARGETING_MATCH", + "rule_index": 0, + "value": true + }, + "flag": "adults", + "name": "adults/user-1/{\"age\": \"18.0\"}", + "user": "user-1" + }, + { + "attributes": { + "age": " 30 " + }, + "expect": { + "enabled": true, + "reason": "TARGETING_MATCH", + "rule_index": 0, + "value": true + }, + "flag": "adults", + "name": "adults/user-1/{\"age\": \" 30 \"}", + "user": "user-1" + }, + { + "attributes": { + "age": "abc" + }, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "value": false + }, + "flag": "adults", + "name": "adults/user-1/{\"age\": \"abc\"}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "value": false + }, + "flag": "adults", + "name": "adults/user-1/{}", + "user": "user-1" + }, + { + "attributes": { + "score": "10" + }, + "expect": { + "enabled": true, + "reason": "TARGETING_MATCH", + "rule_index": 0, + "value": true + }, + "flag": "numeric-lt", + "name": "numeric-lt/user-1/{\"score\": \"10\"}", + "user": "user-1" + }, + { + "attributes": { + "score": "10.5" + }, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "value": false + }, + "flag": "numeric-lt", + "name": "numeric-lt/user-1/{\"score\": \"10.5\"}", + "user": "user-1" + }, + { + "attributes": { + "score": "-3" + }, + "expect": { + "enabled": true, + "reason": "TARGETING_MATCH", + "rule_index": 0, + "value": true + }, + "flag": "numeric-lt", + "name": "numeric-lt/user-1/{\"score\": \"-3\"}", + "user": "user-1" + }, + { + "attributes": { + "score": "1e1" + }, + "expect": { + "enabled": true, + "reason": "TARGETING_MATCH", + "rule_index": 0, + "value": true + }, + "flag": "numeric-lt", + "name": "numeric-lt/user-1/{\"score\": \"1e1\"}", + "user": "user-1" + }, + { + "attributes": { + "plan": "free" + }, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "value": false + }, + "flag": "not-free", + "name": "not-free/user-1/{\"plan\": \"free\"}", + "user": "user-1" + }, + { + "attributes": { + "plan": "pro" + }, + "expect": { + "enabled": true, + "reason": "TARGETING_MATCH", + "rule_index": 0, + "value": true + }, + "flag": "not-free", + "name": "not-free/user-1/{\"plan\": \"pro\"}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "TARGETING_MATCH", + "rule_index": 0, + "value": true + }, + "flag": "not-free", + "name": "not-free/missing-attribute-matches", + "user": "user-1" + }, + { + "attributes": { + "email": "a@example.com" + }, + "expect": { + "enabled": true, + "reason": "TARGETING_MATCH", + "rule_index": 0, + "value": true + }, + "flag": "contains-ends", + "name": "contains-ends/user-1/{\"email\": \"a@example.com\"}", + "user": "user-1" + }, + { + "attributes": { + "ua": "Foo Mobile Safari" + }, + "expect": { + "enabled": true, + "reason": "TARGETING_MATCH", + "rule_index": 1, + "value": true + }, + "flag": "contains-ends", + "name": "contains-ends/user-1/{\"ua\": \"Foo Mobile Safari\"}", + "user": "user-1" + }, + { + "attributes": { + "email": "a@example.org", + "ua": "Desktop" + }, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "value": false + }, + "flag": "contains-ends", + "name": "contains-ends/user-1/{\"email\": \"a@example.org\", \"ua\": \"Desktop\"}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "rollout_bucket": 54, + "value": false + }, + "flag": "rollout-30", + "name": "rollout-30/user-1/{}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "rollout_bucket": 94, + "value": false + }, + "flag": "rollout-30", + "name": "rollout-30/user-2/{}", + "user": "user-2" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "rollout_bucket": 54, + "value": false + }, + "flag": "rollout-30", + "name": "rollout-30/user-3/{}", + "user": "user-3" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "rollout_bucket": 16, + "value": true + }, + "flag": "rollout-30", + "name": "rollout-30/user-4/{}", + "user": "user-4" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "rollout_bucket": 77, + "value": false + }, + "flag": "rollout-30", + "name": "rollout-30/user-5/{}", + "user": "user-5" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "rollout_bucket": 18, + "value": true + }, + "flag": "rollout-30", + "name": "rollout-30/user-6/{}", + "user": "user-6" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "rollout_bucket": 36, + "value": false + }, + "flag": "rollout-30", + "name": "rollout-30/user-7/{}", + "user": "user-7" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "rollout_bucket": 45, + "value": false + }, + "flag": "rollout-30", + "name": "rollout-30/user-8/{}", + "user": "user-8" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "rollout_bucket": 16, + "value": true + }, + "flag": "rollout-30", + "name": "rollout-30/user-9/{}", + "user": "user-9" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "rollout_bucket": 96, + "value": false + }, + "flag": "rollout-30", + "name": "rollout-30/user-10/{}", + "user": "user-10" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "rollout_bucket": 17, + "value": true + }, + "flag": "rollout-30", + "name": "rollout-30/user-11/{}", + "user": "user-11" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "rollout_bucket": 59, + "value": false + }, + "flag": "rollout-30", + "name": "rollout-30/user-12/{}", + "user": "user-12" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "value": false + }, + "flag": "rollout-0", + "name": "rollout-0/user-1/{}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "STATIC", + "value": true + }, + "flag": "rollout-100", + "name": "rollout-100/user-1/{}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "value": "control", + "variant_index": 0 + }, + "flag": "weighted", + "name": "weighted/user-1/{}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "value": "a", + "variant_index": 1 + }, + "flag": "weighted", + "name": "weighted/user-2/{}", + "user": "user-2" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "value": "control", + "variant_index": 0 + }, + "flag": "weighted", + "name": "weighted/user-3/{}", + "user": "user-3" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "value": "control", + "variant_index": 0 + }, + "flag": "weighted", + "name": "weighted/user-4/{}", + "user": "user-4" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "value": "control", + "variant_index": 0 + }, + "flag": "weighted", + "name": "weighted/user-5/{}", + "user": "user-5" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "value": "a", + "variant_index": 1 + }, + "flag": "weighted", + "name": "weighted/user-6/{}", + "user": "user-6" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "value": "a", + "variant_index": 1 + }, + "flag": "weighted", + "name": "weighted/user-7/{}", + "user": "user-7" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "value": "control", + "variant_index": 0 + }, + "flag": "weighted", + "name": "weighted/user-8/{}", + "user": "user-8" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "value": "control", + "variant_index": 0 + }, + "flag": "weighted", + "name": "weighted/user-9/{}", + "user": "user-9" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "value": "a", + "variant_index": 1 + }, + "flag": "weighted", + "name": "weighted/user-10/{}", + "user": "user-10" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "value": "a", + "variant_index": 1 + }, + "flag": "weighted", + "name": "weighted/user-11/{}", + "user": "user-11" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "value": "control", + "variant_index": 0 + }, + "flag": "weighted", + "name": "weighted/user-12/{}", + "user": "user-12" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "rollout_bucket": 62, + "value": "none" + }, + "flag": "rollout-weighted", + "name": "rollout-weighted/user-1/{}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "ROLLOUT_EXCLUDED", + "rollout_bucket": 54, + "value": "none" + }, + "flag": "rollout-weighted", + "name": "rollout-weighted/user-2/{}", + "user": "user-2" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "rollout_bucket": 14, + "value": "x", + "variant_index": 0 + }, + "flag": "rollout-weighted", + "name": "rollout-weighted/user-3/{}", + "user": "user-3" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "rollout_bucket": 27, + "value": "y", + "variant_index": 1 + }, + "flag": "rollout-weighted", + "name": "rollout-weighted/user-4/{}", + "user": "user-4" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "rollout_bucket": 11, + "value": "x", + "variant_index": 0 + }, + "flag": "rollout-weighted", + "name": "rollout-weighted/user-5/{}", + "user": "user-5" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "rollout_bucket": 21, + "value": "x", + "variant_index": 0 + }, + "flag": "rollout-weighted", + "name": "rollout-weighted/user-6/{}", + "user": "user-6" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "rollout_bucket": 29, + "value": "x", + "variant_index": 0 + }, + "flag": "rollout-weighted", + "name": "rollout-weighted/user-7/{}", + "user": "user-7" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "rollout_bucket": 44, + "value": "x", + "variant_index": 0 + }, + "flag": "rollout-weighted", + "name": "rollout-weighted/user-8/{}", + "user": "user-8" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "value": "first", + "variant_index": 0 + }, + "flag": "zero-weights", + "name": "zero-weights/user-1/{}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "DEFAULT", + "value": 42 + }, + "flag": "int-flag", + "name": "int-flag/user-1/{}", + "user": "user-1" + }, + { + "attributes": { + "plan": "pro" + }, + "expect": { + "enabled": true, + "reason": "TARGETING_MATCH", + "rule_index": 0, + "value": 100 + }, + "flag": "int-flag", + "name": "int-flag/user-1/{\"plan\": \"pro\"}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "DISABLED", + "value": 0 + }, + "flag": "int-off", + "name": "int-off/user-1/{}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "DEFAULT", + "value": { + "limit": 3, + "theme": "dark" + } + }, + "flag": "json-flag", + "name": "json-flag/user-1/{}", + "user": "user-1" + }, + { + "attributes": { + "beta": "yes" + }, + "expect": { + "enabled": true, + "reason": "TARGETING_MATCH", + "rule_index": 0, + "value": { + "limit": 10, + "theme": "light" + } + }, + "flag": "json-flag", + "name": "json-flag/user-1/{\"beta\": \"yes\"}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "STATIC", + "value": null + }, + "flag": "string-no-default", + "name": "string-no-default/user-1/{}", + "user": "user-1" + }, + { + "attributes": { + "beta": "yes" + }, + "expect": { + "enabled": true, + "reason": "STATIC", + "value": true + }, + "flag": "needs-base", + "name": "needs-base/user-1/{\"beta\": \"yes\"}", + "user": "user-1" + }, + { + "attributes": { + "beta": "no" + }, + "expect": { + "enabled": false, + "reason": "PREREQUISITE_FAILED", + "value": false + }, + "flag": "needs-base", + "name": "needs-base/user-1/{\"beta\": \"no\"}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "PREREQUISITE_FAILED", + "value": false + }, + "flag": "needs-off", + "name": "needs-off/user-1/{}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "STATIC", + "value": "unlocked" + }, + "flag": "needs-variant", + "name": "needs-variant/user-1/{}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "PREREQUISITE_FAILED", + "value": "locked" + }, + "flag": "needs-variant", + "name": "needs-variant/user-2/{}", + "user": "user-2" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "STATIC", + "value": "unlocked" + }, + "flag": "needs-variant", + "name": "needs-variant/user-3/{}", + "user": "user-3" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "STATIC", + "value": "unlocked" + }, + "flag": "needs-variant", + "name": "needs-variant/user-4/{}", + "user": "user-4" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "STATIC", + "value": "unlocked" + }, + "flag": "needs-variant", + "name": "needs-variant/user-5/{}", + "user": "user-5" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "PREREQUISITE_FAILED", + "value": "locked" + }, + "flag": "needs-variant", + "name": "needs-variant/user-6/{}", + "user": "user-6" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "PREREQUISITE_FAILED", + "value": false + }, + "flag": "needs-missing", + "name": "needs-missing/user-1/{}", + "user": "user-1" + }, + { + "attributes": { + "beta": "yes" + }, + "expect": { + "enabled": true, + "reason": "STATIC", + "value": true + }, + "flag": "needs-chain", + "name": "needs-chain/user-1/{\"beta\": \"yes\"}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "PREREQUISITE_FAILED", + "value": false + }, + "flag": "needs-chain", + "name": "needs-chain/user-1/{}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": false, + "reason": "PREREQUISITE_FAILED", + "value": false + }, + "flag": "cycle-a", + "name": "cycle-a/user-1/{}", + "user": "user-1" + }, + { + "attributes": {}, + "expect": null, + "flag": "does-not-exist", + "name": "missing-flag", + "user": "user-1" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "STATIC", + "value": true + }, + "flag": "static-on", + "name": "empty-user-key", + "user": "" + }, + { + "attributes": {}, + "expect": { + "enabled": true, + "reason": "SPLIT", + "rollout_bucket": 13, + "value": true + }, + "flag": "rollout-30", + "name": "unicode-user-key", + "user": "ユーザー-ü" + } + ], + "flags": [ + { + "description": null, + "flag_type": "boolean", + "is_enabled": true, + "key": "static-on", + "rollout_percentage": null, + "rules": [] + }, + { + "description": null, + "flag_type": "boolean", + "is_enabled": false, + "key": "off", + "rollout_percentage": null, + "rules": [] + }, + { + "default_value": "on", + "description": null, + "disabled_value": "off", + "flag_type": "string", + "is_enabled": false, + "key": "string-off-custom", + "rollout_percentage": null, + "rules": [] + }, + { + "description": null, + "flag_type": "boolean", + "is_enabled": true, + "key": "rules-plan", + "rollout_percentage": 0, + "rules": [ + { + "attribute": "plan", + "operator": "equals", + "values": [ + "pro", + "team" + ] + } + ] + }, + { + "description": null, + "flag_type": "boolean", + "is_enabled": true, + "key": "rules-plan-default", + "rollout_percentage": null, + "rules": [ + { + "attribute": "plan", + "operator": "equals", + "values": [ + "pro" + ] + } + ] + }, + { + "default_value": "standard", + "description": null, + "flag_type": "string", + "is_enabled": true, + "key": "multi-rule", + "rollout_percentage": null, + "rules": [ + { + "attribute": "country", + "operator": "equals", + "values": [ + "PH", + "SG" + ], + "variant": "asia" + }, + { + "attribute": "plan", + "operator": "starts_with", + "values": [ + "ent" + ], + "variant": "enterprise" + } + ] + }, + { + "description": null, + "flag_type": "boolean", + "is_enabled": true, + "key": "adults", + "rollout_percentage": 0, + "rules": [ + { + "attribute": "age", + "operator": "greater_than_or_equal", + "values": [ + "18" + ] + } + ] + }, + { + "description": null, + "flag_type": "boolean", + "is_enabled": true, + "key": "numeric-lt", + "rollout_percentage": 0, + "rules": [ + { + "attribute": "score", + "operator": "less_than", + "values": [ + "10.5" + ] + } + ] + }, + { + "description": null, + "flag_type": "boolean", + "is_enabled": true, + "key": "not-free", + "rollout_percentage": 0, + "rules": [ + { + "attribute": "plan", + "operator": "not_equals", + "values": [ + "free" + ] + } + ] + }, + { + "description": null, + "flag_type": "boolean", + "is_enabled": true, + "key": "contains-ends", + "rollout_percentage": 0, + "rules": [ + { + "attribute": "email", + "operator": "ends_with", + "values": [ + "@example.com" + ] + }, + { + "attribute": "ua", + "operator": "contains", + "values": [ + "Mobile" + ] + } + ] + }, + { + "description": null, + "flag_type": "boolean", + "is_enabled": true, + "key": "rollout-30", + "rollout_percentage": 30, + "rules": [] + }, + { + "description": null, + "flag_type": "boolean", + "is_enabled": true, + "key": "rollout-0", + "rollout_percentage": 0, + "rules": [] + }, + { + "description": null, + "flag_type": "boolean", + "is_enabled": true, + "key": "rollout-100", + "rollout_percentage": 100, + "rules": [] + }, + { + "default_value": "unused", + "description": null, + "flag_type": "string", + "is_enabled": true, + "key": "weighted", + "rollout_percentage": null, + "rules": [], + "variants": [ + { + "value": "control", + "weight": 60 + }, + { + "value": "a", + "weight": 30 + }, + { + "value": "b", + "weight": 10 + } + ] + }, + { + "description": null, + "disabled_value": "none", + "flag_type": "string", + "is_enabled": true, + "key": "rollout-weighted", + "rollout_percentage": 50, + "rules": [], + "variants": [ + { + "value": "x", + "weight": 1 + }, + { + "value": "y", + "weight": 1 + } + ] + }, + { + "description": null, + "flag_type": "string", + "is_enabled": true, + "key": "zero-weights", + "rollout_percentage": null, + "rules": [], + "variants": [ + { + "value": "first", + "weight": 0 + }, + { + "value": "second", + "weight": 0 + } + ] + }, + { + "default_value": 42, + "description": null, + "disabled_value": 0, + "flag_type": "integer", + "is_enabled": true, + "key": "int-flag", + "rollout_percentage": null, + "rules": [ + { + "attribute": "plan", + "operator": "equals", + "values": [ + "pro" + ], + "variant": 100 + } + ] + }, + { + "default_value": 42, + "description": null, + "disabled_value": 0, + "flag_type": "integer", + "is_enabled": false, + "key": "int-off", + "rollout_percentage": null, + "rules": [] + }, + { + "default_value": { + "limit": 3, + "theme": "dark" + }, + "description": null, + "flag_type": "json", + "is_enabled": true, + "key": "json-flag", + "rollout_percentage": null, + "rules": [ + { + "attribute": "beta", + "operator": "equals", + "values": [ + "yes" + ], + "variant": { + "limit": 10, + "theme": "light" + } + } + ] + }, + { + "description": null, + "flag_type": "string", + "is_enabled": true, + "key": "string-no-default", + "rollout_percentage": null, + "rules": [] + }, + { + "description": null, + "flag_type": "boolean", + "is_enabled": true, + "key": "prereq-base", + "rollout_percentage": 0, + "rules": [ + { + "attribute": "beta", + "operator": "equals", + "values": [ + "yes" + ] + } + ] + }, + { + "description": null, + "flag_type": "boolean", + "is_enabled": true, + "key": "needs-base", + "prerequisites": [ + { + "flag_key": "prereq-base" + } + ], + "rollout_percentage": null, + "rules": [] + }, + { + "description": null, + "flag_type": "boolean", + "is_enabled": true, + "key": "needs-off", + "prerequisites": [ + { + "flag_key": "off" + } + ], + "rollout_percentage": null, + "rules": [] + }, + { + "default_value": "unlocked", + "description": null, + "disabled_value": "locked", + "flag_type": "string", + "is_enabled": true, + "key": "needs-variant", + "prerequisites": [ + { + "flag_key": "weighted", + "required_value": "control" + } + ], + "rollout_percentage": null, + "rules": [] + }, + { + "description": null, + "flag_type": "boolean", + "is_enabled": true, + "key": "needs-missing", + "prerequisites": [ + { + "flag_key": "ghost" + } + ], + "rollout_percentage": null, + "rules": [] + }, + { + "description": null, + "flag_type": "boolean", + "is_enabled": true, + "key": "needs-chain", + "prerequisites": [ + { + "flag_key": "static-on" + }, + { + "flag_key": "needs-base" + } + ], + "rollout_percentage": null, + "rules": [] + }, + { + "description": null, + "flag_type": "boolean", + "is_enabled": true, + "key": "cycle-a", + "prerequisites": [ + { + "flag_key": "cycle-b" + } + ], + "rollout_percentage": null, + "rules": [] + }, + { + "description": null, + "flag_type": "boolean", + "is_enabled": true, + "key": "cycle-b", + "prerequisites": [ + { + "flag_key": "cycle-a" + } + ], + "rollout_percentage": null, + "rules": [] + } + ], + "malformed": [ + { + "json": "{\"is_enabled\":true,\"rollout_percentage\":null,\"description\":null}", + "note": "must be rejected: never loaded, never evaluated" + }, + { + "json": "{\"key\":\"bad-rollout\",\"is_enabled\":true,\"rollout_percentage\":\"50\",\"description\":null}", + "note": "must be rejected: never loaded, never evaluated" + }, + { + "json": "{\"key\":\"bad-op\",\"is_enabled\":true,\"rollout_percentage\":null,\"description\":null,\"rules\":[{\"attribute\":\"a\",\"operator\":\"regex\",\"values\":[\"x\"]}]}", + "note": "must be rejected: never loaded, never evaluated" + }, + { + "json": "{\"key\":\"bad-type\",\"is_enabled\":true,\"rollout_percentage\":null,\"description\":null,\"flag_type\":\"float\"}", + "note": "must be rejected: never loaded, never evaluated" + }, + { + "json": "{\"key\":\"neg-weight\",\"is_enabled\":true,\"rollout_percentage\":null,\"description\":null,\"variants\":[{\"weight\":-1,\"value\":\"a\"}]}", + "note": "must be rejected: never loaded, never evaluated" + }, + { + "json": "not json", + "note": "must be rejected: never loaded, never evaluated" + } + ], + "schema": 1 +} From d46053520a7f0953757b3a2d5eb240ab3f648a90 Mon Sep 17 00:00:00 2001 From: Dennis Paler Date: Sat, 21 Nov 2026 21:52:26 +0800 Subject: [PATCH 02/38] feat(node): getDetails() and onStatusChange() getDetails() returns the engine's explanation (reason, matched rule, rollout bucket, weighted variant, prerequisite outcomes) from the same local evaluation as getVariant(). onStatusChange() reports connection-state transitions, and successful polls while in poll fallback. On a stream 'ready' the client now marks itself ready before switching to 'streaming', so a status listener sees isReady() on a first connection. test/vectors.test.js checks all 86 shared vectors through the public API with the real addon. CI gains sdk-node-native (Node 20/22/24): the real engine plus the OpenFeature provider; sdk-node keeps running the stand-in engine. --- .github/workflows/ci.yml | 38 +++++++++++ docs/sdks/nodejs.md | 30 ++++++++ sdks/nodejs/index.d.ts | 54 +++++++++++++++ sdks/nodejs/index.js | 98 +++++++++++++++++++++++++-- sdks/nodejs/src/lib.rs | 22 +++++- sdks/nodejs/test/client.test.js | 23 +++++++ sdks/nodejs/test/vectors.test.js | 113 +++++++++++++++++++++++++++++++ 7 files changed, 372 insertions(+), 6 deletions(-) create mode 100644 sdks/nodejs/test/vectors.test.js diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d3db83bd..bfbe4ff7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -477,6 +477,44 @@ jobs: working-directory: sdks/nodejs run: node --test + # --------------------------------------------------------------------------- + # Node SDK with the REAL native engine (sdk-node above uses the stand-in): + # the shared evaluation vectors, and the OpenFeature provider against the + # real OpenFeature SDK and a real SSE stream. Node 20, 22 and 24 are the + # supported LTS lines in November 2026. + # --------------------------------------------------------------------------- + sdk-node-native: + name: Node SDK (native) + OpenFeature provider + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node: [20, 22, 24] + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-node@v5 + with: + node-version: ${{ matrix.node }} + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + + - name: Cache Rust build artifacts + uses: Swatinem/rust-cache@v2 + + - name: Build the native addon + working-directory: sdks/nodejs + run: npm ci && npm run build:debug + + - name: Node SDK tests (real engine, shared vectors) + working-directory: sdks/nodejs + run: node --test + + - name: OpenFeature provider — install, typecheck, test + working-directory: sdks/openfeature-provider + run: npm ci && npm run typecheck && npm test + # --------------------------------------------------------------------------- # Web + React Native SDKs — client-logic unit tests (vitest; the WASM core is # stubbed for web, the JSI bridge faked for RN — no native/WASM build needed) diff --git a/docs/sdks/nodejs.md b/docs/sdks/nodejs.md index d0590f89..601d9599 100644 --- a/docs/sdks/nodejs.md +++ b/docs/sdks/nodejs.md @@ -125,6 +125,36 @@ missing. const color = client.getValue('checkout-button-color', userId, {}, 'blue') // string ``` +### `client.getDetails(flagKey, userKey, attributes): EvaluationDetails | null` + +The same local evaluation as `getVariant()`, plus why it resolved that way. Use it for +debugging and logging; `isEnabled()` stays the fastest call. + +```typescript +const d = client.getDetails('new-checkout', userId, { plan: 'pro' }) +// { enabled: true, value: true, reason: 'TARGETING_MATCH', ruleIndex: 0 } +``` + +| `reason` | Meaning | Extra fields | +|---|---|---| +| `DISABLED` | The flag is switched off. | | +| `PREREQUISITE_FAILED` | A prerequisite flag was not satisfied. | `prerequisites` | +| `TARGETING_MATCH` | A targeting rule matched. | `ruleIndex` | +| `ROLLOUT_EXCLUDED` | The user is outside the percentage rollout. | `rolloutBucket` (0–99) when hashed | +| `SPLIT` | Hashing decided: inside a partial rollout, or a weighted variant. | `rolloutBucket`, `variantIndex` | +| `DEFAULT` | The flag has rules; none matched. | | +| `STATIC` | No rules, partial rollout or variants: same value for everyone. | | + +`prerequisites` lists the flag's own prerequisites in the order they were checked, each with an +`outcome` (`satisfied`, `unsatisfied`, `not_found`, `limit_exceeded`) and, when evaluated, its +`result`. Checking stops at the first failure. Returns `null` if the flag does not exist. + +### `client.onStatusChange(callback): () => void` + +Calls `callback(client.getStatus())` whenever the connection state changes, and after each +successful poll while in poll fallback. Returns an unsubscribe function. The +[OpenFeature provider](./openfeature) uses it to report `STALE` and `READY`. + ### `client.track(eventKey, userKey, opts?): void` Records a goal/conversion event for [A/B testing](/guide/experimentation#a-b-testing). Buffered diff --git a/sdks/nodejs/index.d.ts b/sdks/nodejs/index.d.ts index 4126edcc..11318e3b 100644 --- a/sdks/nodejs/index.d.ts +++ b/sdks/nodejs/index.d.ts @@ -15,6 +15,39 @@ export interface FlagEvaluation { value: FlagValue; } +/** Why an evaluation resolved as it did (see {@link CheckgateClient.getDetails}). */ +export type EvaluationReason = + | 'DISABLED' + | 'PREREQUISITE_FAILED' + | 'TARGETING_MATCH' + | 'ROLLOUT_EXCLUDED' + | 'SPLIT' + | 'DEFAULT' + | 'STATIC'; + +/** One prerequisite of the evaluated flag, in the order they were checked. */ +export interface PrerequisiteCheck { + flagKey: string; + outcome: 'satisfied' | 'unsatisfied' | 'not_found' | 'limit_exceeded'; + /** The value the prerequisite must resolve to; absent means "enabled". */ + requiredValue?: FlagValue; + /** What the prerequisite resolved to; absent when it was not evaluated. */ + result?: FlagEvaluation; +} + +/** An evaluation plus the path that produced it. */ +export interface EvaluationDetails extends FlagEvaluation { + reason: EvaluationReason; + /** Index into the flag's `rules` of the rule that matched. */ + ruleIndex?: number; + /** The user's rollout bucket (0–99), when a partial rollout was checked. */ + rolloutBucket?: number; + /** Index into the flag's `variants` of the weighted variant assigned. */ + variantIndex?: number; + /** The flag's own prerequisites as checked (stops at the first failure). */ + prerequisites?: PrerequisiteCheck[]; +} + export interface CheckgateClientOptions { /** Base URL of your Checkgate server. */ serverUrl: string; @@ -117,6 +150,14 @@ export declare class CheckgateClient { /** Connection health, for detecting stale flags. */ getStatus(): CheckgateStatus; + /** + * Registers a listener called with {@link getStatus} whenever the connection + * state changes, and after each successful poll while in poll fallback. + * + * @returns an unsubscribe function. + */ + onStatusChange(callback: (status: CheckgateStatus) => void): () => void; + /** Whether the initial bootstrap has completed and flags are ready to evaluate. */ isReady(): boolean; @@ -176,6 +217,19 @@ export declare class CheckgateClient { defaultValue?: FlagValue ): FlagValue; + /** + * Evaluates a flag and explains the result (reason, matched rule, rollout + * bucket, weighted variant, prerequisites). Same local evaluation as + * {@link getVariant}; no network IO. + * + * @returns The details, or `null` if the flag does not exist. + */ + getDetails( + flagKey: string, + userKey: string, + userAttributes?: Record + ): EvaluationDetails | null; + /** * Records a goal/conversion event for A/B testing (e.g. "checkout_complete"). * Buffered and reported asynchronously, mirroring impression reporting. diff --git a/sdks/nodejs/index.js b/sdks/nodejs/index.js index 704a5667..82fe3264 100644 --- a/sdks/nodejs/index.js +++ b/sdks/nodejs/index.js @@ -99,6 +99,23 @@ function parseSnapshot(body) { return { flags: body.flags, revisions }; } +/** The engine's explanation (snake_case JSON) in the SDK's camelCase shape. */ +function toDetails(raw) { + const out = { enabled: raw.enabled, value: raw.value, reason: raw.reason }; + if (raw.rule_index !== undefined) out.ruleIndex = raw.rule_index; + if (raw.rollout_bucket !== undefined) out.rolloutBucket = raw.rollout_bucket; + if (raw.variant_index !== undefined) out.variantIndex = raw.variant_index; + if (Array.isArray(raw.prerequisites)) { + out.prerequisites = raw.prerequisites.map((p) => { + const check = { flagKey: p.flag_key, outcome: p.outcome }; + if (p.required_value !== undefined) check.requiredValue = p.required_value; + if (p.result !== undefined) check.result = p.result; + return check; + }); + } + return out; +} + /** HTTP statuses that mean the SDK key itself is rejected: retrying cannot help. */ const AUTH_FAILURE_STATUSES = new Set([401, 403]); @@ -203,6 +220,7 @@ class CheckgateClient { this._resolveReady = null; this._rejectReady = null; this._changeListeners = []; + this._statusListeners = []; this.sse = null; // Connection health (see getStatus()). The watchdog closes a stream @@ -275,7 +293,7 @@ class CheckgateClient { this._userClosed = false; this._lastError = null; - this._state = this._ready ? 'reconnecting' : 'connecting'; + this._setState(this._ready ? 'reconnecting' : 'connecting'); this._connectPromise = new Promise((resolve, reject) => { this._resolveReady = resolve; this._rejectReady = reject; @@ -323,6 +341,9 @@ class CheckgateClient { _markReady() { this._lastSyncAt = Date.now(); this._ready = true; + // While polling, a successful poll is the only sign the flags are + // current again (the state stays 'polling'), so report it. + if (this._state === 'polling') this._notifyStatus(); // Also settles a connect() issued after an auth failure, when the // client was already ready once. const resolve = this._resolveReady; @@ -357,6 +378,41 @@ class CheckgateClient { } } + /** + * Registers a listener invoked with `getStatus()` whenever the connection + * state changes (e.g. `'streaming'` → `'reconnecting'`), and after each + * successful poll while in poll fallback (`'polling'` stays the state, but + * `lastSyncAt` shows the flags are current again). Not called for + * heartbeats or individual flag changes (see onChange). + * + * @param {(status: { state: string, lastSyncAt: number|null, error: Error|null }) => void} callback + * @returns {() => void} an unsubscribe function. + */ + onStatusChange(callback) { + this._statusListeners.push(callback); + return () => { + this._statusListeners = this._statusListeners.filter((cb) => cb !== callback); + }; + } + + _setState(state) { + if (this._state === state) return; + this._state = state; + this._notifyStatus(); + } + + _notifyStatus() { + if (this._statusListeners.length === 0) return; + const status = this.getStatus(); + for (const cb of this._statusListeners) { + try { + cb(status); + } catch (err) { + console.error('[Checkgate] status listener threw:', err); + } + } + } + _connectDeltas() { this._closeStream(); // The replay this stream sends is read after this point. @@ -441,8 +497,10 @@ class CheckgateClient { this._hydrated = true; // Persist the freshly-bootstrapped full flag set for offline use. this._persistCache(); - this._state = 'streaming'; + // Ready before the state change, so status listeners already see + // isReady() on a first connection. this._markReady(); + this._setState('streaming'); }); on('update', (e) => { @@ -533,7 +591,7 @@ class CheckgateClient { this._staged = null; this._stagedRevisions = null; this._reconnectAttempts = 0; - this._state = 'auth_failed'; + this._setState('auth_failed'); this._lastError = err; const reject = this._rejectReady; this._resolveReady = null; @@ -602,7 +660,7 @@ class CheckgateClient { if (this._reconnectAttempts >= this.pollFallbackThreshold) { this._startPollFallback(); } - this._state = this._polling ? 'polling' : (this._ready ? 'reconnecting' : 'connecting'); + this._setState(this._polling ? 'polling' : (this._ready ? 'reconnecting' : 'connecting')); console.warn(`[Checkgate] Stream disconnected — reconnecting in ${Math.round(delay)}ms.`); this._reconnectTimer = setTimeout(() => { @@ -813,6 +871,36 @@ class CheckgateClient { return variant === null ? defaultValue : variant.value; } + /** + * Evaluates a flag and explains the result: `{ enabled, value, reason }` + * plus `ruleIndex`, `rolloutBucket`, `variantIndex` and `prerequisites` + * when they apply. Same evaluation as getVariant() (same engine code), + * locally and without network IO; slightly more work, since it records + * the path. Reasons: `DISABLED`, `PREREQUISITE_FAILED`, `TARGETING_MATCH`, + * `ROLLOUT_EXCLUDED`, `SPLIT`, `DEFAULT`, `STATIC`. + * + * @param {string} flagKey + * @param {string} userKey + * @param {Record} [userAttributes={}] + * @returns {object|null} `null` if the flag does not exist (or before + * connect() resolved and nothing was hydrated). + */ + getDetails(flagKey, userKey, userAttributes = {}) { + if (!this._ready && !this._hydrated) { + console.warn('[Checkgate] getDetails() called before connect() resolved. Returning null.'); + return null; + } + let raw; + try { + raw = JSON.parse(this.core.explain(flagKey, userKey, userAttributes)); + } catch { + return null; + } + if (raw === null) return null; + this._recordImpression(flagKey, userKey, this._formatValue(raw.value), userAttributes); + return toDetails(raw); + } + // --------------------------------------------------------------------- // Impression reporting (async, batched, best-effort) // --------------------------------------------------------------------- @@ -983,7 +1071,7 @@ class CheckgateClient { disconnect() { // Stop managed reconnection before tearing down the stream. this._userClosed = true; - this._state = 'closed'; + this._setState('closed'); if (this._reconnectTimer) { clearTimeout(this._reconnectTimer); this._reconnectTimer = null; diff --git a/sdks/nodejs/src/lib.rs b/sdks/nodejs/src/lib.rs index 35190cc1..2751b4b9 100644 --- a/sdks/nodejs/src/lib.rs +++ b/sdks/nodejs/src/lib.rs @@ -17,7 +17,7 @@ #[macro_use] extern crate napi_derive; -use checkgate_core::evaluator::{Flag, UserContext, evaluate, evaluate_variant}; +use checkgate_core::evaluator::{Flag, UserContext, evaluate, evaluate_variant, explain}; use checkgate_core::store::FlagStore; use napi::bindgen_prelude::{JsObjectValue, Object}; use std::collections::{HashMap, HashSet}; @@ -202,4 +202,24 @@ impl CheckgateCore { let result = evaluate_variant(flag.as_ref(), &ctx, &self.store); Ok(serde_json::to_string(&result).unwrap_or_else(|_| "null".to_string())) } + + /// Evaluate a flag and return its explanation as a JSON string: the + /// result `{ enabled, value }` plus `reason`, and `rule_index`, + /// `rollout_bucket`, `variant_index` and `prerequisites` when they apply + /// (see `checkgate_core::evaluator::explain`). Returns `"null"` if the + /// flag is not found. Same evaluation code as `get_variant`. + #[napi] + pub fn explain( + &self, + flag_key: String, + user_key: String, + user_attributes: Option>, + ) -> napi::Result { + let Some(flag) = self.store.get_flag(&flag_key) else { + return Ok("null".to_string()); + }; + let ctx = user_context(&flag, &self.store, user_key, user_attributes)?; + let explanation = explain(flag.as_ref(), &ctx, &self.store); + Ok(serde_json::to_string(&explanation).unwrap_or_else(|_| "null".to_string())) + } } diff --git a/sdks/nodejs/test/client.test.js b/sdks/nodejs/test/client.test.js index a79b031e..aaba8b26 100644 --- a/sdks/nodejs/test/client.test.js +++ b/sdks/nodejs/test/client.test.js @@ -606,3 +606,26 @@ test('polls ask for ?v=2; a server without revisions gets the old behaviour', as assert.equal(client._revisions.size, 0, 'no revisions invented (never revision 0)'); client.disconnect(); }); + +test('onStatusChange reports each state transition once', () => { + const client = connectedClient(); + const seen = []; + const off = client.onStatusChange((s) => seen.push(s.state)); + bootstrap(client, [[{ key: 'f', is_enabled: true }, 1]]); + assert.deepEqual(seen, ['streaming']); + // A dropped stream schedules a reconnect: one transition, not one per event. + client.sse.listeners.error({}); + assert.deepEqual(seen, ['streaming', 'reconnecting']); + client.sse = null; + // A listener that throws does not break the client or other listeners. + client.onStatusChange(() => { throw new Error('boom'); }); + const quiet = console.error; + console.error = () => {}; + client.disconnect(); + console.error = quiet; + assert.deepEqual(seen, ['streaming', 'reconnecting', 'closed']); + off(); + client.connect().catch(() => {}); + assert.deepEqual(seen, ['streaming', 'reconnecting', 'closed'], 'unsubscribed'); + client.disconnect(); +}); diff --git a/sdks/nodejs/test/vectors.test.js b/sdks/nodejs/test/vectors.test.js new file mode 100644 index 00000000..43512cb8 --- /dev/null +++ b/sdks/nodejs/test/vectors.test.js @@ -0,0 +1,113 @@ +// The shared evaluation vectors (sdks/conformance/vectors/evaluation.json), +// through the public client API with the real native engine. Needs the addon +// built (`npm run build`); skipped otherwise. +// +// The flags reach the client the way an offline start does: hydrated from a +// storage adapter, with no server reachable. Every SDK checks the same file; +// the Rust core is the oracle that produced `expect`. + +const { test } = require('node:test') +const assert = require('node:assert') +const fs = require('node:fs') +const path = require('node:path') + +let native = null +try { + native = require('../native-binding.js') +} catch { + native = null +} +const opts = { skip: native ? false : 'native addon not built' } + +const vectors = JSON.parse( + fs.readFileSync(path.join(__dirname, '../../conformance/vectors/evaluation.json'), 'utf8'), +) + +/** A client holding exactly the vector flags, hydrated offline. */ +async function hydratedClient() { + const { CheckgateClient } = require('../index.js') + const snapshot = Object.fromEntries(vectors.flags.map((f) => [f.key, f])) + const client = new CheckgateClient({ + // Nothing listens here: the client stays offline on the hydrated flags. + serverUrl: 'http://127.0.0.1:9', + reportImpressions: false, + reconnectDelayMs: 60_000, + storage: { getItem: () => JSON.stringify(snapshot), setItem: () => {} }, + }) + client.connect().catch(() => {}) + // Hydration is one awaited getItem; give it a turn of the event loop. + for (let i = 0; i < 50 && !client._hydrated; i++) await new Promise((r) => setTimeout(r, 10)) + assert.ok(client._hydrated, 'client hydrated from storage') + return client +} + +/** `getDetails` in the vector file's snake_case shape. */ +function asVector(details) { + if (details === null) return null + const out = { enabled: details.enabled, value: details.value, reason: details.reason } + if (details.ruleIndex !== undefined) out.rule_index = details.ruleIndex + if (details.rolloutBucket !== undefined) out.rollout_bucket = details.rolloutBucket + if (details.variantIndex !== undefined) out.variant_index = details.variantIndex + return out +} + +test('every vector case evaluates as the core says', opts, async () => { + const quiet = console.warn + console.warn = () => {} + const client = await hydratedClient() + try { + assert.ok(vectors.cases.length > 50) + for (const c of vectors.cases) { + const details = client.getDetails(c.flag, c.user, c.attributes) + assert.deepStrictEqual(asVector(details), c.expect, c.name) + if (c.expect === null) { + assert.strictEqual(client.isEnabled(c.flag, c.user, c.attributes), false, c.name) + assert.strictEqual(client.getVariant(c.flag, c.user, c.attributes), null, c.name) + assert.strictEqual(client.getValue(c.flag, c.user, c.attributes, 'dflt'), 'dflt', c.name) + continue + } + // The plain APIs agree with the detailed one. + assert.strictEqual(client.isEnabled(c.flag, c.user, c.attributes), c.expect.enabled, c.name) + assert.deepStrictEqual( + client.getVariant(c.flag, c.user, c.attributes), + { enabled: c.expect.enabled, value: c.expect.value }, + c.name, + ) + assert.deepStrictEqual(client.getValue(c.flag, c.user, c.attributes), c.expect.value, c.name) + } + } finally { + client.disconnect() + console.warn = quiet + } +}) + +test('getDetails reports prerequisites in camelCase', opts, async () => { + const quiet = console.warn + console.warn = () => {} + const client = await hydratedClient() + try { + const d = client.getDetails('needs-chain', 'user-1', {}) + assert.strictEqual(d.reason, 'PREREQUISITE_FAILED') + assert.deepStrictEqual(d.prerequisites.map((p) => [p.flagKey, p.outcome]), [ + ['static-on', 'satisfied'], + ['needs-base', 'unsatisfied'], + ]) + assert.deepStrictEqual(d.prerequisites[1].result, { enabled: false, value: false }) + const missing = client.getDetails('needs-missing', 'user-1', {}) + assert.deepStrictEqual(missing.prerequisites, [{ flagKey: 'ghost', outcome: 'not_found' }]) + } finally { + client.disconnect() + console.warn = quiet + } +}) + +test('malformed configurations are never loaded', opts, () => { + const core = new native.CheckgateCore() + for (const bad of vectors.malformed) { + core.upsertFlagV2(bad.json) + } + for (const key of ['bad-rollout', 'bad-op', 'bad-type', 'neg-weight']) { + assert.strictEqual(core.explain(key, 'u', {}), 'null', key) + assert.strictEqual(core.isEnabled(key, 'u', {}), false, key) + } +}) From a7cbf82306db850c10cd2eddb9582560a52ca11a Mon Sep 17 00:00:00 2001 From: Dennis Paler Date: Sat, 21 Nov 2026 21:52:30 +0800 Subject: [PATCH 03/38] feat(node-integrations): Express, Fastify and NestJS adapters for @checkgate/node One package, @checkgate/node-integrations, with subpath exports ./express, ./fastify and ./nestjs over a shared core: - RequestFlags: a per-request evaluator bound to one shared CheckgateClient. The context comes from a context(req) extractor, resolved once on first use; attributes are coerced (numbers, bigints, booleans to strings; other values dropped) so a non-string referenced attribute cannot throw inside a request. Evaluations never throw and make no network call. - startCheckgate / stopCheckgate: startup waits at most readyTimeoutMs, then continues (cached or default values, syncing in the background) or fails; a rejected SDK key always fails. Shutdown disconnects exactly once. - Express: checkgateMiddleware -> req.checkgate, listenWithCheckgate for ordered startup and close(). - Fastify: fastify-plugin plugin -> fastify.checkgate / request.checkgate, connect during plugin load, disconnect in onClose. - NestJS: CheckgateModule.forRoot / forRootAsync / forTesting, CheckgateService, @Checkgate() parameter, @RequireFlag() guard; no REQUEST-scoped providers. Plain CommonJS with hand-written .d.ts. Frameworks are optional peers. --- sdks/node-integrations/LICENSE | 21 + sdks/node-integrations/package-lock.json | 2256 ++++++++++++++++++++++ sdks/node-integrations/package.json | 92 + sdks/node-integrations/src/core.js | 335 ++++ sdks/node-integrations/src/express.d.ts | 55 + sdks/node-integrations/src/express.js | 97 + sdks/node-integrations/src/fastify.d.ts | 40 + sdks/node-integrations/src/fastify.js | 64 + sdks/node-integrations/src/index.d.ts | 148 ++ sdks/node-integrations/src/index.js | 19 + sdks/node-integrations/src/nestjs.d.ts | 78 + sdks/node-integrations/src/nestjs.js | 230 +++ sdks/node-integrations/src/testing.js | 70 + 13 files changed, 3505 insertions(+) create mode 100644 sdks/node-integrations/LICENSE create mode 100644 sdks/node-integrations/package-lock.json create mode 100644 sdks/node-integrations/package.json create mode 100644 sdks/node-integrations/src/core.js create mode 100644 sdks/node-integrations/src/express.d.ts create mode 100644 sdks/node-integrations/src/express.js create mode 100644 sdks/node-integrations/src/fastify.d.ts create mode 100644 sdks/node-integrations/src/fastify.js create mode 100644 sdks/node-integrations/src/index.d.ts create mode 100644 sdks/node-integrations/src/index.js create mode 100644 sdks/node-integrations/src/nestjs.d.ts create mode 100644 sdks/node-integrations/src/nestjs.js create mode 100644 sdks/node-integrations/src/testing.js diff --git a/sdks/node-integrations/LICENSE b/sdks/node-integrations/LICENSE new file mode 100644 index 00000000..605a128f --- /dev/null +++ b/sdks/node-integrations/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 ThinkGrid Labs + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/sdks/node-integrations/package-lock.json b/sdks/node-integrations/package-lock.json new file mode 100644 index 00000000..c3dfff71 --- /dev/null +++ b/sdks/node-integrations/package-lock.json @@ -0,0 +1,2256 @@ +{ + "name": "@checkgate/node-integrations", + "version": "0.2.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@checkgate/node-integrations", + "version": "0.2.0", + "license": "Apache-2.0", + "dependencies": { + "fastify-plugin": "^5.0.0 || ^6.0.0" + }, + "devDependencies": { + "@checkgate/node": "file:../nodejs", + "@nestjs/common": "^12.6.0", + "@nestjs/core": "^12.6.0", + "@nestjs/platform-express": "^12.6.0", + "@nestjs/testing": "^12.6.0", + "@types/express": "^5.0.0", + "@types/node": "^22.0.0", + "express": "^5.3.0", + "fastify": "^5.12.8", + "reflect-metadata": "^0.2.2", + "rxjs": "^7.8.2", + "typescript": "^5.9.3" + }, + "engines": { + "node": ">=22.12.0" + }, + "peerDependencies": { + "@checkgate/node": ">=0.1.31 <0.3.0", + "@nestjs/common": "^12.0.0", + "@nestjs/core": "^12.0.0", + "express": "^5.0.0", + "fastify": "^5.0.0" + }, + "peerDependenciesMeta": { + "@nestjs/common": { + "optional": true + }, + "@nestjs/core": { + "optional": true + }, + "express": { + "optional": true + }, + "fastify": { + "optional": true + } + } + }, + "../nodejs": { + "name": "@checkgate/node", + "version": "0.1.31", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "eventsource": "^4.1.0" + }, + "devDependencies": { + "@napi-rs/cli": "^3.5.1" + } + }, + "node_modules/@borewit/text-codec": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@borewit/text-codec/-/text-codec-0.2.3.tgz", + "integrity": "sha512-49CycTz1aAZmvFcwkeFyhud1HUmRIB5Tabf7ALV+VA4Iu85MTfz2cUwzPagMFAdVBvrWdkCxG67I30tUwwpKsw==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/@checkgate/node": { + "resolved": "../nodejs", + "link": true + }, + "node_modules/@fastify/ajv-compiler": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/@fastify/ajv-compiler/-/ajv-compiler-4.0.8.tgz", + "integrity": "sha512-xYcAFYoyP/NELMgj6I7LmMAmiqeXMal0wsM2SgueN9OyMr6bVKHomO9OxuStC7bIAEl4Z3JXBbDPwpXRp59NPQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "ajv": "^8.12.0", + "ajv-formats": "^3.0.1", + "fast-uri": "^4.0.0" + } + }, + "node_modules/@fastify/deepmerge": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@fastify/deepmerge/-/deepmerge-3.2.4.tgz", + "integrity": "sha512-kc8GQq5gX9RRhw0rov3DMrN8wS8yRlxJRdDzsYwwdBV/wazuVgc/1K7CKL90tlvu3RlHan6Y0R0aE3nJtBz2eQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/@fastify/error": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/@fastify/error/-/error-4.3.0.tgz", + "integrity": "sha512-mtIdc4R7HnUMOuUDQgnJkEF+Omr2p3JrSSJ44+RME/eAQ5TqdDy5MvXAjze/RyVHhJckuJKkXnMhKfPmFMKqyA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/@fastify/fast-json-stringify-compiler": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@fastify/fast-json-stringify-compiler/-/fast-json-stringify-compiler-5.2.0.tgz", + "integrity": "sha512-LPTVA0w4oPITWHAvox9NgI1rDSrjUnjxX6QN5MCb9FY+HqvDsUmgLucbj9eQakqC8lYwO7UgkDPHEQLJNl9vtg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "fast-json-stringify": "^7.3.0" + } + }, + "node_modules/@fastify/forwarded": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@fastify/forwarded/-/forwarded-3.1.2.tgz", + "integrity": "sha512-89WiRG+hW3VQSfCwg4Hb8b43PeyEX15K5+lEfsZ4EUth/FyOjS/lv8HsVuswUNXWiSnxMGNouE/fq/0w3VumHQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/@fastify/merge-json-schemas": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/@fastify/merge-json-schemas/-/merge-json-schemas-0.2.2.tgz", + "integrity": "sha512-d/gx9sRbUCVgGRGzma46wLcwiY8noTqO2Nmjg/vbTARxHRE5bdh5PIL8s97Lt1X7ScRWRW52eVYxwIoPwIdVUA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/@fastify/proxy-addr": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/@fastify/proxy-addr/-/proxy-addr-5.1.3.tgz", + "integrity": "sha512-ptgIgB+abBNTs5lsKNvFaKMCauPaTOE6ZIjxJr3FxCLehmYQQKYGg4srwwNICR9QQlFrYw59jWAo+i9GalVCaw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/forwarded": "^3.0.0", + "ipaddr.js": "^2.1.0" + } + }, + "node_modules/@lukeed/csprng": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@lukeed/csprng/-/csprng-1.1.0.tgz", + "integrity": "sha512-Z7C/xXCiGWsg0KuKsHTKJxbWhpI3Vs5GwLfOean7MGyVFGqdRgBbAjOCh6u4bbjPc/8MJ2pZmK/0DLdCbivLDA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@nestjs/common": { + "version": "12.6.0", + "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-12.6.0.tgz", + "integrity": "sha512-qlCebomQxvtNSdOQfgBryWwi2gjUYGTmXnwRP0vLp5xdKfR3DfAl4KRsvuXEbAUCBPUtHsgWSxh76IP1pc262A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "1.1.0", + "file-type": "22.3.0", + "iterare": "1.2.1", + "load-esm": "1.0.3", + "tslib": "2.9.1", + "uid": "2.0.2" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "class-transformer": ">=0.4.1", + "class-validator": ">=0.13.2", + "reflect-metadata": "^0.1.12 || ^0.2.0", + "rxjs": "^7.1.0" + }, + "peerDependenciesMeta": { + "class-transformer": { + "optional": true + }, + "class-validator": { + "optional": true + } + } + }, + "node_modules/@nestjs/core": { + "version": "12.6.0", + "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-12.6.0.tgz", + "integrity": "sha512-LmIF9DtTw4HgGWxlNZYFr3L+D8hw8vzwBV7Fkgr+lcVfeYYFBshQpwuwt6ewT6YvDnvIgI8+GdRDV7RbcVAiRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-safe-stringify": "2.1.1", + "iterare": "1.2.1", + "path-to-regexp": "8.4.2", + "tslib": "2.9.1", + "uid": "2.0.2" + }, + "engines": { + "node": ">= 20" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "@nestjs/common": "^12.0.0", + "@nestjs/microservices": "^12.0.0", + "@nestjs/platform-express": "^12.0.0", + "@nestjs/websockets": "^12.0.0", + "reflect-metadata": "^0.1.12 || ^0.2.0", + "rxjs": "^7.1.0" + }, + "peerDependenciesMeta": { + "@nestjs/microservices": { + "optional": true + }, + "@nestjs/platform-express": { + "optional": true + }, + "@nestjs/websockets": { + "optional": true + } + } + }, + "node_modules/@nestjs/platform-express": { + "version": "12.6.0", + "resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-12.6.0.tgz", + "integrity": "sha512-/qAWhyqiy9eKAJt+7tvSfsavKfF893PpCEOQ1HqmDD4stIvQCXfGfb+/6MMU9hiwXq8MMbC6pnyFaIhICc13rw==", + "dev": true, + "license": "MIT", + "dependencies": { + "cors": "2.8.6", + "express": "5.3.0", + "multer": "2.5.0", + "path-to-regexp": "8.4.2", + "tslib": "2.9.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "@nestjs/common": "^12.0.0", + "@nestjs/core": "^12.0.0", + "rxjs": "^7.1.0" + } + }, + "node_modules/@nestjs/testing": { + "version": "12.6.0", + "resolved": "https://registry.npmjs.org/@nestjs/testing/-/testing-12.6.0.tgz", + "integrity": "sha512-84whoYLvjORtUb/qD2QIYUsXHRUu654cmrbmzHFVrb38Vbox2wPQiQvu9LDtPdwEFiiMHUb5LIdWSolNvFa9ag==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "2.9.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "@nestjs/common": "^12.0.0", + "@nestjs/core": "^12.0.0", + "@nestjs/microservices": "^12.0.0", + "@nestjs/platform-express": "^12.0.0" + }, + "peerDependenciesMeta": { + "@nestjs/microservices": { + "optional": true + }, + "@nestjs/platform-express": { + "optional": true + } + } + }, + "node_modules/@pinojs/redact": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", + "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tokenizer/inflate": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.6.1.tgz", + "integrity": "sha512-EuqSyHdOXN61cc5/rsW6uUn1TJZJGZr56jlkUbsLwVJ6uHgvwQyFkYfOCf+zzPFAYjftPk1WeJnEhpLVvzbm1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "strtok3": "^10.8.0", + "token-types": "^6.2.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/@tokenizer/token": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", + "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/body-parser": { + "version": "1.19.6", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", + "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/express": { + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz", + "integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^5.0.0", + "@types/serve-static": "^2" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.3.tgz", + "integrity": "sha512-dPfW8NFiOF4wOHc7+N/QSxlY9cfSsenewGbAz8C8U/MULPd/YZ27LvJUIlzaXie7e6Ove9YunJGgC9tbHD2cKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/http-errors": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", + "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/qs": { + "version": "6.15.1", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz", + "integrity": "sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz", + "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-2.2.0.tgz", + "integrity": "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*" + } + }, + "node_modules/abstract-logging": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz", + "integrity": "sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==", + "dev": true, + "license": "MIT" + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ajv/node_modules/fast-uri": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/append-field": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", + "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==", + "dev": true, + "license": "MIT" + }, + "node_modules/atomic-sleep": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", + "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/avvio": { + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/avvio/-/avvio-9.3.1.tgz", + "integrity": "sha512-QyTKW61/qlba+cUQBm/sT9X8lri4UdomqSDwCnrnj1IvLVDRRiXRkz4CgBRWB+/cmfC7SK5WQc8T1vSdGvaUcQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/error": "^4.0.0", + "fastq": "^1.17.1" + } + }, + "node_modules/body-parser": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", + "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.1.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.3", + "on-finished": "^2.4.1", + "qs": "^6.16.1", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dev": true, + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", + "integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "dev": true, + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.3.tgz", + "integrity": "sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "dev": true, + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz", + "integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==", + "dev": true, + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.3.0", + "content-disposition": "^2.0.1", + "content-type": "^2.0.0", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.8", + "qs": "^6.16.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.1.0", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/fast-decode-uri-component": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fast-decode-uri-component/-/fast-decode-uri-component-1.0.1.tgz", + "integrity": "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-json-stringify": { + "version": "7.3.8", + "resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-7.3.8.tgz", + "integrity": "sha512-kaCWXREa8kcb/PbCoe75oJazOkIAWwpvJYwTw9OOb7puth6rSAShPKvb2GjwZp+odRtDxNzUsx9MJZMDPFwKYg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/merge-json-schemas": "^0.2.0", + "ajv": "^8.12.0", + "ajv-formats": "^3.0.1", + "fast-uri": "^4.0.0", + "json-schema-ref-resolver": "^3.0.0", + "rfdc": "^1.2.0" + } + }, + "node_modules/fast-querystring": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/fast-querystring/-/fast-querystring-1.1.2.tgz", + "integrity": "sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-decode-uri-component": "^1.0.1" + } + }, + "node_modules/fast-safe-stringify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-4.2.3.tgz", + "integrity": "sha512-I1PXwP5eAhlNlcdpjt9CgB59op2ZvZfxw+BkqGFVIUOgNpCVTcTqp3HhTX7brxj5vsip+nSY4nTvff+eIA76hg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fastify": { + "version": "5.12.8", + "resolved": "https://registry.npmjs.org/fastify/-/fastify-5.12.8.tgz", + "integrity": "sha512-moP8exb2sCHLUbJkwp+I6C0padhy4D8lp0SdmzY7HhSdZuqm7O/u3o2aq7u8okaQ//33QDzj3G/u+FsSdB8Qzw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/ajv-compiler": "^4.0.5", + "@fastify/error": "^4.0.0", + "@fastify/fast-json-stringify-compiler": "^5.0.0", + "@fastify/proxy-addr": "^5.0.0", + "abstract-logging": "^2.0.1", + "avvio": "^9.0.0", + "fast-json-stringify": "^7.0.0", + "find-my-way": "^9.10.0", + "light-my-request": "^6.0.0", + "pino": "^9.14.0 || ^10.1.0", + "process-warning": "^5.1.0", + "rfdc": "^1.3.1", + "secure-json-parse": "^4.0.0", + "semver": "^7.6.0", + "toad-cache": "^3.7.0" + } + }, + "node_modules/fastify-plugin": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-6.0.1.tgz", + "integrity": "sha512-4wW4RxSmvPXLrh5mgQEiu43qU3bw44N2ss4FTkTkQIbprUhE+/s43QX0j/ttcztdWK7PEkHqVthdc5GdEGDvjA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/fastq": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.3.tgz", + "integrity": "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==", + "dev": true, + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/file-type": { + "version": "22.3.0", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-22.3.0.tgz", + "integrity": "sha512-PrPedgnnWl5bWz3JHgar0QSzRvzeyFh7dZ9JpYOgcPZu4KALS9zw4MMa6qXRYyjeBsAlpaWB2boLuG991+0HIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@tokenizer/inflate": "^0.6.0", + "strtok3": "^10.6.3", + "token-types": "^6.1.2", + "uint8array-extras": "^1.6.0" + }, + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/sindresorhus/file-type?sponsor=1" + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/find-my-way": { + "version": "9.10.2", + "resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-9.10.2.tgz", + "integrity": "sha512-gbLMuTm2FV5QiRh/eM0uhL4nyOvbSqqa2K3mASAtkIqxvY8ZmoLOCLMd2syLWT/SyhrvOR7GPxOKj/kcV6o8bg==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-querystring": "^1.0.0", + "safe-regex2": "^5.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.5.0.tgz", + "integrity": "sha512-aq+t5NAc+cS6rZQQVWC2x98CPqGtKKTMDd4Gaodv0wShnItdKg/51djkGJ1hqH+Oy0ivDftCbSLCQob8zso01w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/iterare": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/iterare/-/iterare-1.2.1.tgz", + "integrity": "sha512-RKYVTCjAnRthyJes037NX/IiqeidgN1xc3j1RjFfECFp28A1GVwK9nA+i0rJPaHqSZwygLzRnFlzUuHFoWWy+Q==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=6" + } + }, + "node_modules/json-schema-ref-resolver": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-3.0.1.tgz", + "integrity": "sha512-w+HwgljXpVwZ3IidoUR1qPZxSOQ+NRQWuVe6a5pe8XbHsNZE4UAwVPUvzZagn7yBKbJtt6UJnRFYbNTRPZI45Q==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, + "node_modules/light-my-request": { + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-6.8.1.tgz", + "integrity": "sha512-20biUK0HAIPG9BZOK3/4s8uVAkAoi1+qW55lciHZCR0puTWipBgyMPEUjqXDWLjsZeqfO6DGsuwW5eyfsTGtyg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause", + "dependencies": { + "@fastify/deepmerge": "^3.1.0", + "cookie": "^2.0.0", + "process-warning": "^5.0.0", + "set-cookie-parser": "^3.0.1" + } + }, + "node_modules/light-my-request/node_modules/cookie": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-2.0.2.tgz", + "integrity": "sha512-SL0cVuEdETEp7pN0FuZb01toc3vnODEfVUCooxG1SJN0yIirh7JMb9X9bvfCFf0vzzbT68RdbKDHYTiWy7a7iw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/load-esm": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/load-esm/-/load-esm-1.0.3.tgz", + "integrity": "sha512-v5xlu8eHD1+6r8EHTg6hfmO97LN8ugKtiXcy5e6oN72iD2r6u0RPfLl6fxM+7Wnh2ZRq15o0russMst44WauPA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + }, + { + "type": "buymeacoffee", + "url": "https://buymeacoffee.com/borewit" + } + ], + "license": "MIT", + "engines": { + "node": ">=13.2.0" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/multer": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/multer/-/multer-2.5.0.tgz", + "integrity": "sha512-BsqOzYGVq49JcW2IzoSAxeKYRevb+dGGPPWleOR8Lrlk4igwxu1/9pwSXlByhCb7MVZDrNJFC0IBP5/O5nLYRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.6.0", + "type-is": "^1.6.18" + }, + "engines": { + "node": ">= 10.16.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/multer/node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/negotiator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", + "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", + "dev": true, + "license": "MIT", + "dependencies": { + "content-type": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.14.0.tgz", + "integrity": "sha512-IVgHNlp/jwQX271+Xzoq9LZNTWXxZK+cEOrGBOBxXNbn7fapnZ+Ts6TVMgNOuAezwG2wdtnMX97tTPK6VEnuOQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-exit-leak-free": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", + "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/on-finished": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz", + "integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/pino": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/pino/-/pino-10.4.0.tgz", + "integrity": "sha512-bk1ZMTwG/Vymx+zPoa28MhNzucFvXJWp3csrSuxuHPSMeUettaCoQ5Jvg07mtC4JGNpcfTwz41oVCnNgBK9+vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@pinojs/redact": "^0.4.0", + "atomic-sleep": "^1.0.0", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^3.0.0", + "pino-std-serializers": "^7.0.0", + "process-warning": "^5.0.0", + "quick-format-unescaped": "^4.0.3", + "real-require": "^1.0.0", + "safe-stable-stringify": "^2.3.1", + "sonic-boom": "^4.0.1", + "thread-stream": "^4.0.0" + }, + "bin": { + "pino": "bin.js" + } + }, + "node_modules/pino-abstract-transport": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz", + "integrity": "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "split2": "^4.0.0" + } + }, + "node_modules/pino-std-serializers": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz", + "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==", + "dev": true, + "license": "MIT" + }, + "node_modules/process-warning": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.1.1.tgz", + "integrity": "sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/proxy-addr": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/proxy-addr/node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.17.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", + "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/quick-format-unescaped": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", + "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", + "dev": true, + "license": "MIT" + }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/real-require": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/real-require/-/real-require-1.0.0.tgz", + "integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==", + "dev": true, + "license": "MIT" + }, + "node_modules/reflect-metadata": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ret": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.5.1.tgz", + "integrity": "sha512-Z/nyvABwcRnRD2mMP7Kz6G1dFZZqX1mNErOnxF42OCQKE07b9k9hK9SQxHL3LFEZUdzQaLM4dId1E/E6Vm4WhA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "dev": true, + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rfdc": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", + "dev": true, + "license": "MIT" + }, + "node_modules/router": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.3.0.tgz", + "integrity": "sha512-bpowRfGjEPe8t9R6fJIzhwmyCGAXwKvxBUsgJm+bJukwdcWmUXbMo7p22w7aYmQBPQTUMNqMV39YX0kMou3z8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/rxjs": { + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", + "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/safe-regex2": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-5.1.2.tgz", + "integrity": "sha512-tAtCGFPPP02VroDVzp4daGi6bC7jWG+41D47GKf18FeH/ubvKQHT9VmhAkvtjNOmJwqtApzWeUpEhkyEYULvmw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "ret": "~0.5.0" + }, + "bin": { + "safe-regex2": "bin/safe-regex2.js" + } + }, + "node_modules/safe-stable-stringify": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", + "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/secure-json-parse": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-4.1.1.tgz", + "integrity": "sha512-lnd81MQEZKjhW/Gd2TQqdd4XP6QYNdDW/EP+I7nTrFHP9y2LmaGPIHk9xsnzcOiEr1c39c/e84xFgGviQKBTRw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/set-cookie-parser": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-3.2.3.tgz", + "integrity": "sha512-bDO7NdAkLprNt3BNl3LAh0oVnOS5+WspzxOxiboo7vRIyTqj2pvFmNWYEFynSGQgpJ+7yG/9nc/aSG20UDBUpg==", + "dev": true, + "license": "MIT" + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "dev": true, + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/sonic-boom": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz", + "integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0" + } + }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "dev": true, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/strtok3": { + "version": "10.8.0", + "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.8.0.tgz", + "integrity": "sha512-e6bW3fD6V01DPmcbLfNtn0cjsiHvTKS/hivgbzqYMfHb/nLes4QQ0H5QBxlkPQayF4xv08AvlSgptGwN86Eemw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@tokenizer/token": "^0.3.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/thread-stream": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.1.tgz", + "integrity": "sha512-Stg6edJXC/6/xqGwSXwFokrUhChJ18amEjpKH89WrQQ0oVFDF+pUUcTpiwWhFUrE89Vf16FBOlwhaw+lescxMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "real-require": "^1.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/toad-cache": { + "version": "3.7.4", + "resolved": "https://registry.npmjs.org/toad-cache/-/toad-cache-3.7.4.tgz", + "integrity": "sha512-m1TdR/rvT7kgGJZhspNtXdsdYk0fddFpJJFlG5s+UkPFo6lkLoZ3YLOaovPYjq1R75NP5JfeTlSHaOsE09peCg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/token-types": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.2.0.tgz", + "integrity": "sha512-s9euYHM//T3loJtbNUYdbAzsMlvKBeRS+XCLFy+UGosMQH19Hwjap5k19i4PPAEJJBsVIpMpVTxl4fIqCuNfUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@borewit/text-codec": "^0.2.3", + "@tokenizer/token": "^0.3.0", + "ieee754": "^1.2.1" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD" + }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "dev": true, + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/uid": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/uid/-/uid-2.0.2.tgz", + "integrity": "sha512-u3xV3X7uzvi5b1MncmZo3i2Aw222Zk1keqLA1YkHldREkAhAqi65wuPfe7lHx8H/Wzy+8CE7S7uS3jekIM5s8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@lukeed/csprng": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/uint8array-extras": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.6.0.tgz", + "integrity": "sha512-8iAasVS4wUx0gPLjH8Xtz2PeDzTSiy8QiLGu2DT3X5GU+egFEQhpnbtkehbAwjvDcxIERmCYcysiODFmE3Ud0Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, + "license": "ISC" + } + } +} diff --git a/sdks/node-integrations/package.json b/sdks/node-integrations/package.json new file mode 100644 index 00000000..3b38d1e9 --- /dev/null +++ b/sdks/node-integrations/package.json @@ -0,0 +1,92 @@ +{ + "name": "@checkgate/node-integrations", + "version": "0.2.0", + "description": "Express, Fastify and NestJS integrations for @checkgate/node: request-bound flag evaluation and startup/shutdown lifecycle.", + "main": "src/index.js", + "types": "src/index.d.ts", + "exports": { + ".": { + "types": "./src/index.d.ts", + "default": "./src/index.js" + }, + "./express": { + "types": "./src/express.d.ts", + "default": "./src/express.js" + }, + "./fastify": { + "types": "./src/fastify.d.ts", + "default": "./src/fastify.js" + }, + "./nestjs": { + "types": "./src/nestjs.d.ts", + "default": "./src/nestjs.js" + }, + "./package.json": "./package.json" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/checkgate-sh/checkgate.git", + "directory": "sdks/node-integrations" + }, + "homepage": "https://checkgate-sh.github.io/checkgate/sdks/node-frameworks", + "bugs": { + "url": "https://github.com/checkgate-sh/checkgate/issues" + }, + "license": "Apache-2.0", + "keywords": [ + "feature-flags", + "checkgate", + "express", + "fastify", + "nestjs" + ], + "files": [ + "src/*.js", + "src/*.d.ts" + ], + "engines": { + "node": ">=22.12.0" + }, + "scripts": { + "test": "node --test --test-concurrency=1 test/", + "typecheck": "tsc -p test/types/tsconfig.json" + }, + "dependencies": { + "fastify-plugin": "^5.0.0 || ^6.0.0" + }, + "peerDependencies": { + "@checkgate/node": ">=0.1.31 <0.3.0", + "@nestjs/common": "^12.0.0", + "@nestjs/core": "^12.0.0", + "express": "^5.0.0", + "fastify": "^5.0.0" + }, + "peerDependenciesMeta": { + "@nestjs/common": { + "optional": true + }, + "@nestjs/core": { + "optional": true + }, + "express": { + "optional": true + }, + "fastify": { + "optional": true + } + }, + "devDependencies": { + "@checkgate/node": "file:../nodejs", + "@nestjs/common": "^12.6.0", + "@nestjs/core": "^12.6.0", + "@nestjs/platform-express": "^12.6.0", + "@nestjs/testing": "^12.6.0", + "@types/express": "^5.0.0", + "@types/node": "^22.0.0", + "express": "^5.3.0", + "fastify": "^5.12.8", + "reflect-metadata": "^0.2.2", + "rxjs": "^7.8.2", + "typescript": "^5.9.3" + } +} diff --git a/sdks/node-integrations/src/core.js b/sdks/node-integrations/src/core.js new file mode 100644 index 00000000..83121efd --- /dev/null +++ b/sdks/node-integrations/src/core.js @@ -0,0 +1,335 @@ +'use strict' + +// Framework-independent pieces shared by the Express, Fastify and NestJS +// adapters: the request-bound evaluator, attribute normalization, and the +// startup/shutdown lifecycle around one shared CheckgateClient. +// +// Nothing here stores per-request data on the client, and nothing here does +// network I/O: an evaluation is a synchronous call into the client's in-memory +// flag store. + +const DEFAULT_KEY = 'anonymous' + +/** + * Converts one attribute value to the string the evaluation core expects, or + * `undefined` to drop it. The native core throws when an attribute a flag rule + * references is not a string; coercing here keeps that error out of requests. + * + * - strings are kept as they are; + * - finite numbers and bigints become their decimal string (`30` -> `"30"`), so + * numeric rule operators (`greater_than`, ...) work on them; + * - booleans become `"true"` / `"false"`; + * - everything else is dropped: `null`, `undefined`, `NaN`, `Infinity`, + * objects, arrays, dates, symbols, functions. A rule on a dropped attribute + * evaluates as if the attribute were absent. + */ +function toAttributeValue(value) { + switch (typeof value) { + case 'string': + return value + case 'number': + return Number.isFinite(value) ? String(value) : undefined + case 'bigint': + return value.toString() + case 'boolean': + return value ? 'true' : 'false' + default: + return undefined + } +} + +/** + * A fresh `Record` holding the coercible attributes of + * `input` (own enumerable string keys only). Never throws; anything that is + * not an object yields `{}`. + */ +function normalizeAttributes(input) { + const out = {} + if (input === null || typeof input !== 'object') return out + let keys + try { + keys = Object.keys(input) + } catch { + return out + } + for (const key of keys) { + // Would set the prototype of `out` instead of a property. + if (key === '__proto__') continue + let raw + try { + raw = input[key] + } catch { + continue + } + const value = toAttributeValue(raw) + if (value !== undefined) out[key] = value + } + return out +} + +/** The user key as a non-empty string, or `fallback`. */ +function normalizeKey(key, fallback) { + if (typeof key === 'string') return key.length > 0 ? key : fallback + if (typeof key === 'number') return Number.isFinite(key) ? String(key) : fallback + if (typeof key === 'bigint') return key.toString() + return fallback +} + +/** + * Normalizes what a `context(req)` extractor returned: `{ key, attributes }`, + * a bare key string, or nothing (anonymous). Returns a frozen + * `{ key: string, attributes: Record }`. + */ +function normalizeContext(raw, defaultKey = DEFAULT_KEY) { + if (raw === null || raw === undefined) { + return Object.freeze({ key: defaultKey, attributes: Object.freeze({}) }) + } + if (typeof raw !== 'object') { + return Object.freeze({ key: normalizeKey(raw, defaultKey), attributes: Object.freeze({}) }) + } + return Object.freeze({ + key: normalizeKey(raw.key, defaultKey), + attributes: Object.freeze(normalizeAttributes(raw.attributes)), + }) +} + +/** + * The extractor used when none is given: the request's authenticated user id + * (`req.user.id`, as Passport and most auth middleware set it), else anonymous. + */ +function defaultContext(req) { + const user = req && req.user + return user && typeof user === 'object' ? { key: user.id } : null +} + +function defaultOnError(err, info) { + const where = info && info.flag !== undefined ? ` evaluating "${String(info.flag)}"` : ` (${info && info.phase})` + console.error(`[Checkgate] Integration error${where}; serving the default.`, err) +} + +/** + * Flags evaluated for one request. Created per request from the one shared + * client; holds only that request's context, which is resolved from + * `resolveContext()` on first use (so auth middleware that runs after the + * Checkgate middleware has set `req.user` by then) and then reused for every + * evaluation of the request. + * + * No method throws: a failure (an extractor that throws, a malformed flag key) + * is reported to `onError` and the evaluation returns its default. + */ +class RequestFlags { + #client + #resolveContext + #defaultKey + #onError + #context = null + + /** + * @param {object} client - a CheckgateClient (or anything with its evaluation methods) + * @param {() => unknown} resolveContext - returns `{ key, attributes }`, a key, or nothing + * @param {{ defaultKey?: string, onError?: (err: unknown, info: object) => void }} [options] + */ + constructor(client, resolveContext, { defaultKey = DEFAULT_KEY, onError = defaultOnError } = {}) { + this.#client = client + this.#resolveContext = resolveContext + this.#defaultKey = defaultKey + this.#onError = onError + } + + /** The normalized `{ key, attributes }` this request evaluates with. */ + get context() { + if (this.#context === null) { + let raw = null + try { + raw = typeof this.#resolveContext === 'function' ? this.#resolveContext() : this.#resolveContext + } catch (err) { + this.#report(err, { phase: 'context' }) + raw = null + } + this.#context = normalizeContext(raw, this.#defaultKey) + } + return this.#context + } + + /** + * Whether the client can answer from flags yet. Before the first + * bootstrap and without an offline cache, the SDK would return the same + * defaults but log a warning per call; skipping the call keeps a server + * that started without Checkgate (`onTimeout: 'continue'`) from logging + * one line per request. `_hydrated` is the SDK's own flag for "flags are + * loaded from the offline cache"; a client without it is always asked. + */ + #servable() { + const client = this.#client + if (typeof client.isReady !== 'function' || client.isReady()) return true + return client._hydrated !== false + } + + #report(err, info) { + try { + this.#onError(err, info) + } catch { + // A throwing error handler must not take the request down either. + } + } + + /** `true` if `flag` is on for this request's user; `false` if it is off, missing, or on error. */ + isEnabled(flag) { + try { + if (!this.#servable()) return false + const { key, attributes } = this.context + return this.#client.isEnabled(flag, key, attributes) === true + } catch (err) { + this.#report(err, { flag }) + return false + } + } + + /** `{ enabled, value }` for this request's user, or `null` if the flag is missing (or on error). */ + getVariant(flag) { + try { + if (!this.#servable()) return null + const { key, attributes } = this.context + const variant = this.#client.getVariant(flag, key, attributes) + return variant === undefined ? null : variant + } catch (err) { + this.#report(err, { flag }) + return null + } + } + + /** The resolved value for this request's user, or `defaultValue` if the flag is missing (or on error). */ + getValue(flag, defaultValue = null) { + const variant = this.getVariant(flag) + return variant === null ? defaultValue : variant.value + } + + /** Records a goal event for this request's user (see `CheckgateClient.track`). */ + track(eventKey, opts) { + try { + if (typeof this.#client.track === 'function') this.#client.track(eventKey, this.context.key, opts) + } catch (err) { + this.#report(err, { phase: 'track' }) + } + } +} + +/** + * The evaluator for one request. + * + * @param {object} client - the one shared CheckgateClient + * @param {() => unknown} resolveContext - called at most once, on first use + * @param {object} [options] - `{ defaultKey, onError }` + */ +function createRequestFlags(client, resolveContext, options) { + return new RequestFlags(client, resolveContext, options) +} + +// --------------------------------------------------------------------------- +// Lifecycle +// --------------------------------------------------------------------------- + +/** Raised by startCheckgate() with `onTimeout: 'fail'` when the client was not ready in time. */ +class CheckgateStartupTimeoutError extends Error { + constructor(timeoutMs, state) { + super(`[Checkgate] Flags were not ready within ${timeoutMs} ms (connection state: ${state}). ` + + "Failing startup because onTimeout is 'fail'.") + this.name = 'CheckgateStartupTimeoutError' + this.timeoutMs = timeoutMs + this.state = state + } +} + +// Clients stopCheckgate() has disconnected and startCheckgate() has not +// started again since. Keyed weakly so a dropped client is not kept alive. +const stopped = new WeakSet() + +function stateOf(client) { + try { + return typeof client.getStatus === 'function' ? client.getStatus().state : 'unknown' + } catch { + return 'unknown' + } +} + +/** + * Connects `client` for an application that is starting. + * + * `client.connect()` keeps retrying while the server is unreachable, so this + * waits at most `readyTimeoutMs`. Then, with `onTimeout: 'continue'` + * (default), it resolves `{ ready: false, timedOut: true }` and the client + * keeps syncing in the background, serving its offline cache (if a `storage` + * adapter has one) or defaults until then; with `'fail'` it disconnects the + * client and rejects with a CheckgateStartupTimeoutError. + * + * A rejected SDK key (CheckgateAuthError) always rejects, whatever + * `onTimeout` says: it will not fix itself. + * + * @param {object} client + * @param {{ readyTimeoutMs?: number, onTimeout?: 'continue'|'fail', logger?: { warn(...args: unknown[]): void } }} [options] + * @returns {Promise<{ ready: boolean, timedOut: boolean }>} + */ +async function startCheckgate(client, { readyTimeoutMs = 5000, onTimeout = 'continue', logger = console } = {}) { + if (!client || typeof client.connect !== 'function') { + throw new TypeError('[Checkgate] startCheckgate() needs a CheckgateClient.') + } + if (onTimeout !== 'continue' && onTimeout !== 'fail') { + throw new TypeError(`[Checkgate] onTimeout must be 'continue' or 'fail', got ${String(onTimeout)}.`) + } + if (typeof readyTimeoutMs !== 'number' || !(readyTimeoutMs >= 0)) { + throw new TypeError('[Checkgate] readyTimeoutMs must be a number >= 0.') + } + stopped.delete(client) + + const READY = Symbol('ready') + const TIMEOUT = Symbol('timeout') + let timer = null + const timeout = new Promise((resolve) => { + timer = setTimeout(resolve, readyTimeoutMs, TIMEOUT) + }) + let outcome + try { + // Rejects on a rejected key, or when the client is disconnected first. + const connected = Promise.resolve().then(() => client.connect()).then(() => READY) + outcome = await Promise.race([connected, timeout]) + } finally { + clearTimeout(timer) + } + if (outcome === READY) return { ready: true, timedOut: false } + + const state = stateOf(client) + if (onTimeout === 'fail') { + stopCheckgate(client) + throw new CheckgateStartupTimeoutError(readyTimeoutMs, state) + } + if (logger && typeof logger.warn === 'function') { + logger.warn(`[Checkgate] Flags not ready within ${readyTimeoutMs} ms (state: ${state}); ` + + 'starting anyway with cached or default values, still syncing in the background.') + } + return { ready: false, timedOut: true } +} + +/** + * Disconnects `client` once: later calls (a second close, a shutdown hook + * after a failed start) do nothing until startCheckgate() starts it again. + * Returns whether this call disconnected it. + */ +function stopCheckgate(client) { + if (!client || stopped.has(client)) return false + stopped.add(client) + if (typeof client.disconnect === 'function') client.disconnect() + return true +} + +module.exports = { + DEFAULT_KEY, + RequestFlags, + CheckgateStartupTimeoutError, + createRequestFlags, + defaultContext, + normalizeAttributes, + normalizeContext, + startCheckgate, + stopCheckgate, + toAttributeValue, +} diff --git a/sdks/node-integrations/src/express.d.ts b/sdks/node-integrations/src/express.d.ts new file mode 100644 index 00000000..3e538089 --- /dev/null +++ b/sdks/node-integrations/src/express.d.ts @@ -0,0 +1,55 @@ +import type { Server, IncomingMessage, RequestListener } from 'node:http' +import type { + CheckgateClientLike, ContextExtractor, RequestFlags, RequestFlagsOptions, StartOptions, StartResult, +} from './index' + +export type { RequestFlags } from './index' +export { startCheckgate, stopCheckgate } from './index' + +declare global { + // eslint-disable-next-line @typescript-eslint/no-namespace + namespace Express { + interface Request { + /** The flags of this request's user, set by `checkgateMiddleware()`. */ + checkgate: RequestFlags + } + } +} + +export interface CheckgateMiddlewareOptions extends RequestFlagsOptions { + /** The one CheckgateClient shared by the whole app. */ + client: CheckgateClientLike + /** + * Returns the request's `{ key, attributes }`. Called once per request, on + * the first evaluation. Default: `{ key: req.user.id }`, else anonymous. + */ + context?: ContextExtractor +} + +/** Sets `req.checkgate` on every request. */ +export declare function checkgateMiddleware( + options: CheckgateMiddlewareOptions +): (req: Req, res: unknown, next: (err?: unknown) => void) => void + +export interface ListenOptions extends StartOptions { + client: CheckgateClientLike + /** Default 0 (any free port). */ + port?: number + host?: string +} + +export interface CheckgateServer { + server: Server + startup: StartResult + /** + * Stops accepting connections, waits for requests in flight, then + * disconnects the client exactly once. Idempotent. + */ + close(): Promise +} + +/** Starts Checkgate (waiting at most `readyTimeoutMs`), then listens. Installs no signal handlers. */ +export declare function listenWithCheckgate( + app: RequestListener | ((req: any, res: any) => void), + options: ListenOptions +): Promise diff --git a/sdks/node-integrations/src/express.js b/sdks/node-integrations/src/express.js new file mode 100644 index 00000000..9b67c39a --- /dev/null +++ b/sdks/node-integrations/src/express.js @@ -0,0 +1,97 @@ +'use strict' + +// Express adapter: `req.checkgate` per request, plus a startup/shutdown helper +// for the HTTP server. Uses nothing from Express itself, so the middleware +// also fits any (req, res, next) stack. + +const http = require('node:http') +const { createRequestFlags, defaultContext, startCheckgate, stopCheckgate } = require('./core.js') + +function requireClient(client, name) { + if (!client || typeof client.isEnabled !== 'function') { + throw new TypeError(`[Checkgate] ${name} needs { client }: one CheckgateClient shared by the whole app.`) + } +} + +/** + * Middleware that sets `req.checkgate`, the flags for this request's user. + * `context(req)` is called once, on the first evaluation, so it can read + * `req.user` set by auth middleware mounted after this one. + * + * @param {object} options + * @param {object} options.client - the one shared CheckgateClient + * @param {(req: object) => unknown} [options.context] - returns `{ key, attributes }`; + * default: `{ key: req.user.id }`, else anonymous + * @param {string} [options.defaultKey='anonymous'] - user key when the context has none + * @param {(err: unknown, info: object) => void} [options.onError] - evaluation errors + * (default: logged to console.error); the evaluation returns its default + */ +function checkgateMiddleware({ client, context = defaultContext, defaultKey, onError } = {}) { + requireClient(client, 'checkgateMiddleware()') + if (typeof context !== 'function') throw new TypeError('[Checkgate] context must be a function (req) => { key, attributes }.') + const options = { defaultKey, onError } + return function checkgate(req, _res, next) { + req.checkgate = createRequestFlags(client, () => context(req), options) + next() + } +} + +/** + * Starts Checkgate, then the HTTP server, and returns a `close()` that stops + * both in order: the server stops accepting connections and finishes the + * requests in flight (with flags still served), then the client disconnects + * exactly once. `close()` is idempotent. + * + * The helper does not install signal handlers; wire them yourself: + * + * const { close } = await listenWithCheckgate(app, { client, port: 3000 }) + * process.once('SIGTERM', () => close().then(() => process.exit(0))) + * + * @param {(req: object, res: object) => void} app - an Express app (any request listener) + * @param {object} options + * @param {object} options.client + * @param {number} [options.port=0] + * @param {string} [options.host] + * @param {number} [options.readyTimeoutMs=5000] + * @param {'continue'|'fail'} [options.onTimeout='continue'] + * @param {{ warn(...args: unknown[]): void }} [options.logger=console] + */ +async function listenWithCheckgate(app, { client, port = 0, host, readyTimeoutMs, onTimeout, logger } = {}) { + requireClient(client, 'listenWithCheckgate()') + const startup = await startCheckgate(client, { readyTimeoutMs, onTimeout, logger }) + const server = http.createServer(app) + try { + await new Promise((resolve, reject) => { + server.once('error', reject) + const done = () => { + server.off('error', reject) + resolve() + } + if (host === undefined) server.listen(port, done) + else server.listen(port, host, done) + }) + } catch (err) { + stopCheckgate(client) + throw err + } + + let closing = null + const close = () => { + if (!closing) { + closing = new Promise((resolve) => { + // Resolves once every connection has ended; an error only + // means the server was not listening any more. + server.close(() => resolve()) + // Keep-alive sockets with no request in flight would hold + // close() open until they time out. + if (typeof server.closeIdleConnections === 'function') server.closeIdleConnections() + }).finally(() => { + stopCheckgate(client) + }) + } + return closing + } + return { server, startup, close } +} + +module.exports = { checkgateMiddleware, listenWithCheckgate, startCheckgate, stopCheckgate } diff --git a/sdks/node-integrations/src/fastify.d.ts b/sdks/node-integrations/src/fastify.d.ts new file mode 100644 index 00000000..38a4032f --- /dev/null +++ b/sdks/node-integrations/src/fastify.d.ts @@ -0,0 +1,40 @@ +import type { FastifyPluginAsync, FastifyRequest } from 'fastify' +import type { CheckgateClientOptions } from '@checkgate/node' +import type { CheckgateClientLike, ContextExtractor, RequestFlags, RequestFlagsOptions, StartOptions } from './index' + +export type { RequestFlags } from './index' +export { startCheckgate, stopCheckgate } from './index' + +declare module 'fastify' { + interface FastifyInstance { + /** The shared CheckgateClient. */ + checkgate: CheckgateClientLike + } + interface FastifyRequest { + /** The flags of this request's user. */ + checkgate: RequestFlags + } +} + +interface CommonOptions extends RequestFlagsOptions, Omit { + /** + * Returns the request's `{ key, attributes }`. Called once per request, on + * the first evaluation. Default: `{ key: request.user.id }`, else anonymous. + */ + context?: ContextExtractor + /** Must be below Fastify's `pluginTimeout` (10 s by default). */ + readyTimeoutMs?: number +} + +export type CheckgatePluginOptions = + | (CommonOptions & { client: CheckgateClientLike; clientOptions?: never }) + | (CommonOptions & { clientOptions: CheckgateClientOptions; client?: never }) + +/** + * Connects while the plugin loads (so `ready()` / `listen()` wait for it, up + * to `readyTimeoutMs`) and disconnects in `onClose`. + */ +declare const checkgatePlugin: FastifyPluginAsync + +export default checkgatePlugin +export { checkgatePlugin } diff --git a/sdks/node-integrations/src/fastify.js b/sdks/node-integrations/src/fastify.js new file mode 100644 index 00000000..16d9f34b --- /dev/null +++ b/sdks/node-integrations/src/fastify.js @@ -0,0 +1,64 @@ +'use strict' + +// Fastify plugin: `fastify.checkgate` (the shared client) and +// `request.checkgate` (the flags for that request's user). The client connects +// while the plugin loads, so `fastify.ready()` / `listen()` wait for it (up to +// `readyTimeoutMs`), and disconnects in `onClose`. + +const fp = require('fastify-plugin') +const { createRequestFlags, defaultContext, startCheckgate, stopCheckgate } = require('./core.js') + +/** + * @param {import('fastify').FastifyInstance} fastify + * @param {object} opts + * @param {object} [opts.client] - a CheckgateClient; or + * @param {object} [opts.clientOptions] - options to construct one (the plugin then owns it) + * @param {(request: object) => unknown} [opts.context] - returns `{ key, attributes }`; + * default: `{ key: request.user.id }`, else anonymous. Called once per request, on first use. + * @param {string} [opts.defaultKey='anonymous'] + * @param {(err: unknown, info: object) => void} [opts.onError] + * @param {number} [opts.readyTimeoutMs=5000] + * @param {'continue'|'fail'} [opts.onTimeout='continue'] + */ +async function checkgatePlugin(fastify, opts) { + const { client: given, clientOptions, context = defaultContext, defaultKey, onError, readyTimeoutMs, onTimeout } = opts || {} + if (given && clientOptions) throw new TypeError('[Checkgate] Pass either client or clientOptions, not both.') + if (!given && !clientOptions) throw new TypeError('[Checkgate] The Fastify plugin needs client or clientOptions.') + if (typeof context !== 'function') throw new TypeError('[Checkgate] context must be a function (request) => { key, attributes }.') + // Fastify aborts a plugin that takes longer than `pluginTimeout` (10 s by + // default) with a timeout error of its own, which would hide the + // onTimeout policy. + const pluginTimeout = fastify.initialConfig && fastify.initialConfig.pluginTimeout + const waitMs = readyTimeoutMs === undefined ? 5000 : readyTimeoutMs + if (typeof pluginTimeout === 'number' && pluginTimeout > 0 && waitMs >= pluginTimeout) { + throw new TypeError(`[Checkgate] readyTimeoutMs (${waitMs}) must be below Fastify's pluginTimeout (${pluginTimeout}).`) + } + // Loaded here, not at the top: an app that passes its own client (or a + // test client) does not need the native addon to load this module. + const client = given || new (require('@checkgate/node').CheckgateClient)(clientOptions) + + const options = { defaultKey, onError } + fastify.decorate('checkgate', client) + // Fastify 5: reference-type request decorators must start as null and be + // assigned per request, or every request would share one object. + fastify.decorateRequest('checkgate', null) + fastify.addHook('onRequest', function checkgateRequest(request, _reply, done) { + request.checkgate = createRequestFlags(client, () => context(request), options) + done() + }) + // Registered before connecting, so a close after a failed start still + // disconnects (once). + fastify.addHook('onClose', async function checkgateClose() { + stopCheckgate(client) + }) + + await startCheckgate(client, { readyTimeoutMs, onTimeout, logger: fastify.log }) +} + +const plugin = fp(checkgatePlugin, { fastify: '5.x', name: 'checkgate' }) + +module.exports = plugin +module.exports.default = plugin +module.exports.checkgatePlugin = plugin +module.exports.startCheckgate = startCheckgate +module.exports.stopCheckgate = stopCheckgate diff --git a/sdks/node-integrations/src/index.d.ts b/sdks/node-integrations/src/index.d.ts new file mode 100644 index 00000000..85f77a2d --- /dev/null +++ b/sdks/node-integrations/src/index.d.ts @@ -0,0 +1,148 @@ +import type { CheckgateClient, FlagEvaluation, FlagValue } from '@checkgate/node' + +export type { FlagEvaluation, FlagValue } + +/** + * The part of a CheckgateClient the integrations use. A real + * `CheckgateClient` satisfies it, and so does {@link createTestClient}. + */ +export interface CheckgateClientLike { + connect(): Promise + disconnect(): void + isReady(): boolean + isEnabled(flagKey: string, userKey: string, userAttributes?: Record): boolean + getVariant(flagKey: string, userKey: string, userAttributes?: Record): FlagEvaluation | null + getStatus?(): { state: string } + track?(eventKey: string, userKey: string, opts?: { value?: number; context?: Record }): void +} + +/** An attribute value as the extractor may return it; see {@link normalizeAttributes}. */ +export type AttributeInput = string | number | bigint | boolean | null | undefined | object + +/** What a `context(req)` extractor returns. */ +export interface EvaluationContextInput { + /** Stable user key used for rollout hashing. Missing or empty: `defaultKey`. */ + key?: string | number | bigint | null + /** Targeting attributes; coerced by {@link normalizeAttributes}. */ + attributes?: Record | null +} + +/** A context extractor: `{ key, attributes }`, a bare key, or nothing (anonymous). */ +export type ContextExtractor = (req: Req) => EvaluationContextInput | string | number | null | undefined + +/** The normalized context an evaluator uses. */ +export interface EvaluationContext { + readonly key: string + readonly attributes: Readonly> +} + +export interface ErrorInfo { + /** The flag being evaluated, when the error came from an evaluation. */ + flag?: unknown + /** `'context'` (the extractor threw) or `'track'`. */ + phase?: 'context' | 'track' +} + +export interface RequestFlagsOptions { + /** User key when the context has none. Default `'anonymous'`. */ + defaultKey?: string + /** Called when an evaluation fails; the evaluation returns its default. Default: console.error. */ + onError?: (err: unknown, info: ErrorInfo) => void +} + +/** + * The flags of one request, bound to that request's user. Every method is + * synchronous, makes no network call, and never throws. + */ +export declare class RequestFlags { + constructor(client: CheckgateClientLike, resolveContext: () => unknown, options?: RequestFlagsOptions) + /** Resolved from the extractor on first use, then fixed for the request. */ + readonly context: EvaluationContext + /** `true` if the flag is on for this user; `false` if off, missing, or on error. */ + isEnabled(flagKey: string): boolean + /** `{ enabled, value }`, or `null` if the flag is missing (or on error). */ + getVariant(flagKey: string): FlagEvaluation | null + /** The resolved value, or `defaultValue` if the flag is missing (or on error). */ + getValue(flagKey: string, defaultValue?: T): FlagValue | T + /** Records a goal event for this user. */ + track(eventKey: string, opts?: { value?: number; context?: Record }): void +} + +export declare function createRequestFlags( + client: CheckgateClientLike, + resolveContext: () => unknown, + options?: RequestFlagsOptions +): RequestFlags + +/** The default extractor: `{ key: req.user.id }` when there is a `req.user`, else anonymous. */ +export declare function defaultContext(req: unknown): EvaluationContextInput | null + +/** + * Strings stay; finite numbers, bigints and booleans become strings; every + * other value (null, undefined, NaN, Infinity, objects, arrays, dates, + * symbols, functions) is dropped. Never throws. + */ +export declare function normalizeAttributes(input: unknown): Record + +export declare function normalizeContext(raw: unknown, defaultKey?: string): EvaluationContext + +export interface StartOptions { + /** How long startup waits for the first flag set. Default 5000. */ + readyTimeoutMs?: number + /** + * After the timeout: `'continue'` (default) starts with cached or default + * values and keeps syncing in the background; `'fail'` disconnects and + * rejects with {@link CheckgateStartupTimeoutError}. A rejected SDK key + * always rejects. + */ + onTimeout?: 'continue' | 'fail' + /** Receives the timeout warning with `'continue'`. Default: console. */ + logger?: { warn(...args: any[]): void } +} + +export interface StartResult { + /** The first flag set from the server arrived in time. */ + ready: boolean + /** Startup gave up waiting (`onTimeout: 'continue'`). */ + timedOut: boolean +} + +export declare class CheckgateStartupTimeoutError extends Error { + readonly name: 'CheckgateStartupTimeoutError' + readonly timeoutMs: number + /** The client's connection state when startup gave up. */ + readonly state: string +} + +/** Connects `client`, waiting at most `readyTimeoutMs`; see {@link StartOptions}. */ +export declare function startCheckgate(client: CheckgateClientLike, options?: StartOptions): Promise + +/** Disconnects `client` once (until started again). Returns whether this call disconnected it. */ +export declare function stopCheckgate(client: CheckgateClientLike): boolean + +/** Per-flag test values: a value, or a function of the context. */ +export type TestFlags = Record }) => FlagValue)> + +/** An in-memory client for application tests: no server, no native addon. */ +export interface TestClient extends CheckgateClientLike { + /** Calls to disconnect(). */ + readonly disconnectCalls: number + /** Goal events recorded by track(). */ + readonly tracked: Array<{ eventKey: string; key: string; opts?: unknown }> + getValue(flagKey: string, userKey: string, userAttributes?: Record, defaultValue?: FlagValue): FlagValue + isPolling(): boolean + getStatus(): { state: 'idle' | 'streaming'; lastSyncAt: number | null; error: null } + onChange(callback: (flagKey: string) => void): () => void + track(eventKey: string, userKey: string, opts?: { value?: number; context?: Record }): void + /** Sets a flag's test value; `undefined` removes the flag. */ + setFlag(flagKey: string, value: TestFlags[string] | undefined): void +} + +/** + * `true`/`false`: on/off; another value: on, serving it; `null`: off; a key + * not listed: missing. + */ +export declare function createTestClient(flags?: TestFlags): TestClient + +/** Re-exported for convenience. */ +export type { CheckgateClient } diff --git a/sdks/node-integrations/src/index.js b/sdks/node-integrations/src/index.js new file mode 100644 index 00000000..19e4ba85 --- /dev/null +++ b/sdks/node-integrations/src/index.js @@ -0,0 +1,19 @@ +'use strict' + +// @checkgate/node-integrations: the framework-independent core. The adapters +// are at the subpaths ./express, ./fastify and ./nestjs. + +const core = require('./core.js') +const { createTestClient } = require('./testing.js') + +module.exports = { + RequestFlags: core.RequestFlags, + CheckgateStartupTimeoutError: core.CheckgateStartupTimeoutError, + createRequestFlags: core.createRequestFlags, + defaultContext: core.defaultContext, + normalizeAttributes: core.normalizeAttributes, + normalizeContext: core.normalizeContext, + startCheckgate: core.startCheckgate, + stopCheckgate: core.stopCheckgate, + createTestClient, +} diff --git a/sdks/node-integrations/src/nestjs.d.ts b/sdks/node-integrations/src/nestjs.d.ts new file mode 100644 index 00000000..4aaf6632 --- /dev/null +++ b/sdks/node-integrations/src/nestjs.d.ts @@ -0,0 +1,78 @@ +import type { CanActivate, DynamicModule, ExecutionContext, InjectionToken, ModuleMetadata, OptionalFactoryDependency, PipeTransform } from '@nestjs/common' +import type { Reflector } from '@nestjs/core' +import type { CheckgateClientOptions } from '@checkgate/node' +import type { + CheckgateClientLike, ContextExtractor, EvaluationContextInput, RequestFlags, RequestFlagsOptions, StartOptions, + StartResult, TestFlags, +} from './index' + +export type { RequestFlags, TestClient } from './index' +export { createTestClient, startCheckgate, stopCheckgate } from './index' + +/** Injection token of the shared CheckgateClient. */ +export declare const CHECKGATE_CLIENT: unique symbol +/** Injection token of the module options. */ +export declare const CHECKGATE_OPTIONS: unique symbol +/** Metadata key holding RequireFlag() requirements. */ +export declare const REQUIRE_FLAG_METADATA: 'checkgate:require-flag' + +export interface CheckgateModuleOptions extends RequestFlagsOptions, StartOptions { + /** A client you built; or */ + client?: CheckgateClientLike + /** options to construct one. */ + clientOptions?: CheckgateClientOptions + /** + * Returns the request's `{ key, attributes }` from the platform request + * (Express or Fastify). Called once per request, on first use. + * Default: `{ key: req.user.id }`, else anonymous. + */ + context?: ContextExtractor + /** Register the module globally. Default true. */ + isGlobal?: boolean +} + +export interface CheckgateModuleAsyncOptions extends Pick { + useFactory: (...args: any[]) => CheckgateModuleOptions | Promise + inject?: Array + /** Default true. */ + isGlobal?: boolean +} + +export declare class CheckgateModule { + static forRoot(options: CheckgateModuleOptions): DynamicModule + static forRootAsync(options: CheckgateModuleAsyncOptions): DynamicModule + /** Backed by createTestClient(flags): no server, no native addon. */ + static forTesting(flags?: TestFlags, options?: Omit): DynamicModule +} + +export declare class CheckgateService { + readonly client: CheckgateClientLike + readonly options: CheckgateModuleOptions + /** Result of startup, or null before bootstrap. */ + readonly startup: StartResult | null + /** Flags for a platform request (one evaluator per request). */ + forRequest(req: unknown): RequestFlags + /** Flags for an explicit context: jobs, consumers, scripts. */ + forContext(context: EvaluationContextInput | string | null): RequestFlags + onApplicationBootstrap(): Promise + onApplicationShutdown(): void +} + +export declare class CheckgateFlagGuard implements CanActivate { + constructor(reflector: Reflector, checkgate: CheckgateService) + canActivate(context: ExecutionContext): boolean +} + +export declare class CheckgateRequestPipe implements PipeTransform { + constructor(checkgate: CheckgateService) + transform(req: unknown): RequestFlags +} + +/** + * The route answers only when `flagKey` is on for the request's user, else + * 404 (or 403). On a class or a method; several must all pass. + */ +export declare function RequireFlag(flagKey: string, options?: { status?: 404 | 403 }): ClassDecorator & MethodDecorator + +/** Parameter decorator: this request's {@link RequestFlags}. */ +export declare function Checkgate(): ParameterDecorator diff --git a/sdks/node-integrations/src/nestjs.js b/sdks/node-integrations/src/nestjs.js new file mode 100644 index 00000000..029134f1 --- /dev/null +++ b/sdks/node-integrations/src/nestjs.js @@ -0,0 +1,230 @@ +'use strict' + +// NestJS module. Plain JavaScript: the decorators are applied by calling them, +// which is what TypeScript compiles `@Injectable()` / `@Inject(token)` into. +// Every constructor parameter names its token with Inject(), so nothing +// depends on `emitDecoratorMetadata`. +// +// No provider here is REQUEST-scoped. A request-scoped provider makes every +// provider that injects it request-scoped too, so Nest would rebuild those +// controllers and services on every request. Instead the singleton +// CheckgateService hands out a small per-request evaluator, cached on the +// request object itself (never on the shared client). + +const { + ForbiddenException, + Inject, + Injectable, + Module, + NotFoundException, + UseGuards, + createParamDecorator, +} = require('@nestjs/common') +const { GUARDS_METADATA } = require('@nestjs/common/constants') +const { Reflector } = require('@nestjs/core') +const { createRequestFlags, defaultContext, startCheckgate, stopCheckgate } = require('./core.js') +const { createTestClient } = require('./testing.js') + +/** Injection token of the shared CheckgateClient. */ +const CHECKGATE_CLIENT = Symbol('CHECKGATE_CLIENT') +/** Injection token of the options passed to forRoot() / returned by forRootAsync()'s factory. */ +const CHECKGATE_OPTIONS = Symbol('CHECKGATE_OPTIONS') +/** Metadata key holding RequireFlag() requirements. */ +const REQUIRE_FLAG_METADATA = 'checkgate:require-flag' + +// Where the request's evaluator is cached, so a guard and a handler parameter +// in the same request share one context (resolved once). +const REQUEST_FLAGS = Symbol('checkgate.requestFlags') + +function injectParams(target, tokens) { + tokens.forEach((token, index) => Inject(token)(target, undefined, index)) +} + +/** The request object of an execution context (the first argument outside HTTP). */ +function requestOf(ctx) { + return ctx.getType() === 'http' ? ctx.switchToHttp().getRequest() : ctx.getArgByIndex(0) +} + +/** + * The application's entry point to Checkgate: owns the client's lifecycle and + * hands out request-bound evaluators. + */ +class CheckgateService { + constructor(client, options) { + this.client = client + this.options = options || {} + /** The result of startup: `{ ready, timedOut }`, or null before bootstrap. */ + this.startup = null + this._context = this.options.context || defaultContext + this._evalOptions = { defaultKey: this.options.defaultKey, onError: this.options.onError } + } + + /** Flags for the request `req` (cached on it: one context per request). */ + forRequest(req) { + if (req === null || typeof req !== 'object') return this.forContext(null) + let flags = req[REQUEST_FLAGS] + if (!flags) { + flags = createRequestFlags(this.client, () => this._context(req), this._evalOptions) + Object.defineProperty(req, REQUEST_FLAGS, { value: flags, configurable: true }) + } + return flags + } + + /** Flags for an explicit context (`{ key, attributes }` or a key): jobs, consumers, scripts. */ + forContext(context) { + return createRequestFlags(this.client, () => context, this._evalOptions) + } + + async onApplicationBootstrap() { + const { readyTimeoutMs, onTimeout, logger } = this.options + this.startup = await startCheckgate(this.client, { readyTimeoutMs, onTimeout, logger }) + } + + // Runs on app.close(), and on SIGTERM/SIGINT only with app.enableShutdownHooks(). + onApplicationShutdown() { + stopCheckgate(this.client) + } +} +Injectable()(CheckgateService) +injectParams(CheckgateService, [CHECKGATE_CLIENT, CHECKGATE_OPTIONS]) + +/** + * Guard behind RequireFlag(): lets the request through only if every + * required flag is on for the request's user; otherwise 404 (default) or 403. + */ +class CheckgateFlagGuard { + constructor(reflector, checkgate) { + this.reflector = reflector + this.checkgate = checkgate + } + + canActivate(ctx) { + const required = this.reflector.getAllAndMerge(REQUIRE_FLAG_METADATA, [ctx.getClass(), ctx.getHandler()]) + if (!required || required.length === 0) return true + const flags = this.checkgate.forRequest(requestOf(ctx)) + for (const { flag, status } of required) { + if (flags.isEnabled(flag)) continue + throw status === 403 ? new ForbiddenException() : new NotFoundException() + } + return true + } +} +Injectable()(CheckgateFlagGuard) +injectParams(CheckgateFlagGuard, [Reflector, CheckgateService]) + +/** + * Method or controller decorator: the route answers only when `flag` is on + * for the request's user, else 404 (or 403 with `{ status: 403 }`). Several + * RequireFlag()s (on the class and the method) must all pass. + * + * Guards run in order: global, controller, then method guards, and method + * decorators apply bottom-up. Put authentication at the controller or global + * level, or list RequireFlag() above UseGuards(AuthGuard) on the method, so + * `req.user` is set when the flag is evaluated. + */ +function RequireFlag(flag, { status = 404 } = {}) { + if (typeof flag !== 'string' || flag.length === 0) throw new TypeError('[Checkgate] RequireFlag() needs a flag key.') + if (status !== 404 && status !== 403) throw new TypeError('[Checkgate] RequireFlag() status must be 404 or 403.') + return (target, key, descriptor) => { + const where = descriptor ? descriptor.value : target + const existing = Reflect.getMetadata(REQUIRE_FLAG_METADATA, where) || [] + Reflect.defineMetadata(REQUIRE_FLAG_METADATA, [...existing, { flag, status }], where) + // One guard per target however many flags it requires. + const guards = Reflect.getMetadata(GUARDS_METADATA, where) || [] + if (!guards.includes(CheckgateFlagGuard)) UseGuards(CheckgateFlagGuard)(target, key, descriptor) + return descriptor + } +} + +/** Turns the request into its evaluator; a pipe so it is built by Nest's injector. */ +class CheckgateRequestPipe { + constructor(checkgate) { + this.checkgate = checkgate + } + + transform(req) { + return this.checkgate.forRequest(req) + } +} +Injectable()(CheckgateRequestPipe) +injectParams(CheckgateRequestPipe, [CheckgateService]) + +const RequestParam = createParamDecorator((_data, ctx) => requestOf(ctx)) + +/** + * Parameter decorator: the flags for this request's user, e.g. + * `handler(@Checkgate() flags: RequestFlags)`. + */ +function Checkgate() { + return RequestParam(CheckgateRequestPipe) +} + +function clientProvider() { + return { + provide: CHECKGATE_CLIENT, + useFactory: (options) => { + if (options.client && options.clientOptions) { + throw new TypeError('[Checkgate] Pass either client or clientOptions, not both.') + } + if (options.client) return options.client + if (!options.clientOptions) throw new TypeError('[Checkgate] CheckgateModule needs client or clientOptions.') + // Loaded only here, so forTesting() and a supplied client need no native addon. + const { CheckgateClient } = require('@checkgate/node') + return new CheckgateClient(options.clientOptions) + }, + inject: [CHECKGATE_OPTIONS], + } +} + +function dynamicModule(optionsProvider, { isGlobal = true, imports = [], extraProviders = [] } = {}) { + return { + module: CheckgateModule, + global: isGlobal, + imports, + providers: [optionsProvider, clientProvider(), CheckgateService, CheckgateFlagGuard, CheckgateRequestPipe, ...extraProviders], + exports: [CHECKGATE_CLIENT, CHECKGATE_OPTIONS, CheckgateService, CheckgateFlagGuard, CheckgateRequestPipe], + } +} + +class CheckgateModule { + /** + * @param {object} options - `{ client | clientOptions, context, defaultKey, onError, + * readyTimeoutMs, onTimeout, logger, isGlobal = true }` + */ + static forRoot(options = {}) { + return dynamicModule({ provide: CHECKGATE_OPTIONS, useValue: options }, { isGlobal: options.isGlobal !== false }) + } + + /** + * @param {object} options - `{ useFactory(...deps) => options, inject?, imports?, isGlobal = true }` + */ + static forRootAsync({ useFactory, inject = [], imports = [], isGlobal = true } = {}) { + if (typeof useFactory !== 'function') throw new TypeError('[Checkgate] forRootAsync() needs useFactory.') + return dynamicModule({ provide: CHECKGATE_OPTIONS, useFactory, inject }, { isGlobal: isGlobal !== false, imports }) + } + + /** + * A module backed by createTestClient(flags): no server, no native addon. + * The client is exported under CHECKGATE_CLIENT, so a test can change + * flags with `moduleRef.get(CHECKGATE_CLIENT).setFlag(key, value)`. + */ + static forTesting(flags = {}, options = {}) { + return CheckgateModule.forRoot({ ...options, client: createTestClient(flags), clientOptions: undefined }) + } +} +Module({})(CheckgateModule) + +module.exports = { + CHECKGATE_CLIENT, + CHECKGATE_OPTIONS, + REQUIRE_FLAG_METADATA, + Checkgate, + CheckgateFlagGuard, + CheckgateModule, + CheckgateRequestPipe, + CheckgateService, + RequireFlag, + createTestClient, + startCheckgate, + stopCheckgate, +} diff --git a/sdks/node-integrations/src/testing.js b/sdks/node-integrations/src/testing.js new file mode 100644 index 00000000..99433a7c --- /dev/null +++ b/sdks/node-integrations/src/testing.js @@ -0,0 +1,70 @@ +'use strict' + +/** + * An in-memory stand-in for CheckgateClient, for application tests: no + * server, no native addon, no network. Pass it as `client` to any adapter + * (or use `CheckgateModule.forTesting()` in NestJS). + * + * `flags` maps a flag key to its value for every user, or to a function + * `({ key, attributes }) => value` for per-user answers: + * + * - `true` / `false`: a boolean flag that is on / off; + * - any other value (string, number, object): the flag is on and serves it; + * - `null`: the flag is off. + * + * A key that is not in `flags` behaves like a missing flag: `isEnabled` is + * `false`, `getVariant` is `null`, `getValue` returns the default. + * + * @param {Record} [flags] + */ +function createTestClient(flags = {}) { + const values = new Map(Object.entries(flags)) + let connected = false + const resolve = (flag, key, attributes) => { + const value = values.get(flag) + return typeof value === 'function' ? value({ key, attributes }) : value + } + const client = { + /** Calls to disconnect(), for assertions. */ + disconnectCalls: 0, + /** Goal events passed to track(), for assertions. */ + tracked: [], + connect() { + connected = true + return Promise.resolve() + }, + disconnect() { + connected = false + client.disconnectCalls++ + }, + isReady: () => connected, + isPolling: () => false, + getStatus: () => ({ state: connected ? 'streaming' : 'idle', lastSyncAt: connected ? Date.now() : null, error: null }), + onChange: () => () => {}, + isEnabled(flag, key, attributes = {}) { + if (!values.has(flag)) return false + const value = resolve(flag, key, attributes) + return value !== false && value !== null && value !== undefined + }, + getVariant(flag, key, attributes = {}) { + if (!values.has(flag)) return null + const value = resolve(flag, key, attributes) + return { enabled: value !== false && value !== null && value !== undefined, value: value === undefined ? null : value } + }, + getValue(flag, key, attributes = {}, defaultValue = null) { + const variant = client.getVariant(flag, key, attributes) + return variant === null ? defaultValue : variant.value + }, + track(eventKey, key, opts) { + client.tracked.push({ eventKey, key, opts }) + }, + /** Changes a flag (or removes it with `undefined`) for the rest of the test. */ + setFlag(flag, value) { + if (value === undefined) values.delete(flag) + else values.set(flag, value) + }, + } + return client +} + +module.exports = { createTestClient } From 4a7bbda5ff02e0dd8bd98b6e409be0bcdca78d2a Mon Sep 17 00:00:00 2001 From: Dennis Paler Date: Sat, 21 Nov 2026 21:52:41 +0800 Subject: [PATCH 04/38] feat(openfeature): @checkgate/openfeature-provider MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An OpenFeature server-SDK provider over @checkgate/node. Every evaluation is answered by the client's local engine (getDetails) — no network request per evaluation, no second copy of the targeting rules. - Boolean / string / number / object resolution with type checks: a value of the wrong type resolves TYPE_MISMATCH; a flag that is off, or has no value, and has no value of the requested type returns the caller's default. - Reasons map to OpenFeature (ROLLOUT_EXCLUDED -> SPLIT, custom PREREQUISITE_FAILED); flagMetadata carries checkgateReason, ruleIndex, variantIndex, rolloutBucket. - Context: targetingKey is the user key; numbers, booleans and dates become string attributes, objects/arrays/null are dropped (the engine rejects non-string attributes a rule reads). - Lifecycle: READY after the first flag set, STALE while reconnecting, READY again on recovery (polling counts only after a successful poll), FATAL on a rejected key at startup, ERROR on a later rejection or an initTimeoutMs expiry; ConfigurationChanged batches the keys of one snapshot. - { client } shares an existing client, which the provider never disconnects. Tests run the real OpenFeature SDK, the real native engine and a real SSE stream (conformance FaultServer): all shared vectors, zero network requests across 4,000 evaluations, lifecycle transitions, auth failure, init timeout, close semantics. Docs: docs/sdks/openfeature.md. --- docs/.vitepress/config.ts | 1 + docs/sdks/openfeature.md | 109 +++++++ sdks/openfeature-provider/.gitignore | 1 + sdks/openfeature-provider/LICENSE | 21 ++ sdks/openfeature-provider/README.md | 51 +++ sdks/openfeature-provider/examples/basic.mjs | 18 ++ sdks/openfeature-provider/examples/typed.ts | 25 ++ sdks/openfeature-provider/package-lock.json | 94 ++++++ sdks/openfeature-provider/package.json | 53 ++++ sdks/openfeature-provider/src/index.d.ts | 72 +++++ sdks/openfeature-provider/src/index.js | 284 +++++++++++++++++ sdks/openfeature-provider/test/bench.mjs | 44 +++ .../test/provider.test.mjs | 292 ++++++++++++++++++ sdks/openfeature-provider/tsconfig.json | 17 + 14 files changed, 1082 insertions(+) create mode 100644 docs/sdks/openfeature.md create mode 100644 sdks/openfeature-provider/.gitignore create mode 100644 sdks/openfeature-provider/LICENSE create mode 100644 sdks/openfeature-provider/README.md create mode 100644 sdks/openfeature-provider/examples/basic.mjs create mode 100644 sdks/openfeature-provider/examples/typed.ts create mode 100644 sdks/openfeature-provider/package-lock.json create mode 100644 sdks/openfeature-provider/package.json create mode 100644 sdks/openfeature-provider/src/index.d.ts create mode 100644 sdks/openfeature-provider/src/index.js create mode 100644 sdks/openfeature-provider/test/bench.mjs create mode 100644 sdks/openfeature-provider/test/provider.test.mjs create mode 100644 sdks/openfeature-provider/tsconfig.json diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 7a7a4e90..bbdd0799 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -88,6 +88,7 @@ export default defineConfig({ { text: "Web (WebAssembly)", link: "/sdks/web" }, { text: "React Native (JSI)", link: "/sdks/react-native" }, { text: "Flutter (FFI)", link: "/sdks/flutter" }, + { text: "OpenFeature (Node.js)", link: "/sdks/openfeature" }, ], }, { diff --git a/docs/sdks/openfeature.md b/docs/sdks/openfeature.md new file mode 100644 index 00000000..014d4b5e --- /dev/null +++ b/docs/sdks/openfeature.md @@ -0,0 +1,109 @@ +--- +title: "OpenFeature Provider for Node.js — Checkgate" +description: "Use Checkgate through the OpenFeature server SDK. Flags are evaluated locally by the Checkgate Rust engine: no network request per evaluation." +--- + +# OpenFeature provider (Node.js) + +`@checkgate/openfeature-provider` plugs Checkgate into the +[OpenFeature](https://openfeature.dev) server SDK for Node.js. Code written against the +OpenFeature API keeps working; evaluations are answered by the same local engine as +[`@checkgate/node`](./nodejs), so there is no network request per evaluation. + +## Installation + +```bash +npm install @checkgate/openfeature-provider @checkgate/node @openfeature/server-sdk +``` + +Requires Node.js 20 or later, `@openfeature/server-sdk` 1.17 or later and `@checkgate/node` 0.2. + +## Quick start + +```typescript +import { OpenFeature } from '@openfeature/server-sdk' +import { CheckgateProvider } from '@checkgate/openfeature-provider' + +const provider = new CheckgateProvider({ + serverUrl: process.env.CHECKGATE_URL!, + sdkKey: process.env.CHECKGATE_SDK_KEY!, +}) + +await OpenFeature.setProviderAndWait(provider) +const client = OpenFeature.getClient() + +const enabled = await client.getBooleanValue('new-checkout', false, { + targetingKey: 'user-123', + plan: 'pro', +}) +``` + +Create the provider once at startup, as you would a `CheckgateClient`. To use the same +connection directly as well, pass an existing client: `new CheckgateProvider({ client })`. The +provider then never disconnects it. + +## Options + +| Option | Default | | +|---|---|---| +| `client` | — | An existing `CheckgateClient` to use instead of creating one. | +| `serverUrl`, `sdkKey`, … | — | Any [`CheckgateClient` option](./nodejs#new-checkgateclient-options), when the provider creates its own client. | +| `initTimeoutMs` | wait | Stop waiting for the first flag set after this long: the provider reports `ERROR`, keeps connecting in the background, and turns `READY` when it succeeds. | +| `requireTargetingKey` | `true` | Without a `targetingKey`, resolve `TARGETING_KEY_MISSING`. With `false`, an empty key is used (fine for flags without percentage rollouts or weighted variants). | + +## Evaluation context + +`targetingKey` is the user key that percentage rollouts and weighted variants hash. Every other +context field becomes a targeting attribute. Checkgate attributes are strings, so numbers and +booleans are converted to strings (numeric operators still compare them as numbers), dates +become ISO-8601 strings, and objects, arrays and `null` are left out. + +## Types + +| OpenFeature call | Checkgate flag type | +|---|---| +| `getBooleanValue` | boolean | +| `getStringValue` | string | +| `getNumberValue` | integer (exact up to 2^53) | +| `getObjectValue` | JSON (object or array) | + +A flag of another type resolves `TYPE_MISMATCH` and returns your default. A flag that is off, or +on with no value configured, and has no value of the requested type returns your default +without an error. + +## Resolution details + +| Checkgate | OpenFeature `reason` | +|---|---| +| flag switched off | `DISABLED` | +| a prerequisite is not satisfied | `PREREQUISITE_FAILED` (custom reason) | +| a targeting rule matched | `TARGETING_MATCH` | +| percentage rollout or weighted variant (in or out) | `SPLIT` | +| rules present, none matched | `DEFAULT` | +| no rules, rollout or variants | `STATIC` | +| flag does not exist | `ERROR`, `FLAG_NOT_FOUND` | + +`variant` is the resolved value as a string for boolean, string and number flags. +`flagMetadata.checkgateReason` carries the exact Checkgate reason (`ROLLOUT_EXCLUDED` is +reported as `SPLIT` to OpenFeature), plus `ruleIndex`, `variantIndex` and `rolloutBucket` +when they apply. See [`getDetails()`](./nodejs#client-getdetails-flagkey-userkey-attributes-evaluationdetails-null). + +## Provider lifecycle + +| Checkgate client | Provider status | +|---|---| +| first flag set received | `READY` | +| stream lost, reconnecting (flags still served) | `STALE` | +| stream or poll back | `READY` | +| `initTimeoutMs` elapsed before the first flag set | `ERROR`, then `READY` when it arrives | +| SDK key rejected before the first flag set | `FATAL` | +| SDK key rejected later (held flags still served) | `ERROR` | + +A flag change emits `PROVIDER_CONFIGURATION_CHANGED` with `flagsChanged`; the flags of one +snapshot are reported in one event. `OpenFeature.close()` disconnects a client the provider +created. + +## Tracking + +`client.track('checkout', { targetingKey: 'user-123' }, { value: 49.99 })` records a Checkgate +goal event for [experiments](../guide/experimentation), with the remaining details as its context. diff --git a/sdks/openfeature-provider/.gitignore b/sdks/openfeature-provider/.gitignore new file mode 100644 index 00000000..c2658d7d --- /dev/null +++ b/sdks/openfeature-provider/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/sdks/openfeature-provider/LICENSE b/sdks/openfeature-provider/LICENSE new file mode 100644 index 00000000..605a128f --- /dev/null +++ b/sdks/openfeature-provider/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 ThinkGrid Labs + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/sdks/openfeature-provider/README.md b/sdks/openfeature-provider/README.md new file mode 100644 index 00000000..ef3365f8 --- /dev/null +++ b/sdks/openfeature-provider/README.md @@ -0,0 +1,51 @@ +# @checkgate/openfeature-provider + +[OpenFeature](https://openfeature.dev) provider for [Checkgate](https://github.com/checkgate-sh/checkgate) +(Node.js, server paradigm). Flags are evaluated in-process by the Checkgate Rust engine that +powers [`@checkgate/node`](https://www.npmjs.com/package/@checkgate/node): no network request +per evaluation, the same results as calling the SDK directly. + +```bash +npm install @checkgate/openfeature-provider @checkgate/node @openfeature/server-sdk +``` + +```typescript +import { OpenFeature } from '@openfeature/server-sdk' +import { CheckgateProvider } from '@checkgate/openfeature-provider' + +const provider = new CheckgateProvider({ + serverUrl: process.env.CHECKGATE_URL!, + sdkKey: process.env.CHECKGATE_SDK_KEY!, +}) + +await OpenFeature.setProviderAndWait(provider) +const client = OpenFeature.getClient() + +const enabled = await client.getBooleanValue('new-checkout', false, { + targetingKey: 'user-123', + plan: 'pro', +}) +``` + +- `targetingKey` is the user key; other context fields are targeting attributes (numbers, + booleans and dates are converted to strings; objects and arrays are left out). +- Reasons: `DISABLED`, `TARGETING_MATCH`, `SPLIT`, `DEFAULT`, `STATIC`, and the custom + `PREREQUISITE_FAILED`. `flagMetadata` carries `checkgateReason`, `ruleIndex`, + `variantIndex` and `rolloutBucket` when they apply. +- Lifecycle: `READY` after the first flag set, `STALE` while reconnecting (last known flags + are still served), `FATAL` if the SDK key is rejected at startup. `initTimeoutMs` bounds the + startup wait. +- `new CheckgateProvider({ client })` shares an existing `CheckgateClient`; the provider never + disconnects a client it did not create. + +Full documentation: [OpenFeature provider](https://checkgate-sh.github.io/checkgate/sdks/openfeature). + +## Development + +```bash +(cd ../nodejs && npm ci && npm run build) # the native engine +npm ci && npm run typecheck && npm test +node test/bench.mjs # provider overhead vs. direct SDK calls +``` + +Apache-2.0 diff --git a/sdks/openfeature-provider/examples/basic.mjs b/sdks/openfeature-provider/examples/basic.mjs new file mode 100644 index 00000000..f1fe4474 --- /dev/null +++ b/sdks/openfeature-provider/examples/basic.mjs @@ -0,0 +1,18 @@ +// Run against a local Checkgate server: +// CHECKGATE_URL=http://localhost:3000 CHECKGATE_SDK_KEY= node examples/basic.mjs +import { OpenFeature } from '@openfeature/server-sdk'; +import { CheckgateProvider } from '@checkgate/openfeature-provider'; + +const provider = new CheckgateProvider({ + serverUrl: process.env.CHECKGATE_URL ?? 'http://localhost:3000', + sdkKey: process.env.CHECKGATE_SDK_KEY, + initTimeoutMs: 5_000, +}); + +await OpenFeature.setProviderAndWait(provider); +const client = OpenFeature.getClient(); + +const details = await client.getBooleanDetails('new-checkout', false, { targetingKey: 'user-123', plan: 'pro' }); +console.log(details); // { value, reason, variant, flagMetadata: { checkgateReason, ... } } + +await OpenFeature.close(); diff --git a/sdks/openfeature-provider/examples/typed.ts b/sdks/openfeature-provider/examples/typed.ts new file mode 100644 index 00000000..1a6594c3 --- /dev/null +++ b/sdks/openfeature-provider/examples/typed.ts @@ -0,0 +1,25 @@ +// Type-checked by `npm run typecheck` (never executed): the README example, +// compiled against the real OpenFeature and Checkgate declarations. +import { OpenFeature } from '@openfeature/server-sdk'; +import { CheckgateProvider } from '@checkgate/openfeature-provider'; + +export async function main(): Promise { + const provider = new CheckgateProvider({ + serverUrl: process.env.CHECKGATE_URL!, + sdkKey: process.env.CHECKGATE_SDK_KEY!, + initTimeoutMs: 5_000, + }); + + await OpenFeature.setProviderAndWait(provider); + const client = OpenFeature.getClient(); + + const enabled: boolean = await client.getBooleanValue('new-checkout', false, { + targetingKey: 'user-123', + plan: 'pro', + }); + const details = await client.getStringDetails('checkout-theme', 'classic', { targetingKey: 'user-123' }); + const reason: string | undefined = details.reason; + void reason; + await OpenFeature.close(); + return enabled; +} diff --git a/sdks/openfeature-provider/package-lock.json b/sdks/openfeature-provider/package-lock.json new file mode 100644 index 00000000..849abe28 --- /dev/null +++ b/sdks/openfeature-provider/package-lock.json @@ -0,0 +1,94 @@ +{ + "name": "@checkgate/openfeature-provider", + "version": "0.2.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@checkgate/openfeature-provider", + "version": "0.2.0", + "license": "Apache-2.0", + "devDependencies": { + "@checkgate/node": "file:../nodejs", + "@openfeature/server-sdk": "1.23.0", + "@types/node": "22.19.1", + "typescript": "5.9.3" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@checkgate/node": ">=0.2.0 <1", + "@openfeature/server-sdk": "^1.17.0" + } + }, + "../nodejs": { + "name": "@checkgate/node", + "version": "0.1.31", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "eventsource": "^4.1.0" + }, + "devDependencies": { + "@napi-rs/cli": "^3.5.1" + } + }, + "node_modules/@checkgate/node": { + "resolved": "../nodejs", + "link": true + }, + "node_modules/@openfeature/core": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/@openfeature/core/-/core-1.12.0.tgz", + "integrity": "sha512-7PCPzyd1OC19begz30+CRknFB0ChtyaZUhk7YWrk+Bov1fpVw0HYkTXtoxxsvPfDZB9P9WsT7uixN+Z8f9+bcA==", + "dev": true, + "license": "Apache-2.0", + "peer": true + }, + "node_modules/@openfeature/server-sdk": { + "version": "1.23.0", + "resolved": "https://registry.npmjs.org/@openfeature/server-sdk/-/server-sdk-1.23.0.tgz", + "integrity": "sha512-JWeLvltJIV0AFgOfbw7hK9b9Rw/5wWq+RMhCIU9sJtAqarxr8hSPglG+JAGGhYdElAz3Qwe9W3ApWyPNkQEyqg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@openfeature/core": "^1.12.0" + } + }, + "node_modules/@types/node": { + "version": "22.19.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.1.tgz", + "integrity": "sha512-LCCV0HdSZZZb34qifBsyWlUmok6W7ouER+oQIGBScS8EsZsQbrtFTUrDX4hOl+CS6p7cnNC4td+qrSVGSCTUfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/sdks/openfeature-provider/package.json b/sdks/openfeature-provider/package.json new file mode 100644 index 00000000..ebc2d713 --- /dev/null +++ b/sdks/openfeature-provider/package.json @@ -0,0 +1,53 @@ +{ + "name": "@checkgate/openfeature-provider", + "version": "0.2.0", + "description": "OpenFeature provider for Checkgate \u2014 flags evaluated locally by the Checkgate Rust engine, no network call per evaluation.", + "main": "src/index.js", + "types": "src/index.d.ts", + "repository": { + "type": "git", + "url": "git+https://github.com/checkgate-sh/checkgate.git", + "directory": "sdks/openfeature-provider" + }, + "homepage": "https://github.com/checkgate-sh/checkgate#readme", + "bugs": { + "url": "https://github.com/checkgate-sh/checkgate/issues" + }, + "license": "Apache-2.0", + "keywords": [ + "openfeature", + "feature-flags", + "checkgate", + "provider" + ], + "files": [ + "src/index.js", + "src/index.d.ts", + "README.md", + "LICENSE" + ], + "engines": { + "node": ">=20" + }, + "scripts": { + "test": "node --test", + "typecheck": "tsc --noEmit -p tsconfig.json" + }, + "peerDependencies": { + "@checkgate/node": ">=0.2.0 <1", + "@openfeature/server-sdk": "^1.17.0" + }, + "devDependencies": { + "@checkgate/node": "file:../nodejs", + "@openfeature/server-sdk": "1.23.0", + "typescript": "5.9.3", + "@types/node": "22.19.1" + }, + "exports": { + ".": { + "types": "./src/index.d.ts", + "default": "./src/index.js" + }, + "./package.json": "./package.json" + } +} diff --git a/sdks/openfeature-provider/src/index.d.ts b/sdks/openfeature-provider/src/index.d.ts new file mode 100644 index 00000000..0e1ad8c7 --- /dev/null +++ b/sdks/openfeature-provider/src/index.d.ts @@ -0,0 +1,72 @@ +import type { + EvaluationContext, + JsonValue, + Logger, + OpenFeatureEventEmitter, + Provider, + ResolutionDetails, + TrackingEventDetails, +} from '@openfeature/server-sdk'; +import type { CheckgateClient, CheckgateClientOptions } from '@checkgate/node'; + +interface ProviderBehaviour { + /** + * Stop waiting for the first flag set after this many milliseconds: + * `initialize()` rejects (provider ERROR) while the client keeps connecting + * in the background, and the provider turns READY once it succeeds. + * Default: wait as long as it takes. + */ + initTimeoutMs?: number; + /** + * Resolve `TARGETING_KEY_MISSING` when the context has no `targetingKey`. + * With `false`, a missing key evaluates as the empty string. Default: true. + */ + requireTargetingKey?: boolean; +} + +/** Use an existing client (shared with direct SDK use); it is never disconnected by the provider. */ +export interface CheckgateProviderClientOptions extends ProviderBehaviour { + client: CheckgateClient; +} + +/** Let the provider create, connect and (on close) disconnect its own client. */ +export interface CheckgateProviderConnectionOptions extends ProviderBehaviour, CheckgateClientOptions { + client?: undefined; +} + +export type CheckgateProviderOptions = + | CheckgateProviderClientOptions + | CheckgateProviderConnectionOptions; + +/** + * OpenFeature provider (server paradigm) backed by Checkgate's local + * evaluation engine. No network request per evaluation. + * + * Reasons: `DISABLED`, `TARGETING_MATCH`, `SPLIT` (partial rollout or + * weighted variant, including users a rollout excluded), `DEFAULT`, `STATIC`, + * and the custom `PREREQUISITE_FAILED`. `flagMetadata` carries + * `checkgateReason` and, when they apply, `ruleIndex`, `variantIndex` and + * `rolloutBucket`. + */ +export declare class CheckgateProvider implements Provider { + constructor(options: CheckgateProviderOptions); + readonly metadata: { readonly name: 'checkgate' }; + readonly runsOn: 'server'; + readonly hooks: []; + readonly events: OpenFeatureEventEmitter; + /** The Checkgate client answering evaluations. */ + readonly client: CheckgateClient; + initialize(context?: EvaluationContext): Promise; + onClose(): Promise; + resolveBooleanEvaluation(flagKey: string, defaultValue: boolean, context: EvaluationContext, logger?: Logger): Promise>; + resolveStringEvaluation(flagKey: string, defaultValue: string, context: EvaluationContext, logger?: Logger): Promise>; + resolveNumberEvaluation(flagKey: string, defaultValue: number, context: EvaluationContext, logger?: Logger): Promise>; + resolveObjectEvaluation(flagKey: string, defaultValue: T, context: EvaluationContext, logger?: Logger): Promise>; + track(trackingEventName: string, context: EvaluationContext, trackingEventDetails?: TrackingEventDetails): void; +} + +/** The Checkgate attributes an OpenFeature context becomes (strings only; `targetingKey` excluded). */ +export declare function toAttributes(context: EvaluationContext | undefined): Record; + +/** Checkgate evaluation reason → OpenFeature reason. */ +export declare const REASONS: Readonly>; diff --git a/sdks/openfeature-provider/src/index.js b/sdks/openfeature-provider/src/index.js new file mode 100644 index 00000000..d374b332 --- /dev/null +++ b/sdks/openfeature-provider/src/index.js @@ -0,0 +1,284 @@ +'use strict'; + +// OpenFeature provider for Checkgate (server paradigm). +// +// Every evaluation is answered by the Checkgate client's local Rust engine +// (`getDetails`), the same code that answers `isEnabled`/`getVariant`: no +// network request per evaluation and no second copy of the targeting rules. +// The provider only translates — OpenFeature context in, OpenFeature +// resolution details out — and maps the client's connection state onto the +// OpenFeature provider lifecycle (READY / STALE / ERROR / FATAL). + +const { + OpenFeatureEventEmitter, + ProviderEvents, + ErrorCode, + FlagNotFoundError, + TypeMismatchError, + TargetingKeyMissingError, + ProviderNotReadyError, + ProviderFatalError, + GeneralError, + StandardResolutionReasons, +} = require('@openfeature/server-sdk'); + +/** Checkgate reason → OpenFeature reason. */ +const REASONS = { + DISABLED: StandardResolutionReasons.DISABLED, + // OpenFeature has no standard word for it; custom reasons are allowed. + PREREQUISITE_FAILED: 'PREREQUISITE_FAILED', + TARGETING_MATCH: StandardResolutionReasons.TARGETING_MATCH, + ROLLOUT_EXCLUDED: StandardResolutionReasons.SPLIT, + SPLIT: StandardResolutionReasons.SPLIT, + DEFAULT: StandardResolutionReasons.DEFAULT, + STATIC: StandardResolutionReasons.STATIC, +}; + +/** States in which the held flags may be going stale. */ +const STALE_STATES = new Set(['connecting', 'reconnecting']); + +/** + * OpenFeature evaluation context → Checkgate attributes. + * + * Checkgate attributes are strings (numeric operators parse them), so + * numbers and booleans are stringified, dates become ISO-8601, and values a + * string cannot represent (objects, arrays, null) are left out — rather than + * passed through to the engine, which rejects a non-string attribute a rule + * reads. `targetingKey` is the user key, not an attribute. + */ +function toAttributes(context) { + const attributes = {}; + for (const [name, value] of Object.entries(context || {})) { + if (name === 'targetingKey' || value === undefined || value === null) continue; + if (typeof value === 'string') attributes[name] = value; + else if (typeof value === 'number') { + if (Number.isFinite(value)) attributes[name] = String(value); + } else if (typeof value === 'boolean') attributes[name] = String(value); + else if (value instanceof Date) { + if (!Number.isNaN(value.getTime())) attributes[name] = value.toISOString(); + } + } + return attributes; +} + +function typeOf(value) { + if (value === null) return 'null'; + if (Array.isArray(value)) return 'array'; + return typeof value; +} + +/** Whether `value` is acceptable for a resolution of `expected` type. */ +function matchesType(value, expected) { + if (expected === 'object') return value !== null && typeof value === 'object'; + return typeof value === expected; +} + +class CheckgateProvider { + /** + * @param {object} options + * Either `{ client }` — an existing `CheckgateClient` the application + * also uses directly (the provider never disconnects it) — or the + * `CheckgateClient` options (`serverUrl`, `sdkKey`, ...), in which case + * the provider creates, connects and on close disconnects its own client. + * @param {number} [options.initTimeoutMs] - give up waiting for the first + * flag set after this long: `initialize()` rejects (provider ERROR) + * while the client keeps connecting in the background, and the provider + * turns READY when it succeeds. Default: wait as long as it takes + * (OpenFeature's `setProviderAndWait` then waits too). + * @param {boolean} [options.requireTargetingKey=true] - resolve + * TARGETING_KEY_MISSING when the context has no `targetingKey`. With + * false, a missing key is evaluated as the empty string (fine for flags + * with no percentage rollout or weighted variants). + */ + constructor(options = {}) { + const { client, initTimeoutMs, requireTargetingKey = true, ...clientOptions } = options; + this.metadata = { name: 'checkgate' }; + this.runsOn = 'server'; + this.hooks = []; + this.events = new OpenFeatureEventEmitter(); + this._initTimeoutMs = initTimeoutMs; + this._requireTargetingKey = requireTargetingKey; + if (client) { + this.client = client; + this._ownsClient = false; + } else { + if (!clientOptions.serverUrl) { + throw new Error('[Checkgate] CheckgateProvider needs `client` or `serverUrl`.'); + } + // Required lazily so `{ client }` users need not resolve it twice. + const { CheckgateClient } = require('@checkgate/node'); + this.client = new CheckgateClient(clientOptions); + this._ownsClient = true; + } + this._initialized = false; + this._closed = false; + this._announced = null; // last lifecycle event emitted: 'ready' | 'stale' | 'error' + this._staleSince = 0; + this._pendingChanges = null; + this._unsubscribe = []; + } + + /** Called by OpenFeature once the provider is set; resolves → READY. */ + async initialize() { + this._closed = false; + this._watch(); + if (!this.client.isReady()) { + try { + await this._connect(); + } catch (err) { + if (err && err.name === 'CheckgateAuthError') { + // A rejected key does not become valid by waiting: FATAL. + throw new ProviderFatalError(err.message); + } + throw new GeneralError(err && err.message ? err.message : String(err)); + } + } + this._initialized = true; + this._announced = 'ready'; + } + + _connect() { + const connecting = this.client.connect(); + if (typeof this._initTimeoutMs !== 'number') return connecting; + let timer; + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error( + `[Checkgate] No flag set from the server within ${this._initTimeoutMs} ms; ` + + 'still connecting in the background.')), this._initTimeoutMs); + if (timer.unref) timer.unref(); + }); + return Promise.race([connecting, timeout]).finally(() => clearTimeout(timer)); + } + + /** Subscribes to the client once: flag changes and connection state. */ + _watch() { + if (this._unsubscribe.length > 0) return; + this._unsubscribe.push(this.client.onChange((key) => this._queueChange(key))); + this._unsubscribe.push(this.client.onStatusChange((status) => this._onStatus(status))); + } + + /** Flag changes of one snapshot are reported as one event. */ + _queueChange(key) { + if (this._closed) return; + if (this._pendingChanges) { + this._pendingChanges.add(key); + return; + } + this._pendingChanges = new Set([key]); + queueMicrotask(() => { + const flagsChanged = Array.from(this._pendingChanges); + this._pendingChanges = null; + if (!this._closed) this.events.emit(ProviderEvents.ConfigurationChanged, { flagsChanged }); + }); + } + + _onStatus({ state, error, lastSyncAt }) { + if (this._closed) return; + // 'polling' is entered before any poll has succeeded; it shows + // current flags only once a sync lands after the provider went stale. + const fresh = state === 'streaming' || + (state === 'polling' && lastSyncAt !== null && lastSyncAt >= this._staleSince); + if (fresh && this.client.isReady()) { + // Recovered (or became ready after a timed-out initialize). + if (this._announced !== 'ready') { + this._initialized = true; + this._announce('ready', ProviderEvents.Ready, {}); + } + } else if ((STALE_STATES.has(state) || state === 'polling') && this._initialized) { + if (this._announced !== 'stale') this._staleSince = Date.now(); + this._announce('stale', ProviderEvents.Stale, { + message: `Checkgate connection ${state}; serving the last known flags.`, + }); + } else if (state === 'auth_failed' && this._initialized) { + // Flags already held keep being served, so not FATAL: evaluations + // continue while the key is fixed and connect() retried. + this._announce('error', ProviderEvents.Error, { + message: error && error.message ? error.message : 'SDK key rejected', + errorCode: ErrorCode.GENERAL, + }); + } + } + + _announce(kind, event, details) { + if (this._announced === kind) return; + this._announced = kind; + this.events.emit(event, details); + } + + async onClose() { + this._closed = true; + for (const off of this._unsubscribe.splice(0)) off(); + this._pendingChanges = null; + if (this._ownsClient) this.client.disconnect(); + this._initialized = false; + this._announced = null; + } + + resolveBooleanEvaluation(flagKey, defaultValue, context, logger) { + return this._resolve(flagKey, defaultValue, context, 'boolean', logger); + } + + resolveStringEvaluation(flagKey, defaultValue, context, logger) { + return this._resolve(flagKey, defaultValue, context, 'string', logger); + } + + resolveNumberEvaluation(flagKey, defaultValue, context, logger) { + return this._resolve(flagKey, defaultValue, context, 'number', logger); + } + + resolveObjectEvaluation(flagKey, defaultValue, context, logger) { + return this._resolve(flagKey, defaultValue, context, 'object', logger); + } + + /** + * OpenFeature tracking → a Checkgate goal event (A/B conversions). + * `trackingEventDetails.value` becomes the event value; the remaining + * details are its context. + */ + track(trackingEventName, context, trackingEventDetails = {}) { + const key = context && context.targetingKey; + if (typeof key !== 'string' || key === '') return; + const { value, ...rest } = trackingEventDetails || {}; + this.client.track(trackingEventName, key, { + ...(typeof value === 'number' ? { value } : {}), + ...(Object.keys(rest).length > 0 ? { context: rest } : {}), + }); + } + + // Async to satisfy the interface; resolves on the same tick (no I/O). + async _resolve(flagKey, defaultValue, context, expected) { + if (!this._initialized) throw new ProviderNotReadyError('Checkgate provider is not initialized.'); + const targetingKey = context && context.targetingKey; + if (typeof targetingKey !== 'string' || targetingKey === '') { + if (this._requireTargetingKey) { + throw new TargetingKeyMissingError('Checkgate needs `targetingKey` in the evaluation context.'); + } + } + const details = this.client.getDetails( + flagKey, typeof targetingKey === 'string' ? targetingKey : '', toAttributes(context)); + if (details === null) throw new FlagNotFoundError(`Flag '${flagKey}' not found.`); + + const reason = REASONS[details.reason] || details.reason; + const flagMetadata = { checkgateReason: details.reason }; + if (details.ruleIndex !== undefined) flagMetadata.ruleIndex = details.ruleIndex; + if (details.variantIndex !== undefined) flagMetadata.variantIndex = details.variantIndex; + if (details.rolloutBucket !== undefined) flagMetadata.rolloutBucket = details.rolloutBucket; + + const value = details.value; + if (!matchesType(value, expected)) { + // A flag that is off (or on with no value configured) and has no + // value of the requested type means "use the caller's default" — + // not a type error. + if (!details.enabled || value === null) { + return { value: defaultValue, reason, flagMetadata }; + } + throw new TypeMismatchError( + `Flag '${flagKey}' resolved to a ${typeOf(value)}, not a ${expected}.`); + } + const resolution = { value, reason, flagMetadata }; + if (typeof value !== 'object') resolution.variant = String(value); + return resolution; + } +} + +module.exports = { CheckgateProvider, toAttributes, REASONS }; diff --git a/sdks/openfeature-provider/test/bench.mjs b/sdks/openfeature-provider/test/bench.mjs new file mode 100644 index 00000000..b5e9ecbc --- /dev/null +++ b/sdks/openfeature-provider/test/bench.mjs @@ -0,0 +1,44 @@ +// Provider overhead: the same evaluation through OpenFeature vs. the Checkgate +// client directly, same process, same flags. Not part of `npm test`. +// node test/bench.mjs [iterations] +import { createRequire } from 'node:module'; +import { FaultServer } from '../../conformance/fault-server.mjs'; +const require = createRequire(import.meta.url); +const { OpenFeature } = require('@openfeature/server-sdk'); +const { CheckgateProvider } = require('../src/index.js'); +for (const level of ['log', 'warn']) console[level] = () => {}; + +const N = Number(process.argv[2] || 200_000); +const server = new FaultServer(); +const url = await server.start(); +server.upsert({ key: 'plain', is_enabled: true, rollout_percentage: null, rules: [] }); +server.upsert({ key: 'targeted', is_enabled: true, rollout_percentage: 50, rules: [{ attribute: 'plan', operator: 'equals', values: ['enterprise'] }] }); +const provider = new CheckgateProvider({ serverUrl: url, sdkKey: 'sk_conformance', reportImpressions: false }); +await OpenFeature.setProviderAndWait(provider); +const of = OpenFeature.getClient(); +const direct = provider.client; + +async function time(label, fn) { + for (let i = 0; i < 20_000; i++) await fn(i); // warm-up + const runs = []; + for (let r = 0; r < 5; r++) { + const t = process.hrtime.bigint(); + for (let i = 0; i < N; i++) await fn(i); + runs.push(Number(process.hrtime.bigint() - t) / N); + } + runs.sort((a, b) => a - b); + console.error(`${label.padEnd(44)} median ${runs[2].toFixed(0)} ns/op (min ${runs[0].toFixed(0)}, max ${runs[4].toFixed(0)})`); + return runs[2]; +} +const ctx = { targetingKey: 'user-1', plan: 'pro', country: 'PH' }; +const attrs = { plan: 'pro', country: 'PH' }; +const out = {}; +out.direct_isEnabled_plain = await time('direct isEnabled (plain)', () => direct.isEnabled('plain', 'user-1', attrs)); +out.direct_getDetails_plain = await time('direct getDetails (plain)', () => direct.getDetails('plain', 'user-1', attrs)); +out.of_getBooleanValue_plain = await time('OpenFeature getBooleanValue (plain)', () => of.getBooleanValue('plain', false, ctx)); +out.direct_isEnabled_targeted = await time('direct isEnabled (rule + 50% rollout)', (i) => direct.isEnabled('targeted', `user-${i & 1023}`, attrs)); +out.direct_getDetails_targeted = await time('direct getDetails (rule + 50% rollout)', (i) => direct.getDetails('targeted', `user-${i & 1023}`, attrs)); +out.of_getBooleanValue_targeted = await time('OpenFeature getBooleanValue (rule + rollout)', (i) => of.getBooleanValue('targeted', false, { ...ctx, targetingKey: `user-${i & 1023}` })); +console.log(JSON.stringify({ node: process.version, iterations: N, ns_per_op: out })); +await OpenFeature.close(); +await server.stop(); diff --git a/sdks/openfeature-provider/test/provider.test.mjs b/sdks/openfeature-provider/test/provider.test.mjs new file mode 100644 index 00000000..6f3f4f50 --- /dev/null +++ b/sdks/openfeature-provider/test/provider.test.mjs @@ -0,0 +1,292 @@ +// CheckgateProvider against the real OpenFeature server SDK, the real +// @checkgate/node client with its native engine, and a real SSE stream from +// the conformance FaultServer (which speaks the server's SDK protocol). +// Needs the native addon (`cd ../nodejs && npm run build`); skipped otherwise. + +import { test, after } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { createRequire } from 'node:module'; +import { FaultServer } from '../../conformance/fault-server.mjs'; + +const require = createRequire(import.meta.url); +const { OpenFeature, ProviderEvents, ProviderStatus, ErrorCode } = require('@openfeature/server-sdk'); +const { CheckgateProvider, toAttributes } = require('../src/index.js'); + +let native = true; +try { + require('@checkgate/node'); +} catch { + native = false; +} +const opts = { skip: native ? false : 'native addon not built' }; + +const vectors = JSON.parse(fs.readFileSync(new URL('../../conformance/vectors/evaluation.json', import.meta.url), 'utf8')); + +// The client logs connection changes; keep the test output readable. +for (const level of ['log', 'warn']) console[level] = () => {}; + +const FAST = { + reportImpressions: false, reconnectDelayMs: 20, maxReconnectDelayMs: 100, + pollFallbackThreshold: Infinity, connectTimeoutMs: 500, +}; + +let domainSeq = 0; +async function setUp({ flags = [], providerOptions = {}, serverOptions = {}, start = true } = {}) { + const server = new FaultServer(serverOptions); + const url = await server.start(); + for (const f of flags) server.upsert(f); + const provider = new CheckgateProvider({ serverUrl: url, sdkKey: 'sk_conformance', ...FAST, ...providerOptions }); + const domain = `test-${++domainSeq}`; + if (start) await OpenFeature.setProviderAndWait(domain, provider); + return { server, provider, domain, client: OpenFeature.getClient(domain) }; +} + +async function tearDown({ server }) { + await OpenFeature.close(); + await server.stop(); +} + +function until(predicate, ms = 5000) { + const started = Date.now(); + return new Promise((resolve, reject) => { + const tick = () => { + if (predicate()) return resolve(); + if (Date.now() - started > ms) return reject(new Error('condition not reached')); + setTimeout(tick, 10); + }; + tick(); + }); +} + +after(() => OpenFeature.close()); + +/** The OpenFeature resolution type for a vector flag. */ +function kind(flag) { + return { boolean: 'Boolean', string: 'String', integer: 'Number', json: 'Object' }[flag.flag_type || 'boolean']; +} +const DEFAULTS = { Boolean: false, String: 'dflt', Number: -1, Object: { dflt: true } }; +const OF_REASON = { + DISABLED: 'DISABLED', PREREQUISITE_FAILED: 'PREREQUISITE_FAILED', TARGETING_MATCH: 'TARGETING_MATCH', + ROLLOUT_EXCLUDED: 'SPLIT', SPLIT: 'SPLIT', DEFAULT: 'DEFAULT', STATIC: 'STATIC', +}; + +test('every shared vector resolves through OpenFeature as the engine says', opts, async () => { + // The flags arrive over the stream, as in production. + const env = await setUp({ flags: vectors.flags }); + try { + const byKey = new Map(vectors.flags.map((f) => [f.key, f])); + let checked = 0; + for (const c of vectors.cases) { + const flag = byKey.get(c.flag); + const type = flag ? kind(flag) : 'Boolean'; + const dflt = DEFAULTS[type]; + const ctx = { targetingKey: c.user, ...c.attributes }; + const d = await env.client[`get${type}Details`](c.flag, dflt, ctx); + if (c.user === '') { + // The provider requires a targeting key by default. + assert.equal(d.errorCode, ErrorCode.TARGETING_KEY_MISSING, c.name); + assert.deepEqual(d.value, dflt, c.name); + continue; + } + if (c.expect === null) { + assert.equal(d.errorCode, ErrorCode.FLAG_NOT_FOUND, c.name); + assert.deepEqual(d.value, dflt, c.name); + continue; + } + assert.equal(d.errorCode, undefined, `${c.name}: ${d.errorMessage}`); + assert.equal(d.reason, OF_REASON[c.expect.reason], c.name); + assert.equal(d.flagMetadata.checkgateReason, c.expect.reason, c.name); + assert.equal(d.flagMetadata.ruleIndex, c.expect.rule_index, c.name); + assert.equal(d.flagMetadata.variantIndex, c.expect.variant_index, c.name); + assert.equal(d.flagMetadata.rolloutBucket, c.expect.rollout_bucket, c.name); + const typed = { Boolean: 'boolean', String: 'string', Number: 'number', Object: 'object' }[type]; + const engineValue = c.expect.value; + const usable = engineValue !== null && typeof engineValue === typed; + if (usable) { + assert.deepEqual(d.value, engineValue, c.name); + } else { + // Off (or no value configured) without a value of this type: + // the caller's default, without an error. + assert.ok(!c.expect.enabled || engineValue === null, `${c.name}: unexpected type mismatch`); + assert.deepEqual(d.value, dflt, c.name); + } + // Parity with direct SDK use of the very same client. + const direct = env.provider.client.getDetails(c.flag, c.user, c.attributes); + assert.equal(direct.reason, c.expect.reason, c.name); + checked++; + } + assert.ok(checked > 70, `checked ${checked}`); + } finally { + await tearDown(env); + } +}); + +test('evaluations make no network request', opts, async () => { + const env = await setUp({ flags: vectors.flags }); + try { + const before = { ...env.server.counters }; + for (let i = 0; i < 2000; i++) { + await env.client.getBooleanValue('rollout-30', false, { targetingKey: `user-${i}` }); + await env.client.getStringValue('multi-rule', 'x', { targetingKey: 'u', country: 'PH' }); + } + assert.equal(env.server.counters.streamRequests, before.streamRequests); + assert.equal(env.server.counters.snapshotRequests, before.snapshotRequests); + } finally { + await tearDown(env); + } +}); + +test('a type mismatch returns the default with TYPE_MISMATCH', opts, async () => { + const env = await setUp({ flags: vectors.flags }); + try { + const d = await env.client.getBooleanDetails('multi-rule', true, { targetingKey: 'u', country: 'PH' }); + assert.equal(d.errorCode, ErrorCode.TYPE_MISMATCH); + assert.equal(d.value, true); + const n = await env.client.getNumberDetails('json-flag', 7, { targetingKey: 'u' }); + assert.equal(n.errorCode, ErrorCode.TYPE_MISMATCH); + assert.equal(n.value, 7); + } finally { + await tearDown(env); + } +}); + +test('context: numbers, booleans and dates become strings; objects are left out', () => { + assert.deepEqual( + toAttributes({ targetingKey: 'u', age: 30, beta: true, plan: 'pro', when: new Date(0), nested: { a: 1 }, list: [1], none: null, nan: NaN }), + { age: '30', beta: 'true', plan: 'pro', when: '1970-01-01T00:00:00.000Z' }, + ); +}); + +test('a numeric context attribute drives a numeric rule', opts, async () => { + const env = await setUp({ flags: vectors.flags }); + try { + assert.equal(await env.client.getBooleanValue('adults', false, { targetingKey: 'u', age: 30 }), true); + assert.equal(await env.client.getBooleanValue('adults', true, { targetingKey: 'u', age: 17 }), false); + // An object where a rule expects a string is dropped, not thrown on. + const d = await env.client.getBooleanDetails('rules-plan', true, { targetingKey: 'u', plan: { tier: 'pro' } }); + assert.equal(d.errorCode, undefined); + assert.equal(d.value, false); + } finally { + await tearDown(env); + } +}); + +test('a missing targetingKey is an error unless allowed', opts, async () => { + const env = await setUp({ flags: vectors.flags }); + try { + const d = await env.client.getBooleanDetails('static-on', false, {}); + assert.equal(d.errorCode, ErrorCode.TARGETING_KEY_MISSING); + assert.equal(d.value, false); + } finally { + await tearDown(env); + } + const lax = await setUp({ flags: vectors.flags, providerOptions: { requireTargetingKey: false } }); + try { + assert.equal(await lax.client.getBooleanValue('static-on', false, {}), true); + } finally { + await tearDown(lax); + } +}); + +test('an uninitialized provider answers PROVIDER_NOT_READY', opts, async () => { + const provider = new CheckgateProvider({ serverUrl: 'http://127.0.0.1:9', ...FAST }); + await assert.rejects(provider.resolveBooleanEvaluation('f', false, { targetingKey: 'u' }), (e) => e.code === ErrorCode.PROVIDER_NOT_READY); + await provider.onClose(); +}); + +test('lifecycle: READY, STALE on a dropped stream, READY again, then offline evaluation', opts, async () => { + const env = await setUp({ flags: vectors.flags }); + try { + assert.equal(env.client.providerStatus, ProviderStatus.READY); + const events = []; + for (const e of [ProviderEvents.Ready, ProviderEvents.Stale, ProviderEvents.Error]) { + env.client.addHandler(e, () => events.push(e)); + } + // OpenFeature runs a Ready handler at once when the provider is already ready. + assert.deepEqual(events, [ProviderEvents.Ready]); + events.length = 0; + env.server.mode = 'refuse'; + env.server.severAll(); + await until(() => env.client.providerStatus === ProviderStatus.STALE); + // Held flags keep answering while disconnected. + assert.equal(await env.client.getBooleanValue('static-on', false, { targetingKey: 'u' }), true); + env.server.mode = 'pass'; + await until(() => env.client.providerStatus === ProviderStatus.READY); + assert.deepEqual(events, [ProviderEvents.Stale, ProviderEvents.Ready]); + } finally { + await tearDown(env); + } +}); + +test('a flag change emits one ConfigurationChanged with the flag key', opts, async () => { + const env = await setUp({ flags: vectors.flags }); + try { + const changes = []; + env.client.addHandler(ProviderEvents.ConfigurationChanged, (d) => changes.push(d.flagsChanged)); + env.server.upsert({ key: 'static-on', is_enabled: false, rollout_percentage: null, rules: [] }); + await until(() => changes.length > 0); + assert.deepEqual(changes, [['static-on']]); + assert.equal(await env.client.getBooleanValue('static-on', true, { targetingKey: 'u' }), false); + } finally { + await tearDown(env); + } +}); + +test('a rejected SDK key makes the provider FATAL', opts, async () => { + const env = await setUp({ flags: vectors.flags, start: false }); + try { + env.server.setAcceptedKey(null); + await assert.rejects(OpenFeature.setProviderAndWait(env.domain, env.provider)); + assert.equal(env.client.providerStatus, ProviderStatus.FATAL); + const d = await env.client.getBooleanDetails('static-on', false, { targetingKey: 'u' }); + assert.equal(d.errorCode, ErrorCode.PROVIDER_FATAL); + } finally { + await tearDown(env); + } +}); + +test('initTimeoutMs: ERROR while unreachable, READY once the server answers', opts, async () => { + const env = await setUp({ flags: vectors.flags, start: false, providerOptions: { initTimeoutMs: 300 } }); + try { + env.server.mode = 'refuse'; + await assert.rejects(OpenFeature.setProviderAndWait(env.domain, env.provider)); + assert.equal(env.client.providerStatus, ProviderStatus.ERROR); + env.server.mode = 'pass'; + await until(() => env.client.providerStatus === ProviderStatus.READY); + assert.equal(await env.client.getBooleanValue('static-on', false, { targetingKey: 'u' }), true); + } finally { + await tearDown(env); + } +}); + +test('close disconnects an owned client but never a shared one', opts, async () => { + const owned = await setUp({ flags: vectors.flags }); + await until(() => owned.server.streams.size === 1); + await OpenFeature.close(); + await until(() => owned.server.streams.size === 0); + await owned.server.stop(); + + const server = new FaultServer(); + const url = await server.start(); + server.upsert({ key: 'f', is_enabled: true, rollout_percentage: null }); + const { CheckgateClient } = require('@checkgate/node'); + const shared = new CheckgateClient({ serverUrl: url, sdkKey: 'sk_conformance', ...FAST }); + await shared.connect(); + await OpenFeature.setProviderAndWait('shared', new CheckgateProvider({ client: shared })); + assert.equal(await OpenFeature.getClient('shared').getBooleanValue('f', false, { targetingKey: 'u' }), true); + await OpenFeature.close(); + assert.equal(shared.isEnabled('f', 'u'), true, 'shared client still serving'); + assert.equal(shared.getStatus().state, 'streaming'); + shared.disconnect(); + await server.stop(); +}); + +test('track() forwards to the client as a goal event', opts, () => { + const calls = []; + const fake = { track: (...a) => calls.push(a), onChange: () => () => {}, onStatusChange: () => () => {}, isReady: () => true }; + const provider = new CheckgateProvider({ client: fake }); + provider.track('checkout', { targetingKey: 'u1' }, { value: 9.5, sku: 'x' }); + provider.track('ignored', {}, {}); + assert.deepEqual(calls, [['checkout', 'u1', { value: 9.5, context: { sku: 'x' } }]]); +}); diff --git a/sdks/openfeature-provider/tsconfig.json b/sdks/openfeature-provider/tsconfig.json new file mode 100644 index 00000000..0d67ddce --- /dev/null +++ b/sdks/openfeature-provider/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "strict": true, + "noEmit": true, + "module": "nodenext", + "moduleResolution": "nodenext", + "target": "es2022", + "skipLibCheck": false, + "types": [ + "node" + ] + }, + "files": [ + "src/index.d.ts", + "examples/typed.ts" + ] +} From c41898805bb49a18f8a69cd08cfdee41cb5a96eb Mon Sep 17 00:00:00 2001 From: Dennis Paler Date: Sat, 21 Nov 2026 21:53:50 +0800 Subject: [PATCH 05/38] test(node-integrations): real-addon suite per framework against the fake server Every adapter runs the same checks with the real @checkgate/node client and native addon, using sdks/conformance/fault-server.mjs as the Checkgate server: 400 concurrent requests with different users and attributes (no context leakage), startup with the server up / down (continue serves defaults or the offline cache and syncs later; fail rejects and stops retrying) / rejecting the key, a live flag change with no per-request network call (fake server counters and a global fetch counter), the server killed and restarted mid-run, and shutdown disconnecting exactly once with no stream left open. Plus adapter-specific tests (lazy context after auth middleware, Fastify encapsulation and clientOptions, NestJS RequireFlag 404/403, forTesting, overrideProvider, forRootAsync), core unit tests, a compile check of the .d.ts files (npm run typecheck), and the shared evaluation vectors when sdks/conformance/vectors/evaluation.json is present. --- sdks/node-integrations/package.json | 2 +- sdks/node-integrations/test/core.test.mjs | 183 ++++++++ sdks/node-integrations/test/express.test.mjs | 81 ++++ sdks/node-integrations/test/fastify.test.mjs | 100 ++++ sdks/node-integrations/test/helpers.mjs | 443 ++++++++++++++++++ sdks/node-integrations/test/nestjs.test.mjs | 187 ++++++++ .../test/types/tsconfig.json | 14 + sdks/node-integrations/test/types/usage.ts | 108 +++++ 8 files changed, 1117 insertions(+), 1 deletion(-) create mode 100644 sdks/node-integrations/test/core.test.mjs create mode 100644 sdks/node-integrations/test/express.test.mjs create mode 100644 sdks/node-integrations/test/fastify.test.mjs create mode 100644 sdks/node-integrations/test/helpers.mjs create mode 100644 sdks/node-integrations/test/nestjs.test.mjs create mode 100644 sdks/node-integrations/test/types/tsconfig.json create mode 100644 sdks/node-integrations/test/types/usage.ts diff --git a/sdks/node-integrations/package.json b/sdks/node-integrations/package.json index 3b38d1e9..73683f83 100644 --- a/sdks/node-integrations/package.json +++ b/sdks/node-integrations/package.json @@ -48,7 +48,7 @@ "node": ">=22.12.0" }, "scripts": { - "test": "node --test --test-concurrency=1 test/", + "test": "node --test --test-concurrency=1 \"test/*.test.mjs\"", "typecheck": "tsc -p test/types/tsconfig.json" }, "dependencies": { diff --git a/sdks/node-integrations/test/core.test.mjs b/sdks/node-integrations/test/core.test.mjs new file mode 100644 index 00000000..e198b1b6 --- /dev/null +++ b/sdks/node-integrations/test/core.test.mjs @@ -0,0 +1,183 @@ +// The framework-independent core: attribute coercion against the real native +// core, the request evaluator's no-throw contract, the startup/shutdown +// helpers, the test client, and the shared evaluation vectors when present. + +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import fs from 'node:fs' +import { createRequire } from 'node:module' +import { test } from 'node:test' +import { fileURLToPath } from 'node:url' +import { deadFake, flag, makeClient, quietLogger, startFake } from './helpers.mjs' + +const require = createRequire(import.meta.url) +const { + CheckgateStartupTimeoutError, createRequestFlags, createTestClient, normalizeAttributes, normalizeContext, + startCheckgate, stopCheckgate, +} = require('@checkgate/node-integrations') +const { CheckgateCore } = require('@checkgate/node/native-binding.js') + +test('normalizeAttributes keeps strings, stringifies numbers / bigints / booleans, drops the rest', () => { + const input = { + plan: 'pro', seats: 30, ratio: 0.5, negative: -1, big: 10n, beta: true, off: false, + nan: NaN, inf: Infinity, nil: null, undef: undefined, obj: { a: 1 }, arr: ['x'], date: new Date(0), + sym: Symbol('s'), fn: () => 1, + } + assert.deepEqual(normalizeAttributes(input), { + plan: 'pro', seats: '30', ratio: '0.5', negative: '-1', big: '10', beta: 'true', off: 'false', + }) + assert.deepEqual(normalizeAttributes(null), {}) + assert.deepEqual(normalizeAttributes('plan=pro'), {}) + // `__proto__` as an own key (JSON.parse makes those) cannot pollute the result. + const hostile = JSON.parse('{"__proto__": {"polluted": "yes"}, "plan": "pro"}') + const out = normalizeAttributes(hostile) + assert.deepEqual(out, { plan: 'pro' }) + assert.equal(Object.getPrototypeOf(out), Object.prototype) + // A throwing getter drops that attribute, not the request. + const trap = { plan: 'pro', get boom() { throw new Error('getter') } } + assert.deepEqual(normalizeAttributes(trap), { plan: 'pro' }) +}) + +test('normalizeContext: object, bare key, nothing', () => { + assert.deepEqual(normalizeContext({ key: 'u1', attributes: { n: 1 } }), { key: 'u1', attributes: { n: '1' } }) + assert.deepEqual(normalizeContext('u2'), { key: 'u2', attributes: {} }) + assert.deepEqual(normalizeContext(42), { key: '42', attributes: {} }) + assert.deepEqual(normalizeContext(null), { key: 'anonymous', attributes: {} }) + assert.deepEqual(normalizeContext({ key: '' }, 'guest'), { key: 'guest', attributes: {} }) + assert.equal(Object.isFrozen(normalizeContext({ key: 'u' }).attributes), true) +}) + +test('the native core throws on a non-string referenced attribute; the evaluator coerces instead', () => { + const core = new CheckgateCore() + core.upsertFlagV2(JSON.stringify(flag('big-team'))) + // What an app calling the SDK directly with a number hits. + assert.throws(() => core.isEnabled('big-team', 'u', { seats: 30 }), /String/) + const client = { isReady: () => true, isEnabled: (f, k, a) => core.isEnabled(f, k, a), getVariant: (f, k, a) => JSON.parse(core.getVariant(f, k, a)) } + const errors = [] + const flags = createRequestFlags(client, () => ({ key: 'u', attributes: { seats: 30 } }), { onError: (e) => errors.push(e) }) + assert.equal(flags.isEnabled('big-team'), true) + const few = createRequestFlags(client, () => ({ key: 'u', attributes: { seats: 3 } })) + assert.equal(few.isEnabled('big-team'), false) + // An object-valued attribute is dropped: the rule sees no attribute. + const odd = createRequestFlags(client, () => ({ key: 'u', attributes: { seats: { n: 30 } } }), { onError: (e) => errors.push(e) }) + assert.equal(odd.isEnabled('big-team'), false) + assert.deepEqual(errors, []) +}) + +test('the evaluator never throws: bad flag keys and throwing clients return defaults', () => { + const errors = [] + const throwing = { + isReady: () => true, + isEnabled() { throw new Error('core exploded') }, + getVariant() { throw new Error('core exploded') }, + track() { throw new Error('track exploded') }, + } + const flags = createRequestFlags(throwing, () => 'u', { onError: (err, info) => errors.push([err.message, info]) }) + assert.equal(flags.isEnabled('x'), false) + assert.equal(flags.getVariant('x'), null) + assert.equal(flags.getValue('x', 'dflt'), 'dflt') + flags.track('goal') + assert.equal(errors.length, 4) + // An onError that throws is swallowed too. + const loud = createRequestFlags(throwing, () => 'u', { onError: () => { throw new Error('handler') } }) + assert.equal(loud.isEnabled('x'), false) +}) + +test('the context is resolved once per request, on first use', () => { + let calls = 0 + const flags = createRequestFlags(createTestClient({ a: true }), () => { calls++; return 'u' }) + assert.equal(calls, 0) + flags.isEnabled('a') + flags.getValue('a') + void flags.context + assert.equal(calls, 1) +}) + +test('startCheckgate validates its options', async () => { + const client = createTestClient() + await assert.rejects(startCheckgate(client, { onTimeout: 'maybe' }), /onTimeout must be/) + await assert.rejects(startCheckgate(client, { readyTimeoutMs: -1 }), /readyTimeoutMs/) + await assert.rejects(startCheckgate({}), /needs a CheckgateClient/) + assert.deepEqual(await startCheckgate(client), { ready: true, timedOut: false }) +}) + +test('startCheckgate with the real client: continue and fail timeouts', async () => { + const dead = await deadFake() + const cont = makeClient(dead.url) + assert.deepEqual(await startCheckgate(cont, { readyTimeoutMs: 100, logger: quietLogger }), { ready: false, timedOut: true }) + assert.notEqual(cont.getStatus().state, 'closed', "'continue' keeps the client syncing") + stopCheckgate(cont) + + const fail = makeClient(dead.url) + await assert.rejects(startCheckgate(fail, { readyTimeoutMs: 100, onTimeout: 'fail' }), (err) => { + assert.ok(err instanceof CheckgateStartupTimeoutError) + assert.equal(err.timeoutMs, 100) + return true + }) + assert.equal(fail.getStatus().state, 'closed') +}) + +test('stopCheckgate disconnects once until started again', async () => { + const client = createTestClient() + await startCheckgate(client) + assert.equal(stopCheckgate(client), true) + assert.equal(stopCheckgate(client), false) + assert.equal(client.disconnectCalls, 1) + await startCheckgate(client) + assert.equal(stopCheckgate(client), true) + assert.equal(client.disconnectCalls, 2) +}) + +test('createTestClient semantics', () => { + const client = createTestClient({ on: true, off: false, color: 'gold', nothing: null, perUser: ({ key }) => key === 'a' }) + assert.equal(client.isEnabled('on', 'u'), true) + assert.equal(client.isEnabled('off', 'u'), false) + assert.equal(client.isEnabled('color', 'u'), true) + assert.equal(client.isEnabled('nothing', 'u'), false) + assert.equal(client.isEnabled('missing', 'u'), false) + assert.deepEqual(client.getVariant('color', 'u'), { enabled: true, value: 'gold' }) + assert.equal(client.getVariant('missing', 'u'), null) + assert.equal(client.getValue('missing', 'u', {}, 'd'), 'd') + assert.equal(client.isEnabled('perUser', 'a'), true) + assert.equal(client.isEnabled('perUser', 'b'), false) + client.setFlag('on', undefined) + assert.equal(client.getVariant('on', 'u'), null) +}) + +test('a test client keeps the native addon unloaded (forTesting needs no build)', () => { + const here = fileURLToPath(new URL('.', import.meta.url)) + const script = ` + require('reflect-metadata') + const { CheckgateModule } = require('@checkgate/node-integrations/nestjs') + require('@checkgate/node-integrations/express') + require('@checkgate/node-integrations/fastify') + CheckgateModule.forTesting({ a: true }) + const loaded = Object.keys(require.cache).filter((p) => /native-binding|\\.node$/.test(p)) + process.stdout.write(JSON.stringify(loaded))` + const out = execFileSync(process.execPath, ['-e', script], { cwd: here }) + assert.deepEqual(JSON.parse(out.toString()), []) +}) + +// The cross-SDK evaluation vectors (sdks/conformance/vectors/evaluation.json), +// evaluated through the request evaluator over a real client and stream. +const vectorsPath = fileURLToPath(new URL('../../conformance/vectors/evaluation.json', import.meta.url)) +const vectors = fs.existsSync(vectorsPath) ? JSON.parse(fs.readFileSync(vectorsPath, 'utf8')) : null +test('shared evaluation vectors', { skip: vectors ? false : 'sdks/conformance/vectors/evaluation.json is not on this branch' }, async () => { + const fake = await startFake({ flags: vectors.flags }) + const client = makeClient(fake.url) + await client.connect() + try { + for (const c of vectors.cases) { + const flags = createRequestFlags(client, () => ({ key: c.user, attributes: c.attributes })) + if (c.expect === null) { + assert.equal(flags.getVariant(c.flag), null, c.name) + continue + } + assert.equal(flags.isEnabled(c.flag), c.expect.enabled, `${c.name}: enabled`) + assert.deepEqual(flags.getValue(c.flag), c.expect.value, `${c.name}: value`) + } + } finally { + client.disconnect() + await fake.stop() + } +}) diff --git a/sdks/node-integrations/test/express.test.mjs b/sdks/node-integrations/test/express.test.mjs new file mode 100644 index 00000000..a13d1fc5 --- /dev/null +++ b/sdks/node-integrations/test/express.test.mjs @@ -0,0 +1,81 @@ +// Express adapter against the real @checkgate/node client and the fake +// Checkgate server (see helpers.mjs). + +import assert from 'node:assert/strict' +import { createRequire } from 'node:module' +import { test } from 'node:test' +import { checkResponse, contextFromHeaders, frameworkSuite, get, makeClient, quietLogger, startFake, userFor } from './helpers.mjs' + +const require = createRequire(import.meta.url) +const express = require('express') +const { checkgateMiddleware, listenWithCheckgate } = require('@checkgate/node-integrations/express') + +function buildApp(client, context = (req) => contextFromHeaders(req.headers)) { + const app = express() + app.use(checkgateMiddleware({ client, context })) + app.get('/check', async (req, res) => { + res.json(await checkResponse(req.checkgate)) + }) + return app +} + +frameworkSuite('express', { + async start({ client, readyTimeoutMs, onTimeout }) { + const { server, close } = await listenWithCheckgate(buildApp(client), { + client, host: '127.0.0.1', readyTimeoutMs, onTimeout, logger: quietLogger, + }) + return { url: `http://127.0.0.1:${server.address().port}`, close } + }, +}) + +test('[express] context resolves lazily: auth middleware mounted after Checkgate still counts', async () => { + const fake = await startFake() + const client = makeClient(fake.url) + const app = express() + // Default extractor: req.user.id. + app.use(checkgateMiddleware({ client })) + app.use((req, _res, next) => { + if (req.headers['x-user']) req.user = { id: req.headers['x-user'] } + next() + }) + app.get('/whoami', (req, res) => res.json({ key: req.checkgate.context.key })) + const { server, close } = await listenWithCheckgate(app, { client, host: '127.0.0.1', logger: quietLogger }) + try { + const url = `http://127.0.0.1:${server.address().port}` + assert.equal((await get(url, '/whoami', { 'x-user': 'u-42' })).body.key, 'u-42') + assert.equal((await get(url, '/whoami')).body.key, 'anonymous') + } finally { + await close() + await fake.stop() + } +}) + +test('[express] a throwing context extractor serves the anonymous context and reports the error', async () => { + const fake = await startFake() + const client = makeClient(fake.url) + const errors = [] + const app = express() + app.use(checkgateMiddleware({ + client, + context: () => { throw new Error('extractor bug') }, + onError: (err, info) => errors.push({ message: err.message, info }), + })) + app.get('/check', async (req, res) => res.json(await checkResponse(req.checkgate))) + const { server, close } = await listenWithCheckgate(app, { client, host: '127.0.0.1', logger: quietLogger }) + try { + const res = await get(`http://127.0.0.1:${server.address().port}`, '/check', userFor(0).headers) + assert.equal(res.status, 200) + assert.equal(res.body.key, 'anonymous') + assert.equal(res.body.pro, false) + // Resolved once per request, so reported once. + assert.deepEqual(errors, [{ message: 'extractor bug', info: { phase: 'context' } }]) + } finally { + await close() + await fake.stop() + } +}) + +test('[express] checkgateMiddleware() rejects a missing client at setup', () => { + assert.throws(() => checkgateMiddleware({}), /needs \{ client \}/) + assert.throws(() => checkgateMiddleware({ client: makeClient('http://127.0.0.1:9'), context: 'nope' }), /context must be a function/) +}) diff --git a/sdks/node-integrations/test/fastify.test.mjs b/sdks/node-integrations/test/fastify.test.mjs new file mode 100644 index 00000000..5861c61c --- /dev/null +++ b/sdks/node-integrations/test/fastify.test.mjs @@ -0,0 +1,100 @@ +// Fastify plugin against the real @checkgate/node client and the fake +// Checkgate server (see helpers.mjs). + +import assert from 'node:assert/strict' +import { createRequire } from 'node:module' +import { test } from 'node:test' +import { SDK_KEY, checkResponse, contextFromHeaders, frameworkSuite, get, makeClient, startFake, waitFor } from './helpers.mjs' + +const require = createRequire(import.meta.url) +const Fastify = require('fastify') +const checkgatePlugin = require('@checkgate/node-integrations/fastify') + +async function buildApp(pluginOptions) { + const app = Fastify({ logger: false }) + await app.register(checkgatePlugin, { context: (request) => contextFromHeaders(request.headers), ...pluginOptions }) + app.get('/check', async (request) => checkResponse(request.checkgate)) + return app +} + +frameworkSuite('fastify', { + async start({ client, readyTimeoutMs, onTimeout }) { + const app = Fastify({ logger: false }) + app.register(checkgatePlugin, { + client, readyTimeoutMs, onTimeout, context: (request) => contextFromHeaders(request.headers), + }) + app.get('/check', async (request) => checkResponse(request.checkgate)) + try { + await app.listen({ port: 0, host: '127.0.0.1' }) + } catch (err) { + await app.close().catch(() => {}) + throw err + } + return { url: `http://127.0.0.1:${app.server.address().port}`, close: () => app.close() } + }, +}) + +test('[fastify] decorates the instance with the shared client and each request with its own flags', async () => { + const fake = await startFake() + const client = makeClient(fake.url) + const app = Fastify({ logger: false }) + await app.register(checkgatePlugin, { client, context: (request) => contextFromHeaders(request.headers) }) + const seen = [] + app.get('/same', async (request) => { + seen.push(request.checkgate) + return { shared: app.checkgate === client } + }) + await app.listen({ port: 0, host: '127.0.0.1' }) + try { + const url = `http://127.0.0.1:${app.server.address().port}` + assert.equal((await get(url, '/same')).body.shared, true) + await get(url, '/same') + assert.equal(seen.length, 2) + assert.notEqual(seen[0], seen[1], 'a fresh evaluator per request') + } finally { + await app.close() + await fake.stop() + } +}) + +test('[fastify] the plugin is not encapsulated: routes in child plugins see request.checkgate', async () => { + const fake = await startFake() + const app = await buildApp({ client: makeClient(fake.url) }) + app.register(async (child) => { + child.get('/child', async (request) => ({ key: request.checkgate.context.key })) + }, { prefix: '/nested' }) + await app.listen({ port: 0, host: '127.0.0.1' }) + try { + const res = await get(`http://127.0.0.1:${app.server.address().port}`, '/nested/child', { 'x-user': 'kid' }) + assert.equal(res.body.key, 'kid') + } finally { + await app.close() + await fake.stop() + } +}) + +test('[fastify] clientOptions: the plugin builds, connects and closes its own client', async () => { + const fake = await startFake() + const app = await buildApp({ + clientOptions: { serverUrl: fake.url, sdkKey: SDK_KEY, reportImpressions: false }, + readyTimeoutMs: 3000, + onTimeout: 'fail', + }) + await app.listen({ port: 0, host: '127.0.0.1' }) + assert.equal(app.checkgate.isReady(), true) + const res = await get(`http://127.0.0.1:${app.server.address().port}`, '/check', { 'x-user': 'p', 'x-plan': 'pro' }) + assert.equal(res.body.pro, true) + await app.close() + assert.equal(app.checkgate.getStatus().state, 'closed') + await waitFor(() => fake.streams.size === 0, { label: 'the stream to close' }) + await fake.stop() +}) + +test('[fastify] option errors surface from register()', async () => { + await assert.rejects(buildApp({}), /needs client or clientOptions/) + await assert.rejects(buildApp({ client: makeClient('http://127.0.0.1:9'), clientOptions: {} }), /either client or clientOptions/) + // A wait longer than Fastify's own plugin timeout would end in Fastify's error, not ours. + const app = Fastify({ logger: false, pluginTimeout: 1000 }) + app.register(checkgatePlugin, { client: makeClient('http://127.0.0.1:9'), readyTimeoutMs: 1000 }) + await assert.rejects(app.ready(), /must be below Fastify's pluginTimeout/) +}) diff --git a/sdks/node-integrations/test/helpers.mjs b/sdks/node-integrations/test/helpers.mjs new file mode 100644 index 00000000..fb2f01d4 --- /dev/null +++ b/sdks/node-integrations/test/helpers.mjs @@ -0,0 +1,443 @@ +// Shared fixtures for the integration tests: the conformance fake server +// (sdks/conformance/fault-server.mjs) as the Checkgate server, the REAL +// @checkgate/node client with its native addon, and one suite of behaviour +// checks that every framework adapter must pass. + +import assert from 'node:assert/strict' +import http from 'node:http' +import { createRequire } from 'node:module' +import { test } from 'node:test' +import { setTimeout as sleep } from 'node:timers/promises' +import { FaultServer } from '../../conformance/fault-server.mjs' + +const require = createRequire(import.meta.url) + +let sdk +try { + sdk = require('@checkgate/node') +} catch (err) { + throw new Error('These tests need the real @checkgate/node with its native addon: ' + + 'run `npm ci && npm run build:debug` in sdks/nodejs, then `npm ci` here.\n' + err.message) +} +export const { CheckgateClient } = sdk + +export const SDK_KEY = 'sk_integrations_test' + +// The SDK logs every (re)connect; keep the output readable but keep what an +// assertion may want to look at. +export const logs = [] +for (const level of ['log', 'warn', 'error']) { + console[level] = (...args) => logs.push({ level, text: args.map(String).join(' ') }) +} +export const quietLogger = { warn: (...args) => logs.push({ level: 'warn', text: args.join(' ') }) } + +// Every network call the SDK makes goes through the global fetch (the stream +// via eventsource's fetch hook, polls, analytics). Test traffic to the app +// uses node:http, so this counts only Checkgate traffic. +export const sdkFetches = [] +const realFetch = globalThis.fetch +globalThis.fetch = (url, init) => { + sdkFetches.push(String(url)) + return realFetch(url, init) +} + +// -- flags ------------------------------------------------------------------ + +const base = { rollout_percentage: null, description: null, rules: [] } +export const FLAGS = [ + // On only for plan=pro (rules only: rollout 0 serves nobody else). + { ...base, key: 'pro-feature', is_enabled: true, rollout_percentage: 0, + rules: [{ attribute: 'plan', operator: 'equals', values: ['pro'] }] }, + // A numeric rule: `seats` arrives as a number and must be coerced, not thrown on. + { ...base, key: 'big-team', is_enabled: true, rollout_percentage: 0, + rules: [{ attribute: 'seats', operator: 'greater_than', values: ['10'] }] }, + // A boolean attribute, coerced to "true" / "false". + { ...base, key: 'beta-only', is_enabled: true, rollout_percentage: 0, + rules: [{ attribute: 'beta', operator: 'equals', values: ['true'] }] }, + // Per-user hashing: half of all users. + { ...base, key: 'half-rollout', is_enabled: true, rollout_percentage: 50 }, + // A string flag with a per-rule variant. + { ...base, key: 'banner-color', is_enabled: true, flag_type: 'string', default_value: 'blue', + disabled_value: 'grey', rules: [{ attribute: 'plan', operator: 'equals', values: ['pro'], variant: 'gold' }] }, +] +export const flag = (key) => FLAGS.find((f) => f.key === key) + +// -- the fake Checkgate server ----------------------------------------------- + +export async function startFake({ flags = FLAGS, ...opts } = {}) { + const server = new FaultServer({ sdkKey: SDK_KEY, heartbeatMs: 100, ...opts }) + for (const f of flags) server.upsert(f) + await server.start() + return server +} + +/** A URL where nothing listens (and the FaultServer that can be revived there). */ +export async function deadFake(opts) { + const server = await startFake(opts) + const port = await killFake(server) + return { server, port, url: server.url } +} + +/** Takes the fake server down (every stream cut, port closed); returns its port. */ +export async function killFake(server) { + const port = Number(new URL(server.url).port) + await server.stop() + return port +} + +/** Brings a killed fake server back on the same port, with the state it had. */ +export async function reviveFake(server, port) { + await new Promise((resolve, reject) => { + server.server.once('error', reject) + server.server.listen(port, '127.0.0.1', () => { + server.server.off('error', reject) + resolve() + }) + }) +} + +export function makeClient(serverUrl, overrides = {}) { + return new CheckgateClient({ + serverUrl, + sdkKey: SDK_KEY, + reportImpressions: false, + // Production rules, test-speed constants (as sdks/conformance). + reconnectDelayMs: 20, + maxReconnectDelayMs: 200, + connectTimeoutMs: 500, + pollFallbackThreshold: 3, + pollIntervalMs: 100, + ...overrides, + }) +} + +/** Wraps client.disconnect() to count calls. */ +export function countDisconnects(client) { + const counter = { calls: 0 } + const original = client.disconnect.bind(client) + client.disconnect = () => { + counter.calls++ + original() + } + return counter +} + +/** A storage adapter backed by a Map (the offline cache). */ +export function memoryStorage() { + const map = new Map() + return { map, getItem: (k) => (map.has(k) ? map.get(k) : null), setItem: (k, v) => void map.set(k, v) } +} + +export async function waitFor(predicate, { timeoutMs = 5000, label = 'condition' } = {}) { + const deadline = Date.now() + timeoutMs + for (;;) { + if (await predicate()) return + if (Date.now() > deadline) throw new Error(`timed out after ${timeoutMs} ms waiting for ${label}`) + await sleep(20) + } +} + +// -- the app's view: one route, same answers in every framework ------------- + +/** The context extractor every test app uses: user and attributes from headers. */ +export function contextFromHeaders(headers) { + const key = headers['x-user'] + if (!key) return null + return { + key, + attributes: { + plan: headers['x-plan'], + seats: headers['x-seats'] === undefined ? undefined : Number(headers['x-seats']), + beta: headers['x-beta'] === undefined ? undefined : headers['x-beta'] === '1', + // Not coercible: dropped, never sent to the core. + meta: { nested: true }, + }, + } +} + +/** + * What every test app's `GET /check` answers, from the request's flags. + * Waits a random few ms before evaluating so concurrent requests interleave + * between "flags object created" and "flags evaluated". + */ +export async function checkResponse(flags) { + await sleep(Math.random() * 5) + const context = flags.context + await sleep(Math.random() * 3) + return { + key: context.key, + attributes: context.attributes, + pro: flags.isEnabled('pro-feature'), + bigTeam: flags.isEnabled('big-team'), + beta: flags.isEnabled('beta-only'), + half: flags.isEnabled('half-rollout'), + color: flags.getValue('banner-color', 'none'), + variant: flags.getVariant('banner-color'), + missing: flags.getValue('no-such-flag', 'fallback'), + } +} + +/** The user and headers of test request `i`. */ +export function userFor(i) { + const plan = i % 3 === 0 ? 'pro' : 'free' + const seats = (i % 4) * 7 // 0, 7, 14, 21 + const beta = i % 5 === 0 + return { + key: `user-${i}`, + plan, + seats, + beta, + headers: { 'x-user': `user-${i}`, 'x-plan': plan, 'x-seats': String(seats), 'x-beta': beta ? '1' : '0' }, + } +} + +const agent = new http.Agent({ keepAlive: true, maxSockets: 64 }) + +/** GET `path` on the app over real HTTP; resolves { status, body }. */ +export function get(baseUrl, path, headers = {}) { + return new Promise((resolve, reject) => { + const req = http.get(new URL(path, baseUrl), { agent, headers }, (res) => { + let data = '' + res.setEncoding('utf8') + res.on('data', (chunk) => (data += chunk)) + res.on('end', () => { + let body = data + try { + body = JSON.parse(data) + } catch { + // not JSON (an error page) + } + resolve({ status: res.statusCode, body }) + }) + }) + req.on('error', reject) + }) +} + +/** Asserts `/check` for user `u` matches what that user must get from `client`. */ +function assertUserResponse(client, u, body) { + assert.equal(body.key, u.key, 'context leaked from another request') + assert.deepEqual(body.attributes, { + plan: u.plan, + seats: String(u.seats), + beta: u.beta ? 'true' : 'false', + }) + assert.equal(body.pro, u.plan === 'pro', `${u.key} pro-feature`) + assert.equal(body.bigTeam, u.seats > 10, `${u.key} big-team`) + assert.equal(body.beta, u.beta, `${u.key} beta-only`) + // Rollout hashing of this user's key, evaluated directly on the client. + assert.equal(body.half, client.isEnabled('half-rollout', u.key, {}), `${u.key} half-rollout`) + assert.equal(body.color, u.plan === 'pro' ? 'gold' : 'blue', `${u.key} banner-color`) + assert.deepEqual(body.variant, { enabled: true, value: u.plan === 'pro' ? 'gold' : 'blue' }) + assert.equal(body.missing, 'fallback') +} + +// -- the suite ---------------------------------------------------------------- + +/** + * The behaviour every adapter must have. `adapter.start({ client, readyTimeoutMs, onTimeout })` + * starts an app whose `GET /check` answers checkResponse(request flags), and + * resolves `{ url, close() }` once it is listening (rejecting if startup fails). + */ +export function frameworkSuite(name, adapter) { + const opts = { concurrency: false } + + test(`[${name}] concurrent requests each evaluate for their own user`, opts, async () => { + const fake = await startFake() + const client = makeClient(fake.url) + const app = await adapter.start({ client, readyTimeoutMs: 3000, onTimeout: 'fail' }) + try { + assert.equal(client.isReady(), true) + const users = Array.from({ length: 400 }, (_, i) => userFor(i)) + const responses = await Promise.all(users.map((u) => get(app.url, '/check', u.headers))) + responses.forEach((res, i) => { + assert.equal(res.status, 200) + assertUserResponse(client, users[i], res.body) + }) + // Sanity: the population really is mixed. + assert.ok(responses.some((r) => r.body.half) && responses.some((r) => !r.body.half)) + // An anonymous request gets the default key and no attributes. + const anon = await get(app.url, '/check') + assert.equal(anon.body.key, 'anonymous') + assert.deepEqual(anon.body.attributes, {}) + assert.equal(fake.streams.size, 1, 'one stream for the whole app') + } finally { + await app.close() + await fake.stop() + } + }) + + test(`[${name}] startup: server up -> ready`, opts, async () => { + const fake = await startFake() + const client = makeClient(fake.url) + const started = Date.now() + const app = await adapter.start({ client, readyTimeoutMs: 3000, onTimeout: 'fail' }) + try { + assert.equal(client.isReady(), true) + assert.ok(Date.now() - started < 3000) + const res = await get(app.url, '/check', userFor(0).headers) + assert.equal(res.body.pro, true) + } finally { + await app.close() + await fake.stop() + } + }) + + test(`[${name}] startup: server down, onTimeout 'continue' starts on time, serves defaults, then syncs`, opts, async () => { + const dead = await deadFake() + const client = makeClient(dead.url) + const started = Date.now() + const app = await adapter.start({ client, readyTimeoutMs: 300, onTimeout: 'continue' }) + try { + const elapsed = Date.now() - started + assert.ok(elapsed >= 280 && elapsed < 3000, `started after ${elapsed} ms`) + assert.equal(client.isReady(), false) + const before = logs.length + const res = await get(app.url, '/check', userFor(0).headers) + assert.equal(res.status, 200) + assert.equal(res.body.pro, false) + assert.equal(res.body.color, 'none') + assert.equal(res.body.variant, null) + assert.equal(res.body.missing, 'fallback') + // No per-request "called before connect() resolved" warning. + assert.equal(logs.slice(before).filter((l) => /before connect\(\) resolved/.test(l.text)).length, 0) + // The client kept trying in the background: bring the server up. + await reviveFake(dead.server, dead.port) + await waitFor(async () => (await get(app.url, '/check', userFor(0).headers)).body.pro === true, + { label: 'flags after the server came up' }) + assert.equal(client.isReady(), true) + } finally { + await app.close() + await dead.server.stop() + } + }) + + test(`[${name}] startup: server down, onTimeout 'continue' serves the offline cache`, opts, async () => { + const fake = await startFake() + const storage = memoryStorage() + const first = makeClient(fake.url, { storage }) + await first.connect() + await waitFor(() => storage.map.size > 0, { label: 'cache persisted' }) + first.disconnect() + await killFake(fake) + + const client = makeClient(fake.url, { storage }) + const app = await adapter.start({ client, readyTimeoutMs: 300, onTimeout: 'continue' }) + try { + assert.equal(client.isReady(), false) + const responses = await Promise.all([0, 1, 2, 3].map((i) => get(app.url, '/check', userFor(i).headers))) + responses.forEach((res, i) => assertUserResponse(client, userFor(i), res.body)) + } finally { + await app.close() + } + }) + + test(`[${name}] startup: server down, onTimeout 'fail' rejects and stops retrying`, opts, async () => { + const dead = await deadFake() + const client = makeClient(dead.url) + const disconnects = countDisconnects(client) + const started = Date.now() + await assert.rejects(adapter.start({ client, readyTimeoutMs: 300, onTimeout: 'fail' }), + (err) => err.name === 'CheckgateStartupTimeoutError') + const elapsed = Date.now() - started + assert.ok(elapsed >= 280 && elapsed < 3000, `failed after ${elapsed} ms`) + assert.equal(disconnects.calls, 1) + // Once the server is back, a stopped client does not connect to it. + await reviveFake(dead.server, dead.port) + await sleep(400) + assert.equal(dead.server.counters.streamRequests, 0) + await dead.server.stop() + }) + + test(`[${name}] startup: a rejected SDK key fails startup even with onTimeout 'continue'`, opts, async () => { + const fake = await startFake() + fake.setAcceptedKey('sk_some_other_key') + const client = makeClient(fake.url) + await assert.rejects(adapter.start({ client, readyTimeoutMs: 3000, onTimeout: 'continue' }), + (err) => err.name === 'CheckgateAuthError' && err.status === 401) + assert.ok(fake.counters.unauthorized >= 1) + // Not retried: a rejected key does not become valid by asking again. + const requests = fake.counters.streamRequests + fake.counters.snapshotRequests + await sleep(400) + assert.equal(fake.counters.streamRequests + fake.counters.snapshotRequests, requests) + await fake.stop() + }) + + test(`[${name}] live change: next requests see it, with no per-request network call`, opts, async () => { + // The fake server shares this process's event loop: a slow heartbeat + // keeps a burst of requests from delaying it past the 3-heartbeat + // idle deadline (which would reconnect, legitimately, and muddle the count). + const fake = await startFake({ heartbeatMs: 2000 }) + const client = makeClient(fake.url) + const app = await adapter.start({ client, readyTimeoutMs: 3000, onTimeout: 'fail' }) + try { + const free = userFor(1) + assert.equal((await get(app.url, '/check', free.headers)).body.pro, false) + // Turn pro-feature on for the free plan too. + fake.upsert({ ...flag('pro-feature'), rules: [{ attribute: 'plan', operator: 'equals', values: ['pro', 'free'] }] }) + await waitFor(async () => (await get(app.url, '/check', free.headers)).body.pro === true, + { label: 'the change to reach requests' }) + + const counters = { ...fake.counters } + const fetches = sdkFetches.length + const users = Array.from({ length: 200 }, (_, i) => userFor(i)) + const responses = await Promise.all(users.map((u) => get(app.url, '/check', u.headers))) + responses.forEach((res) => assert.equal(res.body.pro, true)) + assert.equal(fake.counters.streamRequests, counters.streamRequests, 'no stream request per request') + assert.equal(fake.counters.snapshotRequests, counters.snapshotRequests, 'no snapshot request per request') + assert.equal(sdkFetches.length, fetches, 'the SDK made no network call while serving requests') + assert.equal(fake.streams.size, 1) + } finally { + await app.close() + await fake.stop() + } + }) + + test(`[${name}] offline: server killed mid-run keeps answering from held flags, converges on restart`, opts, async () => { + const fake = await startFake() + const client = makeClient(fake.url) + const app = await adapter.start({ client, readyTimeoutMs: 3000, onTimeout: 'fail' }) + try { + const users = Array.from({ length: 60 }, (_, i) => userFor(i)) + const port = await killFake(fake) + const during = await Promise.all(users.map((u) => get(app.url, '/check', u.headers))) + during.forEach((res, i) => assertUserResponse(client, users[i], res.body)) + // Changed while the app could not hear about it. + fake.upsert({ ...flag('banner-color'), default_value: 'green' }) + await sleep(300) + const stillOld = await get(app.url, '/check', userFor(1).headers) + assert.equal(stillOld.body.color, 'blue') + + await reviveFake(fake, port) + await waitFor(async () => (await get(app.url, '/check', userFor(1).headers)).body.color === 'green', + { label: 'convergence after restart' }) + await waitFor(() => fake.streams.size === 1, { label: 'one stream after recovery' }) + // Everything else unchanged. + const after = await get(app.url, '/check', userFor(3).headers) + assert.equal(after.body.pro, true) + assert.equal(after.body.color, 'gold') + } finally { + await app.close() + await fake.stop() + } + }) + + test(`[${name}] shutdown: close disconnects exactly once and leaves no stream open`, opts, async () => { + const fake = await startFake() + const client = makeClient(fake.url) + const disconnects = countDisconnects(client) + const app = await adapter.start({ client, readyTimeoutMs: 3000, onTimeout: 'fail' }) + assert.equal(fake.streams.size, 1) + await app.close() + await app.close() // a second close (signal + manual) must not disconnect again + assert.equal(disconnects.calls, 1) + assert.equal(client.getStatus().state, 'closed') + await waitFor(() => fake.streams.size === 0, { label: 'the stream to close' }) + const requests = fake.counters.streamRequests + await sleep(400) + assert.equal(fake.counters.streamRequests, requests, 'no reconnect after shutdown') + await fake.stop() + }) +} + +export { sleep } diff --git a/sdks/node-integrations/test/nestjs.test.mjs b/sdks/node-integrations/test/nestjs.test.mjs new file mode 100644 index 00000000..96b5276b --- /dev/null +++ b/sdks/node-integrations/test/nestjs.test.mjs @@ -0,0 +1,187 @@ +// NestJS module against the real @checkgate/node client and the fake +// Checkgate server (see helpers.mjs). Plain JavaScript, so the decorators +// are applied by calling them, as TypeScript's output does. + +import assert from 'node:assert/strict' +import { createRequire } from 'node:module' +import { test } from 'node:test' +import { checkResponse, contextFromHeaders, frameworkSuite, get, makeClient, quietLogger, startFake } from './helpers.mjs' + +const require = createRequire(import.meta.url) +require('reflect-metadata') +const { Controller, Get, Inject, Injectable, Module, UseGuards } = require('@nestjs/common') +const { Test } = require('@nestjs/testing') +const { + CHECKGATE_CLIENT, Checkgate, CheckgateModule, CheckgateService, RequireFlag, createTestClient, +} = require('@checkgate/node-integrations/nestjs') + +/** Applies method decorators like TypeScript's `__decorate` does. */ +function decorate(Cls, method, decorators) { + const proto = Cls.prototype + const descriptor = Object.getOwnPropertyDescriptor(proto, method) + Object.defineProperty(proto, method, Reflect.decorate(decorators, proto, method, descriptor) || descriptor) +} + +class CheckController { + async check(flags) { + return checkResponse(flags) + } +} +Controller()(CheckController) +decorate(CheckController, 'check', [Get('check')]) +Checkgate()(CheckController.prototype, 'check', 0) + +/** Stand-in for an auth guard: sets req.user from headers. */ +class FakeAuthGuard { + canActivate(ctx) { + const req = ctx.switchToHttp().getRequest() + if (req.headers['x-user']) { + req.user = { id: req.headers['x-user'], plan: req.headers['x-plan'], beta: req.headers['x-beta'] === '1' } + } + return true + } +} +Injectable()(FakeAuthGuard) + +class GatedController { + notFound() { return { ok: true } } + forbidden() { return { ok: true } } + both() { return { ok: true } } + open(flags) { return { key: flags.context.key, pro: flags.isEnabled('pro-feature') } } +} +// Auth at controller level runs before the method-level RequireFlag guard. +Controller('gated')(GatedController) +UseGuards(FakeAuthGuard)(GatedController) +decorate(GatedController, 'notFound', [Get('not-found'), RequireFlag('pro-feature')]) +decorate(GatedController, 'forbidden', [Get('forbidden'), RequireFlag('pro-feature', { status: 403 })]) +decorate(GatedController, 'both', [Get('both'), RequireFlag('pro-feature'), RequireFlag('beta-only')]) +decorate(GatedController, 'open', [Get('open'), RequireFlag('pro-feature')]) +Checkgate()(GatedController.prototype, 'open', 0) + +const userContext = (req) => (req.user ? { key: req.user.id, attributes: { plan: req.user.plan, beta: req.user.beta } } : null) + +async function listen(moduleRef) { + const app = moduleRef.createNestApplication({ logger: false }) + try { + await app.listen(0, '127.0.0.1') + } catch (err) { + await app.close().catch(() => {}) + throw err + } + return { app, url: `http://127.0.0.1:${app.getHttpServer().address().port}` } +} + +frameworkSuite('nestjs', { + async start({ client, readyTimeoutMs, onTimeout }) { + const moduleRef = await Test.createTestingModule({ + imports: [CheckgateModule.forRoot({ + client, readyTimeoutMs, onTimeout, logger: quietLogger, context: (req) => contextFromHeaders(req.headers), + })], + controllers: [CheckController], + }).compile() + const { app, url } = await listen(moduleRef) + return { url, close: () => app.close() } + }, +}) + +test('[nestjs] RequireFlag: 404 / 403 when off, passes when on, all flags must pass', async () => { + const fake = await startFake() + const moduleRef = await Test.createTestingModule({ + imports: [CheckgateModule.forRoot({ client: makeClient(fake.url), context: userContext, logger: quietLogger })], + controllers: [GatedController], + }).compile() + const { app, url } = await listen(moduleRef) + try { + const pro = { 'x-user': 'p', 'x-plan': 'pro' } + const proBeta = { ...pro, 'x-beta': '1' } + const free = { 'x-user': 'f', 'x-plan': 'free' } + assert.equal((await get(url, '/gated/not-found', pro)).status, 200) + assert.equal((await get(url, '/gated/not-found', free)).status, 404) + assert.equal((await get(url, '/gated/not-found')).status, 404) + assert.equal((await get(url, '/gated/forbidden', pro)).status, 200) + assert.equal((await get(url, '/gated/forbidden', free)).status, 403) + assert.equal((await get(url, '/gated/both', pro)).status, 404) + assert.equal((await get(url, '/gated/both', proBeta)).status, 200) + // Guard and parameter share one evaluator: the context the guard used. + assert.deepEqual((await get(url, '/gated/open', pro)).body, { key: 'p', pro: true }) + } finally { + await app.close() + await fake.stop() + } +}) + +test('[nestjs] forTesting(): no server, no addon; flags settable per test', async () => { + const moduleRef = await Test.createTestingModule({ + imports: [CheckgateModule.forTesting({ + 'pro-feature': ({ key }) => key === 'p', + 'beta-only': true, + 'banner-color': 'gold', + }, { context: userContext })], + controllers: [GatedController, CheckController], + }).compile() + const { app, url } = await listen(moduleRef) + try { + assert.equal((await get(url, '/gated/both', { 'x-user': 'p' })).status, 200) + assert.equal((await get(url, '/gated/both', { 'x-user': 'q' })).status, 404) + moduleRef.get(CHECKGATE_CLIENT).setFlag('beta-only', false) + assert.equal((await get(url, '/gated/both', { 'x-user': 'p' })).status, 404) + await app.close() + assert.equal(moduleRef.get(CHECKGATE_CLIENT).disconnectCalls, 1) + } finally { + await app.close() + } +}) + +test('[nestjs] overrideProvider(CHECKGATE_CLIENT) swaps in a test client', async () => { + const fakeClient = createTestClient({ 'pro-feature': true }) + const moduleRef = await Test.createTestingModule({ + // clientOptions are never used: the provider is overridden. + imports: [CheckgateModule.forRoot({ clientOptions: { serverUrl: 'http://127.0.0.1:9' }, context: userContext })], + controllers: [GatedController], + }).overrideProvider(CHECKGATE_CLIENT).useValue(fakeClient).compile() + const { app, url } = await listen(moduleRef) + try { + assert.equal((await get(url, '/gated/not-found', { 'x-user': 'anyone' })).status, 200) + } finally { + await app.close() + } +}) + +test('[nestjs] forRootAsync() with an injected config, and CheckgateService in another provider', async () => { + const fake = await startFake() + const CONFIG = 'APP_CONFIG' + class ConfigModule {} + Module({ providers: [{ provide: CONFIG, useValue: { url: fake.url } }], exports: [CONFIG] })(ConfigModule) + + class ReportJob { + constructor(checkgate) { this.checkgate = checkgate } + run(plan) { return this.checkgate.forContext({ key: 'nightly', attributes: { plan } }).isEnabled('pro-feature') } + } + Injectable()(ReportJob) + Inject(CheckgateService)(ReportJob, undefined, 0) + + const moduleRef = await Test.createTestingModule({ + imports: [CheckgateModule.forRootAsync({ + imports: [ConfigModule], + inject: [CONFIG], + useFactory: (config) => ({ client: makeClient(config.url), readyTimeoutMs: 3000, onTimeout: 'fail', logger: quietLogger }), + })], + providers: [ReportJob], + }).compile() + const app = moduleRef.createNestApplication({ logger: false }) + await app.init() + try { + const service = app.get(CheckgateService) + assert.deepEqual(service.startup, { ready: true, timedOut: false }) + assert.equal(app.get(ReportJob).run('pro'), true) + assert.equal(app.get(ReportJob).run('free'), false) + } finally { + await app.close() + await fake.stop() + } +}) + +test('[nestjs] forRoot() without client or clientOptions fails at module creation', async () => { + await assert.rejects(Test.createTestingModule({ imports: [CheckgateModule.forRoot({})] }).compile(), + /needs client or clientOptions/) +}) diff --git a/sdks/node-integrations/test/types/tsconfig.json b/sdks/node-integrations/test/types/tsconfig.json new file mode 100644 index 00000000..9b66a124 --- /dev/null +++ b/sdks/node-integrations/test/types/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "es2022", + "module": "nodenext", + "moduleResolution": "nodenext", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "experimentalDecorators": true, + "emitDecoratorMetadata": true, + "types": ["node"] + }, + "files": ["usage.ts"] +} diff --git a/sdks/node-integrations/test/types/usage.ts b/sdks/node-integrations/test/types/usage.ts new file mode 100644 index 00000000..0285445e --- /dev/null +++ b/sdks/node-integrations/test/types/usage.ts @@ -0,0 +1,108 @@ +// Compile-only check of the hand-written .d.ts files: `npm run typecheck`. +// Mirrors how an application uses each adapter, so a declaration that does +// not match real usage fails here. + +import express from 'express' +import Fastify from 'fastify' +import { Controller, Get, Injectable, Module, UseGuards } from '@nestjs/common' +import { Test } from '@nestjs/testing' +import { CheckgateClient } from '@checkgate/node' +import { + createRequestFlags, createTestClient, normalizeAttributes, startCheckgate, stopCheckgate, + type RequestFlags, type StartResult, +} from '@checkgate/node-integrations' +import { checkgateMiddleware, listenWithCheckgate } from '@checkgate/node-integrations/express' +import checkgatePlugin from '@checkgate/node-integrations/fastify' +import { + CHECKGATE_CLIENT, Checkgate, CheckgateModule, CheckgateService, RequireFlag, type TestClient, +} from '@checkgate/node-integrations/nestjs' + +declare global { + namespace Express { + // What auth middleware such as Passport declares. + interface Request { user?: { id: string; plan: string } } + } +} + +const client = new CheckgateClient({ serverUrl: 'http://localhost:3000', sdkKey: 'sk_test' }) + +// -- core ------------------------------------------------------------------- +async function core(): Promise { + const result: StartResult = await startCheckgate(client, { readyTimeoutMs: 1000, onTimeout: 'fail' }) + const stopped: boolean = stopCheckgate(client) + const attrs: Record = normalizeAttributes({ seats: 3 }) + const flags: RequestFlags = createRequestFlags(client, () => ({ key: 'u', attributes: { seats: 3, beta: true } })) + const on: boolean = flags.isEnabled('x') + const color = flags.getValue('color', 'blue') + const variant = flags.getVariant('color') + flags.track('goal', { value: 1 }) + const key: string = flags.context.key + const fake: TestClient = createTestClient({ a: true, b: ({ key }) => key === 'u' }) + fake.setFlag('a', false) + void [result, stopped, attrs, on, color, variant, key] +} + +// -- express ---------------------------------------------------------------- +async function expressApp(): Promise { + const app = express() + app.use(checkgateMiddleware({ + client, + context: (req: express.Request) => ({ key: req.user?.id, attributes: { plan: req.user?.plan } }), + })) + app.get('/', (req, res) => { + res.json({ on: req.checkgate.isEnabled('new-ui') }) + }) + const { server, startup, close } = await listenWithCheckgate(app, { client, port: 3000, onTimeout: 'continue' }) + process.once('SIGTERM', () => void close()) + void [server.address(), startup.ready] +} + +// -- fastify ---------------------------------------------------------------- +async function fastifyApp(): Promise { + const app = Fastify() + await app.register(checkgatePlugin, { + client, + context: (request) => ({ key: String(request.headers['x-user'] ?? '') }), + readyTimeoutMs: 3000, + }) + await app.register(checkgatePlugin, { clientOptions: { serverUrl: 'http://localhost:3000' } }) + app.get('/', async (request) => ({ on: request.checkgate.isEnabled('new-ui'), shared: app.checkgate.isReady() })) + await app.listen({ port: 3000 }) +} + +// -- nestjs ----------------------------------------------------------------- +@Injectable() +class AuthGuard { + canActivate(): boolean { return true } +} + +@Controller('beta') +@UseGuards(AuthGuard) +class BetaController { + constructor(private readonly checkgate: CheckgateService) {} + + @Get() + @RequireFlag('beta-page') + page(@Checkgate() flags: RequestFlags) { + return { color: flags.getValue('color', 'blue'), job: this.checkgate.forContext('job').isEnabled('x') } + } +} + +@Module({ + imports: [ + CheckgateModule.forRoot({ clientOptions: { serverUrl: 'http://localhost:3000' }, readyTimeoutMs: 3000 }), + CheckgateModule.forRootAsync({ useFactory: () => ({ client }), inject: [] }), + ], + controllers: [BetaController], +}) +class AppModule {} + +async function nestTest(): Promise { + const moduleRef = await Test.createTestingModule({ + imports: [CheckgateModule.forTesting({ 'beta-page': true })], + controllers: [BetaController], + }).compile() + moduleRef.get(CHECKGATE_CLIENT).setFlag('beta-page', false) +} + +void [core, expressApp, fastifyApp, nestTest, AppModule] From cc9ceb4512b086405c01eb417f0890482e17dd87 Mon Sep 17 00:00:00 2001 From: Dennis Paler Date: Sat, 21 Nov 2026 21:56:50 +0800 Subject: [PATCH 06/38] docs(node-integrations): runnable Express, Fastify and NestJS examples Minimal apps reading CHECKGATE_URL / CHECKGATE_SDK_KEY from the environment, with a stand-in auth step, a context extractor, flag reads, and SIGTERM shutdown. The NestJS one is TypeScript (compiled with tsc into the ignored examples/nestjs/dist/) and shows @Checkgate() and @RequireFlag(). test/examples.test.mjs runs each as its own process against the fake server and checks the answers and that SIGTERM closes the stream and exits. --- .gitignore | 3 + .../examples/express/server.mjs | 51 ++++++++++++ .../examples/fastify/server.mjs | 41 ++++++++++ .../examples/nestjs/src/main.ts | 77 +++++++++++++++++++ .../examples/nestjs/tsconfig.json | 15 ++++ sdks/node-integrations/test/examples.test.mjs | 70 +++++++++++++++++ 6 files changed, 257 insertions(+) create mode 100644 sdks/node-integrations/examples/express/server.mjs create mode 100644 sdks/node-integrations/examples/fastify/server.mjs create mode 100644 sdks/node-integrations/examples/nestjs/src/main.ts create mode 100644 sdks/node-integrations/examples/nestjs/tsconfig.json create mode 100644 sdks/node-integrations/test/examples.test.mjs diff --git a/.gitignore b/.gitignore index d18b4c5b..0dedeeab 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,9 @@ coverage/ .flutter-plugins-dependencies sdks/flutter/dart/build/ +# Compiled output of the NestJS integration example (npx tsc -p examples/nestjs). +sdks/node-integrations/examples/nestjs/dist/ + # TypeScript incremental build state — regenerated by every `tsc -b`, so # tracking it churns the diff on each commit. *.tsbuildinfo diff --git a/sdks/node-integrations/examples/express/server.mjs b/sdks/node-integrations/examples/express/server.mjs new file mode 100644 index 00000000..a239e0a5 --- /dev/null +++ b/sdks/node-integrations/examples/express/server.mjs @@ -0,0 +1,51 @@ +// Minimal Express app with Checkgate. +// +// CHECKGATE_URL=http://localhost:3000 CHECKGATE_SDK_KEY= node examples/express/server.mjs +// curl -H 'x-user-id: alice' -H 'x-plan: pro' http://localhost:8080/ + +import express from 'express' +import { CheckgateClient } from '@checkgate/node' +import { checkgateMiddleware, listenWithCheckgate } from '@checkgate/node-integrations/express' + +// One client for the whole process. +const client = new CheckgateClient({ + serverUrl: process.env.CHECKGATE_URL ?? 'http://localhost:3000', + sdkKey: process.env.CHECKGATE_SDK_KEY, +}) + +const app = express() + +// Stand-in for real authentication, which would set req.user. +app.use((req, _res, next) => { + const id = req.get('x-user-id') + if (id) req.user = { id, plan: req.get('x-plan') ?? 'free' } + next() +}) + +app.use(checkgateMiddleware({ + client, + context: (req) => (req.user ? { key: req.user.id, attributes: { plan: req.user.plan } } : null), +})) + +app.get('/', (req, res) => { + res.json({ + user: req.checkgate.context.key, + newCheckout: req.checkgate.isEnabled('new-checkout'), + bannerColor: req.checkgate.getValue('banner-color', 'blue'), + }) +}) + +// Waits up to 5 s for flags, then listens either way (cached or default values +// until the first sync). +const { server, close } = await listenWithCheckgate(app, { + client, + port: Number(process.env.PORT ?? 8080), + readyTimeoutMs: 5000, + onTimeout: 'continue', +}) +console.log(`listening on http://localhost:${server.address().port}`) + +// Finish requests in flight, then disconnect from Checkgate. +for (const signal of ['SIGTERM', 'SIGINT']) { + process.once(signal, () => close().then(() => process.exit(0))) +} diff --git a/sdks/node-integrations/examples/fastify/server.mjs b/sdks/node-integrations/examples/fastify/server.mjs new file mode 100644 index 00000000..f1ce388f --- /dev/null +++ b/sdks/node-integrations/examples/fastify/server.mjs @@ -0,0 +1,41 @@ +// Minimal Fastify app with Checkgate. +// +// CHECKGATE_URL=http://localhost:3000 CHECKGATE_SDK_KEY= node examples/fastify/server.mjs +// curl -H 'x-user-id: alice' -H 'x-plan: pro' http://localhost:8080/ + +import Fastify from 'fastify' +import checkgate from '@checkgate/node-integrations/fastify' + +const app = Fastify({ logger: { level: 'warn' } }) + +// Stand-in for real authentication, which would set request.user. +app.decorateRequest('user', null) +app.addHook('onRequest', async (request) => { + const id = request.headers['x-user-id'] + if (id) request.user = { id, plan: request.headers['x-plan'] ?? 'free' } +}) + +// The plugin builds the client, connects while loading (up to 5 s; then the +// app starts with cached or default values) and disconnects on close. +await app.register(checkgate, { + clientOptions: { + serverUrl: process.env.CHECKGATE_URL ?? 'http://localhost:3000', + sdkKey: process.env.CHECKGATE_SDK_KEY, + }, + context: (request) => (request.user ? { key: request.user.id, attributes: { plan: request.user.plan } } : null), + readyTimeoutMs: 5000, + onTimeout: 'continue', +}) + +app.get('/', async (request) => ({ + user: request.checkgate.context.key, + newCheckout: request.checkgate.isEnabled('new-checkout'), + bannerColor: request.checkgate.getValue('banner-color', 'blue'), +})) + +const address = await app.listen({ port: Number(process.env.PORT ?? 8080), host: '127.0.0.1' }) +console.log(`listening on ${address}`) + +for (const signal of ['SIGTERM', 'SIGINT']) { + process.once(signal, () => app.close().then(() => process.exit(0))) +} diff --git a/sdks/node-integrations/examples/nestjs/src/main.ts b/sdks/node-integrations/examples/nestjs/src/main.ts new file mode 100644 index 00000000..89a6b4f8 --- /dev/null +++ b/sdks/node-integrations/examples/nestjs/src/main.ts @@ -0,0 +1,77 @@ +// Minimal NestJS app with Checkgate. +// +// npx tsc -p examples/nestjs +// CHECKGATE_URL=http://localhost:3000 CHECKGATE_SDK_KEY= node examples/nestjs/dist/main.js +// curl -H 'x-user-id: alice' -H 'x-plan: pro' http://localhost:8080/ +// curl -H 'x-user-id: alice' http://localhost:8080/beta # 404 unless beta-page is on for alice + +import 'reflect-metadata' +import { Controller, Get, Injectable, Module, UseGuards, type CanActivate, type ExecutionContext } from '@nestjs/common' +import { NestFactory } from '@nestjs/core' +import { Checkgate, CheckgateModule, RequireFlag, type RequestFlags } from '@checkgate/node-integrations/nestjs' + +interface DemoRequest { + headers: Record + user?: { id: string; plan: string } +} + +/** Stand-in for real authentication, which would set req.user. */ +@Injectable() +class DemoAuthGuard implements CanActivate { + canActivate(ctx: ExecutionContext): boolean { + const req = ctx.switchToHttp().getRequest() + const id = req.headers['x-user-id'] + if (typeof id === 'string') { + const plan = req.headers['x-plan'] + req.user = { id, plan: typeof plan === 'string' ? plan : 'free' } + } + return true + } +} + +// Authentication at controller level runs before the method's RequireFlag guard. +@Controller() +@UseGuards(DemoAuthGuard) +class AppController { + @Get() + home(@Checkgate() flags: RequestFlags) { + return { + user: flags.context.key, + newCheckout: flags.isEnabled('new-checkout'), + bannerColor: flags.getValue('banner-color', 'blue'), + } + } + + @Get('beta') + @RequireFlag('beta-page') + beta() { + return { welcome: 'to the beta' } + } +} + +@Module({ + imports: [ + CheckgateModule.forRoot({ + clientOptions: { + serverUrl: process.env.CHECKGATE_URL ?? 'http://localhost:3000', + sdkKey: process.env.CHECKGATE_SDK_KEY, + }, + context: (req: DemoRequest) => (req.user ? { key: req.user.id, attributes: { plan: req.user.plan } } : null), + // Waits up to 5 s during bootstrap, then starts with cached or default values. + readyTimeoutMs: 5000, + onTimeout: 'continue', + }), + ], + controllers: [AppController], +}) +class AppModule {} + +async function bootstrap(): Promise { + const app = await NestFactory.create(AppModule, { logger: ['warn', 'error'] }) + // SIGTERM / SIGINT run onApplicationShutdown, which disconnects the client. + app.enableShutdownHooks() + await app.listen(Number(process.env.PORT ?? 8080)) + console.log(`listening on ${await app.getUrl()}`) +} + +void bootstrap() diff --git a/sdks/node-integrations/examples/nestjs/tsconfig.json b/sdks/node-integrations/examples/nestjs/tsconfig.json new file mode 100644 index 00000000..e4f77543 --- /dev/null +++ b/sdks/node-integrations/examples/nestjs/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "es2022", + "module": "nodenext", + "moduleResolution": "nodenext", + "rootDir": "src", + "outDir": "dist", + "strict": true, + "experimentalDecorators": true, + "emitDecoratorMetadata": true, + "skipLibCheck": true, + "types": ["node"] + }, + "include": ["src"] +} diff --git a/sdks/node-integrations/test/examples.test.mjs b/sdks/node-integrations/test/examples.test.mjs new file mode 100644 index 00000000..ae750383 --- /dev/null +++ b/sdks/node-integrations/test/examples.test.mjs @@ -0,0 +1,70 @@ +// Runs each example app (examples/*) as its own process against the fake +// Checkgate server: it must start, answer from flags, and on SIGTERM close +// its stream to the server and exit. + +import assert from 'node:assert/strict' +import { execFileSync, spawn } from 'node:child_process' +import { once } from 'node:events' +import { fileURLToPath } from 'node:url' +import { test } from 'node:test' +import { SDK_KEY, get, startFake, waitFor } from './helpers.mjs' + +const root = fileURLToPath(new URL('..', import.meta.url)) +const base = { rollout_percentage: null, description: null, rules: [] } +const flags = [ + { ...base, key: 'new-checkout', is_enabled: true, rollout_percentage: 0, + rules: [{ attribute: 'plan', operator: 'equals', values: ['pro'] }] }, + { ...base, key: 'banner-color', is_enabled: true, flag_type: 'string', default_value: 'green' }, + { ...base, key: 'beta-page', is_enabled: true, rollout_percentage: 0, + rules: [{ attribute: 'plan', operator: 'equals', values: ['pro'] }] }, +] + +async function runExample(entry, check) { + const fake = await startFake({ flags }) + const child = spawn(process.execPath, [entry], { + cwd: root, + env: { ...process.env, CHECKGATE_URL: fake.url, CHECKGATE_SDK_KEY: SDK_KEY, PORT: '0' }, + stdio: ['ignore', 'pipe', 'pipe'], + }) + let output = '' + child.stdout.on('data', (d) => (output += d)) + child.stderr.on('data', (d) => (output += d)) + try { + await waitFor(() => /listening on (http:\/\/\S+)/.test(output), { timeoutMs: 20000, label: `${entry} to listen` }) + const url = output.match(/listening on (http:\/\/\S+)/)[1].replace('[::1]', '127.0.0.1').replace('localhost', '127.0.0.1') + assert.equal(fake.streams.size, 1) + await check(url) + child.kill('SIGTERM') + const [code, signal] = await once(child, 'exit') + // Express/Fastify exit 0; Nest re-raises the signal after its shutdown hooks. + assert.ok(code === 0 || signal === 'SIGTERM', `exit ${code} ${signal}\n${output}`) + await waitFor(() => fake.streams.size === 0, { label: 'the stream to close' }) + } finally { + if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL') + await fake.stop() + } +} + +async function checkHome(url) { + const pro = await get(url, '/', { 'x-user-id': 'alice', 'x-plan': 'pro' }) + assert.deepEqual(pro.body, { user: 'alice', newCheckout: true, bannerColor: 'green' }) + const free = await get(url, '/', { 'x-user-id': 'bob' }) + assert.deepEqual(free.body, { user: 'bob', newCheckout: false, bannerColor: 'green' }) +} + +test('[example] express', async () => { + await runExample('examples/express/server.mjs', checkHome) +}) + +test('[example] fastify', async () => { + await runExample('examples/fastify/server.mjs', checkHome) +}) + +test('[example] nestjs (compiled with tsc)', async () => { + execFileSync(process.execPath, [fileURLToPath(new URL('../node_modules/typescript/bin/tsc', import.meta.url)), '-p', 'examples/nestjs'], { cwd: root }) + await runExample('examples/nestjs/dist/main.js', async (url) => { + await checkHome(url) + assert.equal((await get(url, '/beta', { 'x-user-id': 'alice', 'x-plan': 'pro' })).status, 200) + assert.equal((await get(url, '/beta', { 'x-user-id': 'bob' })).status, 404) + }) +}) From 662a151e92e298db2d587cf5582158b0b3280715 Mon Sep 17 00:00:00 2001 From: Dennis Paler Date: Sat, 21 Nov 2026 22:08:21 +0800 Subject: [PATCH 07/38] fix(node-integrations): every root export visible to ESM; bound readyTimeoutMs The root entry re-exported members (core.RequestFlags, ...), which Node's CommonJS export detection does not follow: an ESM importer saw only one name. It now exports plain identifiers, and a test imports every entry point as ESM and checks each documented name. readyTimeoutMs above 2^31 - 1 (or Infinity) made setTimeout fire after 1 ms; it is now rejected. --- sdks/node-integrations/src/core.js | 6 +++-- sdks/node-integrations/src/index.d.ts | 2 +- sdks/node-integrations/src/index.js | 29 ++++++++++++++++------- sdks/node-integrations/test/core.test.mjs | 17 +++++++++++++ 4 files changed, 42 insertions(+), 12 deletions(-) diff --git a/sdks/node-integrations/src/core.js b/sdks/node-integrations/src/core.js index 83121efd..84cf461d 100644 --- a/sdks/node-integrations/src/core.js +++ b/sdks/node-integrations/src/core.js @@ -9,6 +9,7 @@ // flag store. const DEFAULT_KEY = 'anonymous' +const MAX_TIMEOUT_MS = 2 ** 31 - 1 /** * Converts one attribute value to the string the evaluation core expects, or @@ -276,8 +277,9 @@ async function startCheckgate(client, { readyTimeoutMs = 5000, onTimeout = 'cont if (onTimeout !== 'continue' && onTimeout !== 'fail') { throw new TypeError(`[Checkgate] onTimeout must be 'continue' or 'fail', got ${String(onTimeout)}.`) } - if (typeof readyTimeoutMs !== 'number' || !(readyTimeoutMs >= 0)) { - throw new TypeError('[Checkgate] readyTimeoutMs must be a number >= 0.') + // setTimeout() treats anything above 2^31 - 1 ms (and Infinity) as 1 ms. + if (!Number.isFinite(readyTimeoutMs) || readyTimeoutMs < 0 || readyTimeoutMs > MAX_TIMEOUT_MS) { + throw new TypeError(`[Checkgate] readyTimeoutMs must be a number from 0 to ${MAX_TIMEOUT_MS}.`) } stopped.delete(client) diff --git a/sdks/node-integrations/src/index.d.ts b/sdks/node-integrations/src/index.d.ts index 85f77a2d..6c7cc666 100644 --- a/sdks/node-integrations/src/index.d.ts +++ b/sdks/node-integrations/src/index.d.ts @@ -87,7 +87,7 @@ export declare function normalizeAttributes(input: unknown): Record { const client = createTestClient() await assert.rejects(startCheckgate(client, { onTimeout: 'maybe' }), /onTimeout must be/) await assert.rejects(startCheckgate(client, { readyTimeoutMs: -1 }), /readyTimeoutMs/) + await assert.rejects(startCheckgate(client, { readyTimeoutMs: Infinity }), /readyTimeoutMs/) await assert.rejects(startCheckgate({}), /needs a CheckgateClient/) assert.deepEqual(await startCheckgate(client), { ready: true, timedOut: false }) }) @@ -181,3 +182,19 @@ test('shared evaluation vectors', { skip: vectors ? false : 'sdks/conformance/ve await fake.stop() } }) + +test('ESM importers see every named export of every entry point', async () => { + const expected = { + '@checkgate/node-integrations': ['CheckgateStartupTimeoutError', 'RequestFlags', 'createRequestFlags', 'createTestClient', + 'defaultContext', 'normalizeAttributes', 'normalizeContext', 'startCheckgate', 'stopCheckgate'], + '@checkgate/node-integrations/express': ['checkgateMiddleware', 'listenWithCheckgate', 'startCheckgate', 'stopCheckgate'], + '@checkgate/node-integrations/fastify': ['checkgatePlugin', 'default', 'startCheckgate', 'stopCheckgate'], + '@checkgate/node-integrations/nestjs': ['CHECKGATE_CLIENT', 'CHECKGATE_OPTIONS', 'Checkgate', 'CheckgateFlagGuard', + 'CheckgateModule', 'CheckgateRequestPipe', 'CheckgateService', 'REQUIRE_FLAG_METADATA', 'RequireFlag', + 'createTestClient', 'startCheckgate', 'stopCheckgate'], + } + for (const [specifier, names] of Object.entries(expected)) { + const ns = await import(specifier) + for (const name of names) assert.notEqual(ns[name], undefined, `${specifier} exports ${name}`) + } +}) From 03232ff3f5ea4983ddaa20dc18e77e97535358e5 Mon Sep 17 00:00:00 2001 From: Dennis Paler Date: Sat, 21 Nov 2026 22:08:22 +0800 Subject: [PATCH 08/38] test(node-integrations): run the NestJS suite on the Fastify platform too The shared framework suite and the RequireFlag checks now also run with @nestjs/platform-fastify, where the request is a FastifyRequest. --- sdks/node-integrations/package-lock.json | 119 ++++++++++++++++++++ sdks/node-integrations/package.json | 1 + sdks/node-integrations/test/nestjs.test.mjs | 39 ++++--- 3 files changed, 143 insertions(+), 16 deletions(-) diff --git a/sdks/node-integrations/package-lock.json b/sdks/node-integrations/package-lock.json index c3dfff71..156b54fa 100644 --- a/sdks/node-integrations/package-lock.json +++ b/sdks/node-integrations/package-lock.json @@ -16,6 +16,7 @@ "@nestjs/common": "^12.6.0", "@nestjs/core": "^12.6.0", "@nestjs/platform-express": "^12.6.0", + "@nestjs/platform-fastify": "^12.6.0", "@nestjs/testing": "^12.6.0", "@types/express": "^5.0.0", "@types/node": "^22.0.0", @@ -99,6 +100,27 @@ "fast-uri": "^4.0.0" } }, + "node_modules/@fastify/cors": { + "version": "11.4.3", + "resolved": "https://registry.npmjs.org/@fastify/cors/-/cors-11.4.3.tgz", + "integrity": "sha512-6NNFNR1i9t1oG1WlQftwc2ugElFm4cG75ylYyGNiKKiyxlVGueneup9MQ9Nd3eI4lT6kVOJaxV1Jqa727/E4jg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "fastify-plugin": "^6.0.0", + "toad-cache": "^3.7.0" + } + }, "node_modules/@fastify/deepmerge": { "version": "3.2.4", "resolved": "https://registry.npmjs.org/@fastify/deepmerge/-/deepmerge-3.2.4.tgz", @@ -153,6 +175,27 @@ "fast-json-stringify": "^7.3.0" } }, + "node_modules/@fastify/formbody": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/@fastify/formbody/-/formbody-9.0.2.tgz", + "integrity": "sha512-VJdbcbFlsp7xTAY5/Qrc8SZPyuke0YymWCe11INALPTQfRh2+0y1lnaosJwWIN7GtFfcBa+RBo4VnhxjW2kDNQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "fast-querystring": "^1.1.2", + "fastify-plugin": "^6.0.0" + } + }, "node_modules/@fastify/forwarded": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/@fastify/forwarded/-/forwarded-3.1.2.tgz", @@ -190,6 +233,41 @@ "dequal": "^2.0.3" } }, + "node_modules/@fastify/middie": { + "version": "9.3.7", + "resolved": "https://registry.npmjs.org/@fastify/middie/-/middie-9.3.7.tgz", + "integrity": "sha512-Th/Htlg81STi0RYdK5zA9LggfpOCsqd5t4RiLKSE25IS7Zv6zNd9nouPdlsYHE3wdt3EkBAbp58Ltsn0HOroCA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/error": "^4.0.0", + "fastify-plugin": "^6.0.0", + "find-my-way": "^9.5.0", + "path-to-regexp": "^9.0.0", + "reusify": "^1.0.4" + } + }, + "node_modules/@fastify/middie/node_modules/path-to-regexp": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-9.0.0.tgz", + "integrity": "sha512-kfo5HIFCfEH24bcHSWEFIfrwiCsm/DXR+j1fc0696VIdWkICdAcKH2LxRClvz5HQcG4iCQpb4qBZ7pttGPG/dA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/@fastify/proxy-addr": { "version": "5.1.3", "resolved": "https://registry.npmjs.org/@fastify/proxy-addr/-/proxy-addr-5.1.3.tgz", @@ -317,6 +395,47 @@ "rxjs": "^7.1.0" } }, + "node_modules/@nestjs/platform-fastify": { + "version": "12.6.0", + "resolved": "https://registry.npmjs.org/@nestjs/platform-fastify/-/platform-fastify-12.6.0.tgz", + "integrity": "sha512-d/fxT9zmcBoXpDp9Csv13g6/N5KWnNe2beDxas3/b5xlYB0CS7nMwr9aekZYi/pt16gyf50NR1hmNPXinaZ4ng==", + "dev": true, + "license": "MIT", + "dependencies": { + "@fastify/cors": "11.4.3", + "@fastify/formbody": "9.0.2", + "@fastify/middie": "9.3.7", + "fast-querystring": "1.1.2", + "fastify": "5.12.8", + "find-my-way": "9.10.2", + "light-my-request": "6.8.1", + "path-to-regexp": "8.4.2", + "tslib": "2.9.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "@fastify/multipart": "^10.1.0", + "@fastify/static": "^10.1.10", + "@fastify/view": "^10.0.0 || ^11.0.0 || ^12.0.0", + "@nestjs/common": "^12.0.0", + "@nestjs/core": "^12.0.0", + "rxjs": "^7.1.0" + }, + "peerDependenciesMeta": { + "@fastify/multipart": { + "optional": true + }, + "@fastify/static": { + "optional": true + }, + "@fastify/view": { + "optional": true + } + } + }, "node_modules/@nestjs/testing": { "version": "12.6.0", "resolved": "https://registry.npmjs.org/@nestjs/testing/-/testing-12.6.0.tgz", diff --git a/sdks/node-integrations/package.json b/sdks/node-integrations/package.json index 73683f83..c5be2a80 100644 --- a/sdks/node-integrations/package.json +++ b/sdks/node-integrations/package.json @@ -80,6 +80,7 @@ "@nestjs/common": "^12.6.0", "@nestjs/core": "^12.6.0", "@nestjs/platform-express": "^12.6.0", + "@nestjs/platform-fastify": "^12.6.0", "@nestjs/testing": "^12.6.0", "@types/express": "^5.0.0", "@types/node": "^22.0.0", diff --git a/sdks/node-integrations/test/nestjs.test.mjs b/sdks/node-integrations/test/nestjs.test.mjs index 96b5276b..3921ef7f 100644 --- a/sdks/node-integrations/test/nestjs.test.mjs +++ b/sdks/node-integrations/test/nestjs.test.mjs @@ -11,6 +11,7 @@ const require = createRequire(import.meta.url) require('reflect-metadata') const { Controller, Get, Inject, Injectable, Module, UseGuards } = require('@nestjs/common') const { Test } = require('@nestjs/testing') +const { FastifyAdapter } = require('@nestjs/platform-fastify') const { CHECKGATE_CLIENT, Checkgate, CheckgateModule, CheckgateService, RequireFlag, createTestClient, } = require('@checkgate/node-integrations/nestjs') @@ -60,8 +61,12 @@ Checkgate()(GatedController.prototype, 'open', 0) const userContext = (req) => (req.user ? { key: req.user.id, attributes: { plan: req.user.plan, beta: req.user.beta } } : null) -async function listen(moduleRef) { - const app = moduleRef.createNestApplication({ logger: false }) +// Nest's default HTTP platform is Express; 'fastify' runs the same app on +// @nestjs/platform-fastify, where the request is a FastifyRequest. +async function listen(moduleRef, platform = 'express') { + const app = platform === 'fastify' + ? moduleRef.createNestApplication(new FastifyAdapter(), { logger: false }) + : moduleRef.createNestApplication({ logger: false }) try { await app.listen(0, '127.0.0.1') } catch (err) { @@ -71,26 +76,28 @@ async function listen(moduleRef) { return { app, url: `http://127.0.0.1:${app.getHttpServer().address().port}` } } -frameworkSuite('nestjs', { - async start({ client, readyTimeoutMs, onTimeout }) { - const moduleRef = await Test.createTestingModule({ - imports: [CheckgateModule.forRoot({ - client, readyTimeoutMs, onTimeout, logger: quietLogger, context: (req) => contextFromHeaders(req.headers), - })], - controllers: [CheckController], - }).compile() - const { app, url } = await listen(moduleRef) - return { url, close: () => app.close() } - }, -}) +for (const platform of ['express', 'fastify']) { + frameworkSuite(platform === 'express' ? 'nestjs' : 'nestjs/fastify-platform', { + async start({ client, readyTimeoutMs, onTimeout }) { + const moduleRef = await Test.createTestingModule({ + imports: [CheckgateModule.forRoot({ + client, readyTimeoutMs, onTimeout, logger: quietLogger, context: (req) => contextFromHeaders(req.headers), + })], + controllers: [CheckController], + }).compile() + const { app, url } = await listen(moduleRef, platform) + return { url, close: () => app.close() } + }, + }) +} -test('[nestjs] RequireFlag: 404 / 403 when off, passes when on, all flags must pass', async () => { +for (const platform of ['express', 'fastify']) test(`[nestjs/${platform}] RequireFlag: 404 / 403 when off, passes when on, all flags must pass`, async () => { const fake = await startFake() const moduleRef = await Test.createTestingModule({ imports: [CheckgateModule.forRoot({ client: makeClient(fake.url), context: userContext, logger: quietLogger })], controllers: [GatedController], }).compile() - const { app, url } = await listen(moduleRef) + const { app, url } = await listen(moduleRef, platform) try { const pro = { 'x-user': 'p', 'x-plan': 'pro' } const proBeta = { ...pro, 'x-beta': '1' } From 88394aef1e5aac5676d35d1cb369518be537bb3a Mon Sep 17 00:00:00 2001 From: Dennis Paler Date: Sat, 21 Nov 2026 22:08:22 +0800 Subject: [PATCH 09/38] ci: node-integrations job on Node 22, 24 and 26 Builds the @checkgate/node native addon (debug) and runs the integration package's type check and tests against it. The matrix is the Node.js lines in LTS in November 2026: 22 and 24 (maintenance) and 26 (active); 20 reached end of life on 2026-04-30. --- .github/workflows/ci.yml | 46 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d3db83bd..cea2091f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -477,6 +477,52 @@ jobs: working-directory: sdks/nodejs run: node --test + # --------------------------------------------------------------------------- + # Node framework integrations — @checkgate/node-integrations (Express, + # Fastify, NestJS) over the REAL @checkgate/node and its native addon, with + # sdks/conformance/fault-server.mjs as the Checkgate server. Every Node.js + # line in LTS (22 and 24 maintenance, 26 active); 20 reached end of life on + # 2026-04-30. + # --------------------------------------------------------------------------- + node-integrations: + name: Node integrations (Node ${{ matrix.node }}) + runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + node: [22, 24, 26] + steps: + - uses: actions/checkout@v5 + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + + - name: Cache Rust build artifacts + uses: Swatinem/rust-cache@v2 + + - uses: actions/setup-node@v5 + with: + node-version: ${{ matrix.node }} + + - name: Build the Node SDK native addon + working-directory: sdks/nodejs + run: | + npm ci + npm run build:debug + + - name: Install dependencies + working-directory: sdks/node-integrations + run: npm ci + + - name: Type definitions compile + working-directory: sdks/node-integrations + run: npm run typecheck + + - name: Run tests (adapters, examples, core) + working-directory: sdks/node-integrations + run: npm test + # --------------------------------------------------------------------------- # Web + React Native SDKs — client-logic unit tests (vitest; the WASM core is # stubbed for web, the JSI bridge faked for RN — no native/WASM build needed) From 04041454394eedddefb03e846e927b85f8267aa0 Mon Sep 17 00:00:00 2001 From: Dennis Paler Date: Sat, 21 Nov 2026 22:09:55 +0800 Subject: [PATCH 10/38] docs: Express, Fastify and NestJS guide for @checkgate/node-integrations New public page docs/sdks/node-frameworks.md (supported versions, the request context and attribute coercion, the startup timeout policy, each adapter, NestJS testing and why no provider is REQUEST-scoped, limitations), linked from the sidebar, the SDK chooser, the Node.js SDK page and the README. Package README for sdks/node-integrations. --- README.md | 1 + docs/.vitepress/config.ts | 1 + docs/sdks/index.md | 8 +- docs/sdks/node-frameworks.md | 283 +++++++++++++++++++++++++++++++ docs/sdks/nodejs.md | 3 + sdks/node-integrations/README.md | 100 +++++++++++ 6 files changed, 395 insertions(+), 1 deletion(-) create mode 100644 docs/sdks/node-frameworks.md create mode 100644 sdks/node-integrations/README.md diff --git a/README.md b/README.md index 2094e8e8..2cf4138c 100644 --- a/README.md +++ b/README.md @@ -183,6 +183,7 @@ Method, assumptions and sources: [Infrastructure cost and efficiency](docs/perfo | Step-by-step setup | [Getting Started](docs/guide/getting-started.md) | | REST API + SSE stream reference | [API Reference](docs/api-reference.md) | | Node.js SDK | [SDK: Node.js](docs/sdks/nodejs.md) | +| Express, Fastify, NestJS | [SDK: Node.js frameworks](docs/sdks/node-frameworks.md) | | Web (WASM) SDK | [SDK: Web](docs/sdks/web.md) | | React Native (JSI) SDK | [SDK: React Native](docs/sdks/react-native.md) | | Flutter (FFI) SDK | [SDK: Flutter](docs/sdks/flutter.md) | diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 7a7a4e90..e9eadbd6 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -85,6 +85,7 @@ export default defineConfig({ items: [ { text: "Which SDK do I need?", link: "/sdks/" }, { text: "Node.js (NAPI)", link: "/sdks/nodejs" }, + { text: "Express, Fastify, NestJS", link: "/sdks/node-frameworks" }, { text: "Web (WebAssembly)", link: "/sdks/web" }, { text: "React Native (JSI)", link: "/sdks/react-native" }, { text: "Flutter (FFI)", link: "/sdks/flutter" }, diff --git a/docs/sdks/index.md b/docs/sdks/index.md index 00e2205e..dee9bdc8 100644 --- a/docs/sdks/index.md +++ b/docs/sdks/index.md @@ -22,7 +22,7 @@ Find your stack below — each section lists what's **required**, what's | **SPA** — Vite, Vue, React, Svelte, Angular | `@checkgate/web` | `@checkgate/cli` | | **React Native** | `@checkgate/react-native` | `@checkgate/cli` | | **Flutter** | `checkgate_flutter` | `@checkgate/cli` | -| **Node.js server** — Express, Fastify, NestJS | `@checkgate/node` | `@checkgate/cli` | +| **Node.js server** — Express, Fastify, NestJS | `@checkgate/node` | `@checkgate/node-integrations`, `@checkgate/cli` | | **Edge** — Cloudflare Workers, Vercel Edge, middleware | `@checkgate/edge` + `@checkgate/web` | `@checkgate/cli` | `@checkgate/cli` is optional everywhere — it's a dev-time tool that generates @@ -165,6 +165,12 @@ app.get('/', (req, res) => { See the [Node.js SDK reference](/sdks/nodejs). +**Optional: `@checkgate/node-integrations`** — middleware for Express, a plugin +for Fastify and a module for NestJS. Each request gets flags bound to its own +user (`req.checkgate.isEnabled('new-homepage')`), startup waits for flags with +a timeout instead of hanging, and shutdown disconnects the client. See +[Express, Fastify and NestJS](/sdks/node-frameworks). + --- ## Edge runtimes (Cloudflare Workers, Vercel Edge, middleware) diff --git a/docs/sdks/node-frameworks.md b/docs/sdks/node-frameworks.md new file mode 100644 index 00000000..f93931f6 --- /dev/null +++ b/docs/sdks/node-frameworks.md @@ -0,0 +1,283 @@ +--- +title: "Express, Fastify and NestJS — Checkgate Feature Flags in Node.js Frameworks" +description: "Use Checkgate feature flags in Express, Fastify and NestJS with @checkgate/node-integrations: per-request flag evaluation bound to the current user, startup with a timeout policy, graceful shutdown, and test doubles." +--- + +# Express, Fastify and NestJS + +`@checkgate/node-integrations` connects the [Node.js SDK](/sdks/nodejs) to a web +framework. It gives every request a small evaluator bound to that request's +user, starts the client with a timeout so your server never hangs waiting for +Checkgate, and disconnects it once when the app shuts down. + +```bash +npm install @checkgate/node @checkgate/node-integrations +``` + +| Import | For | +|---|---| +| `@checkgate/node-integrations/express` | Express (any `(req, res, next)` stack) | +| `@checkgate/node-integrations/fastify` | Fastify | +| `@checkgate/node-integrations/nestjs` | NestJS | +| `@checkgate/node-integrations` | the framework-independent core and `createTestClient()` | + +Each framework is an optional peer dependency: install only the one you use. + +| Package | Supported | +|---|---| +| Node.js | 22.12 or later (tested on 22, 24 and 26) | +| `@checkgate/node` | 0.1.31 or later, below 0.3 | +| `express` | 5.x | +| `fastify` | 5.x (`fastify-plugin` is a dependency of this package) | +| `@nestjs/common`, `@nestjs/core` | 12.x, on the Express or Fastify platform | + +NestJS 12 is published as ES modules only; this package is CommonJS and loads +it with `require()`, which Node.js supports from 22.12. Your app can be either +CommonJS or ES modules. + +## How it works + +- **One client per process.** You create one `CheckgateClient` (or let the + Fastify plugin / Nest module create it). It holds one stream to the server + and the flags in memory. +- **One evaluator per request.** `req.checkgate` (Express), + `request.checkgate` (Fastify) or `@Checkgate()` (NestJS) is a + `RequestFlags` object: `isEnabled(flag)`, `getValue(flag, default)`, + `getVariant(flag)`, `track(event, opts)` and `context`. Nothing about the + request is stored on the shared client. +- **No network call per request.** Every evaluation is a synchronous lookup + in the client's memory. Flag changes arrive over the client's stream. + (Impressions, if you leave `reportImpressions` on, are batched and sent + by the SDK in the background, not per request.) +- **Evaluations never throw.** A failure is passed to `onError` (default: + `console.error`) and the evaluation returns its default: `false`, `null`, + or the default you passed to `getValue()`. + +### The request context + +You supply a `context(req)` function that returns the user key (used for +rollout hashing) and the attributes your targeting rules read: + +```js +context: (req) => req.user + ? { key: req.user.id, attributes: { plan: req.user.plan, seats: req.user.seats } } + : null // anonymous +``` + +It is called **once per request, on the first evaluation**, so it sees +`req.user` even when your authentication middleware runs after the Checkgate +one. Without a `context` option the default is `{ key: req.user.id }` when +there is a `req.user`. A missing or empty key becomes `defaultKey` +(`'anonymous'` unless you set it), and a `context` that throws is reported to +`onError` and treated as anonymous. + +The evaluation core only accepts string attributes. Values are converted +before they reach it: + +| Attribute value | Sent as | +|---|---| +| string | unchanged | +| finite number, bigint | decimal string (`30` → `"30"`), so numeric operators like `greater_than` work | +| boolean | `"true"` / `"false"` | +| `null`, `undefined`, `NaN`, `Infinity`, objects, arrays, dates, symbols, functions | dropped: a rule on it behaves as if the attribute were missing | + +Convert dates and nested values yourself (`createdAt: user.createdAt.toISOString()`). + +### Startup and shutdown + +`client.connect()` keeps retrying while the Checkgate server is unreachable, so +every adapter waits at most `readyTimeoutMs` (default 5000) for the first flag +set and then follows `onTimeout`: + +| | The server answers in time | It does not | It rejects the SDK key (401/403) | +|---|---|---|---| +| `onTimeout: 'continue'` (default) | starts with live flags | starts anyway, logs a warning, serves the [offline cache](/sdks/nodejs#resilience-offline) if the client has a `storage` adapter with flags, else defaults, and keeps syncing in the background | startup fails with `CheckgateAuthError` | +| `onTimeout: 'fail'` | starts with live flags | startup fails with `CheckgateStartupTimeoutError`; the client is disconnected | startup fails with `CheckgateAuthError` | + +A rejected key always fails startup: it does not fix itself by waiting. On +shutdown each adapter calls `client.disconnect()` exactly once, however many +times close runs. + +## Express + +```js +import express from 'express' +import { CheckgateClient } from '@checkgate/node' +import { checkgateMiddleware, listenWithCheckgate } from '@checkgate/node-integrations/express' + +const client = new CheckgateClient({ + serverUrl: process.env.CHECKGATE_URL, + sdkKey: process.env.CHECKGATE_SDK_KEY, +}) + +const app = express() +app.use(checkgateMiddleware({ + client, + context: (req) => (req.user ? { key: req.user.id, attributes: { plan: req.user.plan } } : null), +})) + +app.get('/checkout', (req, res) => { + res.json({ ui: req.checkgate.isEnabled('new-checkout-flow') ? 'v2' : 'v1' }) +}) + +const { server, close } = await listenWithCheckgate(app, { + client, + port: 8080, + readyTimeoutMs: 5000, + onTimeout: 'continue', +}) + +process.once('SIGTERM', () => close().then(() => process.exit(0))) +``` + +`listenWithCheckgate()` starts Checkgate first (with the policy above), then +listens. Its `close()` stops accepting connections, lets requests in flight +finish (with flags still served), then disconnects the client. It installs no +signal handlers; wire them as shown. If you create the server yourself, use +`startCheckgate(client, options)` before `listen()` and +`stopCheckgate(client)` after `server.close()`, from the same import. + +TypeScript: importing the module adds `checkgate: RequestFlags` to Express's +`Request` type. + +## Fastify + +```js +import Fastify from 'fastify' +import checkgate from '@checkgate/node-integrations/fastify' + +const app = Fastify() + +await app.register(checkgate, { + clientOptions: { serverUrl: process.env.CHECKGATE_URL, sdkKey: process.env.CHECKGATE_SDK_KEY }, + context: (request) => (request.user ? { key: request.user.id, attributes: { plan: request.user.plan } } : null), + readyTimeoutMs: 5000, + onTimeout: 'continue', +}) + +app.get('/checkout', async (request) => ({ + ui: request.checkgate.isEnabled('new-checkout-flow') ? 'v2' : 'v1', +})) + +await app.listen({ port: 8080 }) +process.once('SIGTERM', () => app.close().then(() => process.exit(0))) +``` + +- Pass `clientOptions` and the plugin builds the client, or `client` to use + one you built. Either way it connects while the plugin loads, so + `ready()` / `listen()` wait for it (up to `readyTimeoutMs`), and it + disconnects in `onClose`. +- `fastify.checkgate` is the shared client; `request.checkgate` is the + request's evaluator (assigned in an `onRequest` hook, so every request gets + its own). +- The plugin is not encapsulated: routes in every child plugin see the + decorators. +- `readyTimeoutMs` must be below Fastify's `pluginTimeout` (10 s by default), + otherwise registration fails: Fastify would abort the plugin with its own + timeout first. +- TypeScript: importing the module augments `FastifyInstance` and + `FastifyRequest`. + +## NestJS + +```ts +import { Controller, Get, Module, UseGuards } from '@nestjs/common' +import { NestFactory } from '@nestjs/core' +import { Checkgate, CheckgateModule, RequireFlag, type RequestFlags } from '@checkgate/node-integrations/nestjs' + +@Controller('checkout') +@UseGuards(AuthGuard) // sets req.user +class CheckoutController { + @Get() + page(@Checkgate() flags: RequestFlags) { + return { ui: flags.isEnabled('new-checkout-flow') ? 'v2' : 'v1' } + } + + @Get('beta') + @RequireFlag('checkout-beta') // 404 unless on for this user + beta() { + return { beta: true } + } +} + +@Module({ + imports: [ + CheckgateModule.forRoot({ + clientOptions: { serverUrl: process.env.CHECKGATE_URL!, sdkKey: process.env.CHECKGATE_SDK_KEY }, + context: (req) => (req.user ? { key: req.user.id, attributes: { plan: req.user.plan } } : null), + readyTimeoutMs: 5000, + onTimeout: 'continue', + }), + ], + controllers: [CheckoutController], +}) +class AppModule {} + +const app = await NestFactory.create(AppModule) +app.enableShutdownHooks() // SIGTERM/SIGINT then run onApplicationShutdown +await app.listen(8080) +``` + +- **`CheckgateModule.forRoot(options)`** takes `client` or `clientOptions`, + `context`, `defaultKey`, `onError`, `readyTimeoutMs`, `onTimeout`, + `logger`, and `isGlobal` (default `true`: import it once, in the root + module). **`forRootAsync({ imports, inject, useFactory })`** builds the same + options from other providers, e.g. a config service. +- The client is a singleton under the exported `CHECKGATE_CLIENT` token. + **`CheckgateService`** connects it in `onApplicationBootstrap` (so + `app.listen()` / `app.init()` waits, with the timeout policy) and + disconnects it in `onApplicationShutdown`. That hook runs on `app.close()`; + for SIGTERM/SIGINT call `app.enableShutdownHooks()`. +- **`@Checkgate()`** is a parameter decorator that injects the request's + `RequestFlags`. Outside HTTP handlers (jobs, queue consumers) inject + `CheckgateService` and use `forContext({ key, attributes })`. +- **`@RequireFlag(flag, { status })`** on a method or controller answers 404 + (or 403 with `{ status: 403 }`) unless the flag is on for the request's + user. Several must all pass. It evaluates in a guard, and guards run + global → controller → method, with method decorators applied bottom-up: put + authentication at the controller or global level, or list `@RequireFlag()` + above `@UseGuards(AuthGuard)` on the same method, so `req.user` is set + first. +- **No REQUEST-scoped providers.** A request-scoped provider makes every + provider that injects it request-scoped too, so Nest would re-create those + controllers and services on every request. The module's providers are all + singletons; the per-request evaluator is created by a guard or pipe and + cached on the request object, so a guard and a handler parameter in the + same request share one context. + +### Testing a Nest app + +`CheckgateModule.forTesting(flags)` replaces the client with an in-memory one: +no Checkgate server, no native addon. + +```ts +const moduleRef = await Test.createTestingModule({ + imports: [CheckgateModule.forTesting({ + 'new-checkout-flow': true, + 'banner-color': 'gold', + 'checkout-beta': ({ key }) => key === 'beta-tester', + }, { context: (req) => req.user?.id })], + controllers: [CheckoutController], +}).compile() + +moduleRef.get(CHECKGATE_CLIENT).setFlag('new-checkout-flow', false) +``` + +Or keep your real module and override the token: +`.overrideProvider(CHECKGATE_CLIENT).useValue(createTestClient({ ... }))`. + +## Testing with other frameworks + +`createTestClient(flags)` from `@checkgate/node-integrations` works as the +`client` of any adapter. A value of `true`/`false` is a boolean flag on/off, +any other value means on and serving that value, `null` means off, and a key +that is not listed is a missing flag. A function receives `{ key, attributes }` +for per-user answers. `setFlag(key, value)` changes a flag mid-test; +`disconnectCalls` and `tracked` record what the app did. + +## Limitations + +- Express 4, Fastify 4 and NestJS 11 are not tested and not declared as + supported peers. +- The adapters cover HTTP. For other Nest transports, use + `CheckgateService.forContext()`. diff --git a/docs/sdks/nodejs.md b/docs/sdks/nodejs.md index d0590f89..87eccf8a 100644 --- a/docs/sdks/nodejs.md +++ b/docs/sdks/nodejs.md @@ -188,6 +188,9 @@ stream idle timeout (older servers announce no heartbeat). See ## Usage with Express +For Express, Fastify and NestJS, [`@checkgate/node-integrations`](/sdks/node-frameworks) binds +flags to each request's user and handles startup timeouts and shutdown. Without it: + ```typescript import express from 'express' import { CheckgateClient } from '@checkgate/node' diff --git a/sdks/node-integrations/README.md b/sdks/node-integrations/README.md new file mode 100644 index 00000000..d96045c1 --- /dev/null +++ b/sdks/node-integrations/README.md @@ -0,0 +1,100 @@ +

+ Checkgate +

+ +# @checkgate/node-integrations + +Express, Fastify and NestJS integrations for [`@checkgate/node`](../nodejs/README.md): + +- **Flags bound to each request's user**: `req.checkgate.isEnabled('new-ui')`, + from one shared client, with no network call per request or per evaluation. +- **Startup that does not hang**: waits at most `readyTimeoutMs` for flags, then + continues (cached or default values, still syncing) or fails. A rejected SDK + key always fails. +- **Graceful shutdown**: the client disconnects exactly once. + +```bash +npm install @checkgate/node @checkgate/node-integrations +``` + +| Supported | | +|---|---| +| Node.js | 22.12+ (CI: 22, 24, 26) | +| `@checkgate/node` | `>=0.1.31 <0.3.0` | +| `express` | 5.x | +| `fastify` | 5.x | +| `@nestjs/common`, `@nestjs/core` | 12.x (Express or Fastify platform) | + +## Express + +```js +const { checkgateMiddleware, listenWithCheckgate } = require('@checkgate/node-integrations/express') + +app.use(checkgateMiddleware({ + client, // one CheckgateClient for the process + context: (req) => (req.user ? { key: req.user.id, attributes: { plan: req.user.plan } } : null), +})) +app.get('/', (req, res) => res.json({ v2: req.checkgate.isEnabled('new-ui') })) + +const { close } = await listenWithCheckgate(app, { client, port: 8080, readyTimeoutMs: 5000, onTimeout: 'continue' }) +process.once('SIGTERM', () => close().then(() => process.exit(0))) +``` + +## Fastify + +```js +await fastify.register(require('@checkgate/node-integrations/fastify'), { + clientOptions: { serverUrl: process.env.CHECKGATE_URL, sdkKey: process.env.CHECKGATE_SDK_KEY }, + context: (request) => (request.user ? { key: request.user.id } : null), +}) +fastify.get('/', async (request) => ({ v2: request.checkgate.isEnabled('new-ui') })) +``` + +## NestJS + +```ts +@Module({ imports: [CheckgateModule.forRoot({ clientOptions: { serverUrl, sdkKey }, context: (req) => req.user?.id })] }) +class AppModule {} + +@Get() page(@Checkgate() flags: RequestFlags) { return { v2: flags.isEnabled('new-ui') } } +@Get('beta') @RequireFlag('beta') beta() { /* 404 unless on for this user */ } +``` + +`forRootAsync()`, `CheckgateService`, `forTesting()` and the guard-ordering +rules are in the docs. + +## Notes + +- `context(req)` is called once per request, on the first evaluation, so it + can read `req.user` set by auth middleware that runs later. +- Attributes are coerced for the evaluation core: finite numbers, bigints and + booleans become strings; `null`, `undefined`, objects, arrays, dates and other + values are dropped. Nothing a request supplies can make an evaluation throw. +- `createTestClient(flags)` (from the package root) is an in-memory client for + tests: no server, no native addon. + +Full guide: [Express, Fastify and NestJS](https://checkgate-sh.github.io/checkgate/sdks/node-frameworks). + +## Examples + +Runnable apps in [`examples/`](examples), reading `CHECKGATE_URL` and +`CHECKGATE_SDK_KEY` from the environment: + +```bash +npm ci +CHECKGATE_URL=http://localhost:3000 CHECKGATE_SDK_KEY= node examples/express/server.mjs +CHECKGATE_URL=http://localhost:3000 CHECKGATE_SDK_KEY= node examples/fastify/server.mjs +npx tsc -p examples/nestjs && CHECKGATE_URL=http://localhost:3000 CHECKGATE_SDK_KEY= node examples/nestjs/dist/main.js +``` + +## Development + +The tests run the real `@checkgate/node` client and native addon against the +fake Checkgate server in `sdks/conformance/fault-server.mjs`: + +```bash +(cd ../nodejs && npm ci && npm run build:debug) # needs a Rust toolchain +npm ci +npm run typecheck +npm test +``` From 795a0cd1f679b9880a38c09366f607c05631c446 Mon Sep 17 00:00:00 2001 From: Dennis Paler Date: Sat, 21 Nov 2026 22:10:58 +0800 Subject: [PATCH 11/38] chore: bump-version.sh covers sdks/node-integrations --- scripts/bump-version.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/bump-version.sh b/scripts/bump-version.sh index d1381af9..561404f7 100755 --- a/scripts/bump-version.sh +++ b/scripts/bump-version.sh @@ -29,7 +29,7 @@ SED_INPLACE "s/^version = \".*\"$/version = \"$VERSION\"/" "$ROOT/Cargo.toml" echo " updated Cargo.toml [workspace.package]" # --- JS SDKs --- -for pkg in nodejs web react-native; do +for pkg in nodejs node-integrations web react-native; do FILE="$ROOT/sdks/$pkg/package.json" SED_INPLACE "s/\"version\": \".*\"/\"version\": \"$VERSION\"/" "$FILE" echo " updated sdks/$pkg/package.json" From 45e779f202fb47d908e6fc0a1029059b88650469 Mon Sep 17 00:00:00 2001 From: Dennis Paler Date: Sat, 21 Nov 2026 22:30:01 +0800 Subject: [PATCH 12/38] feat: evaluation playground (server endpoint + dashboard page) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit POST /api/environments/{env}/flags/{key}/evaluate evaluates a flag for a hypothetical user with checkgate_core::explain, over the flags read by the SDK snapshot's own statement and expanded by the same segment code — so it answers what an SDK holding that revision answers. The response carries the value and type, reason, matched rule with its stored index and segment origin, rollout bucket, weighted variant, prerequisite outcomes (with their revisions), the attributes the rules read and which are missing, and the configuration revision. It changes nothing (no audit entry, no impression; the body is neither logged nor stored), takes the environment's read access (project members, read_only tokens; SDK keys refused by the route allowlist; non-members get the same answer whether or not the flag exists), and bounds its input (512-byte key, 100 attributes, 128/1024-byte names/values; non-scalar values are refused, not dropped; 413 over the body limit). The snapshot reader is split so both paths share decoding; the SDK path's statement and work are unchanged. Segment expansion records rule origins through a closure that is a no-op on the SDK path. Dashboard: Playground page (side by side: context on the left, result and explanation on the right; JSON attributes with validation; example context from the flag's rules; reset). Tests: server/tests/playground.rs (all 86 shared vectors through the endpoint, segment tracing, validation, RBAC, no side effects) and dashboard Playground.test.tsx. --- dashboard/src/App.tsx | 2 + dashboard/src/api.ts | 18 + dashboard/src/components/Sidebar.tsx | 2 + dashboard/src/pages/Playground.test.tsx | 109 ++++++ dashboard/src/pages/Playground.tsx | 334 ++++++++++++++++++ dashboard/src/types.ts | 47 +++ docs/.vitepress/config.ts | 1 + docs/api-reference.md | 49 +++ docs/guide/playground.md | 47 +++ server/src/api.rs | 2 + server/src/api/flags.rs | 2 +- server/src/api/playground.rs | 346 +++++++++++++++++++ server/src/api/segments.rs | 63 +++- server/src/stream.rs | 39 ++- server/tests/playground.rs | 439 ++++++++++++++++++++++++ 15 files changed, 1488 insertions(+), 12 deletions(-) create mode 100644 dashboard/src/pages/Playground.test.tsx create mode 100644 dashboard/src/pages/Playground.tsx create mode 100644 docs/guide/playground.md create mode 100644 server/src/api/playground.rs create mode 100644 server/tests/playground.rs diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsx index b2454ee1..139a8212 100644 --- a/dashboard/src/App.tsx +++ b/dashboard/src/App.tsx @@ -6,6 +6,7 @@ import Layout from './components/Layout' import Login from './pages/Login' import Setup from './pages/Setup' import AuditLog from './pages/AuditLog' +import Playground from './pages/Playground' import Dashboard from './pages/Dashboard' import FlagList from './pages/FlagList' import Scheduled from './pages/Scheduled' @@ -106,6 +107,7 @@ export default function App() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/dashboard/src/api.ts b/dashboard/src/api.ts index 05ef23fe..a7d61f63 100644 --- a/dashboard/src/api.ts +++ b/dashboard/src/api.ts @@ -14,6 +14,7 @@ import type { IntegrationDelivery, IntegrationKind, IntegrationTestResult, + PlaygroundEvaluation, ScheduledChange, Segment, SegmentPatch, @@ -98,6 +99,23 @@ export const api = { return request(`/api/environments/${envId}/flags/${encodeURIComponent(key)}`) }, + /** + * Evaluates a flag for a hypothetical user on the server, with the SDK + * engine and the configuration revision SDKs are served. Changes nothing + * and stores nothing. + */ + evaluateFlag( + envId: string, + key: string, + targetingKey: string, + attributes: Record, + ): Promise { + return request(`/api/environments/${envId}/flags/${encodeURIComponent(key)}/evaluate`, { + method: 'POST', + body: JSON.stringify({ targeting_key: targetingKey, attributes }), + }) + }, + createFlag(envId: string, flag: Flag): Promise { return request(`/api/environments/${envId}/flags`, { method: 'POST', diff --git a/dashboard/src/components/Sidebar.tsx b/dashboard/src/components/Sidebar.tsx index fd2b1955..8867fc6e 100644 --- a/dashboard/src/components/Sidebar.tsx +++ b/dashboard/src/components/Sidebar.tsx @@ -8,6 +8,7 @@ import { Globe, ChevronDown, Activity, + FlaskRound, FolderKanban, Plus, Tags, @@ -69,6 +70,7 @@ const NAV_GROUPS: NavGroup[] = [ { to: '/experiments', icon: FlaskConical, label: 'Experiments' }, { to: '/exposure', icon: PieChart, label: 'Exposure' }, { to: '/impressions', icon: Activity, label: 'Impressions' }, + { to: '/playground', icon: FlaskRound, label: 'Playground' }, { to: '/audit', icon: History, label: 'Audit Log' }, { to: '/webhooks', icon: Webhook, label: 'Webhooks', adminOnly: true }, { to: '/integrations', icon: MessageSquare, label: 'Chat Alerts', adminOnly: true }, diff --git a/dashboard/src/pages/Playground.test.tsx b/dashboard/src/pages/Playground.test.tsx new file mode 100644 index 00000000..53db7a0c --- /dev/null +++ b/dashboard/src/pages/Playground.test.tsx @@ -0,0 +1,109 @@ +import { render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { describe, it, expect, vi, beforeEach } from 'vitest' +import Playground, { exampleContext, parseAttributes } from './Playground' +import { api } from '../api' +import type { Flag, PlaygroundEvaluation } from '../types' + +vi.mock('../api', () => ({ + api: { listFlags: vi.fn(), evaluateFlag: vi.fn() }, +})) + +const ENV = { id: 'env-1', name: 'Development', color: '#4f46e5' } +const ENV_CTX = { environments: [ENV], activeEnv: ENV, setActiveEnv: vi.fn() } +vi.mock('../context/EnvironmentContext', () => ({ useEnvironment: () => ENV_CTX })) + +const FLAG: Flag = { + key: 'new-checkout', + is_enabled: true, + rollout_percentage: 30, + description: null, + rules: [ + { attribute: 'plan', operator: 'equals', values: ['pro', 'team'] }, + { attribute: 'country', operator: 'equals', values: ['PH'] }, + ], + flag_type: 'boolean', +} + +const RESULT: PlaygroundEvaluation = { + environment_id: 'env-1', + flag_key: 'new-checkout', + flag_type: 'boolean', + revision: 17, + enabled: true, + value: true, + reason: 'TARGETING_MATCH', + matched_rule: { + rule: { attribute: 'plan', operator: 'equals', values: ['pro', 'team'] }, + source_index: 0, + }, + prerequisites: [], + referenced_attributes: ['country', 'plan'], + missing_attributes: ['country'], +} + +describe('parseAttributes', () => { + it('accepts scalars and an empty editor', () => { + expect(parseAttributes('')).toEqual({ attributes: {} }) + expect(parseAttributes('{"plan":"pro","age":30,"beta":true}')).toEqual({ + attributes: { plan: 'pro', age: 30, beta: true }, + }) + }) + it('refuses invalid JSON, non-objects, nested values and too many attributes', () => { + for (const bad of ['{', '[1]', '"x"', 'null', '{"o":{"a":1}}', '{"n":null}', '{"l":[1]}']) { + expect(parseAttributes(bad).error, bad).toBeTruthy() + } + const many = JSON.stringify(Object.fromEntries(Array.from({ length: 101 }, (_, i) => [`a${i}`, 'v']))) + expect(parseAttributes(many).error).toMatch(/At most 100/) + }) +}) + +describe('exampleContext', () => { + it('uses the first value of each rule attribute', () => { + expect(exampleContext(FLAG)).toEqual({ plan: 'pro', country: 'PH' }) + expect(exampleContext(undefined)).toEqual({}) + }) +}) + +describe('Playground', () => { + beforeEach(() => { + vi.clearAllMocks() + vi.mocked(api.listFlags).mockResolvedValue([FLAG]) + vi.mocked(api.evaluateFlag).mockResolvedValue(RESULT) + }) + + it('evaluates on the server and explains the result', async () => { + const user = userEvent.setup() + render() + await waitFor(() => expect(screen.getByLabelText('Flag')).toHaveValue('new-checkout')) + await user.click(screen.getByRole('button', { name: /Example from this flag/ })) + await user.click(screen.getByRole('button', { name: /Evaluate/ })) + expect(api.evaluateFlag).toHaveBeenCalledWith('env-1', 'new-checkout', 'user-123', { plan: 'pro', country: 'PH' }) + expect(await screen.findByTestId('result-reason')).toHaveTextContent('TARGETING_MATCH') + expect(screen.getByTestId('result-state')).toHaveTextContent('ENABLED') + expect(screen.getByText(/#1: plan equals pro, team/)).toBeInTheDocument() + expect(screen.getByText('17')).toBeInTheDocument() + }) + + it('blocks evaluation while the attributes are invalid', async () => { + const user = userEvent.setup() + render() + await waitFor(() => expect(screen.getByLabelText('Flag')).toHaveValue('new-checkout')) + const editor = screen.getByLabelText('Attributes') + await user.clear(editor) + await user.type(editor, '{{"o": [1]}') + expect(screen.getByRole('alert')).toBeInTheDocument() + expect(screen.getByRole('button', { name: /Evaluate/ })).toBeDisabled() + expect(api.evaluateFlag).not.toHaveBeenCalled() + }) + + it('shows server errors and renders untrusted text as text', async () => { + vi.mocked(api.evaluateFlag).mockRejectedValue(new Error('')) + const user = userEvent.setup() + const { container } = render() + await waitFor(() => expect(screen.getByLabelText('Flag')).toHaveValue('new-checkout')) + await user.click(screen.getByRole('button', { name: /Evaluate/ })) + expect(await screen.findByRole('alert')).toHaveTextContent('') + expect(container.querySelector('img')).toBeNull() + }) +}) diff --git a/dashboard/src/pages/Playground.tsx b/dashboard/src/pages/Playground.tsx new file mode 100644 index 00000000..88609e90 --- /dev/null +++ b/dashboard/src/pages/Playground.tsx @@ -0,0 +1,334 @@ +import { useEffect, useMemo, useState } from 'react' +import { FlaskRound, Play, RotateCcw, AlertTriangle } from 'lucide-react' +import { api } from '../api' +import type { EvaluationReason, Flag, FlagValue, PlaygroundEvaluation, TargetingRule } from '../types' +import { useEnvironment } from '../context/EnvironmentContext' + +// --------------------------------------------------------------------------- +// Evaluation playground: "what would an SDK answer for this user?" +// +// The evaluation runs on the server with the SDK engine and the configuration +// revision SDKs are served. Nothing here re-implements targeting: this page +// only collects a context and displays the explanation. Nothing is stored. +// --------------------------------------------------------------------------- + +const MAX_ATTRIBUTES = 100 + +const REASON_TEXT: Record = { + DISABLED: 'The flag is switched off.', + PREREQUISITE_FAILED: 'A prerequisite flag is not satisfied, so the flag resolves as off.', + TARGETING_MATCH: 'A targeting rule matched.', + ROLLOUT_EXCLUDED: 'The user is outside the percentage rollout.', + SPLIT: 'Hashing the user key decided: inside a partial rollout, or a weighted variant.', + DEFAULT: 'The flag has rules, none matched: the default value.', + STATIC: 'No rules, partial rollout or variants: every user gets this value.', +} + +type Attributes = Record + +/** Parses the attributes editor; returns an error message instead of throwing. */ +export function parseAttributes(text: string): { attributes?: Attributes; error?: string } { + if (text.trim() === '') return { attributes: {} } + let parsed: unknown + try { + parsed = JSON.parse(text) + } catch { + return { error: 'Attributes must be valid JSON, e.g. {"plan": "pro"}.' } + } + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + return { error: 'Attributes must be a JSON object.' } + } + const entries = Object.entries(parsed as Record) + if (entries.length > MAX_ATTRIBUTES) return { error: `At most ${MAX_ATTRIBUTES} attributes.` } + const attributes: Attributes = {} + for (const [name, value] of entries) { + if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') { + return { error: `"${name}" must be a string, number or boolean.` } + } + attributes[name] = value + } + return { attributes } +} + +/** An example context that exercises each of the flag's own rules. */ +export function exampleContext(flag: Flag | undefined): Attributes { + const out: Attributes = {} + for (const rule of flag?.rules ?? []) { + if (rule.attribute && rule.values?.length && !(rule.attribute in out)) { + out[rule.attribute] = rule.values[0] + } + } + return out +} + +function describeRule(rule: TargetingRule): string { + if (rule.segment_key) return `in segment “${rule.segment_key}”` + return `${rule.attribute} ${rule.operator.replace(/_/g, ' ')} ${rule.values.join(', ')}` +} + +function formatValue(value: FlagValue | undefined): string { + if (value === undefined) return '—' + return typeof value === 'string' ? JSON.stringify(value) : JSON.stringify(value, null, 2) +} + +function valueType(value: FlagValue): string { + if (value === null) return 'null' + if (Array.isArray(value)) return 'array' + return typeof value +} + +function Row({ label, children }: { label: string; children: React.ReactNode }) { + return ( +
+ {label} +
{children}
+
+ ) +} + +export default function Playground() { + const { activeEnv } = useEnvironment() + const [flags, setFlags] = useState([]) + const [flagKey, setFlagKey] = useState('') + const [targetingKey, setTargetingKey] = useState('user-123') + const [attributesText, setAttributesText] = useState('{}') + const [result, setResult] = useState(null) + const [error, setError] = useState(null) + const [loading, setLoading] = useState(false) + + useEffect(() => { + setFlags([]) + setFlagKey('') + setResult(null) + if (!activeEnv) return + let cancelled = false + api + .listFlags(activeEnv.id) + .then(list => { + if (cancelled) return + setFlags(list) + setFlagKey(list[0]?.key ?? '') + }) + .catch(e => !cancelled && setError(e instanceof Error ? e.message : String(e))) + return () => { + cancelled = true + } + }, [activeEnv]) + + const flag = useMemo(() => flags.find(f => f.key === flagKey), [flags, flagKey]) + const parsed = useMemo(() => parseAttributes(attributesText), [attributesText]) + + const reset = () => { + setTargetingKey('user-123') + setAttributesText('{}') + setResult(null) + setError(null) + } + + const evaluate = async () => { + if (!activeEnv || !flagKey || parsed.error || !parsed.attributes) return + setLoading(true) + setError(null) + try { + setResult(await api.evaluateFlag(activeEnv.id, flagKey, targetingKey, parsed.attributes)) + } catch (e) { + setResult(null) + setError(e instanceof Error ? e.message : String(e)) + } finally { + setLoading(false) + } + } + + const inputClass = + 'w-full bg-white border border-gray-100 rounded-xl px-4 py-2.5 text-sm text-gray-900 focus:outline-none focus:ring-4 focus:ring-brand-500/10 focus:border-brand-500/30 transition-all' + + return ( +
+
+
+
+ +
+
+

Evaluation Playground

+

+ See what an SDK would answer for a user in {activeEnv?.name ?? '…'}, and why. + Evaluated on the server with the SDK engine; nothing is changed or stored. +

+
+
+
+ +
+ {/* Left: context */} +
+ + + + +