@temps-sdk/node-sdk 0.0.4 → 0.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/sdk.gen.d.ts +640 -21
- package/dist/client/sdk.gen.js +3320 -894
- package/dist/client/types.gen.d.ts +15276 -5084
- package/dist/flags/client.d.ts +100 -0
- package/dist/flags/client.js +257 -0
- package/dist/flags/evaluate.d.ts +32 -0
- package/dist/flags/evaluate.js +77 -0
- package/dist/flags/index.d.ts +3 -0
- package/dist/flags/index.js +2 -0
- package/dist/flags/types.d.ts +104 -0
- package/dist/flags/types.js +6 -0
- package/dist/index.d.ts +63 -19
- package/dist/index.js +7 -0
- package/package.json +5 -5
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory feature-flag client for services running on Temps.
|
|
3
|
+
*
|
|
4
|
+
* Reads are synchronous and cost no network I/O: the whole environment's flag
|
|
5
|
+
* set lives in memory and is refreshed in the background. That is the point —
|
|
6
|
+
* a per-check HTTP round trip (~200-500ms) is unusable in a request handler.
|
|
7
|
+
*
|
|
8
|
+
* Zero configuration on Temps: `TEMPS_API_URL` and `TEMPS_API_TOKEN` are
|
|
9
|
+
* injected into every deployment, and the token pins the project (and usually
|
|
10
|
+
* the environment), so `new FlagsClient()` already knows what to fetch.
|
|
11
|
+
*/
|
|
12
|
+
import type { EvalContext, Evaluation, FlagsClientOptions } from './types';
|
|
13
|
+
export declare class FlagsClient {
|
|
14
|
+
private readonly apiUrl;
|
|
15
|
+
private readonly apiToken;
|
|
16
|
+
private readonly environmentId?;
|
|
17
|
+
private readonly refreshIntervalMs;
|
|
18
|
+
private readonly timeoutMs;
|
|
19
|
+
private readonly reportExposure;
|
|
20
|
+
private readonly onError;
|
|
21
|
+
private flags;
|
|
22
|
+
private etag;
|
|
23
|
+
private timer;
|
|
24
|
+
/**
|
|
25
|
+
* Keys actually evaluated since the last report.
|
|
26
|
+
*
|
|
27
|
+
* Only keys present in the snapshot are recorded, which bounds this by the
|
|
28
|
+
* project's flag count — a caller doing `get('user-' + id, ...)` cannot grow
|
|
29
|
+
* it without limit.
|
|
30
|
+
*/
|
|
31
|
+
private evaluated;
|
|
32
|
+
/** True once a snapshot has been successfully loaded at least once. */
|
|
33
|
+
ready: boolean;
|
|
34
|
+
/**
|
|
35
|
+
* The most recent refresh failure, or `null`. Exposed rather than swallowed:
|
|
36
|
+
* a self-hosted operator debugging alone needs to see that flags are stale,
|
|
37
|
+
* not guess why a rollout did nothing.
|
|
38
|
+
*/
|
|
39
|
+
lastError: Error | null;
|
|
40
|
+
constructor(options?: FlagsClientOptions);
|
|
41
|
+
/**
|
|
42
|
+
* Load the first snapshot and start background refresh.
|
|
43
|
+
*
|
|
44
|
+
* Never throws. A flag service that is unreachable must not stop an app from
|
|
45
|
+
* booting — every `get()` returns its caller-supplied fallback until a
|
|
46
|
+
* snapshot arrives, and `ready` stays `false` so you can surface it.
|
|
47
|
+
*/
|
|
48
|
+
init(): Promise<void>;
|
|
49
|
+
/** Stop background refresh. Safe to call more than once. */
|
|
50
|
+
close(): void;
|
|
51
|
+
/**
|
|
52
|
+
* Read a flag. Synchronous, in-memory, no network I/O.
|
|
53
|
+
*
|
|
54
|
+
* `fallback` is returned whenever the flag cannot be resolved — unknown key,
|
|
55
|
+
* snapshot not loaded yet, or a stored value that does not match the flag's
|
|
56
|
+
* declared type.
|
|
57
|
+
*/
|
|
58
|
+
get<T>(key: string, context: EvalContext | undefined, fallback: T): T;
|
|
59
|
+
/**
|
|
60
|
+
* Read a flag along with the reason it resolved that way.
|
|
61
|
+
*
|
|
62
|
+
* Use this when debugging "why is this user seeing the old checkout?" — the
|
|
63
|
+
* reason distinguishes a kill switch from an unset value from a flag that
|
|
64
|
+
* does not exist.
|
|
65
|
+
*/
|
|
66
|
+
getDetails<T>(key: string, context: EvalContext | undefined, fallback: T): Evaluation<T>;
|
|
67
|
+
/** Every flag key currently cached. */
|
|
68
|
+
keys(): string[];
|
|
69
|
+
/**
|
|
70
|
+
* Fetch the snapshot once.
|
|
71
|
+
*
|
|
72
|
+
* A failure leaves the previous snapshot in place: stale flags are far better
|
|
73
|
+
* than every flag suddenly reverting to its fallback because the control
|
|
74
|
+
* plane blinked.
|
|
75
|
+
*/
|
|
76
|
+
refresh(): Promise<void>;
|
|
77
|
+
/**
|
|
78
|
+
* Report which flags were actually evaluated since the last flush.
|
|
79
|
+
*
|
|
80
|
+
* This is what gives `last evaluated` in the console a real meaning: the
|
|
81
|
+
* server hands out the whole flag set and evaluation happens here, so
|
|
82
|
+
* without this it could only ever know that *something* fetched the list.
|
|
83
|
+
*
|
|
84
|
+
* Best-effort. A failure drops the batch rather than retrying forever —
|
|
85
|
+
* usage telemetry must never grow unboundedly or interfere with reads.
|
|
86
|
+
*/
|
|
87
|
+
flushExposure(): Promise<void>;
|
|
88
|
+
private fail;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Process-wide client, for the common case where an app has one flag set.
|
|
92
|
+
*
|
|
93
|
+
* ```ts
|
|
94
|
+
* import { flags } from '@temps-sdk/node-sdk';
|
|
95
|
+
*
|
|
96
|
+
* await flags.init();
|
|
97
|
+
* if (flags.get('checkout.v2', { key: user.id }, false)) { ... }
|
|
98
|
+
* ```
|
|
99
|
+
*/
|
|
100
|
+
export declare const flags: FlagsClient;
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory feature-flag client for services running on Temps.
|
|
3
|
+
*
|
|
4
|
+
* Reads are synchronous and cost no network I/O: the whole environment's flag
|
|
5
|
+
* set lives in memory and is refreshed in the background. That is the point —
|
|
6
|
+
* a per-check HTTP round trip (~200-500ms) is unusable in a request handler.
|
|
7
|
+
*
|
|
8
|
+
* Zero configuration on Temps: `TEMPS_API_URL` and `TEMPS_API_TOKEN` are
|
|
9
|
+
* injected into every deployment, and the token pins the project (and usually
|
|
10
|
+
* the environment), so `new FlagsClient()` already knows what to fetch.
|
|
11
|
+
*/
|
|
12
|
+
import { evaluate } from './evaluate';
|
|
13
|
+
const DEFAULT_REFRESH_INTERVAL_MS = 30_000;
|
|
14
|
+
const DEFAULT_TIMEOUT_MS = 5_000;
|
|
15
|
+
/**
|
|
16
|
+
* Matches `MAX_EXPOSURE_KEYS` on the server, which now rejects (rather than
|
|
17
|
+
* truncates) an over-sized batch. A project with more flags than this must be
|
|
18
|
+
* chunked, or its overflow keys would never be stamped.
|
|
19
|
+
*/
|
|
20
|
+
const MAX_EXPOSURE_KEYS = 500;
|
|
21
|
+
/**
|
|
22
|
+
* Read an environment variable without depending on Node type definitions.
|
|
23
|
+
*
|
|
24
|
+
* This package is consumed from browsers too, so `lib` is DOM-flavoured and
|
|
25
|
+
* there is no `process` global in the type environment. Going through
|
|
26
|
+
* `globalThis` keeps the client usable in both without pulling `@types/node`
|
|
27
|
+
* into every consumer.
|
|
28
|
+
*/
|
|
29
|
+
function envVar(name) {
|
|
30
|
+
const global = globalThis;
|
|
31
|
+
return global.process?.env?.[name];
|
|
32
|
+
}
|
|
33
|
+
export class FlagsClient {
|
|
34
|
+
apiUrl;
|
|
35
|
+
apiToken;
|
|
36
|
+
environmentId;
|
|
37
|
+
refreshIntervalMs;
|
|
38
|
+
timeoutMs;
|
|
39
|
+
reportExposure;
|
|
40
|
+
onError;
|
|
41
|
+
flags = new Map();
|
|
42
|
+
etag = null;
|
|
43
|
+
timer = null;
|
|
44
|
+
/**
|
|
45
|
+
* Keys actually evaluated since the last report.
|
|
46
|
+
*
|
|
47
|
+
* Only keys present in the snapshot are recorded, which bounds this by the
|
|
48
|
+
* project's flag count — a caller doing `get('user-' + id, ...)` cannot grow
|
|
49
|
+
* it without limit.
|
|
50
|
+
*/
|
|
51
|
+
evaluated = new Set();
|
|
52
|
+
/** True once a snapshot has been successfully loaded at least once. */
|
|
53
|
+
ready = false;
|
|
54
|
+
/**
|
|
55
|
+
* The most recent refresh failure, or `null`. Exposed rather than swallowed:
|
|
56
|
+
* a self-hosted operator debugging alone needs to see that flags are stale,
|
|
57
|
+
* not guess why a rollout did nothing.
|
|
58
|
+
*/
|
|
59
|
+
lastError = null;
|
|
60
|
+
constructor(options = {}) {
|
|
61
|
+
this.apiUrl = (options.apiUrl ?? envVar('TEMPS_API_URL') ?? '').replace(/\/+$/, '');
|
|
62
|
+
this.apiToken = options.apiToken ?? envVar('TEMPS_API_TOKEN') ?? '';
|
|
63
|
+
this.environmentId = options.environmentId;
|
|
64
|
+
this.refreshIntervalMs = options.refreshIntervalMs ?? DEFAULT_REFRESH_INTERVAL_MS;
|
|
65
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
66
|
+
this.reportExposure = options.reportExposure ?? true;
|
|
67
|
+
this.onError =
|
|
68
|
+
options.onError ??
|
|
69
|
+
((error) => {
|
|
70
|
+
console.warn(`[temps-flags] ${error.message}`);
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Load the first snapshot and start background refresh.
|
|
75
|
+
*
|
|
76
|
+
* Never throws. A flag service that is unreachable must not stop an app from
|
|
77
|
+
* booting — every `get()` returns its caller-supplied fallback until a
|
|
78
|
+
* snapshot arrives, and `ready` stays `false` so you can surface it.
|
|
79
|
+
*/
|
|
80
|
+
async init() {
|
|
81
|
+
if (!this.apiUrl || !this.apiToken) {
|
|
82
|
+
this.fail(new Error('TEMPS_API_URL and TEMPS_API_TOKEN are required (both are injected automatically for apps deployed on Temps). Flags will serve fallbacks.'));
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
await this.refresh();
|
|
86
|
+
}
|
|
87
|
+
if (this.timer === null && this.refreshIntervalMs > 0) {
|
|
88
|
+
this.timer = setInterval(() => {
|
|
89
|
+
void this.refresh();
|
|
90
|
+
void this.flushExposure();
|
|
91
|
+
}, this.refreshIntervalMs);
|
|
92
|
+
// On Node, don't hold the process open just to poll for flags. No-op in
|
|
93
|
+
// a browser, where timer handles are plain numbers.
|
|
94
|
+
this.timer.unref?.();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/** Stop background refresh. Safe to call more than once. */
|
|
98
|
+
close() {
|
|
99
|
+
if (this.timer !== null) {
|
|
100
|
+
clearInterval(this.timer);
|
|
101
|
+
this.timer = null;
|
|
102
|
+
}
|
|
103
|
+
// Best-effort final report so a graceful shutdown doesn't discard the
|
|
104
|
+
// last interval's worth of usage.
|
|
105
|
+
void this.flushExposure();
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Read a flag. Synchronous, in-memory, no network I/O.
|
|
109
|
+
*
|
|
110
|
+
* `fallback` is returned whenever the flag cannot be resolved — unknown key,
|
|
111
|
+
* snapshot not loaded yet, or a stored value that does not match the flag's
|
|
112
|
+
* declared type.
|
|
113
|
+
*/
|
|
114
|
+
get(key, context = {}, fallback) {
|
|
115
|
+
return this.getDetails(key, context, fallback).value;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Read a flag along with the reason it resolved that way.
|
|
119
|
+
*
|
|
120
|
+
* Use this when debugging "why is this user seeing the old checkout?" — the
|
|
121
|
+
* reason distinguishes a kill switch from an unset value from a flag that
|
|
122
|
+
* does not exist.
|
|
123
|
+
*/
|
|
124
|
+
getDetails(key, context = {}, fallback) {
|
|
125
|
+
const flag = this.flags.get(key);
|
|
126
|
+
// Note the key in memory only — reporting happens on the refresh interval.
|
|
127
|
+
// Writing per evaluation would put a network call in the caller's hot path,
|
|
128
|
+
// which is the entire thing this client exists to avoid.
|
|
129
|
+
if (flag && this.reportExposure) {
|
|
130
|
+
this.evaluated.add(key);
|
|
131
|
+
}
|
|
132
|
+
return evaluate(flag, context, fallback);
|
|
133
|
+
}
|
|
134
|
+
/** Every flag key currently cached. */
|
|
135
|
+
keys() {
|
|
136
|
+
return [...this.flags.keys()];
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Fetch the snapshot once.
|
|
140
|
+
*
|
|
141
|
+
* A failure leaves the previous snapshot in place: stale flags are far better
|
|
142
|
+
* than every flag suddenly reverting to its fallback because the control
|
|
143
|
+
* plane blinked.
|
|
144
|
+
*/
|
|
145
|
+
async refresh() {
|
|
146
|
+
const controller = new AbortController();
|
|
147
|
+
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
148
|
+
try {
|
|
149
|
+
const url = new URL(`${this.apiUrl}/flags/snapshot`);
|
|
150
|
+
if (this.environmentId !== undefined) {
|
|
151
|
+
url.searchParams.set('environment_id', String(this.environmentId));
|
|
152
|
+
}
|
|
153
|
+
const headers = {
|
|
154
|
+
Authorization: `Bearer ${this.apiToken}`,
|
|
155
|
+
Accept: 'application/json',
|
|
156
|
+
};
|
|
157
|
+
if (this.etag) {
|
|
158
|
+
headers['If-None-Match'] = this.etag;
|
|
159
|
+
}
|
|
160
|
+
const response = await fetch(url, { headers, signal: controller.signal });
|
|
161
|
+
// Nothing changed since the last poll — the common case.
|
|
162
|
+
if (response.status === 304) {
|
|
163
|
+
this.lastError = null;
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (!response.ok) {
|
|
167
|
+
this.fail(new Error(`Flag snapshot request failed: ${response.status} ${response.statusText}. Serving ${this.ready ? 'the last known' : 'fallback'} values.`));
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
const body = (await response.json());
|
|
171
|
+
const next = new Map();
|
|
172
|
+
for (const flag of body.flags ?? []) {
|
|
173
|
+
next.set(flag.key, flag);
|
|
174
|
+
}
|
|
175
|
+
this.flags = next;
|
|
176
|
+
this.etag = response.headers.get('etag');
|
|
177
|
+
this.ready = true;
|
|
178
|
+
this.lastError = null;
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
182
|
+
this.fail(new Error(`Flag snapshot request failed: ${reason}. Serving ${this.ready ? 'the last known' : 'fallback'} values.`));
|
|
183
|
+
}
|
|
184
|
+
finally {
|
|
185
|
+
clearTimeout(timeout);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Report which flags were actually evaluated since the last flush.
|
|
190
|
+
*
|
|
191
|
+
* This is what gives `last evaluated` in the console a real meaning: the
|
|
192
|
+
* server hands out the whole flag set and evaluation happens here, so
|
|
193
|
+
* without this it could only ever know that *something* fetched the list.
|
|
194
|
+
*
|
|
195
|
+
* Best-effort. A failure drops the batch rather than retrying forever —
|
|
196
|
+
* usage telemetry must never grow unboundedly or interfere with reads.
|
|
197
|
+
*/
|
|
198
|
+
async flushExposure() {
|
|
199
|
+
if (!this.reportExposure || this.evaluated.size === 0)
|
|
200
|
+
return;
|
|
201
|
+
if (!this.apiUrl || !this.apiToken)
|
|
202
|
+
return;
|
|
203
|
+
// Take the batch up front so evaluations during the request aren't lost.
|
|
204
|
+
const pending = [...this.evaluated];
|
|
205
|
+
this.evaluated.clear();
|
|
206
|
+
// Chunk to the server's cap. It rejects over-sized batches outright, so a
|
|
207
|
+
// project with >500 flags would otherwise have its whole report refused
|
|
208
|
+
// and those flags would read as "never evaluated" forever.
|
|
209
|
+
for (let i = 0; i < pending.length; i += MAX_EXPOSURE_KEYS) {
|
|
210
|
+
const keys = pending.slice(i, i + MAX_EXPOSURE_KEYS);
|
|
211
|
+
const controller = new AbortController();
|
|
212
|
+
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
213
|
+
try {
|
|
214
|
+
const response = await fetch(`${this.apiUrl}/flags/exposure`, {
|
|
215
|
+
method: 'POST',
|
|
216
|
+
headers: {
|
|
217
|
+
Authorization: `Bearer ${this.apiToken}`,
|
|
218
|
+
'Content-Type': 'application/json',
|
|
219
|
+
},
|
|
220
|
+
body: JSON.stringify({ keys }),
|
|
221
|
+
signal: controller.signal,
|
|
222
|
+
});
|
|
223
|
+
// Put a rejected batch back so the next flush retries it. Bounded by
|
|
224
|
+
// the flag count, so this cannot grow without limit.
|
|
225
|
+
if (!response.ok) {
|
|
226
|
+
for (const key of keys)
|
|
227
|
+
this.evaluated.add(key);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
catch {
|
|
231
|
+
// Deliberately silent: a dropped usage report is not worth a warning
|
|
232
|
+
// in the app's logs, and `lastError` is reserved for the failure that
|
|
233
|
+
// actually matters (flags going stale).
|
|
234
|
+
for (const key of keys)
|
|
235
|
+
this.evaluated.add(key);
|
|
236
|
+
}
|
|
237
|
+
finally {
|
|
238
|
+
clearTimeout(timeout);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
fail(error) {
|
|
243
|
+
this.lastError = error;
|
|
244
|
+
this.onError(error);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Process-wide client, for the common case where an app has one flag set.
|
|
249
|
+
*
|
|
250
|
+
* ```ts
|
|
251
|
+
* import { flags } from '@temps-sdk/node-sdk';
|
|
252
|
+
*
|
|
253
|
+
* await flags.init();
|
|
254
|
+
* if (flags.get('checkout.v2', { key: user.id }, false)) { ... }
|
|
255
|
+
* ```
|
|
256
|
+
*/
|
|
257
|
+
export const flags = new FlagsClient();
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Flag evaluation. Pure, synchronous, total — no I/O, never throws.
|
|
3
|
+
*
|
|
4
|
+
* This is a deliberate line-for-line mirror of `evaluate()` in
|
|
5
|
+
* `crates/temps-flags/src/eval.rs`. If you change the resolution order here,
|
|
6
|
+
* change it there in the same commit, or the same flag will resolve
|
|
7
|
+
* differently in the app and on the server.
|
|
8
|
+
*
|
|
9
|
+
* Resolution order:
|
|
10
|
+
*
|
|
11
|
+
* 1. flag missing or archived -> caller's fallback FLAG_NOT_FOUND
|
|
12
|
+
* 2. enabled === false -> default_value DISABLED
|
|
13
|
+
* 3. -- reserved for rules -- RULE_MATCH{i}
|
|
14
|
+
* | PERCENTAGE_ROLLOUT{i}
|
|
15
|
+
* 4. environment value present -> that value ENVIRONMENT_VALUE
|
|
16
|
+
* 5. otherwise -> default_value DEFAULT
|
|
17
|
+
*/
|
|
18
|
+
import type { EvalContext, Evaluation, FlagSnapshot, FlagValueType } from './types';
|
|
19
|
+
/**
|
|
20
|
+
* Whether a concrete JSON value is admissible for a declared flag type.
|
|
21
|
+
*
|
|
22
|
+
* `json` accepts anything except `null`: a flag must always resolve to
|
|
23
|
+
* something usable, and `null` is indistinguishable from "unset".
|
|
24
|
+
*/
|
|
25
|
+
export declare function valueMatchesType(valueType: FlagValueType, value: unknown): boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Evaluate one flag. Always returns a usable value.
|
|
28
|
+
*
|
|
29
|
+
* `_context` is accepted and ignored: targeting has not shipped. The parameter
|
|
30
|
+
* is the expensive half of the contract; the code that reads it is cheap.
|
|
31
|
+
*/
|
|
32
|
+
export declare function evaluate<T>(flag: FlagSnapshot | undefined, _context: EvalContext, fallback: T): Evaluation<T>;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Flag evaluation. Pure, synchronous, total — no I/O, never throws.
|
|
3
|
+
*
|
|
4
|
+
* This is a deliberate line-for-line mirror of `evaluate()` in
|
|
5
|
+
* `crates/temps-flags/src/eval.rs`. If you change the resolution order here,
|
|
6
|
+
* change it there in the same commit, or the same flag will resolve
|
|
7
|
+
* differently in the app and on the server.
|
|
8
|
+
*
|
|
9
|
+
* Resolution order:
|
|
10
|
+
*
|
|
11
|
+
* 1. flag missing or archived -> caller's fallback FLAG_NOT_FOUND
|
|
12
|
+
* 2. enabled === false -> default_value DISABLED
|
|
13
|
+
* 3. -- reserved for rules -- RULE_MATCH{i}
|
|
14
|
+
* | PERCENTAGE_ROLLOUT{i}
|
|
15
|
+
* 4. environment value present -> that value ENVIRONMENT_VALUE
|
|
16
|
+
* 5. otherwise -> default_value DEFAULT
|
|
17
|
+
*/
|
|
18
|
+
/**
|
|
19
|
+
* Whether a concrete JSON value is admissible for a declared flag type.
|
|
20
|
+
*
|
|
21
|
+
* `json` accepts anything except `null`: a flag must always resolve to
|
|
22
|
+
* something usable, and `null` is indistinguishable from "unset".
|
|
23
|
+
*/
|
|
24
|
+
export function valueMatchesType(valueType, value) {
|
|
25
|
+
switch (valueType) {
|
|
26
|
+
case 'bool':
|
|
27
|
+
return typeof value === 'boolean';
|
|
28
|
+
case 'string':
|
|
29
|
+
return typeof value === 'string';
|
|
30
|
+
case 'number':
|
|
31
|
+
return typeof value === 'number' && Number.isFinite(value);
|
|
32
|
+
case 'json':
|
|
33
|
+
return value !== null && value !== undefined;
|
|
34
|
+
default:
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function outcome(value, reason) {
|
|
39
|
+
return { value: value, variant: null, reason };
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Serve `value` if it matches the flag's declared type, otherwise degrade to
|
|
43
|
+
* the flag default. An operator typing the wrong thing into the flag UI must
|
|
44
|
+
* not break the running app.
|
|
45
|
+
*/
|
|
46
|
+
function sanitized(flag, value, reason, fallback) {
|
|
47
|
+
if (valueMatchesType(flag.value_type, value)) {
|
|
48
|
+
return outcome(value, reason);
|
|
49
|
+
}
|
|
50
|
+
if (valueMatchesType(flag.value_type, flag.default_value)) {
|
|
51
|
+
return outcome(flag.default_value, { kind: 'ERROR' });
|
|
52
|
+
}
|
|
53
|
+
return outcome(fallback, { kind: 'ERROR' });
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Evaluate one flag. Always returns a usable value.
|
|
57
|
+
*
|
|
58
|
+
* `_context` is accepted and ignored: targeting has not shipped. The parameter
|
|
59
|
+
* is the expensive half of the contract; the code that reads it is cheap.
|
|
60
|
+
*/
|
|
61
|
+
export function evaluate(flag, _context, fallback) {
|
|
62
|
+
if (!flag) {
|
|
63
|
+
return outcome(fallback, { kind: 'FLAG_NOT_FOUND' });
|
|
64
|
+
}
|
|
65
|
+
if (!flag.enabled) {
|
|
66
|
+
return sanitized(flag, flag.default_value, { kind: 'DISABLED' }, fallback);
|
|
67
|
+
}
|
|
68
|
+
// -------------------------------------------------------------------------
|
|
69
|
+
// Step 3: targeting rules evaluate HERE, ahead of the environment value and
|
|
70
|
+
// behind the kill switch. Nothing above or below this point changes when
|
|
71
|
+
// they land.
|
|
72
|
+
// -------------------------------------------------------------------------
|
|
73
|
+
if (flag.environment_value !== null && flag.environment_value !== undefined) {
|
|
74
|
+
return sanitized(flag, flag.environment_value, { kind: 'ENVIRONMENT_VALUE' }, fallback);
|
|
75
|
+
}
|
|
76
|
+
return sanitized(flag, flag.default_value, { kind: 'DEFAULT' }, fallback);
|
|
77
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Feature-flag types. These mirror `crates/temps-flags/src/eval.rs` exactly —
|
|
3
|
+
* the SDK evaluates locally, so the two implementations must agree or the same
|
|
4
|
+
* flag resolves differently on the server and in the app.
|
|
5
|
+
*/
|
|
6
|
+
export type FlagValueType = 'bool' | 'string' | 'number' | 'json';
|
|
7
|
+
/**
|
|
8
|
+
* Why an evaluation produced the value it did.
|
|
9
|
+
*
|
|
10
|
+
* `RULE_MATCH` and `PERCENTAGE_ROLLOUT` are declared because they are part of
|
|
11
|
+
* the wire contract, but the server never emits them yet — targeting has not
|
|
12
|
+
* shipped. Code that switches on `reason` should handle them from day one.
|
|
13
|
+
*/
|
|
14
|
+
export type EvalReason = {
|
|
15
|
+
kind: 'FLAG_NOT_FOUND';
|
|
16
|
+
} | {
|
|
17
|
+
kind: 'DISABLED';
|
|
18
|
+
} | {
|
|
19
|
+
kind: 'RULE_MATCH';
|
|
20
|
+
index: number;
|
|
21
|
+
} | {
|
|
22
|
+
kind: 'PERCENTAGE_ROLLOUT';
|
|
23
|
+
index: number;
|
|
24
|
+
} | {
|
|
25
|
+
kind: 'ENVIRONMENT_VALUE';
|
|
26
|
+
} | {
|
|
27
|
+
kind: 'DEFAULT';
|
|
28
|
+
} | {
|
|
29
|
+
kind: 'ERROR';
|
|
30
|
+
};
|
|
31
|
+
/** One flag, already resolved down to a single environment. */
|
|
32
|
+
export interface FlagSnapshot {
|
|
33
|
+
key: string;
|
|
34
|
+
value_type: FlagValueType;
|
|
35
|
+
default_value: unknown;
|
|
36
|
+
/** `false` means the kill switch is engaged for this environment. */
|
|
37
|
+
enabled: boolean;
|
|
38
|
+
/** `null` means "inherit `default_value`". */
|
|
39
|
+
environment_value?: unknown | null;
|
|
40
|
+
}
|
|
41
|
+
export interface FlagSnapshotResponse {
|
|
42
|
+
environment_id: number;
|
|
43
|
+
flags: FlagSnapshot[];
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Everything you know about the subject being evaluated.
|
|
47
|
+
*
|
|
48
|
+
* Accepted and ignored today: targeting has not shipped. It is in the signature
|
|
49
|
+
* now so that when it does, you add attributes to a call you have already
|
|
50
|
+
* written instead of editing every call site.
|
|
51
|
+
*/
|
|
52
|
+
export interface EvalContext {
|
|
53
|
+
/** Stable bucketing subject (user id, account id, device id). */
|
|
54
|
+
key?: string;
|
|
55
|
+
/** Targeting attributes, e.g. `{ plan: 'enterprise', region: 'eu' }`. */
|
|
56
|
+
attributes?: Record<string, string | number | boolean>;
|
|
57
|
+
}
|
|
58
|
+
export interface Evaluation<T> {
|
|
59
|
+
value: T;
|
|
60
|
+
/** Named variant, once variants exist. Always `null` today. */
|
|
61
|
+
variant: string | null;
|
|
62
|
+
reason: EvalReason;
|
|
63
|
+
}
|
|
64
|
+
export interface FlagsClientOptions {
|
|
65
|
+
/**
|
|
66
|
+
* Control-plane API base URL. Defaults to `TEMPS_API_URL`, which Temps
|
|
67
|
+
* injects into every deployment.
|
|
68
|
+
*/
|
|
69
|
+
apiUrl?: string;
|
|
70
|
+
/**
|
|
71
|
+
* Deployment token. Defaults to `TEMPS_API_TOKEN`, injected alongside
|
|
72
|
+
* `TEMPS_API_URL`.
|
|
73
|
+
*/
|
|
74
|
+
apiToken?: string;
|
|
75
|
+
/**
|
|
76
|
+
* Only needed when the token is project-wide rather than scoped to one
|
|
77
|
+
* environment.
|
|
78
|
+
*/
|
|
79
|
+
environmentId?: number;
|
|
80
|
+
/**
|
|
81
|
+
* Background refresh interval in milliseconds. Default 30s. Unchanged flags
|
|
82
|
+
* cost a 304, not a payload.
|
|
83
|
+
*/
|
|
84
|
+
refreshIntervalMs?: number;
|
|
85
|
+
/** Per-request timeout in milliseconds. Default 5s. */
|
|
86
|
+
timeoutMs?: number;
|
|
87
|
+
/**
|
|
88
|
+
* Report which flag keys were actually evaluated, on the refresh interval.
|
|
89
|
+
* Defaults to `true`.
|
|
90
|
+
*
|
|
91
|
+
* This is what makes "last evaluated" in the console meaningful — the server
|
|
92
|
+
* hands out the whole flag set and evaluation happens locally, so without it
|
|
93
|
+
* the control plane cannot tell a flag live code still reads from one nothing
|
|
94
|
+
* has called in a year. Only keys that exist in the snapshot are reported,
|
|
95
|
+
* and only on the interval, never per call.
|
|
96
|
+
*/
|
|
97
|
+
reportExposure?: boolean;
|
|
98
|
+
/**
|
|
99
|
+
* Called when a background refresh fails. Defaults to a `console.warn`.
|
|
100
|
+
* Failures never throw and never clear the cache — the last good snapshot
|
|
101
|
+
* keeps serving.
|
|
102
|
+
*/
|
|
103
|
+
onError?: (error: Error) => void;
|
|
104
|
+
}
|