@withgateway/sdk 0.1.3

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 (40) hide show
  1. package/README.md +229 -0
  2. package/dist/context/index.d.mts +225 -0
  3. package/dist/context/index.d.ts +225 -0
  4. package/dist/context/index.js +440 -0
  5. package/dist/context/index.js.map +1 -0
  6. package/dist/context/index.mjs +411 -0
  7. package/dist/context/index.mjs.map +1 -0
  8. package/dist/experiments/index.d.mts +260 -0
  9. package/dist/experiments/index.d.ts +260 -0
  10. package/dist/experiments/index.js +407 -0
  11. package/dist/experiments/index.js.map +1 -0
  12. package/dist/experiments/index.mjs +374 -0
  13. package/dist/experiments/index.mjs.map +1 -0
  14. package/dist/index-Caw3XVub.d.mts +193 -0
  15. package/dist/index-Caw3XVub.d.ts +193 -0
  16. package/dist/index.d.mts +20 -0
  17. package/dist/index.d.ts +20 -0
  18. package/dist/index.js +1476 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/index.mjs +1434 -0
  21. package/dist/index.mjs.map +1 -0
  22. package/dist/memory/index.d.mts +124 -0
  23. package/dist/memory/index.d.ts +124 -0
  24. package/dist/memory/index.js +192 -0
  25. package/dist/memory/index.js.map +1 -0
  26. package/dist/memory/index.mjs +164 -0
  27. package/dist/memory/index.mjs.map +1 -0
  28. package/dist/security/index.d.mts +114 -0
  29. package/dist/security/index.d.ts +114 -0
  30. package/dist/security/index.js +297 -0
  31. package/dist/security/index.js.map +1 -0
  32. package/dist/security/index.mjs +275 -0
  33. package/dist/security/index.mjs.map +1 -0
  34. package/dist/tracing/index.d.mts +1 -0
  35. package/dist/tracing/index.d.ts +1 -0
  36. package/dist/tracing/index.js +226 -0
  37. package/dist/tracing/index.js.map +1 -0
  38. package/dist/tracing/index.mjs +202 -0
  39. package/dist/tracing/index.mjs.map +1 -0
  40. package/package.json +112 -0
@@ -0,0 +1,260 @@
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+ import { Context } from '@opentelemetry/api';
3
+ import { SpanProcessor, Span, ReadableSpan } from '@opentelemetry/sdk-trace-base';
4
+
5
+ /**
6
+ * Type definitions for A/B experiments.
7
+ *
8
+ * These mirror the Python SDK types in gatewaysdk/sdk/src/gatewaysdk/experiments/types.py
9
+ */
10
+ interface Variant {
11
+ key: string;
12
+ weight: number;
13
+ config: Record<string, unknown>;
14
+ }
15
+ interface ExperimentConfig {
16
+ key: string;
17
+ variants: Variant[];
18
+ trafficPercent: number;
19
+ }
20
+ interface Exposure {
21
+ userId: string;
22
+ experimentId: string;
23
+ variantKey: string;
24
+ timestamp: string;
25
+ }
26
+ interface RegisterExperimentInput {
27
+ key: string;
28
+ variants: Array<{
29
+ key: string;
30
+ weight?: number;
31
+ config?: Record<string, unknown>;
32
+ }>;
33
+ trafficPercent?: number;
34
+ syncToBackend?: boolean;
35
+ evaluatorNames?: string[];
36
+ }
37
+ interface ExperimentContext {
38
+ experimentId: string;
39
+ variantKey: string;
40
+ userId: string;
41
+ }
42
+ interface ExperimentClientConfig {
43
+ apiUrl: string;
44
+ apiKey: string;
45
+ secretKey?: string;
46
+ projectId: string;
47
+ exposureLogger?: {
48
+ batchSize?: number;
49
+ flushIntervalMs?: number;
50
+ };
51
+ }
52
+ interface GetVariantResult {
53
+ variant: Variant | null;
54
+ inExperiment: boolean;
55
+ experimentKey: string;
56
+ run: <T>(fn: () => T) => T;
57
+ }
58
+ interface ExposureLoggerConfig {
59
+ apiUrl: string;
60
+ apiKey: string;
61
+ secretKey?: string;
62
+ batchSize?: number;
63
+ flushIntervalMs?: number;
64
+ }
65
+
66
+ /**
67
+ * Deterministic variant assignment for A/B experiments.
68
+ *
69
+ * Algorithm:
70
+ * 1. Hash (experiment_key + user_id) → deterministic bucket [0, 1)
71
+ * 2. If bucket >= traffic_percent/100 → user not in experiment
72
+ * 3. Otherwise, normalize bucket within traffic and assign to variant by weight
73
+ */
74
+
75
+ declare function computeHash(experimentKey: string, userId: string): number;
76
+ declare function assignVariant(config: ExperimentConfig, userId: string): Variant | null;
77
+
78
+ /**
79
+ * Async context management for experiments.
80
+ *
81
+ * Uses AsyncLocalStorage.enterWith() to set context that persists for the
82
+ * remainder of the current async execution context. This provides:
83
+ *
84
+ * - Request isolation in concurrent server environments
85
+ * - Context that survives across async boundaries (streaming, etc.)
86
+ * - No callback wrapper required
87
+ *
88
+ * The context persists until clearExperimentContext() is called or the
89
+ * async context naturally ends (e.g., request completes).
90
+ */
91
+
92
+ declare const experimentContextStorage: AsyncLocalStorage<ExperimentContext>;
93
+ /**
94
+ * Get the current experiment context.
95
+ */
96
+ declare function getExperimentContext(): ExperimentContext | undefined;
97
+ /**
98
+ * Set the experiment context for the current async execution.
99
+ *
100
+ * Uses enterWith() which sets context for the remainder of the current
101
+ * async execution without requiring a callback wrapper. This means:
102
+ * - Context persists across await boundaries
103
+ * - Context is isolated per request in concurrent environments
104
+ * - Context persists until clearExperimentContext() or request ends
105
+ *
106
+ * Called by getVariant() when a user is assigned to a variant.
107
+ */
108
+ declare function setExperimentContext(context: ExperimentContext): void;
109
+ /**
110
+ * Clear the experiment context.
111
+ *
112
+ * Call this when you're done with an experiment session (e.g., after handling
113
+ * a user request) to stop attributing spans to the experiment.
114
+ *
115
+ * Note: In most server frameworks, the async context naturally ends when the
116
+ * request completes, so this is optional but recommended for explicit cleanup.
117
+ */
118
+ declare function clearExperimentContext$1(): void;
119
+ /**
120
+ * Run a function with experiment context (scoped).
121
+ *
122
+ * The context is automatically cleared when the function completes.
123
+ * This is useful for synchronous operations or fully-contained async operations.
124
+ *
125
+ * For streaming/async patterns, prefer setExperimentContext() which persists
126
+ * across async boundaries.
127
+ */
128
+ declare function runWithExperimentContext<T>(context: ExperimentContext, fn: () => T): T;
129
+
130
+ /**
131
+ * Batched asynchronous exposure logging.
132
+ *
133
+ * Collects exposure events in memory and flushes periodically
134
+ * or when the batch size threshold is reached.
135
+ */
136
+
137
+ declare class ExposureLogger {
138
+ private buffer;
139
+ private readonly batchSize;
140
+ private readonly flushIntervalMs;
141
+ private readonly apiUrl;
142
+ private readonly apiKey;
143
+ private readonly secretKey;
144
+ private flushTimer;
145
+ private isFlushing;
146
+ constructor(config: ExposureLoggerConfig);
147
+ log(exposure: Exposure): void;
148
+ flush(): Promise<void>;
149
+ shutdown(): Promise<void>;
150
+ }
151
+
152
+ /**
153
+ * Main A/B experiment client for TypeScript.
154
+ *
155
+ * Mirrors the Python SDK's ExperimentClient in:
156
+ * gatewaysdk/sdk/src/gatewaysdk/experiments/client.py
157
+ */
158
+
159
+ declare class ExperimentClient {
160
+ private readonly apiUrl;
161
+ private readonly apiKey;
162
+ private readonly secretKey;
163
+ private readonly projectId;
164
+ private readonly configs;
165
+ private readonly exposureLogger;
166
+ constructor(config: ExperimentClientConfig);
167
+ register(input: RegisterExperimentInput): Promise<void>;
168
+ fetch(experimentKeys?: string[]): Promise<void>;
169
+ getVariant(experimentKey: string, userId: string, options?: {
170
+ fetchIfMissing?: boolean;
171
+ }): Promise<GetVariantResult>;
172
+ getConfig(experimentKey: string): ExperimentConfig | undefined;
173
+ shutdown(): Promise<void>;
174
+ private syncToBackendAsync;
175
+ }
176
+
177
+ /**
178
+ * OpenTelemetry integration for A/B experiments.
179
+ *
180
+ * Provides a SpanProcessor that automatically injects experiment
181
+ * context into spans. Mirrors the Python SDK's TracingContextSpanProcessor.
182
+ */
183
+
184
+ declare const EXPERIMENT_ATTRIBUTES: {
185
+ readonly EXPERIMENT_ID: "gateway.experiment.id";
186
+ readonly VARIANT_KEY: "gateway.variant.key";
187
+ readonly USER_ID: "gateway.experiment.user_id";
188
+ };
189
+ declare class ExperimentSpanProcessor implements SpanProcessor {
190
+ onStart(span: Span, _parentContext: Context): void;
191
+ onEnd(_span: ReadableSpan): void;
192
+ shutdown(): Promise<void>;
193
+ forceFlush(): Promise<void>;
194
+ }
195
+ declare function addExperimentAttributes(span: Span, experimentId: string, variantKey: string, userId: string): void;
196
+
197
+ /**
198
+ * Singleton experiment client for simple usage.
199
+ *
200
+ * This mirrors the Python SDK's `gateway.experiments` singleton pattern.
201
+ * For advanced use cases, instantiate ExperimentClient directly.
202
+ */
203
+
204
+ interface InitConfig {
205
+ apiKey: string;
206
+ secretKey?: string;
207
+ baseUrl: string;
208
+ projectId?: string;
209
+ }
210
+ /**
211
+ * Initialize the experiments singleton.
212
+ * Must be called before using other methods.
213
+ */
214
+ declare function init(config: InitConfig): void;
215
+ /**
216
+ * Register an experiment configuration.
217
+ */
218
+ declare function register(input: RegisterExperimentInput): Promise<void>;
219
+ /**
220
+ * Get variant for a user. Returns null if user is not in experiment.
221
+ */
222
+ declare function getVariant(experimentKey: string, userId: string, options?: {
223
+ fetchIfMissing?: boolean;
224
+ }): Promise<GetVariantResult>;
225
+ /**
226
+ * Fetch experiment configurations from the backend.
227
+ */
228
+ declare function fetch(experimentKeys?: string[]): Promise<void>;
229
+ /**
230
+ * Flush pending exposures and shut down the client.
231
+ */
232
+ declare function shutdown(): Promise<void>;
233
+ /**
234
+ * Clear the current experiment context.
235
+ *
236
+ * Call this when you're done with an experiment session (e.g., after handling
237
+ * a user request) to stop attributing new spans to the experiment.
238
+ *
239
+ * This mirrors Python's `gateway.experiments.clear_current_experiment()`.
240
+ */
241
+ declare function clearExperimentContext(): void;
242
+ /**
243
+ * Get the underlying ExperimentClient instance.
244
+ * Returns null if not initialized.
245
+ */
246
+ declare function getClient(): ExperimentClient | null;
247
+
248
+ type singleton_InitConfig = InitConfig;
249
+ declare const singleton_clearExperimentContext: typeof clearExperimentContext;
250
+ declare const singleton_fetch: typeof fetch;
251
+ declare const singleton_getClient: typeof getClient;
252
+ declare const singleton_getVariant: typeof getVariant;
253
+ declare const singleton_init: typeof init;
254
+ declare const singleton_register: typeof register;
255
+ declare const singleton_shutdown: typeof shutdown;
256
+ declare namespace singleton {
257
+ export { type singleton_InitConfig as InitConfig, singleton_clearExperimentContext as clearExperimentContext, singleton_fetch as fetch, singleton_getClient as getClient, singleton_getVariant as getVariant, singleton_init as init, singleton_register as register, singleton_shutdown as shutdown };
258
+ }
259
+
260
+ export { EXPERIMENT_ATTRIBUTES, ExperimentClient, type ExperimentClientConfig, type ExperimentConfig, type ExperimentContext, ExperimentSpanProcessor, type Exposure, ExposureLogger, type ExposureLoggerConfig, type GetVariantResult, type RegisterExperimentInput, type Variant, addExperimentAttributes, assignVariant, clearExperimentContext$1 as clearExperimentContext, computeHash, experimentContextStorage, singleton as experiments, getExperimentContext, runWithExperimentContext, setExperimentContext };
@@ -0,0 +1,260 @@
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+ import { Context } from '@opentelemetry/api';
3
+ import { SpanProcessor, Span, ReadableSpan } from '@opentelemetry/sdk-trace-base';
4
+
5
+ /**
6
+ * Type definitions for A/B experiments.
7
+ *
8
+ * These mirror the Python SDK types in gatewaysdk/sdk/src/gatewaysdk/experiments/types.py
9
+ */
10
+ interface Variant {
11
+ key: string;
12
+ weight: number;
13
+ config: Record<string, unknown>;
14
+ }
15
+ interface ExperimentConfig {
16
+ key: string;
17
+ variants: Variant[];
18
+ trafficPercent: number;
19
+ }
20
+ interface Exposure {
21
+ userId: string;
22
+ experimentId: string;
23
+ variantKey: string;
24
+ timestamp: string;
25
+ }
26
+ interface RegisterExperimentInput {
27
+ key: string;
28
+ variants: Array<{
29
+ key: string;
30
+ weight?: number;
31
+ config?: Record<string, unknown>;
32
+ }>;
33
+ trafficPercent?: number;
34
+ syncToBackend?: boolean;
35
+ evaluatorNames?: string[];
36
+ }
37
+ interface ExperimentContext {
38
+ experimentId: string;
39
+ variantKey: string;
40
+ userId: string;
41
+ }
42
+ interface ExperimentClientConfig {
43
+ apiUrl: string;
44
+ apiKey: string;
45
+ secretKey?: string;
46
+ projectId: string;
47
+ exposureLogger?: {
48
+ batchSize?: number;
49
+ flushIntervalMs?: number;
50
+ };
51
+ }
52
+ interface GetVariantResult {
53
+ variant: Variant | null;
54
+ inExperiment: boolean;
55
+ experimentKey: string;
56
+ run: <T>(fn: () => T) => T;
57
+ }
58
+ interface ExposureLoggerConfig {
59
+ apiUrl: string;
60
+ apiKey: string;
61
+ secretKey?: string;
62
+ batchSize?: number;
63
+ flushIntervalMs?: number;
64
+ }
65
+
66
+ /**
67
+ * Deterministic variant assignment for A/B experiments.
68
+ *
69
+ * Algorithm:
70
+ * 1. Hash (experiment_key + user_id) → deterministic bucket [0, 1)
71
+ * 2. If bucket >= traffic_percent/100 → user not in experiment
72
+ * 3. Otherwise, normalize bucket within traffic and assign to variant by weight
73
+ */
74
+
75
+ declare function computeHash(experimentKey: string, userId: string): number;
76
+ declare function assignVariant(config: ExperimentConfig, userId: string): Variant | null;
77
+
78
+ /**
79
+ * Async context management for experiments.
80
+ *
81
+ * Uses AsyncLocalStorage.enterWith() to set context that persists for the
82
+ * remainder of the current async execution context. This provides:
83
+ *
84
+ * - Request isolation in concurrent server environments
85
+ * - Context that survives across async boundaries (streaming, etc.)
86
+ * - No callback wrapper required
87
+ *
88
+ * The context persists until clearExperimentContext() is called or the
89
+ * async context naturally ends (e.g., request completes).
90
+ */
91
+
92
+ declare const experimentContextStorage: AsyncLocalStorage<ExperimentContext>;
93
+ /**
94
+ * Get the current experiment context.
95
+ */
96
+ declare function getExperimentContext(): ExperimentContext | undefined;
97
+ /**
98
+ * Set the experiment context for the current async execution.
99
+ *
100
+ * Uses enterWith() which sets context for the remainder of the current
101
+ * async execution without requiring a callback wrapper. This means:
102
+ * - Context persists across await boundaries
103
+ * - Context is isolated per request in concurrent environments
104
+ * - Context persists until clearExperimentContext() or request ends
105
+ *
106
+ * Called by getVariant() when a user is assigned to a variant.
107
+ */
108
+ declare function setExperimentContext(context: ExperimentContext): void;
109
+ /**
110
+ * Clear the experiment context.
111
+ *
112
+ * Call this when you're done with an experiment session (e.g., after handling
113
+ * a user request) to stop attributing spans to the experiment.
114
+ *
115
+ * Note: In most server frameworks, the async context naturally ends when the
116
+ * request completes, so this is optional but recommended for explicit cleanup.
117
+ */
118
+ declare function clearExperimentContext$1(): void;
119
+ /**
120
+ * Run a function with experiment context (scoped).
121
+ *
122
+ * The context is automatically cleared when the function completes.
123
+ * This is useful for synchronous operations or fully-contained async operations.
124
+ *
125
+ * For streaming/async patterns, prefer setExperimentContext() which persists
126
+ * across async boundaries.
127
+ */
128
+ declare function runWithExperimentContext<T>(context: ExperimentContext, fn: () => T): T;
129
+
130
+ /**
131
+ * Batched asynchronous exposure logging.
132
+ *
133
+ * Collects exposure events in memory and flushes periodically
134
+ * or when the batch size threshold is reached.
135
+ */
136
+
137
+ declare class ExposureLogger {
138
+ private buffer;
139
+ private readonly batchSize;
140
+ private readonly flushIntervalMs;
141
+ private readonly apiUrl;
142
+ private readonly apiKey;
143
+ private readonly secretKey;
144
+ private flushTimer;
145
+ private isFlushing;
146
+ constructor(config: ExposureLoggerConfig);
147
+ log(exposure: Exposure): void;
148
+ flush(): Promise<void>;
149
+ shutdown(): Promise<void>;
150
+ }
151
+
152
+ /**
153
+ * Main A/B experiment client for TypeScript.
154
+ *
155
+ * Mirrors the Python SDK's ExperimentClient in:
156
+ * gatewaysdk/sdk/src/gatewaysdk/experiments/client.py
157
+ */
158
+
159
+ declare class ExperimentClient {
160
+ private readonly apiUrl;
161
+ private readonly apiKey;
162
+ private readonly secretKey;
163
+ private readonly projectId;
164
+ private readonly configs;
165
+ private readonly exposureLogger;
166
+ constructor(config: ExperimentClientConfig);
167
+ register(input: RegisterExperimentInput): Promise<void>;
168
+ fetch(experimentKeys?: string[]): Promise<void>;
169
+ getVariant(experimentKey: string, userId: string, options?: {
170
+ fetchIfMissing?: boolean;
171
+ }): Promise<GetVariantResult>;
172
+ getConfig(experimentKey: string): ExperimentConfig | undefined;
173
+ shutdown(): Promise<void>;
174
+ private syncToBackendAsync;
175
+ }
176
+
177
+ /**
178
+ * OpenTelemetry integration for A/B experiments.
179
+ *
180
+ * Provides a SpanProcessor that automatically injects experiment
181
+ * context into spans. Mirrors the Python SDK's TracingContextSpanProcessor.
182
+ */
183
+
184
+ declare const EXPERIMENT_ATTRIBUTES: {
185
+ readonly EXPERIMENT_ID: "gateway.experiment.id";
186
+ readonly VARIANT_KEY: "gateway.variant.key";
187
+ readonly USER_ID: "gateway.experiment.user_id";
188
+ };
189
+ declare class ExperimentSpanProcessor implements SpanProcessor {
190
+ onStart(span: Span, _parentContext: Context): void;
191
+ onEnd(_span: ReadableSpan): void;
192
+ shutdown(): Promise<void>;
193
+ forceFlush(): Promise<void>;
194
+ }
195
+ declare function addExperimentAttributes(span: Span, experimentId: string, variantKey: string, userId: string): void;
196
+
197
+ /**
198
+ * Singleton experiment client for simple usage.
199
+ *
200
+ * This mirrors the Python SDK's `gateway.experiments` singleton pattern.
201
+ * For advanced use cases, instantiate ExperimentClient directly.
202
+ */
203
+
204
+ interface InitConfig {
205
+ apiKey: string;
206
+ secretKey?: string;
207
+ baseUrl: string;
208
+ projectId?: string;
209
+ }
210
+ /**
211
+ * Initialize the experiments singleton.
212
+ * Must be called before using other methods.
213
+ */
214
+ declare function init(config: InitConfig): void;
215
+ /**
216
+ * Register an experiment configuration.
217
+ */
218
+ declare function register(input: RegisterExperimentInput): Promise<void>;
219
+ /**
220
+ * Get variant for a user. Returns null if user is not in experiment.
221
+ */
222
+ declare function getVariant(experimentKey: string, userId: string, options?: {
223
+ fetchIfMissing?: boolean;
224
+ }): Promise<GetVariantResult>;
225
+ /**
226
+ * Fetch experiment configurations from the backend.
227
+ */
228
+ declare function fetch(experimentKeys?: string[]): Promise<void>;
229
+ /**
230
+ * Flush pending exposures and shut down the client.
231
+ */
232
+ declare function shutdown(): Promise<void>;
233
+ /**
234
+ * Clear the current experiment context.
235
+ *
236
+ * Call this when you're done with an experiment session (e.g., after handling
237
+ * a user request) to stop attributing new spans to the experiment.
238
+ *
239
+ * This mirrors Python's `gateway.experiments.clear_current_experiment()`.
240
+ */
241
+ declare function clearExperimentContext(): void;
242
+ /**
243
+ * Get the underlying ExperimentClient instance.
244
+ * Returns null if not initialized.
245
+ */
246
+ declare function getClient(): ExperimentClient | null;
247
+
248
+ type singleton_InitConfig = InitConfig;
249
+ declare const singleton_clearExperimentContext: typeof clearExperimentContext;
250
+ declare const singleton_fetch: typeof fetch;
251
+ declare const singleton_getClient: typeof getClient;
252
+ declare const singleton_getVariant: typeof getVariant;
253
+ declare const singleton_init: typeof init;
254
+ declare const singleton_register: typeof register;
255
+ declare const singleton_shutdown: typeof shutdown;
256
+ declare namespace singleton {
257
+ export { type singleton_InitConfig as InitConfig, singleton_clearExperimentContext as clearExperimentContext, singleton_fetch as fetch, singleton_getClient as getClient, singleton_getVariant as getVariant, singleton_init as init, singleton_register as register, singleton_shutdown as shutdown };
258
+ }
259
+
260
+ export { EXPERIMENT_ATTRIBUTES, ExperimentClient, type ExperimentClientConfig, type ExperimentConfig, type ExperimentContext, ExperimentSpanProcessor, type Exposure, ExposureLogger, type ExposureLoggerConfig, type GetVariantResult, type RegisterExperimentInput, type Variant, addExperimentAttributes, assignVariant, clearExperimentContext$1 as clearExperimentContext, computeHash, experimentContextStorage, singleton as experiments, getExperimentContext, runWithExperimentContext, setExperimentContext };