@fireweaveai/web-sdk-cjs 0.0.0-reserve.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +52 -0
- package/dist/application/client.d.ts +104 -0
- package/dist/application/client.js +147 -0
- package/dist/application/mode.d.ts +99 -0
- package/dist/application/mode.js +101 -0
- package/dist/application/ports.d.ts +101 -0
- package/dist/application/ports.js +2 -0
- package/dist/application/runtime.d.ts +70 -0
- package/dist/application/runtime.js +348 -0
- package/dist/build/node/define.d.ts +14 -0
- package/dist/build/node/define.js +38 -0
- package/dist/build/node/shared.d.ts +19 -0
- package/dist/build/node/shared.js +39 -0
- package/dist/build/node/vite.d.ts +53 -0
- package/dist/build/node/vite.js +106 -0
- package/dist/build/src/start/build-info.d.ts +2 -0
- package/dist/build/src/start/build-info.js +9 -0
- package/dist/build/src/start/names.d.ts +38 -0
- package/dist/build/src/start/names.js +41 -0
- package/dist/build/src/start/policy.d.ts +70 -0
- package/dist/build/src/start/policy.js +128 -0
- package/dist/domain/context.d.ts +51 -0
- package/dist/domain/context.js +72 -0
- package/dist/domain/errors.d.ts +36 -0
- package/dist/domain/errors.js +97 -0
- package/dist/domain/target.d.ts +2 -0
- package/dist/domain/target.js +2 -0
- package/dist/domain/types.d.ts +89 -0
- package/dist/domain/types.js +10 -0
- package/dist/domain/validation.d.ts +128 -0
- package/dist/domain/validation.js +358 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.js +66 -0
- package/dist/infrastructure/adapters/inmemory.d.ts +50 -0
- package/dist/infrastructure/adapters/inmemory.js +94 -0
- package/dist/infrastructure/adapters/local.d.ts +79 -0
- package/dist/infrastructure/adapters/local.js +98 -0
- package/dist/infrastructure/adapters/remote.d.ts +44 -0
- package/dist/infrastructure/adapters/remote.js +329 -0
- package/dist/infrastructure/hosts.d.ts +10 -0
- package/dist/infrastructure/hosts.js +84 -0
- package/dist/start/build-info.d.ts +2 -0
- package/dist/start/build-info.js +9 -0
- package/dist/start/control-points.d.ts +24 -0
- package/dist/start/control-points.js +61 -0
- package/dist/start/fw.d.ts +42 -0
- package/dist/start/fw.js +137 -0
- package/dist/start/identity.d.ts +19 -0
- package/dist/start/identity.js +93 -0
- package/dist/start/index.d.ts +34 -0
- package/dist/start/index.js +38 -0
- package/dist/start/names.d.ts +38 -0
- package/dist/start/names.js +41 -0
- package/dist/start/policy.d.ts +70 -0
- package/dist/start/policy.js +128 -0
- package/dist/start/state.d.ts +103 -0
- package/dist/start/state.js +375 -0
- package/package.json +68 -0
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical data shapes, mirroring `spec/decision.schema.json`,
|
|
3
|
+
* `spec/signal.schema.json`, and `spec/release-context.schema.json`.
|
|
4
|
+
*
|
|
5
|
+
* Identical in meaning to the server SDK's `types.ts`. Duplicated rather than
|
|
6
|
+
* shared so the browser package has no cross-package dependency to audit; the
|
|
7
|
+
* JSON Schemas in `spec/` are what keep the two honest.
|
|
8
|
+
*/
|
|
9
|
+
export type JsonValue = string | number | boolean | null | JsonValue[] | {
|
|
10
|
+
[key: string]: JsonValue;
|
|
11
|
+
};
|
|
12
|
+
export type FlagValueType = 'boolean' | 'string' | 'number' | 'object';
|
|
13
|
+
export type DecisionReason = 'STATIC' | 'DEFAULT' | 'TARGETING_MATCH' | 'SPLIT' | 'CACHED' | 'STALE' | 'DISABLED' | 'UNKNOWN' | 'ERROR';
|
|
14
|
+
export interface Decision {
|
|
15
|
+
readonly controlPointKey: string;
|
|
16
|
+
readonly value: JsonValue;
|
|
17
|
+
readonly reason: DecisionReason;
|
|
18
|
+
readonly variant?: string;
|
|
19
|
+
readonly errorCode?: string;
|
|
20
|
+
readonly errorKind?: string;
|
|
21
|
+
readonly errorMessage?: string;
|
|
22
|
+
readonly metadata?: Record<string, string | number | boolean>;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* A browser lifecycle has one state the server does not: STALE.
|
|
26
|
+
*
|
|
27
|
+
* It means "initialize completed, but the prefetch did not, so reads are being
|
|
28
|
+
* served from an empty or outdated cache". Collapsing it into READY would make
|
|
29
|
+
* a failed boot indistinguishable from a successful one — which is the specific
|
|
30
|
+
* failure this SDK is written to avoid.
|
|
31
|
+
*/
|
|
32
|
+
export type LifecycleState = 'UNINITIALIZED' | 'INITIALIZING' | 'READY' | 'STALE' | 'ERROR' | 'SHUTDOWN';
|
|
33
|
+
export interface CanonicalContext {
|
|
34
|
+
readonly targetingKey?: string;
|
|
35
|
+
readonly attributes: Record<string, JsonValue>;
|
|
36
|
+
readonly groups?: Record<string, string>;
|
|
37
|
+
readonly groupProperties?: Record<string, Record<string, JsonValue>>;
|
|
38
|
+
}
|
|
39
|
+
export type SignalKind = 'health' | 'error' | 'metric' | 'outcome';
|
|
40
|
+
export interface Signal {
|
|
41
|
+
readonly kind: SignalKind;
|
|
42
|
+
readonly name: string;
|
|
43
|
+
readonly targetingKey?: string;
|
|
44
|
+
readonly controlPointKey?: string;
|
|
45
|
+
readonly variant?: string;
|
|
46
|
+
readonly status?: string;
|
|
47
|
+
readonly errorKind?: string;
|
|
48
|
+
readonly message?: string;
|
|
49
|
+
readonly value?: number;
|
|
50
|
+
readonly rolloutId?: string;
|
|
51
|
+
readonly changeId?: string;
|
|
52
|
+
readonly stampId?: string;
|
|
53
|
+
readonly timestamp?: string;
|
|
54
|
+
}
|
|
55
|
+
export interface Exposure {
|
|
56
|
+
readonly controlPointKey: string;
|
|
57
|
+
readonly targetingKey: string;
|
|
58
|
+
readonly value: JsonValue;
|
|
59
|
+
readonly variant?: string;
|
|
60
|
+
readonly rolloutId?: string;
|
|
61
|
+
readonly changeId?: string;
|
|
62
|
+
readonly stampId?: string;
|
|
63
|
+
}
|
|
64
|
+
export type ReleaseState = 'PENDING' | 'RUNNING' | 'COMPLETED' | 'FAILED';
|
|
65
|
+
export interface ReleaseContext {
|
|
66
|
+
readonly rolloutId?: string;
|
|
67
|
+
readonly changeId?: string;
|
|
68
|
+
readonly stampId?: string;
|
|
69
|
+
readonly environment?: string;
|
|
70
|
+
}
|
|
71
|
+
export interface Capabilities {
|
|
72
|
+
readonly static: {
|
|
73
|
+
readonly language: 'web';
|
|
74
|
+
readonly sdkVersion: string;
|
|
75
|
+
readonly specVersion: string;
|
|
76
|
+
readonly openFeature: {
|
|
77
|
+
readonly specFloor: string;
|
|
78
|
+
readonly providerName: string;
|
|
79
|
+
readonly serverOnly: boolean;
|
|
80
|
+
};
|
|
81
|
+
readonly features: Record<string, boolean>;
|
|
82
|
+
};
|
|
83
|
+
readonly runtime: {
|
|
84
|
+
readonly backend: 'fireweave' | 'inmemory' | 'none' | 'other';
|
|
85
|
+
readonly lifecycle: LifecycleState;
|
|
86
|
+
readonly features: Record<string, boolean>;
|
|
87
|
+
readonly limits: Record<string, number>;
|
|
88
|
+
};
|
|
89
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Canonical data shapes, mirroring `spec/decision.schema.json`,
|
|
4
|
+
* `spec/signal.schema.json`, and `spec/release-context.schema.json`.
|
|
5
|
+
*
|
|
6
|
+
* Identical in meaning to the server SDK's `types.ts`. Duplicated rather than
|
|
7
|
+
* shared so the browser package has no cross-package dependency to audit; the
|
|
8
|
+
* JSON Schemas in `spec/` are what keep the two honest.
|
|
9
|
+
*/
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fireweave web SDK validation — pure, total functions per
|
|
3
|
+
* spec/control-points.md "Validation, before any I/O" and spec/modes.md
|
|
4
|
+
* "Initialisation validation".
|
|
5
|
+
*
|
|
6
|
+
* Ported from sdks/node/src/domain/validation.ts (the reference
|
|
7
|
+
* implementation) — same five validators, same `Validated<T>` discipline,
|
|
8
|
+
* same malformed-key → ControlPointNotFound mapping. Reimplemented here rather than
|
|
9
|
+
* shared so the browser package keeps zero cross-package dependency to
|
|
10
|
+
* audit — the same reasoning ADR-0009 gives for duplicating types.ts/errors.ts
|
|
11
|
+
* extends to this module.
|
|
12
|
+
*
|
|
13
|
+
* Every read-path validator here (`validateControlPointKey`,
|
|
14
|
+
* `validateDefaultValue`, `validateContext`) returns `Validated<T>` instead
|
|
15
|
+
* of throwing. `FireweaveWebRuntime.evaluateSync` runs them, in the fixed
|
|
16
|
+
* order the spec names — key, default-vs-type, context, lifecycle — and
|
|
17
|
+
* degrades to the caller's default on the first failure; it NEVER throws
|
|
18
|
+
* (spec/control-points.md "Return discipline — never throw into a read
|
|
19
|
+
* path"). `validateInitOptions` is the one exception (spec/modes.md
|
|
20
|
+
* "Initialisation validation"): it still returns `Validated<T>` — mode.ts is
|
|
21
|
+
* what converts a failed result into the throw spec/modes.md requires.
|
|
22
|
+
*
|
|
23
|
+
* Note: unlike node, web's `FireweaveError` has no custom-message support —
|
|
24
|
+
* messages are FIXED per kind by design, because a browser error is visible
|
|
25
|
+
* in a devtools console on a machine this package does not control
|
|
26
|
+
* (errors.ts's own doc comment). So every branch below that would carry a
|
|
27
|
+
* distinct node message instead just uses the taxonomy's fixed message for
|
|
28
|
+
* its kind.
|
|
29
|
+
*/
|
|
30
|
+
import { FireweaveError } from './errors.js';
|
|
31
|
+
import type { ContextPolicy } from './context.js';
|
|
32
|
+
import type { CanonicalContext, JsonValue } from './types.js';
|
|
33
|
+
/** Result of a pure validator: success carries the validated value, failure the canonical error. */
|
|
34
|
+
export type Validated<T> = {
|
|
35
|
+
ok: true;
|
|
36
|
+
value: T;
|
|
37
|
+
} | {
|
|
38
|
+
ok: false;
|
|
39
|
+
error: FireweaveError;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* key — non-empty, ≤256 characters, no control characters
|
|
43
|
+
* (spec/control-points.md rule 1, the first check in the fixed order).
|
|
44
|
+
*
|
|
45
|
+
* No taxonomy kind names "malformed key" explicitly (the return-discipline
|
|
46
|
+
* table's closest row is "key unknown to the backend" → ControlPointNotFound):
|
|
47
|
+
* controller-ruled interim mapping (mirrors node's domain/validation.ts
|
|
48
|
+
* verbatim) — the 15-kind taxonomy in errors.schema.json is frozen at
|
|
49
|
+
* exactly 15 entries, `InvalidContext` is textually scoped to the evaluation
|
|
50
|
+
* *context* (not the key), and the schema already maps another non-literal
|
|
51
|
+
* case — quota-limited responses — onto `ControlPointNotFound` rather than adding a
|
|
52
|
+
* kind for it. `ControlPointNotFound` is therefore the least-wrong existing kind,
|
|
53
|
+
* not a literal fit. Other-language implementations copying node as the
|
|
54
|
+
* reference SHOULD use the same mapping rather than each independently
|
|
55
|
+
* guessing a different one.
|
|
56
|
+
*/
|
|
57
|
+
export declare function validateControlPointKey(key: string): Validated<string>;
|
|
58
|
+
export type ExpectedFlagType = 'boolean' | 'string' | 'number' | 'object';
|
|
59
|
+
/**
|
|
60
|
+
* Whether `value` matches the shape `expected` names. Shared by
|
|
61
|
+
* {@link validateDefaultValue} (the caller's default, before any read) and
|
|
62
|
+
* `FireweaveWebRuntime.evaluateSync`'s post-cache-lookup check (the backend's
|
|
63
|
+
* resolved value, from the prefetched cache) — same predicate, two different
|
|
64
|
+
* inputs.
|
|
65
|
+
*/
|
|
66
|
+
export declare function matchesExpectedType(value: JsonValue | undefined, expected: ExpectedFlagType): boolean;
|
|
67
|
+
/**
|
|
68
|
+
* default vs type — e.g. `getBooleanValue` with a non-boolean default is
|
|
69
|
+
* TypeMismatch (spec/control-points.md rule 2, checked before any read).
|
|
70
|
+
*/
|
|
71
|
+
export declare function validateDefaultValue(expectedType: ExpectedFlagType, defaultValue: JsonValue): Validated<JsonValue>;
|
|
72
|
+
/**
|
|
73
|
+
* targetingKey: "An SDK MUST NOT invent one: a missing targeting key is
|
|
74
|
+
* InvalidContext where the evaluation needs it, never a generated anonymous
|
|
75
|
+
* id" (spec/control-points.md "Context"). `required` is call-site policy —
|
|
76
|
+
* the remote adapter always requires one for `prefetch`/`registerTarget`; the
|
|
77
|
+
* generic context pipeline ({@link validateContext}) only does when
|
|
78
|
+
* `ContextPolicy.requireTargetingKey` opts in (unset by default here — web's
|
|
79
|
+
* targetingKey requirement is enforced at the remote adapter, not the
|
|
80
|
+
* general-purpose context validator every read runs).
|
|
81
|
+
*/
|
|
82
|
+
export declare function validateTargetingKey(targetingKey: string | undefined, required: boolean): Validated<string | undefined>;
|
|
83
|
+
/**
|
|
84
|
+
* context — depth, key count, value size, reserved keys
|
|
85
|
+
* (evaluation-context.schema.json) (spec/control-points.md rule 3). Also
|
|
86
|
+
* enforces `policy.requireTargetingKey` via {@link validateTargetingKey}, and
|
|
87
|
+
* — on success — extracts `groups`/`groupProperties` the same way the former
|
|
88
|
+
* `canonicalizeContext` did.
|
|
89
|
+
*
|
|
90
|
+
* `groups`/`groupProperties` (and their `fireweave.*` aliases) are pulled out
|
|
91
|
+
* BEFORE the attribute-count/size limit checks run, matching the pre-existing
|
|
92
|
+
* behaviour this module replaces: they are not ordinary attributes and were
|
|
93
|
+
* never counted against those limits.
|
|
94
|
+
*
|
|
95
|
+
* `merged` is the already-merged (global → invocation) raw input; merging
|
|
96
|
+
* itself (`mergeContexts`) lives in context.ts and carries no validation
|
|
97
|
+
* concerns of its own.
|
|
98
|
+
*/
|
|
99
|
+
export declare function validateContext(merged: {
|
|
100
|
+
targetingKey?: string;
|
|
101
|
+
attributes: Record<string, unknown>;
|
|
102
|
+
}, policy: ContextPolicy): Validated<CanonicalContext>;
|
|
103
|
+
/**
|
|
104
|
+
* Throwing wrapper around {@link validateContext}, kept for callers that
|
|
105
|
+
* genuinely want a throw (`FireweaveWebRuntime.refresh`, which is already
|
|
106
|
+
* inside its own try/catch feeding lifecycle state — see runtime.ts). Read
|
|
107
|
+
* paths do not use this — they call {@link validateContext} directly so a
|
|
108
|
+
* failure degrades instead of throwing.
|
|
109
|
+
*/
|
|
110
|
+
export declare function canonicalizeContext(merged: {
|
|
111
|
+
targetingKey?: string;
|
|
112
|
+
attributes: Record<string, unknown>;
|
|
113
|
+
}, policy: ContextPolicy): CanonicalContext;
|
|
114
|
+
/**
|
|
115
|
+
* Initialisation-validation table (spec/modes.md), rows 1, 2 and 4:
|
|
116
|
+
* - `mode` absent or unrecognised
|
|
117
|
+
* - `mode: 'remote'` with `apiKey` or `apiUrl` missing/blank
|
|
118
|
+
* - `mode: 'local'` with credentials supplied (a config half-migrated from
|
|
119
|
+
* remote to local reads as neither, silently — reject it instead)
|
|
120
|
+
*
|
|
121
|
+
* Row 3 ("apiUrl fails the host allowlist") is intentionally NOT checked
|
|
122
|
+
* here — mode.ts validates it directly via `assertHostAllowed` before
|
|
123
|
+
* calling into the (deliberately non-throwing) runtime; see mode.ts's module
|
|
124
|
+
* doc comment for why web cannot rely on the runtime the way node does.
|
|
125
|
+
*/
|
|
126
|
+
export declare function validateInitOptions<T extends {
|
|
127
|
+
readonly mode?: unknown;
|
|
128
|
+
}>(options: T): Validated<T>;
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.validateControlPointKey = validateControlPointKey;
|
|
4
|
+
exports.matchesExpectedType = matchesExpectedType;
|
|
5
|
+
exports.validateDefaultValue = validateDefaultValue;
|
|
6
|
+
exports.validateTargetingKey = validateTargetingKey;
|
|
7
|
+
exports.validateContext = validateContext;
|
|
8
|
+
exports.canonicalizeContext = canonicalizeContext;
|
|
9
|
+
exports.validateInitOptions = validateInitOptions;
|
|
10
|
+
/**
|
|
11
|
+
* Fireweave web SDK validation — pure, total functions per
|
|
12
|
+
* spec/control-points.md "Validation, before any I/O" and spec/modes.md
|
|
13
|
+
* "Initialisation validation".
|
|
14
|
+
*
|
|
15
|
+
* Ported from sdks/node/src/domain/validation.ts (the reference
|
|
16
|
+
* implementation) — same five validators, same `Validated<T>` discipline,
|
|
17
|
+
* same malformed-key → ControlPointNotFound mapping. Reimplemented here rather than
|
|
18
|
+
* shared so the browser package keeps zero cross-package dependency to
|
|
19
|
+
* audit — the same reasoning ADR-0009 gives for duplicating types.ts/errors.ts
|
|
20
|
+
* extends to this module.
|
|
21
|
+
*
|
|
22
|
+
* Every read-path validator here (`validateControlPointKey`,
|
|
23
|
+
* `validateDefaultValue`, `validateContext`) returns `Validated<T>` instead
|
|
24
|
+
* of throwing. `FireweaveWebRuntime.evaluateSync` runs them, in the fixed
|
|
25
|
+
* order the spec names — key, default-vs-type, context, lifecycle — and
|
|
26
|
+
* degrades to the caller's default on the first failure; it NEVER throws
|
|
27
|
+
* (spec/control-points.md "Return discipline — never throw into a read
|
|
28
|
+
* path"). `validateInitOptions` is the one exception (spec/modes.md
|
|
29
|
+
* "Initialisation validation"): it still returns `Validated<T>` — mode.ts is
|
|
30
|
+
* what converts a failed result into the throw spec/modes.md requires.
|
|
31
|
+
*
|
|
32
|
+
* Note: unlike node, web's `FireweaveError` has no custom-message support —
|
|
33
|
+
* messages are FIXED per kind by design, because a browser error is visible
|
|
34
|
+
* in a devtools console on a machine this package does not control
|
|
35
|
+
* (errors.ts's own doc comment). So every branch below that would carry a
|
|
36
|
+
* distinct node message instead just uses the taxonomy's fixed message for
|
|
37
|
+
* its kind.
|
|
38
|
+
*/
|
|
39
|
+
const errors_js_1 = require("./errors.js");
|
|
40
|
+
const ok = (value) => ({ ok: true, value });
|
|
41
|
+
const fail = (error) => ({ ok: false, error });
|
|
42
|
+
// ---------------------------------------------------------------------------
|
|
43
|
+
// Rule 1 — validateControlPointKey (spec/control-points.md "Validation,
|
|
44
|
+
// before any I/O": "key — non-empty, ≤256 characters, no control characters")
|
|
45
|
+
// ---------------------------------------------------------------------------
|
|
46
|
+
/** C0 + C1 control characters (U+0000-U+001F, U+007F-U+009F). */
|
|
47
|
+
const CONTROL_CHARACTERS = new RegExp('[' + String.fromCharCode(0x00) + '-' + String.fromCharCode(0x1f) +
|
|
48
|
+
String.fromCharCode(0x7f) + '-' + String.fromCharCode(0x9f) + ']');
|
|
49
|
+
const MAX_CONTROL_POINT_KEY_LENGTH = 256;
|
|
50
|
+
/**
|
|
51
|
+
* key — non-empty, ≤256 characters, no control characters
|
|
52
|
+
* (spec/control-points.md rule 1, the first check in the fixed order).
|
|
53
|
+
*
|
|
54
|
+
* No taxonomy kind names "malformed key" explicitly (the return-discipline
|
|
55
|
+
* table's closest row is "key unknown to the backend" → ControlPointNotFound):
|
|
56
|
+
* controller-ruled interim mapping (mirrors node's domain/validation.ts
|
|
57
|
+
* verbatim) — the 15-kind taxonomy in errors.schema.json is frozen at
|
|
58
|
+
* exactly 15 entries, `InvalidContext` is textually scoped to the evaluation
|
|
59
|
+
* *context* (not the key), and the schema already maps another non-literal
|
|
60
|
+
* case — quota-limited responses — onto `ControlPointNotFound` rather than adding a
|
|
61
|
+
* kind for it. `ControlPointNotFound` is therefore the least-wrong existing kind,
|
|
62
|
+
* not a literal fit. Other-language implementations copying node as the
|
|
63
|
+
* reference SHOULD use the same mapping rather than each independently
|
|
64
|
+
* guessing a different one.
|
|
65
|
+
*/
|
|
66
|
+
function validateControlPointKey(key) {
|
|
67
|
+
if (typeof key !== 'string' || key.length === 0) {
|
|
68
|
+
return fail(new errors_js_1.FireweaveError('ControlPointNotFound'));
|
|
69
|
+
}
|
|
70
|
+
if (key.length > MAX_CONTROL_POINT_KEY_LENGTH) {
|
|
71
|
+
return fail(new errors_js_1.FireweaveError('ControlPointNotFound'));
|
|
72
|
+
}
|
|
73
|
+
if (CONTROL_CHARACTERS.test(key)) {
|
|
74
|
+
return fail(new errors_js_1.FireweaveError('ControlPointNotFound'));
|
|
75
|
+
}
|
|
76
|
+
return ok(key);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Whether `value` matches the shape `expected` names. Shared by
|
|
80
|
+
* {@link validateDefaultValue} (the caller's default, before any read) and
|
|
81
|
+
* `FireweaveWebRuntime.evaluateSync`'s post-cache-lookup check (the backend's
|
|
82
|
+
* resolved value, from the prefetched cache) — same predicate, two different
|
|
83
|
+
* inputs.
|
|
84
|
+
*/
|
|
85
|
+
function matchesExpectedType(value, expected) {
|
|
86
|
+
switch (expected) {
|
|
87
|
+
case 'boolean':
|
|
88
|
+
return typeof value === 'boolean';
|
|
89
|
+
case 'string':
|
|
90
|
+
return typeof value === 'string';
|
|
91
|
+
case 'number':
|
|
92
|
+
return typeof value === 'number';
|
|
93
|
+
case 'object':
|
|
94
|
+
return typeof value === 'object' && value !== null;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* default vs type — e.g. `getBooleanValue` with a non-boolean default is
|
|
99
|
+
* TypeMismatch (spec/control-points.md rule 2, checked before any read).
|
|
100
|
+
*/
|
|
101
|
+
function validateDefaultValue(expectedType, defaultValue) {
|
|
102
|
+
if (!matchesExpectedType(defaultValue, expectedType)) {
|
|
103
|
+
return fail(new errors_js_1.FireweaveError('TypeMismatch'));
|
|
104
|
+
}
|
|
105
|
+
return ok(defaultValue);
|
|
106
|
+
}
|
|
107
|
+
// ---------------------------------------------------------------------------
|
|
108
|
+
// validateTargetingKey (spec/control-points.md "Context": targetingKey)
|
|
109
|
+
// ---------------------------------------------------------------------------
|
|
110
|
+
/**
|
|
111
|
+
* targetingKey: "An SDK MUST NOT invent one: a missing targeting key is
|
|
112
|
+
* InvalidContext where the evaluation needs it, never a generated anonymous
|
|
113
|
+
* id" (spec/control-points.md "Context"). `required` is call-site policy —
|
|
114
|
+
* the remote adapter always requires one for `prefetch`/`registerTarget`; the
|
|
115
|
+
* generic context pipeline ({@link validateContext}) only does when
|
|
116
|
+
* `ContextPolicy.requireTargetingKey` opts in (unset by default here — web's
|
|
117
|
+
* targetingKey requirement is enforced at the remote adapter, not the
|
|
118
|
+
* general-purpose context validator every read runs).
|
|
119
|
+
*/
|
|
120
|
+
function validateTargetingKey(targetingKey, required) {
|
|
121
|
+
if (required && (targetingKey === undefined || targetingKey === '')) {
|
|
122
|
+
return fail(new errors_js_1.FireweaveError('InvalidContext', { openFeatureErrorCode: 'TARGETING_KEY_MISSING' }));
|
|
123
|
+
}
|
|
124
|
+
return ok(targetingKey);
|
|
125
|
+
}
|
|
126
|
+
// ---------------------------------------------------------------------------
|
|
127
|
+
// Rule 3 — validateContext (spec/control-points.md rule 3: "context — depth,
|
|
128
|
+
// key count, value size, reserved keys (evaluation-context.schema.json)")
|
|
129
|
+
// ---------------------------------------------------------------------------
|
|
130
|
+
/**
|
|
131
|
+
* UTF-8 byte length. `TextEncoder` rather than `Buffer.byteLength` — `Buffer`
|
|
132
|
+
* does not exist in a browser at all (browser-portability.test.ts pins this).
|
|
133
|
+
*/
|
|
134
|
+
const utf8Encoder = new TextEncoder();
|
|
135
|
+
const byteLength = (s) => utf8Encoder.encode(s).length;
|
|
136
|
+
/**
|
|
137
|
+
* Sentinel returned (never thrown) when `deepCopyJson` walks back into an
|
|
138
|
+
* object already on the current recursion path — an actual reference cycle,
|
|
139
|
+
* not merely the same object shared by two sibling branches (which is legal
|
|
140
|
+
* and handled by backtracking `seen.delete(...)` below). Untyped caller
|
|
141
|
+
* input is `unknown`, so a circular attribute value is reachable from a
|
|
142
|
+
* caller today; without this, recursion never terminates and crashes with
|
|
143
|
+
* `RangeError: Maximum call stack size exceeded` — exactly the kind of throw
|
|
144
|
+
* a "before any I/O" validator must not allow (spec/control-points.md
|
|
145
|
+
* "Return discipline — never throw into a read path"). Module-local: never
|
|
146
|
+
* returned across this file's public surface, only used to fail
|
|
147
|
+
* `validateContext` closed as `InvalidContext`.
|
|
148
|
+
*/
|
|
149
|
+
const CYCLIC = Symbol('fireweave.cyclicJson');
|
|
150
|
+
function deepCopyJson(value, seen = new WeakSet()) {
|
|
151
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean' || typeof value === 'number') {
|
|
152
|
+
return value;
|
|
153
|
+
}
|
|
154
|
+
if (Array.isArray(value)) {
|
|
155
|
+
if (seen.has(value))
|
|
156
|
+
return CYCLIC;
|
|
157
|
+
seen.add(value);
|
|
158
|
+
const out = [];
|
|
159
|
+
for (const v of value) {
|
|
160
|
+
const copied = deepCopyJson(v, seen);
|
|
161
|
+
if (copied === CYCLIC)
|
|
162
|
+
return CYCLIC;
|
|
163
|
+
out.push(copied);
|
|
164
|
+
}
|
|
165
|
+
seen.delete(value);
|
|
166
|
+
return out;
|
|
167
|
+
}
|
|
168
|
+
if (typeof value === 'object') {
|
|
169
|
+
if (seen.has(value))
|
|
170
|
+
return CYCLIC;
|
|
171
|
+
seen.add(value);
|
|
172
|
+
const out = {};
|
|
173
|
+
for (const [k, v] of Object.entries(value)) {
|
|
174
|
+
if (v !== undefined) {
|
|
175
|
+
const copied = deepCopyJson(v, seen);
|
|
176
|
+
if (copied === CYCLIC)
|
|
177
|
+
return CYCLIC;
|
|
178
|
+
out[k] = copied;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
seen.delete(value);
|
|
182
|
+
return out;
|
|
183
|
+
}
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Cycle-safe defensively: `nestingDepth` only ever runs on `deepCopyJson`'s
|
|
188
|
+
* own output today, which is guaranteed acyclic by construction (it builds
|
|
189
|
+
* fresh containers, never back-references). Guarded anyway per the same
|
|
190
|
+
* "must be genuinely total" reasoning as `deepCopyJson`. A detected cycle
|
|
191
|
+
* returns `Infinity`, which always exceeds `limits.maxNestingDepth` and fails
|
|
192
|
+
* closed through the existing bound check below — no new failure path.
|
|
193
|
+
*/
|
|
194
|
+
function nestingDepth(value, seen = new WeakSet()) {
|
|
195
|
+
if (value === null || typeof value !== 'object')
|
|
196
|
+
return 0;
|
|
197
|
+
if (seen.has(value))
|
|
198
|
+
return Infinity;
|
|
199
|
+
seen.add(value);
|
|
200
|
+
let max = 0;
|
|
201
|
+
const children = Array.isArray(value) ? value : Object.values(value);
|
|
202
|
+
for (const child of children) {
|
|
203
|
+
const d = nestingDepth(child, seen);
|
|
204
|
+
if (d > max)
|
|
205
|
+
max = d;
|
|
206
|
+
}
|
|
207
|
+
seen.delete(value);
|
|
208
|
+
return max + 1;
|
|
209
|
+
}
|
|
210
|
+
const invalidContext = () => new errors_js_1.FireweaveError('InvalidContext');
|
|
211
|
+
/** groups/groupProperties carriers: canonical fireweave.* spelling first, then the plain alias. */
|
|
212
|
+
function extractSpecialKey(attributes, canonicalKey, aliasKey) {
|
|
213
|
+
if (canonicalKey in attributes)
|
|
214
|
+
return attributes[canonicalKey];
|
|
215
|
+
if (aliasKey in attributes)
|
|
216
|
+
return attributes[aliasKey];
|
|
217
|
+
return undefined;
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* context — depth, key count, value size, reserved keys
|
|
221
|
+
* (evaluation-context.schema.json) (spec/control-points.md rule 3). Also
|
|
222
|
+
* enforces `policy.requireTargetingKey` via {@link validateTargetingKey}, and
|
|
223
|
+
* — on success — extracts `groups`/`groupProperties` the same way the former
|
|
224
|
+
* `canonicalizeContext` did.
|
|
225
|
+
*
|
|
226
|
+
* `groups`/`groupProperties` (and their `fireweave.*` aliases) are pulled out
|
|
227
|
+
* BEFORE the attribute-count/size limit checks run, matching the pre-existing
|
|
228
|
+
* behaviour this module replaces: they are not ordinary attributes and were
|
|
229
|
+
* never counted against those limits.
|
|
230
|
+
*
|
|
231
|
+
* `merged` is the already-merged (global → invocation) raw input; merging
|
|
232
|
+
* itself (`mergeContexts`) lives in context.ts and carries no validation
|
|
233
|
+
* concerns of its own.
|
|
234
|
+
*/
|
|
235
|
+
function validateContext(merged, policy) {
|
|
236
|
+
const { limits } = policy;
|
|
237
|
+
const rawAttributes = { ...merged.attributes };
|
|
238
|
+
const rawGroups = extractSpecialKey(rawAttributes, 'fireweave.groups', 'groups');
|
|
239
|
+
const rawGroupProperties = extractSpecialKey(rawAttributes, 'fireweave.groupProperties', 'groupProperties');
|
|
240
|
+
delete rawAttributes['fireweave.groups'];
|
|
241
|
+
delete rawAttributes['groups'];
|
|
242
|
+
delete rawAttributes['fireweave.groupProperties'];
|
|
243
|
+
delete rawAttributes['groupProperties'];
|
|
244
|
+
const copied = deepCopyJson(rawAttributes);
|
|
245
|
+
if (copied === CYCLIC) {
|
|
246
|
+
return fail(invalidContext());
|
|
247
|
+
}
|
|
248
|
+
const attributes = copied;
|
|
249
|
+
const keys = Object.keys(attributes);
|
|
250
|
+
if (keys.length > limits.maxAttributeCount) {
|
|
251
|
+
return fail(invalidContext());
|
|
252
|
+
}
|
|
253
|
+
for (const key of keys) {
|
|
254
|
+
if (byteLength(key) > limits.maxKeyBytes) {
|
|
255
|
+
return fail(invalidContext());
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
for (const key of keys) {
|
|
259
|
+
const value = attributes[key];
|
|
260
|
+
if (byteLength(JSON.stringify(value ?? null)) > limits.maxValueBytes) {
|
|
261
|
+
return fail(invalidContext());
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
for (const key of keys) {
|
|
265
|
+
const value = attributes[key];
|
|
266
|
+
if (value !== undefined && nestingDepth(value) > limits.maxNestingDepth) {
|
|
267
|
+
return fail(invalidContext());
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
const serialized = JSON.stringify({ targetingKey: merged.targetingKey, attributes });
|
|
271
|
+
if (byteLength(serialized) > limits.maxSerializedBytes) {
|
|
272
|
+
return fail(invalidContext());
|
|
273
|
+
}
|
|
274
|
+
for (const key of keys) {
|
|
275
|
+
if (policy.reservedAttributeKeys.includes(key)) {
|
|
276
|
+
return fail(invalidContext());
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
const targetingKeyResult = validateTargetingKey(merged.targetingKey, policy.requireTargetingKey);
|
|
280
|
+
if (!targetingKeyResult.ok)
|
|
281
|
+
return targetingKeyResult;
|
|
282
|
+
let groups;
|
|
283
|
+
if (rawGroups !== undefined) {
|
|
284
|
+
const g = deepCopyJson(rawGroups);
|
|
285
|
+
if (g !== CYCLIC && g !== null && typeof g === 'object' && !Array.isArray(g)) {
|
|
286
|
+
const entries = Object.entries(g);
|
|
287
|
+
if (entries.every(([, v]) => typeof v === 'string')) {
|
|
288
|
+
groups = Object.fromEntries(entries);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
let groupProperties;
|
|
293
|
+
if (rawGroupProperties !== undefined) {
|
|
294
|
+
const gp = deepCopyJson(rawGroupProperties);
|
|
295
|
+
if (gp !== CYCLIC && gp !== null && typeof gp === 'object' && !Array.isArray(gp)) {
|
|
296
|
+
groupProperties = gp;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
const canonical = {
|
|
300
|
+
attributes,
|
|
301
|
+
...(merged.targetingKey !== undefined ? { targetingKey: merged.targetingKey } : {}),
|
|
302
|
+
...(groups !== undefined ? { groups } : {}),
|
|
303
|
+
...(groupProperties !== undefined ? { groupProperties } : {}),
|
|
304
|
+
};
|
|
305
|
+
return ok(canonical);
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Throwing wrapper around {@link validateContext}, kept for callers that
|
|
309
|
+
* genuinely want a throw (`FireweaveWebRuntime.refresh`, which is already
|
|
310
|
+
* inside its own try/catch feeding lifecycle state — see runtime.ts). Read
|
|
311
|
+
* paths do not use this — they call {@link validateContext} directly so a
|
|
312
|
+
* failure degrades instead of throwing.
|
|
313
|
+
*/
|
|
314
|
+
function canonicalizeContext(merged, policy) {
|
|
315
|
+
const result = validateContext(merged, policy);
|
|
316
|
+
if (!result.ok)
|
|
317
|
+
throw result.error;
|
|
318
|
+
return result.value;
|
|
319
|
+
}
|
|
320
|
+
// ---------------------------------------------------------------------------
|
|
321
|
+
// validateInitOptions (spec/modes.md "Initialisation validation")
|
|
322
|
+
// ---------------------------------------------------------------------------
|
|
323
|
+
/** "missing" and "blank" collapse to one check: not a non-empty string. */
|
|
324
|
+
const isBlank = (value) => typeof value !== 'string' || value.trim().length === 0;
|
|
325
|
+
const configError = () => new errors_js_1.FireweaveError('Configuration');
|
|
326
|
+
/**
|
|
327
|
+
* Initialisation-validation table (spec/modes.md), rows 1, 2 and 4:
|
|
328
|
+
* - `mode` absent or unrecognised
|
|
329
|
+
* - `mode: 'remote'` with `apiKey` or `apiUrl` missing/blank
|
|
330
|
+
* - `mode: 'local'` with credentials supplied (a config half-migrated from
|
|
331
|
+
* remote to local reads as neither, silently — reject it instead)
|
|
332
|
+
*
|
|
333
|
+
* Row 3 ("apiUrl fails the host allowlist") is intentionally NOT checked
|
|
334
|
+
* here — mode.ts validates it directly via `assertHostAllowed` before
|
|
335
|
+
* calling into the (deliberately non-throwing) runtime; see mode.ts's module
|
|
336
|
+
* doc comment for why web cannot rely on the runtime the way node does.
|
|
337
|
+
*/
|
|
338
|
+
function validateInitOptions(options) {
|
|
339
|
+
const mode = options?.mode;
|
|
340
|
+
if (mode !== 'local' && mode !== 'remote') {
|
|
341
|
+
return fail(configError());
|
|
342
|
+
}
|
|
343
|
+
// Runtime-only guard: a config object half-migrated from remote to local
|
|
344
|
+
// can carry apiKey/apiUrl even though the local-mode type declares
|
|
345
|
+
// neither — TypeScript's excess-property check only fires on a fresh
|
|
346
|
+
// object literal, not on a variable assembled elsewhere and passed in.
|
|
347
|
+
const credentials = options;
|
|
348
|
+
if (mode === 'remote') {
|
|
349
|
+
if (isBlank(credentials.apiKey) || isBlank(credentials.apiUrl)) {
|
|
350
|
+
return fail(configError());
|
|
351
|
+
}
|
|
352
|
+
return ok(options);
|
|
353
|
+
}
|
|
354
|
+
if (!isBlank(credentials.apiKey) || !isBlank(credentials.apiUrl)) {
|
|
355
|
+
return fail(configError());
|
|
356
|
+
}
|
|
357
|
+
return ok(options);
|
|
358
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fireweaveai/web-sdk — Fireweave control points for the browser (ADR-0009).
|
|
3
|
+
*
|
|
4
|
+
* Remote-only and secret-free by construction: it never evaluates locally, has
|
|
5
|
+
* no vendor SDK dependency, reads no environment, and rejects vendor/secret key
|
|
6
|
+
* shapes at the door. Credentials are passed in explicitly by the embedding app.
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* import { initFireweave } from '@fireweaveai/web-sdk';
|
|
10
|
+
*
|
|
11
|
+
* const fw = await initFireweave({
|
|
12
|
+
* mode: 'remote',
|
|
13
|
+
* apiKey,
|
|
14
|
+
* apiUrl,
|
|
15
|
+
* context: { targetingKey: 'anonymous' },
|
|
16
|
+
* });
|
|
17
|
+
*
|
|
18
|
+
* // Reads are SYNCHRONOUS — no await, safe inside render.
|
|
19
|
+
* const on = fw.controlPoints.getBooleanValue('new-checkout', false);
|
|
20
|
+
* ```
|
|
21
|
+
*
|
|
22
|
+
* `src/` is layered domain/ · application/ · infrastructure/
|
|
23
|
+
* (test/unit/architecture-layers.test.ts guards the boundary): `domain/` is
|
|
24
|
+
* pure data + validation with no outward imports; `application/` wires
|
|
25
|
+
* domain types into the runtime/client surface, with `mode.ts` as the sole
|
|
26
|
+
* composition root allowed to reach into `infrastructure/`; `infrastructure/`
|
|
27
|
+
* holds the concrete adapters and the host allowlist.
|
|
28
|
+
*/
|
|
29
|
+
export { FireweaveError, ERROR_TAXONOMY, isFireweaveError } from './domain/errors.js';
|
|
30
|
+
export type { FireweaveErrorKind, FireweaveErrorOptions, OpenFeatureErrorCode, ErrorKindSpec } from './domain/errors.js';
|
|
31
|
+
export type { JsonValue, FlagValueType, Decision, DecisionReason, CanonicalContext, LifecycleState, Signal, SignalKind, Exposure, ReleaseContext, ReleaseState, Capabilities, } from './domain/types.js';
|
|
32
|
+
export { DEFAULT_CONTEXT_LIMITS, DEFAULT_RESERVED_ATTRIBUTE_KEYS, mergeContexts } from './domain/context.js';
|
|
33
|
+
export type { ContextInput, ContextLimits, ContextPolicy } from './domain/context.js';
|
|
34
|
+
export { canonicalizeContext, matchesExpectedType, validateContext, validateControlPointKey, validateDefaultValue, validateTargetingKey, validateInitOptions, } from './domain/validation.js';
|
|
35
|
+
export type { Validated } from './domain/validation.js';
|
|
36
|
+
export type { TargetKind } from './domain/target.js';
|
|
37
|
+
export { DEFAULT_ALLOWED_HOSTS, assertHostAllowed, assertNotSecretKey, isLoopbackHostname } from './infrastructure/hosts.js';
|
|
38
|
+
export type { WebBackendAdapter, AdapterResolution, AdapterRuntimeFeatures, PrefetchOptions, PrefetchResult, RegisterTargetOptions, RegisterTargetResult, } from './application/ports.js';
|
|
39
|
+
export { FireweaveRemoteWebAdapter } from './infrastructure/adapters/remote.js';
|
|
40
|
+
export type { FireweaveRemoteWebAdapterOptions, FireweaveFetchLike } from './infrastructure/adapters/remote.js';
|
|
41
|
+
export { InMemoryWebAdapter } from './infrastructure/adapters/inmemory.js';
|
|
42
|
+
export type { InMemoryWebAdapterOptions, InMemoryFlagDefinition, InMemoryFault } from './infrastructure/adapters/inmemory.js';
|
|
43
|
+
export { FireweaveLocalWebAdapter } from './infrastructure/adapters/local.js';
|
|
44
|
+
export type { FireweaveLocalWebAdapterOptions, LocalRegisteredTarget } from './infrastructure/adapters/local.js';
|
|
45
|
+
export { FireweaveWebRuntime, DEFAULT_FLAGS_READY_TIMEOUT_MS } from './application/runtime.js';
|
|
46
|
+
export type { FireweaveWebRuntimeConfig, ExpectedFlagType } from './application/runtime.js';
|
|
47
|
+
export { FireweaveWebClient, WebControlPointsApi } from './application/client.js';
|
|
48
|
+
export type { FireweaveWebClientOptions, ExtensionResult, EvaluateOptions } from './application/client.js';
|
|
49
|
+
export { initFireweave } from './application/mode.js';
|
|
50
|
+
export type { InitFireweaveOptions, InitFireweaveLocalOptions, InitFireweaveRemoteOptions } from './application/mode.js';
|