@flagwire/sdk-node 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FlagWire contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,15 @@
1
+ # `@flagwire/sdk-node`
2
+
3
+ Node.js SDK for deterministic local FlagWire evaluation. Bundles are fetched with ETags and kept
4
+ fresh through polling with optional streaming notifications.
5
+
6
+ ```ts
7
+ import { createServerClient } from "@flagwire/sdk-node";
8
+
9
+ const flags = createServerClient({ serverKey: process.env.FLAGWIRE_SERVER_KEY! });
10
+ await flags.waitForInitialization({ timeoutMs: 5_000 });
11
+
12
+ const enabled = flags.evaluate("checkout-redesign", { key: "user-123" }, false);
13
+ ```
14
+
15
+ Call `await flags.close()` during graceful shutdown. Never expose a server key to a browser.
@@ -0,0 +1,25 @@
1
+ import { type EvaluationDetail, type EvaluationReason } from "@flagwire/evaluate";
2
+ import { type EvaluationContext, type JsonValue } from "@flagwire/schema";
3
+ export type { EvaluationContext, EvaluationDetail, EvaluationReason, JsonValue };
4
+ /** Augmented by flags.gen.ts. */
5
+ export interface FlagwireFlags {
6
+ }
7
+ export type FlagKey = keyof FlagwireFlags extends never ? string : Extract<keyof FlagwireFlags, string>;
8
+ export type FlagValue<K extends string, D extends JsonValue> = K extends keyof FlagwireFlags ? FlagwireFlags[K] extends JsonValue ? FlagwireFlags[K] : D : D;
9
+ export interface ServerClientOptions {
10
+ baseUrl?: string;
11
+ pollIntervalMs?: number;
12
+ serverKey: string;
13
+ stream?: boolean;
14
+ }
15
+ export interface ServerClient {
16
+ allFlags(context: EvaluationContext): Record<string, JsonValue>;
17
+ close(): Promise<void>;
18
+ evaluate<K extends FlagKey, D extends JsonValue>(key: K, context: EvaluationContext, defaultValue: D): FlagValue<K, D>;
19
+ evaluateDetail<K extends FlagKey, D extends JsonValue>(key: K, context: EvaluationContext, defaultValue: D): EvaluationDetail;
20
+ flush(): Promise<void>;
21
+ waitForInitialization(options?: {
22
+ timeoutMs?: number;
23
+ }): Promise<void>;
24
+ }
25
+ export declare function createServerClient(options: ServerClientOptions): ServerClient;
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import{evaluateBundle as z,evaluateFlag as J}from"@flagwire/evaluate";import{bundleSchema as _}from"@flagwire/schema";var I="https://edge.flagwire.dev",O=3e5;function E(a){let o=a;if(typeof o!="object"||o===null||!("unref"in o))return;let g=o.unref;typeof g=="function"&&g.call(o)}function W(a){return{reason:"ERROR",value:a,variantKey:null}}function B(a){if(!/^sk_live_[A-Za-z0-9_-]{43}$/.test(a.serverKey))throw new Error("FlagWire server clients require a valid sk_live_ server key");let o=(a.baseUrl??I).replace(/\/$/,""),g=Math.max(1e3,a.pollIntervalMs??3e4),s=new Map,i,m,l=!1,d=!1,w=!1,u,c,p,y,T=0,f,F=!1,b,K=new Promise(e=>{b=e}),k=(e,t={})=>fetch(`${o}${e}`,{...t,headers:{Authorization:`Bearer ${a.serverKey}`,...t.headers}}),D=()=>{if(l)return;c&&clearTimeout(c);let e=i?.revoked||d||w?O:g;c=setTimeout(()=>{h().catch(()=>{})},e),E(c)},h=()=>l?Promise.resolve():f||(f=(async()=>{let e={};m&&(e["If-None-Match"]=m);let t=await k("/v1/bundle",{headers:e});if(t.status===304){d=!1;return}if(t.status===401||t.status===403){i=void 0,m=void 0,d=!0,u?.close(1008,"SDK key rejected");return}if(!t.ok)throw new Error(`FlagWire bundle fetch failed with HTTP ${t.status}`);let n=await t.json(),r=_.safeParse(n);if(!r.success)throw new Error("FlagWire returned an invalid environment bundle");r.data.version<(i?.version??0)||(i=r.data,m=t.headers.get("ETag")??`"v${r.data.version}"`,d=!1,F||(F=!0,b?.()))})().finally(()=>{f=void 0,D()}),f),P=(e,t)=>{let n=i?.flags[e]?.version;if(!n||!t.variantKey)return;let r=`${e}\0${n}\0${t.variantKey}`;s.set(r,(s.get(r)??0)+1),s.size>=100&&v().catch(()=>{})},v=async()=>{if(s.size===0)return;let e=[...s].slice(0,100);e.forEach(([n])=>s.delete(n));let t=e.map(([n,r])=>{let[x,R,$]=n.split("\0");return{count:r,flagKey:x,flagVersion:Number(R),variant:$}});try{let n=await k("/v1/events",{body:JSON.stringify(t),headers:{"Content-Type":"application/json"},method:"POST"});if(!n.ok)throw new Error(`FlagWire event flush failed with HTTP ${n.status}`)}catch(n){throw e.forEach(([r,x])=>s.set(r,(s.get(r)??0)+x)),n}s.size>0&&await v()},V=()=>{l||(p=setTimeout(()=>{v().catch(()=>{}).finally(V)},1e4),E(p))},S=()=>{if(l||a.stream===!1||typeof WebSocket>"u"||d)return;let e=new URL(`${o}/v1/stream`);e.protocol=e.protocol==="https:"?"wss:":"ws:",e.searchParams.set("key",a.serverKey),u=new WebSocket(e),u.addEventListener("open",()=>{w=!0,T=0,h().catch(()=>{})}),u.addEventListener("message",t=>{try{let n=JSON.parse(String(t.data));n.t==="v"&&typeof n.version=="number"&&n.version>(i?.version??0)&&h().catch(()=>{})}catch{}}),u.addEventListener("close",()=>{if(u=void 0,w=!1,D(),!l&&!d){let t=Math.min(3e4,500*2**T++);y=setTimeout(S,t),E(y)}})};h().catch(()=>{}),V(),S();let C=(e,t,n)=>{let r=i?J(i,e,t,n):W(n);return P(e,r),r};return{allFlags(e){if(!i)return{};let t=z(i,e);return Object.fromEntries(Object.entries(t.flags).map(([n,r])=>(P(n,r),[n,r.value])))},async close(){l||(l=!0,c&&clearTimeout(c),p&&clearTimeout(p),y&&clearTimeout(y),u?.close(1e3,"Client closed"),await v())},evaluate(e,t,n){return C(e,t,n).value},evaluateDetail:C,flush:v,waitForInitialization({timeoutMs:e}={}){return F?Promise.resolve():e===void 0?K:!Number.isFinite(e)||e<=0?Promise.reject(new Error("timeoutMs must be a positive finite number")):new Promise((t,n)=>{let r=setTimeout(()=>n(new Error(`FlagWire initialization timed out after ${e}ms`)),e);K.then(()=>{clearTimeout(r),t()})})}}}export{B as createServerClient};
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@flagwire/sdk-node",
3
+ "version": "0.1.0",
4
+ "description": "Local-evaluation Node.js SDK for FlagWire feature flags",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ }
15
+ },
16
+ "types": "./dist/index.d.ts",
17
+ "module": "./dist/index.js",
18
+ "sideEffects": false,
19
+ "engines": {
20
+ "node": ">=22.4.0"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/flagwire/flagwire-js.git",
25
+ "directory": "packages/sdk-node"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public",
29
+ "provenance": true
30
+ },
31
+ "dependencies": {
32
+ "@flagwire/schema": "0.1.0",
33
+ "@flagwire/evaluate": "0.1.0"
34
+ },
35
+ "devDependencies": {
36
+ "esbuild": "0.28.2"
37
+ },
38
+ "scripts": {
39
+ "build": "node ../../scripts/clean-package-dist.mjs && tsc -p tsconfig.build.json && esbuild src/index.ts --bundle --minify --format=esm --platform=node --target=node22 --external:@flagwire/evaluate --external:@flagwire/schema --outfile=dist/index.js",
40
+ "lint": "eslint src",
41
+ "test": "vitest run",
42
+ "typecheck": "tsc -p tsconfig.json --noEmit"
43
+ }
44
+ }