@toggld/browser 0.0.0-stage → 0.1.0
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 +202 -0
- package/README.md +112 -2
- package/dist/client-BQFClvyL.d.ts +232 -0
- package/dist/client-BwTN-sJD.js +742 -0
- package/dist/effect.d.ts +43 -0
- package/dist/effect.js +62 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/package.json +61 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,113 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @toggld/browser
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Toggld SDK for browsers. It evaluates every flag for the current user in
|
|
4
|
+
one request, then answers each evaluation synchronously from memory. Flag
|
|
5
|
+
changes arrive live over a WebSocket.
|
|
6
|
+
|
|
7
|
+
- **Zero dependencies.** About 4 KB minified and gzipped.
|
|
8
|
+
- **`@toggld/browser`**: a plain Promise API.
|
|
9
|
+
- **`@toggld/browser/effect`**: the same client as an [Effect](https://effect.website)
|
|
10
|
+
service and `Layer`. `effect` (`^4.0.5`) is an optional peer dependency that only
|
|
11
|
+
this entry uses.
|
|
12
|
+
- For React, use [`@toggld/react`](../react).
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pnpm add @toggld/browser
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Use
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import { ToggldClient } from "@toggld/browser"
|
|
24
|
+
|
|
25
|
+
const flags = await ToggldClient.create({
|
|
26
|
+
publicToken: "ffp_…", // the environment's public token (never a secret ffk_ key)
|
|
27
|
+
context: { targetingKey: user.id, plan: user.plan },
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
// Synchronous: no request per call. Never throws; returns the default on error.
|
|
31
|
+
flags.getBooleanValue("new-checkout", false)
|
|
32
|
+
flags.getStringDetails("theme", "light") // { value, variant, reason, errorCode, … }
|
|
33
|
+
|
|
34
|
+
// After sign-in: replaces the context and re-evaluates (one request).
|
|
35
|
+
await flags.setContext({ targetingKey: user.id, plan: "pro" })
|
|
36
|
+
|
|
37
|
+
// React to changes (new values, status, context).
|
|
38
|
+
const unsubscribe = flags.subscribe(() => render(flags.getSnapshot()))
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Live updates
|
|
42
|
+
|
|
43
|
+
By default the client also opens the evaluation stream, a WebSocket to
|
|
44
|
+
`/eval/v1/stream`. It sends its context there, and Toggld pushes new values
|
|
45
|
+
whenever a flag change alters them. HTTP still loads the first values and the
|
|
46
|
+
values for each new context: it is fast and works where WebSockets are blocked.
|
|
47
|
+
|
|
48
|
+
- While the stream is open and has sent values for the current context,
|
|
49
|
+
polling and refresh-on-visible pause, and `refresh()` sends nothing. They are
|
|
50
|
+
the fallback when the stream is not available.
|
|
51
|
+
- The client reconnects with jittered backoff (1 s doubling to 30 s) and
|
|
52
|
+
re-sends its context. It stops after a 1008 close (revoked token or deleted
|
|
53
|
+
environment), and waits a minute after a 4429 close (too many context changes).
|
|
54
|
+
- Heartbeat: the client pings every 30 s and reconnects if no answer comes
|
|
55
|
+
within 10 s. It also pings when the page returns after being hidden longer
|
|
56
|
+
than `staleAfterMs`.
|
|
57
|
+
- After 3 connects in a row that fail before opening (a rejected token, an
|
|
58
|
+
older server without the stream), the client stops reconnecting until the
|
|
59
|
+
next `setContext()` or `refresh()`, which tries once more. A token rejected
|
|
60
|
+
over HTTP (401/403) stops the stream too.
|
|
61
|
+
- `getSnapshot().streaming` is `true` while the stream is open.
|
|
62
|
+
- Options: `stream: false` turns it off. `webSocket` passes a custom
|
|
63
|
+
constructor (default: the global `WebSocket`; without one the client uses
|
|
64
|
+
HTTP only). The stream opens only where `document` exists, unless you pass
|
|
65
|
+
`webSocket`.
|
|
66
|
+
- Privacy: while connected, Toggld stores the browser's evaluation context for
|
|
67
|
+
that connection, and deletes it when the connection closes.
|
|
68
|
+
|
|
69
|
+
## Request policy
|
|
70
|
+
|
|
71
|
+
Every request counts against the public token's per-environment rate limit,
|
|
72
|
+
which all visitors share. So the client sends a request only when it is
|
|
73
|
+
created (skipped with a `bootstrap`), on `setContext` / `refresh()`, and when a
|
|
74
|
+
hidden page becomes visible with values older than `staleAfterMs` (60 s).
|
|
75
|
+
Polling is **off** unless you set `pollIntervalMs` (it then runs only while the
|
|
76
|
+
page is visible). Visibility refreshes and polling pause while the stream is
|
|
77
|
+
open. Failures retry with jittered backoff up to 1 minute; a 429
|
|
78
|
+
waits for `Retry-After`; a rejected token (401/403) or context (400) does not
|
|
79
|
+
retry.
|
|
80
|
+
|
|
81
|
+
## Server-side rendering
|
|
82
|
+
|
|
83
|
+
Evaluate on the server with `@toggld/node`'s `evaluateAll(context)` and pass the
|
|
84
|
+
results as `bootstrap` (same context). The client is ready at once, sends no
|
|
85
|
+
first request, and, without a `document`, starts no background work and opens
|
|
86
|
+
no stream.
|
|
87
|
+
|
|
88
|
+
## Effect
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
import { Effect } from "effect"
|
|
92
|
+
import { ToggldClient, layer } from "@toggld/browser/effect"
|
|
93
|
+
|
|
94
|
+
const program = Effect.gen(function* () {
|
|
95
|
+
const flags = yield* ToggldClient
|
|
96
|
+
yield* flags.ready
|
|
97
|
+
return yield* flags.getBooleanValue("new-checkout", false)
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
program.pipe(Effect.provide(layer({ publicToken, context })), Effect.runPromise)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
`flags.changes` is a `Stream` of the current state and every change. The layer's
|
|
104
|
+
scope closes the client.
|
|
105
|
+
|
|
106
|
+
## Development
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
pnpm test # stubbed fetch/WebSocket suites + a run against the in-process flag API
|
|
110
|
+
pnpm size # build, then fail if the default entry exceeds its gzip budget or imports any package
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Docs: [docs.toggld.io/sdks/browser](https://docs.toggld.io/sdks/browser).
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A resolved flag value. OpenFeature permits `boolean | string | number |
|
|
3
|
+
* structure`; we model the union as JSON, which also covers arrays and null for
|
|
4
|
+
* "object" typed flags.
|
|
5
|
+
*/
|
|
6
|
+
type FlagValue = null | boolean | number | string | ReadonlyArray<FlagValue> | {
|
|
7
|
+
readonly [key: string]: FlagValue;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Flag metadata: "arbitrary properties, with keys of type string, and values of
|
|
11
|
+
* type boolean, string, or number." (Requirement 2.2.10)
|
|
12
|
+
*/
|
|
13
|
+
type MetadataValue = string | number | boolean;
|
|
14
|
+
type FlagMetadata = {
|
|
15
|
+
readonly [key: string]: MetadataValue;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* An OpenFeature evaluation context: an optional `targetingKey` identifying the
|
|
19
|
+
* subject (Requirement 3.1.1) plus arbitrary custom JSON-valued attributes
|
|
20
|
+
* (Requirement 3.1.2).
|
|
21
|
+
*/
|
|
22
|
+
type EvaluationContext = {
|
|
23
|
+
readonly [attribute: string]: FlagValue;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Resolution reasons. (Requirement 2.2.5)
|
|
27
|
+
*/
|
|
28
|
+
type Reason = "STATIC" | "DEFAULT" | "TARGETING_MATCH" | "SPLIT" | "CACHED" | "DISABLED" | "UNKNOWN" | "STALE" | "ERROR";
|
|
29
|
+
/**
|
|
30
|
+
* OpenFeature error codes.
|
|
31
|
+
* @see https://openfeature.dev/specification/types
|
|
32
|
+
*/
|
|
33
|
+
type ErrorCode = "PROVIDER_NOT_READY" | "PROVIDER_FATAL" | "FLAG_NOT_FOUND" | "PARSE_ERROR" | "TYPE_MISMATCH" | "TARGETING_KEY_MISSING" | "INVALID_CONTEXT" | "GENERAL";
|
|
34
|
+
/**
|
|
35
|
+
* The outcome of evaluating one flag — OpenFeature "evaluation details", with
|
|
36
|
+
* the value typed to the requested flag type.
|
|
37
|
+
*
|
|
38
|
+
* On any abnormal evaluation (no data yet, unknown flag, type mismatch, a
|
|
39
|
+
* server-reported error) the call still returns: `value` holds the caller's
|
|
40
|
+
* default, `reason` is `"ERROR"`, and `errorCode`/`errorMessage` say why.
|
|
41
|
+
* Evaluation never throws.
|
|
42
|
+
*/
|
|
43
|
+
interface EvaluationDetails<T extends FlagValue> {
|
|
44
|
+
readonly flagKey: string;
|
|
45
|
+
readonly value: T;
|
|
46
|
+
readonly variant: string | undefined;
|
|
47
|
+
readonly reason: Reason;
|
|
48
|
+
readonly errorCode: ErrorCode | undefined;
|
|
49
|
+
readonly errorMessage: string | undefined;
|
|
50
|
+
readonly flagMetadata: FlagMetadata;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Where the client is, relative to its **current** evaluation context.
|
|
54
|
+
*
|
|
55
|
+
* - `"loading"` — no flag values yet; the first request is in flight.
|
|
56
|
+
* Evaluations return the caller's default with `PROVIDER_NOT_READY`.
|
|
57
|
+
* - `"ready"` — the values in memory belong to the current context.
|
|
58
|
+
* - `"reconciling"` — the context changed and the new values are in flight.
|
|
59
|
+
* Evaluations keep serving the previous context's values until they arrive.
|
|
60
|
+
* - `"error"` — the client has no values for the current context because the
|
|
61
|
+
* last request for it failed. It serves older values if it has any, or the
|
|
62
|
+
* caller's default otherwise, and retries in the background unless the
|
|
63
|
+
* failure was permanent (a rejected token or context).
|
|
64
|
+
*
|
|
65
|
+
* A failed background refresh does not change a `"ready"` status: the values
|
|
66
|
+
* still match the context. Its message is in {@link ClientSnapshot.error}.
|
|
67
|
+
*/
|
|
68
|
+
type ClientStatus = "loading" | "ready" | "reconciling" | "error";
|
|
69
|
+
/**
|
|
70
|
+
* An immutable picture of the client's state. {@link ToggldClient.getSnapshot}
|
|
71
|
+
* returns the same object until something changes, and a new one after each
|
|
72
|
+
* change, so it works directly with React's `useSyncExternalStore`.
|
|
73
|
+
*/
|
|
74
|
+
interface ClientSnapshot {
|
|
75
|
+
readonly status: ClientStatus;
|
|
76
|
+
/** The context the client evaluates for (the last one set). */
|
|
77
|
+
readonly context: EvaluationContext;
|
|
78
|
+
/**
|
|
79
|
+
* The last evaluated result of every flag, by key. A failed flag keeps its
|
|
80
|
+
* `errorCode` and a `null` value. A flag whose result did not change between
|
|
81
|
+
* refreshes keeps the same object, so identity comparisons are cheap.
|
|
82
|
+
*/
|
|
83
|
+
readonly flags: ReadonlyMap<string, EvaluationDetails<FlagValue>>;
|
|
84
|
+
/** Why the last request failed, or `undefined` after a success. */
|
|
85
|
+
readonly error: string | undefined;
|
|
86
|
+
/** When the last values arrived (`Date.now()`), from HTTP or the stream, if ever. */
|
|
87
|
+
readonly updatedAt: number | undefined;
|
|
88
|
+
/**
|
|
89
|
+
* Whether the evaluation stream is connected. While it is, flag changes
|
|
90
|
+
* arrive within moments, without polling. `false` when the stream is off,
|
|
91
|
+
* unavailable, or reconnecting; the client then falls back to HTTP refresh.
|
|
92
|
+
*/
|
|
93
|
+
readonly streaming: boolean;
|
|
94
|
+
}
|
|
95
|
+
/** Configuration for a browser {@link ToggldClient}. */
|
|
96
|
+
interface ToggldClientOptions {
|
|
97
|
+
/**
|
|
98
|
+
* The environment's **public token** (`ffp_…`), sent as `Authorization:
|
|
99
|
+
* Bearer <token>`. It is safe to ship to browsers: it can evaluate flags but
|
|
100
|
+
* cannot read rules or change anything. Find it in **Settings → API Keys**.
|
|
101
|
+
* Never put a secret key (`ffk_…`) in browser code.
|
|
102
|
+
*/
|
|
103
|
+
readonly publicToken: string;
|
|
104
|
+
/** Base URL of the flag API. Default `https://api.toggld.io`. */
|
|
105
|
+
readonly endpoint?: string;
|
|
106
|
+
/**
|
|
107
|
+
* The evaluation context: who the flags are evaluated for. Include a stable
|
|
108
|
+
* `targetingKey` (the user ID, or a stored random ID for anonymous visitors)
|
|
109
|
+
* so percentage rollouts stay consistent. Change it later with
|
|
110
|
+
* {@link ToggldClient.setContext}.
|
|
111
|
+
*/
|
|
112
|
+
readonly context?: EvaluationContext;
|
|
113
|
+
/**
|
|
114
|
+
* Flag results that are already known, for example evaluated on your server
|
|
115
|
+
* during server-side rendering with `@toggld/node`'s `evaluateAll`. They must
|
|
116
|
+
* belong to the same {@link context}. A non-empty bootstrap makes the client
|
|
117
|
+
* `"ready"` at once and skips the first request, which also saves an
|
|
118
|
+
* evaluation request.
|
|
119
|
+
*/
|
|
120
|
+
readonly bootstrap?: ReadonlyArray<EvaluationDetails<FlagValue>>;
|
|
121
|
+
/**
|
|
122
|
+
* Re-fetch every flag at this interval, in milliseconds, while the page is
|
|
123
|
+
* visible. **Off by default.** Public tokens share a per-environment rate
|
|
124
|
+
* limit across every visitor, so enable polling only if a page stays open for a long time and
|
|
125
|
+
* must pick up flag changes without a reload. Must be at least 5000. Polling
|
|
126
|
+
* pauses while the evaluation stream delivers updates ({@link stream}).
|
|
127
|
+
*/
|
|
128
|
+
readonly pollIntervalMs?: number;
|
|
129
|
+
/**
|
|
130
|
+
* Re-fetch when the page becomes visible again (tab switch, phone unlock) and
|
|
131
|
+
* the values are older than {@link staleAfterMs}. Default `true`. Paused,
|
|
132
|
+
* like polling, while the evaluation stream delivers updates.
|
|
133
|
+
*/
|
|
134
|
+
readonly refreshOnVisible?: boolean;
|
|
135
|
+
/** Age after which {@link refreshOnVisible} re-fetches, in milliseconds. Default `60000`. */
|
|
136
|
+
readonly staleAfterMs?: number;
|
|
137
|
+
/** Per-request timeout in milliseconds. Default `5000`. */
|
|
138
|
+
readonly timeoutMs?: number;
|
|
139
|
+
/**
|
|
140
|
+
* How long {@link ToggldClient.create} waits for the first values before it
|
|
141
|
+
* resolves anyway, in milliseconds. Default `5000`.
|
|
142
|
+
*/
|
|
143
|
+
readonly readyTimeoutMs?: number;
|
|
144
|
+
/** Custom `fetch` implementation. Defaults to the global `fetch`. */
|
|
145
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
146
|
+
/**
|
|
147
|
+
* Open the evaluation stream, a WebSocket that pushes new values as soon as a
|
|
148
|
+
* flag change alters them. Default `true`. HTTP still loads the first values
|
|
149
|
+
* and the values for each new context; polling and refresh-on-visible pause
|
|
150
|
+
* while the stream is live and take over when it is not. While connected,
|
|
151
|
+
* Toggld stores the evaluation context for that connection and deletes it
|
|
152
|
+
* when the connection closes.
|
|
153
|
+
*
|
|
154
|
+
* The stream opens only where there is a page (`document` exists), so a
|
|
155
|
+
* client built during server-side rendering opens nothing, unless you pass
|
|
156
|
+
* {@link webSocket}.
|
|
157
|
+
*/
|
|
158
|
+
readonly stream?: boolean;
|
|
159
|
+
/**
|
|
160
|
+
* Custom `WebSocket` constructor for the stream. Defaults to the global
|
|
161
|
+
* `WebSocket`; without either, the client uses HTTP only. Passing one also
|
|
162
|
+
* opens the stream where there is no `document`.
|
|
163
|
+
*/
|
|
164
|
+
readonly webSocket?: typeof WebSocket;
|
|
165
|
+
}
|
|
166
|
+
type Details = EvaluationDetails<FlagValue>;
|
|
167
|
+
/**
|
|
168
|
+
* A Toggld client for browser code. Create one per page (outside any React
|
|
169
|
+
* render), with {@link ToggldClient.create} to await the first values or with
|
|
170
|
+
* `new ToggldClient(options)` to start loading in the background.
|
|
171
|
+
*/
|
|
172
|
+
declare class ToggldClient {
|
|
173
|
+
#private;
|
|
174
|
+
constructor(options: ToggldClientOptions);
|
|
175
|
+
/**
|
|
176
|
+
* Create a client and wait for its first values, or for `readyTimeoutMs`
|
|
177
|
+
* (default 5 s), whichever is first. It never rejects: on a timeout or a
|
|
178
|
+
* failure the client serves caller defaults and keeps retrying.
|
|
179
|
+
*/
|
|
180
|
+
static create(options: ToggldClientOptions): Promise<ToggldClient>;
|
|
181
|
+
/**
|
|
182
|
+
* Resolves once the client first has values for its context, or once a
|
|
183
|
+
* failure makes that impossible (a rejected token or context). It never
|
|
184
|
+
* rejects. A client built with a bootstrap is ready at once.
|
|
185
|
+
*/
|
|
186
|
+
ready(): Promise<void>;
|
|
187
|
+
/** The current {@link ClientSnapshot}: the same object until something changes. */
|
|
188
|
+
readonly getSnapshot: () => ClientSnapshot;
|
|
189
|
+
/**
|
|
190
|
+
* Call `listener` after every state change: new values, a status change, or
|
|
191
|
+
* a new context. Returns a function that removes it. The signature matches
|
|
192
|
+
* React's `useSyncExternalStore`, so `client.subscribe` can be passed as is.
|
|
193
|
+
*/
|
|
194
|
+
readonly subscribe: (listener: () => void) => (() => void);
|
|
195
|
+
get status(): ClientStatus;
|
|
196
|
+
get context(): EvaluationContext;
|
|
197
|
+
/**
|
|
198
|
+
* Evaluate for a new context: for example after sign-in, or when an
|
|
199
|
+
* attribute that targeting rules use changes. The context is **replaced**,
|
|
200
|
+
* not merged. Until the new values arrive the status is `"reconciling"` and
|
|
201
|
+
* the previous values are still served. Resolves when the request settles; it
|
|
202
|
+
* never rejects. Setting an identical context does nothing. An open stream
|
|
203
|
+
* receives the new context too.
|
|
204
|
+
*/
|
|
205
|
+
setContext(context: EvaluationContext): Promise<void>;
|
|
206
|
+
/**
|
|
207
|
+
* Fetch fresh values for the current context now. A request already in
|
|
208
|
+
* flight for it is shared rather than repeated. Resolves when it settles; it
|
|
209
|
+
* never rejects. After a 429 it waits for `Retry-After` first. While the
|
|
210
|
+
* stream is live it does nothing: the values are already current.
|
|
211
|
+
*/
|
|
212
|
+
refresh(): Promise<void>;
|
|
213
|
+
/**
|
|
214
|
+
* Stop all background work (requests, retries, polling, the stream,
|
|
215
|
+
* listeners). Values stay readable, but they no longer update.
|
|
216
|
+
*/
|
|
217
|
+
close(): void;
|
|
218
|
+
/** Resolve a flag, returning full details with an untyped (JSON) value. */
|
|
219
|
+
evaluate(key: string, defaultValue: FlagValue): Details;
|
|
220
|
+
/** The last result of every flag for the current context. */
|
|
221
|
+
allFlags(): ReadonlyArray<Details>;
|
|
222
|
+
getBooleanValue(key: string, defaultValue: boolean): boolean;
|
|
223
|
+
getBooleanDetails(key: string, defaultValue: boolean): EvaluationDetails<boolean>;
|
|
224
|
+
getStringValue(key: string, defaultValue: string): string;
|
|
225
|
+
getStringDetails(key: string, defaultValue: string): EvaluationDetails<string>;
|
|
226
|
+
getNumberValue(key: string, defaultValue: number): number;
|
|
227
|
+
getNumberDetails(key: string, defaultValue: number): EvaluationDetails<number>;
|
|
228
|
+
/** Object values are deep-frozen and shared: do not mutate them. */
|
|
229
|
+
getObjectValue<T extends FlagValue>(key: string, defaultValue: T): T;
|
|
230
|
+
getObjectDetails<T extends FlagValue>(key: string, defaultValue: T): EvaluationDetails<T>;
|
|
231
|
+
}
|
|
232
|
+
export { ToggldClientOptions as a, FlagMetadata as c, EvaluationDetails as i, FlagValue as l, ClientSnapshot as n, ErrorCode as o, ClientStatus as r, EvaluationContext as s, ToggldClient as t, Reason as u };
|