@temps-sdk/node-sdk 0.0.5 → 0.0.8-beta.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 (42) hide show
  1. package/dist/analytics/identify.d.ts +72 -0
  2. package/dist/analytics/identify.js +103 -0
  3. package/dist/analytics/index.d.ts +6 -0
  4. package/dist/analytics/index.js +6 -0
  5. package/dist/client/client/client.gen.js +2 -0
  6. package/dist/client/client/index.js +2 -1
  7. package/dist/client/client/types.gen.js +2 -1
  8. package/dist/client/client/utils.gen.js +2 -0
  9. package/dist/client/client.gen.js +2 -1
  10. package/dist/client/core/auth.gen.js +2 -1
  11. package/dist/client/core/bodySerializer.gen.js +2 -1
  12. package/dist/client/core/params.gen.js +2 -1
  13. package/dist/client/core/pathSerializer.gen.js +2 -1
  14. package/dist/client/core/serverSentEvents.gen.js +2 -1
  15. package/dist/client/core/types.gen.js +2 -1
  16. package/dist/client/core/utils.gen.js +2 -1
  17. package/dist/client/index.js +2 -0
  18. package/dist/client/sdk.gen.d.ts +20 -0
  19. package/dist/client/sdk.gen.js +80 -2
  20. package/dist/client/types.gen.d.ts +661 -8
  21. package/dist/client/types.gen.js +2 -1
  22. package/dist/errors/client.js +2 -0
  23. package/dist/errors/hub.js +2 -0
  24. package/dist/errors/index.js +2 -0
  25. package/dist/errors/scope.js +2 -0
  26. package/dist/errors/stacktrace.js +2 -0
  27. package/dist/errors/transaction.js +2 -0
  28. package/dist/errors/transport.js +2 -0
  29. package/dist/errors/types.js +2 -0
  30. package/dist/flags/client.d.ts +89 -0
  31. package/dist/flags/client.js +279 -0
  32. package/dist/flags/evaluate.d.ts +23 -0
  33. package/dist/flags/evaluate.js +307 -0
  34. package/dist/flags/index.d.ts +3 -0
  35. package/dist/flags/index.js +4 -0
  36. package/dist/flags/sha256.d.ts +4 -0
  37. package/dist/flags/sha256.js +81 -0
  38. package/dist/flags/types.d.ts +147 -0
  39. package/dist/flags/types.js +3 -0
  40. package/dist/index.d.ts +88 -0
  41. package/dist/index.js +9201 -548
  42. package/package.json +8 -3
@@ -1,2 +1,3 @@
1
- // This file is auto-generated by @hey-api/openapi-ts
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
2
3
  export {};
@@ -1,3 +1,5 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
1
3
  import { Hub } from './hub.js';
2
4
  import { createTransportFromDsn } from './transport.js';
3
5
  import { exceptionFromError, extractErrorMessage, isError } from './stacktrace.js';
@@ -1,3 +1,5 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
1
3
  import { Scope } from './scope.js';
2
4
  export class Hub {
3
5
  scopes = [];
@@ -1,3 +1,5 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
1
3
  import { ErrorTrackingClient } from './client.js';
2
4
  let globalClient = null;
3
5
  export function init(options) {
@@ -1,3 +1,5 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
1
3
  export class Scope {
2
4
  user = null;
3
5
  tags = {};
@@ -1,3 +1,5 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
1
3
  const STACKTRACE_LIMIT = 50;
2
4
  export function parseStackTrace(error) {
3
5
  if (!error.stack) {
@@ -1,3 +1,5 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
1
3
  export class TransactionImpl {
2
4
  onFinish;
3
5
  name;
@@ -1,3 +1,5 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
1
3
  export class HttpTransport {
2
4
  url;
3
5
  headers;
@@ -1 +1,3 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
1
3
  export {};
@@ -0,0 +1,89 @@
1
+ import type { EvalContext, Evaluation, FlagsClientOptions } from './types';
2
+ export declare class FlagsClient {
3
+ private readonly apiUrl;
4
+ private readonly apiToken;
5
+ private readonly environmentId?;
6
+ private readonly refreshIntervalMs;
7
+ private readonly timeoutMs;
8
+ private readonly reportExposure;
9
+ private readonly onError;
10
+ private flags;
11
+ private etag;
12
+ private timer;
13
+ /**
14
+ * Keys actually evaluated since the last report.
15
+ *
16
+ * Only keys present in the snapshot are recorded, which bounds this by the
17
+ * project's flag count — a caller doing `get('user-' + id, ...)` cannot grow
18
+ * it without limit.
19
+ */
20
+ private evaluated;
21
+ /** True once a snapshot has been successfully loaded at least once. */
22
+ ready: boolean;
23
+ /**
24
+ * The most recent refresh failure, or `null`. Exposed rather than swallowed:
25
+ * a self-hosted operator debugging alone needs to see that flags are stale,
26
+ * not guess why a rollout did nothing.
27
+ */
28
+ lastError: Error | null;
29
+ constructor(options?: FlagsClientOptions);
30
+ /**
31
+ * Load the first snapshot and start background refresh.
32
+ *
33
+ * Never throws. A flag service that is unreachable must not stop an app from
34
+ * booting — every `get()` returns its caller-supplied fallback until a
35
+ * snapshot arrives, and `ready` stays `false` so you can surface it.
36
+ */
37
+ init(): Promise<void>;
38
+ /** Stop background refresh. Safe to call more than once. */
39
+ close(): void;
40
+ /**
41
+ * Read a flag. Synchronous, in-memory, no network I/O.
42
+ *
43
+ * `fallback` is returned whenever the flag cannot be resolved — unknown key,
44
+ * snapshot not loaded yet, or a stored value that does not match the flag's
45
+ * declared type.
46
+ */
47
+ get<T>(key: string, context: EvalContext | undefined, fallback: T): T;
48
+ /**
49
+ * Read a flag along with the reason it resolved that way.
50
+ *
51
+ * Use this when debugging "why is this user seeing the old checkout?" — the
52
+ * reason distinguishes a kill switch from an unset value from a flag that
53
+ * does not exist.
54
+ */
55
+ getDetails<T>(key: string, context: EvalContext | undefined, fallback: T): Evaluation<T>;
56
+ /** Every flag key currently cached. */
57
+ keys(): string[];
58
+ /**
59
+ * Fetch the snapshot once.
60
+ *
61
+ * A failure leaves the previous snapshot in place: stale flags are far better
62
+ * than every flag suddenly reverting to its fallback because the control
63
+ * plane blinked.
64
+ */
65
+ refresh(): Promise<void>;
66
+ /**
67
+ * Report which flags were actually evaluated since the last flush.
68
+ *
69
+ * This is what gives `last evaluated` in the console a real meaning: the
70
+ * server hands out the whole flag set and evaluation happens here, so
71
+ * without this it could only ever know that *something* fetched the list.
72
+ *
73
+ * Best-effort. A failure drops the batch rather than retrying forever —
74
+ * usage telemetry must never grow unboundedly or interfere with reads.
75
+ */
76
+ flushExposure(): Promise<void>;
77
+ private fail;
78
+ }
79
+ /**
80
+ * Process-wide client, for the common case where an app has one flag set.
81
+ *
82
+ * ```ts
83
+ * import { flags } from '@temps-sdk/node-sdk';
84
+ *
85
+ * await flags.init();
86
+ * if (flags.get('checkout.v2', { key: user.id }, false)) { ... }
87
+ * ```
88
+ */
89
+ export declare const flags: FlagsClient;
@@ -0,0 +1,279 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
3
+ /**
4
+ * In-memory feature-flag client for services running on Temps.
5
+ *
6
+ * Reads are synchronous and cost no network I/O: the whole environment's flag
7
+ * set lives in memory and is refreshed in the background. That is the point —
8
+ * a per-check HTTP round trip (~200-500ms) is unusable in a request handler.
9
+ *
10
+ * Zero configuration on Temps: `TEMPS_API_URL` and `TEMPS_API_TOKEN` are
11
+ * injected into every deployment, and the token pins the project (and usually
12
+ * the environment), so `new FlagsClient()` already knows what to fetch.
13
+ */
14
+ import { evaluate } from './evaluate';
15
+ const DEFAULT_REFRESH_INTERVAL_MS = 30_000;
16
+ const DEFAULT_TIMEOUT_MS = 5_000;
17
+ /**
18
+ * Matches `MAX_EXPOSURE_KEYS` on the server, which now rejects (rather than
19
+ * truncates) an over-sized batch. A project with more flags than this must be
20
+ * chunked, or its overflow keys would never be stamped.
21
+ */
22
+ const MAX_EXPOSURE_KEYS = 500;
23
+ /**
24
+ * Read an environment variable without depending on Node type definitions.
25
+ *
26
+ * This package is consumed from browsers too, so `lib` is DOM-flavoured and
27
+ * there is no `process` global in the type environment. Going through
28
+ * `globalThis` keeps the client usable in both without pulling `@types/node`
29
+ * into every consumer.
30
+ */
31
+ function envVar(name) {
32
+ const global = globalThis;
33
+ return global.process?.env?.[name];
34
+ }
35
+ /**
36
+ * Parse `TEMPS_FLAGS_REFRESH_INTERVAL_MS`, falling back to `fallback` for an
37
+ * unset, non-numeric, or negative value.
38
+ *
39
+ * A malformed value is surfaced via `console.warn` rather than silently
40
+ * ignored — an operator who set this and sees no effect needs to know the
41
+ * value they set was rejected, not that the feature doesn't exist.
42
+ */
43
+ function refreshIntervalFromEnv(fallback) {
44
+ const raw = envVar('TEMPS_FLAGS_REFRESH_INTERVAL_MS');
45
+ if (raw === undefined)
46
+ return fallback;
47
+ const parsed = Number(raw);
48
+ if (!Number.isFinite(parsed) || parsed < 0) {
49
+ console.warn(`[temps-flags] TEMPS_FLAGS_REFRESH_INTERVAL_MS=${JSON.stringify(raw)} is not a valid non-negative number. Using the default of ${fallback}ms instead.`);
50
+ return fallback;
51
+ }
52
+ return parsed;
53
+ }
54
+ export class FlagsClient {
55
+ apiUrl;
56
+ apiToken;
57
+ environmentId;
58
+ refreshIntervalMs;
59
+ timeoutMs;
60
+ reportExposure;
61
+ onError;
62
+ flags = new Map();
63
+ etag = null;
64
+ timer = null;
65
+ /**
66
+ * Keys actually evaluated since the last report.
67
+ *
68
+ * Only keys present in the snapshot are recorded, which bounds this by the
69
+ * project's flag count — a caller doing `get('user-' + id, ...)` cannot grow
70
+ * it without limit.
71
+ */
72
+ evaluated = new Set();
73
+ /** True once a snapshot has been successfully loaded at least once. */
74
+ ready = false;
75
+ /**
76
+ * The most recent refresh failure, or `null`. Exposed rather than swallowed:
77
+ * a self-hosted operator debugging alone needs to see that flags are stale,
78
+ * not guess why a rollout did nothing.
79
+ */
80
+ lastError = null;
81
+ constructor(options = {}) {
82
+ this.apiUrl = (options.apiUrl ?? envVar('TEMPS_API_URL') ?? '').replace(/\/+$/, '');
83
+ this.apiToken = options.apiToken ?? envVar('TEMPS_API_TOKEN') ?? '';
84
+ this.environmentId = options.environmentId;
85
+ this.refreshIntervalMs =
86
+ options.refreshIntervalMs ?? refreshIntervalFromEnv(DEFAULT_REFRESH_INTERVAL_MS);
87
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
88
+ this.reportExposure = options.reportExposure ?? true;
89
+ this.onError =
90
+ options.onError ??
91
+ ((error) => {
92
+ console.warn(`[temps-flags] ${error.message}`);
93
+ });
94
+ }
95
+ /**
96
+ * Load the first snapshot and start background refresh.
97
+ *
98
+ * Never throws. A flag service that is unreachable must not stop an app from
99
+ * booting — every `get()` returns its caller-supplied fallback until a
100
+ * snapshot arrives, and `ready` stays `false` so you can surface it.
101
+ */
102
+ async init() {
103
+ if (!this.apiUrl || !this.apiToken) {
104
+ 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.'));
105
+ }
106
+ else {
107
+ await this.refresh();
108
+ }
109
+ if (this.timer === null && this.refreshIntervalMs > 0) {
110
+ this.timer = setInterval(() => {
111
+ void this.refresh();
112
+ void this.flushExposure();
113
+ }, this.refreshIntervalMs);
114
+ // On Node, don't hold the process open just to poll for flags. No-op in
115
+ // a browser, where timer handles are plain numbers.
116
+ this.timer.unref?.();
117
+ }
118
+ }
119
+ /** Stop background refresh. Safe to call more than once. */
120
+ close() {
121
+ if (this.timer !== null) {
122
+ clearInterval(this.timer);
123
+ this.timer = null;
124
+ }
125
+ // Best-effort final report so a graceful shutdown doesn't discard the
126
+ // last interval's worth of usage.
127
+ void this.flushExposure();
128
+ }
129
+ /**
130
+ * Read a flag. Synchronous, in-memory, no network I/O.
131
+ *
132
+ * `fallback` is returned whenever the flag cannot be resolved — unknown key,
133
+ * snapshot not loaded yet, or a stored value that does not match the flag's
134
+ * declared type.
135
+ */
136
+ get(key, context = {}, fallback) {
137
+ return this.getDetails(key, context, fallback).value;
138
+ }
139
+ /**
140
+ * Read a flag along with the reason it resolved that way.
141
+ *
142
+ * Use this when debugging "why is this user seeing the old checkout?" — the
143
+ * reason distinguishes a kill switch from an unset value from a flag that
144
+ * does not exist.
145
+ */
146
+ getDetails(key, context = {}, fallback) {
147
+ const flag = this.flags.get(key);
148
+ // Note the key in memory only — reporting happens on the refresh interval.
149
+ // Writing per evaluation would put a network call in the caller's hot path,
150
+ // which is the entire thing this client exists to avoid.
151
+ if (flag && this.reportExposure) {
152
+ this.evaluated.add(key);
153
+ }
154
+ return evaluate(flag, context, fallback);
155
+ }
156
+ /** Every flag key currently cached. */
157
+ keys() {
158
+ return [...this.flags.keys()];
159
+ }
160
+ /**
161
+ * Fetch the snapshot once.
162
+ *
163
+ * A failure leaves the previous snapshot in place: stale flags are far better
164
+ * than every flag suddenly reverting to its fallback because the control
165
+ * plane blinked.
166
+ */
167
+ async refresh() {
168
+ const controller = new AbortController();
169
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
170
+ try {
171
+ const url = new URL(`${this.apiUrl}/flags/snapshot`);
172
+ if (this.environmentId !== undefined) {
173
+ url.searchParams.set('environment_id', String(this.environmentId));
174
+ }
175
+ const headers = {
176
+ Authorization: `Bearer ${this.apiToken}`,
177
+ Accept: 'application/json',
178
+ };
179
+ if (this.etag) {
180
+ headers['If-None-Match'] = this.etag;
181
+ }
182
+ const response = await fetch(url, { headers, signal: controller.signal });
183
+ // Nothing changed since the last poll — the common case.
184
+ if (response.status === 304) {
185
+ this.lastError = null;
186
+ return;
187
+ }
188
+ if (!response.ok) {
189
+ this.fail(new Error(`Flag snapshot request failed: ${response.status} ${response.statusText}. Serving ${this.ready ? 'the last known' : 'fallback'} values.`));
190
+ return;
191
+ }
192
+ const body = (await response.json());
193
+ const next = new Map();
194
+ for (const flag of body.flags ?? []) {
195
+ next.set(flag.key, flag);
196
+ }
197
+ this.flags = next;
198
+ this.etag = response.headers.get('etag');
199
+ this.ready = true;
200
+ this.lastError = null;
201
+ }
202
+ catch (error) {
203
+ const reason = error instanceof Error ? error.message : String(error);
204
+ this.fail(new Error(`Flag snapshot request failed: ${reason}. Serving ${this.ready ? 'the last known' : 'fallback'} values.`));
205
+ }
206
+ finally {
207
+ clearTimeout(timeout);
208
+ }
209
+ }
210
+ /**
211
+ * Report which flags were actually evaluated since the last flush.
212
+ *
213
+ * This is what gives `last evaluated` in the console a real meaning: the
214
+ * server hands out the whole flag set and evaluation happens here, so
215
+ * without this it could only ever know that *something* fetched the list.
216
+ *
217
+ * Best-effort. A failure drops the batch rather than retrying forever —
218
+ * usage telemetry must never grow unboundedly or interfere with reads.
219
+ */
220
+ async flushExposure() {
221
+ if (!this.reportExposure || this.evaluated.size === 0)
222
+ return;
223
+ if (!this.apiUrl || !this.apiToken)
224
+ return;
225
+ // Take the batch up front so evaluations during the request aren't lost.
226
+ const pending = [...this.evaluated];
227
+ this.evaluated.clear();
228
+ // Chunk to the server's cap. It rejects over-sized batches outright, so a
229
+ // project with >500 flags would otherwise have its whole report refused
230
+ // and those flags would read as "never evaluated" forever.
231
+ for (let i = 0; i < pending.length; i += MAX_EXPOSURE_KEYS) {
232
+ const keys = pending.slice(i, i + MAX_EXPOSURE_KEYS);
233
+ const controller = new AbortController();
234
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
235
+ try {
236
+ const response = await fetch(`${this.apiUrl}/flags/exposure`, {
237
+ method: 'POST',
238
+ headers: {
239
+ Authorization: `Bearer ${this.apiToken}`,
240
+ 'Content-Type': 'application/json',
241
+ },
242
+ body: JSON.stringify({ keys }),
243
+ signal: controller.signal,
244
+ });
245
+ // Put a rejected batch back so the next flush retries it. Bounded by
246
+ // the flag count, so this cannot grow without limit.
247
+ if (!response.ok) {
248
+ for (const key of keys)
249
+ this.evaluated.add(key);
250
+ }
251
+ }
252
+ catch {
253
+ // Deliberately silent: a dropped usage report is not worth a warning
254
+ // in the app's logs, and `lastError` is reserved for the failure that
255
+ // actually matters (flags going stale).
256
+ for (const key of keys)
257
+ this.evaluated.add(key);
258
+ }
259
+ finally {
260
+ clearTimeout(timeout);
261
+ }
262
+ }
263
+ }
264
+ fail(error) {
265
+ this.lastError = error;
266
+ this.onError(error);
267
+ }
268
+ }
269
+ /**
270
+ * Process-wide client, for the common case where an app has one flag set.
271
+ *
272
+ * ```ts
273
+ * import { flags } from '@temps-sdk/node-sdk';
274
+ *
275
+ * await flags.init();
276
+ * if (flags.get('checkout.v2', { key: user.id }, false)) { ... }
277
+ * ```
278
+ */
279
+ export const flags = new FlagsClient();
@@ -0,0 +1,23 @@
1
+ import type { EvalContext, Evaluation, FlagSnapshot, FlagValueType } from './types';
2
+ /**
3
+ * Longest string a `matches` condition is tested against. JavaScript regular
4
+ * expressions backtrack (the server's do not), so the SDK bounds the input a
5
+ * pattern can be run on. Longer values never match.
6
+ */
7
+ export declare const MAX_MATCHED_LENGTH = 1024;
8
+ /**
9
+ * Whether a concrete JSON value is admissible for a declared flag type.
10
+ *
11
+ * `json` accepts anything except `null`: a flag must always resolve to
12
+ * something usable, and `null` is indistinguishable from "unset".
13
+ */
14
+ export declare function valueMatchesType(valueType: FlagValueType, value: unknown): boolean;
15
+ /**
16
+ * Stable bucket in [0, 100]. Identical to `bucket()` on the server: the first
17
+ * 32 bits of SHA-256 over `key:salt:subject`.
18
+ */
19
+ export declare function bucket(flagKey: string, salt: string, subject: string): number;
20
+ /** The split position, independent of the rollout bucket. */
21
+ export declare function splitBucket(flagKey: string, salt: string, subject: string): number;
22
+ /** Evaluate one flag. Always returns a usable value. */
23
+ export declare function evaluate<T>(flag: FlagSnapshot | undefined, context: EvalContext, fallback: T): Evaluation<T>;