@nanoflags/sdk 0.0.0-stage → 0.4.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/NOTICE +4 -0
- package/README.md +374 -2
- package/dist/index-D5qa8ji-.d.cts +302 -0
- package/dist/index-D5qa8ji-.d.ts +302 -0
- package/dist/index.cjs +12 -0
- package/dist/index.d.cts +13 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +1 -0
- package/dist/node.cjs +108 -0
- package/dist/node.d.cts +35 -0
- package/dist/node.d.ts +35 -0
- package/dist/node.js +101 -0
- package/dist/react.cjs +65 -0
- package/dist/react.d.cts +28 -0
- package/dist/react.d.ts +28 -0
- package/dist/react.js +62 -0
- package/dist/src-CVTvEKbT.js +1556 -0
- package/dist/src-IVd-Wps4.cjs +1615 -0
- package/package.json +98 -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/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,375 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @nanoflags/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
JavaScript/TypeScript SDK for NanoFlags. Flags are evaluated **locally and synchronously** against an
|
|
4
|
+
in-memory configuration bundle. The network is used only in the background — to load the bundle, to
|
|
5
|
+
learn about new revisions, and to send sampled telemetry. An accessor never performs I/O and never throws.
|
|
6
|
+
|
|
7
|
+
- ESM and CommonJS builds, TypeScript types included, no runtime dependencies (the evaluation engine is
|
|
8
|
+
bundled). Node 18 or newer; `react` (18 or newer) is an optional peer dependency, needed only for
|
|
9
|
+
`@nanoflags/sdk/react`.
|
|
10
|
+
- Entry points: `@nanoflags/sdk` (Node, browsers, edge runtimes), `@nanoflags/sdk/react`, and
|
|
11
|
+
`@nanoflags/sdk/node` (test-session propagation with `AsyncLocalStorage`).
|
|
12
|
+
- v2 adds [signature verification](#signature-verification) and [test sessions](#test-sessions).
|
|
13
|
+
- **0.4** verifies signatures **by default** when `baseUrl` is the hosted edge (`https://edge.nanoflags.io`), with
|
|
14
|
+
the production public keys embedded in the SDK, and refuses unsigned bundles there (see
|
|
15
|
+
[Signature verification](#signature-verification)). It also refuses bundles produced for a newer evaluation engine
|
|
16
|
+
(`bundle.engine`, see [Engine version](#engine-version)) and stops reconnecting when the edge reports that the
|
|
17
|
+
environment was deleted. Self-hosted edges (any other `baseUrl`) behave as in 0.3 unless `verify` is set.
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
npm install @nanoflags/sdk
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Releases are published to npm from [motazalmaroai/nanoflags-sdk](https://github.com/motazalmaroai/nanoflags-sdk)
|
|
26
|
+
by its release workflow (`.github/workflows/release.yml`, tag `sdk-v<version>`).
|
|
27
|
+
|
|
28
|
+
## Quickstart
|
|
29
|
+
|
|
30
|
+
### Node
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
import { createClient } from "@nanoflags/sdk";
|
|
34
|
+
|
|
35
|
+
const flags = createClient({
|
|
36
|
+
sdkKey: process.env.NANOFLAGS_SDK_KEY!, // nf_srv_…
|
|
37
|
+
baseUrl: "https://flags.example.com",
|
|
38
|
+
service: "checkout-api",
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
await flags.ready(); // never rejects — see "Fallbacks and staleness"
|
|
42
|
+
|
|
43
|
+
const enabled = flags.boolean("checkout-v2", false, { key: user.id, signedIn: true, region: "US" });
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Create one client per process and reuse it. Call `flags.close()` on shutdown. Background timers are
|
|
47
|
+
`unref`'d, but the live connection (WebSocket, or the SSE stream it falls back to) keeps a Node process
|
|
48
|
+
alive until `close()`; in short-lived scripts and serverless functions either call `close()` or pass
|
|
49
|
+
`streaming: false`. The live socket needs a global `WebSocket` (Node ≥ 22, browsers, Deno, Bun); on
|
|
50
|
+
older Node versions pass one (`webSocket: require("ws")`) or the SDK uses SSE + polling. Node has no default
|
|
51
|
+
persistence (safe for read-only and ephemeral file systems); pass `store` if you want one.
|
|
52
|
+
|
|
53
|
+
### Browser
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
import { createClient } from "@nanoflags/sdk";
|
|
57
|
+
|
|
58
|
+
const flags = createClient({
|
|
59
|
+
sdkKey: "nf_pub_…", // browser key: only client-exposed flags are delivered
|
|
60
|
+
baseUrl: "https://flags.example.com",
|
|
61
|
+
service: "web",
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
await flags.ready();
|
|
65
|
+
const ranking = flags.string("search-ranking", "relevance-v2", { key: user.id });
|
|
66
|
+
flags.on("update", ({ revision }) => console.log("now on revision", revision));
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Never ship an `nf_srv_` key to a browser. Rules of client-exposed flags are visible to anyone who has
|
|
70
|
+
the browser key, and evaluation runs on the user's device — do not use browser flags for authorization.
|
|
71
|
+
|
|
72
|
+
### React
|
|
73
|
+
|
|
74
|
+
```tsx
|
|
75
|
+
import { createClient } from "@nanoflags/sdk";
|
|
76
|
+
import { NanoFlagsProvider, useFlag, useFlagsStatus } from "@nanoflags/sdk/react";
|
|
77
|
+
|
|
78
|
+
const client = createClient({ sdkKey: "nf_pub_…", baseUrl: "https://flags.example.com" });
|
|
79
|
+
|
|
80
|
+
export function App({ user }) {
|
|
81
|
+
return (
|
|
82
|
+
<NanoFlagsProvider client={client} context={{ key: user.id, plan: user.plan }}>
|
|
83
|
+
<Search />
|
|
84
|
+
</NanoFlagsProvider>
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function Search() {
|
|
89
|
+
const ranking = useFlag("search-ranking", "relevance-v2"); // string accessor (from the fallback's type)
|
|
90
|
+
const compact = useFlag("compact-results", false, { device: "mobile" }); // context override, shallow-merged
|
|
91
|
+
const { status, revision } = useFlagsStatus(); // "not-ready" | "ready" | "stale"
|
|
92
|
+
…
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Hooks use `useSyncExternalStore`: components re-render when a new revision arrives or the status
|
|
97
|
+
changes. Until a bundle is loaded they return the fallback. For server rendering, pass the bundle you
|
|
98
|
+
evaluated with on the server as `bootstrap` so the first client render matches.
|
|
99
|
+
|
|
100
|
+
## API
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
createClient({
|
|
104
|
+
sdkKey, baseUrl,
|
|
105
|
+
service?: string, // shown in "which revision is this service running"
|
|
106
|
+
pollIntervalMs?: number, // 30000; 0 disables polling
|
|
107
|
+
streaming?: boolean, // true; false = polling only (no WebSocket, no SSE)
|
|
108
|
+
live?: boolean, // true; false = SSE + polling as in 0.2 (no WebSocket)
|
|
109
|
+
livePollIntervalMs?: number, // 300000: safety poll while the live socket is healthy
|
|
110
|
+
webSocket?: WebSocketConstructor, // default: the global WebSocket
|
|
111
|
+
bootstrap?: Bundle,
|
|
112
|
+
store?: { get(): Promise<string | null>; set(v: string): Promise<void> } | false,
|
|
113
|
+
events?: { enabled?: boolean /* true */, sampleRate?: number /* 0.1 */, flushIntervalMs?: number /* 10000 */, reportIntervalMs?: number /* 60000 */, redact?: (ctx) => object } | false,
|
|
114
|
+
verify?: { publicKeys?: JsonWebKey[] | "fetch", require?: boolean } | false, // default: see Signature verification
|
|
115
|
+
fetch?: typeof fetch,
|
|
116
|
+
})
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
| Member | |
|
|
120
|
+
| --- | --- |
|
|
121
|
+
| `ready(): Promise<void>` | Resolves when a usable bundle is loaded (network, store or bootstrap) — or when the first load attempt finished without one. **Never rejects.** Check `status`. |
|
|
122
|
+
| `status` | `"not-ready"` · `"ready"` · `"stale"` |
|
|
123
|
+
| `revision` | Revision of the bundle in use, `null` without one. |
|
|
124
|
+
| `transport` | How updates reach this client right now: `"live"` (WebSocket open) · `"stream"` (SSE) · `"poll"`. |
|
|
125
|
+
| `boolean / string / number / json (key, fallback, ctx?)` | The value, or `fallback`. |
|
|
126
|
+
| `evaluate(key, fallback, ctx?)` | The engine `Evaluation`: `value`, `reason`, `ruleIndex`, `ruleId`, `inRollout`, `bucket`, `revision`, `trace`. No type check. |
|
|
127
|
+
| `session(token, { service? })` | `Promise<SessionEvaluator>` for a test session. Never rejects. See [Test sessions](#test-sessions). |
|
|
128
|
+
| `useSession(token \| null)` / `sessionHeaders()` | Browser only: join or leave a test session for this page session; headers for downstream calls. |
|
|
129
|
+
| `on("update" \| "error", cb)` | Returns an unsubscribe function. `update` receives `{ revision, previousRevision, checksum, source, transport, latencyMs }` (see [Updates](#updates)). `error` receives a `NanoFlagsError` with `code`: `network`, `unauthorized`, `http`, `invalid_bundle`, `store`, `config`, `signature`, `session`, `engine` (bundle for a newer engine, refused), `environment_deleted`. |
|
|
130
|
+
| `refresh()` / `flush()` / `close()` | Revalidate now / send queued telemetry now / stop all background work. |
|
|
131
|
+
|
|
132
|
+
## Fallbacks and staleness
|
|
133
|
+
|
|
134
|
+
The `fallback` argument is what your application does when NanoFlags cannot answer. It is returned when:
|
|
135
|
+
|
|
136
|
+
| Situation | `reason` |
|
|
137
|
+
| --- | --- |
|
|
138
|
+
| No bundle loaded yet (`status: "not-ready"`) | `flag_not_found` |
|
|
139
|
+
| The flag is not in the bundle (unknown, archived, or server-only with a browser key) | `flag_not_found` |
|
|
140
|
+
| The flag's value has a different type than the accessor (`boolean()` on a string flag) | `error` |
|
|
141
|
+
| The configuration is malformed | `error` |
|
|
142
|
+
|
|
143
|
+
A **disabled** flag is not a fallback case: it returns the flag's configured `off` value (`reason: "off"`).
|
|
144
|
+
|
|
145
|
+
`status` describes the bundle, not individual flags:
|
|
146
|
+
|
|
147
|
+
- `not-ready` — no bundle. Every accessor returns its fallback.
|
|
148
|
+
- `ready` — the bundle was confirmed by the edge on the last attempt (or was supplied as `bootstrap`
|
|
149
|
+
and no attempt has failed yet).
|
|
150
|
+
- `stale` — a bundle is in use but is **not known to be current**: it was restored from the store and
|
|
151
|
+
not yet revalidated, the last revalidation failed (offline, edge error, rejected key), or the edge
|
|
152
|
+
itself served its last-known-good copy because its origin was unreachable. Evaluations continue on
|
|
153
|
+
that bundle; the SDK keeps retrying (after a failure: 1 s, 2 s, 4 s … up to the poll interval).
|
|
154
|
+
|
|
155
|
+
The SDK never discards a working bundle because of an error, and never replaces a bundle with an older
|
|
156
|
+
one served as last-known-good. If the environment is deleted, the edge closes the live socket with code `4004`: the client reports
|
|
157
|
+
`error` (`code: "environment_deleted"`), turns `stale`, keeps evaluating the last bundle and stops reconnecting
|
|
158
|
+
(only the regular poll continues, which then reports the key as rejected). If a key is revoked, the client reports `error` (`code: "unauthorized"`)
|
|
159
|
+
and keeps evaluating the last bundle as `stale` — revocation stops updates, it does not erase
|
|
160
|
+
configuration that already reached a process.
|
|
161
|
+
|
|
162
|
+
## Updates
|
|
163
|
+
|
|
164
|
+
1. **Live push (default)** — one WebSocket to `GET /v1/live`. The moment a revision is published the
|
|
165
|
+
edge sends a `rev` message that carries the signed bundle itself, so the SDK applies it **without
|
|
166
|
+
any further request**; on (re)connect a `hello` message carries the current revision, so a client
|
|
167
|
+
that was offline catches up in one message. The key travels in the WebSocket subprotocol list
|
|
168
|
+
(`["nanoflags.v1", "key.<sdk key>"]`), never in the URL. Server and browser keys both use it;
|
|
169
|
+
browser keys receive the client view. The SDK pings every ~30 s (answered by the edge without
|
|
170
|
+
waking anything), replaces the socket every ~50 minutes so the key is validated again, and
|
|
171
|
+
reconnects with jittered exponential backoff (1 s, 2 s, 4 s … capped at 5 min, each × 0.5–1.5).
|
|
172
|
+
While the socket is healthy, SSE is not opened and polling drops to `livePollIntervalMs` (5 min).
|
|
173
|
+
2. **Stream (fallback)** — when the socket cannot be established (no `WebSocket` in the runtime, a
|
|
174
|
+
proxy that does not pass upgrades, the edge answering `503` because an environment reached its
|
|
175
|
+
connection cap) the SDK opens a server-sent-events connection that carries only
|
|
176
|
+
`{ revision, checksum }` and fetches the bundle conditionally (`GET /v1/bundle`, `If-None-Match`).
|
|
177
|
+
Browser keys use `EventSource` (`?key=`, browser keys only); everything else a `fetch` stream with
|
|
178
|
+
the `Authorization` header. It keeps retrying the live socket in the background and closes the
|
|
179
|
+
stream once a socket opens.
|
|
180
|
+
3. **Polling (safety net)** — the conditional request every `pollIntervalMs` ± 20 % jitter. Hidden
|
|
181
|
+
tabs do not poll and catch up when they become visible.
|
|
182
|
+
|
|
183
|
+
`live: false` keeps the 0.2 behaviour (2 + 3); `streaming: false` leaves polling only.
|
|
184
|
+
|
|
185
|
+
A new bundle replaces the old one in a single assignment: an evaluation sees either the old or the new
|
|
186
|
+
revision in full, never a mixture. The SDK never moves to an older revision than one it was pushed.
|
|
187
|
+
|
|
188
|
+
The `update` event says how the bundle arrived: `transport` is `"live"` (pushed), `"stream"` (fetched
|
|
189
|
+
after an SSE notification) or `"poll"` (everything else, including the initial load, the store and
|
|
190
|
+
`bootstrap`). For pushed revisions `latencyMs` is the time from the commit in the database to the
|
|
191
|
+
event (`Date.now() - committedAt`); it is `null` when the commit time is not known (other transports,
|
|
192
|
+
the `hello` of an environment whose last revision was distributed by the fallback path). It compares
|
|
193
|
+
the database's clock with yours, so read it as accurate to within the clock difference of the two
|
|
194
|
+
machines. Measured on the hosted edge: typically 140–180 ms with the live socket; with SSE up to ~10 s;
|
|
195
|
+
with polling up to one poll interval. This is propagation, not a guarantee.
|
|
196
|
+
|
|
197
|
+
With `verify`, a pushed bundle is verified exactly like a fetched one before it is used (the message
|
|
198
|
+
carries the signature, key id and environment id). A push that does not verify changes nothing, emits
|
|
199
|
+
`error` (`code: "signature"`), and makes the SDK ask the edge over HTTP what is current.
|
|
200
|
+
|
|
201
|
+
## Signature verification
|
|
202
|
+
|
|
203
|
+
Published bundles are signed by the NanoFlags publisher with Ed25519. The SDK checks the signature **before** a new
|
|
204
|
+
bundle replaces the one in use.
|
|
205
|
+
|
|
206
|
+
**Default (0.4):**
|
|
207
|
+
|
|
208
|
+
| `baseUrl` | `verify` not set | |
|
|
209
|
+
| --- | --- | --- |
|
|
210
|
+
| `https://edge.nanoflags.io` | verified against the embedded production keys (`OFFICIAL_SIGNING_KEYS`), `require: true` | pushed (WebSocket) and fetched bundles must be signed and verify |
|
|
211
|
+
| any other edge | not verified (as in 0.3) | configure `verify` for a self-hosted edge |
|
|
212
|
+
|
|
213
|
+
`verify: false` turns verification off explicitly. To configure it yourself:
|
|
214
|
+
|
|
215
|
+
```ts
|
|
216
|
+
const flags = createClient({
|
|
217
|
+
sdkKey, baseUrl,
|
|
218
|
+
verify: {
|
|
219
|
+
publicKeys: [{ kty: "OKP", crv: "Ed25519", x: "wQu1EsaE-yTjqpUbibGyBrajy3IiRb7LyaiqeYRxG4U", kid: "k1" }],
|
|
220
|
+
require: true,
|
|
221
|
+
},
|
|
222
|
+
});
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
- A response with `X-NanoFlags-Signed: true` (and every pushed bundle) is verified against the canonical string
|
|
226
|
+
`nanoflags-bundle-v1\n<environment id>\n<revision>\n<checksum>\n<sha256 hex of the bundle JSON text>`
|
|
227
|
+
(the bundle text exactly as the edge sent it), using WebCrypto, with the key whose `kid` the edge names
|
|
228
|
+
(`X-NanoFlags-Key-Id`, or `kid` in the push).
|
|
229
|
+
- **Bad signature → the update is rejected.** The previous bundle stays in use, `status` does not
|
|
230
|
+
change, and `error` fires with `code: "signature"`. The SDK retries on its normal schedule.
|
|
231
|
+
- **Unsigned bundles** (the edge sends `X-NanoFlags-Signed: false` while the publisher is catching up,
|
|
232
|
+
typically for well under a minute after a publish) are rejected when `require` is true — the default on the hosted
|
|
233
|
+
edge: the bundle in use stays, `error` (`signature`) fires, and the SDK fetches again with a short backoff (1 s,
|
|
234
|
+
2 s, 4 s … up to the poll interval) until the signed revision is there. With `require: false` (the default for
|
|
235
|
+
other edges) they are accepted; then someone who can alter responses can also strip the signature.
|
|
236
|
+
- **Keys and rotation.** Keys are selected by `kid` and cached. With the embedded keys, a bundle signed with a key id
|
|
237
|
+
the SDK does not know (the hosted edge rotated its key after this SDK version was built) makes the SDK load
|
|
238
|
+
`GET /v1/keys` once and verify against those keys as well; an id that is still unknown is rejected, and the reload
|
|
239
|
+
is not repeated within a minute. `publicKeys: "fetch"` loads all keys from `GET /v1/keys` (again when an unknown
|
|
240
|
+
key id appears, at most once a minute) — this detects corruption and tampering in storage and caches, but fetched
|
|
241
|
+
keys are only as trustworthy as the edge that served them. Explicitly pinned `publicKeys` are never extended from
|
|
242
|
+
the network: **pin the keys in your build** if the edge itself is in your threat model, and add the new key before
|
|
243
|
+
a rotation (the edge lists the old key as `status: "retiring"` during the overlap).
|
|
244
|
+
- After the first verified bundle the client remembers the environment id and rejects bundles signed
|
|
245
|
+
for a different environment.
|
|
246
|
+
- A persisted bundle (see below) is stored with its signature and verified again when restored; with
|
|
247
|
+
`require`, an unsigned stored copy is ignored. A `bootstrap` bundle is trusted as given.
|
|
248
|
+
With `publicKeys: "fetch"` a stored copy can only be verified once the keys were loaded, so an
|
|
249
|
+
offline start does not restore it; pinned and embedded keys do not have this limitation.
|
|
250
|
+
- Only public keys are accepted. A JWK with a private part (`d`) is ignored and reported as a `config`
|
|
251
|
+
error. Private signing keys and admin keys never belong in an application.
|
|
252
|
+
- Requires Ed25519 in WebCrypto: Node 20+, current Chrome, Firefox and Safari, Cloudflare Workers,
|
|
253
|
+
Deno, Bun. Where it is missing, signed bundles are rejected (they cannot be checked) — on the hosted edge pass
|
|
254
|
+
`verify: false` for such runtimes (Node 18) if you accept that.
|
|
255
|
+
|
|
256
|
+
Not covered: test-session bundles (`GET /v1/session`) are not signed, and verification says nothing
|
|
257
|
+
about *freshness* — it does not stop an attacker from withholding updates.
|
|
258
|
+
|
|
259
|
+
## Engine version
|
|
260
|
+
|
|
261
|
+
Bundles produced by the publisher carry `engine`, the version of the evaluation engine they were produced for
|
|
262
|
+
(`1` today; `SUPPORTED_ENGINE_VERSION` is what this SDK evaluates). A bundle with a **newer** `engine` — a rule format
|
|
263
|
+
this SDK does not understand — is refused wherever it comes from (fetch, push, store, `bootstrap`): the bundle in use
|
|
264
|
+
stays, `status` does not change, and `error` fires with `code: "engine"`. Upgrade the SDK to receive it. Bundles
|
|
265
|
+
without the field (older revisions, the edge's unsigned fallback) are evaluated as engine 1.
|
|
266
|
+
|
|
267
|
+
## Test sessions
|
|
268
|
+
|
|
269
|
+
A test session pins a configuration snapshot and a synthetic context to a token (`nf_ts_…`, created in
|
|
270
|
+
the dashboard). Services that receive the token in the `x-nanoflags-session` header evaluate against
|
|
271
|
+
that snapshot instead of the published configuration — for that request only.
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
const s = await flags.session(req.headers["x-nanoflags-session"], { service: "checkout-api" });
|
|
275
|
+
s.boolean("checkout-v2", false, { key: user.id }); // session bundle, context { ...session.context, key }
|
|
276
|
+
s.active; // false when the session is unknown, expired, revoked or not permitted for this service
|
|
277
|
+
s.id; // session id (null when not resolved)
|
|
278
|
+
s.expiresAt; // ISO timestamp (null when not resolved)
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
- `session()` asks the edge once per token and service (`GET /v1/session`) and caches the answer until
|
|
282
|
+
the session expires. Unknown tokens are remembered for 15 s, failed lookups for 3 s.
|
|
283
|
+
- It **never throws and never rejects**. Without an active session the evaluator behaves exactly like
|
|
284
|
+
the client, so the same code path serves normal traffic. When a session expires mid-flight,
|
|
285
|
+
`active` turns false and evaluations continue on the published configuration.
|
|
286
|
+
- Sampled events from a session carry `sessionId`.
|
|
287
|
+
- A session changes which snapshot and context an evaluation uses. It grants no data access and
|
|
288
|
+
must not be used for authorization. A revoked session keeps working in a process that already
|
|
289
|
+
cached it until its expiry time.
|
|
290
|
+
|
|
291
|
+
### Node: per-request propagation
|
|
292
|
+
|
|
293
|
+
```ts
|
|
294
|
+
import { sessionMiddleware, flagsFor, sessionHeaders, withSession, currentSession, withSessionHandler } from "@nanoflags/sdk/node";
|
|
295
|
+
|
|
296
|
+
app.use(sessionMiddleware(flags)); // Express / Connect
|
|
297
|
+
app.get("/cart", async (req, res) => {
|
|
298
|
+
const v2 = req.flags.boolean("checkout-v2", false, { key: req.user.id }); // or flagsFor(flags)
|
|
299
|
+
const prices = await fetch(PRICING_URL, { headers: { ...sessionHeaders() } }); // next service joins the session
|
|
300
|
+
…
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
export default { fetch: withSessionHandler(flags, async (request) => { … flagsFor(flags) … }) }; // fetch-style handlers
|
|
304
|
+
|
|
305
|
+
await withSession(token, async () => { … currentSession() … }); // queues, jobs, tests
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
The current session lives in `AsyncLocalStorage`: it follows one request through awaits and callbacks
|
|
309
|
+
and is invisible to every other request. Nothing is stored on the client or in module state.
|
|
310
|
+
`sessionFlags(client)` is the async variant of `flagsFor` for code that runs outside the middleware.
|
|
311
|
+
`sessionHeaders()` returns `{}` outside a session, so it is always safe to spread.
|
|
312
|
+
|
|
313
|
+
### Browser
|
|
314
|
+
|
|
315
|
+
```ts
|
|
316
|
+
await flags.useSession(token); // the nf_ts_… token your test tooling hands to the page; null leaves the session
|
|
317
|
+
fetch("/api/cart", { headers: { ...flags.sessionHeaders() } });
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
`useSession` keeps the token in `sessionStorage` (this tab, until it is closed; reloads resume it) and
|
|
321
|
+
routes the client's own accessors — and therefore the React hooks — through the session while it is
|
|
322
|
+
active. Browser keys only ever receive client-exposed flags, in sessions too. On a server
|
|
323
|
+
`useSession` is refused (one client serves many requests); use `session()` or `@nanoflags/sdk/node`.
|
|
324
|
+
|
|
325
|
+
## Persistence
|
|
326
|
+
|
|
327
|
+
- Browser: IndexedDB when available; otherwise none. Node/edge runtimes: none by default.
|
|
328
|
+
- `store` accepts any async string store (`get`/`set`), `false` disables persistence.
|
|
329
|
+
- The stored value contains the bundle (flag rules), never the SDK key. It is bound to the key and
|
|
330
|
+
`baseUrl`, so a copy written for another environment is ignored.
|
|
331
|
+
|
|
332
|
+
## Telemetry: what is sent
|
|
333
|
+
|
|
334
|
+
While evaluations are being sampled, every `flushIntervalMs` (10 s) the SDK sends one request to
|
|
335
|
+
`POST /v1/events`; while nothing is queued it sends the service report alone every
|
|
336
|
+
`reportIntervalMs` (60 s). A request carries:
|
|
337
|
+
|
|
338
|
+
- a **service report** — `{ service, sdk: "js/<version>", revision }`, and
|
|
339
|
+
- up to 50 **sampled evaluation events** (`sampleRate`, default 10 %): flag key, value, reason, rule
|
|
340
|
+
index, revision, time, and a redacted context.
|
|
341
|
+
|
|
342
|
+
**Default redaction sends no attribute values.** For each sampled event the SDK sends only the *names* of
|
|
343
|
+
the context attributes that the evaluated flag's rules reference (conditions, segments, the rollout's
|
|
344
|
+
bucketing attribute) and that were present, each mapped to the value's *type* — for example
|
|
345
|
+
`{ "region": "string", "signedIn": "boolean", "key": "string" }`. Attributes no rule uses are dropped
|
|
346
|
+
entirely. To send more (or less), provide `events.redact(ctx)`; its return value is sent as is, so
|
|
347
|
+
anything you return leaves the process. Flag *values* are sent (truncated above 1 KB); do not put secrets
|
|
348
|
+
in flag values.
|
|
349
|
+
|
|
350
|
+
Telemetry is off the evaluation path: an evaluation appends to a bounded in-memory queue (500 entries,
|
|
351
|
+
then dropped). Batches that fail to send are dropped, never retried. Disable with `events: false`.
|
|
352
|
+
|
|
353
|
+
### What a reported signal does and does not prove
|
|
354
|
+
|
|
355
|
+
- A service report proves that **a process using this SDK key, naming itself `service`, had revision N
|
|
356
|
+
loaded when it flushed**. It does not prove that every instance of the service is on that revision,
|
|
357
|
+
that the service is healthy, or that it is still running — only "last seen". A missing report proves
|
|
358
|
+
nothing either: telemetry may be disabled, blocked, sampled out, or dropped.
|
|
359
|
+
- `service` is self-declared and unauthenticated beyond the SDK key. With a browser key, anyone can
|
|
360
|
+
send reports and events. Treat them as observability, not as an audit trail.
|
|
361
|
+
- A sampled event proves that an evaluation with that result happened in some process. It does not
|
|
362
|
+
prove the user saw the feature, and absence of events does not prove a flag is unused: with the
|
|
363
|
+
default 10 % sampling, rarely evaluated flags can go unseen for a long time.
|
|
364
|
+
- Counts are estimates. Sampling is per evaluation, events are dropped under back-pressure or network
|
|
365
|
+
failure, and React components may evaluate once per relevant change rather than once per user action.
|
|
366
|
+
|
|
367
|
+
## Development
|
|
368
|
+
|
|
369
|
+
```sh
|
|
370
|
+
pnpm --filter @nanoflags/sdk test
|
|
371
|
+
pnpm --filter @nanoflags/sdk typecheck
|
|
372
|
+
pnpm --filter @nanoflags/sdk build # dist/: ESM + CJS + .d.ts/.d.cts (tsdown, engine bundled in)
|
|
373
|
+
# SDK → edge → your environment (key from the environment only; base URL defaults to https://edge.nanoflags.io)
|
|
374
|
+
NANOFLAGS_SDK_KEY=nf_srv_… pnpm --filter @nanoflags/sdk smoke
|
|
375
|
+
```
|