@smplkit/sdk 1.1.10 → 1.2.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.
- package/dist/index.cjs +1678 -409
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +658 -201
- package/dist/index.d.ts +658 -201
- package/dist/index.js +1664 -79
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
- package/dist/chunk-RF6LYU4V.js +0 -317
- package/dist/chunk-RF6LYU4V.js.map +0 -1
- package/dist/runtime-FT745HBO.js +0 -7
- package/dist/runtime-FT745HBO.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
ConfigRuntime
|
|
3
|
-
} from "./chunk-RF6LYU4V.js";
|
|
4
|
-
|
|
5
1
|
// src/config/client.ts
|
|
6
2
|
import createClient from "openapi-fetch";
|
|
7
3
|
|
|
@@ -47,6 +43,13 @@ var SmplConflictError = class extends SmplError {
|
|
|
47
43
|
Object.setPrototypeOf(this, new.target.prototype);
|
|
48
44
|
}
|
|
49
45
|
};
|
|
46
|
+
var SmplNotConnectedError = class extends SmplError {
|
|
47
|
+
constructor(message) {
|
|
48
|
+
super(message);
|
|
49
|
+
this.name = "SmplNotConnectedError";
|
|
50
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
50
53
|
var SmplValidationError = class extends SmplError {
|
|
51
54
|
constructor(message, statusCode, responseBody) {
|
|
52
55
|
super(message, statusCode ?? 422, responseBody);
|
|
@@ -55,6 +58,34 @@ var SmplValidationError = class extends SmplError {
|
|
|
55
58
|
}
|
|
56
59
|
};
|
|
57
60
|
|
|
61
|
+
// src/config/resolve.ts
|
|
62
|
+
function deepMerge(base, override) {
|
|
63
|
+
const result = { ...base };
|
|
64
|
+
for (const [key, value] of Object.entries(override)) {
|
|
65
|
+
if (key in result && typeof result[key] === "object" && result[key] !== null && !Array.isArray(result[key]) && typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
66
|
+
result[key] = deepMerge(
|
|
67
|
+
result[key],
|
|
68
|
+
value
|
|
69
|
+
);
|
|
70
|
+
} else {
|
|
71
|
+
result[key] = value;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return result;
|
|
75
|
+
}
|
|
76
|
+
function resolveChain(chain, environment) {
|
|
77
|
+
let accumulated = {};
|
|
78
|
+
for (let i = chain.length - 1; i >= 0; i--) {
|
|
79
|
+
const config = chain[i];
|
|
80
|
+
const baseValues = config.items ?? {};
|
|
81
|
+
const envEntry = (config.environments ?? {})[environment];
|
|
82
|
+
const envValues = envEntry !== null && envEntry !== void 0 && typeof envEntry === "object" && !Array.isArray(envEntry) ? envEntry.values ?? {} : {};
|
|
83
|
+
const configResolved = deepMerge(baseValues, envValues);
|
|
84
|
+
accumulated = deepMerge(accumulated, configResolved);
|
|
85
|
+
}
|
|
86
|
+
return accumulated;
|
|
87
|
+
}
|
|
88
|
+
|
|
58
89
|
// src/config/types.ts
|
|
59
90
|
var Config = class {
|
|
60
91
|
/** UUID of the config. */
|
|
@@ -181,45 +212,6 @@ var Config = class {
|
|
|
181
212
|
await this.setValues(existing, environment);
|
|
182
213
|
}
|
|
183
214
|
}
|
|
184
|
-
/**
|
|
185
|
-
* Connect to this config for runtime value resolution.
|
|
186
|
-
*
|
|
187
|
-
* Eagerly fetches this config and its full parent chain, resolves values
|
|
188
|
-
* for the given environment via deep merge, and returns a
|
|
189
|
-
* {@link ConfigRuntime} with a fully populated local cache.
|
|
190
|
-
*
|
|
191
|
-
* A background WebSocket connection is started for real-time updates.
|
|
192
|
-
* If the WebSocket fails to connect, the runtime operates in cache-only
|
|
193
|
-
* mode and reconnects automatically.
|
|
194
|
-
*
|
|
195
|
-
* Supports both `await` and `await using` (TypeScript 5.2+)::
|
|
196
|
-
*
|
|
197
|
-
* ```typescript
|
|
198
|
-
* // Simple await
|
|
199
|
-
* const runtime = await config.connect("production");
|
|
200
|
-
* try { ... } finally { await runtime.close(); }
|
|
201
|
-
*
|
|
202
|
-
* // await using (auto-close)
|
|
203
|
-
* await using runtime = await config.connect("production");
|
|
204
|
-
* ```
|
|
205
|
-
*
|
|
206
|
-
* @param environment - The environment to resolve for (e.g. `"production"`).
|
|
207
|
-
* @param options.timeout - Milliseconds to wait for the initial fetch.
|
|
208
|
-
*/
|
|
209
|
-
async connect(environment, options) {
|
|
210
|
-
const { ConfigRuntime: ConfigRuntime2 } = await import("./runtime-FT745HBO.js");
|
|
211
|
-
const timeout = options?.timeout ?? 3e4;
|
|
212
|
-
const chain = await this._buildChain(timeout);
|
|
213
|
-
return new ConfigRuntime2({
|
|
214
|
-
configKey: this.key,
|
|
215
|
-
configId: this.id,
|
|
216
|
-
environment,
|
|
217
|
-
chain,
|
|
218
|
-
apiKey: this._client._apiKey,
|
|
219
|
-
baseUrl: this._client._baseUrl,
|
|
220
|
-
fetchChain: () => this._buildChain(timeout)
|
|
221
|
-
});
|
|
222
|
-
}
|
|
223
215
|
/**
|
|
224
216
|
* Walk the parent chain and return config data objects, child-to-root.
|
|
225
217
|
* @internal
|
|
@@ -364,6 +356,12 @@ var ConfigClient = class {
|
|
|
364
356
|
_baseUrl = BASE_URL;
|
|
365
357
|
/** @internal */
|
|
366
358
|
_http;
|
|
359
|
+
/** @internal — returns the shared WebSocket for real-time updates. */
|
|
360
|
+
_getSharedWs;
|
|
361
|
+
/** @internal — set by SmplClient after construction. */
|
|
362
|
+
_parent = null;
|
|
363
|
+
_configCache = {};
|
|
364
|
+
_connected = false;
|
|
367
365
|
/** @internal */
|
|
368
366
|
constructor(apiKey, timeout) {
|
|
369
367
|
this._apiKey = apiKey;
|
|
@@ -461,6 +459,44 @@ var ConfigClient = class {
|
|
|
461
459
|
wrapFetchError(err);
|
|
462
460
|
}
|
|
463
461
|
}
|
|
462
|
+
/**
|
|
463
|
+
* Fetch all configs, resolve values for the environment, and cache.
|
|
464
|
+
* @internal — called by SmplClient.connect().
|
|
465
|
+
*/
|
|
466
|
+
async _connectInternal(environment) {
|
|
467
|
+
const configs = await this.list();
|
|
468
|
+
const cache = {};
|
|
469
|
+
for (const cfg of configs) {
|
|
470
|
+
const chain = await cfg._buildChain(this._http);
|
|
471
|
+
cache[cfg.key] = resolveChain(chain, environment);
|
|
472
|
+
}
|
|
473
|
+
this._configCache = cache;
|
|
474
|
+
this._connected = true;
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Read a resolved config value (prescriptive access).
|
|
478
|
+
*
|
|
479
|
+
* Requires {@link SmplClient.connect} to have been called.
|
|
480
|
+
*
|
|
481
|
+
* @param configKey - The config key to look up.
|
|
482
|
+
* @param itemKey - Optional specific item key. If omitted, returns all values.
|
|
483
|
+
* @param defaultValue - Default value if the key is missing.
|
|
484
|
+
*
|
|
485
|
+
* @throws {SmplNotConnectedError} If connect() has not been called.
|
|
486
|
+
*/
|
|
487
|
+
getValue(configKey, itemKey, defaultValue) {
|
|
488
|
+
if (!this._connected) {
|
|
489
|
+
throw new SmplNotConnectedError("SmplClient is not connected. Call client.connect() first.");
|
|
490
|
+
}
|
|
491
|
+
const resolved = this._configCache[configKey];
|
|
492
|
+
if (resolved === void 0) {
|
|
493
|
+
return defaultValue ?? null;
|
|
494
|
+
}
|
|
495
|
+
if (itemKey === void 0) {
|
|
496
|
+
return { ...resolved };
|
|
497
|
+
}
|
|
498
|
+
return itemKey in resolved ? resolved[itemKey] : defaultValue ?? null;
|
|
499
|
+
}
|
|
464
500
|
/**
|
|
465
501
|
* Internal: PUT a full config update and return the updated model.
|
|
466
502
|
*
|
|
@@ -528,58 +564,1607 @@ var ConfigClient = class {
|
|
|
528
564
|
}
|
|
529
565
|
};
|
|
530
566
|
|
|
531
|
-
// src/
|
|
532
|
-
import
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
567
|
+
// src/flags/client.ts
|
|
568
|
+
import createClient2 from "openapi-fetch";
|
|
569
|
+
|
|
570
|
+
// src/auth.ts
|
|
571
|
+
function buildAuthHeader(apiKey) {
|
|
572
|
+
return `Bearer ${apiKey}`;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
// src/transport.ts
|
|
576
|
+
var SDK_VERSION = "0.0.0";
|
|
577
|
+
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
578
|
+
var Transport = class {
|
|
579
|
+
apiKey;
|
|
580
|
+
timeout;
|
|
581
|
+
constructor(options) {
|
|
582
|
+
this.apiKey = options.apiKey;
|
|
583
|
+
this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
|
|
584
|
+
}
|
|
585
|
+
/**
|
|
586
|
+
* Send a GET request.
|
|
587
|
+
*
|
|
588
|
+
* @param url - Fully-qualified URL (e.g. `https://config.smplkit.com/api/v1/configs`).
|
|
589
|
+
* @param params - Optional query parameters.
|
|
590
|
+
* @returns Parsed JSON response body.
|
|
591
|
+
*/
|
|
592
|
+
async get(url, params) {
|
|
593
|
+
return this.request("GET", url, void 0, params);
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Send a POST request with a JSON body.
|
|
597
|
+
*
|
|
598
|
+
* @param url - Fully-qualified URL.
|
|
599
|
+
* @param body - JSON-serializable request body.
|
|
600
|
+
* @returns Parsed JSON response body.
|
|
601
|
+
*/
|
|
602
|
+
async post(url, body) {
|
|
603
|
+
return this.request("POST", url, body);
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* Send a PUT request with a JSON body.
|
|
607
|
+
*
|
|
608
|
+
* @param url - Fully-qualified URL.
|
|
609
|
+
* @param body - JSON-serializable request body.
|
|
610
|
+
* @returns Parsed JSON response body.
|
|
611
|
+
*/
|
|
612
|
+
async put(url, body) {
|
|
613
|
+
return this.request("PUT", url, body);
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* Send a DELETE request.
|
|
617
|
+
*
|
|
618
|
+
* @param url - Fully-qualified URL.
|
|
619
|
+
* @returns Parsed JSON response body (empty object for 204 responses).
|
|
620
|
+
*/
|
|
621
|
+
async delete(url) {
|
|
622
|
+
return this.request("DELETE", url);
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* Core request method. Handles headers, timeouts, and error mapping.
|
|
626
|
+
*/
|
|
627
|
+
async request(method, url, body, params) {
|
|
628
|
+
if (params) {
|
|
629
|
+
const searchParams = new URLSearchParams(params);
|
|
630
|
+
url += `?${searchParams.toString()}`;
|
|
631
|
+
}
|
|
632
|
+
const headers = {
|
|
633
|
+
Authorization: buildAuthHeader(this.apiKey),
|
|
634
|
+
"User-Agent": `smplkit-typescript-sdk/${SDK_VERSION}`,
|
|
635
|
+
Accept: "application/vnd.api+json"
|
|
636
|
+
};
|
|
637
|
+
if (body !== void 0) {
|
|
638
|
+
headers["Content-Type"] = "application/vnd.api+json";
|
|
639
|
+
}
|
|
640
|
+
const controller = new AbortController();
|
|
641
|
+
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
642
|
+
let response;
|
|
643
|
+
try {
|
|
644
|
+
response = await fetch(url, {
|
|
645
|
+
method,
|
|
646
|
+
headers,
|
|
647
|
+
body: body !== void 0 ? JSON.stringify(body) : void 0,
|
|
648
|
+
signal: controller.signal
|
|
649
|
+
});
|
|
650
|
+
} catch (error) {
|
|
651
|
+
clearTimeout(timeoutId);
|
|
652
|
+
if (error instanceof DOMException && error.name === "AbortError") {
|
|
653
|
+
throw new SmplTimeoutError(`Request timed out after ${this.timeout}ms`);
|
|
550
654
|
}
|
|
551
|
-
if (
|
|
552
|
-
|
|
553
|
-
if (eqIndex !== -1) {
|
|
554
|
-
const value = trimmed.slice(eqIndex + 1).trim();
|
|
555
|
-
if (value) return value;
|
|
556
|
-
}
|
|
655
|
+
if (error instanceof TypeError) {
|
|
656
|
+
throw new SmplConnectionError(`Network error: ${error.message}`);
|
|
557
657
|
}
|
|
658
|
+
throw new SmplConnectionError(
|
|
659
|
+
`Request failed: ${error instanceof Error ? error.message : String(error)}`
|
|
660
|
+
);
|
|
661
|
+
} finally {
|
|
662
|
+
clearTimeout(timeoutId);
|
|
663
|
+
}
|
|
664
|
+
if (response.status === 204) {
|
|
665
|
+
return {};
|
|
666
|
+
}
|
|
667
|
+
const responseText = await response.text();
|
|
668
|
+
if (!response.ok) {
|
|
669
|
+
this.throwForStatus(response.status, responseText);
|
|
670
|
+
}
|
|
671
|
+
try {
|
|
672
|
+
return JSON.parse(responseText);
|
|
673
|
+
} catch {
|
|
674
|
+
throw new SmplError(`Invalid JSON response: ${responseText}`, response.status, responseText);
|
|
558
675
|
}
|
|
559
|
-
} catch {
|
|
560
676
|
}
|
|
561
|
-
|
|
562
|
-
|
|
677
|
+
/**
|
|
678
|
+
* Map HTTP error status codes to typed SDK exceptions.
|
|
679
|
+
*
|
|
680
|
+
* @throws {SmplNotFoundError} On 404.
|
|
681
|
+
* @throws {SmplConflictError} On 409.
|
|
682
|
+
* @throws {SmplValidationError} On 422.
|
|
683
|
+
* @throws {SmplError} On any other non-2xx status.
|
|
684
|
+
*/
|
|
685
|
+
throwForStatus(status, body) {
|
|
686
|
+
switch (status) {
|
|
687
|
+
case 404:
|
|
688
|
+
throw new SmplNotFoundError(body, 404, body);
|
|
689
|
+
case 409:
|
|
690
|
+
throw new SmplConflictError(body, 409, body);
|
|
691
|
+
case 422:
|
|
692
|
+
throw new SmplValidationError(body, 422, body);
|
|
693
|
+
default:
|
|
694
|
+
throw new SmplError(`HTTP ${status}: ${body}`, status, body);
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
};
|
|
563
698
|
|
|
564
|
-
// src/
|
|
565
|
-
var
|
|
566
|
-
/**
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
699
|
+
// src/flags/models.ts
|
|
700
|
+
var Flag = class {
|
|
701
|
+
/** UUID of the flag. */
|
|
702
|
+
id;
|
|
703
|
+
/** Unique key within the account. */
|
|
704
|
+
key;
|
|
705
|
+
/** Human-readable display name. */
|
|
706
|
+
name;
|
|
707
|
+
/** Value type: BOOLEAN, STRING, NUMERIC, or JSON. */
|
|
708
|
+
type;
|
|
709
|
+
/** Flag-level default value. */
|
|
710
|
+
default;
|
|
711
|
+
/** Closed set of possible values. */
|
|
712
|
+
values;
|
|
713
|
+
/** Optional description. */
|
|
714
|
+
description;
|
|
715
|
+
/** Per-environment configuration. */
|
|
716
|
+
environments;
|
|
717
|
+
/** When the flag was created. */
|
|
718
|
+
createdAt;
|
|
719
|
+
/** When the flag was last updated. */
|
|
720
|
+
updatedAt;
|
|
721
|
+
/** @internal */
|
|
722
|
+
_client;
|
|
723
|
+
/** @internal */
|
|
724
|
+
constructor(client, fields) {
|
|
725
|
+
this._client = client;
|
|
726
|
+
this.id = fields.id;
|
|
727
|
+
this.key = fields.key;
|
|
728
|
+
this.name = fields.name;
|
|
729
|
+
this.type = fields.type;
|
|
730
|
+
this.default = fields.default;
|
|
731
|
+
this.values = fields.values;
|
|
732
|
+
this.description = fields.description;
|
|
733
|
+
this.environments = fields.environments;
|
|
734
|
+
this.createdAt = fields.createdAt;
|
|
735
|
+
this.updatedAt = fields.updatedAt;
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* Update this flag's attributes on the server.
|
|
739
|
+
*
|
|
740
|
+
* Only provided fields are changed; others retain their current values.
|
|
741
|
+
*/
|
|
742
|
+
async update(options) {
|
|
743
|
+
const updated = await this._client._updateFlag({
|
|
744
|
+
flag: this,
|
|
745
|
+
environments: options.environments,
|
|
746
|
+
values: options.values,
|
|
747
|
+
default: options.default,
|
|
748
|
+
description: options.description,
|
|
749
|
+
name: options.name
|
|
750
|
+
});
|
|
751
|
+
this._apply(updated);
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* Add a rule to a specific environment.
|
|
755
|
+
*
|
|
756
|
+
* The built rule must include an `environment` key (set via
|
|
757
|
+
* `Rule(...).environment("env_key")`). Re-fetches current state
|
|
758
|
+
* first to avoid stale data.
|
|
759
|
+
*/
|
|
760
|
+
async addRule(builtRule) {
|
|
761
|
+
const envKey = builtRule.environment;
|
|
762
|
+
if (!envKey) {
|
|
763
|
+
throw new Error(
|
|
764
|
+
`Built rule must include 'environment' key. Use new Rule(...).environment("env_key").when(...).serve(...).build()`
|
|
765
|
+
);
|
|
766
|
+
}
|
|
767
|
+
const current = await this._client.get(this.id);
|
|
768
|
+
this._apply(current);
|
|
769
|
+
const envs = { ...this.environments };
|
|
770
|
+
const envData = { ...envs[envKey] ?? { enabled: true, rules: [] } };
|
|
771
|
+
const rules = [...envData.rules ?? []];
|
|
772
|
+
const { environment: _env, ...ruleCopy } = builtRule;
|
|
773
|
+
rules.push(ruleCopy);
|
|
774
|
+
envData.rules = rules;
|
|
775
|
+
envs[envKey] = envData;
|
|
776
|
+
const updated = await this._client._updateFlag({
|
|
777
|
+
flag: this,
|
|
778
|
+
environments: envs
|
|
779
|
+
});
|
|
780
|
+
this._apply(updated);
|
|
781
|
+
}
|
|
782
|
+
/** @internal */
|
|
783
|
+
_apply(other) {
|
|
784
|
+
this.id = other.id;
|
|
785
|
+
this.key = other.key;
|
|
786
|
+
this.name = other.name;
|
|
787
|
+
this.type = other.type;
|
|
788
|
+
this.default = other.default;
|
|
789
|
+
this.values = other.values;
|
|
790
|
+
this.description = other.description;
|
|
791
|
+
this.environments = other.environments;
|
|
792
|
+
this.createdAt = other.createdAt;
|
|
793
|
+
this.updatedAt = other.updatedAt;
|
|
794
|
+
}
|
|
795
|
+
toString() {
|
|
796
|
+
return `Flag(key=${this.key}, type=${this.type}, default=${this.default})`;
|
|
797
|
+
}
|
|
798
|
+
};
|
|
799
|
+
var ContextType = class {
|
|
800
|
+
/** UUID. */
|
|
801
|
+
id;
|
|
802
|
+
/** Unique key within the account. */
|
|
803
|
+
key;
|
|
804
|
+
/** Human-readable display name. */
|
|
805
|
+
name;
|
|
806
|
+
/** Known attributes. */
|
|
807
|
+
attributes;
|
|
808
|
+
constructor(fields) {
|
|
809
|
+
this.id = fields.id;
|
|
810
|
+
this.key = fields.key;
|
|
811
|
+
this.name = fields.name;
|
|
812
|
+
this.attributes = fields.attributes;
|
|
813
|
+
}
|
|
814
|
+
toString() {
|
|
815
|
+
return `ContextType(key=${this.key}, name=${this.name})`;
|
|
816
|
+
}
|
|
817
|
+
};
|
|
818
|
+
|
|
819
|
+
// src/flags/client.ts
|
|
820
|
+
import jsonLogic from "json-logic-js";
|
|
821
|
+
var FLAGS_BASE_URL = "https://flags.smplkit.com";
|
|
822
|
+
var APP_BASE_URL = "https://app.smplkit.com";
|
|
823
|
+
var CACHE_MAX_SIZE = 1e4;
|
|
824
|
+
var CONTEXT_REGISTRATION_LRU_SIZE = 1e4;
|
|
825
|
+
var CONTEXT_BATCH_FLUSH_SIZE = 100;
|
|
826
|
+
async function checkError2(response, context) {
|
|
827
|
+
const body = await response.text().catch(() => "");
|
|
828
|
+
switch (response.status) {
|
|
829
|
+
case 404:
|
|
830
|
+
throw new SmplNotFoundError(body || context, 404, body);
|
|
831
|
+
case 409:
|
|
832
|
+
throw new SmplConflictError(body || context, 409, body);
|
|
833
|
+
case 422:
|
|
834
|
+
throw new SmplValidationError(body || context, 422, body);
|
|
835
|
+
default:
|
|
836
|
+
throw new SmplError(`HTTP ${response.status}: ${body}`, response.status, body);
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
function wrapFetchError2(err) {
|
|
840
|
+
if (err instanceof SmplNotFoundError || err instanceof SmplConflictError || err instanceof SmplValidationError || err instanceof SmplError) {
|
|
841
|
+
throw err;
|
|
842
|
+
}
|
|
843
|
+
if (err instanceof TypeError) {
|
|
844
|
+
throw new SmplConnectionError(`Network error: ${err.message}`);
|
|
845
|
+
}
|
|
846
|
+
throw new SmplConnectionError(
|
|
847
|
+
`Request failed: ${err instanceof Error ? err.message : String(err)}`
|
|
848
|
+
);
|
|
849
|
+
}
|
|
850
|
+
function contextsToEvalDict(contexts) {
|
|
851
|
+
const result = {};
|
|
852
|
+
for (const ctx of contexts) {
|
|
853
|
+
result[ctx.type] = { key: ctx.key, ...ctx.attributes };
|
|
854
|
+
}
|
|
855
|
+
return result;
|
|
856
|
+
}
|
|
857
|
+
function sortedStringify(obj) {
|
|
858
|
+
if (obj === null || obj === void 0) return "null";
|
|
859
|
+
if (typeof obj !== "object") return JSON.stringify(obj);
|
|
860
|
+
if (Array.isArray(obj)) return "[" + obj.map(sortedStringify).join(",") + "]";
|
|
861
|
+
const keys = Object.keys(obj).sort();
|
|
862
|
+
return "{" + keys.map((k) => JSON.stringify(k) + ":" + sortedStringify(obj[k])).join(",") + "}";
|
|
863
|
+
}
|
|
864
|
+
function hashContext(evalDict) {
|
|
865
|
+
const serialized = sortedStringify(evalDict);
|
|
866
|
+
let hash = 0;
|
|
867
|
+
for (let i = 0; i < serialized.length; i++) {
|
|
868
|
+
const chr = serialized.charCodeAt(i);
|
|
869
|
+
hash = (hash << 5) - hash + chr | 0;
|
|
870
|
+
}
|
|
871
|
+
return hash.toString(36);
|
|
872
|
+
}
|
|
873
|
+
function evaluateFlag(flagDef, environment, evalDict) {
|
|
874
|
+
const flagDefault = flagDef.default;
|
|
875
|
+
const environments = flagDef.environments ?? {};
|
|
876
|
+
if (environment === null || !(environment in environments)) {
|
|
877
|
+
return flagDefault;
|
|
878
|
+
}
|
|
879
|
+
const envConfig = environments[environment];
|
|
880
|
+
const envDefault = envConfig.default;
|
|
881
|
+
const fallback = envDefault !== void 0 && envDefault !== null ? envDefault : flagDefault;
|
|
882
|
+
if (!envConfig.enabled) {
|
|
883
|
+
return fallback;
|
|
884
|
+
}
|
|
885
|
+
const rules = envConfig.rules ?? [];
|
|
886
|
+
for (const rule of rules) {
|
|
887
|
+
const logic = rule.logic;
|
|
888
|
+
if (!logic || Object.keys(logic).length === 0) {
|
|
889
|
+
continue;
|
|
890
|
+
}
|
|
891
|
+
try {
|
|
892
|
+
const result = jsonLogic.apply(logic, evalDict);
|
|
893
|
+
if (result) {
|
|
894
|
+
return rule.value;
|
|
895
|
+
}
|
|
896
|
+
} catch {
|
|
897
|
+
continue;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
return fallback;
|
|
901
|
+
}
|
|
902
|
+
var FlagChangeEvent = class {
|
|
903
|
+
key;
|
|
904
|
+
source;
|
|
905
|
+
constructor(key, source) {
|
|
906
|
+
this.key = key;
|
|
907
|
+
this.source = source;
|
|
908
|
+
}
|
|
909
|
+
};
|
|
910
|
+
var ResolutionCache = class {
|
|
911
|
+
_maxSize;
|
|
912
|
+
_cache = /* @__PURE__ */ new Map();
|
|
913
|
+
cacheHits = 0;
|
|
914
|
+
cacheMisses = 0;
|
|
915
|
+
constructor(maxSize = CACHE_MAX_SIZE) {
|
|
916
|
+
this._maxSize = maxSize;
|
|
917
|
+
}
|
|
918
|
+
get(cacheKey) {
|
|
919
|
+
if (this._cache.has(cacheKey)) {
|
|
920
|
+
const value = this._cache.get(cacheKey);
|
|
921
|
+
this._cache.delete(cacheKey);
|
|
922
|
+
this._cache.set(cacheKey, value);
|
|
923
|
+
this.cacheHits++;
|
|
924
|
+
return [true, value];
|
|
925
|
+
}
|
|
926
|
+
this.cacheMisses++;
|
|
927
|
+
return [false, null];
|
|
928
|
+
}
|
|
929
|
+
put(cacheKey, value) {
|
|
930
|
+
if (this._cache.has(cacheKey)) {
|
|
931
|
+
this._cache.delete(cacheKey);
|
|
932
|
+
}
|
|
933
|
+
this._cache.set(cacheKey, value);
|
|
934
|
+
if (this._cache.size > this._maxSize) {
|
|
935
|
+
const firstKey = this._cache.keys().next().value;
|
|
936
|
+
if (firstKey !== void 0) {
|
|
937
|
+
this._cache.delete(firstKey);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
clear() {
|
|
942
|
+
this._cache.clear();
|
|
943
|
+
}
|
|
944
|
+
};
|
|
945
|
+
var FlagStats = class {
|
|
946
|
+
cacheHits;
|
|
947
|
+
cacheMisses;
|
|
948
|
+
constructor(cacheHits, cacheMisses) {
|
|
949
|
+
this.cacheHits = cacheHits;
|
|
950
|
+
this.cacheMisses = cacheMisses;
|
|
951
|
+
}
|
|
952
|
+
};
|
|
953
|
+
var FlagHandleBase = class {
|
|
954
|
+
/** @internal */
|
|
955
|
+
_namespace;
|
|
956
|
+
/** @internal */
|
|
957
|
+
_key;
|
|
958
|
+
/** @internal */
|
|
959
|
+
_default;
|
|
960
|
+
/** @internal */
|
|
961
|
+
_listeners = [];
|
|
962
|
+
constructor(namespace, key, defaultValue) {
|
|
963
|
+
this._namespace = namespace;
|
|
964
|
+
this._key = key;
|
|
965
|
+
this._default = defaultValue;
|
|
966
|
+
}
|
|
967
|
+
get key() {
|
|
968
|
+
return this._key;
|
|
969
|
+
}
|
|
970
|
+
get default() {
|
|
971
|
+
return this._default;
|
|
972
|
+
}
|
|
973
|
+
/* v8 ignore next 3 — overridden by all exported subclasses */
|
|
974
|
+
get(options) {
|
|
975
|
+
return this._namespace._evaluateHandle(this._key, this._default, options?.context ?? null);
|
|
976
|
+
}
|
|
977
|
+
/** Register a flag-specific change listener. Works as a decorator. */
|
|
978
|
+
onChange(callback) {
|
|
979
|
+
this._listeners.push(callback);
|
|
980
|
+
return callback;
|
|
981
|
+
}
|
|
982
|
+
};
|
|
983
|
+
var BoolFlagHandle = class extends FlagHandleBase {
|
|
984
|
+
get(options) {
|
|
985
|
+
const value = this._namespace._evaluateHandle(
|
|
986
|
+
this._key,
|
|
987
|
+
this._default,
|
|
988
|
+
options?.context ?? null
|
|
989
|
+
);
|
|
990
|
+
if (typeof value === "boolean") {
|
|
991
|
+
return value;
|
|
992
|
+
}
|
|
993
|
+
return this._default;
|
|
994
|
+
}
|
|
995
|
+
};
|
|
996
|
+
var StringFlagHandle = class extends FlagHandleBase {
|
|
997
|
+
get(options) {
|
|
998
|
+
const value = this._namespace._evaluateHandle(
|
|
999
|
+
this._key,
|
|
1000
|
+
this._default,
|
|
1001
|
+
options?.context ?? null
|
|
1002
|
+
);
|
|
1003
|
+
if (typeof value === "string") {
|
|
1004
|
+
return value;
|
|
1005
|
+
}
|
|
1006
|
+
return this._default;
|
|
1007
|
+
}
|
|
1008
|
+
};
|
|
1009
|
+
var NumberFlagHandle = class extends FlagHandleBase {
|
|
1010
|
+
get(options) {
|
|
1011
|
+
const value = this._namespace._evaluateHandle(
|
|
1012
|
+
this._key,
|
|
1013
|
+
this._default,
|
|
1014
|
+
options?.context ?? null
|
|
1015
|
+
);
|
|
1016
|
+
if (typeof value === "number") {
|
|
1017
|
+
return value;
|
|
1018
|
+
}
|
|
1019
|
+
return this._default;
|
|
1020
|
+
}
|
|
1021
|
+
};
|
|
1022
|
+
var JsonFlagHandle = class extends FlagHandleBase {
|
|
1023
|
+
get(options) {
|
|
1024
|
+
const value = this._namespace._evaluateHandle(
|
|
1025
|
+
this._key,
|
|
1026
|
+
this._default,
|
|
1027
|
+
options?.context ?? null
|
|
1028
|
+
);
|
|
1029
|
+
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
1030
|
+
return value;
|
|
1031
|
+
}
|
|
1032
|
+
return this._default;
|
|
1033
|
+
}
|
|
1034
|
+
};
|
|
1035
|
+
var ContextRegistrationBuffer = class {
|
|
1036
|
+
_seen = /* @__PURE__ */ new Map();
|
|
1037
|
+
_pending = [];
|
|
1038
|
+
observe(contexts) {
|
|
1039
|
+
for (const ctx of contexts) {
|
|
1040
|
+
const cacheKey = `${ctx.type}:${ctx.key}`;
|
|
1041
|
+
if (!this._seen.has(cacheKey)) {
|
|
1042
|
+
if (this._seen.size >= CONTEXT_REGISTRATION_LRU_SIZE) {
|
|
1043
|
+
const firstKey = this._seen.keys().next().value;
|
|
1044
|
+
if (firstKey !== void 0) {
|
|
1045
|
+
this._seen.delete(firstKey);
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
this._seen.set(cacheKey, ctx.attributes);
|
|
1049
|
+
this._pending.push({
|
|
1050
|
+
id: `${ctx.type}:${ctx.key}`,
|
|
1051
|
+
name: ctx.name ?? ctx.key,
|
|
1052
|
+
attributes: { ...ctx.attributes }
|
|
1053
|
+
});
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
drain() {
|
|
1058
|
+
const batch = this._pending;
|
|
1059
|
+
this._pending = [];
|
|
1060
|
+
return batch;
|
|
1061
|
+
}
|
|
1062
|
+
get pendingCount() {
|
|
1063
|
+
return this._pending.length;
|
|
1064
|
+
}
|
|
1065
|
+
};
|
|
1066
|
+
var FlagsClient = class {
|
|
1067
|
+
/** @internal */
|
|
1068
|
+
_apiKey;
|
|
1069
|
+
/** @internal */
|
|
1070
|
+
_baseUrl = FLAGS_BASE_URL;
|
|
1071
|
+
/** @internal */
|
|
1072
|
+
_http;
|
|
1073
|
+
/** @internal */
|
|
1074
|
+
_transport;
|
|
1075
|
+
// Runtime state
|
|
1076
|
+
_environment = null;
|
|
1077
|
+
_flagStore = {};
|
|
1078
|
+
_connected = false;
|
|
1079
|
+
_cache = new ResolutionCache();
|
|
1080
|
+
_contextProvider = null;
|
|
1081
|
+
_contextBuffer = new ContextRegistrationBuffer();
|
|
1082
|
+
_handles = {};
|
|
1083
|
+
_globalListeners = [];
|
|
1084
|
+
// Shared WebSocket (set during connect)
|
|
1085
|
+
_wsManager = null;
|
|
1086
|
+
_ensureWs;
|
|
1087
|
+
/** @internal — set by SmplClient after construction. */
|
|
1088
|
+
_parent = null;
|
|
1089
|
+
/** @internal */
|
|
1090
|
+
constructor(apiKey, ensureWs, timeout) {
|
|
1091
|
+
this._apiKey = apiKey;
|
|
1092
|
+
this._ensureWs = ensureWs;
|
|
1093
|
+
const ms = timeout ?? 3e4;
|
|
1094
|
+
this._http = createClient2({
|
|
1095
|
+
baseUrl: FLAGS_BASE_URL,
|
|
1096
|
+
headers: {
|
|
1097
|
+
Authorization: `Bearer ${apiKey}`,
|
|
1098
|
+
Accept: "application/json"
|
|
1099
|
+
},
|
|
1100
|
+
fetch: async (request) => {
|
|
1101
|
+
const controller = new AbortController();
|
|
1102
|
+
const timer = setTimeout(() => controller.abort(), ms);
|
|
1103
|
+
try {
|
|
1104
|
+
return await fetch(new Request(request, { signal: controller.signal }));
|
|
1105
|
+
} catch (err) {
|
|
1106
|
+
if (err instanceof DOMException && err.name === "AbortError") {
|
|
1107
|
+
throw new SmplTimeoutError(`Request timed out after ${ms}ms`);
|
|
1108
|
+
}
|
|
1109
|
+
throw err;
|
|
1110
|
+
} finally {
|
|
1111
|
+
clearTimeout(timer);
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
});
|
|
1115
|
+
this._transport = new Transport({ apiKey, timeout: ms });
|
|
1116
|
+
}
|
|
1117
|
+
// ------------------------------------------------------------------
|
|
1118
|
+
// Management methods
|
|
1119
|
+
// ------------------------------------------------------------------
|
|
1120
|
+
/** Create a flag. */
|
|
1121
|
+
async create(key, options) {
|
|
1122
|
+
let values = options.values;
|
|
1123
|
+
if (values === void 0 && options.type === "BOOLEAN") {
|
|
1124
|
+
values = [
|
|
1125
|
+
{ name: "True", value: true },
|
|
1126
|
+
{ name: "False", value: false }
|
|
1127
|
+
];
|
|
1128
|
+
}
|
|
1129
|
+
const body = {
|
|
1130
|
+
data: {
|
|
1131
|
+
type: "flag",
|
|
1132
|
+
attributes: {
|
|
1133
|
+
key,
|
|
1134
|
+
name: options.name,
|
|
1135
|
+
description: options.description ?? "",
|
|
1136
|
+
type: options.type,
|
|
1137
|
+
default: options.default,
|
|
1138
|
+
values: values ?? []
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
};
|
|
1142
|
+
let data;
|
|
1143
|
+
try {
|
|
1144
|
+
const result = await this._http.POST("/api/v1/flags", { body });
|
|
1145
|
+
if (result.error !== void 0) await checkError2(result.response, "Failed to create flag");
|
|
1146
|
+
data = result.data;
|
|
1147
|
+
} catch (err) {
|
|
1148
|
+
wrapFetchError2(err);
|
|
1149
|
+
}
|
|
1150
|
+
if (!data || !data.data) throw new SmplValidationError("Failed to create flag");
|
|
1151
|
+
return this._resourceToModel(data.data);
|
|
1152
|
+
}
|
|
1153
|
+
/** Fetch a flag by UUID. */
|
|
1154
|
+
async get(flagId) {
|
|
1155
|
+
let data;
|
|
1156
|
+
try {
|
|
1157
|
+
const result = await this._http.GET("/api/v1/flags/{id}", {
|
|
1158
|
+
params: { path: { id: flagId } }
|
|
1159
|
+
});
|
|
1160
|
+
if (result.error !== void 0) await checkError2(result.response, `Flag ${flagId} not found`);
|
|
1161
|
+
data = result.data;
|
|
1162
|
+
} catch (err) {
|
|
1163
|
+
wrapFetchError2(err);
|
|
1164
|
+
}
|
|
1165
|
+
if (!data || !data.data) throw new SmplNotFoundError(`Flag ${flagId} not found`);
|
|
1166
|
+
return this._resourceToModel(data.data);
|
|
1167
|
+
}
|
|
1168
|
+
/** List all flags. */
|
|
1169
|
+
async list() {
|
|
1170
|
+
let data;
|
|
1171
|
+
try {
|
|
1172
|
+
const result = await this._http.GET("/api/v1/flags", {});
|
|
1173
|
+
if (result.error !== void 0) await checkError2(result.response, "Failed to list flags");
|
|
1174
|
+
data = result.data;
|
|
1175
|
+
} catch (err) {
|
|
1176
|
+
wrapFetchError2(err);
|
|
1177
|
+
}
|
|
1178
|
+
if (!data) return [];
|
|
1179
|
+
return data.data.map((r) => this._resourceToModel(r));
|
|
1180
|
+
}
|
|
1181
|
+
/** Delete a flag by UUID. */
|
|
1182
|
+
async delete(flagId) {
|
|
1183
|
+
try {
|
|
1184
|
+
const result = await this._http.DELETE("/api/v1/flags/{id}", {
|
|
1185
|
+
params: { path: { id: flagId } }
|
|
1186
|
+
});
|
|
1187
|
+
if (result.error !== void 0 && result.response.status !== 204)
|
|
1188
|
+
await checkError2(result.response, `Failed to delete flag ${flagId}`);
|
|
1189
|
+
} catch (err) {
|
|
1190
|
+
wrapFetchError2(err);
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
/**
|
|
1194
|
+
* Internal: PUT a full flag update.
|
|
1195
|
+
* Called by {@link Flag} instance methods.
|
|
1196
|
+
* @internal
|
|
1197
|
+
*/
|
|
1198
|
+
async _updateFlag(options) {
|
|
1199
|
+
const { flag } = options;
|
|
1200
|
+
const body = {
|
|
1201
|
+
data: {
|
|
1202
|
+
type: "flag",
|
|
1203
|
+
attributes: {
|
|
1204
|
+
key: flag.key,
|
|
1205
|
+
name: options.name !== void 0 ? options.name : flag.name,
|
|
1206
|
+
type: flag.type,
|
|
1207
|
+
default: options.default !== void 0 ? options.default : flag.default,
|
|
1208
|
+
values: options.values !== void 0 ? options.values : flag.values,
|
|
1209
|
+
description: options.description !== void 0 ? options.description : flag.description ?? "",
|
|
1210
|
+
...options.environments !== void 0 ? { environments: options.environments } : flag.environments && Object.keys(flag.environments).length > 0 ? { environments: flag.environments } : {}
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
};
|
|
1214
|
+
let data;
|
|
1215
|
+
try {
|
|
1216
|
+
const result = await this._http.PUT("/api/v1/flags/{id}", {
|
|
1217
|
+
params: { path: { id: flag.id } },
|
|
1218
|
+
body
|
|
1219
|
+
});
|
|
1220
|
+
if (result.error !== void 0)
|
|
1221
|
+
await checkError2(result.response, `Failed to update flag ${flag.id}`);
|
|
1222
|
+
data = result.data;
|
|
1223
|
+
} catch (err) {
|
|
1224
|
+
wrapFetchError2(err);
|
|
1225
|
+
}
|
|
1226
|
+
if (!data || !data.data) throw new SmplValidationError(`Failed to update flag ${flag.id}`);
|
|
1227
|
+
return this._resourceToModel(data.data);
|
|
1228
|
+
}
|
|
1229
|
+
// ------------------------------------------------------------------
|
|
1230
|
+
// Context type management (direct HTTP — not in generated spec)
|
|
1231
|
+
// ------------------------------------------------------------------
|
|
1232
|
+
/** Create a context type. */
|
|
1233
|
+
async createContextType(key, options) {
|
|
1234
|
+
const resp = await this._transport.post(`${APP_BASE_URL}/api/v1/context_types`, {
|
|
1235
|
+
data: { type: "context_type", attributes: { key, name: options.name } }
|
|
1236
|
+
});
|
|
1237
|
+
const data = resp.data ?? {};
|
|
1238
|
+
return this._parseContextType(data);
|
|
1239
|
+
}
|
|
1240
|
+
/** Update a context type (merge attributes). */
|
|
1241
|
+
async updateContextType(ctId, options) {
|
|
1242
|
+
const resp = await this._transport.put(`${APP_BASE_URL}/api/v1/context_types/${ctId}`, {
|
|
1243
|
+
data: { type: "context_type", attributes: { attributes: options.attributes } }
|
|
1244
|
+
});
|
|
1245
|
+
const data = resp.data ?? {};
|
|
1246
|
+
return this._parseContextType(data);
|
|
1247
|
+
}
|
|
1248
|
+
/** List all context types. */
|
|
1249
|
+
async listContextTypes() {
|
|
1250
|
+
const resp = await this._transport.get(`${APP_BASE_URL}/api/v1/context_types`);
|
|
1251
|
+
const items = resp.data ?? [];
|
|
1252
|
+
return items.map((item) => this._parseContextType(item));
|
|
1253
|
+
}
|
|
1254
|
+
/** Delete a context type. */
|
|
1255
|
+
async deleteContextType(ctId) {
|
|
1256
|
+
await this._transport.delete(`${APP_BASE_URL}/api/v1/context_types/${ctId}`);
|
|
1257
|
+
}
|
|
1258
|
+
/** List context instances filtered by context type key. */
|
|
1259
|
+
async listContexts(options) {
|
|
1260
|
+
const resp = await this._transport.get(`${APP_BASE_URL}/api/v1/contexts`, {
|
|
1261
|
+
"filter[context_type]": options.contextTypeKey
|
|
1262
|
+
});
|
|
1263
|
+
return resp.data ?? [];
|
|
1264
|
+
}
|
|
1265
|
+
// ------------------------------------------------------------------
|
|
1266
|
+
// Runtime: typed flag handles
|
|
1267
|
+
// ------------------------------------------------------------------
|
|
1268
|
+
/** Declare a boolean flag handle. */
|
|
1269
|
+
boolFlag(key, defaultValue) {
|
|
1270
|
+
const handle = new BoolFlagHandle(this, key, defaultValue);
|
|
1271
|
+
this._handles[key] = handle;
|
|
1272
|
+
return handle;
|
|
1273
|
+
}
|
|
1274
|
+
/** Declare a string flag handle. */
|
|
1275
|
+
stringFlag(key, defaultValue) {
|
|
1276
|
+
const handle = new StringFlagHandle(this, key, defaultValue);
|
|
1277
|
+
this._handles[key] = handle;
|
|
1278
|
+
return handle;
|
|
1279
|
+
}
|
|
1280
|
+
/** Declare a numeric flag handle. */
|
|
1281
|
+
numberFlag(key, defaultValue) {
|
|
1282
|
+
const handle = new NumberFlagHandle(this, key, defaultValue);
|
|
1283
|
+
this._handles[key] = handle;
|
|
1284
|
+
return handle;
|
|
1285
|
+
}
|
|
1286
|
+
/** Declare a JSON flag handle. */
|
|
1287
|
+
jsonFlag(key, defaultValue) {
|
|
1288
|
+
const handle = new JsonFlagHandle(this, key, defaultValue);
|
|
1289
|
+
this._handles[key] = handle;
|
|
1290
|
+
return handle;
|
|
1291
|
+
}
|
|
1292
|
+
// ------------------------------------------------------------------
|
|
1293
|
+
// Runtime: context provider
|
|
1294
|
+
// ------------------------------------------------------------------
|
|
1295
|
+
/**
|
|
1296
|
+
* Register a context provider function.
|
|
1297
|
+
*
|
|
1298
|
+
* Called on every `handle.get()` to supply the current evaluation
|
|
1299
|
+
* context. Can also be used as a decorator:
|
|
1300
|
+
*
|
|
1301
|
+
* ```typescript
|
|
1302
|
+
* client.flags.setContextProvider(() => [
|
|
1303
|
+
* new Context("user", userId, { plan: userPlan }),
|
|
1304
|
+
* ]);
|
|
1305
|
+
* ```
|
|
1306
|
+
*/
|
|
1307
|
+
setContextProvider(fn) {
|
|
1308
|
+
this._contextProvider = fn;
|
|
1309
|
+
}
|
|
1310
|
+
/**
|
|
1311
|
+
* Register a context provider — decorator-style alias.
|
|
1312
|
+
*
|
|
1313
|
+
* ```typescript
|
|
1314
|
+
* const provider = client.flags.contextProvider(() => [...]);
|
|
1315
|
+
* ```
|
|
1316
|
+
*/
|
|
1317
|
+
contextProvider(fn) {
|
|
1318
|
+
this._contextProvider = fn;
|
|
1319
|
+
return fn;
|
|
1320
|
+
}
|
|
1321
|
+
// ------------------------------------------------------------------
|
|
1322
|
+
// Runtime: connect / disconnect / refresh
|
|
1323
|
+
// ------------------------------------------------------------------
|
|
1324
|
+
/**
|
|
1325
|
+
* Connect to an environment: fetch flag definitions, register on
|
|
1326
|
+
* shared WebSocket, enable local evaluation.
|
|
1327
|
+
* @internal — called by SmplClient.connect().
|
|
1328
|
+
*/
|
|
1329
|
+
async _connectInternal(environment) {
|
|
1330
|
+
this._environment = environment;
|
|
1331
|
+
await this._fetchAllFlags();
|
|
1332
|
+
this._connected = true;
|
|
1333
|
+
this._cache.clear();
|
|
1334
|
+
this._wsManager = this._ensureWs();
|
|
1335
|
+
this._wsManager.on("flag_changed", this._handleFlagChanged);
|
|
1336
|
+
this._wsManager.on("flag_deleted", this._handleFlagDeleted);
|
|
1337
|
+
}
|
|
1338
|
+
/** Disconnect: unregister from WebSocket, flush contexts, clear state. */
|
|
1339
|
+
async disconnect() {
|
|
1340
|
+
if (this._wsManager !== null) {
|
|
1341
|
+
this._wsManager.off("flag_changed", this._handleFlagChanged);
|
|
1342
|
+
this._wsManager.off("flag_deleted", this._handleFlagDeleted);
|
|
1343
|
+
this._wsManager = null;
|
|
1344
|
+
}
|
|
1345
|
+
await this._flushContexts();
|
|
1346
|
+
this._flagStore = {};
|
|
1347
|
+
this._cache.clear();
|
|
1348
|
+
this._connected = false;
|
|
1349
|
+
this._environment = null;
|
|
1350
|
+
}
|
|
1351
|
+
/** Re-fetch all flag definitions and clear cache. */
|
|
1352
|
+
async refresh() {
|
|
1353
|
+
await this._fetchAllFlags();
|
|
1354
|
+
this._cache.clear();
|
|
1355
|
+
this._fireChangeListenersAll("manual");
|
|
1356
|
+
}
|
|
1357
|
+
/** Return the current WebSocket connection status. */
|
|
1358
|
+
connectionStatus() {
|
|
1359
|
+
if (this._wsManager !== null) {
|
|
1360
|
+
return this._wsManager.connectionStatus;
|
|
1361
|
+
}
|
|
1362
|
+
return "disconnected";
|
|
1363
|
+
}
|
|
1364
|
+
/** Return cache statistics. */
|
|
1365
|
+
stats() {
|
|
1366
|
+
return new FlagStats(this._cache.cacheHits, this._cache.cacheMisses);
|
|
1367
|
+
}
|
|
1368
|
+
// ------------------------------------------------------------------
|
|
1369
|
+
// Runtime: change listeners
|
|
1370
|
+
// ------------------------------------------------------------------
|
|
1371
|
+
/** Register a global change listener that fires for any flag change. */
|
|
1372
|
+
onChangeAny(callback) {
|
|
1373
|
+
this._globalListeners.push(callback);
|
|
1374
|
+
return callback;
|
|
1375
|
+
}
|
|
1376
|
+
/**
|
|
1377
|
+
* Register a global change listener — decorator-style alias.
|
|
1378
|
+
*
|
|
1379
|
+
* ```typescript
|
|
1380
|
+
* const listener = client.flags.onChange((event) => { ... });
|
|
1381
|
+
* ```
|
|
1382
|
+
*/
|
|
1383
|
+
onChange(callback) {
|
|
1384
|
+
return this.onChangeAny(callback);
|
|
1385
|
+
}
|
|
1386
|
+
// ------------------------------------------------------------------
|
|
1387
|
+
// Runtime: context registration
|
|
1388
|
+
// ------------------------------------------------------------------
|
|
1389
|
+
/**
|
|
1390
|
+
* Explicitly register context(s) for background batch registration.
|
|
1391
|
+
*
|
|
1392
|
+
* Accepts a single Context or an array. Fire-and-forget — never
|
|
1393
|
+
* blocks. Works before `connect()` is called.
|
|
1394
|
+
*/
|
|
1395
|
+
register(context) {
|
|
1396
|
+
if (Array.isArray(context)) {
|
|
1397
|
+
this._contextBuffer.observe(context);
|
|
1398
|
+
} else {
|
|
1399
|
+
this._contextBuffer.observe([context]);
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
/** Flush pending context registrations to the server. */
|
|
1403
|
+
async flushContexts() {
|
|
1404
|
+
await this._flushContexts();
|
|
1405
|
+
}
|
|
1406
|
+
// ------------------------------------------------------------------
|
|
1407
|
+
// Runtime: Tier 1 evaluate
|
|
1408
|
+
// ------------------------------------------------------------------
|
|
1409
|
+
/**
|
|
1410
|
+
* Tier 1 explicit evaluation — stateless, no provider or cache.
|
|
1411
|
+
*
|
|
1412
|
+
* Useful for scripts, one-off jobs, and infrastructure code.
|
|
1413
|
+
*/
|
|
1414
|
+
async evaluate(key, options) {
|
|
1415
|
+
const evalDict = contextsToEvalDict(options.context);
|
|
1416
|
+
if (this._parent?._service && !("service" in evalDict)) {
|
|
1417
|
+
evalDict["service"] = { key: this._parent._service };
|
|
1418
|
+
}
|
|
1419
|
+
let flagDef = null;
|
|
1420
|
+
if (this._connected && key in this._flagStore) {
|
|
1421
|
+
flagDef = this._flagStore[key];
|
|
1422
|
+
} else {
|
|
1423
|
+
const flags = await this._fetchFlagsList();
|
|
1424
|
+
for (const f of flags) {
|
|
1425
|
+
if (f.key === key) {
|
|
1426
|
+
flagDef = f;
|
|
1427
|
+
break;
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
if (flagDef === null) {
|
|
1432
|
+
return null;
|
|
1433
|
+
}
|
|
1434
|
+
return evaluateFlag(flagDef, options.environment, evalDict);
|
|
1435
|
+
}
|
|
1436
|
+
// ------------------------------------------------------------------
|
|
1437
|
+
// Internal: evaluation
|
|
1438
|
+
// ------------------------------------------------------------------
|
|
1439
|
+
/** @internal */
|
|
1440
|
+
_evaluateHandle(key, defaultValue, context) {
|
|
1441
|
+
if (!this._connected) {
|
|
1442
|
+
throw new SmplNotConnectedError("SmplClient is not connected. Call client.connect() first.");
|
|
1443
|
+
}
|
|
1444
|
+
let evalDict;
|
|
1445
|
+
if (context !== null) {
|
|
1446
|
+
evalDict = contextsToEvalDict(context);
|
|
1447
|
+
} else if (this._contextProvider !== null) {
|
|
1448
|
+
const contexts = this._contextProvider();
|
|
1449
|
+
evalDict = contextsToEvalDict(contexts);
|
|
1450
|
+
this._contextBuffer.observe(contexts);
|
|
1451
|
+
if (this._contextBuffer.pendingCount >= CONTEXT_BATCH_FLUSH_SIZE) {
|
|
1452
|
+
void this._flushContexts();
|
|
1453
|
+
}
|
|
1454
|
+
} else {
|
|
1455
|
+
evalDict = {};
|
|
1456
|
+
}
|
|
1457
|
+
if (this._parent?._service && !("service" in evalDict)) {
|
|
1458
|
+
evalDict["service"] = { key: this._parent._service };
|
|
1459
|
+
}
|
|
1460
|
+
const ctxHash = hashContext(evalDict);
|
|
1461
|
+
const cacheKey = `${key}:${ctxHash}`;
|
|
1462
|
+
const [hit, cachedValue] = this._cache.get(cacheKey);
|
|
1463
|
+
if (hit) {
|
|
1464
|
+
return cachedValue;
|
|
1465
|
+
}
|
|
1466
|
+
const flagDef = this._flagStore[key];
|
|
1467
|
+
if (flagDef === void 0) {
|
|
1468
|
+
this._cache.put(cacheKey, defaultValue);
|
|
1469
|
+
return defaultValue;
|
|
1470
|
+
}
|
|
1471
|
+
let value = evaluateFlag(flagDef, this._environment, evalDict);
|
|
1472
|
+
if (value === null || value === void 0) {
|
|
1473
|
+
value = defaultValue;
|
|
1474
|
+
}
|
|
1475
|
+
this._cache.put(cacheKey, value);
|
|
1476
|
+
return value;
|
|
1477
|
+
}
|
|
1478
|
+
// ------------------------------------------------------------------
|
|
1479
|
+
// Internal: event handlers (called by SharedWebSocket)
|
|
1480
|
+
// ------------------------------------------------------------------
|
|
1481
|
+
_handleFlagChanged = (data) => {
|
|
1482
|
+
const flagKey = data.key;
|
|
1483
|
+
void this._fetchAllFlags().then(() => {
|
|
1484
|
+
this._cache.clear();
|
|
1485
|
+
this._fireChangeListeners(flagKey ?? null, "websocket");
|
|
1486
|
+
});
|
|
1487
|
+
};
|
|
1488
|
+
_handleFlagDeleted = (data) => {
|
|
1489
|
+
const flagKey = data.key;
|
|
1490
|
+
void this._fetchAllFlags().then(() => {
|
|
1491
|
+
this._cache.clear();
|
|
1492
|
+
this._fireChangeListeners(flagKey ?? null, "websocket");
|
|
1493
|
+
});
|
|
1494
|
+
};
|
|
1495
|
+
// ------------------------------------------------------------------
|
|
1496
|
+
// Internal: flag store
|
|
1497
|
+
// ------------------------------------------------------------------
|
|
1498
|
+
async _fetchAllFlags() {
|
|
1499
|
+
const flags = await this._fetchFlagsList();
|
|
1500
|
+
const store = {};
|
|
1501
|
+
for (const f of flags) {
|
|
1502
|
+
store[f.key] = f;
|
|
1503
|
+
}
|
|
1504
|
+
this._flagStore = store;
|
|
1505
|
+
}
|
|
1506
|
+
async _fetchFlagsList() {
|
|
1507
|
+
let data;
|
|
1508
|
+
try {
|
|
1509
|
+
const result = await this._http.GET("/api/v1/flags", {});
|
|
1510
|
+
if (result.error !== void 0) await checkError2(result.response, "Failed to list flags");
|
|
1511
|
+
data = result.data;
|
|
1512
|
+
} catch (err) {
|
|
1513
|
+
wrapFetchError2(err);
|
|
1514
|
+
}
|
|
1515
|
+
if (!data) return [];
|
|
1516
|
+
return data.data.map((r) => this._resourceToPlainDict(r));
|
|
1517
|
+
}
|
|
1518
|
+
// ------------------------------------------------------------------
|
|
1519
|
+
// Internal: change listeners
|
|
1520
|
+
// ------------------------------------------------------------------
|
|
1521
|
+
_fireChangeListeners(flagKey, source) {
|
|
1522
|
+
if (flagKey) {
|
|
1523
|
+
const event = new FlagChangeEvent(flagKey, source);
|
|
1524
|
+
for (const cb of this._globalListeners) {
|
|
1525
|
+
try {
|
|
1526
|
+
cb(event);
|
|
1527
|
+
} catch {
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
const handle = this._handles[flagKey];
|
|
1531
|
+
if (handle) {
|
|
1532
|
+
for (const cb of handle._listeners) {
|
|
1533
|
+
try {
|
|
1534
|
+
cb(event);
|
|
1535
|
+
} catch {
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
_fireChangeListenersAll(source) {
|
|
1542
|
+
for (const flagKey of Object.keys(this._flagStore)) {
|
|
1543
|
+
this._fireChangeListeners(flagKey, source);
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
// ------------------------------------------------------------------
|
|
1547
|
+
// Internal: context flush
|
|
1548
|
+
// ------------------------------------------------------------------
|
|
1549
|
+
async _flushContexts() {
|
|
1550
|
+
const batch = this._contextBuffer.drain();
|
|
1551
|
+
if (batch.length === 0) return;
|
|
1552
|
+
try {
|
|
1553
|
+
await this._transport.put(`${APP_BASE_URL}/api/v1/contexts/bulk`, {
|
|
1554
|
+
contexts: batch
|
|
1555
|
+
});
|
|
1556
|
+
} catch {
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
// ------------------------------------------------------------------
|
|
1560
|
+
// Internal: model conversion
|
|
1561
|
+
// ------------------------------------------------------------------
|
|
1562
|
+
_resourceToModel(resource) {
|
|
1563
|
+
const attrs = resource.attributes;
|
|
1564
|
+
return new Flag(this, {
|
|
1565
|
+
id: resource.id ?? "",
|
|
1566
|
+
key: attrs.key,
|
|
1567
|
+
name: attrs.name,
|
|
1568
|
+
type: attrs.type,
|
|
1569
|
+
default: attrs.default,
|
|
1570
|
+
values: (attrs.values ?? []).map((v) => ({ name: v.name, value: v.value })),
|
|
1571
|
+
description: attrs.description ?? null,
|
|
1572
|
+
environments: attrs.environments ?? {},
|
|
1573
|
+
createdAt: attrs.created_at ?? null,
|
|
1574
|
+
updatedAt: attrs.updated_at ?? null
|
|
1575
|
+
});
|
|
1576
|
+
}
|
|
1577
|
+
_resourceToPlainDict(resource) {
|
|
1578
|
+
const attrs = resource.attributes;
|
|
1579
|
+
return {
|
|
1580
|
+
key: attrs.key,
|
|
1581
|
+
name: attrs.name,
|
|
1582
|
+
type: attrs.type,
|
|
1583
|
+
default: attrs.default,
|
|
1584
|
+
values: (attrs.values ?? []).map((v) => ({ name: v.name, value: v.value })),
|
|
1585
|
+
description: attrs.description ?? null,
|
|
1586
|
+
environments: attrs.environments ?? {}
|
|
1587
|
+
};
|
|
1588
|
+
}
|
|
1589
|
+
_parseContextType(data) {
|
|
1590
|
+
const attrs = data.attributes ?? {};
|
|
1591
|
+
return new ContextType({
|
|
1592
|
+
id: data.id ?? "",
|
|
1593
|
+
key: attrs.key ?? "",
|
|
1594
|
+
name: attrs.name ?? "",
|
|
1595
|
+
attributes: attrs.attributes ?? {}
|
|
1596
|
+
});
|
|
1597
|
+
}
|
|
1598
|
+
};
|
|
1599
|
+
|
|
1600
|
+
// src/ws.ts
|
|
1601
|
+
import WebSocket from "ws";
|
|
1602
|
+
var BACKOFF_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 32e3, 6e4];
|
|
1603
|
+
var SharedWebSocket = class {
|
|
1604
|
+
_appBaseUrl;
|
|
1605
|
+
_apiKey;
|
|
1606
|
+
_listeners = /* @__PURE__ */ new Map();
|
|
1607
|
+
_connectionStatus = "disconnected";
|
|
1608
|
+
_closed = false;
|
|
1609
|
+
_ws = null;
|
|
1610
|
+
_reconnectTimer = null;
|
|
1611
|
+
_backoffIndex = 0;
|
|
1612
|
+
constructor(appBaseUrl, apiKey) {
|
|
1613
|
+
this._appBaseUrl = appBaseUrl;
|
|
1614
|
+
this._apiKey = apiKey;
|
|
1615
|
+
}
|
|
1616
|
+
// ------------------------------------------------------------------
|
|
1617
|
+
// Listener registration
|
|
1618
|
+
// ------------------------------------------------------------------
|
|
1619
|
+
/** Register a listener for a specific event type. */
|
|
1620
|
+
on(eventName, callback) {
|
|
1621
|
+
if (!this._listeners.has(eventName)) {
|
|
1622
|
+
this._listeners.set(eventName, []);
|
|
1623
|
+
}
|
|
1624
|
+
this._listeners.get(eventName).push(callback);
|
|
1625
|
+
}
|
|
1626
|
+
/** Unregister a listener for a specific event type. */
|
|
1627
|
+
off(eventName, callback) {
|
|
1628
|
+
const list = this._listeners.get(eventName);
|
|
1629
|
+
if (list) {
|
|
1630
|
+
const idx = list.indexOf(callback);
|
|
1631
|
+
if (idx !== -1) {
|
|
1632
|
+
list.splice(idx, 1);
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
_dispatch(eventName, data) {
|
|
1637
|
+
const callbacks = this._listeners.get(eventName);
|
|
1638
|
+
if (callbacks) {
|
|
1639
|
+
for (const cb of [...callbacks]) {
|
|
1640
|
+
try {
|
|
1641
|
+
cb(data);
|
|
1642
|
+
} catch {
|
|
1643
|
+
}
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
// ------------------------------------------------------------------
|
|
1648
|
+
// Connection status
|
|
1649
|
+
// ------------------------------------------------------------------
|
|
1650
|
+
get connectionStatus() {
|
|
1651
|
+
return this._connectionStatus;
|
|
1652
|
+
}
|
|
1653
|
+
// ------------------------------------------------------------------
|
|
1654
|
+
// Lifecycle
|
|
1655
|
+
// ------------------------------------------------------------------
|
|
1656
|
+
/** Start the WebSocket connection. */
|
|
1657
|
+
start() {
|
|
1658
|
+
this._closed = false;
|
|
1659
|
+
this._connect();
|
|
1660
|
+
}
|
|
1661
|
+
/** Stop the WebSocket connection. */
|
|
1662
|
+
stop() {
|
|
1663
|
+
this._closed = true;
|
|
1664
|
+
this._connectionStatus = "disconnected";
|
|
1665
|
+
if (this._reconnectTimer !== null) {
|
|
1666
|
+
clearTimeout(this._reconnectTimer);
|
|
1667
|
+
this._reconnectTimer = null;
|
|
1668
|
+
}
|
|
1669
|
+
if (this._ws !== null) {
|
|
1670
|
+
this._ws.close();
|
|
1671
|
+
this._ws = null;
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
// ------------------------------------------------------------------
|
|
1675
|
+
// Connection internals
|
|
1676
|
+
// ------------------------------------------------------------------
|
|
1677
|
+
_buildWsUrl() {
|
|
1678
|
+
let url = this._appBaseUrl;
|
|
1679
|
+
if (url.startsWith("https://")) {
|
|
1680
|
+
url = "wss://" + url.slice("https://".length);
|
|
1681
|
+
} else if (url.startsWith("http://")) {
|
|
1682
|
+
url = "ws://" + url.slice("http://".length);
|
|
1683
|
+
} else {
|
|
1684
|
+
url = "wss://" + url;
|
|
1685
|
+
}
|
|
1686
|
+
url = url.replace(/\/$/, "");
|
|
1687
|
+
return `${url}/api/ws/v1/events?api_key=${this._apiKey}`;
|
|
1688
|
+
}
|
|
1689
|
+
_connect() {
|
|
1690
|
+
if (this._closed) return;
|
|
1691
|
+
this._connectionStatus = "connecting";
|
|
1692
|
+
const wsUrl = this._buildWsUrl();
|
|
1693
|
+
try {
|
|
1694
|
+
const ws = new WebSocket(wsUrl);
|
|
1695
|
+
this._ws = ws;
|
|
1696
|
+
ws.on("open", () => {
|
|
1697
|
+
if (this._closed) {
|
|
1698
|
+
ws.close();
|
|
1699
|
+
return;
|
|
1700
|
+
}
|
|
1701
|
+
});
|
|
1702
|
+
ws.on("message", (data) => {
|
|
1703
|
+
try {
|
|
1704
|
+
const raw = String(data);
|
|
1705
|
+
if (raw === "ping") {
|
|
1706
|
+
ws.send("pong");
|
|
1707
|
+
return;
|
|
1708
|
+
}
|
|
1709
|
+
const msg = JSON.parse(raw);
|
|
1710
|
+
if (msg.type === "connected") {
|
|
1711
|
+
this._backoffIndex = 0;
|
|
1712
|
+
this._connectionStatus = "connected";
|
|
1713
|
+
return;
|
|
1714
|
+
}
|
|
1715
|
+
if (msg.type === "error") {
|
|
1716
|
+
return;
|
|
1717
|
+
}
|
|
1718
|
+
const eventName = msg.event;
|
|
1719
|
+
if (eventName) {
|
|
1720
|
+
this._dispatch(eventName, msg);
|
|
1721
|
+
}
|
|
1722
|
+
} catch {
|
|
1723
|
+
}
|
|
1724
|
+
});
|
|
1725
|
+
ws.on("close", () => {
|
|
1726
|
+
if (!this._closed) {
|
|
1727
|
+
this._connectionStatus = "disconnected";
|
|
1728
|
+
this._scheduleReconnect();
|
|
1729
|
+
}
|
|
1730
|
+
});
|
|
1731
|
+
ws.on("error", () => {
|
|
1732
|
+
});
|
|
1733
|
+
} catch {
|
|
1734
|
+
if (!this._closed) {
|
|
1735
|
+
this._scheduleReconnect();
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
_scheduleReconnect() {
|
|
1740
|
+
if (this._closed) return;
|
|
1741
|
+
const delay = BACKOFF_MS[Math.min(this._backoffIndex, BACKOFF_MS.length - 1)];
|
|
1742
|
+
this._backoffIndex++;
|
|
1743
|
+
this._connectionStatus = "connecting";
|
|
1744
|
+
this._reconnectTimer = setTimeout(() => {
|
|
1745
|
+
this._reconnectTimer = null;
|
|
1746
|
+
this._connect();
|
|
1747
|
+
}, delay);
|
|
1748
|
+
}
|
|
1749
|
+
};
|
|
1750
|
+
|
|
1751
|
+
// src/resolve.ts
|
|
1752
|
+
import { readFileSync } from "fs";
|
|
1753
|
+
import { homedir } from "os";
|
|
1754
|
+
import { join } from "path";
|
|
1755
|
+
var NO_API_KEY_MESSAGE = "No API key provided. Set one of:\n 1. Pass apiKey to the constructor\n 2. Set the SMPLKIT_API_KEY environment variable\n 3. Create a ~/.smplkit file with:\n [default]\n api_key = your_key_here";
|
|
1756
|
+
function resolveApiKey(explicit) {
|
|
1757
|
+
if (explicit) return explicit;
|
|
1758
|
+
const envVal = process.env.SMPLKIT_API_KEY;
|
|
1759
|
+
if (envVal) return envVal;
|
|
1760
|
+
const configPath = join(homedir(), ".smplkit");
|
|
1761
|
+
try {
|
|
1762
|
+
const content = readFileSync(configPath, "utf-8");
|
|
1763
|
+
let inDefaultSection = false;
|
|
1764
|
+
for (const line of content.split("\n")) {
|
|
1765
|
+
const trimmed = line.trim();
|
|
1766
|
+
if (trimmed === "" || trimmed.startsWith("#")) continue;
|
|
1767
|
+
if (trimmed.startsWith("[")) {
|
|
1768
|
+
inDefaultSection = trimmed.toLowerCase() === "[default]";
|
|
1769
|
+
continue;
|
|
1770
|
+
}
|
|
1771
|
+
if (inDefaultSection && trimmed.startsWith("api_key")) {
|
|
1772
|
+
const eqIndex = trimmed.indexOf("=");
|
|
1773
|
+
if (eqIndex !== -1) {
|
|
1774
|
+
const value = trimmed.slice(eqIndex + 1).trim();
|
|
1775
|
+
if (value) return value;
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
}
|
|
1779
|
+
} catch {
|
|
1780
|
+
}
|
|
1781
|
+
throw new SmplError(NO_API_KEY_MESSAGE);
|
|
1782
|
+
}
|
|
1783
|
+
|
|
1784
|
+
// src/client.ts
|
|
1785
|
+
var APP_BASE_URL2 = "https://app.smplkit.com";
|
|
1786
|
+
var NO_ENVIRONMENT_MESSAGE = "No environment provided. Set one of:\n 1. Pass environment to the constructor\n 2. Set the SMPLKIT_ENVIRONMENT environment variable";
|
|
1787
|
+
var SmplClient = class {
|
|
1788
|
+
/** Client for config management-plane operations. */
|
|
1789
|
+
config;
|
|
1790
|
+
/** Client for flags management and runtime operations. */
|
|
1791
|
+
flags;
|
|
1792
|
+
_wsManager = null;
|
|
1793
|
+
_apiKey;
|
|
1794
|
+
/** @internal */
|
|
1795
|
+
_environment;
|
|
1796
|
+
/** @internal */
|
|
1797
|
+
_service;
|
|
1798
|
+
_connected = false;
|
|
1799
|
+
_timeout;
|
|
1800
|
+
constructor(options = {}) {
|
|
1801
|
+
const apiKey = resolveApiKey(options.apiKey);
|
|
1802
|
+
this._apiKey = apiKey;
|
|
1803
|
+
const environment = options.environment || process.env.SMPLKIT_ENVIRONMENT;
|
|
1804
|
+
if (!environment) {
|
|
1805
|
+
throw new SmplError(NO_ENVIRONMENT_MESSAGE);
|
|
1806
|
+
}
|
|
1807
|
+
this._environment = environment;
|
|
1808
|
+
this._service = options.service || process.env.SMPLKIT_SERVICE || null;
|
|
1809
|
+
this._timeout = options.timeout ?? 3e4;
|
|
1810
|
+
this.config = new ConfigClient(apiKey, this._timeout);
|
|
1811
|
+
this.flags = new FlagsClient(apiKey, () => this._ensureWs(), this._timeout);
|
|
1812
|
+
this.config._getSharedWs = () => this._ensureWs();
|
|
1813
|
+
this.flags._parent = this;
|
|
1814
|
+
this.config._parent = this;
|
|
1815
|
+
}
|
|
1816
|
+
/**
|
|
1817
|
+
* Connect to the smplkit platform.
|
|
1818
|
+
*
|
|
1819
|
+
* Fetches initial flag and config data, opens the shared WebSocket,
|
|
1820
|
+
* and registers the service as a context instance (if provided).
|
|
1821
|
+
*
|
|
1822
|
+
* This method is idempotent — calling it multiple times is safe.
|
|
1823
|
+
*/
|
|
1824
|
+
async connect() {
|
|
1825
|
+
if (this._connected) return;
|
|
1826
|
+
if (this._service) {
|
|
1827
|
+
await this._registerServiceContext();
|
|
1828
|
+
}
|
|
1829
|
+
await this.flags._connectInternal(this._environment);
|
|
1830
|
+
await this.config._connectInternal(this._environment);
|
|
1831
|
+
this._connected = true;
|
|
1832
|
+
}
|
|
1833
|
+
/** @internal */
|
|
1834
|
+
async _registerServiceContext() {
|
|
1835
|
+
try {
|
|
1836
|
+
await fetch(`${APP_BASE_URL2}/api/v1/contexts/bulk`, {
|
|
1837
|
+
method: "PUT",
|
|
1838
|
+
headers: {
|
|
1839
|
+
Authorization: `Bearer ${this._apiKey}`,
|
|
1840
|
+
"Content-Type": "application/json"
|
|
1841
|
+
},
|
|
1842
|
+
body: JSON.stringify({
|
|
1843
|
+
contexts: [
|
|
1844
|
+
{
|
|
1845
|
+
type: "service",
|
|
1846
|
+
key: this._service,
|
|
1847
|
+
attributes: { name: this._service }
|
|
1848
|
+
}
|
|
1849
|
+
]
|
|
1850
|
+
})
|
|
1851
|
+
});
|
|
1852
|
+
} catch {
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
/** Lazily create and start the shared WebSocket. @internal */
|
|
1856
|
+
_ensureWs() {
|
|
1857
|
+
if (this._wsManager === null) {
|
|
1858
|
+
this._wsManager = new SharedWebSocket(APP_BASE_URL2, this._apiKey);
|
|
1859
|
+
this._wsManager.start();
|
|
1860
|
+
}
|
|
1861
|
+
return this._wsManager;
|
|
1862
|
+
}
|
|
1863
|
+
/** Close the shared WebSocket and release resources. */
|
|
1864
|
+
close() {
|
|
1865
|
+
if (this._wsManager !== null) {
|
|
1866
|
+
this._wsManager.stop();
|
|
1867
|
+
this._wsManager = null;
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
};
|
|
1871
|
+
|
|
1872
|
+
// src/config/runtime.ts
|
|
1873
|
+
var ConfigRuntime = class {
|
|
1874
|
+
_cache;
|
|
1875
|
+
_chain;
|
|
1876
|
+
_fetchCount;
|
|
1877
|
+
_lastFetchAt;
|
|
1878
|
+
_closed = false;
|
|
1879
|
+
_listeners = [];
|
|
1880
|
+
_environment;
|
|
1881
|
+
_fetchChain;
|
|
1882
|
+
_sharedWs = null;
|
|
1883
|
+
/** @internal */
|
|
1884
|
+
constructor(options) {
|
|
1885
|
+
this._environment = options.environment;
|
|
1886
|
+
this._fetchChain = options.fetchChain;
|
|
1887
|
+
this._chain = options.chain;
|
|
1888
|
+
this._cache = resolveChain(options.chain, options.environment);
|
|
1889
|
+
this._fetchCount = options.chain.length;
|
|
1890
|
+
this._lastFetchAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1891
|
+
if (options.sharedWs) {
|
|
1892
|
+
this._sharedWs = options.sharedWs;
|
|
1893
|
+
this._sharedWs.on("config_changed", this._handleConfigChanged);
|
|
1894
|
+
this._sharedWs.on("config_deleted", this._handleConfigDeleted);
|
|
1895
|
+
}
|
|
1896
|
+
}
|
|
1897
|
+
// ---- Value access (synchronous, local cache) ----
|
|
1898
|
+
/**
|
|
1899
|
+
* Return the resolved value for `key`, or `defaultValue` if absent.
|
|
1900
|
+
*
|
|
1901
|
+
* @param key - The config key to look up.
|
|
1902
|
+
* @param defaultValue - Returned when the key is not present (default: null).
|
|
1903
|
+
*/
|
|
1904
|
+
get(key, defaultValue = null) {
|
|
1905
|
+
return key in this._cache ? this._cache[key] : defaultValue;
|
|
1906
|
+
}
|
|
1907
|
+
/**
|
|
1908
|
+
* Return the value as a string, or `defaultValue` if absent or not a string.
|
|
1909
|
+
*/
|
|
1910
|
+
getString(key, defaultValue = null) {
|
|
1911
|
+
const value = this._cache[key];
|
|
1912
|
+
return typeof value === "string" ? value : defaultValue;
|
|
1913
|
+
}
|
|
1914
|
+
/**
|
|
1915
|
+
* Return the value as a number, or `defaultValue` if absent or not a number.
|
|
1916
|
+
*/
|
|
1917
|
+
getInt(key, defaultValue = null) {
|
|
1918
|
+
const value = this._cache[key];
|
|
1919
|
+
return typeof value === "number" ? value : defaultValue;
|
|
1920
|
+
}
|
|
1921
|
+
/**
|
|
1922
|
+
* Return the value as a boolean, or `defaultValue` if absent or not a boolean.
|
|
1923
|
+
*/
|
|
1924
|
+
getBool(key, defaultValue = null) {
|
|
1925
|
+
const value = this._cache[key];
|
|
1926
|
+
return typeof value === "boolean" ? value : defaultValue;
|
|
1927
|
+
}
|
|
1928
|
+
/**
|
|
1929
|
+
* Return whether `key` is present in the resolved configuration.
|
|
1930
|
+
*/
|
|
1931
|
+
exists(key) {
|
|
1932
|
+
return key in this._cache;
|
|
1933
|
+
}
|
|
1934
|
+
/**
|
|
1935
|
+
* Return a shallow copy of the full resolved configuration.
|
|
1936
|
+
*/
|
|
1937
|
+
getAll() {
|
|
1938
|
+
return { ...this._cache };
|
|
1939
|
+
}
|
|
1940
|
+
// ---- Change listeners ----
|
|
1941
|
+
/**
|
|
1942
|
+
* Register a listener that fires when a config value changes.
|
|
1943
|
+
*
|
|
1944
|
+
* @param callback - Called with a {@link ConfigChangeEvent} on each change.
|
|
1945
|
+
* @param options.key - If provided, the listener fires only for this key.
|
|
1946
|
+
* If omitted, the listener fires for all changes.
|
|
1947
|
+
*/
|
|
1948
|
+
onChange(callback, options) {
|
|
1949
|
+
this._listeners.push({
|
|
1950
|
+
callback,
|
|
1951
|
+
key: options?.key ?? null
|
|
1952
|
+
});
|
|
1953
|
+
}
|
|
1954
|
+
// ---- Diagnostics ----
|
|
1955
|
+
/**
|
|
1956
|
+
* Return diagnostic statistics for this runtime.
|
|
1957
|
+
*/
|
|
1958
|
+
stats() {
|
|
1959
|
+
return {
|
|
1960
|
+
fetchCount: this._fetchCount,
|
|
1961
|
+
lastFetchAt: this._lastFetchAt
|
|
1962
|
+
};
|
|
1963
|
+
}
|
|
1964
|
+
/**
|
|
1965
|
+
* Return the current WebSocket connection status.
|
|
1966
|
+
*/
|
|
1967
|
+
connectionStatus() {
|
|
1968
|
+
if (this._sharedWs) {
|
|
1969
|
+
return this._sharedWs.connectionStatus;
|
|
1970
|
+
}
|
|
1971
|
+
return "disconnected";
|
|
1972
|
+
}
|
|
1973
|
+
// ---- Lifecycle ----
|
|
1974
|
+
/**
|
|
1975
|
+
* Force a manual refresh of the cached configuration.
|
|
1976
|
+
*
|
|
1977
|
+
* Re-fetches the full config chain via HTTP, re-resolves values, updates
|
|
1978
|
+
* the local cache, and fires listeners for any detected changes.
|
|
1979
|
+
*
|
|
1980
|
+
* @throws {Error} If no `fetchChain` function was provided on construction.
|
|
1981
|
+
*/
|
|
1982
|
+
async refresh() {
|
|
1983
|
+
if (!this._fetchChain) {
|
|
1984
|
+
throw new Error("No fetchChain function provided; cannot refresh.");
|
|
1985
|
+
}
|
|
1986
|
+
const newChain = await this._fetchChain();
|
|
1987
|
+
const oldCache = this._cache;
|
|
1988
|
+
this._chain = newChain;
|
|
1989
|
+
this._cache = resolveChain(newChain, this._environment);
|
|
1990
|
+
this._fetchCount += newChain.length;
|
|
1991
|
+
this._lastFetchAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1992
|
+
this._diffAndFire(oldCache, this._cache, "manual");
|
|
1993
|
+
}
|
|
1994
|
+
/**
|
|
1995
|
+
* Close the runtime connection.
|
|
1996
|
+
*
|
|
1997
|
+
* Unregisters from the shared WebSocket. Safe to call multiple times.
|
|
1998
|
+
*/
|
|
1999
|
+
async close() {
|
|
2000
|
+
this._closed = true;
|
|
2001
|
+
if (this._sharedWs !== null) {
|
|
2002
|
+
this._sharedWs.off("config_changed", this._handleConfigChanged);
|
|
2003
|
+
this._sharedWs.off("config_deleted", this._handleConfigDeleted);
|
|
2004
|
+
this._sharedWs = null;
|
|
2005
|
+
}
|
|
2006
|
+
}
|
|
2007
|
+
/**
|
|
2008
|
+
* Async dispose support for `await using` (TypeScript 5.2+).
|
|
2009
|
+
*/
|
|
2010
|
+
async [Symbol.asyncDispose]() {
|
|
2011
|
+
await this.close();
|
|
2012
|
+
}
|
|
2013
|
+
// ---- Shared WebSocket event handlers ----
|
|
2014
|
+
_handleConfigChanged = (data) => {
|
|
2015
|
+
if (this._closed) return;
|
|
2016
|
+
const configId = data.config_id;
|
|
2017
|
+
const changes = data.changes;
|
|
2018
|
+
if (configId && changes) {
|
|
2019
|
+
this._applyChanges(configId, changes);
|
|
2020
|
+
} else if (this._fetchChain) {
|
|
2021
|
+
void this._fetchChain().then((newChain) => {
|
|
2022
|
+
const oldCache = this._cache;
|
|
2023
|
+
this._chain = newChain;
|
|
2024
|
+
this._cache = resolveChain(newChain, this._environment);
|
|
2025
|
+
this._fetchCount += newChain.length;
|
|
2026
|
+
this._lastFetchAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2027
|
+
this._diffAndFire(oldCache, this._cache, "websocket");
|
|
2028
|
+
}).catch(() => {
|
|
2029
|
+
});
|
|
2030
|
+
}
|
|
2031
|
+
};
|
|
2032
|
+
_handleConfigDeleted = (_data) => {
|
|
2033
|
+
this._closed = true;
|
|
2034
|
+
void this.close();
|
|
2035
|
+
};
|
|
2036
|
+
_applyChanges(configId, changes) {
|
|
2037
|
+
const chainEntry = this._chain.find((c) => c.id === configId);
|
|
2038
|
+
if (!chainEntry) return;
|
|
2039
|
+
for (const change of changes) {
|
|
2040
|
+
const { key, new_value } = change;
|
|
2041
|
+
const envEntry = chainEntry.environments[this._environment] !== void 0 && chainEntry.environments[this._environment] !== null ? chainEntry.environments[this._environment] : null;
|
|
2042
|
+
const envValues = envEntry !== null && typeof envEntry === "object" ? envEntry.values ?? {} : null;
|
|
2043
|
+
if (new_value === null || new_value === void 0) {
|
|
2044
|
+
delete chainEntry.items[key];
|
|
2045
|
+
if (envValues) delete envValues[key];
|
|
2046
|
+
} else if (envValues && key in envValues) {
|
|
2047
|
+
envValues[key] = new_value;
|
|
2048
|
+
} else if (key in chainEntry.items) {
|
|
2049
|
+
chainEntry.items[key] = new_value;
|
|
2050
|
+
} else {
|
|
2051
|
+
chainEntry.items[key] = new_value;
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
const oldCache = this._cache;
|
|
2055
|
+
this._cache = resolveChain(this._chain, this._environment);
|
|
2056
|
+
this._diffAndFire(oldCache, this._cache, "websocket");
|
|
2057
|
+
}
|
|
2058
|
+
_diffAndFire(oldCache, newCache, source) {
|
|
2059
|
+
const allKeys = /* @__PURE__ */ new Set([...Object.keys(oldCache), ...Object.keys(newCache)]);
|
|
2060
|
+
for (const key of allKeys) {
|
|
2061
|
+
const oldVal = key in oldCache ? oldCache[key] : null;
|
|
2062
|
+
const newVal = key in newCache ? newCache[key] : null;
|
|
2063
|
+
if (JSON.stringify(oldVal) !== JSON.stringify(newVal)) {
|
|
2064
|
+
const event = { key, oldValue: oldVal, newValue: newVal, source };
|
|
2065
|
+
this._fireListeners(event);
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
_fireListeners(event) {
|
|
2070
|
+
for (const listener of this._listeners) {
|
|
2071
|
+
if (listener.key === null || listener.key === event.key) {
|
|
2072
|
+
try {
|
|
2073
|
+
listener.callback(event);
|
|
2074
|
+
} catch {
|
|
2075
|
+
}
|
|
2076
|
+
}
|
|
2077
|
+
}
|
|
2078
|
+
}
|
|
2079
|
+
};
|
|
2080
|
+
|
|
2081
|
+
// src/flags/types.ts
|
|
2082
|
+
var Context = class {
|
|
2083
|
+
type;
|
|
2084
|
+
key;
|
|
2085
|
+
name;
|
|
2086
|
+
attributes;
|
|
2087
|
+
constructor(type, key, attributes, options) {
|
|
2088
|
+
this.type = type;
|
|
2089
|
+
this.key = key;
|
|
2090
|
+
this.name = options?.name ?? null;
|
|
2091
|
+
this.attributes = { ...attributes ?? {} };
|
|
2092
|
+
}
|
|
2093
|
+
toString() {
|
|
2094
|
+
return `Context(type=${this.type}, key=${this.key}, name=${this.name})`;
|
|
2095
|
+
}
|
|
2096
|
+
};
|
|
2097
|
+
var Rule = class {
|
|
2098
|
+
_description;
|
|
2099
|
+
_conditions = [];
|
|
2100
|
+
_value = null;
|
|
2101
|
+
_environment = null;
|
|
2102
|
+
constructor(description) {
|
|
2103
|
+
this._description = description;
|
|
2104
|
+
}
|
|
2105
|
+
/** Tag this rule with an environment key (used by `addRule`). */
|
|
2106
|
+
environment(envKey) {
|
|
2107
|
+
this._environment = envKey;
|
|
2108
|
+
return this;
|
|
2109
|
+
}
|
|
2110
|
+
/** Add a condition. Multiple calls are AND'd. */
|
|
2111
|
+
when(variable, op, value) {
|
|
2112
|
+
if (op === "contains") {
|
|
2113
|
+
this._conditions.push({ in: [value, { var: variable }] });
|
|
2114
|
+
} else {
|
|
2115
|
+
this._conditions.push({ [op]: [{ var: variable }, value] });
|
|
2116
|
+
}
|
|
2117
|
+
return this;
|
|
2118
|
+
}
|
|
2119
|
+
/** Set the value returned when this rule matches. */
|
|
2120
|
+
serve(value) {
|
|
2121
|
+
this._value = value;
|
|
2122
|
+
return this;
|
|
2123
|
+
}
|
|
2124
|
+
/** Finalize and return the rule as a plain object. */
|
|
2125
|
+
build() {
|
|
2126
|
+
let logic;
|
|
2127
|
+
if (this._conditions.length === 1) {
|
|
2128
|
+
logic = this._conditions[0];
|
|
2129
|
+
} else if (this._conditions.length > 1) {
|
|
2130
|
+
logic = { and: this._conditions };
|
|
2131
|
+
} else {
|
|
2132
|
+
logic = {};
|
|
2133
|
+
}
|
|
2134
|
+
const result = {
|
|
2135
|
+
description: this._description,
|
|
2136
|
+
logic,
|
|
2137
|
+
value: this._value
|
|
2138
|
+
};
|
|
2139
|
+
if (this._environment !== null) {
|
|
2140
|
+
result.environment = this._environment;
|
|
2141
|
+
}
|
|
2142
|
+
return result;
|
|
571
2143
|
}
|
|
572
2144
|
};
|
|
573
2145
|
export {
|
|
2146
|
+
BoolFlagHandle,
|
|
574
2147
|
Config,
|
|
575
2148
|
ConfigClient,
|
|
576
2149
|
ConfigRuntime,
|
|
2150
|
+
Context,
|
|
2151
|
+
ContextType,
|
|
2152
|
+
Flag,
|
|
2153
|
+
FlagChangeEvent,
|
|
2154
|
+
FlagStats,
|
|
2155
|
+
FlagsClient,
|
|
2156
|
+
JsonFlagHandle,
|
|
2157
|
+
NumberFlagHandle,
|
|
2158
|
+
Rule,
|
|
2159
|
+
SharedWebSocket,
|
|
577
2160
|
SmplClient,
|
|
578
2161
|
SmplConflictError,
|
|
579
2162
|
SmplConnectionError,
|
|
580
2163
|
SmplError,
|
|
2164
|
+
SmplNotConnectedError,
|
|
581
2165
|
SmplNotFoundError,
|
|
582
2166
|
SmplTimeoutError,
|
|
583
|
-
SmplValidationError
|
|
2167
|
+
SmplValidationError,
|
|
2168
|
+
StringFlagHandle
|
|
584
2169
|
};
|
|
585
2170
|
//# sourceMappingURL=index.js.map
|