@fireweaveai/server-sdk 2.2.1-staging.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +263 -0
  2. package/dist/application/client.d.ts +92 -0
  3. package/dist/application/client.d.ts.map +1 -0
  4. package/dist/application/client.js +156 -0
  5. package/dist/application/client.js.map +1 -0
  6. package/dist/application/mode.d.ts +71 -0
  7. package/dist/application/mode.d.ts.map +1 -0
  8. package/dist/application/mode.js +72 -0
  9. package/dist/application/mode.js.map +1 -0
  10. package/dist/application/ports.d.ts +95 -0
  11. package/dist/application/ports.d.ts.map +1 -0
  12. package/dist/application/ports.js +2 -0
  13. package/dist/application/ports.js.map +1 -0
  14. package/dist/application/runtime.d.ts +102 -0
  15. package/dist/application/runtime.d.ts.map +1 -0
  16. package/dist/application/runtime.js +342 -0
  17. package/dist/application/runtime.js.map +1 -0
  18. package/dist/domain/context.d.ts +68 -0
  19. package/dist/domain/context.d.ts.map +1 -0
  20. package/dist/domain/context.js +85 -0
  21. package/dist/domain/context.js.map +1 -0
  22. package/dist/domain/errors.d.ts +43 -0
  23. package/dist/domain/errors.d.ts.map +1 -0
  24. package/dist/domain/errors.js +64 -0
  25. package/dist/domain/errors.js.map +1 -0
  26. package/dist/domain/target.d.ts +3 -0
  27. package/dist/domain/target.d.ts.map +1 -0
  28. package/dist/domain/target.js +2 -0
  29. package/dist/domain/target.js.map +1 -0
  30. package/dist/domain/types.d.ts +108 -0
  31. package/dist/domain/types.d.ts.map +1 -0
  32. package/dist/domain/types.js +2 -0
  33. package/dist/domain/types.js.map +1 -0
  34. package/dist/domain/validation.d.ts +125 -0
  35. package/dist/domain/validation.d.ts.map +1 -0
  36. package/dist/domain/validation.js +347 -0
  37. package/dist/domain/validation.js.map +1 -0
  38. package/dist/index.d.ts +35 -0
  39. package/dist/index.d.ts.map +1 -0
  40. package/dist/index.js +23 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/infrastructure/adapters/inmemory.d.ts +78 -0
  43. package/dist/infrastructure/adapters/inmemory.d.ts.map +1 -0
  44. package/dist/infrastructure/adapters/inmemory.js +148 -0
  45. package/dist/infrastructure/adapters/inmemory.js.map +1 -0
  46. package/dist/infrastructure/adapters/local.d.ts +109 -0
  47. package/dist/infrastructure/adapters/local.d.ts.map +1 -0
  48. package/dist/infrastructure/adapters/local.js +102 -0
  49. package/dist/infrastructure/adapters/local.js.map +1 -0
  50. package/dist/infrastructure/adapters/remote.d.ts +75 -0
  51. package/dist/infrastructure/adapters/remote.d.ts.map +1 -0
  52. package/dist/infrastructure/adapters/remote.js +361 -0
  53. package/dist/infrastructure/adapters/remote.js.map +1 -0
  54. package/dist/infrastructure/hosts.d.ts +19 -0
  55. package/dist/infrastructure/hosts.d.ts.map +1 -0
  56. package/dist/infrastructure/hosts.js +68 -0
  57. package/dist/infrastructure/hosts.js.map +1 -0
  58. package/package.json +56 -0
@@ -0,0 +1,72 @@
1
+ /**
2
+ * initFireweave — the single SDK entry point (spec/modes.md).
3
+ *
4
+ * `mode` is required and never inferred: a missing or mistyped credential
5
+ * must fail loudly at boot, not silently fall back to local evaluation —
6
+ * that failure mode looks like a green boot and a feature that never ramps.
7
+ * This function's only job is to validate the initialisation-time contract
8
+ * and select the matching adapter; nothing downstream branches on mode again
9
+ * (spec/modes.md "Behaviour per mode" — both adapters implement the same
10
+ * BackendAdapter port, so FireweaveClient / FireweaveRuntime stay mode-blind).
11
+ *
12
+ * Initialisation fails loudly (throws); reads on the returned client never do
13
+ * (spec/control-points.md "initialise is the exception"). The validation
14
+ * itself lives in `validateInitOptions` (validation.ts), which returns
15
+ * `Validated<T>` like every other validator — this function is what converts
16
+ * a failed `Validated` into the throw spec/modes.md requires.
17
+ */
18
+ import { FireweaveClient } from './client.js';
19
+ import { FireweaveRuntime } from './runtime.js';
20
+ import { FireweaveLocalAdapter } from '../infrastructure/adapters/local.js';
21
+ import { FireweaveRemoteAdapter } from '../infrastructure/adapters/remote.js';
22
+ import { validateInitOptions } from '../domain/validation.js';
23
+ async function initLocal(options) {
24
+ const local = options.local ?? {};
25
+ const adapter = new FireweaveLocalAdapter({
26
+ devFlags: local.controlPoints ?? {},
27
+ ...(local.log !== undefined ? { log: local.log } : {}),
28
+ });
29
+ const runtime = new FireweaveRuntime(adapter);
30
+ await runtime.initialize();
31
+ return new FireweaveClient(runtime);
32
+ }
33
+ async function initRemote(options) {
34
+ const { apiKey, apiUrl, allowedHosts, fetch } = options;
35
+ const adapter = new FireweaveRemoteAdapter({
36
+ apiKey,
37
+ apiUrl,
38
+ ...(allowedHosts !== undefined ? { allowedHosts } : {}),
39
+ ...(fetch !== undefined ? { fetch } : {}),
40
+ });
41
+ const runtime = new FireweaveRuntime(adapter, {
42
+ // The same host the adapter will actually call, gated through the
43
+ // canonical allowlist (hosts.ts) before any network I/O happens.
44
+ host: apiUrl,
45
+ ...(allowedHosts !== undefined ? { allowedHosts } : {}),
46
+ });
47
+ await runtime.initialize();
48
+ return new FireweaveClient(runtime);
49
+ }
50
+ /**
51
+ * Build the adapter matching `options.mode` and bring a {@link FireweaveClient}
52
+ * to READY.
53
+ *
54
+ * Throws {@link FireweaveError} (kind `Configuration`) for every row of the
55
+ * initialisation-validation table (spec/modes.md):
56
+ * - `mode` absent or unrecognised
57
+ * - `mode: 'remote'` with `apiKey` or `apiUrl` missing/blank
58
+ * - `apiUrl` fails the host allowlist
59
+ * - `mode: 'local'` with credentials supplied
60
+ *
61
+ * The first, second and fourth rows are `validateInitOptions`'s job; the
62
+ * third is validated downstream, when `runtime.initialize()` brings the
63
+ * adapter up (`FireweaveRuntime`'s own config validation, `hosts.ts`).
64
+ */
65
+ export async function initFireweave(options) {
66
+ const validated = validateInitOptions(options);
67
+ if (!validated.ok)
68
+ throw validated.error;
69
+ const validOptions = validated.value;
70
+ return validOptions.mode === 'local' ? initLocal(validOptions) : initRemote(validOptions);
71
+ }
72
+ //# sourceMappingURL=mode.js.map
@@ -0,0 +1 @@
1
+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CAAC,CAAC,CAAC,EAAE,CAAC;KAC1C,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,IAAI,gBAAgB,CAAC,OAAO,EAAE;QAC5C,kEAAkE;QAClE,iEAAiE;QACjE,IAAI,EAAE,MAAM;QACZ,GAAG,CAAC,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACxD,CAAC,CAAC;IACH,MAAM,OAAO,CAAC,UAAU,EAAE,CAAC;IAC3B,OAAO,IAAI,eAAe,CAAC,OAAO,CAAC,CAAC;AACtC,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,OAA6B;IAC/D,MAAM,SAAS,GAAG,mBAAmB,CAAC,OAAO,CAAC,CAAC;IAC/C,IAAI,CAAC,SAAS,CAAC,EAAE;QAAE,MAAM,SAAS,CAAC,KAAK,CAAC;IACzC,MAAM,YAAY,GAAG,SAAS,CAAC,KAAK,CAAC;IACrC,OAAO,YAAY,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;AAC5F,CAAC"}
@@ -0,0 +1,95 @@
1
+ import type { FireweaveError } from '../domain/errors.js';
2
+ import type { CanonicalContext, DecisionReason, Exposure, FlagValueType, JsonValue, Signal } from '../domain/types.js';
3
+ import type { TargetKind } from '../domain/target.js';
4
+ export interface RegisterTargetOptions {
5
+ /** Defaults to 'user'. */
6
+ kind?: TargetKind;
7
+ /** Durable targeting facts: plan, beta membership, region, device model. */
8
+ properties?: Record<string, JsonValue>;
9
+ /** Client-declared environment (production, staging, …). */
10
+ environment?: string;
11
+ signal?: AbortSignal;
12
+ }
13
+ export interface RegisterTargetResult {
14
+ /**
15
+ * `false` means the target was NOT registered — rules that depend on its
16
+ * properties will not match until a later attempt succeeds. Callers in a
17
+ * login path normally ignore this; a careful caller logs it, because a
18
+ * silently unregistered target is exactly how targeting rules end up
19
+ * matching nobody.
20
+ */
21
+ readonly ok: boolean;
22
+ readonly error?: FireweaveError;
23
+ }
24
+ /** Result of a backend flag resolution (success path; faults throw FireweaveError). */
25
+ export interface AdapterResolution {
26
+ found: boolean;
27
+ /** Flag enabled state; false ⇒ DISABLED reason with the flag's stored value. */
28
+ enabled?: boolean;
29
+ value?: JsonValue;
30
+ variant?: string;
31
+ /** Declared flag type when known (in-memory fixtures); adapters may omit. */
32
+ flagType?: FlagValueType | 'integer' | 'float';
33
+ /**
34
+ * Adapter-suggested reason override (e.g. SPLIT, STALE) on a `found: true`
35
+ * resolution. On a `found: false` miss, `reason: 'DEFAULT'` instead signals
36
+ * the runtime to return the caller's default with reason `DEFAULT` — not an
37
+ * error — per local mode's unknown-key row (spec/modes.md; see
38
+ * FireweaveLocalAdapter.resolve).
39
+ */
40
+ reason?: DecisionReason;
41
+ /** Vendor reason code (e.g. "condition_match"). */
42
+ reasonCode?: string;
43
+ /** Vendor condition index when the vendor reports one. */
44
+ conditionIndex?: number;
45
+ /** Flag definition version. */
46
+ version?: number;
47
+ /** Vendor-side numeric flag id. */
48
+ vendorFlagId?: number;
49
+ /** Optional flag payload (object or pre-serialized JSON string). */
50
+ payload?: JsonValue;
51
+ /** True when the /flags response reported quota limiting. */
52
+ quotaLimited?: boolean;
53
+ /** True when served from a stale/last-good cache. */
54
+ fromCache?: boolean;
55
+ }
56
+ export interface ResolveOptions {
57
+ signal?: AbortSignal;
58
+ }
59
+ export interface AdapterRuntimeFeatures {
60
+ remoteEvaluation?: boolean;
61
+ localEvaluation?: boolean;
62
+ localOnly?: boolean;
63
+ exposureEmission?: boolean;
64
+ sideEffectFreeReads?: boolean;
65
+ groupAnalytics?: boolean;
66
+ }
67
+ /**
68
+ * Backend adapter boundary (docs/architecture.md §layers). Adapters translate
69
+ * canonical requests to vendor protocols; they never see OpenFeature types.
70
+ */
71
+ export interface BackendAdapter {
72
+ /** Third-party adapters use 'other'; the vendor is fw-server's concern. */
73
+ readonly name: 'inmemory' | 'fireweave' | 'other';
74
+ /** Bring the backend to a usable state. Reject with FireweaveError on failure. */
75
+ initialize(signal?: AbortSignal): Promise<void>;
76
+ /** Resolve one flag. Throws FireweaveError for transport/auth/parse faults. */
77
+ resolve(flagKey: string, context: CanonicalContext, options?: ResolveOptions): Promise<AdapterResolution>;
78
+ /**
79
+ * Register a user or device so rules can target its durable properties
80
+ * (optional capability). Resolves with `ok: false` rather than throwing —
81
+ * registration sits in login paths and must not break sign-in.
82
+ */
83
+ registerTarget?(targetingKey: string, options?: RegisterTargetOptions): Promise<RegisterTargetResult>;
84
+ /** Record an exposure event (optional capability). */
85
+ recordExposure?(exposure: Exposure): void;
86
+ /** Deliver a telemetry signal to the backend sink (optional capability, ruling 17). */
87
+ recordSignal?(signal: Signal): void;
88
+ /** Flush buffered telemetry/exposures. */
89
+ flush?(): Promise<void>;
90
+ /** Release resources; must be idempotent. */
91
+ shutdown(): Promise<void>;
92
+ /** Runtime feature capabilities contributed by this adapter. */
93
+ features(): AdapterRuntimeFeatures;
94
+ }
95
+ //# sourceMappingURL=ports.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ports.d.ts","sourceRoot":"","sources":["../../src/application/ports.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,QAAQ,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACvH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEtD,MAAM,WAAW,qBAAqB;IACpC,0BAA0B;IAC1B,IAAI,CAAC,EAAE,UAAU,CAAC;IAClB,4EAA4E;IAC5E,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;IACvC,4DAA4D;IAC5D,WAAW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G;AACH,MAAM,WAAW,cAAc;IAC7B,2EAA2E;IAC3E,QAAQ,CAAC,IAAI,EAAE,UAAU,GAAG,WAAW,GAAG,OAAO,CAAC;IAClD,kFAAkF;IAClF,UAAU,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAChD,+EAA+E;IAC/E,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;IAC1G;;;;OAIG;IACH,cAAc,CAAC,CACb,YAAY,EAAE,MAAM,EACpB,OAAO,CAAC,EAAE,qBAAqB,GAC9B,OAAO,CAAC,oBAAoB,CAAC,CAAC;IACjC,sDAAsD;IACtD,cAAc,CAAC,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC1C,uFAAuF;IACvF,YAAY,CAAC,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACpC,0CAA0C;IAC1C,KAAK,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACxB,6CAA6C;IAC7C,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B,gEAAgE;IAChE,QAAQ,IAAI,sBAAsB,CAAC;CACpC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ports.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ports.js","sourceRoot":"","sources":["../../src/application/ports.ts"],"names":[],"mappings":""}
@@ -0,0 +1,102 @@
1
+ import { type ContextInput, type ContextLimits } from '../domain/context.js';
2
+ import { type ExpectedFlagType } from '../domain/validation.js';
3
+ import type { BackendAdapter, RegisterTargetOptions, RegisterTargetResult } from './ports.js';
4
+ import type { CanonicalContext, Decision, JsonValue, LifecycleState } from '../domain/types.js';
5
+ export type { ExpectedFlagType } from '../domain/validation.js';
6
+ export interface FireweaveRuntimeConfig {
7
+ /**
8
+ * Fireweave project/runtime key (`project-api-key_…`). Adapters may also read
9
+ * it from their own options.
10
+ */
11
+ projectApiKey?: string;
12
+ /** Backend host (must be http(s) and pass the allowlist). */
13
+ host?: string;
14
+ /**
15
+ * SSRF allowlist: hostnames the SDK may talk to. Empty/undefined ⇒ the
16
+ * canonical Fireweave default allowlist + loopback (DEFAULT_ALLOWED_HOSTS).
17
+ * Custom/self-hosted endpoints must be listed explicitly; ['*'] opts out.
18
+ */
19
+ allowedHosts?: readonly string[];
20
+ /** Require targetingKey on every evaluation. */
21
+ requireTargetingKey?: boolean;
22
+ /** Context bound overrides (defaults are the ratified spec bounds). */
23
+ limits?: Partial<ContextLimits>;
24
+ /** Additional reserved attribute keys. */
25
+ reservedAttributeKeys?: readonly string[];
26
+ /** Shutdown flush deadline (ms). Default DEFAULT_SHUTDOWN_TIMEOUT_MS. */
27
+ shutdownTimeoutMs?: number;
28
+ }
29
+ /** Default bound on shutdown/flush (matches capabilities.get()). */
30
+ export declare const DEFAULT_SHUTDOWN_TIMEOUT_MS = 10000;
31
+ export interface EvaluateOptions {
32
+ /** Attach flag payload as fireweave.payload metadata (sorted-key JSON string). */
33
+ includePayload?: boolean;
34
+ /**
35
+ * When true, emit a Fireweave-owned exposure for a successful evaluation
36
+ * (H-4 / ADR-0001 §23 errata / ruling 20). Default `false` — phase-one
37
+ * evaluate is side-effect-free. Vendor `$feature_flag_called` stays
38
+ * suppressed on the local snapshot path (RB-2); Fireweave owns emission
39
+ * and dedup when opted in.
40
+ */
41
+ sendExposure?: boolean;
42
+ signal?: AbortSignal;
43
+ }
44
+ /** JSON stringify with deterministic (sorted) key order at every level. */
45
+ export declare function stableStringify(value: JsonValue): string;
46
+ export declare class FireweaveRuntime {
47
+ readonly adapter: BackendAdapter;
48
+ readonly config: FireweaveRuntimeConfig;
49
+ private readonly contextPolicy;
50
+ private state;
51
+ private globalContext;
52
+ private clientContext;
53
+ private initPromise;
54
+ private readonly stateListeners;
55
+ /** Dedup window for evaluate/OF-path exposures (cleared on flush / shutdown). */
56
+ private readonly evaluateExposureSeen;
57
+ constructor(adapter: BackendAdapter, config?: FireweaveRuntimeConfig);
58
+ /** Clear evaluate-path exposure dedup (M-2 / clear-on-flush lifecycle). */
59
+ clearEvaluateExposureDedup(): void;
60
+ getState(): LifecycleState;
61
+ onStateChange(listener: (state: LifecycleState) => void): void;
62
+ private setState;
63
+ /** Mark definitions/cache staleness (adapter-driven). */
64
+ markStale(): void;
65
+ setGlobalContext(context: ContextInput | undefined): void;
66
+ setClientContext(context: ContextInput | undefined): void;
67
+ /**
68
+ * Initialize the runtime: validate config, then bring the adapter up.
69
+ * Rejects with FireweaveError; Configuration errors put the runtime in FATAL.
70
+ */
71
+ initialize(signal?: AbortSignal): Promise<void>;
72
+ shutdown(): Promise<void>;
73
+ /** Canonicalize + validate the merged context (throws FireweaveError). */
74
+ resolveContext(invocationContext: ContextInput | undefined): CanonicalContext;
75
+ /**
76
+ * Evaluate a flag to a canonical Decision. Never throws.
77
+ *
78
+ * Validates in the fixed order spec/control-points.md "Validation, before
79
+ * any I/O" names, stopping at the first failure: (1) key, (2) default vs
80
+ * type, (3) context, (4) lifecycle. Only once all four pass does this
81
+ * reach the adapter (the one I/O call in this method).
82
+ */
83
+ evaluate(flagKey: string, expectedType: ExpectedFlagType, defaultValue: JsonValue, invocationContext?: ContextInput, options?: EvaluateOptions): Promise<Decision>;
84
+ /**
85
+ * Register a user or device so flag rules can target its DURABLE properties.
86
+ *
87
+ * Call once per login / device provisioning with the facts that outlive a
88
+ * request (plan, beta membership, region, device model), then send the same
89
+ * `targetingKey` on evaluation. Per-request context attributes still override
90
+ * the registered properties for a single evaluation — the two identity paths
91
+ * compose (spec/remote-protocol.md § Two identity paths).
92
+ *
93
+ * Resolves with `ok: false` instead of throwing: this runs in sign-in paths.
94
+ * Adapters without the capability (in-memory, local dev) report
95
+ * `Unsupported` so a dev harness does not silently look registered.
96
+ */
97
+ registerTarget(targetingKey: string, options?: RegisterTargetOptions): Promise<RegisterTargetResult>;
98
+ private emitEvaluateExposure;
99
+ private lifecycleError;
100
+ private errorDecision;
101
+ }
102
+ //# sourceMappingURL=runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../src/application/runtime.ts"],"names":[],"mappings":"AAQA,OAAO,EAIL,KAAK,YAAY,EACjB,KAAK,aAAa,EAEnB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAKL,KAAK,gBAAgB,EACtB,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAEV,cAAc,EACd,qBAAqB,EACrB,oBAAoB,EACrB,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EACV,gBAAgB,EAChB,QAAQ,EAER,SAAS,EACT,cAAc,EACf,MAAM,oBAAoB,CAAC;AAE5B,YAAY,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAEhE,MAAM,WAAW,sBAAsB;IACrC;;;OAGG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,6DAA6D;IAC7D,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACjC,gDAAgD;IAChD,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,uEAAuE;IACvE,MAAM,CAAC,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC;IAChC,0CAA0C;IAC1C,qBAAqB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,yEAAyE;IACzE,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,oEAAoE;AACpE,eAAO,MAAM,2BAA2B,QAAQ,CAAC;AAEjD,MAAM,WAAW,eAAe;IAC9B,kFAAkF;IAClF,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB;;;;;;OAMG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAiBD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E,eAAoB,GAC5B,OAAO,CAAC,QAAQ,CAAC;IAmGpB;;;;;;;;;;;;OAYG;IACG,cAAc,CAClB,YAAY,EAAE,MAAM,EACpB,OAAO,GAAE,qBAA0B,GAClC,OAAO,CAAC,oBAAoB,CAAC;IAShC,OAAO,CAAC,oBAAoB;IAmB5B,OAAO,CAAC,cAAc;IAgBtB,OAAO,CAAC,aAAa;CAetB"}
@@ -0,0 +1,342 @@
1
+ /**
2
+ * FireweaveRuntime: shared engine behind the OpenFeature provider and the
3
+ * FireweaveClient extensions. Owns lifecycle state machine, config validation,
4
+ * context policy, and decision construction. Defaults never throw: evaluation
5
+ * always returns a Decision.
6
+ */
7
+ import { FireweaveError, isFireweaveError } from '../domain/errors.js';
8
+ import { assertHostAllowed } from '../infrastructure/hosts.js';
9
+ import { DEFAULT_CONTEXT_LIMITS, DEFAULT_RESERVED_ATTRIBUTE_KEYS, mergeContexts, } from '../domain/context.js';
10
+ import { matchesExpectedType, validateContext, validateControlPointKey, validateDefaultValue, } from '../domain/validation.js';
11
+ /** Default bound on shutdown/flush (matches capabilities.get()). */
12
+ export const DEFAULT_SHUTDOWN_TIMEOUT_MS = 10000;
13
+ function validateConfig(config) {
14
+ if (config.host !== undefined) {
15
+ // Allowlist is ON by default (release-blockers H-1): undefined/empty
16
+ // allowedHosts falls back to the canonical Fireweave + loopback list.
17
+ assertHostAllowed(config.host, config.allowedHosts);
18
+ }
19
+ if (config.limits !== undefined) {
20
+ for (const value of Object.values(config.limits)) {
21
+ if (value !== undefined && (!Number.isInteger(value) || value <= 0)) {
22
+ throw new FireweaveError('Configuration');
23
+ }
24
+ }
25
+ }
26
+ }
27
+ /** JSON stringify with deterministic (sorted) key order at every level. */
28
+ export function stableStringify(value) {
29
+ if (value === null || typeof value !== 'object')
30
+ return JSON.stringify(value);
31
+ if (Array.isArray(value))
32
+ return `[${value.map((v) => stableStringify(v)).join(',')}]`;
33
+ const keys = Object.keys(value).sort();
34
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(',')}}`;
35
+ }
36
+ export class FireweaveRuntime {
37
+ adapter;
38
+ config;
39
+ contextPolicy;
40
+ state = 'UNINITIALIZED';
41
+ globalContext;
42
+ clientContext;
43
+ initPromise;
44
+ stateListeners = new Set();
45
+ /** Dedup window for evaluate/OF-path exposures (cleared on flush / shutdown). */
46
+ evaluateExposureSeen = new Set();
47
+ constructor(adapter, config = {}) {
48
+ this.adapter = adapter;
49
+ this.config = { ...config };
50
+ const limits = { ...DEFAULT_CONTEXT_LIMITS, ...(config.limits ?? {}) };
51
+ this.contextPolicy = {
52
+ limits,
53
+ reservedAttributeKeys: [
54
+ ...DEFAULT_RESERVED_ATTRIBUTE_KEYS,
55
+ ...(config.reservedAttributeKeys ?? []),
56
+ ],
57
+ requireTargetingKey: config.requireTargetingKey ?? false,
58
+ };
59
+ }
60
+ /** Clear evaluate-path exposure dedup (M-2 / clear-on-flush lifecycle). */
61
+ clearEvaluateExposureDedup() {
62
+ this.evaluateExposureSeen.clear();
63
+ }
64
+ getState() {
65
+ return this.state;
66
+ }
67
+ onStateChange(listener) {
68
+ this.stateListeners.add(listener);
69
+ }
70
+ setState(next) {
71
+ this.state = next;
72
+ for (const listener of this.stateListeners)
73
+ listener(next);
74
+ }
75
+ /** Mark definitions/cache staleness (adapter-driven). */
76
+ markStale() {
77
+ if (this.state === 'READY')
78
+ this.setState('STALE');
79
+ }
80
+ setGlobalContext(context) {
81
+ this.globalContext = context;
82
+ }
83
+ setClientContext(context) {
84
+ this.clientContext = context;
85
+ }
86
+ /**
87
+ * Initialize the runtime: validate config, then bring the adapter up.
88
+ * Rejects with FireweaveError; Configuration errors put the runtime in FATAL.
89
+ */
90
+ async initialize(signal) {
91
+ if (this.state === 'SHUTDOWN') {
92
+ throw new FireweaveError('AlreadyClosed');
93
+ }
94
+ if (this.state === 'READY')
95
+ return;
96
+ if (this.initPromise !== undefined)
97
+ return this.initPromise;
98
+ this.initPromise = (async () => {
99
+ this.setState('INITIALIZING');
100
+ try {
101
+ validateConfig(this.config);
102
+ }
103
+ catch (err) {
104
+ this.setState('FATAL');
105
+ throw err;
106
+ }
107
+ try {
108
+ await this.adapter.initialize(signal);
109
+ this.setState('READY');
110
+ }
111
+ catch (err) {
112
+ if (isFireweaveError(err) && err.kind === 'Configuration') {
113
+ this.setState('FATAL');
114
+ }
115
+ else {
116
+ this.setState('ERROR');
117
+ }
118
+ throw isFireweaveError(err) ? err : new FireweaveError('Internal', { cause: err });
119
+ }
120
+ finally {
121
+ this.initPromise = undefined;
122
+ }
123
+ })();
124
+ return this.initPromise;
125
+ }
126
+ async shutdown() {
127
+ if (this.state === 'SHUTDOWN')
128
+ return; // idempotent
129
+ // The configured deadline bounds the whole flush+close sequence (M-1/L-4):
130
+ // a wedged vendor client must not hang process exit.
131
+ const timeoutMs = this.config.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;
132
+ let timer;
133
+ const deadline = new Promise((resolve) => {
134
+ timer = setTimeout(resolve, timeoutMs);
135
+ });
136
+ const close = (async () => {
137
+ try {
138
+ await this.adapter.flush?.();
139
+ }
140
+ catch {
141
+ // best-effort flush; never throw from shutdown
142
+ }
143
+ try {
144
+ await this.adapter.shutdown();
145
+ }
146
+ catch {
147
+ // swallow: shutdown must not throw
148
+ }
149
+ })();
150
+ try {
151
+ await Promise.race([close, deadline]);
152
+ }
153
+ finally {
154
+ this.evaluateExposureSeen.clear();
155
+ if (timer !== undefined)
156
+ clearTimeout(timer);
157
+ this.setState('SHUTDOWN');
158
+ }
159
+ }
160
+ /** Canonicalize + validate the merged context (throws FireweaveError). */
161
+ resolveContext(invocationContext) {
162
+ const merged = mergeContexts(this.globalContext, this.clientContext, invocationContext);
163
+ const result = validateContext(merged, this.contextPolicy);
164
+ if (!result.ok)
165
+ throw result.error;
166
+ return result.value;
167
+ }
168
+ /**
169
+ * Evaluate a flag to a canonical Decision. Never throws.
170
+ *
171
+ * Validates in the fixed order spec/control-points.md "Validation, before
172
+ * any I/O" names, stopping at the first failure: (1) key, (2) default vs
173
+ * type, (3) context, (4) lifecycle. Only once all four pass does this
174
+ * reach the adapter (the one I/O call in this method).
175
+ */
176
+ async evaluate(flagKey, expectedType, defaultValue, invocationContext, options = {}) {
177
+ const keyResult = validateControlPointKey(flagKey);
178
+ if (!keyResult.ok) {
179
+ return this.errorDecision(flagKey, defaultValue, keyResult.error);
180
+ }
181
+ const defaultResult = validateDefaultValue(expectedType, defaultValue);
182
+ if (!defaultResult.ok) {
183
+ return this.errorDecision(flagKey, defaultValue, defaultResult.error);
184
+ }
185
+ const merged = mergeContexts(this.globalContext, this.clientContext, invocationContext);
186
+ const contextResult = validateContext(merged, this.contextPolicy);
187
+ if (!contextResult.ok) {
188
+ return this.errorDecision(flagKey, defaultValue, contextResult.error);
189
+ }
190
+ const context = contextResult.value;
191
+ const lifecycleError = this.lifecycleError();
192
+ if (lifecycleError !== undefined) {
193
+ return this.errorDecision(flagKey, defaultValue, lifecycleError);
194
+ }
195
+ let resolution;
196
+ try {
197
+ const resolveOpts = options.signal !== undefined ? { signal: options.signal } : {};
198
+ resolution = await this.adapter.resolve(flagKey, context, resolveOpts);
199
+ }
200
+ catch (err) {
201
+ // H-2: non-Fireweave (vendor/internal) exception text never reaches the
202
+ // outward errorMessage — the fixed taxonomy message is used and the
203
+ // original error is preserved on `cause` only.
204
+ const fw = isFireweaveError(err) ? err : new FireweaveError('Internal', { cause: err });
205
+ return this.errorDecision(flagKey, defaultValue, fw);
206
+ }
207
+ if (!resolution.found) {
208
+ // spec/modes.md "Behaviour per mode": local's unknown-key row is
209
+ // `default` / `reason: DEFAULT` — deliberately not an error, unlike
210
+ // remote's `default` / `ERROR` / `FlagNotFound`. An adapter signals the
211
+ // former by carrying `reason: 'DEFAULT'` on its miss (FireweaveLocalAdapter);
212
+ // any adapter that leaves `reason` unset (InMemoryAdapter,
213
+ // FireweaveRemoteAdapter) keeps the FlagNotFound/ERROR path below.
214
+ if (resolution.reason === 'DEFAULT') {
215
+ return { flagKey, value: defaultValue, reason: 'DEFAULT', metadata: {} };
216
+ }
217
+ const meta = {};
218
+ if (resolution.quotaLimited === true)
219
+ meta['fireweave.quotaLimited'] = true;
220
+ return this.errorDecision(flagKey, defaultValue, new FireweaveError('FlagNotFound', { metadata: meta }));
221
+ }
222
+ const value = resolution.value ?? null;
223
+ if (!matchesExpectedType(value, expectedType)) {
224
+ return this.errorDecision(flagKey, defaultValue, new FireweaveError('TypeMismatch'));
225
+ }
226
+ const metadata = {};
227
+ if (resolution.version !== undefined)
228
+ metadata['fireweave.flagVersion'] = resolution.version;
229
+ // Detailed vendor fields travel together: they surface only when the
230
+ // backend reported BOTH a vendor flag id and a matched condition index
231
+ // (fixtures: eval-detailed-fields exposes them; eval-multivariate-string
232
+ // [index, no id] and eval-payload-attached [id, no index] do not).
233
+ if (resolution.vendorFlagId !== undefined && resolution.conditionIndex !== undefined) {
234
+ metadata['fireweave.vendorFlagId'] = resolution.vendorFlagId;
235
+ if (resolution.reasonCode !== undefined)
236
+ metadata['fireweave.reasonCode'] = resolution.reasonCode;
237
+ }
238
+ if (options.includePayload === true && resolution.payload !== undefined) {
239
+ metadata['fireweave.payload'] =
240
+ typeof resolution.payload === 'string' ? resolution.payload : stableStringify(resolution.payload);
241
+ }
242
+ if (resolution.quotaLimited === true)
243
+ metadata['fireweave.quotaLimited'] = true;
244
+ if (resolution.fromCache === true)
245
+ metadata['fireweave.fromCache'] = true;
246
+ let reason;
247
+ if (resolution.enabled === false) {
248
+ reason = 'DISABLED';
249
+ }
250
+ else if (resolution.reason !== undefined) {
251
+ reason = resolution.reason;
252
+ }
253
+ else if (resolution.fromCache === true || this.state === 'STALE') {
254
+ reason = 'STALE';
255
+ }
256
+ else {
257
+ reason = 'TARGETING_MATCH';
258
+ }
259
+ const decision = { flagKey, value, reason, metadata };
260
+ if (resolution.variant !== undefined)
261
+ decision.variant = resolution.variant;
262
+ // H-4 / ruling 20: evaluate is side-effect-free by default; opt in via sendExposure: true.
263
+ if (options.sendExposure === true) {
264
+ this.emitEvaluateExposure({
265
+ targetingKey: context.targetingKey ?? '',
266
+ flagKey,
267
+ value,
268
+ ...(resolution.variant !== undefined ? { variant: resolution.variant } : {}),
269
+ });
270
+ }
271
+ return decision;
272
+ }
273
+ /**
274
+ * Register a user or device so flag rules can target its DURABLE properties.
275
+ *
276
+ * Call once per login / device provisioning with the facts that outlive a
277
+ * request (plan, beta membership, region, device model), then send the same
278
+ * `targetingKey` on evaluation. Per-request context attributes still override
279
+ * the registered properties for a single evaluation — the two identity paths
280
+ * compose (spec/remote-protocol.md § Two identity paths).
281
+ *
282
+ * Resolves with `ok: false` instead of throwing: this runs in sign-in paths.
283
+ * Adapters without the capability (in-memory, local dev) report
284
+ * `Unsupported` so a dev harness does not silently look registered.
285
+ */
286
+ async registerTarget(targetingKey, options = {}) {
287
+ const lifecycle = this.lifecycleError();
288
+ if (lifecycle !== undefined)
289
+ return { ok: false, error: lifecycle };
290
+ if (this.adapter.registerTarget === undefined) {
291
+ return { ok: false, error: new FireweaveError('UnsupportedCapability') };
292
+ }
293
+ return this.adapter.registerTarget(targetingKey, options);
294
+ }
295
+ emitEvaluateExposure(exposure) {
296
+ if (exposure.targetingKey.length === 0)
297
+ return;
298
+ if (this.adapter.recordExposure === undefined)
299
+ return;
300
+ const key = `${exposure.targetingKey}\u0000${exposure.flagKey}\u0000${exposure.variant ?? ''}\u0000${stableStringify(exposure.value ?? null)}`;
301
+ if (this.evaluateExposureSeen.has(key))
302
+ return;
303
+ this.evaluateExposureSeen.add(key);
304
+ this.adapter.recordExposure({
305
+ targetingKey: exposure.targetingKey,
306
+ flagKey: exposure.flagKey,
307
+ value: exposure.value,
308
+ ...(exposure.variant !== undefined ? { variant: exposure.variant } : {}),
309
+ });
310
+ }
311
+ lifecycleError() {
312
+ switch (this.state) {
313
+ case 'UNINITIALIZED':
314
+ case 'INITIALIZING':
315
+ return new FireweaveError('NotReady');
316
+ case 'ERROR':
317
+ return new FireweaveError('NotReady');
318
+ case 'FATAL':
319
+ return new FireweaveError('Configuration');
320
+ case 'SHUTDOWN':
321
+ return new FireweaveError('AlreadyClosed');
322
+ default:
323
+ return undefined;
324
+ }
325
+ }
326
+ errorDecision(flagKey, defaultValue, err) {
327
+ const metadata = {
328
+ 'fireweave.errorKind': err.kind,
329
+ ...err.metadata,
330
+ };
331
+ return {
332
+ flagKey,
333
+ value: defaultValue,
334
+ reason: 'ERROR',
335
+ errorCode: err.openFeatureErrorCode,
336
+ errorKind: err.kind,
337
+ errorMessage: err.message,
338
+ metadata,
339
+ };
340
+ }
341
+ }
342
+ //# sourceMappingURL=runtime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/application/runtime.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EACL,sBAAsB,EACtB,+BAA+B,EAC/B,aAAa,GAId,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,mBAAmB,EACnB,eAAe,EACf,uBAAuB,EACvB,oBAAoB,GAErB,MAAM,yBAAyB,CAAC;AAyCjC,oEAAoE;AACpE,MAAM,CAAC,MAAM,2BAA2B,GAAG,KAAK,CAAC;AAgBjD,SAAS,cAAc,CAAC,MAA8B;IACpD,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;QAC9B,qEAAqE;QACrE,sEAAsE;QACtE,iBAAiB,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,YAAY,CAAC,CAAC;IACtD,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;QAChC,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;YACjD,IAAI,KAAK,KAAK,S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