@scalemule/sdk 0.0.15 → 0.0.16

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.
@@ -79,6 +79,8 @@ declare class FlagClient {
79
79
  private environment;
80
80
  private gatewayUrl;
81
81
  private config;
82
+ private flagIndex;
83
+ private segmentIndex;
82
84
  private lastETag;
83
85
  private streamState;
84
86
  private pollTimer;
@@ -87,9 +89,12 @@ declare class FlagClient {
87
89
  private abortController;
88
90
  private initPromise;
89
91
  private telemetryCounters;
92
+ private isShuttingDown;
93
+ private streamConnectInFlight;
90
94
  constructor(options: FlagClientOptions);
91
95
  init(): Promise<void>;
92
96
  private doInit;
97
+ private buildIndexes;
93
98
  evaluate(flagKey: string, context: EvaluationContext): FlagEvaluation;
94
99
  evaluateBatch(flagKeys: string[], context: EvaluationContext): Record<string, FlagEvaluation>;
95
100
  shutdown(): Promise<void>;
@@ -108,7 +113,7 @@ declare class FlagClient {
108
113
  * Produces identical results to the server-side evaluation.
109
114
  */
110
115
 
111
- declare function evaluateFlag(flag: FlagWire, config: FlagConfigWire, context: EvaluationContext): FlagEvaluation;
116
+ declare function evaluateFlag(flag: FlagWire, config: FlagConfigWire, context: EvaluationContext, segmentIndex?: Map<string, SegmentWire>): FlagEvaluation;
112
117
 
113
118
  /**
114
119
  * Hash-to-bucket matching Rust: SHA256(salt.flag_key.identifier) → first 4 bytes → u32 BE → mod 10_000
@@ -79,6 +79,8 @@ declare class FlagClient {
79
79
  private environment;
80
80
  private gatewayUrl;
81
81
  private config;
82
+ private flagIndex;
83
+ private segmentIndex;
82
84
  private lastETag;
83
85
  private streamState;
84
86
  private pollTimer;
@@ -87,9 +89,12 @@ declare class FlagClient {
87
89
  private abortController;
88
90
  private initPromise;
89
91
  private telemetryCounters;
92
+ private isShuttingDown;
93
+ private streamConnectInFlight;
90
94
  constructor(options: FlagClientOptions);
91
95
  init(): Promise<void>;
92
96
  private doInit;
97
+ private buildIndexes;
93
98
  evaluate(flagKey: string, context: EvaluationContext): FlagEvaluation;
94
99
  evaluateBatch(flagKeys: string[], context: EvaluationContext): Record<string, FlagEvaluation>;
95
100
  shutdown(): Promise<void>;
@@ -108,7 +113,7 @@ declare class FlagClient {
108
113
  * Produces identical results to the server-side evaluation.
109
114
  */
110
115
 
111
- declare function evaluateFlag(flag: FlagWire, config: FlagConfigWire, context: EvaluationContext): FlagEvaluation;
116
+ declare function evaluateFlag(flag: FlagWire, config: FlagConfigWire, context: EvaluationContext, segmentIndex?: Map<string, SegmentWire>): FlagEvaluation;
112
117
 
113
118
  /**
114
119
  * Hash-to-bucket matching Rust: SHA256(salt.flag_key.identifier) → first 4 bytes → u32 BE → mod 10_000
@@ -181,7 +181,7 @@ function semverCmp(actual, expected) {
181
181
  }
182
182
 
183
183
  // src/flags/evaluator.ts
184
- function evaluateFlag(flag, config, context) {
184
+ function evaluateFlag(flag, config, context, segmentIndex) {
185
185
  const effectiveDefault = flag.environment_default_value ?? flag.default_value;
186
186
  if (flag.status !== "active") {
187
187
  return result(flag, config.environment, effectiveDefault, "disabled");
@@ -194,7 +194,7 @@ function evaluateFlag(flag, config, context) {
194
194
  if (!rule.enabled) continue;
195
195
  if (rule.segment_ids.length > 0) {
196
196
  const segmentMatched = rule.segment_ids.some((segId) => {
197
- const segment = config.segments.find((s) => s.id === segId);
197
+ const segment = segmentIndex ? segmentIndex.get(segId) : config.segments.find((s) => s.id === segId);
198
198
  if (!segment) return false;
199
199
  return userMatchesSegment(segment, context);
200
200
  });
@@ -283,6 +283,8 @@ function result(flag, environment, value, reason) {
283
283
  var FlagClient = class {
284
284
  constructor(options) {
285
285
  this.config = null;
286
+ this.flagIndex = /* @__PURE__ */ new Map();
287
+ this.segmentIndex = /* @__PURE__ */ new Map();
286
288
  this.lastETag = "";
287
289
  this.streamState = "idle";
288
290
  this.pollTimer = null;
@@ -291,11 +293,14 @@ var FlagClient = class {
291
293
  this.abortController = null;
292
294
  this.initPromise = null;
293
295
  this.telemetryCounters = /* @__PURE__ */ new Map();
296
+ this.isShuttingDown = false;
297
+ this.streamConnectInFlight = false;
294
298
  this.apiKey = options.apiKey;
295
299
  this.environment = options.environment;
296
300
  this.gatewayUrl = options.gatewayUrl;
297
301
  }
298
302
  async init() {
303
+ this.isShuttingDown = false;
299
304
  if (this.config) return;
300
305
  if (this.initPromise) return this.initPromise;
301
306
  this.initPromise = this.doInit();
@@ -313,13 +318,25 @@ var FlagClient = class {
313
318
  if (!resp.ok) throw new Error(`Config fetch failed: ${resp.status}`);
314
319
  const json = await resp.json();
315
320
  this.config = json.data;
321
+ this.buildIndexes();
316
322
  this.lastETag = resp.headers.get("etag") || "";
317
323
  this.connectStream();
318
324
  this.startTelemetryFlush();
319
325
  }
326
+ buildIndexes() {
327
+ this.flagIndex.clear();
328
+ this.segmentIndex.clear();
329
+ if (!this.config) return;
330
+ for (const flag of this.config.flags) {
331
+ this.flagIndex.set(flag.flag_key, flag);
332
+ }
333
+ for (const segment of this.config.segments) {
334
+ this.segmentIndex.set(segment.id, segment);
335
+ }
336
+ }
320
337
  evaluate(flagKey, context) {
321
338
  if (!this.config) throw new Error("FlagClient not initialized \u2014 call init() first");
322
- const flagConfig = this.config.flags.find((f) => f.flag_key === flagKey);
339
+ const flagConfig = this.flagIndex.get(flagKey);
323
340
  if (!flagConfig) {
324
341
  return {
325
342
  flag_id: "",
@@ -332,7 +349,7 @@ var FlagClient = class {
332
349
  bucket: null
333
350
  };
334
351
  }
335
- const result2 = evaluateFlag(flagConfig, this.config, context);
352
+ const result2 = evaluateFlag(flagConfig, this.config, context, this.segmentIndex);
336
353
  this.recordTelemetry(result2);
337
354
  return result2;
338
355
  }
@@ -340,9 +357,9 @@ var FlagClient = class {
340
357
  if (!this.config) throw new Error("FlagClient not initialized \u2014 call init() first");
341
358
  const results = {};
342
359
  for (const key of flagKeys) {
343
- const flagConfig = this.config.flags.find((f) => f.flag_key === key);
360
+ const flagConfig = this.flagIndex.get(key);
344
361
  if (flagConfig) {
345
- const result2 = evaluateFlag(flagConfig, this.config, context);
362
+ const result2 = evaluateFlag(flagConfig, this.config, context, this.segmentIndex);
346
363
  this.recordTelemetry(result2);
347
364
  results[key] = result2;
348
365
  }
@@ -350,6 +367,7 @@ var FlagClient = class {
350
367
  return results;
351
368
  }
352
369
  async shutdown() {
370
+ this.isShuttingDown = true;
353
371
  this.streamState = "idle";
354
372
  this.abortController?.abort();
355
373
  this.abortController = null;
@@ -369,9 +387,13 @@ var FlagClient = class {
369
387
  }
370
388
  // ======== SSE Streaming ========
371
389
  async connectStream() {
372
- if (this.streamState === "streaming") return;
390
+ if (this.isShuttingDown || this.streamState === "streaming" || this.streamConnectInFlight) return;
391
+ this.streamConnectInFlight = true;
373
392
  this.abortController?.abort();
374
- this.abortController = new AbortController();
393
+ const abortController = new AbortController();
394
+ this.abortController = abortController;
395
+ const shouldResumePolling = this.streamState !== "polling";
396
+ let startPolling = shouldResumePolling;
375
397
  try {
376
398
  const resp = await fetch(
377
399
  `${this.gatewayUrl}/v1/flags/stream?environment=${encodeURIComponent(this.environment)}`,
@@ -380,33 +402,38 @@ var FlagClient = class {
380
402
  "x-api-key": this.apiKey,
381
403
  "Last-Event-ID": String(this.config?.version ?? 0)
382
404
  },
383
- signal: this.abortController.signal
405
+ signal: abortController.signal
384
406
  }
385
407
  );
386
- if (!resp.ok || !resp.body) {
387
- this.startPolling();
388
- return;
389
- }
390
- this.streamState = "streaming";
391
- this.stopPolling();
392
- const reader = resp.body.getReader();
393
- const decoder = new TextDecoder();
394
- let buffer = "";
395
- while (true) {
396
- const { done, value } = await reader.read();
397
- if (done) break;
398
- buffer += decoder.decode(value, { stream: true });
399
- let idx;
400
- while ((idx = buffer.indexOf("\n\n")) !== -1) {
401
- const frame = buffer.slice(0, idx);
402
- buffer = buffer.slice(idx + 2);
403
- this.handleSseFrame(frame);
408
+ if (resp.ok && resp.body) {
409
+ this.streamState = "streaming";
410
+ this.stopPolling();
411
+ startPolling = false;
412
+ const reader = resp.body.getReader();
413
+ const decoder = new TextDecoder();
414
+ let buffer = "";
415
+ while (true) {
416
+ const { done, value } = await reader.read();
417
+ if (done) break;
418
+ buffer += decoder.decode(value, { stream: true });
419
+ let idx;
420
+ while ((idx = buffer.indexOf("\n\n")) !== -1) {
421
+ const frame = buffer.slice(0, idx);
422
+ buffer = buffer.slice(idx + 2);
423
+ this.handleSseFrame(frame);
424
+ }
425
+ }
426
+ if (this.streamState === "streaming") {
427
+ this.streamState = "idle";
428
+ startPolling = true;
404
429
  }
405
430
  }
406
431
  } catch {
432
+ startPolling = !abortController.signal.aborted && shouldResumePolling;
433
+ } finally {
434
+ this.streamConnectInFlight = false;
407
435
  }
408
- if (this.streamState === "streaming") {
409
- this.streamState = "idle";
436
+ if (!this.isShuttingDown && startPolling) {
410
437
  this.startPolling();
411
438
  }
412
439
  }
@@ -423,6 +450,7 @@ var FlagClient = class {
423
450
  const newConfig = parsed.data;
424
451
  if (newConfig && newConfig.version !== void 0) {
425
452
  this.config = newConfig;
453
+ this.buildIndexes();
426
454
  }
427
455
  } catch {
428
456
  }
@@ -457,6 +485,7 @@ var FlagClient = class {
457
485
  if (!resp.ok) return;
458
486
  const json = await resp.json();
459
487
  this.config = json.data;
488
+ this.buildIndexes();
460
489
  this.lastETag = resp.headers.get("etag") || "";
461
490
  } catch {
462
491
  }
@@ -152,7 +152,7 @@ function semverCmp(actual, expected) {
152
152
  }
153
153
 
154
154
  // src/flags/evaluator.ts
155
- function evaluateFlag(flag, config, context) {
155
+ function evaluateFlag(flag, config, context, segmentIndex) {
156
156
  const effectiveDefault = flag.environment_default_value ?? flag.default_value;
157
157
  if (flag.status !== "active") {
158
158
  return result(flag, config.environment, effectiveDefault, "disabled");
@@ -165,7 +165,7 @@ function evaluateFlag(flag, config, context) {
165
165
  if (!rule.enabled) continue;
166
166
  if (rule.segment_ids.length > 0) {
167
167
  const segmentMatched = rule.segment_ids.some((segId) => {
168
- const segment = config.segments.find((s) => s.id === segId);
168
+ const segment = segmentIndex ? segmentIndex.get(segId) : config.segments.find((s) => s.id === segId);
169
169
  if (!segment) return false;
170
170
  return userMatchesSegment(segment, context);
171
171
  });
@@ -254,6 +254,8 @@ function result(flag, environment, value, reason) {
254
254
  var FlagClient = class {
255
255
  constructor(options) {
256
256
  this.config = null;
257
+ this.flagIndex = /* @__PURE__ */ new Map();
258
+ this.segmentIndex = /* @__PURE__ */ new Map();
257
259
  this.lastETag = "";
258
260
  this.streamState = "idle";
259
261
  this.pollTimer = null;
@@ -262,11 +264,14 @@ var FlagClient = class {
262
264
  this.abortController = null;
263
265
  this.initPromise = null;
264
266
  this.telemetryCounters = /* @__PURE__ */ new Map();
267
+ this.isShuttingDown = false;
268
+ this.streamConnectInFlight = false;
265
269
  this.apiKey = options.apiKey;
266
270
  this.environment = options.environment;
267
271
  this.gatewayUrl = options.gatewayUrl;
268
272
  }
269
273
  async init() {
274
+ this.isShuttingDown = false;
270
275
  if (this.config) return;
271
276
  if (this.initPromise) return this.initPromise;
272
277
  this.initPromise = this.doInit();
@@ -284,13 +289,25 @@ var FlagClient = class {
284
289
  if (!resp.ok) throw new Error(`Config fetch failed: ${resp.status}`);
285
290
  const json = await resp.json();
286
291
  this.config = json.data;
292
+ this.buildIndexes();
287
293
  this.lastETag = resp.headers.get("etag") || "";
288
294
  this.connectStream();
289
295
  this.startTelemetryFlush();
290
296
  }
297
+ buildIndexes() {
298
+ this.flagIndex.clear();
299
+ this.segmentIndex.clear();
300
+ if (!this.config) return;
301
+ for (const flag of this.config.flags) {
302
+ this.flagIndex.set(flag.flag_key, flag);
303
+ }
304
+ for (const segment of this.config.segments) {
305
+ this.segmentIndex.set(segment.id, segment);
306
+ }
307
+ }
291
308
  evaluate(flagKey, context) {
292
309
  if (!this.config) throw new Error("FlagClient not initialized \u2014 call init() first");
293
- const flagConfig = this.config.flags.find((f) => f.flag_key === flagKey);
310
+ const flagConfig = this.flagIndex.get(flagKey);
294
311
  if (!flagConfig) {
295
312
  return {
296
313
  flag_id: "",
@@ -303,7 +320,7 @@ var FlagClient = class {
303
320
  bucket: null
304
321
  };
305
322
  }
306
- const result2 = evaluateFlag(flagConfig, this.config, context);
323
+ const result2 = evaluateFlag(flagConfig, this.config, context, this.segmentIndex);
307
324
  this.recordTelemetry(result2);
308
325
  return result2;
309
326
  }
@@ -311,9 +328,9 @@ var FlagClient = class {
311
328
  if (!this.config) throw new Error("FlagClient not initialized \u2014 call init() first");
312
329
  const results = {};
313
330
  for (const key of flagKeys) {
314
- const flagConfig = this.config.flags.find((f) => f.flag_key === key);
331
+ const flagConfig = this.flagIndex.get(key);
315
332
  if (flagConfig) {
316
- const result2 = evaluateFlag(flagConfig, this.config, context);
333
+ const result2 = evaluateFlag(flagConfig, this.config, context, this.segmentIndex);
317
334
  this.recordTelemetry(result2);
318
335
  results[key] = result2;
319
336
  }
@@ -321,6 +338,7 @@ var FlagClient = class {
321
338
  return results;
322
339
  }
323
340
  async shutdown() {
341
+ this.isShuttingDown = true;
324
342
  this.streamState = "idle";
325
343
  this.abortController?.abort();
326
344
  this.abortController = null;
@@ -340,9 +358,13 @@ var FlagClient = class {
340
358
  }
341
359
  // ======== SSE Streaming ========
342
360
  async connectStream() {
343
- if (this.streamState === "streaming") return;
361
+ if (this.isShuttingDown || this.streamState === "streaming" || this.streamConnectInFlight) return;
362
+ this.streamConnectInFlight = true;
344
363
  this.abortController?.abort();
345
- this.abortController = new AbortController();
364
+ const abortController = new AbortController();
365
+ this.abortController = abortController;
366
+ const shouldResumePolling = this.streamState !== "polling";
367
+ let startPolling = shouldResumePolling;
346
368
  try {
347
369
  const resp = await fetch(
348
370
  `${this.gatewayUrl}/v1/flags/stream?environment=${encodeURIComponent(this.environment)}`,
@@ -351,33 +373,38 @@ var FlagClient = class {
351
373
  "x-api-key": this.apiKey,
352
374
  "Last-Event-ID": String(this.config?.version ?? 0)
353
375
  },
354
- signal: this.abortController.signal
376
+ signal: abortController.signal
355
377
  }
356
378
  );
357
- if (!resp.ok || !resp.body) {
358
- this.startPolling();
359
- return;
360
- }
361
- this.streamState = "streaming";
362
- this.stopPolling();
363
- const reader = resp.body.getReader();
364
- const decoder = new TextDecoder();
365
- let buffer = "";
366
- while (true) {
367
- const { done, value } = await reader.read();
368
- if (done) break;
369
- buffer += decoder.decode(value, { stream: true });
370
- let idx;
371
- while ((idx = buffer.indexOf("\n\n")) !== -1) {
372
- const frame = buffer.slice(0, idx);
373
- buffer = buffer.slice(idx + 2);
374
- this.handleSseFrame(frame);
379
+ if (resp.ok && resp.body) {
380
+ this.streamState = "streaming";
381
+ this.stopPolling();
382
+ startPolling = false;
383
+ const reader = resp.body.getReader();
384
+ const decoder = new TextDecoder();
385
+ let buffer = "";
386
+ while (true) {
387
+ const { done, value } = await reader.read();
388
+ if (done) break;
389
+ buffer += decoder.decode(value, { stream: true });
390
+ let idx;
391
+ while ((idx = buffer.indexOf("\n\n")) !== -1) {
392
+ const frame = buffer.slice(0, idx);
393
+ buffer = buffer.slice(idx + 2);
394
+ this.handleSseFrame(frame);
395
+ }
396
+ }
397
+ if (this.streamState === "streaming") {
398
+ this.streamState = "idle";
399
+ startPolling = true;
375
400
  }
376
401
  }
377
402
  } catch {
403
+ startPolling = !abortController.signal.aborted && shouldResumePolling;
404
+ } finally {
405
+ this.streamConnectInFlight = false;
378
406
  }
379
- if (this.streamState === "streaming") {
380
- this.streamState = "idle";
407
+ if (!this.isShuttingDown && startPolling) {
381
408
  this.startPolling();
382
409
  }
383
410
  }
@@ -394,6 +421,7 @@ var FlagClient = class {
394
421
  const newConfig = parsed.data;
395
422
  if (newConfig && newConfig.version !== void 0) {
396
423
  this.config = newConfig;
424
+ this.buildIndexes();
397
425
  }
398
426
  } catch {
399
427
  }
@@ -428,6 +456,7 @@ var FlagClient = class {
428
456
  if (!resp.ok) return;
429
457
  const json = await resp.json();
430
458
  this.config = json.data;
459
+ this.buildIndexes();
431
460
  this.lastETag = resp.headers.get("etag") || "";
432
461
  } catch {
433
462
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalemule/sdk",
3
- "version": "0.0.15",
3
+ "version": "0.0.16",
4
4
  "description": "Official TypeScript/JavaScript SDK for ScaleMule Backend-as-a-Service",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",