@flagwire/sdk-js 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,19 @@
1
+ # `@flagwire/sdk-js`
2
+
3
+ Zero-dependency browser SDK for FlagWire. Flag rules remain at the edge; the browser receives only
4
+ evaluated values.
5
+
6
+ ```ts
7
+ import { createClient } from "@flagwire/sdk-js";
8
+
9
+ const flags = createClient({
10
+ clientKey: process.env.NEXT_PUBLIC_FLAGWIRE_CLIENT_KEY!,
11
+ context: { key: "user-123", attributes: { plan: "pro" } },
12
+ });
13
+
14
+ await flags.ready();
15
+ const enabled = flags.get("checkout-redesign", false);
16
+ ```
17
+
18
+ Call `flags.close()` when the client is no longer needed. The SDK polls safely when streaming is
19
+ unavailable and validates persisted warm-cache data before use.
@@ -0,0 +1,41 @@
1
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
2
+ [key: string]: JsonValue;
3
+ };
4
+ export type ContextAttribute = string | number | boolean | string[];
5
+ export interface EvaluationContext {
6
+ key: string;
7
+ attributes?: Record<string, ContextAttribute>;
8
+ }
9
+ export interface EvaluationDetail<T extends JsonValue = JsonValue> {
10
+ flagVersion: number;
11
+ reason: string;
12
+ value: T;
13
+ variant: string | null;
14
+ }
15
+ export interface EvalSnapshot {
16
+ flags: Record<string, EvaluationDetail>;
17
+ version: number;
18
+ }
19
+ /** Augmented by flags.gen.ts. */
20
+ export interface FlagwireFlags {
21
+ }
22
+ export type FlagKey = keyof FlagwireFlags extends never ? string : Extract<keyof FlagwireFlags, string>;
23
+ export type FlagValue<K extends string, D extends JsonValue> = K extends keyof FlagwireFlags ? FlagwireFlags[K] extends JsonValue ? FlagwireFlags[K] : D : D;
24
+ export interface ClientOptions {
25
+ baseUrl?: string;
26
+ bootstrap?: EvalSnapshot;
27
+ clientKey: string;
28
+ context: EvaluationContext;
29
+ pollIntervalMs?: number;
30
+ stream?: boolean;
31
+ }
32
+ export interface FlagClient {
33
+ close(): void;
34
+ detail<K extends FlagKey>(key: K): EvaluationDetail | undefined;
35
+ flush(): Promise<void>;
36
+ get<K extends FlagKey, D extends JsonValue>(key: K, defaultValue: D): FlagValue<K, D>;
37
+ on(event: "update", listener: (changedKeys: string[]) => void): () => void;
38
+ ready(): Promise<void>;
39
+ setContext(context: EvaluationContext): Promise<void>;
40
+ }
41
+ export declare function createClient(options: ClientOptions): FlagClient;
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ var N="https://edge.flagwire.dev",P="flagwire:v1";function E(n){if(!n||typeof n!="object")return!1;let i=n;return!Number.isInteger(i.version)||(i.version??-1)<0||!i.flags||typeof i.flags!="object"||Array.isArray(i.flags)?!1:Object.values(i.flags).every(a=>a!==null&&typeof a=="object"&&Number.isInteger(a.flagVersion)&&a.flagVersion>0&&typeof a.reason=="string"&&(typeof a.variant=="string"||a.variant===null)&&"value"in a)}function C(n,i){let a=JSON.stringify(i),o=2166136261;for(let u=0;u<a.length;u+=1)o=Math.imul(o^a.charCodeAt(u),16777619);return`${P}:${n.slice(-12)}:${(o>>>0).toString(36)}`}function T(n){try{let i=JSON.parse(localStorage.getItem(n)??"null");return E(i)?i:void 0}catch{return}}function D(n,i){try{localStorage.setItem(n,JSON.stringify(i))}catch{}}function j(n){try{localStorage.removeItem(n)}catch{}}function W(n,i){return[...new Set([...Object.keys(n?.flags??{}),...Object.keys(i?.flags??{})])].filter(o=>JSON.stringify(n?.flags[o])!==JSON.stringify(i?.flags[o]))}function A(n){if(!/^pk_live_[A-Za-z0-9_-]{43}$/.test(n.clientKey))throw new Error("FlagWire browser clients require a valid pk_live_ client key");if(!n.context.key)throw new Error("FlagWire context.key cannot be empty");let i=(n.baseUrl??N).replace(/\/$/,""),a=new Set,o=new Map,u=n.context,y=C(n.clientKey,u),s=E(n.bootstrap)?n.bootstrap:T(y),p=!1,m=0,h,d,w,S=0,b=(e,r)=>{let t=W(e,r);t.length>0&&a.forEach(l=>l(t))},k=(e,r)=>fetch(`${i}${e}`,{...r,headers:{Authorization:`Bearer ${n.clientKey}`,...r.headers}}),f=()=>{if(p)return Promise.resolve();let e=m;if(h?.generation===e)return h.promise;let r=u,t=y,l=(async()=>{let c=await k("/v1/eval",{body:JSON.stringify({context:r}),headers:{"Content-Type":"application/json"},method:"POST"});if(e!==m)return;if(c.status===401||c.status===403){let I=s;s=void 0,j(t),d?.close(1008,"SDK key rejected"),b(I,void 0)}if(!c.ok)throw new Error(`FlagWire evaluation failed with HTTP ${c.status}`);let g=await c.json();if(!E(g))throw new Error("FlagWire returned an invalid evaluation snapshot");if(g.version<(s?.version??0))return;let x=s;s=g,D(t,g),b(x,g)})().finally(()=>{h?.promise===l&&(h=void 0)});return h={generation:e,promise:l},l},J=(e,r)=>{if(!r?.variant)return;let t=`${e}\0${r.flagVersion}\0${r.variant}`;o.set(t,(o.get(t)??0)+1),o.size>=100&&v().catch(()=>{})},v=async()=>{if(o.size===0)return;let e=[...o].slice(0,100);e.forEach(([t])=>o.delete(t));let r=e.map(([t,l])=>{let[c,g,x]=t.split("\0");return{count:l,flagKey:c,flagVersion:Number(g),variant:x}});try{let t=await k("/v1/events",{body:JSON.stringify(r),headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST"});if(!t.ok)throw new Error(`FlagWire event flush failed with HTTP ${t.status}`)}catch(t){throw e.forEach(([l,c])=>o.set(l,(o.get(l)??0)+c)),t}o.size>0&&await v()},F=()=>{if(p||!n.stream||typeof WebSocket>"u")return;let e=new URL(`${i}/v1/stream`);e.protocol=e.protocol==="https:"?"wss:":"ws:",e.searchParams.set("key",n.clientKey),d=new WebSocket(e),d.addEventListener("open",()=>{S=0}),d.addEventListener("message",r=>{try{let t=JSON.parse(String(r.data));t.t==="v"&&typeof t.version=="number"&&t.version>(s?.version??0)&&f().catch(()=>{})}catch{}}),d.addEventListener("close",r=>{if(d=void 0,!p&&r.code!==1008){let t=Math.min(3e4,500*2**S++);w=setTimeout(F,t)}})},O=s?Promise.resolve():f();s&&f().catch(()=>{});let $=setInterval(()=>{f().catch(()=>{})},n.pollIntervalMs??6e4),_=setInterval(()=>{v().catch(()=>{})},1e4),K=()=>{f().catch(()=>{})},V=()=>{document.visibilityState==="hidden"&&v().catch(()=>{})};return typeof window<"u"&&window.addEventListener("focus",K),typeof document<"u"&&document.addEventListener("visibilitychange",V),F(),{close(){p||(p=!0,clearInterval($),clearInterval(_),w&&clearTimeout(w),d?.close(1e3,"Client closed"),typeof window<"u"&&window.removeEventListener("focus",K),typeof document<"u"&&document.removeEventListener("visibilitychange",V),v().catch(()=>{}),a.clear())},detail(e){return s?.flags[e]},flush:v,get(e,r){let t=s?.flags[e];return J(e,t),t?.value??r},on(e,r){return e!=="update"?()=>{}:(a.add(r),()=>a.delete(r))},ready:()=>O,async setContext(e){if(!e.key)throw new Error("FlagWire context.key cannot be empty");let r=C(n.clientKey,e);if(r===y){u=e,await f();return}let t=s;m+=1,u=e,y=r,s=T(y),b(t,s),await f()}}}export{A as createClient};
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@flagwire/sdk-js",
3
+ "version": "0.1.0",
4
+ "description": "Zero-dependency browser 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
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/flagwire/flagwire-js.git",
22
+ "directory": "packages/sdk-js"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public",
26
+ "provenance": true
27
+ },
28
+ "devDependencies": {
29
+ "@size-limit/file": "13.0.3",
30
+ "esbuild": "0.28.2",
31
+ "size-limit": "13.0.3"
32
+ },
33
+ "size-limit": [
34
+ {
35
+ "gzip": true,
36
+ "path": "dist/index.js",
37
+ "limit": "3 kB"
38
+ }
39
+ ],
40
+ "scripts": {
41
+ "build": "node ../../scripts/clean-package-dist.mjs && tsc -p tsconfig.build.json && esbuild src/index.ts --bundle --minify --format=esm --platform=browser --target=es2022 --outfile=dist/index.js",
42
+ "lint": "eslint src",
43
+ "size": "size-limit",
44
+ "test": "vitest run && size-limit",
45
+ "typecheck": "tsc -p tsconfig.json --noEmit"
46
+ }
47
+ }