@replanejs/sdk 0.5.12 → 0.6.2

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/index.cjs CHANGED
@@ -18,619 +18,20 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var src_exports = {};
20
20
  __export(src_exports, {
21
- ReplaneError: () => ReplaneError,
22
- createInMemoryReplaneClient: () => createInMemoryReplaneClient,
23
- createReplaneClient: () => createReplaneClient
21
+ ReplaneError: () => import_error.ReplaneError,
22
+ ReplaneErrorCode: () => import_error.ReplaneErrorCode,
23
+ createInMemoryReplaneClient: () => import_client.createInMemoryReplaneClient,
24
+ createReplaneClient: () => import_client.createReplaneClient,
25
+ restoreReplaneClient: () => import_client.restoreReplaneClient
24
26
  });
25
27
  module.exports = __toCommonJS(src_exports);
26
- const SUPPORTED_REPLICATION_STREAM_RECORD_TYPES = Object.keys({
27
- config_change: true,
28
- init: true
29
- });
30
- function fnv1a32(input) {
31
- const encoder = new TextEncoder();
32
- const bytes = encoder.encode(input);
33
- let hash = 2166136261 >>> 0;
34
- for (let i = 0; i < bytes.length; i++) {
35
- hash ^= bytes[i];
36
- hash = Math.imul(hash, 16777619) >>> 0;
37
- }
38
- return hash >>> 0;
39
- }
40
- function fnv1a32ToUnit(input) {
41
- const h = fnv1a32(input);
42
- return h / 2 ** 32;
43
- }
44
- function evaluateOverrides(baseValue, overrides, context, logger) {
45
- for (const override of overrides) {
46
- let overrideResult = "matched";
47
- const results = override.conditions.map((c) => evaluateCondition(c, context, logger));
48
- if (results.some((r) => r === "not_matched")) {
49
- overrideResult = "not_matched";
50
- } else if (results.some((r) => r === "unknown")) {
51
- overrideResult = "unknown";
52
- }
53
- if (overrideResult === "matched") {
54
- return override.value;
55
- }
56
- }
57
- return baseValue;
58
- }
59
- function evaluateCondition(condition, context, logger) {
60
- const operator = condition.operator;
61
- if (operator === "and") {
62
- const results = condition.conditions.map((c) => evaluateCondition(c, context, logger));
63
- if (results.some((r) => r === "not_matched")) return "not_matched";
64
- if (results.some((r) => r === "unknown")) return "unknown";
65
- return "matched";
66
- }
67
- if (operator === "or") {
68
- const results = condition.conditions.map((c) => evaluateCondition(c, context, logger));
69
- if (results.some((r) => r === "matched")) return "matched";
70
- if (results.some((r) => r === "unknown")) return "unknown";
71
- return "not_matched";
72
- }
73
- if (operator === "not") {
74
- const result = evaluateCondition(condition.condition, context, logger);
75
- if (result === "matched") return "not_matched";
76
- if (result === "not_matched") return "matched";
77
- return "unknown";
78
- }
79
- if (operator === "segmentation") {
80
- const contextValue2 = context[condition.property];
81
- if (contextValue2 === void 0 || contextValue2 === null) {
82
- return "unknown";
83
- }
84
- const hashInput = String(contextValue2) + condition.seed;
85
- const unitValue = fnv1a32ToUnit(hashInput);
86
- return unitValue >= condition.fromPercentage / 100 && unitValue < condition.toPercentage / 100 ? "matched" : "not_matched";
87
- }
88
- const property = condition.property;
89
- const contextValue = context[property];
90
- const expectedValue = condition.value;
91
- if (contextValue === void 0) {
92
- return "unknown";
93
- }
94
- const castedValue = castToContextType(expectedValue, contextValue);
95
- switch (operator) {
96
- case "equals":
97
- return contextValue === castedValue ? "matched" : "not_matched";
98
- case "in":
99
- if (!Array.isArray(castedValue)) return "unknown";
100
- return castedValue.includes(contextValue) ? "matched" : "not_matched";
101
- case "not_in":
102
- if (!Array.isArray(castedValue)) return "unknown";
103
- return !castedValue.includes(contextValue) ? "matched" : "not_matched";
104
- case "less_than":
105
- if (typeof contextValue === "number" && typeof castedValue === "number") {
106
- return contextValue < castedValue ? "matched" : "not_matched";
107
- }
108
- if (typeof contextValue === "string" && typeof castedValue === "string") {
109
- return contextValue < castedValue ? "matched" : "not_matched";
110
- }
111
- return "not_matched";
112
- case "less_than_or_equal":
113
- if (typeof contextValue === "number" && typeof castedValue === "number") {
114
- return contextValue <= castedValue ? "matched" : "not_matched";
115
- }
116
- if (typeof contextValue === "string" && typeof castedValue === "string") {
117
- return contextValue <= castedValue ? "matched" : "not_matched";
118
- }
119
- return "not_matched";
120
- case "greater_than":
121
- if (typeof contextValue === "number" && typeof castedValue === "number") {
122
- return contextValue > castedValue ? "matched" : "not_matched";
123
- }
124
- if (typeof contextValue === "string" && typeof castedValue === "string") {
125
- return contextValue > castedValue ? "matched" : "not_matched";
126
- }
127
- return "not_matched";
128
- case "greater_than_or_equal":
129
- if (typeof contextValue === "number" && typeof castedValue === "number") {
130
- return contextValue >= castedValue ? "matched" : "not_matched";
131
- }
132
- if (typeof contextValue === "string" && typeof castedValue === "string") {
133
- return contextValue >= castedValue ? "matched" : "not_matched";
134
- }
135
- return "not_matched";
136
- default:
137
- warnNever(operator, logger, `Unexpected operator: ${operator}`);
138
- return "unknown";
139
- }
140
- }
141
- function warnNever(value, logger, message) {
142
- logger.warn(message, { value });
143
- }
144
- function castToContextType(expectedValue, contextValue) {
145
- if (typeof contextValue === "number") {
146
- if (typeof expectedValue === "string") {
147
- const num = Number(expectedValue);
148
- return isNaN(num) ? expectedValue : num;
149
- }
150
- return expectedValue;
151
- }
152
- if (typeof contextValue === "boolean") {
153
- if (typeof expectedValue === "string") {
154
- if (expectedValue === "true") return true;
155
- if (expectedValue === "false") return false;
156
- }
157
- if (typeof expectedValue === "number") {
158
- return expectedValue !== 0;
159
- }
160
- return expectedValue;
161
- }
162
- if (typeof contextValue === "string") {
163
- if (typeof expectedValue === "number" || typeof expectedValue === "boolean") {
164
- return String(expectedValue);
165
- }
166
- return expectedValue;
167
- }
168
- return expectedValue;
169
- }
170
- async function delay(ms) {
171
- return new Promise((resolve) => setTimeout(resolve, ms));
172
- }
173
- async function retryDelay(averageDelay) {
174
- const jitter = averageDelay / 5;
175
- const delayMs = averageDelay + Math.random() * jitter - jitter / 2;
176
- await delay(delayMs);
177
- }
178
- class ReplaneRemoteStorage {
179
- closeController = new AbortController();
180
- // never throws
181
- async *startReplicationStream(options) {
182
- const { signal, cleanUpSignals } = combineAbortSignals([
183
- this.closeController.signal,
184
- options.signal
185
- ]);
186
- try {
187
- let failedAttempts = 0;
188
- while (!signal.aborted) {
189
- try {
190
- for await (const event of this.startReplicationStreamImpl({
191
- ...options,
192
- signal,
193
- onConnect: () => {
194
- failedAttempts = 0;
195
- }
196
- })) {
197
- yield event;
198
- }
199
- } catch (error) {
200
- failedAttempts++;
201
- const retryDelayMs = Math.min(options.retryDelayMs * 2 ** (failedAttempts - 1), 1e4);
202
- if (!signal.aborted) {
203
- options.logger.error(
204
- `Failed to fetch project events, retrying in ${retryDelayMs}ms...`,
205
- error
206
- );
207
- await retryDelay(retryDelayMs);
208
- }
209
- }
210
- }
211
- } finally {
212
- cleanUpSignals();
213
- }
214
- }
215
- async *startReplicationStreamImpl(options) {
216
- const inactivityAbortController = new AbortController();
217
- const { signal: combinedSignal, cleanUpSignals } = options.signal ? combineAbortSignals([options.signal, inactivityAbortController.signal]) : { signal: inactivityAbortController.signal, cleanUpSignals: () => {
218
- } };
219
- let inactivityTimer = null;
220
- const resetInactivityTimer = () => {
221
- if (inactivityTimer) clearTimeout(inactivityTimer);
222
- inactivityTimer = setTimeout(() => {
223
- inactivityAbortController.abort();
224
- }, options.inactivityTimeoutMs);
225
- };
226
- try {
227
- const rawEvents = fetchSse({
228
- fetchFn: options.fetchFn,
229
- headers: {
230
- Authorization: this.getAuthHeader(options),
231
- "Content-Type": "application/json"
232
- },
233
- body: JSON.stringify(options.getBody()),
234
- timeoutMs: options.requestTimeoutMs,
235
- method: "POST",
236
- signal: combinedSignal,
237
- url: this.getApiEndpoint(`/sdk/v1/replication/stream`, options),
238
- onConnect: () => {
239
- resetInactivityTimer();
240
- options.onConnect?.();
241
- }
242
- });
243
- for await (const sseEvent of rawEvents) {
244
- resetInactivityTimer();
245
- if (sseEvent.type === "ping") continue;
246
- const event = JSON.parse(sseEvent.payload);
247
- if (typeof event === "object" && event !== null && "type" in event && typeof event.type === "string" && SUPPORTED_REPLICATION_STREAM_RECORD_TYPES.includes(event.type)) {
248
- yield event;
249
- }
250
- }
251
- } finally {
252
- if (inactivityTimer) clearTimeout(inactivityTimer);
253
- cleanUpSignals();
254
- }
255
- }
256
- close() {
257
- this.closeController.abort();
258
- }
259
- getAuthHeader(options) {
260
- return `Bearer ${options.sdkKey}`;
261
- }
262
- getApiEndpoint(path, options) {
263
- return `${options.baseUrl}/api${path}`;
264
- }
265
- }
266
- var ReplaneErrorCode = /* @__PURE__ */ ((ReplaneErrorCode2) => {
267
- ReplaneErrorCode2["NotFound"] = "not_found";
268
- ReplaneErrorCode2["Timeout"] = "timeout";
269
- ReplaneErrorCode2["NetworkError"] = "network_error";
270
- ReplaneErrorCode2["AuthError"] = "auth_error";
271
- ReplaneErrorCode2["Forbidden"] = "forbidden";
272
- ReplaneErrorCode2["ServerError"] = "server_error";
273
- ReplaneErrorCode2["ClientError"] = "client_error";
274
- ReplaneErrorCode2["Closed"] = "closed";
275
- ReplaneErrorCode2["NotInitialized"] = "not_initialized";
276
- ReplaneErrorCode2["Unknown"] = "unknown";
277
- return ReplaneErrorCode2;
278
- })(ReplaneErrorCode || {});
279
- class ReplaneError extends Error {
280
- code;
281
- constructor(params) {
282
- super(params.message, { cause: params.cause });
283
- this.name = "ReplaneError";
284
- this.code = params.code;
285
- }
286
- }
287
- async function createReplaneClient(sdkOptions) {
288
- const storage = new ReplaneRemoteStorage();
289
- return await _createReplaneClient(toFinalOptions(sdkOptions), storage);
290
- }
291
- function createInMemoryReplaneClient(initialData) {
292
- return {
293
- get: (configName) => {
294
- const config = initialData[configName];
295
- if (config === void 0) {
296
- throw new ReplaneError({
297
- message: `Config not found: ${String(configName)}`,
298
- code: "not_found" /* NotFound */
299
- });
300
- }
301
- return config;
302
- },
303
- subscribe: () => {
304
- return () => {
305
- };
306
- },
307
- close: () => {
308
- }
309
- };
310
- }
311
- async function _createReplaneClient(sdkOptions, storage) {
312
- if (!sdkOptions.sdkKey) throw new Error("SDK key is required");
313
- const configs = new Map(
314
- sdkOptions.fallbacks.map((config) => [config.name, config])
315
- );
316
- const clientReady = new Deferred();
317
- const configSubscriptions = /* @__PURE__ */ new Map();
318
- const clientSubscriptions = /* @__PURE__ */ new Set();
319
- (async () => {
320
- try {
321
- const replicationStream = storage.startReplicationStream({
322
- ...sdkOptions,
323
- getBody: () => ({
324
- currentConfigs: [...configs.values()].map((config) => ({
325
- name: config.name,
326
- overrides: config.overrides,
327
- version: config.version,
328
- value: config.value
329
- })),
330
- requiredConfigs: sdkOptions.requiredConfigs
331
- })
332
- });
333
- for await (const event of replicationStream) {
334
- const updatedConfigs = event.type === "config_change" ? [event] : event.configs;
335
- for (const config of updatedConfigs) {
336
- if (config.version <= (configs.get(config.name)?.version ?? -1)) continue;
337
- configs.set(config.name, {
338
- name: config.name,
339
- overrides: config.overrides,
340
- version: config.version,
341
- value: config.value
342
- });
343
- for (const callback of clientSubscriptions) {
344
- callback({ name: config.name, value: config.value });
345
- }
346
- for (const callback of configSubscriptions.get(config.name) ?? []) {
347
- callback({ name: config.name, value: config.value });
348
- }
349
- }
350
- clientReady.resolve();
351
- }
352
- } catch (error) {
353
- sdkOptions.logger.error("Replane: error initializing client:", error);
354
- clientReady.reject(error);
355
- }
356
- })();
357
- function get(configName, getConfigOptions = {}) {
358
- const config = configs.get(String(configName));
359
- if (config === void 0) {
360
- throw new ReplaneError({
361
- message: `Config not found: ${String(configName)}`,
362
- code: "not_found" /* NotFound */
363
- });
364
- }
365
- try {
366
- return evaluateOverrides(
367
- config.value,
368
- config.overrides,
369
- { ...sdkOptions.context, ...getConfigOptions?.context ?? {} },
370
- sdkOptions.logger
371
- );
372
- } catch (error) {
373
- sdkOptions.logger.error(
374
- `Replane: error evaluating overrides for config ${String(configName)}:`,
375
- error
376
- );
377
- return config.value;
378
- }
379
- }
380
- const subscribe = (callbackOrConfigName, callbackOrUndefined) => {
381
- let configName = void 0;
382
- let callback;
383
- if (typeof callbackOrConfigName === "function") {
384
- callback = callbackOrConfigName;
385
- } else {
386
- configName = callbackOrConfigName;
387
- if (callbackOrUndefined === void 0) {
388
- throw new Error("callback is required when config name is provided");
389
- }
390
- callback = callbackOrUndefined;
391
- }
392
- const originalCallback = callback;
393
- callback = (...args) => {
394
- originalCallback(...args);
395
- };
396
- if (configName === void 0) {
397
- clientSubscriptions.add(callback);
398
- return () => {
399
- clientSubscriptions.delete(callback);
400
- };
401
- }
402
- if (!configSubscriptions.has(configName)) {
403
- configSubscriptions.set(configName, /* @__PURE__ */ new Set());
404
- }
405
- configSubscriptions.get(configName).add(callback);
406
- return () => {
407
- configSubscriptions.get(configName)?.delete(callback);
408
- if (configSubscriptions.get(configName)?.size === 0) {
409
- configSubscriptions.delete(configName);
410
- }
411
- };
412
- };
413
- const close = () => storage.close();
414
- const initializationTimeoutId = setTimeout(() => {
415
- if (sdkOptions.fallbacks.length === 0) {
416
- close();
417
- clientReady.reject(
418
- new ReplaneError({
419
- message: "Replane client initialization timed out",
420
- code: "timeout" /* Timeout */
421
- })
422
- );
423
- return;
424
- }
425
- const missingRequiredConfigs = [];
426
- for (const requiredConfigName of sdkOptions.requiredConfigs) {
427
- if (!configs.has(requiredConfigName)) {
428
- missingRequiredConfigs.push(requiredConfigName);
429
- }
430
- }
431
- if (missingRequiredConfigs.length > 0) {
432
- close();
433
- clientReady.reject(
434
- new ReplaneError({
435
- message: `Required configs are missing: ${missingRequiredConfigs.join(", ")}`,
436
- code: "not_found" /* NotFound */
437
- })
438
- );
439
- return;
440
- }
441
- clientReady.resolve();
442
- }, sdkOptions.initializationTimeoutMs);
443
- clientReady.promise.then(() => clearTimeout(initializationTimeoutId));
444
- await clientReady.promise;
445
- return {
446
- get,
447
- subscribe,
448
- close
449
- };
450
- }
451
- function toFinalOptions(defaults) {
452
- return {
453
- sdkKey: defaults.sdkKey,
454
- baseUrl: defaults.baseUrl.replace(/\/+$/, ""),
455
- fetchFn: defaults.fetchFn ?? // some browsers require binding the fetch function to window
456
- globalThis.fetch.bind(globalThis),
457
- requestTimeoutMs: defaults.requestTimeoutMs ?? 2e3,
458
- initializationTimeoutMs: defaults.initializationTimeoutMs ?? 5e3,
459
- inactivityTimeoutMs: defaults.inactivityTimeoutMs ?? 6e4,
460
- logger: defaults.logger ?? console,
461
- retryDelayMs: defaults.retryDelayMs ?? 200,
462
- context: {
463
- ...defaults.context ?? {}
464
- },
465
- requiredConfigs: Array.isArray(defaults.required) ? defaults.required.map((name) => String(name)) : Object.entries(defaults.required ?? {}).filter(([_, value]) => value !== void 0).map(([name]) => name),
466
- fallbacks: Object.entries(defaults.fallbacks ?? {}).filter(([_, value]) => value !== void 0).map(([name, value]) => ({
467
- name,
468
- overrides: [],
469
- version: -1,
470
- value
471
- }))
472
- };
473
- }
474
- async function fetchWithTimeout(input, init, timeoutMs, fetchFn) {
475
- if (!fetchFn) {
476
- throw new Error("Global fetch is not available. Provide options.fetchFn.");
477
- }
478
- if (!timeoutMs) return fetchFn(input, init);
479
- const timeoutController = new AbortController();
480
- const t = setTimeout(() => timeoutController.abort(), timeoutMs);
481
- const { signal } = combineAbortSignals([init.signal, timeoutController.signal]);
482
- try {
483
- return await fetchFn(input, {
484
- ...init,
485
- signal
486
- });
487
- } finally {
488
- clearTimeout(t);
489
- }
490
- }
491
- const SSE_DATA_PREFIX = "data:";
492
- async function* fetchSse(params) {
493
- const abortController = new AbortController();
494
- const { signal, cleanUpSignals } = params.signal ? combineAbortSignals([params.signal, abortController.signal]) : { signal: abortController.signal, cleanUpSignals: () => {
495
- } };
496
- try {
497
- const res = await fetchWithTimeout(
498
- params.url,
499
- {
500
- method: params.method ?? "GET",
501
- headers: { Accept: "text/event-stream", ...params.headers ?? {} },
502
- body: params.body,
503
- signal
504
- },
505
- params.timeoutMs,
506
- params.fetchFn
507
- );
508
- await ensureSuccessfulResponse(res, `SSE ${params.url}`);
509
- const responseContentType = res.headers.get("content-type") ?? "";
510
- if (!responseContentType.includes("text/event-stream")) {
511
- throw new ReplaneError({
512
- message: `Expected text/event-stream, got "${responseContentType}"`,
513
- code: "server_error" /* ServerError */
514
- });
515
- }
516
- if (!res.body) {
517
- throw new ReplaneError({
518
- message: `Failed to fetch SSE ${params.url}: body is empty`,
519
- code: "unknown" /* Unknown */
520
- });
521
- }
522
- if (params.onConnect) {
523
- params.onConnect();
524
- }
525
- const decoded = res.body.pipeThrough(new TextDecoderStream());
526
- const reader = decoded.getReader();
527
- let buffer = "";
528
- try {
529
- while (true) {
530
- const { value, done } = await reader.read();
531
- if (done) break;
532
- buffer += value;
533
- const frames = buffer.split(/\r?\n\r?\n/);
534
- buffer = frames.pop() ?? "";
535
- for (const frame of frames) {
536
- const dataLines = [];
537
- let isPing = false;
538
- for (const rawLine of frame.split(/\r?\n/)) {
539
- if (!rawLine) continue;
540
- if (rawLine.startsWith(":")) {
541
- isPing = true;
542
- continue;
543
- }
544
- if (rawLine.startsWith(SSE_DATA_PREFIX)) {
545
- const line = rawLine.slice(SSE_DATA_PREFIX.length).replace(/^\s/, "");
546
- dataLines.push(line);
547
- }
548
- }
549
- if (dataLines.length) {
550
- const payload = dataLines.join("\n");
551
- yield { type: "data", payload };
552
- } else if (isPing) {
553
- yield { type: "ping" };
554
- }
555
- }
556
- }
557
- } finally {
558
- try {
559
- await reader.cancel();
560
- } catch {
561
- }
562
- abortController.abort();
563
- }
564
- } finally {
565
- cleanUpSignals();
566
- }
567
- }
568
- async function ensureSuccessfulResponse(response, message) {
569
- if (response.status === 404) {
570
- throw new ReplaneError({
571
- message: `Not found: ${message}`,
572
- code: "not_found" /* NotFound */
573
- });
574
- }
575
- if (response.status === 401) {
576
- throw new ReplaneError({
577
- message: `Unauthorized access: ${message}`,
578
- code: "auth_error" /* AuthError */
579
- });
580
- }
581
- if (response.status === 403) {
582
- throw new ReplaneError({
583
- message: `Forbidden access: ${message}`,
584
- code: "forbidden" /* Forbidden */
585
- });
586
- }
587
- if (!response.ok) {
588
- let body;
589
- try {
590
- body = await response.text();
591
- } catch {
592
- body = "<unable to read response body>";
593
- }
594
- const code = response.status >= 500 ? "server_error" /* ServerError */ : response.status >= 400 ? "client_error" /* ClientError */ : "unknown" /* Unknown */;
595
- throw new ReplaneError({
596
- message: `Fetch response isn't successful (${message}): ${response.status} ${response.statusText} - ${body}`,
597
- code
598
- });
599
- }
600
- }
601
- function combineAbortSignals(signals) {
602
- const controller = new AbortController();
603
- const onAbort = () => {
604
- controller.abort();
605
- cleanUpSignals();
606
- };
607
- const cleanUpSignals = () => {
608
- for (const s of signals) {
609
- s?.removeEventListener("abort", onAbort);
610
- }
611
- };
612
- for (const s of signals) {
613
- s?.addEventListener("abort", onAbort, { once: true });
614
- }
615
- if (signals.some((s) => s?.aborted)) {
616
- onAbort();
617
- }
618
- return { signal: controller.signal, cleanUpSignals };
619
- }
620
- class Deferred {
621
- promise;
622
- resolve;
623
- reject;
624
- constructor() {
625
- this.promise = new Promise((resolve, reject) => {
626
- this.resolve = resolve;
627
- this.reject = reject;
628
- });
629
- }
630
- }
28
+ var import_client = require("./client");
29
+ var import_error = require("./error");
631
30
  // Annotate the CommonJS export names for ESM import in node:
632
31
  0 && (module.exports = {
633
32
  ReplaneError,
33
+ ReplaneErrorCode,
634
34
  createInMemoryReplaneClient,
635
- createReplaneClient
35
+ createReplaneClient,
36
+ restoreReplaneClient
636
37
  });