@wolfstar/experiments 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2022 Wolfstar Project
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,49 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
+ <picture>
3
+ <img src="https://cdn.wolfstar.rocks/assets/stars-components/wordmark.webp" alt="Stars Components" width="440" />
4
+ </picture>
2
5
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
6
+ # @wolfstar/experiments
7
+
8
+ **Feature-flag experiments for the WolfStar network, resolved the same way in every bot and site.**
9
+
10
+ [![version](https://npmx.dev/api/registry/badge/version/@wolfstar/experiments)](https://npmx.dev/package/@wolfstar/experiments)
11
+ [![downloads](https://npmx.dev/api/registry/badge/downloads/@wolfstar/experiments)](https://npmx.dev/package/@wolfstar/experiments)
12
+ [![license](https://img.shields.io/github/license/wolfstar-project/stars-components?style=flat-square&color=informational)](https://github.com/wolfstar-project/stars-components/blob/main/LICENSE)
13
+
14
+ </div>
15
+
16
+ ## Description
17
+
18
+ Ring keeps the definitions of the experiments and their overrides. WolfStar, Staryl and the dashboard have to agree on which guild or user is in an experiment, so the hash and the order of the checks live here, once. The package has no dependencies and runs on Node.js, Workers and in the browser.
19
+
20
+ An experiment is a key (`{YYYYMMDD}-{category}-{slug}`), a rollout on a scale of 0 to 10000 and, optionally, a window, a bot and manual overrides. An entity is resolved in this order: disabled, outside the window (or of the wrong kind of entity), override, and then `MurmurHash3("{key}:{entityId}") % 10000` against the rollout, the same bucketing Discord uses.
21
+
22
+ ## Usage
23
+
24
+ ```typescript
25
+ import { ExperimentClient } from '@wolfstar/experiments';
26
+
27
+ const experiments = new ExperimentClient({
28
+ url: 'https://ring.example/experiments/snapshot',
29
+ token: process.env.INTERNAL_RING_TOKEN,
30
+ botId: 'wolfstar'
31
+ });
32
+ await experiments.start(); // reads the snapshot, then again every minute; never throws
33
+
34
+ if (experiments.isEligible('20261202-logging-server-updated-v2', 'guild', guildId)) {
35
+ // the new layout
36
+ }
37
+ ```
38
+
39
+ `isEligible` reads memory only. Until a snapshot has been read, and for a key the snapshot does not hold, it answers `false`, so a feature behind an experiment stays off exactly as it is when no experiment exists. A failed read keeps the last good snapshot and is reported to `onError`.
40
+
41
+ Without a client, resolve against any snapshot with `resolveFromSnapshot(snapshot, key, 'guild', id, { botId })`, or against one definition with `resolveDefinition`.
42
+
43
+ ## Scope of an experiment
44
+
45
+ An experiment with a `botId` only resolves for a consumer with that `botId`; one without applies to every consumer. A consumer ignores the keys it does not know.
46
+
47
+ ## Keeping the bucketing stable
48
+
49
+ `computePosition` is a contract between repositories: a change in it moves guilds in and out of every running experiment. The tests pin it to values computed with an independent implementation of MurmurHash3.
@@ -0,0 +1,122 @@
1
+ /**
2
+ * The bucket an entity lands in for an experiment. The numbers are stored by Ring and sent in its
3
+ * snapshot, so they never change.
4
+ */
5
+ export declare enum ExperimentBucket {
6
+ /** Assigned in by the hash, or by an override: the feature is active. */
7
+ Eligible = 0,
8
+ /** Assigned out by the hash, or the experiment is disabled or expired: the feature is inactive. */
9
+ NotEligible = 1,
10
+ /** Forced on by an administrator: the feature is active whatever the rollout says. */
11
+ Override = 2
12
+ }
13
+ /** Why an entity got its bucket, following the order of the resolution: disabled, expired, override, hash. */
14
+ export type ResolutionSource = 'disabled' | 'expired' | 'override' | 'hash';
15
+ /** What a definition or an override applies to. */
16
+ export type ExperimentEntityType = 'GUILD' | 'USER' | 'BOTH';
17
+ /** The kind of entity being resolved. */
18
+ export type ResolveEntityType = 'guild' | 'user';
19
+ export interface ResolveResult {
20
+ bucket: ExperimentBucket;
21
+ source: ResolutionSource;
22
+ }
23
+ /** A manual override of a guild or a user. It always wins over the hash. */
24
+ export interface ExperimentOverrideEntry {
25
+ entityType: 'GUILD' | 'USER';
26
+ entityId: string;
27
+ bucket: ExperimentBucket;
28
+ }
29
+ /** One experiment as Ring keeps it, with its overrides. Dates are ISO 8601 strings in UTC. */
30
+ export interface ExperimentDefinition {
31
+ /** The immutable key, `{YYYYMMDD}-{category}-{slug}`. */
32
+ id: string;
33
+ entityType: ExperimentEntityType;
34
+ enabled: boolean;
35
+ /** On a scale of 0 to 10000: 5000 is half of the entities, 10000 all of them. */
36
+ rollout: number;
37
+ startDate: string | null;
38
+ endDate: string | null;
39
+ /** The bot the experiment is limited to, `null` for every consumer. */
40
+ botId: string | null;
41
+ overrides: ExperimentOverrideEntry[];
42
+ }
43
+ /** What `GET /experiments/snapshot` answers. */
44
+ export interface ExperimentSnapshot {
45
+ version: 1;
46
+ generatedAt: string;
47
+ experiments: ExperimentDefinition[];
48
+ }
49
+ export interface ResolveOptions {
50
+ /** The consumer's scope. `null` or omitted resolves the experiments of no bot only. */
51
+ botId?: string | null;
52
+ /** The moment to resolve at. Defaults to now. */
53
+ now?: Date;
54
+ }
55
+ export interface ExperimentClientOptions {
56
+ /** Ring's snapshot route, such as `https://ring.example/experiments/snapshot`. */
57
+ url: string;
58
+ /** The token Ring maps to this consumer, sent as the `authorization` header. */
59
+ token: string;
60
+ /** The consumer's scope, sent to Ring and used to resolve. `null` or omitted: the experiments of no bot only. */
61
+ botId?: string | null;
62
+ /** How often the snapshot is read again, in milliseconds. Defaults to a minute. */
63
+ refreshInterval?: number;
64
+ /** How long a read waits on Ring, in milliseconds. Defaults to 2 seconds. */
65
+ timeout?: number;
66
+ /** Defaults to the global `fetch`. */
67
+ fetch?: typeof fetch;
68
+ /** Called with every failed read. The last good snapshot stays in use. */
69
+ onError?: (error: unknown) => void;
70
+ }
71
+ /**
72
+ * Keeps Ring's snapshot of the experiments in memory and resolves against it, so a check never waits on the network.
73
+ *
74
+ * While the snapshot is not loaded, because Ring was never reached, nothing is eligible: a feature behind an
75
+ * experiment stays off, as it is when no experiment exists. A failed read keeps the last good snapshot.
76
+ */
77
+ export declare class ExperimentClient {
78
+ #private;
79
+ constructor(options: ExperimentClientOptions);
80
+ /** Whether a snapshot was read at least once. */
81
+ get loaded(): boolean;
82
+ /** The snapshot in use, `null` until the first read succeeds. */
83
+ get snapshot(): ExperimentSnapshot | null;
84
+ /** Reads the snapshot once and then on every interval. A failed read is reported and never thrown. */
85
+ start(): Promise<void>;
86
+ stop(): void;
87
+ /** Reads the snapshot now. Resolves `true` when it changed. Reads that overlap share one request. */
88
+ refresh(): Promise<boolean>;
89
+ resolve(experimentKey: string, entityType: ResolveEntityType, entityId: string, now?: Date): ResolveResult;
90
+ /** Whether the feature behind an experiment is on for a guild or a user. */
91
+ isEligible(experimentKey: string, entityType: ResolveEntityType, entityId: string, now?: Date): boolean;
92
+ }
93
+ /** The scale of the rollout and of {@link computePosition}. */
94
+ export declare const RolloutScale = 10000;
95
+ /**
96
+ * MurmurHash3 (x86, 32-bit), the hash Discord and Split.io bucket with. It is written out here so every consumer
97
+ * assigns an entity to the same bucket without a dependency. It matches `murmurhash.v3(key)` of the `murmurhash` package
98
+ * for keys of characters up to U+00FF, which is all that experiment keys (slugs) and snowflakes hold.
99
+ */
100
+ export declare function murmurHash3(key: string, seed?: number): number;
101
+ /** The position of an entity in an experiment, in `[0, 9999]`: `MurmurHash3("{experiment}:{entity}") % 10000`. */
102
+ export declare function computePosition(experimentKey: string, entityId: string): number;
103
+ /**
104
+ * Reads what `GET /experiments/snapshot` answered. A body that is not a snapshot gives `null`, and an experiment
105
+ * that is broken is left out, so a bad row turns one feature off and never the whole snapshot.
106
+ */
107
+ export declare function parseSnapshot(value: unknown): ExperimentSnapshot | null;
108
+ /**
109
+ * Resolves the bucket of an entity in one experiment: disabled, then wrong kind of entity or outside the window,
110
+ * then a manual override, then the hash against the rollout.
111
+ *
112
+ * The scope of the experiment is not checked here, see {@link resolveFromSnapshot}.
113
+ */
114
+ export declare function resolveDefinition(definition: ExperimentDefinition, entityType: ResolveEntityType, entityId: string, now?: Date): ResolveResult;
115
+ /**
116
+ * Resolves an entity against a snapshot. An experiment the snapshot does not hold, or that is limited to another
117
+ * bot, is not eligible: the feature stays off.
118
+ */
119
+ export declare function resolveFromSnapshot(snapshot: ExperimentSnapshot | null, experimentKey: string, entityType: ResolveEntityType, entityId: string, options?: ResolveOptions): ResolveResult;
120
+ /** Whether a result turns the feature on. */
121
+ export declare function isEligibleBucket(bucket: ExperimentBucket): boolean;
122
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/lib/types.ts","../../src/lib/client.ts","../../src/lib/hash.ts","../../src/lib/parse.ts","../../src/lib/resolve.ts"],"mappings":";;;;oBAIY;;EAEX;;EAEA;;EAEA;;;YAIW;;YAGA;;YAGA;iBAEK;EAChB,QAAQ;EACR,QAAQ;;;iBAIQ;EAChB;EACA;EACA,QAAQ;;;iBAIQ;;EAEhB;EACA,YAAY;EACZ;;EAEA;EACA;EACA;;EAEA;EACA,WAAW;;;iBAIK;EAChB;EACA;EACA,aAAa;;iBAGG;;EAEhB;;EAEA,MAAM;;iBCxDU;;EAEhB;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,eAAe;;EAEf,WAAW;;;;;;;;qBAYC;;EAQZ,YAAmB,SAAS;;MAajB;;MAKA,YAAY;;EAKV,SAAS;EAYf;;EAMA,WAAW;EAOX,QAAQ,uBAAuB,YAAY,mBAAmB,kBAAkB,MAAM,OAAO;;EAK7F,WAAW,uBAAuB,YAAY,mBAAmB,kBAAkB,MAAM;;;qBCnFpF;;;;;;wBAOG,YAAY,aAAa;;wBA+CzB,gBAAgB,uBAAuB;;;;;wBCRvC,cAAc,iBAAiB;;;;;;;wBC1C/B,kBACf,YAAY,sBACZ,YAAY,mBACZ,kBACA,MAAK,OACH;;;;;wBAsBa,oBACf,UAAU,2BACV,uBACA,YAAY,mBACZ,kBACA,UAAS,iBACP;;wBAQa,iBAAiB,QAAQ"}
@@ -0,0 +1,308 @@
1
+ // src/lib/types.ts
2
+ /**
3
+ * The bucket an entity lands in for an experiment. The numbers are stored by Ring and sent in its
4
+ * snapshot, so they never change.
5
+ */
6
+ let ExperimentBucket = /* @__PURE__ */ function(ExperimentBucket) {
7
+ /** Assigned in by the hash, or by an override: the feature is active. */
8
+ ExperimentBucket[ExperimentBucket["Eligible"] = 0] = "Eligible";
9
+ /** Assigned out by the hash, or the experiment is disabled or expired: the feature is inactive. */
10
+ ExperimentBucket[ExperimentBucket["NotEligible"] = 1] = "NotEligible";
11
+ /** Forced on by an administrator: the feature is active whatever the rollout says. */
12
+ ExperimentBucket[ExperimentBucket["Override"] = 2] = "Override";
13
+ return ExperimentBucket;
14
+ }({});
15
+
16
+ // src/lib/parse.ts
17
+ const EntityTypes = [
18
+ "GUILD",
19
+ "USER",
20
+ "BOTH"
21
+ ];
22
+ function isRecord(value) {
23
+ return typeof value === "object" && value !== null && !Array.isArray(value);
24
+ }
25
+ function parseDate(value) {
26
+ if (value === null) return null;
27
+ return typeof value === "string" && !Number.isNaN(Date.parse(value)) ? value : void 0;
28
+ }
29
+ function parseOverride(value) {
30
+ if (!isRecord(value)) return null;
31
+ const { entityType, entityId, bucket } = value;
32
+ if (entityType !== "GUILD" && entityType !== "USER") return null;
33
+ if (typeof entityId !== "string" || entityId === "") return null;
34
+ if (bucket !== 0 && bucket !== 1 && bucket !== 2) return null;
35
+ return {
36
+ entityType,
37
+ entityId,
38
+ bucket
39
+ };
40
+ }
41
+ function parseDefinition(value) {
42
+ if (!isRecord(value)) return null;
43
+ const { id, entityType, enabled, rollout, botId, overrides } = value;
44
+ const startDate = parseDate(value.startDate);
45
+ const endDate = parseDate(value.endDate);
46
+ if (typeof id !== "string" || id === "") return null;
47
+ if (typeof entityType !== "string" || !EntityTypes.includes(entityType)) return null;
48
+ if (typeof enabled !== "boolean") return null;
49
+ if (typeof rollout !== "number" || !Number.isInteger(rollout) || rollout < 0 || rollout > 1e4) return null;
50
+ if (startDate === void 0 || endDate === void 0) return null;
51
+ if (botId !== null && typeof botId !== "string") return null;
52
+ if (!Array.isArray(overrides)) return null;
53
+ return {
54
+ id,
55
+ entityType,
56
+ enabled,
57
+ rollout,
58
+ startDate,
59
+ endDate,
60
+ botId,
61
+ overrides: overrides.map(parseOverride).filter((entry) => entry !== null)
62
+ };
63
+ }
64
+ /**
65
+ * Reads what `GET /experiments/snapshot` answered. A body that is not a snapshot gives `null`, and an experiment
66
+ * that is broken is left out, so a bad row turns one feature off and never the whole snapshot.
67
+ */
68
+ function parseSnapshot(value) {
69
+ if (!isRecord(value) || value.version !== 1 || typeof value.generatedAt !== "string" || !Array.isArray(value.experiments)) return null;
70
+ return {
71
+ version: 1,
72
+ generatedAt: value.generatedAt,
73
+ experiments: value.experiments.map(parseDefinition).filter((definition) => definition !== null)
74
+ };
75
+ }
76
+
77
+ // src/lib/hash.ts
78
+ const C1 = 0xcc9e2d51;
79
+ const C2 = 461845907;
80
+ const Mix = 0xe6546b64;
81
+ const FMix1 = 0x85ebca6b;
82
+ const FMix2 = 0xc2b2ae35;
83
+ const ByteMask = 255;
84
+ /** The scale of the rollout and of {@link computePosition}. */
85
+ const RolloutScale = 1e4;
86
+ /**
87
+ * MurmurHash3 (x86, 32-bit), the hash Discord and Split.io bucket with. It is written out here so every consumer
88
+ * assigns an entity to the same bucket without a dependency. It matches `murmurhash.v3(key)` of the `murmurhash` package
89
+ * for keys of characters up to U+00FF, which is all that experiment keys (slugs) and snowflakes hold.
90
+ */
91
+ function murmurHash3(key, seed = 0) {
92
+ const remainder = key.length & 3;
93
+ const bytes = key.length - remainder;
94
+ let h1 = seed;
95
+ let i = 0;
96
+ while (i < bytes) {
97
+ let k1 = key.charCodeAt(i) & ByteMask | (key.charCodeAt(++i) & ByteMask) << 8 | (key.charCodeAt(++i) & ByteMask) << 16 | (key.charCodeAt(++i) & ByteMask) << 24;
98
+ ++i;
99
+ k1 = Math.imul(k1, C1);
100
+ k1 = k1 << 15 | k1 >>> 17;
101
+ k1 = Math.imul(k1, C2);
102
+ h1 ^= k1;
103
+ h1 = h1 << 13 | h1 >>> 19;
104
+ h1 = Math.imul(h1, 5) + Mix | 0;
105
+ }
106
+ if (remainder > 0) {
107
+ let k1 = 0;
108
+ if (remainder === 3) k1 ^= (key.charCodeAt(i + 2) & ByteMask) << 16;
109
+ if (remainder >= 2) k1 ^= (key.charCodeAt(i + 1) & ByteMask) << 8;
110
+ k1 ^= key.charCodeAt(i) & ByteMask;
111
+ k1 = Math.imul(k1, C1);
112
+ k1 = k1 << 15 | k1 >>> 17;
113
+ k1 = Math.imul(k1, C2);
114
+ h1 ^= k1;
115
+ }
116
+ h1 ^= key.length;
117
+ h1 ^= h1 >>> 16;
118
+ h1 = Math.imul(h1, FMix1);
119
+ h1 ^= h1 >>> 13;
120
+ h1 = Math.imul(h1, FMix2);
121
+ h1 ^= h1 >>> 16;
122
+ return h1 >>> 0;
123
+ }
124
+ /** The position of an entity in an experiment, in `[0, 9999]`: `MurmurHash3("{experiment}:{entity}") % 10000`. */
125
+ function computePosition(experimentKey, entityId) {
126
+ return murmurHash3(`${experimentKey}:${entityId}`) % RolloutScale;
127
+ }
128
+
129
+ // src/lib/resolve.ts
130
+ const NotEligible = (source) => ({
131
+ bucket: 1,
132
+ source
133
+ });
134
+ /**
135
+ * Resolves the bucket of an entity in one experiment: disabled, then wrong kind of entity or outside the window,
136
+ * then a manual override, then the hash against the rollout.
137
+ *
138
+ * The scope of the experiment is not checked here, see {@link resolveFromSnapshot}.
139
+ */
140
+ function resolveDefinition(definition, entityType, entityId, now = /* @__PURE__ */ new Date()) {
141
+ if (!definition.enabled) return NotEligible("disabled");
142
+ const kind = entityType === "guild" ? "GUILD" : "USER";
143
+ if (definition.entityType !== "BOTH" && definition.entityType !== kind) return NotEligible("disabled");
144
+ if (definition.startDate !== null && new Date(definition.startDate) > now) return NotEligible("disabled");
145
+ if (definition.endDate !== null && new Date(definition.endDate) < now) return NotEligible("expired");
146
+ const override = definition.overrides.find((entry) => entry.entityType === kind && entry.entityId === entityId);
147
+ if (override) return {
148
+ bucket: toBucket(override.bucket),
149
+ source: "override"
150
+ };
151
+ return {
152
+ bucket: computePosition(definition.id, entityId) < definition.rollout ? 0 : 1,
153
+ source: "hash"
154
+ };
155
+ }
156
+ /**
157
+ * Resolves an entity against a snapshot. An experiment the snapshot does not hold, or that is limited to another
158
+ * bot, is not eligible: the feature stays off.
159
+ */
160
+ function resolveFromSnapshot(snapshot, experimentKey, entityType, entityId, options = {}) {
161
+ const botId = options.botId ?? null;
162
+ const definition = snapshot?.experiments.find((experiment) => experiment.id === experimentKey);
163
+ if (!definition || definition.botId !== null && definition.botId !== botId) return NotEligible("disabled");
164
+ return resolveDefinition(definition, entityType, entityId, options.now);
165
+ }
166
+ /** Whether a result turns the feature on. */
167
+ function isEligibleBucket(bucket) {
168
+ return bucket === 0 || bucket === 2;
169
+ }
170
+ /** A stored number that is no known bucket is not eligible, so a corrupt row can never turn a feature on. */
171
+ function toBucket(value) {
172
+ return value === 0 || value === 2 ? value : 1;
173
+ }
174
+
175
+ // \0@oxc-project+runtime@0.160.0/helpers/esm/checkPrivateRedeclaration.js
176
+ function _checkPrivateRedeclaration(e, t) {
177
+ if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
178
+ }
179
+
180
+ // \0@oxc-project+runtime@0.160.0/helpers/esm/classPrivateMethodInitSpec.js
181
+ function _classPrivateMethodInitSpec(e, a) {
182
+ _checkPrivateRedeclaration(e, a), a.add(e);
183
+ }
184
+
185
+ // \0@oxc-project+runtime@0.160.0/helpers/esm/classPrivateFieldInitSpec.js
186
+ function _classPrivateFieldInitSpec(e, t, a) {
187
+ _checkPrivateRedeclaration(e, t), t.set(e, a);
188
+ }
189
+
190
+ // \0@oxc-project+runtime@0.160.0/helpers/esm/assertClassBrand.js
191
+ function _assertClassBrand(e, t, n) {
192
+ if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
193
+ throw new TypeError("Private element is not present on this object");
194
+ }
195
+
196
+ // \0@oxc-project+runtime@0.160.0/helpers/esm/classPrivateFieldSet2.js
197
+ function _classPrivateFieldSet2(s, a, r) {
198
+ return s.set(_assertClassBrand(s, a), r), r;
199
+ }
200
+
201
+ // \0@oxc-project+runtime@0.160.0/helpers/esm/classPrivateFieldGet2.js
202
+ function _classPrivateFieldGet2(s, a) {
203
+ return s.get(_assertClassBrand(s, a));
204
+ }
205
+
206
+ // src/lib/client.ts
207
+ const DefaultRefreshInterval = 6e4;
208
+ const DefaultTimeout = 2e3;
209
+ var _options = /* @__PURE__ */ new WeakMap();
210
+ var _botId = /* @__PURE__ */ new WeakMap();
211
+ var _snapshot = /* @__PURE__ */ new WeakMap();
212
+ var _etag = /* @__PURE__ */ new WeakMap();
213
+ var _timer = /* @__PURE__ */ new WeakMap();
214
+ var _pending = /* @__PURE__ */ new WeakMap();
215
+ var _ExperimentClient_brand = /* @__PURE__ */ new WeakSet();
216
+ /**
217
+ * Keeps Ring's snapshot of the experiments in memory and resolves against it, so a check never waits on the network.
218
+ *
219
+ * While the snapshot is not loaded, because Ring was never reached, nothing is eligible: a feature behind an
220
+ * experiment stays off, as it is when no experiment exists. A failed read keeps the last good snapshot.
221
+ */
222
+ var ExperimentClient = class {
223
+ constructor(options) {
224
+ _classPrivateMethodInitSpec(this, _ExperimentClient_brand);
225
+ _classPrivateFieldInitSpec(this, _options, void 0);
226
+ _classPrivateFieldInitSpec(this, _botId, void 0);
227
+ _classPrivateFieldInitSpec(this, _snapshot, null);
228
+ _classPrivateFieldInitSpec(this, _etag, null);
229
+ _classPrivateFieldInitSpec(this, _timer, null);
230
+ _classPrivateFieldInitSpec(this, _pending, null);
231
+ _classPrivateFieldSet2(_botId, this, options.botId ?? null);
232
+ _classPrivateFieldSet2(_options, this, {
233
+ url: options.url,
234
+ token: options.token,
235
+ refreshInterval: options.refreshInterval ?? DefaultRefreshInterval,
236
+ timeout: options.timeout ?? DefaultTimeout,
237
+ fetch: options.fetch ?? ((input, init) => fetch(input, init)),
238
+ onError: options.onError
239
+ });
240
+ }
241
+ /** Whether a snapshot was read at least once. */
242
+ get loaded() {
243
+ return _classPrivateFieldGet2(_snapshot, this) !== null;
244
+ }
245
+ /** The snapshot in use, `null` until the first read succeeds. */
246
+ get snapshot() {
247
+ return _classPrivateFieldGet2(_snapshot, this);
248
+ }
249
+ /** Reads the snapshot once and then on every interval. A failed read is reported and never thrown. */
250
+ async start() {
251
+ if (_classPrivateFieldGet2(_timer, this) !== null) {
252
+ await _classPrivateFieldGet2(_pending, this);
253
+ return;
254
+ }
255
+ _classPrivateFieldSet2(_timer, this, setInterval(() => void this.refresh(), _classPrivateFieldGet2(_options, this).refreshInterval));
256
+ _classPrivateFieldGet2(_timer, this).unref?.();
257
+ await this.refresh();
258
+ }
259
+ stop() {
260
+ if (_classPrivateFieldGet2(_timer, this) !== null) clearInterval(_classPrivateFieldGet2(_timer, this));
261
+ _classPrivateFieldSet2(_timer, this, null);
262
+ }
263
+ /** Reads the snapshot now. Resolves `true` when it changed. Reads that overlap share one request. */
264
+ refresh() {
265
+ _classPrivateFieldGet2(_pending, this) ?? _classPrivateFieldSet2(_pending, this, _assertClassBrand(_ExperimentClient_brand, this, _read).call(this).finally(() => {
266
+ _classPrivateFieldSet2(_pending, this, null);
267
+ }));
268
+ return _classPrivateFieldGet2(_pending, this);
269
+ }
270
+ resolve(experimentKey, entityType, entityId, now) {
271
+ return resolveFromSnapshot(_classPrivateFieldGet2(_snapshot, this), experimentKey, entityType, entityId, {
272
+ botId: _classPrivateFieldGet2(_botId, this),
273
+ now
274
+ });
275
+ }
276
+ /** Whether the feature behind an experiment is on for a guild or a user. */
277
+ isEligible(experimentKey, entityType, entityId, now) {
278
+ return isEligibleBucket(this.resolve(experimentKey, entityType, entityId, now).bucket);
279
+ }
280
+ };
281
+ async function _read() {
282
+ try {
283
+ const url = new URL(_classPrivateFieldGet2(_options, this).url);
284
+ if (_classPrivateFieldGet2(_botId, this) !== null) url.searchParams.set("botId", _classPrivateFieldGet2(_botId, this));
285
+ const headers = {
286
+ authorization: _classPrivateFieldGet2(_options, this).token,
287
+ accept: "application/json"
288
+ };
289
+ if (_classPrivateFieldGet2(_etag, this) !== null && _classPrivateFieldGet2(_snapshot, this) !== null) headers["if-none-match"] = _classPrivateFieldGet2(_etag, this);
290
+ const response = await _classPrivateFieldGet2(_options, this).fetch(url, {
291
+ headers,
292
+ signal: AbortSignal.timeout(_classPrivateFieldGet2(_options, this).timeout)
293
+ });
294
+ if (response.status === 304) return false;
295
+ if (!response.ok) throw new Error(`Ring answered ${response.status} to the experiments snapshot`);
296
+ const snapshot = parseSnapshot(await response.json());
297
+ if (snapshot === null) throw new Error("Ring sent an experiments snapshot that cannot be read");
298
+ _classPrivateFieldSet2(_snapshot, this, snapshot);
299
+ _classPrivateFieldSet2(_etag, this, response.headers.get("etag"));
300
+ return true;
301
+ } catch (error) {
302
+ _classPrivateFieldGet2(_options, this).onError?.(error);
303
+ return false;
304
+ }
305
+ }
306
+
307
+ export { ExperimentBucket, ExperimentClient, RolloutScale, computePosition, isEligibleBucket, murmurHash3, parseSnapshot, resolveDefinition, resolveFromSnapshot };
308
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/lib/types.ts","../../src/lib/parse.ts","../../src/lib/hash.ts","../../src/lib/resolve.ts","../../src/lib/client.ts"],"sourcesContent":["/**\n * The bucket an entity lands in for an experiment. The numbers are stored by Ring and sent in its\n * snapshot, so they never change.\n */\nexport enum ExperimentBucket {\n\t/** Assigned in by the hash, or by an override: the feature is active. */\n\tEligible = 0,\n\t/** Assigned out by the hash, or the experiment is disabled or expired: the feature is inactive. */\n\tNotEligible = 1,\n\t/** Forced on by an administrator: the feature is active whatever the rollout says. */\n\tOverride = 2\n}\n\n/** Why an entity got its bucket, following the order of the resolution: disabled, expired, override, hash. */\nexport type ResolutionSource = 'disabled' | 'expired' | 'override' | 'hash';\n\n/** What a definition or an override applies to. */\nexport type ExperimentEntityType = 'GUILD' | 'USER' | 'BOTH';\n\n/** The kind of entity being resolved. */\nexport type ResolveEntityType = 'guild' | 'user';\n\nexport interface ResolveResult {\n\tbucket: ExperimentBucket;\n\tsource: ResolutionSource;\n}\n\n/** A manual override of a guild or a user. It always wins over the hash. */\nexport interface ExperimentOverrideEntry {\n\tentityType: 'GUILD' | 'USER';\n\tentityId: string;\n\tbucket: ExperimentBucket;\n}\n\n/** One experiment as Ring keeps it, with its overrides. Dates are ISO 8601 strings in UTC. */\nexport interface ExperimentDefinition {\n\t/** The immutable key, `{YYYYMMDD}-{category}-{slug}`. */\n\tid: string;\n\tentityType: ExperimentEntityType;\n\tenabled: boolean;\n\t/** On a scale of 0 to 10000: 5000 is half of the entities, 10000 all of them. */\n\trollout: number;\n\tstartDate: string | null;\n\tendDate: string | null;\n\t/** The bot the experiment is limited to, `null` for every consumer. */\n\tbotId: string | null;\n\toverrides: ExperimentOverrideEntry[];\n}\n\n/** What `GET /experiments/snapshot` answers. */\nexport interface ExperimentSnapshot {\n\tversion: 1;\n\tgeneratedAt: string;\n\texperiments: ExperimentDefinition[];\n}\n\nexport interface ResolveOptions {\n\t/** The consumer's scope. `null` or omitted resolves the experiments of no bot only. */\n\tbotId?: string | null;\n\t/** The moment to resolve at. Defaults to now. */\n\tnow?: Date;\n}\n","import { ExperimentBucket } from './types.js';\nimport type { ExperimentDefinition, ExperimentEntityType, ExperimentOverrideEntry, ExperimentSnapshot } from './types.js';\n\nconst EntityTypes: readonly string[] = ['GUILD', 'USER', 'BOTH'] satisfies ExperimentEntityType[];\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction parseDate(value: unknown): string | null | undefined {\n\tif (value === null) return null;\n\treturn typeof value === 'string' && !Number.isNaN(Date.parse(value)) ? value : undefined;\n}\n\nfunction parseOverride(value: unknown): ExperimentOverrideEntry | null {\n\tif (!isRecord(value)) return null;\n\tconst { entityType, entityId, bucket } = value;\n\tif (entityType !== 'GUILD' && entityType !== 'USER') return null;\n\tif (typeof entityId !== 'string' || entityId === '') return null;\n\tif (bucket !== ExperimentBucket.Eligible && bucket !== ExperimentBucket.NotEligible && bucket !== ExperimentBucket.Override) return null;\n\treturn { entityType, entityId, bucket };\n}\n\nfunction parseDefinition(value: unknown): ExperimentDefinition | null {\n\tif (!isRecord(value)) return null;\n\tconst { id, entityType, enabled, rollout, botId, overrides } = value;\n\tconst startDate = parseDate(value.startDate);\n\tconst endDate = parseDate(value.endDate);\n\n\tif (typeof id !== 'string' || id === '') return null;\n\tif (typeof entityType !== 'string' || !EntityTypes.includes(entityType)) return null;\n\tif (typeof enabled !== 'boolean') return null;\n\tif (typeof rollout !== 'number' || !Number.isInteger(rollout) || rollout < 0 || rollout > 10_000) return null;\n\tif (startDate === undefined || endDate === undefined) return null;\n\tif (botId !== null && typeof botId !== 'string') return null;\n\tif (!Array.isArray(overrides)) return null;\n\n\treturn {\n\t\tid,\n\t\tentityType: entityType as ExperimentEntityType,\n\t\tenabled,\n\t\trollout,\n\t\tstartDate,\n\t\tendDate,\n\t\tbotId,\n\t\t// A broken override is dropped, not trusted: the entity falls back to the hash.\n\t\toverrides: overrides.map(parseOverride).filter((entry): entry is ExperimentOverrideEntry => entry !== null)\n\t};\n}\n\n/**\n * Reads what `GET /experiments/snapshot` answered. A body that is not a snapshot gives `null`, and an experiment\n * that is broken is left out, so a bad row turns one feature off and never the whole snapshot.\n */\nexport function parseSnapshot(value: unknown): ExperimentSnapshot | null {\n\tif (!isRecord(value) || value.version !== 1 || typeof value.generatedAt !== 'string' || !Array.isArray(value.experiments)) return null;\n\treturn {\n\t\tversion: 1,\n\t\tgeneratedAt: value.generatedAt,\n\t\texperiments: value.experiments.map(parseDefinition).filter((definition): definition is ExperimentDefinition => definition !== null)\n\t};\n}\n","const C1 = 3432918353; // 0xcc9e2d51\nconst C2 = 461845907; // 0x1b873593\nconst Mix = 3864292196; // 0xe6546b64\nconst FMix1 = 2246822507; // 0x85ebca6b\nconst FMix2 = 3266489909; // 0xc2b2ae35\nconst ByteMask = 255;\n\n/** The scale of the rollout and of {@link computePosition}. */\nexport const RolloutScale = 10_000;\n\n/**\n * MurmurHash3 (x86, 32-bit), the hash Discord and Split.io bucket with. It is written out here so every consumer\n * assigns an entity to the same bucket without a dependency. It matches `murmurhash.v3(key)` of the `murmurhash` package\n * for keys of characters up to U+00FF, which is all that experiment keys (slugs) and snowflakes hold.\n */\nexport function murmurHash3(key: string, seed = 0): number {\n\tconst remainder = key.length & 3;\n\tconst bytes = key.length - remainder;\n\n\tlet h1 = seed;\n\tlet i = 0;\n\n\twhile (i < bytes) {\n\t\tlet k1 =\n\t\t\t(key.charCodeAt(i) & ByteMask) |\n\t\t\t((key.charCodeAt(++i) & ByteMask) << 8) |\n\t\t\t((key.charCodeAt(++i) & ByteMask) << 16) |\n\t\t\t((key.charCodeAt(++i) & ByteMask) << 24);\n\t\t++i;\n\n\t\tk1 = Math.imul(k1, C1);\n\t\tk1 = (k1 << 15) | (k1 >>> 17);\n\t\tk1 = Math.imul(k1, C2);\n\n\t\th1 ^= k1;\n\t\th1 = (h1 << 13) | (h1 >>> 19);\n\t\th1 = (Math.imul(h1, 5) + Mix) | 0;\n\t}\n\n\t// The last one to three characters, folded in little-endian like the full blocks.\n\tif (remainder > 0) {\n\t\tlet k1 = 0;\n\t\tif (remainder === 3) k1 ^= (key.charCodeAt(i + 2) & ByteMask) << 16;\n\t\tif (remainder >= 2) k1 ^= (key.charCodeAt(i + 1) & ByteMask) << 8;\n\t\tk1 ^= key.charCodeAt(i) & ByteMask;\n\t\tk1 = Math.imul(k1, C1);\n\t\tk1 = (k1 << 15) | (k1 >>> 17);\n\t\tk1 = Math.imul(k1, C2);\n\t\th1 ^= k1;\n\t}\n\n\th1 ^= key.length;\n\th1 ^= h1 >>> 16;\n\th1 = Math.imul(h1, FMix1);\n\th1 ^= h1 >>> 13;\n\th1 = Math.imul(h1, FMix2);\n\th1 ^= h1 >>> 16;\n\n\treturn h1 >>> 0;\n}\n\n/** The position of an entity in an experiment, in `[0, 9999]`: `MurmurHash3(\"{experiment}:{entity}\") % 10000`. */\nexport function computePosition(experimentKey: string, entityId: string): number {\n\treturn murmurHash3(`${experimentKey}:${entityId}`) % RolloutScale;\n}\n","import { computePosition } from './hash.js';\nimport { ExperimentBucket } from './types.js';\nimport type { ExperimentDefinition, ExperimentSnapshot, ResolveEntityType, ResolveOptions, ResolveResult } from './types.js';\n\nconst NotEligible = (source: ResolveResult['source']): ResolveResult => ({ bucket: ExperimentBucket.NotEligible, source });\n\n/**\n * Resolves the bucket of an entity in one experiment: disabled, then wrong kind of entity or outside the window,\n * then a manual override, then the hash against the rollout.\n *\n * The scope of the experiment is not checked here, see {@link resolveFromSnapshot}.\n */\nexport function resolveDefinition(\n\tdefinition: ExperimentDefinition,\n\tentityType: ResolveEntityType,\n\tentityId: string,\n\tnow: Date = new Date()\n): ResolveResult {\n\tif (!definition.enabled) return NotEligible('disabled');\n\n\t// A guild experiment never resolves for a user and the other way round: without this the hash would assign\n\t// an entity of the wrong kind.\n\tconst kind = entityType === 'guild' ? 'GUILD' : 'USER';\n\tif (definition.entityType !== 'BOTH' && definition.entityType !== kind) return NotEligible('disabled');\n\n\tif (definition.startDate !== null && new Date(definition.startDate) > now) return NotEligible('disabled');\n\tif (definition.endDate !== null && new Date(definition.endDate) < now) return NotEligible('expired');\n\n\tconst override = definition.overrides.find((entry) => entry.entityType === kind && entry.entityId === entityId);\n\tif (override) return { bucket: toBucket(override.bucket), source: 'override' };\n\n\tconst position = computePosition(definition.id, entityId);\n\treturn { bucket: position < definition.rollout ? ExperimentBucket.Eligible : ExperimentBucket.NotEligible, source: 'hash' };\n}\n\n/**\n * Resolves an entity against a snapshot. An experiment the snapshot does not hold, or that is limited to another\n * bot, is not eligible: the feature stays off.\n */\nexport function resolveFromSnapshot(\n\tsnapshot: ExperimentSnapshot | null,\n\texperimentKey: string,\n\tentityType: ResolveEntityType,\n\tentityId: string,\n\toptions: ResolveOptions = {}\n): ResolveResult {\n\tconst botId = options.botId ?? null;\n\tconst definition = snapshot?.experiments.find((experiment) => experiment.id === experimentKey);\n\tif (!definition || (definition.botId !== null && definition.botId !== botId)) return NotEligible('disabled');\n\treturn resolveDefinition(definition, entityType, entityId, options.now);\n}\n\n/** Whether a result turns the feature on. */\nexport function isEligibleBucket(bucket: ExperimentBucket): boolean {\n\treturn bucket === ExperimentBucket.Eligible || bucket === ExperimentBucket.Override;\n}\n\n/** A stored number that is no known bucket is not eligible, so a corrupt row can never turn a feature on. */\nfunction toBucket(value: number): ExperimentBucket {\n\treturn value === ExperimentBucket.Eligible || value === ExperimentBucket.Override ? value : ExperimentBucket.NotEligible;\n}\n","import { parseSnapshot } from './parse.js';\nimport { isEligibleBucket, resolveFromSnapshot } from './resolve.js';\nimport type { ExperimentSnapshot, ResolveEntityType, ResolveResult } from './types.js';\n\nexport interface ExperimentClientOptions {\n\t/** Ring's snapshot route, such as `https://ring.example/experiments/snapshot`. */\n\turl: string;\n\t/** The token Ring maps to this consumer, sent as the `authorization` header. */\n\ttoken: string;\n\t/** The consumer's scope, sent to Ring and used to resolve. `null` or omitted: the experiments of no bot only. */\n\tbotId?: string | null;\n\t/** How often the snapshot is read again, in milliseconds. Defaults to a minute. */\n\trefreshInterval?: number;\n\t/** How long a read waits on Ring, in milliseconds. Defaults to 2 seconds. */\n\ttimeout?: number;\n\t/** Defaults to the global `fetch`. */\n\tfetch?: typeof fetch;\n\t/** Called with every failed read. The last good snapshot stays in use. */\n\tonError?: (error: unknown) => void;\n}\n\nconst DefaultRefreshInterval = 60_000;\nconst DefaultTimeout = 2000;\n\n/**\n * Keeps Ring's snapshot of the experiments in memory and resolves against it, so a check never waits on the network.\n *\n * While the snapshot is not loaded, because Ring was never reached, nothing is eligible: a feature behind an\n * experiment stays off, as it is when no experiment exists. A failed read keeps the last good snapshot.\n */\nexport class ExperimentClient {\n\treadonly #options: Required<Omit<ExperimentClientOptions, 'onError' | 'botId'>> & Pick<ExperimentClientOptions, 'onError'>;\n\treadonly #botId: string | null;\n\t#snapshot: ExperimentSnapshot | null = null;\n\t#etag: string | null = null;\n\t#timer: ReturnType<typeof setInterval> | null = null;\n\t#pending: Promise<boolean> | null = null;\n\n\tpublic constructor(options: ExperimentClientOptions) {\n\t\tthis.#botId = options.botId ?? null;\n\t\tthis.#options = {\n\t\t\turl: options.url,\n\t\t\ttoken: options.token,\n\t\t\trefreshInterval: options.refreshInterval ?? DefaultRefreshInterval,\n\t\t\ttimeout: options.timeout ?? DefaultTimeout,\n\t\t\tfetch: options.fetch ?? ((input, init) => fetch(input, init)),\n\t\t\tonError: options.onError\n\t\t};\n\t}\n\n\t/** Whether a snapshot was read at least once. */\n\tpublic get loaded(): boolean {\n\t\treturn this.#snapshot !== null;\n\t}\n\n\t/** The snapshot in use, `null` until the first read succeeds. */\n\tpublic get snapshot(): ExperimentSnapshot | null {\n\t\treturn this.#snapshot;\n\t}\n\n\t/** Reads the snapshot once and then on every interval. A failed read is reported and never thrown. */\n\tpublic async start(): Promise<void> {\n\t\t// A second start waits for the read of the first one, so both return once a snapshot is in.\n\t\tif (this.#timer !== null) {\n\t\t\tawait this.#pending;\n\t\t\treturn;\n\t\t}\n\t\tthis.#timer = setInterval(() => void this.refresh(), this.#options.refreshInterval);\n\t\t// A timer of ours must never be what keeps a process alive.\n\t\t(this.#timer as { unref?: () => void }).unref?.();\n\t\tawait this.refresh();\n\t}\n\n\tpublic stop(): void {\n\t\tif (this.#timer !== null) clearInterval(this.#timer);\n\t\tthis.#timer = null;\n\t}\n\n\t/** Reads the snapshot now. Resolves `true` when it changed. Reads that overlap share one request. */\n\tpublic refresh(): Promise<boolean> {\n\t\tthis.#pending ??= this.#read().finally(() => {\n\t\t\tthis.#pending = null;\n\t\t});\n\t\treturn this.#pending;\n\t}\n\n\tpublic resolve(experimentKey: string, entityType: ResolveEntityType, entityId: string, now?: Date): ResolveResult {\n\t\treturn resolveFromSnapshot(this.#snapshot, experimentKey, entityType, entityId, { botId: this.#botId, now });\n\t}\n\n\t/** Whether the feature behind an experiment is on for a guild or a user. */\n\tpublic isEligible(experimentKey: string, entityType: ResolveEntityType, entityId: string, now?: Date): boolean {\n\t\treturn isEligibleBucket(this.resolve(experimentKey, entityType, entityId, now).bucket);\n\t}\n\n\tasync #read(): Promise<boolean> {\n\t\ttry {\n\t\t\tconst url = new URL(this.#options.url);\n\t\t\tif (this.#botId !== null) url.searchParams.set('botId', this.#botId);\n\n\t\t\tconst headers: Record<string, string> = { authorization: this.#options.token, accept: 'application/json' };\n\t\t\tif (this.#etag !== null && this.#snapshot !== null) headers['if-none-match'] = this.#etag;\n\n\t\t\tconst response = await this.#options.fetch(url, { headers, signal: AbortSignal.timeout(this.#options.timeout) });\n\t\t\tif (response.status === 304) return false;\n\t\t\tif (!response.ok) throw new Error(`Ring answered ${response.status} to the experiments snapshot`);\n\n\t\t\tconst snapshot = parseSnapshot(await response.json());\n\t\t\tif (snapshot === null) throw new Error('Ring sent an experiments snapshot that cannot be read');\n\n\t\t\tthis.#snapshot = snapshot;\n\t\t\tthis.#etag = response.headers.get('etag');\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tthis.#options.onError?.(error);\n\t\t\treturn false;\n\t\t}\n\t}\n}\n"],"mappings":";;;;;AAIA,IAAY,mBAAL;;CAEN;;CAEA;;CAEA;;AACD;;;ACRA,MAAM,cAAiC;CAAC;CAAS;CAAQ;AAAM;AAE/D,SAAS,SAAS,OAAkD;CACnE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC3E;AAEA,SAAS,UAAU,OAA2C;CAC7D,IAAI,UAAU,MAAM,OAAO;CAC3B,OAAO,OAAO,UAAU,YAAY,CAAC,OAAO,MAAM,KAAK,MAAM,KAAK,CAAC,IAAI,QAAQ;AAChF;AAEA,SAAS,cAAc,OAAgD;CACtE,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO;CAC7B,MAAM,EAAE,YAAY,UAAU,W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;GAAE;GAAS,QAAQ,YAAY,yCAAQ,MAAc,OAAO;EAAE,CAAC;EAC/G,IAAI,SAAS,WAAW,KAAK,OAAO;EACpC,IAAI,CAAC,SAAS,IAAI,MAAM,IAAI,MAAM,iBAAiB,SAAS,OAAO,6BAA6B;EAEhG,MAAM,WAAW,cAAc,MAAM,SAAS,KAAK,CAAC;EACpD,IAAI,aAAa,MAAM,MAAM,IAAI,MAAM,uDAAuD;EAE9F,wCAAiB;EACjB,oCAAa,SAAS,QAAQ,IAAI,MAAM;EACxC,OAAO;CACR,SAAS,OAAO;EACf,uCAAc,UAAU,KAAK;EAC7B,OAAO;CACR;AACD"}
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@wolfstar/experiments",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Feature-flag experiments for the WolfStar network: deterministic bucketing, a pure resolver and a polling client for Ring's snapshot",
5
+ "keywords": [
6
+ "experiments",
7
+ "feature-flags",
8
+ "murmurhash",
9
+ "rollout",
10
+ "wolfstar"
11
+ ],
12
+ "homepage": "https://github.com/wolfstar-project/stars-components/tree/main/packages/experiments",
13
+ "bugs": {
14
+ "url": "https://github.com/wolfstar-project/stars-components/issues"
15
+ },
16
+ "license": "Apache-2.0",
17
+ "author": "@wolfstar",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/wolfstar-project/stars-components.git",
21
+ "directory": "packages/experiments"
22
+ },
23
+ "files": [
24
+ "dist/"
25
+ ],
26
+ "type": "module",
27
+ "sideEffects": false,
28
+ "main": "dist/esm/index.js",
29
+ "module": "dist/esm/index.js",
30
+ "types": "dist/esm/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "import": {
34
+ "types": "./dist/esm/index.d.ts",
35
+ "default": "./dist/esm/index.js"
36
+ }
37
+ },
38
+ "./package.json": "./package.json"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public",
42
+ "provenance": true
43
+ },
44
+ "devDependencies": {
45
+ "@vitest/coverage-v8": "^5.1.2",
46
+ "golar": "^0.1.11",
47
+ "tsdown": "^0.23.7",
48
+ "typescript": "~7.0.2",
49
+ "vitest": "^5.1.2"
50
+ },
51
+ "engines": {
52
+ "node": ">=20"
53
+ },
54
+ "scripts": {
55
+ "test": "vitest run",
56
+ "build": "tsdown --config-loader unrun",
57
+ "watch": "tsdown --config-loader unrun --watch",
58
+ "typecheck": "golar tsc -p ../../tsconfig.json",
59
+ "lint": "oxlint src --fix"
60
+ }
6
61
  }