From 73aefb30343d183714c4ab9555c6c9790fbbc8b0 Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:23:37 +0000 Subject: [PATCH 01/18] docs: add v2 SDK pages with linked legacy v1 archive --- .generated/sdk-docs/browser-sdk/v1.json | 11 + .generated/sdk-docs/browser-sdk/v2.json | 14 + .generated/sdk-docs/node-sdk/v1.json | 12 + .generated/sdk-docs/node-sdk/v2.json | 12 + .generated/sdk-docs/react-native-sdk/v0.json | 13 + .generated/sdk-docs/react-sdk/v1.json | 10 + .generated/sdk-docs/react-sdk/v2.json | 13 + .generated/sdk-docs/vue-sdk/v1.json | 10 + .generated/sdk-docs/vue-sdk/v2.json | 12 + .gitattributes | 9 + .github/README.md | 16 + .github/scripts/check-sdk-docs.mjs | 200 + .github/scripts/check-sdk-examples.cjs | 131 + .github/scripts/sdk-docs.mjs | 307 + .github/scripts/sdk-docs.test.mjs | 235 + .github/workflows/sdk-docs.yml | 112 + README.md | 34 +- SUMMARY.md | 14 + guides/self-opt-in.md | 12 +- guides/toggle-toolbar-with-a-flag.md | 45 +- guides/use-reflag-in-your-cli.md | 120 +- legacy/v1/README.md | 34 + legacy/v1/_media/type-check-failed.png | Bin 0 -> 105925 bytes .../v1/_media/type-check-payload-failed.png | Bin 0 -> 69185 bytes legacy/v1/browser-sdk/README.md | 615 ++ legacy/v1/browser-sdk/feedback.md | 479 ++ legacy/v1/browser-sdk/globals.md | 5250 ++++++++++++++ legacy/v1/node-sdk/README.md | 1155 +++ legacy/v1/node-sdk/globals.md | 6457 +++++++++++++++++ legacy/v1/react-sdk/README.md | 984 +++ legacy/v1/react-sdk/globals.md | 2326 ++++++ legacy/v1/vue-sdk/README.md | 712 ++ legacy/v1/vue-sdk/globals.md | 1899 +++++ product-handbook/anonymous-users.md | 73 +- .../ai-code-clean-up-beta.md | 26 +- .../feature-entitlements/README.md | 42 +- .../simple-role-based-entitlements.md | 2 +- product-handbook/launch-monitor/README.md | 32 +- .../launch-monitor/give-feedback-button.md | 33 +- product-handbook/remote-config.md | 113 +- product-handbook/service-resiliency.md | 19 +- product-handbook/type-safety.md | 93 +- sdk/@reflag/browser-sdk/README.md | 630 +- sdk/@reflag/browser-sdk/globals.md | 1206 +-- sdk/@reflag/node-sdk/README.md | 1163 +-- sdk/@reflag/node-sdk/globals.md | 3270 +++------ sdk/@reflag/react-native-sdk/README.md | 14 +- sdk/@reflag/react-native-sdk/globals.md | 98 +- sdk/@reflag/react-sdk/README.md | 979 +-- sdk/@reflag/react-sdk/globals.md | 1491 ++-- sdk/@reflag/vue-sdk/README.md | 704 +- sdk/@reflag/vue-sdk/globals.md | 550 +- sdk/documents/browser-sdk/FEEDBACK.md | 14 +- sdk/documents/react-native-sdk/README.md | 14 +- sdk/documents/react-sdk/README.md | 979 +-- supported-languages/browser-sdk/README.md | 638 +- supported-languages/browser-sdk/feedback.md | 14 +- supported-languages/browser-sdk/globals.md | 1120 +-- supported-languages/migrating-from-v1.md | 117 + supported-languages/next.js.md | 175 +- supported-languages/node-sdk/README.md | 1095 +-- supported-languages/node-sdk/globals.md | 3162 +++----- supported-languages/overview.md | 4 + .../react-native-sdk/README.md | 54 +- .../react-native-sdk/globals.md | 1728 ++++- supported-languages/react-sdk/README.md | 979 +-- supported-languages/react-sdk/globals.md | 2072 +++++- supported-languages/vue-sdk/README.md | 704 +- supported-languages/vue-sdk/globals.md | 512 +- 69 files changed, 30584 insertions(+), 14588 deletions(-) create mode 100644 .generated/sdk-docs/browser-sdk/v1.json create mode 100644 .generated/sdk-docs/browser-sdk/v2.json create mode 100644 .generated/sdk-docs/node-sdk/v1.json create mode 100644 .generated/sdk-docs/node-sdk/v2.json create mode 100644 .generated/sdk-docs/react-native-sdk/v0.json create mode 100644 .generated/sdk-docs/react-sdk/v1.json create mode 100644 .generated/sdk-docs/react-sdk/v2.json create mode 100644 .generated/sdk-docs/vue-sdk/v1.json create mode 100644 .generated/sdk-docs/vue-sdk/v2.json create mode 100644 .gitattributes create mode 100644 .github/scripts/check-sdk-docs.mjs create mode 100644 .github/scripts/check-sdk-examples.cjs create mode 100644 .github/scripts/sdk-docs.mjs create mode 100644 .github/scripts/sdk-docs.test.mjs create mode 100644 .github/workflows/sdk-docs.yml create mode 100644 legacy/v1/README.md create mode 100644 legacy/v1/_media/type-check-failed.png create mode 100644 legacy/v1/_media/type-check-payload-failed.png create mode 100644 legacy/v1/browser-sdk/README.md create mode 100644 legacy/v1/browser-sdk/feedback.md create mode 100644 legacy/v1/browser-sdk/globals.md create mode 100644 legacy/v1/node-sdk/README.md create mode 100644 legacy/v1/node-sdk/globals.md create mode 100644 legacy/v1/react-sdk/README.md create mode 100644 legacy/v1/react-sdk/globals.md create mode 100644 legacy/v1/vue-sdk/README.md create mode 100644 legacy/v1/vue-sdk/globals.md create mode 100644 supported-languages/migrating-from-v1.md diff --git a/.generated/sdk-docs/browser-sdk/v1.json b/.generated/sdk-docs/browser-sdk/v1.json new file mode 100644 index 0000000..1881b05 --- /dev/null +++ b/.generated/sdk-docs/browser-sdk/v1.json @@ -0,0 +1,11 @@ +{ + "sourceRepository": "https://github.com/reflagcom/javascript", + "sourceCommit": "b4fe5b3d9386b87c6546175c323862d9878e1430", + "package": "@reflag/browser-sdk", + "version": "1.7.4", + "files": { + "legacy/v1/browser-sdk/README.md": "b949d2d5c5d9f2eb4bca99c97d6fad63d95d6ba03592bdb01dc9c632d854fea2", + "legacy/v1/browser-sdk/globals.md": "a45fb2bb4784310a826b109bf9e361bcb552974791ee9f142514353eb8da0600", + "legacy/v1/browser-sdk/feedback.md": "f2507ea56bbef40b7acafed1f05d55261905e68aa2a8097eee48e348cecc0177" + } +} diff --git a/.generated/sdk-docs/browser-sdk/v2.json b/.generated/sdk-docs/browser-sdk/v2.json new file mode 100644 index 0000000..ed9147e --- /dev/null +++ b/.generated/sdk-docs/browser-sdk/v2.json @@ -0,0 +1,14 @@ +{ + "sourceRepository": "https://github.com/reflagcom/javascript", + "sourceCommit": "9f3a0ae027e386747a2d4cf7683a68dcab70b355", + "package": "@reflag/browser-sdk", + "version": "2.0.0-next.0", + "files": { + "supported-languages/browser-sdk/README.md": "ec01a2b277092690794f16ac8c50658633985e8b2157b87af6efae1ca0843a25", + "sdk/@reflag/browser-sdk/README.md": "af928c7dfac25302f70d5bde6082b3029ccf62f6ef3194c853579190e8d8a257", + "supported-languages/browser-sdk/globals.md": "13ca9d9b3e51933e730e1ae37c969d94d0af8b75d766b3ca8e1d3c04b7013d27", + "sdk/@reflag/browser-sdk/globals.md": "8d802a419e6abb9233bd74552a36a9ed8bda9785b9d193bb5f9da61cab796723", + "supported-languages/browser-sdk/feedback.md": "c0d799195022b39cd0b12a12c39ec7728d8dc40c5b4874f01934177e15daffa5", + "sdk/documents/browser-sdk/FEEDBACK.md": "9607d6e90d45158106fead43881f5cb8450f692b7fdb02e609e32fafcb8acf3a" + } +} diff --git a/.generated/sdk-docs/node-sdk/v1.json b/.generated/sdk-docs/node-sdk/v1.json new file mode 100644 index 0000000..61858d4 --- /dev/null +++ b/.generated/sdk-docs/node-sdk/v1.json @@ -0,0 +1,12 @@ +{ + "sourceRepository": "https://github.com/reflagcom/javascript", + "sourceCommit": "b4fe5b3d9386b87c6546175c323862d9878e1430", + "package": "@reflag/node-sdk", + "version": "1.8.3", + "files": { + "legacy/v1/_media/type-check-failed.png": "f04547c0bf0425bcf554aa1a1dddec56096ca9967d120bdca7737562327d4db8", + "legacy/v1/_media/type-check-payload-failed.png": "8b53c24ecd19288111bda14eab7c490f7e26abba569eea11e16504cc7abeb54a", + "legacy/v1/node-sdk/README.md": "a5cdfc5e190f99930970ada4e8bf84cd448c318143b17853db4e0655f01450be", + "legacy/v1/node-sdk/globals.md": "16458989c24ed3d4762d969dd2a1f827c2600fc82ad13e8280cc5d8ab01ae4d2" + } +} diff --git a/.generated/sdk-docs/node-sdk/v2.json b/.generated/sdk-docs/node-sdk/v2.json new file mode 100644 index 0000000..ae3b4bb --- /dev/null +++ b/.generated/sdk-docs/node-sdk/v2.json @@ -0,0 +1,12 @@ +{ + "sourceRepository": "https://github.com/reflagcom/javascript", + "sourceCommit": "0809be2b95f43fa1785c6b7b188c03ac8fd40965", + "package": "@reflag/node-sdk", + "version": "2.0.0-next.0", + "files": { + "supported-languages/node-sdk/README.md": "b834d55e0e66ea4fa3a2f726f4b3d5f2ae7ea91a22456cf8d2db60c358ad9a45", + "sdk/@reflag/node-sdk/README.md": "27d170717e75d99eb8e10fbbedf17c84cd1e8fffd95c655fd3fe60780bea222d", + "supported-languages/node-sdk/globals.md": "1bab9869b7a1779fc7a5e25ec076f7fbeecd11a3703c8b8e26fcf6184887cf75", + "sdk/@reflag/node-sdk/globals.md": "2c92c66aa42ccdadfae1bad027f42a240379227f71764d04205d4483e519ccb7" + } +} diff --git a/.generated/sdk-docs/react-native-sdk/v0.json b/.generated/sdk-docs/react-native-sdk/v0.json new file mode 100644 index 0000000..752ea8c --- /dev/null +++ b/.generated/sdk-docs/react-native-sdk/v0.json @@ -0,0 +1,13 @@ +{ + "sourceRepository": "https://github.com/reflagcom/javascript", + "sourceCommit": "b4fe5b3d9386b87c6546175c323862d9878e1430", + "package": "@reflag/react-native-sdk", + "version": "0.3.7", + "files": { + "supported-languages/react-native-sdk/README.md": "0a9952a6a72c21c6c5baec486671c968e3b290752dbc18a6239a4d3aa4325195", + "sdk/@reflag/react-native-sdk/README.md": "360b297aeb72f6ac7accf9f16707437eb4c01ebd060f5f56870764c2f6fa0ad9", + "sdk/documents/react-native-sdk/README.md": "360b297aeb72f6ac7accf9f16707437eb4c01ebd060f5f56870764c2f6fa0ad9", + "supported-languages/react-native-sdk/globals.md": "b7cd9cc4f5bece6e701fcae3ece028e2ce7588d0a3fbb6f170c69b01eac18ac3", + "sdk/@reflag/react-native-sdk/globals.md": "d028c5ff2ad94e2ae670aea1ff159786cc9f117e674af510ee625b1d6e9f7205" + } +} diff --git a/.generated/sdk-docs/react-sdk/v1.json b/.generated/sdk-docs/react-sdk/v1.json new file mode 100644 index 0000000..c2da38f --- /dev/null +++ b/.generated/sdk-docs/react-sdk/v1.json @@ -0,0 +1,10 @@ +{ + "sourceRepository": "https://github.com/reflagcom/javascript", + "sourceCommit": "b4fe5b3d9386b87c6546175c323862d9878e1430", + "package": "@reflag/react-sdk", + "version": "1.7.4", + "files": { + "legacy/v1/react-sdk/README.md": "d0f7ae8c094dfef0064ed19c5f6f78b74bc876f321b7b92b9c47b9d9db12e79a", + "legacy/v1/react-sdk/globals.md": "fb761c2ca1208bc90cd08eea64c0167ea63e84a19d02d7a9497694505ae2dc36" + } +} diff --git a/.generated/sdk-docs/react-sdk/v2.json b/.generated/sdk-docs/react-sdk/v2.json new file mode 100644 index 0000000..55d99db --- /dev/null +++ b/.generated/sdk-docs/react-sdk/v2.json @@ -0,0 +1,13 @@ +{ + "sourceRepository": "https://github.com/reflagcom/javascript", + "sourceCommit": "9f3a0ae027e386747a2d4cf7683a68dcab70b355", + "package": "@reflag/react-sdk", + "version": "2.0.0-next.0", + "files": { + "supported-languages/react-sdk/README.md": "895ea9b16b4e6a3775bb5813abf472b631aa778341b1be35b2221ce1112a60d9", + "sdk/@reflag/react-sdk/README.md": "0a170cf33a8bff4df2daed6b086a1c919da72c605532d2917d52a293223289d5", + "sdk/documents/react-sdk/README.md": "0a170cf33a8bff4df2daed6b086a1c919da72c605532d2917d52a293223289d5", + "supported-languages/react-sdk/globals.md": "0c3eec56a80b4080882308794b01ae041f53713aed83ac75a9a8a9e7d786c6ce", + "sdk/@reflag/react-sdk/globals.md": "6dbfd4e00a45765c20fadb1594b3279c1279264eb021afdc83543af67a8813ae" + } +} diff --git a/.generated/sdk-docs/vue-sdk/v1.json b/.generated/sdk-docs/vue-sdk/v1.json new file mode 100644 index 0000000..e95d45c --- /dev/null +++ b/.generated/sdk-docs/vue-sdk/v1.json @@ -0,0 +1,10 @@ +{ + "sourceRepository": "https://github.com/reflagcom/javascript", + "sourceCommit": "b4fe5b3d9386b87c6546175c323862d9878e1430", + "package": "@reflag/vue-sdk", + "version": "1.5.7", + "files": { + "legacy/v1/vue-sdk/README.md": "64a47b3fa4fd104f19fd14250e34438a00c5b5c0474573d68fb7af0aa40442ce", + "legacy/v1/vue-sdk/globals.md": "c6053f46cef5bce2882434cbeb1003d0f08f35147f5d98eb7d8276e572c831bb" + } +} diff --git a/.generated/sdk-docs/vue-sdk/v2.json b/.generated/sdk-docs/vue-sdk/v2.json new file mode 100644 index 0000000..0aebd22 --- /dev/null +++ b/.generated/sdk-docs/vue-sdk/v2.json @@ -0,0 +1,12 @@ +{ + "sourceRepository": "https://github.com/reflagcom/javascript", + "sourceCommit": "9f3a0ae027e386747a2d4cf7683a68dcab70b355", + "package": "@reflag/vue-sdk", + "version": "2.0.0-next.0", + "files": { + "supported-languages/vue-sdk/README.md": "58d538146d48b8d90d3a0dbc8836471bb621d72d2706e59cb3bae405bf06bb3d", + "sdk/@reflag/vue-sdk/README.md": "bd5f7130b3e920f6affa13a67d54c42664fce7d79fb394b7b88aa7c7f25f6d1e", + "supported-languages/vue-sdk/globals.md": "51f74d439a28e1c05c0fdfbbefcea2c85f04b75b6f4c6fb7f82e900bbb21663c", + "sdk/@reflag/vue-sdk/globals.md": "acfe7ac37c8599236c8e8a1daabe06eec7dfba179e34d00885a7a1545e443d4b" + } +} diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..08038a7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# Generated SDK copies; authoritative READMEs/comments live in reflagcom/javascript. +sdk/** linguist-generated=true +supported-languages/browser-sdk/** linguist-generated=true +supported-languages/react-sdk/** linguist-generated=true +supported-languages/vue-sdk/** linguist-generated=true +supported-languages/node-sdk/** linguist-generated=true +supported-languages/react-native-sdk/** linguist-generated=true +legacy/v1/*-sdk/** linguist-generated=true +.generated/** linguist-generated=true diff --git a/.github/README.md b/.github/README.md index bf0ec1c..556e903 100644 --- a/.github/README.md +++ b/.github/README.md @@ -17,6 +17,22 @@ Reflag is built to work at the company/organization level right out of the box, This repository syncs the documentation to [docs.reflag.com](https://docs.reflag.com). For SDK docs, please go to the [javascript repository](https://github.com/reflagcom/javascript) repository. +## SDK documentation ownership + +SDK READMEs and source comments are maintained in `reflagcom/javascript`. Current Browser/React/Vue/Node pages are generated into `supported-languages/`; protocol-v1 pages live in `legacy/v1/`. Do not hand-edit their generated bodies. Source/version and file hashes are recorded in `.generated/sdk-docs/`. + +Generate one SDK from an explicitly selected, clean source checkout after building declarations and running its canonical `docs.sh`: + +```sh +node .github/scripts/sdk-docs.mjs import --source /path/to/built/javascript --package react-sdk +node .github/scripts/check-sdk-docs.mjs +node --test .github/scripts/sdk-docs.test.mjs +``` + +The importer derives the destination from the package major, preserves historical SDK aliases, and never deletes a tree or overwrites navigation, migration guidance or GitBook settings. Release automation uses the `release` subcommand with an exact tagged-source plan; prereleases do not promote stable documentation automatically. The SDK documentation workflow rebuilds the source commits listed in the manifests and checks representative examples against matching declarations. + +This is ordinary page-based navigation. No GitBook variants or additional published spaces are required. + ## Quick links - Ready to get started? [Follow the guide](https://docs.reflag.com/) diff --git a/.github/scripts/check-sdk-docs.mjs b/.github/scripts/check-sdk-docs.mjs new file mode 100644 index 0000000..8ccc120 --- /dev/null +++ b/.github/scripts/check-sdk-docs.mjs @@ -0,0 +1,200 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { docsPath, hash, webSDKs, documentedPackages } from "./sdk-docs.mjs"; + +export const root = path.resolve(fileURLToPath(new URL("../../", import.meta.url))); +const read = (base, file) => fs.readFileSync(path.join(base, file), "utf8"); +export const prose = (content) => content.replace(/```[^\n]*\n[\s\S]*?```/g, ""); +export const links = (content) => + [ + ...prose(content).matchAll( + /\[[^\]]*\]\(([^\s)]+)(?:\s+"[^"]*")?\)|(?:src|href)=["']([^"']+)["']/g, + ), + ].map((match) => match[1] ?? match[2]); +const slug = (text) => + text + .toLowerCase() + .replace(/<\/?(?:a|code|strong|em|span|br)(?:\s[^>]*)?>/g, "") + .replace(/[^\p{L}\p{N}_ -]/gu, "") + .replace(/ /g, "-"); + +export function anchors(content) { + const ids = new Set(); + for (const match of prose(content).matchAll(/\bid=["']([^"']+)["']/g)) ids.add(match[1]); + const headingIDs = new Set(); + for (const match of prose(content).matchAll(/^#{1,6} (.+)$/gm)) { + const base = slug(match[1]); + let id = base; + for (let suffix = 1; headingIDs.has(id); suffix++) id = `${base}-${suffix}`; + headingIDs.add(id); + ids.add(id); + } + return ids; +} + +function resolveLink(base, file, href) { + const [pathname, fragment] = href.split("#"); + let target = path.resolve( + base, + path.dirname(file), + decodeURIComponent(pathname || path.basename(file)), + ); + assert(target.startsWith(`${base}${path.sep}`), `Link escapes repository: ${file} -> ${href}`); + if (fs.existsSync(target) && fs.statSync(target).isDirectory()) + target = path.join(target, "README.md"); + return { target, fragment }; +} + +export function checkLinks(base, pages) { + const errors = []; + for (const file of pages) { + for (const href of links(read(base, file))) { + if (/^(?:[a-z][a-z\d+.-]*:|\/|\{)/i.test(href)) continue; + try { + const { target, fragment } = resolveLink(base, file, href); + assert(fs.existsSync(target), `Missing file: ${file} -> ${href}`); + if (fragment && target.endsWith(".md")) + assert( + anchors(fs.readFileSync(target, "utf8")).has(decodeURIComponent(fragment)), + `Missing anchor: ${file} -> ${href}`, + ); + } catch (error) { + errors.push(error.message); + } + } + } + assert.equal(errors.length, 0, errors.join("\n")); +} + +export function sourceMatrix(base = root) { + const commits = new Map(); + for (const name of fs.readdirSync(path.join(base, ".generated/sdk-docs"))) { + assert(documentedPackages.includes(name), `Unknown generated owner: ${name}`); + for (const filename of fs.readdirSync(path.join(base, ".generated/sdk-docs", name))) { + const manifest = JSON.parse(read(base, `.generated/sdk-docs/${name}/${filename}`)); + assert(/^[a-f\d]{40}$/.test(manifest.sourceCommit), "Invalid SDK source ref"); + const packages = commits.get(manifest.sourceCommit) ?? new Set(); + packages.add(name); + commits.set(manifest.sourceCommit, packages); + } + } + return { + include: [...commits].map(([ref, packages]) => ({ + ref, + packages: [...packages] + .sort() + .map((name) => `--package ${name}`) + .join(" "), + })), + }; +} + +export function checkSDKDocs(base = root) { + const summary = read(base, "SUMMARY.md"); + const navigation = links(summary).filter((href) => !/^[a-z][a-z\d+.-]*:/i.test(href)); + assert.equal(new Set(navigation).size, navigation.length, "Duplicate navigation entry"); + const generated = new Set(); + const owners = new Map(); + for (const name of fs.readdirSync(path.join(base, ".generated/sdk-docs"))) { + for (const filename of fs.readdirSync(path.join(base, ".generated/sdk-docs", name))) { + const manifest = JSON.parse(read(base, `.generated/sdk-docs/${name}/${filename}`)); + assert.equal(manifest.package, `@reflag/${name}`); + assert(/^[a-f\d]{40}$/.test(manifest.sourceCommit), "Missing exact source commit"); + for (const [file, expected] of Object.entries(manifest.files)) { + const actual = hash(fs.readFileSync(path.join(base, file))); + assert.equal(actual, expected, `Generated file drift: ${file}`); + assert(!owners.has(file) || owners.get(file) === actual, `Conflicting ownership: ${file}`); + owners.set(file, actual); + if (file.endsWith(".md")) generated.add(file); + } + } + } + for (const major of [1, 2]) + for (const name of webSDKs) { + for (const filename of [ + "README.md", + "globals.md", + ...(name === "browser-sdk" ? ["feedback.md"] : []), + ]) { + const file = docsPath(name, major, filename); + assert(navigation.includes(file), `SDK page missing from navigation: ${file}`); + assert(generated.has(file), `SDK page has no source manifest: ${file}`); + const content = read(base, file); + const counterpart = docsPath(name, major === 1 ? 2 : 1, filename); + assert( + links(content).some((href) => { + if (/^(?:[a-z][a-z\d+.-]*:|\/)/i.test(href)) return false; + return path.relative(base, resolveLink(base, file, href).target) === counterpart; + }), + `Missing equivalent-version link: ${file}`, + ); + assert(content.includes(major === 1 ? "Protocol v1 — legacy" : "Protocol v2")); + if (major === 1) { + assert( + !/cdn\.jsdelivr\.net\/npm\/@reflag\/browser-sdk@(?!1\b)/.test(content), + "Legacy CDN must target v1", + ); + for (const line of content.split("\n")) + if (/^\s*(?:npm (?:i|install)|yarn add|pnpm add|bun add|deno add|npx)\b/.test(line)) { + for (const match of line.matchAll( + /@reflag\/(?:node-sdk|browser-sdk|react-sdk|vue-sdk|cli)(?:@([^\s]+))?/g, + )) + assert.equal(match[1], "1", `Unpinned legacy install: ${file}: ${line}`); + } + } + } + } + const shared = navigation.filter( + (file) => + !generated.has(file) && + !file.startsWith("legacy/") && + !file.startsWith("api/") && + !file.endsWith("globals.md") && + !file.includes("react-native-sdk") && + file !== "supported-languages/migrating-from-v1.md", + ); + for (const file of shared) { + const content = read(base, file); + assert( + !/\{\s*(?:isEnabled|config\s*:)[^\n]*\}\s*=\s*(?:useFlag|.*\.getFlag)\(/.test(content), + `Legacy wrapper in shared example: ${file}`, + ); + assert(!content.includes("../sdk/v2/"), `Obsolete SDK preview link: ${file}`); + } + // Existing unrelated handbook anchors are not a gate for generated SDK output. + // New SDK links, migration/overview links and all navigation must resolve. + checkLinks(base, [ + "SUMMARY.md", + ...generated, + "legacy/v1/README.md", + "supported-languages/migrating-from-v1.md", + "supported-languages/overview.md", + ...shared.filter((file) => + [ + "README.md", + "supported-languages/next.js.md", + "product-handbook/service-resiliency.md", + "product-handbook/type-safety.md", + ].includes(file), + ), + ]); + return { generatedPages: generated.size, navigationPages: navigation.length }; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { + console.log(JSON.stringify(checkSDKDocs(), null, 2)); + if (process.argv.includes("--sources")) { + const outputs = { + matrix: JSON.stringify(sourceMatrix()), + react_v1_ref: JSON.parse(read(root, ".generated/sdk-docs/react-sdk/v1.json")).sourceCommit, + react_v2_ref: JSON.parse(read(root, ".generated/sdk-docs/react-sdk/v2.json")).sourceCommit, + node_v2_ref: JSON.parse(read(root, ".generated/sdk-docs/node-sdk/v2.json")).sourceCommit, + }; + if (process.env.GITHUB_OUTPUT) + for (const [key, value] of Object.entries(outputs)) + fs.appendFileSync(process.env.GITHUB_OUTPUT, `${key}=${value}\n`); + console.log(JSON.stringify(outputs, null, 2)); + } +} diff --git a/.github/scripts/check-sdk-examples.cjs b/.github/scripts/check-sdk-examples.cjs new file mode 100644 index 0000000..8e462db --- /dev/null +++ b/.github/scripts/check-sdk-examples.cjs @@ -0,0 +1,131 @@ +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { createRequire } = require("node:module"); + +const [frameworkRoot, nodeRoot, legacyRoot] = process.argv + .slice(2) + .map((root) => path.resolve(root)); +assert( + frameworkRoot && nodeRoot && legacyRoot, + "Pass built framework-v2, node-v2 and v1 source directories", +); +const root = path.resolve(__dirname, "../.."); +const sdkRequire = createRequire(path.join(frameworkRoot, "package.json")); +const ts = sdkRequire("typescript"); +const reactTypes = path.dirname(sdkRequire.resolve("@types/react/package.json")); +const nodeTypes = path.dirname(sdkRequire.resolve("@types/node/package.json")); +const temp = fs.mkdtempSync(path.join(os.tmpdir(), "reflag-sdk-doc-examples-")); +let snippets = 0; +function declaration(base, name) { + const dir = path.join(base, "packages", name); + const pkg = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8")); + const file = path.join(dir, pkg.types); + assert(fs.existsSync(file), `Build declarations first: ${file}`); + return file; +} +function blocks(file) { + return [ + ...fs + .readFileSync(path.join(root, file), "utf8") + .matchAll(/```(?:tsx|jsx|typescript|ts)\r?\n([\s\S]*?)```/g), + ].map((match) => match[1]); +} +function compile(label, code, legacy = false, extra = {}) { + const dir = path.join(temp, `${snippets++}`); + fs.mkdirSync(dir); + const file = path.join(dir, "example.tsx"); + const globals = path.join(dir, "globals.d.ts"); + fs.writeFileSync(file, code); + fs.writeFileSync( + globals, + `declare module "your-component-library" { export const Spinner: import("react").FC>; }\n`, + ); + const paths = { + "@reflag/react-sdk": [declaration(legacy ? legacyRoot : frameworkRoot, "react-sdk")], + "@reflag/browser-sdk": [declaration(legacy ? legacyRoot : frameworkRoot, "browser-sdk")], + "@reflag/node-sdk": [declaration(legacy ? legacyRoot : nodeRoot, "node-sdk")], + "@reflag/vue-sdk": [declaration(legacy ? legacyRoot : frameworkRoot, "vue-sdk")], + react: [path.join(reactTypes, "index.d.ts")], + "react/jsx-runtime": [path.join(reactTypes, "jsx-runtime.d.ts")], + next: [path.join(path.dirname(sdkRequire.resolve("next/package.json")), "index.d.ts")], + }; + for (const [name, content] of Object.entries(extra)) { + const target = path.join(dir, `${name.replaceAll(/[^\w]/g, "-")}.tsx`); + fs.writeFileSync(target, content); + paths[name] = [target]; + } + const ambient = label.startsWith("Next.js") ? [path.join(reactTypes, "canary.d.ts")] : []; + const program = ts.createProgram( + [file, globals, path.join(nodeTypes, "index.d.ts"), ...ambient], + { + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, + jsx: ts.JsxEmit.ReactJSX, + strict: true, + noEmit: true, + skipLibCheck: true, + types: [], + baseUrl: frameworkRoot, + paths, + }, + ); + const diagnostics = ts.getPreEmitDiagnostics(program); + if (diagnostics.length) + throw new Error( + `${label}:\n${ts.formatDiagnosticsWithColorAndContext(diagnostics, { getCanonicalFileName: (file) => file, getCurrentDirectory: () => root, getNewLine: () => "\n" })}`, + ); +} +try { + for (const file of [ + "product-handbook/remote-config.md", + "product-handbook/anonymous-users.md", + "product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta.md", + "product-handbook/type-safety.md", + "product-handbook/launch-monitor/README.md", + "product-handbook/launch-monitor/give-feedback-button.md", + "guides/toggle-toolbar-with-a-flag.md", + "guides/use-reflag-in-your-cli.md", + ]) + blocks(file).forEach((code, index) => compile(`${file} #${index + 1}`, code)); + blocks("product-handbook/feature-entitlements/README.md") + .slice(0, 2) + .forEach((code, index) => compile(`Entitlements #${index + 1}`, code)); + compile("Opt-in loading and membership", blocks("guides/self-opt-in.md")[0]); + const gettingStarted = blocks("README.md"); + compile("Getting started: Boolean", gettingStarted[0]); + compile("Getting started: feedback", gettingStarted[2]); + const next = blocks("supported-languages/next.js.md"); + compile("Next.js singleton", next[0]); + compile("Next.js server action", next[1], false, { + "@/app/reflag": next[0], + "@/app/auth": + 'import type { Context } from "@reflag/node-sdk"; export async function getContext(): Promise { return {}; }', + }); + compile("Next.js Pages router", next[2], false, { + "@/app/reflag": next[0], + "@/app/auth": + 'import type { Context } from "@reflag/node-sdk"; export async function getContext(): Promise { return {}; }', + }); + compile("Next.js client", next[3]); + compile( + "Vue v2 declaration guard", + `import { useFlag } from "@reflag/vue-sdk";\nconst enabled: boolean = useFlag("huddle").value;\nconst count: number = useFlag("settings", { maxItems: 10 }).value.maxItems;\n// @ts-expect-error Vue returns a ref of the direct value, not a flag wrapper.\nuseFlag("huddle").isEnabled;\n// @ts-expect-error Ref contents are not any.\nconst invalid: string = useFlag("settings", { maxItems: 10 }).value.maxItems;\n`, + ); + compile( + "v1 declaration guard", + `import { useFlag } from "@reflag/react-sdk";\nconst enabled: boolean = useFlag("huddle").isEnabled;\n// @ts-expect-error Reject any-shaped declarations.\nconst invalid: number = useFlag("huddle").isEnabled;\n`, + true, + ); + compile( + "v2 declaration guard", + `import { useFlag, useFlagSuspense } from "@reflag/react-sdk";\nimport { ReflagClient } from "@reflag/node-sdk";\nconst enabled: boolean = useFlag("huddle");\nconst count: number = useFlag("settings", { maxItems: 10 }).maxItems;\nconst suspended: boolean = useFlagSuspense("huddle");\n// @ts-expect-error No wrapper API in v2.\nuseFlag("huddle").isEnabled;\n// @ts-expect-error Inferred fields are not any.\nconst invalid: string = useFlag("settings", { maxItems: 10 }).maxItems;\nconst client = new ReflagClient();\nconst serverEnabled: boolean = client.getFlag({}, "huddle");\n// @ts-expect-error Node returns a value, not a wrapper.\nclient.getFlag({}, "huddle").isEnabled;\n`, + ); + console.log( + `${snippets} documentation examples/declaration guards compiled with zero diagnostics.`, + ); +} finally { + fs.rmSync(temp, { recursive: true, force: true }); +} diff --git a/.github/scripts/sdk-docs.mjs b/.github/scripts/sdk-docs.mjs new file mode 100644 index 0000000..e352984 --- /dev/null +++ b/.github/scripts/sdk-docs.mjs @@ -0,0 +1,307 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { parseArgs } from "node:util"; + +export const webSDKs = ["browser-sdk", "react-sdk", "vue-sdk", "node-sdk"]; +const references = [...webSDKs, "react-native-sdk", "management-sdk"]; +export const documentedPackages = [...references, "cli"]; +const repository = "https://github.com/reflagcom/javascript"; +const versionPattern = + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[\da-zA-Z.-]+)?(?:\+[\da-zA-Z.-]+)?$/; +const read = (root, file) => fs.readFileSync(path.join(root, file), "utf8"); +const git = (source, ...args) => + execFileSync("git", ["-C", source, ...args], { encoding: "utf8" }).trim(); +export const hash = (content) => createHash("sha256").update(content).digest("hex"); +const relative = (from, to) => path.posix.relative(path.posix.dirname(from), to); + +export function docsPath(name, major, filename = "README.md") { + assert(documentedPackages.includes(name), `Unknown documentation owner: ${name}`); + if (webSDKs.includes(name)) { + assert([1, 2].includes(major), `Unmapped SDK major: ${major}`); + return `${major === 1 ? "legacy/v1" : "supported-languages"}/${name}/${filename}`; + } + if (name === "management-sdk") return `api/management-sdk/${filename}`; + if (name === "cli") return "api/cli.md"; + return `supported-languages/react-native-sdk/${filename}`; +} + +function metadata(source, name) { + assert(documentedPackages.includes(name), `Unknown documentation owner: ${name}`); + const pkg = JSON.parse(read(source, `packages/${name}/package.json`)); + assert.equal(pkg.name, `@reflag/${name}`); + assert(versionPattern.test(pkg.version), `Invalid version: ${pkg.name}`); + assert(!pkg.private, `Private package: ${pkg.name}`); + return pkg; +} + +function withBanner(content, message) { + const note = `{% hint style="info" %}\n${message}\n{% endhint %}\n\n`; + if (!content.startsWith("---\n")) return note + content; + const end = content.indexOf("\n---\n", 4); + assert(end >= 0, "Unclosed frontmatter"); + return content.slice(0, end + 5) + "\n" + note + content.slice(end + 5).trimStart(); +} + +export function planPackage({ source, name, commit }) { + assert(/^[a-f\d]{40}$/.test(commit), "A full SDK source commit is required"); + const pkg = metadata(source, name); + const major = Number(pkg.version.split(".")[0]); + const web = webSDKs.includes(name); + const files = new Map(); + const mediaRoot = web + ? major === 1 + ? "legacy/v1/_media" + : "supported-languages/_media" + : "sdk/_media"; + const add = (file, content) => { + const bytes = Buffer.from(content); + assert( + !files.has(file) || files.get(file).equals(bytes), + `Conflicting generated output: ${file}`, + ); + files.set(file, bytes); + }; + const targetMajor = (target) => { + if (!webSDKs.includes(target)) return Number(metadata(source, target).version.split(".")[0]); + if (web) return major; + const range = + pkg.dependencies?.[`@reflag/${target}`] ?? + pkg.peerDependencies?.[`@reflag/${target}`] ?? + (name === "react-native-sdk" ? pkg.dependencies?.["@reflag/react-sdk"] : undefined); + const selected = /^[~^]?(\d+)\./.exec(range ?? "")?.[1]; + assert(selected, `Cannot determine linked SDK major: ${target}`); + return Number(selected); + }; + const route = (url, output) => { + if (url.startsWith("#")) return url; + // Absolute SDK links must not send legacy readers into the current API. + const publicLink = + /^https:\/\/docs\.reflag\.com\/(?:supported-languages|sdk\/@reflag)\/([^/#]+)(?:\/(globals)(?:\.md)?)?\/?(#[^\s]*)?$/.exec( + url, + ); + if (publicLink && webSDKs.includes(publicLink[1])) { + return ( + relative( + output.file, + docsPath( + publicLink[1], + targetMajor(publicLink[1]), + publicLink[2] ? "globals.md" : "README.md", + ), + ) + (publicLink[3] ?? "") + ); + } + if (/^(?:[a-z][a-z\d+.-]*:|\/)/i.test(url)) { + return url + .replace(`${repository}/blob/main/`, `${repository}/blob/${commit}/`) + .replace(`${repository}/tree/main/`, `${repository}/tree/${commit}/`); + } + const [pathname, fragment = ""] = url.split(/(?=#)/, 2); + let raw = path.posix.normalize( + path.posix.join(path.posix.dirname(output.raw), decodeURIComponent(pathname)), + ); + assert(!raw.startsWith("../") && !path.posix.isAbsolute(raw), `Link escapes SDK docs: ${url}`); + // TypeDoc's shared README attachment can contain the wrong package's README. + if (raw === "_media/README.md") { + const original = read(source, `packages/${name}/README.md`); + const linked = /\]\(\.\.\/([^/]+)\/README\.md\)/.exec(original)?.[1]; + assert(linked && documentedPackages.includes(linked), "Unmapped README attachment"); + raw = `@reflag/${linked}/README.md`; + } + const sdk = /^@reflag\/([^/]+)\/(README|globals)\.md$/.exec(raw); + if (sdk) + return ( + relative(output.file, docsPath(sdk[1], targetMajor(sdk[1]), `${sdk[2]}.md`)) + fragment + ); + if (raw === "documents/browser-sdk/FEEDBACK.md") + return ( + relative(output.file, docsPath("browser-sdk", targetMajor("browser-sdk"), "feedback.md")) + + fragment + ); + const document = /^documents\/([^/]+)\/README\.md$/.exec(raw); + if (document && references.includes(document[1])) + return relative(output.file, docsPath(document[1], targetMajor(document[1]))) + fragment; + if (raw.startsWith("_media/")) { + const target = `${mediaRoot}/${raw.slice("_media/".length)}`; + add(target, fs.readFileSync(path.join(source, "dist/docs", raw))); + return relative(output.file, target) + fragment; + } + return `${repository}/blob/${commit}/${raw}${fragment}`; + }; + const render = (raw, file, kind) => { + let content = read(source, `dist/docs/${raw}`); + // Canonical docs.sh normalizes property anchors; normalize all links, too. + content = content.replace(/(globals\.md#[\w-]+?)-\d+(?=[)"\s])/g, "$1"); + content = content.replace(/```[^\n]*\n[\s\S]*?```/g, (block) => block.replace(/[ \t]+$/gm, "")); + content = content.replace( + /(\]\()([^\s)]+)([^)]*\))/g, + (_, open, url, close) => `${open}${route(url, { raw, file })}${close}`, + ); + content = content.replace( + /((?:src|href)=["'])([^"']+)(["'])/g, + (_, open, url, close) => `${open}${route(url, { raw, file })}${close}`, + ); + if (web) { + // Pin installation/CDN commands, never imports or JSON application data. + content = content + .split("\n") + .map((line) => { + if (!/^\s*(?:npm (?:i|install)|yarn add|pnpm add|bun add|deno add|npx)\b/.test(line)) + return line; + return line.replace( + /@reflag\/(?:node-sdk|browser-sdk|react-sdk|vue-sdk|cli)(?:@[\w.^~-]+)?(?![\w/-])/g, + (match) => `${match.replace(/@[^@/]+$/, "")}@${major}`, + ); + }) + .join("\n"); + content = content.replace( + /(https:\/\/cdn\.jsdelivr\.net\/npm\/@reflag\/browser-sdk)(?:@[^/"'<>\s]+)?/g, + `$1@${major}`, + ); + const counterpart = docsPath( + name, + major === 1 ? 2 : 1, + kind === "feedback" ? "feedback.md" : kind === "reference" ? "globals.md" : "README.md", + ); + const label = major === 1 ? "Protocol v1 — legacy" : "Protocol v2"; + const versionLink = major === 1 ? "Current v2 documentation" : "Legacy v1 documentation"; + const prerelease = + major === 2 && versionPattern.exec(pkg.version)[4] + ? "\n\n**Prerelease source documentation.** The installation examples target major 2; use them only when the matching SDK/CLI packages are available. A server rollout alone does not publish npm packages." + : ""; + content = withBanner( + content, + `**${label}.** [${versionLink}](${relative(file, counterpart)}) · [Migration guide](${relative(file, "supported-languages/migrating-from-v1.md")})${prerelease}\n\nGenerated from [\`${pkg.name}@${pkg.version}\`](${repository}/tree/${commit}/packages/${name}); SDK READMEs and code comments remain the source of truth.`, + ); + } else if (name === "react-native-sdk") { + content = withBanner( + content, + `**Independent SDK compatibility.** This React Native release uses React/Browser protocol v${targetMajor("react-sdk")}. Follow the [matching React documentation](${relative(file, docsPath("react-sdk", targetMajor("react-sdk")))}) and use a [matching Node SDK](${relative(file, docsPath("node-sdk", targetMajor("react-sdk")))}) for bootstrap. Do not pass protocol-v2 bootstrap into a v1 consumer.`, + ); + } + add(file, content); + }; + if (references.includes(name)) { + for (const filename of ["README.md", "globals.md"]) { + const raw = `@reflag/${name}/${filename}`; + const kind = filename === "globals.md" ? "reference" : "readme"; + render(raw, docsPath(name, major, filename), kind); + // Keep historical SDK URLs and their reference anchors usable, but only + // the current major owns these aliases. A v1 release cannot replace v2. + if (!web || major === 2) render(raw, `sdk/@reflag/${name}/${filename}`, kind); + if ( + ((name === "react-sdk" && major === 2) || name === "react-native-sdk") && + filename === "README.md" + ) + render(raw, `sdk/documents/${name}/README.md`, kind); + } + } + if (name === "browser-sdk") { + const raw = "documents/browser-sdk/FEEDBACK.md"; + render(raw, docsPath(name, major, "feedback.md"), "feedback"); + if (major === 2) render(raw, "sdk/documents/browser-sdk/FEEDBACK.md", "feedback"); + } + if (name === "cli") { + render("documents/cli/README.md", "api/cli.md", "readme"); + render("documents/cli/README.md", "sdk/documents/cli/README.md", "readme"); + } + const manifest = { + sourceRepository: repository, + sourceCommit: commit, + package: pkg.name, + version: pkg.version, + files: Object.fromEntries([...files].map(([file, content]) => [file, hash(content)])), + }; + add(`.generated/sdk-docs/${name}/v${major}.json`, `${JSON.stringify(manifest, null, 2)}\n`); + return files; +} + +export function applyPlan(files, destination, { check = false } = {}) { + for (const [file, content] of files) { + assert(!path.isAbsolute(file) && !file.split("/").includes(".."), "Unsafe generated path"); + const target = path.join(destination, file); + if (check) + assert(fs.readFileSync(target).equals(content), `Generated documentation differs: ${file}`); + else { + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.writeFileSync(target, content); + } + } + // Never delete a tree, or take ownership of navigation, guides or GitBook settings. +} + +export function releaseFiles(source, plan) { + assert.equal( + git(source, "status", "--porcelain", "--untracked-files=no"), + "", + "SDK source must be clean", + ); + const commit = git(source, "rev-parse", "HEAD"); + assert.equal(plan.sourceCommit, commit, "Release source changed"); + assert(Array.isArray(plan.releases), "Invalid release plan"); + const files = new Map(); + const seen = new Set(); + for (const release of plan.releases) { + assert(/^@reflag\/[a-z][a-z0-9-]*$/.test(release.name), "Invalid package name"); + const name = release.name.slice("@reflag/".length); + const pkg = metadata(source, name); + assert(!seen.has(name), `Duplicate package: ${name}`); + seen.add(name); + assert.equal(pkg.version, release.version, "Published/source version mismatch"); + assert(!versionPattern.exec(pkg.version)[4], "Prereleases cannot promote stable docs"); + assert.equal( + git(source, "rev-parse", `refs/tags/${pkg.name}@${pkg.version}^{commit}`), + commit, + "Release tag/source mismatch", + ); + for (const [file, content] of planPackage({ source, name, commit })) { + assert(!files.has(file) || files.get(file).equals(content), `Conflicting output: ${file}`); + files.set(file, content); + } + } + return files; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { + const { values, positionals } = parseArgs({ + allowPositionals: true, + options: { + source: { type: "string" }, + destination: { type: "string", default: "." }, + package: { type: "string", multiple: true }, + plan: { type: "string" }, + check: { type: "boolean", default: false }, + }, + }); + assert(values.source, "--source is required"); + const source = path.resolve(values.source); + let files; + if (positionals[0] === "release") { + assert(values.plan, "--plan is required"); + files = releaseFiles(source, JSON.parse(fs.readFileSync(values.plan, "utf8"))); + } else { + assert.equal(positionals[0], "import", "Use import or release"); + assert(values.package?.length, "Select --package explicitly"); + assert.equal( + git(source, "status", "--porcelain", "--untracked-files=no"), + "", + "SDK source must be clean", + ); + files = new Map(); + for (const name of values.package) + for (const [file, content] of planPackage({ + source, + name, + commit: git(source, "rev-parse", "HEAD"), + })) { + assert(!files.has(file) || files.get(file).equals(content), `Conflicting output: ${file}`); + files.set(file, content); + } + } + applyPlan(files, path.resolve(values.destination), { check: values.check }); + console.log(`${values.check ? "Verified" : "Generated"} ${files.size} SDK documentation files.`); +} diff --git a/.github/scripts/sdk-docs.test.mjs b/.github/scripts/sdk-docs.test.mjs new file mode 100644 index 0000000..73720b6 --- /dev/null +++ b/.github/scripts/sdk-docs.test.mjs @@ -0,0 +1,235 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { applyPlan, docsPath, planPackage, releaseFiles, webSDKs } from "./sdk-docs.mjs"; +import { anchors, checkLinks, checkSDKDocs, root, sourceMatrix } from "./check-sdk-docs.mjs"; + +function fixture(t, major = 2) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "reflag-sdk-docs-test-")); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const source = path.join(dir, "source"), + destination = path.join(dir, "docs"); + const put = (file, content) => { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, content); + }; + const names = [...webSDKs, "react-native-sdk", "management-sdk", "cli"]; + for (const name of names) { + put( + path.join(source, `packages/${name}/package.json`), + JSON.stringify({ + name: `@reflag/${name}`, + version: `${major}.0.0`, + dependencies: { "@reflag/react-sdk": "1.7.4" }, + }), + ); + put( + path.join(source, `packages/${name}/README.md`), + "# SDK\n[Browser](../browser-sdk/README.md)\n", + ); + put( + path.join(source, `dist/docs/@reflag/${name}/README.md`), + `---\nlayout: {}\n---\n# SDK\n[Browser](../../_media/README.md)\n[Feedback](../../documents/browser-sdk/FEEDBACK.md)\n[Toolbar](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions)\nnpm install @reflag/${name}\nbun add @reflag/${name}\ndeno add npm:@reflag/${name}\nnpx @reflag/cli new\n\n[Source](https://github.com/reflagcom/javascript/blob/main/packages/${name}/README.md)\n`, + ); + put( + path.join(source, `dist/docs/@reflag/${name}/globals.md`), + '# Reference\n## FlagValueFromDefault\\\n\n', + ); + } + put( + path.join(source, "dist/docs/documents/browser-sdk/FEEDBACK.md"), + "# Feedback\n[Browser](../../@reflag/browser-sdk/README.md)\n", + ); + put(path.join(source, "dist/docs/documents/cli/README.md"), "# CLI\n"); + return { + source, + destination, + put, + options: { source, name: "react-sdk", commit: "a".repeat(40) }, + }; +} + +test("repository navigation, provenance, cross-version links, assets and anchors", () => { + assert(checkSDKDocs().generatedPages >= 28); +}); + +test("CI discovers exact source refs from manifests rather than hardcoding the first import", () => { + const matrix = sourceMatrix(); + assert(matrix.include.length > 0); + for (const row of matrix.include) { + assert(/^[a-f\d]{40}$/.test(row.ref)); + assert.match( + row.packages, + /^(?:--package (?:browser-sdk|react-sdk|vue-sdk|node-sdk|react-native-sdk|management-sdk|cli)(?: |$))+$/, + ); + } +}); + +test("v1 import owns only the archive, pins installers/CDN and routes SDK links to v1", (t) => { + const { options } = fixture(t, 1); + const files = planPackage(options); + assert( + [...files.keys()].every( + (file) => file.startsWith("legacy/v1/") || file.startsWith(".generated/"), + ), + ); + const readme = files.get("legacy/v1/react-sdk/README.md").toString(); + assert.match(readme, /npm install @reflag\/react-sdk@1/); + assert.match(readme, /bun add @reflag\/react-sdk@1/); + assert.match(readme, /deno add npm:@reflag\/react-sdk@1/); + assert.match(readme, /npx @reflag\/cli@1 new/); + assert.match(readme, /browser-sdk@1/); + assert.match(readme, /\(\.\.\/browser-sdk\/globals.md#toolbaroptions\)/); + assert.match(readme, /blob\/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\//); + assert(readme.indexOf("---") < readme.indexOf("{% hint"), "Keep frontmatter first"); +}); + +test("v2 sync cannot modify archived docs, navigation, settings or handwritten guides", (t) => { + const { options, destination, put } = fixture(t); + const preserved = [ + "legacy/v1/react-sdk/README.md", + "SUMMARY.md", + "README.md", + "gitbook-docs.yaml", + "supported-languages/migrating-from-v1.md", + ]; + for (const file of preserved) put(path.join(destination, file), "preserve"); + const files = planPackage(options); + applyPlan(files, destination); + applyPlan(files, destination, { check: true }); + for (const file of preserved) + assert.equal(fs.readFileSync(path.join(destination, file), "utf8"), "preserve"); + assert(files.has("supported-languages/react-sdk/README.md")); + assert(files.has("sdk/@reflag/react-sdk/globals.md"), "Preserve historical reference URLs"); + assert.match( + files.get("sdk/@reflag/react-sdk/README.md").toString(), + /\.\.\/\.\.\/\.\.\/legacy\/v1\/react-sdk\/README.md/, + ); +}); + +test("independent Native references route to its pinned React/Browser major, not workspace v2", (t) => { + const { options } = fixture(t); + const files = planPackage({ ...options, name: "react-native-sdk" }); + const readme = files.get("supported-languages/react-native-sdk/README.md").toString(); + assert.match(readme, /legacy\/v1\/browser-sdk\/README.md/); + assert.match(readme, /legacy\/v1\/react-sdk\/README.md/); + assert(!files.has("supported-languages/react-sdk/README.md")); + assert(!files.has("legacy/v1/react-sdk/README.md")); +}); + +test("Management and CLI updates never own coordinated SDK trees", (t) => { + const { options, source, put } = fixture(t); + put(path.join(source, "dist/docs/@reflag/management-sdk/README.md"), "# Management SDK\n"); + for (const name of ["management-sdk", "cli"]) { + const files = planPackage({ ...options, name }); + assert( + ![...files.keys()].some( + (file) => file.startsWith("legacy/") || file.startsWith("supported-languages/"), + ), + ); + } +}); + +test("missing generated input fails before applying any changes", (t) => { + const { source, options, destination } = fixture(t); + fs.unlinkSync(path.join(source, "dist/docs/@reflag/react-sdk/globals.md")); + assert.throws(() => applyPlan(planPackage(options), destination), /ENOENT/); + assert(!fs.existsSync(destination)); +}); + +test("manifest check detects manual generated-content changes", (t) => { + const { options, destination, put } = fixture(t); + const plan = planPackage(options); + applyPlan(plan, destination); + put(path.join(destination, "supported-languages/react-sdk/README.md"), "edited"); + assert.throws( + () => applyPlan(plan, destination, { check: true }), + /Generated documentation differs/, + ); +}); + +test("unknown owners and majors fail closed", (t) => { + const { options } = fixture(t); + assert.throws( + () => planPackage({ ...options, name: "../../escape" }), + /Unknown documentation owner/, + ); + assert.throws(() => docsPath("react-sdk", 3), /Unmapped SDK major/); + assert.throws(() => planPackage({ ...options, commit: "main" }), /full SDK source commit/); +}); + +test("negative link controls catch missing files and anchors; generic headings remain addressable", (t) => { + const { destination, put } = fixture(t); + put(path.join(destination, "page.md"), "[missing](other.md)\n"); + assert.throws(() => checkLinks(destination, ["page.md"]), /Missing file/); + put(path.join(destination, "other.md"), "# FlagValueFromDefault\\\n"); + put(path.join(destination, "page.md"), "[missing](other.md#nope)\n"); + assert.throws(() => checkLinks(destination, ["page.md"]), /Missing anchor/); + assert( + anchors(fs.readFileSync(path.join(destination, "other.md"), "utf8")).has( + "flagvaluefromdefaultt", + ), + ); +}); + +test("release sync requires the exact clean tagged source and rejects prereleases before writes", (t) => { + const { source, options, put } = fixture(t); + const git = (...args) => + execFileSync("git", ["-C", source, ...args], { encoding: "utf8" }).trim(); + git("init", "--quiet"); + git("add", "."); + git( + "-c", + "user.name=Test", + "-c", + "user.email=test@example.invalid", + "commit", + "--quiet", + "-m", + "Fixture", + ); + const sourceCommit = git("rev-parse", "HEAD"); + const plan = { sourceCommit, releases: [{ name: "@reflag/react-sdk", version: "2.0.0" }] }; + git("tag", "@reflag/react-sdk@2.0.0"); + assert(releaseFiles(source, plan).has("supported-languages/react-sdk/README.md")); + assert.throws( + () => releaseFiles(source, { ...plan, sourceCommit: options.commit }), + /source changed/, + ); + assert.throws( + () => releaseFiles(source, { ...plan, releases: [...plan.releases, ...plan.releases] }), + /Duplicate package/, + ); + put( + path.join(source, "packages/react-sdk/package.json"), + JSON.stringify({ name: "@reflag/react-sdk", version: "2.0.1-next.0" }), + ); + assert.throws(() => releaseFiles(source, plan), /must be clean/); + git("add", "."); + git( + "-c", + "user.name=Test", + "-c", + "user.email=test@example.invalid", + "commit", + "--quiet", + "-m", + "Prerelease", + ); + assert.throws( + () => + releaseFiles(source, { + sourceCommit: git("rev-parse", "HEAD"), + releases: [{ name: "@reflag/react-sdk", version: "2.0.1-next.0" }], + }), + /Prereleases cannot promote/, + ); +}); + +test("this change does not introduce a GitBook variant picker or alternate site mapping", () => { + assert(!fs.existsSync(path.join(root, ".gitbook.yaml")), "No new per-space root mapping"); + assert(!fs.readFileSync(path.join(root, "SUMMARY.md"), "utf8").includes("v2-candidate/")); +}); diff --git a/.github/workflows/sdk-docs.yml b/.github/workflows/sdk-docs.yml new file mode 100644 index 0000000..330e46a --- /dev/null +++ b/.github/workflows/sdk-docs.yml @@ -0,0 +1,112 @@ +name: SDK documentation + +on: + pull_request: + paths: + - "**/*.md" + - .generated/** + - .github/scripts/** + - .github/workflows/sdk-docs.yml + - gitbook-docs.yaml + +permissions: + contents: read + +jobs: + check: + name: Navigation and version isolation + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.sources.outputs.matrix }} + react_v1_ref: ${{ steps.sources.outputs.react_v1_ref }} + react_v2_ref: ${{ steps.sources.outputs.react_v2_ref }} + node_v2_ref: ${{ steps.sources.outputs.node_v2_ref }} + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: 24 + - run: node --test .github/scripts/sdk-docs.test.mjs + - id: sources + name: Discover pinned SDK sources from generated manifests + run: node .github/scripts/check-sdk-docs.mjs --sources + + sources: + name: Rebuild SDK sources + needs: check + runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: ${{ fromJSON(needs.check.outputs.matrix) }} + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: 24 + - run: corepack enable + - uses: actions/checkout@v4 + with: + repository: reflagcom/javascript + ref: ${{ matrix.ref }} + path: .sdk-source + persist-credentials: false + - name: Install exact SDK sources + working-directory: .sdk-source + run: yarn install --immutable + - name: Build declarations and canonical TypeDoc output + working-directory: .sdk-source + run: | + if test -d packages/flag-evaluation; then + yarn workspace @reflag/flag-evaluation build + fi + yarn workspace @reflag/node-sdk build + yarn workspace @reflag/browser-sdk build + yarn workspace @reflag/react-sdk build + yarn workspace @reflag/vue-sdk build + # Published v1 docs.sh uses [[ despite its /bin/sh shebang. + yarn exec bash ./docs.sh + - name: Verify generated content against pinned sources + run: node .github/scripts/sdk-docs.mjs import --source .sdk-source ${{ matrix.packages }} --check + + examples: + name: Compile matching SDK examples + needs: check + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: 24 + - run: corepack enable + - uses: actions/checkout@v4 + with: + repository: reflagcom/javascript + ref: ${{ needs.check.outputs.react_v1_ref }} + path: .sdk-v1 + persist-credentials: false + - uses: actions/checkout@v4 + with: + repository: reflagcom/javascript + ref: ${{ needs.check.outputs.react_v2_ref }} + path: .sdk-v2 + persist-credentials: false + - uses: actions/checkout@v4 + with: + repository: reflagcom/javascript + ref: ${{ needs.check.outputs.node_v2_ref }} + path: .sdk-node-v2 + persist-credentials: false + - name: Build matching declarations + run: | + (cd .sdk-v1 && yarn install --immutable && yarn workspace @reflag/browser-sdk build && yarn workspace @reflag/react-sdk build && yarn workspace @reflag/vue-sdk build && yarn workspace @reflag/node-sdk build) + (cd .sdk-v2 && yarn install --immutable && yarn workspace @reflag/flag-evaluation build && yarn workspace @reflag/node-sdk build && yarn workspace @reflag/browser-sdk build && yarn workspace @reflag/react-sdk build && yarn workspace @reflag/vue-sdk build) + (cd .sdk-node-v2 && yarn install --immutable && yarn workspace @reflag/flag-evaluation build && yarn workspace @reflag/node-sdk build) + - run: node .github/scripts/check-sdk-examples.cjs .sdk-v2 .sdk-node-v2 .sdk-v1 diff --git a/README.md b/README.md index 4b72bc2..db76a92 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,9 @@ # Getting started +{% hint style="info" %} +These examples use **protocol v2**. The SDK page banners identify prerelease source versions and package availability. Maintaining a v1 application? Use the [legacy SDK docs](legacy/v1/README.md) or [migration guide](supported-languages/migrating-from-v1.md). +{% endhint %} + **Welcome!** Let's get started. We'll do the following: 1. Create your first flag. @@ -15,10 +19,10 @@ Now let's create your first flag. {% tabs %} {% tab title="CLI" %} ``` -npx @reflag/cli new +npx @reflag/cli@2 new ``` -See [CLI docs](api/cli.md). +This requires a compatible CLI 2 release; for the current v2 prerelease rollout, use the package version supplied to you. You can also create the flag in the UI without installing the CLI. See [Type safety](product-handbook/type-safety.md) for v2 type generation. {% endtab %} {% tab title="UI" %} @@ -54,13 +58,13 @@ If you've installed the React SDK and created a flag called `my-new-flag`, getti import { useFlag } from "@reflag/react-sdk"; const MyFlag = () => { - const { isEnabled } = useFlag("my-new-flag"); + const enabled = useFlag("my-new-flag"); - return isEnabled ? "You have access!" : null; + return enabled ? "You have access!" : null; }; ``` -You can now use `isEnabled` to gate access to the flag. +You can now use the Boolean value directly to gate access to the flag. ## 3. Set access rules @@ -80,10 +84,12 @@ In the React SDK, you enable it with `toolbar:` ```jsx + + ``` ## 5. Monitor your flag launch @@ -109,20 +115,22 @@ To get feedback from your users, you can add a [static "Feedback" button](produc Here's an example with a static feedback button. ```tsx -import { useFlag } from "@reflag/react-sdk"; +import { useFlag, useTrack, useRequestFeedback } from "@reflag/react-sdk"; const MyFlag = () => { - const { isEnabled, track, requestFeedback } = useFlag("my-new-flag"); + const enabled = useFlag("my-new-flag"); + const track = useTrack(); + const requestFeedback = useRequestFeedback(); - if (!isEnabled) { + if (!enabled) { return null; } return ( <> - + @@ -131,6 +139,8 @@ const MyFlag = () => { } ``` +Configure your flag's adoption rules to match the event name you send with `track()`. + ## Get support * Need some help? [Chat with us](mailto:hello@reflag.com) diff --git a/SUMMARY.md b/SUMMARY.md index 3a5477e..4f7e3c0 100644 --- a/SUMMARY.md +++ b/SUMMARY.md @@ -7,6 +7,7 @@ ## Supported languages * [Overview](supported-languages/overview.md) +* [Migrating from v1](supported-languages/migrating-from-v1.md) * [React SDK](supported-languages/react-sdk/README.md) * [Reference](supported-languages/react-sdk/globals.md) * [React Native SDK (beta)](supported-languages/react-native-sdk/README.md) @@ -96,6 +97,19 @@ * [Beta feature opt-in](guides/self-opt-in.md) * [Toggle toolbar with a flag](guides/toggle-toolbar-with-a-flag.md) +## Legacy SDKs + +* [Legacy SDKs (v1)](legacy/v1/README.md) + * [Browser SDK (v1)](legacy/v1/browser-sdk/README.md) + * [Reference](legacy/v1/browser-sdk/globals.md) + * [Feedback](legacy/v1/browser-sdk/feedback.md) + * [React SDK (v1)](legacy/v1/react-sdk/README.md) + * [Reference](legacy/v1/react-sdk/globals.md) + * [Vue SDK (v1)](legacy/v1/vue-sdk/README.md) + * [Reference](legacy/v1/vue-sdk/globals.md) + * [Node.js SDK (v1)](legacy/v1/node-sdk/README.md) + * [Reference](legacy/v1/node-sdk/globals.md) + ## Support * [Get support](support/get-support.md) diff --git a/guides/self-opt-in.md b/guides/self-opt-in.md index 037b37f..17303a1 100644 --- a/guides/self-opt-in.md +++ b/guides/self-opt-in.md @@ -31,7 +31,11 @@ import { import { Spinner } from "your-component-library"; function OptInPage() { - const { flags: optInFlags } = useOptInFlags(); + const { flags: optInFlags, isLoading } = useOptInFlags({ suspense: false }); + + if (isLoading) { + return ; + } if (optInFlags.length === 0) { return

No opt-in flags are available.

; @@ -107,9 +111,9 @@ User and company opt-ins are independent. Setting `optedIn` to `false` removes o Cancelling every opt-in does not necessarily disable the flag: an access rule may independently enable it for the current context. -## Managing loading state with `` and without `` +## Managing opt-in loading state -Only apps using `ReflagBootstrappedProvider` without Suspense need to handle this loading state. Bootstrapped flag data does not include opt-in metadata, so the SDK fetches it when `useOptInFlags()` is first used. +Check opt-in loading before rendering an empty state, including during ordinary initialization. Metadata arrives with v2 evaluated-flags responses. A bootstrapped snapshot may omit it; the SDK then fetches missing metadata on demand without replacing server-derived flag values. Check the hook's `isLoading` value before rendering an empty state: @@ -125,7 +129,7 @@ if (optInFlags.length === 0) { } ``` -With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal flags request, so `useOptInFlags().isLoading` remains `false`. Use `useIsLoading()`, suspense or the provider's `loadingComponent` for the normal initial loading state. +For general provider initialization, use `useIsLoading()` or `loadingComponent`. React `useFlag()` itself never suspends; use `useFlagSuspense()` for a suspending flag read. Opt-in hooks have their own suspense/loading contract; do not assume their loading value is always `false` with a regular provider. ## Next steps diff --git a/guides/toggle-toolbar-with-a-flag.md b/guides/toggle-toolbar-with-a-flag.md index cf91262..7a6a60b 100644 --- a/guides/toggle-toolbar-with-a-flag.md +++ b/guides/toggle-toolbar-with-a-flag.md @@ -1,45 +1,30 @@ --- -description: >- - Learn how you can control who gets the toolbar in production by toggling a - feature flag on/off +description: Show the SDK v2 toolbar toggle to selected users. icon: toolbox --- # Toggle toolbar with a flag -In some cases, you want to limit who has access to the toolbar in production. If you already have an "admin" or "internalUser" boolean on the user model, that is how most people decide whether to show the toolbar. +Use a Boolean flag to choose who sees the SDK toolbar toggle. Create a `toolbar` flag in Reflag, configure its access rules, and leave the provider's unconditional `toolbar` option disabled. -Beyond those simple cases, using a feature flag that you can enable for certain people is a great way to manage who gets to see the toolbar. - -Here's an example of how it can be done with the React SDK: - -1. Create the flag: - -```bash -$ npx reflag new toolbar -``` - -2. If you've set the `toolbar` prop on the ``, remove it. We'll manage this by calling `client.showToolbar()` when the flag is enabled. -3. Put this tiny component inside the ``: +Put this component inside your React SDK v2 provider: ```tsx -function ToolbarFlagControl() { +import { useEffect } from "react"; +import { useClient, useFlag } from "@reflag/react-sdk"; + +export function ToolbarFlagControl() { const client = useClient(); - const {isEnabled: toolbarEnabled} = useFlag("toolbar"); + const toolbarEnabled = useFlag("toolbar"); + useEffect(() => { - if (toolbarEnabled) { - client?.showToolbarToggle(); - } - }, [toolbarEnabled]); + if (toolbarEnabled) client.showToolbarToggle(); + }, [client, toolbarEnabled]); + + return null; } ``` -Done! You can now enable/disable the toolbar for users by toggling the `toolbar` feature flag for them inside Reflag. - -{% hint style="info" %} -showToolbarToggle() became available in the following SDK versions: +This shows the toggle once access is granted. `showToolbarToggle()` does not provide a corresponding hide operation: switching the flag off later does not remove an already mounted toggle. Reload or recreate the client to apply a new visibility decision. -* @reflag/react-sdk: 1.3.0 -* @reflag/vue-sdk: 1.3.0 -* @reflag/browser-sdk: 1.3.0 -{% endhint %} +This is a convenience control, **not an authorization boundary**. Users control their own browser; never use the toolbar flag to protect secrets or administrative server operations. See [Browser SDK v2](../supported-languages/browser-sdk/README.md) for toolbar options. diff --git a/guides/use-reflag-in-your-cli.md b/guides/use-reflag-in-your-cli.md index c156dc5..065bd02 100644 --- a/guides/use-reflag-in-your-cli.md +++ b/guides/use-reflag-in-your-cli.md @@ -1,111 +1,71 @@ --- -description: High-level guide to flagging features in your CLI +description: Gate a workflow in your own CLI with SDK v2. icon: rectangle-terminal --- # Use Reflag in your CLI -### If you use API token for auth +This guide is about **your application's CLI**, not the Reflag management CLI. Authenticate your caller using your existing API-token or OAuth flow, then evaluate flags with the server-side Node SDK v2. Do not embed a Reflag secret SDK key or a Management API key in a distributed CLI. -First, create an endpoint in your backend for the CLI to call: +## Evaluate on your backend -``` -POST /get-flags -Authorization: Bearer -``` +Create an authenticated endpoint such as `POST /get-flags`. Look up the user and company from your trusted session/token store; do not trust caller-supplied identities or subscription attributes. -The endpoint will take the API key and use it to look up the associated user. +A reusable evaluation helper can accept the resulting context: -Then, use the [public-api-reference.md](../api/public-api/public-api-reference.md "mention") to get enabled flags for the authenticated user. Return the flags to the CLI: +```typescript +import { ReflagClient, type Context } from "@reflag/node-sdk"; -``` -{ - flags: ['flag1', 'flag2'] -} -``` +const client = new ReflagClient({ secretKey: process.env.REFLAG_SECRET_KEY ?? "" }); +const initialized = client.initialize(); -Finally, check for access with a simple: - -```tsx -/function isFlagEnabled(flag: string) { - return flags.contains('myflag'); +export async function getCliAccess(context: Context) { + await initialized; + const bound = client.bindClient(context); + return { + exportEnabled: bound.getFlag("export-to-csv"), + settings: bound.getFlag("export-settings", { maxRows: 1000 }), + }; } ``` -### If you use API token for auth AND Node.js +Call `getCliAccess()` after authentication and return only the values your CLI needs. This registers checks for these requested roots. Diagnostic APIs are not a substitute for application reads. -First, create an endpoint in your backend for the CLI to call: +The JSON response contains direct values, not flag wrappers: +```json +{ + "exportEnabled": true, + "settings": { "maxRows": 1000 } +} ``` -POST /get-flags -Authorization: Bearer -``` - -The endpoint will take the API key and use it to look up the associated user. -Use the [node-sdk](../supported-languages/node-sdk/ "mention") get enabled flags for the authenticated user. +## Gate the CLI workflow -```jsx -import { ReflagClient } from "@reflag/node-sdk"; +Use the Boolean directly and validate the response before using nested configuration. Recheck sensitive access on the backend that performs the operation; a CLI display check is not authorization. -// configure the client -const boundClient = reflagClient.bindClient({ - user: { - id: "c1_u1", - name: "John Doe" - }, - company: { - id: "c1", - name: "Acme, Inc." - }, -}); - -// get flags -const flags = boundClient.getFlags(); -``` - -Finally, check for access with a simple: - -```tsx -if(flags['myflag'].isEnabled) { - //feature access +```typescript +export function canExport(response: { exportEnabled: boolean }) { + return response.exportEnabled; } ``` -### If you use OAuth for auth - -Use [node-sdk](../supported-languages/node-sdk/ "mention") or [public-api-reference.md](../api/public-api/public-api-reference.md "mention") to get flags for the authenticated user. +If you expose a list of enabled Boolean keys instead, use `enabledKeys.includes("export-to-csv")`. Do not treat a general JSON-valued flag map as a list of enabled keys or apply truthiness to Multivariate values. -In Node, configure the SDK like so: +## Track successful usage separately -```jsx -import { ReflagClient } from "@reflag/node-sdk"; +After the protected operation succeeds, track the application's adoption event with the same authenticated context. Configure the flag's adoption rules to match that event. -// configure the client -const boundClient = reflagClient.bindClient({ - user: { - id: "c1_u1", - name: "John Doe" - }, - company: { - id: "c1", - name: "Acme, Inc." - }, -}); -``` - -Check access for individual flag: +```typescript +import { ReflagClient, type Context } from "@reflag/node-sdk"; -```jsx -const { isEnabled } = boundClient.getFlag("myflag"); +const client = new ReflagClient({ secretKey: process.env.REFLAG_SECRET_KEY ?? "" }); +const initialized = client.initialize(); -if (isEnabled) { - //feature access -} +export async function recordExport(context: Context) { + await initialized; + await client.bindClient(context).track("Exported CSV"); +} ``` -Or get all flags: - -```jsx -const flags = boundClient.getFlags(); -``` +There is no `getFlag(...).track()` wrapper method in v2. Initialize the client once per process and use its normal lifecycle/flush handling for short-lived server processes. See [Node SDK v2](../supported-languages/node-sdk/README.md) and the [migration guide](../supported-languages/migrating-from-v1.md). diff --git a/legacy/v1/README.md b/legacy/v1/README.md new file mode 100644 index 0000000..28ee2d4 --- /dev/null +++ b/legacy/v1/README.md @@ -0,0 +1,34 @@ +--- +description: Legacy protocol-v1 documentation for the Browser, React, Vue and Node.js SDKs. +--- + +# Legacy SDKs (v1) + +These pages document the **protocol-v1 SDKs**. For new v2 integrations, start with the [current SDK documentation](../../supported-languages/overview.md). For an existing application, read [Migrating from v1](../../supported-languages/migrating-from-v1.md) before upgrading. + +| SDK | Package major | Documentation | API reference | +| --- | --- | --- | --- | +| Browser | `@reflag/browser-sdk@1` | [Browser SDK v1](browser-sdk/README.md) | [Reference](browser-sdk/globals.md) | +| React | `@reflag/react-sdk@1` | [React SDK v1](react-sdk/README.md) | [Reference](react-sdk/globals.md) | +| Vue | `@reflag/vue-sdk@1` | [Vue SDK v1](vue-sdk/README.md) | [Reference](vue-sdk/globals.md) | +| Node.js | `@reflag/node-sdk@1` | [Node.js SDK v1](node-sdk/README.md) | [Reference](node-sdk/globals.md) | + +The archive includes [Browser feedback documentation](browser-sdk/feedback.md). Each page's banner identifies the exact archived source version. SDK content is generated from the matching published v1 sources, not reconstructed from v2 examples. + +## Installing v1 + +Pin the major when maintaining a v1 application: + +```sh +npm install @reflag/react-sdk@1 +``` + +Use `@reflag/browser-sdk@1`, `@reflag/vue-sdk@1`, or `@reflag/node-sdk@1` as appropriate. Keep CLI 1 with legacy generated declarations. Unversioned installation commands can select a breaking major after it becomes the default on npm. + +## Compatibility + +- Keep both ends of a server-to-browser bootstrap integration on protocol v1. A Node v2 bootstrap envelope cannot initialize a v1 Browser, React or Vue client. +- React Native and the OpenFeature providers have independent release schedules. Follow their own supported dependency versions; their presence in the main navigation does not imply protocol-v2 support. +- General guides and handbook examples show v2. Use the SDK pages in this archive for legacy wrapper APIs such as `.isEnabled` and `.config.payload`. + +Legacy means an older protocol, not a claim about an end-of-support date. See the [migration guide](../../supported-languages/migrating-from-v1.md) for the breaking changes. diff --git a/legacy/v1/_media/type-check-failed.png b/legacy/v1/_media/type-check-failed.png new file mode 100644 index 0000000000000000000000000000000000000000..4ffbd40ba63e3aa37f382746a20ec07e0d5ded1c GIT binary patch literal 105925 zcma&N1z20#)+maUAf-rw;$EOdgS%UCE$$NBiUlX7#k~|OR-6_s4#A2QcXxN!pf}xn zci;2gyYJjT-?y@6)|z8X8FTnZn5weuGYk?81O$XDkRNpy)Z0s!&5Z;7+PC`}vH1neS=qfMdLn031>#w}x0*JXEh9z)w zgQ8-epnbqm7b|CqVA4^;MRb?emd3Zoub>TgP}3}Lq>2dq!TQ3!5QKu|?P&LK+yM^aKL zex^d95#sB5y%tF^_LW`<=q|*-`2J%#KLYr92(27q;Cg7s&dfZ%R0#gZ@{&*n9O|@~ zaw{1bdhC@K9|q#c*ngVeMCMYusXyeW&@i6Wn zR?4~sq=iP7%3M~7!+4jFzbC#Qt+S!$`3u*0{`ex2^_`J$Fk@!P@Q^}Oc>21%c)z{0 z!%keA20yd30ZokR{zo>9;}pFqV;3yqQOZkJ6Q<2x^&BLEt=5!pnQUgtHu7uu)hE}@ z{u=xv;l369vK5IsM5VvBo+9JB*m&f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9@W&f*0qTQ47kF__&5%{m^hOo-$%WZ6g?*cxLD-w7OEBg0b6MN}@=I9_5 z&cI)5{qNV|1Yb2_hxzK*6KC+h<_5tkvHfgs6v-JBG~wBXV@r3f%l|#0CI(3aqe*I#9spqW1ls--B znvM8(;d;l;xJIr-+-`KkZjB58)T+b@%YCTe<+ z8|{=f2LaoP>rs+AdFzgjDt7!&bsDO$>D;gTD*xJY(i;41rFMnBt@8ygV*3Vd=Ho}& zVeFT2GO3a7e{(BN@PntMOn5rKr`r(h2gesLq&zuPBB!asp09{pTU`IK24&K5#Cpe$ zOVpAY#$zk}8o%Qegk@jY`W4payroY=^HVxA|ELY1R z_VYhf`j$QejG*-7!WWz{Ai)tW>Az+*UTORo76%k%a#xb>)np<%D~u1;SM$!I_ zsg!2G|6|vhyf>K!==?um^M+~ygu`-x1GD34WKU}~$14ARLHxt8Y>gHb2!Mv47xe`f zzhD~Eyb$`xsu;DxtN6&~@A7>xWRZvR;g(>-+~>ckUZ31v(kT5^!|8M&8 z5}rYez~&ogAVOa`NG5e^GrqQ$3&O#@fq#pXLHd7x$->7k8LhhamtX$(U;q3va}&Qr zybAAMZu`qc!DOVR3O%p>^2@)J@s^6TboU3zwPLSdtsq^=PD}GIxBZ_w2DKYYS2mH0 r|KBS~%8H9UgUj)H)2@}_8H~$*fTqH~$B>Wh6dZY3m6zo&%-;VGb}n}= literal 0 HcmV?d00001 diff --git a/legacy/v1/browser-sdk/README.md b/legacy/v1/browser-sdk/README.md new file mode 100644 index 0000000..e9764c5 --- /dev/null +++ b/legacy/v1/browser-sdk/README.md @@ -0,0 +1,615 @@ +--- +layout: + visible: true +title: + visible: true +description: + visible: false +tableOfContents: + visible: true +outline: + visible: true +pagination: + visible: true +--- + +{% hint style="info" %} +**Protocol v1 — legacy.** [Current v2 documentation](../../../supported-languages/browser-sdk/README.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) + +Generated from [`@reflag/browser-sdk@1.7.4`](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk); SDK READMEs and code comments remain the source of truth. +{% endhint %} + +# Reflag Browser SDK + +Basic client for [Reflag.com](https://reflag.com). If you're using React, you'll be better off with the Reflag React SDK. + +Reflag supports flag toggling, tracking flag usage, [collecting feedback](#qualitative-feedback-on-beta-flags) on flags, and [remotely configuring flags](#remote-config). + +## Install + +First find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag. + +The package can be imported or used directly in a HTML script tag: + +A. Import module: + +```typescript +import { ReflagClient } from "@reflag/browser-sdk"; + +const user = { + id: 42, + role: "manager", +}; + +const company = { + id: 99, + plan: "enterprise", +}; + +const reflagClient = new ReflagClient({ publishableKey, user, company }); + +await reflagClient.initialize(); + +const { + isEnabled, + config: { payload: question }, + track, + requestFeedback, +} = reflagClient.getFlag("huddle"); + +if (isEnabled) { + // Show flag. When retrieving `isEnabled` the client automatically + // sends a "check" event for the "huddle" flag which is shown in the + // Reflag UI. + + // On usage, call `track` to let Reflag know that a user interacted with the flag + track(); + + // The `payload` is a user-supplied JSON in Reflag that is dynamically picked + // out depending on the user/company. + const question = payload?.question ?? "Tell us what you think of Huddles"; + + // Use `requestFeedback` to create "Send feedback" buttons easily for specific + // flags. This is not related to `track` and you can call them individually. + requestFeedback({ title: question }); +} + +// `track` just calls `reflagClient.track()` to send an event using the same flag key +// You can also use `track` on the client directly to send any custom event. +reflagClient.track("huddle"); + +// similarly, `requestFeedback` just calls `reflagClient.requestFeedback({flagKey: })` +// which you can also call directly: +reflagClient.requestFeedback({ flagKey: "huddle" }); +``` + +B. Script tag (client-side directly in html) + +See [example/browser.html](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/example/browser.html) for a working example: + +```html + + +Loading... + +``` + +### Init options + +Supply these to the constructor call: + +```typescript +type Configuration = { + logger: console; // by default only logs warn/error, by passing `console` you'll log everything + apiBaseUrl?: "https://front.reflag.com"; + credentials?: "include" | "same-origin" | "omit"; // forwarded to fetch requests; "include" also enables credentials for the default EventSource transport + feedback?: undefined; // See FEEDBACK.md + enableTracking?: true; // set to `false` to stop sending track events and user/company updates to Reflag servers. Useful when you're impersonating a user + enableLiveFlagUpdates?: false; // Set to `true` to keep flags up to date over SSE (browser SDK default: false) + eventSourceFactory?: (url: string) => { + // Advanced: provide a custom EventSource-compatible transport + addEventListener: (type: string, cb: (event: any) => void) => void; + close: () => void; + }; + fallbackFlags?: + | string[] + | Record; // Enable these flags if unable to contact reflag.com. Can be a list of flag keys or a record with configuration values + timeoutMs?: number; // Timeout for fetching flags (default: 5000ms) + staleWhileRevalidate?: boolean; // Revalidate in the background when cached flags turn stale to avoid latency in the UI (default: false) + staleTimeMs?: number; // at initialization time flags are loaded from the cache unless they have gone stale. Defaults to 0 which means the cache is disabled. Increase this in the case of a non-SPA + expireTimeMs?: number; // In case we're unable to fetch flags from Reflag, cached/stale flags will be used instead until they expire after `expireTimeMs`. Default is 30 days + offline?: boolean; // Use the SDK in offline mode. Offline mode is useful during testing and local development +}; +``` + +## Migrating from Bucket SDK + +If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: + +- `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) +- `Feature*` classes, and types have been renamed to `Feature*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) +- All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) +- The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags` +- `featureKey` has been renamed to `flagKey` in all methods that accepts that argument +- The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead og `bucket-*` +- The `featuresUpdated` hook has been renamed to `flagsUpdated` +- The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on + +To ease in transition to Reflag SDK, some of the old methods have been preserved as aliases to the new methods: + +- `getFeature` method is an alias for `getFlag` +- `getFeatures` method is an alias for `getFlags` +- `featuresUpdated` hook is an alias for `flagsUpdated` + +If you are running with strict Content Security Policies active on your website, you will need change them as follows: + +- `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com` + +Finally, if you have customized the look & feel of the Feedback component, update `--bucket-feedback-*` CSS classes to `--reflag-feedback-*` + +## Flag toggles + +Reflag determines which flags are active for a given user/company. The user/company is given in the ReflagClient constructor. + +If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. +In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. + +Attributes cannot be nested (multiple levels) and must be either strings, integers or booleans. +Some attributes are special and used in Reflag UI: + +- `name` -- display name for `user`/`company`, +- `email` -- is accepted for `user`s and will be highlighted in the Reflag UI if available, +- `avatar` -- can be provided for both `user` and `company` and should be an URL to an image. + +```ts +const reflagClient = new ReflagClient({ + publishableKey, + user: { + id: "user_123", + name: "John Doe", + email: "john@acme.com" + avatar: "https://example.com/images/udsy6363" + }, + company: { + id: "company_123", + name: "Acme, Inc", + avatar: "https://example.com/images/31232ds" + }, +}); +``` + +To retrieve flags along with their targeting information, use `getFlag(key: string)`: + +```ts +const huddle = reflagClient.getFlag("huddle"); +// { +// isEnabled: true, +// config: { key: "zoom", payload: { ... } }, +// track: () => Promise +// requestFeedback: (options: RequestFeedbackData) => void +// } +``` + +You can use `getFlags()` to retrieve all enabled flags currently. + +```ts +const flags = reflagClient.getFlags(); +// { +// huddle: { +// isEnabled: true, +// targetingVersion: 42, +// config: ... +// } +// } +``` + +`getFlags()` is meant to be more low-level than `getFlag()` and it typically used +by down-stream clients, like the React SDK. + +Note that accessing `isEnabled` on the object returned by `getFlags` does not automatically +generate a `check` event, contrary to the `isEnabled` property on the object returned by `getFlag`. + +## End-user opt-in + +If a flag has end-user opt-in enabled in Reflag, you can list the opt-in options for the current context and set or cancel opt-in for the current user or company. + +```ts +const optInFlags = reflagClient.getOptInFlags(); +// [{ key, name, description, isEnabled, userOptedIn, companyOptedIn, isOptedIn }] + +try { + const response = await reflagClient.setOptIn("huddle", { + optedIn: true, // Use false to cancel this scope's opt-in. + scope: "user", // Use "company" to change the current company's opt-in. + }); + if (!response?.ok) { + console.error("Could not update opt-in"); + } +} catch (error) { + console.error("Could not update opt-in", error); +} +``` + +By default, `setOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. + +User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. + +`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and `flagsUpdated` listeners have been notified when flags change. + +The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. + +The `description` comes from the dedicated SDK-facing opt-in description configured in Reflag. + +When using bootstrapped flags, the first `getOptInFlags()` or `getIsLoadingOptInFlags()` call requests a flags refresh. The list call returns the currently available list synchronously, and the loading getter returns `true` until that refresh succeeds or fails. Normal initialization also exposes loading through the client's state. + +Listen for `optInFlagsLoadingUpdated` to update UI when this loading state changes. `flagsUpdated` is emitted when a successful refresh updates the list. + +If fetching opt-in metadata fails, loading ends without exposing an error. Call `reflagClient.refresh()` to retry. + +## Remote config + +Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. + +Similar to `isEnabled`, each flag has a `config` property. This configuration is managed from within Reflag. +It is managed similar to the way access to flags is managed, but instead of the binary `isEnabled` you can have +multiple configuration values which are given to different user/companies. + +```ts +const flags = reflagClient.getFlags(); +// { +// huddle: { +// isEnabled: true, +// targetingVersion: 42, +// config: { +// key: "gpt-3.5", +// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } +// } +// } +// } +``` + +`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. + +Just as `isEnabled`, accessing `config` on the object returned by `getFlags` does not automatically +generate a `check` event, contrary to the `config` property on the object returned by `getFlag`. + +## Server-side rendering and bootstrapping + +For server-side rendered applications, you can render immediately with pre-fetched flag data by bootstrapping the client. + +### Init options bootstrapped + +```typescript +type Configuration = { + logger: console; // by default only logs warn/error, by passing `console` you'll log everything + apiBaseUrl?: "https://front.reflag.com"; + credentials?: "include" | "same-origin" | "omit"; // forwarded to fetch requests; "include" also enables credentials for the default EventSource transport + feedback?: undefined; // See FEEDBACK.md + enableTracking?: true; // set to `false` to stop sending track events and user/company updates to Reflag servers. Useful when you're impersonating a user + offline?: boolean; // Use the SDK in offline mode. Offline mode is useful during testing and local development + bootstrappedState?: { + context: ReflagContext; + flags: FetchedFlags; + flagStateVersion?: number; + }; // Pre-fetched evaluated state from server-side (see Server-side rendering section) + bootstrappedFlags?: FetchedFlags; // Deprecated: use `bootstrappedState` instead +}; +``` + +### Using `bootstrappedState` + +Use the Node SDK's `getFlagsForBootstrap()` method to pre-fetch evaluated state server-side, then pass the returned object directly to the browser client: + +```typescript +// Server-side: Get bootstrapped state using Node SDK +import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; + +const serverClient = new ReflagNodeClient({ secretKey: "your-secret-key" }); +await serverClient.initialize(); + +const bootstrappedState = serverClient.getFlagsForBootstrap({ + user: { id: "user123", name: "John Doe", email: "john@acme.com" }, + company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, +}); + +// Pass the bootstrapped state to the client using your framework's preferred method +app.get("/", (req, res) => { + res.set("Content-Type", "text/html"); + res.send( + Buffer.from( + ` +
`, + ), + ); +}); + +// Client-side: Initialize with pre-fetched evaluated state +import { ReflagClient } from "@reflag/browser-sdk"; + +const reflagClient = new ReflagClient({ + publishableKey: "your-publishable-key", + bootstrappedState, // Contains context, flags, and optional flagStateVersion +}); + +await reflagClient.initialize(); +const { isEnabled } = reflagClient.getFlag("huddle"); +``` + +The `bootstrappedState` object contains: + +- `context`: the evaluation context used on the server +- `flags`: the evaluated raw flags +- `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping + +If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. + +If a bootstrapped application requests opt-in flags, the browser SDK performs one flags refresh. Applications that do not request opt-in data do not make this request. + +If you previously used `bootstrappedFlags`, migrate like this: + +```typescript +// Before +const { flags } = serverClient.getFlagsForBootstrap(context); +const client = new ReflagClient({ + publishableKey, + user: context.user, + company: context.company, + other: context.other, + bootstrappedFlags: flags, +}); + +// After +const bootstrappedState = serverClient.getFlagsForBootstrap(context); +const client = new ReflagClient({ + publishableKey, + bootstrappedState, +}); +``` + +{% hint style="info" %} +After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. + +Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. +{% endhint %} + +This eliminates loading states and removes the initial render's dependency on the flags API. + +## Context management + +### Updating user/company/other context + +Attributes given for the user/company/other context in the ReflagClient constructor can be updated for use in flag targeting evaluation with the `updateUser()`, `updateCompany()` and `updateOtherContext()` methods. +They return a promise which resolves once the flags have been re-evaluated follow the update of the attributes. + +{% hint style="info" %} +{% endhint %} + +### setContext() + +The `setContext()` method allows you to replace the entire context (user, company, and other attributes) at once. This method is useful when you need to completely change the context, such as when a user logs in or switches between different accounts. + +```ts +await reflagClient.setContext({ + user: { + id: "new-user-123", + name: "Jane Doe", + email: "jane@example.com", + role: "admin", + }, + company: { + id: "company-456", + name: "New Company Inc", + plan: "enterprise", + }, + other: { + feature: "beta", + locale: "en-US", + }, +}); +``` + +The method will: + +- Replace the entire context with the new values +- Re-evaluate all flags based on the new context +- Update the user and company information on Reflag servers +- Return a promise that resolves once the flags have been re-evaluated + +### getContext() + +The `getContext()` method returns the current context being used for flag evaluation. This is useful for debugging or when you need to inspect the current user, company, and other attributes. + +```ts +const currentContext = reflagClient.getContext(); +console.log(currentContext); +// { +// user: { id: "user-123", name: "John Doe", email: "john@example.com" }, +// company: { id: "company-456", name: "Acme Inc", plan: "enterprise" }, +// other: { locale: "en-US", feature: "beta" } +// } +``` + +The returned context object contains: + +- `user`: Current user attributes (if any) +- `company`: Current company attributes (if any) +- `other`: Additional context attributes not related to user or company + +## Toolbar + +The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off. + +Toolbar screenshot + +The toolbar will automatically appear on `localhost`. However, it can also be incredibly useful in production. +You have full control over when it appears through the `toolbar` configuration option passed to the `ReflagClient`. + +You can pass a simple boolean to force the toolbar to appear/disappear: + +```typescript +const client = new ReflagClient({ + // show the toolbar even in production if the user is an internal/admin user + toolbar: user?.isInternal, + ... +}); +``` + +You can also configure the position of the toolbar on the screen: + +```typescript +const client = new ReflagClient({ + toolbar: { + show: true; + position: { + placement: "bottom-left", + offset: {x: "1rem", y: "1rem"} + } + } + ... +}) +``` + +See [the reference](globals.md#toolbaroptions) for details. + +## Qualitative feedback on beta flags + +Reflag can collect qualitative feedback from your users in the form of a [Customer Satisfaction Score](https://en.wikipedia.org/wiki/Customer_satisfaction) and a comment. + +### Automated feedback collection + +The Reflag Browser SDK comes with automated feedback collection mode enabled by default, which lets the Reflag service ask your users for feedback for relevant flags just after they've used them. + +{% hint style="info" %} +To get started with automatic feedback collection, make sure you've set `user` in the `ReflagClient` constructor. +{% endhint %} + +Automated feedback surveys work even if you're not using the SDK to send events to Reflag. +It works because the Reflag Browser SDK maintains a live connection to Reflag's servers and can automatically show a feedback prompt whenever the Reflag servers determines that an event should trigger a prompt - regardless of how this event is sent to Reflag. + +You can find all the options to make changes to the default behavior in the [Reflag feedback documentation](feedback.md). + +### Reflag feedback UI + +Reflag can assist you with collecting your user's feedback by offering a pre-built UI, allowing you to get started with minimal code and effort. + +[Read the Reflag feedback UI documentation](feedback.md) + +### Reflag feedback SDK + +Feedback can be submitted to Reflag using the SDK: + +```ts +reflagClient.feedback({ + flagKey: "my-flag-key", // String (required), copy from Flag feedback tab + score: 5, // Number: 1-5 (optional) + comment: "Absolutely stellar work!", // String (optional) +}); +``` + +### Reflag feedback API + +If you are not using the Reflag Browser SDK, you can still submit feedback using the HTTP API. + +See details in [Feedback HTTP API](https://docs.reflag.com/api/http-api#post-feedback) + +## Tracking flag usage + +The `track` function lets you send events to Reflag to denote flag usage. +By default Reflag expects event names to align with the flag keys, but +you can customize it as you wish. + +```ts +reflagClient.track("huddle", { voiceHuddle: true }); +``` + +## Event listeners + +Event listeners allow for capturing various events occurring in the `ReflagClient`. This is useful to build integrations with other system or for various debugging purposes. The available events are: + +- `check`: Your code used `isEnabled` or `config` for a flag +- `flagsUpdated`: Flags were updated. Either because they were loaded as part of initialization or because the user/company updated +- `optInFlagsLoadingUpdated`: The opt-in flag loading state changed +- `user`: User information updated (similar to the `identify` call used in tracking terminology) +- `company`: Company information updated (sometimes to the `group` call used in tracking terminology) +- `track`: Track event occurred. + +Use the `on()` method to add an event listener to respond to certain events. See the API reference for details on each hook. + +```ts +import { ReflagClient, CheckEvent, RawFlags } from "@reflag/browser-sdk"; + +const client = new ReflagClient({ + // options +}); + +// or add the hooks after construction: +const unsub = client.on("check", (check: CheckEvent) => + console.log(`Check event ${check}`), +); +// use the returned function to unsubscribe, or call `off()` with the same arguments again +unsub(); +``` + +## Zero PII + +The Reflag Browser SDK doesn't collect any metadata and HTTP IP addresses are _not_ being stored. + +For tracking individual users, we recommend using something like database ID as userId, as it's unique and doesn't include any PII (personal identifiable information). If, however, you're using e.g. email address as userId, but prefer not to send any PII to Reflag, you can hash the sensitive data before sending it to Reflag: + +```ts +import reflag from "@reflag/browser-sdk"; +import { sha256 } from "crypto-hash"; + +reflag.user(await sha256("john_doe")); +``` + +## Use of cookies + +The Reflag Browser SDK uses a couple of cookies to support automated feedback surveys. These cookies are not used for tracking purposes and thus should not need to appear in cookie consent forms. + +The two cookies are: + +- `reflag-prompt-${userId}`: store the last automated feedback prompt message ID received to avoid repeating surveys +- `reflag-token-${userId}`: caching a token used to connect to Reflag's live messaging infrastructure that is used to deliver automated feedback surveys in real time. + +## TypeScript + +Types are bundled together with the library and exposed automatically when importing through a package manager. + +## Content Security Policy (CSP) + +If you are running with strict Content Security Policies active on your website, you will need to enable these directives in order to use the SDK: + +| Directive | Values | Reason | +| ----------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | +| connect-src | [https://front.reflag.com](https://front.reflag.com) | API requests plus Server-Sent Events for live flag updates and automated feedback surveys. | +| style-src | 'unsafe-inline' | The feedback UI is styled with inline styles. Not having this directive results unstyled HTML elements. | + +If you are including the Reflag tracking SDK with a ` +``` + +## Internationalization (i18n) + +By default, the feedback UI is written in English. However, you can supply your own +translations by passing an object in the options to either or both of the +`new ReflagClient(options)` or `reflagClient.requestFeedback(options)` calls. +These translations will replace the English ones used by the feedback interface. +See examples below. + +![image](https://github.com/reflagcom/javascript/assets/331790/68805b38-e9f6-4de5-9f55-188216983e3c) + +See [default English localization keys](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) +for a reference of what translation keys can be supplied. + +### Static language configuration + +If you know the language at page load, you can configure your translation keys while +initializing the Reflag Browser SDK: + +```typescript +new ReflagClient({ + publishableKey: "my-publishable-key", + feedback: { + ui: { + translations: { + DefaultQuestionLabel: + "Dans quelle mesure êtes-vous satisfait de cette fonctionnalité ?", + QuestionPlaceholder: + "Comment pouvons-nous améliorer cette fonctionnalité ?", + ScoreStatusDescription: "Choisissez une note et laissez un commentaire", + ScoreStatusLoading: "Chargement...", + ScoreStatusReceived: "La note a été reçue !", + ScoreVeryDissatisfiedLabel: "Très insatisfait", + ScoreDissatisfiedLabel: "Insatisfait", + ScoreNeutralLabel: "Neutre", + ScoreSatisfiedLabel: "Satisfait", + ScoreVerySatisfiedLabel: "Très satisfait", + SuccessMessage: "Merci d'avoir envoyé vos commentaires!", + SendButton: "Envoyer", + }, + }, + }, +}); +``` + +### Runtime language configuration + +If you only know the user's language after the page has loaded, you can provide +translations to either the `reflagClient.requestFeedback(options)` call or +the `autoFeedbackHandler` option before the feedback interface opens. +See examples below. + +```typescript +reflagClient.requestFeedback({ + ... // Other options + translations: { + // your translation keys + } +}) +``` + +### Translations + +When you are collecting feedback through the Reflag automation, you can intercept +the default prompt handling and override the defaults. + +If you set the prompt question in the Reflag app to be one of your own translation +keys, you can even get a translated version of the question you want to ask your +customer in the feedback UI. + +```javascript +new ReflagClient({ + publishableKey: "reflag-publishable-key", + feedback: { + autoFeedbackHandler: (message, handlers) => { + const translatedQuestion = + i18nLookup[message.question] ?? message.question; + handlers.openFeedbackForm({ + title: translatedQuestion, + translations: { + // your static translation keys + }, + }); + }, + }, +}); +``` + +## Custom styling + +You can adapt parts of the look of the Reflag feedback UI by applying CSS custom +properties to your page in your CSS `:root`-scope. + +For example, a dark mode theme might look like this: + +![image](https://github.com/reflagcom/javascript/assets/34348/5d579b7b-a830-4530-8b40-864488a8597e) + +```css +:root { + --reflag-feedback-dialog-background-color: #1e1f24; + --reflag-feedback-dialog-color: rgba(255, 255, 255, 0.92); + --reflag-feedback-dialog-secondary-color: rgba(255, 255, 255, 0.3); + --reflag-feedback-dialog-border: rgba(255, 255, 255, 0.16); + --reflag-feedback-dialog-primary-button-background-color: #655bfa; + --reflag-feedback-dialog-primary-button-color: white; + --reflag-feedback-dialog-input-border-color: rgba(255, 255, 255, 0.16); + --reflag-feedback-dialog-input-focus-border-color: rgba(255, 255, 255, 0.3); + --reflag-feedback-dialog-error-color: #f56565; + + --reflag-feedback-dialog-rating-1-color: #ed8936; + --reflag-feedback-dialog-rating-1-background-color: #7b341e; + --reflag-feedback-dialog-rating-2-color: #dd6b20; + --reflag-feedback-dialog-rating-2-background-color: #652b19; + --reflag-feedback-dialog-rating-3-color: #787c91; + --reflag-feedback-dialog-rating-3-background-color: #3e404c; + --reflag-feedback-dialog-rating-4-color: #38a169; + --reflag-feedback-dialog-rating-4-background-color: #1c4532; + --reflag-feedback-dialog-rating-5-color: #48bb78; + --reflag-feedback-dialog-rating-5-background-color: #22543d; + + --reflag-feedback-dialog-submitted-check-background-color: #38a169; + --reflag-feedback-dialog-submitted-check-color: #ffffff; +} +``` + +Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/src/feedback/ui/index.css). + +## Using your own UI to collect feedback + +You may have very strict design guidelines for your app and maybe the Reflag feedback +UI doesn't quite work for you. In this case, you can implement your own feedback +collection mechanism, which follows your own design guidelines. This is the data +type you need to collect: + +```typescript +type DataToCollect = { + // Customer satisfaction score + score?: 1 | 2 | 3 | 4 | 5; + + // The comment. + comment?: string; +}; +``` + +Either `score` or `comment` must be defined in order to pass validation in the +Reflag API. + +### Manual feedback collection with custom UI + +Examples of a HTML-form that collects the relevant data can be found +in [feedback.html](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/example/feedback/Feedback.jsx). + +Once you have collected the feedback data, pass it along to `reflagClient.feedback()`: + +```javascript +reflagClient.feedback({ + flagKey: "reflag-flag-key", + userId: "your-user-id", + score: 5, + comment: "Best thing I've ever tried!", +}); +``` + +### Intercepting automated feedback survey events + +When using automated feedback surveys, the Reflag service will, when specified, +send a feedback prompt message to your user's instance of the Reflag Browser SDK. +This will result in the feedback UI being opened. + +You can intercept this behavior and open your own custom feedback collection form: + +```typescript +new ReflagClient({ + publishableKey: "reflag-publishable-key", + feedback: { + autoFeedbackHandler: async (promptMessage, handlers) => { + // This opens your custom UI + customFeedbackCollection({ + // The question configured in the Reflag UI for the flag + question: promptMessage.question, + // When the user successfully submits feedback data. + // Use this instead of `reflagClient.feedback()`, otherwise + // the feedback prompt handler will keep being called + // with the same prompt message + onFeedbackSubmitted: (feedback) => { + handlers.reply(feedback); + }, + // When the user closes the custom feedback form + // without leaving any response. + // It is important to feed this back, otherwise + // the feedback prompt handler will keep being called + // with the same prompt message + onFeedbackDismissed: () => { + handlers.reply(null); + }, + }); + }, + }, +}); +``` diff --git a/legacy/v1/browser-sdk/globals.md b/legacy/v1/browser-sdk/globals.md new file mode 100644 index 0000000..be82688 --- /dev/null +++ b/legacy/v1/browser-sdk/globals.md @@ -0,0 +1,5250 @@ +--- +layout: + visible: true +title: + visible: true +description: + visible: false +tableOfContents: + visible: true +outline: + visible: true +pagination: + visible: true +--- + +{% hint style="info" %} +**Protocol v1 — legacy.** [Current v2 documentation](../../../supported-languages/browser-sdk/globals.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) + +Generated from [`@reflag/browser-sdk@1.7.4`](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk); SDK READMEs and code comments remain the source of truth. +{% endhint %} + +# @reflag/browser-sdk + +## Classes + +### ReflagClient + +ReflagClient lets you interact with the Reflag API. + +#### Constructors + +##### new ReflagClient() + +```ts +new ReflagClient(opts: InitOptions): ReflagClient +``` + +Create a new ReflagClient instance. + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +[`InitOptions`](globals.md#initoptions) + +
+ +###### Returns + +[`ReflagClient`](globals.md#reflagclient) + +#### Properties + + + + + + + + + + + + + + + + +
PropertyModifierType
+ + `logger` + + + +`readonly` + + + +[`Logger`](globals.md#logger) + +
+ +#### Methods + +##### applyBootstrappedState() + +```ts +applyBootstrappedState(bootstrappedState: BootstrappedState, triggerEvent: boolean): void +``` + +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDefault value
+ +`bootstrappedState` + + + +[`BootstrappedState`](globals.md#bootstrappedstate) + + + +`undefined` + +
+ +`triggerEvent` + + + +`boolean` + + + +`true` + +
+ +###### Returns + +`void` + +##### feedback() + +```ts +feedback(payload: Feedback): Promise< + | undefined +| Response> +``` + +Submit user feedback to Reflag. Must include either `score` or `comment`, or both. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`payload` + + + +[`Feedback`](globals.md#feedback) + + + +The feedback details to submit. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +The server response. + +##### getConfig() + +```ts +getConfig(): Config +``` + +Get the current configuration. + +###### Returns + +[`Config`](globals.md#config) + +##### getContext() + +```ts +getContext(): ReflagContext +``` + +Get the current context. + +###### Returns + +[`ReflagContext`](globals.md#reflagcontext) + +##### ~~getFeature()~~ + +```ts +getFeature(flagKey: string): Flag +``` + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`flagKey` + + + +`string` + +
+ +###### Returns + +[`Flag`](globals.md#flag) + +###### Deprecated + +Use `getFlag` instead. + +##### ~~getFeatures()~~ + +```ts +getFeatures(): RawFlags +``` + +###### Returns + +[`RawFlags`](globals.md#rawflags) + +###### Deprecated + +Use `getFlags` instead. + +##### getFlag() + +```ts +getFlag(flagKey: string): Flag +``` + +Return a flag. Accessing `isEnabled` or `config` will automatically send a `check` event. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`flagKey` + + + +`string` + + + +The key of the flag to get. + +
+ +###### Returns + +[`Flag`](globals.md#flag) + +A flag. + +##### getFlags() + +```ts +getFlags(): RawFlags +``` + +Returns a map of enabled flags. +Accessing a flag will *not* send a check event +and `isEnabled` does not take any flag overrides +into account. + +###### Returns + +[`RawFlags`](globals.md#rawflags) + +Map of flags. + +##### getIsLoadingOptInFlags() + +```ts +getIsLoadingOptInFlags(): boolean +``` + +Returns whether opt-in flags are loading for the current context. + +Calling this method requests opt-in metadata if it is not already available. + +###### Returns + +`boolean` + +##### getOptInFlags() + +```ts +getOptInFlags(): OptInFlag[] +``` + +Returns opt-in-enabled flags for the current context. + +###### Returns + +[`OptInFlag`](globals.md#optinflag)[] + +##### getState() + +```ts +getState(): State +``` + +###### Returns + +[`State`](globals.md#state) + +##### initialize() + +```ts +initialize(): Promise +``` + +Initialize the Reflag SDK. + +Must be called before calling other SDK methods. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +##### off() + +```ts +off(type: THookType, handler: (args0: HookArgs[THookType]) => void): void +``` + +Remove an event listener + +###### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`THookType` *extends* keyof [`HookArgs`](globals.md#hookargs) + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`type` + + + +`THookType` + + + +Type of event to remove. + +
+ +`handler` + + + +(`args0`: [`HookArgs`](globals.md#hookargs)\[`THookType`\]) => `void` + + + +The same function that was passed to `on`. + +
+ +###### Returns + +`void` + +A function to remove the hook. + +##### on() + +```ts +on(type: THookType, handler: (args0: HookArgs[THookType]) => void): () => void +``` + +Add an event listener + +###### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`THookType` *extends* keyof [`HookArgs`](globals.md#hookargs) + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`type` + + + +`THookType` + + + +Type of events to listen for + +
+ +`handler` + + + +(`args0`: [`HookArgs`](globals.md#hookargs)\[`THookType`\]) => `void` + + + +The function to call when the event is triggered. + +
+ +###### Returns + +`Function` + +A function to remove the hook. + +###### Returns + +`void` + +##### refresh() + +```ts +refresh(): Promise +``` + +Force refresh flags from the API, bypassing cache. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`undefined` \| [`RawFlags`](globals.md#rawflags)\> + +##### requestFeedback() + +```ts +requestFeedback(options: RequestFeedbackData): void +``` + +Display the Reflag feedback form UI programmatically. + +This can be used to collect feedback from users in Reflag in cases where Automated Feedback Surveys isn't appropriate. + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`options` + + + +[`RequestFeedbackData`](globals.md#requestfeedbackdata) + +
+ +###### Returns + +`void` + +##### setContext() + +```ts +setContext(context: ReflagDeprecatedContext): Promise +``` + +Update the context. +Replaces the existing context with a new context. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`context` + + + +[`ReflagDeprecatedContext`](globals.md#reflagdeprecatedcontext) + + + +The context to update. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +##### setOptIn() + +```ts +setOptIn(flagKey: string, options: SetOptInOptions): Promise< + | undefined +| Response> +``` + +Set whether the current user or company has opted into a flag. + +A successful Response is returned after the refreshed flag state confirms +the membership change. HTTP failures return a non-OK Response without +refreshing flags. Offline mode, invalid arguments, or missing scoped context +return undefined. Network and confirmation failures reject the promise; +a confirmation failure may occur after membership changed remotely. + +###### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`flagKey` + + + +`string` + +
+ +`options` + + + +[`SetOptInOptions`](globals.md#setoptinoptions) + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +##### showToolbarToggle() + +```ts +showToolbarToggle(position?: ToolbarPosition): void +``` + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`position`? + + + +[`ToolbarPosition`](globals.md#toolbarposition) + +
+ +###### Returns + +`void` + +##### stop() + +```ts +stop(): Promise +``` + +Stop the SDK. +This will stop any automated feedback surveys. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +##### track() + +```ts +track(eventName: string, attributes?: + | null + | Record): Promise< + | undefined +| Response> +``` + +Track an event in Reflag. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`eventName` + + + +`string` + + + +The name of the event. + +
+ +`attributes`? + + + + \| `null` \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + + + +Any attributes you want to attach to the event. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +##### updateCompany() + +```ts +updateCompany(company: {}): Promise +``` + +Update the company context. +Performs a shallow merge with the existing company context. +It will not update the context if nothing has changed. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`company` + + + +\{\} + + + +The company details. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +##### updateFlags() + +```ts +updateFlags( + flags: RawFlags, + triggerEvent: boolean, + flagStateVersion?: number): void +``` + +Update the flags. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDefault valueDescription
+ +`flags` + + + +[`RawFlags`](globals.md#rawflags) + + + +`undefined` + + + +The flags to update. + +
+ +`triggerEvent` + + + +`boolean` + + + +`true` + + + +Whether to trigger the `flagsUpdated` event. + +
+ +`flagStateVersion`? + + + +`number` + + + +`undefined` + + + +‐ + +
+ +###### Returns + +`void` + +##### updateOtherContext() + +```ts +updateOtherContext(otherContext: {}): Promise +``` + +Update the company context. +Performs a shallow merge with the existing company context. +It will not update the context if nothing has changed. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`otherContext` + + + +\{\} + + + +Additional context. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +##### updateUser() + +```ts +updateUser(user: {}): Promise +``` + +Update the user context. +Performs a shallow merge with the existing user context. +It will not update the context if nothing has changed. + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`user` + + + +\{\} + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +## Interfaces + +### CheckEvent + +Event representing checking the flag evaluation result + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `action` + + + +`"check-is-enabled"` \| `"check-config"` + + + +`check-is-enabled` means `isEnabled` was checked, `check-config` means `config` was checked. + +
+ + `evaluationErrors?` + + + +\{ `code`: `string`; `field`: `string`; `message`: `string`; `operator`: `string`; \}[] + + + +Non-fatal diagnostics produced while evaluating the flag. + +
+ + `key` + + + +`string` + + + +Flag key. + +
+ + ~~`missingContextFields?`~~ + + + +`string`[] + + + +Missing context fields. + +**Deprecated** + +Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. + +
+ + `ruleEvaluationResults?` + + + +`boolean`[] + + + +Rule evaluation results. + +
+ + `value?` + + + + \| `boolean` \| \{ `key`: `string`; `payload`: `any`; \} + + + +Result of flag or configuration evaluation. +If `action` is `check-is-enabled`, this is the result of the flag evaluation and `value` is a boolean. +If `action` is `check-config`, this is the result of the configuration evaluation. + +
+ + `version?` + + + +`number` + + + +Version of targeting rules. + +
+ +*** + +### CompanyContext + +Context is a set of key-value pairs. +This is used to determine if feature targeting matches and to track events. +Id should always be present so that it can be referenced to an existing company. + +#### Indexable + +```ts +[key: string]: ContextValue +``` + +#### Properties + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `id` + + + +`undefined` \| `string` \| `number` + + + +Company id + +
+ + `name?` + + + +`string` + + + +Company name + +
+ +*** + +### Config + +ReflagClient configuration. + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `apiBaseUrl` + + + +`string` + + + +Base URL of Reflag servers. + +
+ + `appBaseUrl` + + + +`string` + + + +Base URL of the Reflag web app. + +
+ + `bootstrapped` + + + +`boolean` + + + +Whether the client is bootstrapped. + +
+ + `enableTracking` + + + +`boolean` + + + +Whether to enable tracking. + +
+ + `offline` + + + +`boolean` + + + +Whether to enable offline mode. + +
+ + `sseBaseUrl` + + + +`string` + + + +Base URL used for pubsub SSE connections. +Defaults to `apiBaseUrl`. + +
+ +*** + +### FeedbackScoreSubmission + +#### Properties + + + + + + + + + + + + + + + + + + + + + + +
PropertyType
+ + `feedbackId?` + + + +`string` + +
+ + `question` + + + +`string` + +
+ + `score` + + + +`number` + +
+ +*** + +### FeedbackSubmission + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyType
+ + `comment` + + + +`string` + +
+ + `feedbackId?` + + + +`string` + +
+ + `question` + + + +`string` + +
+ + `score` + + + +`number` + +
+ +*** + +### Flag + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `config` + + + +[`FlagRemoteConfig`](globals.md#flagremoteconfig) + + + +‐ + +
+ + `isEnabled` + + + +`boolean` + + + +Result of flag flag evaluation. +Note: Does not take local overrides into account. + +
+ + `isEnabledOverride` + + + +`null` \| `boolean` + + + +The current override status of isEnabled for the flag. + +
+ + `requestFeedback` + + + +(`options`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`RequestFeedbackData`](globals.md#requestfeedbackdata), `"featureId"` \| `"flagKey"`\>) => `void` + + + +Function to request feedback for this flag. + +
+ + `track` + + + +() => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + + + +Function to send analytics events for this flag. + +
+ +#### Methods + +##### setIsEnabledOverride() + +```ts +setIsEnabledOverride(isEnabled: null | boolean): void +``` + +Set the override status for isEnabled for the flag. +Set to `null` to remove the override. + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`isEnabled` + + + +`null` \| `boolean` + +
+ +###### Returns + +`void` + +*** + +### HookArgs + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `check` + + + +[`CheckEvent`](globals.md#checkevent) + + + +‐ + +
+ + `company` + + + +[`CompanyContext`](globals.md#companycontext) + + + +‐ + +
+ + ~~`featuresUpdated`~~ + + + +[`RawFlags`](globals.md#rawflags) + + + +**Deprecated** + +Use `flagsUpdated` instead. + +
+ + `flagsUpdated` + + + +[`RawFlags`](globals.md#rawflags) + + + +‐ + +
+ + `optInFlagsLoadingUpdated` + + + +`boolean` + + + +‐ + +
+ + `stateUpdated` + + + +[`State`](globals.md#state) + + + +‐ + +
+ + `track` + + + +[`TrackEvent`](globals.md#trackevent) + + + +‐ + +
+ + `user` + + + +[`UserContext`](globals.md#usercontext) + + + +‐ + +
+ +*** + +### Logger + +#### Methods + +##### debug() + +```ts +debug(message: string, ...args: any[]): void +``` + +###### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`message` + + + +`string` + +
+ +...`args` + + + +`any`[] + +
+ +###### Returns + +`void` + +##### error() + +```ts +error(message: string, ...args: any[]): void +``` + +###### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`message` + + + +`string` + +
+ +...`args` + + + +`any`[] + +
+ +###### Returns + +`void` + +##### info() + +```ts +info(message: string, ...args: any[]): void +``` + +###### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`message` + + + +`string` + +
+ +...`args` + + + +`any`[] + +
+ +###### Returns + +`void` + +##### warn() + +```ts +warn(message: string, ...args: any[]): void +``` + +###### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`message` + + + +`string` + +
+ +...`args` + + + +`any`[] + +
+ +###### Returns + +`void` + +*** + +### OnScoreSubmitResult + +#### Properties + + + + + + + + + + + + + + +
PropertyType
+ + `feedbackId` + + + +`string` + +
+ +*** + +### OpenFeedbackFormOptions + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `key` + + + +`string` + + + +‐ + +
+ + `onClose?` + + + +() => `void` + + + +‐ + +
+ + `onDismiss?` + + + +() => `void` + + + +‐ + +
+ + `onScoreSubmit?` + + + +(`data`: [`FeedbackScoreSubmission`](globals.md#feedbackscoresubmission)) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`OnScoreSubmitResult`](globals.md#onscoresubmitresult)\> + + + +‐ + +
+ + `onSubmit` + + + +(`data`: [`FeedbackSubmission`](globals.md#feedbacksubmission)) => \| `void` \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + + + +‐ + +
+ + `openWithCommentVisible?` + + + +`boolean` + + + +Open the form with both the score and comment fields visible. +Defaults to `false` + +
+ + `position?` + + + +[`Position`](globals.md#position) + + + +Control the placement and behavior of the feedback form. + +
+ + `title?` + + + +`string` + + + +‐ + +
+ + `translations?` + + + +[`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`FeedbackTranslations`](globals.md#feedbacktranslations)\> + + + +Add your own custom translations for the feedback form. +Undefined translation keys fall back to english defaults. + +
+ +*** + +### ReflagContext + +Context is a set of key-value pairs. +This is used to determine if feature targeting matches and to track events. + +#### Extended by + +- [`ReflagDeprecatedContext`](globals.md#reflagdeprecatedcontext) + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `company?` + + + +[`CompanyContext`](globals.md#companycontext) + + + +Company related context. If you provide `id` Reflag will enrich the evaluation context with +company attributes on Reflag servers. + +
+ + `other?` + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`ContextValue`](globals.md#contextvalue)\> + + + +Context which is not related to a user or a company. + +
+ + `user?` + + + +[`UserContext`](globals.md#usercontext) + + + +User related context. If you provide `id` Reflag will enrich the evaluation context with +user attributes on Reflag servers. + +
+ +*** + +### ~~ReflagDeprecatedContext~~ + +**`Internal`** + +#### Deprecated + +Use `ReflagContext` instead, this interface will be removed in the next major version + +#### Extends + +- [`ReflagContext`](globals.md#reflagcontext) + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + ~~`company?`~~ + + + +[`CompanyContext`](globals.md#companycontext) + + + +Company related context. If you provide `id` Reflag will enrich the evaluation context with +company attributes on Reflag servers. + +
+ + ~~`other?`~~ + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`ContextValue`](globals.md#contextvalue)\> + + + +Context which is not related to a user or a company. + +
+ + ~~`otherContext?`~~ + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`ContextValue`](globals.md#contextvalue)\> + + + +Context which is not related to a user or a company. + +**Deprecated** + +Use `other` instead, this property will be removed in the next major version + +
+ + ~~`user?`~~ + + + +[`UserContext`](globals.md#usercontext) + + + +User related context. If you provide `id` Reflag will enrich the evaluation context with +user attributes on Reflag servers. + +
+ +*** + +### ToolbarPosition + +#### Properties + + + + + + + + + + + + + + + + + + +
PropertyType
+ + `offset?` + + + +[`Offset`](globals.md#offset) + +
+ + `placement` + + + +[`DialogPlacement`](globals.md#dialogplacement) + +
+ +*** + +### UserContext + +Context is a set of key-value pairs. +This is used to determine if feature targeting matches and to track events. +Id should always be present so that it can be referenced to an existing user. + +#### Indexable + +```ts +[key: string]: ContextValue +``` + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `email?` + + + +`string` + + + +User email + +
+ + `id` + + + +`undefined` \| `string` \| `number` + + + +User id + +
+ + `name?` + + + +`string` + + + +User name + +
+ +## Type Aliases + +### BootstrappedState + +```ts +type BootstrappedState = { + context: ReflagContext; + flags: RawFlags; + flagStateVersion: number; +}; +``` + +Pre-fetched evaluated state used to bootstrap the client. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `context` + + + +[`ReflagContext`](globals.md#reflagcontext) + +
+ + `flags` + + + +[`RawFlags`](globals.md#rawflags) + +
+ + `flagStateVersion`? + + + +`number` + +
+ +*** + +### ContextValue + +```ts +type ContextValue = DefinedContextValue | undefined; +``` + +A context value. Object properties set to `undefined` are omitted. + +*** + +### DefinedContextValue + +```ts +type DefinedContextValue = + | string + | number + | boolean + | null + | DefinedContextValue[] +| {}; +``` + +A JSON-compatible context value that is not `undefined`. + +*** + +### DialogPlacement + +```ts +type DialogPlacement = "bottom-right" | "bottom-left" | "top-right" | "top-left"; +``` + +*** + +### EventSourceFactory() + +```ts +type EventSourceFactory = (url: string) => EventSourceLike; +``` + +#### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`url` + + + +`string` + +
+ +#### Returns + +[`EventSourceLike`](globals.md#eventsourcelike) + +*** + +### EventSourceLike + +```ts +type EventSourceLike = { + addEventListener: (type: string, cb: (event: any) => void) => void; + close: () => void; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `addEventListener` + + + +(`type`: `string`, `cb`: (`event`: `any`) => `void`) => `void` + +
+ + `close` + + + +() => `void` + +
+ +*** + +### FallbackFlagOverride + +```ts +type FallbackFlagOverride = + | { + key: string; + payload: any; + } + | true; +``` + +*** + +### Feedback + +```ts +type Feedback = UnassignedFeedback & { + companyId: string; + userId: string; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`companyId`? + + + +`string` + + + +Company ID from your own application. + +
+ +`userId`? + + + +`string` + + + +User ID from your own application. + +
+ +*** + +### FeedbackOptions + +```ts +type FeedbackOptions = { + autoFeedbackHandler: FeedbackPromptHandler; + enableAutoFeedback: boolean; + ui: { + position: Position; + translations: Partial; + }; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `autoFeedbackHandler`? + + + +[`FeedbackPromptHandler`](globals.md#feedbackprompthandler) + + + +‐ + +
+ + `enableAutoFeedback`? + + + +`boolean` + + + +Enables automatic feedback prompting if it's set up in Reflag + +
+ + `ui`? + + + +\{ + `position`: [`Position`](globals.md#position); + `translations`: [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`FeedbackTranslations`](globals.md#feedbacktranslations)\>; + \} + + + +With these options you can override the look of the feedback prompt + +
+ +`ui.position`? + + + +[`Position`](globals.md#position) + + + +Control the placement and behavior of the feedback form. + +
+ +`ui.translations`? + + + +[`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`FeedbackTranslations`](globals.md#feedbacktranslations)\> + + + +Add your own custom translations for the feedback form. +Undefined translation keys fall back to english defaults. + +
+ +*** + +### FeedbackPrompt + +```ts +type FeedbackPrompt = { + featureId: string; + promptId: string; + question: string; + showAfter: Date; + showBefore: Date; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `featureId` + + + +`string` + + + +Feature ID from Reflag + +
+ + `promptId` + + + +`string` + + + +Id of the prompt + +
+ + `question` + + + +`string` + + + +Specific question user was asked + +
+ + `showAfter` + + + +[`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) + + + +Feedback prompt should appear only after this time + +
+ + `showBefore` + + + +[`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) + + + +Feedback prompt will not be shown after this time + +
+ +*** + +### FeedbackPromptHandler() + +```ts +type FeedbackPromptHandler = (prompt: FeedbackPrompt, handlers: FeedbackPromptHandlerCallbacks) => void; +``` + +#### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`prompt` + + + +[`FeedbackPrompt`](globals.md#feedbackprompt) + +
+ +`handlers` + + + +[`FeedbackPromptHandlerCallbacks`](globals.md#feedbackprompthandlercallbacks) + +
+ +#### Returns + +`void` + +*** + +### FeedbackPromptHandlerCallbacks + +```ts +type FeedbackPromptHandlerCallbacks = { + openFeedbackForm: (options: FeedbackPromptHandlerOpenFeedbackFormOptions) => void; + reply: FeedbackPromptReplyHandler; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `openFeedbackForm` + + + +(`options`: [`FeedbackPromptHandlerOpenFeedbackFormOptions`](globals.md#feedbackprompthandleropenfeedbackformoptions)) => `void` + +
+ + `reply` + + + +[`FeedbackPromptReplyHandler`](globals.md#feedbackpromptreplyhandler) + +
+ +*** + +### FeedbackPromptHandlerOpenFeedbackFormOptions + +```ts +type FeedbackPromptHandlerOpenFeedbackFormOptions = Omit; +``` + +*** + +### FeedbackPromptReply + +```ts +type FeedbackPromptReply = { + comment: string; + companyId: string; + question: string; + score: number; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `comment`? + + + +`string` + +
+ + `companyId`? + + + +`string` + +
+ + `question` + + + +`string` + +
+ + `score`? + + + +`number` + +
+ +*** + +### FeedbackPromptReplyHandler() + +```ts +type FeedbackPromptReplyHandler = (reply: T) => T extends null ? Promise : Promise<{ + feedbackId: string; +}>; +``` + +#### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`T` *extends* [`FeedbackPromptReply`](globals.md#feedbackpromptreply) \| `null` + +
+ +#### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`reply` + + + +`T` + +
+ +#### Returns + +`T` *extends* `null` ? [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> : [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<\{ + `feedbackId`: `string`; + \}\> + +*** + +### FeedbackTranslations + +```ts +type FeedbackTranslations = { + DefaultQuestionLabel: string; + QuestionPlaceholder: string; + ScoreDissatisfiedLabel: string; + ScoreNeutralLabel: string; + ScoreSatisfiedLabel: string; + ScoreStatusDescription: string; + ScoreStatusLoading: string; + ScoreStatusReceived: string; + ScoreVeryDissatisfiedLabel: string; + ScoreVerySatisfiedLabel: string; + SendButton: string; + SuccessMessage: string; +}; +``` + +You can use this to override text values in the feedback form +with desired language translation + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `DefaultQuestionLabel` + + + +`string` + +
+ + `QuestionPlaceholder` + + + +`string` + +
+ + `ScoreDissatisfiedLabel` + + + +`string` + +
+ + `ScoreNeutralLabel` + + + +`string` + +
+ + `ScoreSatisfiedLabel` + + + +`string` + +
+ + `ScoreStatusDescription` + + + +`string` + +
+ + `ScoreStatusLoading` + + + +`string` + +
+ + `ScoreStatusReceived` + + + +`string` + +
+ + `ScoreVeryDissatisfiedLabel` + + + +`string` + +
+ + `ScoreVerySatisfiedLabel` + + + +`string` + +
+ + `SendButton` + + + +`string` + +
+ + `SuccessMessage` + + + +`string` + +
+ +*** + +### FlagOverrides + +```ts +type FlagOverrides = Record; +``` + +*** + +### FlagRemoteConfig + +```ts +type FlagRemoteConfig = + | { + key: string; + payload: any; + } + | { + key: undefined; + payload: undefined; +}; +``` + +A remotely managed configuration value for a flag. + +#### Type declaration + +\{ + `key`: `string`; + `payload`: `any`; + \} + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`key` + + + +`string` + + + +The key of the matched configuration value. + +
+ +`payload` + + + +`any` + + + +The optional user-supplied payload data. + +
+ +\{ + `key`: `undefined`; + `payload`: `undefined`; + \} + + + + + + + + + + + + + + + + + + +
NameType
+ +`key` + + + +`undefined` + +
+ +`payload` + + + +`undefined` + +
+ +*** + +### InitOptions + +```ts +type InitOptions = ReflagDeprecatedContext & { + apiBaseUrl: string; + appBaseUrl: string; + bootstrappedFlags: RawFlags; + bootstrappedState: BootstrappedState; + credentials: "include" | "same-origin" | "omit"; + enableLiveFlagUpdates: boolean; + enableTracking: boolean; + eventSourceFactory: EventSourceFactory; + expireTimeMs: number; + fallbackFlags: | string[] + | Record; + feedback: FeedbackOptions; + logger: Logger; + offline: boolean; + publishableKey: string; + sdkVersion: string; + sseBaseUrl: string; + staleTimeMs: number; + staleWhileRevalidate: boolean; + storage: StorageAdapter; + timeoutMs: number; + toolbar: ToolbarOptions; + trackingQueue: { + flushDelayMs: number; + maxSize: number; + retryBaseDelayMs: number; + retryMaxDelayMs: number; + }; +}; +``` + +ReflagClient initialization options. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`apiBaseUrl`? + + + +`string` + + + +Base URL of Reflag servers. You can override this to use your mocked server. + +
+ +`appBaseUrl`? + + + +`string` + + + +Base URL of the Reflag web app. Links open ín this app by default. + +
+ +`bootstrappedFlags`? + + + +[`RawFlags`](globals.md#rawflags) + + + +Pre-fetched flags used for the initial flag state. +The client fetches opt-in metadata on demand when opt-in flags are requested. + +**Deprecated** + +Use `bootstrappedState` instead. + +
+ +`bootstrappedState`? + + + +[`BootstrappedState`](globals.md#bootstrappedstate) + + + +Pre-fetched evaluated state used for the initial flag state. +The client fetches opt-in metadata on demand when opt-in flags are requested. + +
+ +`credentials`? + + + +`"include"` \| `"same-origin"` \| `"omit"` + + + +When proxying requests, you may want to include credentials like cookies +so you can authorize the request in the proxy. +This option controls the `credentials` option of the fetch API. + +
+ +`enableLiveFlagUpdates`? + + + +`boolean` + + + +Whether to enable live flag updates. + +When enabled, the SDK opens a Server-Sent Events (SSE) connection and +refreshes flag definitions automatically whenever they change on the +server, without relying on context changes or manual refreshes. + +Defaults to `false` in the browser SDK. + +
+ +`enableTracking`? + + + +`boolean` + + + +Whether to enable tracking. Defaults to `true`. + +
+ +`eventSourceFactory`? + + + +[`EventSourceFactory`](globals.md#eventsourcefactory) + + + +Optional factory used to create SSE connections. + +By default the SDK uses the global `EventSource` implementation available +in browsers. This option is intended for alternative runtimes where you +need to provide an EventSource-compatible transport manually. The React +Native wrapper already injects a transport automatically. + +
+ +`expireTimeMs`? + + + +`number` + + + +If set, flags will be cached between page loads for this duration + +
+ +`fallbackFlags`? + + + + \| `string`[] + \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FallbackFlagOverride`](globals.md#fallbackflagoverride)\> + + + +Flag keys for which `isEnabled` should fallback to true +if SDK fails to fetch flags from Reflag servers. If a record +is supplied instead of array, the values of each key represent the +configuration values and `isEnabled` is assume `true`. + +
+ +`feedback`? + + + +[`FeedbackOptions`](globals.md#feedbackoptions) + + + +AutoFeedback specific configuration + +
+ +`logger`? + + + +[`Logger`](globals.md#logger) + + + +You can provide a logger to see the logs of the network calls. +This is undefined by default. +For debugging purposes you can just set the browser console to this property: +```javascript +options.logger = window.console; +``` + +
+ +`offline`? + + + +`boolean` + + + +Whether to enable offline mode. Defaults to `false`. + +
+ +`publishableKey` + + + +`string` + + + +Publishable key for authentication + +
+ +`sdkVersion`? + + + +`string` + + + +Version of the SDK + +
+ +`sseBaseUrl`? + + + +`string` + + + +**Deprecated** + +SSE now uses the same origin as `apiBaseUrl` by default. +Override only if you need a separate pubsub host temporarily. + +
+ +`staleTimeMs`? + + + +`number` + + + +Stale flags will be returned if staleWhileRevalidate is true if no new flags can be fetched + +
+ +`staleWhileRevalidate`? + + + +`boolean` + + + +If set to true stale flags will be returned while refetching flags + +
+ +`storage`? + + + +[`StorageAdapter`](globals.md#storageadapter) + + + +Optional storage adapter used for caching flags and overrides. +Useful for React Native (AsyncStorage). + +
+ +`timeoutMs`? + + + +`number` + + + +Timeout in milliseconds when fetching flags + +
+ +`toolbar`? + + + +[`ToolbarOptions`](globals.md#toolbaroptions) + + + +Toolbar configuration + +
+ +`trackingQueue`? + + + +\{ + `flushDelayMs`: `number`; + `maxSize`: `number`; + `retryBaseDelayMs`: `number`; + `retryMaxDelayMs`: `number`; + \} + + + +Queue settings for tracking updates sent to `/bulk`. +Applies to user/company updates, check events, and prompt events. +Events are buffered in memory and flushed in the background. + +
+ +`trackingQueue.flushDelayMs`? + + + +`number` + + + +Delay in milliseconds before flushing queued events. +Lower values send sooner; slightly higher values batch better. +Defaults to 200ms. + +
+ +`trackingQueue.maxSize`? + + + +`number` + + + +Maximum number of queued events retained locally. +Oldest events are dropped when the cap is exceeded. +Defaults to 100. + +
+ +`trackingQueue.retryBaseDelayMs`? + + + +`number` + + + +Deprecated: retries are no longer performed for bulk delivery. + +
+ +`trackingQueue.retryMaxDelayMs`? + + + +`number` + + + +Deprecated: retries are no longer performed for bulk delivery. + +
+ +*** + +### Offset + +```ts +type Offset = { + x: string | number; + y: string | number; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `x`? + + + +`string` \| `number` + + + +Offset from the nearest horizontal screen edge after placement is resolved + +
+ + `y`? + + + +`string` \| `number` + + + +Offset from the nearest vertical screen edge after placement is resolved + +
+ +*** + +### OptInFlag + +```ts +type OptInFlag = RawFlagOptIn & { + isEnabled: boolean; + key: string; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`isEnabled` + + + +`boolean` + + + +Result of flag evaluation. + +
+ +`key` + + + +`string` + + + +Flag key. + +
+ +*** + +### PopoverPlacement + +```ts +type PopoverPlacement = Placement; +``` + +*** + +### Position + +```ts +type Position = + | { + type: "MODAL"; + } + | { + offset: Offset; + placement: DialogPlacement; + type: "DIALOG"; + } + | { + anchor: any | null; + placement: PopoverPlacement; + type: "POPOVER"; +}; +``` + +*** + +### RawFlag + +```ts +type RawFlag = { + config: { + evaluationErrors: RawFlag["evaluationErrors"]; + key: string; + missingContextFields: string[]; + payload: any; + ruleEvaluationResults: boolean[]; + version: number; + }; + evaluationErrors: { + code: string; + field: string; + message: string; + operator: string; + }[]; + isEnabled: boolean; + isEnabledOverride: boolean | null; + key: string; + missingContextFields: string[]; + optIn: RawFlagOptIn | null; + optInEnabled: boolean; + ruleEvaluationResults: boolean[]; + targetingVersion: number; +}; +``` + +A flag fetched from the server. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `config`? + + + +\{ + `evaluationErrors`: [`RawFlag`](globals.md#rawflag)\[`"evaluationErrors"`\]; + `key`: `string`; + `missingContextFields`: `string`[]; + `payload`: `any`; + `ruleEvaluationResults`: `boolean`[]; + `version`: `number`; + \} + + + +Optional user-defined dynamic configuration. + +
+ +`config.evaluationErrors`? + + + +[`RawFlag`](globals.md#rawflag)\[`"evaluationErrors"`\] + + + +Non-fatal diagnostics produced while evaluating targeting rules. + +
+ +`config.key` + + + +`string` + + + +The key of the matched configuration value. + +
+ +`config.missingContextFields`? + + + +`string`[] + + + +The missing context fields. + +**Deprecated** + +Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. + +
+ +`config.payload`? + + + +`any` + + + +The optional user-supplied payload data. + +
+ +`config.ruleEvaluationResults`? + + + +`boolean`[] + + + +The rule evaluation results. + +
+ +`config.version`? + + + +`number` + + + +The version of the matched configuration value. + +
+ + `evaluationErrors`? + + + +\{ + `code`: `string`; + `field`: `string`; + `message`: `string`; + `operator`: `string`; + \}[] + + + +Non-fatal diagnostics produced while evaluating targeting rules. + +
+ + `isEnabled` + + + +`boolean` + + + +Result of flag evaluation. +Note: does not take local overrides into account. + +
+ + `isEnabledOverride`? + + + +`boolean` \| `null` + + + +If not null or undefined, the result is being overridden locally + +
+ + `key` + + + +`string` + + + +Flag key. + +
+ + `missingContextFields`? + + + +`string`[] + + + +Missing context fields. + +**Deprecated** + +Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. + +
+ + `optIn`? + + + +[`RawFlagOptIn`](globals.md#rawflagoptin) \| `null` + + + +Opt-in metadata for this flag and the current context. + +
+ + `optInEnabled`? + + + +`boolean` + + + +Whether end-user opt-in is enabled for this flag. + +
+ + `ruleEvaluationResults`? + + + +`boolean`[] + + + +Rule evaluation results. + +
+ + `targetingVersion`? + + + +`number` + + + +Version of targeting rules. + +
+ +*** + +### RawFlagOptIn + +```ts +type RawFlagOptIn = { + companyOptedIn: boolean; + description: string | null; + isOptedIn: boolean; + name: string; + userOptedIn: boolean; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `companyOptedIn` + + + +`boolean` + + + +Whether the current company has opted into the flag. + +
+ + `description` + + + +`string` \| `null` + + + +SDK-facing opt-in description. + +
+ + `isOptedIn` + + + +`boolean` + + + +Whether either the current user or company has opted into the flag. + +
+ + `name` + + + +`string` + + + +Display name of the opt-in flag. + +
+ + `userOptedIn` + + + +`boolean` + + + +Whether the current user has opted into the flag. + +
+ +*** + +### RawFlags + +```ts +type RawFlags = Record; +``` + +*** + +### RequestFeedbackData + +```ts +type RequestFeedbackData = Omit & { + companyId: string; + flagKey: string; + onAfterSubmit: (data: FeedbackSubmission) => void; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`companyId`? + + + +`string` + + + +Company ID from your own application. + +
+ +`flagKey` + + + +`string` + + + +Flag key. + +
+ +`onAfterSubmit`? + + + +(`data`: [`FeedbackSubmission`](globals.md#feedbacksubmission)) => `void` + + + +Allows you to handle a copy of the already submitted +feedback. + +This can be used for side effects, such as storing a +copy of the feedback in your own application or CRM. + +
+ +*** + +### RequestFeedbackOptions + +```ts +type RequestFeedbackOptions = RequestFeedbackData & { + userId: string; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`userId` + + + +`string` + + + +User ID from your own application. + +
+ +*** + +### SetOptInOptions + +```ts +type SetOptInOptions = { + optedIn: boolean; + scope?: "user" | "company"; +}; +``` + +Options for changing the current user or company's opt-in membership. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `optedIn` + + + +`boolean` + + + +Whether the scoped subject has opted in. + +
+ + `scope`? + + + +`"user"` \| `"company"` + + + +Whether to update the current user or current company. Defaults to `user`. + +
+ +*** + +### State + +```ts +type State = "idle" | "initializing" | "initialized" | "stopped"; +``` + +State of the client. + +*** + +### StorageAdapter + +```ts +type StorageAdapter = { + getItem: Promise; + removeItem: Promise; + setItem: Promise; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `getItem()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`null` \| `string`\> + +
+ + `removeItem()`? + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +
+ + `setItem()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +
+ +*** + +### ToolbarOptions + +```ts +type ToolbarOptions = + | boolean + | { + position: ToolbarPosition; + show: boolean; +}; +``` + +Toolbar options. + +*** + +### TrackEvent + +```ts +type TrackEvent = { + attributes: | Record + | null; + company: CompanyContext; + eventName: string; + user: UserContext; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `attributes`? + + + + \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + \| `null` + +
+ + `company`? + + + +[`CompanyContext`](globals.md#companycontext) + +
+ + `eventName` + + + +`string` + +
+ + `user` + + + +[`UserContext`](globals.md#usercontext) + +
+ +*** + +### UnassignedFeedback + +```ts +type UnassignedFeedback = { + comment: string; + feedbackId: string; + flagKey: string; + promptedQuestion: string; + promptId: string; + question: string; + score: number; + source: "prompt" | "sdk" | "widget"; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `comment`? + + + +`string` + + + +User supplied comment about your flag. + +
+ + `feedbackId`? + + + +`string` + + + +Reflag feedback ID + +
+ + `flagKey` + + + +`string` + + + +Flag key. + +
+ + `promptedQuestion`? + + + +`string` + + + +The original question. +This only needs to be populated if the feedback was submitted through the automated feedback surveys channel. + +
+ + `promptId`? + + + +`string` + + + +Reflag feedback prompt ID. + +This only exists if the feedback was submitted +as part of an automated prompt from Reflag. + +Used for internal state management of automated +feedback. + +
+ + `question`? + + + +`string` + + + +The question that was presented to the user. + +
+ + `score`? + + + +`number` + + + +Customer satisfaction score. + +
+ + `source`? + + + +`"prompt"` \| `"sdk"` \| `"widget"` + + + +Source of the feedback, depending on how the user was asked +- `prompt` - Feedback submitted by way of an automated feedback survey (prompted) +- `widget` - Feedback submitted via `requestFeedback` +- `sdk` - Feedback submitted via `feedback` + +
+ +## Variables + +### DEFAULT\_TRANSLATIONS + +```ts +const DEFAULT_TRANSLATIONS: FeedbackTranslations; +``` + +```tsx +import { FeedbackTranslations } from "../types"; +/** + * {@includeCode ./defaultTranslations.tsx} + */ +export const DEFAULT_TRANSLATIONS: FeedbackTranslations = { + DefaultQuestionLabel: "How satisfied are you with this feature?", + QuestionPlaceholder: "Write a comment", + ScoreStatusDescription: "Pick a score and leave a comment", + ScoreStatusLoading: "Saving score, please wait...", + ScoreStatusReceived: "Score has been received!", + ScoreVeryDissatisfiedLabel: "Very dissatisfied (1/5)", + ScoreDissatisfiedLabel: "Dissatisfied (2/5)", + ScoreNeutralLabel: "Neutral (3/5)", + ScoreSatisfiedLabel: "Satisfied (4/5)", + ScoreVerySatisfiedLabel: "Very satisfied (5/5)", + SuccessMessage: "Feedback received, thank you!", + SendButton: "Send feedback", +}; +``` + +*** + +### feedbackContainerId + +```ts +const feedbackContainerId: "reflag-feedback-dialog-container" = "reflag-feedback-dialog-container"; +``` + +ID of HTML DIV element which contains the feedback dialog + +*** + +### propagatedEvents + +```ts +const propagatedEvents: string[]; +``` + +These events will be propagated to the feedback dialog + +#### See + +[https://developer.mozilla.org/en-US/docs/Web/API/Element#events](https://developer.mozilla.org/en-US/docs/Web/API/Element#events) diff --git a/legacy/v1/node-sdk/README.md b/legacy/v1/node-sdk/README.md new file mode 100644 index 0000000..65a91ec --- /dev/null +++ b/legacy/v1/node-sdk/README.md @@ -0,0 +1,1155 @@ +--- +layout: + visible: true +title: + visible: true +description: + visible: false +tableOfContents: + visible: true +outline: + visible: true +pagination: + visible: true +--- + +{% hint style="info" %} +**Protocol v1 — legacy.** [Current v2 documentation](../../../supported-languages/node-sdk/README.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) + +Generated from [`@reflag/node-sdk@1.8.3`](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/node-sdk); SDK READMEs and code comments remain the source of truth. +{% endhint %} + +# Reflag Node.js SDK + +Node.js, JavaScript/TypeScript client for [Reflag.com](https://reflag.com). + +Reflag supports flag toggling, tracking flag usage, collecting feedback on features, and [remotely configuring flags](#remote-config). + +## Installation + +Install using your favorite package manager: + +{% tabs %} +{% tab title="npm" %} + +```sh +npm i @reflag/node-sdk@1 +``` + +{% endtab %} + +{% tab title="yarn" %} + +```sh +yarn add @reflag/node-sdk@1 +``` + +{% endtab %} + +{% tab title="bun" %} + +```sh +bun add @reflag/node-sdk@1 +``` + +{% endtab %} + +{% tab title="pnpm" %} + +```sh +pnpm add @reflag/node-sdk@1 +``` + +{% endtab %} + +{% tab title="deno" %} + +```sh +deno add npm:@reflag/node-sdk@1 +``` + +{% endtab %} +{% endtabs %} + +Other supported languages/frameworks are in the [Supported languages](https://docs.reflag.com/quickstart/supported-languages) documentation pages. + +You can also [use the HTTP API directly](https://docs.reflag.com/api/http-api) + +## Basic usage + +To get started you need to obtain your secret key from the [environment settings](https://app.reflag.com/env-current/settings/app-environments) +in Reflag. + +Reflag will load settings through the various environment variables automatically (see [Configuring](#configuring) below). + +1. Find the Reflag secret key for your development environment under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag. +2. Set `REFLAG_SECRET_KEY` in your `.env` file +3. Create a `reflag.ts` file containing the following: + +```typescript +import { ReflagClient } from "@reflag/node-sdk"; + +// Create a new instance of the client with the secret key. Additional options +// are available, such as supplying a logger and other custom properties. +// +// We recommend that only one global instance of `client` should be created +// to avoid multiple round-trips to our servers. +export const reflagClient = new ReflagClient(); + +// Initialize the client and begin fetching flag targeting definitions. +// You must call this method prior to any calls to `getFlags()`, +// otherwise an empty object will be returned. +reflagClient.initialize().then(() => { + console.log("Reflag initialized!"); +}); +``` + +Once the client is initialized, you can obtain flags along with the `isEnabled` +status to indicate whether the flag is targeted for this user/company: + +{% hint style="warning" %} +If `user.id` is not given, the whole `user` object is ignore. Similarly, without `company.id` the `company` object is ignored. +{% endhint %} + +```typescript +// configure the client +const boundClient = reflagClient.bindClient({ + user: { + id: "john_doe", + name: "John Doe", + email: "john@acme.com", + avatar: "https://example.com/users/jdoe", + }, + company: { + id: "acme_inc", + name: "Acme, Inc.", + avatar: "https://example.com/companies/acme", + }, +}); + +// get the huddle flag using company, user and custom context to +// evaluate the targeting. +const { isEnabled, track, config } = boundClient.getFlag("huddle"); + +if (isEnabled) { + // this is your flag gated code ... + // send an event when the flag is used: + track(); + + if (config?.key === "zoom") { + // this code will run if a given remote configuration + // is set up. + } + + // CAUTION: if you plan to use the event for automated feedback surveys + // call `flush` immediately after `track`. It can optionally be awaited + // to guarantee the sent happened. + boundClient.flush(); +} +``` + +You can also use the `getFlags()` method which returns a map of all flags: + +```typescript +// get the current flags (uses company, user and custom context to +// evaluate the flags). +const flags = boundClient.getFlags(); +const bothEnabled = flags.huddle?.isEnabled && flags.voiceHuddle?.isEnabled; +``` + +## High performance flag targeting + +The SDK contacts the Reflag servers when you call `initialize()` +and downloads the flags with their targeting rules. +These rules are then matched against the user/company information you provide +to `getFlags()` (or through `bindClient(..).getFlags()`). That means the +`getFlags()` call does not need to contact the Reflag servers once +`initialize()` has completed. By default, `ReflagClient` uses +`flagsSyncMode: "push"`, which keeps targeting rules up to date via live SSE +updates. You can switch `flagsSyncMode` to `polling` for periodic background +refreshes or `in-request` for request-driven refreshes instead. + +### Batch Operations + +The SDK automatically batches operations like user/company updates and flag tracking events to minimize API calls. +The batch buffer is configurable through the client options: + +```typescript +const client = new ReflagClient({ + batchOptions: { + maxSize: 100, // Maximum number of events to batch + intervalMs: 10000, // Flush interval in milliseconds (default: 10000) + }, +}); +``` + +You can manually flush the batch buffer at any time: + +```typescript +await client.flush(); +``` + +{% hint style="success" %} +It's recommended to call `flush()` before your application shuts down to ensure all events are sent. +{% endhint %} + +### Rate Limiting + +The SDK includes automatic rate limiting for flag events to prevent overwhelming the API. +Rate limiting is applied per unique combination of flag key and evaluation context. +This behavior is built in and does not currently require configuration. + +### Flag definitions + +Flag definitions include the rules needed to determine which flags should be enabled and which config values should be applied to any given user/company. +Flag definitions are automatically fetched when calling `initialize()`. +They are then cached and refreshed in the background. Ordinary refreshes use +ETags to avoid downloading unchanged definitions. A `304 Not Modified` response +keeps the cached definitions and resets their freshness without recompiling +rules or writing a new fallback snapshot. Initial fetches and refreshes with a +`waitForVersion` target remain unconditional. When a fallback provider is +configured, the SDK retains the ETag only after the snapshot is saved +successfully. A failed or pending save keeps ordinary refreshes unconditional +so persistence can recover, without delaying flag availability. + +Custom HTTP clients can enable this optimization by returning the exact ETag +value in `HttpClientResponse.etag` and returning 304 responses with +`body: undefined`. Clients that omit the ETag continue using full fetches. + +It's also possible to get the currently in use flag definitions: + +```typescript +import fs from "fs"; + +const client = new ReflagClient(); + +const flagDefs = await client.getFlagDefinitions(); +// [{ +// key: "huddle", +// description: "Live voice conversations with colleagues." +// flag: { ... } +// config: { ... } +// }] +``` + +### Fallback provider + +`flagsFallbackProvider` is a reliability feature that lets the SDK persist the latest successfully fetched raw flag definitions to fallback storage such as a local file, Redis, S3, GCS, or a custom backend. + +{% hint style="info" %} + +`fallbackFlags` is deprecated. Prefer `flagsFallbackProvider` for startup fallback and outage recovery. +`flagsFallbackProvider` is not used in offline mode. +{% endhint %} + +#### How it works + +Reflag servers remain the primary source of truth. On `initialize()`, the SDK always tries to fetch a live copy of the flag definitions first, and it continues refreshing those definitions from the Reflag servers over time. + +If that initial live fetch fails, the SDK can call `flagsFallbackProvider.load()` and start with the last saved snapshot instead. This is mainly useful for cold starts in the exceedingly rare case that Reflag has an outage. + +If Reflag becomes unavailable after the SDK has already initialized successfully, the SDK keeps using the last successfully fetched definitions it already has in memory. In other words, the fallback provider is mainly what helps future processes start, not what keeps an already running process alive. + +After successfully fetching updated flag definitions, the SDK calls `flagsFallbackProvider.save()` to keep the stored snapshot up to date. + +Typical reliability flow: + +1. The SDK starts and tries to fetch live flag definitions from Reflag. +2. If that succeeds, those definitions are used immediately and the SDK continues operating normally. +3. After successfully fetching updated flag definitions, the SDK saves the latest snapshot through the fallback provider so a recent copy is available if needed later. +4. If a future process starts while Reflag is unavailable, it can load the last saved snapshot from the fallback provider and still initialize. +5. Once Reflag becomes available again, the SDK resumes using live data and refreshes the fallback snapshot. + +Most deployments run multiple SDK processes, so more than one process may save identical flag definitions to the fallback storage at roughly the same time. This is expected and generally harmless for backends like a local file, Redis, S3, or GCS because the operation is cheap. In practice, this only becomes worth thinking about once you have many thousands of SDK processes writing to the same fallback storage. + +{% hint style="success" %} +If you are building a web or client-side application and want the most resilient setup, combine `flagsFallbackProvider` on the server with bootstrapped flags on the client. + +`flagsFallbackProvider` helps new server processes start if they cannot reach Reflag during initialization. Bootstrapping helps clients render from server-provided flags instead of depending on an initial client-side fetch from the Reflag servers. + +This applies to React (`getFlagsForBootstrap()` + `ReflagBootstrappedProvider`), React Native, the Browser SDK (`bootstrappedState`), and the Vue SDK (bootstrapped flags via the provider). +{% endhint %} + +#### Built-in providers + +You can access the built-in providers through the `fallbackProviders` namespace: + +- `fallbackProviders.static(...)` +- `fallbackProviders.file(...)` +- `fallbackProviders.redis(...)` +- `fallbackProviders.s3(...)` +- `fallbackProviders.gcs(...)` + +##### Static provider + +If you just want a fixed fallback copy of simple enabled/disabled flags, you can provide a static map: + +```typescript +import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; + +const client = new ReflagClient({ + secretKey: process.env.REFLAG_SECRET_KEY, + flagsFallbackProvider: fallbackProviders.static({ + flags: { + huddle: true, + "smart-summaries": false, + }, + }), +}); + +await client.initialize(); +``` + +##### File provider + +```typescript +import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; + +const client = new ReflagClient({ + secretKey: process.env.REFLAG_SECRET_KEY, + flagsFallbackProvider: fallbackProviders.file({ + directory: ".reflag", + }), +}); + +await client.initialize(); +``` + +The file provider stores one snapshot file per environment in the configured +`directory`, using the filename +`flags-fallback-.json`. + +##### Redis provider + +The built-in Redis provider creates a Redis client automatically when omitted and uses `REDIS_URL` from the environment. It stores snapshots under the configured `keyPrefix` and appends the first 16 characters of the secret key hash to that prefix. + +Without a `keyPrefix` set, it will default to the key `reflag:flags-fallback:`. When you provide a custom `keyPrefix`, any trailing `:` is trimmed before the hash suffix is appended. + +```typescript +import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; + +const client = new ReflagClient({ + secretKey: process.env.REFLAG_SECRET_KEY, + flagsFallbackProvider: fallbackProviders.redis(), +}); + +await client.initialize(); +``` + +##### S3 provider + +The built-in S3 provider works out of the box using the AWS SDK's default credential chain and region resolution. It stores the snapshot object under the configured `keyPrefix` and uses the filename `flags-fallback-.json`. + +Without a `keyPrefix` set, it will default to the object key `reflag/flags-fallback/flags-fallback-.json`. When you provide a custom `keyPrefix`, any trailing `/` is trimmed before the filename is appended. + +```typescript +import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; + +const client = new ReflagClient({ + secretKey: process.env.REFLAG_SECRET_KEY, + flagsFallbackProvider: fallbackProviders.s3({ + bucket: "reflag-fallback-bucket", + }), +}); + +await client.initialize(); +``` + +##### GCS provider + +The built-in GCS provider works out of the box using Google Cloud's default application credentials. It stores the snapshot object under the configured `keyPrefix` and uses the filename `flags-fallback-.json`. + +Without a `keyPrefix` set, it will default to the object key `reflag/flags-fallback/flags-fallback-.json`. When you provide a custom `keyPrefix`, any trailing `/` is trimmed before the filename is appended. + +```typescript +import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; + +const client = new ReflagClient({ + secretKey: process.env.REFLAG_SECRET_KEY, + flagsFallbackProvider: fallbackProviders.gcs({ + bucket: "reflag-fallback-bucket", + }), +}); + +await client.initialize(); +``` + +#### Testing fallback startup locally + +To test fallback startup in your own app, first run it once with a working Reflag connection so a snapshot is saved. Then restart it with the same secret key and fallback provider configuration, but set `apiBaseUrl` (or set the `REFLAG_API_BASE_URL` environment variable) to `http://127.0.0.1:65535`. That forces the live fetch to fail and lets you verify that the SDK initializes from the saved snapshot instead. + +#### Writing a custom provider + +If you just store definitions in your database or similar, a custom provider can be very small: + +```typescript +import type { + FlagsFallbackProvider, + FlagsFallbackSnapshot, +} from "@reflag/node-sdk"; + +export const customFallbackProvider: FlagsFallbackProvider = { + async load(context) { + // load snapshot from database + // optionally, look up the snapshot using the context.secretKeyHash as a key + return snapshot; + }, + + async save(context, snapshot) { + const serialized = JSON.stringify(snapshot); + // write serialized snapshot to database, optionally using context.secretKeyHash as a key + }, +}; +``` + +## Bootstrapping client-side applications + +The `getFlagsForBootstrap()` method is useful whenever you need to pass flag data to another runtime or serialize it without wrapper functions. Server-side rendering (SSR) is a common example, but it is also useful for other bootstrapping and hydration flows. + +```typescript +const client = new ReflagClient(); +await client.initialize(); + +// Get bootstrapped state with full context +const bootstrappedState = client.getFlagsForBootstrap({ + user: { + id: "user123", + name: "John Doe", + email: "john@acme.com", + }, + company: { + id: "company456", + name: "Acme Inc", + plan: "enterprise", + }, + other: { + source: "web", + platform: "desktop", + }, +}); + +// Pass this data to your client-side application +console.log(bootstrappedState); +// { +// context: { ... }, +// flags: { +// "huddle": { +// "key": "huddle", +// "isEnabled": true, +// "config": { +// "key": "enhanced", +// "payload": { "maxParticipants": 50, "videoQuality": "hd" }, +// } +// } +// }, +// flagStateVersion: 42 +// } +``` + +You can also use a bound client for simpler API: + +```typescript +const boundClient = client.bindClient({ + user: { id: "user123", name: "John Doe", email: "john@acme.com" }, + company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, +}); + +const bootstrappedState = boundClient.getFlagsForBootstrap(); +``` + +### Key differences from `getFlags()` + +- **Raw data**: Returns plain objects without `track()` functions, making them JSON serializable +- **Context included**: Returns both the evaluated flags and the context used for evaluation +- **Version included**: Returns `flagStateVersion` when known so bootstrapped clients can avoid redundant live-update refreshes +- **Bootstrapping focus**: Designed specifically for passing data to client-side applications + +## Edge-runtimes like Cloudflare Workers + +To use the Reflag NodeSDK with Cloudflare workers, set the `node_compat` flag [in your wrangler file](https://developers.cloudflare.com/workers/runtime-apis/nodejs/#get-started). + +Instead of using `ReflagClient`, use `EdgeClient` and make sure you call `ctx.waitUntil(reflag.flush());` before returning from your worker function. + +```typescript +import { EdgeClient } from "@reflag/node-sdk"; + +// set the REFLAG_SECRET_KEY environment variable or pass the secret key in the constructor +const reflag = new EdgeClient(); + +export default { + async fetch(request, _env, ctx): Promise { + // initialize the client and wait for it to complete + // if the client was initialized on a previous invocation, this is a no-op. + await reflag.initialize(); + const flags = reflag.getFlags({ + user: { id: "userId" }, + company: { id: "companyId" }, + }); + + // ensure all events are flushed and any requests to refresh the flag cache + // have completed after the response is sent + ctx.waitUntil(reflag.flush()); + + return new Response( + `Flags for user ${userId} and company ${companyId}: ${JSON.stringify(flags, null, 2)}`, + ); + }, +}; +``` + +See [examples/cloudflare-worker](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/node-sdk/examples/cloudflare-worker/src/index.ts) for a deployable example. + +Reflag maintains a cached set of flag definitions in the memory of your worker which it uses to decide which flags to turn on for which users/companies. + +The SDK caches flag definitions in memory for fast performance. The first request to a new worker instance fetches definitions from Reflag's servers, while subsequent requests use the cache. When the cache expires, it's updated in the background. `ctx.waitUntil(reflag.flush())` ensures completion of the background work, so response times are not affected. This background work may increase wall-clock time for your worker, but it will not measurably increase billable CPU time on platforms like Cloudflare. + +`EdgeClient` uses `flagsSyncMode: "in-request"`. Refresh fetch starts are throttled to at most once per second, and Cloudflare Workers cannot rely on delayed timer callbacks to run follow-up refreshes later. That means `refreshFlags()` calls made during the throttle window only mark a refresh as pending, so the call itself may resolve before the fetch runs. The queued refresh runs on the next request/access or `refreshFlags()` call after the throttle window expires. + +## Error Handling + +The SDK is designed to fail gracefully and never throw exceptions to the caller. Instead, it logs errors and provides +fallback behavior: + +1. **Flag Evaluation Failures**: + + ```typescript + const { isEnabled } = client.getFlag("my-flag"); + // If flag evaluation fails, isEnabled will be false + ``` + +2. **Network Errors**: + + ```typescript + // Network errors during tracking are logged but don't affect your application + const { isEnabled, track } = client.getFlag("my-flag"); + if (isEnabled) { + // network errors are caught internally and logged and never bubbled up to your application + // no need to try/catch around "track" or "getFlag" + await track(); + } + ``` + +3. **Missing Context**: + + ```typescript + // The SDK tracks missing context fields but continues operation + const flags = client.getFlags({ + user: { id: "user123" }, + // Missing company context will be logged but won't cause errors + }); + ``` + +4. **Offline Mode**: + + ```typescript + // In offline mode, the SDK uses explicit local configuration only. + // It does not fetch from Reflag or use flagsFallbackProvider. + const client = new ReflagClient({ + offline: true, + flagOverrides: () => ({ + "my-flag": true, + }), + }); + ``` + +The SDK logs all errors with appropriate severity levels. You can customize logging by providing your own logger: + +```typescript +const client = new ReflagClient({ + logger: { + debug: (msg) => console.debug(msg), + info: (msg) => console.info(msg), + warn: (msg) => console.warn(msg), + error: (msg, error) => { + console.error(msg, error); + // Send to your error tracking service + errorTracker.capture(error); + }, + }, +}); +``` + +## Remote config + +Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. + +Similar to `isEnabled`, each flag has a `config` property. This configuration is managed from within Reflag. +It is managed similar to the way access to flags is managed, but instead of the binary `isEnabled` you can have +multiple configuration values which are given to different user/companies. + +```ts +const flags = reflagClient.getFlags(); +// { +// huddle: { +// isEnabled: true, +// targetingVersion: 42, +// config: { +// key: "gpt-3.5", +// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } +// } +// } +// } +``` + +`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. + +Just as `isEnabled`, accessing `config` on the object returned by `getFlags` does not automatically +generate a `check` event, contrary to the `config` property on the object returned by `getFlag`. + +## Configuring + +The Reflag `Node.js` SDK can be configured through environment variables, +a configuration file on disk or by passing options to the `ReflagClient` +constructor. By default, the SDK searches for `reflag.config.json` in the +current working directory. + +| Option | Type | Description | Env Var | +| ----------------------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | +| `secretKey` | string | The secret key used for authentication with Reflag's servers. | REFLAG_SECRET_KEY | +| `logLevel` | string | The log level for the SDK (e.g., `"DEBUG"`, `"INFO"`, `"WARN"`, `"ERROR"`). Default: `INFO` | REFLAG_LOG_LEVEL | +| `offline` | boolean | Operate in offline mode. Default: `false`, except in tests it will default to `true` based off of the `TEST` env. var. In offline mode the SDK does not fetch from Reflag and does not use `flagsFallbackProvider`. | REFLAG_OFFLINE | +| `apiBaseUrl` | string | The base API URL for the Reflag servers. | REFLAG_API_BASE_URL | +| `flagOverrides` | Record | An object specifying flag overrides for testing or local development. See [examples/express/app.test.ts](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/node-sdk/examples/express/app.test.ts) for how to use `flagOverrides` in tests. | REFLAG_FLAGS_ENABLED, REFLAG_FLAGS_DISABLED | +| `flagsFallbackProvider` | `FlagsFallbackProvider` | Optional provider used to load and save raw flag definitions for fallback startup when the initial live fetch fails. Available only through the constructor. Ignored in offline mode. | - | +| `flagsSyncMode` | `"polling" \| "in-request" \| "push"` | Flag-definition sync mode. `push` subscribes to live updates, `polling` uses periodic background refresh, and `in-request` refreshes stale flags during request handling. Default: `"push"`. | - | +| `flagsPushUrl` | string | Push endpoint used when `flagsSyncMode: "push"`. The SDK opens it as an authenticated streaming GET. Default: `https://front.reflag.com/sse/server`. | - | +| `configFile` | string | Load this config file from disk. Default: `reflag.config.json` | REFLAG_CONFIG_FILE | + +{% hint style="info" %} + +`REFLAG_FLAGS_ENABLED` and `REFLAG_FLAGS_DISABLED` are comma separated lists of flags which will be enabled or disabled respectively. +{% endhint %} + +`reflag.config.json` example: + +```json +{ + "secretKey": "...", + "logLevel": "warn", + "offline": true, + "apiBaseUrl": "https://proxy.slick-demo.com", + "flagOverrides": { + "huddles": true, + "voiceChat": { "isEnabled": false }, + "aiAssist": { + "isEnabled": true, + "config": { + "key": "gpt-4.0", + "payload": { + "maxTokens": 50000 + } + } + } + } +} +``` + +When using a `reflag.config.json` for local development, make sure you add it to your +`.gitignore` file. You can also set these options directly in the `ReflagClient` +constructor. The precedence for configuration options is as follows, listed in the +order of importance: + +1. Options passed along to the constructor directly, +2. Environment variable, +3. The config file. + +## Type safe flags + +To get type checked flags, install the Reflag CLI: + +```sh +npm i --save-dev @reflag/cli@1 +``` + +then generate the types: + +```sh +npx reflag flags types +``` + +This will generate a `reflag.d.ts` containing all your flags. +Any flag look ups will now be checked against the flags that exist in Reflag. + +Here's an example of a failed type check: + +```typescript +import { ReflagClient } from "@reflag/node-sdk"; + +export const reflagClient = new ReflagClient(); + +reflagClient.initialize().then(() => { + console.log("Reflag initialized!"); + + // TypeScript will catch this error: "invalid-flag" doesn't exist + reflagClient.getFlag("invalid-flag"); + + const { + isEnabled, + config: { payload }, + } = reflagClient.getFlag("create-todos"); +}); +``` + +![Type check failed](../_media/type-check-failed.png "Type check failed") + +This is an example of a failed config payload check: + +```typescript +reflagClient.initialize().then(() => { + // TypeScript will catch this error as well: "minLength" is not part of the payload. + if (isEnabled && todo.length > config.payload.minLength) { + // ... + } +}); +``` + +![Config type check failed](../_media/type-check-payload-failed.png "Remote config type check failed") + +## Testing with flag overrides + +When writing tests that cover code with flags, you can toggle flags on/off programmatically to test different behavior. For tests, you will often want to run the client in offline mode: + +`reflag.ts`: + +```typescript +import { ReflagClient } from "@reflag/node-sdk"; + +export const reflag = new ReflagClient({ + offline: true, +}); +``` + +There are a few ways to programmatically manipulate the overrides which are appropriate when testing: + +### Base overrides + +You can set base overrides for a test run by passing `flagOverrides` in the constructor, replacing them later with `setFlagOverrides()` and clearing them with `clearFlagOverrides()`: + +```typescript +// pass directly in the constructor +const client = new ReflagClient({ + offline: true, + flagOverrides: { myFlag: true }, +}); + +// or replace the base overrides at a later time +client.setFlagOverrides({ myFlag: false }); + +// clear only the base overrides +client.clearFlagOverrides(); +``` + +`app.test.ts`: + +```typescript +import { reflag } from "./reflag.ts"; + +beforeAll(async () => await reflag.initialize()); +afterEach(() => { + reflag.clearFlagOverrides(); +}); + +describe("API Tests", () => { + it("should return 200 for the root endpoint", async () => { + reflag.setFlagOverrides({ + "show-todo": true, + }); + + const response = await request(app).get("/"); + expect(response.status).toBe(200); + expect(response.body).toEqual({ message: "Ready to manage some TODOs!" }); + }); +}); +``` + +### Layering overrides + +`pushFlagOverrides()` serves a different purpose: it adds a temporary layer on top of the base overrides and returns a remove function that removes only that layer. This is useful for nested tests: + +```typescript +export const flag = function (name: string, enabled: boolean): void { + let remove: (() => void) | undefined; + + beforeEach(function () { + remove = reflagClient.pushFlagOverrides({ [name]: enabled }); + }); + + afterEach(function () { + remove?.(); + remove = undefined; + }); +}; + +describe("foo", () => { + describe("with new search ranking enabled", () => { + flag("search-ranking-v2", true); + + describe("with summaries enabled", () => { + flag("smart-summaries", true); + + // ... + }); + }); +}); +``` + +The precedence is: + +1. Base overrides from the constructor or `setFlagOverrides()` +2. Temporary layers added by `pushFlagOverrides()` + +If the same flag is set in both places, the pushed override wins until its remove function is called. + +### Context dependent overrides + +`setFlagOverrides()` and `pushFlagOverrides()` also accept a function if the override depends on the evaluation context: + +```typescript +const remove = client.pushFlagOverrides((context) => ({ + "smart-summaries": context.user?.id === "qa-user", +})); + +// ... + +remove(); +``` + +### Additional ways to provide flag overrides + +You also have these additional ways to provide overrides, which can be helpful when testing out locally: + +1. Through environment variables: + +```bash +REFLAG_FLAGS_ENABLED=flag1,flag2 +REFLAG_FLAGS_DISABLED=flag3,flag4 +``` + +1. Through `reflag.config.json`: + +```json +{ + "flagOverrides": { + "delete-todos": { + "isEnabled": true, + "config": { + "key": "dev-config", + "payload": { + "requireConfirmation": true, + "maxDeletionsPerDay": 5 + } + } + } + } +} +``` + +## Remote Flag Evaluation + +In addition to local flag evaluation, Reflag supports remote evaluation using stored context. This is useful when you want to evaluate flags using user/company attributes that were previously sent to Reflag: + +```typescript +// First, update user and company attributes +await client.updateUser("user123", { + attributes: { + role: "admin", + subscription: "premium", + }, +}); + +await client.updateCompany("company456", { + attributes: { + tier: "enterprise", + employees: 1000, + }, +}); + +// Later, evaluate flags remotely using stored context. +// Note: the argument order is (userId, companyId, additionalContext?) +const userId = "user123"; +const companyId = "company456"; + +const flags = await client.getFlagsRemote(userId, companyId); +// Or evaluate a single flag +const flag = await client.getFlagRemote("create-todos", userId, companyId); + +// You can also provide additional context +const flagsWithContext = await client.getFlagsRemote(userId, companyId, { + other: { + location: "US", + platform: "mobile", + }, +}); +``` + +Remote evaluation is particularly useful when: + +- You want to use the most up-to-date user/company attributes stored in Reflag +- You don't want to pass all context attributes with every evaluation +- You need to ensure consistent flag evaluation across different services + +## Using with Express + +A popular way to integrate the Reflag Node.js SDK is through an express middleware. + +```typescript +import reflag from "./reflag"; +import express from "express"; +import { BoundReflagClient } from "@reflag/node-sdk"; + +// Augment the Express types to include a `boundReflagClient` property on the +// `res.locals` object. +// This will allow us to access the ReflagClient instance in our route handlers +// without having to pass it around manually +declare global { + namespace Express { + interface Locals { + boundReflagClient: BoundReflagClient; + } + } +} + +// Add express middleware +app.use((req, res, next) => { + // Extract the user and company IDs from the request + // You'll want to use a proper authentication and identification + // mechanism in a real-world application + const user = { + id: req.user?.id, + name: req.user?.name, + email: req.user?.email + } + + const company = { + id: req.user?.companyId, + name: req.user?.companyName + } + + // Create a new BoundReflagClient instance by calling the `bindClient` + // method on a `ReflagClient` instance + // This will create a new instance that is bound to the user/company given. + const boundReflagClient = reflag.bindClient({ user, company }); + + // Store the BoundReflagClient instance in the `res.locals` object so we + // can access it in our route handlers + res.locals.boundReflagClient = boundReflagClient; + next(); +}); + +// Now use res.locals.boundReflagClient in your handlers +app.get("/todos", async (_req, res) => { + const { track, isEnabled } = res.locals.boundReflagClient.getFlag("show-todos"); + + if (!isEnabled) { + res.status(403).send({"error": "flag inaccessible"}) + return + } + + ... +} +``` + +See [examples/express/app.ts](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/node-sdk/example/express/app.ts) for a full example. + +## Remote flag evaluation with stored context + +If you don't want to provide context each time when evaluating flags but +rather you would like to utilize the attributes you sent to Reflag previously +(by calling `updateCompany` and `updateUser`) you can do so by calling `getFlagsRemote` +(or `getFlagRemote` for a specific flag) with just `userId` and `companyId` +in that order. +These methods will call Reflag's servers and flags will be evaluated remotely +using the stored attributes. + +```typescript +// Update user and company attributes +client.updateUser("john_doe", { + attributes: { + name: "John O.", + role: "admin", + }, +}); + +client.updateCompany("acme_inc", { + attributes: { + name: "Acme, Inc", + tier: "premium" + }, +}); +... + +// This will evaluate flags using the stored attributes for the user/company pair +const flags = await client.getFlagsRemote("john_doe", "acme_inc"); +``` + +{% hint style="warning" %} +User and company attribute updates are processed asynchronously, so there might +be a small delay between when attributes are updated and when they are available +for evaluation. +{% endhint %} + +## Opting out of tracking + +There are use cases in which you not want to be sending `user`, `company` and +`track` events to [Reflag.com](https://reflag.com). These are usually cases where you could be impersonating +another user in the system and do not want to interfere with the data being +collected by Reflag. + +To disable tracking, bind the client using `bindClient()` as follows: + +```typescript +// binds the client to a given user and company and set `enableTracking` to `false`. +const boundClient = client.bindClient({ user, company, enableTracking: false }); + +boundClient.track("some event"); // this will not actually send the event to Reflag. + +// the following code will not update the `user` nor `company` in Reflag and will +// not send `track` events either. +const { isEnabled, track } = boundClient.getFlag("user-menu"); +if (isEnabled) { + track(); +} +``` + +Another way way to disable tracking without employing a bound client is to call `getFlag()` +or `getFlags()` by supplying `enableTracking: false` in the arguments passed to +these functions. + +{% hint style="warning" %} +Note, however, that calling `track()`, `updateCompany()` or `updateUser()` in the `ReflagClient` +will still send tracking data. As such, it is always recommended to use `bindClient()` +when using this SDK. +{% endhint %} + +## Flushing + +ReflagClient employs a batching technique to minimize the number of calls that are sent to +Reflag's servers. + +By default, the SDK attempts to flush pending events when the Node.js event loop empties +(the `beforeExit` event). This behavior is controlled by the `flushOnExit` option in the client configuration: + +```typescript +const client = new ReflagClient({ + batchOptions: { + flushOnExit: false, // disable automatic flushing on exit + }, +}); +``` + +Node.js does not emit `beforeExit` for unhandled termination signals (such as `SIGTERM` or +`SIGINT`) or explicit `process.exit()` calls. For these shutdown paths, **await `client.flush()` +in your application's existing graceful shutdown hook**, after stopping incoming work and +waiting for in-flight requests or jobs to finish, and before exiting. This ensures events +produced during shutdown are included. Automatic flushing is best-effort and does not replace +an application-managed shutdown hook. + +## Tracking custom events and setting custom attributes + +Tracking allows events and updating user/company attributes in Reflag. +For example, if a customer changes their plan, you'll want Reflag to know about it, +in order to continue to provide up-do-date targeting information in the Reflag interface. + +The following example shows how to register a new user, associate it with a company +and finally update the plan they are on. + +```typescript +// registers the user with Reflag using the provided unique ID, and +// providing a set of custom attributes (can be anything) +client.updateUser("user_id", { + attributes: { longTimeUser: true, payingCustomer: false }, +}); +client.updateCompany("company_id", { userId: "user_id" }); + +// the user started a voice huddle +client.track("user_id", "huddle", { attributes: { voice: true } }); +``` + +It's also possible to achieve the same through a bound client in the following manner: + +```typescript +const boundClient = client.bindClient({ + user: { id: "user_id", longTimeUser: true, payingCustomer: false }, + company: { id: "company_id" }, +}); + +boundClient.track("huddle", { attributes: { voice: true } }); +``` + +Some attributes are used by Reflag to improve the UI, and are recommended +to provide for easier navigation: + +- `name` -- display name for `user`/`company`, +- `email` -- the email of the user, +- `avatar` -- the URL for `user`/`company` avatar image. + +Attributes cannot be nested (multiple levels) and must be either strings, +integers or booleans. + +## Managing `Last seen` + +By default `updateUser`/`updateCompany` calls automatically update the given +user/company `Last seen` property on Reflag servers. + +You can control if `Last seen` should be updated when the events are sent by setting +`meta.active = false`. This is often useful if you +have a background job that goes through a set of companies just to update their +attributes but not their activity. + +Example: + +```typescript +client.updateUser("john_doe", { + attributes: { name: "John O." }, + meta: { active: true }, +}); + +client.updateCompany("acme_inc", { + attributes: { name: "Acme, Inc" }, + meta: { active: false }, +}); +``` + +`bindClient()` updates attributes on the Reflag servers but does not automatically +update `Last seen`. + +## Zero PII + +The Reflag SDK doesn't collect any metadata and HTTP IP addresses are _not_ being +stored. For tracking individual users, we recommend using something like database +ID as userId, as it's unique and doesn't include any PII (personal identifiable +information). If, however, you're using e.g. email address as userId, but prefer +not to send any PII to Reflag, you can hash the sensitive data before sending +it to Reflag: + +```typescript +import { sha256 } from 'crypto-hash'; + +client.updateUser({ userId: await sha256("john_doe"), ... }); +``` + +## Migrating from Bucket SDK + +If you have been using the Bucket SDKs previously, the following list will help you migrate to Reflag SDK: + +- `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) +- `Feature*` classes, and types have been renamed to `Flag*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) +- When using strongly-typed flags, the new `Flags` interface replaced `Features` interface +- All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) +- All environment variables that were prefixed with `BUCKET_` are now prefixed with `REFLAG_` +- The `BUCKET_HOST` environment variable and `host` option have been removed from `ReflagClient` constructor, use `REFLAG_API_BASE_URL` instead +- The `BUCKET_FEATURES_ENABLED` and `BUCKET_FEATURES_DISABLED` have been renamed to `REFLAG_FLAGS_ENABLED` and `REFLAG_FLAGS_DISABLED` +- The default configuration file has been renamed from `bucketConfig.json` to `reflag.config.json` +- The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags` +- `featureKey` has been renamed to `flagKey` in all methods that accepts that argument +- The SDKs will not emit `evaluate` and `evaluate-config` events anymore + +## Typescript + +Types are bundled together with the library and exposed automatically when importing +through a package manager. + +## License + +> MIT License +> Copyright (c) 2025 Bucket ApS diff --git a/legacy/v1/node-sdk/globals.md b/legacy/v1/node-sdk/globals.md new file mode 100644 index 0000000..206cc99 --- /dev/null +++ b/legacy/v1/node-sdk/globals.md @@ -0,0 +1,6457 @@ +--- +layout: + visible: true +title: + visible: true +description: + visible: false +tableOfContents: + visible: true +outline: + visible: true +pagination: + visible: true +--- + +{% hint style="info" %} +**Protocol v1 — legacy.** [Current v2 documentation](../../../supported-languages/node-sdk/globals.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) + +Generated from [`@reflag/node-sdk@1.8.3`](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/node-sdk); SDK READMEs and code comments remain the source of truth. +{% endhint %} + +# @reflag/node-sdk + +## Classes + +### BoundReflagClient + +A client bound with a specific user, company, and other context. + +#### Constructors + +##### new BoundReflagClient() + +```ts +new BoundReflagClient(client: ReflagClient, options: ContextWithTracking): BoundReflagClient +``` + +**`Internal`** + +(Internal) Creates a new BoundReflagClient. Use `bindClient` to create a new client bound with a specific context. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`client` + + + +[`ReflagClient`](globals.md#reflagclient) + + + +The `ReflagClient` to use. + +
+ +`options` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +The options for the client. + +
+ +###### Returns + +[`BoundReflagClient`](globals.md#boundreflagclient) + +#### Accessors + +##### company + +###### Get Signature + +```ts +get company(): + | undefined + | { +[k: string]: any; avatar: string; + id: undefined | string | number; + name: string; +} +``` + +Gets the company associated with the client. + +###### Returns + + \| `undefined` + \| \{ +`[k: string]`: `any`; `avatar`: `string`; + `id`: `undefined` \| `string` \| `number`; + `name`: `string`; + \} + +The company or `undefined` if it is not set. + +##### otherContext + +###### Get Signature + +```ts +get otherContext(): + | undefined +| Record +``` + +Gets the "other" context associated with the client. + +###### Returns + + \| `undefined` + \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + +The "other" context or `undefined` if it is not set. + +##### user + +###### Get Signature + +```ts +get user(): + | undefined + | { +[k: string]: any; avatar: string; + email: string; + id: undefined | string | number; + name: string; +} +``` + +Gets the user associated with the client. + +###### Returns + + \| `undefined` + \| \{ +`[k: string]`: `any`; `avatar`: `string`; + `email`: `string`; + `id`: `undefined` \| `string` \| `number`; + `name`: `string`; + \} + +The user or `undefined` if it is not set. + +#### Methods + +##### bindClient() + +```ts +bindClient(context: ContextWithTracking): BoundReflagClient +``` + +Create a new client bound with the additional context. +Note: This performs a shallow merge for user/company/other individually. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`context` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +The context to bind the client to. + +
+ +###### Returns + +[`BoundReflagClient`](globals.md#boundreflagclient) + +new client bound with the additional context + +##### flush() + +```ts +flush(): Promise +``` + +Flushes the batch buffer. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +##### getFlag() + +```ts +getFlag(key: TKey): Flag +``` + +Get a specific flag for the user/company/other context bound to this client. +Using the `isEnabled` property sends a `check` event to Reflag. + +###### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`TKey` *extends* `string` + +
+ +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`key` + + + +`TKey` + + + +The key of the flag to get. + +
+ +###### Returns + +[`Flag`](globals.md#flagtconfig) + +Flags for the given user/company and whether each one is enabled or not + +##### getFlagRemote() + +```ts +getFlagRemote(key: string): Promise +``` + +Get remotely evaluated flag for the user/company/other context bound to this client. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`key` + + + +`string` + + + +The key of the flag to get. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Flag`](globals.md#flagtconfig)\> + +Flag for the given user/company and key and whether it's enabled or not + +##### getFlags() + +```ts +getFlags(): Record +``` + +Get flags for the user/company/other context bound to this client. +Meant for use in serialization of flags for transferring to the client-side/browser. + +###### Returns + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\> + +Flags for the given user/company and whether each one is enabled or not + +##### getFlagsForBootstrap() + +```ts +getFlagsForBootstrap(): BootstrappedFlags +``` + +Get raw flags for the user/company/other context bound to this client without wrapping them in getters. +This method returns raw flag data suitable for bootstrapping client-side applications. + +###### Returns + +[`BootstrappedFlags`](globals.md#bootstrappedflags) + +Raw flags for the given user/company and whether each one is enabled or not + +##### getFlagsRemote() + +```ts +getFlagsRemote(): Promise> +``` + +Get remotely evaluated flag for the user/company/other context bound to this client. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\>\> + +Flags for the given user/company and whether each one is enabled or not + +##### refreshFlags() + +```ts +refreshFlags(waitForVersion?: number): Promise +``` + +Refreshes the flag definitions from the server. + +Fetch starts are throttled to at most once per second. Outside +`in-request` mode, a call to `refreshFlags(waitForVersion)` still waits +until the cache has applied that version or newer. + +In `in-request` mode, a throttled call only records pending refresh work. +The fetch then runs on the next request/access or `refreshFlags()` call +after the throttle window expires. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`waitForVersion`? + + + +`number` + + + +Optional flag state version to wait for before returning updated definitions. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +##### track() + +```ts +track(event: string, options?: TrackOptions & { + companyId: string; +}): Promise +``` + +Track an event in Reflag. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`event` + + + +`string` + + + +The event to track. + +
+ +`options`? + + + +[`TrackOptions`](globals.md#trackoptions) & \{ `companyId`: `string`; \} + + + +The options for the event. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Throws + +An error if the event is invalid or the options are invalid. + +*** + +### EdgeClient + +The EdgeClient is ReflagClient pre-configured to be used in edge runtimes, like +Cloudflare Workers. + +It always uses `flagsSyncMode: "in-request"`. Refresh fetch starts are +throttled to at most once per second. A `refreshFlags()` call made during +that throttle window only records pending refresh work, so the call may +resolve before the fetch runs. That pending refresh is executed on the next +request/access or `refreshFlags()` call after the window expires. + +#### Example + +```ts +// set the REFLAG_SECRET_KEY environment variable or pass the secret key in the constructor +const client = new EdgeClient(); + +// evaluate a flag +const context = { + user: { id: "user-id" }, + company: { id: "company-id" }, +} +const { isEnabled } = client.getFlag(context, "flag-key"); + +``` + +#### Extends + +- [`ReflagClient`](globals.md#reflagclient) + +#### Constructors + +##### new EdgeClient() + +```ts +new EdgeClient(options: EdgeClientOptions): EdgeClient +``` + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`options` + + + +[`EdgeClientOptions`](globals.md#edgeclientoptions) + +
+ +###### Returns + +[`EdgeClient`](globals.md#edgeclient) + +###### Overrides + +[`ReflagClient`](globals.md#reflagclient).[`constructor`](globals.md#constructors) + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyModifierTypeDescription
+ + `httpClient` + + + +`public` + + + +[`HttpClient`](globals.md#httpclient) + + + +‐ + +
+ + `logger` + + + +`readonly` + + + +[`Logger`](globals.md#logger) + + + +Gets the logger associated with the client. + +
+ +#### Accessors + +##### flagOverrides + +###### Set Signature + +```ts +set flagOverrides(overrides: + | Partial> + | FlagOverridesFn): void +``` + +###### Deprecated + +Use `setFlagOverrides()` for replacing the base override set. + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`overrides` + + + + \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagOverride`](globals.md#flagoverride)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn) + +
+ +###### Returns + +`void` + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`flagOverrides`](globals.md#flagoverrides) + +#### Methods + +##### bindClient() + +```ts +bindClient(context: ContextWithTracking): BoundReflagClient +``` + +Returns a new BoundReflagClient with the user/company/otherContext +set to be used in subsequent calls. +For example, for evaluating flag targeting or tracking events. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`context` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +The context to bind the client to. + +
+ +###### Returns + +[`BoundReflagClient`](globals.md#boundreflagclient) + +A new client bound with the arguments given. + +###### Throws + +An error if the user/company is given but their ID is not a string. + +###### Remarks + +The `updateUser` / `updateCompany` methods will automatically be called when +the user/company is set respectively. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`bindClient`](globals.md#bindclient) + +##### clearFlagOverrides() + +```ts +clearFlagOverrides(): void +``` + +Clears the base flag overrides. + +###### Returns + +`void` + +###### Remarks + +This does not affect temporary layers added with `pushFlagOverrides()`. + +###### Example + +```ts +client.clearFlagOverrides(); +``` + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`clearFlagOverrides`](globals.md#clearflagoverrides) + +##### destroy() + +```ts +destroy(): void +``` + +Destroys the client and cleans up all resources including timers and background processes. + +###### Returns + +`void` + +###### Remarks + +After calling this method, the client should not be used anymore. +This is particularly useful in development environments with hot reloading to prevent +multiple background processes from running simultaneously. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`destroy`](globals.md#destroy) + +##### flush() + +```ts +flush(): Promise +``` + +Flushes and completes any in-flight fetches in the flag cache. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Remarks + +It is recommended to call this method when the application is shutting down to ensure all events are sent +before the process exits. + +This method is automatically called on natural process exit (`beforeExit`) if +`batchOptions.flushOnExit` is `true` in the options (default). For signal-driven +shutdown or an explicit `process.exit()`, await this method in your application's +shutdown hook before exiting. The SDK does not install signal handlers. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`flush`](globals.md#flush) + +##### getFlag() + +```ts +getFlag(__namedParameters: ContextWithTracking, key: TKey): Flag +``` + +Gets the evaluated flag for the current context which includes the user, company, and custom context. +Using the `isEnabled` property sends a `check` event to Reflag. + +###### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`TKey` *extends* `string` + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`__namedParameters` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +‐ + +
+ +`key` + + + +`TKey` + + + +The key of the flag to get. + +
+ +###### Returns + +[`Flag`](globals.md#flagtconfig) + +The evaluated flag. + +###### Remarks + +Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`getFlag`](globals.md#getflag) + +##### getFlagDefinitions() + +```ts +getFlagDefinitions(): FlagDefinition[] +``` + +Gets the flag definitions, including all config values. +To evaluate which flags are enabled for a given user/company, use `getFlags`. + +###### Returns + +[`FlagDefinition`](globals.md#flagdefinition)[] + +The flags definitions. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`getFlagDefinitions`](globals.md#getflagdefinitions) + +##### getFlagRemote() + +```ts +getFlagRemote( + key: TKey, + userId?: IdType, + companyId?: IdType, +additionalContext?: Context): Promise +``` + +Gets evaluated flag with the usage of remote context. +This method triggers a network request every time it's called. + +###### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`TKey` *extends* `string` + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`key` + + + +`TKey` + + + +The key of the flag to get. + +
+ +`userId`? + + + +[`IdType`](globals.md#idtype) + + + +The userId of the user to get the flag for. + +
+ +`companyId`? + + + +[`IdType`](globals.md#idtype) + + + +The companyId of the company to get the flag for. + +
+ +`additionalContext`? + + + +[`Context`](globals.md#context) + + + +The additional context to get the flag for. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Flag`](globals.md#flagtconfig)\> + +evaluated flag + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`getFlagRemote`](globals.md#getflagremote) + +##### getFlags() + +```ts +getFlags(options: ContextWithTracking): Record +``` + +Gets the evaluated flags for the current context which includes the user, company, and custom context. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`options` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +The options for the context. + +
+ +###### Returns + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\> + +The evaluated flags. + +###### Remarks + +Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`getFlags`](globals.md#getflags) + +##### getFlagsForBootstrap() + +```ts +getFlagsForBootstrap(options: ContextWithTracking): BootstrappedFlags +``` + +Gets the evaluated flags for the current context without wrapping them in getters. +This method returns raw flag data suitable for bootstrapping client-side applications. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`options` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +The options for the context. + +
+ +###### Returns + +[`BootstrappedFlags`](globals.md#bootstrappedflags) + +The evaluated raw flags and the context. + +###### Remarks + +Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. +This method returns RawFlag objects without wrapping them in getters, making them suitable for serialization. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`getFlagsForBootstrap`](globals.md#getflagsforbootstrap) + +##### getFlagsRemote() + +```ts +getFlagsRemote( + userId?: IdType, + companyId?: IdType, +additionalContext?: Context): Promise> +``` + +Gets evaluated flags with the usage of remote context. +This method triggers a network request every time it's called. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`userId`? + + + +[`IdType`](globals.md#idtype) + + + +The userId of the user to get the flags for. + +
+ +`companyId`? + + + +[`IdType`](globals.md#idtype) + + + +The companyId of the company to get the flags for. + +
+ +`additionalContext`? + + + +[`Context`](globals.md#context) + + + +The additional context to get the flags for. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\>\> + +evaluated flags + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`getFlagsRemote`](globals.md#getflagsremote) + +##### initialize() + +```ts +initialize(): Promise +``` + +Initializes the client by caching the flags definitions. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Remarks + +Call this method before calling `getFlags` to ensure the flag definitions are cached. +The client will ignore subsequent calls to this method. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`initialize`](globals.md#initialize) + +##### pushFlagOverrides() + +```ts +pushFlagOverrides(overrides: + | Partial> + | FlagOverridesFn): () => void +``` + +Temporarily layers flag overrides on top of the current overrides. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`overrides` + + + + \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagOverride`](globals.md#flagoverride)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn) + + + +The flag overrides to apply for the scoped period. + +
+ +###### Returns + +`Function` + +A remove function that removes only this override layer. + +###### Returns + +`void` + +###### Remarks + +This is intended for tests or other short-lived local overrides. The remove +function is idempotent and can safely be called multiple times. + +###### Example + +```ts +let remove: (() => void) | undefined; + +beforeEach(() => { + remove = client.pushFlagOverrides({ "flag-1": true }); +}); + +afterEach(() => { + remove?.(); + remove = undefined; +}); +``` + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`pushFlagOverrides`](globals.md#pushflagoverrides) + +##### refreshFlags() + +```ts +refreshFlags(waitForVersion?: number): Promise +``` + +Refreshes the flag definitions from the server. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`waitForVersion`? + + + +`number` + + + +Optional flag state version to wait for before returning updated definitions. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Remarks + +This triggers an on-demand refresh of the cached flag definitions. +Useful when you know flags have changed and don't want to wait for the next automatic refresh cycle. + +Note: updated flag rules take a few seconds to propagate to all servers. + +Fetch starts are throttled to at most once per second. +Outside `in-request` mode, throttling only delays when the next fetch +begins: `refreshFlags(99)` still waits until the cache has applied flag +definitions from version `99` or newer before the promise resolves. +Concurrent callers are deduplicated and may share the same in-flight or +scheduled follow-up refresh. + +In `in-request` mode, delayed follow-up refreshes are not scheduled. On edge +runtimes like Cloudflare Workers, a call during the throttle window only +records pending refresh work, and the promise may resolve before that fetch +runs. The pending refresh is executed on the next request/access or +`refreshFlags()` call after the throttle window expires. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`refreshFlags`](globals.md#refreshflags) + +##### setFlagOverrides() + +```ts +setFlagOverrides(overrides: + | Partial> + | FlagOverridesFn): void +``` + +Replaces the base flag overrides used by the client. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`overrides` + + + + \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagOverride`](globals.md#flagoverride)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn) + + + +The flag overrides. + +
+ +###### Returns + +`void` + +###### Remarks + +Base overrides are always applied before any temporary layers added through +`pushFlagOverrides()`. + +###### Example + +```ts +client.setFlagOverrides({ + "flag-1": true, + "flag-2": false, +}); +``` + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`setFlagOverrides`](globals.md#setflagoverrides) + +##### track() + +```ts +track( + userId: IdType, + event: string, + options?: TrackOptions & { + companyId: IdType; +}): Promise +``` + +Tracks an event in Reflag. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`userId` + + + +[`IdType`](globals.md#idtype) + +
+ +`event` + + + +`string` + +
+ +`options`? + + + +[`TrackOptions`](globals.md#trackoptions) & \{ `companyId`: [`IdType`](globals.md#idtype); \} + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Throws + +An error if the user is not set or the event is invalid or the options are invalid. + +###### Remarks + +If the company is set, the event will be associated with the company. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`track`](globals.md#track) + +##### updateCompany() + +```ts +updateCompany(companyId: IdType, options?: TrackOptions & { + userId: IdType; +}): Promise +``` + +Updates the associated company in Reflag. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`companyId` + + + +[`IdType`](globals.md#idtype) + + + +The companyId of the company to update. + +
+ +`options`? + + + +[`TrackOptions`](globals.md#trackoptions) & \{ `userId`: [`IdType`](globals.md#idtype); \} + + + +The options for the company. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Throws + +An error if the company is not set or the options are invalid. + +###### Remarks + +The company must be set using `withCompany` before calling this method. +If the user is set, the company will be associated with the user. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`updateCompany`](globals.md#updatecompany) + +##### updateUser() + +```ts +updateUser(userId: IdType, options?: TrackOptions): Promise +``` + +Updates the associated user in Reflag. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`userId` + + + +[`IdType`](globals.md#idtype) + + + +The userId of the user to update. + +
+ +`options`? + + + +[`TrackOptions`](globals.md#trackoptions) + + + +The options for the user. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Throws + +An error if the company is not set or the options are invalid. + +###### Remarks + +The company must be set using `withCompany` before calling this method. +If the user is set, the company will be associated with the user. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`updateUser`](globals.md#updateuser) + +*** + +### ReflagClient + +The SDK client. + +#### Remarks + +This is the main class for interacting with Reflag. +It is used to evaluate flags, update user and company contexts, and track events. + +#### Example + +```ts +// set the REFLAG_SECRET_KEY environment variable or pass the secret key to the constructor +const client = new ReflagClient(); + +// evaluate a flag +const isFlagEnabled = client.getFlag("flag-key", { + user: { id: "user-id" }, + company: { id: "company-id" }, +}); +``` + +#### Extended by + +- [`EdgeClient`](globals.md#edgeclient) + +#### Constructors + +##### new ReflagClient() + +```ts +new ReflagClient(options: ClientOptions): ReflagClient +``` + +Creates a new SDK client. +See README for configuration options. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`options` + + + +[`ClientOptions`](globals.md#clientoptions) + + + +The options for the client or an existing client to clone. + +
+ +###### Returns + +[`ReflagClient`](globals.md#reflagclient) + +###### Throws + +An error if the options are invalid. + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyModifierTypeDescription
+ + `httpClient` + + + +`public` + + + +[`HttpClient`](globals.md#httpclient) + + + +‐ + +
+ + `logger` + + + +`readonly` + + + +[`Logger`](globals.md#logger) + + + +Gets the logger associated with the client. + +
+ +#### Accessors + +##### flagOverrides + +###### Set Signature + +```ts +set flagOverrides(overrides: + | Partial> + | FlagOverridesFn): void +``` + +###### Deprecated + +Use `setFlagOverrides()` for replacing the base override set. + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`overrides` + + + + \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagOverride`](globals.md#flagoverride)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn) + +
+ +###### Returns + +`void` + +#### Methods + +##### bindClient() + +```ts +bindClient(context: ContextWithTracking): BoundReflagClient +``` + +Returns a new BoundReflagClient with the user/company/otherContext +set to be used in subsequent calls. +For example, for evaluating flag targeting or tracking events. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`context` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +The context to bind the client to. + +
+ +###### Returns + +[`BoundReflagClient`](globals.md#boundreflagclient) + +A new client bound with the arguments given. + +###### Throws + +An error if the user/company is given but their ID is not a string. + +###### Remarks + +The `updateUser` / `updateCompany` methods will automatically be called when +the user/company is set respectively. + +##### clearFlagOverrides() + +```ts +clearFlagOverrides(): void +``` + +Clears the base flag overrides. + +###### Returns + +`void` + +###### Remarks + +This does not affect temporary layers added with `pushFlagOverrides()`. + +###### Example + +```ts +client.clearFlagOverrides(); +``` + +##### destroy() + +```ts +destroy(): void +``` + +Destroys the client and cleans up all resources including timers and background processes. + +###### Returns + +`void` + +###### Remarks + +After calling this method, the client should not be used anymore. +This is particularly useful in development environments with hot reloading to prevent +multiple background processes from running simultaneously. + +##### flush() + +```ts +flush(): Promise +``` + +Flushes and completes any in-flight fetches in the flag cache. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Remarks + +It is recommended to call this method when the application is shutting down to ensure all events are sent +before the process exits. + +This method is automatically called on natural process exit (`beforeExit`) if +`batchOptions.flushOnExit` is `true` in the options (default). For signal-driven +shutdown or an explicit `process.exit()`, await this method in your application's +shutdown hook before exiting. The SDK does not install signal handlers. + +##### getFlag() + +```ts +getFlag(__namedParameters: ContextWithTracking, key: TKey): Flag +``` + +Gets the evaluated flag for the current context which includes the user, company, and custom context. +Using the `isEnabled` property sends a `check` event to Reflag. + +###### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`TKey` *extends* `string` + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`__namedParameters` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +‐ + +
+ +`key` + + + +`TKey` + + + +The key of the flag to get. + +
+ +###### Returns + +[`Flag`](globals.md#flagtconfig) + +The evaluated flag. + +###### Remarks + +Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. + +##### getFlagDefinitions() + +```ts +getFlagDefinitions(): FlagDefinition[] +``` + +Gets the flag definitions, including all config values. +To evaluate which flags are enabled for a given user/company, use `getFlags`. + +###### Returns + +[`FlagDefinition`](globals.md#flagdefinition)[] + +The flags definitions. + +##### getFlagRemote() + +```ts +getFlagRemote( + key: TKey, + userId?: IdType, + companyId?: IdType, +additionalContext?: Context): Promise +``` + +Gets evaluated flag with the usage of remote context. +This method triggers a network request every time it's called. + +###### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`TKey` *extends* `string` + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`key` + + + +`TKey` + + + +The key of the flag to get. + +
+ +`userId`? + + + +[`IdType`](globals.md#idtype) + + + +The userId of the user to get the flag for. + +
+ +`companyId`? + + + +[`IdType`](globals.md#idtype) + + + +The companyId of the company to get the flag for. + +
+ +`additionalContext`? + + + +[`Context`](globals.md#context) + + + +The additional context to get the flag for. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Flag`](globals.md#flagtconfig)\> + +evaluated flag + +##### getFlags() + +```ts +getFlags(options: ContextWithTracking): Record +``` + +Gets the evaluated flags for the current context which includes the user, company, and custom context. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`options` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +The options for the context. + +
+ +###### Returns + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\> + +The evaluated flags. + +###### Remarks + +Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. + +##### getFlagsForBootstrap() + +```ts +getFlagsForBootstrap(options: ContextWithTracking): BootstrappedFlags +``` + +Gets the evaluated flags for the current context without wrapping them in getters. +This method returns raw flag data suitable for bootstrapping client-side applications. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`options` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +The options for the context. + +
+ +###### Returns + +[`BootstrappedFlags`](globals.md#bootstrappedflags) + +The evaluated raw flags and the context. + +###### Remarks + +Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. +This method returns RawFlag objects without wrapping them in getters, making them suitable for serialization. + +##### getFlagsRemote() + +```ts +getFlagsRemote( + userId?: IdType, + companyId?: IdType, +additionalContext?: Context): Promise> +``` + +Gets evaluated flags with the usage of remote context. +This method triggers a network request every time it's called. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`userId`? + + + +[`IdType`](globals.md#idtype) + + + +The userId of the user to get the flags for. + +
+ +`companyId`? + + + +[`IdType`](globals.md#idtype) + + + +The companyId of the company to get the flags for. + +
+ +`additionalContext`? + + + +[`Context`](globals.md#context) + + + +The additional context to get the flags for. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\>\> + +evaluated flags + +##### initialize() + +```ts +initialize(): Promise +``` + +Initializes the client by caching the flags definitions. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Remarks + +Call this method before calling `getFlags` to ensure the flag definitions are cached. +The client will ignore subsequent calls to this method. + +##### pushFlagOverrides() + +```ts +pushFlagOverrides(overrides: + | Partial> + | FlagOverridesFn): () => void +``` + +Temporarily layers flag overrides on top of the current overrides. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`overrides` + + + + \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagOverride`](globals.md#flagoverride)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn) + + + +The flag overrides to apply for the scoped period. + +
+ +###### Returns + +`Function` + +A remove function that removes only this override layer. + +###### Returns + +`void` + +###### Remarks + +This is intended for tests or other short-lived local overrides. The remove +function is idempotent and can safely be called multiple times. + +###### Example + +```ts +let remove: (() => void) | undefined; + +beforeEach(() => { + remove = client.pushFlagOverrides({ "flag-1": true }); +}); + +afterEach(() => { + remove?.(); + remove = undefined; +}); +``` + +##### refreshFlags() + +```ts +refreshFlags(waitForVersion?: number): Promise +``` + +Refreshes the flag definitions from the server. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`waitForVersion`? + + + +`number` + + + +Optional flag state version to wait for before returning updated definitions. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Remarks + +This triggers an on-demand refresh of the cached flag definitions. +Useful when you know flags have changed and don't want to wait for the next automatic refresh cycle. + +Note: updated flag rules take a few seconds to propagate to all servers. + +Fetch starts are throttled to at most once per second. +Outside `in-request` mode, throttling only delays when the next fetch +begins: `refreshFlags(99)` still waits until the cache has applied flag +definitions from version `99` or newer before the promise resolves. +Concurrent callers are deduplicated and may share the same in-flight or +scheduled follow-up refresh. + +In `in-request` mode, delayed follow-up refreshes are not scheduled. On edge +runtimes like Cloudflare Workers, a call during the throttle window only +records pending refresh work, and the promise may resolve before that fetch +runs. The pending refresh is executed on the next request/access or +`refreshFlags()` call after the throttle window expires. + +##### setFlagOverrides() + +```ts +setFlagOverrides(overrides: + | Partial> + | FlagOverridesFn): void +``` + +Replaces the base flag overrides used by the client. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`overrides` + + + + \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagOverride`](globals.md#flagoverride)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn) + + + +The flag overrides. + +
+ +###### Returns + +`void` + +###### Remarks + +Base overrides are always applied before any temporary layers added through +`pushFlagOverrides()`. + +###### Example + +```ts +client.setFlagOverrides({ + "flag-1": true, + "flag-2": false, +}); +``` + +##### track() + +```ts +track( + userId: IdType, + event: string, + options?: TrackOptions & { + companyId: IdType; +}): Promise +``` + +Tracks an event in Reflag. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`userId` + + + +[`IdType`](globals.md#idtype) + +
+ +`event` + + + +`string` + +
+ +`options`? + + + +[`TrackOptions`](globals.md#trackoptions) & \{ `companyId`: [`IdType`](globals.md#idtype); \} + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Throws + +An error if the user is not set or the event is invalid or the options are invalid. + +###### Remarks + +If the company is set, the event will be associated with the company. + +##### updateCompany() + +```ts +updateCompany(companyId: IdType, options?: TrackOptions & { + userId: IdType; +}): Promise +``` + +Updates the associated company in Reflag. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`companyId` + + + +[`IdType`](globals.md#idtype) + + + +The companyId of the company to update. + +
+ +`options`? + + + +[`TrackOptions`](globals.md#trackoptions) & \{ `userId`: [`IdType`](globals.md#idtype); \} + + + +The options for the company. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Throws + +An error if the company is not set or the options are invalid. + +###### Remarks + +The company must be set using `withCompany` before calling this method. +If the user is set, the company will be associated with the user. + +##### updateUser() + +```ts +updateUser(userId: IdType, options?: TrackOptions): Promise +``` + +Updates the associated user in Reflag. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`userId` + + + +[`IdType`](globals.md#idtype) + + + +The userId of the user to update. + +
+ +`options`? + + + +[`TrackOptions`](globals.md#trackoptions) + + + +The options for the user. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Throws + +An error if the company is not set or the options are invalid. + +###### Remarks + +The company must be set using `withCompany` before calling this method. +If the user is set, the company will be associated with the user. + +## Interfaces + +### ContextWithTracking + +A context with tracking option. + +#### Extends + +- [`Context`](globals.md#context) + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `company?` + + + +\{ `[k: string]`: `any`; `avatar`: `string`; `id`: `undefined` \| `string` \| `number`; `name`: `string`; \} + + + +The company context. If no `id` key is set, the whole object is ignored. + +
+ +`company.avatar?` + + + +`string` + + + +The avatar URL of the company. + +
+ +`company.id` + + + +`undefined` \| `string` \| `number` + + + +The identifier of the company. + +
+ +`company.name?` + + + +`string` + + + +The name of the company. + +
+ + `enableTracking?` + + + +`boolean` + + + +Enable tracking for the context. +If set to `false`, tracking will be disabled for the context. Default is `true`. + +
+ + `meta?` + + + +[`TrackingMeta`](globals.md#trackingmeta) + + + +The meta context used to update the user or company when syncing is required during +feature retrieval. + +
+ + `other?` + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + + + +The other context. This is used for any additional context that is not related to user or company. + +
+ + `user?` + + + +\{ `[k: string]`: `any`; `avatar`: `string`; `email`: `string`; `id`: `undefined` \| `string` \| `number`; `name`: `string`; \} + + + +The user context. If no `id` key is set, the whole object is ignored. + +
+ +`user.avatar?` + + + +`string` + + + +The avatar URL of the user. + +
+ +`user.email?` + + + +`string` + + + +The email of the user. + +
+ +`user.id` + + + +`undefined` \| `string` \| `number` + + + +The identifier of the user. + +
+ +`user.name?` + + + +`string` + + + +The name of the user. + +
+ +*** + +### Flag\ + +Describes a feature + +#### Type Parameters + + + + + + + + + + + + + + +
Type ParameterDefault type
+ +`TConfig` *extends* [`FlagType`](globals.md#flagtype)\[`"config"`\] + + + +[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) + +
+ +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `config` + + + + \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| \{ `key`: `string`; \} & `TConfig` + + + +‐ + +
+ + `isEnabled` + + + +`boolean` + + + +If the feature is enabled. + +
+ + `key` + + + +`string` + + + +The key of the feature. + +
+ +#### Methods + +##### track() + +```ts +track(): Promise +``` + +Track feature usage in Reflag. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +*** + +### Flags + +Describes a collection of evaluated features. + +#### Remarks + +You should extend the Flags interface to define the available features. + +*** + +### FlagsFallbackProvider + +Provider used to load and save raw flag definition snapshots. + +#### Methods + +##### load() + +```ts +load(context: FlagsFallbackProviderContext): Promise +``` + +Load a previously saved snapshot. + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`context` + + + +[`FlagsFallbackProviderContext`](globals.md#flagsfallbackprovidercontext) + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`undefined` \| [`FlagsFallbackSnapshot`](globals.md#flagsfallbacksnapshot)\> + +##### save() + +```ts +save(context: FlagsFallbackProviderContext, snapshot: FlagsFallbackSnapshot): Promise +``` + +Persist a snapshot after a successful live fetch. + +###### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`context` + + + +[`FlagsFallbackProviderContext`](globals.md#flagsfallbackprovidercontext) + +
+ +`snapshot` + + + +[`FlagsFallbackSnapshot`](globals.md#flagsfallbacksnapshot) + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +*** + +### HttpClient + +Defines the interface for an HTTP client. + +#### Remarks + +This interface is used to abstract the HTTP client implementation from the SDK. +Define your own implementation of this interface to use a different HTTP client. + +#### Methods + +##### get() + +```ts +get( + url: string, + headers: Record, +timeoutMs: number): Promise> +``` + +Sends a GET request to the specified URL. + +###### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`TResponse` + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`url` + + + +`string` + + + +The URL to send the request to. + +
+ +`headers` + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `string`\> + + + +The headers to include in the request. + +
+ +`timeoutMs` + + + +`number` + + + +‐ + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`HttpClientResponse`](globals.md#httpclientresponsetresponse)\<`TResponse`\>\> + +The response from the server. + +##### post() + +```ts +post( + url: string, + headers: Record, +body: TBody): Promise> +``` + +Sends a POST request to the specified URL. + +###### Type Parameters + + + + + + + + + + + + + + + +
Type Parameter
+ +`TBody` + +
+ +`TResponse` + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`url` + + + +`string` + + + +The URL to send the request to. + +
+ +`headers` + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `string`\> + + + +The headers to include in the request. + +
+ +`body` + + + +`TBody` + + + +The body of the request. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`HttpClientResponse`](globals.md#httpclientresponsetresponse)\<`TResponse`\>\> + +The response from the server. + +*** + +### Logger + +Logger interface for logging messages + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `debug` + + + +(`message`: `string`, `data`?: `any`) => `void` + + + +Log a debug messages + +
+ + `error` + + + +(`message`: `string`, `data`?: `any`) => `void` + + + +Log an error messages + +
+ + `info` + + + +(`message`: `string`, `data`?: `any`) => `void` + + + +Log an info messages + +
+ + `warn` + + + +(`message`: `string`, `data`?: `any`) => `void` + + + +Log a warning messages + +
+ +*** + +### RawFlag + +Describes a feature. + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `config?` + + + +[`RawFlagRemoteConfig`](globals.md#rawflagremoteconfig) + + + +The remote configuration value for the feature. + +
+ + `evaluationErrors?` + + + +`EvaluationError`[] + + + +Non-fatal diagnostics produced while evaluating targeting rules. + +
+ + `isEnabled` + + + +`boolean` + + + +If the feature is enabled. + +
+ + `key` + + + +`string` + + + +The key of the feature. + +
+ + ~~`missingContextFields?`~~ + + + +`string`[] + + + +The missing fields in the evaluation context (optional). + +**Deprecated** + +Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. + +
+ + `ruleEvaluationResults?` + + + +`boolean`[] + + + +The rule results of the evaluation (optional). + +
+ + `targetingVersion?` + + + +`number` + + + +The version of the targeting used to evaluate if the feature is enabled (optional). + +
+ +## Type Aliases + +### Attributes + +```ts +type Attributes = Record; +``` + +Describes the attributes of a user, company or event. + +*** + +### BatchBufferOptions\ + +```ts +type BatchBufferOptions = { + flushHandler: (items: T[]) => Promise; + flushOnExit: boolean; + intervalMs: number; + logger: Logger; + maxSize: number; +}; +``` + +Options for configuring the BatchBuffer. + +#### Type Parameters + + + + + + + + + + + + + + +
Type ParameterDescription
+ +`T` + + + +The type of items in the buffer. + +
+ +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `flushHandler` + + + +(`items`: `T`[]) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + + + +A function that handles flushing the items in the buffer. + +
+ + `flushOnExit`? + + + +`boolean` + + + +Whether to flush the buffer on natural process exit (`beforeExit`). +This does not install signal handlers. For signal-driven shutdown or an +explicit `process.exit()`, await `client.flush()` in your application's +shutdown hook before exiting. + +
+ + `intervalMs`? + + + +`number` + + + +The interval in milliseconds at which the buffer is flushed. + +**Remarks** + +If `0`, the buffer is flushed only when `maxSize` is reached. + +
+ + `logger`? + + + +[`Logger`](globals.md#logger) + + + +The logger to use for logging (optional). + +
+ + `maxSize`? + + + +`number` + + + +The maximum size of the buffer before it is flushed. + +
+ +*** + +### BootstrappedFlags + +```ts +type BootstrappedFlags = { + context: Context; + flags: RawFlags; + flagStateVersion: number; +}; +``` + +Describes a collection of evaluated raw flags and the context for bootstrapping. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `context` + + + +[`Context`](globals.md#context) + +
+ + `flags` + + + +[`RawFlags`](globals.md#rawflags) + +
+ + `flagStateVersion`? + + + +`number` + +
+ +*** + +### CacheStrategy + +```ts +type CacheStrategy = "periodically-update" | "in-request"; +``` + +*** + +### ClientOptions + +```ts +type ClientOptions = { + apiBaseUrl: string; + batchOptions: Omit, "flushHandler" | "logger">; + cacheStrategy: CacheStrategy; + configFile: string; + emitEvaluationEvents: boolean; + fallbackFlags: | TypedFlagKey[] + | Record>; + fetchTimeoutMs: number; + flagOverrides: | FlagOverrides + | (context: Context) => FlagOverrides; + flagsFallbackProvider: FlagsFallbackProvider; + flagsFetchRetries: number; + flagsPushUrl: string; + flagsSyncMode: FlagsSyncMode; + host: string; + httpClient: HttpClient; + logger: Logger; + logLevel: LogLevel; + offline: boolean; + secretKey: string; +}; +``` + +Defines the options for the SDK client. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `apiBaseUrl`? + + + +`string` + + + +The host to send requests to (optional). + +
+ + `batchOptions`? + + + +[`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`BatchBufferOptions`](globals.md#batchbufferoptionst)\<`any`\>, `"flushHandler"` \| `"logger"`\> + + + +The options for the batch buffer (optional). +If not provided, the default options are used. + +
+ + `cacheStrategy`? + + + +[`CacheStrategy`](globals.md#cachestrategy) + + + +**Deprecated** + +Use `flagsSyncMode`. + +
+ + `configFile`? + + + +`string` + + + +The path to the config file. If supplied, the config file will be loaded. +Defaults to `reflag.config.json` when NODE_ENV is not production. Can also be +set through the environment variable REFLAG_CONFIG_FILE. + +
+ + `emitEvaluationEvents`? + + + +`boolean` + + + +Deprecated: evaluation events are no longer emitted. + +**Deprecated** + +This option has no effect and will be removed in the next major version. + +
+ + `fallbackFlags`? + + + + \| [`TypedFlagKey`](globals.md#typedflagkey)[] + \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<[`TypedFlagKey`](globals.md#typedflagkey), [`Exclude`](https://www.typescriptlang.org/docs/handbook/utility-types.html#excludeuniontype-excludedmembers)\<[`FlagOverride`](globals.md#flagoverride), `false`\>\> + + + +The features to "enable" as fallbacks when the API is unavailable (optional). +Can be an array of feature keys, or a record of feature keys and boolean or object values. + +If a record is supplied instead of array, the values of each key are either the +configuration values or the boolean value `true`. + +**Deprecated** + +Use `flagsFallbackProvider` instead. + +
+ + `fetchTimeoutMs`? + + + +`number` + + + +The timeout in milliseconds for fetching feature targeting data (optional). +Default is 10000 ms. + +
+ + `flagOverrides`? + + + + \| [`FlagOverrides`](globals.md#flagoverrides) + \| (`context`: [`Context`](globals.md#context)) => [`FlagOverrides`](globals.md#flagoverrides) + + + +Local flag overrides for testing or development. + +If a function is specified, the function will be called with the context +and should return a record of flag keys and boolean or object values. + +
+ + `flagsFallbackProvider`? + + + +[`FlagsFallbackProvider`](globals.md#flagsfallbackprovider) + + + +Optional provider used to load and save raw flag definitions for fallback startup. +Ignored in offline mode. + +
+ + `flagsFetchRetries`? + + + +`number` + + + +Number of times to retry fetching feature definitions (optional). +Default is 3 times. + +
+ + `flagsPushUrl`? + + + +`string` + + + +Push endpoint used when `flagsSyncMode` is `"push"`. + +
+ + `flagsSyncMode`? + + + +[`FlagsSyncMode`](globals.md#flagssyncmode) + + + +How flag definitions are synchronized. + +- `push` (default): live updates over SSE keep flag definitions up to date. +- `polling`: periodic background refresh. +- `in-request`: stale refresh is triggered during request handling. + +
+ + `host`? + + + +`string` + + + +**Deprecated** + +Use `apiBaseUrl` instead. + +
+ + `httpClient`? + + + +[`HttpClient`](globals.md#httpclient) + + + +The HTTP client to use for sending requests (optional). Default is the built-in fetch client. + +
+ + `logger`? + + + +[`Logger`](globals.md#logger) + + + +The logger to use for logging (optional). Default is info level logging to console. + +
+ + `logLevel`? + + + +[`LogLevel`](globals.md#loglevel) + + + +Use the console logger, but set a log level. Ineffective if a custom logger is provided. + +
+ + `offline`? + + + +`boolean` + + + +In offline mode, no data is sent or fetched from the the Reflag API, +and `flagsFallbackProvider` is not used. +This is useful for testing or development. + +
+ + `secretKey`? + + + +`string` + + + +The secret key used to authenticate with the Reflag API. + +
+ +*** + +### Context + +```ts +type Context = { + company: { + [k: string]: any; avatar: string; + id: string | number | undefined; + name: string; + }; + other: Record; + user: { + [k: string]: any; avatar: string; + email: string; + id: string | number | undefined; + name: string; + }; +}; +``` + +Describes the current user context, company context, and other context. +This is used to determine if feature targeting matches and to track events. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `company`? + + + +\{ +`[k: string]`: `any`; `avatar`: `string`; + `id`: `string` \| `number` \| `undefined`; + `name`: `string`; + \} + + + +The company context. If no `id` key is set, the whole object is ignored. + +
+ +`company.avatar`? + + + +`string` + + + +The avatar URL of the company. + +
+ +`company.id` + + + +`string` \| `number` \| `undefined` + + + +The identifier of the company. + +
+ +`company.name`? + + + +`string` + + + +The name of the company. + +
+ + `other`? + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + + + +The other context. This is used for any additional context that is not related to user or company. + +
+ + `user`? + + + +\{ +`[k: string]`: `any`; `avatar`: `string`; + `email`: `string`; + `id`: `string` \| `number` \| `undefined`; + `name`: `string`; + \} + + + +The user context. If no `id` key is set, the whole object is ignored. + +
+ +`user.avatar`? + + + +`string` + + + +The avatar URL of the user. + +
+ +`user.email`? + + + +`string` + + + +The email of the user. + +
+ +`user.id` + + + +`string` \| `number` \| `undefined` + + + +The identifier of the user. + +
+ +`user.name`? + + + +`string` + + + +The name of the user. + +
+ +*** + +### EdgeClientOptions + +```ts +type EdgeClientOptions = Omit; +``` + +*** + +### EmptyFlagRemoteConfig + +```ts +type EmptyFlagRemoteConfig = { + key: undefined; + payload: undefined; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `key` + + + +`undefined` + +
+ + `payload` + + + +`undefined` + +
+ +*** + +### FileFallbackProviderOptions + +```ts +type FileFallbackProviderOptions = { + directory: string; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `directory`? + + + +`string` + + + +Directory where per-environment snapshots are stored. + +
+ +*** + +### FlagAPIResponse + +```ts +type FlagAPIResponse = { + config: { + variants: FlagConfigVariant[]; + version: number; + }; + description: string | null; + key: string; + targeting: { + rules: { + filter: RuleFilter; + }[]; + version: number; + }; +}; +``` + +**`Internal`** + +(Internal) Describes a specific feature in the API response. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `config`? + + + +\{ + `variants`: [`FlagConfigVariant`](globals.md#flagconfigvariant)[]; + `version`: `number`; + \} + + + +The remote configuration for the feature. + +
+ +`config.variants` + + + +[`FlagConfigVariant`](globals.md#flagconfigvariant)[] + + + +The variants of the remote configuration. + +
+ +`config.version` + + + +`number` + + + +The version of the remote configuration. + +
+ + `description` + + + +`string` \| `null` + + + +Description of the feature. + +
+ + `key` + + + +`string` + + + +The key of the feature. + +
+ + `targeting` + + + +\{ + `rules`: \{ + `filter`: `RuleFilter`; + \}[]; + `version`: `number`; + \} + + + +The targeting rules for the feature. + +
+ +`targeting.rules` + + + +\{ + `filter`: `RuleFilter`; + \}[] + + + +The targeting rules. + +
+ +`targeting.version` + + + +`number` + + + +The version of the targeting rules. + +
+ +*** + +### FlagConfigVariant + +```ts +type FlagConfigVariant = { + filter: RuleFilter; + key: string; + payload: any; +}; +``` + +Describes a remote feature config variant. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `filter` + + + +`RuleFilter` + + + +The filter for the variant. + +
+ + `key` + + + +`string` + + + +The key of the variant. + +
+ + `payload` + + + +`any` + + + +The optional user-supplied payload data. + +
+ +*** + +### FlagDefinition + +```ts +type FlagDefinition = { + config: { + variants: FlagConfigVariant[]; + version: number; + }; + description: string | null; + flag: { + rules: { + filter: RuleFilter; + }[]; + version: number; + }; + key: string; +}; +``` + +Describes a feature definition. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `config`? + + + +\{ + `variants`: [`FlagConfigVariant`](globals.md#flagconfigvariant)[]; + `version`: `number`; + \} + + + +The remote configuration for the feature. + +
+ +`config.variants` + + + +[`FlagConfigVariant`](globals.md#flagconfigvariant)[] + + + +The variants of the remote configuration. + +
+ +`config.version` + + + +`number` + + + +The version of the remote configuration. + +
+ + `description` + + + +`string` \| `null` + + + +Description of the feature. + +
+ + `flag` + + + +\{ + `rules`: \{ + `filter`: `RuleFilter`; + \}[]; + `version`: `number`; + \} + + + +The targeting rules for the feature. + +
+ +`flag.rules` + + + +\{ + `filter`: `RuleFilter`; + \}[] + + + +The targeting rules. + +
+ +`flag.version` + + + +`number` + + + +The version of the targeting rules. + +
+ + `key` + + + +`string` + + + +The key of the feature. + +
+ +*** + +### FlagOverride + +```ts +type FlagOverride = + | FlagType & { + config: { + key: string; + }; + isEnabled: boolean; + } + | boolean; +``` + +*** + +### FlagOverrides + +```ts +type FlagOverrides = Partial : { [FlagKey in keyof Flags]: Flags[FlagKey] extends FlagOverride ? Flags[FlagKey] : Exclude }>; +``` + +Describes the feature overrides. + +*** + +### FlagOverridesFn() + +```ts +type FlagOverridesFn = (context: Context) => FlagOverrides; +``` + +#### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`context` + + + +[`Context`](globals.md#context) + +
+ +#### Returns + +[`FlagOverrides`](globals.md#flagoverrides) + +*** + +### FlagRemoteConfig + +```ts +type FlagRemoteConfig = + | { + key: string; + payload: any; + } + | EmptyFlagRemoteConfig; +``` + +A remotely managed configuration value for a feature. + +#### Type declaration + +\{ + `key`: `string`; + `payload`: `any`; + \} + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`key` + + + +`string` + + + +The key of the matched configuration value. + +
+ +`payload` + + + +`any` + + + +The optional user-supplied payload data. + +
+ +[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) + +*** + +### FlagsAPIResponse + +```ts +type FlagsAPIResponse = { + features: FlagAPIResponse[]; + flagStateVersion: number; +}; +``` + +**`Internal`** + +(Internal) Describes the response of the features endpoint. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `features` + + + +[`FlagAPIResponse`](globals.md#flagapiresponse)[] + + + +The feature definitions. + +
+ + `flagStateVersion`? + + + +`number` + + + +Optional for backward compatibility; when absent, the snapshot version +should be treated as unknown by consumers. + +
+ +*** + +### FlagsFallbackProviderContext + +```ts +type FlagsFallbackProviderContext = { + secretKeyHash: string; +}; +``` + +Non-secret context passed to fallback providers so they can derive +storage keys without access to the raw secret key. + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `secretKeyHash` + + + +`string` + + + +Deterministic hash of the configured secret key. + +
+ +*** + +### FlagsFallbackSnapshot + +```ts +type FlagsFallbackSnapshot = { + flags: FlagAPIResponse[]; + savedAt: string; + version: number; +}; +``` + +Snapshot of flag definitions used for fallback initialization. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `flags` + + + +[`FlagAPIResponse`](globals.md#flagapiresponse)[] + + + +Raw flag definitions as returned by the API. + +
+ + `savedAt` + + + +`string` + + + +ISO timestamp indicating when the snapshot was saved. + +
+ + `version` + + + +`number` + + + +Snapshot schema version. + +
+ +*** + +### FlagsSyncMode + +```ts +type FlagsSyncMode = "polling" | "in-request" | "push"; +``` + +*** + +### FlagType + +```ts +type FlagType = { + config: { + payload: any; + }; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `config`? + + + +\{ + `payload`: `any`; + \} + +
+ +`config.payload` + + + +`any` + +
+ +*** + +### GCSFallbackProviderClient + +```ts +type GCSFallbackProviderClient = + | GCSLegacyClient + | GCSGoogleApisClient; +``` + +*** + +### GCSFallbackProviderOptions + +```ts +type GCSFallbackProviderOptions = { + bucket: string; + client: GCSFallbackProviderClient; + keyPrefix: string; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `bucket` + + + +`string` + + + +Bucket where snapshots are stored. + +
+ + `client`? + + + +[`GCSFallbackProviderClient`](globals.md#gcsfallbackproviderclient) + + + +Optional GCS client. A default client is created when omitted. + +Accepts either a legacy `bucket().file()` client or a generated +`@googleapis/storage` client. + +TODO(next major): Replace this with a simpler object-store interface. + +
+ + `keyPrefix`? + + + +`string` + + + +Prefix for generated per-environment keys. + +
+ +*** + +### GCSGoogleApisClient + +```ts +type GCSGoogleApisClient = { + objects: { + get: Promise<{ + data: unknown; + }>; + insert: Promise; + }; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `objects` + + + +\{ + `get`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<\{ + `data`: `unknown`; + \}\>; + `insert`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`unknown`\>; + \} + +
+ + `get()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<\{ + `data`: `unknown`; + \}\> + +
+ + `insert()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`unknown`\> + +
+ +*** + +### GCSLegacyClient + +```ts +type GCSLegacyClient = { + bucket: { + file: { + download: Promise<[Uint8Array]>; + exists: Promise<[boolean]>; + save: Promise; + }; + }; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + +
NameType
+ + `bucket()` + + + +\{ + `file`: \{ + `download`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<\[[`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\]\>; + `exists`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<\[`boolean`\]\>; + `save`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`unknown`\>; + \}; + \} + +
+ +*** + +### HttpClientResponse\ + +```ts +type HttpClientResponse = { + body: TResponse | undefined; + etag: string; + ok: boolean; + status: number; +}; +``` + +Describes the response of a HTTP client. + +#### Type Parameters + + + + + + + + + + + + + + +
Type ParameterDescription
+ +`TResponse` + + + +The type of the response body. + +
+ +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `body` + + + +`TResponse` \| `undefined` + + + +The body of the response if available. + +
+ + `etag`? + + + +`string` + + + +The response's ETag, if available. Return its exact value to enable +conditional flag-definition refreshes with a custom HTTP client. + +
+ + `ok` + + + +`boolean` + + + +Indicates that the request succeeded. + +
+ + `status` + + + +`number` + + + +The status code of the response. + +
+ +*** + +### IdType + +```ts +type IdType = string | number; +``` + +*** + +### LogLevel + +```ts +type LogLevel = typeof LOG_LEVELS[number]; +``` + +*** + +### RawFlagRemoteConfig + +```ts +type RawFlagRemoteConfig = { + evaluationErrors: EvaluationError[]; + key: string; + missingContextFields: string[]; + payload: any; + ruleEvaluationResults: boolean[]; + targetingVersion: number; +}; +``` + +A remotely managed configuration value for a feature. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `evaluationErrors`? + + + +`EvaluationError`[] + + + +Non-fatal diagnostics produced while evaluating targeting rules. + +
+ + `key` + + + +`string` + + + +The key of the matched configuration value. + +
+ + `missingContextFields`? + + + +`string`[] + + + +The missing fields in the evaluation context (optional). + +**Deprecated** + +Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. + +
+ + `payload` + + + +`any` + + + +The optional user-supplied payload data. + +
+ + `ruleEvaluationResults`? + + + +`boolean`[] + + + +The rule results of the evaluation (optional). + +
+ + `targetingVersion`? + + + +`number` + + + +The version of the targeting rules used to select the config value. + +
+ +*** + +### RawFlags + +```ts +type RawFlags = Record; +``` + +Describes a collection of evaluated raw flags. + +*** + +### RedisFallbackProviderOptions + +```ts +type RedisFallbackProviderOptions = { + client: { + get: Promise; + set: Promise; + }; + keyPrefix: string; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `client`? + + + +\{ + `get`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`undefined` \| `null` \| `string`\>; + `set`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`unknown`\>; + \} + + + +Optional Redis client. When omitted, a client is created using `REDIS_URL`. + +
+ + `get()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`undefined` \| `null` \| `string`\> + + + +‐ + +
+ + `set()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`unknown`\> + + + +‐ + +
+ + `keyPrefix`? + + + +`string` + + + +Prefix for generated per-environment keys. + +
+ +*** + +### S3FallbackProviderOptions + +```ts +type S3FallbackProviderOptions = { + bucket: string; + client: { + send: Promise; + }; + keyPrefix: string; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `bucket` + + + +`string` + + + +Bucket where snapshots are stored. + +
+ + `client`? + + + +\{ + `send`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`any`\>; + \} + + + +Optional S3 client. A default client is created when omitted. + +
+ + `send()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`any`\> + + + +‐ + +
+ + `keyPrefix`? + + + +`string` + + + +Prefix for generated per-environment keys. + +
+ +*** + +### StaticFallbackProviderOptions + +```ts +type StaticFallbackProviderOptions = { + flags: Record; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `flags` + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `boolean`\> + + + +Static fallback flags keyed by flag key. + +
+ +*** + +### TrackingMeta + +```ts +type TrackingMeta = { + active: boolean; +}; +``` + +Describes the meta context associated with tracking. + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `active`? + + + +`boolean` + + + +Whether the user or company is active. + +
+ +*** + +### TrackOptions + +```ts +type TrackOptions = { + attributes: Attributes; + meta: TrackingMeta; +}; +``` + +Defines the options for tracking of entities. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `attributes`? + + + +[`Attributes`](globals.md#attributes) + + + +The attributes associated with the event. + +
+ + `meta`? + + + +[`TrackingMeta`](globals.md#trackingmeta) + + + +The meta context associated with the event. + +
+ +*** + +### TypedFlagKey + +```ts +type TypedFlagKey = keyof TypedFlags; +``` + +*** + +### TypedFlags + +```ts +type TypedFlags = keyof Flags extends never ? Record : { [FlagKey in keyof Flags]: Flags[FlagKey] extends FlagType ? Flag : Flag }; +``` + +Describes a collection of evaluated feature. + +#### Remarks + +This types falls back to a generic Record if the Flags interface +has not been extended. + +## Variables + +### fallbackProviders + +```ts +const fallbackProviders: { + file: (__namedParameters: FileFallbackProviderOptions) => FlagsFallbackProvider; + gcs: (__namedParameters: GCSFallbackProviderOptions) => FlagsFallbackProvider; + redis: (__namedParameters: RedisFallbackProviderOptions) => FlagsFallbackProvider; + s3: (__namedParameters: S3FallbackProviderOptions) => FlagsFallbackProvider; + static: (__namedParameters: StaticFallbackProviderOptions) => FlagsFallbackProvider; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDefault value
+ + `file` + + + +(`__namedParameters`: [`FileFallbackProviderOptions`](globals.md#filefallbackprovideroptions)) => [`FlagsFallbackProvider`](globals.md#flagsfallbackprovider) + + + +createFileFallbackProvider + +
+ + `gcs` + + + +(`__namedParameters`: [`GCSFallbackProviderOptions`](globals.md#gcsfallbackprovideroptions)) => [`FlagsFallbackProvider`](globals.md#flagsfallbackprovider) + + + +createGCSFallbackProvider + +
+ + `redis` + + + +(`__namedParameters`: [`RedisFallbackProviderOptions`](globals.md#redisfallbackprovideroptions)) => [`FlagsFallbackProvider`](globals.md#flagsfallbackprovider) + + + +createRedisFallbackProvider + +
+ + `s3` + + + +(`__namedParameters`: [`S3FallbackProviderOptions`](globals.md#s3fallbackprovideroptions)) => [`FlagsFallbackProvider`](globals.md#flagsfallbackprovider) + + + +createS3FallbackProvider + +
+ + `static` + + + +(`__namedParameters`: [`StaticFallbackProviderOptions`](globals.md#staticfallbackprovideroptions)) => [`FlagsFallbackProvider`](globals.md#flagsfallbackprovider) + + + +createStaticFallbackProvider + +
+ +*** + +### LOG\_LEVELS + +```ts +const LOG_LEVELS: readonly ["DEBUG", "INFO", "WARN", "ERROR"]; +``` diff --git a/legacy/v1/react-sdk/README.md b/legacy/v1/react-sdk/README.md new file mode 100644 index 0000000..7162133 --- /dev/null +++ b/legacy/v1/react-sdk/README.md @@ -0,0 +1,984 @@ +--- +layout: + visible: true +title: + visible: true +description: + visible: false +tableOfContents: + visible: true +outline: + visible: true +pagination: + visible: true +--- + +{% hint style="info" %} +**Protocol v1 — legacy.** [Current v2 documentation](../../../supported-languages/react-sdk/README.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) + +Generated from [`@reflag/react-sdk@1.7.4`](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/react-sdk); SDK READMEs and code comments remain the source of truth. +{% endhint %} + +# Reflag React SDK + +React client side library for [Reflag.com](https://reflag.com) + +Reflag supports flag toggling, tracking flag usage, [requesting feedback](#userequestfeedback) on features, and [remotely configuring flags](#remote-config). + +The Reflag React SDK comes with a [built-in toolbar](../browser-sdk/README.md#toolbar) which appears on `localhost` by default. + +## Install + +Install via npm: + +```shell +npm i @reflag/react-sdk@1 +``` + +## Get started + +### 1. Add the `ReflagProvider` context provider + +Add the `ReflagProvider` context provider to your application: + +**Example:** + +```tsx +import { ReflagProvider } from "@reflag/react-sdk"; + +} +> + {/* children here are shown when loading finishes or immediately if no `loadingComponent` is given */} +; +``` + +### 2. Create a new flag and set up type safety + +Install the Reflag CLI: + +```shell +npm i --save-dev @reflag/cli@1 +``` + +Run `npx reflag new` to create your first flag! +On the first run, it will sign into Reflag and set up type generation for your project: + +```shell +❯ npx reflag new +Opened web browser to facilitate login: https://app.reflag.com/api/oauth/cli/authorize + +Welcome to ◪ Reflag! + +? Where should we generate the types? gen/flags.d.ts +? What is the output format? react +✔ Configuration created at reflag.config.json. + +Creating flag for app Slick app. +? New flag name: Huddle +? New flag key: huddle +✔ Created flag Huddle with key huddle (https://app.reflag.com/features/huddles) +✔ Generated react types in gen/flags.d.ts. +``` + +> [!Note] +> By default, types will be generated in `gen/flags.d.ts`. +> The default `tsconfig.json` file `include`s this file by default, but if your `tsconfig.json` is different, make sure the file is covered in the `include` property. + +### 3. Use `useFlag()` to get flag status + +Using the `useFlag` hook from your components lets you toggle flags on/off and track flag usage: + +**Example:** + +```tsx +function StartHuddleButton() { + const { + isEnabled, // boolean indicating if the flag is enabled + track, // track usage of the flag + } = useFlag("huddle"); + + if (!isEnabled) { + return null; + } + + return ; +} +``` + +`useFlag` can help you do much more. See a full example for `useFlag` [see below](#useflag). + +## Setting context + +Reflag determines which flags are active for a given `user`, `company`, or `other` context. +You can pass these to the `ReflagProvider` using the `context` prop. + +### Using the `context` prop + +```tsx + + + {/* children here are shown when loading finishes */} + + +``` + +### Legacy individual props (deprecated) + +For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version: + +```tsx + + + {/* children here are shown when loading finishes */} + + +``` + +> [!Important] +> The `user`, `company`, and `otherContext` props are deprecated. Use the `context` prop instead, which provides the same functionality in a more structured way. + +### Context requirements + +If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. +In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. +Attributes which are not properties of the `user` or `company` can be supplied using the `other` property. + +Attributes cannot be nested (multiple levels) and must be either strings, numbers or booleans. +A number of special attributes exist: + +- `name` -- display name for `user`/`company`, +- `email` -- the email of the user, +- `avatar` -- the URL for `user`/`company` avatar image. + +To retrieve flags along with their targeting information, use `useFlag(key: string)` hook (described in a section below). + +Note that accessing `isEnabled` on the object returned by `useFlag()` automatically +generates a `check` event. + +## React Native + +For React Native, use `@reflag/react-native-sdk`, which is a thin wrapper around +`@reflag/react-sdk` and wires up AsyncStorage by default. + +An Expo example app lives at `packages/react-native-sdk/dev/expo`. + +## Remote config + +Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. + +Similar to `isEnabled`, each flag accessed using the `useFlag()` hook, has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the +binary `isEnabled` you can have multiple configuration values which are given to different user/companies. + +### Get started with Remote config + +1. Update your flag definitions: + +```typescript +import "@reflag/react-sdk"; + +// Define your flags by extending the `Flags` interface in @reflag/react-sdk +declare module "@reflag/react-sdk" { + interface Flags { + huddle: { + // change from `boolean` to an object which sets + // a type for the remote config for `questionnaire` + maxTokens: number; + model: string; + }; + } +} +``` + +```ts +const { + isEnabled, + config: { key, payload }, +} = useFlag("huddles"); + +// isEnabled: true, +// key: "gpt-3.5", +// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } +``` + +`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. + +Note that, similar to `isEnabled`, accessing `config` on the object returned by `useFlag()` automatically +generates a `check` event. + +## Toolbar + +The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off. + +Toolbar + +The toolbar will automatically appear on `localhost`. However, it can also be incredibly useful in production. You have full control over when it appears through the `toolbar` configuration option passed to the ReflagProvider. + +You can pass a simple boolean to force the toolbar to appear/disappear: + +```ts +` component is a specialized version of `ReflagProvider` designed for server-side rendering, preloaded flag scenarios, and high-reliability setups. It uses pre-fetched evaluated state for the initial render, resulting in faster initial page loads, better SSR compatibility, and a more resilient startup path for React applications. + +```tsx +import { useState, useEffect } from "react"; +import { BootstrappedFlags } from "@reflag/react-sdk"; + +interface BootstrapData { + user: User; + flags: BootstrappedFlags; +} + +function useBootstrap() { + const [data, setData] = useState(null); + + useEffect(() => { + fetch("/bootstrap") + .then((res) => res.json()) + .then(setData); + }, []); + + return data; +} + +// Usage in your app +function App() { + const { user, flags } = useBootstrap(); + + return ( + + + + + + ); +} +``` + +### Server-side endpoint setup + +Create an endpoint that provides bootstrap data to your client application: + +```typescript +// server.js or your Express app +import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; + +const reflagClient = new ReflagNodeClient({ + secretKey: process.env.REFLAG_SECRET_KEY, +}); +await reflagClient.initialize(); + +app.get("/bootstrap", (req, res) => { + const user = getUser(req); // Get user from your auth system + const company = getCompany(req); // Get company from your auth system + + const flags = reflagClient.getFlagsForBootstrap({ + user: { id: "user123", name: "John Doe", email: "john@acme.com" }, + company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, + other: { source: "web" }, + }); + + res.status(200).json({ + user, + flags, + }); +}); +``` + +The `flags` object returned by `getFlagsForBootstrap()` contains the full bootstrapped state package: + +- `context`: the evaluation context used on the server +- `flags`: the evaluated raw flags +- `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping + +If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. + +### Next.js Page Router SSR example + +For Next.js applications using server-side rendering, you can pre-fetch flags in `getServerSideProps`: + +```typescript +// pages/index.tsx +import { GetServerSideProps } from "next"; +import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; +import { ReflagBootstrappedProvider, BootstrappedFlags, useFlag } from "@reflag/react-sdk"; + +interface PageProps { + bootstrapData: BootstrappedFlags; +} + +export const getServerSideProps: GetServerSideProps = async (context) => { + const serverClient = new ReflagNodeClient({ + secretKey: process.env.REFLAG_SECRET_KEY + }); + await serverClient.initialize(); + + const user = await getUserFromSession(context.req); + const company = await getCompanyFromUser(user); + + const bootstrapData = serverClient.getFlagsForBootstrap({ + user: { id: "user123", name: "John Doe", email: "john@acme.com" }, + company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, + other: { page: "homepage" } + }); + + return { props: { bootstrapData } }; +}; + +export default function HomePage({ bootstrapData }: PageProps) { + return ( + + + + ); +} + +function HuddleFeature() { + const { isEnabled, track, config } = useFlag("huddle"); + + if (!isEnabled) return null; + + return ( +
+

Start a Huddle

+

Max participants: {config.payload?.maxParticipants ?? 10}

+

Video quality: {config.payload?.videoQuality ?? "standard"}

+ +
+ ); +} +``` + +This approach eliminates loading states and removes the initial render's dependency on the flags API. + +### Next.js App Router example + +For Next.js applications using the App Router (Next.js 13+), you can pre-fetch flags in Server Components and pass them to client components: + +```typescript +// app/layout.tsx (Server Component) +import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; +import { ClientProviders } from "./providers"; + +async function getBootstrapData() { + const serverClient = new ReflagNodeClient({ + secretKey: process.env.REFLAG_SECRET_KEY! + }); + await serverClient.initialize(); + + // In a real app, you'd get user/company from your auth system + const bootstrapData = serverClient.getFlagsForBootstrap({ + user: { id: "user123", name: "John Doe", email: "john@acme.com" }, + company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, + other: { source: "web" } + }); + + return bootstrapData; +} + +export default async function RootLayout({ + children, +}: { + children: React.ReactNode; +}) { + const bootstrapData = await getBootstrapData(); + + return ( + + + + {children} + + + + ); +} +``` + +```typescript +// app/providers.tsx (Client Component) +"use client"; + +import { ReflagBootstrappedProvider, BootstrappedFlags } from "@reflag/react-sdk"; + +interface ClientProvidersProps { + children: React.ReactNode; + bootstrapData: BootstrappedFlags; +} + +export function ClientProviders({ children, bootstrapData }: ClientProvidersProps) { + return ( + + {children} + + ); +} +``` + +```typescript +// app/page.tsx (Server Component) +import { HuddleFeature } from "./huddle-feature"; + +export default function HomePage() { + return ( +
+

My App

+ +
+ ); +} +``` + +```typescript +// app/huddle-feature.tsx (Client Component) +"use client"; + +import { useFlag } from "@reflag/react-sdk"; + +export function HuddleFeature() { + const { isEnabled, track, config } = useFlag("huddle"); + + if (!isEnabled) return null; + + return ( +
+

Start a Huddle

+

Max participants: {config.payload?.maxParticipants ?? 10}

+

Video quality: {config.payload?.videoQuality ?? "standard"}

+ +
+ ); +} +``` + +This App Router approach leverages Server Components for server-side flag fetching while using Client Components only where React state and hooks are needed. + +## `` component + +The `` is a lower-level component that accepts a `ReflagClient` instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application. + +In most cases you should initialize the client before rendering this provider. If you pass an idle client and enable `suspense`, a `useFlag()` call that suspends can initialize the client on demand; without Suspense, you must initialize the client yourself. + +### Usage + +```tsx +import { ReflagClient } from "@reflag/browser-sdk"; +import { ReflagClientProvider } from "@reflag/react-sdk"; + +// Initialize the client yourself +const client = new ReflagClient({ + publishableKey: "your-publishable-key", + user: { id: "user123", name: "John Doe" }, + company: { id: "company456", name: "Acme Inc" }, + // ... other configuration options +}); + +// Initialize the client +await client.initialize(); + +function App() { + return ( + }> + + + ); +} +``` + +### Props + +The `ReflagClientProvider` accepts the following props: + +- `client`: A `ReflagClient` instance. Prefer passing an already-initialized client; idle clients are initialized on demand only by suspense-enabled `useFlag()` calls. +- `loadingComponent`: Optional React component to show while the client is initializing (same as `ReflagProvider`) +- `suspense`: Optional. Set to `true` to make `useFlag()` suspend while the client is loading + +> [!Note] +> Most applications should use `ReflagProvider` or `ReflagBootstrappedProvider` instead of `ReflagClientProvider`. Only use this component when you need the advanced control it provides. + +## `` component + +The `` initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props: + +- `publishableKey` is used to connect the provider to an _environment_ on Reflag. Find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag, +- `context` (recommended): An object containing `user`, `company`, and `other` properties that make up the evaluation context used to determine if a flag is enabled or not. `company` and `user` contexts are automatically transmitted to Reflag servers so the Reflag app can show you which companies have access to which flags etc. +- `company`, `user` and `other` (deprecated): Individual props for context. These are deprecated in favor of the `context` prop and will be removed in the next major version. + > [!Note] + > If you specify `company` and/or `user` they must have at least the `id` property, otherwise they will be ignored in their entirety. You should also supply anything additional you want to be able to evaluate flag targeting against, +- `fallbackFlags`: A list of strings which specify which flags to consider enabled if the SDK is unable to fetch flags. Can be provided in two formats: + + ```ts + // Simple array of flag keys + fallbackFlags={["flag1", "flag2"]} + + // Or with configuration overrides + fallbackFlags: { + "flag1": true, // just enable the flag + "flag2": { // enable with configuration + key: "variant-a", + payload: { + limit: 100, + mode: "test" + } + } + } + ``` + +- `timeoutMs`: Timeout in milliseconds when fetching flags from the server. +- `staleWhileRevalidate`: If set to `true`, stale flags will be returned while refetching flags in the background. +- `expireTimeMs`: If set, flags will be cached between page loads for this duration (in milliseconds). +- `staleTimeMs`: Maximum time (in milliseconds) that stale flags will be returned if `staleWhileRevalidate` is true and new flags cannot be fetched. +- `offline`: Provide this option when testing or in local development environments to avoid contacting Reflag servers. +- `loadingComponent` lets you specify an React component to be rendered instead of the children while the Reflag provider is initializing. If you want more control over loading screens, `useFlag()` and `useIsLoading` returns `isLoading` which you can use to customize the loading experience. +- `suspense`: Set to `true` to make `useFlag()` suspend while the provider is loading and `useOptInFlags()` suspend while required opt-in metadata is loading. Wrap components that call these hooks in React `` boundaries and omit `loadingComponent` if you want Suspense fallbacks to control loading UI. +- `enableTracking`: Set to `false` to stop sending tracking events and user/company updates to Reflag. Useful when you're impersonating a user (defaults to `true`), +- `enableLiveFlagUpdates`: Enables live flag updates over SSE. Defaults to `true` in the React SDK. +- `apiBaseUrl`: Optional base URL for the Reflag API. This also controls the SSE origin used for live flag updates and automated feedback, +- `credentials`: Optional fetch credentials mode. Set to `"include"` when proxying through your backend and authenticating with cookies; this also enables credentials for live-update SSE connections. +- `appBaseUrl`: Optional base URL for the Reflag application. Use this to override the default app URL, + +- `logger`: Optional custom logger implementation (`debug`, `info`, `warn`, `error`) used by the underlying client, +- `debug`: Set to `true` to enable debug logging to the console. If both `logger` and `debug` are provided, `logger` takes precedence, +- `toolbar`: Optional [configuration](../browser-sdk/globals.md#toolbaroptions) for the Reflag toolbar, +- `feedback`: Optional configuration for feedback collection + +## `` component + +The `` is a specialized version of the `ReflagProvider` that uses pre-fetched flag data for the initial render. This is ideal for server-side rendering scenarios. + +The component accepts the following props: + +- `flags`: Pre-fetched bootstrapped state of type `BootstrappedFlags` obtained from the Node SDK's `getFlagsForBootstrap()` method. This contains the context (`flags.context`), the evaluated flags (`flags.flags`), and an optional `flags.flagStateVersion`. +- All other props available in [`ReflagProvider`](#reflagprovider-component) are supported except `context`, `user`, `company`, and `other` (which are extracted from `flags.context`). + +**Example:** + +```tsx +import { + ReflagBootstrappedProvider, + BootstrappedFlags, +} from "@reflag/react-sdk"; + +interface AppProps { + bootstrapData: BootstrappedFlags; +} + +function App({ bootstrapData }: AppProps) { + return ( + } + debug={process.env.NODE_ENV === "development"} + > + + + ); +} +``` + +> [!Note] +> When using `ReflagBootstrappedProvider`, pass the entire object returned by `getFlagsForBootstrap()` directly as the `flags` prop. The context is extracted from `flags.context`, and `flags.flagStateVersion` is used when present. +> +> With `ReflagBootstrappedProvider`, `useOptInFlags()` requests a flags refresh on first use. It returns `isLoading: true` (or suspends) until that refresh settles. +> +> If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. +> +> After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. +> +> Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. + +## Hooks + +### `useFlag()` + +Returns the state of a given flag for the current context. The hook provides type-safe access to flags and their configurations. + +```tsx +import { useFlag } from "@reflag/react-sdk"; +import { Loading } from "./Loading"; + +function StartHuddleButton() { + const { + isLoading, // true while flags are being loaded + isEnabled, // boolean indicating if the flag is enabled + config: { + // flag configuration + key, // string identifier for the config variant + payload, // type-safe configuration object + }, + track, // function to track flag usage + requestFeedback, // function to request feedback for this flag + } = useFlag("huddle"); + + if (isLoading) { + return ; + } + + if (!isEnabled) { + return null; + } + + return ( + <> + + + + ); +} +``` + +#### Suspense loading + +Enable `suspense` on the provider to have `useFlag()` throw a promise while `isLoading` is true. The nearest `` boundary will render its fallback until flags are ready. + +```tsx +import { Suspense } from "react"; +import { ReflagProvider } from "@reflag/react-sdk"; + + + }> + + +; +``` + +You can also opt in for a single call with `useFlag("huddle", { suspense: true })`, or opt out inside a suspense-enabled provider with `{ suspense: false }`. + +### `useOptInFlags()` and `useSetOptIn()` + +Use these hooks to build an end-user opt-in UI for flags where opt-in is enabled in Reflag. + +```tsx +import { + type OptInFlag, + useIsLoading, + useOptInFlags, + useSetOptIn, +} from "@reflag/react-sdk"; + +function OptInList() { + const isProviderLoading = useIsLoading(); + const { flags, isLoading } = useOptInFlags(); + const setOptIn = useSetOptIn(); + + async function toggleOptIn(flag: OptInFlag) { + try { + const response = await setOptIn(flag.key, { + optedIn: !flag.userOptedIn, + }); + if (!response?.ok) { + console.error("Could not update opt-in"); + } + } catch (error) { + console.error("Could not update opt-in", error); + } + } + + if (isProviderLoading || isLoading) { + return

Loading…

; + } + + return flags.map((flag) => ( + + )); +} +``` + +By default, `useSetOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. + +User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. + +`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and subscribers have been notified when flags change. React may not have committed the resulting render yet. + +The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. + +`useOptInFlags()` returns `{ flags, isLoading }`. With `ReflagBootstrappedProvider`, it fetches opt-in metadata on first use and reports `isLoading: true` until that refresh succeeds or fails. + +If fetching opt-in metadata fails, loading ends without exposing an error. Call `client.refresh()` on the client returned by `useClient()` to retry. + +With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal initial flags request, so `useOptInFlags().isLoading` remains `false`. Use the general `useIsLoading()` hook or the provider's `loadingComponent` for that initial loading state. + +`useOptInFlags()` also supports Suspense. It respects the provider-level `suspense` option, or you can enable it for only this hook with `useOptInFlags({ suspense: true })`. While required opt-in metadata is loading, the nearest `` boundary renders its fallback: + +```tsx +import { Suspense } from "react"; + + + }> + + +; +``` + +Opt-in metadata Suspense is primarily relevant with `ReflagBootstrappedProvider`. Use `useOptInFlags({ suspense: false })` to opt out for one call when Suspense is enabled on the provider. + +### `useTrack()` + +`useTrack()` lets you send custom events to Reflag. Use this whenever a user _uses_ a feature. These events can be used to analyze feature usage in Reflag. + +```tsx +import { useTrack } from "@reflag/react-sdk"; + +function StartHuddle() { + const { track } = useTrack(); +
+ +
; +} +``` + +### `useRequestFeedback()` + +`useRequestFeedback()` returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features as part of roll out. See [Automated Feedback Surveys](https://docs.reflag.com/product-handbook/live-satisfaction) for how to do this automatically, without code. + +When using the `useRequestFeedback` you must pass the flag key to `requestFeedback`. +The example below shows how to use `position` to ensure the popover appears next to the "Give feedback!" button. + +```tsx +import { useRequestFeedback } from "@reflag/react-sdk"; + +function FeedbackButton() { + const requestFeedback = useRequestFeedback(); + return ( + + ); +} +``` + +See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/FEEDBACK.md#manual-feedback-collection) for more information on `requestFeedback` options. + +### `useSendFeedback()` + +Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag. + +```tsx +import { useSendFeedback } from "@reflag/react-sdk"; + +function CustomFeedbackForm() { + const sendFeedback = useSendFeedback(); + + const handleSubmit = async (data: FormData) => { + await sendFeedback({ + flagKey: "reflag-flag-key", + score: parseInt(data.get("score") as string), + comment: data.get("comment") as string, + }); + }; + + return
...
; +} +``` + +### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` + +These hooks return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session. + +```tsx +import { + useUpdateUser, + useUpdateCompany, + useUpdateOtherContext, +} from "@reflag/react-sdk"; + +function FlagOptIn() { + const updateUser = useUpdateUser(); + const updateCompany = useUpdateCompany(); + const updateOtherContext = useUpdateOtherContext(); + + const handleUserUpdate = async () => { + await updateUser({ + role: "admin", + betaFlags: "enabled", + }); + }; + + const handleCompanyUpdate = async () => { + await updateCompany({ + plan: "enterprise", + employees: 500, + }); + }; + + const handleContextUpdate = async () => { + await updateOtherContext({ + currentWorkspace: "workspace-123", + theme: "dark", + }); + }; + + return ( +
+ + + +
+ ); +} +``` + +### `useClient()` + +Returns the `ReflagClient` used by the `ReflagProvider`. The client offers more functionality that +is not directly accessible thorough the other hooks. + +```tsx +import { useClient } from "@reflag/react-sdk"; + +function LoggingWrapper({ children }: { children: ReactNode }) { + const client = useClient(); + + console.log(client.getContext()); + + return children; +} +``` + +### `useIsLoading()` + +Returns the loading state of the flags in the `ReflagClient`. +Initially, the value will be `true` if no bootstrap flags have been provided and the client has not be initialized. + +```tsx +import { useIsLoading } from "@reflag/react-sdk"; +import { Spinner } from "./Spinner"; + +function LoadingWrapper({ children }: { children: ReactNode }) { + const isLoading = useIsLoading(); + + if (isLoading) { + return ; + } + + return children; +} +``` + +### `useOnEvent()` + +Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount. + +```tsx +import { useOnEvent } from "@reflag/react-sdk"; + +function LoggingWrapper({ children }: { children: ReactNode }) { + useOnEvent("flagsUpdated", (newFlags) => { + console.log(newFlags); + }); + + return children; +} +``` + +## Migrating from Bucket SDK + +If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: + +- `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) +- `Feature*` classes, and types have been renamed to `Flag*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) +- When using strongly-typed flags, the new `Flags` interface replaced `Features` interface +- All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) +- The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags` +- `featureKey` has been renamed to `flagKey` in all methods that accepts that argument +- The SDKs will not emit `evaluate` and `evaluate-config` events anymore +- The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead of `bucket-*` +- The `featuresUpdated` hook has been renamed to `flagsUpdated` +- The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on + +To ease in transition to Reflag SDK, some of the old methods have been preserved as aliases to the new methods: + +- `getFeature` method is an alias for `getFlag` +- `getFeatures` method is an alias for `getFlags` +- `useFeature` method is an alias for `useFlag` +- `featuresUpdated` hook is an alias for `flagsUpdated` + +If you are running with strict Content Security Policies active on your website, you will need change them as follows: + +- `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com` + +## Content Security Policy (CSP) + +See [CSP](https://github.com/reflagcom/javascript/blob/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/README.md#content-security-policy-csp) for info on using Reflag React SDK with CSP + +## License + +MIT License + +Copyright (c) 2025 Bucket ApS diff --git a/legacy/v1/react-sdk/globals.md b/legacy/v1/react-sdk/globals.md new file mode 100644 index 0000000..fd3fe4c --- /dev/null +++ b/legacy/v1/react-sdk/globals.md @@ -0,0 +1,2326 @@ +--- +layout: + visible: true +title: + visible: true +description: + visible: false +tableOfContents: + visible: true +outline: + visible: true +pagination: + visible: true +--- + +{% hint style="info" %} +**Protocol v1 — legacy.** [Current v2 documentation](../../../supported-languages/react-sdk/globals.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) + +Generated from [`@reflag/react-sdk@1.7.4`](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/react-sdk); SDK READMEs and code comments remain the source of truth. +{% endhint %} + +# @reflag/react-sdk + +## Interfaces + +### CheckEvent + +Event representing checking the flag evaluation result + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `action` + + + +`"check-is-enabled"` \| `"check-config"` + + + +`check-is-enabled` means `isEnabled` was checked, `check-config` means `config` was checked. + +
+ + `evaluationErrors?` + + + +\{ `code`: `string`; `field`: `string`; `message`: `string`; `operator`: `string`; \}[] + + + +Non-fatal diagnostics produced while evaluating the flag. + +
+ + `key` + + + +`string` + + + +Flag key. + +
+ + ~~`missingContextFields?`~~ + + + +`string`[] + + + +Missing context fields. + +**Deprecated** + +Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. + +
+ + `ruleEvaluationResults?` + + + +`boolean`[] + + + +Rule evaluation results. + +
+ + `value?` + + + + \| `boolean` \| \{ `key`: `string`; `payload`: `any`; \} + + + +Result of flag or configuration evaluation. +If `action` is `check-is-enabled`, this is the result of the flag evaluation and `value` is a boolean. +If `action` is `check-config`, this is the result of the configuration evaluation. + +
+ + `version?` + + + +`number` + + + +Version of targeting rules. + +
+ +*** + +### CompanyContext + +Context is a set of key-value pairs. +This is used to determine if feature targeting matches and to track events. +Id should always be present so that it can be referenced to an existing company. + +#### Indexable + +```ts +[key: string]: ContextValue +``` + +#### Properties + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `id` + + + +`undefined` \| `string` \| `number` + + + +Company id + +
+ + `name?` + + + +`string` + + + +Company name + +
+ +*** + +### Flag\ + +Describes a feature + +#### Type Parameters + + + + + + + + + + + + + + +
Type ParameterDefault type
+ +`TConfig` *extends* [`FlagType`](globals.md#flagtype)\[`"config"`\] + + + +[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) + +
+ +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `config` + + + + \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| \{ `key`: `string`; \} & `TConfig` + + + +‐ + +
+ + `isEnabled` + + + +`boolean` + + + +If the feature is enabled. + +
+ + `isLoading` + + + +`boolean` + + + +If the feature is loading. + +
+ + `key` + + + +`string` + + + +The key of the feature. + +
+ + `requestFeedback` + + + +(`opts`: [`RequestFeedbackOptions`](globals.md#requestfeedbackoptions)) => `void` + + + +Request feedback from the user. + +
+ +#### Methods + +##### track() + +```ts +track(): + | undefined + | Promise< + | undefined +| Response> +``` + +Track feature usage in Reflag. + +###### Returns + + \| `undefined` + \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +*** + +### Flags + +*** + +### UserContext + +Context is a set of key-value pairs. +This is used to determine if feature targeting matches and to track events. +Id should always be present so that it can be referenced to an existing user. + +#### Indexable + +```ts +[key: string]: ContextValue +``` + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `email?` + + + +`string` + + + +User email + +
+ + `id` + + + +`undefined` \| `string` \| `number` + + + +User id + +
+ + `name?` + + + +`string` + + + +User name + +
+ +## Type Aliases + +### BootstrappedFlags + +```ts +type BootstrappedFlags = BootstrappedState & { + flags: RawFlags; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + +
NameType
+ +`flags` + + + +[`RawFlags`](../browser-sdk/globals.md#rawflags) + +
+ +*** + +### EmptyFlagRemoteConfig + +```ts +type EmptyFlagRemoteConfig = { + key: undefined; + payload: undefined; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `key` + + + +`undefined` + +
+ + `payload` + + + +`undefined` + +
+ +*** + +### FlagKey + +```ts +type FlagKey = keyof TypedFlags; +``` + +*** + +### FlagRemoteConfig + +```ts +type FlagRemoteConfig = + | { + key: string; + payload: any; + } + | EmptyFlagRemoteConfig; +``` + +A remotely managed configuration value for a feature. + +#### Type declaration + +\{ + `key`: `string`; + `payload`: `any`; + \} + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`key` + + + +`string` + + + +The key of the matched configuration value. + +
+ +`payload` + + + +`any` + + + +The optional user-supplied payload data. + +
+ +[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) + +*** + +### FlagType + +```ts +type FlagType = { + config: { + payload: any; + }; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `config`? + + + +\{ + `payload`: `any`; + \} + +
+ +`config.payload` + + + +`any` + +
+ +*** + +### OptInFlag + +```ts +type OptInFlag = Omit & { + key: FlagKey; +}; +``` + +An opt-in-enabled flag for the generated React SDK flag definitions. + +Includes all fields from [BrowserOptInFlag](../browser-sdk/globals.md#optinflag): `name`, `description`, +`isEnabled`, `userOptedIn`, `companyOptedIn`, and `isOptedIn`. +Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. + +#### Type declaration + + + + + + + + + + + + + + +
NameType
+ +`key` + + + +[`FlagKey`](globals.md#flagkey) + +
+ +*** + +### RawFlags + +```ts +type RawFlags = Record; +``` + +Describes a collection of evaluated raw flags. + +*** + +### ReflagBootstrappedProps + +```ts +type ReflagBootstrappedProps = ReflagPropsBase & ReflagInitOptionsBase & { + flags: BootstrappedFlags; +}; +``` + +Props for the ReflagBootstrappedProvider. + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`flags` + + + +[`BootstrappedFlags`](globals.md#bootstrappedflags) + + + +Pre-fetched flags used for the initial render. The browser client fetches opt-in +metadata on demand when opt-in flags are requested. + +
+ +*** + +### ReflagClientProviderProps + +```ts +type ReflagClientProviderProps = Omit & { + client: ReflagClient; +}; +``` + +Props for the ReflagClientProvider. + +#### Type declaration + + + + + + + + + + + + + + +
NameType
+ +`client` + + + +[`ReflagClient`](../browser-sdk/globals.md#reflagclient) + +
+ +*** + +### ReflagInitOptionsBase + +```ts +type ReflagInitOptionsBase = Omit; +``` + +**`Internal`** + +Base init options for the ReflagProvider and ReflagBootstrappedProvider. + +*** + +### ReflagProps + +```ts +type ReflagProps = ReflagPropsBase & ReflagInitOptionsBase & { + company: CompanyContext; + context: ReflagContext; + otherContext: Record; + user: UserContext; +}; +``` + +Props for the ReflagProvider. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`company`? + + + +[`CompanyContext`](globals.md#companycontext) + + + +Company related context. If you provide `id` Reflag will enrich the evaluation context with +company attributes on Reflag servers. + +**Deprecated** + +Use `context` instead, this property will be removed in the next major version + +
+ +`context`? + + + +[`ReflagContext`](../browser-sdk/globals.md#reflagcontext) + + + +The context to use for the ReflagClient containing user, company, and other context. + +
+ +`otherContext`? + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `string` \| `number` \| `undefined`\> + + + +Context which is not related to a user or a company. + +**Deprecated** + +Use `context` instead, this property will be removed in the next major version + +
+ +`user`? + + + +[`UserContext`](globals.md#usercontext) + + + +User related context. If you provide `id` Reflag will enrich the evaluation context with +user attributes on Reflag servers. + +**Deprecated** + +Use `context` instead, this property will be removed in the next major version + +
+ +*** + +### ReflagPropsBase + +```ts +type ReflagPropsBase = { + children: ReactNode; + debug: boolean; + initialLoading: boolean; + loadingComponent: ReactNode; + logger: Logger; + suspense: boolean; +}; +``` + +**`Internal`** + +Base props for the ReflagProvider and ReflagBootstrappedProvider. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `children`? + + + +`ReactNode` + + + +The children to render after the client is initialized. + +
+ + `debug`? + + + +`boolean` + + + +Set to `true` to enable debug logging to the console, + +
+ + `initialLoading`? + + + +`boolean` + + + +Set to `true` to show the loading component while the client is initializing. + +
+ + `loadingComponent`? + + + +`ReactNode` + + + +A React component to show while the client is initializing. + +
+ + `logger`? + + + +[`Logger`](../browser-sdk/globals.md#logger) + + + +A custom logger to use for SDK logs. +Use this for advanced control or filtering of SDK logs. +If both `logger` and `debug` are provided, `logger` takes precedence. + +
+ + `suspense`? + + + +`boolean` + + + +Set to `true` to make `useFlag` and `useOptInFlags` suspend while their +required flag data is loading. Components that call either hook must be +wrapped in a React `` boundary. + +
+ +*** + +### RequestFeedbackOptions + +```ts +type RequestFeedbackOptions = Omit; +``` + +*** + +### SetOptInOptions + +```ts +type SetOptInOptions = { + optedIn: boolean; + scope?: "user" | "company"; +}; +``` + +Options for changing the current user or company's opt-in membership. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `optedIn` + + + +`boolean` + + + +Whether the scoped subject has opted in. + +
+ + `scope`? + + + +`"user"` \| `"company"` + + + +Whether to update the current user or current company. Defaults to `user`. + +
+ +*** + +### StorageAdapter + +```ts +type StorageAdapter = { + getItem: Promise; + removeItem: Promise; + setItem: Promise; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `getItem()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`null` \| `string`\> + +
+ + `removeItem()`? + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +
+ + `setItem()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +
+ +*** + +### TrackEvent + +```ts +type TrackEvent = { + attributes: | Record + | null; + company: CompanyContext; + eventName: string; + user: UserContext; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `attributes`? + + + + \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + \| `null` + +
+ + `company`? + + + +[`CompanyContext`](globals.md#companycontext) + +
+ + `eventName` + + + +`string` + +
+ + `user` + + + +[`UserContext`](globals.md#usercontext) + +
+ +*** + +### TypedFlags + +```ts +type TypedFlags = keyof Flags extends never ? Record : { [TypedFlagKey in keyof Flags]: Flags[TypedFlagKey] extends FlagType ? Flag : Flag }; +``` + +Describes a collection of evaluated feature. + +#### Remarks + +This types falls back to a generic Record if the Flags interface +has not been extended. + +*** + +### UseFlagOptions + +```ts +type UseFlagOptions = { + suspense: boolean; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `suspense`? + + + +`boolean` + + + +Override the provider suspense setting for this `useFlag` call. +When true, `useFlag` throws a promise while flags are loading. + +
+ +*** + +### UseOptInFlagsOptions + +```ts +type UseOptInFlagsOptions = { + suspense?: boolean; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `suspense`? + + + +`boolean` + + + +Override the provider suspense setting for this `useOptInFlags` call. +When true, `useOptInFlags` throws a promise while opt-in flags are loading. + +
+ +*** + +### UseOptInFlagsResult + +```ts +type UseOptInFlagsResult = { + flags: OptInFlag[]; + isLoading: boolean; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `flags` + + + +[`OptInFlag`](globals.md#optinflag)[] + + + +Opt-in-enabled flags for the current context. + +
+ + `isLoading` + + + +`boolean` + + + +Whether a bootstrapped provider is fetching opt-in metadata. + +
+ +## Functions + +### ReflagBootstrappedProvider() + +```ts +function ReflagBootstrappedProvider(__namedParameters: ReflagBootstrappedProps): Element +``` + +Bootstrapped Provider for the ReflagClient using pre-fetched flags. + +#### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`__namedParameters` + + + +[`ReflagBootstrappedProps`](globals.md#reflagbootstrappedprops) + +
+ +#### Returns + +`Element` + +*** + +### ReflagClientProvider() + +```ts +function ReflagClientProvider(__namedParameters: ReflagClientProviderProps): Element +``` + +#### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`__namedParameters` + + + +[`ReflagClientProviderProps`](globals.md#reflagclientproviderprops) + +
+ +#### Returns + +`Element` + +*** + +### ReflagProvider() + +```ts +function ReflagProvider(__namedParameters: ReflagProps): Element +``` + +Provider for the ReflagClient. + +#### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`__namedParameters` + + + +[`ReflagProps`](globals.md#reflagprops) + +
+ +#### Returns + +`Element` + +*** + +### useClient() + +```ts +function useClient(): ReflagClient +``` + +Returns the current `ReflagClient` used by the `ReflagProvider`. + +This is useful if you need to access the `ReflagClient` outside of the `ReflagProvider`. + +#### Returns + +[`ReflagClient`](../browser-sdk/globals.md#reflagclient) + +The `ReflagClient`. + +#### Example + +```ts +import { useClient } from '@reflag/react-sdk'; + +function App() { + const client = useClient(); + console.log(client.getContext()); +} +``` + +*** + +### ~~useFeature()~~ + +```ts +function useFeature(key: TKey, options?: UseFlagOptions): Flag +``` + +#### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`TKey` *extends* `string` + +
+ +#### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`TKey` + +
+ +`options`? + + + +[`UseFlagOptions`](globals.md#useflagoptions) + +
+ +#### Returns + +[`Flag`](globals.md#flagtconfig) + +#### Deprecated + +use `useFlag` instead + +*** + +### useFlag() + +```ts +function useFlag(key: TKey, options: UseFlagOptions): TypedFlags[TKey] +``` + +Returns the state of a given feature for the current context, e.g. + +```ts +function HuddleButton() { + const {isEnabled, config: { payload }, track} = useFlag("huddle"); + if (isEnabled) { + return ; +} +``` + +#### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`TKey` *extends* `string` + +
+ +#### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`TKey` + +
+ +`options` + + + +[`UseFlagOptions`](globals.md#useflagoptions) + +
+ +#### Returns + +[`TypedFlags`](globals.md#typedflags)\[`TKey`\] + +*** + +### useIsLoading() + +```ts +function useIsLoading(): boolean +``` + +Returns a boolean indicating if the Reflag client is loading. +You can use this to check if the Reflag client is loading at any point in your application. +Initially, the value will be true until the client is initialized. + +#### Returns + +`boolean` + +A boolean indicating if the Reflag client is loading. + +#### Example + +```ts +import { useIsLoading } from '@reflag/react-sdk'; + +const isLoading = useIsLoading(); + +console.log(isLoading); +``` + +*** + +### useOnEvent() + +```ts +function useOnEvent( + event: THookType, + handler: (arg0: HookArgs[THookType]) => void, + client?: ReflagClient): void +``` + +Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount. + +#### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`THookType` *extends* keyof [`HookArgs`](../browser-sdk/globals.md#hookargs) + +
+ +#### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`event` + + + +`THookType` + + + +The event to listen to. + +
+ +`handler` + + + +(`arg0`: [`HookArgs`](../browser-sdk/globals.md#hookargs)\[`THookType`\]) => `void` + + + +The function to call when the event is triggered. + +
+ +`client`? + + + +[`ReflagClient`](../browser-sdk/globals.md#reflagclient) + + + +The Reflag client to listen to. If not provided, the client will be retrieved from the context. + +
+ +#### Returns + +`void` + +#### Example + +```ts +import { useOnEvent } from '@reflag/react-sdk'; + +useOnEvent("flagsUpdated", () => { + console.log("flags updated"); +}); +``` + +*** + +### useOptInFlags() + +```ts +function useOptInFlags(options?: UseOptInFlagsOptions): UseOptInFlagsResult +``` + +Returns opt-in-enabled flags and their loading state for the current context. + +The loading state is only used with `ReflagBootstrappedProvider` while +opt-in metadata is fetched on demand. Regular providers load opt-in metadata +with the initial flags; use [useIsLoading](globals.md#useisloading) for their loading state. +When suspense is enabled for the provider or this hook, it suspends instead +of returning a loading result. A Suspense boundary alone does not enable it. + +If fetching opt-in metadata fails, loading ends without exposing an error. +Call `refresh()` on the client returned by [useClient](globals.md#useclient) to retry. + +#### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`options`? + + + +[`UseOptInFlagsOptions`](globals.md#useoptinflagsoptions) + +
+ +#### Returns + +[`UseOptInFlagsResult`](globals.md#useoptinflagsresult) + +*** + +### useRequestFeedback() + +```ts +function useRequestFeedback(): (options: RequestFeedbackData) => void +``` + +Returns a function to open up the feedback form +Note: When calling `useRequestFeedback`, user/company must already be set. + +See [link](../browser-sdk/feedback.md) for more information + +```ts +const requestFeedback = useRequestFeedback(); +reflag.requestFeedback({ + flagKey: "file-uploads", + title: "How satisfied are you with file uploads?", +}); +``` + +#### Returns + +`Function` + +##### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`options` + + + +[`RequestFeedbackData`](../browser-sdk/globals.md#requestfeedbackdata) + +
+ +##### Returns + +`void` + +*** + +### useSendFeedback() + +```ts +function useSendFeedback(): (opts: UnassignedFeedback) => Promise< + | undefined +| Response> +``` + +Returns a function to manually send feedback collected from a user. +Note: When calling `useSendFeedback`, user/company must already be set. + +See [link](../browser-sdk/feedback.md) for more information + +```ts +const sendFeedback = useSendFeedback(); +sendFeedback({ + flagKey: "huddle"; + question: "How did you like the new huddle feature?"; + score: 5; + comment: "I loved it!"; +}); +``` + +#### Returns + +`Function` + +##### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +[`UnassignedFeedback`](../browser-sdk/globals.md#unassignedfeedback) + +
+ +##### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +*** + +### useSetOptIn() + +```ts +function useSetOptIn(): (key: string, options: SetOptInOptions) => Promise< + | undefined +| Response> +``` + +Returns a function to set whether the current user or company has opted into a flag. + +Check the returned Response's `ok` property and catch promise rejections. +HTTP failures return a non-OK Response; offline mode, invalid arguments, or +missing scoped context return undefined. Confirmation failures can reject +after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sdk/globals.md#setoptin). + +#### Returns + +`Function` + +##### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`options` + + + +[`SetOptInOptions`](globals.md#setoptinoptions) + +
+ +##### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +*** + +### useTrack() + +```ts +function useTrack(): (eventName: string, attributes?: + | null + | Record) => Promise< + | undefined +| Response> +``` + +Returns a function to send an event when a user performs an action +Note: When calling `useTrack`, user/company must already be set. + +```ts +const track = useTrack(); +track("Started Huddle", { button: "cta" }); +``` + +#### Returns + +`Function` + +##### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`eventName` + + + +`string` + +
+ +`attributes`? + + + + \| `null` \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + +
+ +##### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +*** + +### useUpdateCompany() + +```ts +function useUpdateCompany(): (opts: {}) => Promise +``` + +Returns a function to update the current company's information. +For example, if the company changed plan or opted into a beta-feature. + +The method returned is a function which returns a promise that +resolves when after the features have been updated as a result +of the company update. + +```ts +const updateCompany = useUpdateCompany(); +updateCompany({ plan: "enterprise" }).then(() => console.log("Flags updated")); +``` + +#### Returns + +`Function` + +##### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +\{\} + +
+ +##### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +*** + +### useUpdateOtherContext() + +```ts +function useUpdateOtherContext(): (opts: {}) => Promise +``` + +Returns a function to update the "other" context information. +For example, if the user changed workspace, you can set the workspace id here. + +The method returned is a function which returns a promise that +resolves when after the features have been updated as a result +of the update to the "other" context. + +```ts +const updateOtherContext = useUpdateOtherContext(); +updateOtherContext({ workspaceId: newWorkspaceId }) + .then(() => console.log("Flags updated")); +``` + +#### Returns + +`Function` + +##### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +\{\} + +
+ +##### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +*** + +### useUpdateUser() + +```ts +function useUpdateUser(): (opts: {}) => Promise +``` + +Returns a function to update the current user's information. +For example, if the user changed role or opted into a beta-feature. + +The method returned is a function which returns a promise that +resolves when after the features have been updated as a result +of the user update. + +```ts +const updateUser = useUpdateUser(); +updateUser({ optInHuddles: "true" }).then(() => console.log("Flags updated")); +``` + +#### Returns + +`Function` + +##### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +\{\} + +
+ +##### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> diff --git a/legacy/v1/vue-sdk/README.md b/legacy/v1/vue-sdk/README.md new file mode 100644 index 0000000..54aad04 --- /dev/null +++ b/legacy/v1/vue-sdk/README.md @@ -0,0 +1,712 @@ +--- +layout: + visible: true +title: + visible: true +description: + visible: false +tableOfContents: + visible: true +outline: + visible: true +pagination: + visible: true +--- + +{% hint style="info" %} +**Protocol v1 — legacy.** [Current v2 documentation](../../../supported-languages/vue-sdk/README.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) + +Generated from [`@reflag/vue-sdk@1.5.7`](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/vue-sdk); SDK READMEs and code comments remain the source of truth. +{% endhint %} + +# Reflag Vue SDK + +Vue client side library for [Reflag.com](https://reflag.com) + +Reflag supports flag toggling, tracking flag usage, requesting feedback on features and remotely configuring flags. + +The Reflag Vue SDK comes with the same built-in toolbar as the browser SDK which appears on `localhost` by default. + +## Install + +Install via npm: + +```shell +npm i @reflag/vue-sdk@1 +``` + +## Migrating from Bucket SDK + +If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: + +- `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) +- `Feature*` classes, and types have been renamed to `Feature*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) +- All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) +- The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags` +- `featureKey` has been renamed to `flagKey` in all methods that accepts that argument +- The SDKs will not emit `evaluate` and `evaluate-config` events anymore +- The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead og `bucket-*` +- The `featuresUpdated` hook has been renamed to `flagsUpdated` +- The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on + +To ease in transition to Reflag SDK, some of the old methods have been preserved as aliases to the new methods: + +- `getFeature` method is an alias for `getFlag` +- `getFeatures` method is an alias for `getFlags` +- `featuresUpdated` hook is an alias for `flagsUpdated` + +If you are running with strict Content Security Policies active on your website, you will need change them as follows: + +- `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com` + +Finally, if you have customized the look & feel of the Feedback component, update `--bucket-feedback-*` CSS classes to `--reflag-feedback-*` + +## Get started + +### 1. Add the `ReflagProvider` context provider + +Add the `ReflagProvider` context provider to your application: + +**Example:** + +```vue + + + + + +``` + +If using Nuxt, wrap `` in ``. `` only renders client-side currently. + +### 2. Use `useFlag get flag status + +```vue + + + +``` + +See [useFlag()](#useflag) for a full example + +## Setting context + +Reflag determines which flags are active for a given `user`, `company`, or `other` context. +You can pass these to the `ReflagProvider` using the `context` prop. + +### Using the `context` prop + +```vue + + + +``` + +### Legacy individual props (deprecated) + +For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version: + +```vue + + + +``` + +> [!Important] +> The `user`, `company`, and `otherContext` props are deprecated. Use the `context` prop instead, which provides the same functionality in a more structured way. + +### Context requirements + +If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. +In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. +Attributes which are not properties of the `user` or `company` can be supplied using the `other` property. + +Attributes cannot be nested (multiple levels) and must be either strings, numbers or booleans. +A number of special attributes exist: + +- `name` -- display name for `user`/`company`, +- `email` -- the email of the user, +- `avatar` -- the URL for `user`/`company` avatar image. + +To retrieve flags along with their targeting information, use `useFlag(key: string)` hook (described in a section below). + +Note that accessing `isEnabled` on the object returned by `useFlag()` automatically +generates a `check` event. + +## Remote config + +Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. + +Similar to `isEnabled`, each flag accessed using the `useFlag()` hook, has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the +binary `isEnabled` you can have multiple configuration values which are given to different user/companies. + +### Get started with Remote config + +```ts +const { + isEnabled, + config: { key, payload }, +} = useFlag("huddles"); + +// isEnabled: true, +// key: "gpt-3.5", +// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } +``` + +`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. + +Note that, similar to `isEnabled`, accessing `config` on the object returned by `useFlag()` automatically +generates a `check` event. + +## `` component + +The `` initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props: + +- `publishableKey` is used to connect the provider to an _environment_ on Reflag. Find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag, +- `context`: An object containing `user`, `company`, and `other` properties that make up the evaluation context used to determine if a flag is enabled or not. `company` and `user` contexts are automatically transmitted to Reflag servers so the Reflag app can show you which companies have access to which flags etc. +- `company`, `user` and `otherContext` (deprecated): Individual props for context. These are deprecated in favor of the `context` prop and will be removed in the next major version. + + > [!Note] + > If you specify `company` and/or `user` they must have at least the `id` property, otherwise they will be ignored in their entirety. You should also supply anything additional you want to be able to evaluate flag targeting against, + +- `timeoutMs`: Timeout in milliseconds when fetching flags from the server, +- `staleWhileRevalidate`: If set to `true`, stale flags will be returned while refetching flags in the background, +- `expireTimeMs`: If set, flags will be cached between page loads for this duration (in milliseconds), +- `staleTimeMs`: Maximum time (in milliseconds) that stale flags will be returned if `staleWhileRevalidate` is true and new flags cannot be fetched. + +- `enableTracking`: Set to `false` to stop sending tracking events and user/company updates to Reflag. Useful when you're impersonating a user (defaults to `true`), +- `apiBaseUrl`: Optional base URL for the Reflag API. This also controls the SSE origin used for live flag updates and automated feedback, +- `credentials`: Optional fetch credentials mode. Set to `"include"` when proxying through your backend and authenticating with cookies; this also enables credentials for live-update SSE connections. +- `appBaseUrl`: Optional base URL for the Reflag application. Use this to override the default app URL, + +- `debug`: Set to `true` to enable debug logging to the console. If both `logger` and `debug` are provided, `logger` takes precedence, +- `logger`: Optional custom logger implementation (`debug`, `info`, `warn`, `error`) used by the underlying client, +- `toolbar`: Optional [configuration](../browser-sdk/globals.md#toolbaroptions) for the Reflag toolbar, +- `feedback`: Optional configuration for feedback collection + +### Loading states + +ReflagProvider lets you define a template to be shown while ReflagProvider is initializing: + +```vue + +``` + +If you want more control over loading screens, `useIsLoading()` returns a `Ref` which you can use to customize the loading experience. + +## `` component + +The `` component is a specialized version of `ReflagProvider` designed for server-side rendering and preloaded flag scenarios. It uses pre-fetched flags for the initial render, resulting in faster initial page loads and better SSR compatibility. + +### Usage + +```vue + + + +``` + +### Getting bootstrapped flags + +You'll typically generate the `bootstrappedFlags` object on your server using the Node.js SDK or by fetching from the Reflag API. Pass the full object returned by `getFlagsForBootstrap()` directly to ``. It contains: + +- `context`: the evaluation context used on the server +- `flags`: the evaluated raw flags +- `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping + +If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. + +With `ReflagBootstrappedProvider`, `useOptInFlags()` requests a flags refresh on first use. It reports `isLoading: true` until that refresh settles. + +Here's an example using the Node.js SDK: + +```js +// server.js (Node.js/SSR) +import { ReflagClient } from "@reflag/node-sdk"; + +const client = new ReflagClient({ + secretKey: "your-secret-key", // Use secret key on server +}); +await client.initialize(); + +// Fetch flags for specific context +const context = { + user: { id: "user123", name: "John Doe", email: "john@acme.com" }, + company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, +}; + +const bootstrappedFlags = client.getFlagsForBootstrap(context); + +// Pass to your Vue app +``` + +### ReflagBootstrappedProvider Props + +`ReflagBootstrappedProvider` accepts all the same props as `ReflagProvider` except: + +- `flags`: The pre-fetched bootstrapped state object containing `context`, evaluated `flags`, and an optional `flagStateVersion` +- All other props available in `ReflagProvider` are supported except `context`, `user`, `company`, and `otherContext` (which are extracted from `flags.context`) + +If the `flags` prop is not provided or is undefined, the provider will not initialize the client and will render in a non-loading state. + +{% hint style="info" %} +After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. + +Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. +{% endhint %} + +## `` component + +The `` is a lower-level component that accepts a pre-initialized `ReflagClient` instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application. + +### ReflagClientProvider Usage + +```vue + + + +``` + +### ReflagClientProvider Props + +The `ReflagClientProvider` accepts the following props: + +- `client`: A pre-initialized `ReflagClient` instance + +### Slots + +- `loading`: Optional slot to show while the client is initializing (same as `ReflagProvider`) + +> [!Note] +> Most applications should use `ReflagProvider` or `ReflagBootstrappedProvider` instead of `ReflagClientProvider`. Only use this component when you need the advanced control it provides. + +## Hooks + +### `useFlag()` + +Returns the state of a given flag for the current context. The composable provides access to flags and their configurations. + +`useFlag()` returns an object with this shape: + +```ts +{ + isEnabled: boolean, // is the flag enabled + track: () => void, // send a track event when the flag is used + requestFeedback: (...) => void // open up a feedback dialog + config: {key: string, payload: any}, // remote configuration for this flag + isLoading: boolean // if you want to manage loading state at the flag level +} +``` + +Example: + +```vue + + + +``` + +See the reference docs for details. + +### `useOptInFlags()` and `useSetOptIn()` + +Use these composables to build an end-user opt-in UI for flags where opt-in is enabled in Reflag. + +```vue + + + +``` + +By default, `useSetOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. + +User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. + +`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and subscribers have been notified when flags change. Vue may not have committed the resulting render yet. + +The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. + +`useOptInFlags()` returns `{ flags, isLoading }`, where both values are computed refs. With `ReflagBootstrappedProvider`, it fetches opt-in metadata on first use and reports `isLoading: true` until that refresh succeeds or fails. + +If fetching opt-in metadata fails, loading ends without exposing an error. Call `client.refresh()` on the client returned by `useClient()` to retry. + +With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal initial flags request, so `useOptInFlags().isLoading` remains `false`. Use the general `useIsLoading()` composable or the provider's loading slot for that initial loading state. + +### `useTrack()` + +`useTrack()` returns a function which lets you send custom events to Reflag. It takes a string argument with the event name and optionally an object with properties to attach the event. + +Using `track` returned from `useFlag()` calls this track function with the flag key as the event name. + +```vue + + + +``` + +### `useRequestFeedback()` + +Returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features. + +See [Automated Feedback Surveys](https://docs.reflag.com/product-handbook/live-satisfaction) for how to do this automatically, without code. + +When using the `useRequestFeedback` you must pass the flag key to `requestFeedback`. +The example below shows how to use `position` to ensure the popover appears next to the "Give feedback!" button. + +```vue + + + +``` + +See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/FEEDBACK.md#manual-feedback-collection) for more information on `requestFeedback` options. + +### `useSendFeedback()` + +Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag. + +```vue + + + +``` + +### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` + +These composables return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session. + +```vue + + + +``` + +Note: To change the `user.id` or `company.id`, you need to update the props passed to `ReflagProvider` instead of using these composables. + +### `useClient()` + +Returns the `ReflagClient` used by the `ReflagProvider`. The client offers more functionality that +is not directly accessible through the other composables. + +```vue + + + +``` + +### `useIsLoading()` + +Returns a `Ref` to indicate if Reflag has finished loading. +Initially, the value will be `true` if no bootstrap flags have been provided and the client has not be initialized. + +```vue + + + +``` + +### `useOnEvent()` + +Vue composable for listening to Reflag client events. This composable automatically handles mounting and unmounting of event listeners. + +Available events include: + +- `flagsUpdated`: Triggered when flags are updated +- `track`: Triggered when tracking events are sent +- `feedback`: Triggered when feedback is sent + +```vue + + + +``` + +You can also provide a specific client instance if needed: + +```vue + + + +``` + +## Content Security Policy (CSP) + +See [CSP](https://github.com/reflagcom/javascript/blob/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/README.md#content-security-policy-csp) for info on using Reflag React SDK with CSP + +## License + +MIT License + +Copyright (c) 2025 Bucket ApS diff --git a/legacy/v1/vue-sdk/globals.md b/legacy/v1/vue-sdk/globals.md new file mode 100644 index 0000000..268f896 --- /dev/null +++ b/legacy/v1/vue-sdk/globals.md @@ -0,0 +1,1899 @@ +--- +layout: + visible: true +title: + visible: true +description: + visible: false +tableOfContents: + visible: true +outline: + visible: true +pagination: + visible: true +--- + +{% hint style="info" %} +**Protocol v1 — legacy.** [Current v2 documentation](../../../supported-languages/vue-sdk/globals.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) + +Generated from [`@reflag/vue-sdk@1.5.7`](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/vue-sdk); SDK READMEs and code comments remain the source of truth. +{% endhint %} + +# @reflag/vue-sdk + +## Interfaces + +### CheckEvent + +Event representing checking the flag evaluation result + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `action` + + + +`"check-is-enabled"` \| `"check-config"` + + + +`check-is-enabled` means `isEnabled` was checked, `check-config` means `config` was checked. + +
+ + `evaluationErrors?` + + + +\{ `code`: `string`; `field`: `string`; `message`: `string`; `operator`: `string`; \}[] + + + +Non-fatal diagnostics produced while evaluating the flag. + +
+ + `key` + + + +`string` + + + +Flag key. + +
+ + ~~`missingContextFields?`~~ + + + +`string`[] + + + +Missing context fields. + +**Deprecated** + +Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. + +
+ + `ruleEvaluationResults?` + + + +`boolean`[] + + + +Rule evaluation results. + +
+ + `value?` + + + + \| `boolean` \| \{ `key`: `string`; `payload`: `any`; \} + + + +Result of flag or configuration evaluation. +If `action` is `check-is-enabled`, this is the result of the flag evaluation and `value` is a boolean. +If `action` is `check-config`, this is the result of the configuration evaluation. + +
+ + `version?` + + + +`number` + + + +Version of targeting rules. + +
+ +*** + +### CompanyContext + +Context is a set of key-value pairs. +This is used to determine if feature targeting matches and to track events. +Id should always be present so that it can be referenced to an existing company. + +#### Indexable + +```ts +[key: string]: ContextValue +``` + +#### Properties + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `id` + + + +`undefined` \| `string` \| `number` + + + +Company id + +
+ + `name?` + + + +`string` + + + +Company name + +
+ +*** + +### Flag\ + +#### Type Parameters + + + + + + + + + + + + + + +
Type ParameterDefault type
+ +`TConfig` *extends* [`FlagType`](globals.md#flagtype)\[`"config"`\] + + + +[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) + +
+ +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyType
+ + `config` + + + +`Ref`\< \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| \{ `key`: `string`; \} & `TConfig`, \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| \{ `key`: `string`; \} & `TConfig`\> + +
+ + `isEnabled` + + + +`Ref`\<`boolean`, `boolean`\> + +
+ + `isLoading` + + + +`Ref`\<`boolean`, `boolean`\> + +
+ + `key` + + + +`string` + +
+ + `requestFeedback` + + + +(`opts`: [`RequestFlagFeedbackOptions`](globals.md#requestflagfeedbackoptions)) => `void` + +
+ +#### Methods + +##### track() + +```ts +track(): + | undefined + | Promise< + | undefined +| Response> +``` + +###### Returns + + \| `undefined` + \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +*** + +### Flags + +*** + +### UserContext + +Context is a set of key-value pairs. +This is used to determine if feature targeting matches and to track events. +Id should always be present so that it can be referenced to an existing user. + +#### Indexable + +```ts +[key: string]: ContextValue +``` + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `email?` + + + +`string` + + + +User email + +
+ + `id` + + + +`undefined` \| `string` \| `number` + + + +User id + +
+ + `name?` + + + +`string` + + + +User name + +
+ +## Type Aliases + +### BootstrappedFlags + +```ts +type BootstrappedFlags = BootstrappedState & { + flags: RawFlags; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + +
NameType
+ +`flags` + + + +[`RawFlags`](../browser-sdk/globals.md#rawflags) + +
+ +*** + +### EmptyFlagRemoteConfig + +```ts +type EmptyFlagRemoteConfig = { + key: undefined; + payload: undefined; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `key` + + + +`undefined` + +
+ + `payload` + + + +`undefined` + +
+ +*** + +### FlagKey + +```ts +type FlagKey = keyof TypedFlags; +``` + +*** + +### FlagType + +```ts +type FlagType = { + config: { + payload: any; + }; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `config`? + + + +\{ + `payload`: `any`; + \} + +
+ +`config.payload` + + + +`any` + +
+ +*** + +### OptInFlag + +```ts +type OptInFlag = Omit & { + key: FlagKey; +}; +``` + +An opt-in-enabled flag for the generated Vue SDK flag definitions. + +Includes all fields from [BrowserOptInFlag](../browser-sdk/globals.md#optinflag): `name`, `description`, +`isEnabled`, `userOptedIn`, `companyOptedIn`, and `isOptedIn`. +Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. + +#### Type declaration + + + + + + + + + + + + + + +
NameType
+ +`key` + + + +[`FlagKey`](globals.md#flagkey) + +
+ +*** + +### ReflagBaseProps + +```ts +type ReflagBaseProps = { + debug: boolean; + initialLoading: boolean; + logger: Logger; +}; +``` + +**`Internal`** + +Base props for the ReflagProvider and ReflagBootstrappedProvider. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `debug`? + + + +`boolean` + + + +Set to `true` to enable debug logging to the console. + +
+ + `initialLoading`? + + + +`boolean` + + + +Set to `true` to show the loading component while the client is initializing. + +
+ + `logger`? + + + +[`Logger`](../browser-sdk/globals.md#logger) + + + +A custom logger to use for SDK logs. +Use this for advanced control or filtering of SDK logs. +If both `logger` and `debug` are provided, `logger` takes precedence. + +
+ +*** + +### ReflagBootstrappedProps + +```ts +type ReflagBootstrappedProps = ReflagInitOptionsBase & ReflagBaseProps & { + flags: BootstrappedFlags; +}; +``` + +Props for the ReflagBootstrappedProvider. + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`flags` + + + +[`BootstrappedFlags`](globals.md#bootstrappedflags) + + + +Pre-fetched flags used for the initial render. The browser client fetches opt-in +metadata on demand when opt-in flags are requested. + +
+ +*** + +### ReflagClientProviderProps + +```ts +type ReflagClientProviderProps = Omit & { + client: ReflagClient; +}; +``` + +Props for the ReflagClientProvider. + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`client` + + + +[`ReflagClient`](../browser-sdk/globals.md#reflagclient) + + + +A pre-initialized ReflagClient to use. + +
+ +*** + +### ReflagInitOptionsBase + +```ts +type ReflagInitOptionsBase = Omit; +``` + +**`Internal`** + +Base init options for the ReflagProvider and ReflagBootstrappedProvider. + +*** + +### ReflagProps + +```ts +type ReflagProps = ReflagInitOptionsBase & ReflagBaseProps & { + company: CompanyContext; + context: ReflagContext; + otherContext: Record; + user: UserContext; +}; +``` + +Props for the ReflagProvider. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`company`? + + + +[`CompanyContext`](globals.md#companycontext) + + + +Company related context. If you provide `id` Reflag will enrich the evaluation context with +company attributes on Reflag servers. + +**Deprecated** + +Use `context` instead, this property will be removed in the next major version + +
+ +`context`? + + + +[`ReflagContext`](../browser-sdk/globals.md#reflagcontext) + + + +The context to use for the ReflagClient containing user, company, and other context. + +
+ +`otherContext`? + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `string` \| `number` \| `undefined`\> + + + +Context which is not related to a user or a company. + +**Deprecated** + +Use `context` instead, this property will be removed in the next major version + +
+ +`user`? + + + +[`UserContext`](globals.md#usercontext) + + + +User related context. If you provide `id` Reflag will enrich the evaluation context with +user attributes on Reflag servers. + +**Deprecated** + +Use `context` instead, this property will be removed in the next major version + +
+ +*** + +### RequestFlagFeedbackOptions + +```ts +type RequestFlagFeedbackOptions = Omit; +``` + +*** + +### SetOptInOptions + +```ts +type SetOptInOptions = { + optedIn: boolean; + scope?: "user" | "company"; +}; +``` + +Options for changing the current user or company's opt-in membership. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `optedIn` + + + +`boolean` + + + +Whether the scoped subject has opted in. + +
+ + `scope`? + + + +`"user"` \| `"company"` + + + +Whether to update the current user or current company. Defaults to `user`. + +
+ +*** + +### TrackEvent + +```ts +type TrackEvent = { + attributes: | Record + | null; + company: CompanyContext; + eventName: string; + user: UserContext; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `attributes`? + + + + \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + \| `null` + +
+ + `company`? + + + +[`CompanyContext`](globals.md#companycontext) + +
+ + `eventName` + + + +`string` + +
+ + `user` + + + +[`UserContext`](globals.md#usercontext) + +
+ +*** + +### TypedFlags + +```ts +type TypedFlags = keyof Flags extends never ? Record : { [TypedFlagKey in keyof Flags]: Flags[TypedFlagKey] extends FlagType ? Flag : Flag }; +``` + +*** + +### UseOptInFlagsResult + +```ts +type UseOptInFlagsResult = { + flags: ComputedRef; + isLoading: ComputedRef; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `flags` + + + +`ComputedRef`\<[`OptInFlag`](globals.md#optinflag)[]\> + +
+ + `isLoading` + + + +`ComputedRef`\<`boolean`\> + +
+ +## Variables + +### default + +```ts +default: { + install: void; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + +
NameType
+ + `install()` + + + +`void` + +
+ +*** + +### ReflagBootstrappedProvider + +```ts +const ReflagBootstrappedProvider: DefineComponent, Record, unknown>; +``` + +## Functions + +### useClient() + +```ts +function useClient(): ReflagClient +``` + +Vue composable for getting the Reflag client. + +This composable returns the Reflag client. You can use this to get the Reflag +client at any point in your application. + +#### Returns + +[`ReflagClient`](../browser-sdk/globals.md#reflagclient) + +The Reflag client. + +#### Example + +```ts +import { useClient } from '@reflag/vue-sdk'; + +const client = useClient(); + +console.log(client.getContext()); +``` + +*** + +### useFlag() + +```ts +function useFlag(key: TKey): TypedFlags[TKey] +``` + +Vue composable for getting the state of a given flag for the current context. + +This composable returns an object with the state of the flag for the current context. + +#### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`TKey` *extends* `string` + +
+ +#### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`key` + + + +`TKey` + + + +The key of the flag to get the state of. + +
+ +#### Returns + +[`TypedFlags`](globals.md#typedflags)\[`TKey`\] + +An object with the state of the flag. + +#### Example + +```ts +import { useFlag } from '@reflag/vue-sdk'; + +const { isEnabled, config, track, requestFeedback } = useFlag("huddles"); + +function StartHuddlesButton() { + const { isEnabled, config: { payload }, track } = useFlag("huddles"); + if (isEnabled) { + return ; +} +``` + +*** + +### useIsLoading() + +```ts +function useIsLoading(): Ref +``` + +Vue composable for checking if the Reflag client is loading. + +This composable returns a boolean value that indicates whether the Reflag client is loading. +You can use this to check if the Reflag client is loading at any point in your application. +Initially, the value will be true until the client is initialized. + +#### Returns + +`Ref`\<`boolean`, `boolean`\> + +#### Example + +```ts +import { useIsLoading } from '@reflag/vue-sdk'; + +const isLoading = useIsLoading(); + +console.log(isLoading); +``` + +*** + +### useOnEvent() + +```ts +function useOnEvent( + event: THookType, + handler: (arg0: HookArgs[THookType]) => void, + client?: ReflagClient): void +``` + +Vue composable for listening to Reflag client events. + +#### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`THookType` *extends* keyof [`HookArgs`](../browser-sdk/globals.md#hookargs) + +
+ +#### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`event` + + + +`THookType` + + + +The event to listen to. + +
+ +`handler` + + + +(`arg0`: [`HookArgs`](../browser-sdk/globals.md#hookargs)\[`THookType`\]) => `void` + + + +The function to call when the event is triggered. + +
+ +`client`? + + + +[`ReflagClient`](../browser-sdk/globals.md#reflagclient) + + + +The Reflag client to listen to. If not provided, the client will be retrieved from the context. + +
+ +#### Returns + +`void` + +#### Example + +```ts +import { useOnEvent } from '@reflag/vue-sdk'; + +useOnEvent("flagsUpdated", () => { + console.log("flags updated"); +}); +``` + +*** + +### useOptInFlags() + +```ts +function useOptInFlags(): UseOptInFlagsResult +``` + +Vue composable for getting opt-in-enabled flags and their loading state for +the current context. + +The loading state is only used with `ReflagBootstrappedProvider` while +opt-in metadata is fetched on demand. Regular providers load opt-in metadata +with the initial flags; use [useIsLoading](globals.md#useisloading) for their loading state. + +If fetching opt-in metadata fails, loading ends without exposing an error. +Call `refresh()` on the client returned by [useClient](globals.md#useclient) to retry. + +#### Returns + +[`UseOptInFlagsResult`](globals.md#useoptinflagsresult) + +*** + +### useRequestFeedback() + +```ts +function useRequestFeedback(): (options: RequestFeedbackData) => void +``` + +Vue composable for requesting user feedback. + +This composable returns a function that can be used to trigger the feedback +collection flow with the Reflag SDK. You can use this to prompt users for +feedback at any point in your application. + +#### Returns + +`Function` + +A function that requests feedback from the user. The function accepts: + - `options`: An object containing feedback request options. + +##### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`options` + + + +[`RequestFeedbackData`](../browser-sdk/globals.md#requestfeedbackdata) + +
+ +##### Returns + +`void` + +#### Example + +```ts +import { useRequestFeedback } from '@reflag/vue-sdk'; + +const requestFeedback = useRequestFeedback(); + +// Request feedback from the user +requestFeedback({ + prompt: "How was your experience?", + metadata: { page: "dashboard" } +}); +``` + +*** + +### useSendFeedback() + +```ts +function useSendFeedback(): (opts: UnassignedFeedback) => Promise< + | undefined +| Response> +``` + +Vue composable for sending feedback. + +This composable returns a function that can be used to send feedback to the +Reflag SDK. You can use this to send feedback from your application. + +#### Returns + +`Function` + +A function that sends feedback to the Reflag SDK. The function accepts: + - `options`: An object containing feedback options. + +##### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +[`UnassignedFeedback`](../browser-sdk/globals.md#unassignedfeedback) + +
+ +##### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +#### Example + +```ts +import { useSendFeedback } from '@reflag/vue-sdk'; + +const sendFeedback = useSendFeedback(); + +// Send feedback from the user +sendFeedback({ + feedback: "I love this flag!", + metadata: { page: "dashboard" } +}); +``` + +*** + +### useSetOptIn() + +```ts +function useSetOptIn(): (key: string, options: SetOptInOptions) => Promise< + | undefined +| Response> +``` + +Vue composable for setting whether the current user or company has opted into a flag. + +Check the returned Response's `ok` property and catch promise rejections. +HTTP failures return a non-OK Response; offline mode, invalid arguments, or +missing scoped context return undefined. Confirmation failures can reject +after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sdk/globals.md#setoptin). + +#### Returns + +`Function` + +##### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`options` + + + +[`SetOptInOptions`](globals.md#setoptinoptions) + +
+ +##### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +*** + +### useTrack() + +```ts +function useTrack(): (eventName: string, attributes?: + | null + | Record) => Promise< + | undefined +| Response> +``` + +Vue composable for tracking custom events. + +This composable returns a function that can be used to track custom events +with the Reflag SDK. + +#### Returns + +`Function` + +A function that tracks an event. The function accepts: + - `eventName`: The name of the event to track. + - `attributes`: (Optional) Additional attributes to associate with the event. + +##### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`eventName` + + + +`string` + +
+ +`attributes`? + + + + \| `null` \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + +
+ +##### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +#### Example + +```ts +import { useTrack } from '@reflag/vue-sdk'; + +const track = useTrack(); + +// Track a custom event +track('button_clicked', { buttonName: 'Start Huddles' }); +``` + +*** + +### useUpdateCompany() + +```ts +function useUpdateCompany(): (opts: {}) => Promise +``` + +Vue composable for updating the company context. + +This composable returns a function that can be used to update the company +context with the Reflag SDK. You can use this to update the company context +at any point in your application. + +#### Returns + +`Function` + +A function that updates the company context. The function accepts: + - `opts`: An object containing the company context to update. + +##### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +\{\} + +
+ +##### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +#### Example + +```ts +import { useUpdateCompany } from '@reflag/vue-sdk'; + +const updateCompany = useUpdateCompany(); + +// Update the company context +updateCompany({ id: "123", name: "Acme Inc." }); +``` + +*** + +### useUpdateOtherContext() + +```ts +function useUpdateOtherContext(): (opts: {}) => Promise +``` + +Vue composable for updating the other context. + +This composable returns a function that can be used to update the other +context with the Reflag SDK. You can use this to update the other context +at any point in your application. + +#### Returns + +`Function` + +A function that updates the other context. The function accepts: + - `opts`: An object containing the other context to update. + +##### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +\{\} + +
+ +##### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +#### Example + +```ts +import { useUpdateOtherContext } from '@reflag/vue-sdk'; + +const updateOtherContext = useUpdateOtherContext(); + +// Update the other context +updateOtherContext({ id: "123", name: "Acme Inc." }); +``` + +*** + +### useUpdateUser() + +```ts +function useUpdateUser(): (opts: {}) => Promise +``` + +Vue composable for updating the user context. + +This composable returns a function that can be used to update the user context +with the Reflag SDK. You can use this to update the user context at any point +in your application. + +#### Returns + +`Function` + +A function that updates the user context. The function accepts: + - `opts`: An object containing the user context to update. + +##### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +\{\} + +
+ +##### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +#### Example + +```ts +import { useUpdateUser } from '@reflag/vue-sdk'; + +const updateUser = useUpdateUser(); + +// Update the user context +updateUser({ id: "123", name: "John Doe" }); +``` + +## References + +### ReflagClientProvider + +Renames and re-exports [ReflagBootstrappedProvider](globals.md#reflagbootstrappedprovider) + +### ReflagProvider + +Renames and re-exports [ReflagBootstrappedProvider](globals.md#reflagbootstrappedprovider) diff --git a/product-handbook/anonymous-users.md b/product-handbook/anonymous-users.md index e09532f..39d6654 100644 --- a/product-handbook/anonymous-users.md +++ b/product-handbook/anonymous-users.md @@ -1,80 +1,85 @@ --- -description: How to use Reflag with anonymous users +description: Use SDK v2 with anonymous users and optional company context. --- # Anonymous users -Reflag is designed for SaaS applications in which users are authenticated and belong to a company group. However, you can still use Reflag for certain use cases where users aren't authenticated. +Reflag supports contexts without a user, including public pages and company-branded applications. Omit unknown identities rather than supplying empty-string IDs. Rules that require an omitted identity or attribute cannot match it. -Example use cases: +## How to toggle features for anonymous users -* Toggle features on/off for all anonymous users on marketing pages or docs. -* For anonymous users that belong to companies, for example for a white-label solution for ordering food online: roll out features to anonymous users belonging to certain restaurants or roll it users belonging to a percentage of restaurants (companies). - -### How to toggle features for anonymnous users - -First, create a new flag, use it on the respective feature and ship it. - -On the Access tab, you can now use "No-one" or "Everyone" to toggle the feature off and on. "Some" is not supported for anonymous users. - -For anonymous users you supply an empty user ID and empty company ID. +For a global Boolean flag, use Everyone/No-one access and an empty context. Initialize the Node client before reading: {% tabs %} {% tab title="Node.js" %} ```typescript import { ReflagClient } from "@reflag/node-sdk"; -const client = new ReflagClient(...) -// using an empty context for anonymous users -const { isEnabled } = client.bindClient({}).getFlag("export-to-csv") +const client = new ReflagClient({ secretKey: process.env.REFLAG_SECRET_KEY ?? "" }); +await client.initialize(); +const enabled = client.getFlag({}, "export-to-csv"); +console.log(enabled); ``` {% endtab %} - {% tab title="React" %} ```tsx -import { ReflagProvider } from "@reflag/react-sdk"; +import { ReflagProvider, useFlag } from "@reflag/react-sdk"; + +function ExportButton() { + const enabled = useFlag("export-to-csv"); + return enabled ? : null; +} -function App() { +export function App() { return ( - // no user/company provided - + + ); } - ``` {% endtab %} {% endtabs %} -### How to toggle features for anonymous users where you know their company +Bare reads return Boolean with implicit false. Supply a positional default when reading JSON-valued Multivariate flags. + +## How to toggle features for anonymous users where you know their company -If the user is anonymous but you do know the company entity, you can simply supply the given company ID and an empty user ID. This lets you control features for anonymous users beloning to the given company. +Provide only the company when your application has a trustworthy company identity. Company targeting can then apply without inventing a user. {% tabs %} {% tab title="Node.js" %} ```typescript import { ReflagClient } from "@reflag/node-sdk"; -const client = new ReflagClient(...) - -// supply only the company ID if the users is anonymous but belongs to a company -const { isEnabled } = client.bindClient({company: {id: "petes-burgers"}).getFlag("export-to-csv") +const client = new ReflagClient({ secretKey: process.env.REFLAG_SECRET_KEY ?? "" }); +await client.initialize(); +const companyClient = client.bindClient({ company: { id: "petes-burgers" } }); +const enabled = companyClient.getFlag("export-to-csv"); +console.log(enabled); ``` {% endtab %} - {% tab title="React" %} ```tsx -import { ReflagProvider } from "@reflag/react-sdk"; +import { ReflagProvider, useFlag } from "@reflag/react-sdk"; -function App() { +function ExportButton() { + const enabled = useFlag("export-to-csv"); + return enabled ? : null; +} + +export function App() { return ( - // company provided - + + ); } - ``` {% endtab %} {% endtabs %} +A browser's company ID is not an authorization boundary. Enforce sensitive access on your authenticated server, using context derived from your own session or API-token lookup. See [Node SDK v2](../supported-languages/node-sdk/README.md) and [React SDK v2](../supported-languages/react-sdk/README.md) for complete setup. diff --git a/product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta.md b/product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta.md index cf56199..c5904da 100644 --- a/product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta.md +++ b/product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta.md @@ -3,11 +3,11 @@ When the [GitHub integration](../../integrations/github.md) is enabled, Reflag can automatically clean up your code after flags turn stale. The Reflag bot submits a pull request to your GitHub repository that removes flag code once a flag turns stale. {% hint style="warning" %} -This automation **keeps the codepath that grants access (`isEnabled == true`)** when cleaning up and archiving a flag. In practice, it releases the flag to everyone by removing the flagging code. +This automation **keeps the codepath that grants access (the Boolean flag value is `true`)** when cleaning up and archiving a flag. In practice, it releases the flag to everyone by removing the flagging code. {% endhint %} {% hint style="info" %} -Note: This works best when using the [React SDK](../../supported-languages/browser-sdk/), but stay tuned for improved Node.js support +Note: This works best when using the [React SDK](../../supported-languages/react-sdk/README.md), but stay tuned for improved Node.js support {% endhint %}
@@ -101,25 +101,31 @@ When the AI clean-up bot runs, it searches for usage of the Reflag SDK in your c For React, this usually corresponds to the `useFlag` hook, like in this contrived example: -```javascript +```tsx +import { useFlag, useTrack } from "@reflag/react-sdk"; + function StartHuddleButton() { - const { isEnabled } = useFlag("huddle"); - if (!isEnabled) { + const enabled = useFlag("huddle"); + const track = useTrack(); + if (!enabled) { return null; } - return ; + return ; } ``` -When the bot cleans up the file, it removes the hook and only retains the `isEnabled` codepath: +When the bot cleans up the file, it removes the hook and only retains the enabled codepath: + +```tsx +import { useTrack } from "@reflag/react-sdk"; -```javascript function StartHuddleButton() { - return ; + const track = useTrack(); + return ; } ``` **Limitations**: -* Only `isEnabled` is removed, whereas `track`, `config`, and `requestFeedback` are untouched. +* Review the generated PR carefully. Removing the Boolean gate does not imply that usage tracking, feedback hooks or separately authored configuration should be removed. Multivariate values need an explicit cleanup decision; do not apply Boolean truthiness to arbitrary JSON. * Works best with the React SDK while in beta. diff --git a/product-handbook/feature-entitlements/README.md b/product-handbook/feature-entitlements/README.md index 81e5295..3cf4f7b 100644 --- a/product-handbook/feature-entitlements/README.md +++ b/product-handbook/feature-entitlements/README.md @@ -24,24 +24,25 @@ Reflag is purpose-built for B2B, with native support for gating flags at the com ### Step 1: Initialize Reflag -Choose [an SDK](https://app.gitbook.com/s/pgXAy2Cgsm5pON9oJ06m/supported-languages) to get started, if you haven't already.\ +Choose [an SDK](../../supported-languages/overview.md) to get started, if you haven't already.\ \ Reflag needs to know who the authenticated user is and which company they belong to. We attach attribute metadata such as the company's subscription plan. ```tsx -// identify user -reflag.user(userId1356, { - name: “Rasmus Makwarth”, -}); - -// associate user with company -reflag.company(companyId51, { - name: “Acme Inc.”, - plan: “business”, -}); +import { ReflagProvider } from "@reflag/react-sdk"; + + + {/* your application */} +; ``` -Reflag now understands that Rasmus works for Acme Inc. and Acme Inc. is on the Business subscription plan. +Reflag can now target the company's Business subscription plan. Enforce sensitive entitlements on the server with context derived from your trusted session or subscription store; browser-supplied attributes are not an authorization boundary. {% hint style="info" %} You can send company attributes as part of the user sign-in event, via a nightly job, or use `updateCompany()` when the attribute value changes. @@ -74,12 +75,12 @@ Each flag comes with a [flag key](../concepts/feature.md#flag-key), such as `exp In React, it’d look like this: ```tsx -const { isEnabled } = useFlag("export-to-csv"); - -if(isEnabled) { - - // access to csv export! +import { useFlag } from "@reflag/react-sdk"; +function ExportButton() { + const enabled = useFlag("export-to-csv"); + if (!enabled) return null; + return ; } ``` @@ -119,10 +120,9 @@ Send usage metrics to Reflag using company attributes. For example, you can send the company's current usage metrics to Reflag at an hourly or daily interval. -```tsx -reflag.companyUpdate(companyId51, { - apiRequestsCurrentMonth: 793 -}); +```ts +// On an initialized Browser SDK v2 client: +await reflag.updateCompany({ apiRequestsCurrentMonth: 793 }); ``` ### Step 2: Gate using usage attribute diff --git a/product-handbook/feature-entitlements/simple-role-based-entitlements.md b/product-handbook/feature-entitlements/simple-role-based-entitlements.md index 9ab45ed..bb7f35d 100644 --- a/product-handbook/feature-entitlements/simple-role-based-entitlements.md +++ b/product-handbook/feature-entitlements/simple-role-based-entitlements.md @@ -20,7 +20,7 @@ If you zoom out, this is what controlling feature access at the customer subscri
-To add simple user role controls to the mix, you can choose to hard code the user role check within the `isEnabled` check. +To add simple user role controls to the mix, you can choose to hard code the user role check alongside the Boolean value returned by `useFlag()` or `getFlag()`.
diff --git a/product-handbook/launch-monitor/README.md b/product-handbook/launch-monitor/README.md index d7793ac..0c67b6f 100644 --- a/product-handbook/launch-monitor/README.md +++ b/product-handbook/launch-monitor/README.md @@ -12,24 +12,21 @@ The Exposed chart shows the distinct count of companies that have been exposed t The Tracked chart shows the distinct count of companies that have interacted with the flagged workflow. Interactions are tracked with the `track` method. -```typescript -import { useFlag } from "@reflag/react-sdk"; +```tsx +import { useFlag, useTrack } from "@reflag/react-sdk"; function StartHuddleButton() { - const { isLoading, isEnabled, track } = useFlag("huddle"); - - if (isLoading) { - return ; - } + const enabled = useFlag("huddle"); + const track = useTrack(); - if (!isEnabled) { + if (!enabled) { return null; } return (
Huddles - +
); } @@ -41,19 +38,18 @@ You can collect end-user feedback on new flag rollouts to catch and fix issues f ### Static feedback button -Here's a brief example using the [Reflag React SDK](../../supported-languages/browser-sdk/) to collect feedback: +Configure adoption rules to match the usage event name you send. Reading a flag registers a check; tracking usage is a separate operation. + +Here's a brief example using the [Reflag React SDK v2](../../supported-languages/react-sdk/README.md) to collect feedback: ```tsx -import { useFlag } from "@reflag/react-sdk"; +import { useFlag, useRequestFeedback } from "@reflag/react-sdk"; function StartHuddleButton() { - const { isLoading, isEnabled, requestFeedback } = useFlag("my-flag"); - - if (isLoading) { - return ; - } + const enabled = useFlag("my-flag"); + const requestFeedback = useRequestFeedback(); - if (!isEnabled) { + if (!enabled) { return null; } @@ -61,7 +57,7 @@ function StartHuddleButton() { <> diff --git a/product-handbook/launch-monitor/give-feedback-button.md b/product-handbook/launch-monitor/give-feedback-button.md index 79373fa..dc561b2 100644 --- a/product-handbook/launch-monitor/give-feedback-button.md +++ b/product-handbook/launch-monitor/give-feedback-button.md @@ -1,36 +1,33 @@ --- -description: Adding a feedback button using Reflag SDKs in a few lines of code. +description: Add a feedback button with the React SDK v2 feedback hook. --- # Give feedback button -Collecting feedback through a "Give feedback" button is a great way to collect feedback from users. - -Here's a brief example using the [Reflag React SDK](../../supported-languages/browser-sdk/): +Use a separate feedback hook to open a feedback form. The flag read controls the workflow; it does not return feedback or tracking methods. ```tsx -import { useFlag } from "@reflag/react-sdk"; - -function StartHuddleButton() { - const { isLoading, isEnabled, track, requestFeedback } = useFlag("huddle"); +import { useFlag, useRequestFeedback, useTrack } from "@reflag/react-sdk"; - if (isLoading) { - return ; - } +export function StartHuddleButton() { + const enabled = useFlag("huddle"); + const track = useTrack(); + const requestFeedback = useRequestFeedback(); - if (!isEnabled) { - return null; - } + if (!enabled) return null; return ( <> - - + ); } ``` + +Render this component inside a [React SDK v2 provider](../../supported-languages/react-sdk/README.md) with the appropriate user/company context. Configure adoption rules to match the event you track. For widget positioning, translations, styling, or your own UI, see [Browser feedback](../../supported-languages/browser-sdk/feedback.md). diff --git a/product-handbook/remote-config.md b/product-handbook/remote-config.md index bcc3c28..cc4ea7b 100644 --- a/product-handbook/remote-config.md +++ b/product-handbook/remote-config.md @@ -1,106 +1,91 @@ --- -description: Learn more about remote config in Reflag +description: Configure JSON-valued Multivariate flags for different audiences. --- # Remote config ## What is remote config? -Remote config is a dynamic way to configure flags for different audiences. A flag's remote config consists of a set of **config values**. Each config value is a **key** — **payload** pair where the key is unique and the value is any valid JSON value. Both are supplied by you. +Use a **Multivariate flag** when different users or companies need different configuration values. Unlike a Boolean flag, which answers an access question, a Multivariate flag selects a named variant and returns its JSON value directly. -Config values have **environment-specific targeting rules** used by Reflag to match them against your users and companies. +A value can be an object, array, string, number, Boolean, or `null`. There are no reserved application fields: names such as `model`, `config`, `payload`, or `enabled` are ordinary data that you choose. -Remote config reduces the need for code changes. It lets you test and adjust flag behavior without redeploying your application. +For example, configure `assistant-settings` with variants containing different model settings, then read it with React SDK v2: -This is what remote config looks like in React: - -{% code fullWidth="false" %} ```tsx -function AISummarizerRemotelyConfigured({copy}: {copy: string}) { - const { config: { payload } } = useFlag('my-ai-flag'); - - return +import { useFlag } from "@reflag/react-sdk"; + +export function AssistantSettings() { + const settings = useFlag("assistant-settings", { + model: "quick", + maxTokens: 512, + includeCitations: false, + }); + + return ( +

+ Model: {settings.model}; token limit: {settings.maxTokens}; + citations: {settings.includeCitations ? "on" : "off"} +

+ ); } ``` -{% endcode %} -{% hint style="info" %} -Remote config works independently from [access rules](feature-rollouts/feature-targeting-rules.md). In other words, remote config is not affected by whether the user has access to the flag. -{% endhint %} +The second argument is the application's fallback value, not hook options. A bare `useFlag("assistant-settings")` is a Boolean read, even if the flag is Multivariate. Supply an appropriate default for a JSON read; use explicit `null` if you need arbitrary JSON and will narrow the result yourself. ## Config values -Config values consist of: +Each environment's definition contains: -* A mandatory unique string **key**, supplied by you. The key is unique per flag. If you just need a string configuration, you can use the key by itself. -* An optional JSON **payload**, that can be any valid JSON value: `null`, `string`, `number`, `array` or `object` -* Targeting rules which are environment-specific, allowing you to target different config values to different users/companies in different environments -* Default setting, which tells Reflag which config value to use as fallback if no targeting set matches the given user/company context +- **Variants:** unique keys and their JSON values. The SDK returns the selected **value**, not the variant key or a wrapper. +- **Specific targets:** explicit user/company assignments to variants. +- **Ordered rules:** filters and results, including percentage distributions. +- **Default variant:** the authored selection when no more-specific target or applicable rule selects a variant. -{% hint style="danger" %} -Do not store sensitive data in the key or the payload of the config value even if the flag is marked as **secret.** - -Sensitive data, like API keys or passwords should be managed with proper care outside of Reflag -{% endhint %} +Definitions, targeting, and values are environment-specific. Save the complete definition together; changing another environment does not automatically copy its values or rules. An empty Multivariate definition evaluates to `null`. -The config values are shared across all environments. Any new value that you add in one environment is automatically added to other environments, but without targeting rules, making it disabled there by default. +The authored default variant is different from the application's SDK fallback. A real default-variant selection retains its selection identity; the SDK fallback does not invent one. -

Remote config with three values in the Production environment

- -In the image above, a flag is set up with three config values. This example configures LLM settings for an AI workflow. The `gpt-4o` value is the default and is served with requests that do not match a more specific rule. The `claude-3-7-sonnet` value is served to users in `Apex` and `Blaze`. The `gpt-5` value is served to `Adrian Borer` and the `Logix` and `Hightrix` companies. - -{% hint style="info" %} -We recommend that you choose simple text values for config value keys. Avoid spaces and special characters unless you plan to use the key as display text in your application. +{% hint style="danger" %} +Do not store credentials or other secrets in flag values. Anything sent to a browser can be inspected by its users. Keep application secrets in an appropriate secret manager. {% endhint %} ## Matching algorithm -* Users, companies and segments can appear only once in the targeting rules for each environment. This means that you cannot configure two distinct config values in the same environment to target the same entity explicitly -* Matches are not evaluated in the order of their appearance, but in order of their **specificity**: - * Directly specified users match first - * Then, directly specified companies match - * Then, going top to bottom in order of appearance of the config values, segments specified are matched against the company - * Finally, if no rule is matched, the default one is used -* **`Other context`** is not taken into account when evaluating config value targeting rules -* _Percentage rollout_ is not supported for remote config +Specific user assignments take precedence over company assignments. Then rules are considered in order; the default variant handles contexts that do not select an earlier result. Rules can use the supported user, company, segment, and other-context filters. Percentage distributions select a variant using the configured bucketing attribute; preserve stable variant/rule identities when editing definitions. -## Usage scenarios +For a separate on/off gate, use a Boolean flag. A Multivariate value of `false`, `0`, `""`, `[]`, or `null` is application data, not a universal access-denied signal. Do not use JavaScript truthiness to decide whether a variant was selected. -In addition to the AI model configuration example above, this section shows some other scenarios that can be solved by using remote config. +## Usage scenarios ### Basic flag configuration -Sometimes it is useful to store flag-specific config that your application can use. This is true even if you do not plan to target different config values to different users. You can create a single config value, set it as **default**, and store any JSON payload in it. In that case, the key can be any value you choose. +Use a single default variant for centrally managed configuration, or add rules and more variants as different audiences need different settings. Choose a safe application fallback and validate any nested data your application depends on. -On the application side, you can check if the user has access to the flag, and use the accompanying config when needed. - -{% hint style="info" %} -Since config values are evaluated independently from access, your application can still use remote config even if the flag is disabled for the user. For example, the payload can explain why the flag is unavailable or offer an alternative path. -{% endhint %} +Non-null SDK defaults check the selected value's **top-level category**. They do not recursively validate a returned object's fields. Generated TypeScript declarations are compile-time assistance, not runtime validation. ### Multivariate flags -The **multivariate flag** is a classic remote config use case. To create one: - -1. Create a flag and define its access rules, if any. -2. Create the "_variants_" by using config values. Each config value has its key representing the variant name. -3. Adjust the targeting rules on each config value. -4. Payloads can be be ignored if additional configuration is not required for each variant. +For string-valued variants, the value can itself be the model or mode your application needs: -### Entitlements +```tsx +import { useFlag } from "@reflag/react-sdk"; -Remote config is a strong fit for [entitlements scenarios](feature-entitlements/). For each flag you create, you can add config values that target different **companies** or **company segments**. Each config value can then define a different access tier or usage limit. +export function AssistantModel() { + const model = useFlag("assistant-model", "quick"); + return

Selected model: {model}

; +} +``` -

Example of AI model variations by subscription tier

+### Entitlements -The image above shows a flag called "_AI Transcripts_" that serves four customer categories: "_Not customers_", "_Beta_", "_Business Plan_", and "_Enterprise Plan_". Each category receives a different tier. +Combine a Boolean entitlement such as `assistant-enabled` with a separate settings flag when access and configuration are independent product decisions. Use company attributes and rules to select settings for each subscription tier. Read only the flags needed by the workflow. ## Start using remote config -First, [create your first flag](https://app.reflag.com/env-current/flags/new), if you have not already. Then open your flag and click the "_Remote config_" tab. - -

Click "Create config value" to start

- -Once you have set up your flag and config values, configure the targeting rules in your other environments as well. +1. Create a **Multivariate** flag in an app where Multivariate support is available. +2. Open its **Variants** tab and configure variants, specific targets, rules, and the default for the selected environment. +3. Save, then configure and verify any other environments separately. +4. Read the value with matching [SDK v2](../supported-languages/overview.md) packages and a positional default. -Finally, use [any of our SDKs](../supported-languages/overview.md) to access the flag and its config in your application. +Existing v1 Boolean flags with an independent remote-config payload do **not** automatically become Multivariate flags. Plan their authored-data migration explicitly; upgrading an SDK does not copy or reinterpret old payloads. See the [v1 → v2 migration guide](../supported-languages/migrating-from-v1.md). diff --git a/product-handbook/service-resiliency.md b/product-handbook/service-resiliency.md index 821c2e2..30e836d 100644 --- a/product-handbook/service-resiliency.md +++ b/product-handbook/service-resiliency.md @@ -57,9 +57,9 @@ flowchart LR ## Recommended production setup -1. Evaluate flags on the server with a local-evaluation SDK, such as the [Node.js SDK](../supported-languages/node-sdk/) or [OpenFeature Node.js provider](../supported-languages/openfeature.md). -2. Configure a [`flagsFallbackProvider`](../supported-languages/node-sdk/#fallback-provider) so fresh server processes can initialize from saved flag definitions when Reflag cannot be reached. -3. Use [`getFlagsForBootstrap()`](../supported-languages/node-sdk/#bootstrapping-client-side-applications) on the server and a bootstrapped client provider in React, React Native, Vue, or the Browser SDK. +1. Evaluate flags on the server with the [Node.js SDK v2](../supported-languages/node-sdk/README.md). +2. Configure a [`flagsFallbackProvider`](../supported-languages/node-sdk/README.md#fallback-providers) so fresh server processes can initialize from saved flag definitions when Reflag cannot be reached. +3. Use [`getFlagsForBootstrap()`](../supported-languages/node-sdk/README.md#bootstrap-state) on the server and a matching v2 bootstrapped client provider in React, Vue, or the Browser SDK. 4. If your client SDK supports caching, tune it based on how long your app can tolerate stale flags. 5. Test the disruption path in staging: block access to Reflag, start a fresh server process, and confirm it initializes from fallback storage and the client renders from bootstrapped flags. @@ -90,18 +90,19 @@ Use the file provider for single-server deployments only when the disk persists Choose fallback storage based on where your application runs. The storage should be reachable whenever your application is reachable, so prefer storage in the same cloud provider, region, or network as the application deployment that will use it. If an outage affects Reflag's infrastructure but your application is still running elsewhere, your application can still load the saved snapshot. If the same provider or region outage also takes down your application, fallback storage cannot help until your application environment is available again. -For all built-in providers and custom provider examples, see the [fallback provider docs](../supported-languages/node-sdk/#fallback-provider). +For built-in providers and the v2 snapshot contract, see the [fallback provider docs](../supported-languages/node-sdk/README.md#fallback-providers). V1 snapshots cannot initialize a v2 collection cache; built-in storage uses isolated v2 keys. ## Bootstrapped flags Bootstrapping lets your server evaluate flags and pass the server-evaluated state to your client-side application. The client can render immediately from that state instead of depending on an initial request to Reflag. -Use [`getFlagsForBootstrap()`](../supported-languages/node-sdk/#bootstrapping-client-side-applications) in the Node.js SDK together with the bootstrapping APIs in your client SDK: +Use [`getFlagsForBootstrap()`](../supported-languages/node-sdk/README.md#bootstrap-state) in Node SDK v2 together with the matching v2 bootstrapping APIs: -* [React SDK](../supported-languages/react-sdk/#server-side-rendering-and-bootstrapping): `ReflagBootstrappedProvider` -* [React Native SDK](../supported-languages/react-native-sdk/#bootstrapping): `ReflagBootstrappedProvider` -* [Vue SDK](../supported-languages/vue-sdk/#reflagbootstrappedprovider-component): `ReflagBootstrappedProvider` -* [Browser SDK](../supported-languages/browser-sdk/#using-bootstrappedstate): `bootstrappedState` +* [React SDK](../supported-languages/react-sdk/README.md#bootstrap-and-ssr): `ReflagBootstrappedProvider` +* [Vue SDK](../supported-languages/vue-sdk/README.md#bootstrap): `ReflagBootstrappedProvider` +* [Browser SDK](../supported-languages/browser-sdk/README.md#server-bootstrap): `bootstrappedState` + +Pass the entire protocol-v2 envelope, not only its `flags` property. React Native and the OpenFeature providers retain their independently supported contracts. Do not feed Node v2 bootstrap into a v1 consumer; use the [legacy Node SDK](../legacy/v1/node-sdk/README.md) with v1 consumers until their coordinated migration. Bootstrapping is the recommended client setup for high-availability applications because the first render depends on your application server response, not on the client's ability to reach Reflag. Combined with server-side local evaluation and `flagsFallbackProvider`, it lets end users continue receiving evaluated flags during a Reflag service disruption. diff --git a/product-handbook/type-safety.md b/product-handbook/type-safety.md index be54a80..815a98b 100644 --- a/product-handbook/type-safety.md +++ b/product-handbook/type-safety.md @@ -1,54 +1,85 @@ --- -description: Reflag offers type safety which reduces errors and frustation +description: Register flag keys and direct-value schemas with SDK v2 and CLI 2. --- # Type safety -{% embed url="https://www.youtube.com/watch?v=2ay2sc9g6Oc" %} +Reflag SDK v2 can infer a direct return type from the default you pass, without a generated file. Registering your flag schemas also catches misspelled keys and incompatible non-null defaults. -Type safety in Reflag ensures that flag key typos become build errors. This guarantees that if you try to use a non-existent flag key, you'll receive a type error, preventing potential runtime errors and improving code reliability. For remote config, it also ensures that the shape of the payload defined on Reflag matches what your code expects. +```tsx +import { useFlag } from "@reflag/react-sdk"; -Use the Reflag CLI to generate flag types from their definition in Reflag. Once flag types have been generated they are automatically picked up by TypeScript. +export function TokenLimit() { + const settings = useFlag("assistant-settings", { maxTokens: 512 }); + return {settings.maxTokens}; +} +``` -It's recommended that you do not check in the flag types, but instead generate them in your build process and on your local development machines. +The fallback determines the widened return type: `512` becomes `number`, not the literal type `512`. Bare or explicit-`undefined` reads return Boolean; explicit `null` requests arbitrary JSON. ## Set up type safety for flags -1. Install the Reflag CLI and set up your repository +Use **CLI 2 with Node/React/Vue SDK v2**. Keep CLI 1 with v1 applications. CLI 2 and the SDK v2 packages must be available before using these installation commands; a staging server deployment alone does not release them. - ``` - npm install --save-dev @reflag/cli - npx reflag init - ``` -2. Generate the types locally +```sh +npm install --save-dev @reflag/cli@2 +npx reflag init +npx reflag flags types +``` - ``` - npx reflag types generate - ``` -3. Add the generated files to `.gitignore` +Choose the appropriate output format during initialization, or pass it explicitly: - ``` - echo "gen/flags.d.ts" >> .gitignore - ``` -4. Retrieve an [API Key](http://app.reflag.com/env-current/settings/org-api-access) for your build system -5. Set up your build system to run the Reflag CLI to generate types (use the `--api-key` option or specify the API key in the `REFLAG_API_KEY` environment variable) +```sh +npx reflag flags types --format react --out gen/flags.d.ts +npx reflag flags types --format node --out gen/flags.d.ts +npx reflag flags types --format vue --out gen/flags.d.ts +``` - ``` - npx reflag apps list --api-key $REFLAG_API_KEY - ``` +Generate only the declarations needed by your application's SDKs and ensure TypeScript includes the output. These examples show alternative formats; do not overwrite the same file three times in your actual build. -Example CI workflow: +Generation uses current production-environment Multivariate values to describe possible JSON shapes. Empty or unknown data remains JSON-capable rather than being invented as Boolean. Regenerate when flag definitions change. Generation errors must fail your build rather than leaving an unnoticed stale declaration file. -```yaml -# GitHub Actions example -- name: Generate types - run: npx reflag flags types --api-key ${{ secrets.REFLAG_API_KEY }} +You can commit the generated file, or ignore it and generate it on local setup and in CI. If you ignore it: + +```sh +echo "gen/flags.d.ts" >> .gitignore +``` + +## Registered schemas and defaults + +A React registration looks like this (the CLI writes the appropriate augmentation for you): + +```tsx +import { useFlag } from "@reflag/react-sdk"; -# GitHub Actions example (using environment): -- name: Generate types (environment) +declare module "@reflag/react-sdk" { + interface Flags { + "assistant-settings": { maxTokens: number; model: "quick" | "reasoner" }; + } +} + +export function RegisteredSettings() { + const settings = useFlag("assistant-settings", { + maxTokens: 512, + model: "quick", + }); + return {settings.model}: {settings.maxTokens}; +} +``` + +Registered non-null defaults must match the selected key's schema, including required/nested fields, array elements, and literal unions. Named interfaces and readonly defaults are supported. This does not change bare Boolean reads or the arbitrary-JSON meaning of explicit `null`. + +The SDK validates that defaults are JSON-compatible and checks the selected value's top-level category. It does **not** recursively enforce generated schemas on server-returned values. Add application validation when nested data is a trust boundary. + +## Using in CI/CD pipelines + +Store an authorized [Management API key](../api/api-access.md) in your CI secret store. Do not commit it or send it to a browser. + +```yaml +- name: Generate flag types run: npx reflag flags types env: REFLAG_API_KEY: ${{ secrets.REFLAG_CI_API_KEY }} ``` -There's further guidance and examples of using [Reflag CLI in CI/CD pipelines](https://docs.reflag.com/api/cli#using-in-ci-cd-pipelines-beta). +Install CLI 2 from your lockfile before running this step. The command is **`reflag flags types`**, not `reflag types generate` or `reflag flags generate`. See the [SDK migration guide](../supported-languages/migrating-from-v1.md) before replacing legacy wrapper-shaped declarations. diff --git a/sdk/@reflag/browser-sdk/README.md b/sdk/@reflag/browser-sdk/README.md index d1b8990..10bb7a1 100644 --- a/sdk/@reflag/browser-sdk/README.md +++ b/sdk/@reflag/browser-sdk/README.md @@ -13,597 +13,159 @@ pagination: visible: true --- -# Reflag Browser SDK - -Basic client for [Reflag.com](https://reflag.com). If you're using React, you'll be better off with the Reflag React SDK. - -Reflag supports flag toggling, tracking flag usage, [collecting feedback](#qualitative-feedback-on-beta-flags) on flags, and [remotely configuring flags](#remote-config). - -## Install - -First find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag. - -The package can be imported or used directly in a HTML script tag: - -A. Import module: - -```typescript -import { ReflagClient } from "@reflag/browser-sdk"; - -const user = { - id: 42, - role: "manager", -}; - -const company = { - id: 99, - plan: "enterprise", -}; - -const reflagClient = new ReflagClient({ publishableKey, user, company }); - -await reflagClient.initialize(); - -const { - isEnabled, - config: { payload: question }, - track, - requestFeedback, -} = reflagClient.getFlag("huddle"); - -if (isEnabled) { - // Show flag. When retrieving `isEnabled` the client automatically - // sends a "check" event for the "huddle" flag which is shown in the - // Reflag UI. - - // On usage, call `track` to let Reflag know that a user interacted with the flag - track(); - - // The `payload` is a user-supplied JSON in Reflag that is dynamically picked - // out depending on the user/company. - const question = payload?.question ?? "Tell us what you think of Huddles"; - - // Use `requestFeedback` to create "Send feedback" buttons easily for specific - // flags. This is not related to `track` and you can call them individually. - requestFeedback({ title: question }); -} - -// `track` just calls `reflagClient.track()` to send an event using the same flag key -// You can also use `track` on the client directly to send any custom event. -reflagClient.track("huddle"); - -// similarly, `requestFeedback` just calls `reflagClient.requestFeedback({flagKey: })` -// which you can also call directly: -reflagClient.requestFeedback({ flagKey: "huddle" }); -``` - -B. Script tag (client-side directly in html) - -See [example/browser.html](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/example/browser.html) for a working example: - -```html - - -Loading... - -``` - -### Init options - -Supply these to the constructor call: - -```typescript -type Configuration = { - logger: console; // by default only logs warn/error, by passing `console` you'll log everything - apiBaseUrl?: "https://front.reflag.com"; - credentials?: "include" | "same-origin" | "omit"; // forwarded to fetch requests; "include" also enables credentials for the default EventSource transport - feedback?: undefined; // See FEEDBACK.md - enableTracking?: true; // set to `false` to stop sending track events and user/company updates to Reflag servers. Useful when you're impersonating a user - enableLiveFlagUpdates?: false; // Set to `true` to keep flags up to date over SSE (browser SDK default: false) - eventSourceFactory?: (url: string) => { - // Advanced: provide a custom EventSource-compatible transport - addEventListener: (type: string, cb: (event: any) => void) => void; - close: () => void; - }; - fallbackFlags?: - | string[] - | Record; // Enable these flags if unable to contact reflag.com. Can be a list of flag keys or a record with configuration values - timeoutMs?: number; // Timeout for fetching flags (default: 5000ms) - staleWhileRevalidate?: boolean; // Revalidate in the background when cached flags turn stale to avoid latency in the UI (default: false) - staleTimeMs?: number; // at initialization time flags are loaded from the cache unless they have gone stale. Defaults to 0 which means the cache is disabled. Increase this in the case of a non-SPA - expireTimeMs?: number; // In case we're unable to fetch flags from Reflag, cached/stale flags will be used instead until they expire after `expireTimeMs`. Default is 30 days - offline?: boolean; // Use the SDK in offline mode. Offline mode is useful during testing and local development -}; -``` - -## Migrating from Bucket SDK - -If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: - -- `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) -- `Feature*` classes, and types have been renamed to `Feature*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) -- All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) -- The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags` -- `featureKey` has been renamed to `flagKey` in all methods that accepts that argument -- The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead og `bucket-*` -- The `featuresUpdated` hook has been renamed to `flagsUpdated` -- The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on - -To ease in transition to Reflag SDK, some of the old methods have been preserved as aliases to the new methods: - -- `getFeature` method is an alias for `getFlag` -- `getFeatures` method is an alias for `getFlags` -- `featuresUpdated` hook is an alias for `flagsUpdated` - -If you are running with strict Content Security Policies active on your website, you will need change them as follows: - -- `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com` - -Finally, if you have customized the look & feel of the Feedback component, update `--bucket-feedback-*` CSS classes to `--reflag-feedback-*` - -## Flag toggles - -Reflag determines which flags are active for a given user/company. The user/company is given in the ReflagClient constructor. - -If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. -In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. - -Attributes cannot be nested (multiple levels) and must be either strings, integers or booleans. -Some attributes are special and used in Reflag UI: - -- `name` -- display name for `user`/`company`, -- `email` -- is accepted for `user`s and will be highlighted in the Reflag UI if available, -- `avatar` -- can be provided for both `user` and `company` and should be an URL to an image. - -```ts -const reflagClient = new ReflagClient({ - publishableKey, - user: { - id: "user_123", - name: "John Doe", - email: "john@acme.com" - avatar: "https://example.com/images/udsy6363" - }, - company: { - id: "company_123", - name: "Acme, Inc", - avatar: "https://example.com/images/31232ds" - }, -}); -``` - -To retrieve flags along with their targeting information, use `getFlag(key: string)`: - -```ts -const huddle = reflagClient.getFlag("huddle"); -// { -// isEnabled: true, -// config: { key: "zoom", payload: { ... } }, -// track: () => Promise -// requestFeedback: (options: RequestFeedbackData) => void -// } -``` - -You can use `getFlags()` to retrieve all enabled flags currently. - -```ts -const flags = reflagClient.getFlags(); -// { -// huddle: { -// isEnabled: true, -// targetingVersion: 42, -// config: ... -// } -// } -``` - -`getFlags()` is meant to be more low-level than `getFlag()` and it typically used -by down-stream clients, like the React SDK. - -Note that accessing `isEnabled` on the object returned by `getFlags` does not automatically -generate a `check` event, contrary to the `isEnabled` property on the object returned by `getFlag`. - -## End-user opt-in - -If a flag has end-user opt-in enabled in Reflag, you can list the opt-in options for the current context and set or cancel opt-in for the current user or company. - -```ts -const optInFlags = reflagClient.getOptInFlags(); -// [{ key, name, description, isEnabled, userOptedIn, companyOptedIn, isOptedIn }] - -try { - const response = await reflagClient.setOptIn("huddle", { - optedIn: true, // Use false to cancel this scope's opt-in. - scope: "user", // Use "company" to change the current company's opt-in. - }); - if (!response?.ok) { - console.error("Could not update opt-in"); - } -} catch (error) { - console.error("Could not update opt-in", error); -} -``` - -By default, `setOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. - -User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. - -`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and `flagsUpdated` listeners have been notified when flags change. - -The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. - -The `description` comes from the dedicated SDK-facing opt-in description configured in Reflag. +{% hint style="info" %} +**Protocol v2.** [Legacy v1 documentation](../../../legacy/v1/browser-sdk/README.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) -When using bootstrapped flags, the first `getOptInFlags()` or `getIsLoadingOptInFlags()` call requests a flags refresh. The list call returns the currently available list synchronously, and the loading getter returns `true` until that refresh succeeds or fails. Normal initialization also exposes loading through the client's state. +**Prerelease source documentation.** The installation examples target major 2; use them only when the matching SDK/CLI packages are available. A server rollout alone does not publish npm packages. -Listen for `optInFlagsLoadingUpdated` to update UI when this loading state changes. `flagsUpdated` is emitted when a successful refresh updates the list. +Generated from [`@reflag/browser-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk); SDK READMEs and code comments remain the source of truth. +{% endhint %} -If fetching opt-in metadata fails, loading ends without exposing an error. Call `reflagClient.refresh()` to retry. +# Reflag Browser SDK v2 -## Remote config +Client-side feature flags and JSON values for [Reflag](https://reflag.com). -Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. +> This is a breaking v2 prerelease. It requires the v2 evaluated-flags/check protocol on the server. Do not switch existing v1 applications or bootstrap consumers without coordinating that upgrade. Nothing in this branch publishes or deploys the SDK/server. -Similar to `isEnabled`, each flag has a `config` property. This configuration is managed from within Reflag. -It is managed similar to the way access to flags is managed, but instead of the binary `isEnabled` you can have -multiple configuration values which are given to different user/companies. +## Get started ```ts -const flags = reflagClient.getFlags(); -// { -// huddle: { -// isEnabled: true, -// targetingVersion: 42, -// config: { -// key: "gpt-3.5", -// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } -// } -// } -// } -``` - -`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. - -Just as `isEnabled`, accessing `config` on the object returned by `getFlags` does not automatically -generate a `check` event, contrary to the `config` property on the object returned by `getFlag`. - -## Server-side rendering and bootstrapping - -For server-side rendered applications, you can render immediately with pre-fetched flag data by bootstrapping the client. - -### Init options bootstrapped - -```typescript -type Configuration = { - logger: console; // by default only logs warn/error, by passing `console` you'll log everything - apiBaseUrl?: "https://front.reflag.com"; - credentials?: "include" | "same-origin" | "omit"; // forwarded to fetch requests; "include" also enables credentials for the default EventSource transport - feedback?: undefined; // See FEEDBACK.md - enableTracking?: true; // set to `false` to stop sending track events and user/company updates to Reflag servers. Useful when you're impersonating a user - offline?: boolean; // Use the SDK in offline mode. Offline mode is useful during testing and local development - bootstrappedState?: { - context: ReflagContext; - flags: FetchedFlags; - flagStateVersion?: number; - }; // Pre-fetched evaluated state from server-side (see Server-side rendering section) - bootstrappedFlags?: FetchedFlags; // Deprecated: use `bootstrappedState` instead -}; -``` - -### Using `bootstrappedState` - -Use the Node SDK's `getFlagsForBootstrap()` method to pre-fetch evaluated state server-side, then pass the returned object directly to the browser client: - -```typescript -// Server-side: Get bootstrapped state using Node SDK -import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; - -const serverClient = new ReflagNodeClient({ secretKey: "your-secret-key" }); -await serverClient.initialize(); - -const bootstrappedState = serverClient.getFlagsForBootstrap({ - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, -}); - -// Pass the bootstrapped state to the client using your framework's preferred method -app.get("/", (req, res) => { - res.set("Content-Type", "text/html"); - res.send( - Buffer.from( - ` -
`, - ), - ); -}); - -// Client-side: Initialize with pre-fetched evaluated state import { ReflagClient } from "@reflag/browser-sdk"; -const reflagClient = new ReflagClient({ +const reflag = new ReflagClient({ publishableKey: "your-publishable-key", - bootstrappedState, // Contains context, flags, and optional flagStateVersion -}); - -await reflagClient.initialize(); -const { isEnabled } = reflagClient.getFlag("huddle"); -``` - -The `bootstrappedState` object contains: - -- `context`: the evaluation context used on the server -- `flags`: the evaluated raw flags -- `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping - -If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. - -If a bootstrapped application requests opt-in flags, the browser SDK performs one flags refresh. Applications that do not request opt-in data do not make this request. - -If you previously used `bootstrappedFlags`, migrate like this: - -```typescript -// Before -const { flags } = serverClient.getFlagsForBootstrap(context); -const client = new ReflagClient({ - publishableKey, - user: context.user, - company: context.company, - other: context.other, - bootstrappedFlags: flags, + user: { id: "alice", role: "manager" }, + company: { id: "acme", plan: "enterprise" }, }); +await reflag.initialize(); -// After -const bootstrappedState = serverClient.getFlagsForBootstrap(context); -const client = new ReflagClient({ - publishableKey, - bootstrappedState, -}); -``` - -{% hint style="info" %} -After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. - -Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. -{% endhint %} - -This eliminates loading states and removes the initial render's dependency on the flags API. +const enabled = reflag.getFlag("huddles"); // boolean, implicit false +const settings = reflag.getFlag("assistant-settings", { model: "quick" }); +// settings: { model: string } -## Context management - -### Updating user/company/other context - -Attributes given for the user/company/other context in the ReflagClient constructor can be updated for use in flag targeting evaluation with the `updateUser()`, `updateCompany()` and `updateOtherContext()` methods. -They return a promise which resolves once the flags have been re-evaluated follow the update of the attributes. - -{% hint style="info" %} -{% endhint %} - -### setContext() - -The `setContext()` method allows you to replace the entire context (user, company, and other attributes) at once. This method is useful when you need to completely change the context, such as when a user logs in or switches between different accounts. - -```ts -await reflagClient.setContext({ - user: { - id: "new-user-123", - name: "Jane Doe", - email: "jane@example.com", - role: "admin", - }, - company: { - id: "company-456", - name: "New Company Inc", - plan: "enterprise", - }, - other: { - feature: "beta", - locale: "en-US", - }, -}); +if (enabled) { + // Application usage tracking is separate from reading the flag. + await reflag.track("Started huddle"); +} ``` -The method will: - -- Replace the entire context with the new values -- Re-evaluate all flags based on the new context -- Update the user and company information on Reflag servers -- Return a promise that resolves once the flags have been re-evaluated +Use only a **publishable** key in a browser. Secret keys belong on your server. -### getContext() - -The `getContext()` method returns the current context being used for flag evaluation. This is useful for debugging or when you need to inspect the current user, company, and other attributes. +## Direct-value reads ```ts -const currentContext = reflagClient.getContext(); -console.log(currentContext); -// { -// user: { id: "user-123", name: "John Doe", email: "john@example.com" }, -// company: { id: "company-456", name: "Acme Inc", plan: "enterprise" }, -// other: { locale: "en-US", feature: "beta" } -// } +reflag.getFlag("release"); // boolean; missing/mismatched -> false +reflag.getFlag("model", "quick"); // string +reflag.getFlag("limit", 10); // number +reflag.getFlag("settings", { model: "quick" }); +reflag.getFlag("nullable-settings", null); // FlagValue (arbitrary JSON) ``` -The returned context object contains: +- Defaults are positional JSON values; generation is not required for useful types. Primitive literals widen, and readonly defaults are accepted. +- A non-null default accepts only the same **top-level JSON category**: Boolean, number, string, array or object. A mismatch warns without logging the payload and returns the default. A bare read can never return a truthy object. +- Explicit `null` accepts any JSON value, including authored null. Missing values return null. +- Falsy selected values (`false`, `0`, `""`, null) are preserved when accepted by the requested category. +- Object fields and array elements are **not schema-validated**. Validate untrusted/nested payloads in your application. +- Values and defaults are returned as independent mutable copies. There are no reserved JSON property names. -- `user`: Current user attributes (if any) -- `company`: Current company attributes (if any) -- `other`: Additional context attributes not related to user or company +`getFlags()` returns a direct-value record (entries may be undefined) and registers checks for its returned roots. `getFlagResults()` returns owned evaluated diagnostics **without checks**; it is intended for tooling, not ordinary application reads. `getFlagsForBootstrap()` serializes protocol-v2 evaluated state without checks. -## Toolbar +## Checks and delivery -The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off. +Calling a getter registers a requested-root check immediately, even if its return value is ignored. There are no `.isEnabled`, `.config`, `.value` or flag `.track()` wrappers. Delivery remains buffered through `/bulk` and identity-aware rate-limited. -Toolbar screenshot +A selected check carries the authored selected key as `evalResult`, its `sourceVersionId` and the available snapshot `flagStateVersion`. Payload equality is not identity: equal-valued selections or segment-only snapshot changes remain distinguishable on subsequent reads. Defaults, category mismatches, local overrides and static fallback values do not fabricate authored selections. Diagnostics and bootstrap serialization generate no checks. The server evaluates dependencies; fetching their results does not itself register reads. -The toolbar will automatically appear on `localhost`. However, it can also be incredibly useful in production. -You have full control over when it appears through the `toolbar` configuration option passed to the `ReflagClient`. +`enableTracking: false` disables checks and user/company/usage tracking. `offline: true` skips HTTP and tracking. `await reflag.stop()` flushes buffered events and closes the client's background transports. -You can pass a simple boolean to force the toolbar to appear/disappear: +## Context, refresh and cache -```typescript -const client = new ReflagClient({ - // show the toolbar even in production if the user is an internal/admin user - toolbar: user?.isInternal, - ... +```ts +await reflag.updateUser({ role: "admin" }); +await reflag.updateCompany({ plan: "enterprise" }); +await reflag.updateOtherContext({ region: "eu" }); +await reflag.setContext({ + user: { id: "bob" }, + company: { id: "other-company" }, }); +await reflag.refresh(); ``` -You can also configure the position of the toolbar on the screen: - -```typescript -const client = new ReflagClient({ - toolbar: { - show: true; - position: { - placement: "bottom-left", - offset: {x: "1rem", y: "1rem"} - } - } - ... -}) -``` - -See [the reference](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions) for details. - -## Qualitative feedback on beta flags - -Reflag can collect qualitative feedback from your users in the form of a [Customer Satisfaction Score](https://en.wikipedia.org/wiki/Customer_satisfaction) and a comment. +`setContext()` replaces the context; update methods shallow-merge their section. User/company sections require IDs, including valid numeric zero. Context supports nested JSON and arrays. A context change clears the old context's values while fetching; stale/in-flight responses cannot replace a newer context or snapshot. -### Automated feedback collection +Values come from `GET /flags/evaluated`, not legacy `/features/evaluated`. Server evaluation retains the complete internal graph and authorized public roots. The Browser SDK does not cache dependency evaluations of its own. -The Reflag Browser SDK comes with automated feedback collection mode enabled by default, which lets the Reflag service ask your users for feedback for relevant flags just after they've used them. +Constructor options include: -{% hint style="info" %} -To get started with automatic feedback collection, make sure you've set `user` in the `ReflagClient` constructor. -{% endhint %} - -Automated feedback surveys work even if you're not using the SDK to send events to Reflag. -It works because the Reflag Browser SDK maintains a live connection to Reflag's servers and can automatically show a feedback prompt whenever the Reflag servers determines that an event should trigger a prompt - regardless of how this event is sent to Reflag. - -You can find all the options to make changes to the default behavior in the [Reflag feedback documentation](../../documents/browser-sdk/FEEDBACK.md). - -### Reflag feedback UI +| Option | Behavior | +| ------------------------------- | --------------------------------------------------------------------------- | +| `apiBaseUrl`, `appBaseUrl` | API origin and toolbar/feedback links | +| `credentials` | Fetch credentials mode; `include` also enables default SSE credentials | +| `timeoutMs` | Flag request timeout; default 5,000 ms | +| `staleTimeMs` | Fresh-cache duration; default 0 | +| `staleWhileRevalidate` | Serve stale cached state while revalidating; default false | +| `expireTimeMs` | Cache expiry; default 30 days | +| `storage` | Optional async storage adapter | +| `fallbackFlags` | Value record or array of enabled Boolean keys, without authored provenance | +| `enableLiveFlagUpdates` | Refresh after SSE publications; default false in Browser, true in React/Vue | +| `eventSourceFactory` | Optional EventSource-compatible transport | +| `trackingQueue` | Buffered-delivery `flushDelayMs` and `maxSize` | +| `logger`, `toolbar`, `feedback` | Logging, Boolean override toolbar and feedback options | -Reflag can assist you with collecting your user's feedback by offering a pre-built UI, allowing you to get started with minimal code and effort. +Evaluated cache and override storage use isolated v2 keys. V1 cache entries are never interpreted as v2 values. Malformed refreshes leave known-good state intact. Valid saved v2 selections retain their real provenance on restore. There is no automatic periodic HTTP fallback after an SSE failure; manual refresh/context updates remain available. -[Read the Reflag feedback UI documentation](../../documents/browser-sdk/FEEDBACK.md) - -### Reflag feedback SDK - -Feedback can be submitted to Reflag using the SDK: +## Overrides and toolbar ```ts -reflagClient.feedback({ - flagKey: "my-flag-key", // String (required), copy from Flag feedback tab - score: 5, // Number: 1-5 (optional) - comment: "Absolutely stellar work!", // String (optional) -}); +reflag.setFlagOverride("release", true); +reflag.setFlagOverride("settings", { model: "local" }); +reflag.setFlagOverride("nullable-settings", null); // a real null override +reflag.setFlagOverride("release", undefined); // clear the override ``` -### Reflag feedback API - -If you are not using the Reflag Browser SDK, you can still submit feedback using the HTTP API. +Overrides apply after server evaluation and do not rewrite authored dependency results. The built-in toolbar appears on localhost by default and offers Boolean overrides only. It uses diagnostic access, so opening it does not register application checks. -See details in [Feedback HTTP API](https://docs.reflag.com/api/http-api#post-feedback) +## Server bootstrap -## Tracking flag usage - -The `track` function lets you send events to Reflag to denote flag usage. -By default Reflag expects event names to align with the flag keys, but -you can customize it as you wish. +Generate the full payload with **Node SDK v2** on your server: ```ts -reflagClient.track("huddle", { voiceHuddle: true }); +const bootstrappedState = serverClient.getFlagsForBootstrap(context); +// Send via your framework's safe JSON/hydration mechanism. ``` -## Event listeners - -Event listeners allow for capturing various events occurring in the `ReflagClient`. This is useful to build integrations with other system or for various debugging purposes. The available events are: - -- `check`: Your code used `isEnabled` or `config` for a flag -- `flagsUpdated`: Flags were updated. Either because they were loaded as part of initialization or because the user/company updated -- `optInFlagsLoadingUpdated`: The opt-in flag loading state changed -- `user`: User information updated (similar to the `identify` call used in tracking terminology) -- `company`: Company information updated (sometimes to the `group` call used in tracking terminology) -- `track`: Track event occurred. - -Use the `on()` method to add an event listener to respond to certain events. See the API reference for details on each hook. - ```ts -import { ReflagClient, CheckEvent, RawFlags } from "@reflag/browser-sdk"; - -const client = new ReflagClient({ - // options -}); - -// or add the hooks after construction: -const unsub = client.on("check", (check: CheckEvent) => - console.log(`Check event ${check}`), -); -// use the returned function to unsubscribe, or call `off()` with the same arguments again -unsub(); +const reflag = new ReflagClient({ publishableKey, bootstrappedState }); +await reflag.initialize(); +const enabled = reflag.getFlag("release"); ``` -## Zero PII +The payload includes `protocolVersion: 2`, context, evaluated diagnostics/selections and an optional snapshot version. V1 payloads and the old `bootstrappedFlags` option are rejected. Preserve the entire envelope; do not pass just its `flags` property. A version is required for bootstrapped live updates. Never embed secrets or server-only context in public bootstrap data. Later refreshes use browser-visible context and can differ from server-only evaluation; disable live updates when that is inappropriate. -The Reflag Browser SDK doesn't collect any metadata and HTTP IP addresses are _not_ being stored. - -For tracking individual users, we recommend using something like database ID as userId, as it's unique and doesn't include any PII (personal identifiable information). If, however, you're using e.g. email address as userId, but prefer not to send any PII to Reflag, you can hash the sensitive data before sending it to Reflag: +## End-user opt-in ```ts -import reflag from "@reflag/browser-sdk"; -import { sha256 } from "crypto-hash"; - -reflag.user(await sha256("john_doe")); +const options = reflag.getOptInFlags(); +const loading = reflag.getIsLoadingOptInFlags(); +await reflag.setOptIn("huddles", { optedIn: true }); +await reflag.setOptIn("huddles", { optedIn: false, scope: "company" }); ``` -## Use of cookies - -The Reflag Browser SDK uses a couple of cookies to support automated feedback surveys. These cookies are not used for tracking purposes and thus should not need to appear in cookie consent forms. - -The two cookies are: - -- `reflag-prompt-${userId}`: store the last automated feedback prompt message ID received to avoid repeating surveys -- `reflag-token-${userId}`: caching a token used to connect to Reflag's live messaging infrastructure that is used to deliver automated feedback surveys in real time. - -## TypeScript - -Types are bundled together with the library and exposed automatically when importing through a package manager. - -## Content Security Policy (CSP) +The list contains presentation/membership metadata (`key`, `name`, `description`, `isEnabled`, `userOptedIn`, `companyOptedIn`, `isOptedIn`); this is not the ordinary flag getter API. User/company grants remain independent. The selected scope requires its ID. Successful mutations wait for versioned evaluation and membership confirmation. -If you are running with strict Content Security Policies active on your website, you will need to enable these directives in order to use the SDK: +Metadata arrives with ordinary `/flags/evaluated` responses and is cached with the evaluated snapshot. Bootstrapped clients whose snapshot lacks metadata fetch it on demand from the same v2 endpoint, without replacing server-derived values or provenance with browser-context evaluations. Loading settles on success or failure, including an empty list. Opt-in mutations confirm values and membership together in one versioned refresh. `optInFlagsLoadingUpdated` and `flagsUpdated` support UI subscriptions. -| Directive | Values | Reason | -| ----------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | -| connect-src | [https://front.reflag.com](https://front.reflag.com) | API requests plus Server-Sent Events for live flag updates and automated feedback surveys. | -| style-src | 'unsafe-inline' | The feedback UI is styled with inline styles. Not having this directive results unstyled HTML elements. | +## Tracking, feedback and events -If you are including the Reflag tracking SDK with a ` - - - -``` - -If using Nuxt, wrap `` in ``. `` only renders client-side currently. - -### 2. Use `useFlag get flag status - -```vue - - - -``` - -See [useFlag()](#useflag) for a full example - -## Setting context - -Reflag determines which flags are active for a given `user`, `company`, or `other` context. -You can pass these to the `ReflagProvider` using the `context` prop. - -### Using the `context` prop - -```vue - - - -``` - -### Legacy individual props (deprecated) - -For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version: - -```vue - - - -``` - -> [!Important] -> The `user`, `company`, and `otherContext` props are deprecated. Use the `context` prop instead, which provides the same functionality in a more structured way. - -### Context requirements - -If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. -In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. -Attributes which are not properties of the `user` or `company` can be supplied using the `other` property. - -Attributes cannot be nested (multiple levels) and must be either strings, numbers or booleans. -A number of special attributes exist: - -- `name` -- display name for `user`/`company`, -- `email` -- the email of the user, -- `avatar` -- the URL for `user`/`company` avatar image. - -To retrieve flags along with their targeting information, use `useFlag(key: string)` hook (described in a section below). - -Note that accessing `isEnabled` on the object returned by `useFlag()` automatically -generates a `check` event. - -## Remote config - -Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. - -Similar to `isEnabled`, each flag accessed using the `useFlag()` hook, has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the -binary `isEnabled` you can have multiple configuration values which are given to different user/companies. - -### Get started with Remote config - -```ts -const { - isEnabled, - config: { key, payload }, -} = useFlag("huddles"); - -// isEnabled: true, -// key: "gpt-3.5", -// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } -``` - -`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. - -Note that, similar to `isEnabled`, accessing `config` on the object returned by `useFlag()` automatically -generates a `check` event. - -## `` component - -The `` initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props: - -- `publishableKey` is used to connect the provider to an _environment_ on Reflag. Find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag, -- `context`: An object containing `user`, `company`, and `other` properties that make up the evaluation context used to determine if a flag is enabled or not. `company` and `user` contexts are automatically transmitted to Reflag servers so the Reflag app can show you which companies have access to which flags etc. -- `company`, `user` and `otherContext` (deprecated): Individual props for context. These are deprecated in favor of the `context` prop and will be removed in the next major version. - - > [!Note] - > If you specify `company` and/or `user` they must have at least the `id` property, otherwise they will be ignored in their entirety. You should also supply anything additional you want to be able to evaluate flag targeting against, - -- `timeoutMs`: Timeout in milliseconds when fetching flags from the server, -- `staleWhileRevalidate`: If set to `true`, stale flags will be returned while refetching flags in the background, -- `expireTimeMs`: If set, flags will be cached between page loads for this duration (in milliseconds), -- `staleTimeMs`: Maximum time (in milliseconds) that stale flags will be returned if `staleWhileRevalidate` is true and new flags cannot be fetched. - -- `enableTracking`: Set to `false` to stop sending tracking events and user/company updates to Reflag. Useful when you're impersonating a user (defaults to `true`), -- `apiBaseUrl`: Optional base URL for the Reflag API. This also controls the SSE origin used for live flag updates and automated feedback, -- `credentials`: Optional fetch credentials mode. Set to `"include"` when proxying through your backend and authenticating with cookies; this also enables credentials for live-update SSE connections. -- `appBaseUrl`: Optional base URL for the Reflag application. Use this to override the default app URL, - -- `debug`: Set to `true` to enable debug logging to the console. If both `logger` and `debug` are provided, `logger` takes precedence, -- `logger`: Optional custom logger implementation (`debug`, `info`, `warn`, `error`) used by the underlying client, -- `toolbar`: Optional [configuration](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions) for the Reflag toolbar, -- `feedback`: Optional configuration for feedback collection - -### Loading states - -ReflagProvider lets you define a template to be shown while ReflagProvider is initializing: - -```vue ``` -If you want more control over loading screens, `useIsLoading()` returns a `Ref` which you can use to customize the loading experience. - -## `` component +Provider options forward Browser settings, including cache/storage, fallback values, offline/tracking, feedback, toolbar, credentials and API origins. `logger` takes precedence over `debug`. Live updates default to true; disable with `:enable-live-flag-updates="false"`. For an ordinary client-only Nuxt provider, wrap it in ``. -The `` component is a specialized version of `ReflagProvider` designed for server-side rendering and preloaded flag scenarios. It uses pre-fetched flags for the initial render, resulting in faster initial page loads and better SSR compatibility. - -### Usage +## `useFlag(key, defaultValue?)` ```vue - - -``` - -### Getting bootstrapped flags - -You'll typically generate the `bootstrappedFlags` object on your server using the Node.js SDK or by fetching from the Reflag API. Pass the full object returned by `getFlagsForBootstrap()` directly to ``. It contains: - -- `context`: the evaluation context used on the server -- `flags`: the evaluated raw flags -- `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping - -If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. - -With `ReflagBootstrappedProvider`, `useOptInFlags()` requests a flags refresh on first use. It reports `isLoading: true` until that refresh settles. - -Here's an example using the Node.js SDK: - -```js -// server.js (Node.js/SSR) -import { ReflagClient } from "@reflag/node-sdk"; - -const client = new ReflagClient({ - secretKey: "your-secret-key", // Use secret key on server -}); -await client.initialize(); - -// Fetch flags for specific context -const context = { - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, -}; - -const bootstrappedFlags = client.getFlagsForBootstrap(context); - -// Pass to your Vue app -``` +import { useFlag, useIsLoading, useTrack } from "@reflag/vue-sdk"; -### ReflagBootstrappedProvider Props - -`ReflagBootstrappedProvider` accepts all the same props as `ReflagProvider` except: - -- `flags`: The pre-fetched bootstrapped state object containing `context`, evaluated `flags`, and an optional `flagStateVersion` -- All other props available in `ReflagProvider` are supported except `context`, `user`, `company`, and `otherContext` (which are extracted from `flags.context`) - -If the `flags` prop is not provided or is undefined, the provider will not initialize the client and will render in a non-loading state. - -{% hint style="info" %} -After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. - -Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. -{% endhint %} - -## `` component - -The `` is a lower-level component that accepts a pre-initialized `ReflagClient` instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application. - -### ReflagClientProvider Usage - -```vue - ``` -### ReflagClientProvider Props +Vue unwraps refs in templates; use `.value` in script. This is a **Vue ref**, not a flag wrapper. There are no `.isEnabled`, `.config`, flag `.track()` or flag loading fields. -The `ReflagClientProvider` accepts the following props: - -- `client`: A pre-initialized `ReflagClient` instance +```ts +useFlag("release"); // ShallowRef +useFlag("model", "quick"); // ShallowRef +useFlag("limit", 10); // ShallowRef +useFlag("settings", { model: "quick" }); // ShallowRef<{ model: string }> +useFlag("nullable-settings", null); // ShallowRef +``` -### Slots +Defaults are positional JSON; literals widen without generated types. Non-null defaults require the same top-level category (Boolean/number/string/array/object), otherwise the default is returned with a payload-safe warning. Null explicitly accepts arbitrary JSON, including authored null; missing returns null. Valid false/zero/empty strings are preserved. Nested payload schemas are not validated by the SDK. Returned values/defaults are independent copies; readonly defaults are accepted. -- `loading`: Optional slot to show while the client is initializing (same as `ReflagProvider`) +The ref updates when evaluated flags change. A composable read registers the requested root through the Browser SDK, even if its result is ignored; refresh-driven rereads are identity-aware rate-limited and delivered in batches. Diagnostics/bootstrap inspection register none. Checks carry genuine selected key/source/snapshot identity, never payloads or invented selections for defaults/overrides. -> [!Note] -> Most applications should use `ReflagProvider` or `ReflagBootstrappedProvider` instead of `ReflagClientProvider`. Only use this component when you need the advanced control it provides. +## Loading, context and client access -## Hooks +- `useIsLoading()` returns a Boolean ref for provider loading; the `#loading` slot and `initialLoading` control initial presentation. +- `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return async shallow-update functions. +- `useClient()` exposes the Browser client, including `setContext(context)`, `refresh()` and `setFlagOverride(key, value)`. Undefined clears an override; null is a JSON override. +- `getFlags()` returns direct values and registers returned-root checks. Use `getFlagResults()` for tooling without checks. +- `useOnEvent(type, handler, client?)` subscribes on mount and unsubscribes on unmount. An external client may be supplied explicitly. -### `useFlag()` +A context change clears old values while fetching. Late responses for previous contexts or lower snapshot versions cannot replace accepted state. V2 cache/override storage is isolated from v1. Browser fetching uses `/flags/evaluated` and never re-evaluates/caches dependencies locally. -Returns the state of a given flag for the current context. The composable provides access to flags and their configurations. +## Bootstrap -`useFlag()` returns an object with this shape: +On the server, use Node SDK v2 and your framework's safe serialization mechanism: ```ts -{ - isEnabled: boolean, // is the flag enabled - track: () => void, // send a track event when the flag is used - requestFeedback: (...) => void // open up a feedback dialog - config: {key: string, payload: any}, // remote configuration for this flag - isLoading: boolean // if you want to manage loading state at the flag level -} +const flags = serverClient.getFlagsForBootstrap(context); ``` -Example: - ```vue - - - + + + ``` -See the reference docs for details. +Pass the entire envelope (`protocolVersion: 2`, context, evaluated flags and optional snapshot version). Legacy v1 bootstrap is rejected. A snapshot version is required for live updates. Never expose secret keys/server-only attributes in bootstrap data; later refreshes use browser-visible context, so disable live updates when they must not replace server-only evaluations. -### `useOptInFlags()` and `useSetOptIn()` +`ReflagClientProvider` accepts an externally initialized Browser v2 client. Its lifecycle belongs to the application. -Use these composables to build an end-user opt-in UI for flags where opt-in is enabled in Reflag. +## Opt-in, tracking and feedback -```vue - - - -``` - -By default, `useSetOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. - -User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. - -`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and subscribers have been notified when flags change. Vue may not have committed the resulting render yet. - -The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. - -`useOptInFlags()` returns `{ flags, isLoading }`, where both values are computed refs. With `ReflagBootstrappedProvider`, it fetches opt-in metadata on first use and reports `isLoading: true` until that refresh succeeds or fails. - -If fetching opt-in metadata fails, loading ends without exposing an error. Call `client.refresh()` on the client returned by `useClient()` to retry. - -With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal initial flags request, so `useOptInFlags().isLoading` remains `false`. Use the general `useIsLoading()` composable or the provider's loading slot for that initial loading state. - -### `useTrack()` - -`useTrack()` returns a function which lets you send custom events to Reflag. It takes a string argument with the event name and optionally an object with properties to attach the event. - -Using `track` returned from `useFlag()` calls this track function with the flag key as the event name. - -```vue - - - -``` - -### `useRequestFeedback()` - -Returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features. - -See [Automated Feedback Surveys](https://docs.reflag.com/product-handbook/live-satisfaction) for how to do this automatically, without code. - -When using the `useRequestFeedback` you must pass the flag key to `requestFeedback`. -The example below shows how to use `position` to ensure the popover appears next to the "Give feedback!" button. - -```vue - - - -``` - -See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/FEEDBACK.md#manual-feedback-collection) for more information on `requestFeedback` options. - -### `useSendFeedback()` - -Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag. - -```vue - - - +await sendFeedback({ flagKey: "huddles", score: 5 }); ``` -### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` +Opt-in metadata arrives with ordinary `/flags/evaluated` responses. Bootstrapped providers fetch missing metadata on demand from the same v2 endpoint without replacing server-derived values or provenance; loading settles on success or failure. User/company grants remain independent; successful mutations confirm versioned evaluation and membership in a single refresh. The metadata list retains presentation/membership fields such as `isEnabled`; ordinary reads remain direct values. -These composables return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session. +`enableTracking: false` disables checks and ordinary tracking. Offline mode skips HTTP/tracking. See [Browser feedback documentation](../../../supported-languages/browser-sdk/feedback.md) for prompting/UI options. -```vue - - - -``` - -Note: To change the `user.id` or `company.id`, you need to update the props passed to `ReflagProvider` instead of using these composables. - -### `useClient()` - -Returns the `ReflagClient` used by the `ReflagProvider`. The client offers more functionality that -is not directly accessible through the other composables. - -```vue - - - -``` - -### `useIsLoading()` - -Returns a `Ref` to indicate if Reflag has finished loading. -Initially, the value will be `true` if no bootstrap flags have been provided and the client has not be initialized. - -```vue - - - -``` +## Optional key registration and migration -### `useOnEvent()` - -Vue composable for listening to Reflag client events. This composable automatically handles mounting and unmounting of event listeners. - -Available events include: - -- `flagsUpdated`: Triggered when flags are updated -- `track`: Triggered when tracking events are sent -- `feedback`: Triggered when feedback is sent - -```vue - - - -``` - -You can also provide a specific client instance if needed: - -```vue - - - +```ts +import "@reflag/vue-sdk"; +declare module "@reflag/vue-sdk" { + interface Flags { + huddles: boolean; + "huddle-settings": { maxParticipants: number }; + } +} ``` -## Content Security Policy (CSP) - -See [CSP](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/README.md#content-security-policy-csp) for info on using Reflag React SDK with CSP - -## License - -MIT License +Registration constrains keys and checks non-null defaults against the registered value schema, including required and nested properties. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request; bare/`undefined` reads remain Boolean refs. Positional defaults still determine widened direct-value types, and generated declarations do not add nested runtime validation. The v2 CLI generates these schemas from current production-environment variants with `--format vue`; regenerate old wrapper declarations when migrating. -Copyright (c) 2025 Bucket ApS +Replace `const { isEnabled } = useFlag(key)` with `const enabled = useFlag(key)` (then `enabled.value` in script). Replace remote-config wrappers with separately authored multivariate flags and positional defaults, and move usage/feedback into their separate composables. Bootstrap both ends with v2. This branch does not publish SDKs or deploy the required server changes. diff --git a/sdk/@reflag/vue-sdk/globals.md b/sdk/@reflag/vue-sdk/globals.md index 0ae59b1..f581925 100644 --- a/sdk/@reflag/vue-sdk/globals.md +++ b/sdk/@reflag/vue-sdk/globals.md @@ -13,13 +13,21 @@ pagination: visible: true --- +{% hint style="info" %} +**Protocol v2.** [Legacy v1 documentation](../../../legacy/v1/vue-sdk/globals.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) + +**Prerelease source documentation.** The installation examples target major 2; use them only when the matching SDK/CLI packages are available. A server rollout alone does not publish npm packages. + +Generated from [`@reflag/vue-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/vue-sdk); SDK READMEs and code comments remain the source of truth. +{% endhint %} + # @reflag/vue-sdk ## Interfaces ### CheckEvent -Event representing checking the flag evaluation result +A root read records selection identity, never its JSON payload. #### Properties @@ -28,7 +36,6 @@ Event representing checking the flag evaluation result Property Type -Description @@ -40,53 +47,38 @@ Event representing checking the flag evaluation result -`"check-is-enabled"` \| `"check-config"` - - - - -`check-is-enabled` means `isEnabled` was checked, `check-config` means `config` was checked. +`"check"` - `evaluationErrors?` - - - - -\{ `code`: `string`; `field`: `string`; `message`: `string`; `operator`: `string`; \}[] + `evalContext?` -Non-fatal diagnostics produced while evaluating the flag. +[`ReflagContext`](../../../supported-languages/browser-sdk/globals.md#reflagcontext) - `key` - - - - -`string` + `evalErrors?` -Flag key. +[`EvaluationError`](../../../supported-languages/browser-sdk/globals.md#evaluationerror)[] - ~~`missingContextFields?`~~ + `evalMissingFields?` @@ -94,66 +86,64 @@ Flag key. `string`[] + + -Missing context fields. + `evalResult?` -**Deprecated** + + -Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. +`string` - `ruleEvaluationResults?` + `evalRuleResults?` `boolean`[] - - - -Rule evaluation results. - - `value?` + `flagStateVersion?` - \| `boolean` \| \{ `key`: `string`; `payload`: `any`; \} +`number` + + -Result of flag or configuration evaluation. -If `action` is `check-is-enabled`, this is the result of the flag evaluation and `value` is a boolean. -If `action` is `check-config`, this is the result of the configuration evaluation. + `key` - - - `version?` +`string` + + -`number` + `sourceVersionId?` -Version of targeting rules. +`string` @@ -224,127 +214,6 @@ Company name *** -### Flag\ - -#### Type Parameters - - - - - - - - - - - - - - -
Type ParameterDefault type
- -`TConfig` *extends* [`FlagType`](globals.md#flagtype)\[`"config"`\] - - - -[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) - -
- -#### Properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyType
- - `config` - - - -`Ref`\< \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| \{ `key`: `string`; \} & `TConfig`, \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| \{ `key`: `string`; \} & `TConfig`\> - -
- - `isEnabled` - - - -`Ref`\<`boolean`, `boolean`\> - -
- - `isLoading` - - - -`Ref`\<`boolean`, `boolean`\> - -
- - `key` - - - -`string` - -
- - `requestFeedback` - - - -(`opts`: [`RequestFlagFeedbackOptions`](globals.md#requestflagfeedbackoptions)) => `void` - -
- -#### Methods - -##### track() - -```ts -track(): - | undefined - | Promise< - | undefined -| Response> -``` - -###### Returns - - \| `undefined` - \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< - \| `undefined` - \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> - -*** - ### Flags *** @@ -431,137 +300,68 @@ User name ### BootstrappedFlags ```ts -type BootstrappedFlags = BootstrappedState & { - flags: RawFlags; -}; +type BootstrappedFlags = BootstrappedState; ``` -#### Type declaration - - - - - - - - - - - - - - -
NameType
- -`flags` - - - -[`RawFlags`](../browser-sdk/globals.md#rawflags) - -
- *** -### EmptyFlagRemoteConfig +### FlagDefaultValue ```ts -type EmptyFlagRemoteConfig = { - key: undefined; - payload: undefined; -}; +type FlagDefaultValue = + | null + | boolean + | number + | string + | readonly FlagDefaultValue[] +| {}; ``` -#### Type declaration - - - - - - - - - - - - - - - - - - -
NameType
- - `key` - - - -`undefined` - -
- - `payload` - - +*** -`undefined` +### FlagKey -
+```ts +type FlagKey = keyof Flags extends never ? string : Extract; +``` *** -### FlagKey +### FlagValue ```ts -type FlagKey = keyof TypedFlags; +type FlagValue = + | null + | boolean + | number + | string + | FlagValue[] +| {}; ``` *** -### FlagType +### FlagValueFromDefault\ ```ts -type FlagType = { - config: { - payload: any; - }; -}; +type FlagValueFromDefault = T extends null ? FlagValue : T extends boolean ? boolean : T extends number ? number : T extends string ? string : T extends readonly infer Element[] ? [Element] extends [never] ? FlagValue[] : FlagValueFromDefault[] : T extends object ? { -readonly [Key in keyof T]: FlagValueFromDefault } : never; ``` -#### Type declaration +Widen literals and return mutable copies. Null requests arbitrary JSON. + +#### Type Parameters - - + - - - - - @@ -578,12 +378,6 @@ type OptInFlag = Omit & { }; ``` -An opt-in-enabled flag for the generated Vue SDK flag definitions. - -Includes all fields from [BrowserOptInFlag](../browser-sdk/globals.md#optinflag): `name`, `description`, -`isEnabled`, `userOptedIn`, `companyOptedIn`, and `isOptedIn`. -Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. - #### Type declaration
NameTypeType Parameter
- `config`? - - - -\{ - `payload`: `any`; - \} - -
- -`config.payload` - - - -`any` +`T`
@@ -602,7 +396,7 @@ Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. @@ -678,7 +472,7 @@ Set to `true` to show the loading component while the client is initializing. @@ -1047,7 +841,7 @@ type TrackEvent = { @@ -1059,7 +853,7 @@ type TrackEvent = { ### TypedFlags ```ts -type TypedFlags = keyof Flags extends never ? Record : { [TypedFlagKey in keyof Flags]: Flags[TypedFlagKey] extends FlagType ? Flag : Flag }; +type TypedFlags = keyof Flags extends never ? Record : { [Key in keyof Flags]: Flags[Key] | undefined }; ``` *** @@ -1091,14 +885,14 @@ type UseOptInFlagsResult = { @@ -1360,7 +1268,7 @@ The event to listen to. @@ -1529,7 +1434,7 @@ A function that sends feedback to the Reflag SDK. The function accepts: @@ -1568,11 +1473,6 @@ function useSetOptIn(): (key: string, options: SetOptInOptions) => Promise< Vue composable for setting whether the current user or company has opted into a flag. -Check the returned Response's `ok` property and catch promise rejections. -HTTP failures return a non-OK Response; offline mode, invalid arguments, or -missing scoped context return undefined. Confirmation failures can reject -after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sdk/globals.md#setoptin). - #### Returns `Function` @@ -1607,7 +1507,7 @@ after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sd @@ -1625,7 +1525,7 @@ after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sd ### useTrack() ```ts -function useTrack(): (eventName: string, attributes?: +function useTrack(): (eventName: string, attributes?: | null | Record) => Promise< | undefined @@ -1886,8 +1786,8 @@ updateUser({ id: "123", name: "John Doe" }); ### ReflagClientProvider -Renames and re-exports [ReflagBootstrappedProvider](globals.md#reflagbootstrappedprovider) +Renames and re-exports [ReflagBootstrappedProvider](../../../supported-languages/vue-sdk/globals.md#reflagbootstrappedprovider) ### ReflagProvider -Renames and re-exports [ReflagBootstrappedProvider](globals.md#reflagbootstrappedprovider) +Renames and re-exports [ReflagBootstrappedProvider](../../../supported-languages/vue-sdk/globals.md#reflagbootstrappedprovider) diff --git a/sdk/documents/browser-sdk/FEEDBACK.md b/sdk/documents/browser-sdk/FEEDBACK.md index 25ea4a0..79e7a4d 100644 --- a/sdk/documents/browser-sdk/FEEDBACK.md +++ b/sdk/documents/browser-sdk/FEEDBACK.md @@ -13,6 +13,14 @@ pagination: visible: true --- +{% hint style="info" %} +**Protocol v2.** [Legacy v1 documentation](../../../legacy/v1/browser-sdk/feedback.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) + +**Prerelease source documentation.** The installation examples target major 2; use them only when the matching SDK/CLI packages are available. A server rollout alone does not publish npm packages. + +Generated from [`@reflag/browser-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk); SDK READMEs and code comments remain the source of truth. +{% endhint %} + # Reflag Feedback UI The Reflag Browser SDK includes a UI you can use to collect feedback from user @@ -282,7 +290,7 @@ See examples below. ![image](https://github.com/reflagcom/javascript/assets/331790/68805b38-e9f6-4de5-9f55-188216983e3c) -See [default English localization keys](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) +See [default English localization keys](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) for a reference of what translation keys can be supplied. ### Static language configuration @@ -396,7 +404,7 @@ For example, a dark mode theme might look like this: } ``` -Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/src/feedback/ui/index.css). +Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk/src/feedback/ui/index.css). ## Using your own UI to collect feedback @@ -421,7 +429,7 @@ Reflag API. ### Manual feedback collection with custom UI Examples of a HTML-form that collects the relevant data can be found -in [feedback.html](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/example/feedback/Feedback.jsx). +in [feedback.html](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk/example/feedback/Feedback.jsx). Once you have collected the feedback data, pass it along to `reflagClient.feedback()`: diff --git a/sdk/documents/react-native-sdk/README.md b/sdk/documents/react-native-sdk/README.md index 16195f6..1634758 100644 --- a/sdk/documents/react-native-sdk/README.md +++ b/sdk/documents/react-native-sdk/README.md @@ -13,13 +13,17 @@ pagination: visible: true --- +{% hint style="info" %} +**Independent SDK compatibility.** This React Native release uses React/Browser protocol v1. Follow the [matching React documentation](../../../legacy/v1/react-sdk/README.md) and use a [matching Node SDK](../../../legacy/v1/node-sdk/README.md) for bootstrap. Do not pass protocol-v2 bootstrap into a v1 consumer. +{% endhint %} + # Reflag React Native SDK A thin React Native wrapper around `@reflag/react-sdk`. -For more usage details, see the [React SDK README](../react-sdk/README.md). +For more usage details, see the [React SDK README](../../../legacy/v1/react-sdk/README.md). -An Expo example app lives in [packages/react-native-sdk/dev/expo](https://github.com/reflagcom/javascript/tree/main/packages/react-native-sdk/dev/expo). +An Expo example app lives in [packages/react-native-sdk/dev/expo](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/react-native-sdk/dev/expo). ## Get started @@ -61,7 +65,7 @@ function StartHuddleButton() { } ``` -See the [React SDK README](../react-sdk/README.md) for more details. +See the [React SDK README](../../../legacy/v1/react-sdk/README.md) for more details. ## React Native differences @@ -74,7 +78,7 @@ See the [React SDK README](../react-sdk/README.md) for more details. The React Native SDK shares its API with the React SDK. Use the React SDK reference for full types and details: -[React SDK Reference](../react-sdk/README.md) +[React SDK Reference](../../../legacy/v1/react-sdk/README.md) ## Cookbook @@ -146,4 +150,4 @@ If you want live flag updates to continue working after bootstrapping, use a rec After bootstrapping, any live flag updates are fetched directly by the client SDK from Reflag using the client-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the app, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. -For bootstrap usage patterns and options, see the [React SDK bootstrapping docs](../react-sdk/README.md). +For bootstrap usage patterns and options, see the [React SDK bootstrapping docs](../../../legacy/v1/react-sdk/README.md). diff --git a/sdk/documents/react-sdk/README.md b/sdk/documents/react-sdk/README.md index f9d2c2a..887e436 100644 --- a/sdk/documents/react-sdk/README.md +++ b/sdk/documents/react-sdk/README.md @@ -13,966 +13,163 @@ pagination: visible: true --- -# Reflag React SDK +{% hint style="info" %} +**Protocol v2.** [Legacy v1 documentation](../../../legacy/v1/react-sdk/README.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) -React client side library for [Reflag.com](https://reflag.com) +**Prerelease source documentation.** The installation examples target major 2; use them only when the matching SDK/CLI packages are available. A server rollout alone does not publish npm packages. -Reflag supports flag toggling, tracking flag usage, [requesting feedback](#userequestfeedback) on features, and [remotely configuring flags](#remote-config). +Generated from [`@reflag/react-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/react-sdk); SDK READMEs and code comments remain the source of truth. +{% endhint %} -The Reflag React SDK comes with a [built-in toolbar](https://docs.reflag.com/supported-languages/browser-sdk#toolbar) which appears on `localhost` by default. +# Reflag React SDK v2 -## Install +Direct-value feature flags for React, backed by [Browser SDK v2](../../../supported-languages/browser-sdk/README.md). -Install via npm: +> Breaking prerelease: requires compatible v2 server endpoints and **Node SDK v2** for bootstrap. The v2 CLI generates direct-value declarations; regenerate legacy wrapper-shaped output when migrating. Useful default-based inference does not require generated declarations. React Native remains on published React/Browser v1 in this repository. -```shell -npm i @reflag/react-sdk -``` - -## Get started - -### 1. Add the `ReflagProvider` context provider - -Add the `ReflagProvider` context provider to your application: - -**Example:** +## Setup ```tsx import { ReflagProvider } from "@reflag/react-sdk"; } > - {/* children here are shown when loading finishes or immediately if no `loadingComponent` is given */} + ; ``` -### 2. Create a new flag and set up type safety - -Install the Reflag CLI: - -```shell -npm i --save-dev @reflag/cli -``` - -Run `npx reflag new` to create your first flag! -On the first run, it will sign into Reflag and set up type generation for your project: - -```shell -❯ npx reflag new -Opened web browser to facilitate login: https://app.reflag.com/api/oauth/cli/authorize - -Welcome to ◪ Reflag! - -? Where should we generate the types? gen/flags.d.ts -? What is the output format? react -✔ Configuration created at reflag.config.json. - -Creating flag for app Slick app. -? New flag name: Huddle -? New flag key: huddle -✔ Created flag Huddle with key huddle (https://app.reflag.com/features/huddles) -✔ Generated react types in gen/flags.d.ts. -``` - -> [!Note] -> By default, types will be generated in `gen/flags.d.ts`. -> The default `tsconfig.json` file `include`s this file by default, but if your `tsconfig.json` is different, make sure the file is covered in the `include` property. - -### 3. Use `useFlag()` to get flag status - -Using the `useFlag` hook from your components lets you toggle flags on/off and track flag usage: - -**Example:** - -```tsx -function StartHuddleButton() { - const { - isEnabled, // boolean indicating if the flag is enabled - track, // track usage of the flag - } = useFlag("huddle"); - - if (!isEnabled) { - return null; - } - - return ; -} -``` - -`useFlag` can help you do much more. See a full example for `useFlag` [see below](#useflag). - -## Setting context - -Reflag determines which flags are active for a given `user`, `company`, or `other` context. -You can pass these to the `ReflagProvider` using the `context` prop. - -### Using the `context` prop - -```tsx - - - {/* children here are shown when loading finishes */} - - -``` - -### Legacy individual props (deprecated) - -For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version: - -```tsx - - - {/* children here are shown when loading finishes */} - - -``` - -> [!Important] -> The `user`, `company`, and `otherContext` props are deprecated. Use the `context` prop instead, which provides the same functionality in a more structured way. - -### Context requirements - -If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. -In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. -Attributes which are not properties of the `user` or `company` can be supplied using the `other` property. - -Attributes cannot be nested (multiple levels) and must be either strings, numbers or booleans. -A number of special attributes exist: - -- `name` -- display name for `user`/`company`, -- `email` -- the email of the user, -- `avatar` -- the URL for `user`/`company` avatar image. - -To retrieve flags along with their targeting information, use `useFlag(key: string)` hook (described in a section below). - -Note that accessing `isEnabled` on the object returned by `useFlag()` automatically -generates a `check` event. - -## React Native - -For React Native, use `@reflag/react-native-sdk`, which is a thin wrapper around -`@reflag/react-sdk` and wires up AsyncStorage by default. - -An Expo example app lives at `packages/react-native-sdk/dev/expo`. - -## Remote config - -Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. - -Similar to `isEnabled`, each flag accessed using the `useFlag()` hook, has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the -binary `isEnabled` you can have multiple configuration values which are given to different user/companies. - -### Get started with Remote config - -1. Update your flag definitions: - -```typescript -import "@reflag/react-sdk"; - -// Define your flags by extending the `Flags` interface in @reflag/react-sdk -declare module "@reflag/react-sdk" { - interface Flags { - huddle: { - // change from `boolean` to an object which sets - // a type for the remote config for `questionnaire` - maxTokens: number; - model: string; - }; - } -} -``` - -```ts -const { - isEnabled, - config: { key, payload }, -} = useFlag("huddles"); - -// isEnabled: true, -// key: "gpt-3.5", -// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } -``` - -`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. - -Note that, similar to `isEnabled`, accessing `config` on the object returned by `useFlag()` automatically -generates a `check` event. - -## Toolbar - -The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off. - -Toolbar - -The toolbar will automatically appear on `localhost`. However, it can also be incredibly useful in production. You have full control over when it appears through the `toolbar` configuration option passed to the ReflagProvider. - -You can pass a simple boolean to force the toolbar to appear/disappear: - -```ts -` component is a specialized version of `ReflagProvider` designed for server-side rendering, preloaded flag scenarios, and high-reliability setups. It uses pre-fetched evaluated state for the initial render, resulting in faster initial page loads, better SSR compatibility, and a more resilient startup path for React applications. - -```tsx -import { useState, useEffect } from "react"; -import { BootstrappedFlags } from "@reflag/react-sdk"; - -interface BootstrapData { - user: User; - flags: BootstrappedFlags; -} - -function useBootstrap() { - const [data, setData] = useState(null); - - useEffect(() => { - fetch("/bootstrap") - .then((res) => res.json()) - .then(setData); - }, []); - - return data; -} - -// Usage in your app -function App() { - const { user, flags } = useBootstrap(); - - return ( - - - - - - ); -} -``` - -### Server-side endpoint setup - -Create an endpoint that provides bootstrap data to your client application: - -```typescript -// server.js or your Express app -import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; - -const reflagClient = new ReflagNodeClient({ - secretKey: process.env.REFLAG_SECRET_KEY, -}); -await reflagClient.initialize(); - -app.get("/bootstrap", (req, res) => { - const user = getUser(req); // Get user from your auth system - const company = getCompany(req); // Get company from your auth system - - const flags = reflagClient.getFlagsForBootstrap({ - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, - other: { source: "web" }, - }); - - res.status(200).json({ - user, - flags, - }); -}); -``` - -The `flags` object returned by `getFlagsForBootstrap()` contains the full bootstrapped state package: - -- `context`: the evaluation context used on the server -- `flags`: the evaluated raw flags -- `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping - -If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. - -### Next.js Page Router SSR example - -For Next.js applications using server-side rendering, you can pre-fetch flags in `getServerSideProps`: - -```typescript -// pages/index.tsx -import { GetServerSideProps } from "next"; -import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; -import { ReflagBootstrappedProvider, BootstrappedFlags, useFlag } from "@reflag/react-sdk"; - -interface PageProps { - bootstrapData: BootstrappedFlags; -} - -export const getServerSideProps: GetServerSideProps = async (context) => { - const serverClient = new ReflagNodeClient({ - secretKey: process.env.REFLAG_SECRET_KEY - }); - await serverClient.initialize(); - - const user = await getUserFromSession(context.req); - const company = await getCompanyFromUser(user); - - const bootstrapData = serverClient.getFlagsForBootstrap({ - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, - other: { page: "homepage" } - }); - - return { props: { bootstrapData } }; -}; - -export default function HomePage({ bootstrapData }: PageProps) { - return ( - - - - ); -} - -function HuddleFeature() { - const { isEnabled, track, config } = useFlag("huddle"); - - if (!isEnabled) return null; - - return ( -
-

Start a Huddle

-

Max participants: {config.payload?.maxParticipants ?? 10}

-

Video quality: {config.payload?.videoQuality ?? "standard"}

- -
- ); -} -``` - -This approach eliminates loading states and removes the initial render's dependency on the flags API. - -### Next.js App Router example - -For Next.js applications using the App Router (Next.js 13+), you can pre-fetch flags in Server Components and pass them to client components: - -```typescript -// app/layout.tsx (Server Component) -import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; -import { ClientProviders } from "./providers"; - -async function getBootstrapData() { - const serverClient = new ReflagNodeClient({ - secretKey: process.env.REFLAG_SECRET_KEY! - }); - await serverClient.initialize(); - - // In a real app, you'd get user/company from your auth system - const bootstrapData = serverClient.getFlagsForBootstrap({ - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, - other: { source: "web" } - }); - - return bootstrapData; -} - -export default async function RootLayout({ - children, -}: { - children: React.ReactNode; -}) { - const bootstrapData = await getBootstrapData(); - - return ( - - - - {children} - - - - ); -} -``` - -```typescript -// app/providers.tsx (Client Component) -"use client"; - -import { ReflagBootstrappedProvider, BootstrappedFlags } from "@reflag/react-sdk"; - -interface ClientProvidersProps { - children: React.ReactNode; - bootstrapData: BootstrappedFlags; -} - -export function ClientProviders({ children, bootstrapData }: ClientProvidersProps) { - return ( - - {children} - - ); -} -``` - -```typescript -// app/page.tsx (Server Component) -import { HuddleFeature } from "./huddle-feature"; +Provider options forward Browser SDK settings, including `logger`, `debug`, `enableTracking`, `offline`, cache/fallback options, `toolbar`, `feedback`, `credentials` and API origins. A custom logger takes precedence over debug logging. Live updates default to true; set `enableLiveFlagUpdates={false}` to disable them. -export default function HomePage() { - return ( -
-

My App

- -
- ); -} -``` - -```typescript -// app/huddle-feature.tsx (Client Component) -"use client"; - -import { useFlag } from "@reflag/react-sdk"; - -export function HuddleFeature() { - const { isEnabled, track, config } = useFlag("huddle"); - - if (!isEnabled) return null; - - return ( -
-

Start a Huddle

-

Max participants: {config.payload?.maxParticipants ?? 10}

-

Video quality: {config.payload?.videoQuality ?? "standard"}

- -
- ); -} -``` - -This App Router approach leverages Server Components for server-side flag fetching while using Client Components only where React state and hooks are needed. - -## `` component - -The `` is a lower-level component that accepts a `ReflagClient` instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application. - -In most cases you should initialize the client before rendering this provider. If you pass an idle client and enable `suspense`, a `useFlag()` call that suspends can initialize the client on demand; without Suspense, you must initialize the client yourself. - -### Usage +## `useFlag(key, defaultValue?)` ```tsx -import { ReflagClient } from "@reflag/browser-sdk"; -import { ReflagClientProvider } from "@reflag/react-sdk"; - -// Initialize the client yourself -const client = new ReflagClient({ - publishableKey: "your-publishable-key", - user: { id: "user123", name: "John Doe" }, - company: { id: "company456", name: "Acme Inc" }, - // ... other configuration options -}); +import { useFlag, useTrack } from "@reflag/react-sdk"; -// Initialize the client -await client.initialize(); - -function App() { +function Huddles() { + const enabled = useFlag("huddles"); // boolean, implicit false + const settings = useFlag("huddle-settings", { maxParticipants: 10 }); + const track = useTrack(); + if (!enabled) return null; return ( - }> - - + ); } ``` -### Props - -The `ReflagClientProvider` accepts the following props: - -- `client`: A `ReflagClient` instance. Prefer passing an already-initialized client; idle clients are initialized on demand only by suspense-enabled `useFlag()` calls. -- `loadingComponent`: Optional React component to show while the client is initializing (same as `ReflagProvider`) -- `suspense`: Optional. Set to `true` to make `useFlag()` suspend while the client is loading - -> [!Note] -> Most applications should use `ReflagProvider` or `ReflagBootstrappedProvider` instead of `ReflagClientProvider`. Only use this component when you need the advanced control it provides. - -## `` component - -The `` initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props: - -- `publishableKey` is used to connect the provider to an _environment_ on Reflag. Find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag, -- `context` (recommended): An object containing `user`, `company`, and `other` properties that make up the evaluation context used to determine if a flag is enabled or not. `company` and `user` contexts are automatically transmitted to Reflag servers so the Reflag app can show you which companies have access to which flags etc. -- `company`, `user` and `other` (deprecated): Individual props for context. These are deprecated in favor of the `context` prop and will be removed in the next major version. - > [!Note] - > If you specify `company` and/or `user` they must have at least the `id` property, otherwise they will be ignored in their entirety. You should also supply anything additional you want to be able to evaluate flag targeting against, -- `fallbackFlags`: A list of strings which specify which flags to consider enabled if the SDK is unable to fetch flags. Can be provided in two formats: - - ```ts - // Simple array of flag keys - fallbackFlags={["flag1", "flag2"]} - - // Or with configuration overrides - fallbackFlags: { - "flag1": true, // just enable the flag - "flag2": { // enable with configuration - key: "variant-a", - payload: { - limit: 100, - mode: "test" - } - } - } - ``` - -- `timeoutMs`: Timeout in milliseconds when fetching flags from the server. -- `staleWhileRevalidate`: If set to `true`, stale flags will be returned while refetching flags in the background. -- `expireTimeMs`: If set, flags will be cached between page loads for this duration (in milliseconds). -- `staleTimeMs`: Maximum time (in milliseconds) that stale flags will be returned if `staleWhileRevalidate` is true and new flags cannot be fetched. -- `offline`: Provide this option when testing or in local development environments to avoid contacting Reflag servers. -- `loadingComponent` lets you specify an React component to be rendered instead of the children while the Reflag provider is initializing. If you want more control over loading screens, `useFlag()` and `useIsLoading` returns `isLoading` which you can use to customize the loading experience. -- `suspense`: Set to `true` to make `useFlag()` suspend while the provider is loading and `useOptInFlags()` suspend while required opt-in metadata is loading. Wrap components that call these hooks in React `` boundaries and omit `loadingComponent` if you want Suspense fallbacks to control loading UI. -- `enableTracking`: Set to `false` to stop sending tracking events and user/company updates to Reflag. Useful when you're impersonating a user (defaults to `true`), -- `enableLiveFlagUpdates`: Enables live flag updates over SSE. Defaults to `true` in the React SDK. -- `apiBaseUrl`: Optional base URL for the Reflag API. This also controls the SSE origin used for live flag updates and automated feedback, -- `credentials`: Optional fetch credentials mode. Set to `"include"` when proxying through your backend and authenticating with cookies; this also enables credentials for live-update SSE connections. -- `appBaseUrl`: Optional base URL for the Reflag application. Use this to override the default app URL, - -- `logger`: Optional custom logger implementation (`debug`, `info`, `warn`, `error`) used by the underlying client, -- `debug`: Set to `true` to enable debug logging to the console. If both `logger` and `debug` are provided, `logger` takes precedence, -- `toolbar`: Optional [configuration](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions) for the Reflag toolbar, -- `feedback`: Optional configuration for feedback collection - -## `` component - -The `` is a specialized version of the `ReflagProvider` that uses pre-fetched flag data for the initial render. This is ideal for server-side rendering scenarios. - -The component accepts the following props: +Bare reads return Boolean/false, including while initial data is unavailable. A positional default infers widened direct types, even without generated declarations: -- `flags`: Pre-fetched bootstrapped state of type `BootstrappedFlags` obtained from the Node SDK's `getFlagsForBootstrap()` method. This contains the context (`flags.context`), the evaluated flags (`flags.flags`), and an optional `flags.flagStateVersion`. -- All other props available in [`ReflagProvider`](#reflagprovider-component) are supported except `context`, `user`, `company`, and `other` (which are extracted from `flags.context`). - -**Example:** - -```tsx -import { - ReflagBootstrappedProvider, - BootstrappedFlags, -} from "@reflag/react-sdk"; - -interface AppProps { - bootstrapData: BootstrappedFlags; -} - -function App({ bootstrapData }: AppProps) { - return ( - } - debug={process.env.NODE_ENV === "development"} - > - - - ); -} +```ts +useFlag("model", "quick"); // string +useFlag("limit", 10); // number +useFlag("settings", { model: "quick" }); // { model: string } +useFlag("nullable-settings", null); // FlagValue: arbitrary JSON ``` -> [!Note] -> When using `ReflagBootstrappedProvider`, pass the entire object returned by `getFlagsForBootstrap()` directly as the `flags` prop. The context is extracted from `flags.context`, and `flags.flagStateVersion` is used when present. -> -> With `ReflagBootstrappedProvider`, `useOptInFlags()` requests a flags refresh on first use. It returns `isLoading: true` (or suspends) until that refresh settles. -> -> If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. -> -> After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. -> -> Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. +Non-null defaults enforce only the top-level JSON category (Boolean/number/string/array/object). Mismatches return the default and warn without logging the payload. Explicit null accepts authored null and all other JSON; missing values return null. Accepted false, zero and empty strings are preserved. Nested fields/elements are not schema-validated. Values/defaults are independent mutable copies; readonly defaults are accepted. -## Hooks +`useFlag` never suspends. Its second argument is **payload data**, not `{ suspense: ... }` options; ordinary JSON has no reserved keys. Use the dedicated hook below for suspension. Use `useIsLoading()` or the provider's `loadingComponent` when you need an explicit loading UI. -### `useFlag()` - -Returns the state of a given flag for the current context. The hook provides type-safe access to flags and their configurations. - -```tsx -import { useFlag } from "@reflag/react-sdk"; -import { Loading } from "./Loading"; - -function StartHuddleButton() { - const { - isLoading, // true while flags are being loaded - isEnabled, // boolean indicating if the flag is enabled - config: { - // flag configuration - key, // string identifier for the config variant - payload, // type-safe configuration object - }, - track, // function to track flag usage - requestFeedback, // function to request feedback for this flag - } = useFlag("huddle"); - - if (isLoading) { - return ; - } - - if (!isEnabled) { - return null; - } - - return ( - <> - - - - ); -} -``` - -#### Suspense loading - -Enable `suspense` on the provider to have `useFlag()` throw a promise while `isLoading` is true. The nearest `` boundary will render its fallback until flags are ready. +## `useFlagSuspense(key, defaultValue?)` ```tsx import { Suspense } from "react"; -import { ReflagProvider } from "@reflag/react-sdk"; - - - }> - - -; -``` - -You can also opt in for a single call with `useFlag("huddle", { suspense: true })`, or opt out inside a suspense-enabled provider with `{ suspense: false }`. +import { useFlagSuspense } from "@reflag/react-sdk"; -### `useOptInFlags()` and `useSetOptIn()` - -Use these hooks to build an end-user opt-in UI for flags where opt-in is enabled in Reflag. - -```tsx -import { - type OptInFlag, - useIsLoading, - useOptInFlags, - useSetOptIn, -} from "@reflag/react-sdk"; - -function OptInList() { - const isProviderLoading = useIsLoading(); - const { flags, isLoading } = useOptInFlags(); - const setOptIn = useSetOptIn(); - - async function toggleOptIn(flag: OptInFlag) { - try { - const response = await setOptIn(flag.key, { - optedIn: !flag.userOptedIn, - }); - if (!response?.ok) { - console.error("Could not update opt-in"); - } - } catch (error) { - console.error("Could not update opt-in", error); - } - } - - if (isProviderLoading || isLoading) { - return

Loading…

; - } - - return flags.map((flag) => ( - - )); +function Model() { + const model = useFlagSuspense("model", "quick"); + return {model}; } -``` - -By default, `useSetOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. -User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. - -`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and subscribers have been notified when flags change. React may not have committed the resulting render yet. - -The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. - -`useOptInFlags()` returns `{ flags, isLoading }`. With `ReflagBootstrappedProvider`, it fetches opt-in metadata on first use and reports `isLoading: true` until that refresh succeeds or fails. - -If fetching opt-in metadata fails, loading ends without exposing an error. Call `client.refresh()` on the client returned by `useClient()` to retry. - -With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal initial flags request, so `useOptInFlags().isLoading` remains `false`. Use the general `useIsLoading()` hook or the provider's `loadingComponent` for that initial loading state. - -`useOptInFlags()` also supports Suspense. It respects the provider-level `suspense` option, or you can enable it for only this hook with `useOptInFlags({ suspense: true })`. While required opt-in metadata is loading, the nearest `` boundary renders its fallback: - -```tsx -import { Suspense } from "react"; - - - }> - - -; +Loading flags…}> + +; ``` -Opt-in metadata Suspense is primarily relevant with `ReflagBootstrappedProvider`. Use `useOptInFlags({ suspense: false })` to opt out for one call when Suspense is enabled on the provider. - -### `useTrack()` - -`useTrack()` lets you send custom events to Reflag. Use this whenever a user _uses_ a feature. These events can be used to analyze feature usage in Reflag. - -```tsx -import { useTrack } from "@reflag/react-sdk"; - -function StartHuddle() { - const { track } = useTrack(); -
- -
; -} -``` +This hook has the same Boolean/default-based return types. It waits for initialization before reading. Once initialization settles, missing flags return their default rather than suspending forever. Bootstrap values can render immediately. Suspended attempts do not register a root read before data is ready. -### `useRequestFeedback()` +The provider's existing `suspense` prop continues to configure **`useOptInFlags` only**. It does not change `useFlag`; `useFlagSuspense` is explicit. -`useRequestFeedback()` returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features as part of roll out. See [Automated Feedback Surveys](https://docs.reflag.com/product-handbook/live-satisfaction) for how to do this automatically, without code. +## Checks and usage tracking -When using the `useRequestFeedback` you must pass the flag key to `requestFeedback`. -The example below shows how to use `position` to ensure the popover appears next to the "Give feedback!" button. +A completed getter/hook read registers its requested-root check immediately, even if the value is ignored. Actual delivery remains buffered and identity-aware rate-limited by the Browser SDK. Checks contain selected variant/source/snapshot identity, not payloads. Defaults, category mismatches and local overrides never invent authored selections. Diagnostic/bootstrap inspection registers no checks. -```tsx -import { useRequestFeedback } from "@reflag/react-sdk"; +Application usage and feedback remain separate hooks: -function FeedbackButton() { - const requestFeedback = useRequestFeedback(); - return ( - - ); -} +```ts +const track = useTrack(); +await track("Started huddle", { button: "cta" }); +const requestFeedback = useRequestFeedback(); +requestFeedback({ flagKey: "huddles", title: "How did it go?" }); +const sendFeedback = useSendFeedback(); +await sendFeedback({ flagKey: "huddles", score: 5 }); ``` -See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/FEEDBACK.md#manual-feedback-collection) for more information on `requestFeedback` options. +See [Browser feedback documentation](../../../supported-languages/browser-sdk/feedback.md) for UI/prompt configuration. -### `useSendFeedback()` +## Optional key registration -Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag. - -```tsx -import { useSendFeedback } from "@reflag/react-sdk"; - -function CustomFeedbackForm() { - const sendFeedback = useSendFeedback(); - - const handleSubmit = async (data: FormData) => { - await sendFeedback({ - flagKey: "reflag-flag-key", - score: parseInt(data.get("score") as string), - comment: data.get("comment") as string, - }); - }; - - return
...; +```ts +import "@reflag/react-sdk"; +declare module "@reflag/react-sdk" { + interface Flags { + huddles: boolean; + "huddle-settings": { maxParticipants: number }; + } } ``` -### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` +Registration constrains keys and checks non-null defaults against the registered value schema, including required and nested properties. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request; bare/`undefined` reads remain Boolean. The positional default still determines the widened return type, and generated declarations do not add nested runtime validation. The same rules apply to `useFlagSuspense`. The v2 CLI generates direct-value declarations from current production-environment variants; regenerate legacy wrapper declarations when migrating. -These hooks return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session. +## Bootstrap and SSR -```tsx -import { - useUpdateUser, - useUpdateCompany, - useUpdateOtherContext, -} from "@reflag/react-sdk"; - -function FlagOptIn() { - const updateUser = useUpdateUser(); - const updateCompany = useUpdateCompany(); - const updateOtherContext = useUpdateOtherContext(); - - const handleUserUpdate = async () => { - await updateUser({ - role: "admin", - betaFlags: "enabled", - }); - }; - - const handleCompanyUpdate = async () => { - await updateCompany({ - plan: "enterprise", - employees: 500, - }); - }; - - const handleContextUpdate = async () => { - await updateOtherContext({ - currentWorkspace: "workspace-123", - theme: "dark", - }); - }; +On the server, use Node SDK v2: - return ( -
- - - -
- ); -} +```ts +const flags = serverClient.getFlagsForBootstrap(context); ``` -### `useClient()` - -Returns the `ReflagClient` used by the `ReflagProvider`. The client offers more functionality that -is not directly accessible thorough the other hooks. +Pass the **entire** safe, serialized envelope to the client provider: ```tsx -import { useClient } from "@reflag/react-sdk"; +import { ReflagBootstrappedProvider } from "@reflag/react-sdk"; -function LoggingWrapper({ children }: { children: ReactNode }) { - const client = useClient(); - - console.log(client.getContext()); - - return children; -} + + +; ``` -### `useIsLoading()` +The envelope includes `protocolVersion: 2`, context, evaluated flag results and optional `flagStateVersion`. V1 bootstrap is rejected. Use a snapshot version for live updates; later refreshes use browser-visible context. Do not send secrets/server-only attributes to the browser. Disable live updates if later browser evaluation must not replace server-only results. -Returns the loading state of the flags in the `ReflagClient`. -Initially, the value will be `true` if no bootstrap flags have been provided and the client has not be initialized. +For a pre-existing Browser v2 client, use ``. The provider does not own its lifecycle; initialize/stop externally, except that a suspending read can start on-demand initialization. -```tsx -import { useIsLoading } from "@reflag/react-sdk"; -import { Spinner } from "./Spinner"; - -function LoadingWrapper({ children }: { children: ReactNode }) { - const isLoading = useIsLoading(); +## Context, loading and events - if (isLoading) { - return ; - } +- `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return async shallow-update functions. `useClient().setContext(context)` replaces the whole context. +- Context changes clear old-context values while fetching. Stale/in-flight responses cannot replace a newer context/snapshot. +- `useIsLoading()` returns provider loading state. `loadingComponent` and `initialLoading` configure initial presentation; they are not getter arguments. +- `useClient()` returns the underlying Browser client. Its `getFlags()` returns direct values/checks; `getFlagResults()` is diagnostic-only. +- `useOnEvent(type, handler, client?)` subscribes and unsubscribes on unmount. A supplied external client works without a provider. - return children; -} -``` - -### `useOnEvent()` - -Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount. +## Opt-in hooks ```tsx -import { useOnEvent } from "@reflag/react-sdk"; - -function LoggingWrapper({ children }: { children: ReactNode }) { - useOnEvent("flagsUpdated", (newFlags) => { - console.log(newFlags); - }); - - return children; -} +const { flags, isLoading } = useOptInFlags(); +const setOptIn = useSetOptIn(); +await setOptIn("huddles", { optedIn: true }); +await setOptIn("huddles", { optedIn: false, scope: "company" }); ``` -## Migrating from Bucket SDK - -If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: - -- `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) -- `Feature*` classes, and types have been renamed to `Flag*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) -- When using strongly-typed flags, the new `Flags` interface replaced `Features` interface -- All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) -- The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags` -- `featureKey` has been renamed to `flagKey` in all methods that accepts that argument -- The SDKs will not emit `evaluate` and `evaluate-config` events anymore -- The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead of `bucket-*` -- The `featuresUpdated` hook has been renamed to `flagsUpdated` -- The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on - -To ease in transition to Reflag SDK, some of the old methods have been preserved as aliases to the new methods: - -- `getFeature` method is an alias for `getFlag` -- `getFeatures` method is an alias for `getFlags` -- `useFeature` method is an alias for `useFlag` -- `featuresUpdated` hook is an alias for `flagsUpdated` - -If you are running with strict Content Security Policies active on your website, you will need change them as follows: - -- `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com` - -## Content Security Policy (CSP) - -See [CSP](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/README.md#content-security-policy-csp) for info on using Reflag React SDK with CSP +Metadata arrives with the initial v2 evaluation for regular providers. Bootstrapped providers fetch missing metadata on demand from `/flags/evaluated` without replacing server-derived values. `isLoading` covers initialization and metadata retrieval; it settles on success or failure. Metadata presentation includes `isEnabled` and membership fields, separately from direct flag reads. User/company grants remain independent. Mutations confirm versioned evaluation and membership in a single refresh. -## License +`useOptInFlags({ suspense: true | false })` retains its own per-hook loading options and may inherit provider `suspense`. These options are unrelated to the positional payload defaults used by `useFlag` / `useFlagSuspense`. -MIT License +## Migration from v1 -Copyright (c) 2025 Bucket ApS +Use `const enabled = useFlag(key)` instead of destructuring `.isEnabled`. Replace wrapper config access with an authored multivariate flag and positional default. Move `.track()` and `.requestFeedback()` to separate hooks. Replace `useFlag(key, { suspense: true })` with `useFlagSuspense(key)`, and use `useIsLoading()` instead of a flag wrapper's loading property. Upgrade Browser/server bootstrap together. Nothing here publishes the prerelease or deploys its required server changes. diff --git a/supported-languages/browser-sdk/README.md b/supported-languages/browser-sdk/README.md index 162250d..610e2ed 100644 --- a/supported-languages/browser-sdk/README.md +++ b/supported-languages/browser-sdk/README.md @@ -1,609 +1,171 @@ --- +layout: + visible: true title: visible: true +description: + visible: false tableOfContents: visible: true outline: visible: true pagination: visible: true -layout: - width: default - title: - visible: true - description: - visible: true - tableOfContents: - visible: true - outline: - visible: true - pagination: - visible: true - metadata: - visible: true - tags: - visible: true - actions: - visible: true - anchors: - visible: true --- -# Browser SDK - -Basic client for [Reflag.com](https://reflag.com). If you're using React, you'll be better off with the Reflag React SDK. - -Reflag supports flag toggling, tracking flag usage, [collecting feedback](./#qualitative-feedback-on-beta-flags) on flags, and [remotely configuring flags](./#remote-config). - -## Install - -First find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag. - -The package can be imported or used directly in a HTML script tag: - -A. Import module: - -```typescript -import { ReflagClient } from "@reflag/browser-sdk"; - -const user = { - id: 42, - role: "manager", -}; - -const company = { - id: 99, - plan: "enterprise", -}; - -const reflagClient = new ReflagClient({ publishableKey, user, company }); - -await reflagClient.initialize(); - -const { - isEnabled, - config: { payload: question }, - track, - requestFeedback, -} = reflagClient.getFlag("huddle"); - -if (isEnabled) { - // Show flag. When retrieving `isEnabled` the client automatically - // sends a "check" event for the "huddle" flag which is shown in the - // Reflag UI. - - // On usage, call `track` to let Reflag know that a user interacted with the flag - track(); - - // The `payload` is a user-supplied JSON in Reflag that is dynamically picked - // out depending on the user/company. - const question = payload?.question ?? "Tell us what you think of Huddles"; - - // Use `requestFeedback` to create "Send feedback" buttons easily for specific - // flags. This is not related to `track` and you can call them individually. - requestFeedback({ title: question }); -} - -// `track` just calls `reflagClient.track()` to send an event using the same flag key -// You can also use `track` on the client directly to send any custom event. -reflagClient.track("huddle"); - -// similarly, `requestFeedback` just calls `reflagClient.requestFeedback({flagKey: })` -// which you can also call directly: -reflagClient.requestFeedback({ flagKey: "huddle" }); -``` - -B. Script tag (client-side directly in html) - -See [example/browser.html](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/example/browser.html) for a working example: - -```html - - -Loading... - -``` - -### Init options - -Supply these to the constructor call: - -```typescript -type Configuration = { - logger: console; // by default only logs warn/error, by passing `console` you'll log everything - apiBaseUrl?: "https://front.reflag.com"; - credentials?: "include" | "same-origin" | "omit"; // forwarded to fetch requests; "include" also enables credentials for the default EventSource transport - feedback?: undefined; // See FEEDBACK.md - enableTracking?: true; // set to `false` to stop sending track events and user/company updates to Reflag servers. Useful when you're impersonating a user - enableLiveFlagUpdates?: false; // Set to `true` to keep flags up to date over SSE (browser SDK default: false) - eventSourceFactory?: (url: string) => { - // Advanced: provide a custom EventSource-compatible transport - addEventListener: (type: string, cb: (event: any) => void) => void; - close: () => void; - }; - fallbackFlags?: - | string[] - | Record; // Enable these flags if unable to contact reflag.com. Can be a list of flag keys or a record with configuration values - timeoutMs?: number; // Timeout for fetching flags (default: 5000ms) - staleWhileRevalidate?: boolean; // Revalidate in the background when cached flags turn stale to avoid latency in the UI (default: false) - staleTimeMs?: number; // at initialization time flags are loaded from the cache unless they have gone stale. Defaults to 0 which means the cache is disabled. Increase this in the case of a non-SPA - expireTimeMs?: number; // In case we're unable to fetch flags from Reflag, cached/stale flags will be used instead until they expire after `expireTimeMs`. Default is 30 days - offline?: boolean; // Use the SDK in offline mode. Offline mode is useful during testing and local development -}; -``` - -## Migrating from Bucket SDK - -If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: - -* `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) -* `Feature*` classes, and types have been renamed to `Feature*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) -* All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) -* The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags` -* `featureKey` has been renamed to `flagKey` in all methods that accepts that argument -* The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead og `bucket-*` -* The `featuresUpdated` hook has been renamed to `flagsUpdated` -* The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on - -To ease in transition to Reflag SDK, some of the old methods have been preserved as aliases to the new methods: - -* `getFeature` method is an alias for `getFlag` -* `getFeatures` method is an alias for `getFlags` -* `featuresUpdated` hook is an alias for `flagsUpdated` - -If you are running with strict Content Security Policies active on your website, you will need change them as follows: - -* `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com` - -Finally, if you have customized the look & feel of the Feedback component, update `--bucket-feedback-*` CSS classes to `--reflag-feedback-*` - -## Flag toggles - -Reflag determines which flags are active for a given user/company. The user/company is given in the ReflagClient constructor. - -If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. - -Attributes cannot be nested (multiple levels) and must be either strings, integers or booleans. Some attributes are special and used in Reflag UI: - -* `name` -- display name for `user`/`company`, -* `email` -- is accepted for `user`s and will be highlighted in the Reflag UI if available, -* `avatar` -- can be provided for both `user` and `company` and should be an URL to an image. - -```ts -const reflagClient = new ReflagClient({ - publishableKey, - user: { - id: "user_123", - name: "John Doe", - email: "john@acme.com" - avatar: "https://example.com/images/udsy6363" - }, - company: { - id: "company_123", - name: "Acme, Inc", - avatar: "https://example.com/images/31232ds" - }, -}); -``` - -To retrieve flags along with their targeting information, use `getFlag(key: string)`: - -```ts -const huddle = reflagClient.getFlag("huddle"); -// { -// isEnabled: true, -// config: { key: "zoom", payload: { ... } }, -// track: () => Promise -// requestFeedback: (options: RequestFeedbackData) => void -// } -``` - -You can use `getFlags()` to retrieve all enabled flags currently. - -```ts -const flags = reflagClient.getFlags(); -// { -// huddle: { -// isEnabled: true, -// targetingVersion: 42, -// config: ... -// } -// } -``` - -`getFlags()` is meant to be more low-level than `getFlag()` and it typically used by down-stream clients, like the React SDK. - -Note that accessing `isEnabled` on the object returned by `getFlags` does not automatically generate a `check` event, contrary to the `isEnabled` property on the object returned by `getFlag`. - -## End-user opt-in - -If a flag has end-user opt-in enabled in Reflag, you can list the opt-in options for the current context and set or cancel opt-in for the current user or company. - -```ts -const optInFlags = reflagClient.getOptInFlags(); -// [{ key, name, description, isEnabled, userOptedIn, companyOptedIn, isOptedIn }] - -try { - const response = await reflagClient.setOptIn("huddle", { - optedIn: true, // Use false to cancel this scope's opt-in. - scope: "user", // Use "company" to change the current company's opt-in. - }); - if (!response?.ok) { - console.error("Could not update opt-in"); - } -} catch (error) { - console.error("Could not update opt-in", error); -} -``` - -By default, `setOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. - -User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. - -`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and `flagsUpdated` listeners have been notified when flags change. - -The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. - -The `description` comes from the dedicated SDK-facing opt-in description configured in Reflag. +{% hint style="info" %} +**Protocol v2.** [Legacy v1 documentation](../../legacy/v1/browser-sdk/README.md) · [Migration guide](../migrating-from-v1.md) -When using bootstrapped flags, the first `getOptInFlags()` or `getIsLoadingOptInFlags()` call requests a flags refresh. The list call returns the currently available list synchronously, and the loading getter returns `true` until that refresh succeeds or fails. Normal initialization also exposes loading through the client's state. +**Prerelease source documentation.** The installation examples target major 2; use them only when the matching SDK/CLI packages are available. A server rollout alone does not publish npm packages. -Listen for `optInFlagsLoadingUpdated` to update UI when this loading state changes. `flagsUpdated` is emitted when a successful refresh updates the list. +Generated from [`@reflag/browser-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk); SDK READMEs and code comments remain the source of truth. +{% endhint %} -If fetching opt-in metadata fails, loading ends without exposing an error. Call `reflagClient.refresh()` to retry. +# Reflag Browser SDK v2 -## Remote config +Client-side feature flags and JSON values for [Reflag](https://reflag.com). -Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. +> This is a breaking v2 prerelease. It requires the v2 evaluated-flags/check protocol on the server. Do not switch existing v1 applications or bootstrap consumers without coordinating that upgrade. Nothing in this branch publishes or deploys the SDK/server. -Similar to `isEnabled`, each flag has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the binary `isEnabled` you can have multiple configuration values which are given to different user/companies. +## Get started ```ts -const flags = reflagClient.getFlags(); -// { -// huddle: { -// isEnabled: true, -// targetingVersion: 42, -// config: { -// key: "gpt-3.5", -// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } -// } -// } -// } -``` - -`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. - -Just as `isEnabled`, accessing `config` on the object returned by `getFlags` does not automatically generate a `check` event, contrary to the `config` property on the object returned by `getFlag`. - -## Server-side rendering and bootstrapping - -For server-side rendered applications, you can render immediately with pre-fetched flag data by bootstrapping the client. - -### Init options bootstrapped - -```typescript -type Configuration = { - logger: console; // by default only logs warn/error, by passing `console` you'll log everything - apiBaseUrl?: "https://front.reflag.com"; - credentials?: "include" | "same-origin" | "omit"; // forwarded to fetch requests; "include" also enables credentials for the default EventSource transport - feedback?: undefined; // See FEEDBACK.md - enableTracking?: true; // set to `false` to stop sending track events and user/company updates to Reflag servers. Useful when you're impersonating a user - offline?: boolean; // Use the SDK in offline mode. Offline mode is useful during testing and local development - bootstrappedState?: { - context: ReflagContext; - flags: FetchedFlags; - flagStateVersion?: number; - }; // Pre-fetched evaluated state from server-side (see Server-side rendering section) - bootstrappedFlags?: FetchedFlags; // Deprecated: use `bootstrappedState` instead -}; -``` - -### Using `bootstrappedState` - -Use the Node SDK's `getFlagsForBootstrap()` method to pre-fetch evaluated state server-side, then pass the returned object directly to the browser client: - -```typescript -// Server-side: Get bootstrapped state using Node SDK -import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; - -const serverClient = new ReflagNodeClient({ secretKey: "your-secret-key" }); -await serverClient.initialize(); - -const bootstrappedState = serverClient.getFlagsForBootstrap({ - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, -}); - -// Pass the bootstrapped state to the client using your framework's preferred method -app.get("/", (req, res) => { - res.set("Content-Type", "text/html"); - res.send( - Buffer.from( - ` -
`, - ), - ); -}); - -// Client-side: Initialize with pre-fetched evaluated state import { ReflagClient } from "@reflag/browser-sdk"; -const reflagClient = new ReflagClient({ +const reflag = new ReflagClient({ publishableKey: "your-publishable-key", - bootstrappedState, // Contains context, flags, and optional flagStateVersion -}); - -await reflagClient.initialize(); -const { isEnabled } = reflagClient.getFlag("huddle"); -``` - -The `bootstrappedState` object contains: - -* `context`: the evaluation context used on the server -* `flags`: the evaluated raw flags -* `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping - -If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. - -If a bootstrapped application requests opt-in flags, the browser SDK performs one flags refresh. Applications that do not request opt-in data do not make this request. - -If you previously used `bootstrappedFlags`, migrate like this: - -```typescript -// Before -const { flags } = serverClient.getFlagsForBootstrap(context); -const client = new ReflagClient({ - publishableKey, - user: context.user, - company: context.company, - other: context.other, - bootstrappedFlags: flags, + user: { id: "alice", role: "manager" }, + company: { id: "acme", plan: "enterprise" }, }); +await reflag.initialize(); -// After -const bootstrappedState = serverClient.getFlagsForBootstrap(context); -const client = new ReflagClient({ - publishableKey, - bootstrappedState, -}); -``` - -{% hint style="info" %} -After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. - -Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. -{% endhint %} - -This eliminates loading states and removes the initial render's dependency on the flags API. - -## Context management - -### Updating user/company/other context +const enabled = reflag.getFlag("huddles"); // boolean, implicit false +const settings = reflag.getFlag("assistant-settings", { model: "quick" }); +// settings: { model: string } -Attributes given for the user/company/other context in the ReflagClient constructor can be updated for use in flag targeting evaluation with the `updateUser()`, `updateCompany()` and `updateOtherContext()` methods. They return a promise which resolves once the flags have been re-evaluated follow the update of the attributes. - -### setContext() - -The `setContext()` method allows you to replace the entire context (user, company, and other attributes) at once. This method is useful when you need to completely change the context, such as when a user logs in or switches between different accounts. - -```ts -await reflagClient.setContext({ - user: { - id: "new-user-123", - name: "Jane Doe", - email: "jane@example.com", - role: "admin", - }, - company: { - id: "company-456", - name: "New Company Inc", - plan: "enterprise", - }, - other: { - feature: "beta", - locale: "en-US", - }, -}); +if (enabled) { + // Application usage tracking is separate from reading the flag. + await reflag.track("Started huddle"); +} ``` -The method will: - -* Replace the entire context with the new values -* Re-evaluate all flags based on the new context -* Update the user and company information on Reflag servers -* Return a promise that resolves once the flags have been re-evaluated +Use only a **publishable** key in a browser. Secret keys belong on your server. -### getContext() - -The `getContext()` method returns the current context being used for flag evaluation. This is useful for debugging or when you need to inspect the current user, company, and other attributes. +## Direct-value reads ```ts -const currentContext = reflagClient.getContext(); -console.log(currentContext); -// { -// user: { id: "user-123", name: "John Doe", email: "john@example.com" }, -// company: { id: "company-456", name: "Acme Inc", plan: "enterprise" }, -// other: { locale: "en-US", feature: "beta" } -// } +reflag.getFlag("release"); // boolean; missing/mismatched -> false +reflag.getFlag("model", "quick"); // string +reflag.getFlag("limit", 10); // number +reflag.getFlag("settings", { model: "quick" }); +reflag.getFlag("nullable-settings", null); // FlagValue (arbitrary JSON) ``` -The returned context object contains: +- Defaults are positional JSON values; generation is not required for useful types. Primitive literals widen, and readonly defaults are accepted. +- A non-null default accepts only the same **top-level JSON category**: Boolean, number, string, array or object. A mismatch warns without logging the payload and returns the default. A bare read can never return a truthy object. +- Explicit `null` accepts any JSON value, including authored null. Missing values return null. +- Falsy selected values (`false`, `0`, `""`, null) are preserved when accepted by the requested category. +- Object fields and array elements are **not schema-validated**. Validate untrusted/nested payloads in your application. +- Values and defaults are returned as independent mutable copies. There are no reserved JSON property names. -* `user`: Current user attributes (if any) -* `company`: Current company attributes (if any) -* `other`: Additional context attributes not related to user or company +`getFlags()` returns a direct-value record (entries may be undefined) and registers checks for its returned roots. `getFlagResults()` returns owned evaluated diagnostics **without checks**; it is intended for tooling, not ordinary application reads. `getFlagsForBootstrap()` serializes protocol-v2 evaluated state without checks. -## Toolbar +## Checks and delivery -The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off. +Calling a getter registers a requested-root check immediately, even if its return value is ignored. There are no `.isEnabled`, `.config`, `.value` or flag `.track()` wrappers. Delivery remains buffered through `/bulk` and identity-aware rate-limited. -Toolbar screenshot +A selected check carries the authored selected key as `evalResult`, its `sourceVersionId` and the available snapshot `flagStateVersion`. Payload equality is not identity: equal-valued selections or segment-only snapshot changes remain distinguishable on subsequent reads. Defaults, category mismatches, local overrides and static fallback values do not fabricate authored selections. Diagnostics and bootstrap serialization generate no checks. The server evaluates dependencies; fetching their results does not itself register reads. -The toolbar will automatically appear on `localhost`. However, it can also be incredibly useful in production. You have full control over when it appears through the `toolbar` configuration option passed to the `ReflagClient`. +`enableTracking: false` disables checks and user/company/usage tracking. `offline: true` skips HTTP and tracking. `await reflag.stop()` flushes buffered events and closes the client's background transports. -You can pass a simple boolean to force the toolbar to appear/disappear: +## Context, refresh and cache -```typescript -const client = new ReflagClient({ - // show the toolbar even in production if the user is an internal/admin user - toolbar: user?.isInternal, - ... +```ts +await reflag.updateUser({ role: "admin" }); +await reflag.updateCompany({ plan: "enterprise" }); +await reflag.updateOtherContext({ region: "eu" }); +await reflag.setContext({ + user: { id: "bob" }, + company: { id: "other-company" }, }); +await reflag.refresh(); ``` -You can also configure the position of the toolbar on the screen: - -```typescript -const client = new ReflagClient({ - toolbar: { - show: true; - position: { - placement: "bottom-left", - offset: {x: "1rem", y: "1rem"} - } - } - ... -}) -``` - -See [the reference](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions) for details. - -## Qualitative feedback on beta flags - -Reflag can collect qualitative feedback from your users in the form of a [Customer Satisfaction Score](https://en.wikipedia.org/wiki/Customer_satisfaction) and a comment. +`setContext()` replaces the context; update methods shallow-merge their section. User/company sections require IDs, including valid numeric zero. Context supports nested JSON and arrays. A context change clears the old context's values while fetching; stale/in-flight responses cannot replace a newer context or snapshot. -### Automated feedback collection +Values come from `GET /flags/evaluated`, not legacy `/features/evaluated`. Server evaluation retains the complete internal graph and authorized public roots. The Browser SDK does not cache dependency evaluations of its own. -The Reflag Browser SDK comes with automated feedback collection mode enabled by default, which lets the Reflag service ask your users for feedback for relevant flags just after they've used them. +Constructor options include: -{% hint style="info" %} -To get started with automatic feedback collection, make sure you've set `user` in the `ReflagClient` constructor. -{% endhint %} - -Automated feedback surveys work even if you're not using the SDK to send events to Reflag. It works because the Reflag Browser SDK maintains a live connection to Reflag's servers and can automatically show a feedback prompt whenever the Reflag servers determines that an event should trigger a prompt - regardless of how this event is sent to Reflag. - -You can find all the options to make changes to the default behavior in the [Reflag feedback documentation](feedback.md). - -### Reflag feedback UI +| Option | Behavior | +| ------------------------------- | --------------------------------------------------------------------------- | +| `apiBaseUrl`, `appBaseUrl` | API origin and toolbar/feedback links | +| `credentials` | Fetch credentials mode; `include` also enables default SSE credentials | +| `timeoutMs` | Flag request timeout; default 5,000 ms | +| `staleTimeMs` | Fresh-cache duration; default 0 | +| `staleWhileRevalidate` | Serve stale cached state while revalidating; default false | +| `expireTimeMs` | Cache expiry; default 30 days | +| `storage` | Optional async storage adapter | +| `fallbackFlags` | Value record or array of enabled Boolean keys, without authored provenance | +| `enableLiveFlagUpdates` | Refresh after SSE publications; default false in Browser, true in React/Vue | +| `eventSourceFactory` | Optional EventSource-compatible transport | +| `trackingQueue` | Buffered-delivery `flushDelayMs` and `maxSize` | +| `logger`, `toolbar`, `feedback` | Logging, Boolean override toolbar and feedback options | -Reflag can assist you with collecting your user's feedback by offering a pre-built UI, allowing you to get started with minimal code and effort. +Evaluated cache and override storage use isolated v2 keys. V1 cache entries are never interpreted as v2 values. Malformed refreshes leave known-good state intact. Valid saved v2 selections retain their real provenance on restore. There is no automatic periodic HTTP fallback after an SSE failure; manual refresh/context updates remain available. -[Read the Reflag feedback UI documentation](feedback.md) - -### Reflag feedback SDK - -Feedback can be submitted to Reflag using the SDK: +## Overrides and toolbar ```ts -reflagClient.feedback({ - flagKey: "my-flag-key", // String (required), copy from Flag feedback tab - score: 5, // Number: 1-5 (optional) - comment: "Absolutely stellar work!", // String (optional) -}); +reflag.setFlagOverride("release", true); +reflag.setFlagOverride("settings", { model: "local" }); +reflag.setFlagOverride("nullable-settings", null); // a real null override +reflag.setFlagOverride("release", undefined); // clear the override ``` -### Reflag feedback API - -If you are not using the Reflag Browser SDK, you can still submit feedback using the HTTP API. +Overrides apply after server evaluation and do not rewrite authored dependency results. The built-in toolbar appears on localhost by default and offers Boolean overrides only. It uses diagnostic access, so opening it does not register application checks. -See details in [Feedback HTTP API](https://docs.reflag.com/api/http-api#post-feedback) +## Server bootstrap -## Tracking flag usage - -The `track` function lets you send events to Reflag to denote flag usage. By default Reflag expects event names to align with the flag keys, but you can customize it as you wish. +Generate the full payload with **Node SDK v2** on your server: ```ts -reflagClient.track("huddle", { voiceHuddle: true }); +const bootstrappedState = serverClient.getFlagsForBootstrap(context); +// Send via your framework's safe JSON/hydration mechanism. ``` -## Event listeners - -Event listeners allow for capturing various events occurring in the `ReflagClient`. This is useful to build integrations with other system or for various debugging purposes. The available events are: - -* `check`: Your code used `isEnabled` or `config` for a flag -* `flagsUpdated`: Flags were updated. Either because they were loaded as part of initialization or because the user/company updated -* `optInFlagsLoadingUpdated`: The opt-in flag loading state changed -* `user`: User information updated (similar to the `identify` call used in tracking terminology) -* `company`: Company information updated (sometimes to the `group` call used in tracking terminology) -* `track`: Track event occurred. - -Use the `on()` method to add an event listener to respond to certain events. See the API reference for details on each hook. - ```ts -import { ReflagClient, CheckEvent, RawFlags } from "@reflag/browser-sdk"; - -const client = new ReflagClient({ - // options -}); - -// or add the hooks after construction: -const unsub = client.on("check", (check: CheckEvent) => - console.log(`Check event ${check}`), -); -// use the returned function to unsubscribe, or call `off()` with the same arguments again -unsub(); +const reflag = new ReflagClient({ publishableKey, bootstrappedState }); +await reflag.initialize(); +const enabled = reflag.getFlag("release"); ``` -## Zero PII +The payload includes `protocolVersion: 2`, context, evaluated diagnostics/selections and an optional snapshot version. V1 payloads and the old `bootstrappedFlags` option are rejected. Preserve the entire envelope; do not pass just its `flags` property. A version is required for bootstrapped live updates. Never embed secrets or server-only context in public bootstrap data. Later refreshes use browser-visible context and can differ from server-only evaluation; disable live updates when that is inappropriate. -The Reflag Browser SDK doesn't collect any metadata and HTTP IP addresses are _not_ being stored. - -For tracking individual users, we recommend using something like database ID as userId, as it's unique and doesn't include any PII (personal identifiable information). If, however, you're using e.g. email address as userId, but prefer not to send any PII to Reflag, you can hash the sensitive data before sending it to Reflag: +## End-user opt-in ```ts -import reflag from "@reflag/browser-sdk"; -import { sha256 } from "crypto-hash"; - -reflag.user(await sha256("john_doe")); +const options = reflag.getOptInFlags(); +const loading = reflag.getIsLoadingOptInFlags(); +await reflag.setOptIn("huddles", { optedIn: true }); +await reflag.setOptIn("huddles", { optedIn: false, scope: "company" }); ``` -## Use of cookies - -The Reflag Browser SDK uses a couple of cookies to support automated feedback surveys. These cookies are not used for tracking purposes and thus should not need to appear in cookie consent forms. - -The two cookies are: - -* `reflag-prompt-${userId}`: store the last automated feedback prompt message ID received to avoid repeating surveys -* `reflag-token-${userId}`: caching a token used to connect to Reflag's live messaging infrastructure that is used to deliver automated feedback surveys in real time. - -## TypeScript - -Types are bundled together with the library and exposed automatically when importing through a package manager. - -## Content Security Policy (CSP) +The list contains presentation/membership metadata (`key`, `name`, `description`, `isEnabled`, `userOptedIn`, `companyOptedIn`, `isOptedIn`); this is not the ordinary flag getter API. User/company grants remain independent. The selected scope requires its ID. Successful mutations wait for versioned evaluation and membership confirmation. -If you are running with strict Content Security Policies active on your website, you will need to enable these directives in order to use the SDK: +Metadata arrives with ordinary `/flags/evaluated` responses and is cached with the evaluated snapshot. Bootstrapped clients whose snapshot lacks metadata fetch it on demand from the same v2 endpoint, without replacing server-derived values or provenance with browser-context evaluations. Loading settles on success or failure, including an empty list. Opt-in mutations confirm values and membership together in one versioned refresh. `optInFlagsLoadingUpdated` and `flagsUpdated` support UI subscriptions. -| Directive | Values | Reason | -| ----------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | -| connect-src | [https://front.reflag.com](https://front.reflag.com) | API requests plus Server-Sent Events for live flag updates and automated feedback surveys. | -| style-src | 'unsafe-inline' | The feedback UI is styled with inline styles. Not having this directive results unstyled HTML elements. | +## Tracking, feedback and events -If you are including the Reflag tracking SDK with a ` - - - -``` - -If using Nuxt, wrap `` in ``. `` only renders client-side currently. - -### 2. Use `useFlag get flag status - -```vue - - - -``` - -See [useFlag()](#useflag) for a full example - -## Setting context - -Reflag determines which flags are active for a given `user`, `company`, or `other` context. -You can pass these to the `ReflagProvider` using the `context` prop. - -### Using the `context` prop - -```vue - - - -``` - -### Legacy individual props (deprecated) - -For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version: - -```vue - - - -``` - -> [!Important] -> The `user`, `company`, and `otherContext` props are deprecated. Use the `context` prop instead, which provides the same functionality in a more structured way. - -### Context requirements - -If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. -In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. -Attributes which are not properties of the `user` or `company` can be supplied using the `other` property. - -Attributes cannot be nested (multiple levels) and must be either strings, numbers or booleans. -A number of special attributes exist: - -- `name` -- display name for `user`/`company`, -- `email` -- the email of the user, -- `avatar` -- the URL for `user`/`company` avatar image. - -To retrieve flags along with their targeting information, use `useFlag(key: string)` hook (described in a section below). - -Note that accessing `isEnabled` on the object returned by `useFlag()` automatically -generates a `check` event. - -## Remote config - -Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. - -Similar to `isEnabled`, each flag accessed using the `useFlag()` hook, has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the -binary `isEnabled` you can have multiple configuration values which are given to different user/companies. - -### Get started with Remote config - -```ts -const { - isEnabled, - config: { key, payload }, -} = useFlag("huddles"); - -// isEnabled: true, -// key: "gpt-3.5", -// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } -``` - -`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. - -Note that, similar to `isEnabled`, accessing `config` on the object returned by `useFlag()` automatically -generates a `check` event. - -## `` component - -The `` initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props: - -- `publishableKey` is used to connect the provider to an _environment_ on Reflag. Find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag, -- `context`: An object containing `user`, `company`, and `other` properties that make up the evaluation context used to determine if a flag is enabled or not. `company` and `user` contexts are automatically transmitted to Reflag servers so the Reflag app can show you which companies have access to which flags etc. -- `company`, `user` and `otherContext` (deprecated): Individual props for context. These are deprecated in favor of the `context` prop and will be removed in the next major version. - - > [!Note] - > If you specify `company` and/or `user` they must have at least the `id` property, otherwise they will be ignored in their entirety. You should also supply anything additional you want to be able to evaluate flag targeting against, - -- `timeoutMs`: Timeout in milliseconds when fetching flags from the server, -- `staleWhileRevalidate`: If set to `true`, stale flags will be returned while refetching flags in the background, -- `expireTimeMs`: If set, flags will be cached between page loads for this duration (in milliseconds), -- `staleTimeMs`: Maximum time (in milliseconds) that stale flags will be returned if `staleWhileRevalidate` is true and new flags cannot be fetched. - -- `enableTracking`: Set to `false` to stop sending tracking events and user/company updates to Reflag. Useful when you're impersonating a user (defaults to `true`), -- `apiBaseUrl`: Optional base URL for the Reflag API. This also controls the SSE origin used for live flag updates and automated feedback, -- `credentials`: Optional fetch credentials mode. Set to `"include"` when proxying through your backend and authenticating with cookies; this also enables credentials for live-update SSE connections. -- `appBaseUrl`: Optional base URL for the Reflag application. Use this to override the default app URL, - -- `debug`: Set to `true` to enable debug logging to the console. If both `logger` and `debug` are provided, `logger` takes precedence, -- `logger`: Optional custom logger implementation (`debug`, `info`, `warn`, `error`) used by the underlying client, -- `toolbar`: Optional [configuration](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions) for the Reflag toolbar, -- `feedback`: Optional configuration for feedback collection - -### Loading states - -ReflagProvider lets you define a template to be shown while ReflagProvider is initializing: - -```vue ``` -If you want more control over loading screens, `useIsLoading()` returns a `Ref` which you can use to customize the loading experience. - -## `` component +Provider options forward Browser settings, including cache/storage, fallback values, offline/tracking, feedback, toolbar, credentials and API origins. `logger` takes precedence over `debug`. Live updates default to true; disable with `:enable-live-flag-updates="false"`. For an ordinary client-only Nuxt provider, wrap it in ``. -The `` component is a specialized version of `ReflagProvider` designed for server-side rendering and preloaded flag scenarios. It uses pre-fetched flags for the initial render, resulting in faster initial page loads and better SSR compatibility. - -### Usage +## `useFlag(key, defaultValue?)` ```vue - - -``` - -### Getting bootstrapped flags - -You'll typically generate the `bootstrappedFlags` object on your server using the Node.js SDK or by fetching from the Reflag API. Pass the full object returned by `getFlagsForBootstrap()` directly to ``. It contains: - -- `context`: the evaluation context used on the server -- `flags`: the evaluated raw flags -- `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping - -If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. - -With `ReflagBootstrappedProvider`, `useOptInFlags()` requests a flags refresh on first use. It reports `isLoading: true` until that refresh settles. - -Here's an example using the Node.js SDK: - -```js -// server.js (Node.js/SSR) -import { ReflagClient } from "@reflag/node-sdk"; - -const client = new ReflagClient({ - secretKey: "your-secret-key", // Use secret key on server -}); -await client.initialize(); - -// Fetch flags for specific context -const context = { - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, -}; - -const bootstrappedFlags = client.getFlagsForBootstrap(context); - -// Pass to your Vue app -``` +import { useFlag, useIsLoading, useTrack } from "@reflag/vue-sdk"; -### ReflagBootstrappedProvider Props - -`ReflagBootstrappedProvider` accepts all the same props as `ReflagProvider` except: - -- `flags`: The pre-fetched bootstrapped state object containing `context`, evaluated `flags`, and an optional `flagStateVersion` -- All other props available in `ReflagProvider` are supported except `context`, `user`, `company`, and `otherContext` (which are extracted from `flags.context`) - -If the `flags` prop is not provided or is undefined, the provider will not initialize the client and will render in a non-loading state. - -{% hint style="info" %} -After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. - -Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. -{% endhint %} - -## `` component - -The `` is a lower-level component that accepts a pre-initialized `ReflagClient` instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application. - -### ReflagClientProvider Usage - -```vue - ``` -### ReflagClientProvider Props +Vue unwraps refs in templates; use `.value` in script. This is a **Vue ref**, not a flag wrapper. There are no `.isEnabled`, `.config`, flag `.track()` or flag loading fields. -The `ReflagClientProvider` accepts the following props: - -- `client`: A pre-initialized `ReflagClient` instance +```ts +useFlag("release"); // ShallowRef +useFlag("model", "quick"); // ShallowRef +useFlag("limit", 10); // ShallowRef +useFlag("settings", { model: "quick" }); // ShallowRef<{ model: string }> +useFlag("nullable-settings", null); // ShallowRef +``` -### Slots +Defaults are positional JSON; literals widen without generated types. Non-null defaults require the same top-level category (Boolean/number/string/array/object), otherwise the default is returned with a payload-safe warning. Null explicitly accepts arbitrary JSON, including authored null; missing returns null. Valid false/zero/empty strings are preserved. Nested payload schemas are not validated by the SDK. Returned values/defaults are independent copies; readonly defaults are accepted. -- `loading`: Optional slot to show while the client is initializing (same as `ReflagProvider`) +The ref updates when evaluated flags change. A composable read registers the requested root through the Browser SDK, even if its result is ignored; refresh-driven rereads are identity-aware rate-limited and delivered in batches. Diagnostics/bootstrap inspection register none. Checks carry genuine selected key/source/snapshot identity, never payloads or invented selections for defaults/overrides. -> [!Note] -> Most applications should use `ReflagProvider` or `ReflagBootstrappedProvider` instead of `ReflagClientProvider`. Only use this component when you need the advanced control it provides. +## Loading, context and client access -## Hooks +- `useIsLoading()` returns a Boolean ref for provider loading; the `#loading` slot and `initialLoading` control initial presentation. +- `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return async shallow-update functions. +- `useClient()` exposes the Browser client, including `setContext(context)`, `refresh()` and `setFlagOverride(key, value)`. Undefined clears an override; null is a JSON override. +- `getFlags()` returns direct values and registers returned-root checks. Use `getFlagResults()` for tooling without checks. +- `useOnEvent(type, handler, client?)` subscribes on mount and unsubscribes on unmount. An external client may be supplied explicitly. -### `useFlag()` +A context change clears old values while fetching. Late responses for previous contexts or lower snapshot versions cannot replace accepted state. V2 cache/override storage is isolated from v1. Browser fetching uses `/flags/evaluated` and never re-evaluates/caches dependencies locally. -Returns the state of a given flag for the current context. The composable provides access to flags and their configurations. +## Bootstrap -`useFlag()` returns an object with this shape: +On the server, use Node SDK v2 and your framework's safe serialization mechanism: ```ts -{ - isEnabled: boolean, // is the flag enabled - track: () => void, // send a track event when the flag is used - requestFeedback: (...) => void // open up a feedback dialog - config: {key: string, payload: any}, // remote configuration for this flag - isLoading: boolean // if you want to manage loading state at the flag level -} +const flags = serverClient.getFlagsForBootstrap(context); ``` -Example: - ```vue - - - + + + ``` -See the reference docs for details. +Pass the entire envelope (`protocolVersion: 2`, context, evaluated flags and optional snapshot version). Legacy v1 bootstrap is rejected. A snapshot version is required for live updates. Never expose secret keys/server-only attributes in bootstrap data; later refreshes use browser-visible context, so disable live updates when they must not replace server-only evaluations. -### `useOptInFlags()` and `useSetOptIn()` +`ReflagClientProvider` accepts an externally initialized Browser v2 client. Its lifecycle belongs to the application. -Use these composables to build an end-user opt-in UI for flags where opt-in is enabled in Reflag. +## Opt-in, tracking and feedback -```vue - - - -``` - -By default, `useSetOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. - -User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. - -`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and subscribers have been notified when flags change. Vue may not have committed the resulting render yet. - -The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. - -`useOptInFlags()` returns `{ flags, isLoading }`, where both values are computed refs. With `ReflagBootstrappedProvider`, it fetches opt-in metadata on first use and reports `isLoading: true` until that refresh succeeds or fails. - -If fetching opt-in metadata fails, loading ends without exposing an error. Call `client.refresh()` on the client returned by `useClient()` to retry. - -With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal initial flags request, so `useOptInFlags().isLoading` remains `false`. Use the general `useIsLoading()` composable or the provider's loading slot for that initial loading state. - -### `useTrack()` - -`useTrack()` returns a function which lets you send custom events to Reflag. It takes a string argument with the event name and optionally an object with properties to attach the event. - -Using `track` returned from `useFlag()` calls this track function with the flag key as the event name. - -```vue - - - -``` - -### `useRequestFeedback()` - -Returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features. - -See [Automated Feedback Surveys](https://docs.reflag.com/product-handbook/live-satisfaction) for how to do this automatically, without code. - -When using the `useRequestFeedback` you must pass the flag key to `requestFeedback`. -The example below shows how to use `position` to ensure the popover appears next to the "Give feedback!" button. - -```vue - - - -``` - -See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/FEEDBACK.md#manual-feedback-collection) for more information on `requestFeedback` options. - -### `useSendFeedback()` - -Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag. - -```vue - - - +await sendFeedback({ flagKey: "huddles", score: 5 }); ``` -### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` +Opt-in metadata arrives with ordinary `/flags/evaluated` responses. Bootstrapped providers fetch missing metadata on demand from the same v2 endpoint without replacing server-derived values or provenance; loading settles on success or failure. User/company grants remain independent; successful mutations confirm versioned evaluation and membership in a single refresh. The metadata list retains presentation/membership fields such as `isEnabled`; ordinary reads remain direct values. -These composables return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session. +`enableTracking: false` disables checks and ordinary tracking. Offline mode skips HTTP/tracking. See [Browser feedback documentation](../browser-sdk/feedback.md) for prompting/UI options. -```vue - - - -``` - -Note: To change the `user.id` or `company.id`, you need to update the props passed to `ReflagProvider` instead of using these composables. - -### `useClient()` - -Returns the `ReflagClient` used by the `ReflagProvider`. The client offers more functionality that -is not directly accessible through the other composables. - -```vue - - - -``` - -### `useIsLoading()` - -Returns a `Ref` to indicate if Reflag has finished loading. -Initially, the value will be `true` if no bootstrap flags have been provided and the client has not be initialized. - -```vue - - - -``` +## Optional key registration and migration -### `useOnEvent()` - -Vue composable for listening to Reflag client events. This composable automatically handles mounting and unmounting of event listeners. - -Available events include: - -- `flagsUpdated`: Triggered when flags are updated -- `track`: Triggered when tracking events are sent -- `feedback`: Triggered when feedback is sent - -```vue - - - -``` - -You can also provide a specific client instance if needed: - -```vue - - - +```ts +import "@reflag/vue-sdk"; +declare module "@reflag/vue-sdk" { + interface Flags { + huddles: boolean; + "huddle-settings": { maxParticipants: number }; + } +} ``` -## Content Security Policy (CSP) - -See [CSP](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/README.md#content-security-policy-csp) for info on using Reflag React SDK with CSP - -## License - -MIT License +Registration constrains keys and checks non-null defaults against the registered value schema, including required and nested properties. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request; bare/`undefined` reads remain Boolean refs. Positional defaults still determine widened direct-value types, and generated declarations do not add nested runtime validation. The v2 CLI generates these schemas from current production-environment variants with `--format vue`; regenerate old wrapper declarations when migrating. -Copyright (c) 2025 Bucket ApS +Replace `const { isEnabled } = useFlag(key)` with `const enabled = useFlag(key)` (then `enabled.value` in script). Replace remote-config wrappers with separately authored multivariate flags and positional defaults, and move usage/feedback into their separate composables. Bootstrap both ends with v2. This branch does not publish SDKs or deploy the required server changes. diff --git a/supported-languages/vue-sdk/globals.md b/supported-languages/vue-sdk/globals.md index 0ae59b1..166c3b3 100644 --- a/supported-languages/vue-sdk/globals.md +++ b/supported-languages/vue-sdk/globals.md @@ -13,13 +13,21 @@ pagination: visible: true --- +{% hint style="info" %} +**Protocol v2.** [Legacy v1 documentation](../../legacy/v1/vue-sdk/globals.md) · [Migration guide](../migrating-from-v1.md) + +**Prerelease source documentation.** The installation examples target major 2; use them only when the matching SDK/CLI packages are available. A server rollout alone does not publish npm packages. + +Generated from [`@reflag/vue-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/vue-sdk); SDK READMEs and code comments remain the source of truth. +{% endhint %} + # @reflag/vue-sdk ## Interfaces ### CheckEvent -Event representing checking the flag evaluation result +A root read records selection identity, never its JSON payload. #### Properties @@ -28,7 +36,6 @@ Event representing checking the flag evaluation result
- @@ -40,53 +47,38 @@ Event representing checking the flag evaluation result - - - + + + - + + - - + + @@ -224,127 +214,6 @@ Company name *** -### Flag\ - -#### Type Parameters - -
-[`FlagKey`](globals.md#flagkey) +[`FlagKey`](../../../supported-languages/vue-sdk/globals.md#flagkey)
-[`Logger`](../browser-sdk/globals.md#logger-1) +[`Logger`](../../../supported-languages/browser-sdk/globals.md#logger) @@ -723,7 +517,7 @@ Props for the ReflagBootstrappedProvider. -[`BootstrappedFlags`](globals.md#bootstrappedflags) +[`BootstrappedFlags`](../../../supported-languages/vue-sdk/globals.md#bootstrappedflags) @@ -767,7 +561,7 @@ Props for the ReflagClientProvider. -[`ReflagClient`](../browser-sdk/globals.md#reflagclient) +[`ReflagClient`](../../../supported-languages/browser-sdk/globals.md#reflagclient) @@ -784,7 +578,7 @@ A pre-initialized ReflagClient to use. ### ReflagInitOptionsBase ```ts -type ReflagInitOptionsBase = Omit -[`CompanyContext`](globals.md#companycontext) +[`CompanyContext`](../../../supported-languages/vue-sdk/globals.md#companycontext) @@ -854,7 +648,7 @@ Use `context` instead, this property will be removed in the next major version -[`ReflagContext`](../browser-sdk/globals.md#reflagcontext) +[`ReflagContext`](../../../supported-languages/browser-sdk/globals.md#reflagcontext) @@ -892,7 +686,7 @@ Use `context` instead, this property will be removed in the next major version -[`UserContext`](globals.md#usercontext) +[`UserContext`](../../../supported-languages/vue-sdk/globals.md#usercontext) @@ -928,7 +722,7 @@ type SetOptInOptions = { }; ``` -Options for changing the current user or company's opt-in membership. +Represents a flag. #### Type declaration @@ -1023,7 +817,7 @@ type TrackEvent = { -[`CompanyContext`](globals.md#companycontext) +[`CompanyContext`](../../../supported-languages/vue-sdk/globals.md#companycontext)
-[`UserContext`](globals.md#usercontext) +[`UserContext`](../../../supported-languages/vue-sdk/globals.md#usercontext)
-`ComputedRef`\<[`OptInFlag`](globals.md#optinflag)[]\> +`ComputedRef`\<[`OptInFlag`](../../../supported-languages/vue-sdk/globals.md#optinflag)[]\>
- `isLoading` + `isLoading` @@ -1168,7 +962,7 @@ client at any point in your application. #### Returns -[`ReflagClient`](../browser-sdk/globals.md#reflagclient) +[`ReflagClient`](../../../supported-languages/browser-sdk/globals.md#reflagclient) The Reflag client. @@ -1186,15 +980,64 @@ console.log(client.getContext()); ### useFlag() +#### Call Signature + ```ts -function useFlag(key: TKey): TypedFlags[TKey] +function useFlag(key: string, defaultValue?: undefined): ShallowRef ``` -Vue composable for getting the state of a given flag for the current context. +Reactive direct values: Boolean/false by default, or infer a positional JSON default. -This composable returns an object with the state of the flag for the current context. +##### Parameters -#### Type Parameters + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`defaultValue`? + + + +`undefined` + +
+ +##### Returns + +`ShallowRef`\<`boolean`\> + +#### Call Signature + +```ts +function useFlag(key: Key, defaultValue: Default): ShallowRef> +``` + +Reactive direct values: Boolean/false by default, or infer a positional JSON default. + +##### Type Parameters @@ -1206,21 +1049,27 @@ This composable returns an object with the state of the flag for the current con + + +
-`TKey` *extends* `string` +`Key` *extends* `string` + +
+ +`Default` *extends* `object` \| [`FlagDefaultValue`](../../../supported-languages/vue-sdk/globals.md#flagdefaultvalue)
-#### Parameters +##### Parameters - @@ -1232,37 +1081,96 @@ This composable returns an object with the state of the flag for the current con + + +
Parameter TypeDescription
-`TKey` +`Key` + +
+ +`defaultValue` -The key of the flag to get the state of. +`Default`
-#### Returns - -[`TypedFlags`](globals.md#typedflags)\[`TKey`\] +##### Returns -An object with the state of the flag. +`ShallowRef`\<[`FlagValueFromDefault`](../../../supported-languages/vue-sdk/globals.md#flagvaluefromdefaultt)\<`Default`\>\> -#### Example +#### Call Signature ```ts -import { useFlag } from '@reflag/vue-sdk'; +function useFlag(key: string, defaultValue: Default): ShallowRef> +``` -const { isEnabled, config, track, requestFeedback } = useFlag("huddles"); +Reactive direct values: Boolean/false by default, or infer a positional JSON default. -function StartHuddlesButton() { - const { isEnabled, config: { payload }, track } = useFlag("huddles"); - if (isEnabled) { - return ; -} -``` +##### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`Default` *extends* `object` \| [`FlagDefaultValue`](../../../supported-languages/vue-sdk/globals.md#flagdefaultvalue) + +
+ +##### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`defaultValue` + + + +`Default` + +
+ +##### Returns + +`ShallowRef`\<[`FlagValueFromDefault`](../../../supported-languages/vue-sdk/globals.md#flagvaluefromdefaultt)\<`Default`\>\> *** @@ -1298,8 +1206,8 @@ console.log(isLoading); ```ts function useOnEvent( - event: THookType, - handler: (arg0: HookArgs[THookType]) => void, + event: THookType, + handler: (arg0: HookArgs[THookType]) => void, client?: ReflagClient): void ``` @@ -1317,7 +1225,7 @@ Vue composable for listening to Reflag client events.
-`THookType` *extends* keyof [`HookArgs`](../browser-sdk/globals.md#hookargs) +`THookType` *extends* keyof [`HookArgs`](../../../supported-languages/browser-sdk/globals.md#hookargs)
-(`arg0`: [`HookArgs`](../browser-sdk/globals.md#hookargs)\[`THookType`\]) => `void` +(`arg0`: [`HookArgs`](../../../supported-languages/browser-sdk/globals.md#hookargs)\[`THookType`\]) => `void` @@ -1377,7 +1285,7 @@ The function to call when the event is triggered. -[`ReflagClient`](../browser-sdk/globals.md#reflagclient) +[`ReflagClient`](../../../supported-languages/browser-sdk/globals.md#reflagclient) @@ -1416,14 +1324,11 @@ the current context. The loading state is only used with `ReflagBootstrappedProvider` while opt-in metadata is fetched on demand. Regular providers load opt-in metadata -with the initial flags; use [useIsLoading](globals.md#useisloading) for their loading state. - -If fetching opt-in metadata fails, loading ends without exposing an error. -Call `refresh()` on the client returned by [useClient](globals.md#useclient) to retry. +with the initial flags. #### Returns -[`UseOptInFlagsResult`](globals.md#useoptinflagsresult) +[`UseOptInFlagsResult`](../../../supported-languages/vue-sdk/globals.md#useoptinflagsresult) *** @@ -1464,7 +1369,7 @@ A function that requests feedback from the user. The function accepts: -[`RequestFeedbackData`](../browser-sdk/globals.md#requestfeedbackdata) +[`RequestFeedbackData`](../../../supported-languages/browser-sdk/globals.md#requestfeedbackdata)
-[`UnassignedFeedback`](../browser-sdk/globals.md#unassignedfeedback) +[`UnassignedFeedback`](../../../supported-languages/browser-sdk/globals.md#unassignedfeedback)
-[`SetOptInOptions`](globals.md#setoptinoptions) +[`SetOptInOptions`](../../../supported-languages/vue-sdk/globals.md#setoptinoptions)
Property TypeDescription
-`"check-is-enabled"` \| `"check-config"` - - - -`check-is-enabled` means `isEnabled` was checked, `check-config` means `config` was checked. +`"check"`
- `evaluationErrors?` - - - -\{ `code`: `string`; `field`: `string`; `message`: `string`; `operator`: `string`; \}[] + `evalContext?` -Non-fatal diagnostics produced while evaluating the flag. +[`ReflagContext`](../browser-sdk/globals.md#reflagcontext)
- `key` + `evalErrors?` -`string` - - - -Flag key. +[`EvaluationError`](../browser-sdk/globals.md#evaluationerror)[]
- ~~`missingContextFields?`~~ + `evalMissingFields?` @@ -94,66 +86,64 @@ Flag key. `string`[]
-Missing context fields. + `evalResult?` -**Deprecated** + -Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. +`string`
- `ruleEvaluationResults?` + `evalRuleResults?` `boolean`[] - - -Rule evaluation results. -
- `value?` + `flagStateVersion?` - \| `boolean` \| \{ `key`: `string`; `payload`: `any`; \} +`number`
-Result of flag or configuration evaluation. -If `action` is `check-is-enabled`, this is the result of the flag evaluation and `value` is a boolean. -If `action` is `check-config`, this is the result of the configuration evaluation. + `key`
- `version?` +`string`
-`number` + `sourceVersionId?` -Version of targeting rules. +`string`
- - - - - - - - - - - - -
Type ParameterDefault type
- -`TConfig` *extends* [`FlagType`](globals.md#flagtype)\[`"config"`\] - - - -[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) - -
- -#### Properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyType
- - `config` - - - -`Ref`\< \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| \{ `key`: `string`; \} & `TConfig`, \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| \{ `key`: `string`; \} & `TConfig`\> - -
- - `isEnabled` - - - -`Ref`\<`boolean`, `boolean`\> - -
- - `isLoading` - - - -`Ref`\<`boolean`, `boolean`\> - -
- - `key` - - - -`string` - -
- - `requestFeedback` - - - -(`opts`: [`RequestFlagFeedbackOptions`](globals.md#requestflagfeedbackoptions)) => `void` - -
- -#### Methods - -##### track() - -```ts -track(): - | undefined - | Promise< - | undefined -| Response> -``` - -###### Returns - - \| `undefined` - \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< - \| `undefined` - \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> - -*** - ### Flags *** @@ -431,137 +300,68 @@ User name ### BootstrappedFlags ```ts -type BootstrappedFlags = BootstrappedState & { - flags: RawFlags; -}; +type BootstrappedFlags = BootstrappedState; ``` -#### Type declaration - - - - - - - - - - - - - - -
NameType
- -`flags` - - - -[`RawFlags`](../browser-sdk/globals.md#rawflags) - -
- *** -### EmptyFlagRemoteConfig +### FlagDefaultValue ```ts -type EmptyFlagRemoteConfig = { - key: undefined; - payload: undefined; -}; +type FlagDefaultValue = + | null + | boolean + | number + | string + | readonly FlagDefaultValue[] +| {}; ``` -#### Type declaration - - - - - - - - - - - - - - - - - - -
NameType
- - `key` - - - -`undefined` - -
- - `payload` - - +*** -`undefined` +### FlagKey -
+```ts +type FlagKey = keyof Flags extends never ? string : Extract; +``` *** -### FlagKey +### FlagValue ```ts -type FlagKey = keyof TypedFlags; +type FlagValue = + | null + | boolean + | number + | string + | FlagValue[] +| {}; ``` *** -### FlagType +### FlagValueFromDefault\ ```ts -type FlagType = { - config: { - payload: any; - }; -}; +type FlagValueFromDefault = T extends null ? FlagValue : T extends boolean ? boolean : T extends number ? number : T extends string ? string : T extends readonly infer Element[] ? [Element] extends [never] ? FlagValue[] : FlagValueFromDefault[] : T extends object ? { -readonly [Key in keyof T]: FlagValueFromDefault } : never; ``` -#### Type declaration +Widen literals and return mutable copies. Null requests arbitrary JSON. + +#### Type Parameters - - + - - - - - @@ -578,12 +378,6 @@ type OptInFlag = Omit & { }; ``` -An opt-in-enabled flag for the generated Vue SDK flag definitions. - -Includes all fields from [BrowserOptInFlag](../browser-sdk/globals.md#optinflag): `name`, `description`, -`isEnabled`, `userOptedIn`, `companyOptedIn`, and `isOptedIn`. -Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. - #### Type declaration
NameTypeType Parameter
- `config`? - - - -\{ - `payload`: `any`; - \} - -
- -`config.payload` - - - -`any` +`T`
@@ -678,7 +472,7 @@ Set to `true` to show the loading component while the client is initializing.
-[`Logger`](../browser-sdk/globals.md#logger-1) +[`Logger`](../browser-sdk/globals.md#logger) @@ -784,7 +578,7 @@ A pre-initialized ReflagClient to use. ### ReflagInitOptionsBase ```ts -type ReflagInitOptionsBase = Omit : { [TypedFlagKey in keyof Flags]: Flags[TypedFlagKey] extends FlagType ? Flag : Flag }; +type TypedFlags = keyof Flags extends never ? Record : { [Key in keyof Flags]: Flags[Key] | undefined }; ``` *** @@ -1098,7 +892,7 @@ type UseOptInFlagsResult = {
- `isLoading` + `isLoading` @@ -1186,15 +980,64 @@ console.log(client.getContext()); ### useFlag() +#### Call Signature + ```ts -function useFlag(key: TKey): TypedFlags[TKey] +function useFlag(key: string, defaultValue?: undefined): ShallowRef ``` -Vue composable for getting the state of a given flag for the current context. +Reactive direct values: Boolean/false by default, or infer a positional JSON default. -This composable returns an object with the state of the flag for the current context. +##### Parameters -#### Type Parameters + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`defaultValue`? + + + +`undefined` + +
+ +##### Returns + +`ShallowRef`\<`boolean`\> + +#### Call Signature + +```ts +function useFlag(key: Key, defaultValue: Default): ShallowRef> +``` + +Reactive direct values: Boolean/false by default, or infer a positional JSON default. + +##### Type Parameters @@ -1206,21 +1049,27 @@ This composable returns an object with the state of the flag for the current con + + +
-`TKey` *extends* `string` +`Key` *extends* `string` + +
+ +`Default` *extends* `object` \| [`FlagDefaultValue`](globals.md#flagdefaultvalue)
-#### Parameters +##### Parameters - @@ -1232,37 +1081,96 @@ This composable returns an object with the state of the flag for the current con + + +
Parameter TypeDescription
-`TKey` +`Key`
-The key of the flag to get the state of. +`defaultValue` + + + +`Default`
-#### Returns - -[`TypedFlags`](globals.md#typedflags)\[`TKey`\] +##### Returns -An object with the state of the flag. +`ShallowRef`\<[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\>\> -#### Example +#### Call Signature ```ts -import { useFlag } from '@reflag/vue-sdk'; +function useFlag(key: string, defaultValue: Default): ShallowRef> +``` -const { isEnabled, config, track, requestFeedback } = useFlag("huddles"); +Reactive direct values: Boolean/false by default, or infer a positional JSON default. -function StartHuddlesButton() { - const { isEnabled, config: { payload }, track } = useFlag("huddles"); - if (isEnabled) { - return ; -} -``` +##### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`Default` *extends* `object` \| [`FlagDefaultValue`](globals.md#flagdefaultvalue) + +
+ +##### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`defaultValue` + + + +`Default` + +
+ +##### Returns + +`ShallowRef`\<[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\>\> *** @@ -1298,8 +1206,8 @@ console.log(isLoading); ```ts function useOnEvent( - event: THookType, - handler: (arg0: HookArgs[THookType]) => void, + event: THookType, + handler: (arg0: HookArgs[THookType]) => void, client?: ReflagClient): void ``` @@ -1416,10 +1324,7 @@ the current context. The loading state is only used with `ReflagBootstrappedProvider` while opt-in metadata is fetched on demand. Regular providers load opt-in metadata -with the initial flags; use [useIsLoading](globals.md#useisloading) for their loading state. - -If fetching opt-in metadata fails, loading ends without exposing an error. -Call `refresh()` on the client returned by [useClient](globals.md#useclient) to retry. +with the initial flags. #### Returns @@ -1568,11 +1473,6 @@ function useSetOptIn(): (key: string, options: SetOptInOptions) => Promise< Vue composable for setting whether the current user or company has opted into a flag. -Check the returned Response's `ok` property and catch promise rejections. -HTTP failures return a non-OK Response; offline mode, invalid arguments, or -missing scoped context return undefined. Confirmation failures can reject -after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sdk/globals.md#setoptin). - #### Returns `Function` @@ -1625,7 +1525,7 @@ after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sd ### useTrack() ```ts -function useTrack(): (eventName: string, attributes?: +function useTrack(): (eventName: string, attributes?: | null | Record) => Promise< | undefined From 3d3bb136b26ace8d8ed08828f363d9afc292ea86 Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:30:10 +0000 Subject: [PATCH 02/18] fix: preserve SDK heading anchors in GitBook --- .generated/sdk-docs/browser-sdk/v1.json | 6 +- .generated/sdk-docs/browser-sdk/v2.json | 12 +- .generated/sdk-docs/node-sdk/v1.json | 4 +- .generated/sdk-docs/node-sdk/v2.json | 8 +- .generated/sdk-docs/react-native-sdk/v0.json | 10 +- .generated/sdk-docs/react-sdk/v1.json | 4 +- .generated/sdk-docs/react-sdk/v2.json | 10 +- .generated/sdk-docs/vue-sdk/v1.json | 4 +- .generated/sdk-docs/vue-sdk/v2.json | 8 +- .github/scripts/sdk-docs.mjs | 35 + .github/scripts/sdk-docs.test.mjs | 19 +- legacy/v1/browser-sdk/README.md | 54 +- legacy/v1/browser-sdk/feedback.md | 40 +- legacy/v1/browser-sdk/globals.md | 392 +++++----- legacy/v1/node-sdk/README.md | 80 +-- legacy/v1/node-sdk/globals.md | 680 +++++++++--------- legacy/v1/react-sdk/README.md | 76 +- legacy/v1/react-sdk/globals.md | 230 +++--- legacy/v1/vue-sdk/README.md | 68 +- legacy/v1/vue-sdk/globals.md | 208 +++--- sdk/@reflag/browser-sdk/README.md | 20 +- sdk/@reflag/browser-sdk/globals.md | 420 +++++------ sdk/@reflag/node-sdk/README.md | 24 +- sdk/@reflag/node-sdk/globals.md | 650 ++++++++--------- sdk/@reflag/react-native-sdk/README.md | 22 +- sdk/@reflag/react-native-sdk/globals.md | 222 +++--- sdk/@reflag/react-sdk/README.md | 20 +- sdk/@reflag/react-sdk/globals.md | 270 +++---- sdk/@reflag/vue-sdk/README.md | 14 +- sdk/@reflag/vue-sdk/globals.md | 208 +++--- sdk/documents/browser-sdk/FEEDBACK.md | 40 +- sdk/documents/react-native-sdk/README.md | 22 +- sdk/documents/react-sdk/README.md | 20 +- supported-languages/browser-sdk/README.md | 20 +- supported-languages/browser-sdk/feedback.md | 40 +- supported-languages/browser-sdk/globals.md | 420 +++++------ supported-languages/node-sdk/README.md | 24 +- supported-languages/node-sdk/globals.md | 650 ++++++++--------- .../react-native-sdk/README.md | 22 +- .../react-native-sdk/globals.md | 222 +++--- supported-languages/react-sdk/README.md | 20 +- supported-languages/react-sdk/globals.md | 270 +++---- supported-languages/vue-sdk/README.md | 14 +- supported-languages/vue-sdk/globals.md | 208 +++--- 44 files changed, 2931 insertions(+), 2879 deletions(-) diff --git a/.generated/sdk-docs/browser-sdk/v1.json b/.generated/sdk-docs/browser-sdk/v1.json index 1881b05..b1e102f 100644 --- a/.generated/sdk-docs/browser-sdk/v1.json +++ b/.generated/sdk-docs/browser-sdk/v1.json @@ -4,8 +4,8 @@ "package": "@reflag/browser-sdk", "version": "1.7.4", "files": { - "legacy/v1/browser-sdk/README.md": "b949d2d5c5d9f2eb4bca99c97d6fad63d95d6ba03592bdb01dc9c632d854fea2", - "legacy/v1/browser-sdk/globals.md": "a45fb2bb4784310a826b109bf9e361bcb552974791ee9f142514353eb8da0600", - "legacy/v1/browser-sdk/feedback.md": "f2507ea56bbef40b7acafed1f05d55261905e68aa2a8097eee48e348cecc0177" + "legacy/v1/browser-sdk/README.md": "b090a9913b825df8d3e6baecc30aecff8a2a235451152314b78d96e7851be630", + "legacy/v1/browser-sdk/globals.md": "a3250063ef38ea283fd6d467dc416bf7f80da6867b84773fc79559c32d711f2b", + "legacy/v1/browser-sdk/feedback.md": "e6b4e0cc3056f1cddc2164c05ed15fdb996f5b8f675a4ae20766b38d88f34305" } } diff --git a/.generated/sdk-docs/browser-sdk/v2.json b/.generated/sdk-docs/browser-sdk/v2.json index ed9147e..6ea0cde 100644 --- a/.generated/sdk-docs/browser-sdk/v2.json +++ b/.generated/sdk-docs/browser-sdk/v2.json @@ -4,11 +4,11 @@ "package": "@reflag/browser-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/browser-sdk/README.md": "ec01a2b277092690794f16ac8c50658633985e8b2157b87af6efae1ca0843a25", - "sdk/@reflag/browser-sdk/README.md": "af928c7dfac25302f70d5bde6082b3029ccf62f6ef3194c853579190e8d8a257", - "supported-languages/browser-sdk/globals.md": "13ca9d9b3e51933e730e1ae37c969d94d0af8b75d766b3ca8e1d3c04b7013d27", - "sdk/@reflag/browser-sdk/globals.md": "8d802a419e6abb9233bd74552a36a9ed8bda9785b9d193bb5f9da61cab796723", - "supported-languages/browser-sdk/feedback.md": "c0d799195022b39cd0b12a12c39ec7728d8dc40c5b4874f01934177e15daffa5", - "sdk/documents/browser-sdk/FEEDBACK.md": "9607d6e90d45158106fead43881f5cb8450f692b7fdb02e609e32fafcb8acf3a" + "supported-languages/browser-sdk/README.md": "d8b1b0ec1a47e763a7ceb03dc7111341ace17792d44bc1885650998ed99cdb72", + "sdk/@reflag/browser-sdk/README.md": "873e3b3be0e0e5e0c84cf6a31dd379ad790ef984ff8e7e7f39bb89540682faf4", + "supported-languages/browser-sdk/globals.md": "1df4e9a0a1052e363f31df176dbba9d11d76fd57a934f876e8fcadd18c89e9a6", + "sdk/@reflag/browser-sdk/globals.md": "3a6a4c5dcab9691a33c70d7263d55ee51decca7a6ade3b9d26fbf6b818583856", + "supported-languages/browser-sdk/feedback.md": "bb86d515cd28ed153026885ed3241273825b8995491396256fb00cdbddc92f75", + "sdk/documents/browser-sdk/FEEDBACK.md": "bf9979efd7d8e5ba802e88459d61575f3172d223ca2e551fc5ac7d7e232c72ed" } } diff --git a/.generated/sdk-docs/node-sdk/v1.json b/.generated/sdk-docs/node-sdk/v1.json index 61858d4..5bc0e57 100644 --- a/.generated/sdk-docs/node-sdk/v1.json +++ b/.generated/sdk-docs/node-sdk/v1.json @@ -6,7 +6,7 @@ "files": { "legacy/v1/_media/type-check-failed.png": "f04547c0bf0425bcf554aa1a1dddec56096ca9967d120bdca7737562327d4db8", "legacy/v1/_media/type-check-payload-failed.png": "8b53c24ecd19288111bda14eab7c490f7e26abba569eea11e16504cc7abeb54a", - "legacy/v1/node-sdk/README.md": "a5cdfc5e190f99930970ada4e8bf84cd448c318143b17853db4e0655f01450be", - "legacy/v1/node-sdk/globals.md": "16458989c24ed3d4762d969dd2a1f827c2600fc82ad13e8280cc5d8ab01ae4d2" + "legacy/v1/node-sdk/README.md": "40753985d1766113d3dcfb271d74bc770207a6599393438ca9aad14f6a02696d", + "legacy/v1/node-sdk/globals.md": "eef5e5e976ba25ca4acc7006cdcbb6b4c23817ab7c10745401eecb748f84f358" } } diff --git a/.generated/sdk-docs/node-sdk/v2.json b/.generated/sdk-docs/node-sdk/v2.json index ae3b4bb..b9c9214 100644 --- a/.generated/sdk-docs/node-sdk/v2.json +++ b/.generated/sdk-docs/node-sdk/v2.json @@ -4,9 +4,9 @@ "package": "@reflag/node-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/node-sdk/README.md": "b834d55e0e66ea4fa3a2f726f4b3d5f2ae7ea91a22456cf8d2db60c358ad9a45", - "sdk/@reflag/node-sdk/README.md": "27d170717e75d99eb8e10fbbedf17c84cd1e8fffd95c655fd3fe60780bea222d", - "supported-languages/node-sdk/globals.md": "1bab9869b7a1779fc7a5e25ec076f7fbeecd11a3703c8b8e26fcf6184887cf75", - "sdk/@reflag/node-sdk/globals.md": "2c92c66aa42ccdadfae1bad027f42a240379227f71764d04205d4483e519ccb7" + "supported-languages/node-sdk/README.md": "af436dd97f0f6fad6db86e947ecc05b7466804ff9d95121d4240323089cb7796", + "sdk/@reflag/node-sdk/README.md": "2b86f2e8a2a29c1b410a21240f3f23a67a50f1bba9fac6c13f7b086ce26a13e1", + "supported-languages/node-sdk/globals.md": "2c85d6c65f3a3be1a1c0c9072923d3487f7b694ea5fad5a700baa354f6f8bd74", + "sdk/@reflag/node-sdk/globals.md": "a25edb601d2b7d263589f147000b61aebc9a2a83c03ba7a30b9561a04805a5c8" } } diff --git a/.generated/sdk-docs/react-native-sdk/v0.json b/.generated/sdk-docs/react-native-sdk/v0.json index 752ea8c..5d14aaf 100644 --- a/.generated/sdk-docs/react-native-sdk/v0.json +++ b/.generated/sdk-docs/react-native-sdk/v0.json @@ -4,10 +4,10 @@ "package": "@reflag/react-native-sdk", "version": "0.3.7", "files": { - "supported-languages/react-native-sdk/README.md": "0a9952a6a72c21c6c5baec486671c968e3b290752dbc18a6239a4d3aa4325195", - "sdk/@reflag/react-native-sdk/README.md": "360b297aeb72f6ac7accf9f16707437eb4c01ebd060f5f56870764c2f6fa0ad9", - "sdk/documents/react-native-sdk/README.md": "360b297aeb72f6ac7accf9f16707437eb4c01ebd060f5f56870764c2f6fa0ad9", - "supported-languages/react-native-sdk/globals.md": "b7cd9cc4f5bece6e701fcae3ece028e2ce7588d0a3fbb6f170c69b01eac18ac3", - "sdk/@reflag/react-native-sdk/globals.md": "d028c5ff2ad94e2ae670aea1ff159786cc9f117e674af510ee625b1d6e9f7205" + "supported-languages/react-native-sdk/README.md": "2ae69a40046d515f59ffd90e3eb8c18c159d582e74aa55bf96defa63228f0424", + "sdk/@reflag/react-native-sdk/README.md": "ecf2a23a9ca454ec7f3bd9dbe5e4664d9a93e0a7a1b4ca35637295ec22084b8b", + "sdk/documents/react-native-sdk/README.md": "ecf2a23a9ca454ec7f3bd9dbe5e4664d9a93e0a7a1b4ca35637295ec22084b8b", + "supported-languages/react-native-sdk/globals.md": "06a0f5349886e508b07709fc51356151c21a747f6c46ba70f173bacd9f988ad6", + "sdk/@reflag/react-native-sdk/globals.md": "34ea55c548c3580033d4af2a70564240ec45e3072e10db46f216657e0200627d" } } diff --git a/.generated/sdk-docs/react-sdk/v1.json b/.generated/sdk-docs/react-sdk/v1.json index c2da38f..6dad916 100644 --- a/.generated/sdk-docs/react-sdk/v1.json +++ b/.generated/sdk-docs/react-sdk/v1.json @@ -4,7 +4,7 @@ "package": "@reflag/react-sdk", "version": "1.7.4", "files": { - "legacy/v1/react-sdk/README.md": "d0f7ae8c094dfef0064ed19c5f6f78b74bc876f321b7b92b9c47b9d9db12e79a", - "legacy/v1/react-sdk/globals.md": "fb761c2ca1208bc90cd08eea64c0167ea63e84a19d02d7a9497694505ae2dc36" + "legacy/v1/react-sdk/README.md": "109a2a300fa2d1d77064ff41cc3d073acacf715b88d1c780f82f65c88981258b", + "legacy/v1/react-sdk/globals.md": "772b03ebe7edd5ad22964525f939f9f938c616c69e07c8bf49fe6b59e498474c" } } diff --git a/.generated/sdk-docs/react-sdk/v2.json b/.generated/sdk-docs/react-sdk/v2.json index 55d99db..70a48bb 100644 --- a/.generated/sdk-docs/react-sdk/v2.json +++ b/.generated/sdk-docs/react-sdk/v2.json @@ -4,10 +4,10 @@ "package": "@reflag/react-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/react-sdk/README.md": "895ea9b16b4e6a3775bb5813abf472b631aa778341b1be35b2221ce1112a60d9", - "sdk/@reflag/react-sdk/README.md": "0a170cf33a8bff4df2daed6b086a1c919da72c605532d2917d52a293223289d5", - "sdk/documents/react-sdk/README.md": "0a170cf33a8bff4df2daed6b086a1c919da72c605532d2917d52a293223289d5", - "supported-languages/react-sdk/globals.md": "0c3eec56a80b4080882308794b01ae041f53713aed83ac75a9a8a9e7d786c6ce", - "sdk/@reflag/react-sdk/globals.md": "6dbfd4e00a45765c20fadb1594b3279c1279264eb021afdc83543af67a8813ae" + "supported-languages/react-sdk/README.md": "3caa29755bc7a582c01545cfbaaaddf0d5fd8f1e84cc123e73f98d6b5b519bbb", + "sdk/@reflag/react-sdk/README.md": "b93d25281a6a82acc793c64017a2d254b02bb66f1f70326e16b24810f6427c5a", + "sdk/documents/react-sdk/README.md": "b93d25281a6a82acc793c64017a2d254b02bb66f1f70326e16b24810f6427c5a", + "supported-languages/react-sdk/globals.md": "16ec44f49748d59985e4a13674931ec1722fb7d85d0b901030f62841436f2b33", + "sdk/@reflag/react-sdk/globals.md": "8f6bfaffb9a504aa68e3c4f537500d25be7b0951ad1c18197fee352295470bc8" } } diff --git a/.generated/sdk-docs/vue-sdk/v1.json b/.generated/sdk-docs/vue-sdk/v1.json index e95d45c..b04308a 100644 --- a/.generated/sdk-docs/vue-sdk/v1.json +++ b/.generated/sdk-docs/vue-sdk/v1.json @@ -4,7 +4,7 @@ "package": "@reflag/vue-sdk", "version": "1.5.7", "files": { - "legacy/v1/vue-sdk/README.md": "64a47b3fa4fd104f19fd14250e34438a00c5b5c0474573d68fb7af0aa40442ce", - "legacy/v1/vue-sdk/globals.md": "c6053f46cef5bce2882434cbeb1003d0f08f35147f5d98eb7d8276e572c831bb" + "legacy/v1/vue-sdk/README.md": "2f05a529e8d056a89967a48a8df050fdf9c8c0c05bac7784bc80289faecc147d", + "legacy/v1/vue-sdk/globals.md": "a636b697713d0bb56e74d9a405ab4e83a118184fc708aa8eb45d170b2c1f1511" } } diff --git a/.generated/sdk-docs/vue-sdk/v2.json b/.generated/sdk-docs/vue-sdk/v2.json index 0aebd22..3080759 100644 --- a/.generated/sdk-docs/vue-sdk/v2.json +++ b/.generated/sdk-docs/vue-sdk/v2.json @@ -4,9 +4,9 @@ "package": "@reflag/vue-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/vue-sdk/README.md": "58d538146d48b8d90d3a0dbc8836471bb621d72d2706e59cb3bae405bf06bb3d", - "sdk/@reflag/vue-sdk/README.md": "bd5f7130b3e920f6affa13a67d54c42664fce7d79fb394b7b88aa7c7f25f6d1e", - "supported-languages/vue-sdk/globals.md": "51f74d439a28e1c05c0fdfbbefcea2c85f04b75b6f4c6fb7f82e900bbb21663c", - "sdk/@reflag/vue-sdk/globals.md": "acfe7ac37c8599236c8e8a1daabe06eec7dfba179e34d00885a7a1545e443d4b" + "supported-languages/vue-sdk/README.md": "6424a2704bfb8cc912cdab966707f26ddc186dc0e3c6e70e12309f535b4e6819", + "sdk/@reflag/vue-sdk/README.md": "7e221353ecbd358843f9a900e242402584248c8c5bf845cf1689db50ecef0667", + "supported-languages/vue-sdk/globals.md": "10e6553c25423f35473babce7bfb18261a5598fa31f963063a00ade055f5896d", + "sdk/@reflag/vue-sdk/globals.md": "f12f4c627c2b023afe60dc83c9b7ea56a89462cdad8905233e4eb590f1ba6ef2" } } diff --git a/.github/scripts/sdk-docs.mjs b/.github/scripts/sdk-docs.mjs index e352984..4b16526 100644 --- a/.github/scripts/sdk-docs.mjs +++ b/.github/scripts/sdk-docs.mjs @@ -46,6 +46,40 @@ function withBanner(content, message) { return content.slice(0, end + 5) + "\n" + note + content.slice(end + 5).trimStart(); } +export const headingSlug = (text) => + text + .toLowerCase() + .replace(/<\/?(?:a|code|strong|em|span|br)(?:\s[^>]*)?>/g, "") + .replace(/[^\p{L}\p{N}_ -]/gu, "") + .replace(/ /g, "-"); + +export function anchorHeadings(content) { + const ids = new Set(); + let fence; + return content + .split("\n") + .map((line) => { + const marker = /^\s*(`{3,}|~{3,})/.exec(line)?.[1]; + if (marker) { + if (!fence) fence = marker; + else if (fence[0] === marker[0] && marker.length >= fence.length) fence = undefined; + return line; + } + if (fence) return line; + const heading = /^#{1,6} (.+)$/.exec(line)?.[1]; + if (!heading) return line; + const base = headingSlug(heading); + let id = base; + for (let suffix = 1; ids.has(id); suffix++) id = `${base}-${suffix}`; + ids.add(id); + // GitBook otherwise expands into "less-than-t-greater-than" and + // punctuation into different slugs than TypeDoc's existing deep links. + if (/\bid=["']/.test(heading)) return line; + return `${line} `; + }) + .join("\n"); +} + export function planPackage({ source, name, commit }) { assert(/^[a-f\d]{40}$/.test(commit), "A full SDK source commit is required"); const pkg = metadata(source, name); @@ -145,6 +179,7 @@ export function planPackage({ source, name, commit }) { /((?:src|href)=["'])([^"']+)(["'])/g, (_, open, url, close) => `${open}${route(url, { raw, file })}${close}`, ); + content = anchorHeadings(content); if (web) { // Pin installation/CDN commands, never imports or JSON application data. content = content diff --git a/.github/scripts/sdk-docs.test.mjs b/.github/scripts/sdk-docs.test.mjs index 73720b6..2aad884 100644 --- a/.github/scripts/sdk-docs.test.mjs +++ b/.github/scripts/sdk-docs.test.mjs @@ -4,7 +4,14 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import test from "node:test"; -import { applyPlan, docsPath, planPackage, releaseFiles, webSDKs } from "./sdk-docs.mjs"; +import { + anchorHeadings, + applyPlan, + docsPath, + planPackage, + releaseFiles, + webSDKs, +} from "./sdk-docs.mjs"; import { anchors, checkLinks, checkSDKDocs, root, sourceMatrix } from "./check-sdk-docs.mjs"; function fixture(t, major = 2) { @@ -133,6 +140,16 @@ test("Management and CLI updates never own coordinated SDK trees", (t) => { } }); +test("GitBook heading IDs preserve TypeDoc/generic deep links without changing code fences", () => { + const content = + "# `` component\n## FlagValueFromDefault\\\n## Properties\n## Properties\n```md\n# Leave code alone\n```\n"; + const rendered = anchorHeadings(content); + assert.match(rendered, /id="reflagprovider-component"/); + assert.match(rendered, /id="flagvaluefromdefaultt"/); + assert.match(rendered, /id="properties-1"/); + assert(rendered.includes("```md\n# Leave code alone\n```")); +}); + test("missing generated input fails before applying any changes", (t) => { const { source, options, destination } = fixture(t); fs.unlinkSync(path.join(source, "dist/docs/@reflag/react-sdk/globals.md")); diff --git a/legacy/v1/browser-sdk/README.md b/legacy/v1/browser-sdk/README.md index e9764c5..7f25040 100644 --- a/legacy/v1/browser-sdk/README.md +++ b/legacy/v1/browser-sdk/README.md @@ -19,13 +19,13 @@ pagination: Generated from [`@reflag/browser-sdk@1.7.4`](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk); SDK READMEs and code comments remain the source of truth. {% endhint %} -# Reflag Browser SDK +# Reflag Browser SDK Basic client for [Reflag.com](https://reflag.com). If you're using React, you'll be better off with the Reflag React SDK. Reflag supports flag toggling, tracking flag usage, [collecting feedback](#qualitative-feedback-on-beta-flags) on flags, and [remotely configuring flags](#remote-config). -## Install +## Install First find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag. @@ -112,7 +112,7 @@ See [example/browser.html](https://github.com/reflagcom/javascript/tree/b4fe5b3d ``` -### Init options +### Init options Supply these to the constructor call: @@ -140,7 +140,7 @@ type Configuration = { }; ``` -## Migrating from Bucket SDK +## Migrating from Bucket SDK If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: @@ -165,7 +165,7 @@ If you are running with strict Content Security Policies active on your website, Finally, if you have customized the look & feel of the Feedback component, update `--bucket-feedback-*` CSS classes to `--reflag-feedback-*` -## Flag toggles +## Flag toggles Reflag determines which flags are active for a given user/company. The user/company is given in the ReflagClient constructor. @@ -227,7 +227,7 @@ by down-stream clients, like the React SDK. Note that accessing `isEnabled` on the object returned by `getFlags` does not automatically generate a `check` event, contrary to the `isEnabled` property on the object returned by `getFlag`. -## End-user opt-in +## End-user opt-in If a flag has end-user opt-in enabled in Reflag, you can list the opt-in options for the current context and set or cancel opt-in for the current user or company. @@ -264,7 +264,7 @@ Listen for `optInFlagsLoadingUpdated` to update UI when this loading state chang If fetching opt-in metadata fails, loading ends without exposing an error. Call `reflagClient.refresh()` to retry. -## Remote config +## Remote config Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. @@ -291,11 +291,11 @@ const flags = reflagClient.getFlags(); Just as `isEnabled`, accessing `config` on the object returned by `getFlags` does not automatically generate a `check` event, contrary to the `config` property on the object returned by `getFlag`. -## Server-side rendering and bootstrapping +## Server-side rendering and bootstrapping For server-side rendered applications, you can render immediately with pre-fetched flag data by bootstrapping the client. -### Init options bootstrapped +### Init options bootstrapped ```typescript type Configuration = { @@ -314,7 +314,7 @@ type Configuration = { }; ``` -### Using `bootstrappedState` +### Using `bootstrappedState` Use the Node SDK's `getFlagsForBootstrap()` method to pre-fetch evaluated state server-side, then pass the returned object directly to the browser client: @@ -392,9 +392,9 @@ Requesting opt-in flags also triggers a browser-side refresh, even when `enableL This eliminates loading states and removes the initial render's dependency on the flags API. -## Context management +## Context management -### Updating user/company/other context +### Updating user/company/other context Attributes given for the user/company/other context in the ReflagClient constructor can be updated for use in flag targeting evaluation with the `updateUser()`, `updateCompany()` and `updateOtherContext()` methods. They return a promise which resolves once the flags have been re-evaluated follow the update of the attributes. @@ -402,7 +402,7 @@ They return a promise which resolves once the flags have been re-evaluated follo {% hint style="info" %} {% endhint %} -### setContext() +### setContext() The `setContext()` method allows you to replace the entire context (user, company, and other attributes) at once. This method is useful when you need to completely change the context, such as when a user logs in or switches between different accounts. @@ -433,7 +433,7 @@ The method will: - Update the user and company information on Reflag servers - Return a promise that resolves once the flags have been re-evaluated -### getContext() +### getContext() The `getContext()` method returns the current context being used for flag evaluation. This is useful for debugging or when you need to inspect the current user, company, and other attributes. @@ -453,7 +453,7 @@ The returned context object contains: - `company`: Current company attributes (if any) - `other`: Additional context attributes not related to user or company -## Toolbar +## Toolbar The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off. @@ -489,11 +489,11 @@ const client = new ReflagClient({ See [the reference](globals.md#toolbaroptions) for details. -## Qualitative feedback on beta flags +## Qualitative feedback on beta flags Reflag can collect qualitative feedback from your users in the form of a [Customer Satisfaction Score](https://en.wikipedia.org/wiki/Customer_satisfaction) and a comment. -### Automated feedback collection +### Automated feedback collection The Reflag Browser SDK comes with automated feedback collection mode enabled by default, which lets the Reflag service ask your users for feedback for relevant flags just after they've used them. @@ -506,13 +506,13 @@ It works because the Reflag Browser SDK maintains a live connection to Reflag's You can find all the options to make changes to the default behavior in the [Reflag feedback documentation](feedback.md). -### Reflag feedback UI +### Reflag feedback UI Reflag can assist you with collecting your user's feedback by offering a pre-built UI, allowing you to get started with minimal code and effort. [Read the Reflag feedback UI documentation](feedback.md) -### Reflag feedback SDK +### Reflag feedback SDK Feedback can be submitted to Reflag using the SDK: @@ -524,13 +524,13 @@ reflagClient.feedback({ }); ``` -### Reflag feedback API +### Reflag feedback API If you are not using the Reflag Browser SDK, you can still submit feedback using the HTTP API. See details in [Feedback HTTP API](https://docs.reflag.com/api/http-api#post-feedback) -## Tracking flag usage +## Tracking flag usage The `track` function lets you send events to Reflag to denote flag usage. By default Reflag expects event names to align with the flag keys, but @@ -540,7 +540,7 @@ you can customize it as you wish. reflagClient.track("huddle", { voiceHuddle: true }); ``` -## Event listeners +## Event listeners Event listeners allow for capturing various events occurring in the `ReflagClient`. This is useful to build integrations with other system or for various debugging purposes. The available events are: @@ -568,7 +568,7 @@ const unsub = client.on("check", (check: CheckEvent) => unsub(); ``` -## Zero PII +## Zero PII The Reflag Browser SDK doesn't collect any metadata and HTTP IP addresses are _not_ being stored. @@ -581,7 +581,7 @@ import { sha256 } from "crypto-hash"; reflag.user(await sha256("john_doe")); ``` -## Use of cookies +## Use of cookies The Reflag Browser SDK uses a couple of cookies to support automated feedback surveys. These cookies are not used for tracking purposes and thus should not need to appear in cookie consent forms. @@ -590,11 +590,11 @@ The two cookies are: - `reflag-prompt-${userId}`: store the last automated feedback prompt message ID received to avoid repeating surveys - `reflag-token-${userId}`: caching a token used to connect to Reflag's live messaging infrastructure that is used to deliver automated feedback surveys in real time. -## TypeScript +## TypeScript Types are bundled together with the library and exposed automatically when importing through a package manager. -## Content Security Policy (CSP) +## Content Security Policy (CSP) If you are running with strict Content Security Policies active on your website, you will need to enable these directives in order to use the SDK: @@ -609,7 +609,7 @@ If you are including the Reflag tracking SDK with a ` ``` -## Internationalization (i18n) +## Internationalization (i18n) By default, the feedback UI is written in English. However, you can supply your own translations by passing an object in the options to either or both of the @@ -291,7 +291,7 @@ See examples below. See [default English localization keys](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) for a reference of what translation keys can be supplied. -### Static language configuration +### Static language configuration If you know the language at page load, you can configure your translation keys while initializing the Reflag Browser SDK: @@ -322,7 +322,7 @@ new ReflagClient({ }); ``` -### Runtime language configuration +### Runtime language configuration If you only know the user's language after the page has loaded, you can provide translations to either the `reflagClient.requestFeedback(options)` call or @@ -338,7 +338,7 @@ reflagClient.requestFeedback({ }) ``` -### Translations +### Translations When you are collecting feedback through the Reflag automation, you can intercept the default prompt handling and override the defaults. @@ -365,7 +365,7 @@ new ReflagClient({ }); ``` -## Custom styling +## Custom styling You can adapt parts of the look of the Reflag feedback UI by applying CSS custom properties to your page in your CSS `:root`-scope. @@ -404,7 +404,7 @@ For example, a dark mode theme might look like this: Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/src/feedback/ui/index.css). -## Using your own UI to collect feedback +## Using your own UI to collect feedback You may have very strict design guidelines for your app and maybe the Reflag feedback UI doesn't quite work for you. In this case, you can implement your own feedback @@ -424,7 +424,7 @@ type DataToCollect = { Either `score` or `comment` must be defined in order to pass validation in the Reflag API. -### Manual feedback collection with custom UI +### Manual feedback collection with custom UI Examples of a HTML-form that collects the relevant data can be found in [feedback.html](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/example/feedback/Feedback.jsx). @@ -440,7 +440,7 @@ reflagClient.feedback({ }); ``` -### Intercepting automated feedback survey events +### Intercepting automated feedback survey events When using automated feedback surveys, the Reflag service will, when specified, send a feedback prompt message to your user's instance of the Reflag Browser SDK. diff --git a/legacy/v1/browser-sdk/globals.md b/legacy/v1/browser-sdk/globals.md index be82688..422c652 100644 --- a/legacy/v1/browser-sdk/globals.md +++ b/legacy/v1/browser-sdk/globals.md @@ -19,17 +19,17 @@ pagination: Generated from [`@reflag/browser-sdk@1.7.4`](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk); SDK READMEs and code comments remain the source of truth. {% endhint %} -# @reflag/browser-sdk +# @reflag/browser-sdk -## Classes +## Classes -### ReflagClient +### ReflagClient ReflagClient lets you interact with the Reflag API. -#### Constructors +#### Constructors -##### new ReflagClient() +##### new ReflagClient() ```ts new ReflagClient(opts: InitOptions): ReflagClient @@ -37,7 +37,7 @@ new ReflagClient(opts: InitOptions): ReflagClient Create a new ReflagClient instance. -###### Parameters +###### Parameters @@ -62,11 +62,11 @@ Create a new ReflagClient instance.
-###### Returns +###### Returns [`ReflagClient`](globals.md#reflagclient) -#### Properties +#### Properties @@ -97,15 +97,15 @@ Create a new ReflagClient instance.
-#### Methods +#### Methods -##### applyBootstrappedState() +##### applyBootstrappedState() ```ts applyBootstrappedState(bootstrappedState: BootstrappedState, triggerEvent: boolean): void ``` -###### Parameters +###### Parameters @@ -153,11 +153,11 @@ applyBootstrappedState(bootstrappedState: BootstrappedState, triggerEvent: boole
-###### Returns +###### Returns `void` -##### feedback() +##### feedback() ```ts feedback(payload: Feedback): Promise< @@ -167,7 +167,7 @@ feedback(payload: Feedback): Promise< Submit user feedback to Reflag. Must include either `score` or `comment`, or both. -###### Parameters +###### Parameters @@ -198,7 +198,7 @@ The feedback details to submit.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` @@ -206,7 +206,7 @@ The feedback details to submit. The server response. -##### getConfig() +##### getConfig() ```ts getConfig(): Config @@ -214,11 +214,11 @@ getConfig(): Config Get the current configuration. -###### Returns +###### Returns [`Config`](globals.md#config) -##### getContext() +##### getContext() ```ts getContext(): ReflagContext @@ -226,17 +226,17 @@ getContext(): ReflagContext Get the current context. -###### Returns +###### Returns [`ReflagContext`](globals.md#reflagcontext) -##### ~~getFeature()~~ +##### ~~getFeature()~~ ```ts getFeature(flagKey: string): Flag ``` -###### Parameters +###### Parameters @@ -261,29 +261,29 @@ getFeature(flagKey: string): Flag
-###### Returns +###### Returns [`Flag`](globals.md#flag) -###### Deprecated +###### Deprecated Use `getFlag` instead. -##### ~~getFeatures()~~ +##### ~~getFeatures()~~ ```ts getFeatures(): RawFlags ``` -###### Returns +###### Returns [`RawFlags`](globals.md#rawflags) -###### Deprecated +###### Deprecated Use `getFlags` instead. -##### getFlag() +##### getFlag() ```ts getFlag(flagKey: string): Flag @@ -291,7 +291,7 @@ getFlag(flagKey: string): Flag Return a flag. Accessing `isEnabled` or `config` will automatically send a `check` event. -###### Parameters +###### Parameters @@ -322,13 +322,13 @@ The key of the flag to get.
-###### Returns +###### Returns [`Flag`](globals.md#flag) A flag. -##### getFlags() +##### getFlags() ```ts getFlags(): RawFlags @@ -339,13 +339,13 @@ Accessing a flag will *not* send a check event and `isEnabled` does not take any flag overrides into account. -###### Returns +###### Returns [`RawFlags`](globals.md#rawflags) Map of flags. -##### getIsLoadingOptInFlags() +##### getIsLoadingOptInFlags() ```ts getIsLoadingOptInFlags(): boolean @@ -355,11 +355,11 @@ Returns whether opt-in flags are loading for the current context. Calling this method requests opt-in metadata if it is not already available. -###### Returns +###### Returns `boolean` -##### getOptInFlags() +##### getOptInFlags() ```ts getOptInFlags(): OptInFlag[] @@ -367,21 +367,21 @@ getOptInFlags(): OptInFlag[] Returns opt-in-enabled flags for the current context. -###### Returns +###### Returns [`OptInFlag`](globals.md#optinflag)[] -##### getState() +##### getState() ```ts getState(): State ``` -###### Returns +###### Returns [`State`](globals.md#state) -##### initialize() +##### initialize() ```ts initialize(): Promise @@ -391,11 +391,11 @@ Initialize the Reflag SDK. Must be called before calling other SDK methods. -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### off() +##### off() ```ts off(type: THookType, handler: (args0: HookArgs[THookType]) => void): void @@ -403,7 +403,7 @@ off(type: THookType, handler: (args0: HookArgs[THookType]) => void): Remove an event listener -###### Type Parameters +###### Type Parameters @@ -422,7 +422,7 @@ Remove an event listener
-###### Parameters +###### Parameters @@ -470,13 +470,13 @@ The same function that was passed to `on`.
-###### Returns +###### Returns `void` A function to remove the hook. -##### on() +##### on() ```ts on(type: THookType, handler: (args0: HookArgs[THookType]) => void): () => void @@ -484,7 +484,7 @@ on(type: THookType, handler: (args0: HookArgs[THookType]) => void): ( Add an event listener -###### Type Parameters +###### Type Parameters @@ -503,7 +503,7 @@ Add an event listener
-###### Parameters +###### Parameters @@ -551,17 +551,17 @@ The function to call when the event is triggered.
-###### Returns +###### Returns `Function` A function to remove the hook. -###### Returns +###### Returns `void` -##### refresh() +##### refresh() ```ts refresh(): Promise @@ -569,11 +569,11 @@ refresh(): Promise Force refresh flags from the API, bypassing cache. -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`undefined` \| [`RawFlags`](globals.md#rawflags)\> -##### requestFeedback() +##### requestFeedback() ```ts requestFeedback(options: RequestFeedbackData): void @@ -583,7 +583,7 @@ Display the Reflag feedback form UI programmatically. This can be used to collect feedback from users in Reflag in cases where Automated Feedback Surveys isn't appropriate. -###### Parameters +###### Parameters @@ -608,11 +608,11 @@ This can be used to collect feedback from users in Reflag in cases where Automat
-###### Returns +###### Returns `void` -##### setContext() +##### setContext() ```ts setContext(context: ReflagDeprecatedContext): Promise @@ -621,7 +621,7 @@ setContext(context: ReflagDeprecatedContext): Promise Update the context. Replaces the existing context with a new context. -###### Parameters +###### Parameters @@ -652,11 +652,11 @@ The context to update.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### setOptIn() +##### setOptIn() ```ts setOptIn(flagKey: string, options: SetOptInOptions): Promise< @@ -672,7 +672,7 @@ refreshing flags. Offline mode, invalid arguments, or missing scoped context return undefined. Network and confirmation failures reject the promise; a confirmation failure may occur after membership changed remotely. -###### Parameters +###### Parameters @@ -709,19 +709,19 @@ a confirmation failure may occur after membership changed remotely.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> -##### showToolbarToggle() +##### showToolbarToggle() ```ts showToolbarToggle(position?: ToolbarPosition): void ``` -###### Parameters +###### Parameters @@ -746,11 +746,11 @@ showToolbarToggle(position?: ToolbarPosition): void
-###### Returns +###### Returns `void` -##### stop() +##### stop() ```ts stop(): Promise @@ -759,11 +759,11 @@ stop(): Promise Stop the SDK. This will stop any automated feedback surveys. -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### track() +##### track() ```ts track(eventName: string, attributes?: @@ -775,7 +775,7 @@ track(eventName: string, attributes?: Track an event in Reflag. -###### Parameters +###### Parameters @@ -823,13 +823,13 @@ Any attributes you want to attach to the event.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> -##### updateCompany() +##### updateCompany() ```ts updateCompany(company: {}): Promise @@ -839,7 +839,7 @@ Update the company context. Performs a shallow merge with the existing company context. It will not update the context if nothing has changed. -###### Parameters +###### Parameters @@ -870,11 +870,11 @@ The company details.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### updateFlags() +##### updateFlags() ```ts updateFlags( @@ -885,7 +885,7 @@ updateFlags( Update the flags. -###### Parameters +###### Parameters @@ -966,11 +966,11 @@ Whether to trigger the `flagsUpdated` event.
-###### Returns +###### Returns `void` -##### updateOtherContext() +##### updateOtherContext() ```ts updateOtherContext(otherContext: {}): Promise @@ -980,7 +980,7 @@ Update the company context. Performs a shallow merge with the existing company context. It will not update the context if nothing has changed. -###### Parameters +###### Parameters @@ -1011,11 +1011,11 @@ Additional context.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### updateUser() +##### updateUser() ```ts updateUser(user: {}): Promise @@ -1025,7 +1025,7 @@ Update the user context. Performs a shallow merge with the existing user context. It will not update the context if nothing has changed. -###### Parameters +###### Parameters @@ -1050,17 +1050,17 @@ It will not update the context if nothing has changed.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -## Interfaces +## Interfaces -### CheckEvent +### CheckEvent Event representing checking the flag evaluation result -#### Properties +#### Properties @@ -1201,19 +1201,19 @@ Version of targeting rules. *** -### CompanyContext +### CompanyContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing company. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties
@@ -1263,11 +1263,11 @@ Company name *** -### Config +### Config ReflagClient configuration. -#### Properties +#### Properties
@@ -1386,9 +1386,9 @@ Defaults to `apiBaseUrl`. *** -### FeedbackScoreSubmission +### FeedbackScoreSubmission -#### Properties +#### Properties
@@ -1439,9 +1439,9 @@ Defaults to `apiBaseUrl`. *** -### FeedbackSubmission +### FeedbackSubmission -#### Properties +#### Properties
@@ -1504,9 +1504,9 @@ Defaults to `apiBaseUrl`. *** -### Flag +### Flag -#### Properties +#### Properties
@@ -1606,9 +1606,9 @@ Function to send analytics events for this flag.
-#### Methods +#### Methods -##### setIsEnabledOverride() +##### setIsEnabledOverride() ```ts setIsEnabledOverride(isEnabled: null | boolean): void @@ -1617,7 +1617,7 @@ setIsEnabledOverride(isEnabled: null | boolean): void Set the override status for isEnabled for the flag. Set to `null` to remove the override. -###### Parameters +###### Parameters @@ -1642,15 +1642,15 @@ Set to `null` to remove the override.
-###### Returns +###### Returns `void` *** -### HookArgs +### HookArgs -#### Properties +#### Properties @@ -1804,17 +1804,17 @@ Use `flagsUpdated` instead. *** -### Logger +### Logger -#### Methods +#### Methods -##### debug() +##### debug() ```ts debug(message: string, ...args: any[]): void ``` -###### Parameters +###### Parameters
@@ -1851,17 +1851,17 @@ debug(message: string, ...args: any[]): void
-###### Returns +###### Returns `void` -##### error() +##### error() ```ts error(message: string, ...args: any[]): void ``` -###### Parameters +###### Parameters @@ -1898,17 +1898,17 @@ error(message: string, ...args: any[]): void
-###### Returns +###### Returns `void` -##### info() +##### info() ```ts info(message: string, ...args: any[]): void ``` -###### Parameters +###### Parameters @@ -1945,17 +1945,17 @@ info(message: string, ...args: any[]): void
-###### Returns +###### Returns `void` -##### warn() +##### warn() ```ts warn(message: string, ...args: any[]): void ``` -###### Parameters +###### Parameters @@ -1992,15 +1992,15 @@ warn(message: string, ...args: any[]): void
-###### Returns +###### Returns `void` *** -### OnScoreSubmitResult +### OnScoreSubmitResult -#### Properties +#### Properties @@ -2027,9 +2027,9 @@ warn(message: string, ...args: any[]): void *** -### OpenFeedbackFormOptions +### OpenFeedbackFormOptions -#### Properties +#### Properties
@@ -2200,16 +2200,16 @@ Undefined translation keys fall back to english defaults. *** -### ReflagContext +### ReflagContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. -#### Extended by +#### Extended by - [`ReflagDeprecatedContext`](globals.md#reflagdeprecatedcontext) -#### Properties +#### Properties
@@ -2278,19 +2278,19 @@ user attributes on Reflag servers. *** -### ~~ReflagDeprecatedContext~~ +### ~~ReflagDeprecatedContext~~ **`Internal`** -#### Deprecated +#### Deprecated Use `ReflagContext` instead, this interface will be removed in the next major version -#### Extends +#### Extends - [`ReflagContext`](globals.md#reflagcontext) -#### Properties +#### Properties
@@ -2380,9 +2380,9 @@ user attributes on Reflag servers. *** -### ToolbarPosition +### ToolbarPosition -#### Properties +#### Properties
@@ -2421,19 +2421,19 @@ user attributes on Reflag servers. *** -### UserContext +### UserContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing user. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties
@@ -2498,9 +2498,9 @@ User name
-## Type Aliases +## Type Aliases -### BootstrappedState +### BootstrappedState ```ts type BootstrappedState = { @@ -2512,7 +2512,7 @@ type BootstrappedState = { Pre-fetched evaluated state used to bootstrap the client. -#### Type declaration +#### Type declaration @@ -2563,7 +2563,7 @@ Pre-fetched evaluated state used to bootstrap the client. *** -### ContextValue +### ContextValue ```ts type ContextValue = DefinedContextValue | undefined; @@ -2573,7 +2573,7 @@ A context value. Object properties set to `undefined` are omitted. *** -### DefinedContextValue +### DefinedContextValue ```ts type DefinedContextValue = @@ -2589,7 +2589,7 @@ A JSON-compatible context value that is not `undefined`. *** -### DialogPlacement +### DialogPlacement ```ts type DialogPlacement = "bottom-right" | "bottom-left" | "top-right" | "top-left"; @@ -2597,13 +2597,13 @@ type DialogPlacement = "bottom-right" | "bottom-left" | "top-right" | "top-left" *** -### EventSourceFactory() +### EventSourceFactory() ```ts type EventSourceFactory = (url: string) => EventSourceLike; ``` -#### Parameters +#### Parameters
@@ -2628,13 +2628,13 @@ type EventSourceFactory = (url: string) => EventSourceLike;
-#### Returns +#### Returns [`EventSourceLike`](globals.md#eventsourcelike) *** -### EventSourceLike +### EventSourceLike ```ts type EventSourceLike = { @@ -2643,7 +2643,7 @@ type EventSourceLike = { }; ``` -#### Type declaration +#### Type declaration @@ -2682,7 +2682,7 @@ type EventSourceLike = { *** -### FallbackFlagOverride +### FallbackFlagOverride ```ts type FallbackFlagOverride = @@ -2695,7 +2695,7 @@ type FallbackFlagOverride = *** -### Feedback +### Feedback ```ts type Feedback = UnassignedFeedback & { @@ -2704,7 +2704,7 @@ type Feedback = UnassignedFeedback & { }; ``` -#### Type declaration +#### Type declaration
@@ -2754,7 +2754,7 @@ User ID from your own application. *** -### FeedbackOptions +### FeedbackOptions ```ts type FeedbackOptions = { @@ -2767,7 +2767,7 @@ type FeedbackOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -2872,7 +2872,7 @@ Undefined translation keys fall back to english defaults. *** -### FeedbackPrompt +### FeedbackPrompt ```ts type FeedbackPrompt = { @@ -2884,7 +2884,7 @@ type FeedbackPrompt = { }; ``` -#### Type declaration +#### Type declaration
@@ -2985,13 +2985,13 @@ Feedback prompt will not be shown after this time *** -### FeedbackPromptHandler() +### FeedbackPromptHandler() ```ts type FeedbackPromptHandler = (prompt: FeedbackPrompt, handlers: FeedbackPromptHandlerCallbacks) => void; ``` -#### Parameters +#### Parameters
@@ -3028,13 +3028,13 @@ type FeedbackPromptHandler = (prompt: FeedbackPrompt, handlers: FeedbackPromptHa
-#### Returns +#### Returns `void` *** -### FeedbackPromptHandlerCallbacks +### FeedbackPromptHandlerCallbacks ```ts type FeedbackPromptHandlerCallbacks = { @@ -3043,7 +3043,7 @@ type FeedbackPromptHandlerCallbacks = { }; ``` -#### Type declaration +#### Type declaration @@ -3082,7 +3082,7 @@ type FeedbackPromptHandlerCallbacks = { *** -### FeedbackPromptHandlerOpenFeedbackFormOptions +### FeedbackPromptHandlerOpenFeedbackFormOptions ```ts type FeedbackPromptHandlerOpenFeedbackFormOptions = Omit ```ts type FeedbackPromptReply = { @@ -3107,7 +3107,7 @@ type FeedbackPromptReply = { }; ``` -#### Type declaration +#### Type declaration
@@ -3170,7 +3170,7 @@ type FeedbackPromptReply = { *** -### FeedbackPromptReplyHandler() +### FeedbackPromptReplyHandler() ```ts type FeedbackPromptReplyHandler = (reply: T) => T extends null ? Promise : Promise<{ @@ -3178,7 +3178,7 @@ type FeedbackPromptReplyHandler = (reply: T) => T extends null ? Promise; ``` -#### Type Parameters +#### Type Parameters
@@ -3197,7 +3197,7 @@ type FeedbackPromptReplyHandler = (reply: T) => T extends null ? Promise
-#### Parameters +#### Parameters @@ -3222,7 +3222,7 @@ type FeedbackPromptReplyHandler = (reply: T) => T extends null ? Promise
-#### Returns +#### Returns `T` *extends* `null` ? [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> : [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<\{ `feedbackId`: `string`; @@ -3230,7 +3230,7 @@ type FeedbackPromptReplyHandler = (reply: T) => T extends null ? Promise ```ts type FeedbackTranslations = { @@ -3252,7 +3252,7 @@ type FeedbackTranslations = { You can use this to override text values in the feedback form with desired language translation -#### Type declaration +#### Type declaration @@ -3411,7 +3411,7 @@ with desired language translation *** -### FlagOverrides +### FlagOverrides ```ts type FlagOverrides = Record; @@ -3419,7 +3419,7 @@ type FlagOverrides = Record; *** -### FlagRemoteConfig +### FlagRemoteConfig ```ts type FlagRemoteConfig = @@ -3435,7 +3435,7 @@ type FlagRemoteConfig = A remotely managed configuration value for a flag. -#### Type declaration +#### Type declaration \{ `key`: `string`; @@ -3530,7 +3530,7 @@ The optional user-supplied payload data. *** -### InitOptions +### InitOptions ```ts type InitOptions = ReflagDeprecatedContext & { @@ -3567,7 +3567,7 @@ type InitOptions = ReflagDeprecatedContext & { ReflagClient initialization options. -#### Type declaration +#### Type declaration
@@ -4068,7 +4068,7 @@ Deprecated: retries are no longer performed for bulk delivery. *** -### Offset +### Offset ```ts type Offset = { @@ -4077,7 +4077,7 @@ type Offset = { }; ``` -#### Type declaration +#### Type declaration
@@ -4127,7 +4127,7 @@ Offset from the nearest vertical screen edge after placement is resolved *** -### OptInFlag +### OptInFlag ```ts type OptInFlag = RawFlagOptIn & { @@ -4136,7 +4136,7 @@ type OptInFlag = RawFlagOptIn & { }; ``` -#### Type declaration +#### Type declaration
@@ -4186,7 +4186,7 @@ Flag key. *** -### PopoverPlacement +### PopoverPlacement ```ts type PopoverPlacement = Placement; @@ -4194,7 +4194,7 @@ type PopoverPlacement = Placement; *** -### Position +### Position ```ts type Position = @@ -4215,7 +4215,7 @@ type Position = *** -### RawFlag +### RawFlag ```ts type RawFlag = { @@ -4246,7 +4246,7 @@ type RawFlag = { A flag fetched from the server. -#### Type declaration +#### Type declaration
@@ -4555,7 +4555,7 @@ Version of targeting rules. *** -### RawFlagOptIn +### RawFlagOptIn ```ts type RawFlagOptIn = { @@ -4567,7 +4567,7 @@ type RawFlagOptIn = { }; ``` -#### Type declaration +#### Type declaration
@@ -4668,7 +4668,7 @@ Whether the current user has opted into the flag. *** -### RawFlags +### RawFlags ```ts type RawFlags = Record; @@ -4676,7 +4676,7 @@ type RawFlags = Record; *** -### RequestFeedbackData +### RequestFeedbackData ```ts type RequestFeedbackData = Omit & { @@ -4686,7 +4686,7 @@ type RequestFeedbackData = Omit & { }; ``` -#### Type declaration +#### Type declaration
@@ -4757,7 +4757,7 @@ copy of the feedback in your own application or CRM. *** -### RequestFeedbackOptions +### RequestFeedbackOptions ```ts type RequestFeedbackOptions = RequestFeedbackData & { @@ -4765,7 +4765,7 @@ type RequestFeedbackOptions = RequestFeedbackData & { }; ``` -#### Type declaration +#### Type declaration
@@ -4798,7 +4798,7 @@ User ID from your own application. *** -### SetOptInOptions +### SetOptInOptions ```ts type SetOptInOptions = { @@ -4809,7 +4809,7 @@ type SetOptInOptions = { Options for changing the current user or company's opt-in membership. -#### Type declaration +#### Type declaration
@@ -4859,7 +4859,7 @@ Whether to update the current user or current company. Defaults to `user`. *** -### State +### State ```ts type State = "idle" | "initializing" | "initialized" | "stopped"; @@ -4869,7 +4869,7 @@ State of the client. *** -### StorageAdapter +### StorageAdapter ```ts type StorageAdapter = { @@ -4879,7 +4879,7 @@ type StorageAdapter = { }; ``` -#### Type declaration +#### Type declaration
@@ -4930,7 +4930,7 @@ type StorageAdapter = { *** -### ToolbarOptions +### ToolbarOptions ```ts type ToolbarOptions = @@ -4945,7 +4945,7 @@ Toolbar options. *** -### TrackEvent +### TrackEvent ```ts type TrackEvent = { @@ -4957,7 +4957,7 @@ type TrackEvent = { }; ``` -#### Type declaration +#### Type declaration
@@ -5021,7 +5021,7 @@ type TrackEvent = { *** -### UnassignedFeedback +### UnassignedFeedback ```ts type UnassignedFeedback = { @@ -5036,7 +5036,7 @@ type UnassignedFeedback = { }; ``` -#### Type declaration +#### Type declaration
@@ -5196,9 +5196,9 @@ Source of the feedback, depending on how the user was asked
-## Variables +## Variables -### DEFAULT\_TRANSLATIONS +### DEFAULT\_TRANSLATIONS ```ts const DEFAULT_TRANSLATIONS: FeedbackTranslations; @@ -5227,7 +5227,7 @@ export const DEFAULT_TRANSLATIONS: FeedbackTranslations = { *** -### feedbackContainerId +### feedbackContainerId ```ts const feedbackContainerId: "reflag-feedback-dialog-container" = "reflag-feedback-dialog-container"; @@ -5237,7 +5237,7 @@ ID of HTML DIV element which contains the feedback dialog *** -### propagatedEvents +### propagatedEvents ```ts const propagatedEvents: string[]; @@ -5245,6 +5245,6 @@ const propagatedEvents: string[]; These events will be propagated to the feedback dialog -#### See +#### See [https://developer.mozilla.org/en-US/docs/Web/API/Element#events](https://developer.mozilla.org/en-US/docs/Web/API/Element#events) diff --git a/legacy/v1/node-sdk/README.md b/legacy/v1/node-sdk/README.md index 65a91ec..e1f3507 100644 --- a/legacy/v1/node-sdk/README.md +++ b/legacy/v1/node-sdk/README.md @@ -19,13 +19,13 @@ pagination: Generated from [`@reflag/node-sdk@1.8.3`](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/node-sdk); SDK READMEs and code comments remain the source of truth. {% endhint %} -# Reflag Node.js SDK +# Reflag Node.js SDK Node.js, JavaScript/TypeScript client for [Reflag.com](https://reflag.com). Reflag supports flag toggling, tracking flag usage, collecting feedback on features, and [remotely configuring flags](#remote-config). -## Installation +## Installation Install using your favorite package manager: @@ -75,7 +75,7 @@ Other supported languages/frameworks are in the [Supported languages](https://do You can also [use the HTTP API directly](https://docs.reflag.com/api/http-api) -## Basic usage +## Basic usage To get started you need to obtain your secret key from the [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag. @@ -157,7 +157,7 @@ const flags = boundClient.getFlags(); const bothEnabled = flags.huddle?.isEnabled && flags.voiceHuddle?.isEnabled; ``` -## High performance flag targeting +## High performance flag targeting The SDK contacts the Reflag servers when you call `initialize()` and downloads the flags with their targeting rules. @@ -169,7 +169,7 @@ to `getFlags()` (or through `bindClient(..).getFlags()`). That means the updates. You can switch `flagsSyncMode` to `polling` for periodic background refreshes or `in-request` for request-driven refreshes instead. -### Batch Operations +### Batch Operations The SDK automatically batches operations like user/company updates and flag tracking events to minimize API calls. The batch buffer is configurable through the client options: @@ -193,13 +193,13 @@ await client.flush(); It's recommended to call `flush()` before your application shuts down to ensure all events are sent. {% endhint %} -### Rate Limiting +### Rate Limiting The SDK includes automatic rate limiting for flag events to prevent overwhelming the API. Rate limiting is applied per unique combination of flag key and evaluation context. This behavior is built in and does not currently require configuration. -### Flag definitions +### Flag definitions Flag definitions include the rules needed to determine which flags should be enabled and which config values should be applied to any given user/company. Flag definitions are automatically fetched when calling `initialize()`. @@ -232,7 +232,7 @@ const flagDefs = await client.getFlagDefinitions(); // }] ``` -### Fallback provider +### Fallback provider `flagsFallbackProvider` is a reliability feature that lets the SDK persist the latest successfully fetched raw flag definitions to fallback storage such as a local file, Redis, S3, GCS, or a custom backend. @@ -242,7 +242,7 @@ const flagDefs = await client.getFlagDefinitions(); `flagsFallbackProvider` is not used in offline mode. {% endhint %} -#### How it works +#### How it works Reflag servers remain the primary source of truth. On `initialize()`, the SDK always tries to fetch a live copy of the flag definitions first, and it continues refreshing those definitions from the Reflag servers over time. @@ -270,7 +270,7 @@ If you are building a web or client-side application and want the most resilient This applies to React (`getFlagsForBootstrap()` + `ReflagBootstrappedProvider`), React Native, the Browser SDK (`bootstrappedState`), and the Vue SDK (bootstrapped flags via the provider). {% endhint %} -#### Built-in providers +#### Built-in providers You can access the built-in providers through the `fallbackProviders` namespace: @@ -280,7 +280,7 @@ You can access the built-in providers through the `fallbackProviders` namespace: - `fallbackProviders.s3(...)` - `fallbackProviders.gcs(...)` -##### Static provider +##### Static provider If you just want a fixed fallback copy of simple enabled/disabled flags, you can provide a static map: @@ -300,7 +300,7 @@ const client = new ReflagClient({ await client.initialize(); ``` -##### File provider +##### File provider ```typescript import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; @@ -319,7 +319,7 @@ The file provider stores one snapshot file per environment in the configured `directory`, using the filename `flags-fallback-.json`. -##### Redis provider +##### Redis provider The built-in Redis provider creates a Redis client automatically when omitted and uses `REDIS_URL` from the environment. It stores snapshots under the configured `keyPrefix` and appends the first 16 characters of the secret key hash to that prefix. @@ -336,7 +336,7 @@ const client = new ReflagClient({ await client.initialize(); ``` -##### S3 provider +##### S3 provider The built-in S3 provider works out of the box using the AWS SDK's default credential chain and region resolution. It stores the snapshot object under the configured `keyPrefix` and uses the filename `flags-fallback-.json`. @@ -355,7 +355,7 @@ const client = new ReflagClient({ await client.initialize(); ``` -##### GCS provider +##### GCS provider The built-in GCS provider works out of the box using Google Cloud's default application credentials. It stores the snapshot object under the configured `keyPrefix` and uses the filename `flags-fallback-.json`. @@ -374,11 +374,11 @@ const client = new ReflagClient({ await client.initialize(); ``` -#### Testing fallback startup locally +#### Testing fallback startup locally To test fallback startup in your own app, first run it once with a working Reflag connection so a snapshot is saved. Then restart it with the same secret key and fallback provider configuration, but set `apiBaseUrl` (or set the `REFLAG_API_BASE_URL` environment variable) to `http://127.0.0.1:65535`. That forces the live fetch to fail and lets you verify that the SDK initializes from the saved snapshot instead. -#### Writing a custom provider +#### Writing a custom provider If you just store definitions in your database or similar, a custom provider can be very small: @@ -402,7 +402,7 @@ export const customFallbackProvider: FlagsFallbackProvider = { }; ``` -## Bootstrapping client-side applications +## Bootstrapping client-side applications The `getFlagsForBootstrap()` method is useful whenever you need to pass flag data to another runtime or serialize it without wrapper functions. Server-side rendering (SSR) is a common example, but it is also useful for other bootstrapping and hydration flows. @@ -457,14 +457,14 @@ const boundClient = client.bindClient({ const bootstrappedState = boundClient.getFlagsForBootstrap(); ``` -### Key differences from `getFlags()` +### Key differences from `getFlags()` - **Raw data**: Returns plain objects without `track()` functions, making them JSON serializable - **Context included**: Returns both the evaluated flags and the context used for evaluation - **Version included**: Returns `flagStateVersion` when known so bootstrapped clients can avoid redundant live-update refreshes - **Bootstrapping focus**: Designed specifically for passing data to client-side applications -## Edge-runtimes like Cloudflare Workers +## Edge-runtimes like Cloudflare Workers To use the Reflag NodeSDK with Cloudflare workers, set the `node_compat` flag [in your wrangler file](https://developers.cloudflare.com/workers/runtime-apis/nodejs/#get-started). @@ -505,7 +505,7 @@ The SDK caches flag definitions in memory for fast performance. The first reques `EdgeClient` uses `flagsSyncMode: "in-request"`. Refresh fetch starts are throttled to at most once per second, and Cloudflare Workers cannot rely on delayed timer callbacks to run follow-up refreshes later. That means `refreshFlags()` calls made during the throttle window only mark a refresh as pending, so the call itself may resolve before the fetch runs. The queued refresh runs on the next request/access or `refreshFlags()` call after the throttle window expires. -## Error Handling +## Error Handling The SDK is designed to fail gracefully and never throw exceptions to the caller. Instead, it logs errors and provides fallback behavior: @@ -569,7 +569,7 @@ const client = new ReflagClient({ }); ``` -## Remote config +## Remote config Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. @@ -596,7 +596,7 @@ const flags = reflagClient.getFlags(); Just as `isEnabled`, accessing `config` on the object returned by `getFlags` does not automatically generate a `check` event, contrary to the `config` property on the object returned by `getFlag`. -## Configuring +## Configuring The Reflag `Node.js` SDK can be configured through environment variables, a configuration file on disk or by passing options to the `ReflagClient` @@ -653,7 +653,7 @@ order of importance: 2. Environment variable, 3. The config file. -## Type safe flags +## Type safe flags To get type checked flags, install the Reflag CLI: @@ -705,7 +705,7 @@ reflagClient.initialize().then(() => { ![Config type check failed](../_media/type-check-payload-failed.png "Remote config type check failed") -## Testing with flag overrides +## Testing with flag overrides When writing tests that cover code with flags, you can toggle flags on/off programmatically to test different behavior. For tests, you will often want to run the client in offline mode: @@ -721,7 +721,7 @@ export const reflag = new ReflagClient({ There are a few ways to programmatically manipulate the overrides which are appropriate when testing: -### Base overrides +### Base overrides You can set base overrides for a test run by passing `flagOverrides` in the constructor, replacing them later with `setFlagOverrides()` and clearing them with `clearFlagOverrides()`: @@ -762,7 +762,7 @@ describe("API Tests", () => { }); ``` -### Layering overrides +### Layering overrides `pushFlagOverrides()` serves a different purpose: it adds a temporary layer on top of the base overrides and returns a remove function that removes only that layer. This is useful for nested tests: @@ -800,7 +800,7 @@ The precedence is: If the same flag is set in both places, the pushed override wins until its remove function is called. -### Context dependent overrides +### Context dependent overrides `setFlagOverrides()` and `pushFlagOverrides()` also accept a function if the override depends on the evaluation context: @@ -814,7 +814,7 @@ const remove = client.pushFlagOverrides((context) => ({ remove(); ``` -### Additional ways to provide flag overrides +### Additional ways to provide flag overrides You also have these additional ways to provide overrides, which can be helpful when testing out locally: @@ -844,7 +844,7 @@ REFLAG_FLAGS_DISABLED=flag3,flag4 } ``` -## Remote Flag Evaluation +## Remote Flag Evaluation In addition to local flag evaluation, Reflag supports remote evaluation using stored context. This is useful when you want to evaluate flags using user/company attributes that were previously sent to Reflag: @@ -888,7 +888,7 @@ Remote evaluation is particularly useful when: - You don't want to pass all context attributes with every evaluation - You need to ensure consistent flag evaluation across different services -## Using with Express +## Using with Express A popular way to integrate the Reflag Node.js SDK is through an express middleware. @@ -951,7 +951,7 @@ app.get("/todos", async (_req, res) => { See [examples/express/app.ts](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/node-sdk/example/express/app.ts) for a full example. -## Remote flag evaluation with stored context +## Remote flag evaluation with stored context If you don't want to provide context each time when evaluating flags but rather you would like to utilize the attributes you sent to Reflag previously @@ -988,7 +988,7 @@ be a small delay between when attributes are updated and when they are available for evaluation. {% endhint %} -## Opting out of tracking +## Opting out of tracking There are use cases in which you not want to be sending `user`, `company` and `track` events to [Reflag.com](https://reflag.com). These are usually cases where you could be impersonating @@ -1021,7 +1021,7 @@ will still send tracking data. As such, it is always recommended to use `bindCli when using this SDK. {% endhint %} -## Flushing +## Flushing ReflagClient employs a batching technique to minimize the number of calls that are sent to Reflag's servers. @@ -1044,7 +1044,7 @@ waiting for in-flight requests or jobs to finish, and before exiting. This ensur produced during shutdown are included. Automatic flushing is best-effort and does not replace an application-managed shutdown hook. -## Tracking custom events and setting custom attributes +## Tracking custom events and setting custom attributes Tracking allows events and updating user/company attributes in Reflag. For example, if a customer changes their plan, you'll want Reflag to know about it, @@ -1086,7 +1086,7 @@ to provide for easier navigation: Attributes cannot be nested (multiple levels) and must be either strings, integers or booleans. -## Managing `Last seen` +## Managing `Last seen` By default `updateUser`/`updateCompany` calls automatically update the given user/company `Last seen` property on Reflag servers. @@ -1113,7 +1113,7 @@ client.updateCompany("acme_inc", { `bindClient()` updates attributes on the Reflag servers but does not automatically update `Last seen`. -## Zero PII +## Zero PII The Reflag SDK doesn't collect any metadata and HTTP IP addresses are _not_ being stored. For tracking individual users, we recommend using something like database @@ -1128,7 +1128,7 @@ import { sha256 } from 'crypto-hash'; client.updateUser({ userId: await sha256("john_doe"), ... }); ``` -## Migrating from Bucket SDK +## Migrating from Bucket SDK If you have been using the Bucket SDKs previously, the following list will help you migrate to Reflag SDK: @@ -1144,12 +1144,12 @@ If you have been using the Bucket SDKs previously, the following list will help - `featureKey` has been renamed to `flagKey` in all methods that accepts that argument - The SDKs will not emit `evaluate` and `evaluate-config` events anymore -## Typescript +## Typescript Types are bundled together with the library and exposed automatically when importing through a package manager. -## License +## License > MIT License > Copyright (c) 2025 Bucket ApS diff --git a/legacy/v1/node-sdk/globals.md b/legacy/v1/node-sdk/globals.md index 206cc99..057fe21 100644 --- a/legacy/v1/node-sdk/globals.md +++ b/legacy/v1/node-sdk/globals.md @@ -19,17 +19,17 @@ pagination: Generated from [`@reflag/node-sdk@1.8.3`](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/node-sdk); SDK READMEs and code comments remain the source of truth. {% endhint %} -# @reflag/node-sdk +# @reflag/node-sdk -## Classes +## Classes -### BoundReflagClient +### BoundReflagClient A client bound with a specific user, company, and other context. -#### Constructors +#### Constructors -##### new BoundReflagClient() +##### new BoundReflagClient() ```ts new BoundReflagClient(client: ReflagClient, options: ContextWithTracking): BoundReflagClient @@ -39,7 +39,7 @@ new BoundReflagClient(client: ReflagClient, options: ContextWithTracking): Bound (Internal) Creates a new BoundReflagClient. Use `bindClient` to create a new client bound with a specific context. -###### Parameters +###### Parameters @@ -87,15 +87,15 @@ The options for the client.
-###### Returns +###### Returns [`BoundReflagClient`](globals.md#boundreflagclient) -#### Accessors +#### Accessors -##### company +##### company -###### Get Signature +###### Get Signature ```ts get company(): @@ -109,7 +109,7 @@ get company(): Gets the company associated with the client. -###### Returns +###### Returns \| `undefined` \| \{ @@ -120,9 +120,9 @@ Gets the company associated with the client. The company or `undefined` if it is not set. -##### otherContext +##### otherContext -###### Get Signature +###### Get Signature ```ts get otherContext(): @@ -132,16 +132,16 @@ get otherContext(): Gets the "other" context associated with the client. -###### Returns +###### Returns \| `undefined` \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> The "other" context or `undefined` if it is not set. -##### user +##### user -###### Get Signature +###### Get Signature ```ts get user(): @@ -156,7 +156,7 @@ get user(): Gets the user associated with the client. -###### Returns +###### Returns \| `undefined` \| \{ @@ -168,9 +168,9 @@ Gets the user associated with the client. The user or `undefined` if it is not set. -#### Methods +#### Methods -##### bindClient() +##### bindClient() ```ts bindClient(context: ContextWithTracking): BoundReflagClient @@ -179,7 +179,7 @@ bindClient(context: ContextWithTracking): BoundReflagClient Create a new client bound with the additional context. Note: This performs a shallow merge for user/company/other individually. -###### Parameters +###### Parameters @@ -210,13 +210,13 @@ The context to bind the client to.
-###### Returns +###### Returns [`BoundReflagClient`](globals.md#boundreflagclient) new client bound with the additional context -##### flush() +##### flush() ```ts flush(): Promise @@ -224,11 +224,11 @@ flush(): Promise Flushes the batch buffer. -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### getFlag() +##### getFlag() ```ts getFlag(key: TKey): Flag @@ -237,7 +237,7 @@ getFlag(key: TKey): Flag Get a specific flag for the user/company/other context bound to this client. Using the `isEnabled` property sends a `check` event to Reflag. -###### Type Parameters +###### Type Parameters @@ -256,7 +256,7 @@ Using the `isEnabled` property sends a `check` event to Reflag.
-###### Parameters +###### Parameters @@ -287,13 +287,13 @@ The key of the flag to get.
-###### Returns +###### Returns [`Flag`](globals.md#flagtconfig) Flags for the given user/company and whether each one is enabled or not -##### getFlagRemote() +##### getFlagRemote() ```ts getFlagRemote(key: string): Promise @@ -301,7 +301,7 @@ getFlagRemote(key: string): Promise Get remotely evaluated flag for the user/company/other context bound to this client. -###### Parameters +###### Parameters @@ -332,13 +332,13 @@ The key of the flag to get.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Flag`](globals.md#flagtconfig)\> Flag for the given user/company and key and whether it's enabled or not -##### getFlags() +##### getFlags() ```ts getFlags(): Record @@ -347,13 +347,13 @@ getFlags(): Record Get flags for the user/company/other context bound to this client. Meant for use in serialization of flags for transferring to the client-side/browser. -###### Returns +###### Returns [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\> Flags for the given user/company and whether each one is enabled or not -##### getFlagsForBootstrap() +##### getFlagsForBootstrap() ```ts getFlagsForBootstrap(): BootstrappedFlags @@ -362,13 +362,13 @@ getFlagsForBootstrap(): BootstrappedFlags Get raw flags for the user/company/other context bound to this client without wrapping them in getters. This method returns raw flag data suitable for bootstrapping client-side applications. -###### Returns +###### Returns [`BootstrappedFlags`](globals.md#bootstrappedflags) Raw flags for the given user/company and whether each one is enabled or not -##### getFlagsRemote() +##### getFlagsRemote() ```ts getFlagsRemote(): Promise> @@ -376,13 +376,13 @@ getFlagsRemote(): Promise> Get remotely evaluated flag for the user/company/other context bound to this client. -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\>\> Flags for the given user/company and whether each one is enabled or not -##### refreshFlags() +##### refreshFlags() ```ts refreshFlags(waitForVersion?: number): Promise @@ -398,7 +398,7 @@ In `in-request` mode, a throttled call only records pending refresh work. The fetch then runs on the next request/access or `refreshFlags()` call after the throttle window expires. -###### Parameters +###### Parameters @@ -429,11 +429,11 @@ Optional flag state version to wait for before returning updated definitions.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### track() +##### track() ```ts track(event: string, options?: TrackOptions & { @@ -443,7 +443,7 @@ track(event: string, options?: TrackOptions & { Track an event in Reflag. -###### Parameters +###### Parameters @@ -491,17 +491,17 @@ The options for the event.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Throws +###### Throws An error if the event is invalid or the options are invalid. *** -### EdgeClient +### EdgeClient The EdgeClient is ReflagClient pre-configured to be used in edge runtimes, like Cloudflare Workers. @@ -512,7 +512,7 @@ that throttle window only records pending refresh work, so the call may resolve before the fetch runs. That pending refresh is executed on the next request/access or `refreshFlags()` call after the window expires. -#### Example +#### Example ```ts // set the REFLAG_SECRET_KEY environment variable or pass the secret key in the constructor @@ -527,19 +527,19 @@ const { isEnabled } = client.getFlag(context, "flag-key"); ``` -#### Extends +#### Extends - [`ReflagClient`](globals.md#reflagclient) -#### Constructors +#### Constructors -##### new EdgeClient() +##### new EdgeClient() ```ts new EdgeClient(options: EdgeClientOptions): EdgeClient ``` -###### Parameters +###### Parameters @@ -564,15 +564,15 @@ new EdgeClient(options: EdgeClientOptions): EdgeClient
-###### Returns +###### Returns [`EdgeClient`](globals.md#edgeclient) -###### Overrides +###### Overrides [`ReflagClient`](globals.md#reflagclient).[`constructor`](globals.md#constructors) -#### Properties +#### Properties @@ -631,11 +631,11 @@ Gets the logger associated with the client.
-#### Accessors +#### Accessors -##### flagOverrides +##### flagOverrides -###### Set Signature +###### Set Signature ```ts set flagOverrides(overrides: @@ -643,11 +643,11 @@ set flagOverrides(overrides: | FlagOverridesFn): void ``` -###### Deprecated +###### Deprecated Use `setFlagOverrides()` for replacing the base override set. -###### Parameters +###### Parameters @@ -672,17 +672,17 @@ Use `setFlagOverrides()` for replacing the base override set.
-###### Returns +###### Returns `void` -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`flagOverrides`](globals.md#flagoverrides) -#### Methods +#### Methods -##### bindClient() +##### bindClient() ```ts bindClient(context: ContextWithTracking): BoundReflagClient @@ -692,7 +692,7 @@ Returns a new BoundReflagClient with the user/company/otherContext set to be used in subsequent calls. For example, for evaluating flag targeting or tracking events. -###### Parameters +###### Parameters @@ -723,26 +723,26 @@ The context to bind the client to.
-###### Returns +###### Returns [`BoundReflagClient`](globals.md#boundreflagclient) A new client bound with the arguments given. -###### Throws +###### Throws An error if the user/company is given but their ID is not a string. -###### Remarks +###### Remarks The `updateUser` / `updateCompany` methods will automatically be called when the user/company is set respectively. -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`bindClient`](globals.md#bindclient) -##### clearFlagOverrides() +##### clearFlagOverrides() ```ts clearFlagOverrides(): void @@ -750,25 +750,25 @@ clearFlagOverrides(): void Clears the base flag overrides. -###### Returns +###### Returns `void` -###### Remarks +###### Remarks This does not affect temporary layers added with `pushFlagOverrides()`. -###### Example +###### Example ```ts client.clearFlagOverrides(); ``` -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`clearFlagOverrides`](globals.md#clearflagoverrides) -##### destroy() +##### destroy() ```ts destroy(): void @@ -776,21 +776,21 @@ destroy(): void Destroys the client and cleans up all resources including timers and background processes. -###### Returns +###### Returns `void` -###### Remarks +###### Remarks After calling this method, the client should not be used anymore. This is particularly useful in development environments with hot reloading to prevent multiple background processes from running simultaneously. -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`destroy`](globals.md#destroy) -##### flush() +##### flush() ```ts flush(): Promise @@ -798,11 +798,11 @@ flush(): Promise Flushes and completes any in-flight fetches in the flag cache. -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Remarks +###### Remarks It is recommended to call this method when the application is shutting down to ensure all events are sent before the process exits. @@ -812,11 +812,11 @@ This method is automatically called on natural process exit (`beforeExit`) if shutdown or an explicit `process.exit()`, await this method in your application's shutdown hook before exiting. The SDK does not install signal handlers. -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`flush`](globals.md#flush) -##### getFlag() +##### getFlag() ```ts getFlag(__namedParameters: ContextWithTracking, key: TKey): Flag @@ -825,7 +825,7 @@ getFlag(__namedParameters: ContextWithTracking, key: TKey): Flag Gets the evaluated flag for the current context which includes the user, company, and custom context. Using the `isEnabled` property sends a `check` event to Reflag. -###### Type Parameters +###### Type Parameters @@ -844,7 +844,7 @@ Using the `isEnabled` property sends a `check` event to Reflag.
-###### Parameters +###### Parameters @@ -892,21 +892,21 @@ The key of the flag to get.
-###### Returns +###### Returns [`Flag`](globals.md#flagtconfig) The evaluated flag. -###### Remarks +###### Remarks Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`getFlag`](globals.md#getflag) -##### getFlagDefinitions() +##### getFlagDefinitions() ```ts getFlagDefinitions(): FlagDefinition[] @@ -915,17 +915,17 @@ getFlagDefinitions(): FlagDefinition[] Gets the flag definitions, including all config values. To evaluate which flags are enabled for a given user/company, use `getFlags`. -###### Returns +###### Returns [`FlagDefinition`](globals.md#flagdefinition)[] The flags definitions. -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`getFlagDefinitions`](globals.md#getflagdefinitions) -##### getFlagRemote() +##### getFlagRemote() ```ts getFlagRemote( @@ -938,7 +938,7 @@ additionalContext?: Context): Promise Gets evaluated flag with the usage of remote context. This method triggers a network request every time it's called. -###### Type Parameters +###### Type Parameters @@ -957,7 +957,7 @@ This method triggers a network request every time it's called.
-###### Parameters +###### Parameters @@ -1039,17 +1039,17 @@ The additional context to get the flag for.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Flag`](globals.md#flagtconfig)\> evaluated flag -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`getFlagRemote`](globals.md#getflagremote) -##### getFlags() +##### getFlags() ```ts getFlags(options: ContextWithTracking): Record @@ -1057,7 +1057,7 @@ getFlags(options: ContextWithTracking): Record Gets the evaluated flags for the current context which includes the user, company, and custom context. -###### Parameters +###### Parameters @@ -1088,21 +1088,21 @@ The options for the context.
-###### Returns +###### Returns [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\> The evaluated flags. -###### Remarks +###### Remarks Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`getFlags`](globals.md#getflags) -##### getFlagsForBootstrap() +##### getFlagsForBootstrap() ```ts getFlagsForBootstrap(options: ContextWithTracking): BootstrappedFlags @@ -1111,7 +1111,7 @@ getFlagsForBootstrap(options: ContextWithTracking): BootstrappedFlags Gets the evaluated flags for the current context without wrapping them in getters. This method returns raw flag data suitable for bootstrapping client-side applications. -###### Parameters +###### Parameters @@ -1142,22 +1142,22 @@ The options for the context.
-###### Returns +###### Returns [`BootstrappedFlags`](globals.md#bootstrappedflags) The evaluated raw flags and the context. -###### Remarks +###### Remarks Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. This method returns RawFlag objects without wrapping them in getters, making them suitable for serialization. -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`getFlagsForBootstrap`](globals.md#getflagsforbootstrap) -##### getFlagsRemote() +##### getFlagsRemote() ```ts getFlagsRemote( @@ -1169,7 +1169,7 @@ additionalContext?: Context): Promise> Gets evaluated flags with the usage of remote context. This method triggers a network request every time it's called. -###### Parameters +###### Parameters @@ -1234,17 +1234,17 @@ The additional context to get the flags for.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\>\> evaluated flags -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`getFlagsRemote`](globals.md#getflagsremote) -##### initialize() +##### initialize() ```ts initialize(): Promise @@ -1252,20 +1252,20 @@ initialize(): Promise Initializes the client by caching the flags definitions. -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Remarks +###### Remarks Call this method before calling `getFlags` to ensure the flag definitions are cached. The client will ignore subsequent calls to this method. -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`initialize`](globals.md#initialize) -##### pushFlagOverrides() +##### pushFlagOverrides() ```ts pushFlagOverrides(overrides: @@ -1275,7 +1275,7 @@ pushFlagOverrides(overrides: Temporarily layers flag overrides on top of the current overrides. -###### Parameters +###### Parameters @@ -1306,22 +1306,22 @@ The flag overrides to apply for the scoped period.
-###### Returns +###### Returns `Function` A remove function that removes only this override layer. -###### Returns +###### Returns `void` -###### Remarks +###### Remarks This is intended for tests or other short-lived local overrides. The remove function is idempotent and can safely be called multiple times. -###### Example +###### Example ```ts let remove: (() => void) | undefined; @@ -1336,11 +1336,11 @@ afterEach(() => { }); ``` -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`pushFlagOverrides`](globals.md#pushflagoverrides) -##### refreshFlags() +##### refreshFlags() ```ts refreshFlags(waitForVersion?: number): Promise @@ -1348,7 +1348,7 @@ refreshFlags(waitForVersion?: number): Promise Refreshes the flag definitions from the server. -###### Parameters +###### Parameters @@ -1379,11 +1379,11 @@ Optional flag state version to wait for before returning updated definitions.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Remarks +###### Remarks This triggers an on-demand refresh of the cached flag definitions. Useful when you know flags have changed and don't want to wait for the next automatic refresh cycle. @@ -1403,11 +1403,11 @@ records pending refresh work, and the promise may resolve before that fetch runs. The pending refresh is executed on the next request/access or `refreshFlags()` call after the throttle window expires. -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`refreshFlags`](globals.md#refreshflags) -##### setFlagOverrides() +##### setFlagOverrides() ```ts setFlagOverrides(overrides: @@ -1417,7 +1417,7 @@ setFlagOverrides(overrides: Replaces the base flag overrides used by the client. -###### Parameters +###### Parameters @@ -1448,16 +1448,16 @@ The flag overrides.
-###### Returns +###### Returns `void` -###### Remarks +###### Remarks Base overrides are always applied before any temporary layers added through `pushFlagOverrides()`. -###### Example +###### Example ```ts client.setFlagOverrides({ @@ -1466,11 +1466,11 @@ client.setFlagOverrides({ }); ``` -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`setFlagOverrides`](globals.md#setflagoverrides) -##### track() +##### track() ```ts track( @@ -1483,7 +1483,7 @@ track( Tracks an event in Reflag. -###### Parameters +###### Parameters @@ -1532,23 +1532,23 @@ Tracks an event in Reflag.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Throws +###### Throws An error if the user is not set or the event is invalid or the options are invalid. -###### Remarks +###### Remarks If the company is set, the event will be associated with the company. -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`track`](globals.md#track) -##### updateCompany() +##### updateCompany() ```ts updateCompany(companyId: IdType, options?: TrackOptions & { @@ -1558,7 +1558,7 @@ updateCompany(companyId: IdType, options?: TrackOptions & { Updates the associated company in Reflag. -###### Parameters +###### Parameters @@ -1606,24 +1606,24 @@ The options for the company.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Throws +###### Throws An error if the company is not set or the options are invalid. -###### Remarks +###### Remarks The company must be set using `withCompany` before calling this method. If the user is set, the company will be associated with the user. -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`updateCompany`](globals.md#updatecompany) -##### updateUser() +##### updateUser() ```ts updateUser(userId: IdType, options?: TrackOptions): Promise @@ -1631,7 +1631,7 @@ updateUser(userId: IdType, options?: TrackOptions): Promise Updates the associated user in Reflag. -###### Parameters +###### Parameters @@ -1679,35 +1679,35 @@ The options for the user.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Throws +###### Throws An error if the company is not set or the options are invalid. -###### Remarks +###### Remarks The company must be set using `withCompany` before calling this method. If the user is set, the company will be associated with the user. -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`updateUser`](globals.md#updateuser) *** -### ReflagClient +### ReflagClient The SDK client. -#### Remarks +#### Remarks This is the main class for interacting with Reflag. It is used to evaluate flags, update user and company contexts, and track events. -#### Example +#### Example ```ts // set the REFLAG_SECRET_KEY environment variable or pass the secret key to the constructor @@ -1720,13 +1720,13 @@ const isFlagEnabled = client.getFlag("flag-key", { }); ``` -#### Extended by +#### Extended by - [`EdgeClient`](globals.md#edgeclient) -#### Constructors +#### Constructors -##### new ReflagClient() +##### new ReflagClient() ```ts new ReflagClient(options: ClientOptions): ReflagClient @@ -1735,7 +1735,7 @@ new ReflagClient(options: ClientOptions): ReflagClient Creates a new SDK client. See README for configuration options. -###### Parameters +###### Parameters @@ -1766,15 +1766,15 @@ The options for the client or an existing client to clone.
-###### Returns +###### Returns [`ReflagClient`](globals.md#reflagclient) -###### Throws +###### Throws An error if the options are invalid. -#### Properties +#### Properties @@ -1833,11 +1833,11 @@ Gets the logger associated with the client.
-#### Accessors +#### Accessors -##### flagOverrides +##### flagOverrides -###### Set Signature +###### Set Signature ```ts set flagOverrides(overrides: @@ -1845,11 +1845,11 @@ set flagOverrides(overrides: | FlagOverridesFn): void ``` -###### Deprecated +###### Deprecated Use `setFlagOverrides()` for replacing the base override set. -###### Parameters +###### Parameters @@ -1874,13 +1874,13 @@ Use `setFlagOverrides()` for replacing the base override set.
-###### Returns +###### Returns `void` -#### Methods +#### Methods -##### bindClient() +##### bindClient() ```ts bindClient(context: ContextWithTracking): BoundReflagClient @@ -1890,7 +1890,7 @@ Returns a new BoundReflagClient with the user/company/otherContext set to be used in subsequent calls. For example, for evaluating flag targeting or tracking events. -###### Parameters +###### Parameters @@ -1921,22 +1921,22 @@ The context to bind the client to.
-###### Returns +###### Returns [`BoundReflagClient`](globals.md#boundreflagclient) A new client bound with the arguments given. -###### Throws +###### Throws An error if the user/company is given but their ID is not a string. -###### Remarks +###### Remarks The `updateUser` / `updateCompany` methods will automatically be called when the user/company is set respectively. -##### clearFlagOverrides() +##### clearFlagOverrides() ```ts clearFlagOverrides(): void @@ -1944,21 +1944,21 @@ clearFlagOverrides(): void Clears the base flag overrides. -###### Returns +###### Returns `void` -###### Remarks +###### Remarks This does not affect temporary layers added with `pushFlagOverrides()`. -###### Example +###### Example ```ts client.clearFlagOverrides(); ``` -##### destroy() +##### destroy() ```ts destroy(): void @@ -1966,17 +1966,17 @@ destroy(): void Destroys the client and cleans up all resources including timers and background processes. -###### Returns +###### Returns `void` -###### Remarks +###### Remarks After calling this method, the client should not be used anymore. This is particularly useful in development environments with hot reloading to prevent multiple background processes from running simultaneously. -##### flush() +##### flush() ```ts flush(): Promise @@ -1984,11 +1984,11 @@ flush(): Promise Flushes and completes any in-flight fetches in the flag cache. -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Remarks +###### Remarks It is recommended to call this method when the application is shutting down to ensure all events are sent before the process exits. @@ -1998,7 +1998,7 @@ This method is automatically called on natural process exit (`beforeExit`) if shutdown or an explicit `process.exit()`, await this method in your application's shutdown hook before exiting. The SDK does not install signal handlers. -##### getFlag() +##### getFlag() ```ts getFlag(__namedParameters: ContextWithTracking, key: TKey): Flag @@ -2007,7 +2007,7 @@ getFlag(__namedParameters: ContextWithTracking, key: TKey): Flag Gets the evaluated flag for the current context which includes the user, company, and custom context. Using the `isEnabled` property sends a `check` event to Reflag. -###### Type Parameters +###### Type Parameters @@ -2026,7 +2026,7 @@ Using the `isEnabled` property sends a `check` event to Reflag.
-###### Parameters +###### Parameters @@ -2074,17 +2074,17 @@ The key of the flag to get.
-###### Returns +###### Returns [`Flag`](globals.md#flagtconfig) The evaluated flag. -###### Remarks +###### Remarks Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. -##### getFlagDefinitions() +##### getFlagDefinitions() ```ts getFlagDefinitions(): FlagDefinition[] @@ -2093,13 +2093,13 @@ getFlagDefinitions(): FlagDefinition[] Gets the flag definitions, including all config values. To evaluate which flags are enabled for a given user/company, use `getFlags`. -###### Returns +###### Returns [`FlagDefinition`](globals.md#flagdefinition)[] The flags definitions. -##### getFlagRemote() +##### getFlagRemote() ```ts getFlagRemote( @@ -2112,7 +2112,7 @@ additionalContext?: Context): Promise Gets evaluated flag with the usage of remote context. This method triggers a network request every time it's called. -###### Type Parameters +###### Type Parameters @@ -2131,7 +2131,7 @@ This method triggers a network request every time it's called.
-###### Parameters +###### Parameters @@ -2213,13 +2213,13 @@ The additional context to get the flag for.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Flag`](globals.md#flagtconfig)\> evaluated flag -##### getFlags() +##### getFlags() ```ts getFlags(options: ContextWithTracking): Record @@ -2227,7 +2227,7 @@ getFlags(options: ContextWithTracking): Record Gets the evaluated flags for the current context which includes the user, company, and custom context. -###### Parameters +###### Parameters @@ -2258,17 +2258,17 @@ The options for the context.
-###### Returns +###### Returns [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\> The evaluated flags. -###### Remarks +###### Remarks Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. -##### getFlagsForBootstrap() +##### getFlagsForBootstrap() ```ts getFlagsForBootstrap(options: ContextWithTracking): BootstrappedFlags @@ -2277,7 +2277,7 @@ getFlagsForBootstrap(options: ContextWithTracking): BootstrappedFlags Gets the evaluated flags for the current context without wrapping them in getters. This method returns raw flag data suitable for bootstrapping client-side applications. -###### Parameters +###### Parameters @@ -2308,18 +2308,18 @@ The options for the context.
-###### Returns +###### Returns [`BootstrappedFlags`](globals.md#bootstrappedflags) The evaluated raw flags and the context. -###### Remarks +###### Remarks Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. This method returns RawFlag objects without wrapping them in getters, making them suitable for serialization. -##### getFlagsRemote() +##### getFlagsRemote() ```ts getFlagsRemote( @@ -2331,7 +2331,7 @@ additionalContext?: Context): Promise> Gets evaluated flags with the usage of remote context. This method triggers a network request every time it's called. -###### Parameters +###### Parameters @@ -2396,13 +2396,13 @@ The additional context to get the flags for.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\>\> evaluated flags -##### initialize() +##### initialize() ```ts initialize(): Promise @@ -2410,16 +2410,16 @@ initialize(): Promise Initializes the client by caching the flags definitions. -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Remarks +###### Remarks Call this method before calling `getFlags` to ensure the flag definitions are cached. The client will ignore subsequent calls to this method. -##### pushFlagOverrides() +##### pushFlagOverrides() ```ts pushFlagOverrides(overrides: @@ -2429,7 +2429,7 @@ pushFlagOverrides(overrides: Temporarily layers flag overrides on top of the current overrides. -###### Parameters +###### Parameters @@ -2460,22 +2460,22 @@ The flag overrides to apply for the scoped period.
-###### Returns +###### Returns `Function` A remove function that removes only this override layer. -###### Returns +###### Returns `void` -###### Remarks +###### Remarks This is intended for tests or other short-lived local overrides. The remove function is idempotent and can safely be called multiple times. -###### Example +###### Example ```ts let remove: (() => void) | undefined; @@ -2490,7 +2490,7 @@ afterEach(() => { }); ``` -##### refreshFlags() +##### refreshFlags() ```ts refreshFlags(waitForVersion?: number): Promise @@ -2498,7 +2498,7 @@ refreshFlags(waitForVersion?: number): Promise Refreshes the flag definitions from the server. -###### Parameters +###### Parameters @@ -2529,11 +2529,11 @@ Optional flag state version to wait for before returning updated definitions.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Remarks +###### Remarks This triggers an on-demand refresh of the cached flag definitions. Useful when you know flags have changed and don't want to wait for the next automatic refresh cycle. @@ -2553,7 +2553,7 @@ records pending refresh work, and the promise may resolve before that fetch runs. The pending refresh is executed on the next request/access or `refreshFlags()` call after the throttle window expires. -##### setFlagOverrides() +##### setFlagOverrides() ```ts setFlagOverrides(overrides: @@ -2563,7 +2563,7 @@ setFlagOverrides(overrides: Replaces the base flag overrides used by the client. -###### Parameters +###### Parameters @@ -2594,16 +2594,16 @@ The flag overrides.
-###### Returns +###### Returns `void` -###### Remarks +###### Remarks Base overrides are always applied before any temporary layers added through `pushFlagOverrides()`. -###### Example +###### Example ```ts client.setFlagOverrides({ @@ -2612,7 +2612,7 @@ client.setFlagOverrides({ }); ``` -##### track() +##### track() ```ts track( @@ -2625,7 +2625,7 @@ track( Tracks an event in Reflag. -###### Parameters +###### Parameters @@ -2674,19 +2674,19 @@ Tracks an event in Reflag.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Throws +###### Throws An error if the user is not set or the event is invalid or the options are invalid. -###### Remarks +###### Remarks If the company is set, the event will be associated with the company. -##### updateCompany() +##### updateCompany() ```ts updateCompany(companyId: IdType, options?: TrackOptions & { @@ -2696,7 +2696,7 @@ updateCompany(companyId: IdType, options?: TrackOptions & { Updates the associated company in Reflag. -###### Parameters +###### Parameters @@ -2744,20 +2744,20 @@ The options for the company.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Throws +###### Throws An error if the company is not set or the options are invalid. -###### Remarks +###### Remarks The company must be set using `withCompany` before calling this method. If the user is set, the company will be associated with the user. -##### updateUser() +##### updateUser() ```ts updateUser(userId: IdType, options?: TrackOptions): Promise @@ -2765,7 +2765,7 @@ updateUser(userId: IdType, options?: TrackOptions): Promise Updates the associated user in Reflag. -###### Parameters +###### Parameters @@ -2813,30 +2813,30 @@ The options for the user.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Throws +###### Throws An error if the company is not set or the options are invalid. -###### Remarks +###### Remarks The company must be set using `withCompany` before calling this method. If the user is set, the company will be associated with the user. -## Interfaces +## Interfaces -### ContextWithTracking +### ContextWithTracking A context with tracking option. -#### Extends +#### Extends - [`Context`](globals.md#context) -#### Properties +#### Properties @@ -3058,11 +3058,11 @@ The name of the user. *** -### Flag\ +### Flag\ Describes a feature -#### Type Parameters +#### Type Parameters
@@ -3087,7 +3087,7 @@ Describes a feature
-#### Properties +#### Properties @@ -3152,9 +3152,9 @@ The key of the feature.
-#### Methods +#### Methods -##### track() +##### track() ```ts track(): Promise @@ -3162,29 +3162,29 @@ track(): Promise Track feature usage in Reflag. -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> *** -### Flags +### Flags Describes a collection of evaluated features. -#### Remarks +#### Remarks You should extend the Flags interface to define the available features. *** -### FlagsFallbackProvider +### FlagsFallbackProvider Provider used to load and save raw flag definition snapshots. -#### Methods +#### Methods -##### load() +##### load() ```ts load(context: FlagsFallbackProviderContext): Promise @@ -3192,7 +3192,7 @@ load(context: FlagsFallbackProviderContext): Promise @@ -3217,11 +3217,11 @@ Load a previously saved snapshot.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`undefined` \| [`FlagsFallbackSnapshot`](globals.md#flagsfallbacksnapshot)\> -##### save() +##### save() ```ts save(context: FlagsFallbackProviderContext, snapshot: FlagsFallbackSnapshot): Promise @@ -3229,7 +3229,7 @@ save(context: FlagsFallbackProviderContext, snapshot: FlagsFallbackSnapshot): Pr Persist a snapshot after a successful live fetch. -###### Parameters +###### Parameters @@ -3266,24 +3266,24 @@ Persist a snapshot after a successful live fetch.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> *** -### HttpClient +### HttpClient Defines the interface for an HTTP client. -#### Remarks +#### Remarks This interface is used to abstract the HTTP client implementation from the SDK. Define your own implementation of this interface to use a different HTTP client. -#### Methods +#### Methods -##### get() +##### get() ```ts get( @@ -3294,7 +3294,7 @@ timeoutMs: number): Promise> Sends a GET request to the specified URL. -###### Type Parameters +###### Type Parameters @@ -3313,7 +3313,7 @@ Sends a GET request to the specified URL.
-###### Parameters +###### Parameters @@ -3378,13 +3378,13 @@ The headers to include in the request.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`HttpClientResponse`](globals.md#httpclientresponsetresponse)\<`TResponse`\>\> The response from the server. -##### post() +##### post() ```ts post( @@ -3395,7 +3395,7 @@ body: TBody): Promise> Sends a POST request to the specified URL. -###### Type Parameters +###### Type Parameters @@ -3421,7 +3421,7 @@ Sends a POST request to the specified URL.
-###### Parameters +###### Parameters @@ -3486,7 +3486,7 @@ The body of the request.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`HttpClientResponse`](globals.md#httpclientresponsetresponse)\<`TResponse`\>\> @@ -3494,11 +3494,11 @@ The response from the server. *** -### Logger +### Logger Logger interface for logging messages -#### Properties +#### Properties @@ -3582,11 +3582,11 @@ Log a warning messages *** -### RawFlag +### RawFlag Describes a feature. -#### Properties +#### Properties
@@ -3723,9 +3723,9 @@ The version of the targeting used to evaluate if the feature is enabled (optiona
-## Type Aliases +## Type Aliases -### Attributes +### Attributes ```ts type Attributes = Record; @@ -3735,7 +3735,7 @@ Describes the attributes of a user, company or event. *** -### BatchBufferOptions\ +### BatchBufferOptions\ ```ts type BatchBufferOptions = { @@ -3749,7 +3749,7 @@ type BatchBufferOptions = { Options for configuring the BatchBuffer. -#### Type Parameters +#### Type Parameters @@ -3774,7 +3774,7 @@ The type of items in the buffer.
-#### Type declaration +#### Type declaration @@ -3882,7 +3882,7 @@ The maximum size of the buffer before it is flushed. *** -### BootstrappedFlags +### BootstrappedFlags ```ts type BootstrappedFlags = { @@ -3894,7 +3894,7 @@ type BootstrappedFlags = { Describes a collection of evaluated raw flags and the context for bootstrapping. -#### Type declaration +#### Type declaration
@@ -3945,7 +3945,7 @@ Describes a collection of evaluated raw flags and the context for bootstrapping. *** -### CacheStrategy +### CacheStrategy ```ts type CacheStrategy = "periodically-update" | "in-request"; @@ -3953,7 +3953,7 @@ type CacheStrategy = "periodically-update" | "in-request"; *** -### ClientOptions +### ClientOptions ```ts type ClientOptions = { @@ -3982,7 +3982,7 @@ type ClientOptions = { Defines the options for the SDK client. -#### Type declaration +#### Type declaration
@@ -4337,7 +4337,7 @@ The secret key used to authenticate with the Reflag API. *** -### Context +### Context ```ts type Context = { @@ -4359,7 +4359,7 @@ type Context = { Describes the current user context, company context, and other context. This is used to determine if feature targeting matches and to track events. -#### Type declaration +#### Type declaration
@@ -4554,7 +4554,7 @@ The name of the user. *** -### EdgeClientOptions +### EdgeClientOptions ```ts type EdgeClientOptions = Omit; @@ -4562,7 +4562,7 @@ type EdgeClientOptions = Omit ```ts type EmptyFlagRemoteConfig = { @@ -4571,7 +4571,7 @@ type EmptyFlagRemoteConfig = { }; ``` -#### Type declaration +#### Type declaration
@@ -4610,7 +4610,7 @@ type EmptyFlagRemoteConfig = { *** -### FileFallbackProviderOptions +### FileFallbackProviderOptions ```ts type FileFallbackProviderOptions = { @@ -4618,7 +4618,7 @@ type FileFallbackProviderOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -4651,7 +4651,7 @@ Directory where per-environment snapshots are stored. *** -### FlagAPIResponse +### FlagAPIResponse ```ts type FlagAPIResponse = { @@ -4674,7 +4674,7 @@ type FlagAPIResponse = { (Internal) Describes a specific feature in the API response. -#### Type declaration +#### Type declaration
@@ -4836,7 +4836,7 @@ The version of the targeting rules. *** -### FlagConfigVariant +### FlagConfigVariant ```ts type FlagConfigVariant = { @@ -4848,7 +4848,7 @@ type FlagConfigVariant = { Describes a remote feature config variant. -#### Type declaration +#### Type declaration
@@ -4915,7 +4915,7 @@ The optional user-supplied payload data. *** -### FlagDefinition +### FlagDefinition ```ts type FlagDefinition = { @@ -4936,7 +4936,7 @@ type FlagDefinition = { Describes a feature definition. -#### Type declaration +#### Type declaration
@@ -5098,7 +5098,7 @@ The key of the feature. *** -### FlagOverride +### FlagOverride ```ts type FlagOverride = @@ -5113,7 +5113,7 @@ type FlagOverride = *** -### FlagOverrides +### FlagOverrides ```ts type FlagOverrides = Partial : { [FlagKey in keyof Flags]: Flags[FlagKey] extends FlagOverride ? Flags[FlagKey] : Exclude }>; @@ -5123,13 +5123,13 @@ Describes the feature overrides. *** -### FlagOverridesFn() +### FlagOverridesFn() ```ts type FlagOverridesFn = (context: Context) => FlagOverrides; ``` -#### Parameters +#### Parameters
@@ -5154,13 +5154,13 @@ type FlagOverridesFn = (context: Context) => FlagOverrides;
-#### Returns +#### Returns [`FlagOverrides`](globals.md#flagoverrides) *** -### FlagRemoteConfig +### FlagRemoteConfig ```ts type FlagRemoteConfig = @@ -5173,7 +5173,7 @@ type FlagRemoteConfig = A remotely managed configuration value for a feature. -#### Type declaration +#### Type declaration \{ `key`: `string`; @@ -5230,7 +5230,7 @@ The optional user-supplied payload data. *** -### FlagsAPIResponse +### FlagsAPIResponse ```ts type FlagsAPIResponse = { @@ -5243,7 +5243,7 @@ type FlagsAPIResponse = { (Internal) Describes the response of the features endpoint. -#### Type declaration +#### Type declaration @@ -5294,7 +5294,7 @@ should be treated as unknown by consumers. *** -### FlagsFallbackProviderContext +### FlagsFallbackProviderContext ```ts type FlagsFallbackProviderContext = { @@ -5305,7 +5305,7 @@ type FlagsFallbackProviderContext = { Non-secret context passed to fallback providers so they can derive storage keys without access to the raw secret key. -#### Type declaration +#### Type declaration
@@ -5338,7 +5338,7 @@ Deterministic hash of the configured secret key. *** -### FlagsFallbackSnapshot +### FlagsFallbackSnapshot ```ts type FlagsFallbackSnapshot = { @@ -5350,7 +5350,7 @@ type FlagsFallbackSnapshot = { Snapshot of flag definitions used for fallback initialization. -#### Type declaration +#### Type declaration
@@ -5417,7 +5417,7 @@ Snapshot schema version. *** -### FlagsSyncMode +### FlagsSyncMode ```ts type FlagsSyncMode = "polling" | "in-request" | "push"; @@ -5425,7 +5425,7 @@ type FlagsSyncMode = "polling" | "in-request" | "push"; *** -### FlagType +### FlagType ```ts type FlagType = { @@ -5435,7 +5435,7 @@ type FlagType = { }; ``` -#### Type declaration +#### Type declaration
@@ -5476,7 +5476,7 @@ type FlagType = { *** -### GCSFallbackProviderClient +### GCSFallbackProviderClient ```ts type GCSFallbackProviderClient = @@ -5486,7 +5486,7 @@ type GCSFallbackProviderClient = *** -### GCSFallbackProviderOptions +### GCSFallbackProviderOptions ```ts type GCSFallbackProviderOptions = { @@ -5496,7 +5496,7 @@ type GCSFallbackProviderOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -5568,7 +5568,7 @@ Prefix for generated per-environment keys. *** -### GCSGoogleApisClient +### GCSGoogleApisClient ```ts type GCSGoogleApisClient = { @@ -5581,7 +5581,7 @@ type GCSGoogleApisClient = { }; ``` -#### Type declaration +#### Type declaration
@@ -5639,7 +5639,7 @@ type GCSGoogleApisClient = { *** -### GCSLegacyClient +### GCSLegacyClient ```ts type GCSLegacyClient = { @@ -5653,7 +5653,7 @@ type GCSLegacyClient = { }; ``` -#### Type declaration +#### Type declaration
@@ -5686,7 +5686,7 @@ type GCSLegacyClient = { *** -### HttpClientResponse\ +### HttpClientResponse\ ```ts type HttpClientResponse = { @@ -5699,7 +5699,7 @@ type HttpClientResponse = { Describes the response of a HTTP client. -#### Type Parameters +#### Type Parameters
@@ -5724,7 +5724,7 @@ The type of the response body.
-#### Type declaration +#### Type declaration @@ -5809,7 +5809,7 @@ The status code of the response. *** -### IdType +### IdType ```ts type IdType = string | number; @@ -5817,7 +5817,7 @@ type IdType = string | number; *** -### LogLevel +### LogLevel ```ts type LogLevel = typeof LOG_LEVELS[number]; @@ -5825,7 +5825,7 @@ type LogLevel = typeof LOG_LEVELS[number]; *** -### RawFlagRemoteConfig +### RawFlagRemoteConfig ```ts type RawFlagRemoteConfig = { @@ -5840,7 +5840,7 @@ type RawFlagRemoteConfig = { A remotely managed configuration value for a feature. -#### Type declaration +#### Type declaration
@@ -5962,7 +5962,7 @@ The version of the targeting rules used to select the config value. *** -### RawFlags +### RawFlags ```ts type RawFlags = Record; @@ -5972,7 +5972,7 @@ Describes a collection of evaluated raw flags. *** -### RedisFallbackProviderOptions +### RedisFallbackProviderOptions ```ts type RedisFallbackProviderOptions = { @@ -5984,7 +5984,7 @@ type RedisFallbackProviderOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -6071,7 +6071,7 @@ Prefix for generated per-environment keys. *** -### S3FallbackProviderOptions +### S3FallbackProviderOptions ```ts type S3FallbackProviderOptions = { @@ -6083,7 +6083,7 @@ type S3FallbackProviderOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -6169,7 +6169,7 @@ Prefix for generated per-environment keys. *** -### StaticFallbackProviderOptions +### StaticFallbackProviderOptions ```ts type StaticFallbackProviderOptions = { @@ -6177,7 +6177,7 @@ type StaticFallbackProviderOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -6210,7 +6210,7 @@ Static fallback flags keyed by flag key. *** -### TrackingMeta +### TrackingMeta ```ts type TrackingMeta = { @@ -6220,7 +6220,7 @@ type TrackingMeta = { Describes the meta context associated with tracking. -#### Type declaration +#### Type declaration
@@ -6253,7 +6253,7 @@ Whether the user or company is active. *** -### TrackOptions +### TrackOptions ```ts type TrackOptions = { @@ -6264,7 +6264,7 @@ type TrackOptions = { Defines the options for tracking of entities. -#### Type declaration +#### Type declaration
@@ -6314,7 +6314,7 @@ The meta context associated with the event. *** -### TypedFlagKey +### TypedFlagKey ```ts type TypedFlagKey = keyof TypedFlags; @@ -6322,7 +6322,7 @@ type TypedFlagKey = keyof TypedFlags; *** -### TypedFlags +### TypedFlags ```ts type TypedFlags = keyof Flags extends never ? Record : { [FlagKey in keyof Flags]: Flags[FlagKey] extends FlagType ? Flag : Flag }; @@ -6330,14 +6330,14 @@ type TypedFlags = keyof Flags extends never ? Record : { [FlagKey Describes a collection of evaluated feature. -#### Remarks +#### Remarks This types falls back to a generic Record if the Flags interface has not been extended. -## Variables +## Variables -### fallbackProviders +### fallbackProviders ```ts const fallbackProviders: { @@ -6349,7 +6349,7 @@ const fallbackProviders: { }; ``` -#### Type declaration +#### Type declaration
@@ -6450,7 +6450,7 @@ createStaticFallbackProvider *** -### LOG\_LEVELS +### LOG\_LEVELS ```ts const LOG_LEVELS: readonly ["DEBUG", "INFO", "WARN", "ERROR"]; diff --git a/legacy/v1/react-sdk/README.md b/legacy/v1/react-sdk/README.md index 7162133..5862d71 100644 --- a/legacy/v1/react-sdk/README.md +++ b/legacy/v1/react-sdk/README.md @@ -19,7 +19,7 @@ pagination: Generated from [`@reflag/react-sdk@1.7.4`](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/react-sdk); SDK READMEs and code comments remain the source of truth. {% endhint %} -# Reflag React SDK +# Reflag React SDK React client side library for [Reflag.com](https://reflag.com) @@ -27,7 +27,7 @@ Reflag supports flag toggling, tracking flag usage, [requesting feedback](#usere The Reflag React SDK comes with a [built-in toolbar](../browser-sdk/README.md#toolbar) which appears on `localhost` by default. -## Install +## Install Install via npm: @@ -35,9 +35,9 @@ Install via npm: npm i @reflag/react-sdk@1 ``` -## Get started +## Get started -### 1. Add the `ReflagProvider` context provider +### 1. Add the `ReflagProvider` context provider Add the `ReflagProvider` context provider to your application: @@ -58,7 +58,7 @@ import { ReflagProvider } from "@reflag/react-sdk"; ; ``` -### 2. Create a new flag and set up type safety +### 2. Create a new flag and set up type safety Install the Reflag CLI: @@ -90,7 +90,7 @@ Creating flag for app Slick app. > By default, types will be generated in `gen/flags.d.ts`. > The default `tsconfig.json` file `include`s this file by default, but if your `tsconfig.json` is different, make sure the file is covered in the `include` property. -### 3. Use `useFlag()` to get flag status +### 3. Use `useFlag()` to get flag status Using the `useFlag` hook from your components lets you toggle flags on/off and track flag usage: @@ -113,12 +113,12 @@ function StartHuddleButton() { `useFlag` can help you do much more. See a full example for `useFlag` [see below](#useflag). -## Setting context +## Setting context Reflag determines which flags are active for a given `user`, `company`, or `other` context. You can pass these to the `ReflagProvider` using the `context` prop. -### Using the `context` prop +### Using the `context` prop ```tsx ``` -### Legacy individual props (deprecated) +### Legacy individual props (deprecated) For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version: @@ -155,7 +155,7 @@ For backward compatibility, you can still use individual props, but these are de > [!Important] > The `user`, `company`, and `otherContext` props are deprecated. Use the `context` prop instead, which provides the same functionality in a more structured way. -### Context requirements +### Context requirements If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. @@ -173,21 +173,21 @@ To retrieve flags along with their targeting information, use `useFlag(key: stri Note that accessing `isEnabled` on the object returned by `useFlag()` automatically generates a `check` event. -## React Native +## React Native For React Native, use `@reflag/react-native-sdk`, which is a thin wrapper around `@reflag/react-sdk` and wires up AsyncStorage by default. An Expo example app lives at `packages/react-native-sdk/dev/expo`. -## Remote config +## Remote config Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. Similar to `isEnabled`, each flag accessed using the `useFlag()` hook, has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the binary `isEnabled` you can have multiple configuration values which are given to different user/companies. -### Get started with Remote config +### Get started with Remote config 1. Update your flag definitions: @@ -223,7 +223,7 @@ const { Note that, similar to `isEnabled`, accessing `config` on the object returned by `useFlag()` automatically generates a `check` event. -## Toolbar +## Toolbar The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off. @@ -242,7 +242,7 @@ You can pass a simple boolean to force the toolbar to appear/disappear: }); ``` -## Server-side rendering and bootstrapping +## Server-side rendering and bootstrapping For server-side rendered applications, you can render immediately with pre-fetched flag data using the `ReflagBootstrappedProvider`. @@ -250,7 +250,7 @@ Bootstrapping is also the recommended setup if you want the most resilient featu If you want "bullet proof feature flags" in a React application, use React bootstrapping together with `flagsFallbackProvider` in the Node SDK. The fallback provider helps your server start with the latest saved snapshot if it cannot reach Reflag during initialization, and bootstrapping gives the React client server-provided flags for its first render. -### Using `ReflagBootstrappedProvider` +### Using `ReflagBootstrappedProvider` The `` component is a specialized version of `ReflagProvider` designed for server-side rendering, preloaded flag scenarios, and high-reliability setups. It uses pre-fetched evaluated state for the initial render, resulting in faster initial page loads, better SSR compatibility, and a more resilient startup path for React applications. @@ -292,7 +292,7 @@ function App() { } ``` -### Server-side endpoint setup +### Server-side endpoint setup Create an endpoint that provides bootstrap data to your client application: @@ -330,7 +330,7 @@ The `flags` object returned by `getFlagsForBootstrap()` contains the full bootst If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. -### Next.js Page Router SSR example +### Next.js Page Router SSR example For Next.js applications using server-side rendering, you can pre-fetch flags in `getServerSideProps`: @@ -391,7 +391,7 @@ function HuddleFeature() { This approach eliminates loading states and removes the initial render's dependency on the flags API. -### Next.js App Router example +### Next.js App Router example For Next.js applications using the App Router (Next.js 13+), you can pre-fetch flags in Server Components and pass them to client components: @@ -496,13 +496,13 @@ export function HuddleFeature() { This App Router approach leverages Server Components for server-side flag fetching while using Client Components only where React state and hooks are needed. -## `` component +## `` component The `` is a lower-level component that accepts a `ReflagClient` instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application. In most cases you should initialize the client before rendering this provider. If you pass an idle client and enable `suspense`, a `useFlag()` call that suspends can initialize the client on demand; without Suspense, you must initialize the client yourself. -### Usage +### Usage ```tsx import { ReflagClient } from "@reflag/browser-sdk"; @@ -528,7 +528,7 @@ function App() { } ``` -### Props +### Props The `ReflagClientProvider` accepts the following props: @@ -539,7 +539,7 @@ The `ReflagClientProvider` accepts the following props: > [!Note] > Most applications should use `ReflagProvider` or `ReflagBootstrappedProvider` instead of `ReflagClientProvider`. Only use this component when you need the advanced control it provides. -## `` component +## `` component The `` initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props: @@ -585,7 +585,7 @@ The `` initializes the Reflag SDK, fetches flags and starts list - `toolbar`: Optional [configuration](../browser-sdk/globals.md#toolbaroptions) for the Reflag toolbar, - `feedback`: Optional configuration for feedback collection -## `` component +## `` component The `` is a specialized version of the `ReflagProvider` that uses pre-fetched flag data for the initial render. This is ideal for server-side rendering scenarios. @@ -631,9 +631,9 @@ function App({ bootstrapData }: AppProps) { > > Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. -## Hooks +## Hooks -### `useFlag()` +### `useFlag()` Returns the state of a given flag for the current context. The hook provides type-safe access to flags and their configurations. @@ -683,7 +683,7 @@ function StartHuddleButton() { } ``` -#### Suspense loading +#### Suspense loading Enable `suspense` on the provider to have `useFlag()` throw a promise while `isLoading` is true. The nearest `` boundary will render its fallback until flags are ready. @@ -700,7 +700,7 @@ import { ReflagProvider } from "@reflag/react-sdk"; You can also opt in for a single call with `useFlag("huddle", { suspense: true })`, or opt out inside a suspense-enabled provider with `{ suspense: false }`. -### `useOptInFlags()` and `useSetOptIn()` +### `useOptInFlags()` and `useSetOptIn()` Use these hooks to build an end-user opt-in UI for flags where opt-in is enabled in Reflag. @@ -770,7 +770,7 @@ import { Suspense } from "react"; Opt-in metadata Suspense is primarily relevant with `ReflagBootstrappedProvider`. Use `useOptInFlags({ suspense: false })` to opt out for one call when Suspense is enabled on the provider. -### `useTrack()` +### `useTrack()` `useTrack()` lets you send custom events to Reflag. Use this whenever a user _uses_ a feature. These events can be used to analyze feature usage in Reflag. @@ -787,7 +787,7 @@ function StartHuddle() { } ``` -### `useRequestFeedback()` +### `useRequestFeedback()` `useRequestFeedback()` returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features as part of roll out. See [Automated Feedback Surveys](https://docs.reflag.com/product-handbook/live-satisfaction) for how to do this automatically, without code. @@ -825,7 +825,7 @@ function FeedbackButton() { See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/FEEDBACK.md#manual-feedback-collection) for more information on `requestFeedback` options. -### `useSendFeedback()` +### `useSendFeedback()` Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag. @@ -847,7 +847,7 @@ function CustomFeedbackForm() { } ``` -### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` +### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` These hooks return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session. @@ -894,7 +894,7 @@ function FlagOptIn() { } ``` -### `useClient()` +### `useClient()` Returns the `ReflagClient` used by the `ReflagProvider`. The client offers more functionality that is not directly accessible thorough the other hooks. @@ -911,7 +911,7 @@ function LoggingWrapper({ children }: { children: ReactNode }) { } ``` -### `useIsLoading()` +### `useIsLoading()` Returns the loading state of the flags in the `ReflagClient`. Initially, the value will be `true` if no bootstrap flags have been provided and the client has not be initialized. @@ -931,7 +931,7 @@ function LoadingWrapper({ children }: { children: ReactNode }) { } ``` -### `useOnEvent()` +### `useOnEvent()` Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount. @@ -947,7 +947,7 @@ function LoggingWrapper({ children }: { children: ReactNode }) { } ``` -## Migrating from Bucket SDK +## Migrating from Bucket SDK If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: @@ -973,11 +973,11 @@ If you are running with strict Content Security Policies active on your website, - `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com` -## Content Security Policy (CSP) +## Content Security Policy (CSP) See [CSP](https://github.com/reflagcom/javascript/blob/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/README.md#content-security-policy-csp) for info on using Reflag React SDK with CSP -## License +## License MIT License diff --git a/legacy/v1/react-sdk/globals.md b/legacy/v1/react-sdk/globals.md index fd3fe4c..bb8f00d 100644 --- a/legacy/v1/react-sdk/globals.md +++ b/legacy/v1/react-sdk/globals.md @@ -19,15 +19,15 @@ pagination: Generated from [`@reflag/react-sdk@1.7.4`](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/react-sdk); SDK READMEs and code comments remain the source of truth. {% endhint %} -# @reflag/react-sdk +# @reflag/react-sdk -## Interfaces +## Interfaces -### CheckEvent +### CheckEvent Event representing checking the flag evaluation result -#### Properties +#### Properties
@@ -168,19 +168,19 @@ Version of targeting rules. *** -### CompanyContext +### CompanyContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing company. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties
@@ -230,11 +230,11 @@ Company name *** -### Flag\ +### Flag\ Describes a feature -#### Type Parameters +#### Type Parameters
@@ -259,7 +259,7 @@ Describes a feature
-#### Properties +#### Properties @@ -358,9 +358,9 @@ Request feedback from the user.
-#### Methods +#### Methods -##### track() +##### track() ```ts track(): @@ -372,7 +372,7 @@ track(): Track feature usage in Reflag. -###### Returns +###### Returns \| `undefined` \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< @@ -381,23 +381,23 @@ Track feature usage in Reflag. *** -### Flags +### Flags *** -### UserContext +### UserContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing user. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties @@ -462,9 +462,9 @@ User name
-## Type Aliases +## Type Aliases -### BootstrappedFlags +### BootstrappedFlags ```ts type BootstrappedFlags = BootstrappedState & { @@ -472,7 +472,7 @@ type BootstrappedFlags = BootstrappedState & { }; ``` -#### Type declaration +#### Type declaration @@ -499,7 +499,7 @@ type BootstrappedFlags = BootstrappedState & { *** -### EmptyFlagRemoteConfig +### EmptyFlagRemoteConfig ```ts type EmptyFlagRemoteConfig = { @@ -508,7 +508,7 @@ type EmptyFlagRemoteConfig = { }; ``` -#### Type declaration +#### Type declaration
@@ -547,7 +547,7 @@ type EmptyFlagRemoteConfig = { *** -### FlagKey +### FlagKey ```ts type FlagKey = keyof TypedFlags; @@ -555,7 +555,7 @@ type FlagKey = keyof TypedFlags; *** -### FlagRemoteConfig +### FlagRemoteConfig ```ts type FlagRemoteConfig = @@ -568,7 +568,7 @@ type FlagRemoteConfig = A remotely managed configuration value for a feature. -#### Type declaration +#### Type declaration \{ `key`: `string`; @@ -625,7 +625,7 @@ The optional user-supplied payload data. *** -### FlagType +### FlagType ```ts type FlagType = { @@ -635,7 +635,7 @@ type FlagType = { }; ``` -#### Type declaration +#### Type declaration
@@ -676,7 +676,7 @@ type FlagType = { *** -### OptInFlag +### OptInFlag ```ts type OptInFlag = Omit & { @@ -690,7 +690,7 @@ Includes all fields from [BrowserOptInFlag](../browser-sdk/globals.md#optinflag) `isEnabled`, `userOptedIn`, `companyOptedIn`, and `isOptedIn`. Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. -#### Type declaration +#### Type declaration
@@ -717,7 +717,7 @@ Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. *** -### RawFlags +### RawFlags ```ts type RawFlags = Record; @@ -727,7 +727,7 @@ Describes a collection of evaluated raw flags. *** -### ReflagBootstrappedProps +### ReflagBootstrappedProps ```ts type ReflagBootstrappedProps = ReflagPropsBase & ReflagInitOptionsBase & { @@ -737,7 +737,7 @@ type ReflagBootstrappedProps = ReflagPropsBase & ReflagInitOptionsBase & { Props for the ReflagBootstrappedProvider. -#### Type declaration +#### Type declaration
@@ -771,7 +771,7 @@ metadata on demand when opt-in flags are requested. *** -### ReflagClientProviderProps +### ReflagClientProviderProps ```ts type ReflagClientProviderProps = Omit & { @@ -781,7 +781,7 @@ type ReflagClientProviderProps = Omit & { Props for the ReflagClientProvider. -#### Type declaration +#### Type declaration
@@ -808,7 +808,7 @@ Props for the ReflagClientProvider. *** -### ReflagInitOptionsBase +### ReflagInitOptionsBase ```ts type ReflagInitOptionsBase = Omit ```ts type ReflagProps = ReflagPropsBase & ReflagInitOptionsBase & { @@ -840,7 +840,7 @@ type ReflagProps = ReflagPropsBase & ReflagInitOptionsBase & { Props for the ReflagProvider. -#### Type declaration +#### Type declaration
@@ -938,7 +938,7 @@ Use `context` instead, this property will be removed in the next major version *** -### ReflagPropsBase +### ReflagPropsBase ```ts type ReflagPropsBase = { @@ -955,7 +955,7 @@ type ReflagPropsBase = { Base props for the ReflagProvider and ReflagBootstrappedProvider. -#### Type declaration +#### Type declaration
@@ -1077,7 +1077,7 @@ wrapped in a React `` boundary. *** -### RequestFeedbackOptions +### RequestFeedbackOptions ```ts type RequestFeedbackOptions = Omit; @@ -1085,7 +1085,7 @@ type RequestFeedbackOptions = Omit *** -### SetOptInOptions +### SetOptInOptions ```ts type SetOptInOptions = { @@ -1096,7 +1096,7 @@ type SetOptInOptions = { Options for changing the current user or company's opt-in membership. -#### Type declaration +#### Type declaration
@@ -1146,7 +1146,7 @@ Whether to update the current user or current company. Defaults to `user`. *** -### StorageAdapter +### StorageAdapter ```ts type StorageAdapter = { @@ -1156,7 +1156,7 @@ type StorageAdapter = { }; ``` -#### Type declaration +#### Type declaration
@@ -1207,7 +1207,7 @@ type StorageAdapter = { *** -### TrackEvent +### TrackEvent ```ts type TrackEvent = { @@ -1219,7 +1219,7 @@ type TrackEvent = { }; ``` -#### Type declaration +#### Type declaration
@@ -1283,7 +1283,7 @@ type TrackEvent = { *** -### TypedFlags +### TypedFlags ```ts type TypedFlags = keyof Flags extends never ? Record : { [TypedFlagKey in keyof Flags]: Flags[TypedFlagKey] extends FlagType ? Flag : Flag }; @@ -1291,14 +1291,14 @@ type TypedFlags = keyof Flags extends never ? Record : { [TypedFla Describes a collection of evaluated feature. -#### Remarks +#### Remarks This types falls back to a generic Record if the Flags interface has not been extended. *** -### UseFlagOptions +### UseFlagOptions ```ts type UseFlagOptions = { @@ -1306,7 +1306,7 @@ type UseFlagOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -1340,7 +1340,7 @@ When true, `useFlag` throws a promise while flags are loading. *** -### UseOptInFlagsOptions +### UseOptInFlagsOptions ```ts type UseOptInFlagsOptions = { @@ -1348,7 +1348,7 @@ type UseOptInFlagsOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -1382,7 +1382,7 @@ When true, `useOptInFlags` throws a promise while opt-in flags are loading. *** -### UseOptInFlagsResult +### UseOptInFlagsResult ```ts type UseOptInFlagsResult = { @@ -1391,7 +1391,7 @@ type UseOptInFlagsResult = { }; ``` -#### Type declaration +#### Type declaration
@@ -1439,9 +1439,9 @@ Whether a bootstrapped provider is fetching opt-in metadata.
-## Functions +## Functions -### ReflagBootstrappedProvider() +### ReflagBootstrappedProvider() ```ts function ReflagBootstrappedProvider(__namedParameters: ReflagBootstrappedProps): Element @@ -1449,7 +1449,7 @@ function ReflagBootstrappedProvider(__namedParameters: ReflagBootstrappedProps): Bootstrapped Provider for the ReflagClient using pre-fetched flags. -#### Parameters +#### Parameters @@ -1474,19 +1474,19 @@ Bootstrapped Provider for the ReflagClient using pre-fetched flags.
-#### Returns +#### Returns `Element` *** -### ReflagClientProvider() +### ReflagClientProvider() ```ts function ReflagClientProvider(__namedParameters: ReflagClientProviderProps): Element ``` -#### Parameters +#### Parameters @@ -1511,13 +1511,13 @@ function ReflagClientProvider(__namedParameters: ReflagClientProviderProps): Ele
-#### Returns +#### Returns `Element` *** -### ReflagProvider() +### ReflagProvider() ```ts function ReflagProvider(__namedParameters: ReflagProps): Element @@ -1525,7 +1525,7 @@ function ReflagProvider(__namedParameters: ReflagProps): Element Provider for the ReflagClient. -#### Parameters +#### Parameters @@ -1550,13 +1550,13 @@ Provider for the ReflagClient.
-#### Returns +#### Returns `Element` *** -### useClient() +### useClient() ```ts function useClient(): ReflagClient @@ -1566,13 +1566,13 @@ Returns the current `ReflagClient` used by the `ReflagProvider`. This is useful if you need to access the `ReflagClient` outside of the `ReflagProvider`. -#### Returns +#### Returns [`ReflagClient`](../browser-sdk/globals.md#reflagclient) The `ReflagClient`. -#### Example +#### Example ```ts import { useClient } from '@reflag/react-sdk'; @@ -1585,13 +1585,13 @@ function App() { *** -### ~~useFeature()~~ +### ~~useFeature()~~ ```ts function useFeature(key: TKey, options?: UseFlagOptions): Flag ``` -#### Type Parameters +#### Type Parameters @@ -1610,7 +1610,7 @@ function useFeature(key: TKey, options?: UseFlagOptions): Flag
-#### Parameters +#### Parameters @@ -1647,17 +1647,17 @@ function useFeature(key: TKey, options?: UseFlagOptions): Flag
-#### Returns +#### Returns [`Flag`](globals.md#flagtconfig) -#### Deprecated +#### Deprecated use `useFlag` instead *** -### useFlag() +### useFlag() ```ts function useFlag(key: TKey, options: UseFlagOptions): TypedFlags[TKey] @@ -1673,7 +1673,7 @@ function HuddleButton() { } ``` -#### Type Parameters +#### Type Parameters @@ -1692,7 +1692,7 @@ function HuddleButton() {
-#### Parameters +#### Parameters @@ -1729,13 +1729,13 @@ function HuddleButton() {
-#### Returns +#### Returns [`TypedFlags`](globals.md#typedflags)\[`TKey`\] *** -### useIsLoading() +### useIsLoading() ```ts function useIsLoading(): boolean @@ -1745,13 +1745,13 @@ Returns a boolean indicating if the Reflag client is loading. You can use this to check if the Reflag client is loading at any point in your application. Initially, the value will be true until the client is initialized. -#### Returns +#### Returns `boolean` A boolean indicating if the Reflag client is loading. -#### Example +#### Example ```ts import { useIsLoading } from '@reflag/react-sdk'; @@ -1763,7 +1763,7 @@ console.log(isLoading); *** -### useOnEvent() +### useOnEvent() ```ts function useOnEvent( @@ -1774,7 +1774,7 @@ function useOnEvent( Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount. -#### Type Parameters +#### Type Parameters @@ -1793,7 +1793,7 @@ Attach a callback handler to client events to act on changes. It automatically d
-#### Parameters +#### Parameters @@ -1858,11 +1858,11 @@ The Reflag client to listen to. If not provided, the client will be retrieved fr
-#### Returns +#### Returns `void` -#### Example +#### Example ```ts import { useOnEvent } from '@reflag/react-sdk'; @@ -1874,7 +1874,7 @@ useOnEvent("flagsUpdated", () => { *** -### useOptInFlags() +### useOptInFlags() ```ts function useOptInFlags(options?: UseOptInFlagsOptions): UseOptInFlagsResult @@ -1891,7 +1891,7 @@ of returning a loading result. A Suspense boundary alone does not enable it. If fetching opt-in metadata fails, loading ends without exposing an error. Call `refresh()` on the client returned by [useClient](globals.md#useclient) to retry. -#### Parameters +#### Parameters @@ -1916,13 +1916,13 @@ Call `refresh()` on the client returned by [useClient](globals.md#useclient) to
-#### Returns +#### Returns [`UseOptInFlagsResult`](globals.md#useoptinflagsresult) *** -### useRequestFeedback() +### useRequestFeedback() ```ts function useRequestFeedback(): (options: RequestFeedbackData) => void @@ -1941,11 +1941,11 @@ reflag.requestFeedback({ }); ``` -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -1970,13 +1970,13 @@ reflag.requestFeedback({
-##### Returns +##### Returns `void` *** -### useSendFeedback() +### useSendFeedback() ```ts function useSendFeedback(): (opts: UnassignedFeedback) => Promise< @@ -1999,11 +1999,11 @@ sendFeedback({ }); ``` -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -2028,7 +2028,7 @@ sendFeedback({
-##### Returns +##### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` @@ -2036,7 +2036,7 @@ sendFeedback({ *** -### useSetOptIn() +### useSetOptIn() ```ts function useSetOptIn(): (key: string, options: SetOptInOptions) => Promise< @@ -2051,11 +2051,11 @@ HTTP failures return a non-OK Response; offline mode, invalid arguments, or missing scoped context return undefined. Confirmation failures can reject after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sdk/globals.md#setoptin). -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -2092,7 +2092,7 @@ after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sd
-##### Returns +##### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` @@ -2100,7 +2100,7 @@ after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sd *** -### useTrack() +### useTrack() ```ts function useTrack(): (eventName: string, attributes?: @@ -2118,11 +2118,11 @@ const track = useTrack(); track("Started Huddle", { button: "cta" }); ``` -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -2159,7 +2159,7 @@ track("Started Huddle", { button: "cta" });
-##### Returns +##### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` @@ -2167,7 +2167,7 @@ track("Started Huddle", { button: "cta" }); *** -### useUpdateCompany() +### useUpdateCompany() ```ts function useUpdateCompany(): (opts: {}) => Promise @@ -2185,11 +2185,11 @@ const updateCompany = useUpdateCompany(); updateCompany({ plan: "enterprise" }).then(() => console.log("Flags updated")); ``` -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -2214,13 +2214,13 @@ updateCompany({ plan: "enterprise" }).then(() => console.log("Flags updated"));
-##### Returns +##### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> *** -### useUpdateOtherContext() +### useUpdateOtherContext() ```ts function useUpdateOtherContext(): (opts: {}) => Promise @@ -2239,11 +2239,11 @@ updateOtherContext({ workspaceId: newWorkspaceId }) .then(() => console.log("Flags updated")); ``` -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -2268,13 +2268,13 @@ updateOtherContext({ workspaceId: newWorkspaceId })
-##### Returns +##### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> *** -### useUpdateUser() +### useUpdateUser() ```ts function useUpdateUser(): (opts: {}) => Promise @@ -2292,11 +2292,11 @@ const updateUser = useUpdateUser(); updateUser({ optInHuddles: "true" }).then(() => console.log("Flags updated")); ``` -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -2321,6 +2321,6 @@ updateUser({ optInHuddles: "true" }).then(() => console.log("Flags updated"));
-##### Returns +##### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> diff --git a/legacy/v1/vue-sdk/README.md b/legacy/v1/vue-sdk/README.md index 54aad04..6db33c3 100644 --- a/legacy/v1/vue-sdk/README.md +++ b/legacy/v1/vue-sdk/README.md @@ -19,7 +19,7 @@ pagination: Generated from [`@reflag/vue-sdk@1.5.7`](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/vue-sdk); SDK READMEs and code comments remain the source of truth. {% endhint %} -# Reflag Vue SDK +# Reflag Vue SDK Vue client side library for [Reflag.com](https://reflag.com) @@ -27,7 +27,7 @@ Reflag supports flag toggling, tracking flag usage, requesting feedback on featu The Reflag Vue SDK comes with the same built-in toolbar as the browser SDK which appears on `localhost` by default. -## Install +## Install Install via npm: @@ -35,7 +35,7 @@ Install via npm: npm i @reflag/vue-sdk@1 ``` -## Migrating from Bucket SDK +## Migrating from Bucket SDK If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: @@ -61,9 +61,9 @@ If you are running with strict Content Security Policies active on your website, Finally, if you have customized the look & feel of the Feedback component, update `--bucket-feedback-*` CSS classes to `--reflag-feedback-*` -## Get started +## Get started -### 1. Add the `ReflagProvider` context provider +### 1. Add the `ReflagProvider` context provider Add the `ReflagProvider` context provider to your application: @@ -87,7 +87,7 @@ import { ReflagProvider } from "@reflag/vue-sdk"; If using Nuxt, wrap `` in ``. `` only renders client-side currently. -### 2. Use `useFlag get flag status +### 2. Use `useFlag get flag status ```vue ``` -## Internationalization (i18n) +## Internationalization (i18n) By default, the feedback UI is written in English. However, you can supply your own translations by passing an object in the options to either or both of the @@ -293,7 +293,7 @@ See examples below. See [default English localization keys](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) for a reference of what translation keys can be supplied. -### Static language configuration +### Static language configuration If you know the language at page load, you can configure your translation keys while initializing the Reflag Browser SDK: @@ -324,7 +324,7 @@ new ReflagClient({ }); ``` -### Runtime language configuration +### Runtime language configuration If you only know the user's language after the page has loaded, you can provide translations to either the `reflagClient.requestFeedback(options)` call or @@ -340,7 +340,7 @@ reflagClient.requestFeedback({ }) ``` -### Translations +### Translations When you are collecting feedback through the Reflag automation, you can intercept the default prompt handling and override the defaults. @@ -367,7 +367,7 @@ new ReflagClient({ }); ``` -## Custom styling +## Custom styling You can adapt parts of the look of the Reflag feedback UI by applying CSS custom properties to your page in your CSS `:root`-scope. @@ -406,7 +406,7 @@ For example, a dark mode theme might look like this: Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk/src/feedback/ui/index.css). -## Using your own UI to collect feedback +## Using your own UI to collect feedback You may have very strict design guidelines for your app and maybe the Reflag feedback UI doesn't quite work for you. In this case, you can implement your own feedback @@ -426,7 +426,7 @@ type DataToCollect = { Either `score` or `comment` must be defined in order to pass validation in the Reflag API. -### Manual feedback collection with custom UI +### Manual feedback collection with custom UI Examples of a HTML-form that collects the relevant data can be found in [feedback.html](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk/example/feedback/Feedback.jsx). @@ -442,7 +442,7 @@ reflagClient.feedback({ }); ``` -### Intercepting automated feedback survey events +### Intercepting automated feedback survey events When using automated feedback surveys, the Reflag service will, when specified, send a feedback prompt message to your user's instance of the Reflag Browser SDK. diff --git a/sdk/documents/react-native-sdk/README.md b/sdk/documents/react-native-sdk/README.md index 1634758..eba9bb0 100644 --- a/sdk/documents/react-native-sdk/README.md +++ b/sdk/documents/react-native-sdk/README.md @@ -17,7 +17,7 @@ pagination: **Independent SDK compatibility.** This React Native release uses React/Browser protocol v1. Follow the [matching React documentation](../../../legacy/v1/react-sdk/README.md) and use a [matching Node SDK](../../../legacy/v1/node-sdk/README.md) for bootstrap. Do not pass protocol-v2 bootstrap into a v1 consumer. {% endhint %} -# Reflag React Native SDK +# Reflag React Native SDK A thin React Native wrapper around `@reflag/react-sdk`. @@ -25,15 +25,15 @@ For more usage details, see the [React SDK README](../../../legacy/v1/react-sdk/ An Expo example app lives in [packages/react-native-sdk/dev/expo](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/react-native-sdk/dev/expo). -## Get started +## Get started -### Install +### Install ```shell npm i @reflag/react-native-sdk ``` -### 1. Add the ReflagProvider +### 1. Add the ReflagProvider Wrap your app with the provider from `@reflag/react-native-sdk`: @@ -51,7 +51,7 @@ import { ReflagProvider } from "@reflag/react-native-sdk"; ; ``` -### 2. Use `useFlag()` +### 2. Use `useFlag()` ```tsx import { useFlag } from "@reflag/react-native-sdk"; @@ -67,22 +67,22 @@ function StartHuddleButton() { See the [React SDK README](../../../legacy/v1/react-sdk/README.md) for more details. -## React Native differences +## React Native differences - The Reflag toolbar is web-only and is not available in React Native. - Built-in feedback UI is web-only. In React Native, use your own UI and call `useSendFeedback` or `client.feedback` when you're ready to send feedback. - Live flag updates work out of the box. The React Native SDK bundles an SSE transport via `react-native-sse`, so no global `EventSource` shim is required. - If you need custom SSE behavior, you can still override the transport by passing `eventSourceFactory` to `ReflagProvider` or `ReflagBootstrappedProvider`. -## Reference +## Reference The React Native SDK shares its API with the React SDK. Use the React SDK reference for full types and details: [React SDK Reference](../../../legacy/v1/react-sdk/README.md) -## Cookbook +## Cookbook -### Refresh flags when the app returns to the foreground +### Refresh flags when the app returns to the foreground Flags are updated if the context passed to `` changes, but you might also want to update them when the app comes to the foreground. See this snippet: @@ -123,7 +123,7 @@ export function App() { } ``` -## Suspense loading +## Suspense loading Enable `` support by setting the `suspense` prop on the provider and wrap components that call `useFlag` in a Suspense boundary: @@ -141,7 +141,7 @@ import { ReflagProvider } from "@reflag/react-native-sdk"; You can also override the behavior for one call with `useFlag("huddle", { suspense: true })`. -## Bootstrapping +## Bootstrapping You can use `` in React Native when you already have pre-fetched flags and want to avoid an initial fetch. Pass the full object returned by the Node SDK's `getFlagsForBootstrap()` directly as the provider's `flags` prop; it includes `context`, evaluated `flags`, and an optional `flagStateVersion`. diff --git a/sdk/documents/react-sdk/README.md b/sdk/documents/react-sdk/README.md index 887e436..444a7df 100644 --- a/sdk/documents/react-sdk/README.md +++ b/sdk/documents/react-sdk/README.md @@ -21,13 +21,13 @@ pagination: Generated from [`@reflag/react-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/react-sdk); SDK READMEs and code comments remain the source of truth. {% endhint %} -# Reflag React SDK v2 +# Reflag React SDK v2 Direct-value feature flags for React, backed by [Browser SDK v2](../../../supported-languages/browser-sdk/README.md). > Breaking prerelease: requires compatible v2 server endpoints and **Node SDK v2** for bootstrap. The v2 CLI generates direct-value declarations; regenerate legacy wrapper-shaped output when migrating. Useful default-based inference does not require generated declarations. React Native remains on published React/Browser v1 in this repository. -## Setup +## Setup ```tsx import { ReflagProvider } from "@reflag/react-sdk"; @@ -45,7 +45,7 @@ import { ReflagProvider } from "@reflag/react-sdk"; Provider options forward Browser SDK settings, including `logger`, `debug`, `enableTracking`, `offline`, cache/fallback options, `toolbar`, `feedback`, `credentials` and API origins. A custom logger takes precedence over debug logging. Live updates default to true; set `enableLiveFlagUpdates={false}` to disable them. -## `useFlag(key, defaultValue?)` +## `useFlag(key, defaultValue?)` ```tsx import { useFlag, useTrack } from "@reflag/react-sdk"; @@ -76,7 +76,7 @@ Non-null defaults enforce only the top-level JSON category (Boolean/number/strin `useFlag` never suspends. Its second argument is **payload data**, not `{ suspense: ... }` options; ordinary JSON has no reserved keys. Use the dedicated hook below for suspension. Use `useIsLoading()` or the provider's `loadingComponent` when you need an explicit loading UI. -## `useFlagSuspense(key, defaultValue?)` +## `useFlagSuspense(key, defaultValue?)` ```tsx import { Suspense } from "react"; @@ -96,7 +96,7 @@ This hook has the same Boolean/default-based return types. It waits for initiali The provider's existing `suspense` prop continues to configure **`useOptInFlags` only**. It does not change `useFlag`; `useFlagSuspense` is explicit. -## Checks and usage tracking +## Checks and usage tracking A completed getter/hook read registers its requested-root check immediately, even if the value is ignored. Actual delivery remains buffered and identity-aware rate-limited by the Browser SDK. Checks contain selected variant/source/snapshot identity, not payloads. Defaults, category mismatches and local overrides never invent authored selections. Diagnostic/bootstrap inspection registers no checks. @@ -113,7 +113,7 @@ await sendFeedback({ flagKey: "huddles", score: 5 }); See [Browser feedback documentation](../../../supported-languages/browser-sdk/feedback.md) for UI/prompt configuration. -## Optional key registration +## Optional key registration ```ts import "@reflag/react-sdk"; @@ -127,7 +127,7 @@ declare module "@reflag/react-sdk" { Registration constrains keys and checks non-null defaults against the registered value schema, including required and nested properties. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request; bare/`undefined` reads remain Boolean. The positional default still determines the widened return type, and generated declarations do not add nested runtime validation. The same rules apply to `useFlagSuspense`. The v2 CLI generates direct-value declarations from current production-environment variants; regenerate legacy wrapper declarations when migrating. -## Bootstrap and SSR +## Bootstrap and SSR On the server, use Node SDK v2: @@ -149,7 +149,7 @@ The envelope includes `protocolVersion: 2`, context, evaluated flag results and For a pre-existing Browser v2 client, use ``. The provider does not own its lifecycle; initialize/stop externally, except that a suspending read can start on-demand initialization. -## Context, loading and events +## Context, loading and events - `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return async shallow-update functions. `useClient().setContext(context)` replaces the whole context. - Context changes clear old-context values while fetching. Stale/in-flight responses cannot replace a newer context/snapshot. @@ -157,7 +157,7 @@ For a pre-existing Browser v2 client, use ` ```tsx const { flags, isLoading } = useOptInFlags(); @@ -170,6 +170,6 @@ Metadata arrives with the initial v2 evaluation for regular providers. Bootstrap `useOptInFlags({ suspense: true | false })` retains its own per-hook loading options and may inherit provider `suspense`. These options are unrelated to the positional payload defaults used by `useFlag` / `useFlagSuspense`. -## Migration from v1 +## Migration from v1 Use `const enabled = useFlag(key)` instead of destructuring `.isEnabled`. Replace wrapper config access with an authored multivariate flag and positional default. Move `.track()` and `.requestFeedback()` to separate hooks. Replace `useFlag(key, { suspense: true })` with `useFlagSuspense(key)`, and use `useIsLoading()` instead of a flag wrapper's loading property. Upgrade Browser/server bootstrap together. Nothing here publishes the prerelease or deploys its required server changes. diff --git a/supported-languages/browser-sdk/README.md b/supported-languages/browser-sdk/README.md index 610e2ed..921e2b8 100644 --- a/supported-languages/browser-sdk/README.md +++ b/supported-languages/browser-sdk/README.md @@ -21,13 +21,13 @@ pagination: Generated from [`@reflag/browser-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk); SDK READMEs and code comments remain the source of truth. {% endhint %} -# Reflag Browser SDK v2 +# Reflag Browser SDK v2 Client-side feature flags and JSON values for [Reflag](https://reflag.com). > This is a breaking v2 prerelease. It requires the v2 evaluated-flags/check protocol on the server. Do not switch existing v1 applications or bootstrap consumers without coordinating that upgrade. Nothing in this branch publishes or deploys the SDK/server. -## Get started +## Get started ```ts import { ReflagClient } from "@reflag/browser-sdk"; @@ -51,7 +51,7 @@ if (enabled) { Use only a **publishable** key in a browser. Secret keys belong on your server. -## Direct-value reads +## Direct-value reads ```ts reflag.getFlag("release"); // boolean; missing/mismatched -> false @@ -70,7 +70,7 @@ reflag.getFlag("nullable-settings", null); // FlagValue (arbitrary JSON) `getFlags()` returns a direct-value record (entries may be undefined) and registers checks for its returned roots. `getFlagResults()` returns owned evaluated diagnostics **without checks**; it is intended for tooling, not ordinary application reads. `getFlagsForBootstrap()` serializes protocol-v2 evaluated state without checks. -## Checks and delivery +## Checks and delivery Calling a getter registers a requested-root check immediately, even if its return value is ignored. There are no `.isEnabled`, `.config`, `.value` or flag `.track()` wrappers. Delivery remains buffered through `/bulk` and identity-aware rate-limited. @@ -78,7 +78,7 @@ A selected check carries the authored selected key as `evalResult`, its `sourceV `enableTracking: false` disables checks and user/company/usage tracking. `offline: true` skips HTTP and tracking. `await reflag.stop()` flushes buffered events and closes the client's background transports. -## Context, refresh and cache +## Context, refresh and cache ```ts await reflag.updateUser({ role: "admin" }); @@ -114,7 +114,7 @@ Constructor options include: Evaluated cache and override storage use isolated v2 keys. V1 cache entries are never interpreted as v2 values. Malformed refreshes leave known-good state intact. Valid saved v2 selections retain their real provenance on restore. There is no automatic periodic HTTP fallback after an SSE failure; manual refresh/context updates remain available. -## Overrides and toolbar +## Overrides and toolbar ```ts reflag.setFlagOverride("release", true); @@ -125,7 +125,7 @@ reflag.setFlagOverride("release", undefined); // clear the override Overrides apply after server evaluation and do not rewrite authored dependency results. The built-in toolbar appears on localhost by default and offers Boolean overrides only. It uses diagnostic access, so opening it does not register application checks. -## Server bootstrap +## Server bootstrap Generate the full payload with **Node SDK v2** on your server: @@ -142,7 +142,7 @@ const enabled = reflag.getFlag("release"); The payload includes `protocolVersion: 2`, context, evaluated diagnostics/selections and an optional snapshot version. V1 payloads and the old `bootstrappedFlags` option are rejected. Preserve the entire envelope; do not pass just its `flags` property. A version is required for bootstrapped live updates. Never embed secrets or server-only context in public bootstrap data. Later refreshes use browser-visible context and can differ from server-only evaluation; disable live updates when that is inappropriate. -## End-user opt-in +## End-user opt-in ```ts const options = reflag.getOptInFlags(); @@ -155,13 +155,13 @@ The list contains presentation/membership metadata (`key`, `name`, `description` Metadata arrives with ordinary `/flags/evaluated` responses and is cached with the evaluated snapshot. Bootstrapped clients whose snapshot lacks metadata fetch it on demand from the same v2 endpoint, without replacing server-derived values or provenance with browser-context evaluations. Loading settles on success or failure, including an empty list. Opt-in mutations confirm values and membership together in one versioned refresh. `optInFlagsLoadingUpdated` and `flagsUpdated` support UI subscriptions. -## Tracking, feedback and events +## Tracking, feedback and events Use `track(eventName, attributes?)`, `feedback(payload)` and `requestFeedback({ flagKey, ... })` on the client. See [FEEDBACK.md](feedback.md) for the feedback UI and prompting configuration. `on(event, handler)` returns an unsubscribe function. Events include `stateUpdated`, `flagsUpdated` (evaluated diagnostics), `check`, `track`, `user`, `company` and `optInFlagsLoadingUpdated`. -## Migration from v1 +## Migration from v1 - Replace `getFlag(key).isEnabled` with `getFlag(key)`. - Replace legacy remote config access with a separately authored multivariate flag and a positional default. Legacy config is **not** automatically converted into v2 values. diff --git a/supported-languages/browser-sdk/feedback.md b/supported-languages/browser-sdk/feedback.md index 9b36823..6eb8ceb 100644 --- a/supported-languages/browser-sdk/feedback.md +++ b/supported-languages/browser-sdk/feedback.md @@ -21,14 +21,14 @@ pagination: Generated from [`@reflag/browser-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk); SDK READMEs and code comments remain the source of truth. {% endhint %} -# Reflag Feedback UI +# Reflag Feedback UI The Reflag Browser SDK includes a UI you can use to collect feedback from user about particular flags. ![image](https://github.com/reflagcom/javascript/assets/34348/c387bac1-f2e2-4efd-9dda-5030d76f9532) -## Global feedback configuration +## Global feedback configuration The Reflag Browser SDK feedback UI is configured with reasonable defaults, positioning itself as a [dialog](#dialog) in the lower right-hand corner of @@ -66,7 +66,7 @@ See also: - [Static language configuration](#static-language-configuration) if you want to translate the feedback UI, - [Automated feedback surveys](#automated-feedback-surveys) to override default configuration. -## Automated feedback surveys +## Automated feedback surveys Automated feedback surveys are enabled by default. @@ -80,7 +80,7 @@ browser, but you can intercept the request and override this behavior. The live connection for automated feedback is established when the `ReflagClient` is initialized. -### Disabling automated feedback surveys +### Disabling automated feedback surveys You can disable automated collection in the `ReflagClient` constructor: @@ -94,7 +94,7 @@ const reflag = new ReflagClient({ }); ``` -### Overriding prompt event defaults +### Overriding prompt event defaults If you are not satisfied with the default UI behavior when an automated prompt event arrives, you can can [override the global defaults](#global-feedback-configuration) @@ -135,7 +135,7 @@ See also: - [Use your own UI to collect feedback](#using-your-own-ui-to-collect-feedback) if the feedback UI doesn't match your design. -## Manual feedback collection +## Manual feedback collection To open up the feedback collection UI, call `reflagClient.requestFeedback(options)` with the appropriate options. This approach is particularly beneficial if you wish @@ -147,7 +147,7 @@ Examples of this could be if you want the click of a `give us feedback`-button or the end of a specific user flow, to trigger a pop-up displaying the feedback user interface. -### reflagClient.requestFeedback() options +### reflagClient.requestFeedback() options Minimal usage with defaults: @@ -188,13 +188,13 @@ See also: - [Runtime language configuration](#runtime-language-configuration) if you want to translate the feedback UI. -## Positioning and behavior +## Positioning and behavior The feedback UI can be configured to be placed and behave in 3 different ways: -### Positioning configuration +### Positioning configuration -#### Modal +#### Modal A modal overlay with a backdrop that blocks interaction with the underlying page. It can be dismissed with the keyboard shortcut `` or the dedicated @@ -214,7 +214,7 @@ position: { } ``` -#### Dialog +#### Dialog A dialog that appears in a specified corner of the viewport, without limiting the user's interaction with the rest of the page. It can be dismissed with the dedicated @@ -244,7 +244,7 @@ position: { } ``` -#### Popover +#### Popover A popover that is anchored relative to a DOM-element (typically a button). It can be dismissed by clicking outside the popover or by pressing the dedicated close button. @@ -280,7 +280,7 @@ Popover feedback button example: ``` -## Internationalization (i18n) +## Internationalization (i18n) By default, the feedback UI is written in English. However, you can supply your own translations by passing an object in the options to either or both of the @@ -293,7 +293,7 @@ See examples below. See [default English localization keys](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) for a reference of what translation keys can be supplied. -### Static language configuration +### Static language configuration If you know the language at page load, you can configure your translation keys while initializing the Reflag Browser SDK: @@ -324,7 +324,7 @@ new ReflagClient({ }); ``` -### Runtime language configuration +### Runtime language configuration If you only know the user's language after the page has loaded, you can provide translations to either the `reflagClient.requestFeedback(options)` call or @@ -340,7 +340,7 @@ reflagClient.requestFeedback({ }) ``` -### Translations +### Translations When you are collecting feedback through the Reflag automation, you can intercept the default prompt handling and override the defaults. @@ -367,7 +367,7 @@ new ReflagClient({ }); ``` -## Custom styling +## Custom styling You can adapt parts of the look of the Reflag feedback UI by applying CSS custom properties to your page in your CSS `:root`-scope. @@ -406,7 +406,7 @@ For example, a dark mode theme might look like this: Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk/src/feedback/ui/index.css). -## Using your own UI to collect feedback +## Using your own UI to collect feedback You may have very strict design guidelines for your app and maybe the Reflag feedback UI doesn't quite work for you. In this case, you can implement your own feedback @@ -426,7 +426,7 @@ type DataToCollect = { Either `score` or `comment` must be defined in order to pass validation in the Reflag API. -### Manual feedback collection with custom UI +### Manual feedback collection with custom UI Examples of a HTML-form that collects the relevant data can be found in [feedback.html](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk/example/feedback/Feedback.jsx). @@ -442,7 +442,7 @@ reflagClient.feedback({ }); ``` -### Intercepting automated feedback survey events +### Intercepting automated feedback survey events When using automated feedback surveys, the Reflag service will, when specified, send a feedback prompt message to your user's instance of the Reflag Browser SDK. diff --git a/supported-languages/browser-sdk/globals.md b/supported-languages/browser-sdk/globals.md index c82d836..9b1aa65 100644 --- a/supported-languages/browser-sdk/globals.md +++ b/supported-languages/browser-sdk/globals.md @@ -21,17 +21,17 @@ pagination: Generated from [`@reflag/browser-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk); SDK READMEs and code comments remain the source of truth. {% endhint %} -# @reflag/browser-sdk +# @reflag/browser-sdk -## Classes +## Classes -### ReflagClient +### ReflagClient ReflagClient lets you interact with the Reflag API. -#### Constructors +#### Constructors -##### new ReflagClient() +##### new ReflagClient() ```ts new ReflagClient(opts: InitOptions): ReflagClient @@ -39,7 +39,7 @@ new ReflagClient(opts: InitOptions): ReflagClient Create a new ReflagClient instance. -###### Parameters +###### Parameters @@ -64,11 +64,11 @@ Create a new ReflagClient instance.
-###### Returns +###### Returns [`ReflagClient`](globals.md#reflagclient) -#### Properties +#### Properties @@ -99,15 +99,15 @@ Create a new ReflagClient instance.
-#### Methods +#### Methods -##### applyBootstrappedState() +##### applyBootstrappedState() ```ts applyBootstrappedState(bootstrappedState: BootstrappedState, triggerEvent: boolean): void ``` -###### Parameters +###### Parameters @@ -155,11 +155,11 @@ applyBootstrappedState(bootstrappedState: BootstrappedState, triggerEvent: boole
-###### Returns +###### Returns `void` -##### feedback() +##### feedback() ```ts feedback(payload: Feedback): Promise< @@ -169,7 +169,7 @@ feedback(payload: Feedback): Promise< Submit user feedback to Reflag. Must include either `score` or `comment`, or both. -###### Parameters +###### Parameters @@ -200,7 +200,7 @@ The feedback details to submit.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` @@ -208,7 +208,7 @@ The feedback details to submit. The server response. -##### getConfig() +##### getConfig() ```ts getConfig(): Config @@ -216,11 +216,11 @@ getConfig(): Config Get the current configuration. -###### Returns +###### Returns [`Config`](globals.md#config) -##### getContext() +##### getContext() ```ts getContext(): ReflagContext @@ -228,27 +228,27 @@ getContext(): ReflagContext Get the current context. -###### Returns +###### Returns [`ReflagContext`](globals.md#reflagcontext) -##### ~~getFeatures()~~ +##### ~~getFeatures()~~ ```ts getFeatures(): Record ``` -###### Returns +###### Returns [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `undefined` \| [`FlagValue`](globals.md#flagvalue)\> -###### Deprecated +###### Deprecated Use `getFlags` instead. -##### getFlag() +##### getFlag() -###### Call Signature +###### Call Signature ```ts getFlag(key: string, defaultValue?: undefined): boolean @@ -256,7 +256,7 @@ getFlag(key: string, defaultValue?: undefined): boolean Boolean-first reads; positional defaults select other top-level JSON categories. -###### Parameters +###### Parameters @@ -293,11 +293,11 @@ Boolean-first reads; positional defaults select other top-level JSON categories.
-###### Returns +###### Returns `boolean` -###### Call Signature +###### Call Signature ```ts getFlag(key: string, defaultValue: Default): FlagValueFromDefault @@ -305,7 +305,7 @@ getFlag(key: string, defaultValue: Default): FlagValueFromDefault @@ -324,7 +324,7 @@ Boolean-first reads; positional defaults select other top-level JSON categories.
-###### Parameters +###### Parameters @@ -361,17 +361,17 @@ Boolean-first reads; positional defaults select other top-level JSON categories.
-###### Returns +###### Returns [`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> -##### getFlagOverride() +##### getFlagOverride() ```ts getFlagOverride(key: string): undefined | FlagValue ``` -###### Parameters +###### Parameters @@ -396,11 +396,11 @@ getFlagOverride(key: string): undefined | FlagValue
-###### Returns +###### Returns `undefined` \| [`FlagValue`](globals.md#flagvalue) -##### getFlagResults() +##### getFlagResults() ```ts getFlagResults(): RawFlags @@ -408,11 +408,11 @@ getFlagResults(): RawFlags Owned evaluated diagnostics; inspecting these is not an application read. -###### Returns +###### Returns [`RawFlags`](globals.md#rawflags) -##### getFlags() +##### getFlags() ```ts getFlags(): Record @@ -421,21 +421,21 @@ getFlags(): Record Return direct values and register checks for these returned roots. Use getFlagResults() for diagnostic/serialization access without checks. -###### Returns +###### Returns [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `undefined` \| [`FlagValue`](globals.md#flagvalue)\> -##### getFlagsForBootstrap() +##### getFlagsForBootstrap() ```ts getFlagsForBootstrap(): BootstrappedState ``` -###### Returns +###### Returns [`BootstrappedState`](globals.md#bootstrappedstate) -##### getIsLoadingOptInFlags() +##### getIsLoadingOptInFlags() ```ts getIsLoadingOptInFlags(): boolean @@ -445,11 +445,11 @@ Returns whether opt-in flags are loading for the current context. Calling this method requests opt-in metadata if it is not already available. -###### Returns +###### Returns `boolean` -##### getOptInFlags() +##### getOptInFlags() ```ts getOptInFlags(): OptInFlag[] @@ -457,21 +457,21 @@ getOptInFlags(): OptInFlag[] Returns opt-in-enabled flags for the current context. -###### Returns +###### Returns [`OptInFlag`](globals.md#optinflag)[] -##### getState() +##### getState() ```ts getState(): State ``` -###### Returns +###### Returns [`State`](globals.md#state) -##### initialize() +##### initialize() ```ts initialize(): Promise @@ -481,11 +481,11 @@ Initialize the Reflag SDK. Must be called before calling other SDK methods. -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### off() +##### off() ```ts off(type: THookType, handler: (args0: HookArgs[THookType]) => void): void @@ -493,7 +493,7 @@ off(type: THookType, handler: (args0: HookArgs[THookType]) => void): Remove an event listener -###### Type Parameters +###### Type Parameters @@ -512,7 +512,7 @@ Remove an event listener
-###### Parameters +###### Parameters @@ -560,13 +560,13 @@ The same function that was passed to `on`.
-###### Returns +###### Returns `void` A function to remove the hook. -##### on() +##### on() ```ts on(type: THookType, handler: (args0: HookArgs[THookType]) => void): () => void @@ -574,7 +574,7 @@ on(type: THookType, handler: (args0: HookArgs[THookType]) => void): ( Add an event listener -###### Type Parameters +###### Type Parameters @@ -593,7 +593,7 @@ Add an event listener
-###### Parameters +###### Parameters @@ -641,17 +641,17 @@ The function to call when the event is triggered.
-###### Returns +###### Returns `Function` A function to remove the hook. -###### Returns +###### Returns `void` -##### refresh() +##### refresh() ```ts refresh(): Promise @@ -659,11 +659,11 @@ refresh(): Promise Force refresh flags from the API, bypassing cache. -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`undefined` \| [`RawFlags`](globals.md#rawflags)\> -##### requestFeedback() +##### requestFeedback() ```ts requestFeedback(options: RequestFeedbackData): void @@ -673,7 +673,7 @@ Display the Reflag feedback form UI programmatically. This can be used to collect feedback from users in Reflag in cases where Automated Feedback Surveys isn't appropriate. -###### Parameters +###### Parameters @@ -698,11 +698,11 @@ This can be used to collect feedback from users in Reflag in cases where Automat
-###### Returns +###### Returns `void` -##### setContext() +##### setContext() ```ts setContext(context: ReflagDeprecatedContext): Promise @@ -711,7 +711,7 @@ setContext(context: ReflagDeprecatedContext): Promise Update the context. Replaces the existing context with a new context. -###### Parameters +###### Parameters @@ -742,11 +742,11 @@ The context to update.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### setFlagOverride() +##### setFlagOverride() ```ts setFlagOverride(key: string, value: undefined | FlagValue): void @@ -754,7 +754,7 @@ setFlagOverride(key: string, value: undefined | FlagValue): void Overrides are applied after server evaluation and never invent selections. -###### Parameters +###### Parameters @@ -791,11 +791,11 @@ Overrides are applied after server evaluation and never invent selections.
-###### Returns +###### Returns `void` -##### setOptIn() +##### setOptIn() ```ts setOptIn(flagKey: string, options: SetOptInOptions): Promise< @@ -805,7 +805,7 @@ setOptIn(flagKey: string, options: SetOptInOptions): Promise< Set whether the current user or company has opted into a flag. -###### Parameters +###### Parameters @@ -842,19 +842,19 @@ Set whether the current user or company has opted into a flag.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> -##### showToolbarToggle() +##### showToolbarToggle() ```ts showToolbarToggle(position?: ToolbarPosition): void ``` -###### Parameters +###### Parameters @@ -879,11 +879,11 @@ showToolbarToggle(position?: ToolbarPosition): void
-###### Returns +###### Returns `void` -##### stop() +##### stop() ```ts stop(): Promise @@ -892,11 +892,11 @@ stop(): Promise Stop the SDK. This will stop any automated feedback surveys. -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### track() +##### track() ```ts track(eventName: string, attributes?: @@ -908,7 +908,7 @@ track(eventName: string, attributes?: Track an event in Reflag. -###### Parameters +###### Parameters @@ -956,13 +956,13 @@ Any attributes you want to attach to the event.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> -##### updateCompany() +##### updateCompany() ```ts updateCompany(company: {}): Promise @@ -972,7 +972,7 @@ Update the company context. Performs a shallow merge with the existing company context. It will not update the context if nothing has changed. -###### Parameters +###### Parameters @@ -1003,11 +1003,11 @@ The company details.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### updateFlags() +##### updateFlags() ```ts updateFlags( @@ -1018,7 +1018,7 @@ updateFlags( Update the flags. -###### Parameters +###### Parameters @@ -1099,11 +1099,11 @@ Whether to trigger the `flagsUpdated` event.
-###### Returns +###### Returns `void` -##### updateOtherContext() +##### updateOtherContext() ```ts updateOtherContext(otherContext: {}): Promise @@ -1113,7 +1113,7 @@ Update the company context. Performs a shallow merge with the existing company context. It will not update the context if nothing has changed. -###### Parameters +###### Parameters @@ -1144,11 +1144,11 @@ Additional context.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### updateUser() +##### updateUser() ```ts updateUser(user: {}): Promise @@ -1158,7 +1158,7 @@ Update the user context. Performs a shallow merge with the existing user context. It will not update the context if nothing has changed. -###### Parameters +###### Parameters @@ -1183,17 +1183,17 @@ It will not update the context if nothing has changed.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -## Interfaces +## Interfaces -### CheckEvent +### CheckEvent A root read records selection identity, never its JSON payload. -#### Properties +#### Properties @@ -1316,19 +1316,19 @@ A root read records selection identity, never its JSON payload. *** -### CompanyContext +### CompanyContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing company. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties
@@ -1378,11 +1378,11 @@ Company name *** -### Config +### Config ReflagClient configuration. -#### Properties +#### Properties
@@ -1501,9 +1501,9 @@ Defaults to `apiBaseUrl`. *** -### FeedbackScoreSubmission +### FeedbackScoreSubmission -#### Properties +#### Properties
@@ -1554,9 +1554,9 @@ Defaults to `apiBaseUrl`. *** -### FeedbackSubmission +### FeedbackSubmission -#### Properties +#### Properties
@@ -1619,9 +1619,9 @@ Defaults to `apiBaseUrl`. *** -### HookArgs +### HookArgs -#### Properties +#### Properties
@@ -1775,17 +1775,17 @@ Use `flagsUpdated` instead. *** -### Logger +### Logger -#### Methods +#### Methods -##### debug() +##### debug() ```ts debug(message: string, ...args: any[]): void ``` -###### Parameters +###### Parameters
@@ -1822,17 +1822,17 @@ debug(message: string, ...args: any[]): void
-###### Returns +###### Returns `void` -##### error() +##### error() ```ts error(message: string, ...args: any[]): void ``` -###### Parameters +###### Parameters @@ -1869,17 +1869,17 @@ error(message: string, ...args: any[]): void
-###### Returns +###### Returns `void` -##### info() +##### info() ```ts info(message: string, ...args: any[]): void ``` -###### Parameters +###### Parameters @@ -1916,17 +1916,17 @@ info(message: string, ...args: any[]): void
-###### Returns +###### Returns `void` -##### warn() +##### warn() ```ts warn(message: string, ...args: any[]): void ``` -###### Parameters +###### Parameters @@ -1963,15 +1963,15 @@ warn(message: string, ...args: any[]): void
-###### Returns +###### Returns `void` *** -### OnScoreSubmitResult +### OnScoreSubmitResult -#### Properties +#### Properties @@ -1998,9 +1998,9 @@ warn(message: string, ...args: any[]): void *** -### OpenFeedbackFormOptions +### OpenFeedbackFormOptions -#### Properties +#### Properties
@@ -2171,16 +2171,16 @@ Undefined translation keys fall back to english defaults. *** -### ReflagContext +### ReflagContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. -#### Extended by +#### Extended by - [`ReflagDeprecatedContext`](globals.md#reflagdeprecatedcontext) -#### Properties +#### Properties
@@ -2249,19 +2249,19 @@ user attributes on Reflag servers. *** -### ~~ReflagDeprecatedContext~~ +### ~~ReflagDeprecatedContext~~ **`Internal`** -#### Deprecated +#### Deprecated Use `ReflagContext` instead, this interface will be removed in the next major version -#### Extends +#### Extends - [`ReflagContext`](globals.md#reflagcontext) -#### Properties +#### Properties
@@ -2351,9 +2351,9 @@ user attributes on Reflag servers. *** -### ToolbarPosition +### ToolbarPosition -#### Properties +#### Properties
@@ -2392,19 +2392,19 @@ user attributes on Reflag servers. *** -### UserContext +### UserContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing user. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties
@@ -2469,9 +2469,9 @@ User name
-## Type Aliases +## Type Aliases -### BootstrappedState +### BootstrappedState ```ts type BootstrappedState = { @@ -2484,7 +2484,7 @@ type BootstrappedState = { Pre-fetched evaluated state used to bootstrap the client. -#### Type declaration +#### Type declaration @@ -2547,7 +2547,7 @@ Pre-fetched evaluated state used to bootstrap the client. *** -### ContextValue +### ContextValue ```ts type ContextValue = DefinedContextValue | undefined; @@ -2557,7 +2557,7 @@ A context value. Object properties set to `undefined` are omitted. *** -### DefinedContextValue +### DefinedContextValue ```ts type DefinedContextValue = @@ -2573,7 +2573,7 @@ A JSON-compatible context value that is not `undefined`. *** -### DialogPlacement +### DialogPlacement ```ts type DialogPlacement = "bottom-right" | "bottom-left" | "top-right" | "top-left"; @@ -2581,7 +2581,7 @@ type DialogPlacement = "bottom-right" | "bottom-left" | "top-right" | "top-left" *** -### EvaluationError +### EvaluationError ```ts type EvaluationError = { @@ -2596,7 +2596,7 @@ type EvaluationError = { }; ``` -#### Type declaration +#### Type declaration
@@ -2698,13 +2698,13 @@ type EvaluationError = { *** -### EventSourceFactory() +### EventSourceFactory() ```ts type EventSourceFactory = (url: string) => EventSourceLike; ``` -#### Parameters +#### Parameters
@@ -2729,13 +2729,13 @@ type EventSourceFactory = (url: string) => EventSourceLike;
-#### Returns +#### Returns [`EventSourceLike`](globals.md#eventsourcelike) *** -### EventSourceLike +### EventSourceLike ```ts type EventSourceLike = { @@ -2744,7 +2744,7 @@ type EventSourceLike = { }; ``` -#### Type declaration +#### Type declaration @@ -2783,7 +2783,7 @@ type EventSourceLike = { *** -### FallbackFlagOverride +### FallbackFlagOverride ```ts type FallbackFlagOverride = FlagValue; @@ -2791,7 +2791,7 @@ type FallbackFlagOverride = FlagValue; *** -### Feedback +### Feedback ```ts type Feedback = UnassignedFeedback & { @@ -2800,7 +2800,7 @@ type Feedback = UnassignedFeedback & { }; ``` -#### Type declaration +#### Type declaration
@@ -2850,7 +2850,7 @@ User ID from your own application. *** -### FeedbackOptions +### FeedbackOptions ```ts type FeedbackOptions = { @@ -2863,7 +2863,7 @@ type FeedbackOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -2968,7 +2968,7 @@ Undefined translation keys fall back to english defaults. *** -### FeedbackPrompt +### FeedbackPrompt ```ts type FeedbackPrompt = { @@ -2980,7 +2980,7 @@ type FeedbackPrompt = { }; ``` -#### Type declaration +#### Type declaration
@@ -3081,13 +3081,13 @@ Feedback prompt will not be shown after this time *** -### FeedbackPromptHandler() +### FeedbackPromptHandler() ```ts type FeedbackPromptHandler = (prompt: FeedbackPrompt, handlers: FeedbackPromptHandlerCallbacks) => void; ``` -#### Parameters +#### Parameters
@@ -3124,13 +3124,13 @@ type FeedbackPromptHandler = (prompt: FeedbackPrompt, handlers: FeedbackPromptHa
-#### Returns +#### Returns `void` *** -### FeedbackPromptHandlerCallbacks +### FeedbackPromptHandlerCallbacks ```ts type FeedbackPromptHandlerCallbacks = { @@ -3139,7 +3139,7 @@ type FeedbackPromptHandlerCallbacks = { }; ``` -#### Type declaration +#### Type declaration @@ -3178,7 +3178,7 @@ type FeedbackPromptHandlerCallbacks = { *** -### FeedbackPromptHandlerOpenFeedbackFormOptions +### FeedbackPromptHandlerOpenFeedbackFormOptions ```ts type FeedbackPromptHandlerOpenFeedbackFormOptions = Omit ```ts type FeedbackPromptReply = { @@ -3203,7 +3203,7 @@ type FeedbackPromptReply = { }; ``` -#### Type declaration +#### Type declaration
@@ -3266,7 +3266,7 @@ type FeedbackPromptReply = { *** -### FeedbackPromptReplyHandler() +### FeedbackPromptReplyHandler() ```ts type FeedbackPromptReplyHandler = (reply: T) => T extends null ? Promise : Promise<{ @@ -3274,7 +3274,7 @@ type FeedbackPromptReplyHandler = (reply: T) => T extends null ? Promise; ``` -#### Type Parameters +#### Type Parameters
@@ -3293,7 +3293,7 @@ type FeedbackPromptReplyHandler = (reply: T) => T extends null ? Promise
-#### Parameters +#### Parameters @@ -3318,7 +3318,7 @@ type FeedbackPromptReplyHandler = (reply: T) => T extends null ? Promise
-#### Returns +#### Returns `T` *extends* `null` ? [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> : [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<\{ `feedbackId`: `string`; @@ -3326,7 +3326,7 @@ type FeedbackPromptReplyHandler = (reply: T) => T extends null ? Promise ```ts type FeedbackTranslations = { @@ -3348,7 +3348,7 @@ type FeedbackTranslations = { You can use this to override text values in the feedback form with desired language translation -#### Type declaration +#### Type declaration @@ -3507,7 +3507,7 @@ with desired language translation *** -### FlagDefaultFor\ +### FlagDefaultFor\ ```ts type FlagDefaultFor = keyof Registry extends never ? FlagDefaultValue | object : Key extends keyof Registry ? ReadonlyFlagValue | null : never; @@ -3515,7 +3515,7 @@ type FlagDefaultFor = keyof Registry extends never ? FlagDefaultV Registered defaults match the value schema; null explicitly requests arbitrary JSON. -#### Type Parameters +#### Type Parameters
@@ -3543,7 +3543,7 @@ Registered defaults match the value schema; null explicitly requests arbitrary J *** -### FlagDefaultValue +### FlagDefaultValue ```ts type FlagDefaultValue = @@ -3557,7 +3557,7 @@ type FlagDefaultValue = *** -### FlagOverrides +### FlagOverrides ```ts type FlagOverrides = Record; @@ -3565,7 +3565,7 @@ type FlagOverrides = Record; *** -### FlagValue +### FlagValue ```ts type FlagValue = @@ -3579,7 +3579,7 @@ type FlagValue = *** -### FlagValueFromDefault\ +### FlagValueFromDefault\ ```ts type FlagValueFromDefault = T extends null ? FlagValue : T extends boolean ? boolean : T extends number ? number : T extends string ? string : T extends readonly infer Element[] ? [Element] extends [never] ? FlagValue[] : FlagValueFromDefault[] : T extends object ? { -readonly [Key in keyof T]: FlagValueFromDefault } : never; @@ -3587,7 +3587,7 @@ type FlagValueFromDefault = T extends null ? FlagValue : T extends boolean ? Widen literals and return mutable copies. Null requests arbitrary JSON. -#### Type Parameters +#### Type Parameters
@@ -3608,7 +3608,7 @@ Widen literals and return mutable copies. Null requests arbitrary JSON. *** -### FlagValues +### FlagValues ```ts type FlagValues = Record; @@ -3616,7 +3616,7 @@ type FlagValues = Record; *** -### InitOptions +### InitOptions ```ts type InitOptions = ReflagDeprecatedContext & { @@ -3652,7 +3652,7 @@ type InitOptions = ReflagDeprecatedContext & { ReflagClient initialization options. -#### Type declaration +#### Type declaration
@@ -4129,7 +4129,7 @@ Deprecated: retries are no longer performed for bulk delivery. *** -### Offset +### Offset ```ts type Offset = { @@ -4138,7 +4138,7 @@ type Offset = { }; ``` -#### Type declaration +#### Type declaration
@@ -4188,7 +4188,7 @@ Offset from the nearest vertical screen edge after placement is resolved *** -### OptInFlag +### OptInFlag ```ts type OptInFlag = RawFlagOptIn & { @@ -4197,7 +4197,7 @@ type OptInFlag = RawFlagOptIn & { }; ``` -#### Type declaration +#### Type declaration
@@ -4247,7 +4247,7 @@ Flag key. *** -### PopoverPlacement +### PopoverPlacement ```ts type PopoverPlacement = Placement; @@ -4255,7 +4255,7 @@ type PopoverPlacement = Placement; *** -### Position +### Position ```ts type Position = @@ -4276,7 +4276,7 @@ type Position = *** -### RawFlag +### RawFlag ```ts type RawFlag = { @@ -4295,7 +4295,7 @@ type RawFlag = { Evaluated diagnostics for v2 transport/bootstrap, not a flag wrapper. -#### Type declaration +#### Type declaration
@@ -4481,7 +4481,7 @@ Absent in Node bootstrap/older snapshots; null optIn means unavailable. *** -### RawFlagOptIn +### RawFlagOptIn ```ts type RawFlagOptIn = { @@ -4493,7 +4493,7 @@ type RawFlagOptIn = { }; ``` -#### Type declaration +#### Type declaration
@@ -4594,7 +4594,7 @@ Whether the current user has opted into the flag. *** -### RawFlags +### RawFlags ```ts type RawFlags = Record; @@ -4602,7 +4602,7 @@ type RawFlags = Record; *** -### RequestFeedbackData +### RequestFeedbackData ```ts type RequestFeedbackData = Omit & { @@ -4612,7 +4612,7 @@ type RequestFeedbackData = Omit & { }; ``` -#### Type declaration +#### Type declaration
@@ -4683,7 +4683,7 @@ copy of the feedback in your own application or CRM. *** -### RequestFeedbackOptions +### RequestFeedbackOptions ```ts type RequestFeedbackOptions = RequestFeedbackData & { @@ -4691,7 +4691,7 @@ type RequestFeedbackOptions = RequestFeedbackData & { }; ``` -#### Type declaration +#### Type declaration
@@ -4724,7 +4724,7 @@ User ID from your own application. *** -### RuleEvaluationResult +### RuleEvaluationResult ```ts type RuleEvaluationResult = { @@ -4741,7 +4741,7 @@ type RuleEvaluationResult = { }; ``` -#### Type declaration +#### Type declaration
@@ -4810,7 +4810,7 @@ type RuleEvaluationResult = { *** -### SetOptInOptions +### SetOptInOptions ```ts type SetOptInOptions = { @@ -4821,7 +4821,7 @@ type SetOptInOptions = { Represents a flag. -#### Type declaration +#### Type declaration
@@ -4871,7 +4871,7 @@ Whether to update the current user or current company. Defaults to `user`. *** -### State +### State ```ts type State = "idle" | "initializing" | "initialized" | "stopped"; @@ -4881,7 +4881,7 @@ State of the client. *** -### StorageAdapter +### StorageAdapter ```ts type StorageAdapter = { @@ -4891,7 +4891,7 @@ type StorageAdapter = { }; ``` -#### Type declaration +#### Type declaration
@@ -4942,7 +4942,7 @@ type StorageAdapter = { *** -### ToolbarOptions +### ToolbarOptions ```ts type ToolbarOptions = @@ -4957,7 +4957,7 @@ Toolbar options. *** -### TrackEvent +### TrackEvent ```ts type TrackEvent = { @@ -4969,7 +4969,7 @@ type TrackEvent = { }; ``` -#### Type declaration +#### Type declaration
@@ -5033,7 +5033,7 @@ type TrackEvent = { *** -### UnassignedFeedback +### UnassignedFeedback ```ts type UnassignedFeedback = { @@ -5048,7 +5048,7 @@ type UnassignedFeedback = { }; ``` -#### Type declaration +#### Type declaration
@@ -5208,9 +5208,9 @@ Source of the feedback, depending on how the user was asked
-## Variables +## Variables -### DEFAULT\_TRANSLATIONS +### DEFAULT\_TRANSLATIONS ```ts const DEFAULT_TRANSLATIONS: FeedbackTranslations; @@ -5239,7 +5239,7 @@ export const DEFAULT_TRANSLATIONS: FeedbackTranslations = { *** -### feedbackContainerId +### feedbackContainerId ```ts const feedbackContainerId: "reflag-feedback-dialog-container" = "reflag-feedback-dialog-container"; @@ -5249,7 +5249,7 @@ ID of HTML DIV element which contains the feedback dialog *** -### propagatedEvents +### propagatedEvents ```ts const propagatedEvents: string[]; @@ -5257,6 +5257,6 @@ const propagatedEvents: string[]; These events will be propagated to the feedback dialog -#### See +#### See [https://developer.mozilla.org/en-US/docs/Web/API/Element#events](https://developer.mozilla.org/en-US/docs/Web/API/Element#events) diff --git a/supported-languages/node-sdk/README.md b/supported-languages/node-sdk/README.md index 411daa8..7c5f78e 100644 --- a/supported-languages/node-sdk/README.md +++ b/supported-languages/node-sdk/README.md @@ -21,13 +21,13 @@ pagination: Generated from [`@reflag/node-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/0809be2b95f43fa1785c6b7b188c03ac8fd40965/packages/node-sdk); SDK READMEs and code comments remain the source of truth. {% endhint %} -# Reflag Node.js SDK +# Reflag Node.js SDK Server-side Boolean and multivariate flag values for [Reflag](https://reflag.com). > This branch implements the breaking v2 API. It requires the collection-capable evaluator, the v2 `/flags` endpoint, and compatible variant-key check ingestion. It has not been published or deployed. -## Installation and initialization +## Installation and initialization ```sh yarn add @reflag/node-sdk@2 @@ -44,7 +44,7 @@ export const reflag = new ReflagClient({ await reflag.initialize(); ``` -## Direct values, immediate checks +## Direct values, immediate checks ```ts const context = { @@ -101,7 +101,7 @@ Local reads made before initialization include a `CLIENT_NOT_INITIALIZED` diagno `enableTracking: false` disables checks, context synchronization, and bound-client usage tracking. Explicit calls to the root client's `track()`, `updateUser()`, and `updateCompany()` remain separate operations. -## Evaluation and synchronization +## Evaluation and synchronization The SDK fetches a complete `{ flags, segments }` graph from secret-key-only `GET /flags`. Definitions are validated and prepared before the flags, segments, and snapshot version replace the current cache together. Malformed graphs and stale responses cannot replace last-known-good state. @@ -123,7 +123,7 @@ Refreshes are throttled. In-request mode can queue a refresh during the throttle Ordinary warm `/flags` refreshes send `If-None-Match` when the accepted snapshot has an ETag. A bodyless `304` retains the complete prepared graph and version while resetting freshness, without recompiling or saving it again. Cold/fallback initialization and version-targeted requests remain unconditional. Custom HTTP clients can return the exact optional `HttpClientResponse.etag` to enable this behavior; clients without one continue to use full GETs. Validators are enabled only after the snapshot's fallback save succeeds. Failed or pending saves leave refreshes unconditional, and rejected snapshots cannot replace a validator or overwrite fallback storage. -## Fallback providers +## Fallback providers ```ts import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; @@ -161,7 +161,7 @@ fallbackProviders.static({ Static values, `fallbackFlags`, and overrides do not identify authored variants. Their checks omit `evalResult` and `sourceVersionId`; they must not claim exposure to an authored selection. Restored real collection snapshots retain their real selection/version metadata. Providers are not loaded in offline mode. -## Overrides and tests +## Overrides and tests ```ts const client = new ReflagClient({ @@ -179,7 +179,7 @@ client.clearFlagOverrides(); Overrides are direct JSON values. Pushed layers win over base overrides and can be removed independently. They apply **after evaluation**, so overriding a dependency's returned value does not rewrite dependent flag evaluations. Offline mode does not fetch, load a provider, or send tracking events. -## Typed flags +## Typed flags Generated declarations are optional. Singular reads infer their return type from the default, or return Boolean when no default is supplied. Optionally augment `Flags` to constrain keys, check non-null defaults against each key's value schema, and type batch records: @@ -198,7 +198,7 @@ const models = reflag.getFlags(context); // models.model: "quick" | "quality" | Augmentation rejects defaults with the wrong category, missing required properties, or incompatible nested types. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request, and bare/`undefined` reads still return Boolean. Return types continue to be inferred and widened from the default; generated types do not add nested runtime validation. The v2 CLI generates direct-value schemas from current production-environment variants. Regenerate old CLI wrapper declarations when migrating. Both destructuring `.isEnabled` and accessing it through an assigned singular value fail type checking, including without generated declarations. See the Express example for a typed direct-value integration. -## Bootstrap state +## Bootstrap state ```ts const bootstrap = reflag.getFlagsForBootstrap(context); @@ -211,7 +211,7 @@ Bootstrap uses batch evaluation and preserves selection metadata and raw context **This is a v2 bootstrap contract, not the existing v1 Browser/React/Vue bootstrap shape.** Those consumers require a coordinated migration before accepting this state. Likewise, the current OpenFeature provider deliberately remains on published Node SDK v1 until its separate migration. -## Remote evaluation +## Remote evaluation ```ts const enabled = await reflag.getFlagRemote( @@ -233,11 +233,11 @@ These methods use `/flags/evaluated` and return direct values. Singular remote r Each requested singular root registers a check, including a default after a failed/missing remote evaluation, unless tracking is disabled. Only accepted authored selections retain the server's selection/version metadata. Explicit IDs, including numeric zero, take precedence over IDs in additional context. Stored attribute updates are asynchronous; remote evaluation need not immediately observe a just-sent update. -## Edge runtimes +## Edge runtimes Use `EdgeClient` with Node compatibility enabled. It selects in-request synchronization. Call `ctx.waitUntil(client.flush())` before returning from a Worker so queued events and refresh work can complete. -## Configuration +## Configuration Configuration precedence is constructor options, environment variables, then `reflag.config.json`. Supported environment variables include `REFLAG_SECRET_KEY`, `REFLAG_API_BASE_URL`, `REFLAG_LOG_LEVEL`, `REFLAG_OFFLINE`, `REFLAG_CONFIG_FILE`, and Boolean override lists `REFLAG_FLAGS_ENABLED` / `REFLAG_FLAGS_DISABLED`. @@ -245,6 +245,6 @@ Constructor options also include a custom `logger` / `httpClient`, `flagsSyncMod Invalid options/context or non-JSON defaults can throw. Network or definition-refresh failures are logged and retain usable state. Singular reads use their caller default (implicit `false`) without fabricating an authored false selection; batch reads retain raw values/`undefined`. Call `await client.flush()` before shutting down, then `client.destroy()` to stop background work. `batchOptions.flushOnExit` only flushes on natural Node process exit (`beforeExit`); it does not install signal handlers or force application shutdown. For signal-driven shutdown or an explicit `process.exit()`, await `flush()` in the application's own shutdown hook before exiting. -## License +## License MIT License. Copyright (c) 2025 Bucket ApS. diff --git a/supported-languages/node-sdk/globals.md b/supported-languages/node-sdk/globals.md index 4173afc..5b77b64 100644 --- a/supported-languages/node-sdk/globals.md +++ b/supported-languages/node-sdk/globals.md @@ -21,23 +21,23 @@ pagination: Generated from [`@reflag/node-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/0809be2b95f43fa1785c6b7b188c03ac8fd40965/packages/node-sdk); SDK READMEs and code comments remain the source of truth. {% endhint %} -# @reflag/node-sdk +# @reflag/node-sdk -## Classes +## Classes -### BoundReflagClient +### BoundReflagClient Context-bound reads have the same direct-value and immediate-check semantics. -#### Constructors +#### Constructors -##### new BoundReflagClient() +##### new BoundReflagClient() ```ts new BoundReflagClient(client: ReflagClient, options: ContextWithTracking): BoundReflagClient ``` -###### Parameters +###### Parameters @@ -74,15 +74,15 @@ new BoundReflagClient(client: ReflagClient, options: ContextWithTracking): Bound
-###### Returns +###### Returns [`BoundReflagClient`](globals.md#boundreflagclient) -#### Accessors +#### Accessors -##### company +##### company -###### Get Signature +###### Get Signature ```ts get company(): @@ -94,7 +94,7 @@ get company(): } ``` -###### Returns +###### Returns \| `undefined` \| \{ @@ -103,9 +103,9 @@ get company(): `name`: `string`; \} -##### otherContext +##### otherContext -###### Get Signature +###### Get Signature ```ts get otherContext(): @@ -113,14 +113,14 @@ get otherContext(): | Record ``` -###### Returns +###### Returns \| `undefined` \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> -##### user +##### user -###### Get Signature +###### Get Signature ```ts get user(): @@ -133,7 +133,7 @@ get user(): } ``` -###### Returns +###### Returns \| `undefined` \| \{ @@ -143,15 +143,15 @@ get user(): `name`: `string`; \} -#### Methods +#### Methods -##### bindClient() +##### bindClient() ```ts bindClient(next: ContextWithTracking): BoundReflagClient ``` -###### Parameters +###### Parameters @@ -176,29 +176,29 @@ bindClient(next: ContextWithTracking): BoundReflagClient
-###### Returns +###### Returns [`BoundReflagClient`](globals.md#boundreflagclient) -##### flush() +##### flush() ```ts flush(): Promise ``` -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### getFlag() +##### getFlag() -###### Call Signature +###### Call Signature ```ts getFlag(key: Key, defaultValue?: undefined): boolean ``` -###### Type Parameters +###### Type Parameters @@ -217,7 +217,7 @@ getFlag(key: Key, defaultValue?: undefined): boolean
-###### Parameters +###### Parameters @@ -254,17 +254,17 @@ getFlag(key: Key, defaultValue?: undefined): boolean
-###### Returns +###### Returns `boolean` -###### Call Signature +###### Call Signature ```ts getFlag(key: Key, defaultValue: Default): FlagValueFromDefault ``` -###### Type Parameters +###### Type Parameters @@ -290,7 +290,7 @@ getFlag(key: Key, defaultValue: Default): FlagValueFromDefault
-###### Parameters +###### Parameters @@ -327,19 +327,19 @@ getFlag(key: Key, defaultValue: Default): FlagValueFromDefault
-###### Returns +###### Returns [`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> -##### getFlagRemote() +##### getFlagRemote() -###### Call Signature +###### Call Signature ```ts getFlagRemote(key: Key, defaultValue?: undefined): Promise ``` -###### Type Parameters +###### Type Parameters @@ -358,7 +358,7 @@ getFlagRemote(key: Key, defaultValue?: undefined): Promise
-###### Parameters +###### Parameters @@ -395,17 +395,17 @@ getFlagRemote(key: Key, defaultValue?: undefined): Promise
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`boolean`\> -###### Call Signature +###### Call Signature ```ts getFlagRemote(key: Key, defaultValue: Default): Promise> ``` -###### Type Parameters +###### Type Parameters @@ -431,7 +431,7 @@ getFlagRemote(key: Key, defaultValue: Default): Promise
-###### Parameters +###### Parameters @@ -468,47 +468,47 @@ getFlagRemote(key: Key, defaultValue: Default): Promise
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\>\> -##### getFlags() +##### getFlags() ```ts getFlags(): Record ``` -###### Returns +###### Returns [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `undefined` \| [`FlagValue`](globals.md#flagvalue)\> -##### getFlagsForBootstrap() +##### getFlagsForBootstrap() ```ts getFlagsForBootstrap(): BootstrappedFlags ``` -###### Returns +###### Returns [`BootstrappedFlags`](globals.md#bootstrappedflags) -##### getFlagsRemote() +##### getFlagsRemote() ```ts getFlagsRemote(): Promise> ``` -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `undefined` \| [`FlagValue`](globals.md#flagvalue)\>\> -##### refreshFlags() +##### refreshFlags() ```ts refreshFlags(waitForVersion?: number): Promise ``` -###### Parameters +###### Parameters @@ -533,11 +533,11 @@ refreshFlags(waitForVersion?: number): Promise
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### track() +##### track() ```ts track(event: string, options?: TrackOptions & { @@ -545,7 +545,7 @@ track(event: string, options?: TrackOptions & { }): Promise ``` -###### Parameters +###### Parameters @@ -582,13 +582,13 @@ track(event: string, options?: TrackOptions & {
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> *** -### EdgeClient +### EdgeClient The EdgeClient is ReflagClient pre-configured to be used in edge runtimes, like Cloudflare Workers. @@ -599,7 +599,7 @@ that throttle window only records pending refresh work, so the call may resolve before the fetch runs. That pending refresh is executed on the next request/access or `refreshFlags()` call after the window expires. -#### Example +#### Example ```ts // set the REFLAG_SECRET_KEY environment variable or pass the secret key in the constructor @@ -614,19 +614,19 @@ const { isEnabled } = client.getFlag(context, "flag-key"); ``` -#### Extends +#### Extends - [`ReflagClient`](globals.md#reflagclient) -#### Constructors +#### Constructors -##### new EdgeClient() +##### new EdgeClient() ```ts new EdgeClient(options: EdgeClientOptions): EdgeClient ``` -###### Parameters +###### Parameters @@ -651,15 +651,15 @@ new EdgeClient(options: EdgeClientOptions): EdgeClient
-###### Returns +###### Returns [`EdgeClient`](globals.md#edgeclient) -###### Overrides +###### Overrides [`ReflagClient`](globals.md#reflagclient).[`constructor`](globals.md#constructors) -#### Properties +#### Properties @@ -707,11 +707,11 @@ new EdgeClient(options: EdgeClientOptions): EdgeClient
-#### Accessors +#### Accessors -##### flagOverrides +##### flagOverrides -###### Set Signature +###### Set Signature ```ts set flagOverrides(overrides: @@ -719,11 +719,11 @@ set flagOverrides(overrides: | FlagOverridesFn): void ``` -###### Deprecated +###### Deprecated Use setFlagOverrides. -###### Parameters +###### Parameters @@ -748,23 +748,23 @@ Use setFlagOverrides.
-###### Returns +###### Returns `void` -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`flagOverrides`](globals.md#flagoverrides) -#### Methods +#### Methods -##### bindClient() +##### bindClient() ```ts bindClient(options: ContextWithTracking): BoundReflagClient ``` -###### Parameters +###### Parameters @@ -789,59 +789,59 @@ bindClient(options: ContextWithTracking): BoundReflagClient
-###### Returns +###### Returns [`BoundReflagClient`](globals.md#boundreflagclient) -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`bindClient`](globals.md#bindclient) -##### clearFlagOverrides() +##### clearFlagOverrides() ```ts clearFlagOverrides(): void ``` -###### Returns +###### Returns `void` -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`clearFlagOverrides`](globals.md#clearflagoverrides) -##### destroy() +##### destroy() ```ts destroy(): void ``` -###### Returns +###### Returns `void` -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`destroy`](globals.md#destroy) -##### flush() +##### flush() ```ts flush(): Promise ``` -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`flush`](globals.md#flush) -##### getFlag() +##### getFlag() -###### Call Signature +###### Call Signature ```ts getFlag( @@ -852,7 +852,7 @@ getFlag( Read a Boolean with an implicit false default, or supply an explicit value default. -###### Type Parameters +###### Type Parameters @@ -871,7 +871,7 @@ Read a Boolean with an implicit false default, or supply an explicit value defau
-###### Parameters +###### Parameters @@ -920,15 +920,15 @@ Read a Boolean with an implicit false default, or supply an explicit value defau
-###### Returns +###### Returns `boolean` -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`getFlag`](globals.md#getflag) -###### Call Signature +###### Call Signature ```ts getFlag( @@ -939,7 +939,7 @@ defaultValue: Default): FlagValueFromDefault Read a Boolean with an implicit false default, or supply an explicit value default. -###### Type Parameters +###### Type Parameters @@ -965,7 +965,7 @@ Read a Boolean with an implicit false default, or supply an explicit value defau
-###### Parameters +###### Parameters @@ -1014,15 +1014,15 @@ Read a Boolean with an implicit false default, or supply an explicit value defau
-###### Returns +###### Returns [`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`getFlag`](globals.md#getflag) -##### getFlagDefinitions() +##### getFlagDefinitions() ```ts getFlagDefinitions(): FlagCollection @@ -1030,17 +1030,17 @@ getFlagDefinitions(): FlagCollection Complete definitions, including segments needed for offline evaluation. -###### Returns +###### Returns [`FlagCollection`](globals.md#flagcollection) -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`getFlagDefinitions`](globals.md#getflagdefinitions) -##### getFlagRemote() +##### getFlagRemote() -###### Call Signature +###### Call Signature ```ts getFlagRemote( @@ -1051,7 +1051,7 @@ getFlagRemote( context?: ContextWithTracking): Promise ``` -###### Type Parameters +###### Type Parameters @@ -1070,7 +1070,7 @@ context?: ContextWithTracking): Promise
-###### Parameters +###### Parameters @@ -1143,15 +1143,15 @@ context?: ContextWithTracking): Promise
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`boolean`\> -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`getFlagRemote`](globals.md#getflagremote) -###### Call Signature +###### Call Signature ```ts getFlagRemote( @@ -1162,7 +1162,7 @@ getFlagRemote( context?: ContextWithTracking): Promise> ``` -###### Type Parameters +###### Type Parameters @@ -1188,7 +1188,7 @@ context?: ContextWithTracking): Promise>
-###### Parameters +###### Parameters @@ -1261,15 +1261,15 @@ context?: ContextWithTracking): Promise>
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\>\> -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`getFlagRemote`](globals.md#getflagremote) -##### getFlags() +##### getFlags() ```ts getFlags(options: ContextWithTracking): Record @@ -1277,7 +1277,7 @@ getFlags(options: ContextWithTracking): Record Return all values and immediately register checks for the returned roots. -###### Parameters +###### Parameters @@ -1302,15 +1302,15 @@ Return all values and immediately register checks for the returned roots.
-###### Returns +###### Returns [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `undefined` \| [`FlagValue`](globals.md#flagvalue)\> -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`getFlags`](globals.md#getflags) -##### getFlagsForBootstrap() +##### getFlagsForBootstrap() ```ts getFlagsForBootstrap(options: ContextWithTracking): BootstrappedFlags @@ -1318,7 +1318,7 @@ getFlagsForBootstrap(options: ContextWithTracking): BootstrappedFlags Serialization is not a read by the browser; it must not emit check events. -###### Parameters +###### Parameters @@ -1343,15 +1343,15 @@ Serialization is not a read by the browser; it must not emit check events.
-###### Returns +###### Returns [`BootstrappedFlags`](globals.md#bootstrappedflags) -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`getFlagsForBootstrap`](globals.md#getflagsforbootstrap) -##### getFlagsRemote() +##### getFlagsRemote() ```ts getFlagsRemote( @@ -1360,7 +1360,7 @@ getFlagsRemote( context?: ContextWithTracking): Promise> ``` -###### Parameters +###### Parameters @@ -1409,29 +1409,29 @@ context?: ContextWithTracking): Promise>
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `undefined` \| [`FlagValue`](globals.md#flagvalue)\>\> -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`getFlagsRemote`](globals.md#getflagsremote) -##### initialize() +##### initialize() ```ts initialize(): Promise ``` -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`initialize`](globals.md#initialize) -##### pushFlagOverrides() +##### pushFlagOverrides() ```ts pushFlagOverrides(overrides: @@ -1439,7 +1439,7 @@ pushFlagOverrides(overrides: | FlagOverridesFn): () => void ``` -###### Parameters +###### Parameters @@ -1464,25 +1464,25 @@ pushFlagOverrides(overrides:
-###### Returns +###### Returns `Function` -###### Returns +###### Returns `void` -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`pushFlagOverrides`](globals.md#pushflagoverrides) -##### refreshFlags() +##### refreshFlags() ```ts refreshFlags(waitForVersion?: number): Promise ``` -###### Parameters +###### Parameters @@ -1507,15 +1507,15 @@ refreshFlags(waitForVersion?: number): Promise
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`refreshFlags`](globals.md#refreshflags) -##### setFlagOverrides() +##### setFlagOverrides() ```ts setFlagOverrides(overrides: @@ -1523,7 +1523,7 @@ setFlagOverrides(overrides: | FlagOverridesFn): void ``` -###### Parameters +###### Parameters @@ -1548,15 +1548,15 @@ setFlagOverrides(overrides:
-###### Returns +###### Returns `void` -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`setFlagOverrides`](globals.md#setflagoverrides) -##### track() +##### track() ```ts track( @@ -1567,7 +1567,7 @@ track( }): Promise ``` -###### Parameters +###### Parameters @@ -1616,15 +1616,15 @@ track(
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`track`](globals.md#track) -##### updateCompany() +##### updateCompany() ```ts updateCompany(companyId: IdType, options?: TrackOptions & { @@ -1632,7 +1632,7 @@ updateCompany(companyId: IdType, options?: TrackOptions & { }): Promise ``` -###### Parameters +###### Parameters @@ -1669,21 +1669,21 @@ updateCompany(companyId: IdType, options?: TrackOptions & {
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`updateCompany`](globals.md#updatecompany) -##### updateUser() +##### updateUser() ```ts updateUser(userId: IdType, options?: TrackOptions): Promise ``` -###### Parameters +###### Parameters @@ -1720,33 +1720,33 @@ updateUser(userId: IdType, options?: TrackOptions): Promise
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Inherited from +###### Inherited from [`ReflagClient`](globals.md#reflagclient).[`updateUser`](globals.md#updateuser) *** -### ReflagClient +### ReflagClient V2 client: flag reads return values and immediately register checks. -#### Extended by +#### Extended by - [`EdgeClient`](globals.md#edgeclient) -#### Constructors +#### Constructors -##### new ReflagClient() +##### new ReflagClient() ```ts new ReflagClient(options: ClientOptions): ReflagClient ``` -###### Parameters +###### Parameters @@ -1771,11 +1771,11 @@ new ReflagClient(options: ClientOptions): ReflagClient
-###### Returns +###### Returns [`ReflagClient`](globals.md#reflagclient) -#### Properties +#### Properties @@ -1823,11 +1823,11 @@ new ReflagClient(options: ClientOptions): ReflagClient
-#### Accessors +#### Accessors -##### flagOverrides +##### flagOverrides -###### Set Signature +###### Set Signature ```ts set flagOverrides(overrides: @@ -1835,11 +1835,11 @@ set flagOverrides(overrides: | FlagOverridesFn): void ``` -###### Deprecated +###### Deprecated Use setFlagOverrides. -###### Parameters +###### Parameters @@ -1864,19 +1864,19 @@ Use setFlagOverrides.
-###### Returns +###### Returns `void` -#### Methods +#### Methods -##### bindClient() +##### bindClient() ```ts bindClient(options: ContextWithTracking): BoundReflagClient ``` -###### Parameters +###### Parameters @@ -1901,43 +1901,43 @@ bindClient(options: ContextWithTracking): BoundReflagClient
-###### Returns +###### Returns [`BoundReflagClient`](globals.md#boundreflagclient) -##### clearFlagOverrides() +##### clearFlagOverrides() ```ts clearFlagOverrides(): void ``` -###### Returns +###### Returns `void` -##### destroy() +##### destroy() ```ts destroy(): void ``` -###### Returns +###### Returns `void` -##### flush() +##### flush() ```ts flush(): Promise ``` -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### getFlag() +##### getFlag() -###### Call Signature +###### Call Signature ```ts getFlag( @@ -1948,7 +1948,7 @@ getFlag( Read a Boolean with an implicit false default, or supply an explicit value default. -###### Type Parameters +###### Type Parameters @@ -1967,7 +1967,7 @@ Read a Boolean with an implicit false default, or supply an explicit value defau
-###### Parameters +###### Parameters @@ -2016,11 +2016,11 @@ Read a Boolean with an implicit false default, or supply an explicit value defau
-###### Returns +###### Returns `boolean` -###### Call Signature +###### Call Signature ```ts getFlag( @@ -2031,7 +2031,7 @@ defaultValue: Default): FlagValueFromDefault Read a Boolean with an implicit false default, or supply an explicit value default. -###### Type Parameters +###### Type Parameters @@ -2057,7 +2057,7 @@ Read a Boolean with an implicit false default, or supply an explicit value defau
-###### Parameters +###### Parameters @@ -2106,11 +2106,11 @@ Read a Boolean with an implicit false default, or supply an explicit value defau
-###### Returns +###### Returns [`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> -##### getFlagDefinitions() +##### getFlagDefinitions() ```ts getFlagDefinitions(): FlagCollection @@ -2118,13 +2118,13 @@ getFlagDefinitions(): FlagCollection Complete definitions, including segments needed for offline evaluation. -###### Returns +###### Returns [`FlagCollection`](globals.md#flagcollection) -##### getFlagRemote() +##### getFlagRemote() -###### Call Signature +###### Call Signature ```ts getFlagRemote( @@ -2135,7 +2135,7 @@ getFlagRemote( context?: ContextWithTracking): Promise ``` -###### Type Parameters +###### Type Parameters @@ -2154,7 +2154,7 @@ context?: ContextWithTracking): Promise
-###### Parameters +###### Parameters @@ -2227,11 +2227,11 @@ context?: ContextWithTracking): Promise
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`boolean`\> -###### Call Signature +###### Call Signature ```ts getFlagRemote( @@ -2242,7 +2242,7 @@ getFlagRemote( context?: ContextWithTracking): Promise> ``` -###### Type Parameters +###### Type Parameters @@ -2268,7 +2268,7 @@ context?: ContextWithTracking): Promise>
-###### Parameters +###### Parameters @@ -2341,11 +2341,11 @@ context?: ContextWithTracking): Promise>
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\>\> -##### getFlags() +##### getFlags() ```ts getFlags(options: ContextWithTracking): Record @@ -2353,7 +2353,7 @@ getFlags(options: ContextWithTracking): Record Return all values and immediately register checks for the returned roots. -###### Parameters +###### Parameters @@ -2378,11 +2378,11 @@ Return all values and immediately register checks for the returned roots.
-###### Returns +###### Returns [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `undefined` \| [`FlagValue`](globals.md#flagvalue)\> -##### getFlagsForBootstrap() +##### getFlagsForBootstrap() ```ts getFlagsForBootstrap(options: ContextWithTracking): BootstrappedFlags @@ -2390,7 +2390,7 @@ getFlagsForBootstrap(options: ContextWithTracking): BootstrappedFlags Serialization is not a read by the browser; it must not emit check events. -###### Parameters +###### Parameters @@ -2415,11 +2415,11 @@ Serialization is not a read by the browser; it must not emit check events.
-###### Returns +###### Returns [`BootstrappedFlags`](globals.md#bootstrappedflags) -##### getFlagsRemote() +##### getFlagsRemote() ```ts getFlagsRemote( @@ -2428,7 +2428,7 @@ getFlagsRemote( context?: ContextWithTracking): Promise> ``` -###### Parameters +###### Parameters @@ -2477,21 +2477,21 @@ context?: ContextWithTracking): Promise>
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `undefined` \| [`FlagValue`](globals.md#flagvalue)\>\> -##### initialize() +##### initialize() ```ts initialize(): Promise ``` -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### pushFlagOverrides() +##### pushFlagOverrides() ```ts pushFlagOverrides(overrides: @@ -2499,7 +2499,7 @@ pushFlagOverrides(overrides: | FlagOverridesFn): () => void ``` -###### Parameters +###### Parameters @@ -2524,21 +2524,21 @@ pushFlagOverrides(overrides:
-###### Returns +###### Returns `Function` -###### Returns +###### Returns `void` -##### refreshFlags() +##### refreshFlags() ```ts refreshFlags(waitForVersion?: number): Promise ``` -###### Parameters +###### Parameters @@ -2563,11 +2563,11 @@ refreshFlags(waitForVersion?: number): Promise
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### setFlagOverrides() +##### setFlagOverrides() ```ts setFlagOverrides(overrides: @@ -2575,7 +2575,7 @@ setFlagOverrides(overrides: | FlagOverridesFn): void ``` -###### Parameters +###### Parameters @@ -2600,11 +2600,11 @@ setFlagOverrides(overrides:
-###### Returns +###### Returns `void` -##### track() +##### track() ```ts track( @@ -2615,7 +2615,7 @@ track( }): Promise ``` -###### Parameters +###### Parameters @@ -2664,11 +2664,11 @@ track(
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### updateCompany() +##### updateCompany() ```ts updateCompany(companyId: IdType, options?: TrackOptions & { @@ -2676,7 +2676,7 @@ updateCompany(companyId: IdType, options?: TrackOptions & { }): Promise ``` -###### Parameters +###### Parameters @@ -2713,17 +2713,17 @@ updateCompany(companyId: IdType, options?: TrackOptions & {
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### updateUser() +##### updateUser() ```ts updateUser(userId: IdType, options?: TrackOptions): Promise ``` -###### Parameters +###### Parameters @@ -2760,19 +2760,19 @@ updateUser(userId: IdType, options?: TrackOptions): Promise
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -## Interfaces +## Interfaces -### ContextWithTracking +### ContextWithTracking -#### Extends +#### Extends - [`Context`](globals.md#context) -#### Properties +#### Properties @@ -2931,23 +2931,23 @@ updateUser(userId: IdType, options?: TrackOptions): Promise *** -### Flags +### Flags Augment this interface with flag keys and their returned value types. *** -### FlagsFallbackProvider +### FlagsFallbackProvider -#### Methods +#### Methods -##### load() +##### load() ```ts load(context: FlagsFallbackProviderContext): Promise ``` -###### Parameters +###### Parameters
@@ -2972,17 +2972,17 @@ load(context: FlagsFallbackProviderContext): Promise
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`undefined` \| [`FlagsFallbackSnapshot`](globals.md#flagsfallbacksnapshot)\> -##### save() +##### save() ```ts save(context: FlagsFallbackProviderContext, snapshot: FlagsFallbackSnapshot): Promise ``` -###### Parameters +###### Parameters @@ -3019,17 +3019,17 @@ save(context: FlagsFallbackProviderContext, snapshot: FlagsFallbackSnapshot): Pr
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> *** -### HttpClient +### HttpClient -#### Methods +#### Methods -##### get() +##### get() ```ts get( @@ -3038,7 +3038,7 @@ get( timeoutMs: number): Promise> ``` -###### Type Parameters +###### Type Parameters @@ -3057,7 +3057,7 @@ timeoutMs: number): Promise>
-###### Parameters +###### Parameters @@ -3106,11 +3106,11 @@ timeoutMs: number): Promise>
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`HttpClientResponse`](globals.md#httpclientresponseresponse)\<`Response`\>\> -##### post() +##### post() ```ts post( @@ -3119,7 +3119,7 @@ post( body: Body): Promise> ``` -###### Type Parameters +###### Type Parameters @@ -3145,7 +3145,7 @@ body: Body): Promise>
-###### Parameters +###### Parameters @@ -3194,23 +3194,23 @@ body: Body): Promise>
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`HttpClientResponse`](globals.md#httpclientresponseresponse)\<`Response`\>\> *** -### Logger +### Logger -#### Methods +#### Methods -##### debug() +##### debug() ```ts debug(message: string, data?: any): void ``` -###### Parameters +###### Parameters @@ -3247,17 +3247,17 @@ debug(message: string, data?: any): void
-###### Returns +###### Returns `void` -##### error() +##### error() ```ts error(message: string, data?: any): void ``` -###### Parameters +###### Parameters @@ -3294,17 +3294,17 @@ error(message: string, data?: any): void
-###### Returns +###### Returns `void` -##### info() +##### info() ```ts info(message: string, data?: any): void ``` -###### Parameters +###### Parameters @@ -3341,17 +3341,17 @@ info(message: string, data?: any): void
-###### Returns +###### Returns `void` -##### warn() +##### warn() ```ts warn(message: string, data?: any): void ``` -###### Parameters +###### Parameters @@ -3388,13 +3388,13 @@ warn(message: string, data?: any): void
-###### Returns +###### Returns `void` -## Type Aliases +## Type Aliases -### Attributes +### Attributes ```ts type Attributes = Record; @@ -3402,7 +3402,7 @@ type Attributes = Record; *** -### BatchBufferOptions\ +### BatchBufferOptions\ ```ts type BatchBufferOptions = { @@ -3414,7 +3414,7 @@ type BatchBufferOptions = { }; ``` -#### Type Parameters +#### Type Parameters @@ -3433,7 +3433,7 @@ type BatchBufferOptions = {
-#### Type declaration +#### Type declaration @@ -3535,7 +3535,7 @@ For signals or process.exit(), await client.flush() in the application hook. *** -### BootstrappedFlags +### BootstrappedFlags ```ts type BootstrappedFlags = { @@ -3546,7 +3546,7 @@ type BootstrappedFlags = { }; ``` -#### Type declaration +#### Type declaration
@@ -3609,7 +3609,7 @@ type BootstrappedFlags = { *** -### CacheStrategy +### CacheStrategy ```ts type CacheStrategy = "periodically-update" | "in-request"; @@ -3617,7 +3617,7 @@ type CacheStrategy = "periodically-update" | "in-request"; *** -### ClientOptions +### ClientOptions ```ts type ClientOptions = { @@ -3644,7 +3644,7 @@ type ClientOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -3974,7 +3974,7 @@ Use apiBaseUrl. *** -### Context +### Context ```ts type Context = { @@ -3993,7 +3993,7 @@ type Context = { }; ``` -#### Type declaration +#### Type declaration
@@ -4137,7 +4137,7 @@ type Context = { *** -### EdgeClientOptions +### EdgeClientOptions ```ts type EdgeClientOptions = Omit; @@ -4145,7 +4145,7 @@ type EdgeClientOptions = Omit ```ts type FileFallbackProviderOptions = { @@ -4153,7 +4153,7 @@ type FileFallbackProviderOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -4186,7 +4186,7 @@ Directory where per-environment snapshots are stored. *** -### FlagCollection +### FlagCollection ```ts type FlagCollection = CompiledCollection & { @@ -4194,7 +4194,7 @@ type FlagCollection = CompiledCollection & { }; ``` -#### Type declaration +#### Type declaration
@@ -4221,7 +4221,7 @@ type FlagCollection = CompiledCollection & { *** -### FlagDefaultFor\ +### FlagDefaultFor\ ```ts type FlagDefaultFor = keyof Registry extends never ? FlagDefaultValue | object : Key extends keyof Registry ? ReadonlyFlagValue | null : never; @@ -4229,7 +4229,7 @@ type FlagDefaultFor = keyof Registry extends never ? FlagDefaultV Registered defaults match the value schema; null explicitly requests arbitrary JSON. -#### Type Parameters +#### Type Parameters
@@ -4257,7 +4257,7 @@ Registered defaults match the value schema; null explicitly requests arbitrary J *** -### FlagDefaultValue +### FlagDefaultValue ```ts type FlagDefaultValue = @@ -4273,7 +4273,7 @@ JSON defaults may be readonly; returned values are independent mutable copies. *** -### FlagDefinition +### FlagDefinition ```ts type FlagDefinition = CompiledFlag; @@ -4281,7 +4281,7 @@ type FlagDefinition = CompiledFlag; *** -### FlagEvent +### FlagEvent ```ts type FlagEvent = { @@ -4305,7 +4305,7 @@ type FlagEvent = { A check records the selected variant key, never its JSON payload. -#### Type declaration +#### Type declaration
@@ -4482,7 +4482,7 @@ Use evalErrors and check for MISSING_CONTEXT_FIELD. *** -### FlagOverrides +### FlagOverrides ```ts type FlagOverrides = Partial : { [Key in keyof Flags]: Flags[Key] }>; @@ -4490,13 +4490,13 @@ type FlagOverrides = Partial ```ts type FlagOverridesFn = (context: Context) => FlagOverrides; ``` -#### Parameters +#### Parameters
@@ -4521,13 +4521,13 @@ type FlagOverridesFn = (context: Context) => FlagOverrides;
-#### Returns +#### Returns [`FlagOverrides`](globals.md#flagoverrides) *** -### FlagsAPIResponse +### FlagsAPIResponse ```ts type FlagsAPIResponse = FlagCollection & { @@ -4536,7 +4536,7 @@ type FlagsAPIResponse = FlagCollection & { }; ``` -#### Type declaration +#### Type declaration @@ -4575,7 +4575,7 @@ type FlagsAPIResponse = FlagCollection & { *** -### FlagsFallbackProviderContext +### FlagsFallbackProviderContext ```ts type FlagsFallbackProviderContext = { @@ -4583,7 +4583,7 @@ type FlagsFallbackProviderContext = { }; ``` -#### Type declaration +#### Type declaration
@@ -4610,7 +4610,7 @@ type FlagsFallbackProviderContext = { *** -### FlagsFallbackSnapshot +### FlagsFallbackSnapshot ```ts type FlagsFallbackSnapshot = FlagCollection & { @@ -4623,7 +4623,7 @@ type FlagsFallbackSnapshot = FlagCollection & { V1 snapshots cannot be evaluated by the collection evaluator. -#### Type declaration +#### Type declaration
@@ -4686,7 +4686,7 @@ V1 snapshots cannot be evaluated by the collection evaluator. *** -### FlagsSyncMode +### FlagsSyncMode ```ts type FlagsSyncMode = "polling" | "in-request" | "push"; @@ -4694,7 +4694,7 @@ type FlagsSyncMode = "polling" | "in-request" | "push"; *** -### FlagValue +### FlagValue ```ts type FlagValue = @@ -4708,7 +4708,7 @@ type FlagValue = *** -### FlagValueFromDefault\ +### FlagValueFromDefault\ ```ts type FlagValueFromDefault = T extends null ? FlagValue : T extends boolean ? boolean : T extends number ? number : T extends string ? string : T extends readonly infer Element[] ? [Element] extends [never] ? FlagValue[] : FlagValueFromDefault[] : T extends object ? { -readonly [Key in keyof T]: FlagValueFromDefault } : never; @@ -4716,7 +4716,7 @@ type FlagValueFromDefault = T extends null ? FlagValue : T extends boolean ? Infer values from defaults, widening literals. Null explicitly requests arbitrary JSON. -#### Type Parameters +#### Type Parameters
@@ -4737,7 +4737,7 @@ Infer values from defaults, widening literals. Null explicitly requests arbitrar *** -### GCSFallbackProviderClient +### GCSFallbackProviderClient ```ts type GCSFallbackProviderClient = @@ -4747,7 +4747,7 @@ type GCSFallbackProviderClient = *** -### GCSFallbackProviderOptions +### GCSFallbackProviderOptions ```ts type GCSFallbackProviderOptions = { @@ -4757,7 +4757,7 @@ type GCSFallbackProviderOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -4829,7 +4829,7 @@ Prefix for generated per-environment keys. *** -### GCSGoogleApisClient +### GCSGoogleApisClient ```ts type GCSGoogleApisClient = { @@ -4842,7 +4842,7 @@ type GCSGoogleApisClient = { }; ``` -#### Type declaration +#### Type declaration
@@ -4900,7 +4900,7 @@ type GCSGoogleApisClient = { *** -### GCSLegacyClient +### GCSLegacyClient ```ts type GCSLegacyClient = { @@ -4914,7 +4914,7 @@ type GCSLegacyClient = { }; ``` -#### Type declaration +#### Type declaration
@@ -4947,7 +4947,7 @@ type GCSLegacyClient = { *** -### HttpClientResponse\ +### HttpClientResponse\ ```ts type HttpClientResponse = { @@ -4958,7 +4958,7 @@ type HttpClientResponse = { }; ``` -#### Type Parameters +#### Type Parameters
@@ -4977,7 +4977,7 @@ type HttpClientResponse = {
-#### Type declaration +#### Type declaration @@ -5061,7 +5061,7 @@ Exact response ETag for conditional definition refreshes, when available. *** -### IdType +### IdType ```ts type IdType = string | number; @@ -5069,7 +5069,7 @@ type IdType = string | number; *** -### LogLevel +### LogLevel ```ts type LogLevel = typeof LOG_LEVELS[number]; @@ -5077,7 +5077,7 @@ type LogLevel = typeof LOG_LEVELS[number]; *** -### RawFlag +### RawFlag ```ts type RawFlag = Omit, "sourceVersionId" | "value" | "resolved"> & { @@ -5087,7 +5087,7 @@ type RawFlag = Omit, "sourceVersionId" | "value" }; ``` -#### Type declaration +#### Type declaration
@@ -5138,7 +5138,7 @@ type RawFlag = Omit, "sourceVersionId" | "value" *** -### RawFlags +### RawFlags ```ts type RawFlags = Record; @@ -5146,7 +5146,7 @@ type RawFlags = Record; *** -### RedisFallbackProviderOptions +### RedisFallbackProviderOptions ```ts type RedisFallbackProviderOptions = { @@ -5158,7 +5158,7 @@ type RedisFallbackProviderOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -5245,7 +5245,7 @@ Prefix for generated per-environment keys. *** -### S3FallbackProviderOptions +### S3FallbackProviderOptions ```ts type S3FallbackProviderOptions = { @@ -5257,7 +5257,7 @@ type S3FallbackProviderOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -5343,7 +5343,7 @@ Prefix for generated per-environment keys. *** -### StaticFallbackProviderOptions +### StaticFallbackProviderOptions ```ts type StaticFallbackProviderOptions = { @@ -5351,7 +5351,7 @@ type StaticFallbackProviderOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -5384,7 +5384,7 @@ Static fallback flags keyed by flag key. *** -### TrackingMeta +### TrackingMeta ```ts type TrackingMeta = { @@ -5392,7 +5392,7 @@ type TrackingMeta = { }; ``` -#### Type declaration +#### Type declaration
@@ -5419,7 +5419,7 @@ type TrackingMeta = { *** -### TrackOptions +### TrackOptions ```ts type TrackOptions = { @@ -5428,7 +5428,7 @@ type TrackOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -5467,7 +5467,7 @@ type TrackOptions = { *** -### TypedFlagKey +### TypedFlagKey ```ts type TypedFlagKey = keyof Flags extends never ? string : Extract; @@ -5475,15 +5475,15 @@ type TypedFlagKey = keyof Flags extends never ? string : Extract ```ts type TypedFlags = keyof Flags extends never ? Record : { [Key in keyof Flags]: Flags[Key] | undefined }; ``` -## Variables +## Variables -### fallbackProviders +### fallbackProviders ```ts const fallbackProviders: { @@ -5495,7 +5495,7 @@ const fallbackProviders: { }; ``` -#### Type declaration +#### Type declaration
diff --git a/supported-languages/react-native-sdk/README.md b/supported-languages/react-native-sdk/README.md index eccf625..a55236e 100644 --- a/supported-languages/react-native-sdk/README.md +++ b/supported-languages/react-native-sdk/README.md @@ -17,7 +17,7 @@ pagination: **Independent SDK compatibility.** This React Native release uses React/Browser protocol v1. Follow the [matching React documentation](../../legacy/v1/react-sdk/README.md) and use a [matching Node SDK](../../legacy/v1/node-sdk/README.md) for bootstrap. Do not pass protocol-v2 bootstrap into a v1 consumer. {% endhint %} -# Reflag React Native SDK +# Reflag React Native SDK A thin React Native wrapper around `@reflag/react-sdk`. @@ -25,15 +25,15 @@ For more usage details, see the [React SDK README](../../legacy/v1/react-sdk/REA An Expo example app lives in [packages/react-native-sdk/dev/expo](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/react-native-sdk/dev/expo). -## Get started +## Get started -### Install +### Install ```shell npm i @reflag/react-native-sdk ``` -### 1. Add the ReflagProvider +### 1. Add the ReflagProvider Wrap your app with the provider from `@reflag/react-native-sdk`: @@ -51,7 +51,7 @@ import { ReflagProvider } from "@reflag/react-native-sdk"; ; ``` -### 2. Use `useFlag()` +### 2. Use `useFlag()` ```tsx import { useFlag } from "@reflag/react-native-sdk"; @@ -67,22 +67,22 @@ function StartHuddleButton() { See the [React SDK README](../../legacy/v1/react-sdk/README.md) for more details. -## React Native differences +## React Native differences - The Reflag toolbar is web-only and is not available in React Native. - Built-in feedback UI is web-only. In React Native, use your own UI and call `useSendFeedback` or `client.feedback` when you're ready to send feedback. - Live flag updates work out of the box. The React Native SDK bundles an SSE transport via `react-native-sse`, so no global `EventSource` shim is required. - If you need custom SSE behavior, you can still override the transport by passing `eventSourceFactory` to `ReflagProvider` or `ReflagBootstrappedProvider`. -## Reference +## Reference The React Native SDK shares its API with the React SDK. Use the React SDK reference for full types and details: [React SDK Reference](../../legacy/v1/react-sdk/README.md) -## Cookbook +## Cookbook -### Refresh flags when the app returns to the foreground +### Refresh flags when the app returns to the foreground Flags are updated if the context passed to `` changes, but you might also want to update them when the app comes to the foreground. See this snippet: @@ -123,7 +123,7 @@ export function App() { } ``` -## Suspense loading +## Suspense loading Enable `` support by setting the `suspense` prop on the provider and wrap components that call `useFlag` in a Suspense boundary: @@ -141,7 +141,7 @@ import { ReflagProvider } from "@reflag/react-native-sdk"; You can also override the behavior for one call with `useFlag("huddle", { suspense: true })`. -## Bootstrapping +## Bootstrapping You can use `` in React Native when you already have pre-fetched flags and want to avoid an initial fetch. Pass the full object returned by the Node SDK's `getFlagsForBootstrap()` directly as the provider's `flags` prop; it includes `context`, evaluated `flags`, and an optional `flagStateVersion`. diff --git a/supported-languages/react-native-sdk/globals.md b/supported-languages/react-native-sdk/globals.md index 49c7284..fd7908a 100644 --- a/supported-languages/react-native-sdk/globals.md +++ b/supported-languages/react-native-sdk/globals.md @@ -17,15 +17,15 @@ pagination: **Independent SDK compatibility.** This React Native release uses React/Browser protocol v1. Follow the [matching React documentation](../../legacy/v1/react-sdk/README.md) and use a [matching Node SDK](../../legacy/v1/node-sdk/README.md) for bootstrap. Do not pass protocol-v2 bootstrap into a v1 consumer. {% endhint %} -# @reflag/react-native-sdk +# @reflag/react-native-sdk -## Interfaces +## Interfaces -### CheckEvent +### CheckEvent Event representing checking the flag evaluation result -#### Properties +#### Properties
@@ -166,19 +166,19 @@ Version of targeting rules. *** -### CompanyContext +### CompanyContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing company. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties
@@ -228,11 +228,11 @@ Company name *** -### Flag\ +### Flag\ Describes a feature -#### Type Parameters +#### Type Parameters
@@ -257,7 +257,7 @@ Describes a feature
-#### Properties +#### Properties @@ -356,9 +356,9 @@ Request feedback from the user.
-#### Methods +#### Methods -##### track() +##### track() ```ts track(): @@ -370,7 +370,7 @@ track(): Track feature usage in Reflag. -###### Returns +###### Returns \| `undefined` \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< @@ -379,23 +379,23 @@ Track feature usage in Reflag. *** -### Flags +### Flags *** -### UserContext +### UserContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing user. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties @@ -460,9 +460,9 @@ User name
-## Type Aliases +## Type Aliases -### BootstrappedFlags +### BootstrappedFlags ```ts type BootstrappedFlags = BootstrappedState & { @@ -470,7 +470,7 @@ type BootstrappedFlags = BootstrappedState & { }; ``` -#### Type declaration +#### Type declaration @@ -497,7 +497,7 @@ type BootstrappedFlags = BootstrappedState & { *** -### EmptyFlagRemoteConfig +### EmptyFlagRemoteConfig ```ts type EmptyFlagRemoteConfig = { @@ -506,7 +506,7 @@ type EmptyFlagRemoteConfig = { }; ``` -#### Type declaration +#### Type declaration
@@ -545,7 +545,7 @@ type EmptyFlagRemoteConfig = { *** -### FlagKey +### FlagKey ```ts type FlagKey = keyof TypedFlags; @@ -553,7 +553,7 @@ type FlagKey = keyof TypedFlags; *** -### FlagRemoteConfig +### FlagRemoteConfig ```ts type FlagRemoteConfig = @@ -566,7 +566,7 @@ type FlagRemoteConfig = A remotely managed configuration value for a feature. -#### Type declaration +#### Type declaration \{ `key`: `string`; @@ -623,7 +623,7 @@ The optional user-supplied payload data. *** -### FlagType +### FlagType ```ts type FlagType = { @@ -633,7 +633,7 @@ type FlagType = { }; ``` -#### Type declaration +#### Type declaration
@@ -674,7 +674,7 @@ type FlagType = { *** -### OptInFlag +### OptInFlag ```ts type OptInFlag = Omit & { @@ -688,7 +688,7 @@ Includes all fields from [BrowserOptInFlag](../../legacy/v1/browser-sdk/globals. `isEnabled`, `userOptedIn`, `companyOptedIn`, and `isOptedIn`. Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. -#### Type declaration +#### Type declaration
@@ -715,7 +715,7 @@ Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. *** -### RawFlags +### RawFlags ```ts type RawFlags = Record; @@ -725,7 +725,7 @@ Describes a collection of evaluated raw flags. *** -### ReflagBootstrappedProps +### ReflagBootstrappedProps ```ts type ReflagBootstrappedProps = ReflagPropsBase & ReflagInitOptionsBase & { @@ -735,7 +735,7 @@ type ReflagBootstrappedProps = ReflagPropsBase & ReflagInitOptionsBase & { Props for the ReflagBootstrappedProvider. -#### Type declaration +#### Type declaration
@@ -769,7 +769,7 @@ metadata on demand when opt-in flags are requested. *** -### ReflagClientProviderProps +### ReflagClientProviderProps ```ts type ReflagClientProviderProps = Omit & { @@ -779,7 +779,7 @@ type ReflagClientProviderProps = Omit & { Props for the ReflagClientProvider. -#### Type declaration +#### Type declaration
@@ -806,7 +806,7 @@ Props for the ReflagClientProvider. *** -### ReflagInitOptionsBase +### ReflagInitOptionsBase ```ts type ReflagInitOptionsBase = Omit ```ts type ReflagProps = ReflagPropsBase & ReflagInitOptionsBase & { @@ -838,7 +838,7 @@ type ReflagProps = ReflagPropsBase & ReflagInitOptionsBase & { Props for the ReflagProvider. -#### Type declaration +#### Type declaration
@@ -936,7 +936,7 @@ Use `context` instead, this property will be removed in the next major version *** -### ReflagPropsBase +### ReflagPropsBase ```ts type ReflagPropsBase = { @@ -953,7 +953,7 @@ type ReflagPropsBase = { Base props for the ReflagProvider and ReflagBootstrappedProvider. -#### Type declaration +#### Type declaration
@@ -1075,7 +1075,7 @@ wrapped in a React `` boundary. *** -### RequestFeedbackOptions +### RequestFeedbackOptions ```ts type RequestFeedbackOptions = Omit; @@ -1083,7 +1083,7 @@ type RequestFeedbackOptions = Omit *** -### SetOptInOptions +### SetOptInOptions ```ts type SetOptInOptions = { @@ -1094,7 +1094,7 @@ type SetOptInOptions = { Options for changing the current user or company's opt-in membership. -#### Type declaration +#### Type declaration
@@ -1144,7 +1144,7 @@ Whether to update the current user or current company. Defaults to `user`. *** -### StorageAdapter +### StorageAdapter ```ts type StorageAdapter = { @@ -1154,7 +1154,7 @@ type StorageAdapter = { }; ``` -#### Type declaration +#### Type declaration
@@ -1205,7 +1205,7 @@ type StorageAdapter = { *** -### TrackEvent +### TrackEvent ```ts type TrackEvent = { @@ -1217,7 +1217,7 @@ type TrackEvent = { }; ``` -#### Type declaration +#### Type declaration
@@ -1281,7 +1281,7 @@ type TrackEvent = { *** -### TypedFlags +### TypedFlags ```ts type TypedFlags = keyof Flags extends never ? Record : { [TypedFlagKey in keyof Flags]: Flags[TypedFlagKey] extends FlagType ? Flag : Flag }; @@ -1289,14 +1289,14 @@ type TypedFlags = keyof Flags extends never ? Record : { [TypedFla Describes a collection of evaluated feature. -#### Remarks +#### Remarks This types falls back to a generic Record if the Flags interface has not been extended. *** -### UseFlagOptions +### UseFlagOptions ```ts type UseFlagOptions = { @@ -1304,7 +1304,7 @@ type UseFlagOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -1336,15 +1336,15 @@ When true, `useFlag` throws a promise while flags are loading.
-## Functions +## Functions -### ReflagBootstrappedProvider() +### ReflagBootstrappedProvider() ```ts function ReflagBootstrappedProvider(props: ReflagBootstrappedProps): Element ``` -#### Parameters +#### Parameters @@ -1369,19 +1369,19 @@ function ReflagBootstrappedProvider(props: ReflagBootstrappedProps): Element
-#### Returns +#### Returns `Element` *** -### ReflagClientProvider() +### ReflagClientProvider() ```ts function ReflagClientProvider(__namedParameters: ReflagClientProviderProps): React.JSX.Element ``` -#### Parameters +#### Parameters @@ -1406,19 +1406,19 @@ function ReflagClientProvider(__namedParameters: ReflagClientProviderProps): Rea
-#### Returns +#### Returns `React.JSX.Element` *** -### ReflagProvider() +### ReflagProvider() ```ts function ReflagProvider(props: ReflagProps): Element ``` -#### Parameters +#### Parameters @@ -1443,13 +1443,13 @@ function ReflagProvider(props: ReflagProps): Element
-#### Returns +#### Returns `Element` *** -### useClient() +### useClient() ```ts function useClient(): ReflagClient @@ -1459,13 +1459,13 @@ Returns the current `ReflagClient` used by the `ReflagProvider`. This is useful if you need to access the `ReflagClient` outside of the `ReflagProvider`. -#### Returns +#### Returns [`ReflagClient`](../../legacy/v1/browser-sdk/globals.md#reflagclient) The `ReflagClient`. -#### Example +#### Example ```ts import { useClient } from '@reflag/react-sdk'; @@ -1478,13 +1478,13 @@ function App() { *** -### ~~useFeature()~~ +### ~~useFeature()~~ ```ts function useFeature(key: TKey, options?: UseFlagOptions): Flag ``` -#### Type Parameters +#### Type Parameters @@ -1503,7 +1503,7 @@ function useFeature(key: TKey, options?: UseFlagOptions): Flag
-#### Parameters +#### Parameters @@ -1540,17 +1540,17 @@ function useFeature(key: TKey, options?: UseFlagOptions): Flag
-#### Returns +#### Returns [`Flag`](globals.md#flagtconfig)\<[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig)\> -#### Deprecated +#### Deprecated use `useFlag` instead *** -### useFlag() +### useFlag() ```ts function useFlag(key: TKey, options?: UseFlagOptions): TypedFlags[TKey] @@ -1566,7 +1566,7 @@ function HuddleButton() { } ``` -#### Type Parameters +#### Type Parameters @@ -1585,7 +1585,7 @@ function HuddleButton() {
-#### Parameters +#### Parameters @@ -1622,13 +1622,13 @@ function HuddleButton() {
-#### Returns +#### Returns [`TypedFlags`](globals.md#typedflags)\[`TKey`\] *** -### useIsLoading() +### useIsLoading() ```ts function useIsLoading(): boolean @@ -1638,13 +1638,13 @@ Returns a boolean indicating if the Reflag client is loading. You can use this to check if the Reflag client is loading at any point in your application. Initially, the value will be true until the client is initialized. -#### Returns +#### Returns `boolean` A boolean indicating if the Reflag client is loading. -#### Example +#### Example ```ts import { useIsLoading } from '@reflag/react-sdk'; @@ -1656,7 +1656,7 @@ console.log(isLoading); *** -### useOnEvent() +### useOnEvent() ```ts function useOnEvent( @@ -1667,7 +1667,7 @@ function useOnEvent( Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount. -#### Type Parameters +#### Type Parameters @@ -1686,7 +1686,7 @@ Attach a callback handler to client events to act on changes. It automatically d
-#### Parameters +#### Parameters @@ -1751,11 +1751,11 @@ The Reflag client to listen to. If not provided, the client will be retrieved fr
-#### Returns +#### Returns `void` -#### Example +#### Example ```ts import { useOnEvent } from '@reflag/react-sdk'; @@ -1767,7 +1767,7 @@ useOnEvent("flagsUpdated", () => { *** -### useOptInFlags() +### useOptInFlags() ```ts function useOptInFlags(options?: UseOptInFlagsOptions): UseOptInFlagsResult @@ -1784,7 +1784,7 @@ of returning a loading result. A Suspense boundary alone does not enable it. If fetching opt-in metadata fails, loading ends without exposing an error. Call `refresh()` on the client returned by [useClient](globals.md#useclient) to retry. -#### Parameters +#### Parameters @@ -1809,13 +1809,13 @@ Call `refresh()` on the client returned by [useClient](globals.md#useclient) to
-#### Returns +#### Returns [`UseOptInFlagsResult`](../../legacy/v1/react-sdk/globals.md#useoptinflagsresult) *** -### useRequestFeedback() +### useRequestFeedback() ```ts function useRequestFeedback(): (options: RequestFeedbackData) => void @@ -1834,11 +1834,11 @@ reflag.requestFeedback({ }); ``` -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -1863,13 +1863,13 @@ reflag.requestFeedback({
-##### Returns +##### Returns `void` *** -### useSendFeedback() +### useSendFeedback() ```ts function useSendFeedback(): (opts: UnassignedFeedback) => Promise< @@ -1892,11 +1892,11 @@ sendFeedback({ }); ``` -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -1921,7 +1921,7 @@ sendFeedback({
-##### Returns +##### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response) @@ -1929,7 +1929,7 @@ sendFeedback({ *** -### useSetOptIn() +### useSetOptIn() ```ts function useSetOptIn(): (key: FlagKey, options: SetOptInOptions) => Promise< @@ -1944,11 +1944,11 @@ HTTP failures return a non-OK Response; offline mode, invalid arguments, or missing scoped context return undefined. Confirmation failures can reject after the membership changed remotely. See [ReflagClient.setOptIn](../../legacy/v1/browser-sdk/globals.md#setoptin). -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -1985,7 +1985,7 @@ after the membership changed remotely. See [ReflagClient.setOptIn](../../legacy/
-##### Returns +##### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response) @@ -1993,7 +1993,7 @@ after the membership changed remotely. See [ReflagClient.setOptIn](../../legacy/ *** -### useTrack() +### useTrack() ```ts function useTrack(): (eventName: string, attributes?: @@ -2011,11 +2011,11 @@ const track = useTrack(); track("Started Huddle", { button: "cta" }); ``` -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -2052,7 +2052,7 @@ track("Started Huddle", { button: "cta" });
-##### Returns +##### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response) @@ -2060,7 +2060,7 @@ track("Started Huddle", { button: "cta" }); *** -### useUpdateCompany() +### useUpdateCompany() ```ts function useUpdateCompany(): (opts: {}) => Promise @@ -2078,11 +2078,11 @@ const updateCompany = useUpdateCompany(); updateCompany({ plan: "enterprise" }).then(() => console.log("Flags updated")); ``` -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -2107,13 +2107,13 @@ updateCompany({ plan: "enterprise" }).then(() => console.log("Flags updated"));
-##### Returns +##### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> *** -### useUpdateOtherContext() +### useUpdateOtherContext() ```ts function useUpdateOtherContext(): (opts: {}) => Promise @@ -2132,11 +2132,11 @@ updateOtherContext({ workspaceId: newWorkspaceId }) .then(() => console.log("Flags updated")); ``` -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -2161,13 +2161,13 @@ updateOtherContext({ workspaceId: newWorkspaceId })
-##### Returns +##### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> *** -### useUpdateUser() +### useUpdateUser() ```ts function useUpdateUser(): (opts: {}) => Promise @@ -2185,11 +2185,11 @@ const updateUser = useUpdateUser(); updateUser({ optInHuddles: "true" }).then(() => console.log("Flags updated")); ``` -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -2214,6 +2214,6 @@ updateUser({ optInHuddles: "true" }).then(() => console.log("Flags updated"));
-##### Returns +##### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> diff --git a/supported-languages/react-sdk/README.md b/supported-languages/react-sdk/README.md index 075abb2..4180e10 100644 --- a/supported-languages/react-sdk/README.md +++ b/supported-languages/react-sdk/README.md @@ -21,13 +21,13 @@ pagination: Generated from [`@reflag/react-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/react-sdk); SDK READMEs and code comments remain the source of truth. {% endhint %} -# Reflag React SDK v2 +# Reflag React SDK v2 Direct-value feature flags for React, backed by [Browser SDK v2](../browser-sdk/README.md). > Breaking prerelease: requires compatible v2 server endpoints and **Node SDK v2** for bootstrap. The v2 CLI generates direct-value declarations; regenerate legacy wrapper-shaped output when migrating. Useful default-based inference does not require generated declarations. React Native remains on published React/Browser v1 in this repository. -## Setup +## Setup ```tsx import { ReflagProvider } from "@reflag/react-sdk"; @@ -45,7 +45,7 @@ import { ReflagProvider } from "@reflag/react-sdk"; Provider options forward Browser SDK settings, including `logger`, `debug`, `enableTracking`, `offline`, cache/fallback options, `toolbar`, `feedback`, `credentials` and API origins. A custom logger takes precedence over debug logging. Live updates default to true; set `enableLiveFlagUpdates={false}` to disable them. -## `useFlag(key, defaultValue?)` +## `useFlag(key, defaultValue?)` ```tsx import { useFlag, useTrack } from "@reflag/react-sdk"; @@ -76,7 +76,7 @@ Non-null defaults enforce only the top-level JSON category (Boolean/number/strin `useFlag` never suspends. Its second argument is **payload data**, not `{ suspense: ... }` options; ordinary JSON has no reserved keys. Use the dedicated hook below for suspension. Use `useIsLoading()` or the provider's `loadingComponent` when you need an explicit loading UI. -## `useFlagSuspense(key, defaultValue?)` +## `useFlagSuspense(key, defaultValue?)` ```tsx import { Suspense } from "react"; @@ -96,7 +96,7 @@ This hook has the same Boolean/default-based return types. It waits for initiali The provider's existing `suspense` prop continues to configure **`useOptInFlags` only**. It does not change `useFlag`; `useFlagSuspense` is explicit. -## Checks and usage tracking +## Checks and usage tracking A completed getter/hook read registers its requested-root check immediately, even if the value is ignored. Actual delivery remains buffered and identity-aware rate-limited by the Browser SDK. Checks contain selected variant/source/snapshot identity, not payloads. Defaults, category mismatches and local overrides never invent authored selections. Diagnostic/bootstrap inspection registers no checks. @@ -113,7 +113,7 @@ await sendFeedback({ flagKey: "huddles", score: 5 }); See [Browser feedback documentation](../browser-sdk/feedback.md) for UI/prompt configuration. -## Optional key registration +## Optional key registration ```ts import "@reflag/react-sdk"; @@ -127,7 +127,7 @@ declare module "@reflag/react-sdk" { Registration constrains keys and checks non-null defaults against the registered value schema, including required and nested properties. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request; bare/`undefined` reads remain Boolean. The positional default still determines the widened return type, and generated declarations do not add nested runtime validation. The same rules apply to `useFlagSuspense`. The v2 CLI generates direct-value declarations from current production-environment variants; regenerate legacy wrapper declarations when migrating. -## Bootstrap and SSR +## Bootstrap and SSR On the server, use Node SDK v2: @@ -149,7 +149,7 @@ The envelope includes `protocolVersion: 2`, context, evaluated flag results and For a pre-existing Browser v2 client, use ``. The provider does not own its lifecycle; initialize/stop externally, except that a suspending read can start on-demand initialization. -## Context, loading and events +## Context, loading and events - `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return async shallow-update functions. `useClient().setContext(context)` replaces the whole context. - Context changes clear old-context values while fetching. Stale/in-flight responses cannot replace a newer context/snapshot. @@ -157,7 +157,7 @@ For a pre-existing Browser v2 client, use ` ```tsx const { flags, isLoading } = useOptInFlags(); @@ -170,6 +170,6 @@ Metadata arrives with the initial v2 evaluation for regular providers. Bootstrap `useOptInFlags({ suspense: true | false })` retains its own per-hook loading options and may inherit provider `suspense`. These options are unrelated to the positional payload defaults used by `useFlag` / `useFlagSuspense`. -## Migration from v1 +## Migration from v1 Use `const enabled = useFlag(key)` instead of destructuring `.isEnabled`. Replace wrapper config access with an authored multivariate flag and positional default. Move `.track()` and `.requestFeedback()` to separate hooks. Replace `useFlag(key, { suspense: true })` with `useFlagSuspense(key)`, and use `useIsLoading()` instead of a flag wrapper's loading property. Upgrade Browser/server bootstrap together. Nothing here publishes the prerelease or deploys its required server changes. diff --git a/supported-languages/react-sdk/globals.md b/supported-languages/react-sdk/globals.md index 7e48f2f..21a752d 100644 --- a/supported-languages/react-sdk/globals.md +++ b/supported-languages/react-sdk/globals.md @@ -21,15 +21,15 @@ pagination: Generated from [`@reflag/react-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/react-sdk); SDK READMEs and code comments remain the source of truth. {% endhint %} -# @reflag/react-sdk +# @reflag/react-sdk -## Interfaces +## Interfaces -### CheckEvent +### CheckEvent A root read records selection identity, never its JSON payload. -#### Properties +#### Properties @@ -152,19 +152,19 @@ A root read records selection identity, never its JSON payload. *** -### CompanyContext +### CompanyContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing company. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties
@@ -214,25 +214,25 @@ Company name *** -### Flags +### Flags Optional key/value registration; singular reads infer their type from defaults. *** -### UserContext +### UserContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing user. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties
@@ -297,9 +297,9 @@ User name
-## Type Aliases +## Type Aliases -### BootstrappedFlags +### BootstrappedFlags ```ts type BootstrappedFlags = BootstrappedState & { @@ -307,7 +307,7 @@ type BootstrappedFlags = BootstrappedState & { }; ``` -#### Type declaration +#### Type declaration @@ -334,7 +334,7 @@ type BootstrappedFlags = BootstrappedState & { *** -### FlagDefaultValue +### FlagDefaultValue ```ts type FlagDefaultValue = @@ -348,7 +348,7 @@ type FlagDefaultValue = *** -### FlagKey +### FlagKey ```ts type FlagKey = keyof Flags extends never ? string : Extract; @@ -356,7 +356,7 @@ type FlagKey = keyof Flags extends never ? string : Extract *** -### FlagValue +### FlagValue ```ts type FlagValue = @@ -370,7 +370,7 @@ type FlagValue = *** -### FlagValueFromDefault\ +### FlagValueFromDefault\ ```ts type FlagValueFromDefault = T extends null ? FlagValue : T extends boolean ? boolean : T extends number ? number : T extends string ? string : T extends readonly infer Element[] ? [Element] extends [never] ? FlagValue[] : FlagValueFromDefault[] : T extends object ? { -readonly [Key in keyof T]: FlagValueFromDefault } : never; @@ -378,7 +378,7 @@ type FlagValueFromDefault = T extends null ? FlagValue : T extends boolean ? Widen literals and return mutable copies. Null requests arbitrary JSON. -#### Type Parameters +#### Type Parameters
@@ -399,7 +399,7 @@ Widen literals and return mutable copies. Null requests arbitrary JSON. *** -### OptInFlag +### OptInFlag ```ts type OptInFlag = Omit & { @@ -409,7 +409,7 @@ type OptInFlag = Omit & { An opt-in-enabled flag for the generated React SDK flag definitions. -#### Type declaration +#### Type declaration
@@ -436,7 +436,7 @@ An opt-in-enabled flag for the generated React SDK flag definitions. *** -### RawFlags +### RawFlags ```ts type RawFlags = RawFlags; @@ -446,7 +446,7 @@ Describes a collection of evaluated raw flags. *** -### ReflagBootstrappedProps +### ReflagBootstrappedProps ```ts type ReflagBootstrappedProps = ReflagPropsBase & ReflagInitOptionsBase & { @@ -456,7 +456,7 @@ type ReflagBootstrappedProps = ReflagPropsBase & ReflagInitOptionsBase & { Props for the ReflagBootstrappedProvider. -#### Type declaration +#### Type declaration
@@ -490,7 +490,7 @@ metadata on demand when opt-in flags are requested. *** -### ReflagClientProviderProps +### ReflagClientProviderProps ```ts type ReflagClientProviderProps = Omit & { @@ -500,7 +500,7 @@ type ReflagClientProviderProps = Omit & { Props for the ReflagClientProvider. -#### Type declaration +#### Type declaration
@@ -527,7 +527,7 @@ Props for the ReflagClientProvider. *** -### ReflagInitOptionsBase +### ReflagInitOptionsBase ```ts type ReflagInitOptionsBase = Omit ```ts type ReflagProps = ReflagPropsBase & ReflagInitOptionsBase & { @@ -559,7 +559,7 @@ type ReflagProps = ReflagPropsBase & ReflagInitOptionsBase & { Props for the ReflagProvider. -#### Type declaration +#### Type declaration
@@ -657,7 +657,7 @@ Use `context` instead, this property will be removed in the next major version *** -### ReflagPropsBase +### ReflagPropsBase ```ts type ReflagPropsBase = { @@ -674,7 +674,7 @@ type ReflagPropsBase = { Base props for the ReflagProvider and ReflagBootstrappedProvider. -#### Type declaration +#### Type declaration
@@ -795,7 +795,7 @@ Use `useFlagSuspense` for suspending direct-value reads. *** -### RequestFeedbackOptions +### RequestFeedbackOptions ```ts type RequestFeedbackOptions = Omit; @@ -803,7 +803,7 @@ type RequestFeedbackOptions = Omit *** -### SetOptInOptions +### SetOptInOptions ```ts type SetOptInOptions = { @@ -814,7 +814,7 @@ type SetOptInOptions = { Represents a flag. -#### Type declaration +#### Type declaration
@@ -864,7 +864,7 @@ Whether to update the current user or current company. Defaults to `user`. *** -### StorageAdapter +### StorageAdapter ```ts type StorageAdapter = { @@ -874,7 +874,7 @@ type StorageAdapter = { }; ``` -#### Type declaration +#### Type declaration
@@ -925,7 +925,7 @@ type StorageAdapter = { *** -### TrackEvent +### TrackEvent ```ts type TrackEvent = { @@ -937,7 +937,7 @@ type TrackEvent = { }; ``` -#### Type declaration +#### Type declaration
@@ -1001,7 +1001,7 @@ type TrackEvent = { *** -### TypedFlags +### TypedFlags ```ts type TypedFlags = keyof Flags extends never ? Record : { [Key in keyof Flags]: Flags[Key] | undefined }; @@ -1009,7 +1009,7 @@ type TypedFlags = keyof Flags extends never ? Record ```ts type UseOptInFlagsOptions = { @@ -1017,7 +1017,7 @@ type UseOptInFlagsOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -1051,7 +1051,7 @@ When true, `useOptInFlags` throws a promise while opt-in flags are loading. *** -### UseOptInFlagsResult +### UseOptInFlagsResult ```ts type UseOptInFlagsResult = { @@ -1060,7 +1060,7 @@ type UseOptInFlagsResult = { }; ``` -#### Type declaration +#### Type declaration
@@ -1108,9 +1108,9 @@ Whether a bootstrapped provider is fetching opt-in metadata.
-## Functions +## Functions -### ReflagBootstrappedProvider() +### ReflagBootstrappedProvider() ```ts function ReflagBootstrappedProvider(__namedParameters: ReflagBootstrappedProps): Element @@ -1118,7 +1118,7 @@ function ReflagBootstrappedProvider(__namedParameters: ReflagBootstrappedProps): Bootstrapped Provider for the ReflagClient using pre-fetched flags. -#### Parameters +#### Parameters @@ -1143,19 +1143,19 @@ Bootstrapped Provider for the ReflagClient using pre-fetched flags.
-#### Returns +#### Returns `Element` *** -### ReflagClientProvider() +### ReflagClientProvider() ```ts function ReflagClientProvider(__namedParameters: ReflagClientProviderProps): Element ``` -#### Parameters +#### Parameters @@ -1180,13 +1180,13 @@ function ReflagClientProvider(__namedParameters: ReflagClientProviderProps): Ele
-#### Returns +#### Returns `Element` *** -### ReflagProvider() +### ReflagProvider() ```ts function ReflagProvider(__namedParameters: ReflagProps): Element @@ -1194,7 +1194,7 @@ function ReflagProvider(__namedParameters: ReflagProps): Element Provider for the ReflagClient. -#### Parameters +#### Parameters @@ -1219,13 +1219,13 @@ Provider for the ReflagClient.
-#### Returns +#### Returns `Element` *** -### useClient() +### useClient() ```ts function useClient(): ReflagClient @@ -1235,13 +1235,13 @@ Returns the current `ReflagClient` used by the `ReflagProvider`. This is useful if you need to access the `ReflagClient` outside of the `ReflagProvider`. -#### Returns +#### Returns [`ReflagClient`](../browser-sdk/globals.md#reflagclient) The `ReflagClient`. -#### Example +#### Example ```ts import { useClient } from '@reflag/react-sdk'; @@ -1254,13 +1254,13 @@ function App() { *** -### ~~useFeature()~~ +### ~~useFeature()~~ -#### Deprecated +#### Deprecated Use useFlag. -#### Call Signature +#### Call Signature ```ts function useFeature(key: string, defaultValue?: undefined): boolean @@ -1268,7 +1268,7 @@ function useFeature(key: string, defaultValue?: undefined): boolean Boolean-first, non-suspending reads. Supply a positional default for JSON values. -##### Parameters +##### Parameters @@ -1305,15 +1305,15 @@ Boolean-first, non-suspending reads. Supply a positional default for JSON values
-##### Returns +##### Returns `boolean` -##### Deprecated +##### Deprecated Use useFlag. -#### Call Signature +#### Call Signature ```ts function useFeature(key: Key, defaultValue: Default): FlagValueFromDefault @@ -1321,7 +1321,7 @@ function useFeature(key: Key, defaultValue: Default): FlagValueFro Boolean-first, non-suspending reads. Supply a positional default for JSON values. -##### Type Parameters +##### Type Parameters @@ -1347,7 +1347,7 @@ Boolean-first, non-suspending reads. Supply a positional default for JSON values
-##### Parameters +##### Parameters @@ -1384,15 +1384,15 @@ Boolean-first, non-suspending reads. Supply a positional default for JSON values
-##### Returns +##### Returns [`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> -##### Deprecated +##### Deprecated Use useFlag. -#### Call Signature +#### Call Signature ```ts function useFeature(key: string, defaultValue: Default): FlagValueFromDefault @@ -1400,7 +1400,7 @@ function useFeature(key: string, defaultValue: Default): FlagValueFromD Boolean-first, non-suspending reads. Supply a positional default for JSON values. -##### Type Parameters +##### Type Parameters @@ -1419,7 +1419,7 @@ Boolean-first, non-suspending reads. Supply a positional default for JSON values
-##### Parameters +##### Parameters @@ -1456,19 +1456,19 @@ Boolean-first, non-suspending reads. Supply a positional default for JSON values
-##### Returns +##### Returns [`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> -##### Deprecated +##### Deprecated Use useFlag. *** -### useFlag() +### useFlag() -#### Call Signature +#### Call Signature ```ts function useFlag(key: string, defaultValue?: undefined): boolean @@ -1476,7 +1476,7 @@ function useFlag(key: string, defaultValue?: undefined): boolean Boolean-first, non-suspending reads. Supply a positional default for JSON values. -##### Parameters +##### Parameters @@ -1513,11 +1513,11 @@ Boolean-first, non-suspending reads. Supply a positional default for JSON values
-##### Returns +##### Returns `boolean` -#### Call Signature +#### Call Signature ```ts function useFlag(key: Key, defaultValue: Default): FlagValueFromDefault @@ -1525,7 +1525,7 @@ function useFlag(key: Key, defaultValue: Default): FlagValueFromDe Boolean-first, non-suspending reads. Supply a positional default for JSON values. -##### Type Parameters +##### Type Parameters @@ -1551,7 +1551,7 @@ Boolean-first, non-suspending reads. Supply a positional default for JSON values
-##### Parameters +##### Parameters @@ -1588,11 +1588,11 @@ Boolean-first, non-suspending reads. Supply a positional default for JSON values
-##### Returns +##### Returns [`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> -#### Call Signature +#### Call Signature ```ts function useFlag(key: string, defaultValue: Default): FlagValueFromDefault @@ -1600,7 +1600,7 @@ function useFlag(key: string, defaultValue: Default): FlagValueFromDefa Boolean-first, non-suspending reads. Supply a positional default for JSON values. -##### Type Parameters +##### Type Parameters @@ -1619,7 +1619,7 @@ Boolean-first, non-suspending reads. Supply a positional default for JSON values
-##### Parameters +##### Parameters @@ -1656,15 +1656,15 @@ Boolean-first, non-suspending reads. Supply a positional default for JSON values
-##### Returns +##### Returns [`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> *** -### useFlagSuspense() +### useFlagSuspense() -#### Call Signature +#### Call Signature ```ts function useFlagSuspense(key: string, defaultValue?: undefined): boolean @@ -1672,7 +1672,7 @@ function useFlagSuspense(key: string, defaultValue?: undefined): boolean Wait for initialization, then read once. Missing flags use the default, not an endless suspension. -##### Parameters +##### Parameters @@ -1709,11 +1709,11 @@ Wait for initialization, then read once. Missing flags use the default, not an e
-##### Returns +##### Returns `boolean` -#### Call Signature +#### Call Signature ```ts function useFlagSuspense(key: Key, defaultValue: Default): FlagValueFromDefault @@ -1721,7 +1721,7 @@ function useFlagSuspense(key: Key, defaultValue: Default): FlagVal Wait for initialization, then read once. Missing flags use the default, not an endless suspension. -##### Type Parameters +##### Type Parameters @@ -1747,7 +1747,7 @@ Wait for initialization, then read once. Missing flags use the default, not an e
-##### Parameters +##### Parameters @@ -1784,11 +1784,11 @@ Wait for initialization, then read once. Missing flags use the default, not an e
-##### Returns +##### Returns [`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> -#### Call Signature +#### Call Signature ```ts function useFlagSuspense(key: string, defaultValue: Default): FlagValueFromDefault @@ -1796,7 +1796,7 @@ function useFlagSuspense(key: string, defaultValue: Default): FlagValue Wait for initialization, then read once. Missing flags use the default, not an endless suspension. -##### Type Parameters +##### Type Parameters @@ -1815,7 +1815,7 @@ Wait for initialization, then read once. Missing flags use the default, not an e
-##### Parameters +##### Parameters @@ -1852,13 +1852,13 @@ Wait for initialization, then read once. Missing flags use the default, not an e
-##### Returns +##### Returns [`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> *** -### useIsLoading() +### useIsLoading() ```ts function useIsLoading(): boolean @@ -1868,13 +1868,13 @@ Returns a boolean indicating if the Reflag client is loading. You can use this to check if the Reflag client is loading at any point in your application. Initially, the value will be true until the client is initialized. -#### Returns +#### Returns `boolean` A boolean indicating if the Reflag client is loading. -#### Example +#### Example ```ts import { useIsLoading } from '@reflag/react-sdk'; @@ -1886,7 +1886,7 @@ console.log(isLoading); *** -### useOnEvent() +### useOnEvent() ```ts function useOnEvent( @@ -1897,7 +1897,7 @@ function useOnEvent( Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount. -#### Type Parameters +#### Type Parameters @@ -1916,7 +1916,7 @@ Attach a callback handler to client events to act on changes. It automatically d
-#### Parameters +#### Parameters @@ -1981,11 +1981,11 @@ The Reflag client to listen to. If not provided, the client will be retrieved fr
-#### Returns +#### Returns `void` -#### Example +#### Example ```ts import { useOnEvent } from '@reflag/react-sdk'; @@ -1997,7 +1997,7 @@ useOnEvent("flagsUpdated", () => { *** -### useOptInFlags() +### useOptInFlags() ```ts function useOptInFlags(options: UseOptInFlagsOptions): UseOptInFlagsResult @@ -2011,7 +2011,7 @@ with the initial flags. When suspense is enabled for the provider or this hook, it suspends instead of returning a loading result. -#### Parameters +#### Parameters @@ -2036,13 +2036,13 @@ of returning a loading result.
-#### Returns +#### Returns [`UseOptInFlagsResult`](globals.md#useoptinflagsresult) *** -### useRequestFeedback() +### useRequestFeedback() ```ts function useRequestFeedback(): (options: RequestFeedbackData) => void @@ -2061,11 +2061,11 @@ reflag.requestFeedback({ }); ``` -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -2090,13 +2090,13 @@ reflag.requestFeedback({
-##### Returns +##### Returns `void` *** -### useSendFeedback() +### useSendFeedback() ```ts function useSendFeedback(): (opts: UnassignedFeedback) => Promise< @@ -2119,11 +2119,11 @@ sendFeedback({ }); ``` -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -2148,7 +2148,7 @@ sendFeedback({
-##### Returns +##### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` @@ -2156,7 +2156,7 @@ sendFeedback({ *** -### useSetOptIn() +### useSetOptIn() ```ts function useSetOptIn(): (key: string, options: SetOptInOptions) => Promise< @@ -2166,11 +2166,11 @@ function useSetOptIn(): (key: string, options: SetOptInOptions) => Promise< Returns a function to set whether the current user or company has opted into a flag. -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -2207,7 +2207,7 @@ Returns a function to set whether the current user or company has opted into a f
-##### Returns +##### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` @@ -2215,7 +2215,7 @@ Returns a function to set whether the current user or company has opted into a f *** -### useTrack() +### useTrack() ```ts function useTrack(): (eventName: string, attributes?: @@ -2233,11 +2233,11 @@ const track = useTrack(); track("Started Huddle", { button: "cta" }); ``` -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -2274,7 +2274,7 @@ track("Started Huddle", { button: "cta" });
-##### Returns +##### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` @@ -2282,7 +2282,7 @@ track("Started Huddle", { button: "cta" }); *** -### useUpdateCompany() +### useUpdateCompany() ```ts function useUpdateCompany(): (opts: {}) => Promise @@ -2300,11 +2300,11 @@ const updateCompany = useUpdateCompany(); updateCompany({ plan: "enterprise" }).then(() => console.log("Flags updated")); ``` -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -2329,13 +2329,13 @@ updateCompany({ plan: "enterprise" }).then(() => console.log("Flags updated"));
-##### Returns +##### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> *** -### useUpdateOtherContext() +### useUpdateOtherContext() ```ts function useUpdateOtherContext(): (opts: {}) => Promise @@ -2354,11 +2354,11 @@ updateOtherContext({ workspaceId: newWorkspaceId }) .then(() => console.log("Flags updated")); ``` -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -2383,13 +2383,13 @@ updateOtherContext({ workspaceId: newWorkspaceId })
-##### Returns +##### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> *** -### useUpdateUser() +### useUpdateUser() ```ts function useUpdateUser(): (opts: {}) => Promise @@ -2407,11 +2407,11 @@ const updateUser = useUpdateUser(); updateUser({ optInHuddles: "true" }).then(() => console.log("Flags updated")); ``` -#### Returns +#### Returns `Function` -##### Parameters +##### Parameters @@ -2436,6 +2436,6 @@ updateUser({ optInHuddles: "true" }).then(() => console.log("Flags updated"));
-##### Returns +##### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> diff --git a/supported-languages/vue-sdk/README.md b/supported-languages/vue-sdk/README.md index 52fd8b4..5406fd7 100644 --- a/supported-languages/vue-sdk/README.md +++ b/supported-languages/vue-sdk/README.md @@ -21,13 +21,13 @@ pagination: Generated from [`@reflag/vue-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/vue-sdk); SDK READMEs and code comments remain the source of truth. {% endhint %} -# Reflag Vue SDK v2 (beta) +# Reflag Vue SDK v2 (beta) Reactive direct-value flags for Vue 3, backed by [Browser SDK v2](../browser-sdk/README.md). > Breaking prerelease: requires the compatible v2 server protocol. Bootstrap must come from **Node SDK v2**, not v1. Generated declarations are optional; the v2 CLI supports `--format vue` and direct-value schemas. Regenerate legacy wrapper-shaped declarations when migrating. -## Setup +## Setup ```vue \n[Source](https://github.com/reflagcom/javascript/blob/main/packages/${name}/README.md)\n`, + `---\nlayout: {}\n---\n# SDK\n[Browser](../../_media/README.md)\n[Feedback](../../documents/browser-sdk/FEEDBACK.md)\n[Toolbar](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions)\nnpm install @reflag/${name}\nbun add @reflag/${name}\ndeno add npm:@reflag/${name}\nnpx @reflag/cli new\n\n[Source](https://github.com/reflagcom/javascript/blob/main/packages/${name}/README.md)\n`, ); put( path.join(source, `dist/docs/@reflag/${name}/globals.md`), @@ -117,6 +124,57 @@ test("v2 sync cannot modify archived docs, navigation, settings or handwritten g ); }); +test("current docs use unpinned installs and one short footer even for prerelease sources", (t) => { + const { options, source, put } = fixture(t); + put( + path.join(source, "packages/react-sdk/package.json"), + JSON.stringify({ name: "@reflag/react-sdk", version: "2.0.0-next.0" }), + ); + const files = planPackage(options); + for (const file of [ + "supported-languages/react-sdk/README.md", + "sdk/@reflag/react-sdk/README.md", + "sdk/documents/react-sdk/README.md", + ]) { + const content = files.get(file).toString(); + checkCurrentPagePresentation(content, file); + assert(content.indexOf("# SDK") < content.indexOf("Using v1?")); + assert.match(content, /npm install @reflag\/react-sdk\n/); + assert.match(content, /npx @reflag\/cli new/); + assert.match(content, /browser-sdk"><\/script>/); + assert(!content.includes("{% hint")); + assert( + !content.includes("2.0.0-next.0"), + "Source versions remain in provenance, not page warnings", + ); + } + const manifest = JSON.parse(files.get(".generated/sdk-docs/react-sdk/v2.json")); + assert.equal(manifest.version, "2.0.0-next.0"); +}); + +test("presentation checks reject repeated or leading notices and major-pinned current installs", () => { + const note = "Using v1? [Legacy docs](legacy.md) · [Upgrade guide](migration.md)."; + const page = `# SDK\n\nGet started.\n\n${note}\n`; + checkCurrentPagePresentation(page, "page.md"); + assert.throws(() => checkCurrentPagePresentation(`${note}\n\n# SDK\n`, "page.md"), /at the end/); + assert.throws( + () => checkCurrentPagePresentation(`${note}\n\n${page}`, "page.md"), + /one succinct/, + ); + assert.throws( + () => + checkCurrentPagePresentation( + page.replace("Get started.", "npm install @reflag/react-sdk@2"), + "page.md", + ), + /Major-pinned installs/, + ); + assert.throws( + () => checkCurrentPagePresentation(page.replace("Get started.", "**Protocol v2.**"), "page.md"), + /Repeated protocol banner/, + ); +}); + test("independent Native references route to its pinned React/Browser major, not workspace v2", (t) => { const { options } = fixture(t); const files = planPackage({ ...options, name: "react-native-sdk" }); diff --git a/README.md b/README.md index db76a92..05b096c 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,5 @@ # Getting started -{% hint style="info" %} -These examples use **protocol v2**. The SDK page banners identify prerelease source versions and package availability. Maintaining a v1 application? Use the [legacy SDK docs](legacy/v1/README.md) or [migration guide](supported-languages/migrating-from-v1.md). -{% endhint %} - **Welcome!** Let's get started. We'll do the following: 1. Create your first flag. @@ -19,10 +15,10 @@ Now let's create your first flag. {% tabs %} {% tab title="CLI" %} ``` -npx @reflag/cli@2 new +npx @reflag/cli new ``` -This requires a compatible CLI 2 release; for the current v2 prerelease rollout, use the package version supplied to you. You can also create the flag in the UI without installing the CLI. See [Type safety](product-handbook/type-safety.md) for v2 type generation. +See [Type safety](product-handbook/type-safety.md) to generate TypeScript declarations for your flags. {% endtab %} {% tab title="UI" %} @@ -146,3 +142,5 @@ Configure your flag's adoption rules to match the event name you send with `trac * Need some help? [Chat with us](mailto:hello@reflag.com) * Latest product updates? [See Changelog](https://reflag.com/changelog) * Create account: [Sign up](https://app.reflag.com/) + +Using v1? [Legacy docs](legacy/v1/README.md) · [Upgrade guide](supported-languages/migrating-from-v1.md). diff --git a/SUMMARY.md b/SUMMARY.md index 4f7e3c0..f3c0b74 100644 --- a/SUMMARY.md +++ b/SUMMARY.md @@ -7,7 +7,6 @@ ## Supported languages * [Overview](supported-languages/overview.md) -* [Migrating from v1](supported-languages/migrating-from-v1.md) * [React SDK](supported-languages/react-sdk/README.md) * [Reference](supported-languages/react-sdk/globals.md) * [React Native SDK (beta)](supported-languages/react-native-sdk/README.md) @@ -22,6 +21,7 @@ * [Next.js](supported-languages/next.js.md) * [OpenFeature](supported-languages/openfeature.md) * [Ruby SDK](supported-languages/ruby-sdk.md) +* [Migrating from v1](supported-languages/migrating-from-v1.md) ## API diff --git a/guides/self-opt-in.md b/guides/self-opt-in.md index 17303a1..f724435 100644 --- a/guides/self-opt-in.md +++ b/guides/self-opt-in.md @@ -113,7 +113,7 @@ Cancelling every opt-in does not necessarily disable the flag: an access rule ma ## Managing opt-in loading state -Check opt-in loading before rendering an empty state, including during ordinary initialization. Metadata arrives with v2 evaluated-flags responses. A bootstrapped snapshot may omit it; the SDK then fetches missing metadata on demand without replacing server-derived flag values. +Check opt-in loading before rendering an empty state, including during ordinary initialization. Metadata arrives with evaluated-flags responses. A bootstrapped snapshot may omit it; the SDK then fetches missing metadata on demand without replacing server-derived flag values. Check the hook's `isLoading` value before rendering an empty state: diff --git a/guides/toggle-toolbar-with-a-flag.md b/guides/toggle-toolbar-with-a-flag.md index 7a6a60b..faeb189 100644 --- a/guides/toggle-toolbar-with-a-flag.md +++ b/guides/toggle-toolbar-with-a-flag.md @@ -1,5 +1,5 @@ --- -description: Show the SDK v2 toolbar toggle to selected users. +description: Show the SDK toolbar toggle to selected users. icon: toolbox --- @@ -7,7 +7,7 @@ icon: toolbox Use a Boolean flag to choose who sees the SDK toolbar toggle. Create a `toolbar` flag in Reflag, configure its access rules, and leave the provider's unconditional `toolbar` option disabled. -Put this component inside your React SDK v2 provider: +Put this component inside your React SDK provider: ```tsx import { useEffect } from "react"; @@ -27,4 +27,4 @@ export function ToolbarFlagControl() { This shows the toggle once access is granted. `showToolbarToggle()` does not provide a corresponding hide operation: switching the flag off later does not remove an already mounted toggle. Reload or recreate the client to apply a new visibility decision. -This is a convenience control, **not an authorization boundary**. Users control their own browser; never use the toolbar flag to protect secrets or administrative server operations. See [Browser SDK v2](../supported-languages/browser-sdk/README.md) for toolbar options. +This is a convenience control, **not an authorization boundary**. Users control their own browser; never use the toolbar flag to protect secrets or administrative server operations. See [Browser SDK](../supported-languages/browser-sdk/README.md) for toolbar options. diff --git a/guides/use-reflag-in-your-cli.md b/guides/use-reflag-in-your-cli.md index 065bd02..34a9911 100644 --- a/guides/use-reflag-in-your-cli.md +++ b/guides/use-reflag-in-your-cli.md @@ -1,11 +1,11 @@ --- -description: Gate a workflow in your own CLI with SDK v2. +description: Gate a workflow in your own CLI with Reflag. icon: rectangle-terminal --- # Use Reflag in your CLI -This guide is about **your application's CLI**, not the Reflag management CLI. Authenticate your caller using your existing API-token or OAuth flow, then evaluate flags with the server-side Node SDK v2. Do not embed a Reflag secret SDK key or a Management API key in a distributed CLI. +This guide is about **your application's CLI**, not the Reflag management CLI. Authenticate your caller using your existing API-token or OAuth flow, then evaluate flags with the server-side Node.js SDK. Do not embed a Reflag secret SDK key or a Management API key in a distributed CLI. ## Evaluate on your backend @@ -31,7 +31,7 @@ export async function getCliAccess(context: Context) { Call `getCliAccess()` after authentication and return only the values your CLI needs. This registers checks for these requested roots. Diagnostic APIs are not a substitute for application reads. -The JSON response contains direct values, not flag wrappers: +The JSON response contains the flag values: ```json { @@ -68,4 +68,6 @@ export async function recordExport(context: Context) { } ``` -There is no `getFlag(...).track()` wrapper method in v2. Initialize the client once per process and use its normal lifecycle/flush handling for short-lived server processes. See [Node SDK v2](../supported-languages/node-sdk/README.md) and the [migration guide](../supported-languages/migrating-from-v1.md). +Initialize the client once per process and flush queued events before your server process exits. See the [Node.js SDK](../supported-languages/node-sdk/README.md) for lifecycle options. + +Using v1? [Legacy docs](../legacy/v1/README.md) · [Upgrade guide](../supported-languages/migrating-from-v1.md). diff --git a/product-handbook/anonymous-users.md b/product-handbook/anonymous-users.md index 39d6654..cad346e 100644 --- a/product-handbook/anonymous-users.md +++ b/product-handbook/anonymous-users.md @@ -1,5 +1,5 @@ --- -description: Use SDK v2 with anonymous users and optional company context. +description: Use Reflag with anonymous users and optional company context. --- # Anonymous users @@ -82,4 +82,4 @@ export function App() { {% endtab %} {% endtabs %} -A browser's company ID is not an authorization boundary. Enforce sensitive access on your authenticated server, using context derived from your own session or API-token lookup. See [Node SDK v2](../supported-languages/node-sdk/README.md) and [React SDK v2](../supported-languages/react-sdk/README.md) for complete setup. +A browser's company ID is not an authorization boundary. Enforce sensitive access on your authenticated server, using context derived from your own session or API-token lookup. See the [Node.js SDK](../supported-languages/node-sdk/README.md) and [React SDK](../supported-languages/react-sdk/README.md) for complete setup. diff --git a/product-handbook/feature-entitlements/README.md b/product-handbook/feature-entitlements/README.md index 3cf4f7b..2b6b241 100644 --- a/product-handbook/feature-entitlements/README.md +++ b/product-handbook/feature-entitlements/README.md @@ -121,7 +121,7 @@ Send usage metrics to Reflag using company attributes. For example, you can send the company's current usage metrics to Reflag at an hourly or daily interval. ```ts -// On an initialized Browser SDK v2 client: +// On an initialized Browser SDK client: await reflag.updateCompany({ apiRequestsCurrentMonth: 793 }); ``` diff --git a/product-handbook/launch-monitor/README.md b/product-handbook/launch-monitor/README.md index 0c67b6f..faf5cab 100644 --- a/product-handbook/launch-monitor/README.md +++ b/product-handbook/launch-monitor/README.md @@ -40,7 +40,7 @@ You can collect end-user feedback on new flag rollouts to catch and fix issues f Configure adoption rules to match the usage event name you send. Reading a flag registers a check; tracking usage is a separate operation. -Here's a brief example using the [Reflag React SDK v2](../../supported-languages/react-sdk/README.md) to collect feedback: +Here's a brief example using the [Reflag React SDK](../../supported-languages/react-sdk/README.md) to collect feedback: ```tsx import { useFlag, useRequestFeedback } from "@reflag/react-sdk"; diff --git a/product-handbook/launch-monitor/give-feedback-button.md b/product-handbook/launch-monitor/give-feedback-button.md index dc561b2..426cdcc 100644 --- a/product-handbook/launch-monitor/give-feedback-button.md +++ b/product-handbook/launch-monitor/give-feedback-button.md @@ -1,5 +1,5 @@ --- -description: Add a feedback button with the React SDK v2 feedback hook. +description: Add a feedback button with the React SDK feedback hook. --- # Give feedback button @@ -30,4 +30,4 @@ export function StartHuddleButton() { } ``` -Render this component inside a [React SDK v2 provider](../../supported-languages/react-sdk/README.md) with the appropriate user/company context. Configure adoption rules to match the event you track. For widget positioning, translations, styling, or your own UI, see [Browser feedback](../../supported-languages/browser-sdk/feedback.md). +Render this component inside a [React SDK provider](../../supported-languages/react-sdk/README.md) with the appropriate user/company context. Configure adoption rules to match the event you track. For widget positioning, translations, styling, or your own UI, see [Browser feedback](../../supported-languages/browser-sdk/feedback.md). diff --git a/product-handbook/remote-config.md b/product-handbook/remote-config.md index cc4ea7b..9dbe225 100644 --- a/product-handbook/remote-config.md +++ b/product-handbook/remote-config.md @@ -10,7 +10,7 @@ Use a **Multivariate flag** when different users or companies need different con A value can be an object, array, string, number, Boolean, or `null`. There are no reserved application fields: names such as `model`, `config`, `payload`, or `enabled` are ordinary data that you choose. -For example, configure `assistant-settings` with variants containing different model settings, then read it with React SDK v2: +For example, configure `assistant-settings` with variants containing different model settings, then read it with the React SDK: ```tsx import { useFlag } from "@reflag/react-sdk"; @@ -31,13 +31,13 @@ export function AssistantSettings() { } ``` -The second argument is the application's fallback value, not hook options. A bare `useFlag("assistant-settings")` is a Boolean read, even if the flag is Multivariate. Supply an appropriate default for a JSON read; use explicit `null` if you need arbitrary JSON and will narrow the result yourself. +The second argument is the application's fallback value. A bare `useFlag("assistant-settings")` is a Boolean read, even if the flag is Multivariate. Supply an appropriate default for a JSON read; use explicit `null` if you need arbitrary JSON and will narrow the result yourself. ## Config values Each environment's definition contains: -- **Variants:** unique keys and their JSON values. The SDK returns the selected **value**, not the variant key or a wrapper. +- **Variants:** unique keys and their JSON values. The SDK returns the selected variant's **value**. - **Specific targets:** explicit user/company assignments to variants. - **Ordered rules:** filters and results, including percentage distributions. - **Default variant:** the authored selection when no more-specific target or applicable rule selects a variant. @@ -86,6 +86,6 @@ Combine a Boolean entitlement such as `assistant-enabled` with a separate settin 1. Create a **Multivariate** flag in an app where Multivariate support is available. 2. Open its **Variants** tab and configure variants, specific targets, rules, and the default for the selected environment. 3. Save, then configure and verify any other environments separately. -4. Read the value with matching [SDK v2](../supported-languages/overview.md) packages and a positional default. +4. Read the value with a [Reflag SDK](../supported-languages/overview.md) and a positional default. -Existing v1 Boolean flags with an independent remote-config payload do **not** automatically become Multivariate flags. Plan their authored-data migration explicitly; upgrading an SDK does not copy or reinterpret old payloads. See the [v1 → v2 migration guide](../supported-languages/migrating-from-v1.md). +Using v1? [Legacy docs](../legacy/v1/README.md) · [Upgrade guide](../supported-languages/migrating-from-v1.md). diff --git a/product-handbook/service-resiliency.md b/product-handbook/service-resiliency.md index 30e836d..9f8831c 100644 --- a/product-handbook/service-resiliency.md +++ b/product-handbook/service-resiliency.md @@ -57,9 +57,9 @@ flowchart LR ## Recommended production setup -1. Evaluate flags on the server with the [Node.js SDK v2](../supported-languages/node-sdk/README.md). +1. Evaluate flags on the server with the [Node.js SDK](../supported-languages/node-sdk/README.md). 2. Configure a [`flagsFallbackProvider`](../supported-languages/node-sdk/README.md#fallback-providers) so fresh server processes can initialize from saved flag definitions when Reflag cannot be reached. -3. Use [`getFlagsForBootstrap()`](../supported-languages/node-sdk/README.md#bootstrap-state) on the server and a matching v2 bootstrapped client provider in React, Vue, or the Browser SDK. +3. Use [`getFlagsForBootstrap()`](../supported-languages/node-sdk/README.md#bootstrap-state) on the server and a bootstrapped client provider in React, Vue, or the Browser SDK. 4. If your client SDK supports caching, tune it based on how long your app can tolerate stale flags. 5. Test the disruption path in staging: block access to Reflag, start a fresh server process, and confirm it initializes from fallback storage and the client renders from bootstrapped flags. @@ -90,19 +90,19 @@ Use the file provider for single-server deployments only when the disk persists Choose fallback storage based on where your application runs. The storage should be reachable whenever your application is reachable, so prefer storage in the same cloud provider, region, or network as the application deployment that will use it. If an outage affects Reflag's infrastructure but your application is still running elsewhere, your application can still load the saved snapshot. If the same provider or region outage also takes down your application, fallback storage cannot help until your application environment is available again. -For built-in providers and the v2 snapshot contract, see the [fallback provider docs](../supported-languages/node-sdk/README.md#fallback-providers). V1 snapshots cannot initialize a v2 collection cache; built-in storage uses isolated v2 keys. +See the [fallback provider docs](../supported-languages/node-sdk/README.md#fallback-providers) for built-in storage options and the snapshot format. ## Bootstrapped flags Bootstrapping lets your server evaluate flags and pass the server-evaluated state to your client-side application. The client can render immediately from that state instead of depending on an initial request to Reflag. -Use [`getFlagsForBootstrap()`](../supported-languages/node-sdk/README.md#bootstrap-state) in Node SDK v2 together with the matching v2 bootstrapping APIs: +Use [`getFlagsForBootstrap()`](../supported-languages/node-sdk/README.md#bootstrap-state) in the Node.js SDK together with your client SDK's bootstrapping API: * [React SDK](../supported-languages/react-sdk/README.md#bootstrap-and-ssr): `ReflagBootstrappedProvider` * [Vue SDK](../supported-languages/vue-sdk/README.md#bootstrap): `ReflagBootstrappedProvider` * [Browser SDK](../supported-languages/browser-sdk/README.md#server-bootstrap): `bootstrappedState` -Pass the entire protocol-v2 envelope, not only its `flags` property. React Native and the OpenFeature providers retain their independently supported contracts. Do not feed Node v2 bootstrap into a v1 consumer; use the [legacy Node SDK](../legacy/v1/node-sdk/README.md) with v1 consumers until their coordinated migration. +Pass the entire bootstrap envelope, including context and selection metadata. React Native and OpenFeature have their own compatibility requirements; follow their SDK documentation. Bootstrapping is the recommended client setup for high-availability applications because the first render depends on your application server response, not on the client's ability to reach Reflag. Combined with server-side local evaluation and `flagsFallbackProvider`, it lets end users continue receiving evaluated flags during a Reflag service disruption. @@ -115,3 +115,5 @@ If you enable live client-side flag updates after bootstrapping, the client refr After a client SDK has loaded flags, it keeps recent flag state in memory so temporary network failures do not stop flag usage. Browser-based SDKs can also cache flag state across page loads. Tune cache behavior with options such as `staleTimeMs`, `staleWhileRevalidate`, and `expireTimeMs`. Client caching is a useful safety net for client-side evaluation. For applications that need resilience through server restarts and first render, combine server-side evaluation, fallback storage, and bootstrapping. + +Using v1? [Legacy docs](../legacy/v1/README.md) · [Upgrade guide](../supported-languages/migrating-from-v1.md). diff --git a/product-handbook/type-safety.md b/product-handbook/type-safety.md index 815a98b..205cd7f 100644 --- a/product-handbook/type-safety.md +++ b/product-handbook/type-safety.md @@ -1,10 +1,10 @@ --- -description: Register flag keys and direct-value schemas with SDK v2 and CLI 2. +description: Register flag keys and schemas with the Reflag SDKs and CLI. --- # Type safety -Reflag SDK v2 can infer a direct return type from the default you pass, without a generated file. Registering your flag schemas also catches misspelled keys and incompatible non-null defaults. +The Reflag SDKs infer return types from the defaults you pass, without a generated file. Registering your flag schemas also catches misspelled keys and incompatible non-null defaults. ```tsx import { useFlag } from "@reflag/react-sdk"; @@ -19,10 +19,10 @@ The fallback determines the widened return type: `512` becomes `number`, not the ## Set up type safety for flags -Use **CLI 2 with Node/React/Vue SDK v2**. Keep CLI 1 with v1 applications. CLI 2 and the SDK v2 packages must be available before using these installation commands; a staging server deployment alone does not release them. +Install the Reflag CLI and generate declarations for your flags: ```sh -npm install --save-dev @reflag/cli@2 +npm install --save-dev @reflag/cli npx reflag init npx reflag flags types ``` @@ -82,4 +82,6 @@ Store an authorized [Management API key](../api/api-access.md) in your CI secret REFLAG_API_KEY: ${{ secrets.REFLAG_CI_API_KEY }} ``` -Install CLI 2 from your lockfile before running this step. The command is **`reflag flags types`**, not `reflag types generate` or `reflag flags generate`. See the [SDK migration guide](../supported-languages/migrating-from-v1.md) before replacing legacy wrapper-shaped declarations. +Install the CLI from your lockfile before running this step. + +Using v1? [Legacy docs](../legacy/v1/README.md) · [Upgrade guide](../supported-languages/migrating-from-v1.md). diff --git a/sdk/@reflag/browser-sdk/README.md b/sdk/@reflag/browser-sdk/README.md index 5c49b80..69ea825 100644 --- a/sdk/@reflag/browser-sdk/README.md +++ b/sdk/@reflag/browser-sdk/README.md @@ -13,22 +13,16 @@ pagination: visible: true --- -{% hint style="info" %} -**Protocol v2.** [Legacy v1 documentation](../../../legacy/v1/browser-sdk/README.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) - -**Prerelease source documentation.** The installation examples target major 2; use them only when the matching SDK/CLI packages are available. A server rollout alone does not publish npm packages. - -Generated from [`@reflag/browser-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk); SDK READMEs and code comments remain the source of truth. -{% endhint %} - -# Reflag Browser SDK v2 +# Reflag Browser SDK Client-side feature flags and JSON values for [Reflag](https://reflag.com). -> This is a breaking v2 prerelease. It requires the v2 evaluated-flags/check protocol on the server. Do not switch existing v1 applications or bootstrap consumers without coordinating that upgrade. Nothing in this branch publishes or deploys the SDK/server. - ## Get started +```sh +npm install @reflag/browser-sdk +``` + ```ts import { ReflagClient } from "@reflag/browser-sdk"; @@ -51,7 +45,7 @@ if (enabled) { Use only a **publishable** key in a browser. Secret keys belong on your server. -## Direct-value reads +## Read flags ```ts reflag.getFlag("release"); // boolean; missing/mismatched -> false @@ -68,11 +62,11 @@ reflag.getFlag("nullable-settings", null); // FlagValue (arbitrary JSON) - Object fields and array elements are **not schema-validated**. Validate untrusted/nested payloads in your application. - Values and defaults are returned as independent mutable copies. There are no reserved JSON property names. -`getFlags()` returns a direct-value record (entries may be undefined) and registers checks for its returned roots. `getFlagResults()` returns owned evaluated diagnostics **without checks**; it is intended for tooling, not ordinary application reads. `getFlagsForBootstrap()` serializes protocol-v2 evaluated state without checks. +`getFlags()` returns a direct-value record (entries may be undefined) and registers checks for its returned roots. `getFlagResults()` returns owned evaluated diagnostics **without checks**; it is intended for tooling, not ordinary application reads. `getFlagsForBootstrap()` serializes evaluated state without checks. ## Checks and delivery -Calling a getter registers a requested-root check immediately, even if its return value is ignored. There are no `.isEnabled`, `.config`, `.value` or flag `.track()` wrappers. Delivery remains buffered through `/bulk` and identity-aware rate-limited. +Reading a flag registers an exposure check, even if its return value is ignored. Checks are buffered, sent through `/bulk`, and rate-limited per identity. A selected check carries the authored selected key as `evalResult`, its `sourceVersionId` and the available snapshot `flagStateVersion`. Payload equality is not identity: equal-valued selections or segment-only snapshot changes remain distinguishable on subsequent reads. Defaults, category mismatches, local overrides and static fallback values do not fabricate authored selections. Diagnostics and bootstrap serialization generate no checks. The server evaluates dependencies; fetching their results does not itself register reads. @@ -93,7 +87,7 @@ await reflag.refresh(); `setContext()` replaces the context; update methods shallow-merge their section. User/company sections require IDs, including valid numeric zero. Context supports nested JSON and arrays. A context change clears the old context's values while fetching; stale/in-flight responses cannot replace a newer context or snapshot. -Values come from `GET /flags/evaluated`, not legacy `/features/evaluated`. Server evaluation retains the complete internal graph and authorized public roots. The Browser SDK does not cache dependency evaluations of its own. +Values come from `GET /flags/evaluated`. Server evaluation retains the complete internal graph and authorized public roots. The Browser SDK does not cache dependency evaluations of its own. Constructor options include: @@ -112,7 +106,7 @@ Constructor options include: | `trackingQueue` | Buffered-delivery `flushDelayMs` and `maxSize` | | `logger`, `toolbar`, `feedback` | Logging, Boolean override toolbar and feedback options | -Evaluated cache and override storage use isolated v2 keys. V1 cache entries are never interpreted as v2 values. Malformed refreshes leave known-good state intact. Valid saved v2 selections retain their real provenance on restore. There is no automatic periodic HTTP fallback after an SSE failure; manual refresh/context updates remain available. +Evaluated flags and overrides are cached separately. Malformed refreshes leave known-good state intact. Valid saved selections retain their provenance on restore. There is no automatic periodic HTTP fallback after an SSE failure; manual refresh/context updates remain available. ## Overrides and toolbar @@ -127,7 +121,7 @@ Overrides apply after server evaluation and do not rewrite authored dependency r ## Server bootstrap -Generate the full payload with **Node SDK v2** on your server: +Generate the payload with the **Node.js SDK** on your server: ```ts const bootstrappedState = serverClient.getFlagsForBootstrap(context); @@ -140,7 +134,7 @@ await reflag.initialize(); const enabled = reflag.getFlag("release"); ``` -The payload includes `protocolVersion: 2`, context, evaluated diagnostics/selections and an optional snapshot version. V1 payloads and the old `bootstrappedFlags` option are rejected. Preserve the entire envelope; do not pass just its `flags` property. A version is required for bootstrapped live updates. Never embed secrets or server-only context in public bootstrap data. Later refreshes use browser-visible context and can differ from server-only evaluation; disable live updates when that is inappropriate. +The payload includes `protocolVersion: 2`, context, evaluated diagnostics/selections and an optional snapshot version. Pass the entire envelope as `bootstrappedState`, including its context and selection metadata. A version is required for bootstrapped live updates. Never embed secrets or server-only context in public bootstrap data. Later refreshes use browser-visible context and can differ from server-only evaluation; disable live updates when that is inappropriate. ## End-user opt-in @@ -153,7 +147,7 @@ await reflag.setOptIn("huddles", { optedIn: false, scope: "company" }); The list contains presentation/membership metadata (`key`, `name`, `description`, `isEnabled`, `userOptedIn`, `companyOptedIn`, `isOptedIn`); this is not the ordinary flag getter API. User/company grants remain independent. The selected scope requires its ID. Successful mutations wait for versioned evaluation and membership confirmation. -Metadata arrives with ordinary `/flags/evaluated` responses and is cached with the evaluated snapshot. Bootstrapped clients whose snapshot lacks metadata fetch it on demand from the same v2 endpoint, without replacing server-derived values or provenance with browser-context evaluations. Loading settles on success or failure, including an empty list. Opt-in mutations confirm values and membership together in one versioned refresh. `optInFlagsLoadingUpdated` and `flagsUpdated` support UI subscriptions. +Metadata arrives with ordinary `/flags/evaluated` responses and is cached with the evaluated snapshot. Bootstrapped clients whose snapshot lacks metadata fetch it on demand from the same endpoint, without replacing server-derived values or provenance with browser-context evaluations. Loading settles on success or failure, including an empty list. Opt-in mutations confirm values and membership together in one versioned refresh. `optInFlagsLoadingUpdated` and `flagsUpdated` support UI subscriptions. ## Tracking, feedback and events @@ -161,11 +155,4 @@ Use `track(eventName, attributes?)`, `feedback(payload)` and `requestFeedback({ `on(event, handler)` returns an unsubscribe function. Events include `stateUpdated`, `flagsUpdated` (evaluated diagnostics), `check`, `track`, `user`, `company` and `optInFlagsLoadingUpdated`. -## Migration from v1 - -- Replace `getFlag(key).isEnabled` with `getFlag(key)`. -- Replace legacy remote config access with a separately authored multivariate flag and a positional default. Legacy config is **not** automatically converted into v2 values. -- Move flag `.track()` / `.requestFeedback()` calls to ordinary client methods. -- Replace wrapper overrides with `setFlagOverride(key, value)`; undefined clears, null is a value. -- `getFlags()` now returns values and registers checks. Tooling should use `getFlagResults()`. -- Upgrade both ends of bootstrap to v2. Old Browser/framework clients remain incompatible with v2 bootstrap. +Using v1? [Legacy docs](../../../legacy/v1/browser-sdk/README.md) · [Upgrade guide](../../../supported-languages/migrating-from-v1.md). diff --git a/sdk/@reflag/browser-sdk/globals.md b/sdk/@reflag/browser-sdk/globals.md index 8f844e2..bbfeb2c 100644 --- a/sdk/@reflag/browser-sdk/globals.md +++ b/sdk/@reflag/browser-sdk/globals.md @@ -13,14 +13,6 @@ pagination: visible: true --- -{% hint style="info" %} -**Protocol v2.** [Legacy v1 documentation](../../../legacy/v1/browser-sdk/globals.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) - -**Prerelease source documentation.** The installation examples target major 2; use them only when the matching SDK/CLI packages are available. A server rollout alone does not publish npm packages. - -Generated from [`@reflag/browser-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/browser-sdk); SDK READMEs and code comments remain the source of truth. -{% endhint %} - # @reflag/browser-sdk ## Classes @@ -5260,3 +5252,5 @@ These events will be propagated to the feedback dialog #### See [https://developer.mozilla.org/en-US/docs/Web/API/Element#events](https://developer.mozilla.org/en-US/docs/Web/API/Element#events) + +Using v1? [Legacy docs](../../../legacy/v1/browser-sdk/globals.md) · [Upgrade guide](../../../supported-languages/migrating-from-v1.md). diff --git a/sdk/@reflag/node-sdk/README.md b/sdk/@reflag/node-sdk/README.md index fa924c1..fd9c583 100644 --- a/sdk/@reflag/node-sdk/README.md +++ b/sdk/@reflag/node-sdk/README.md @@ -13,24 +13,14 @@ pagination: visible: true --- -{% hint style="info" %} -**Protocol v2.** [Legacy v1 documentation](../../../legacy/v1/node-sdk/README.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) - -**Prerelease source documentation.** The installation examples target major 2; use them only when the matching SDK/CLI packages are available. A server rollout alone does not publish npm packages. - -Generated from [`@reflag/node-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/0809be2b95f43fa1785c6b7b188c03ac8fd40965/packages/node-sdk); SDK READMEs and code comments remain the source of truth. -{% endhint %} - # Reflag Node.js SDK Server-side Boolean and multivariate flag values for [Reflag](https://reflag.com). -> This branch implements the breaking v2 API. It requires the collection-capable evaluator, the v2 `/flags` endpoint, and compatible variant-key check ingestion. It has not been published or deployed. - ## Installation and initialization ```sh -yarn add @reflag/node-sdk@2 +yarn add @reflag/node-sdk ``` Create one client per process and initialize it before reading flags. Obtain your environment's secret key from Reflag's environment settings; complete flag definitions must remain server-side. @@ -44,7 +34,7 @@ export const reflag = new ReflagClient({ await reflag.initialize(); ``` -## Direct values, immediate checks +## Read flags ```ts const context = { @@ -57,7 +47,7 @@ const model = reflag.getFlag(context, "model", "quick"); // string const limits = reflag.getFlag(context, "limits", { maxItems: 10 }); // { maxItems: number } ``` -**`getFlag()` returns the value itself**, not a flag object. There is no `.value`, `.isEnabled`, `.config`, or flag `.track()` wrapper. Without a default it is a Boolean read: unavailable or non-Boolean values return `false`, never a truthy object. With a positional default, missing values use that default. Valid `false`, `0`, empty strings, arrays, and objects are preserved rather than replaced by truthiness checks. +`getFlag()` returns a Boolean, string, number, array, object, or null. Without a default it is a Boolean read: unavailable or non-Boolean values return `false`. With a positional default, missing values use that default. Valid `false`, `0`, empty strings, arrays, and objects are preserved rather than replaced by truthiness checks. Non-null defaults specify the expected JSON category: Boolean, number, string, array, or object. A category mismatch logs a warning without the payload and returns the default. This is not nested payload validation: object properties and array elements must still match your authored schema. Use an explicit `null` default for arbitrary JSON or nullable/off selections, and narrow the result before accessing object fields: @@ -82,7 +72,7 @@ Each call immediately registers a check for the requested root, including when y } ``` -Boolean selections send `"true"` / `"false"` while returning Boolean values. Caller defaults, including category-mismatch defaults, do not claim an authored selection: their checks omit `evalResult` and `sourceVersionId`. Check deduplication includes normalized context, selection identity, root version, and snapshot version. Equal-valued variants are not interchangeable selections. Batch `getFlags()` remains a raw value record, without per-root caller defaults; unavailable batch values may be `undefined`. +Boolean selections send `"true"` / `"false"` while returning Boolean values. Caller defaults, including category-mismatch defaults, do not claim an authored selection: their checks omit `evalResult` and `sourceVersionId`. Check deduplication includes normalized context, selection identity, root version, and snapshot version. Equal-valued variants are not interchangeable selections. `getFlags()` returns a record of flag values, without per-root caller defaults; unavailable batch values may be `undefined`. ```ts const values = reflag.getFlags(context); // value record; checks each returned root @@ -137,7 +127,7 @@ await client.initialize(); Live state is primary. When the initial live fetch fails, the SDK can load a saved complete collection. Later outages retain the in-memory graph rather than reloading older fallback state. Accepted live snapshots are saved in order; `flush()` also waits for pending saves. -Available providers: `static`, `file`, `redis`, `s3`, and `gcs`, plus custom `FlagsFallbackProvider` implementations. A v2 snapshot contains: +Available providers: `static`, `file`, `redis`, `s3`, and `gcs`, plus custom `FlagsFallbackProvider` implementations. A snapshot contains: ```ts { @@ -149,7 +139,7 @@ Available providers: `static`, `file`, `redis`, `s3`, and `gcs`, plus custom `Fl } ``` -V1 flag-only snapshots are incompatible and are not automatically expanded or converted. Built-in files/S3/GCS objects use `flags-fallback-v2-.json`; Redis uses `:v2:`. This keeps v1 and v2 processes from overwriting each other's fallback state. +Built-in files/S3/GCS objects use `flags-fallback-v2-.json`; Redis uses `:v2:`. A static fallback can contain any JSON values: @@ -196,7 +186,7 @@ const model = reflag.getFlag(context, "model", "quick"); // string const models = reflag.getFlags(context); // models.model: "quick" | "quality" | undefined ``` -Augmentation rejects defaults with the wrong category, missing required properties, or incompatible nested types. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request, and bare/`undefined` reads still return Boolean. Return types continue to be inferred and widened from the default; generated types do not add nested runtime validation. The v2 CLI generates direct-value schemas from current production-environment variants. Regenerate old CLI wrapper declarations when migrating. Both destructuring `.isEnabled` and accessing it through an assigned singular value fail type checking, including without generated declarations. See the Express example for a typed direct-value integration. +Augmentation rejects defaults with the wrong category, missing required properties, or incompatible nested types. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request, and bare/`undefined` reads still return Boolean. Return types continue to be inferred and widened from the default; generated types do not add nested runtime validation. The Reflag CLI generates schemas from current production-environment variants. See the Express example for a typed integration. ## Bootstrap state @@ -209,7 +199,7 @@ const bootstrap = reflag.getFlagsForBootstrap(context); Bootstrap uses batch evaluation and preserves selection metadata and raw context. It does **not** register browser checks. Local overrides/value-only fallbacks carry their values without fabricated authored-selection metadata. -**This is a v2 bootstrap contract, not the existing v1 Browser/React/Vue bootstrap shape.** Those consumers require a coordinated migration before accepting this state. Likewise, the current OpenFeature provider deliberately remains on published Node SDK v1 until its separate migration. +Pass the entire envelope to the Browser, React or Vue SDK's bootstrap option, not just its `flags` property. Use your framework's safe serialization mechanism and never expose secret keys or server-only context in public bootstrap data. ## Remote evaluation @@ -229,7 +219,7 @@ const values = await reflag.getFlagsRemote("user-1", "acme", { }); ``` -These methods use `/flags/evaluated` and return direct values. Singular remote reads use the same defaults, category checks, and JSON validation as local reads. The root `getFlagRemote(key, defaultValue, userId?, companyId?, context?)` places the default second; use `undefined` for an implicit Boolean read when passing explicit IDs. This moves the old positional IDs one place to the right. `getFlagsRemote()` keeps its existing argument order and returns a raw value record. +These methods use `/flags/evaluated` and return direct values. Singular remote reads use the same defaults, category checks, and JSON validation as local reads. The root `getFlagRemote(key, defaultValue, userId?, companyId?, context?)` places the default second; use `undefined` for an implicit Boolean read when passing explicit IDs. `getFlagsRemote(userId?, companyId?, context?)` returns a record of flag values. Each requested singular root registers a check, including a default after a failed/missing remote evaluation, unless tracking is disabled. Only accepted authored selections retain the server's selection/version metadata. Explicit IDs, including numeric zero, take precedence over IDs in additional context. Stored attribute updates are asynchronous; remote evaluation need not immediately observe a just-sent update. @@ -248,3 +238,5 @@ Invalid options/context or non-JSON defaults can throw. Network or definition-re ## License MIT License. Copyright (c) 2025 Bucket ApS. + +Using v1? [Legacy docs](../../../legacy/v1/node-sdk/README.md) · [Upgrade guide](../../../supported-languages/migrating-from-v1.md). diff --git a/sdk/@reflag/node-sdk/globals.md b/sdk/@reflag/node-sdk/globals.md index 49a4887..d39913d 100644 --- a/sdk/@reflag/node-sdk/globals.md +++ b/sdk/@reflag/node-sdk/globals.md @@ -13,14 +13,6 @@ pagination: visible: true --- -{% hint style="info" %} -**Protocol v2.** [Legacy v1 documentation](../../../legacy/v1/node-sdk/globals.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) - -**Prerelease source documentation.** The installation examples target major 2; use them only when the matching SDK/CLI packages are available. A server rollout alone does not publish npm packages. - -Generated from [`@reflag/node-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/0809be2b95f43fa1785c6b7b188c03ac8fd40965/packages/node-sdk); SDK READMEs and code comments remain the source of truth. -{% endhint %} - # @reflag/node-sdk ## Classes @@ -5593,3 +5585,5 @@ createStaticFallbackProvider
+ +Using v1? [Legacy docs](../../../legacy/v1/node-sdk/globals.md) · [Upgrade guide](../../../supported-languages/migrating-from-v1.md). diff --git a/sdk/@reflag/react-sdk/README.md b/sdk/@reflag/react-sdk/README.md index 444a7df..b5c2e4b 100644 --- a/sdk/@reflag/react-sdk/README.md +++ b/sdk/@reflag/react-sdk/README.md @@ -13,22 +13,16 @@ pagination: visible: true --- -{% hint style="info" %} -**Protocol v2.** [Legacy v1 documentation](../../../legacy/v1/react-sdk/README.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) +# Reflag React SDK -**Prerelease source documentation.** The installation examples target major 2; use them only when the matching SDK/CLI packages are available. A server rollout alone does not publish npm packages. - -Generated from [`@reflag/react-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/react-sdk); SDK READMEs and code comments remain the source of truth. -{% endhint %} - -# Reflag React SDK v2 - -Direct-value feature flags for React, backed by [Browser SDK v2](../../../supported-languages/browser-sdk/README.md). - -> Breaking prerelease: requires compatible v2 server endpoints and **Node SDK v2** for bootstrap. The v2 CLI generates direct-value declarations; regenerate legacy wrapper-shaped output when migrating. Useful default-based inference does not require generated declarations. React Native remains on published React/Browser v1 in this repository. +Feature flags and JSON configuration for React, backed by the [Browser SDK](../../../supported-languages/browser-sdk/README.md). ## Setup +```sh +npm install @reflag/react-sdk +``` + ```tsx import { ReflagProvider } from "@reflag/react-sdk"; @@ -74,7 +68,7 @@ useFlag("nullable-settings", null); // FlagValue: arbitrary JSON Non-null defaults enforce only the top-level JSON category (Boolean/number/string/array/object). Mismatches return the default and warn without logging the payload. Explicit null accepts authored null and all other JSON; missing values return null. Accepted false, zero and empty strings are preserved. Nested fields/elements are not schema-validated. Values/defaults are independent mutable copies; readonly defaults are accepted. -`useFlag` never suspends. Its second argument is **payload data**, not `{ suspense: ... }` options; ordinary JSON has no reserved keys. Use the dedicated hook below for suspension. Use `useIsLoading()` or the provider's `loadingComponent` when you need an explicit loading UI. +`useFlag` returns immediately, using the default while flags load. Use `useIsLoading()` or the provider's `loadingComponent` for an explicit loading UI, or `useFlagSuspense()` to wait with React Suspense. ## `useFlagSuspense(key, defaultValue?)` @@ -94,13 +88,13 @@ function Model() { This hook has the same Boolean/default-based return types. It waits for initialization before reading. Once initialization settles, missing flags return their default rather than suspending forever. Bootstrap values can render immediately. Suspended attempts do not register a root read before data is ready. -The provider's existing `suspense` prop continues to configure **`useOptInFlags` only**. It does not change `useFlag`; `useFlagSuspense` is explicit. +The provider's `suspense` prop configures **`useOptInFlags` only**. Use `useFlagSuspense` for flag reads with Suspense. ## Checks and usage tracking A completed getter/hook read registers its requested-root check immediately, even if the value is ignored. Actual delivery remains buffered and identity-aware rate-limited by the Browser SDK. Checks contain selected variant/source/snapshot identity, not payloads. Defaults, category mismatches and local overrides never invent authored selections. Diagnostic/bootstrap inspection registers no checks. -Application usage and feedback remain separate hooks: +Track application usage and collect feedback with these hooks: ```ts const track = useTrack(); @@ -125,11 +119,11 @@ declare module "@reflag/react-sdk" { } ``` -Registration constrains keys and checks non-null defaults against the registered value schema, including required and nested properties. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request; bare/`undefined` reads remain Boolean. The positional default still determines the widened return type, and generated declarations do not add nested runtime validation. The same rules apply to `useFlagSuspense`. The v2 CLI generates direct-value declarations from current production-environment variants; regenerate legacy wrapper declarations when migrating. +Registration constrains keys and checks non-null defaults against the registered value schema, including required and nested properties. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request; bare/`undefined` reads remain Boolean. The positional default still determines the widened return type, and generated declarations do not add nested runtime validation. The same rules apply to `useFlagSuspense`. The Reflag CLI can generate these declarations from current production-environment variants. ## Bootstrap and SSR -On the server, use Node SDK v2: +On the server, use the Node.js SDK: ```ts const flags = serverClient.getFlagsForBootstrap(context); @@ -145,9 +139,9 @@ import { ReflagBootstrappedProvider } from "@reflag/react-sdk";
; ``` -The envelope includes `protocolVersion: 2`, context, evaluated flag results and optional `flagStateVersion`. V1 bootstrap is rejected. Use a snapshot version for live updates; later refreshes use browser-visible context. Do not send secrets/server-only attributes to the browser. Disable live updates if later browser evaluation must not replace server-only results. +The envelope includes `protocolVersion: 2`, context, evaluated flag results and optional `flagStateVersion`. Use a snapshot version for live updates; later refreshes use browser-visible context. Do not send secrets/server-only attributes to the browser. Disable live updates if later browser evaluation must not replace server-only results. -For a pre-existing Browser v2 client, use ``. The provider does not own its lifecycle; initialize/stop externally, except that a suspending read can start on-demand initialization. +For an existing Browser SDK client, use ``. The provider does not own its lifecycle; initialize/stop externally, except that a suspending read can start on-demand initialization. ## Context, loading and events @@ -166,10 +160,8 @@ await setOptIn("huddles", { optedIn: true }); await setOptIn("huddles", { optedIn: false, scope: "company" }); ``` -Metadata arrives with the initial v2 evaluation for regular providers. Bootstrapped providers fetch missing metadata on demand from `/flags/evaluated` without replacing server-derived values. `isLoading` covers initialization and metadata retrieval; it settles on success or failure. Metadata presentation includes `isEnabled` and membership fields, separately from direct flag reads. User/company grants remain independent. Mutations confirm versioned evaluation and membership in a single refresh. +Metadata arrives with the initial evaluation for regular providers. Bootstrapped providers fetch missing metadata on demand from `/flags/evaluated` without replacing server-derived values. `isLoading` covers initialization and metadata retrieval; it settles on success or failure. Metadata presentation includes `isEnabled` and membership fields, separately from direct flag reads. User/company grants remain independent. Mutations confirm versioned evaluation and membership in a single refresh. `useOptInFlags({ suspense: true | false })` retains its own per-hook loading options and may inherit provider `suspense`. These options are unrelated to the positional payload defaults used by `useFlag` / `useFlagSuspense`. -## Migration from v1 - -Use `const enabled = useFlag(key)` instead of destructuring `.isEnabled`. Replace wrapper config access with an authored multivariate flag and positional default. Move `.track()` and `.requestFeedback()` to separate hooks. Replace `useFlag(key, { suspense: true })` with `useFlagSuspense(key)`, and use `useIsLoading()` instead of a flag wrapper's loading property. Upgrade Browser/server bootstrap together. Nothing here publishes the prerelease or deploys its required server changes. +Using v1? [Legacy docs](../../../legacy/v1/react-sdk/README.md) · [Upgrade guide](../../../supported-languages/migrating-from-v1.md). diff --git a/sdk/@reflag/react-sdk/globals.md b/sdk/@reflag/react-sdk/globals.md index 00376b8..eb9dd1c 100644 --- a/sdk/@reflag/react-sdk/globals.md +++ b/sdk/@reflag/react-sdk/globals.md @@ -13,14 +13,6 @@ pagination: visible: true --- -{% hint style="info" %} -**Protocol v2.** [Legacy v1 documentation](../../../legacy/v1/react-sdk/globals.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) - -**Prerelease source documentation.** The installation examples target major 2; use them only when the matching SDK/CLI packages are available. A server rollout alone does not publish npm packages. - -Generated from [`@reflag/react-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/react-sdk); SDK READMEs and code comments remain the source of truth. -{% endhint %} - # @reflag/react-sdk ## Interfaces @@ -2439,3 +2431,5 @@ updateUser({ optInHuddles: "true" }).then(() => console.log("Flags updated")); ### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +Using v1? [Legacy docs](../../../legacy/v1/react-sdk/globals.md) · [Upgrade guide](../../../supported-languages/migrating-from-v1.md). diff --git a/sdk/@reflag/vue-sdk/README.md b/sdk/@reflag/vue-sdk/README.md index 72195f2..d6ea85b 100644 --- a/sdk/@reflag/vue-sdk/README.md +++ b/sdk/@reflag/vue-sdk/README.md @@ -13,22 +13,16 @@ pagination: visible: true --- -{% hint style="info" %} -**Protocol v2.** [Legacy v1 documentation](../../../legacy/v1/vue-sdk/README.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) +# Reflag Vue SDK (beta) -**Prerelease source documentation.** The installation examples target major 2; use them only when the matching SDK/CLI packages are available. A server rollout alone does not publish npm packages. - -Generated from [`@reflag/vue-sdk@2.0.0-next.0`](https://github.com/reflagcom/javascript/tree/9f3a0ae027e386747a2d4cf7683a68dcab70b355/packages/vue-sdk); SDK READMEs and code comments remain the source of truth. -{% endhint %} - -# Reflag Vue SDK v2 (beta) - -Reactive direct-value flags for Vue 3, backed by [Browser SDK v2](../../../supported-languages/browser-sdk/README.md). - -> Breaking prerelease: requires the compatible v2 server protocol. Bootstrap must come from **Node SDK v2**, not v1. Generated declarations are optional; the v2 CLI supports `--format vue` and direct-value schemas. Regenerate legacy wrapper-shaped declarations when migrating. +Reactive feature flags and JSON configuration for Vue 3, backed by the [Browser SDK](../../../supported-languages/browser-sdk/README.md). ## Setup +```sh +npm install @reflag/vue-sdk +``` + ```vue \n[Source](https://github.com/reflagcom/javascript/blob/main/packages/${name}/README.md)\n`, + `---\nlayout: {}\n---\n# SDK\n\nSDK introduction.\n\n## Setup\n[Browser](../../_media/README.md)\n[Feedback](../../documents/browser-sdk/FEEDBACK.md)\n[Toolbar](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions)\nnpm install @reflag/${name}\nbun add @reflag/${name}\ndeno add npm:@reflag/${name}\nnpx @reflag/cli new\n\n[Source](https://github.com/reflagcom/javascript/blob/main/packages/${name}/README.md)\n`, ); put( path.join(source, `dist/docs/@reflag/${name}/globals.md`), @@ -100,7 +101,10 @@ test("v1 import owns only the archive, pins installers/CDN and routes SDK links assert.match(readme, /blob\/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\//); assert(readme.indexOf("---") < readme.indexOf("{% hint"), "Keep frontmatter first"); for (const [file, content] of files) - if (file.endsWith(".md")) assert.doesNotMatch(content.toString(), /generated from/i); + if (file.endsWith(".md")) { + assert.doesNotMatch(content.toString(), /generated from/i); + assert(!content.toString().includes(currentVersionNote)); + } const manifest = JSON.parse(files.get(".generated/sdk-docs/react-sdk/v1.json")); assert.equal(manifest.sourceCommit, options.commit); assert.equal(manifest.version, "1.0.0"); @@ -129,7 +133,7 @@ test("v2 sync cannot modify archived docs, navigation, settings or handwritten g ); }); -test("current docs use unpinned installs and one short footer even for prerelease sources", (t) => { +test("current docs retain the introduction, add one v2 scope line and keep unpinned installs", (t) => { const { options, source, put } = fixture(t); put( path.join(source, "packages/react-sdk/package.json"), @@ -143,7 +147,9 @@ test("current docs use unpinned installs and one short footer even for prereleas ]) { const content = files.get(file).toString(); checkCurrentPagePresentation(content, file); - assert(content.indexOf("# SDK") < content.indexOf("Using v1?")); + assert(content.indexOf("SDK introduction.") < content.indexOf(currentVersionNote)); + assert(content.indexOf(currentVersionNote) < content.indexOf("## Setup")); + assert(content.indexOf("## Setup") < content.indexOf("Using v1?")); assert.match(content, /npm install @reflag\/react-sdk\n/); assert.match(content, /npx @reflag\/cli new/); assert.match(content, /browser-sdk"><\/script>/); @@ -159,8 +165,32 @@ test("current docs use unpinned installs and one short footer even for prereleas test("presentation checks reject repeated or leading notices and major-pinned current installs", () => { const note = "Using v1? [Legacy docs](legacy.md) · [Upgrade guide](migration.md)."; - const page = `# SDK\n\nGet started.\n\n${note}\n`; + const page = `# SDK\n\nGet started.\n\n${currentVersionNote}\n\n## Setup\n\nInstall the SDK.\n\n${note}\n`; checkCurrentPagePresentation(page, "page.md"); + assert.throws( + () => checkCurrentPagePresentation(page.replace(currentVersionNote, ""), "page.md"), + /one SDK v2 scope note/, + ); + assert.throws( + () => checkCurrentPagePresentation(`${currentVersionNote}\n\n${page}`, "page.md"), + /one SDK v2 scope note/, + ); + assert.throws( + () => + checkCurrentPagePresentation( + `${currentVersionNote}\n\n${page.replace(currentVersionNote, "")}`, + "page.md", + ), + /in the introduction/, + ); + assert.throws( + () => + checkCurrentPagePresentation( + page.replace(`${currentVersionNote}\n\n## Setup`, `## Setup\n\n${currentVersionNote}`), + "page.md", + ), + /in the introduction/, + ); assert.throws(() => checkCurrentPagePresentation(`${note}\n\n# SDK\n`, "page.md"), /at the end/); assert.throws( () => checkCurrentPagePresentation(`${note}\n\n${page}`, "page.md"), @@ -186,6 +216,7 @@ test("independent Native references route to its pinned React/Browser major, not const readme = files.get("supported-languages/react-native-sdk/README.md").toString(); assert.match(readme, /legacy\/v1\/browser-sdk\/README.md/); assert.match(readme, /legacy\/v1\/react-sdk\/README.md/); + assert(!readme.includes(currentVersionNote)); assert(!files.has("supported-languages/react-sdk/README.md")); assert(!files.has("legacy/v1/react-sdk/README.md")); }); @@ -213,6 +244,15 @@ test("GitBook heading IDs preserve TypeDoc/generic deep links without changing c assert(rendered.includes("```md\n# Leave code alone\n```")); }); +test("the current-version line stays in the introduction without entering code fences", () => { + const content = "# SDK\n\nIntroduction.\n\n```md\n## Code example\n```\n\n## Setup\n"; + const rendered = anchorHeadings(content, { introNote: currentVersionNote }); + assert(rendered.includes("```md\n## Code example\n```")); + assert(rendered.indexOf("```\n\nThis documentation") > rendered.indexOf("## Code example")); + assert(rendered.indexOf(currentVersionNote) < rendered.indexOf("## Setup")); + assert.equal(rendered.split(currentVersionNote).length - 1, 1); +}); + test("GitBook keeps deep API-member and linked-section anchors without outlining every parameter label", () => { const rendered = anchorHeadings( "### Client\n#### Constructors\n##### getFlag()\n###### Parameters\n[Constructor](globals.md#constructors)\n", diff --git a/sdk/@reflag/browser-sdk/README.md b/sdk/@reflag/browser-sdk/README.md index 69ea825..2026972 100644 --- a/sdk/@reflag/browser-sdk/README.md +++ b/sdk/@reflag/browser-sdk/README.md @@ -17,6 +17,8 @@ pagination: Client-side feature flags and JSON values for [Reflag](https://reflag.com). +This documentation covers SDK v2. + ## Get started ```sh diff --git a/sdk/@reflag/browser-sdk/globals.md b/sdk/@reflag/browser-sdk/globals.md index bbfeb2c..0b4e6fc 100644 --- a/sdk/@reflag/browser-sdk/globals.md +++ b/sdk/@reflag/browser-sdk/globals.md @@ -15,6 +15,8 @@ pagination: # @reflag/browser-sdk +This documentation covers SDK v2. + ## Classes ### ReflagClient diff --git a/sdk/@reflag/node-sdk/README.md b/sdk/@reflag/node-sdk/README.md index fd9c583..ac9a01f 100644 --- a/sdk/@reflag/node-sdk/README.md +++ b/sdk/@reflag/node-sdk/README.md @@ -17,6 +17,8 @@ pagination: Server-side Boolean and multivariate flag values for [Reflag](https://reflag.com). +This documentation covers SDK v2. + ## Installation and initialization ```sh diff --git a/sdk/@reflag/node-sdk/globals.md b/sdk/@reflag/node-sdk/globals.md index d39913d..82a05a7 100644 --- a/sdk/@reflag/node-sdk/globals.md +++ b/sdk/@reflag/node-sdk/globals.md @@ -15,6 +15,8 @@ pagination: # @reflag/node-sdk +This documentation covers SDK v2. + ## Classes ### BoundReflagClient diff --git a/sdk/@reflag/react-sdk/README.md b/sdk/@reflag/react-sdk/README.md index b5c2e4b..cdf3a50 100644 --- a/sdk/@reflag/react-sdk/README.md +++ b/sdk/@reflag/react-sdk/README.md @@ -17,6 +17,8 @@ pagination: Feature flags and JSON configuration for React, backed by the [Browser SDK](../../../supported-languages/browser-sdk/README.md). +This documentation covers SDK v2. + ## Setup ```sh diff --git a/sdk/@reflag/react-sdk/globals.md b/sdk/@reflag/react-sdk/globals.md index eb9dd1c..4617119 100644 --- a/sdk/@reflag/react-sdk/globals.md +++ b/sdk/@reflag/react-sdk/globals.md @@ -15,6 +15,8 @@ pagination: # @reflag/react-sdk +This documentation covers SDK v2. + ## Interfaces ### CheckEvent diff --git a/sdk/@reflag/vue-sdk/README.md b/sdk/@reflag/vue-sdk/README.md index d6ea85b..04acebd 100644 --- a/sdk/@reflag/vue-sdk/README.md +++ b/sdk/@reflag/vue-sdk/README.md @@ -17,6 +17,8 @@ pagination: Reactive feature flags and JSON configuration for Vue 3, backed by the [Browser SDK](../../../supported-languages/browser-sdk/README.md). +This documentation covers SDK v2. + ## Setup ```sh diff --git a/sdk/@reflag/vue-sdk/globals.md b/sdk/@reflag/vue-sdk/globals.md index 998aea0..6e59f0e 100644 --- a/sdk/@reflag/vue-sdk/globals.md +++ b/sdk/@reflag/vue-sdk/globals.md @@ -15,6 +15,8 @@ pagination: # @reflag/vue-sdk +This documentation covers SDK v2. + ## Interfaces ### CheckEvent diff --git a/sdk/documents/browser-sdk/FEEDBACK.md b/sdk/documents/browser-sdk/FEEDBACK.md index bdc6f3a..20637a1 100644 --- a/sdk/documents/browser-sdk/FEEDBACK.md +++ b/sdk/documents/browser-sdk/FEEDBACK.md @@ -20,6 +20,8 @@ about particular flags. ![image](https://github.com/reflagcom/javascript/assets/34348/c387bac1-f2e2-4efd-9dda-5030d76f9532) +This documentation covers SDK v2. + ## Global feedback configuration The Reflag Browser SDK feedback UI is configured with reasonable defaults, diff --git a/sdk/documents/react-sdk/README.md b/sdk/documents/react-sdk/README.md index b5c2e4b..cdf3a50 100644 --- a/sdk/documents/react-sdk/README.md +++ b/sdk/documents/react-sdk/README.md @@ -17,6 +17,8 @@ pagination: Feature flags and JSON configuration for React, backed by the [Browser SDK](../../../supported-languages/browser-sdk/README.md). +This documentation covers SDK v2. + ## Setup ```sh diff --git a/supported-languages/browser-sdk/README.md b/supported-languages/browser-sdk/README.md index d6984ca..2724e7d 100644 --- a/supported-languages/browser-sdk/README.md +++ b/supported-languages/browser-sdk/README.md @@ -17,6 +17,8 @@ pagination: Client-side feature flags and JSON values for [Reflag](https://reflag.com). +This documentation covers SDK v2. + ## Get started ```sh diff --git a/supported-languages/browser-sdk/feedback.md b/supported-languages/browser-sdk/feedback.md index 583611d..24a1221 100644 --- a/supported-languages/browser-sdk/feedback.md +++ b/supported-languages/browser-sdk/feedback.md @@ -20,6 +20,8 @@ about particular flags. ![image](https://github.com/reflagcom/javascript/assets/34348/c387bac1-f2e2-4efd-9dda-5030d76f9532) +This documentation covers SDK v2. + ## Global feedback configuration The Reflag Browser SDK feedback UI is configured with reasonable defaults, diff --git a/supported-languages/browser-sdk/globals.md b/supported-languages/browser-sdk/globals.md index 1379c28..9580530 100644 --- a/supported-languages/browser-sdk/globals.md +++ b/supported-languages/browser-sdk/globals.md @@ -15,6 +15,8 @@ pagination: # @reflag/browser-sdk +This documentation covers SDK v2. + ## Classes ### ReflagClient diff --git a/supported-languages/next.js.md b/supported-languages/next.js.md index d3dd627..ff44c09 100644 --- a/supported-languages/next.js.md +++ b/supported-languages/next.js.md @@ -6,6 +6,8 @@ description: Use the Node.js and React SDKs with Next.js. Use the [Node.js SDK](node-sdk/README.md) to evaluate flags on the server and the [React SDK](react-sdk/README.md) in client components. +This documentation covers SDK v2. + ## Server-side rendering Create one client per server process. Share the initialization promise so concurrent requests do not create separate clients: diff --git a/supported-languages/node-sdk/README.md b/supported-languages/node-sdk/README.md index 04f1013..7d24cd9 100644 --- a/supported-languages/node-sdk/README.md +++ b/supported-languages/node-sdk/README.md @@ -17,6 +17,8 @@ pagination: Server-side Boolean and multivariate flag values for [Reflag](https://reflag.com). +This documentation covers SDK v2. + ## Installation and initialization ```sh diff --git a/supported-languages/node-sdk/globals.md b/supported-languages/node-sdk/globals.md index 61881b4..78244c1 100644 --- a/supported-languages/node-sdk/globals.md +++ b/supported-languages/node-sdk/globals.md @@ -15,6 +15,8 @@ pagination: # @reflag/node-sdk +This documentation covers SDK v2. + ## Classes ### BoundReflagClient diff --git a/supported-languages/react-sdk/README.md b/supported-languages/react-sdk/README.md index f64676d..f6d9af4 100644 --- a/supported-languages/react-sdk/README.md +++ b/supported-languages/react-sdk/README.md @@ -17,6 +17,8 @@ pagination: Feature flags and JSON configuration for React, backed by the [Browser SDK](../browser-sdk/README.md). +This documentation covers SDK v2. + ## Setup ```sh diff --git a/supported-languages/react-sdk/globals.md b/supported-languages/react-sdk/globals.md index 4e0016c..f41cc01 100644 --- a/supported-languages/react-sdk/globals.md +++ b/supported-languages/react-sdk/globals.md @@ -15,6 +15,8 @@ pagination: # @reflag/react-sdk +This documentation covers SDK v2. + ## Interfaces ### CheckEvent diff --git a/supported-languages/vue-sdk/README.md b/supported-languages/vue-sdk/README.md index 92fc9f8..ffa011a 100644 --- a/supported-languages/vue-sdk/README.md +++ b/supported-languages/vue-sdk/README.md @@ -17,6 +17,8 @@ pagination: Reactive feature flags and JSON configuration for Vue 3, backed by the [Browser SDK](../browser-sdk/README.md). +This documentation covers SDK v2. + ## Setup ```sh diff --git a/supported-languages/vue-sdk/globals.md b/supported-languages/vue-sdk/globals.md index c1414ae..52bb0ef 100644 --- a/supported-languages/vue-sdk/globals.md +++ b/supported-languages/vue-sdk/globals.md @@ -15,6 +15,8 @@ pagination: # @reflag/vue-sdk +This documentation covers SDK v2. + ## Interfaces ### CheckEvent From 90b2a5266c6d95ccf711e0772129330cce6a9cfa Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:46:29 +0000 Subject: [PATCH 08/18] docs: plain-language pass over SDK guides and shared pages - Regenerate Browser/React/Vue/Node guides from restructured source READMEs: shared task-based outline, implementation internals removed, toolbar and CSP guidance restored. - Lead the migration guide with a summary of what changes. - Rewrite v1-shaped and spec-like prose in handbook pages and guides. - Keep the v1 footer on SDK and Next.js pages only; surface the upgrade guide at the top of the SDK overview. - Shorten the scope line to "This page covers SDK v2." and fix bootstrap and event anchors. Co-Authored-By: Claude Opus 5.5 --- .generated/sdk-docs/browser-sdk/v2.json | 14 +- .generated/sdk-docs/node-sdk/v2.json | 10 +- .generated/sdk-docs/react-sdk/v2.json | 12 +- .generated/sdk-docs/vue-sdk/v2.json | 10 +- .github/scripts/sdk-docs.mjs | 2 +- .github/scripts/sdk-docs.test.mjs | 2 +- README.md | 6 +- SUMMARY.md | 2 +- guides/self-opt-in.md | 20 +-- guides/toggle-toolbar-with-a-flag.md | 6 +- guides/use-reflag-in-your-cli.md | 18 +- integrations/overview.md | 2 +- legacy/v1/README.md | 14 +- product-handbook/anonymous-users.md | 4 +- .../ai-code-clean-up-beta.md | 2 +- .../feature-entitlements/README.md | 2 +- product-handbook/launch-monitor/README.md | 2 +- .../launch-monitor/give-feedback-button.md | 2 +- product-handbook/remote-config.md | 22 ++- product-handbook/service-resiliency.md | 16 +- product-handbook/type-safety.md | 16 +- sdk/@reflag/browser-sdk/README.md | 165 ++++++++++-------- sdk/@reflag/browser-sdk/globals.md | 2 +- sdk/@reflag/node-sdk/README.md | 164 +++++++---------- sdk/@reflag/node-sdk/globals.md | 2 +- sdk/@reflag/react-sdk/README.md | 151 +++++++++------- sdk/@reflag/react-sdk/globals.md | 2 +- sdk/@reflag/vue-sdk/README.md | 131 +++++++++----- sdk/@reflag/vue-sdk/globals.md | 2 +- sdk/documents/browser-sdk/FEEDBACK.md | 8 +- sdk/documents/react-sdk/README.md | 151 +++++++++------- supported-languages/browser-sdk/README.md | 165 ++++++++++-------- supported-languages/browser-sdk/feedback.md | 8 +- supported-languages/browser-sdk/globals.md | 2 +- supported-languages/migrating-from-v1.md | 61 ++++--- supported-languages/next.js.md | 12 +- supported-languages/node-sdk/README.md | 164 +++++++---------- supported-languages/node-sdk/globals.md | 2 +- supported-languages/overview.md | 4 +- supported-languages/react-sdk/README.md | 151 +++++++++------- supported-languages/react-sdk/globals.md | 2 +- supported-languages/vue-sdk/README.md | 131 +++++++++----- supported-languages/vue-sdk/globals.md | 2 +- 43 files changed, 902 insertions(+), 764 deletions(-) diff --git a/.generated/sdk-docs/browser-sdk/v2.json b/.generated/sdk-docs/browser-sdk/v2.json index 93faed9..656a7e2 100644 --- a/.generated/sdk-docs/browser-sdk/v2.json +++ b/.generated/sdk-docs/browser-sdk/v2.json @@ -1,14 +1,14 @@ { "sourceRepository": "https://github.com/reflagcom/javascript", - "sourceCommit": "23b018b17cd0755fa6512cd209265cdac5f8fb0d", + "sourceCommit": "f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684", "package": "@reflag/browser-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/browser-sdk/README.md": "ccd9abfd0a9107868e5402d0b4d77a56f11a9b4c5936c0fa385144c96888ccb2", - "sdk/@reflag/browser-sdk/README.md": "7f2ec63c0769966840e1a9e95df00050609716fff224a1ab582d2d9b27434035", - "supported-languages/browser-sdk/globals.md": "b14c58f0368bfe307ae221fd2cf743e4e72c7f7ac61fc995ef05bb42c6c87766", - "sdk/@reflag/browser-sdk/globals.md": "0903191a59424fe17d3c916781c3a837aeeaba854af1321c038e8e5cae7549d5", - "supported-languages/browser-sdk/feedback.md": "dec2542a2edb7e86545f14be652f8e9af40185483fe19b87e2ae0fbabed5756a", - "sdk/documents/browser-sdk/FEEDBACK.md": "d6457320a70e4152a08bb41f14f9d03c01ab5478b20fbd4f4855d562b598ed03" + "supported-languages/browser-sdk/README.md": "acbef54e789913d3676d28655d9882b45736b735ad0d2257da51bbba76d48ecc", + "sdk/@reflag/browser-sdk/README.md": "53972ca6f20f557de377a9196c4f47ea43a9fc451d7fb41cc9e45995671c7599", + "supported-languages/browser-sdk/globals.md": "4a3be858a621eb3839408d759329a60ab2ea406d0e21174b44b0639c678a1ffc", + "sdk/@reflag/browser-sdk/globals.md": "a60d58526686dcc14ea5cdcecfa1d17388aff78f198f97f41bd667d35c7c39aa", + "supported-languages/browser-sdk/feedback.md": "704e2ba3985b013c0ab3e23e3439930063fc253fcf12fda97bb1c7e13a69112a", + "sdk/documents/browser-sdk/FEEDBACK.md": "8221ce5cfaf24b29f6c868ae5c6acfe8d4a5822c59bfba37854c5710590f55a6" } } diff --git a/.generated/sdk-docs/node-sdk/v2.json b/.generated/sdk-docs/node-sdk/v2.json index d3d7821..bc6afaa 100644 --- a/.generated/sdk-docs/node-sdk/v2.json +++ b/.generated/sdk-docs/node-sdk/v2.json @@ -1,12 +1,12 @@ { "sourceRepository": "https://github.com/reflagcom/javascript", - "sourceCommit": "693dbde853ea854c9d2e0133a77b98f45642f6f0", + "sourceCommit": "2b71dcc56aab2ff86bd4cea671d5e8effe0060bb", "package": "@reflag/node-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/node-sdk/README.md": "001b1815d3c291c8362fe0e8a52f5e326880ce4d9f1687853afde2c5cb350198", - "sdk/@reflag/node-sdk/README.md": "6f74756bae2e52bf86011b158da34fd6c804958741b048dfb85d1c3856f9e01f", - "supported-languages/node-sdk/globals.md": "a59f27d9a3c3418e43e16ef919d5eadb817186e847396ce9dc71c7c2c7844b5d", - "sdk/@reflag/node-sdk/globals.md": "dd2d9c51aa2bad7fd2f87cd1b6e36773d3d4f3a2efae13c6d916c9fef2d2b800" + "supported-languages/node-sdk/README.md": "f05616c28415ef8f3e1fcb9299ecd51ae170cc76be569240be16b8488ffbfe81", + "sdk/@reflag/node-sdk/README.md": "c979675ff56811e414ffd5d9e16ebbb4007c4743ceaafe3b1a0f464ee6aa99ec", + "supported-languages/node-sdk/globals.md": "e1fc21f052e69b74582782ac7133513b077f328294f674523f087e4846338815", + "sdk/@reflag/node-sdk/globals.md": "3fc142c7e452af2515b11c7efafa34d81bfe887f29ad1e2d6c81d31fb6736cc3" } } diff --git a/.generated/sdk-docs/react-sdk/v2.json b/.generated/sdk-docs/react-sdk/v2.json index 5a6979f..0ccfc77 100644 --- a/.generated/sdk-docs/react-sdk/v2.json +++ b/.generated/sdk-docs/react-sdk/v2.json @@ -1,13 +1,13 @@ { "sourceRepository": "https://github.com/reflagcom/javascript", - "sourceCommit": "23b018b17cd0755fa6512cd209265cdac5f8fb0d", + "sourceCommit": "f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684", "package": "@reflag/react-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/react-sdk/README.md": "02cf3f7f06a0e0efae439a2641cddaa0e93f070a0ad3dfe4fdc2977deabe43b7", - "sdk/@reflag/react-sdk/README.md": "fa6cfeaa7dc03d2460810ca6609b2adf1cf375ef903dfa522c2531b22c598b1f", - "sdk/documents/react-sdk/README.md": "fa6cfeaa7dc03d2460810ca6609b2adf1cf375ef903dfa522c2531b22c598b1f", - "supported-languages/react-sdk/globals.md": "be2241ca671643f5b9584463948e3bbde89c7c90d38ffbf011125d087890d5e1", - "sdk/@reflag/react-sdk/globals.md": "846f78f9ab8dbac0faeaad0c9aa2dc36525b31d891ba53a407811567dcdf8a9a" + "supported-languages/react-sdk/README.md": "ec75e4663a2a51707a81ee290b6267b7e53e6fdf9380e6d12f1d5dbd32b517bd", + "sdk/@reflag/react-sdk/README.md": "d4312429334e929032c66aa45cd93bc831947592465917532596bdbdae48fd0c", + "sdk/documents/react-sdk/README.md": "d4312429334e929032c66aa45cd93bc831947592465917532596bdbdae48fd0c", + "supported-languages/react-sdk/globals.md": "f414859dd7cc94089d06f27613e1c554e3e3d5f049a9a141c2590058af768b1a", + "sdk/@reflag/react-sdk/globals.md": "4cf0d20cca9c19d3998d9c5d0f6670d17d6782c24ee0ccd25e1d34100f42fcc6" } } diff --git a/.generated/sdk-docs/vue-sdk/v2.json b/.generated/sdk-docs/vue-sdk/v2.json index 98c1297..76fa6b1 100644 --- a/.generated/sdk-docs/vue-sdk/v2.json +++ b/.generated/sdk-docs/vue-sdk/v2.json @@ -1,12 +1,12 @@ { "sourceRepository": "https://github.com/reflagcom/javascript", - "sourceCommit": "23b018b17cd0755fa6512cd209265cdac5f8fb0d", + "sourceCommit": "f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684", "package": "@reflag/vue-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/vue-sdk/README.md": "59849b310c4033135737eca9eaa1ff5340ebfd054179d79c5ba66fde3f687c9f", - "sdk/@reflag/vue-sdk/README.md": "12077de855aba05ca3f15d2545a68de2ca19a6a5dbc3a30fab7d4bf0bf492b2d", - "supported-languages/vue-sdk/globals.md": "498b5479d79803b6ad0d889c3bf810d797cfbe2bc7f0fe5e8f6fa7746fb6d073", - "sdk/@reflag/vue-sdk/globals.md": "b736b0a49ab26f8771ecccbad5ab220186f33ae627f385d2df6dfcde45db5643" + "supported-languages/vue-sdk/README.md": "42830e3990636114ec07648f932c113f5d751a93fcb9385e1ece07f2ce069dc8", + "sdk/@reflag/vue-sdk/README.md": "7b98f3bf0536de5cea109c65b71c58f0374ebe6c278ce3284a6149ca4a739907", + "supported-languages/vue-sdk/globals.md": "968ec7df896ee2e78d1d23578acfadfc3378bd511b15c55eca79b6558588727f", + "sdk/@reflag/vue-sdk/globals.md": "73ceaa29875b0d33a02dcfbf12cf1e50644b51d871cc496681bdbcbeee56ab2d" } } diff --git a/.github/scripts/sdk-docs.mjs b/.github/scripts/sdk-docs.mjs index 9504a2c..8430997 100644 --- a/.github/scripts/sdk-docs.mjs +++ b/.github/scripts/sdk-docs.mjs @@ -7,7 +7,7 @@ import { pathToFileURL } from "node:url"; import { parseArgs } from "node:util"; export const webSDKs = ["browser-sdk", "react-sdk", "vue-sdk", "node-sdk"]; -export const currentVersionNote = "This documentation covers SDK v2."; +export const currentVersionNote = "This page covers SDK v2."; const references = [...webSDKs, "react-native-sdk", "management-sdk"]; export const documentedPackages = [...references, "cli"]; const repository = "https://github.com/reflagcom/javascript"; diff --git a/.github/scripts/sdk-docs.test.mjs b/.github/scripts/sdk-docs.test.mjs index 3f96074..a3e0e16 100644 --- a/.github/scripts/sdk-docs.test.mjs +++ b/.github/scripts/sdk-docs.test.mjs @@ -248,7 +248,7 @@ test("the current-version line stays in the introduction without entering code f const content = "# SDK\n\nIntroduction.\n\n```md\n## Code example\n```\n\n## Setup\n"; const rendered = anchorHeadings(content, { introNote: currentVersionNote }); assert(rendered.includes("```md\n## Code example\n```")); - assert(rendered.indexOf("```\n\nThis documentation") > rendered.indexOf("## Code example")); + assert(rendered.indexOf(`\`\`\`\n\n${currentVersionNote}`) > rendered.indexOf("## Code example")); assert(rendered.indexOf(currentVersionNote) < rendered.indexOf("## Setup")); assert.equal(rendered.split(currentVersionNote).length - 1, 1); }); diff --git a/README.md b/README.md index 05b096c..44dbb85 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ Now let's create your first flag. npx @reflag/cli new ``` -See [Type safety](product-handbook/type-safety.md) to generate TypeScript declarations for your flags. +See the [CLI docs](api/cli.md), and [Type safety](product-handbook/type-safety.md) to generate TypeScript types for your flags. {% endtab %} {% tab title="UI" %} @@ -60,7 +60,7 @@ const MyFlag = () => { }; ``` -You can now use the Boolean value directly to gate access to the flag. +`enabled` is `true` for users who have access to the flag. ## 3. Set access rules @@ -142,5 +142,3 @@ Configure your flag's adoption rules to match the event name you send with `trac * Need some help? [Chat with us](mailto:hello@reflag.com) * Latest product updates? [See Changelog](https://reflag.com/changelog) * Create account: [Sign up](https://app.reflag.com/) - -Using v1? [Legacy docs](legacy/v1/README.md) · [Upgrade guide](supported-languages/migrating-from-v1.md). diff --git a/SUMMARY.md b/SUMMARY.md index f3c0b74..061b4c6 100644 --- a/SUMMARY.md +++ b/SUMMARY.md @@ -99,7 +99,7 @@ ## Legacy SDKs -* [Legacy SDKs (v1)](legacy/v1/README.md) +* [SDK v1](legacy/v1/README.md) * [Browser SDK (v1)](legacy/v1/browser-sdk/README.md) * [Reference](legacy/v1/browser-sdk/globals.md) * [Feedback](legacy/v1/browser-sdk/feedback.md) diff --git a/guides/self-opt-in.md b/guides/self-opt-in.md index f724435..ce2dd39 100644 --- a/guides/self-opt-in.md +++ b/guides/self-opt-in.md @@ -19,8 +19,6 @@ For an overview of how opt-in affects access and how memberships are managed in Render the available opt-in flags and let the current user set their opt-in status. -If you're using `` without a `` boundary, see the loading section below. - ```tsx import { useState } from "react"; import { @@ -113,23 +111,9 @@ Cancelling every opt-in does not necessarily disable the flag: an access rule ma ## Managing opt-in loading state -Check opt-in loading before rendering an empty state, including during ordinary initialization. Metadata arrives with evaluated-flags responses. A bootstrapped snapshot may omit it; the SDK then fetches missing metadata on demand without replacing server-derived flag values. - -Check the hook's `isLoading` value before rendering an empty state: - -```tsx -const { flags: optInFlags, isLoading } = useOptInFlags({ suspense: false }); - -if (isLoading) { - return ; -} - -if (optInFlags.length === 0) { - return

No opt-in flags are available.

; -} -``` +The list of opt-in flags can still be loading after the rest of your flags are ready, for example when you bootstrap flags from the server. Check `isLoading` before rendering an empty state, as the quick start does, so users don't briefly see "No opt-in flags are available." -For general provider initialization, use `useIsLoading()` or `loadingComponent`. React `useFlag()` itself never suspends; use `useFlagSuspense()` for a suspending flag read. Opt-in hooks have their own suspense/loading contract; do not assume their loading value is always `false` with a regular provider. +To use a Suspense boundary instead, call `useOptInFlags({ suspense: true })`. ## Next steps diff --git a/guides/toggle-toolbar-with-a-flag.md b/guides/toggle-toolbar-with-a-flag.md index faeb189..cb6545f 100644 --- a/guides/toggle-toolbar-with-a-flag.md +++ b/guides/toggle-toolbar-with-a-flag.md @@ -5,7 +5,7 @@ icon: toolbox # Toggle toolbar with a flag -Use a Boolean flag to choose who sees the SDK toolbar toggle. Create a `toolbar` flag in Reflag, configure its access rules, and leave the provider's unconditional `toolbar` option disabled. +The Reflag toolbar lets you toggle flags for yourself in the browser. Use a flag to choose who gets it in production, such as your team or beta testers: create a Boolean `toolbar` flag in Reflag, enable it for those users, and don't set the provider's `toolbar` prop. Put this component inside your React SDK provider: @@ -25,6 +25,6 @@ export function ToolbarFlagControl() { } ``` -This shows the toggle once access is granted. `showToolbarToggle()` does not provide a corresponding hide operation: switching the flag off later does not remove an already mounted toggle. Reload or recreate the client to apply a new visibility decision. +Now you can turn the toolbar on or off for anyone by changing who the `toolbar` flag is enabled for. Turning it off takes effect the next time the page loads, because the toolbar stays open once it's shown. -This is a convenience control, **not an authorization boundary**. Users control their own browser; never use the toolbar flag to protect secrets or administrative server operations. See [Browser SDK](../supported-languages/browser-sdk/README.md) for toolbar options. +The toolbar only overrides flags in the user's own browser, so it isn't a security control. See the [Browser SDK](../supported-languages/browser-sdk/README.md#overrides-and-toolbar) for more toolbar options. diff --git a/guides/use-reflag-in-your-cli.md b/guides/use-reflag-in-your-cli.md index 34a9911..9279dfe 100644 --- a/guides/use-reflag-in-your-cli.md +++ b/guides/use-reflag-in-your-cli.md @@ -5,13 +5,13 @@ icon: rectangle-terminal # Use Reflag in your CLI -This guide is about **your application's CLI**, not the Reflag management CLI. Authenticate your caller using your existing API-token or OAuth flow, then evaluate flags with the server-side Node.js SDK. Do not embed a Reflag secret SDK key or a Management API key in a distributed CLI. +This guide is about **your application's CLI**, not the Reflag management CLI. Your CLI asks your backend for flag values; the backend evaluates them with the Node.js SDK. That way, your Reflag keys stay on your servers instead of shipping inside the CLI. ## Evaluate on your backend -Create an authenticated endpoint such as `POST /get-flags`. Look up the user and company from your trusted session/token store; do not trust caller-supplied identities or subscription attributes. +Create an endpoint such as `POST /get-flags`, authenticated with your existing API-token or OAuth flow. Look up the user and company from the caller's token, rather than trusting identities the CLI sends. -A reusable evaluation helper can accept the resulting context: +Then evaluate the flags for that context: ```typescript import { ReflagClient, type Context } from "@reflag/node-sdk"; @@ -29,9 +29,7 @@ export async function getCliAccess(context: Context) { } ``` -Call `getCliAccess()` after authentication and return only the values your CLI needs. This registers checks for these requested roots. Diagnostic APIs are not a substitute for application reads. - -The JSON response contains the flag values: +Return only the values your CLI needs: ```json { @@ -42,7 +40,7 @@ The JSON response contains the flag values: ## Gate the CLI workflow -Use the Boolean directly and validate the response before using nested configuration. Recheck sensitive access on the backend that performs the operation; a CLI display check is not authorization. +In the CLI, use the Boolean directly. Users can modify a CLI they run, so if the CLI calls your backend to perform the operation, check the flag there too. ```typescript export function canExport(response: { exportEnabled: boolean }) { @@ -50,11 +48,9 @@ export function canExport(response: { exportEnabled: boolean }) { } ``` -If you expose a list of enabled Boolean keys instead, use `enabledKeys.includes("export-to-csv")`. Do not treat a general JSON-valued flag map as a list of enabled keys or apply truthiness to Multivariate values. - ## Track successful usage separately -After the protected operation succeeds, track the application's adoption event with the same authenticated context. Configure the flag's adoption rules to match that event. +When the operation succeeds, track it with the same context, and configure the flag's adoption rules to match the event name. ```typescript import { ReflagClient, type Context } from "@reflag/node-sdk"; @@ -69,5 +65,3 @@ export async function recordExport(context: Context) { ``` Initialize the client once per process and flush queued events before your server process exits. See the [Node.js SDK](../supported-languages/node-sdk/README.md) for lifecycle options. - -Using v1? [Legacy docs](../legacy/v1/README.md) · [Upgrade guide](../supported-languages/migrating-from-v1.md). diff --git a/integrations/overview.md b/integrations/overview.md index ea048bd..fb87c32 100644 --- a/integrations/overview.md +++ b/integrations/overview.md @@ -14,7 +14,7 @@ These integrations are crafted and maintained by the Reflag team. To build your own integrations with Reflag, you can use: -* [Event listeners](../supported-languages/browser-sdk/#event-listeners) +* [Event listeners](../supported-languages/browser-sdk/README.md#events) * [Runtime API](../api/public-api/) **To request support for more integrations,** [**please fill out this form**](https://share-eu1.hsforms.com/14DktM5t6T229b5Bg8KPDBg2b6w1x) **— Thanks!** diff --git a/legacy/v1/README.md b/legacy/v1/README.md index cbf3c7a..15a7afc 100644 --- a/legacy/v1/README.md +++ b/legacy/v1/README.md @@ -1,10 +1,10 @@ --- -description: Legacy protocol-v1 documentation for the Browser, React, Vue and Node.js SDKs. +description: Documentation for v1 of the Browser, React, Vue and Node.js SDKs. --- # Legacy SDKs (v1) -These pages document the **protocol-v1 SDKs**. For new v2 integrations, start with the [current SDK documentation](../../supported-languages/overview.md). For an existing application, read [Migrating from v1](../../supported-languages/migrating-from-v1.md) before upgrading. +These pages document **v1** of the Browser, React, Vue and Node.js SDKs. For a new integration, start with the [current SDK documentation](../../supported-languages/overview.md). To upgrade an existing application, read [Migrating from v1](../../supported-languages/migrating-from-v1.md). | SDK | Package major | Documentation | API reference | | --- | --- | --- | --- | @@ -23,12 +23,12 @@ Pin the major when maintaining a v1 application: npm install @reflag/react-sdk@1 ``` -Use `@reflag/browser-sdk@1`, `@reflag/vue-sdk@1`, or `@reflag/node-sdk@1` as appropriate. Keep CLI 1 with legacy generated declarations. Unversioned installation commands can select a breaking major after it becomes the default on npm. +Use `@reflag/browser-sdk@1`, `@reflag/vue-sdk@1` or `@reflag/node-sdk@1` in the same way, and keep generating types with CLI 1. Without `@1`, npm installs the latest major version. ## Compatibility -- Keep both ends of a server-to-browser bootstrap integration on protocol v1. A Node v2 bootstrap envelope cannot initialize a v1 Browser, React or Vue client. -- React Native and the OpenFeature providers have independent release schedules. Follow their own supported dependency versions; their presence in the main navigation does not imply protocol-v2 support. -- General guides and handbook examples show v2. Use the SDK pages in this archive for legacy wrapper APIs such as `.isEnabled` and `.config.payload`. +- If you bootstrap flags from the server, keep the Node.js SDK and your Browser, React or Vue SDK on the same major version. v1 clients can't read v2 bootstrap data. +- React Native and the OpenFeature providers are released separately. Check their own documentation for the versions they support. +- Guides and handbook examples use v2. For v1 APIs such as `.isEnabled` and `.config.payload`, use the SDK pages in this section. -Legacy means an older protocol, not a claim about an end-of-support date. See the [migration guide](../../supported-languages/migrating-from-v1.md) for the breaking changes. +"Legacy" means v1 is no longer the latest version. It doesn't announce an end-of-support date. See the [migration guide](../../supported-languages/migrating-from-v1.md) for what changes in v2. diff --git a/product-handbook/anonymous-users.md b/product-handbook/anonymous-users.md index cad346e..52af8c7 100644 --- a/product-handbook/anonymous-users.md +++ b/product-handbook/anonymous-users.md @@ -41,7 +41,7 @@ export function App() { {% endtab %} {% endtabs %} -Bare reads return Boolean with implicit false. Supply a positional default when reading JSON-valued Multivariate flags. +Without a default, `getFlag()` and `useFlag()` return a Boolean. Pass a default to read a Multivariate flag's value. ## How to toggle features for anonymous users where you know their company @@ -82,4 +82,4 @@ export function App() { {% endtab %} {% endtabs %} -A browser's company ID is not an authorization boundary. Enforce sensitive access on your authenticated server, using context derived from your own session or API-token lookup. See the [Node.js SDK](../supported-languages/node-sdk/README.md) and [React SDK](../supported-languages/react-sdk/README.md) for complete setup. +Anyone can change the company ID their browser sends, so check access to sensitive features on your server too. See the [Node.js SDK](../supported-languages/node-sdk/README.md) and [React SDK](../supported-languages/react-sdk/README.md) for complete setup. diff --git a/product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta.md b/product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta.md index c5904da..942a84d 100644 --- a/product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta.md +++ b/product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta.md @@ -127,5 +127,5 @@ function StartHuddleButton() { **Limitations**: -* Review the generated PR carefully. Removing the Boolean gate does not imply that usage tracking, feedback hooks or separately authored configuration should be removed. Multivariate values need an explicit cleanup decision; do not apply Boolean truthiness to arbitrary JSON. +* Review the generated PR carefully. The cleanup removes the flag check only; keep any usage tracking, feedback or configuration you still need. For Multivariate flags, decide yourself which value to keep. * Works best with the React SDK while in beta. diff --git a/product-handbook/feature-entitlements/README.md b/product-handbook/feature-entitlements/README.md index 2b6b241..b5de507 100644 --- a/product-handbook/feature-entitlements/README.md +++ b/product-handbook/feature-entitlements/README.md @@ -42,7 +42,7 @@ import { ReflagProvider } from "@reflag/react-sdk";
; ``` -Reflag can now target the company's Business subscription plan. Enforce sensitive entitlements on the server with context derived from your trusted session or subscription store; browser-supplied attributes are not an authorization boundary. +Reflag can now target the company's Business subscription plan. Users can change what their browser sends, so also check sensitive entitlements on your server, using the plan from your own billing data. {% hint style="info" %} You can send company attributes as part of the user sign-in event, via a nightly job, or use `updateCompany()` when the attribute value changes. diff --git a/product-handbook/launch-monitor/README.md b/product-handbook/launch-monitor/README.md index faf5cab..f37aa02 100644 --- a/product-handbook/launch-monitor/README.md +++ b/product-handbook/launch-monitor/README.md @@ -38,7 +38,7 @@ You can collect end-user feedback on new flag rollouts to catch and fix issues f ### Static feedback button -Configure adoption rules to match the usage event name you send. Reading a flag registers a check; tracking usage is a separate operation. +Configure the flag's adoption rules to match the event name you track. Reading a flag records a check automatically; call `track()` when someone actually uses the feature. Here's a brief example using the [Reflag React SDK](../../supported-languages/react-sdk/README.md) to collect feedback: diff --git a/product-handbook/launch-monitor/give-feedback-button.md b/product-handbook/launch-monitor/give-feedback-button.md index 426cdcc..53298d7 100644 --- a/product-handbook/launch-monitor/give-feedback-button.md +++ b/product-handbook/launch-monitor/give-feedback-button.md @@ -4,7 +4,7 @@ description: Add a feedback button with the React SDK feedback hook. # Give feedback button -Use a separate feedback hook to open a feedback form. The flag read controls the workflow; it does not return feedback or tracking methods. +Use the `useRequestFeedback()` hook to open a feedback form from your own button: ```tsx import { useFlag, useRequestFeedback, useTrack } from "@reflag/react-sdk"; diff --git a/product-handbook/remote-config.md b/product-handbook/remote-config.md index 9dbe225..7025401 100644 --- a/product-handbook/remote-config.md +++ b/product-handbook/remote-config.md @@ -8,7 +8,7 @@ description: Configure JSON-valued Multivariate flags for different audiences. Use a **Multivariate flag** when different users or companies need different configuration values. Unlike a Boolean flag, which answers an access question, a Multivariate flag selects a named variant and returns its JSON value directly. -A value can be an object, array, string, number, Boolean, or `null`. There are no reserved application fields: names such as `model`, `config`, `payload`, or `enabled` are ordinary data that you choose. +A value can be an object, array, string, number, Boolean, or `null`. For example, configure `assistant-settings` with variants containing different model settings, then read it with the React SDK: @@ -31,7 +31,7 @@ export function AssistantSettings() { } ``` -The second argument is the application's fallback value. A bare `useFlag("assistant-settings")` is a Boolean read, even if the flag is Multivariate. Supply an appropriate default for a JSON read; use explicit `null` if you need arbitrary JSON and will narrow the result yourself. +The second argument is a default, used while flags load or if the flag can't be read. Always pass one when reading a Multivariate flag; without it, `useFlag()` reads the flag as a Boolean. Pass `null` to accept any JSON value and narrow it yourself. ## Config values @@ -42,9 +42,9 @@ Each environment's definition contains: - **Ordered rules:** filters and results, including percentage distributions. - **Default variant:** the authored selection when no more-specific target or applicable rule selects a variant. -Definitions, targeting, and values are environment-specific. Save the complete definition together; changing another environment does not automatically copy its values or rules. An empty Multivariate definition evaluates to `null`. +Variants, targets and rules are set per environment. Changes in one environment aren't copied to the others. A Multivariate flag with no variants returns `null`. -The authored default variant is different from the application's SDK fallback. A real default-variant selection retains its selection identity; the SDK fallback does not invent one. +The default variant is set in Reflag. It's different from the default you pass in code, which is only used when the SDK can't read the flag. {% hint style="danger" %} Do not store credentials or other secrets in flag values. Anything sent to a browser can be inspected by its users. Keep application secrets in an appropriate secret manager. @@ -52,17 +52,17 @@ Do not store credentials or other secrets in flag values. Anything sent to a bro ## Matching algorithm -Specific user assignments take precedence over company assignments. Then rules are considered in order; the default variant handles contexts that do not select an earlier result. Rules can use the supported user, company, segment, and other-context filters. Percentage distributions select a variant using the configured bucketing attribute; preserve stable variant/rule identities when editing definitions. +Specific user assignments take precedence over company assignments. Then rules are considered in order; the default variant handles contexts that do not select an earlier result. Rules can use the supported user, company, segment, and other-context filters. Percentage distributions assign variants using the configured bucketing attribute. -For a separate on/off gate, use a Boolean flag. A Multivariate value of `false`, `0`, `""`, `[]`, or `null` is application data, not a universal access-denied signal. Do not use JavaScript truthiness to decide whether a variant was selected. +To turn a feature on or off, use a separate Boolean flag. Values such as `false`, `0` or `null` in a Multivariate flag are ordinary data, so don't use them to decide access. ## Usage scenarios ### Basic flag configuration -Use a single default variant for centrally managed configuration, or add rules and more variants as different audiences need different settings. Choose a safe application fallback and validate any nested data your application depends on. +Use a single default variant for configuration you want to manage in one place, or add rules and more variants when different audiences need different settings. Pass a safe default in code. -Non-null SDK defaults check the selected value's **top-level category**. They do not recursively validate a returned object's fields. Generated TypeScript declarations are compile-time assistance, not runtime validation. +The SDK checks only the top-level type of a value against your default. If your application depends on nested fields, validate them. [Generated types](type-safety.md) are checked at compile time only. ### Multivariate flags @@ -79,13 +79,11 @@ export function AssistantModel() { ### Entitlements -Combine a Boolean entitlement such as `assistant-enabled` with a separate settings flag when access and configuration are independent product decisions. Use company attributes and rules to select settings for each subscription tier. Read only the flags needed by the workflow. +Combine a Boolean entitlement such as `assistant-enabled` with a separate settings flag when access and configuration are independent decisions. Use company attributes and rules to pick settings for each subscription tier. ## Start using remote config 1. Create a **Multivariate** flag in an app where Multivariate support is available. 2. Open its **Variants** tab and configure variants, specific targets, rules, and the default for the selected environment. 3. Save, then configure and verify any other environments separately. -4. Read the value with a [Reflag SDK](../supported-languages/overview.md) and a positional default. - -Using v1? [Legacy docs](../legacy/v1/README.md) · [Upgrade guide](../supported-languages/migrating-from-v1.md). +4. Read the value with a [Reflag SDK](../supported-languages/overview.md), passing a default. diff --git a/product-handbook/service-resiliency.md b/product-handbook/service-resiliency.md index 9f8831c..4d55a4d 100644 --- a/product-handbook/service-resiliency.md +++ b/product-handbook/service-resiliency.md @@ -59,7 +59,7 @@ flowchart LR 1. Evaluate flags on the server with the [Node.js SDK](../supported-languages/node-sdk/README.md). 2. Configure a [`flagsFallbackProvider`](../supported-languages/node-sdk/README.md#fallback-providers) so fresh server processes can initialize from saved flag definitions when Reflag cannot be reached. -3. Use [`getFlagsForBootstrap()`](../supported-languages/node-sdk/README.md#bootstrap-state) on the server and a bootstrapped client provider in React, Vue, or the Browser SDK. +3. Use [`getFlagsForBootstrap()`](../supported-languages/node-sdk/README.md#bootstrap-the-browser) on the server and a bootstrapped client provider in React, Vue, or the Browser SDK. 4. If your client SDK supports caching, tune it based on how long your app can tolerate stale flags. 5. Test the disruption path in staging: block access to Reflag, start a fresh server process, and confirm it initializes from fallback storage and the client renders from bootstrapped flags. @@ -90,19 +90,19 @@ Use the file provider for single-server deployments only when the disk persists Choose fallback storage based on where your application runs. The storage should be reachable whenever your application is reachable, so prefer storage in the same cloud provider, region, or network as the application deployment that will use it. If an outage affects Reflag's infrastructure but your application is still running elsewhere, your application can still load the saved snapshot. If the same provider or region outage also takes down your application, fallback storage cannot help until your application environment is available again. -See the [fallback provider docs](../supported-languages/node-sdk/README.md#fallback-providers) for built-in storage options and the snapshot format. +See the [fallback provider docs](../supported-languages/node-sdk/README.md#fallback-providers) for the built-in storage options. ## Bootstrapped flags Bootstrapping lets your server evaluate flags and pass the server-evaluated state to your client-side application. The client can render immediately from that state instead of depending on an initial request to Reflag. -Use [`getFlagsForBootstrap()`](../supported-languages/node-sdk/README.md#bootstrap-state) in the Node.js SDK together with your client SDK's bootstrapping API: +Use [`getFlagsForBootstrap()`](../supported-languages/node-sdk/README.md#bootstrap-the-browser) in the Node.js SDK together with your client SDK's bootstrapping API: -* [React SDK](../supported-languages/react-sdk/README.md#bootstrap-and-ssr): `ReflagBootstrappedProvider` -* [Vue SDK](../supported-languages/vue-sdk/README.md#bootstrap): `ReflagBootstrappedProvider` -* [Browser SDK](../supported-languages/browser-sdk/README.md#server-bootstrap): `bootstrappedState` +* [React SDK](../supported-languages/react-sdk/README.md#bootstrap-from-the-server): `ReflagBootstrappedProvider` +* [Vue SDK](../supported-languages/vue-sdk/README.md#bootstrap-from-the-server): `ReflagBootstrappedProvider` +* [Browser SDK](../supported-languages/browser-sdk/README.md#bootstrap-from-the-server): `bootstrappedState` -Pass the entire bootstrap envelope, including context and selection metadata. React Native and OpenFeature have their own compatibility requirements; follow their SDK documentation. +Pass the whole object returned by `getFlagsForBootstrap()`. React Native and OpenFeature have their own compatibility requirements; follow their SDK documentation. Bootstrapping is the recommended client setup for high-availability applications because the first render depends on your application server response, not on the client's ability to reach Reflag. Combined with server-side local evaluation and `flagsFallbackProvider`, it lets end users continue receiving evaluated flags during a Reflag service disruption. @@ -115,5 +115,3 @@ If you enable live client-side flag updates after bootstrapping, the client refr After a client SDK has loaded flags, it keeps recent flag state in memory so temporary network failures do not stop flag usage. Browser-based SDKs can also cache flag state across page loads. Tune cache behavior with options such as `staleTimeMs`, `staleWhileRevalidate`, and `expireTimeMs`. Client caching is a useful safety net for client-side evaluation. For applications that need resilience through server restarts and first render, combine server-side evaluation, fallback storage, and bootstrapping. - -Using v1? [Legacy docs](../legacy/v1/README.md) · [Upgrade guide](../supported-languages/migrating-from-v1.md). diff --git a/product-handbook/type-safety.md b/product-handbook/type-safety.md index 205cd7f..b531b8b 100644 --- a/product-handbook/type-safety.md +++ b/product-handbook/type-safety.md @@ -4,7 +4,7 @@ description: Register flag keys and schemas with the Reflag SDKs and CLI. # Type safety -The Reflag SDKs infer return types from the defaults you pass, without a generated file. Registering your flag schemas also catches misspelled keys and incompatible non-null defaults. +The Reflag SDKs infer a flag's type from the default you pass, so you get useful types without any setup. Registering your flags also catches misspelled keys and defaults that don't match your flag's values. ```tsx import { useFlag } from "@reflag/react-sdk"; @@ -15,7 +15,7 @@ export function TokenLimit() { } ``` -The fallback determines the widened return type: `512` becomes `number`, not the literal type `512`. Bare or explicit-`undefined` reads return Boolean; explicit `null` requests arbitrary JSON. +Here the default `512` gives `maxTokens` the type `number`. Without a default, you get a Boolean; with `null`, you get any JSON value. ## Set up type safety for flags @@ -35,9 +35,9 @@ npx reflag flags types --format node --out gen/flags.d.ts npx reflag flags types --format vue --out gen/flags.d.ts ``` -Generate only the declarations needed by your application's SDKs and ensure TypeScript includes the output. These examples show alternative formats; do not overwrite the same file three times in your actual build. +Pick the format for the SDK you use, and make sure TypeScript includes the output file. -Generation uses current production-environment Multivariate values to describe possible JSON shapes. Empty or unknown data remains JSON-capable rather than being invented as Boolean. Regenerate when flag definitions change. Generation errors must fail your build rather than leaving an unnoticed stale declaration file. +Types are generated from the variant values in your production environment. Regenerate them when your flags change, and let generation errors fail your build so the types don't silently go stale. You can commit the generated file, or ignore it and generate it on local setup and in CI. If you ignore it: @@ -67,13 +67,13 @@ export function RegisteredSettings() { } ``` -Registered non-null defaults must match the selected key's schema, including required/nested fields, array elements, and literal unions. Named interfaces and readonly defaults are supported. This does not change bare Boolean reads or the arbitrary-JSON meaning of explicit `null`. +With a registered flag, TypeScript checks that the default you pass matches the flag's type, including nested fields. -The SDK validates that defaults are JSON-compatible and checks the selected value's top-level category. It does **not** recursively enforce generated schemas on server-returned values. Add application validation when nested data is a trust boundary. +These checks happen at compile time. At runtime, the SDK checks only the top-level type of a value, so validate nested fields your application depends on. ## Using in CI/CD pipelines -Store an authorized [Management API key](../api/api-access.md) in your CI secret store. Do not commit it or send it to a browser. +Store a [Management API key](../api/api-access.md) as a secret in your CI system. ```yaml - name: Generate flag types @@ -83,5 +83,3 @@ Store an authorized [Management API key](../api/api-access.md) in your CI secret ``` Install the CLI from your lockfile before running this step. - -Using v1? [Legacy docs](../legacy/v1/README.md) · [Upgrade guide](../supported-languages/migrating-from-v1.md). diff --git a/sdk/@reflag/browser-sdk/README.md b/sdk/@reflag/browser-sdk/README.md index 2026972..2fef5b4 100644 --- a/sdk/@reflag/browser-sdk/README.md +++ b/sdk/@reflag/browser-sdk/README.md @@ -15,16 +15,20 @@ pagination: # Reflag Browser SDK -Client-side feature flags and JSON values for [Reflag](https://reflag.com). +Feature flags, remote configuration, usage tracking and feedback for browser applications. -This documentation covers SDK v2. +This page covers SDK v2. ## Get started +Install the SDK: + ```sh npm install @reflag/browser-sdk ``` +Create a client with your **publishable** key and the signed-in user's context, then read a flag: + ```ts import { ReflagClient } from "@reflag/browser-sdk"; @@ -35,126 +39,145 @@ const reflag = new ReflagClient({ }); await reflag.initialize(); -const enabled = reflag.getFlag("huddles"); // boolean, implicit false -const settings = reflag.getFlag("assistant-settings", { model: "quick" }); -// settings: { model: string } - -if (enabled) { - // Application usage tracking is separate from reading the flag. +if (reflag.getFlag("huddles")) { await reflag.track("Started huddle"); } ``` -Use only a **publishable** key in a browser. Secret keys belong on your server. +Publishable keys are safe to ship to the browser. Keep secret keys on your server. ## Read flags +Without a default, `getFlag()` returns a Boolean. You get `false` if the flag is missing or isn't a Boolean: + ```ts -reflag.getFlag("release"); // boolean; missing/mismatched -> false -reflag.getFlag("model", "quick"); // string -reflag.getFlag("limit", 10); // number -reflag.getFlag("settings", { model: "quick" }); -reflag.getFlag("nullable-settings", null); // FlagValue (arbitrary JSON) +const enabled = reflag.getFlag("huddles"); // boolean ``` -- Defaults are positional JSON values; generation is not required for useful types. Primitive literals widen, and readonly defaults are accepted. -- A non-null default accepts only the same **top-level JSON category**: Boolean, number, string, array or object. A mismatch warns without logging the payload and returns the default. A bare read can never return a truthy object. -- Explicit `null` accepts any JSON value, including authored null. Missing values return null. -- Falsy selected values (`false`, `0`, `""`, null) are preserved when accepted by the requested category. -- Object fields and array elements are **not schema-validated**. Validate untrusted/nested payloads in your application. -- Values and defaults are returned as independent mutable copies. There are no reserved JSON property names. +To read a configuration value, pass a default. The return type follows the default, and you get the default back if the flag is missing or holds a different type of value: -`getFlags()` returns a direct-value record (entries may be undefined) and registers checks for its returned roots. `getFlagResults()` returns owned evaluated diagnostics **without checks**; it is intended for tooling, not ordinary application reads. `getFlagsForBootstrap()` serializes evaluated state without checks. +```ts +const model = reflag.getFlag("model", "quick"); // string +const limit = reflag.getFlag("limit", 10); // number +const settings = reflag.getFlag("assistant-settings", { model: "quick" }); // { model: string } +``` -## Checks and delivery +Pass `null` to accept any JSON value, then narrow it yourself: -Reading a flag registers an exposure check, even if its return value is ignored. Checks are buffered, sent through `/bulk`, and rate-limited per identity. +```ts +const value = reflag.getFlag("nullable-settings", null); +``` -A selected check carries the authored selected key as `evalResult`, its `sourceVersionId` and the available snapshot `flagStateVersion`. Payload equality is not identity: equal-valued selections or segment-only snapshot changes remain distinguishable on subsequent reads. Defaults, category mismatches, local overrides and static fallback values do not fabricate authored selections. Diagnostics and bootstrap serialization generate no checks. The server evaluates dependencies; fetching their results does not itself register reads. +The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. -`enableTracking: false` disables checks and user/company/usage tracking. `offline: true` skips HTTP and tracking. `await reflag.stop()` flushes buffered events and closes the client's background transports. +`getFlags()` returns all flag values as a record. Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. -## Context, refresh and cache +## Track usage and feedback + +```ts +await reflag.track("Started huddle", { button: "cta" }); +reflag.requestFeedback({ flagKey: "huddles", title: "How did it go?" }); +``` + +Configure your flag's adoption rules to match the event names you send. See [FEEDBACK.md](../../../supported-languages/browser-sdk/feedback.md) to configure feedback prompts and the feedback UI. + +## Update context ```ts await reflag.updateUser({ role: "admin" }); await reflag.updateCompany({ plan: "enterprise" }); await reflag.updateOtherContext({ region: "eu" }); + +// Replace the whole context, for example after the user switches company: await reflag.setContext({ user: { id: "bob" }, company: { id: "other-company" }, }); -await reflag.refresh(); ``` -`setContext()` replaces the context; update methods shallow-merge their section. User/company sections require IDs, including valid numeric zero. Context supports nested JSON and arrays. A context change clears the old context's values while fetching; stale/in-flight responses cannot replace a newer context or snapshot. +The update methods merge into their section of the context, while `setContext()` replaces all of it. User and company sections need an `id`. Flag values are refetched for the new context. -Values come from `GET /flags/evaluated`. Server evaluation retains the complete internal graph and authorized public roots. The Browser SDK does not cache dependency evaluations of its own. +## Bootstrap from the server -Constructor options include: +To render flags immediately, without waiting for a network request, evaluate them on your server with the **Node.js SDK** and pass the result to the browser: -| Option | Behavior | -| ------------------------------- | --------------------------------------------------------------------------- | -| `apiBaseUrl`, `appBaseUrl` | API origin and toolbar/feedback links | -| `credentials` | Fetch credentials mode; `include` also enables default SSE credentials | -| `timeoutMs` | Flag request timeout; default 5,000 ms | -| `staleTimeMs` | Fresh-cache duration; default 0 | -| `staleWhileRevalidate` | Serve stale cached state while revalidating; default false | -| `expireTimeMs` | Cache expiry; default 30 days | -| `storage` | Optional async storage adapter | -| `fallbackFlags` | Value record or array of enabled Boolean keys, without authored provenance | -| `enableLiveFlagUpdates` | Refresh after SSE publications; default false in Browser, true in React/Vue | -| `eventSourceFactory` | Optional EventSource-compatible transport | -| `trackingQueue` | Buffered-delivery `flushDelayMs` and `maxSize` | -| `logger`, `toolbar`, `feedback` | Logging, Boolean override toolbar and feedback options | +```ts +// On the server +const bootstrappedState = serverClient.getFlagsForBootstrap(context); +``` -Evaluated flags and overrides are cached separately. Malformed refreshes leave known-good state intact. Valid saved selections retain their provenance on restore. There is no automatic periodic HTTP fallback after an SSE failure; manual refresh/context updates remain available. +```ts +// In the browser +const reflag = new ReflagClient({ publishableKey, bootstrappedState }); +await reflag.initialize(); +``` -## Overrides and toolbar +Pass the whole object returned by `getFlagsForBootstrap()`, serialized with your framework's usual mechanism. Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. + +Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, disable live updates. + +## Let users opt in to flags ```ts -reflag.setFlagOverride("release", true); -reflag.setFlagOverride("settings", { model: "local" }); -reflag.setFlagOverride("nullable-settings", null); // a real null override -reflag.setFlagOverride("release", undefined); // clear the override +const optInFlags = reflag.getOptInFlags(); +await reflag.setOptIn("huddles", { optedIn: true }); +await reflag.setOptIn("huddles", { optedIn: false, scope: "company" }); ``` -Overrides apply after server evaluation and do not rewrite authored dependency results. The built-in toolbar appears on localhost by default and offers Boolean overrides only. It uses diagnostic access, so opening it does not register application checks. +Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent. Use `getIsLoadingOptInFlags()` and the `optInFlagsLoadingUpdated` event to show a loading state. -## Server bootstrap +## Overrides and toolbar -Generate the payload with the **Node.js SDK** on your server: +Override flags locally while developing or testing: ```ts -const bootstrappedState = serverClient.getFlagsForBootstrap(context); -// Send via your framework's safe JSON/hydration mechanism. +reflag.setFlagOverride("huddles", true); +reflag.setFlagOverride("assistant-settings", { model: "local" }); +reflag.setFlagOverride("huddles", undefined); // remove the override ``` +The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` option to show it elsewhere, for example to internal users in production: + ```ts -const reflag = new ReflagClient({ publishableKey, bootstrappedState }); -await reflag.initialize(); -const enabled = reflag.getFlag("release"); +const reflag = new ReflagClient({ + publishableKey, + toolbar: user.isInternal, // show the toolbar to internal users +}); ``` -The payload includes `protocolVersion: 2`, context, evaluated diagnostics/selections and an optional snapshot version. Pass the entire envelope as `bootstrappedState`, including its context and selection metadata. A version is required for bootstrapped live updates. Never embed secrets or server-only context in public bootstrap data. Later refreshes use browser-visible context and can differ from server-only evaluation; disable live updates when that is inappropriate. +## Events -## End-user opt-in +`on(event, handler)` subscribes to client events and returns an unsubscribe function. Events include `stateUpdated`, `flagsUpdated`, `check`, `track`, `user`, `company` and `optInFlagsLoadingUpdated`. -```ts -const options = reflag.getOptInFlags(); -const loading = reflag.getIsLoadingOptInFlags(); -await reflag.setOptIn("huddles", { optedIn: true }); -await reflag.setOptIn("huddles", { optedIn: false, scope: "company" }); -``` +## Configuration -The list contains presentation/membership metadata (`key`, `name`, `description`, `isEnabled`, `userOptedIn`, `companyOptedIn`, `isOptedIn`); this is not the ordinary flag getter API. User/company grants remain independent. The selected scope requires its ID. Successful mutations wait for versioned evaluation and membership confirmation. +| Option | Description | +| -------------------------- | --------------------------------------------------------------- | +| `fallbackFlags` | Values to use if flags can't be fetched | +| `enableLiveFlagUpdates` | Update flags when they change in Reflag; default `false` | +| `staleTimeMs` | How long cached flags count as fresh; default `0` | +| `staleWhileRevalidate` | Use stale cached flags while fetching new ones; default `false` | +| `expireTimeMs` | How long cached flags are kept; default 30 days | +| `timeoutMs` | Flag request timeout; default 5,000 ms | +| `enableTracking` | Set to `false` to stop sending checks and usage events | +| `offline` | Make no network requests, for example in tests | +| `toolbar`, `feedback` | Toolbar and feedback UI options | +| `logger` | Custom logger | +| `apiBaseUrl`, `appBaseUrl` | Override the API and app URLs | +| `credentials` | Fetch credentials mode | +| `storage` | Custom async storage for the flag cache | +| `eventSourceFactory` | Custom EventSource implementation for runtimes without one | +| `trackingQueue` | Event batching: `flushDelayMs` and `maxSize` | -Metadata arrives with ordinary `/flags/evaluated` responses and is cached with the evaluated snapshot. Bootstrapped clients whose snapshot lacks metadata fetch it on demand from the same endpoint, without replacing server-derived values or provenance with browser-context evaluations. Loading settles on success or failure, including an empty list. Opt-in mutations confirm values and membership together in one versioned refresh. `optInFlagsLoadingUpdated` and `flagsUpdated` support UI subscriptions. +Call `await reflag.stop()` to send buffered events and close the client. -## Tracking, feedback and events +## Content Security Policy (CSP) -Use `track(eventName, attributes?)`, `feedback(payload)` and `requestFeedback({ flagKey, ... })` on the client. See [FEEDBACK.md](../../../supported-languages/browser-sdk/feedback.md) for the feedback UI and prompting configuration. +If your site uses a strict Content Security Policy, allow: -`on(event, handler)` returns an unsubscribe function. Events include `stateUpdated`, `flagsUpdated` (evaluated diagnostics), `check`, `track`, `user`, `company` and `optInFlagsLoadingUpdated`. +| Directive | Value | Reason | +| ------------- | -------------------------- | ---------------------------------- | +| `connect-src` | `https://front.reflag.com` | API requests and live updates | +| `style-src` | `'unsafe-inline'` | The feedback UI uses inline styles | Using v1? [Legacy docs](../../../legacy/v1/browser-sdk/README.md) · [Upgrade guide](../../../supported-languages/migrating-from-v1.md). diff --git a/sdk/@reflag/browser-sdk/globals.md b/sdk/@reflag/browser-sdk/globals.md index 0b4e6fc..62ef17e 100644 --- a/sdk/@reflag/browser-sdk/globals.md +++ b/sdk/@reflag/browser-sdk/globals.md @@ -15,7 +15,7 @@ pagination: # @reflag/browser-sdk -This documentation covers SDK v2. +This page covers SDK v2. ## Classes diff --git a/sdk/@reflag/node-sdk/README.md b/sdk/@reflag/node-sdk/README.md index ac9a01f..4a3164b 100644 --- a/sdk/@reflag/node-sdk/README.md +++ b/sdk/@reflag/node-sdk/README.md @@ -15,17 +15,19 @@ pagination: # Reflag Node.js SDK -Server-side Boolean and multivariate flag values for [Reflag](https://reflag.com). +Feature flags, remote configuration and usage tracking for Node.js servers. -This documentation covers SDK v2. +This page covers SDK v2. -## Installation and initialization +## Get started + +Install the SDK: ```sh yarn add @reflag/node-sdk ``` -Create one client per process and initialize it before reading flags. Obtain your environment's secret key from Reflag's environment settings; complete flag definitions must remain server-side. +Create one client per process with your environment's **secret** key, found in your Reflag environment settings. Initialize it before reading flags: ```ts import { ReflagClient } from "@reflag/node-sdk"; @@ -36,7 +38,7 @@ export const reflag = new ReflagClient({ await reflag.initialize(); ``` -## Read flags +Then read a flag for a user and company: ```ts const context = { @@ -44,79 +46,66 @@ const context = { company: { id: "acme", plan: "enterprise" }, }; -const enabled = reflag.getFlag(context, "new-editor"); // boolean; implicit false -const model = reflag.getFlag(context, "model", "quick"); // string -const limits = reflag.getFlag(context, "limits", { maxItems: 10 }); // { maxItems: number } +if (reflag.getFlag(context, "new-editor")) { + // Show the new editor +} ``` -`getFlag()` returns a Boolean, string, number, array, object, or null. Without a default it is a Boolean read: unavailable or non-Boolean values return `false`. With a positional default, missing values use that default. Valid `false`, `0`, empty strings, arrays, and objects are preserved rather than replaced by truthiness checks. +The SDK downloads your flag definitions and evaluates flags locally, so reads don't make network requests. Keep the secret key on your server. + +## Read flags + +Without a default, `getFlag()` returns a Boolean. You get `false` if the flag is missing or isn't a Boolean. -Non-null defaults specify the expected JSON category: Boolean, number, string, array, or object. A category mismatch logs a warning without the payload and returns the default. This is not nested payload validation: object properties and array elements must still match your authored schema. Use an explicit `null` default for arbitrary JSON or nullable/off selections, and narrow the result before accessing object fields: +To read a configuration value, pass a default. The return type follows the default, and you get the default back if the flag is missing or holds a different type of value: ```ts -const payload = reflag.getFlag(context, "nullable-settings", null); // FlagValue -// Authored null is preserved, as are any other valid JSON values. Missing uses null. +const model = reflag.getFlag(context, "model", "quick"); // string +const limits = reflag.getFlag(context, "limits", { maxItems: 10 }); // { maxItems: number } +const payload = reflag.getFlag(context, "nullable-settings", null); // any JSON value; narrow it yourself ``` -Defaults infer useful types without generated declarations, including widening primitive literals. Readonly defaults are accepted; results and defaults are returned as independent copies. Defaults are ordinary JSON payloads, with no reserved property names. +The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. -Each call immediately registers a check for the requested root, including when you do not subsequently use its return value. Dependencies traversed internally do not register extra checks. Delivery is buffered and rate-limited. A check records the selected **variant key**, never the JSON payload: +`getFlags(context)` returns all flag values as a record; a value can be `undefined` if the flag is unavailable. -```ts -{ - type: "feature-flag-event", - action: "check", - key: "model", - evalResult: "quality", - sourceVersionId: "version-id", - flagStateVersion: 42, - evalContext: { company: { id: "acme", plan: "enterprise" } }, -} -``` +Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. + +## Bind a client to a request -Boolean selections send `"true"` / `"false"` while returning Boolean values. Caller defaults, including category-mismatch defaults, do not claim an authored selection: their checks omit `evalResult` and `sourceVersionId`. Check deduplication includes normalized context, selection identity, root version, and snapshot version. Equal-valued variants are not interchangeable selections. `getFlags()` returns a record of flag values, without per-root caller defaults; unavailable batch values may be `undefined`. +To avoid passing the context on every call, bind it once, for example per request: ```ts -const values = reflag.getFlags(context); // value record; checks each returned root const bound = reflag.bindClient(context); -const value = bound.getFlag("model", "quick"); -const allValues = bound.getFlags(); -// Ordinary usage tracking is separate from flag checks. -await bound.track("Document created", { attributes: { source: "editor" } }); -await reflag.flush(); +const model = bound.getFlag("model", "quick"); +const allValues = bound.getFlags(); ``` -Binding queues user/company attributes and their association even if the client is subsequently used only for tracking or remote reads. Synchronization is asynchronous and respects offline/tracking guards; failures are logged. - -Local reads made before initialization include a `CLIENT_NOT_INITIALIZED` diagnostic in their check's optional `evalErrors`. Targeting diagnostics retain their code, field/operator when applicable, message, and dependency origin. Remote evaluation does not require the local definition cache to be initialized, and bootstrap/diagnostic access does not itself register checks. +Binding also sends the user's and company's attributes to Reflag, so you can target and filter by them. -`enableTracking: false` disables checks, context synchronization, and bound-client usage tracking. Explicit calls to the root client's `track()`, `updateUser()`, and `updateCompany()` remain separate operations. +## Track usage -## Evaluation and synchronization +```ts +await bound.track("Document created", { attributes: { source: "editor" } }); +``` -The SDK fetches a complete `{ flags, segments }` graph from secret-key-only `GET /flags`. Definitions are validated and prepared before the flags, segments, and snapshot version replace the current cache together. Malformed graphs and stale responses cannot replace last-known-good state. +Configure your flag's adoption rules to match the event names you send. Events are sent in batches. Call `await reflag.flush()` to send any queued events, for example before your process exits. -`getFlag()` evaluates only its root and dependencies. `getFlags()` evaluates the collection. References are reevaluated on every traversal: there is **no context/dependency-result caching**. Only immutable definition preparation is retained. Returned objects are independent copies, so changing a value cannot mutate the saved definitions. +## Keep flags up to date -Synchronization modes: +The client keeps flag definitions up to date in the background. Choose how with `flagsSyncMode`: -- `push` (default): authenticated SSE updates with reconnect handling. -- `polling`: periodic background refreshes. -- `in-request`: request-driven refreshes, suitable for constrained runtimes. +- `push` (default): receive updates as soon as flags change. +- `polling`: refresh periodically. +- `in-request`: refresh when flags are read, for environments without long-running background work. -```ts -await reflag.refreshFlags(); -await reflag.refreshFlags(42); // request at least this snapshot version -const definitions = reflag.getFlagDefinitions(); // { flags, segments }, not an array -``` - -Refreshes are throttled. In-request mode can queue a refresh during the throttle window until a later access; a refresh call is not an unconditional synchronization barrier. - -Ordinary warm `/flags` refreshes send `If-None-Match` when the accepted snapshot has an ETag. A bodyless `304` retains the complete prepared graph and version while resetting freshness, without recompiling or saving it again. Cold/fallback initialization and version-targeted requests remain unconditional. Custom HTTP clients can return the exact optional `HttpClientResponse.etag` to enable this behavior; clients without one continue to use full GETs. Validators are enabled only after the snapshot's fallback save succeeds. Failed or pending saves leave refreshes unconditional, and rejected snapshots cannot replace a validator or overwrite fallback storage. +Call `await reflag.refreshFlags()` to request a refresh yourself. If a refresh fails, the client keeps using the flags it already has. ## Fallback providers +A fallback provider saves the latest flag definitions so your service can start even if Reflag is unreachable: + ```ts import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; @@ -127,23 +116,9 @@ const client = new ReflagClient({ await client.initialize(); ``` -Live state is primary. When the initial live fetch fails, the SDK can load a saved complete collection. Later outages retain the in-memory graph rather than reloading older fallback state. Accepted live snapshots are saved in order; `flush()` also waits for pending saves. +The client uses saved definitions only when it can't fetch them at startup. Built-in providers are `file`, `redis`, `s3`, `gcs` and `static`. You can also implement your own `FlagsFallbackProvider`. -Available providers: `static`, `file`, `redis`, `s3`, and `gcs`, plus custom `FlagsFallbackProvider` implementations. A snapshot contains: - -```ts -{ - version: 2, - savedAt: "2026-01-01T00:00:00.000Z", - flagStateVersion: 42, - flags: [/* compiled flags */], - segments: [/* compiled segment predicates */], -} -``` - -Built-in files/S3/GCS objects use `flags-fallback-v2-.json`; Redis uses `:v2:`. - -A static fallback can contain any JSON values: +A static provider takes fixed values: ```ts fallbackProviders.static({ @@ -151,29 +126,32 @@ fallbackProviders.static({ }); ``` -Static values, `fallbackFlags`, and overrides do not identify authored variants. Their checks omit `evalResult` and `sourceVersionId`; they must not claim exposure to an authored selection. Restored real collection snapshots retain their real selection/version metadata. Providers are not loaded in offline mode. - ## Overrides and tests +Use offline mode and overrides to run tests without contacting Reflag: + ```ts const client = new ReflagClient({ offline: true, flagOverrides: { "new-editor": true, limits: { maxItems: 5 } }, }); await client.initialize(); + client.setFlagOverrides({ model: "quick" }); + const remove = client.pushFlagOverrides((context) => ({ model: context.company?.id === "qa" ? "quality" : "quick", })); remove(); + client.clearFlagOverrides(); ``` -Overrides are direct JSON values. Pushed layers win over base overrides and can be removed independently. They apply **after evaluation**, so overriding a dependency's returned value does not rewrite dependent flag evaluations. Offline mode does not fetch, load a provider, or send tracking events. +Overrides pushed with `pushFlagOverrides()` take precedence over base overrides and can be removed independently. In offline mode, the client makes no network requests and sends no events. -## Typed flags +## Type safety -Generated declarations are optional. Singular reads infer their return type from the default, or return Boolean when no default is supplied. Optionally augment `Flags` to constrain keys, check non-null defaults against each key's value schema, and type batch records: +Optionally declare your flags to get autocompletion for keys, type checks for defaults and typed `getFlags()` results: ```ts declare module "@reflag/node-sdk" { @@ -183,35 +161,25 @@ declare module "@reflag/node-sdk" { limits: { maxItems: number } | null; } } - -const model = reflag.getFlag(context, "model", "quick"); // string -const models = reflag.getFlags(context); // models.model: "quick" | "quality" | undefined ``` -Augmentation rejects defaults with the wrong category, missing required properties, or incompatible nested types. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request, and bare/`undefined` reads still return Boolean. Return types continue to be inferred and widened from the default; generated types do not add nested runtime validation. The Reflag CLI generates schemas from current production-environment variants. See the Express example for a typed integration. +The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you. Declarations are checked at compile time only. + +## Bootstrap the browser -## Bootstrap state +To render flags in the browser without waiting for a network request, evaluate them on the server and pass the result to the Browser, React or Vue SDK's bootstrap option: ```ts const bootstrap = reflag.getFlagsForBootstrap(context); -// { protocolVersion: 2, context, flags: { model: { resolved, value, -// variantKey, sourceVersionId, matchedRuleId, ruleResults, errors, ... } }, -// flagStateVersion } ``` -Bootstrap uses batch evaluation and preserves selection metadata and raw context. It does **not** register browser checks. Local overrides/value-only fallbacks carry their values without fabricated authored-selection metadata. - -Pass the entire envelope to the Browser, React or Vue SDK's bootstrap option, not just its `flags` property. Use your framework's safe serialization mechanism and never expose secret keys or server-only context in public bootstrap data. +Pass the whole object, serialized with your framework's usual mechanism. Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. ## Remote evaluation +To evaluate flags on Reflag's servers instead of locally, use the remote methods: + ```ts -const enabled = await reflag.getFlagRemote( - "new-editor", - undefined, - "user-1", - "acme", -); const model = await reflag.getFlagRemote("model", "quick", "user-1", "acme"); const boundModel = await reflag .bindClient(context) @@ -221,21 +189,23 @@ const values = await reflag.getFlagsRemote("user-1", "acme", { }); ``` -These methods use `/flags/evaluated` and return direct values. Singular remote reads use the same defaults, category checks, and JSON validation as local reads. The root `getFlagRemote(key, defaultValue, userId?, companyId?, context?)` places the default second; use `undefined` for an implicit Boolean read when passing explicit IDs. `getFlagsRemote(userId?, companyId?, context?)` returns a record of flag values. - -Each requested singular root registers a check, including a default after a failed/missing remote evaluation, unless tracking is disabled. Only accepted authored selections retain the server's selection/version metadata. Explicit IDs, including numeric zero, take precedence over IDs in additional context. Stored attribute updates are asynchronous; remote evaluation need not immediately observe a just-sent update. +On the root client, the default comes second: `getFlagRemote(key, defaultValue, userId?, companyId?, context?)`. Pass `undefined` as the default for a Boolean read. ## Edge runtimes -Use `EdgeClient` with Node compatibility enabled. It selects in-request synchronization. Call `ctx.waitUntil(client.flush())` before returning from a Worker so queued events and refresh work can complete. +Use `EdgeClient` in edge runtimes such as Cloudflare Workers, with Node.js compatibility enabled. It refreshes flags as they're read. Call `ctx.waitUntil(client.flush())` before returning from a Worker so queued events are sent. ## Configuration -Configuration precedence is constructor options, environment variables, then `reflag.config.json`. Supported environment variables include `REFLAG_SECRET_KEY`, `REFLAG_API_BASE_URL`, `REFLAG_LOG_LEVEL`, `REFLAG_OFFLINE`, `REFLAG_CONFIG_FILE`, and Boolean override lists `REFLAG_FLAGS_ENABLED` / `REFLAG_FLAGS_DISABLED`. +Options can be set in the constructor, through environment variables, or in `reflag.config.json`, in that order of precedence. + +Environment variables include `REFLAG_SECRET_KEY`, `REFLAG_API_BASE_URL`, `REFLAG_LOG_LEVEL`, `REFLAG_OFFLINE`, `REFLAG_CONFIG_FILE`, and `REFLAG_FLAGS_ENABLED` / `REFLAG_FLAGS_DISABLED` to override Boolean flags. + +Constructor options include `logger`, `httpClient`, `flagsSyncMode`, `fetchTimeoutMs`, `flagsFetchRetries`, `flagsFallbackProvider`, `flagOverrides`, `enableTracking`, `offline` and `batchOptions` (`maxSize`, `intervalMs`, `flushOnExit`). -Constructor options also include a custom `logger` / `httpClient`, `flagsSyncMode`, `flagsPushUrl`, `fetchTimeoutMs`, `flagsFetchRetries`, `flagsFallbackProvider`, direct-value `flagOverrides`, and `batchOptions` (`maxSize`, `intervalMs`, `flushOnExit`). `emitEvaluationEvents` is deprecated and has no effect. +## Shutting down -Invalid options/context or non-JSON defaults can throw. Network or definition-refresh failures are logged and retain usable state. Singular reads use their caller default (implicit `false`) without fabricating an authored false selection; batch reads retain raw values/`undefined`. Call `await client.flush()` before shutting down, then `client.destroy()` to stop background work. `batchOptions.flushOnExit` only flushes on natural Node process exit (`beforeExit`); it does not install signal handlers or force application shutdown. For signal-driven shutdown or an explicit `process.exit()`, await `flush()` in the application's own shutdown hook before exiting. +Before your process exits, call `await reflag.flush()` to send queued events, then `reflag.destroy()` to stop background work. `batchOptions.flushOnExit` flushes only when Node exits on its own; if you exit on a signal or call `process.exit()`, call `flush()` in your shutdown handler first. ## License diff --git a/sdk/@reflag/node-sdk/globals.md b/sdk/@reflag/node-sdk/globals.md index 82a05a7..86ec85c 100644 --- a/sdk/@reflag/node-sdk/globals.md +++ b/sdk/@reflag/node-sdk/globals.md @@ -15,7 +15,7 @@ pagination: # @reflag/node-sdk -This documentation covers SDK v2. +This page covers SDK v2. ## Classes diff --git a/sdk/@reflag/react-sdk/README.md b/sdk/@reflag/react-sdk/README.md index cdf3a50..844c1af 100644 --- a/sdk/@reflag/react-sdk/README.md +++ b/sdk/@reflag/react-sdk/README.md @@ -15,16 +15,20 @@ pagination: # Reflag React SDK -Feature flags and JSON configuration for React, backed by the [Browser SDK](../../../supported-languages/browser-sdk/README.md). +Feature flags, remote configuration, usage tracking and feedback for React applications. Built on the [Browser SDK](../../../supported-languages/browser-sdk/README.md). -This documentation covers SDK v2. +This page covers SDK v2. -## Setup +## Get started + +Install the SDK: ```sh npm install @reflag/react-sdk ``` +Wrap your application in `ReflagProvider` with your **publishable** key and the signed-in user's context: + ```tsx import { ReflagProvider } from "@reflag/react-sdk"; @@ -39,40 +43,53 @@ import { ReflagProvider } from "@reflag/react-sdk";
; ``` -Provider options forward Browser SDK settings, including `logger`, `debug`, `enableTracking`, `offline`, cache/fallback options, `toolbar`, `feedback`, `credentials` and API origins. A custom logger takes precedence over debug logging. Live updates default to true; set `enableLiveFlagUpdates={false}` to disable them. - -## `useFlag(key, defaultValue?)` +Then read a flag in any component: ```tsx import { useFlag, useTrack } from "@reflag/react-sdk"; function Huddles() { - const enabled = useFlag("huddles"); // boolean, implicit false - const settings = useFlag("huddle-settings", { maxParticipants: 10 }); + const enabled = useFlag("huddles"); const track = useTrack(); if (!enabled) return null; - return ( - - ); + return ; } ``` -Bare reads return Boolean/false, including while initial data is unavailable. A positional default infers widened direct types, even without generated declarations: +## Read flags + +Without a default, `useFlag()` returns a Boolean. You get `false` while flags are loading, and if the flag is missing or isn't a Boolean. + +To read a configuration value, pass a default. The return type follows the default, and you get the default back while loading, or if the flag is missing or holds a different type of value: + +```tsx +const settings = useFlag("huddle-settings", { maxParticipants: 10 }); +// settings.maxParticipants: number -```ts useFlag("model", "quick"); // string useFlag("limit", 10); // number -useFlag("settings", { model: "quick" }); // { model: string } -useFlag("nullable-settings", null); // FlagValue: arbitrary JSON +useFlag("nullable-settings", null); // any JSON value; narrow it yourself ``` -Non-null defaults enforce only the top-level JSON category (Boolean/number/string/array/object). Mismatches return the default and warn without logging the payload. Explicit null accepts authored null and all other JSON; missing values return null. Accepted false, zero and empty strings are preserved. Nested fields/elements are not schema-validated. Values/defaults are independent mutable copies; readonly defaults are accepted. +The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. + +Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. -`useFlag` returns immediately, using the default while flags load. Use `useIsLoading()` or the provider's `loadingComponent` for an explicit loading UI, or `useFlagSuspense()` to wait with React Suspense. +## Loading states and Suspense + +`useFlag()` returns immediately and never suspends. To show a loading UI, use `useIsLoading()` or the provider's `loadingComponent` prop: + +```tsx +} +> + + +``` -## `useFlagSuspense(key, defaultValue?)` +To wait for flags with React Suspense, use `useFlagSuspense()`. It takes the same arguments as `useFlag()`: ```tsx import { Suspense } from "react"; @@ -88,50 +105,34 @@ function Model() {
; ``` -This hook has the same Boolean/default-based return types. It waits for initialization before reading. Once initialization settles, missing flags return their default rather than suspending forever. Bootstrap values can render immediately. Suspended attempts do not register a root read before data is ready. +## Track usage and feedback -The provider's `suspense` prop configures **`useOptInFlags` only**. Use `useFlagSuspense` for flag reads with Suspense. - -## Checks and usage tracking - -A completed getter/hook read registers its requested-root check immediately, even if the value is ignored. Actual delivery remains buffered and identity-aware rate-limited by the Browser SDK. Checks contain selected variant/source/snapshot identity, not payloads. Defaults, category mismatches and local overrides never invent authored selections. Diagnostic/bootstrap inspection registers no checks. - -Track application usage and collect feedback with these hooks: - -```ts +```tsx const track = useTrack(); await track("Started huddle", { button: "cta" }); + const requestFeedback = useRequestFeedback(); requestFeedback({ flagKey: "huddles", title: "How did it go?" }); + const sendFeedback = useSendFeedback(); await sendFeedback({ flagKey: "huddles", score: 5 }); ``` -See [Browser feedback documentation](../../../supported-languages/browser-sdk/feedback.md) for UI/prompt configuration. +Configure your flag's adoption rules to match the event names you send. See the [Browser feedback documentation](../../../supported-languages/browser-sdk/feedback.md) to configure feedback prompts and the feedback UI. -## Optional key registration - -```ts -import "@reflag/react-sdk"; -declare module "@reflag/react-sdk" { - interface Flags { - huddles: boolean; - "huddle-settings": { maxParticipants: number }; - } -} -``` +## Update context -Registration constrains keys and checks non-null defaults against the registered value schema, including required and nested properties. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request; bare/`undefined` reads remain Boolean. The positional default still determines the widened return type, and generated declarations do not add nested runtime validation. The same rules apply to `useFlagSuspense`. The Reflag CLI can generate these declarations from current production-environment variants. +`useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return functions that merge new attributes into the current context. To replace the whole context, call `useClient().setContext(context)`. Flag values are refetched for the new context. -## Bootstrap and SSR +## Bootstrap from the server -On the server, use the Node.js SDK: +To render flags immediately, without waiting for a network request, evaluate them on your server with the **Node.js SDK**: ```ts const flags = serverClient.getFlagsForBootstrap(context); ``` -Pass the **entire** safe, serialized envelope to the client provider: +Then pass the whole result to `ReflagBootstrappedProvider`, serialized with your framework's usual mechanism: ```tsx import { ReflagBootstrappedProvider } from "@reflag/react-sdk"; @@ -141,29 +142,59 @@ import { ReflagBootstrappedProvider } from "@reflag/react-sdk";
; ``` -The envelope includes `protocolVersion: 2`, context, evaluated flag results and optional `flagStateVersion`. Use a snapshot version for live updates; later refreshes use browser-visible context. Do not send secrets/server-only attributes to the browser. Disable live updates if later browser evaluation must not replace server-only results. - -For an existing Browser SDK client, use ``. The provider does not own its lifecycle; initialize/stop externally, except that a suspending read can start on-demand initialization. - -## Context, loading and events - -- `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return async shallow-update functions. `useClient().setContext(context)` replaces the whole context. -- Context changes clear old-context values while fetching. Stale/in-flight responses cannot replace a newer context/snapshot. -- `useIsLoading()` returns provider loading state. `loadingComponent` and `initialLoading` configure initial presentation; they are not getter arguments. -- `useClient()` returns the underlying Browser client. Its `getFlags()` returns direct values/checks; `getFlagResults()` is diagnostic-only. -- `useOnEvent(type, handler, client?)` subscribes and unsubscribes on unmount. A supplied external client works without a provider. +Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, set `enableLiveFlagUpdates={false}`. -## Opt-in hooks +## Let users opt in to flags ```tsx const { flags, isLoading } = useOptInFlags(); const setOptIn = useSetOptIn(); + await setOptIn("huddles", { optedIn: true }); await setOptIn("huddles", { optedIn: false, scope: "company" }); ``` -Metadata arrives with the initial evaluation for regular providers. Bootstrapped providers fetch missing metadata on demand from `/flags/evaluated` without replacing server-derived values. `isLoading` covers initialization and metadata retrieval; it settles on success or failure. Metadata presentation includes `isEnabled` and membership fields, separately from direct flag reads. User/company grants remain independent. Mutations confirm versioned evaluation and membership in a single refresh. +Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent. Check `isLoading` before rendering an empty state. The provider's `suspense` prop, or `useOptInFlags({ suspense: true })`, makes this hook suspend instead. See [Beta feature opt-in](https://docs.reflag.com/guides/self-opt-in) for a complete example. + +## Toolbar + +The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` prop to show it elsewhere, for example to internal users in production: + +```tsx + + + +``` + +## Type safety + +Optionally declare your flags to get autocompletion for keys and type checks for defaults: + +```ts +import "@reflag/react-sdk"; + +declare module "@reflag/react-sdk" { + interface Flags { + huddles: boolean; + "huddle-settings": { maxParticipants: number }; + } +} +``` + +The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you. Declarations are checked at compile time only. + +## Use an existing client + +`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to ``; your application is then responsible for initializing and stopping it. `useOnEvent(type, handler)` subscribes to client events and unsubscribes when the component unmounts. + +## Configuration + +The provider accepts the Browser SDK's configuration options, such as `fallbackFlags`, `enableTracking`, `offline`, `feedback` and `logger`, as props. Live updates are on by default in React; set `enableLiveFlagUpdates={false}` to turn them off. Set `debug` to log to the console. -`useOptInFlags({ suspense: true | false })` retains its own per-hook loading options and may inherit provider `suspense`. These options are unrelated to the positional payload defaults used by `useFlag` / `useFlagSuspense`. +For Content Security Policy requirements and the full list of options, see the [Browser SDK](../../../supported-languages/browser-sdk/README.md). Using v1? [Legacy docs](../../../legacy/v1/react-sdk/README.md) · [Upgrade guide](../../../supported-languages/migrating-from-v1.md). diff --git a/sdk/@reflag/react-sdk/globals.md b/sdk/@reflag/react-sdk/globals.md index 4617119..09fef1e 100644 --- a/sdk/@reflag/react-sdk/globals.md +++ b/sdk/@reflag/react-sdk/globals.md @@ -15,7 +15,7 @@ pagination: # @reflag/react-sdk -This documentation covers SDK v2. +This page covers SDK v2. ## Interfaces diff --git a/sdk/@reflag/vue-sdk/README.md b/sdk/@reflag/vue-sdk/README.md index 04acebd..c30a82c 100644 --- a/sdk/@reflag/vue-sdk/README.md +++ b/sdk/@reflag/vue-sdk/README.md @@ -15,16 +15,20 @@ pagination: # Reflag Vue SDK (beta) -Reactive feature flags and JSON configuration for Vue 3, backed by the [Browser SDK](../../../supported-languages/browser-sdk/README.md). +Feature flags, remote configuration, usage tracking and feedback for Vue 3 applications. Built on the [Browser SDK](../../../supported-languages/browser-sdk/README.md). -This documentation covers SDK v2. +This page covers SDK v2. -## Setup +## Get started + +Install the SDK: ```sh npm install @reflag/vue-sdk ``` +Wrap your application in `ReflagProvider` with your **publishable** key and the signed-in user's context: + ```vue ``` -`useFlag()` returns a reactive ref containing the flag value. Vue unwraps refs in templates; use `.value` in script. +## Read flags + +`useFlag()` returns a ref that updates when the flag changes. Vue unwraps refs in templates; use `.value` in script. + +Without a default, the ref holds a Boolean. It is `false` while flags are loading, and if the flag is missing or isn't a Boolean. + +To read a configuration value, pass a default. The type follows the default, and the ref holds the default while loading, or if the flag is missing or holds a different type of value: ```ts -useFlag("release"); // ShallowRef -useFlag("model", "quick"); // ShallowRef -useFlag("limit", 10); // ShallowRef -useFlag("settings", { model: "quick" }); // ShallowRef<{ model: string }> -useFlag("nullable-settings", null); // ShallowRef +const settings = useFlag("huddle-settings", { maxParticipants: 10 }); +// settings.value.maxParticipants: number + +useFlag("model", "quick"); // Ref of string +useFlag("limit", 10); // Ref of number +useFlag("nullable-settings", null); // any JSON value; narrow it yourself ``` -Defaults are positional JSON; literals widen without generated types. Non-null defaults require the same top-level category (Boolean/number/string/array/object), otherwise the default is returned with a payload-safe warning. Null explicitly accepts arbitrary JSON, including authored null; missing returns null. Valid false/zero/empty strings are preserved. Nested payload schemas are not validated by the SDK. Returned values/defaults are independent copies; readonly defaults are accepted. +The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. + +Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. + +## Loading states + +`useIsLoading()` returns a Boolean ref that is `true` while the provider loads flags. You can also put loading content in the provider's `#loading` slot, as in the example above. -The ref updates when evaluated flags change. A composable read registers the requested root through the Browser SDK, even if its result is ignored; refresh-driven rereads are identity-aware rate-limited and delivered in batches. Diagnostics/bootstrap inspection register none. Checks carry genuine selected key/source/snapshot identity, never payloads or invented selections for defaults/overrides. +## Track usage and feedback + +```ts +const track = useTrack(); +await track("Started huddle", { button: "cta" }); + +const requestFeedback = useRequestFeedback(); +requestFeedback({ flagKey: "huddles", title: "How did it go?" }); + +const sendFeedback = useSendFeedback(); +await sendFeedback({ flagKey: "huddles", score: 5 }); +``` -## Loading, context and client access +Configure your flag's adoption rules to match the event names you send. See the [Browser feedback documentation](../../../supported-languages/browser-sdk/feedback.md) to configure feedback prompts and the feedback UI. -- `useIsLoading()` returns a Boolean ref for provider loading; the `#loading` slot and `initialLoading` control initial presentation. -- `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return async shallow-update functions. -- `useClient()` exposes the Browser client, including `setContext(context)`, `refresh()` and `setFlagOverride(key, value)`. Undefined clears an override; null is a JSON override. -- `getFlags()` returns direct values and registers returned-root checks. Use `getFlagResults()` for tooling without checks. -- `useOnEvent(type, handler, client?)` subscribes on mount and unsubscribes on unmount. An external client may be supplied explicitly. +## Update context -A context change clears old values while fetching. Late responses for previous contexts or lower snapshot versions cannot replace accepted state. Browser fetching uses `/flags/evaluated` and never re-evaluates/caches dependencies locally. +`useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return functions that merge new attributes into the current context. To replace the whole context, call `useClient().setContext(context)`. Flag values are refetched for the new context. -## Bootstrap +## Bootstrap from the server -On the server, use the Node.js SDK and your framework's safe serialization mechanism: +To render flags immediately, without waiting for a network request, evaluate them on your server with the **Node.js SDK**: ```ts const flags = serverClient.getFlagsForBootstrap(context); ``` +Then pass the whole result to `ReflagBootstrappedProvider`, serialized with your framework's usual mechanism: + ```vue ``` -Pass the entire envelope (`protocolVersion: 2`, context, evaluated flags and optional snapshot version). A snapshot version is required for live updates. Never expose secret keys/server-only attributes in bootstrap data; later refreshes use browser-visible context, so disable live updates when they must not replace server-only evaluations. - -`ReflagClientProvider` accepts an externally initialized Browser SDK client. Its lifecycle belongs to the application. +Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, set `:enable-live-flag-updates="false"`. -## Opt-in, tracking and feedback +## Let users opt in to flags ```ts -const { flags, isLoading } = useOptInFlags(); // refs to metadata/list loading +const { flags, isLoading } = useOptInFlags(); const setOptIn = useSetOptIn(); + await setOptIn("huddles", { optedIn: true }); await setOptIn("huddles", { optedIn: false, scope: "company" }); +``` -const track = useTrack(); -await track("Started huddle", { button: "cta" }); -const requestFeedback = useRequestFeedback(); -requestFeedback({ flagKey: "huddles", title: "How did it go?" }); -const sendFeedback = useSendFeedback(); -await sendFeedback({ flagKey: "huddles", score: 5 }); +Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent. Check `isLoading` before rendering an empty state. + +## Toolbar + +The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` prop to show it elsewhere, for example to internal users in production: + +```vue + + + ``` -Opt-in metadata arrives with ordinary `/flags/evaluated` responses. Bootstrapped providers fetch missing metadata on demand from the same endpoint without replacing server-derived values or provenance; loading settles on success or failure. User/company grants remain independent; successful mutations confirm versioned evaluation and membership in a single refresh. The metadata list retains presentation/membership fields such as `isEnabled`; ordinary reads remain direct values. +To override a flag from code, call `useClient().setFlagOverride(key, value)`. Pass `undefined` to remove the override. -`enableTracking: false` disables checks and ordinary tracking. Offline mode skips HTTP/tracking. See [Browser feedback documentation](../../../supported-languages/browser-sdk/feedback.md) for prompting/UI options. +## Type safety -## Optional key registration +Optionally declare your flags to get autocompletion for keys and type checks for defaults: ```ts import "@reflag/vue-sdk"; + declare module "@reflag/vue-sdk" { interface Flags { huddles: boolean; @@ -141,6 +170,16 @@ declare module "@reflag/vue-sdk" { } ``` -Registration constrains keys and checks non-null defaults against the registered value schema, including required and nested properties. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request; bare/`undefined` reads remain Boolean refs. Positional defaults still determine widened direct-value types, and generated declarations do not add nested runtime validation. The Reflag CLI can generate these schemas from current production-environment variants with `--format vue`. +The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you with `--format vue`. Declarations are checked at compile time only. + +## Use an existing client + +`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to `ReflagClientProvider`; your application is then responsible for initializing and stopping it. `useOnEvent(type, handler)` subscribes to client events and unsubscribes when the component unmounts. + +## Configuration + +The provider accepts the Browser SDK's configuration options, such as `fallbackFlags`, `enableTracking`, `offline`, `feedback` and `logger`, as props. Live updates are on by default in Vue; set `:enable-live-flag-updates="false"` to turn them off. Set `debug` to log to the console. + +For Content Security Policy requirements and the full list of options, see the [Browser SDK](../../../supported-languages/browser-sdk/README.md). Using v1? [Legacy docs](../../../legacy/v1/vue-sdk/README.md) · [Upgrade guide](../../../supported-languages/migrating-from-v1.md). diff --git a/sdk/@reflag/vue-sdk/globals.md b/sdk/@reflag/vue-sdk/globals.md index 6e59f0e..366e091 100644 --- a/sdk/@reflag/vue-sdk/globals.md +++ b/sdk/@reflag/vue-sdk/globals.md @@ -15,7 +15,7 @@ pagination: # @reflag/vue-sdk -This documentation covers SDK v2. +This page covers SDK v2. ## Interfaces diff --git a/sdk/documents/browser-sdk/FEEDBACK.md b/sdk/documents/browser-sdk/FEEDBACK.md index 20637a1..5839501 100644 --- a/sdk/documents/browser-sdk/FEEDBACK.md +++ b/sdk/documents/browser-sdk/FEEDBACK.md @@ -20,7 +20,7 @@ about particular flags. ![image](https://github.com/reflagcom/javascript/assets/34348/c387bac1-f2e2-4efd-9dda-5030d76f9532) -This documentation covers SDK v2. +This page covers SDK v2. ## Global feedback configuration @@ -284,7 +284,7 @@ See examples below. ![image](https://github.com/reflagcom/javascript/assets/331790/68805b38-e9f6-4de5-9f55-188216983e3c) -See [default English localization keys](https://github.com/reflagcom/javascript/tree/23b018b17cd0755fa6512cd209265cdac5f8fb0d/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) +See [default English localization keys](https://github.com/reflagcom/javascript/tree/f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) for a reference of what translation keys can be supplied. ### Static language configuration @@ -398,7 +398,7 @@ For example, a dark mode theme might look like this: } ``` -Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/23b018b17cd0755fa6512cd209265cdac5f8fb0d/packages/browser-sdk/src/feedback/ui/index.css). +Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684/packages/browser-sdk/src/feedback/ui/index.css). ## Using your own UI to collect feedback @@ -423,7 +423,7 @@ Reflag API. ### Manual feedback collection with custom UI Examples of a HTML-form that collects the relevant data can be found -in [feedback.html](https://github.com/reflagcom/javascript/tree/23b018b17cd0755fa6512cd209265cdac5f8fb0d/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/23b018b17cd0755fa6512cd209265cdac5f8fb0d/packages/browser-sdk/example/feedback/Feedback.jsx). +in [feedback.html](https://github.com/reflagcom/javascript/tree/f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684/packages/browser-sdk/example/feedback/Feedback.jsx). Once you have collected the feedback data, pass it along to `reflagClient.feedback()`: diff --git a/sdk/documents/react-sdk/README.md b/sdk/documents/react-sdk/README.md index cdf3a50..844c1af 100644 --- a/sdk/documents/react-sdk/README.md +++ b/sdk/documents/react-sdk/README.md @@ -15,16 +15,20 @@ pagination: # Reflag React SDK -Feature flags and JSON configuration for React, backed by the [Browser SDK](../../../supported-languages/browser-sdk/README.md). +Feature flags, remote configuration, usage tracking and feedback for React applications. Built on the [Browser SDK](../../../supported-languages/browser-sdk/README.md). -This documentation covers SDK v2. +This page covers SDK v2. -## Setup +## Get started + +Install the SDK: ```sh npm install @reflag/react-sdk ``` +Wrap your application in `ReflagProvider` with your **publishable** key and the signed-in user's context: + ```tsx import { ReflagProvider } from "@reflag/react-sdk"; @@ -39,40 +43,53 @@ import { ReflagProvider } from "@reflag/react-sdk";
; ``` -Provider options forward Browser SDK settings, including `logger`, `debug`, `enableTracking`, `offline`, cache/fallback options, `toolbar`, `feedback`, `credentials` and API origins. A custom logger takes precedence over debug logging. Live updates default to true; set `enableLiveFlagUpdates={false}` to disable them. - -## `useFlag(key, defaultValue?)` +Then read a flag in any component: ```tsx import { useFlag, useTrack } from "@reflag/react-sdk"; function Huddles() { - const enabled = useFlag("huddles"); // boolean, implicit false - const settings = useFlag("huddle-settings", { maxParticipants: 10 }); + const enabled = useFlag("huddles"); const track = useTrack(); if (!enabled) return null; - return ( - - ); + return ; } ``` -Bare reads return Boolean/false, including while initial data is unavailable. A positional default infers widened direct types, even without generated declarations: +## Read flags + +Without a default, `useFlag()` returns a Boolean. You get `false` while flags are loading, and if the flag is missing or isn't a Boolean. + +To read a configuration value, pass a default. The return type follows the default, and you get the default back while loading, or if the flag is missing or holds a different type of value: + +```tsx +const settings = useFlag("huddle-settings", { maxParticipants: 10 }); +// settings.maxParticipants: number -```ts useFlag("model", "quick"); // string useFlag("limit", 10); // number -useFlag("settings", { model: "quick" }); // { model: string } -useFlag("nullable-settings", null); // FlagValue: arbitrary JSON +useFlag("nullable-settings", null); // any JSON value; narrow it yourself ``` -Non-null defaults enforce only the top-level JSON category (Boolean/number/string/array/object). Mismatches return the default and warn without logging the payload. Explicit null accepts authored null and all other JSON; missing values return null. Accepted false, zero and empty strings are preserved. Nested fields/elements are not schema-validated. Values/defaults are independent mutable copies; readonly defaults are accepted. +The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. + +Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. -`useFlag` returns immediately, using the default while flags load. Use `useIsLoading()` or the provider's `loadingComponent` for an explicit loading UI, or `useFlagSuspense()` to wait with React Suspense. +## Loading states and Suspense + +`useFlag()` returns immediately and never suspends. To show a loading UI, use `useIsLoading()` or the provider's `loadingComponent` prop: + +```tsx +} +> + + +``` -## `useFlagSuspense(key, defaultValue?)` +To wait for flags with React Suspense, use `useFlagSuspense()`. It takes the same arguments as `useFlag()`: ```tsx import { Suspense } from "react"; @@ -88,50 +105,34 @@ function Model() {
; ``` -This hook has the same Boolean/default-based return types. It waits for initialization before reading. Once initialization settles, missing flags return their default rather than suspending forever. Bootstrap values can render immediately. Suspended attempts do not register a root read before data is ready. +## Track usage and feedback -The provider's `suspense` prop configures **`useOptInFlags` only**. Use `useFlagSuspense` for flag reads with Suspense. - -## Checks and usage tracking - -A completed getter/hook read registers its requested-root check immediately, even if the value is ignored. Actual delivery remains buffered and identity-aware rate-limited by the Browser SDK. Checks contain selected variant/source/snapshot identity, not payloads. Defaults, category mismatches and local overrides never invent authored selections. Diagnostic/bootstrap inspection registers no checks. - -Track application usage and collect feedback with these hooks: - -```ts +```tsx const track = useTrack(); await track("Started huddle", { button: "cta" }); + const requestFeedback = useRequestFeedback(); requestFeedback({ flagKey: "huddles", title: "How did it go?" }); + const sendFeedback = useSendFeedback(); await sendFeedback({ flagKey: "huddles", score: 5 }); ``` -See [Browser feedback documentation](../../../supported-languages/browser-sdk/feedback.md) for UI/prompt configuration. +Configure your flag's adoption rules to match the event names you send. See the [Browser feedback documentation](../../../supported-languages/browser-sdk/feedback.md) to configure feedback prompts and the feedback UI. -## Optional key registration - -```ts -import "@reflag/react-sdk"; -declare module "@reflag/react-sdk" { - interface Flags { - huddles: boolean; - "huddle-settings": { maxParticipants: number }; - } -} -``` +## Update context -Registration constrains keys and checks non-null defaults against the registered value schema, including required and nested properties. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request; bare/`undefined` reads remain Boolean. The positional default still determines the widened return type, and generated declarations do not add nested runtime validation. The same rules apply to `useFlagSuspense`. The Reflag CLI can generate these declarations from current production-environment variants. +`useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return functions that merge new attributes into the current context. To replace the whole context, call `useClient().setContext(context)`. Flag values are refetched for the new context. -## Bootstrap and SSR +## Bootstrap from the server -On the server, use the Node.js SDK: +To render flags immediately, without waiting for a network request, evaluate them on your server with the **Node.js SDK**: ```ts const flags = serverClient.getFlagsForBootstrap(context); ``` -Pass the **entire** safe, serialized envelope to the client provider: +Then pass the whole result to `ReflagBootstrappedProvider`, serialized with your framework's usual mechanism: ```tsx import { ReflagBootstrappedProvider } from "@reflag/react-sdk"; @@ -141,29 +142,59 @@ import { ReflagBootstrappedProvider } from "@reflag/react-sdk";
; ``` -The envelope includes `protocolVersion: 2`, context, evaluated flag results and optional `flagStateVersion`. Use a snapshot version for live updates; later refreshes use browser-visible context. Do not send secrets/server-only attributes to the browser. Disable live updates if later browser evaluation must not replace server-only results. - -For an existing Browser SDK client, use ``. The provider does not own its lifecycle; initialize/stop externally, except that a suspending read can start on-demand initialization. - -## Context, loading and events - -- `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return async shallow-update functions. `useClient().setContext(context)` replaces the whole context. -- Context changes clear old-context values while fetching. Stale/in-flight responses cannot replace a newer context/snapshot. -- `useIsLoading()` returns provider loading state. `loadingComponent` and `initialLoading` configure initial presentation; they are not getter arguments. -- `useClient()` returns the underlying Browser client. Its `getFlags()` returns direct values/checks; `getFlagResults()` is diagnostic-only. -- `useOnEvent(type, handler, client?)` subscribes and unsubscribes on unmount. A supplied external client works without a provider. +Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, set `enableLiveFlagUpdates={false}`. -## Opt-in hooks +## Let users opt in to flags ```tsx const { flags, isLoading } = useOptInFlags(); const setOptIn = useSetOptIn(); + await setOptIn("huddles", { optedIn: true }); await setOptIn("huddles", { optedIn: false, scope: "company" }); ``` -Metadata arrives with the initial evaluation for regular providers. Bootstrapped providers fetch missing metadata on demand from `/flags/evaluated` without replacing server-derived values. `isLoading` covers initialization and metadata retrieval; it settles on success or failure. Metadata presentation includes `isEnabled` and membership fields, separately from direct flag reads. User/company grants remain independent. Mutations confirm versioned evaluation and membership in a single refresh. +Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent. Check `isLoading` before rendering an empty state. The provider's `suspense` prop, or `useOptInFlags({ suspense: true })`, makes this hook suspend instead. See [Beta feature opt-in](https://docs.reflag.com/guides/self-opt-in) for a complete example. + +## Toolbar + +The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` prop to show it elsewhere, for example to internal users in production: + +```tsx + + + +``` + +## Type safety + +Optionally declare your flags to get autocompletion for keys and type checks for defaults: + +```ts +import "@reflag/react-sdk"; + +declare module "@reflag/react-sdk" { + interface Flags { + huddles: boolean; + "huddle-settings": { maxParticipants: number }; + } +} +``` + +The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you. Declarations are checked at compile time only. + +## Use an existing client + +`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to ``; your application is then responsible for initializing and stopping it. `useOnEvent(type, handler)` subscribes to client events and unsubscribes when the component unmounts. + +## Configuration + +The provider accepts the Browser SDK's configuration options, such as `fallbackFlags`, `enableTracking`, `offline`, `feedback` and `logger`, as props. Live updates are on by default in React; set `enableLiveFlagUpdates={false}` to turn them off. Set `debug` to log to the console. -`useOptInFlags({ suspense: true | false })` retains its own per-hook loading options and may inherit provider `suspense`. These options are unrelated to the positional payload defaults used by `useFlag` / `useFlagSuspense`. +For Content Security Policy requirements and the full list of options, see the [Browser SDK](../../../supported-languages/browser-sdk/README.md). Using v1? [Legacy docs](../../../legacy/v1/react-sdk/README.md) · [Upgrade guide](../../../supported-languages/migrating-from-v1.md). diff --git a/supported-languages/browser-sdk/README.md b/supported-languages/browser-sdk/README.md index 2724e7d..f874c65 100644 --- a/supported-languages/browser-sdk/README.md +++ b/supported-languages/browser-sdk/README.md @@ -15,16 +15,20 @@ pagination: # Reflag Browser SDK -Client-side feature flags and JSON values for [Reflag](https://reflag.com). +Feature flags, remote configuration, usage tracking and feedback for browser applications. -This documentation covers SDK v2. +This page covers SDK v2. ## Get started +Install the SDK: + ```sh npm install @reflag/browser-sdk ``` +Create a client with your **publishable** key and the signed-in user's context, then read a flag: + ```ts import { ReflagClient } from "@reflag/browser-sdk"; @@ -35,126 +39,145 @@ const reflag = new ReflagClient({ }); await reflag.initialize(); -const enabled = reflag.getFlag("huddles"); // boolean, implicit false -const settings = reflag.getFlag("assistant-settings", { model: "quick" }); -// settings: { model: string } - -if (enabled) { - // Application usage tracking is separate from reading the flag. +if (reflag.getFlag("huddles")) { await reflag.track("Started huddle"); } ``` -Use only a **publishable** key in a browser. Secret keys belong on your server. +Publishable keys are safe to ship to the browser. Keep secret keys on your server. ## Read flags +Without a default, `getFlag()` returns a Boolean. You get `false` if the flag is missing or isn't a Boolean: + ```ts -reflag.getFlag("release"); // boolean; missing/mismatched -> false -reflag.getFlag("model", "quick"); // string -reflag.getFlag("limit", 10); // number -reflag.getFlag("settings", { model: "quick" }); -reflag.getFlag("nullable-settings", null); // FlagValue (arbitrary JSON) +const enabled = reflag.getFlag("huddles"); // boolean ``` -- Defaults are positional JSON values; generation is not required for useful types. Primitive literals widen, and readonly defaults are accepted. -- A non-null default accepts only the same **top-level JSON category**: Boolean, number, string, array or object. A mismatch warns without logging the payload and returns the default. A bare read can never return a truthy object. -- Explicit `null` accepts any JSON value, including authored null. Missing values return null. -- Falsy selected values (`false`, `0`, `""`, null) are preserved when accepted by the requested category. -- Object fields and array elements are **not schema-validated**. Validate untrusted/nested payloads in your application. -- Values and defaults are returned as independent mutable copies. There are no reserved JSON property names. +To read a configuration value, pass a default. The return type follows the default, and you get the default back if the flag is missing or holds a different type of value: -`getFlags()` returns a direct-value record (entries may be undefined) and registers checks for its returned roots. `getFlagResults()` returns owned evaluated diagnostics **without checks**; it is intended for tooling, not ordinary application reads. `getFlagsForBootstrap()` serializes evaluated state without checks. +```ts +const model = reflag.getFlag("model", "quick"); // string +const limit = reflag.getFlag("limit", 10); // number +const settings = reflag.getFlag("assistant-settings", { model: "quick" }); // { model: string } +``` -## Checks and delivery +Pass `null` to accept any JSON value, then narrow it yourself: -Reading a flag registers an exposure check, even if its return value is ignored. Checks are buffered, sent through `/bulk`, and rate-limited per identity. +```ts +const value = reflag.getFlag("nullable-settings", null); +``` -A selected check carries the authored selected key as `evalResult`, its `sourceVersionId` and the available snapshot `flagStateVersion`. Payload equality is not identity: equal-valued selections or segment-only snapshot changes remain distinguishable on subsequent reads. Defaults, category mismatches, local overrides and static fallback values do not fabricate authored selections. Diagnostics and bootstrap serialization generate no checks. The server evaluates dependencies; fetching their results does not itself register reads. +The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. -`enableTracking: false` disables checks and user/company/usage tracking. `offline: true` skips HTTP and tracking. `await reflag.stop()` flushes buffered events and closes the client's background transports. +`getFlags()` returns all flag values as a record. Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. -## Context, refresh and cache +## Track usage and feedback + +```ts +await reflag.track("Started huddle", { button: "cta" }); +reflag.requestFeedback({ flagKey: "huddles", title: "How did it go?" }); +``` + +Configure your flag's adoption rules to match the event names you send. See [FEEDBACK.md](feedback.md) to configure feedback prompts and the feedback UI. + +## Update context ```ts await reflag.updateUser({ role: "admin" }); await reflag.updateCompany({ plan: "enterprise" }); await reflag.updateOtherContext({ region: "eu" }); + +// Replace the whole context, for example after the user switches company: await reflag.setContext({ user: { id: "bob" }, company: { id: "other-company" }, }); -await reflag.refresh(); ``` -`setContext()` replaces the context; update methods shallow-merge their section. User/company sections require IDs, including valid numeric zero. Context supports nested JSON and arrays. A context change clears the old context's values while fetching; stale/in-flight responses cannot replace a newer context or snapshot. +The update methods merge into their section of the context, while `setContext()` replaces all of it. User and company sections need an `id`. Flag values are refetched for the new context. -Values come from `GET /flags/evaluated`. Server evaluation retains the complete internal graph and authorized public roots. The Browser SDK does not cache dependency evaluations of its own. +## Bootstrap from the server -Constructor options include: +To render flags immediately, without waiting for a network request, evaluate them on your server with the **Node.js SDK** and pass the result to the browser: -| Option | Behavior | -| ------------------------------- | --------------------------------------------------------------------------- | -| `apiBaseUrl`, `appBaseUrl` | API origin and toolbar/feedback links | -| `credentials` | Fetch credentials mode; `include` also enables default SSE credentials | -| `timeoutMs` | Flag request timeout; default 5,000 ms | -| `staleTimeMs` | Fresh-cache duration; default 0 | -| `staleWhileRevalidate` | Serve stale cached state while revalidating; default false | -| `expireTimeMs` | Cache expiry; default 30 days | -| `storage` | Optional async storage adapter | -| `fallbackFlags` | Value record or array of enabled Boolean keys, without authored provenance | -| `enableLiveFlagUpdates` | Refresh after SSE publications; default false in Browser, true in React/Vue | -| `eventSourceFactory` | Optional EventSource-compatible transport | -| `trackingQueue` | Buffered-delivery `flushDelayMs` and `maxSize` | -| `logger`, `toolbar`, `feedback` | Logging, Boolean override toolbar and feedback options | +```ts +// On the server +const bootstrappedState = serverClient.getFlagsForBootstrap(context); +``` -Evaluated flags and overrides are cached separately. Malformed refreshes leave known-good state intact. Valid saved selections retain their provenance on restore. There is no automatic periodic HTTP fallback after an SSE failure; manual refresh/context updates remain available. +```ts +// In the browser +const reflag = new ReflagClient({ publishableKey, bootstrappedState }); +await reflag.initialize(); +``` -## Overrides and toolbar +Pass the whole object returned by `getFlagsForBootstrap()`, serialized with your framework's usual mechanism. Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. + +Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, disable live updates. + +## Let users opt in to flags ```ts -reflag.setFlagOverride("release", true); -reflag.setFlagOverride("settings", { model: "local" }); -reflag.setFlagOverride("nullable-settings", null); // a real null override -reflag.setFlagOverride("release", undefined); // clear the override +const optInFlags = reflag.getOptInFlags(); +await reflag.setOptIn("huddles", { optedIn: true }); +await reflag.setOptIn("huddles", { optedIn: false, scope: "company" }); ``` -Overrides apply after server evaluation and do not rewrite authored dependency results. The built-in toolbar appears on localhost by default and offers Boolean overrides only. It uses diagnostic access, so opening it does not register application checks. +Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent. Use `getIsLoadingOptInFlags()` and the `optInFlagsLoadingUpdated` event to show a loading state. -## Server bootstrap +## Overrides and toolbar -Generate the payload with the **Node.js SDK** on your server: +Override flags locally while developing or testing: ```ts -const bootstrappedState = serverClient.getFlagsForBootstrap(context); -// Send via your framework's safe JSON/hydration mechanism. +reflag.setFlagOverride("huddles", true); +reflag.setFlagOverride("assistant-settings", { model: "local" }); +reflag.setFlagOverride("huddles", undefined); // remove the override ``` +The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` option to show it elsewhere, for example to internal users in production: + ```ts -const reflag = new ReflagClient({ publishableKey, bootstrappedState }); -await reflag.initialize(); -const enabled = reflag.getFlag("release"); +const reflag = new ReflagClient({ + publishableKey, + toolbar: user.isInternal, // show the toolbar to internal users +}); ``` -The payload includes `protocolVersion: 2`, context, evaluated diagnostics/selections and an optional snapshot version. Pass the entire envelope as `bootstrappedState`, including its context and selection metadata. A version is required for bootstrapped live updates. Never embed secrets or server-only context in public bootstrap data. Later refreshes use browser-visible context and can differ from server-only evaluation; disable live updates when that is inappropriate. +## Events -## End-user opt-in +`on(event, handler)` subscribes to client events and returns an unsubscribe function. Events include `stateUpdated`, `flagsUpdated`, `check`, `track`, `user`, `company` and `optInFlagsLoadingUpdated`. -```ts -const options = reflag.getOptInFlags(); -const loading = reflag.getIsLoadingOptInFlags(); -await reflag.setOptIn("huddles", { optedIn: true }); -await reflag.setOptIn("huddles", { optedIn: false, scope: "company" }); -``` +## Configuration -The list contains presentation/membership metadata (`key`, `name`, `description`, `isEnabled`, `userOptedIn`, `companyOptedIn`, `isOptedIn`); this is not the ordinary flag getter API. User/company grants remain independent. The selected scope requires its ID. Successful mutations wait for versioned evaluation and membership confirmation. +| Option | Description | +| -------------------------- | --------------------------------------------------------------- | +| `fallbackFlags` | Values to use if flags can't be fetched | +| `enableLiveFlagUpdates` | Update flags when they change in Reflag; default `false` | +| `staleTimeMs` | How long cached flags count as fresh; default `0` | +| `staleWhileRevalidate` | Use stale cached flags while fetching new ones; default `false` | +| `expireTimeMs` | How long cached flags are kept; default 30 days | +| `timeoutMs` | Flag request timeout; default 5,000 ms | +| `enableTracking` | Set to `false` to stop sending checks and usage events | +| `offline` | Make no network requests, for example in tests | +| `toolbar`, `feedback` | Toolbar and feedback UI options | +| `logger` | Custom logger | +| `apiBaseUrl`, `appBaseUrl` | Override the API and app URLs | +| `credentials` | Fetch credentials mode | +| `storage` | Custom async storage for the flag cache | +| `eventSourceFactory` | Custom EventSource implementation for runtimes without one | +| `trackingQueue` | Event batching: `flushDelayMs` and `maxSize` | -Metadata arrives with ordinary `/flags/evaluated` responses and is cached with the evaluated snapshot. Bootstrapped clients whose snapshot lacks metadata fetch it on demand from the same endpoint, without replacing server-derived values or provenance with browser-context evaluations. Loading settles on success or failure, including an empty list. Opt-in mutations confirm values and membership together in one versioned refresh. `optInFlagsLoadingUpdated` and `flagsUpdated` support UI subscriptions. +Call `await reflag.stop()` to send buffered events and close the client. -## Tracking, feedback and events +## Content Security Policy (CSP) -Use `track(eventName, attributes?)`, `feedback(payload)` and `requestFeedback({ flagKey, ... })` on the client. See [FEEDBACK.md](feedback.md) for the feedback UI and prompting configuration. +If your site uses a strict Content Security Policy, allow: -`on(event, handler)` returns an unsubscribe function. Events include `stateUpdated`, `flagsUpdated` (evaluated diagnostics), `check`, `track`, `user`, `company` and `optInFlagsLoadingUpdated`. +| Directive | Value | Reason | +| ------------- | -------------------------- | ---------------------------------- | +| `connect-src` | `https://front.reflag.com` | API requests and live updates | +| `style-src` | `'unsafe-inline'` | The feedback UI uses inline styles | Using v1? [Legacy docs](../../legacy/v1/browser-sdk/README.md) · [Upgrade guide](../migrating-from-v1.md). diff --git a/supported-languages/browser-sdk/feedback.md b/supported-languages/browser-sdk/feedback.md index 24a1221..d8f780d 100644 --- a/supported-languages/browser-sdk/feedback.md +++ b/supported-languages/browser-sdk/feedback.md @@ -20,7 +20,7 @@ about particular flags. ![image](https://github.com/reflagcom/javascript/assets/34348/c387bac1-f2e2-4efd-9dda-5030d76f9532) -This documentation covers SDK v2. +This page covers SDK v2. ## Global feedback configuration @@ -284,7 +284,7 @@ See examples below. ![image](https://github.com/reflagcom/javascript/assets/331790/68805b38-e9f6-4de5-9f55-188216983e3c) -See [default English localization keys](https://github.com/reflagcom/javascript/tree/23b018b17cd0755fa6512cd209265cdac5f8fb0d/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) +See [default English localization keys](https://github.com/reflagcom/javascript/tree/f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) for a reference of what translation keys can be supplied. ### Static language configuration @@ -398,7 +398,7 @@ For example, a dark mode theme might look like this: } ``` -Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/23b018b17cd0755fa6512cd209265cdac5f8fb0d/packages/browser-sdk/src/feedback/ui/index.css). +Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684/packages/browser-sdk/src/feedback/ui/index.css). ## Using your own UI to collect feedback @@ -423,7 +423,7 @@ Reflag API. ### Manual feedback collection with custom UI Examples of a HTML-form that collects the relevant data can be found -in [feedback.html](https://github.com/reflagcom/javascript/tree/23b018b17cd0755fa6512cd209265cdac5f8fb0d/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/23b018b17cd0755fa6512cd209265cdac5f8fb0d/packages/browser-sdk/example/feedback/Feedback.jsx). +in [feedback.html](https://github.com/reflagcom/javascript/tree/f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684/packages/browser-sdk/example/feedback/Feedback.jsx). Once you have collected the feedback data, pass it along to `reflagClient.feedback()`: diff --git a/supported-languages/browser-sdk/globals.md b/supported-languages/browser-sdk/globals.md index 9580530..4804e0a 100644 --- a/supported-languages/browser-sdk/globals.md +++ b/supported-languages/browser-sdk/globals.md @@ -15,7 +15,7 @@ pagination: # @reflag/browser-sdk -This documentation covers SDK v2. +This page covers SDK v2. ## Classes diff --git a/supported-languages/migrating-from-v1.md b/supported-languages/migrating-from-v1.md index 90b8b57..081580d 100644 --- a/supported-languages/migrating-from-v1.md +++ b/supported-languages/migrating-from-v1.md @@ -4,25 +4,25 @@ description: Upgrade Browser, React, Vue and Node.js integrations from protocol # Migrating from v1 -Protocol v2 is a **breaking change** for the Browser, React, Vue and Node.js SDKs. The main SDK pages and shared guides show v2; complete [legacy v1 documentation](../legacy/v1/README.md) remains available. +Version 2 of the Browser, React, Vue and Node.js SDKs changes how you read flags, and includes breaking changes. The [v1 documentation](../legacy/v1/README.md) is still available. -{% hint style="warning" %} -The current v2 pages document `2.0.0-next.0` SDK sources. Until stable v2 packages are published, use the exact prerelease SDK/CLI versions supplied for your rollout. Do not assume an unversioned install or an `@next` tag installs v2; the `@2` commands below require a published major 2. -{% endhint %} +## What changes -## Choose a compatible toolchain +- **Flags return their value directly.** `useFlag("new-editor")` returns `true` or `false` instead of `{ isEnabled }`. +- **Remote config is a Multivariate flag.** Pass a default and get the value back, instead of reading `.config.payload`. +- **Tracking and feedback are separate.** They have their own hooks and client methods instead of being returned with a flag. +- **React's `useFlag()` no longer suspends.** Use `useFlagSuspense()` when you want Suspense. +- **v1 bootstrap data, fallback snapshots and generated types don't work with v2.** Regenerate them. -| Component | Protocol v1 | Protocol v2 | -| --- | --- | --- | -| Browser / React / Vue / Node.js SDK | Package major 1 | Package major 2 | -| Generated declarations | CLI 1, wrapper-shaped schemas | Compatible CLI 2, direct-value schemas | -| Bootstrap | V1 server and client SDKs | V2 server and client SDKs; `protocolVersion: 2` | -| Node fallback snapshots | V1 snapshots | Complete v2 collection snapshots | -| React Native / OpenFeature / Management | Follow each package's documentation | Not automatically upgraded by this migration | +React Native, OpenFeature and the Management SDK are released separately and aren't covered by this guide. -Coordinate the required server protocol, SDKs, generated declarations and authored flag values. A server rollout does not itself publish SDK packages or convert legacy remote config. +## Upgrade the packages -Once stable v2 packages are available, update the SDKs your application uses: +{% hint style="warning" %} +These pages document the `2.0.0-next.0` prerelease. Until stable v2 packages are published, install the exact prerelease versions you were given: an unversioned install or the `@next` tag may not give you v2. The `@2` commands below work once v2 is published. +{% endhint %} + +Update the SDKs your application uses: ```sh # Choose the SDKs used by your application. @@ -35,7 +35,7 @@ npm install @reflag/node-sdk@2 npm install --save-dev @reflag/cli@2 ``` -Update your lockfile and regenerate declarations before checking the code changes below. +Then work through the steps below. ## 1. Read values directly @@ -80,15 +80,24 @@ const enabled = useFlag("new-editor"); const settings = useFlag("editor-settings", { maxItems: 10 }); ``` -A bare singular read is Boolean with an implicit `false` fallback. Pass a positional JSON default for other values. Explicit `null` accepts arbitrary JSON, including authored null; narrow it before accessing fields. Valid `false`, `0` and empty strings are preserved. A non-null default checks the selected value's top-level category, not its nested schema. +Without a default, a read returns a Boolean: `false` if the flag is missing. Pass a default to read any other value; the return type follows the default. Pass `null` to accept any JSON value and narrow it yourself. -`getFlags()` now returns a direct-value record and registers checks for the returned roots. Use diagnostic APIs for inspection without application checks; do not consume diagnostic result objects as the ordinary getter contract. +`getFlags()` now returns a record of values, such as `{ "new-editor": true }`. ## 2. Migrate remote config explicitly -There is no v2 `.config.key` / `.config.payload` wrapper. Author a Multivariate flag with the values your application needs and read it with a positional default. Legacy remote config is **not automatically converted** by installing v2. +v2 has no `.config` property. Create a Multivariate flag with the values your application needs, and read it with a default: -If access and configuration are independent, keep a Boolean access flag and a separate settings flag. Do not use JavaScript truthiness of arbitrary JSON as an access check. See [Remote config](../product-handbook/remote-config.md). +```ts +// v1 +const { config } = useFlag("editor-settings"); +const maxItems = config.payload?.maxItems ?? 10; + +// v2 +const { maxItems } = useFlag("editor-settings", { maxItems: 10 }); +``` + +Existing remote config is **not converted automatically**. If a v1 flag controlled both access and configuration, split it into a Boolean flag for access and a Multivariate flag for the settings. See [Remote config](../product-handbook/remote-config.md). ## 3. Separate usage tracking and feedback @@ -101,26 +110,28 @@ track("Document created"); requestFeedback({ flagKey: "new-editor", title: "How is the new editor?" }); ``` -In Browser and Node.js, use the ordinary client or context-bound client tracking methods. Browser feedback uses the client's feedback methods. Calling a v2 getter registers a check immediately; it no longer waits for a wrapper property to be read. Tracking product usage remains a separate action. +In Browser and Node.js, call `track()` and the feedback methods on the client. Either way, you name the event you track; configure your flag's adoption rules to match it. ## 4. Update loading and Suspense - React `useFlag()` never suspends. Use `useFlagSuspense()` for a suspending read, or `useIsLoading()` / the provider's `loadingComponent` for loading presentation. - React's second `useFlag()` argument is the fallback value, not `{ suspense: ... }` options. - Vue returns a ref containing the direct value; use `useIsLoading()` or the provider's loading slot for loading presentation. -- Opt-in lists retain their own presentation/membership metadata, including `isEnabled`. Those fields are not ordinary getter wrappers. +- `useOptInFlags()` is unchanged: its entries still include `isEnabled` and the opt-in fields. ## 5. Upgrade bootstrap and saved state together -Generate bootstrap with Node SDK v2 and pass the **entire** envelope to Browser, React or Vue SDK v2. Do not pass only its `flags` property. Never expose secret keys or server-only attributes in the public envelope. +Generate bootstrap data with Node.js SDK v2 and pass the whole object returned by `getFlagsForBootstrap()` to Browser, React or Vue SDK v2, not just its `flags` property. + +v1 and v2 bootstrap data aren't compatible, so upgrade the server and client SDKs together. Anything still on v1, such as React Native, needs bootstrap data from Node.js SDK v1. -V1 and v2 bootstrap formats are incompatible. Do not feed Node v2 bootstrap into React Native or another consumer still using v1. Browser cache/override keys and built-in Node fallback storage are version-isolated. Existing v1 fallback snapshots must not be relabeled as v2: restore a valid complete v2 snapshot or fetch one from the compatible service. +Saved state doesn't carry over. The Browser SDK starts with a fresh cache and no overrides, and Node.js fallback providers store v2 snapshots separately from v1 ones. Let a v2 process fetch flags once to save a new snapshot; don't rename v1 snapshot files. ## 6. Regenerate types and review overrides -Regenerate wrapper-shaped declarations with a compatible CLI 2. Direct-value defaults already provide useful inference without generation; see [Type safety](../product-handbook/type-safety.md) for optional schema registration. +Regenerate flag types with CLI 2. Generated types are optional in v2, because the default you pass already determines the return type. See [Type safety](../product-handbook/type-safety.md). -Overrides and static fallback values are direct JSON values. In Browser SDK v2, `undefined` clears an override while `null` is a real value. Review your offline and disruption tests against the new contracts before upgrading production. +Overrides and static fallback values are now plain values, such as `true` or `{ maxItems: 5 }`. In the Browser SDK, `undefined` removes an override, while `null` sets the value to `null`. Run your offline and outage tests against v2 before upgrading production. ## SDK documentation diff --git a/supported-languages/next.js.md b/supported-languages/next.js.md index ff44c09..bf02175 100644 --- a/supported-languages/next.js.md +++ b/supported-languages/next.js.md @@ -6,7 +6,7 @@ description: Use the Node.js and React SDKs with Next.js. Use the [Node.js SDK](node-sdk/README.md) to evaluate flags on the server and the [React SDK](react-sdk/README.md) in client components. -This documentation covers SDK v2. +This page covers SDK v2. ## Server-side rendering @@ -29,7 +29,7 @@ export async function getReflagClient() { } ``` -Derive user/company context from your authenticated session on the server, not from client-supplied subscription attributes. The examples below assume your application's `getContext()` helper does that. +Build the user and company context from your authenticated session on the server. The examples below assume a `getContext()` helper in your application that does this. {% tabs %} {% tab title="App router" %} @@ -83,7 +83,7 @@ export default function Page({ enabled }: InferGetServerSidePropsType -Server-side Boolean and multivariate flag values for [Reflag](https://reflag.com). +Feature flags, remote configuration and usage tracking for Node.js servers. -This documentation covers SDK v2. +This page covers SDK v2. -## Installation and initialization +## Get started + +Install the SDK: ```sh yarn add @reflag/node-sdk ``` -Create one client per process and initialize it before reading flags. Obtain your environment's secret key from Reflag's environment settings; complete flag definitions must remain server-side. +Create one client per process with your environment's **secret** key, found in your Reflag environment settings. Initialize it before reading flags: ```ts import { ReflagClient } from "@reflag/node-sdk"; @@ -36,7 +38,7 @@ export const reflag = new ReflagClient({ await reflag.initialize(); ``` -## Read flags +Then read a flag for a user and company: ```ts const context = { @@ -44,79 +46,66 @@ const context = { company: { id: "acme", plan: "enterprise" }, }; -const enabled = reflag.getFlag(context, "new-editor"); // boolean; implicit false -const model = reflag.getFlag(context, "model", "quick"); // string -const limits = reflag.getFlag(context, "limits", { maxItems: 10 }); // { maxItems: number } +if (reflag.getFlag(context, "new-editor")) { + // Show the new editor +} ``` -`getFlag()` returns a Boolean, string, number, array, object, or null. Without a default it is a Boolean read: unavailable or non-Boolean values return `false`. With a positional default, missing values use that default. Valid `false`, `0`, empty strings, arrays, and objects are preserved rather than replaced by truthiness checks. +The SDK downloads your flag definitions and evaluates flags locally, so reads don't make network requests. Keep the secret key on your server. + +## Read flags + +Without a default, `getFlag()` returns a Boolean. You get `false` if the flag is missing or isn't a Boolean. -Non-null defaults specify the expected JSON category: Boolean, number, string, array, or object. A category mismatch logs a warning without the payload and returns the default. This is not nested payload validation: object properties and array elements must still match your authored schema. Use an explicit `null` default for arbitrary JSON or nullable/off selections, and narrow the result before accessing object fields: +To read a configuration value, pass a default. The return type follows the default, and you get the default back if the flag is missing or holds a different type of value: ```ts -const payload = reflag.getFlag(context, "nullable-settings", null); // FlagValue -// Authored null is preserved, as are any other valid JSON values. Missing uses null. +const model = reflag.getFlag(context, "model", "quick"); // string +const limits = reflag.getFlag(context, "limits", { maxItems: 10 }); // { maxItems: number } +const payload = reflag.getFlag(context, "nullable-settings", null); // any JSON value; narrow it yourself ``` -Defaults infer useful types without generated declarations, including widening primitive literals. Readonly defaults are accepted; results and defaults are returned as independent copies. Defaults are ordinary JSON payloads, with no reserved property names. +The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. -Each call immediately registers a check for the requested root, including when you do not subsequently use its return value. Dependencies traversed internally do not register extra checks. Delivery is buffered and rate-limited. A check records the selected **variant key**, never the JSON payload: +`getFlags(context)` returns all flag values as a record; a value can be `undefined` if the flag is unavailable. -```ts -{ - type: "feature-flag-event", - action: "check", - key: "model", - evalResult: "quality", - sourceVersionId: "version-id", - flagStateVersion: 42, - evalContext: { company: { id: "acme", plan: "enterprise" } }, -} -``` +Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. + +## Bind a client to a request -Boolean selections send `"true"` / `"false"` while returning Boolean values. Caller defaults, including category-mismatch defaults, do not claim an authored selection: their checks omit `evalResult` and `sourceVersionId`. Check deduplication includes normalized context, selection identity, root version, and snapshot version. Equal-valued variants are not interchangeable selections. `getFlags()` returns a record of flag values, without per-root caller defaults; unavailable batch values may be `undefined`. +To avoid passing the context on every call, bind it once, for example per request: ```ts -const values = reflag.getFlags(context); // value record; checks each returned root const bound = reflag.bindClient(context); -const value = bound.getFlag("model", "quick"); -const allValues = bound.getFlags(); -// Ordinary usage tracking is separate from flag checks. -await bound.track("Document created", { attributes: { source: "editor" } }); -await reflag.flush(); +const model = bound.getFlag("model", "quick"); +const allValues = bound.getFlags(); ``` -Binding queues user/company attributes and their association even if the client is subsequently used only for tracking or remote reads. Synchronization is asynchronous and respects offline/tracking guards; failures are logged. - -Local reads made before initialization include a `CLIENT_NOT_INITIALIZED` diagnostic in their check's optional `evalErrors`. Targeting diagnostics retain their code, field/operator when applicable, message, and dependency origin. Remote evaluation does not require the local definition cache to be initialized, and bootstrap/diagnostic access does not itself register checks. +Binding also sends the user's and company's attributes to Reflag, so you can target and filter by them. -`enableTracking: false` disables checks, context synchronization, and bound-client usage tracking. Explicit calls to the root client's `track()`, `updateUser()`, and `updateCompany()` remain separate operations. +## Track usage -## Evaluation and synchronization +```ts +await bound.track("Document created", { attributes: { source: "editor" } }); +``` -The SDK fetches a complete `{ flags, segments }` graph from secret-key-only `GET /flags`. Definitions are validated and prepared before the flags, segments, and snapshot version replace the current cache together. Malformed graphs and stale responses cannot replace last-known-good state. +Configure your flag's adoption rules to match the event names you send. Events are sent in batches. Call `await reflag.flush()` to send any queued events, for example before your process exits. -`getFlag()` evaluates only its root and dependencies. `getFlags()` evaluates the collection. References are reevaluated on every traversal: there is **no context/dependency-result caching**. Only immutable definition preparation is retained. Returned objects are independent copies, so changing a value cannot mutate the saved definitions. +## Keep flags up to date -Synchronization modes: +The client keeps flag definitions up to date in the background. Choose how with `flagsSyncMode`: -- `push` (default): authenticated SSE updates with reconnect handling. -- `polling`: periodic background refreshes. -- `in-request`: request-driven refreshes, suitable for constrained runtimes. +- `push` (default): receive updates as soon as flags change. +- `polling`: refresh periodically. +- `in-request`: refresh when flags are read, for environments without long-running background work. -```ts -await reflag.refreshFlags(); -await reflag.refreshFlags(42); // request at least this snapshot version -const definitions = reflag.getFlagDefinitions(); // { flags, segments }, not an array -``` - -Refreshes are throttled. In-request mode can queue a refresh during the throttle window until a later access; a refresh call is not an unconditional synchronization barrier. - -Ordinary warm `/flags` refreshes send `If-None-Match` when the accepted snapshot has an ETag. A bodyless `304` retains the complete prepared graph and version while resetting freshness, without recompiling or saving it again. Cold/fallback initialization and version-targeted requests remain unconditional. Custom HTTP clients can return the exact optional `HttpClientResponse.etag` to enable this behavior; clients without one continue to use full GETs. Validators are enabled only after the snapshot's fallback save succeeds. Failed or pending saves leave refreshes unconditional, and rejected snapshots cannot replace a validator or overwrite fallback storage. +Call `await reflag.refreshFlags()` to request a refresh yourself. If a refresh fails, the client keeps using the flags it already has. ## Fallback providers +A fallback provider saves the latest flag definitions so your service can start even if Reflag is unreachable: + ```ts import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; @@ -127,23 +116,9 @@ const client = new ReflagClient({ await client.initialize(); ``` -Live state is primary. When the initial live fetch fails, the SDK can load a saved complete collection. Later outages retain the in-memory graph rather than reloading older fallback state. Accepted live snapshots are saved in order; `flush()` also waits for pending saves. +The client uses saved definitions only when it can't fetch them at startup. Built-in providers are `file`, `redis`, `s3`, `gcs` and `static`. You can also implement your own `FlagsFallbackProvider`. -Available providers: `static`, `file`, `redis`, `s3`, and `gcs`, plus custom `FlagsFallbackProvider` implementations. A snapshot contains: - -```ts -{ - version: 2, - savedAt: "2026-01-01T00:00:00.000Z", - flagStateVersion: 42, - flags: [/* compiled flags */], - segments: [/* compiled segment predicates */], -} -``` - -Built-in files/S3/GCS objects use `flags-fallback-v2-.json`; Redis uses `:v2:`. - -A static fallback can contain any JSON values: +A static provider takes fixed values: ```ts fallbackProviders.static({ @@ -151,29 +126,32 @@ fallbackProviders.static({ }); ``` -Static values, `fallbackFlags`, and overrides do not identify authored variants. Their checks omit `evalResult` and `sourceVersionId`; they must not claim exposure to an authored selection. Restored real collection snapshots retain their real selection/version metadata. Providers are not loaded in offline mode. - ## Overrides and tests +Use offline mode and overrides to run tests without contacting Reflag: + ```ts const client = new ReflagClient({ offline: true, flagOverrides: { "new-editor": true, limits: { maxItems: 5 } }, }); await client.initialize(); + client.setFlagOverrides({ model: "quick" }); + const remove = client.pushFlagOverrides((context) => ({ model: context.company?.id === "qa" ? "quality" : "quick", })); remove(); + client.clearFlagOverrides(); ``` -Overrides are direct JSON values. Pushed layers win over base overrides and can be removed independently. They apply **after evaluation**, so overriding a dependency's returned value does not rewrite dependent flag evaluations. Offline mode does not fetch, load a provider, or send tracking events. +Overrides pushed with `pushFlagOverrides()` take precedence over base overrides and can be removed independently. In offline mode, the client makes no network requests and sends no events. -## Typed flags +## Type safety -Generated declarations are optional. Singular reads infer their return type from the default, or return Boolean when no default is supplied. Optionally augment `Flags` to constrain keys, check non-null defaults against each key's value schema, and type batch records: +Optionally declare your flags to get autocompletion for keys, type checks for defaults and typed `getFlags()` results: ```ts declare module "@reflag/node-sdk" { @@ -183,35 +161,25 @@ declare module "@reflag/node-sdk" { limits: { maxItems: number } | null; } } - -const model = reflag.getFlag(context, "model", "quick"); // string -const models = reflag.getFlags(context); // models.model: "quick" | "quality" | undefined ``` -Augmentation rejects defaults with the wrong category, missing required properties, or incompatible nested types. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request, and bare/`undefined` reads still return Boolean. Return types continue to be inferred and widened from the default; generated types do not add nested runtime validation. The Reflag CLI generates schemas from current production-environment variants. See the Express example for a typed integration. +The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you. Declarations are checked at compile time only. + +## Bootstrap the browser -## Bootstrap state +To render flags in the browser without waiting for a network request, evaluate them on the server and pass the result to the Browser, React or Vue SDK's bootstrap option: ```ts const bootstrap = reflag.getFlagsForBootstrap(context); -// { protocolVersion: 2, context, flags: { model: { resolved, value, -// variantKey, sourceVersionId, matchedRuleId, ruleResults, errors, ... } }, -// flagStateVersion } ``` -Bootstrap uses batch evaluation and preserves selection metadata and raw context. It does **not** register browser checks. Local overrides/value-only fallbacks carry their values without fabricated authored-selection metadata. - -Pass the entire envelope to the Browser, React or Vue SDK's bootstrap option, not just its `flags` property. Use your framework's safe serialization mechanism and never expose secret keys or server-only context in public bootstrap data. +Pass the whole object, serialized with your framework's usual mechanism. Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. ## Remote evaluation +To evaluate flags on Reflag's servers instead of locally, use the remote methods: + ```ts -const enabled = await reflag.getFlagRemote( - "new-editor", - undefined, - "user-1", - "acme", -); const model = await reflag.getFlagRemote("model", "quick", "user-1", "acme"); const boundModel = await reflag .bindClient(context) @@ -221,21 +189,23 @@ const values = await reflag.getFlagsRemote("user-1", "acme", { }); ``` -These methods use `/flags/evaluated` and return direct values. Singular remote reads use the same defaults, category checks, and JSON validation as local reads. The root `getFlagRemote(key, defaultValue, userId?, companyId?, context?)` places the default second; use `undefined` for an implicit Boolean read when passing explicit IDs. `getFlagsRemote(userId?, companyId?, context?)` returns a record of flag values. - -Each requested singular root registers a check, including a default after a failed/missing remote evaluation, unless tracking is disabled. Only accepted authored selections retain the server's selection/version metadata. Explicit IDs, including numeric zero, take precedence over IDs in additional context. Stored attribute updates are asynchronous; remote evaluation need not immediately observe a just-sent update. +On the root client, the default comes second: `getFlagRemote(key, defaultValue, userId?, companyId?, context?)`. Pass `undefined` as the default for a Boolean read. ## Edge runtimes -Use `EdgeClient` with Node compatibility enabled. It selects in-request synchronization. Call `ctx.waitUntil(client.flush())` before returning from a Worker so queued events and refresh work can complete. +Use `EdgeClient` in edge runtimes such as Cloudflare Workers, with Node.js compatibility enabled. It refreshes flags as they're read. Call `ctx.waitUntil(client.flush())` before returning from a Worker so queued events are sent. ## Configuration -Configuration precedence is constructor options, environment variables, then `reflag.config.json`. Supported environment variables include `REFLAG_SECRET_KEY`, `REFLAG_API_BASE_URL`, `REFLAG_LOG_LEVEL`, `REFLAG_OFFLINE`, `REFLAG_CONFIG_FILE`, and Boolean override lists `REFLAG_FLAGS_ENABLED` / `REFLAG_FLAGS_DISABLED`. +Options can be set in the constructor, through environment variables, or in `reflag.config.json`, in that order of precedence. + +Environment variables include `REFLAG_SECRET_KEY`, `REFLAG_API_BASE_URL`, `REFLAG_LOG_LEVEL`, `REFLAG_OFFLINE`, `REFLAG_CONFIG_FILE`, and `REFLAG_FLAGS_ENABLED` / `REFLAG_FLAGS_DISABLED` to override Boolean flags. + +Constructor options include `logger`, `httpClient`, `flagsSyncMode`, `fetchTimeoutMs`, `flagsFetchRetries`, `flagsFallbackProvider`, `flagOverrides`, `enableTracking`, `offline` and `batchOptions` (`maxSize`, `intervalMs`, `flushOnExit`). -Constructor options also include a custom `logger` / `httpClient`, `flagsSyncMode`, `flagsPushUrl`, `fetchTimeoutMs`, `flagsFetchRetries`, `flagsFallbackProvider`, direct-value `flagOverrides`, and `batchOptions` (`maxSize`, `intervalMs`, `flushOnExit`). `emitEvaluationEvents` is deprecated and has no effect. +## Shutting down -Invalid options/context or non-JSON defaults can throw. Network or definition-refresh failures are logged and retain usable state. Singular reads use their caller default (implicit `false`) without fabricating an authored false selection; batch reads retain raw values/`undefined`. Call `await client.flush()` before shutting down, then `client.destroy()` to stop background work. `batchOptions.flushOnExit` only flushes on natural Node process exit (`beforeExit`); it does not install signal handlers or force application shutdown. For signal-driven shutdown or an explicit `process.exit()`, await `flush()` in the application's own shutdown hook before exiting. +Before your process exits, call `await reflag.flush()` to send queued events, then `reflag.destroy()` to stop background work. `batchOptions.flushOnExit` flushes only when Node exits on its own; if you exit on a signal or call `process.exit()`, call `flush()` in your shutdown handler first. ## License diff --git a/supported-languages/node-sdk/globals.md b/supported-languages/node-sdk/globals.md index 78244c1..90a1bc7 100644 --- a/supported-languages/node-sdk/globals.md +++ b/supported-languages/node-sdk/globals.md @@ -15,7 +15,7 @@ pagination: # @reflag/node-sdk -This documentation covers SDK v2. +This page covers SDK v2. ## Classes diff --git a/supported-languages/overview.md b/supported-languages/overview.md index c3f10cd..2795221 100644 --- a/supported-languages/overview.md +++ b/supported-languages/overview.md @@ -8,6 +8,8 @@ description: >- Use a Reflag SDK to read feature flags, manage configuration, and track usage in your application. Choose your language or framework below. +Upgrading from v1? Read [Migrating from v1](migrating-from-v1.md). Documentation for the v1 SDKs is in [Legacy SDKs](../legacy/v1/README.md). + ## Official SDKs These SDKs are crafted and maintained by the Reflag team. @@ -23,5 +25,3 @@ The following SDKs are community-led. For non-supported languages, you can use the [Runtime API](../api/public-api/). To request support for more languages, [please fill out this form](https://share-eu1.hsforms.com/14DktM5t6T229b5Bg8KPDBg2b6w1x). - -Using v1? [Legacy docs](../legacy/v1/README.md) · [Upgrade guide](migrating-from-v1.md). diff --git a/supported-languages/react-sdk/README.md b/supported-languages/react-sdk/README.md index f6d9af4..d5e024b 100644 --- a/supported-languages/react-sdk/README.md +++ b/supported-languages/react-sdk/README.md @@ -15,16 +15,20 @@ pagination: # Reflag React SDK -Feature flags and JSON configuration for React, backed by the [Browser SDK](../browser-sdk/README.md). +Feature flags, remote configuration, usage tracking and feedback for React applications. Built on the [Browser SDK](../browser-sdk/README.md). -This documentation covers SDK v2. +This page covers SDK v2. -## Setup +## Get started + +Install the SDK: ```sh npm install @reflag/react-sdk ``` +Wrap your application in `ReflagProvider` with your **publishable** key and the signed-in user's context: + ```tsx import { ReflagProvider } from "@reflag/react-sdk"; @@ -39,40 +43,53 @@ import { ReflagProvider } from "@reflag/react-sdk"; ; ``` -Provider options forward Browser SDK settings, including `logger`, `debug`, `enableTracking`, `offline`, cache/fallback options, `toolbar`, `feedback`, `credentials` and API origins. A custom logger takes precedence over debug logging. Live updates default to true; set `enableLiveFlagUpdates={false}` to disable them. - -## `useFlag(key, defaultValue?)` +Then read a flag in any component: ```tsx import { useFlag, useTrack } from "@reflag/react-sdk"; function Huddles() { - const enabled = useFlag("huddles"); // boolean, implicit false - const settings = useFlag("huddle-settings", { maxParticipants: 10 }); + const enabled = useFlag("huddles"); const track = useTrack(); if (!enabled) return null; - return ( - - ); + return ; } ``` -Bare reads return Boolean/false, including while initial data is unavailable. A positional default infers widened direct types, even without generated declarations: +## Read flags + +Without a default, `useFlag()` returns a Boolean. You get `false` while flags are loading, and if the flag is missing or isn't a Boolean. + +To read a configuration value, pass a default. The return type follows the default, and you get the default back while loading, or if the flag is missing or holds a different type of value: + +```tsx +const settings = useFlag("huddle-settings", { maxParticipants: 10 }); +// settings.maxParticipants: number -```ts useFlag("model", "quick"); // string useFlag("limit", 10); // number -useFlag("settings", { model: "quick" }); // { model: string } -useFlag("nullable-settings", null); // FlagValue: arbitrary JSON +useFlag("nullable-settings", null); // any JSON value; narrow it yourself ``` -Non-null defaults enforce only the top-level JSON category (Boolean/number/string/array/object). Mismatches return the default and warn without logging the payload. Explicit null accepts authored null and all other JSON; missing values return null. Accepted false, zero and empty strings are preserved. Nested fields/elements are not schema-validated. Values/defaults are independent mutable copies; readonly defaults are accepted. +The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. + +Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. -`useFlag` returns immediately, using the default while flags load. Use `useIsLoading()` or the provider's `loadingComponent` for an explicit loading UI, or `useFlagSuspense()` to wait with React Suspense. +## Loading states and Suspense + +`useFlag()` returns immediately and never suspends. To show a loading UI, use `useIsLoading()` or the provider's `loadingComponent` prop: + +```tsx +} +> + + +``` -## `useFlagSuspense(key, defaultValue?)` +To wait for flags with React Suspense, use `useFlagSuspense()`. It takes the same arguments as `useFlag()`: ```tsx import { Suspense } from "react"; @@ -88,50 +105,34 @@ function Model() { ; ``` -This hook has the same Boolean/default-based return types. It waits for initialization before reading. Once initialization settles, missing flags return their default rather than suspending forever. Bootstrap values can render immediately. Suspended attempts do not register a root read before data is ready. +## Track usage and feedback -The provider's `suspense` prop configures **`useOptInFlags` only**. Use `useFlagSuspense` for flag reads with Suspense. - -## Checks and usage tracking - -A completed getter/hook read registers its requested-root check immediately, even if the value is ignored. Actual delivery remains buffered and identity-aware rate-limited by the Browser SDK. Checks contain selected variant/source/snapshot identity, not payloads. Defaults, category mismatches and local overrides never invent authored selections. Diagnostic/bootstrap inspection registers no checks. - -Track application usage and collect feedback with these hooks: - -```ts +```tsx const track = useTrack(); await track("Started huddle", { button: "cta" }); + const requestFeedback = useRequestFeedback(); requestFeedback({ flagKey: "huddles", title: "How did it go?" }); + const sendFeedback = useSendFeedback(); await sendFeedback({ flagKey: "huddles", score: 5 }); ``` -See [Browser feedback documentation](../browser-sdk/feedback.md) for UI/prompt configuration. +Configure your flag's adoption rules to match the event names you send. See the [Browser feedback documentation](../browser-sdk/feedback.md) to configure feedback prompts and the feedback UI. -## Optional key registration - -```ts -import "@reflag/react-sdk"; -declare module "@reflag/react-sdk" { - interface Flags { - huddles: boolean; - "huddle-settings": { maxParticipants: number }; - } -} -``` +## Update context -Registration constrains keys and checks non-null defaults against the registered value schema, including required and nested properties. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request; bare/`undefined` reads remain Boolean. The positional default still determines the widened return type, and generated declarations do not add nested runtime validation. The same rules apply to `useFlagSuspense`. The Reflag CLI can generate these declarations from current production-environment variants. +`useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return functions that merge new attributes into the current context. To replace the whole context, call `useClient().setContext(context)`. Flag values are refetched for the new context. -## Bootstrap and SSR +## Bootstrap from the server -On the server, use the Node.js SDK: +To render flags immediately, without waiting for a network request, evaluate them on your server with the **Node.js SDK**: ```ts const flags = serverClient.getFlagsForBootstrap(context); ``` -Pass the **entire** safe, serialized envelope to the client provider: +Then pass the whole result to `ReflagBootstrappedProvider`, serialized with your framework's usual mechanism: ```tsx import { ReflagBootstrappedProvider } from "@reflag/react-sdk"; @@ -141,29 +142,59 @@ import { ReflagBootstrappedProvider } from "@reflag/react-sdk"; ; ``` -The envelope includes `protocolVersion: 2`, context, evaluated flag results and optional `flagStateVersion`. Use a snapshot version for live updates; later refreshes use browser-visible context. Do not send secrets/server-only attributes to the browser. Disable live updates if later browser evaluation must not replace server-only results. - -For an existing Browser SDK client, use ``. The provider does not own its lifecycle; initialize/stop externally, except that a suspending read can start on-demand initialization. - -## Context, loading and events - -- `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return async shallow-update functions. `useClient().setContext(context)` replaces the whole context. -- Context changes clear old-context values while fetching. Stale/in-flight responses cannot replace a newer context/snapshot. -- `useIsLoading()` returns provider loading state. `loadingComponent` and `initialLoading` configure initial presentation; they are not getter arguments. -- `useClient()` returns the underlying Browser client. Its `getFlags()` returns direct values/checks; `getFlagResults()` is diagnostic-only. -- `useOnEvent(type, handler, client?)` subscribes and unsubscribes on unmount. A supplied external client works without a provider. +Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, set `enableLiveFlagUpdates={false}`. -## Opt-in hooks +## Let users opt in to flags ```tsx const { flags, isLoading } = useOptInFlags(); const setOptIn = useSetOptIn(); + await setOptIn("huddles", { optedIn: true }); await setOptIn("huddles", { optedIn: false, scope: "company" }); ``` -Metadata arrives with the initial evaluation for regular providers. Bootstrapped providers fetch missing metadata on demand from `/flags/evaluated` without replacing server-derived values. `isLoading` covers initialization and metadata retrieval; it settles on success or failure. Metadata presentation includes `isEnabled` and membership fields, separately from direct flag reads. User/company grants remain independent. Mutations confirm versioned evaluation and membership in a single refresh. +Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent. Check `isLoading` before rendering an empty state. The provider's `suspense` prop, or `useOptInFlags({ suspense: true })`, makes this hook suspend instead. See [Beta feature opt-in](https://docs.reflag.com/guides/self-opt-in) for a complete example. + +## Toolbar + +The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` prop to show it elsewhere, for example to internal users in production: + +```tsx + + + +``` + +## Type safety + +Optionally declare your flags to get autocompletion for keys and type checks for defaults: + +```ts +import "@reflag/react-sdk"; + +declare module "@reflag/react-sdk" { + interface Flags { + huddles: boolean; + "huddle-settings": { maxParticipants: number }; + } +} +``` + +The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you. Declarations are checked at compile time only. + +## Use an existing client + +`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to ``; your application is then responsible for initializing and stopping it. `useOnEvent(type, handler)` subscribes to client events and unsubscribes when the component unmounts. + +## Configuration + +The provider accepts the Browser SDK's configuration options, such as `fallbackFlags`, `enableTracking`, `offline`, `feedback` and `logger`, as props. Live updates are on by default in React; set `enableLiveFlagUpdates={false}` to turn them off. Set `debug` to log to the console. -`useOptInFlags({ suspense: true | false })` retains its own per-hook loading options and may inherit provider `suspense`. These options are unrelated to the positional payload defaults used by `useFlag` / `useFlagSuspense`. +For Content Security Policy requirements and the full list of options, see the [Browser SDK](../browser-sdk/README.md). Using v1? [Legacy docs](../../legacy/v1/react-sdk/README.md) · [Upgrade guide](../migrating-from-v1.md). diff --git a/supported-languages/react-sdk/globals.md b/supported-languages/react-sdk/globals.md index f41cc01..859fa6a 100644 --- a/supported-languages/react-sdk/globals.md +++ b/supported-languages/react-sdk/globals.md @@ -15,7 +15,7 @@ pagination: # @reflag/react-sdk -This documentation covers SDK v2. +This page covers SDK v2. ## Interfaces diff --git a/supported-languages/vue-sdk/README.md b/supported-languages/vue-sdk/README.md index ffa011a..a4189a7 100644 --- a/supported-languages/vue-sdk/README.md +++ b/supported-languages/vue-sdk/README.md @@ -15,16 +15,20 @@ pagination: # Reflag Vue SDK (beta) -Reactive feature flags and JSON configuration for Vue 3, backed by the [Browser SDK](../browser-sdk/README.md). +Feature flags, remote configuration, usage tracking and feedback for Vue 3 applications. Built on the [Browser SDK](../browser-sdk/README.md). -This documentation covers SDK v2. +This page covers SDK v2. -## Setup +## Get started + +Install the SDK: ```sh npm install @reflag/vue-sdk ``` +Wrap your application in `ReflagProvider` with your **publishable** key and the signed-in user's context: + ```vue ``` -`useFlag()` returns a reactive ref containing the flag value. Vue unwraps refs in templates; use `.value` in script. +## Read flags + +`useFlag()` returns a ref that updates when the flag changes. Vue unwraps refs in templates; use `.value` in script. + +Without a default, the ref holds a Boolean. It is `false` while flags are loading, and if the flag is missing or isn't a Boolean. + +To read a configuration value, pass a default. The type follows the default, and the ref holds the default while loading, or if the flag is missing or holds a different type of value: ```ts -useFlag("release"); // ShallowRef -useFlag("model", "quick"); // ShallowRef -useFlag("limit", 10); // ShallowRef -useFlag("settings", { model: "quick" }); // ShallowRef<{ model: string }> -useFlag("nullable-settings", null); // ShallowRef +const settings = useFlag("huddle-settings", { maxParticipants: 10 }); +// settings.value.maxParticipants: number + +useFlag("model", "quick"); // Ref of string +useFlag("limit", 10); // Ref of number +useFlag("nullable-settings", null); // any JSON value; narrow it yourself ``` -Defaults are positional JSON; literals widen without generated types. Non-null defaults require the same top-level category (Boolean/number/string/array/object), otherwise the default is returned with a payload-safe warning. Null explicitly accepts arbitrary JSON, including authored null; missing returns null. Valid false/zero/empty strings are preserved. Nested payload schemas are not validated by the SDK. Returned values/defaults are independent copies; readonly defaults are accepted. +The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. + +Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. + +## Loading states + +`useIsLoading()` returns a Boolean ref that is `true` while the provider loads flags. You can also put loading content in the provider's `#loading` slot, as in the example above. -The ref updates when evaluated flags change. A composable read registers the requested root through the Browser SDK, even if its result is ignored; refresh-driven rereads are identity-aware rate-limited and delivered in batches. Diagnostics/bootstrap inspection register none. Checks carry genuine selected key/source/snapshot identity, never payloads or invented selections for defaults/overrides. +## Track usage and feedback + +```ts +const track = useTrack(); +await track("Started huddle", { button: "cta" }); + +const requestFeedback = useRequestFeedback(); +requestFeedback({ flagKey: "huddles", title: "How did it go?" }); + +const sendFeedback = useSendFeedback(); +await sendFeedback({ flagKey: "huddles", score: 5 }); +``` -## Loading, context and client access +Configure your flag's adoption rules to match the event names you send. See the [Browser feedback documentation](../browser-sdk/feedback.md) to configure feedback prompts and the feedback UI. -- `useIsLoading()` returns a Boolean ref for provider loading; the `#loading` slot and `initialLoading` control initial presentation. -- `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return async shallow-update functions. -- `useClient()` exposes the Browser client, including `setContext(context)`, `refresh()` and `setFlagOverride(key, value)`. Undefined clears an override; null is a JSON override. -- `getFlags()` returns direct values and registers returned-root checks. Use `getFlagResults()` for tooling without checks. -- `useOnEvent(type, handler, client?)` subscribes on mount and unsubscribes on unmount. An external client may be supplied explicitly. +## Update context -A context change clears old values while fetching. Late responses for previous contexts or lower snapshot versions cannot replace accepted state. Browser fetching uses `/flags/evaluated` and never re-evaluates/caches dependencies locally. +`useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return functions that merge new attributes into the current context. To replace the whole context, call `useClient().setContext(context)`. Flag values are refetched for the new context. -## Bootstrap +## Bootstrap from the server -On the server, use the Node.js SDK and your framework's safe serialization mechanism: +To render flags immediately, without waiting for a network request, evaluate them on your server with the **Node.js SDK**: ```ts const flags = serverClient.getFlagsForBootstrap(context); ``` +Then pass the whole result to `ReflagBootstrappedProvider`, serialized with your framework's usual mechanism: + ```vue ``` -Pass the entire envelope (`protocolVersion: 2`, context, evaluated flags and optional snapshot version). A snapshot version is required for live updates. Never expose secret keys/server-only attributes in bootstrap data; later refreshes use browser-visible context, so disable live updates when they must not replace server-only evaluations. - -`ReflagClientProvider` accepts an externally initialized Browser SDK client. Its lifecycle belongs to the application. +Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, set `:enable-live-flag-updates="false"`. -## Opt-in, tracking and feedback +## Let users opt in to flags ```ts -const { flags, isLoading } = useOptInFlags(); // refs to metadata/list loading +const { flags, isLoading } = useOptInFlags(); const setOptIn = useSetOptIn(); + await setOptIn("huddles", { optedIn: true }); await setOptIn("huddles", { optedIn: false, scope: "company" }); +``` -const track = useTrack(); -await track("Started huddle", { button: "cta" }); -const requestFeedback = useRequestFeedback(); -requestFeedback({ flagKey: "huddles", title: "How did it go?" }); -const sendFeedback = useSendFeedback(); -await sendFeedback({ flagKey: "huddles", score: 5 }); +Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent. Check `isLoading` before rendering an empty state. + +## Toolbar + +The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` prop to show it elsewhere, for example to internal users in production: + +```vue + + + ``` -Opt-in metadata arrives with ordinary `/flags/evaluated` responses. Bootstrapped providers fetch missing metadata on demand from the same endpoint without replacing server-derived values or provenance; loading settles on success or failure. User/company grants remain independent; successful mutations confirm versioned evaluation and membership in a single refresh. The metadata list retains presentation/membership fields such as `isEnabled`; ordinary reads remain direct values. +To override a flag from code, call `useClient().setFlagOverride(key, value)`. Pass `undefined` to remove the override. -`enableTracking: false` disables checks and ordinary tracking. Offline mode skips HTTP/tracking. See [Browser feedback documentation](../browser-sdk/feedback.md) for prompting/UI options. +## Type safety -## Optional key registration +Optionally declare your flags to get autocompletion for keys and type checks for defaults: ```ts import "@reflag/vue-sdk"; + declare module "@reflag/vue-sdk" { interface Flags { huddles: boolean; @@ -141,6 +170,16 @@ declare module "@reflag/vue-sdk" { } ``` -Registration constrains keys and checks non-null defaults against the registered value schema, including required and nested properties. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request; bare/`undefined` reads remain Boolean refs. Positional defaults still determine widened direct-value types, and generated declarations do not add nested runtime validation. The Reflag CLI can generate these schemas from current production-environment variants with `--format vue`. +The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you with `--format vue`. Declarations are checked at compile time only. + +## Use an existing client + +`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to `ReflagClientProvider`; your application is then responsible for initializing and stopping it. `useOnEvent(type, handler)` subscribes to client events and unsubscribes when the component unmounts. + +## Configuration + +The provider accepts the Browser SDK's configuration options, such as `fallbackFlags`, `enableTracking`, `offline`, `feedback` and `logger`, as props. Live updates are on by default in Vue; set `:enable-live-flag-updates="false"` to turn them off. Set `debug` to log to the console. + +For Content Security Policy requirements and the full list of options, see the [Browser SDK](../browser-sdk/README.md). Using v1? [Legacy docs](../../legacy/v1/vue-sdk/README.md) · [Upgrade guide](../migrating-from-v1.md). diff --git a/supported-languages/vue-sdk/globals.md b/supported-languages/vue-sdk/globals.md index 52bb0ef..d2e14a6 100644 --- a/supported-languages/vue-sdk/globals.md +++ b/supported-languages/vue-sdk/globals.md @@ -15,7 +15,7 @@ pagination: # @reflag/vue-sdk -This documentation covers SDK v2. +This page covers SDK v2. ## Interfaces From 00dd0b4ca37b2b5daae27961cf24062e15d2df0b Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:00:18 +0000 Subject: [PATCH 09/18] docs: simplify how SDK guides explain flag reads and defaults Co-Authored-By: Claude Opus 5.5 --- .generated/sdk-docs/browser-sdk/v2.json | 10 +++++----- .generated/sdk-docs/node-sdk/v2.json | 6 +++--- .generated/sdk-docs/react-sdk/v2.json | 8 ++++---- .generated/sdk-docs/vue-sdk/v2.json | 6 +++--- sdk/@reflag/browser-sdk/README.md | 13 ++++--------- sdk/@reflag/node-sdk/README.md | 11 ++++++++--- sdk/@reflag/react-sdk/README.md | 18 ++++++++++-------- sdk/@reflag/vue-sdk/README.md | 18 ++++++++++-------- sdk/documents/browser-sdk/FEEDBACK.md | 6 +++--- sdk/documents/react-sdk/README.md | 18 ++++++++++-------- supported-languages/browser-sdk/README.md | 13 ++++--------- supported-languages/browser-sdk/feedback.md | 6 +++--- supported-languages/node-sdk/README.md | 11 ++++++++--- supported-languages/react-sdk/README.md | 18 ++++++++++-------- supported-languages/vue-sdk/README.md | 18 ++++++++++-------- 15 files changed, 95 insertions(+), 85 deletions(-) diff --git a/.generated/sdk-docs/browser-sdk/v2.json b/.generated/sdk-docs/browser-sdk/v2.json index 656a7e2..6667ef0 100644 --- a/.generated/sdk-docs/browser-sdk/v2.json +++ b/.generated/sdk-docs/browser-sdk/v2.json @@ -1,14 +1,14 @@ { "sourceRepository": "https://github.com/reflagcom/javascript", - "sourceCommit": "f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684", + "sourceCommit": "e7d2a4039d435f4f1c758b6e72d4ff5222bcc340", "package": "@reflag/browser-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/browser-sdk/README.md": "acbef54e789913d3676d28655d9882b45736b735ad0d2257da51bbba76d48ecc", - "sdk/@reflag/browser-sdk/README.md": "53972ca6f20f557de377a9196c4f47ea43a9fc451d7fb41cc9e45995671c7599", + "supported-languages/browser-sdk/README.md": "170ec681580d7c72dd6d3efbc613ed9947ebee18075ecd279fa8bf73894a0239", + "sdk/@reflag/browser-sdk/README.md": "a58def792a7db5e78f2a34936c00b80142e68715352b495f254ea470ef11224b", "supported-languages/browser-sdk/globals.md": "4a3be858a621eb3839408d759329a60ab2ea406d0e21174b44b0639c678a1ffc", "sdk/@reflag/browser-sdk/globals.md": "a60d58526686dcc14ea5cdcecfa1d17388aff78f198f97f41bd667d35c7c39aa", - "supported-languages/browser-sdk/feedback.md": "704e2ba3985b013c0ab3e23e3439930063fc253fcf12fda97bb1c7e13a69112a", - "sdk/documents/browser-sdk/FEEDBACK.md": "8221ce5cfaf24b29f6c868ae5c6acfe8d4a5822c59bfba37854c5710590f55a6" + "supported-languages/browser-sdk/feedback.md": "821280fe2e6e5282518bfa0b7de912dbfa4db1246aa8e5f12be6539fff5db485", + "sdk/documents/browser-sdk/FEEDBACK.md": "4b5879ddb57ee123859df856923a2a2beff55db4a88cd17f3c4c9150c133d354" } } diff --git a/.generated/sdk-docs/node-sdk/v2.json b/.generated/sdk-docs/node-sdk/v2.json index bc6afaa..684f644 100644 --- a/.generated/sdk-docs/node-sdk/v2.json +++ b/.generated/sdk-docs/node-sdk/v2.json @@ -1,11 +1,11 @@ { "sourceRepository": "https://github.com/reflagcom/javascript", - "sourceCommit": "2b71dcc56aab2ff86bd4cea671d5e8effe0060bb", + "sourceCommit": "6ae28701b5deec5e153bb7bb03fe1c32108e89a5", "package": "@reflag/node-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/node-sdk/README.md": "f05616c28415ef8f3e1fcb9299ecd51ae170cc76be569240be16b8488ffbfe81", - "sdk/@reflag/node-sdk/README.md": "c979675ff56811e414ffd5d9e16ebbb4007c4743ceaafe3b1a0f464ee6aa99ec", + "supported-languages/node-sdk/README.md": "d8552440b4dabc0fb865aef69c5af3c6478818302ea3e96a3eefe647f7d1004c", + "sdk/@reflag/node-sdk/README.md": "4f917c54ba70e34d60922d5b39b97e19694518ec37b2206fe22616d71e2a3122", "supported-languages/node-sdk/globals.md": "e1fc21f052e69b74582782ac7133513b077f328294f674523f087e4846338815", "sdk/@reflag/node-sdk/globals.md": "3fc142c7e452af2515b11c7efafa34d81bfe887f29ad1e2d6c81d31fb6736cc3" } diff --git a/.generated/sdk-docs/react-sdk/v2.json b/.generated/sdk-docs/react-sdk/v2.json index 0ccfc77..b98e1de 100644 --- a/.generated/sdk-docs/react-sdk/v2.json +++ b/.generated/sdk-docs/react-sdk/v2.json @@ -1,12 +1,12 @@ { "sourceRepository": "https://github.com/reflagcom/javascript", - "sourceCommit": "f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684", + "sourceCommit": "e7d2a4039d435f4f1c758b6e72d4ff5222bcc340", "package": "@reflag/react-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/react-sdk/README.md": "ec75e4663a2a51707a81ee290b6267b7e53e6fdf9380e6d12f1d5dbd32b517bd", - "sdk/@reflag/react-sdk/README.md": "d4312429334e929032c66aa45cd93bc831947592465917532596bdbdae48fd0c", - "sdk/documents/react-sdk/README.md": "d4312429334e929032c66aa45cd93bc831947592465917532596bdbdae48fd0c", + "supported-languages/react-sdk/README.md": "8f9da095f57638836073e5af4334dfbc7e0322eb386822a8c7cd5a17a2436f22", + "sdk/@reflag/react-sdk/README.md": "94c265f8b2a439e5dbd2662073182d02da1e5b4d40af33cd32793d757a7603ee", + "sdk/documents/react-sdk/README.md": "94c265f8b2a439e5dbd2662073182d02da1e5b4d40af33cd32793d757a7603ee", "supported-languages/react-sdk/globals.md": "f414859dd7cc94089d06f27613e1c554e3e3d5f049a9a141c2590058af768b1a", "sdk/@reflag/react-sdk/globals.md": "4cf0d20cca9c19d3998d9c5d0f6670d17d6782c24ee0ccd25e1d34100f42fcc6" } diff --git a/.generated/sdk-docs/vue-sdk/v2.json b/.generated/sdk-docs/vue-sdk/v2.json index 76fa6b1..656bdb4 100644 --- a/.generated/sdk-docs/vue-sdk/v2.json +++ b/.generated/sdk-docs/vue-sdk/v2.json @@ -1,11 +1,11 @@ { "sourceRepository": "https://github.com/reflagcom/javascript", - "sourceCommit": "f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684", + "sourceCommit": "e7d2a4039d435f4f1c758b6e72d4ff5222bcc340", "package": "@reflag/vue-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/vue-sdk/README.md": "42830e3990636114ec07648f932c113f5d751a93fcb9385e1ece07f2ce069dc8", - "sdk/@reflag/vue-sdk/README.md": "7b98f3bf0536de5cea109c65b71c58f0374ebe6c278ce3284a6149ca4a739907", + "supported-languages/vue-sdk/README.md": "6034b6df8c207117a82afabee3a9b50c2051003ac87cd6a3fd5ef55b19830175", + "sdk/@reflag/vue-sdk/README.md": "f416fe772bd0b64403f26ceea2228b79740dd9813921a9652b85795e58ba40f6", "supported-languages/vue-sdk/globals.md": "968ec7df896ee2e78d1d23578acfadfc3378bd511b15c55eca79b6558588727f", "sdk/@reflag/vue-sdk/globals.md": "73ceaa29875b0d33a02dcfbf12cf1e50644b51d871cc496681bdbcbeee56ab2d" } diff --git a/sdk/@reflag/browser-sdk/README.md b/sdk/@reflag/browser-sdk/README.md index 2fef5b4..43be7c9 100644 --- a/sdk/@reflag/browser-sdk/README.md +++ b/sdk/@reflag/browser-sdk/README.md @@ -48,25 +48,20 @@ Publishable keys are safe to ship to the browser. Keep secret keys on your serve ## Read flags -Without a default, `getFlag()` returns a Boolean. You get `false` if the flag is missing or isn't a Boolean: +Pass a flag key to check whether the flag is enabled: ```ts -const enabled = reflag.getFlag("huddles"); // boolean +const enabled = reflag.getFlag("huddles"); // true or false ``` -To read a configuration value, pass a default. The return type follows the default, and you get the default back if the flag is missing or holds a different type of value: +To read a configuration value, pass a default as the second argument. You get back a value of the same type as the default: ```ts const model = reflag.getFlag("model", "quick"); // string -const limit = reflag.getFlag("limit", 10); // number const settings = reflag.getFlag("assistant-settings", { model: "quick" }); // { model: string } ``` -Pass `null` to accept any JSON value, then narrow it yourself: - -```ts -const value = reflag.getFlag("nullable-settings", null); -``` +If the flag doesn't exist, or its value has a different type, you get `false`, or your default if you passed one. Pass `null` as the default to accept any JSON value and narrow it yourself. The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. diff --git a/sdk/@reflag/node-sdk/README.md b/sdk/@reflag/node-sdk/README.md index 4a3164b..bdc47c0 100644 --- a/sdk/@reflag/node-sdk/README.md +++ b/sdk/@reflag/node-sdk/README.md @@ -55,16 +55,21 @@ The SDK downloads your flag definitions and evaluates flags locally, so reads do ## Read flags -Without a default, `getFlag()` returns a Boolean. You get `false` if the flag is missing or isn't a Boolean. +Pass a context and a flag key to check whether the flag is enabled: -To read a configuration value, pass a default. The return type follows the default, and you get the default back if the flag is missing or holds a different type of value: +```ts +const enabled = reflag.getFlag(context, "new-editor"); // true or false +``` + +To read a configuration value, pass a default as the third argument. You get back a value of the same type as the default: ```ts const model = reflag.getFlag(context, "model", "quick"); // string const limits = reflag.getFlag(context, "limits", { maxItems: 10 }); // { maxItems: number } -const payload = reflag.getFlag(context, "nullable-settings", null); // any JSON value; narrow it yourself ``` +If the flag doesn't exist, or its value has a different type, you get `false`, or your default if you passed one. Pass `null` as the default to accept any JSON value and narrow it yourself. + The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. `getFlags(context)` returns all flag values as a record; a value can be `undefined` if the flag is unavailable. diff --git a/sdk/@reflag/react-sdk/README.md b/sdk/@reflag/react-sdk/README.md index 844c1af..6d346aa 100644 --- a/sdk/@reflag/react-sdk/README.md +++ b/sdk/@reflag/react-sdk/README.md @@ -58,19 +58,21 @@ function Huddles() { ## Read flags -Without a default, `useFlag()` returns a Boolean. You get `false` while flags are loading, and if the flag is missing or isn't a Boolean. - -To read a configuration value, pass a default. The return type follows the default, and you get the default back while loading, or if the flag is missing or holds a different type of value: +Pass a flag key to check whether the flag is enabled: ```tsx -const settings = useFlag("huddle-settings", { maxParticipants: 10 }); -// settings.maxParticipants: number +const enabled = useFlag("huddles"); // true or false +``` + +To read a configuration value, pass a default as the second argument. You get back a value of the same type as the default: -useFlag("model", "quick"); // string -useFlag("limit", 10); // number -useFlag("nullable-settings", null); // any JSON value; narrow it yourself +```tsx +const model = useFlag("model", "quick"); // string +const settings = useFlag("huddle-settings", { maxParticipants: 10 }); // { maxParticipants: number } ``` +While flags are loading, if the flag doesn't exist, or if its value has a different type, you get `false`, or your default if you passed one. Pass `null` as the default to accept any JSON value and narrow it yourself. + The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. diff --git a/sdk/@reflag/vue-sdk/README.md b/sdk/@reflag/vue-sdk/README.md index c30a82c..2055328 100644 --- a/sdk/@reflag/vue-sdk/README.md +++ b/sdk/@reflag/vue-sdk/README.md @@ -69,19 +69,21 @@ const track = useTrack(); `useFlag()` returns a ref that updates when the flag changes. Vue unwraps refs in templates; use `.value` in script. -Without a default, the ref holds a Boolean. It is `false` while flags are loading, and if the flag is missing or isn't a Boolean. - -To read a configuration value, pass a default. The type follows the default, and the ref holds the default while loading, or if the flag is missing or holds a different type of value: +Pass a flag key to check whether the flag is enabled: ```ts -const settings = useFlag("huddle-settings", { maxParticipants: 10 }); -// settings.value.maxParticipants: number +const enabled = useFlag("huddles"); // ref of true or false +``` + +To read a configuration value, pass a default as the second argument. The ref holds a value of the same type as the default: -useFlag("model", "quick"); // Ref of string -useFlag("limit", 10); // Ref of number -useFlag("nullable-settings", null); // any JSON value; narrow it yourself +```ts +const model = useFlag("model", "quick"); // ref of string +const settings = useFlag("huddle-settings", { maxParticipants: 10 }); // ref of { maxParticipants: number } ``` +While flags are loading, if the flag doesn't exist, or if its value has a different type, the ref holds `false`, or your default if you passed one. Pass `null` as the default to accept any JSON value and narrow it yourself. + The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. diff --git a/sdk/documents/browser-sdk/FEEDBACK.md b/sdk/documents/browser-sdk/FEEDBACK.md index 5839501..000d8ae 100644 --- a/sdk/documents/browser-sdk/FEEDBACK.md +++ b/sdk/documents/browser-sdk/FEEDBACK.md @@ -284,7 +284,7 @@ See examples below. ![image](https://github.com/reflagcom/javascript/assets/331790/68805b38-e9f6-4de5-9f55-188216983e3c) -See [default English localization keys](https://github.com/reflagcom/javascript/tree/f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) +See [default English localization keys](https://github.com/reflagcom/javascript/tree/e7d2a4039d435f4f1c758b6e72d4ff5222bcc340/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) for a reference of what translation keys can be supplied. ### Static language configuration @@ -398,7 +398,7 @@ For example, a dark mode theme might look like this: } ``` -Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684/packages/browser-sdk/src/feedback/ui/index.css). +Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/e7d2a4039d435f4f1c758b6e72d4ff5222bcc340/packages/browser-sdk/src/feedback/ui/index.css). ## Using your own UI to collect feedback @@ -423,7 +423,7 @@ Reflag API. ### Manual feedback collection with custom UI Examples of a HTML-form that collects the relevant data can be found -in [feedback.html](https://github.com/reflagcom/javascript/tree/f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684/packages/browser-sdk/example/feedback/Feedback.jsx). +in [feedback.html](https://github.com/reflagcom/javascript/tree/e7d2a4039d435f4f1c758b6e72d4ff5222bcc340/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/e7d2a4039d435f4f1c758b6e72d4ff5222bcc340/packages/browser-sdk/example/feedback/Feedback.jsx). Once you have collected the feedback data, pass it along to `reflagClient.feedback()`: diff --git a/sdk/documents/react-sdk/README.md b/sdk/documents/react-sdk/README.md index 844c1af..6d346aa 100644 --- a/sdk/documents/react-sdk/README.md +++ b/sdk/documents/react-sdk/README.md @@ -58,19 +58,21 @@ function Huddles() { ## Read flags -Without a default, `useFlag()` returns a Boolean. You get `false` while flags are loading, and if the flag is missing or isn't a Boolean. - -To read a configuration value, pass a default. The return type follows the default, and you get the default back while loading, or if the flag is missing or holds a different type of value: +Pass a flag key to check whether the flag is enabled: ```tsx -const settings = useFlag("huddle-settings", { maxParticipants: 10 }); -// settings.maxParticipants: number +const enabled = useFlag("huddles"); // true or false +``` + +To read a configuration value, pass a default as the second argument. You get back a value of the same type as the default: -useFlag("model", "quick"); // string -useFlag("limit", 10); // number -useFlag("nullable-settings", null); // any JSON value; narrow it yourself +```tsx +const model = useFlag("model", "quick"); // string +const settings = useFlag("huddle-settings", { maxParticipants: 10 }); // { maxParticipants: number } ``` +While flags are loading, if the flag doesn't exist, or if its value has a different type, you get `false`, or your default if you passed one. Pass `null` as the default to accept any JSON value and narrow it yourself. + The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. diff --git a/supported-languages/browser-sdk/README.md b/supported-languages/browser-sdk/README.md index f874c65..5c9a2b1 100644 --- a/supported-languages/browser-sdk/README.md +++ b/supported-languages/browser-sdk/README.md @@ -48,25 +48,20 @@ Publishable keys are safe to ship to the browser. Keep secret keys on your serve ## Read flags -Without a default, `getFlag()` returns a Boolean. You get `false` if the flag is missing or isn't a Boolean: +Pass a flag key to check whether the flag is enabled: ```ts -const enabled = reflag.getFlag("huddles"); // boolean +const enabled = reflag.getFlag("huddles"); // true or false ``` -To read a configuration value, pass a default. The return type follows the default, and you get the default back if the flag is missing or holds a different type of value: +To read a configuration value, pass a default as the second argument. You get back a value of the same type as the default: ```ts const model = reflag.getFlag("model", "quick"); // string -const limit = reflag.getFlag("limit", 10); // number const settings = reflag.getFlag("assistant-settings", { model: "quick" }); // { model: string } ``` -Pass `null` to accept any JSON value, then narrow it yourself: - -```ts -const value = reflag.getFlag("nullable-settings", null); -``` +If the flag doesn't exist, or its value has a different type, you get `false`, or your default if you passed one. Pass `null` as the default to accept any JSON value and narrow it yourself. The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. diff --git a/supported-languages/browser-sdk/feedback.md b/supported-languages/browser-sdk/feedback.md index d8f780d..0ecb8e2 100644 --- a/supported-languages/browser-sdk/feedback.md +++ b/supported-languages/browser-sdk/feedback.md @@ -284,7 +284,7 @@ See examples below. ![image](https://github.com/reflagcom/javascript/assets/331790/68805b38-e9f6-4de5-9f55-188216983e3c) -See [default English localization keys](https://github.com/reflagcom/javascript/tree/f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) +See [default English localization keys](https://github.com/reflagcom/javascript/tree/e7d2a4039d435f4f1c758b6e72d4ff5222bcc340/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) for a reference of what translation keys can be supplied. ### Static language configuration @@ -398,7 +398,7 @@ For example, a dark mode theme might look like this: } ``` -Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684/packages/browser-sdk/src/feedback/ui/index.css). +Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/e7d2a4039d435f4f1c758b6e72d4ff5222bcc340/packages/browser-sdk/src/feedback/ui/index.css). ## Using your own UI to collect feedback @@ -423,7 +423,7 @@ Reflag API. ### Manual feedback collection with custom UI Examples of a HTML-form that collects the relevant data can be found -in [feedback.html](https://github.com/reflagcom/javascript/tree/f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/f7b6eb4fe2ca5ff5339de95d3f4f9158b5d60684/packages/browser-sdk/example/feedback/Feedback.jsx). +in [feedback.html](https://github.com/reflagcom/javascript/tree/e7d2a4039d435f4f1c758b6e72d4ff5222bcc340/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/e7d2a4039d435f4f1c758b6e72d4ff5222bcc340/packages/browser-sdk/example/feedback/Feedback.jsx). Once you have collected the feedback data, pass it along to `reflagClient.feedback()`: diff --git a/supported-languages/node-sdk/README.md b/supported-languages/node-sdk/README.md index efe25bb..f7747f5 100644 --- a/supported-languages/node-sdk/README.md +++ b/supported-languages/node-sdk/README.md @@ -55,16 +55,21 @@ The SDK downloads your flag definitions and evaluates flags locally, so reads do ## Read flags -Without a default, `getFlag()` returns a Boolean. You get `false` if the flag is missing or isn't a Boolean. +Pass a context and a flag key to check whether the flag is enabled: -To read a configuration value, pass a default. The return type follows the default, and you get the default back if the flag is missing or holds a different type of value: +```ts +const enabled = reflag.getFlag(context, "new-editor"); // true or false +``` + +To read a configuration value, pass a default as the third argument. You get back a value of the same type as the default: ```ts const model = reflag.getFlag(context, "model", "quick"); // string const limits = reflag.getFlag(context, "limits", { maxItems: 10 }); // { maxItems: number } -const payload = reflag.getFlag(context, "nullable-settings", null); // any JSON value; narrow it yourself ``` +If the flag doesn't exist, or its value has a different type, you get `false`, or your default if you passed one. Pass `null` as the default to accept any JSON value and narrow it yourself. + The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. `getFlags(context)` returns all flag values as a record; a value can be `undefined` if the flag is unavailable. diff --git a/supported-languages/react-sdk/README.md b/supported-languages/react-sdk/README.md index d5e024b..37aacd5 100644 --- a/supported-languages/react-sdk/README.md +++ b/supported-languages/react-sdk/README.md @@ -58,19 +58,21 @@ function Huddles() { ## Read flags -Without a default, `useFlag()` returns a Boolean. You get `false` while flags are loading, and if the flag is missing or isn't a Boolean. - -To read a configuration value, pass a default. The return type follows the default, and you get the default back while loading, or if the flag is missing or holds a different type of value: +Pass a flag key to check whether the flag is enabled: ```tsx -const settings = useFlag("huddle-settings", { maxParticipants: 10 }); -// settings.maxParticipants: number +const enabled = useFlag("huddles"); // true or false +``` + +To read a configuration value, pass a default as the second argument. You get back a value of the same type as the default: -useFlag("model", "quick"); // string -useFlag("limit", 10); // number -useFlag("nullable-settings", null); // any JSON value; narrow it yourself +```tsx +const model = useFlag("model", "quick"); // string +const settings = useFlag("huddle-settings", { maxParticipants: 10 }); // { maxParticipants: number } ``` +While flags are loading, if the flag doesn't exist, or if its value has a different type, you get `false`, or your default if you passed one. Pass `null` as the default to accept any JSON value and narrow it yourself. + The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. diff --git a/supported-languages/vue-sdk/README.md b/supported-languages/vue-sdk/README.md index a4189a7..47abe03 100644 --- a/supported-languages/vue-sdk/README.md +++ b/supported-languages/vue-sdk/README.md @@ -69,19 +69,21 @@ const track = useTrack(); `useFlag()` returns a ref that updates when the flag changes. Vue unwraps refs in templates; use `.value` in script. -Without a default, the ref holds a Boolean. It is `false` while flags are loading, and if the flag is missing or isn't a Boolean. - -To read a configuration value, pass a default. The type follows the default, and the ref holds the default while loading, or if the flag is missing or holds a different type of value: +Pass a flag key to check whether the flag is enabled: ```ts -const settings = useFlag("huddle-settings", { maxParticipants: 10 }); -// settings.value.maxParticipants: number +const enabled = useFlag("huddles"); // ref of true or false +``` + +To read a configuration value, pass a default as the second argument. The ref holds a value of the same type as the default: -useFlag("model", "quick"); // Ref of string -useFlag("limit", 10); // Ref of number -useFlag("nullable-settings", null); // any JSON value; narrow it yourself +```ts +const model = useFlag("model", "quick"); // ref of string +const settings = useFlag("huddle-settings", { maxParticipants: 10 }); // ref of { maxParticipants: number } ``` +While flags are loading, if the flag doesn't exist, or if its value has a different type, the ref holds `false`, or your default if you passed one. Pass `null` as the default to accept any JSON value and narrow it yourself. + The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. From 3d3b61e03c3512f80b893ff0176b68c823d38cea Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:24:58 +0000 Subject: [PATCH 10/18] docs: separate Multivariate flags from Remote config --- .github/scripts/check-sdk-docs.mjs | 2 + .github/scripts/check-sdk-examples.cjs | 2 +- .github/scripts/sdk-docs.test.mjs | 22 ++++++ SUMMARY.md | 1 + product-handbook/multivariate-flags.md | 89 ++++++++++++++++++++++++ product-handbook/remote-config.md | 88 +---------------------- supported-languages/migrating-from-v1.md | 2 +- 7 files changed, 117 insertions(+), 89 deletions(-) create mode 100644 product-handbook/multivariate-flags.md diff --git a/.github/scripts/check-sdk-docs.mjs b/.github/scripts/check-sdk-docs.mjs index 451caa4..e932663 100644 --- a/.github/scripts/check-sdk-docs.mjs +++ b/.github/scripts/check-sdk-docs.mjs @@ -230,6 +230,8 @@ export function checkSDKDocs(base = root) { "supported-languages/next.js.md", "product-handbook/service-resiliency.md", "product-handbook/type-safety.md", + "product-handbook/remote-config.md", + "product-handbook/multivariate-flags.md", ].includes(file), ), ]); diff --git a/.github/scripts/check-sdk-examples.cjs b/.github/scripts/check-sdk-examples.cjs index 8e462db..69d89b0 100644 --- a/.github/scripts/check-sdk-examples.cjs +++ b/.github/scripts/check-sdk-examples.cjs @@ -80,7 +80,7 @@ function compile(label, code, legacy = false, extra = {}) { } try { for (const file of [ - "product-handbook/remote-config.md", + "product-handbook/multivariate-flags.md", "product-handbook/anonymous-users.md", "product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta.md", "product-handbook/type-safety.md", diff --git a/.github/scripts/sdk-docs.test.mjs b/.github/scripts/sdk-docs.test.mjs index a3e0e16..23c1e77 100644 --- a/.github/scripts/sdk-docs.test.mjs +++ b/.github/scripts/sdk-docs.test.mjs @@ -71,6 +71,28 @@ test("repository navigation, provenance, cross-version links, assets and anchors assert(checkSDKDocs().generatedPages >= 28); }); +test("handbook keeps Remote config as a short pointer to the full Multivariate flags guide", () => { + const summary = fs.readFileSync(path.join(root, "SUMMARY.md"), "utf8"); + for (const file of ["remote-config.md", "multivariate-flags.md"]) + assert(summary.includes(`(product-handbook/${file})`)); + const remote = fs.readFileSync(path.join(root, "product-handbook/remote-config.md"), "utf8"); + const paragraph = remote + .replace(/^---\n[\s\S]*?\n---\n/, "") + .replace(/^# Remote config\s*/m, "") + .trim(); + assert.equal(paragraph.split(/\n\s*\n/).length, 1); + assert.match(paragraph, /\[Multivariate flag\]\(multivariate-flags\.md\)/); + assert(!paragraph.includes("```")); + const multivariate = fs.readFileSync( + path.join(root, "product-handbook/multivariate-flags.md"), + "utf8", + ); + assert.match(multivariate, /^# Multivariate flags$/m); + assert(multivariate.includes("export function AssistantSettings()")); + assert(multivariate.includes("export function AssistantModel()")); + checkLinks(root, ["product-handbook/remote-config.md", "product-handbook/multivariate-flags.md"]); +}); + test("CI discovers exact source refs from manifests rather than hardcoding the first import", () => { const matrix = sourceMatrix(); assert(matrix.include.length > 0); diff --git a/SUMMARY.md b/SUMMARY.md index 061b4c6..01e1707 100644 --- a/SUMMARY.md +++ b/SUMMARY.md @@ -59,6 +59,7 @@ * [End-user opt-in](product-handbook/feature-rollouts/end-user-opt-in.md) * [Flag clean-up and archival](product-handbook/feature-clean-up-and-archival-beta/README.md) * [AI code clean-up](product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta.md) +* [Multivariate flags](product-handbook/multivariate-flags.md) * [Remote config](product-handbook/remote-config.md) * [Type safety](product-handbook/type-safety.md) * [Team permissions](product-handbook/team-permissions.md) diff --git a/product-handbook/multivariate-flags.md b/product-handbook/multivariate-flags.md new file mode 100644 index 0000000..d1435e5 --- /dev/null +++ b/product-handbook/multivariate-flags.md @@ -0,0 +1,89 @@ +--- +description: Configure JSON-valued Multivariate flags for different audiences. +--- + +# Multivariate flags + +## What are Multivariate flags? + +Use a **Multivariate flag** when different users or companies need different configuration values. Unlike a Boolean flag, which answers an access question, a Multivariate flag selects a named variant and returns its JSON value directly. + +A value can be an object, array, string, number, Boolean, or `null`. + +For example, configure `assistant-settings` with variants containing different model settings, then read it with the React SDK: + +```tsx +import { useFlag } from "@reflag/react-sdk"; + +export function AssistantSettings() { + const settings = useFlag("assistant-settings", { + model: "quick", + maxTokens: 512, + includeCitations: false, + }); + + return ( +

+ Model: {settings.model}; token limit: {settings.maxTokens}; citations:{" "} + {settings.includeCitations ? "on" : "off"} +

+ ); +} +``` + +The second argument is a default, used while flags load or if the flag can't be read. Always pass one when reading a Multivariate flag; without it, `useFlag()` reads the flag as a Boolean. Pass `null` to accept any JSON value and narrow it yourself. + +## Variants and values + +Each environment's definition contains: + +- **Variants:** unique keys and their JSON values. The SDK returns the selected variant's **value**. +- **Specific targets:** explicit user/company assignments to variants. +- **Ordered rules:** filters and results, including percentage distributions. +- **Default variant:** the authored selection when no more-specific target or applicable rule selects a variant. + +Variants, targets and rules are set per environment. Changes in one environment aren't copied to the others. A Multivariate flag with no variants returns `null`. + +The default variant is set in Reflag. It's different from the default you pass in code, which is only used when the SDK can't read the flag. + +{% hint style="danger" %} +Do not store credentials or other secrets in flag values. Anything sent to a browser can be inspected by its users. Keep application secrets in an appropriate secret manager. +{% endhint %} + +## Matching algorithm + +Specific user assignments take precedence over company assignments. Then rules are considered in order; the default variant handles contexts that do not select an earlier result. Rules can use the supported user, company, segment, and other-context filters. Percentage distributions assign variants using the configured bucketing attribute. + +To turn a feature on or off, use a separate Boolean flag. Values such as `false`, `0` or `null` in a Multivariate flag are ordinary data, so don't use them to decide access. + +## Usage scenarios + +### Basic flag configuration + +Use a single default variant for configuration you want to manage in one place, or add rules and more variants when different audiences need different settings. Pass a safe default in code. + +The SDK checks only the top-level type of a value against your default. If your application depends on nested fields, validate them. [Generated types](type-safety.md) are checked at compile time only. + +### Model selection + +For string-valued variants, the value can itself be the model or mode your application needs: + +```tsx +import { useFlag } from "@reflag/react-sdk"; + +export function AssistantModel() { + const model = useFlag("assistant-model", "quick"); + return

Selected model: {model}

; +} +``` + +### Entitlements + +Combine a Boolean entitlement such as `assistant-enabled` with a separate settings flag when access and configuration are independent decisions. Use company attributes and rules to pick settings for each subscription tier. + +## Start using Multivariate flags + +1. Create a **Multivariate** flag in an app where Multivariate support is available. +2. Open its **Variants** tab and configure variants, specific targets, rules, and the default for the selected environment. +3. Save, then configure and verify any other environments separately. +4. Read the value with a [Reflag SDK](../supported-languages/overview.md), passing a default. diff --git a/product-handbook/remote-config.md b/product-handbook/remote-config.md index 7025401..0e7558c 100644 --- a/product-handbook/remote-config.md +++ b/product-handbook/remote-config.md @@ -1,89 +1,3 @@ ---- -description: Configure JSON-valued Multivariate flags for different audiences. ---- - # Remote config -## What is remote config? - -Use a **Multivariate flag** when different users or companies need different configuration values. Unlike a Boolean flag, which answers an access question, a Multivariate flag selects a named variant and returns its JSON value directly. - -A value can be an object, array, string, number, Boolean, or `null`. - -For example, configure `assistant-settings` with variants containing different model settings, then read it with the React SDK: - -```tsx -import { useFlag } from "@reflag/react-sdk"; - -export function AssistantSettings() { - const settings = useFlag("assistant-settings", { - model: "quick", - maxTokens: 512, - includeCitations: false, - }); - - return ( -

- Model: {settings.model}; token limit: {settings.maxTokens}; - citations: {settings.includeCitations ? "on" : "off"} -

- ); -} -``` - -The second argument is a default, used while flags load or if the flag can't be read. Always pass one when reading a Multivariate flag; without it, `useFlag()` reads the flag as a Boolean. Pass `null` to accept any JSON value and narrow it yourself. - -## Config values - -Each environment's definition contains: - -- **Variants:** unique keys and their JSON values. The SDK returns the selected variant's **value**. -- **Specific targets:** explicit user/company assignments to variants. -- **Ordered rules:** filters and results, including percentage distributions. -- **Default variant:** the authored selection when no more-specific target or applicable rule selects a variant. - -Variants, targets and rules are set per environment. Changes in one environment aren't copied to the others. A Multivariate flag with no variants returns `null`. - -The default variant is set in Reflag. It's different from the default you pass in code, which is only used when the SDK can't read the flag. - -{% hint style="danger" %} -Do not store credentials or other secrets in flag values. Anything sent to a browser can be inspected by its users. Keep application secrets in an appropriate secret manager. -{% endhint %} - -## Matching algorithm - -Specific user assignments take precedence over company assignments. Then rules are considered in order; the default variant handles contexts that do not select an earlier result. Rules can use the supported user, company, segment, and other-context filters. Percentage distributions assign variants using the configured bucketing attribute. - -To turn a feature on or off, use a separate Boolean flag. Values such as `false`, `0` or `null` in a Multivariate flag are ordinary data, so don't use them to decide access. - -## Usage scenarios - -### Basic flag configuration - -Use a single default variant for configuration you want to manage in one place, or add rules and more variants when different audiences need different settings. Pass a safe default in code. - -The SDK checks only the top-level type of a value against your default. If your application depends on nested fields, validate them. [Generated types](type-safety.md) are checked at compile time only. - -### Multivariate flags - -For string-valued variants, the value can itself be the model or mode your application needs: - -```tsx -import { useFlag } from "@reflag/react-sdk"; - -export function AssistantModel() { - const model = useFlag("assistant-model", "quick"); - return

Selected model: {model}

; -} -``` - -### Entitlements - -Combine a Boolean entitlement such as `assistant-enabled` with a separate settings flag when access and configuration are independent decisions. Use company attributes and rules to pick settings for each subscription tier. - -## Start using remote config - -1. Create a **Multivariate** flag in an app where Multivariate support is available. -2. Open its **Variants** tab and configure variants, specific targets, rules, and the default for the selected environment. -3. Save, then configure and verify any other environments separately. -4. Read the value with a [Reflag SDK](../supported-languages/overview.md), passing a default. +Use a [Multivariate flag](multivariate-flags.md) for remote configuration. Define your configuration values as variants, then use targeting rules to choose which value each user or company receives. diff --git a/supported-languages/migrating-from-v1.md b/supported-languages/migrating-from-v1.md index 081580d..0fd9f0a 100644 --- a/supported-languages/migrating-from-v1.md +++ b/supported-languages/migrating-from-v1.md @@ -97,7 +97,7 @@ const maxItems = config.payload?.maxItems ?? 10; const { maxItems } = useFlag("editor-settings", { maxItems: 10 }); ``` -Existing remote config is **not converted automatically**. If a v1 flag controlled both access and configuration, split it into a Boolean flag for access and a Multivariate flag for the settings. See [Remote config](../product-handbook/remote-config.md). +Existing remote config is **not converted automatically**. If a v1 flag controlled both access and configuration, split it into a Boolean flag for access and a Multivariate flag for the settings. See [Multivariate flags](../product-handbook/multivariate-flags.md). ## 3. Separate usage tracking and feedback From cba8cfca6613f8750f7fdff3d97a3a8517e1913a Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:51:33 +0000 Subject: [PATCH 11/18] docs: clarify Multivariate flags and remote config migration --- .github/scripts/sdk-docs.test.mjs | 2 + product-handbook/multivariate-flags.md | 64 +++++++++++++++++------- supported-languages/migrating-from-v1.md | 16 +++--- 3 files changed, 55 insertions(+), 27 deletions(-) diff --git a/.github/scripts/sdk-docs.test.mjs b/.github/scripts/sdk-docs.test.mjs index 23c1e77..76820a3 100644 --- a/.github/scripts/sdk-docs.test.mjs +++ b/.github/scripts/sdk-docs.test.mjs @@ -90,6 +90,8 @@ test("handbook keeps Remote config as a short pointer to the full Multivariate f assert.match(multivariate, /^# Multivariate flags$/m); assert(multivariate.includes("export function AssistantSettings()")); assert(multivariate.includes("export function AssistantModel()")); + assert.match(multivariate, /^## Migrating from Remote config$/m); + assert(multivariate.includes("[Reflag MCP](../api/mcp.md)")); checkLinks(root, ["product-handbook/remote-config.md", "product-handbook/multivariate-flags.md"]); }); diff --git a/product-handbook/multivariate-flags.md b/product-handbook/multivariate-flags.md index d1435e5..a8a5274 100644 --- a/product-handbook/multivariate-flags.md +++ b/product-handbook/multivariate-flags.md @@ -1,14 +1,14 @@ --- -description: Configure JSON-valued Multivariate flags for different audiences. +description: Serve different configuration values to different users and companies. --- # Multivariate flags ## What are Multivariate flags? -Use a **Multivariate flag** when different users or companies need different configuration values. Unlike a Boolean flag, which answers an access question, a Multivariate flag selects a named variant and returns its JSON value directly. +A **Multivariate flag** lets you serve different configuration values to different users or companies. Each variant has a name and a JSON value. Your application reads the value of the selected variant. -A value can be an object, array, string, number, Boolean, or `null`. +A variant's value can be text, a number, an object, an array, a Boolean, or `null`. For example, configure `assistant-settings` with variants containing different model settings, then read it with the React SDK: @@ -31,42 +31,47 @@ export function AssistantSettings() { } ``` -The second argument is a default, used while flags load or if the flag can't be read. Always pass one when reading a Multivariate flag; without it, `useFlag()` reads the flag as a Boolean. Pass `null` to accept any JSON value and narrow it yourself. +The second argument supplies a default while flags load or if the flag is unavailable. In this example, the default is the `quick` model with a 512-token limit and citations turned off. Pass a default when reading a Multivariate flag; without one, `useFlag()` expects a Boolean value. ## Variants and values -Each environment's definition contains: +For each environment, configure: -- **Variants:** unique keys and their JSON values. The SDK returns the selected variant's **value**. -- **Specific targets:** explicit user/company assignments to variants. -- **Ordered rules:** filters and results, including percentage distributions. -- **Default variant:** the authored selection when no more-specific target or applicable rule selects a variant. +- **Variants:** the named values your application can receive. +- **Specific targets:** users or companies that should receive a particular variant. +- **Rules:** conditions for choosing a variant, or splitting traffic between variants by percentage. +- **Default variant:** the variant to use when no assignment or rule selects one. -Variants, targets and rules are set per environment. Changes in one environment aren't copied to the others. A Multivariate flag with no variants returns `null`. +Configure each environment separately. Changing a variant or rule in one environment doesn't update the others. -The default variant is set in Reflag. It's different from the default you pass in code, which is only used when the SDK can't read the flag. +The **default variant** is a choice you make in Reflag. The **SDK default** is the fallback value you pass in code, used while flags load or when a value can't be read. {% hint style="danger" %} -Do not store credentials or other secrets in flag values. Anything sent to a browser can be inspected by its users. Keep application secrets in an appropriate secret manager. +Don't put API keys, passwords, or other secrets in flag values. Values sent to a browser are visible to its users. Store secrets in a secret manager instead. {% endhint %} ## Matching algorithm -Specific user assignments take precedence over company assignments. Then rules are considered in order; the default variant handles contexts that do not select an earlier result. Rules can use the supported user, company, segment, and other-context filters. Percentage distributions assign variants using the configured bucketing attribute. +Reflag chooses a variant in this order: -To turn a feature on or off, use a separate Boolean flag. Values such as `false`, `0` or `null` in a Multivariate flag are ordinary data, so don't use them to decide access. +1. An assignment for the specific user. +2. An assignment for the user's company. +3. Targeting rules, from top to bottom. +4. The default variant, if nothing else selects a variant. + +Rules can match user or company attributes, segments, and other context. They can also split traffic between variants by percentage. ## Usage scenarios ### Basic flag configuration -Use a single default variant for configuration you want to manage in one place, or add rules and more variants when different audiences need different settings. Pass a safe default in code. +Start with one variant and make it the default. Add more variants and targeting rules when different audiences need different settings. -The SDK checks only the top-level type of a value against your default. If your application depends on nested fields, validate them. [Generated types](type-safety.md) are checked at compile time only. +For structured settings, use consistent fields across variants. [Type safety](type-safety.md) adds autocomplete and type checks in your editor. ### Model selection -For string-valued variants, the value can itself be the model or mode your application needs: +For a simple model selector, use strings as the variant values, such as `"quick"` and `"reasoner"`: ```tsx import { useFlag } from "@reflag/react-sdk"; @@ -79,11 +84,32 @@ export function AssistantModel() { ### Entitlements -Combine a Boolean entitlement such as `assistant-enabled` with a separate settings flag when access and configuration are independent decisions. Use company attributes and rules to pick settings for each subscription tier. +Use Multivariate flags for plan-specific settings, such as usage limits or available models. Target a company's plan to choose the settings for each subscription tier. See [Feature entitlements](feature-entitlements/README.md) for examples. + +If access and configuration are separate decisions, use a Boolean flag such as `assistant-enabled` for the on/off switch and a Multivariate flag for the settings. ## Start using Multivariate flags -1. Create a **Multivariate** flag in an app where Multivariate support is available. +1. Create a **Multivariate** flag. 2. Open its **Variants** tab and configure variants, specific targets, rules, and the default for the selected environment. 3. Save, then configure and verify any other environments separately. 4. Read the value with a [Reflag SDK](../supported-languages/overview.md), passing a default. + +## Migrating from Remote config + +Legacy Remote config and Multivariate flags are separate features. Existing remote configs aren't converted automatically. + +1. **Review the existing config.** Record its keys and JSON payloads, along with the assignments, rules, and default in each environment. Check whether your application reads `config.payload`, `config.key`, or both. +2. **Create a Multivariate flag with a new key**, such as `assistant-settings`. Keep the original Release flag and its access rules in place while you migrate. +3. **Copy the values your application uses.** If it reads `config.payload`, use that JSON as the variant value. If it reads `config.key`, use the old key as a string value. If it needs both, include both in an object and update your code to read that object. +4. **Recreate targeting in each environment.** Copy user/company assignments, rules, and the default. Preserve the original evaluation order when rules overlap. Unlike legacy Remote config, Multivariate variants and values are configured separately in each environment. +5. **Update and test your application.** Use [SDK v2](../supported-languages/migrating-from-v1.md#2-migrate-remote-config-explicitly) to read the new flag's value directly, rather than through `.config`. Keep any existing Boolean access checks. Compare the old and new results for representative users and companies in each environment. +6. **Retire the old config once clients no longer use it.** Leave it available for any clients still on SDK v1. Don't delete a Release flag that's still used for access checks. + +### Using an AI agent + +With [Reflag MCP](../api/mcp.md), an agent can create and configure Multivariate flags. MCP doesn't currently expose legacy Remote config values or targeting, so you'll need to provide that information to the agent. + +Start by asking for a migration plan, rather than an immediate bulk migration: + +> Using the legacy Remote config values and targeting I provide, plan a migration to Multivariate flags for this app. Preserve values, defaults, and targeting in each environment, and keep existing Boolean access checks. Show the proposed flag keys and code changes. Ask for my approval before creating flags or changing configuration. Don't remove the old configs. diff --git a/supported-languages/migrating-from-v1.md b/supported-languages/migrating-from-v1.md index 0fd9f0a..f093bf1 100644 --- a/supported-languages/migrating-from-v1.md +++ b/supported-languages/migrating-from-v1.md @@ -86,7 +86,7 @@ Without a default, a read returns a Boolean: `false` if the flag is missing. Pas ## 2. Migrate remote config explicitly -v2 has no `.config` property. Create a Multivariate flag with the values your application needs, and read it with a default: +v2 has no `.config` property. Create a Multivariate flag with a new key and the values your application needs, then read it with a default: ```ts // v1 @@ -94,10 +94,10 @@ const { config } = useFlag("editor-settings"); const maxItems = config.payload?.maxItems ?? 10; // v2 -const { maxItems } = useFlag("editor-settings", { maxItems: 10 }); +const { maxItems } = useFlag("editor-config", { maxItems: 10 }); ``` -Existing remote config is **not converted automatically**. If a v1 flag controlled both access and configuration, split it into a Boolean flag for access and a Multivariate flag for the settings. See [Multivariate flags](../product-handbook/multivariate-flags.md). +Existing remote config is **not converted automatically**. If a v1 flag controlled both access and configuration, keep the existing Boolean flag for access and use the new Multivariate flag for settings. Follow the [Remote config migration steps](../product-handbook/multivariate-flags.md#migrating-from-remote-config). ## 3. Separate usage tracking and feedback @@ -135,9 +135,9 @@ Overrides and static fallback values are now plain values, such as `true` or `{ ## SDK documentation -| SDK | Current v2 | Legacy v1 | -| --- | --- | --- | +| SDK | Current v2 | Legacy v1 | +| ------- | -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | | Browser | [Guide](browser-sdk/README.md) · [Reference](browser-sdk/globals.md) | [Guide](../legacy/v1/browser-sdk/README.md) · [Reference](../legacy/v1/browser-sdk/globals.md) | -| React | [Guide](react-sdk/README.md) · [Reference](react-sdk/globals.md) | [Guide](../legacy/v1/react-sdk/README.md) · [Reference](../legacy/v1/react-sdk/globals.md) | -| Vue | [Guide](vue-sdk/README.md) · [Reference](vue-sdk/globals.md) | [Guide](../legacy/v1/vue-sdk/README.md) · [Reference](../legacy/v1/vue-sdk/globals.md) | -| Node.js | [Guide](node-sdk/README.md) · [Reference](node-sdk/globals.md) | [Guide](../legacy/v1/node-sdk/README.md) · [Reference](../legacy/v1/node-sdk/globals.md) | +| React | [Guide](react-sdk/README.md) · [Reference](react-sdk/globals.md) | [Guide](../legacy/v1/react-sdk/README.md) · [Reference](../legacy/v1/react-sdk/globals.md) | +| Vue | [Guide](vue-sdk/README.md) · [Reference](vue-sdk/globals.md) | [Guide](../legacy/v1/vue-sdk/README.md) · [Reference](../legacy/v1/vue-sdk/globals.md) | +| Node.js | [Guide](node-sdk/README.md) · [Reference](node-sdk/globals.md) | [Guide](../legacy/v1/node-sdk/README.md) · [Reference](../legacy/v1/node-sdk/globals.md) | From ac7ff2d2e8d39b0f8a9d5aa17eaa5fecbd9c99f0 Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:54:11 +0000 Subject: [PATCH 12/18] docs: use a portable link to the SDK upgrade guide --- product-handbook/multivariate-flags.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/product-handbook/multivariate-flags.md b/product-handbook/multivariate-flags.md index a8a5274..1c1347e 100644 --- a/product-handbook/multivariate-flags.md +++ b/product-handbook/multivariate-flags.md @@ -103,7 +103,7 @@ Legacy Remote config and Multivariate flags are separate features. Existing remo 2. **Create a Multivariate flag with a new key**, such as `assistant-settings`. Keep the original Release flag and its access rules in place while you migrate. 3. **Copy the values your application uses.** If it reads `config.payload`, use that JSON as the variant value. If it reads `config.key`, use the old key as a string value. If it needs both, include both in an object and update your code to read that object. 4. **Recreate targeting in each environment.** Copy user/company assignments, rules, and the default. Preserve the original evaluation order when rules overlap. Unlike legacy Remote config, Multivariate variants and values are configured separately in each environment. -5. **Update and test your application.** Use [SDK v2](../supported-languages/migrating-from-v1.md#2-migrate-remote-config-explicitly) to read the new flag's value directly, rather than through `.config`. Keep any existing Boolean access checks. Compare the old and new results for representative users and companies in each environment. +5. **Update and test your application.** Use [SDK v2](../supported-languages/migrating-from-v1.md) to read the new flag's value directly, rather than through `.config`. Keep any existing Boolean access checks. Compare the old and new results for representative users and companies in each environment. 6. **Retire the old config once clients no longer use it.** Leave it available for any clients still on SDK v1. Don't delete a Release flag that's still used for access checks. ### Using an AI agent From 42cf05d17d363feeacd20aa9a35313ff7667c28e Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:59:46 +0000 Subject: [PATCH 13/18] docs: describe upcoming MCP-assisted remote config migration --- product-handbook/multivariate-flags.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/product-handbook/multivariate-flags.md b/product-handbook/multivariate-flags.md index 1c1347e..a9b93b7 100644 --- a/product-handbook/multivariate-flags.md +++ b/product-handbook/multivariate-flags.md @@ -108,8 +108,8 @@ Legacy Remote config and Multivariate flags are separate features. Existing remo ### Using an AI agent -With [Reflag MCP](../api/mcp.md), an agent can create and configure Multivariate flags. MCP doesn't currently expose legacy Remote config values or targeting, so you'll need to provide that information to the agent. +Once the Remote config MCP tool is available, an agent connected to [Reflag MCP](../api/mcp.md) can read your existing configs and help recreate them as Multivariate flags. Start by asking for a migration plan, rather than an immediate bulk migration: -> Using the legacy Remote config values and targeting I provide, plan a migration to Multivariate flags for this app. Preserve values, defaults, and targeting in each environment, and keep existing Boolean access checks. Show the proposed flag keys and code changes. Ask for my approval before creating flags or changing configuration. Don't remove the old configs. +> Review this app's legacy Remote configs through Reflag MCP and plan a migration to Multivariate flags. Preserve values, defaults, and targeting in each environment, and keep existing Boolean access checks. Identify any clients still using SDK v1. Show the proposed flag keys and code changes. Ask for my approval before creating flags or changing configuration. Don't remove the old configs. From c35d60b363c54b313c87bb874b9627d8be503c14 Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:10:21 +0000 Subject: [PATCH 14/18] docs: present MCP-assisted remote config migration as available --- product-handbook/multivariate-flags.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/product-handbook/multivariate-flags.md b/product-handbook/multivariate-flags.md index a9b93b7..af027a1 100644 --- a/product-handbook/multivariate-flags.md +++ b/product-handbook/multivariate-flags.md @@ -108,7 +108,7 @@ Legacy Remote config and Multivariate flags are separate features. Existing remo ### Using an AI agent -Once the Remote config MCP tool is available, an agent connected to [Reflag MCP](../api/mcp.md) can read your existing configs and help recreate them as Multivariate flags. +An agent connected to [Reflag MCP](../api/mcp.md) can read your existing Remote configs and help migrate them to Multivariate flags. Start by asking for a migration plan, rather than an immediate bulk migration: From d36da389a01c1336f1727a9e3dacece986187dcc Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:02:08 +0000 Subject: [PATCH 15/18] docs: align SDK guide structure and tighten handbook wording Co-Authored-By: Claude Opus 5.5 --- .generated/sdk-docs/browser-sdk/v2.json | 10 ++--- .generated/sdk-docs/node-sdk/v2.json | 6 +-- .generated/sdk-docs/react-sdk/v2.json | 8 ++-- .generated/sdk-docs/vue-sdk/v2.json | 6 +-- product-handbook/multivariate-flags.md | 6 +-- product-handbook/type-safety.md | 16 ++++--- sdk/@reflag/browser-sdk/README.md | 13 ++++-- sdk/@reflag/node-sdk/README.md | 47 +++++++++++++++++---- sdk/@reflag/react-sdk/README.md | 14 ++++-- sdk/@reflag/vue-sdk/README.md | 14 +++--- sdk/documents/browser-sdk/FEEDBACK.md | 6 +-- sdk/documents/react-sdk/README.md | 14 ++++-- supported-languages/browser-sdk/README.md | 13 ++++-- supported-languages/browser-sdk/feedback.md | 6 +-- supported-languages/node-sdk/README.md | 47 +++++++++++++++++---- supported-languages/react-sdk/README.md | 14 ++++-- supported-languages/vue-sdk/README.md | 14 +++--- 17 files changed, 180 insertions(+), 74 deletions(-) diff --git a/.generated/sdk-docs/browser-sdk/v2.json b/.generated/sdk-docs/browser-sdk/v2.json index 6667ef0..57c06a9 100644 --- a/.generated/sdk-docs/browser-sdk/v2.json +++ b/.generated/sdk-docs/browser-sdk/v2.json @@ -1,14 +1,14 @@ { "sourceRepository": "https://github.com/reflagcom/javascript", - "sourceCommit": "e7d2a4039d435f4f1c758b6e72d4ff5222bcc340", + "sourceCommit": "d782fd0339de86a82a0b4293d18bf156fcdb63c4", "package": "@reflag/browser-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/browser-sdk/README.md": "170ec681580d7c72dd6d3efbc613ed9947ebee18075ecd279fa8bf73894a0239", - "sdk/@reflag/browser-sdk/README.md": "a58def792a7db5e78f2a34936c00b80142e68715352b495f254ea470ef11224b", + "supported-languages/browser-sdk/README.md": "a8f1a90ea81f31f6ddcf07e34c6af39f3addf8f3485535652e16bb90b7e3b2c0", + "sdk/@reflag/browser-sdk/README.md": "7f64f5357cae8be2328ed38599fb2210ebbd5e0e8210cfb8dc748ae9e3e664b4", "supported-languages/browser-sdk/globals.md": "4a3be858a621eb3839408d759329a60ab2ea406d0e21174b44b0639c678a1ffc", "sdk/@reflag/browser-sdk/globals.md": "a60d58526686dcc14ea5cdcecfa1d17388aff78f198f97f41bd667d35c7c39aa", - "supported-languages/browser-sdk/feedback.md": "821280fe2e6e5282518bfa0b7de912dbfa4db1246aa8e5f12be6539fff5db485", - "sdk/documents/browser-sdk/FEEDBACK.md": "4b5879ddb57ee123859df856923a2a2beff55db4a88cd17f3c4c9150c133d354" + "supported-languages/browser-sdk/feedback.md": "18902ebb57a7a278095a4b5662b2d023c3ef33092a0646017e39cf2620606794", + "sdk/documents/browser-sdk/FEEDBACK.md": "6c98fb8305be3328a7fd70a5bf18246d057ebadc4bfe7fbee0e9c70f56b8137f" } } diff --git a/.generated/sdk-docs/node-sdk/v2.json b/.generated/sdk-docs/node-sdk/v2.json index 684f644..a890bed 100644 --- a/.generated/sdk-docs/node-sdk/v2.json +++ b/.generated/sdk-docs/node-sdk/v2.json @@ -1,11 +1,11 @@ { "sourceRepository": "https://github.com/reflagcom/javascript", - "sourceCommit": "6ae28701b5deec5e153bb7bb03fe1c32108e89a5", + "sourceCommit": "c6d714437b00d1f3303eef3f7ccf86b880c409ff", "package": "@reflag/node-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/node-sdk/README.md": "d8552440b4dabc0fb865aef69c5af3c6478818302ea3e96a3eefe647f7d1004c", - "sdk/@reflag/node-sdk/README.md": "4f917c54ba70e34d60922d5b39b97e19694518ec37b2206fe22616d71e2a3122", + "supported-languages/node-sdk/README.md": "067e67bf1455824933fbb6e406d3528097ca54e43b61447944847c4763dbbbd2", + "sdk/@reflag/node-sdk/README.md": "27a9916f23a1e3cba2640e489ad06a14184cc70257143e0c9187225cf12836f2", "supported-languages/node-sdk/globals.md": "e1fc21f052e69b74582782ac7133513b077f328294f674523f087e4846338815", "sdk/@reflag/node-sdk/globals.md": "3fc142c7e452af2515b11c7efafa34d81bfe887f29ad1e2d6c81d31fb6736cc3" } diff --git a/.generated/sdk-docs/react-sdk/v2.json b/.generated/sdk-docs/react-sdk/v2.json index b98e1de..03bbb1d 100644 --- a/.generated/sdk-docs/react-sdk/v2.json +++ b/.generated/sdk-docs/react-sdk/v2.json @@ -1,12 +1,12 @@ { "sourceRepository": "https://github.com/reflagcom/javascript", - "sourceCommit": "e7d2a4039d435f4f1c758b6e72d4ff5222bcc340", + "sourceCommit": "d782fd0339de86a82a0b4293d18bf156fcdb63c4", "package": "@reflag/react-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/react-sdk/README.md": "8f9da095f57638836073e5af4334dfbc7e0322eb386822a8c7cd5a17a2436f22", - "sdk/@reflag/react-sdk/README.md": "94c265f8b2a439e5dbd2662073182d02da1e5b4d40af33cd32793d757a7603ee", - "sdk/documents/react-sdk/README.md": "94c265f8b2a439e5dbd2662073182d02da1e5b4d40af33cd32793d757a7603ee", + "supported-languages/react-sdk/README.md": "d86f92dac992e767fe54bd6923246cb50e35c7152c5ee3cbe6be014715bb2c6b", + "sdk/@reflag/react-sdk/README.md": "f738b8bc35662c30fe645dc2fec3d8632a4f880c21f77bfc1d95aebc4030eb9f", + "sdk/documents/react-sdk/README.md": "f738b8bc35662c30fe645dc2fec3d8632a4f880c21f77bfc1d95aebc4030eb9f", "supported-languages/react-sdk/globals.md": "f414859dd7cc94089d06f27613e1c554e3e3d5f049a9a141c2590058af768b1a", "sdk/@reflag/react-sdk/globals.md": "4cf0d20cca9c19d3998d9c5d0f6670d17d6782c24ee0ccd25e1d34100f42fcc6" } diff --git a/.generated/sdk-docs/vue-sdk/v2.json b/.generated/sdk-docs/vue-sdk/v2.json index 656bdb4..a714253 100644 --- a/.generated/sdk-docs/vue-sdk/v2.json +++ b/.generated/sdk-docs/vue-sdk/v2.json @@ -1,11 +1,11 @@ { "sourceRepository": "https://github.com/reflagcom/javascript", - "sourceCommit": "e7d2a4039d435f4f1c758b6e72d4ff5222bcc340", + "sourceCommit": "d782fd0339de86a82a0b4293d18bf156fcdb63c4", "package": "@reflag/vue-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/vue-sdk/README.md": "6034b6df8c207117a82afabee3a9b50c2051003ac87cd6a3fd5ef55b19830175", - "sdk/@reflag/vue-sdk/README.md": "f416fe772bd0b64403f26ceea2228b79740dd9813921a9652b85795e58ba40f6", + "supported-languages/vue-sdk/README.md": "cfc611d1d63d205c0daab869d466e14cd8fef77547305b1bb96fb827ed2b56f6", + "sdk/@reflag/vue-sdk/README.md": "fe9f5e9f331327075d6988d941da20b120279474e31df149b1d3467c400dab3c", "supported-languages/vue-sdk/globals.md": "968ec7df896ee2e78d1d23578acfadfc3378bd511b15c55eca79b6558588727f", "sdk/@reflag/vue-sdk/globals.md": "73ceaa29875b0d33a02dcfbf12cf1e50644b51d871cc496681bdbcbeee56ab2d" } diff --git a/product-handbook/multivariate-flags.md b/product-handbook/multivariate-flags.md index af027a1..a6b4fa2 100644 --- a/product-handbook/multivariate-flags.md +++ b/product-handbook/multivariate-flags.md @@ -50,7 +50,7 @@ The **default variant** is a choice you make in Reflag. The **SDK default** is t Don't put API keys, passwords, or other secrets in flag values. Values sent to a browser are visible to its users. Store secrets in a secret manager instead. {% endhint %} -## Matching algorithm +## How a variant is chosen Reflag chooses a variant in this order: @@ -63,7 +63,7 @@ Rules can match user or company attributes, segments, and other context. They ca ## Usage scenarios -### Basic flag configuration +### Start simple Start with one variant and make it the default. Add more variants and targeting rules when different audiences need different settings. @@ -103,7 +103,7 @@ Legacy Remote config and Multivariate flags are separate features. Existing remo 2. **Create a Multivariate flag with a new key**, such as `assistant-settings`. Keep the original Release flag and its access rules in place while you migrate. 3. **Copy the values your application uses.** If it reads `config.payload`, use that JSON as the variant value. If it reads `config.key`, use the old key as a string value. If it needs both, include both in an object and update your code to read that object. 4. **Recreate targeting in each environment.** Copy user/company assignments, rules, and the default. Preserve the original evaluation order when rules overlap. Unlike legacy Remote config, Multivariate variants and values are configured separately in each environment. -5. **Update and test your application.** Use [SDK v2](../supported-languages/migrating-from-v1.md) to read the new flag's value directly, rather than through `.config`. Keep any existing Boolean access checks. Compare the old and new results for representative users and companies in each environment. +5. **Update and test your application.** [Upgrade to SDK v2](../supported-languages/migrating-from-v1.md) and read the new flag's value directly, rather than through `.config`. Keep any existing Boolean access checks. Compare the old and new results for representative users and companies in each environment. 6. **Retire the old config once clients no longer use it.** Leave it available for any clients still on SDK v1. Don't delete a Release flag that's still used for access checks. ### Using an AI agent diff --git a/product-handbook/type-safety.md b/product-handbook/type-safety.md index b531b8b..af165e2 100644 --- a/product-handbook/type-safety.md +++ b/product-handbook/type-safety.md @@ -27,7 +27,7 @@ npx reflag init npx reflag flags types ``` -Choose the appropriate output format during initialization, or pass it explicitly: +`reflag init` asks which SDK you use. To choose the format explicitly: ```sh npx reflag flags types --format react --out gen/flags.d.ts @@ -35,7 +35,7 @@ npx reflag flags types --format node --out gen/flags.d.ts npx reflag flags types --format vue --out gen/flags.d.ts ``` -Pick the format for the SDK you use, and make sure TypeScript includes the output file. +Make sure TypeScript includes the output file. Types are generated from the variant values in your production environment. Regenerate them when your flags change, and let generation errors fail your build so the types don't silently go stale. @@ -45,7 +45,7 @@ You can commit the generated file, or ignore it and generate it on local setup a echo "gen/flags.d.ts" >> .gitignore ``` -## Registered schemas and defaults +## Check defaults against your flags A React registration looks like this (the CLI writes the appropriate augmentation for you): @@ -63,13 +63,17 @@ export function RegisteredSettings() { maxTokens: 512, model: "quick", }); - return {settings.model}: {settings.maxTokens}; + return ( + + {settings.model}: {settings.maxTokens} + + ); } ``` With a registered flag, TypeScript checks that the default you pass matches the flag's type, including nested fields. -These checks happen at compile time. At runtime, the SDK checks only the top-level type of a value, so validate nested fields your application depends on. +These checks happen at compile time only. See your SDK's guide for what it checks at runtime. ## Using in CI/CD pipelines @@ -82,4 +86,4 @@ Store a [Management API key](../api/api-access.md) as a secret in your CI system REFLAG_API_KEY: ${{ secrets.REFLAG_CI_API_KEY }} ``` -Install the CLI from your lockfile before running this step. +Install your project's dependencies before this step, so it uses the CLI version from your lockfile. diff --git a/sdk/@reflag/browser-sdk/README.md b/sdk/@reflag/browser-sdk/README.md index 43be7c9..925f4f4 100644 --- a/sdk/@reflag/browser-sdk/README.md +++ b/sdk/@reflag/browser-sdk/README.md @@ -65,15 +65,20 @@ If the flag doesn't exist, or its value has a different type, you get `false`, o The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. -`getFlags()` returns all flag values as a record. Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. +`getFlags()` returns all flag values as a record. + +Each read records a check, which Reflag uses for launch monitoring. ## Track usage and feedback ```ts await reflag.track("Started huddle", { button: "cta" }); reflag.requestFeedback({ flagKey: "huddles", title: "How did it go?" }); +await reflag.feedback({ flagKey: "huddles", score: 5 }); ``` +`requestFeedback()` opens the feedback form. `feedback()` sends feedback you collected yourself. + Configure your flag's adoption rules to match the event names you send. See [FEEDBACK.md](../../../supported-languages/browser-sdk/feedback.md) to configure feedback prompts and the feedback UI. ## Update context @@ -109,7 +114,7 @@ await reflag.initialize(); Pass the whole object returned by `getFlagsForBootstrap()`, serialized with your framework's usual mechanism. Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. -Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, disable live updates. +Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, leave `enableLiveFlagUpdates` off (the default). ## Let users opt in to flags @@ -164,7 +169,9 @@ const reflag = new ReflagClient({ | `eventSourceFactory` | Custom EventSource implementation for runtimes without one | | `trackingQueue` | Event batching: `flushDelayMs` and `maxSize` | -Call `await reflag.stop()` to send buffered events and close the client. +## Shut down + +Call `await reflag.stop()` to send buffered events and close the client, for example when the user signs out. ## Content Security Policy (CSP) diff --git a/sdk/@reflag/node-sdk/README.md b/sdk/@reflag/node-sdk/README.md index bdc47c0..3bcdd1b 100644 --- a/sdk/@reflag/node-sdk/README.md +++ b/sdk/@reflag/node-sdk/README.md @@ -74,7 +74,7 @@ The SDK checks only the top-level type of a value. If your application depends o `getFlags(context)` returns all flag values as a record; a value can be `undefined` if the flag is unavailable. -Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. +Each read records a check, which Reflag uses for launch monitoring. ## Bind a client to a request @@ -95,7 +95,7 @@ Binding also sends the user's and company's attributes to Reflag, so you can tar await bound.track("Document created", { attributes: { source: "editor" } }); ``` -Configure your flag's adoption rules to match the event names you send. Events are sent in batches. Call `await reflag.flush()` to send any queued events, for example before your process exits. +Configure your flag's adoption rules to match the event names you send. Events are sent in batches; see [Shutting down](#shutting-down) to send them before your process exits. ## Keep flags up to date @@ -168,7 +168,7 @@ declare module "@reflag/node-sdk" { } ``` -The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you. Declarations are checked at compile time only. +The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you with `--format node`. Declarations are checked at compile time only. ## Bootstrap the browser @@ -194,19 +194,50 @@ const values = await reflag.getFlagsRemote("user-1", "acme", { }); ``` -On the root client, the default comes second: `getFlagRemote(key, defaultValue, userId?, companyId?, context?)`. Pass `undefined` as the default for a Boolean read. +Unlike `getFlag()`, `getFlagRemote()` on the root client takes the default before the user and company IDs. To read a Boolean, pass `undefined` as the default. ## Edge runtimes -Use `EdgeClient` in edge runtimes such as Cloudflare Workers, with Node.js compatibility enabled. It refreshes flags as they're read. Call `ctx.waitUntil(client.flush())` before returning from a Worker so queued events are sent. +Use `EdgeClient` in edge runtimes such as Cloudflare Workers, with Node.js compatibility enabled. It refreshes flags as they're read, instead of in the background: + +```ts +import { EdgeClient } from "@reflag/node-sdk"; + +let reflag: EdgeClient | undefined; + +export default { + async fetch(request, env, ctx) { + reflag ??= new EdgeClient({ secretKey: env.REFLAG_SECRET_KEY }); + await reflag.initialize(); + const enabled = reflag.getFlag({ user: { id: "user-1" } }, "new-editor"); + ctx.waitUntil(reflag.flush()); + return new Response(enabled ? "New editor" : "Old editor"); + }, +}; +``` + +Call `ctx.waitUntil(reflag.flush())` before returning so queued events are sent. ## Configuration Options can be set in the constructor, through environment variables, or in `reflag.config.json`, in that order of precedence. -Environment variables include `REFLAG_SECRET_KEY`, `REFLAG_API_BASE_URL`, `REFLAG_LOG_LEVEL`, `REFLAG_OFFLINE`, `REFLAG_CONFIG_FILE`, and `REFLAG_FLAGS_ENABLED` / `REFLAG_FLAGS_DISABLED` to override Boolean flags. - -Constructor options include `logger`, `httpClient`, `flagsSyncMode`, `fetchTimeoutMs`, `flagsFetchRetries`, `flagsFallbackProvider`, `flagOverrides`, `enableTracking`, `offline` and `batchOptions` (`maxSize`, `intervalMs`, `flushOnExit`). +| Option | Environment variable | Description | +| ----------------------- | ----------------------------------------------- | -------------------------------------------------------------------- | +| `secretKey` | `REFLAG_SECRET_KEY` | Your environment's secret key | +| `apiBaseUrl` | `REFLAG_API_BASE_URL` | Override the API URL | +| `logLevel`, `logger` | `REFLAG_LOG_LEVEL` | Log level (default `INFO`) or a custom logger | +| `offline` | `REFLAG_OFFLINE` | Make no network requests, for example in tests | +| `configFile` | `REFLAG_CONFIG_FILE` | Path to a config file other than `reflag.config.json` | +| `flagOverrides` | `REFLAG_FLAGS_ENABLED`, `REFLAG_FLAGS_DISABLED` | Override flags; the variables take comma-separated Boolean flag keys | +| `flagsSyncMode` | | How flag definitions are kept up to date; default `push` | +| `flagsFallbackProvider` | | Where to save flag definitions for startup | +| `fetchTimeoutMs` | | Request timeout; default 10,000 ms | +| `flagsFetchRetries` | | Retries for fetching flag definitions; default 3 | +| `batchOptions` | | Event batching: `maxSize`, `intervalMs` and `flushOnExit` | +| `httpClient` | | Custom HTTP client | + +To stop sending checks and events for a context, include `enableTracking: false` in it. ## Shutting down diff --git a/sdk/@reflag/react-sdk/README.md b/sdk/@reflag/react-sdk/README.md index 6d346aa..f3a1de7 100644 --- a/sdk/@reflag/react-sdk/README.md +++ b/sdk/@reflag/react-sdk/README.md @@ -75,7 +75,7 @@ While flags are loading, if the flag doesn't exist, or if its value has a differ The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. -Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. +Each read records a check, which Reflag uses for launch monitoring. ## Loading states and Suspense @@ -158,7 +158,7 @@ await setOptIn("huddles", { optedIn: false, scope: "company" }); Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent. Check `isLoading` before rendering an empty state. The provider's `suspense` prop, or `useOptInFlags({ suspense: true })`, makes this hook suspend instead. See [Beta feature opt-in](https://docs.reflag.com/guides/self-opt-in) for a complete example. -## Toolbar +## Overrides and toolbar The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` prop to show it elsewhere, for example to internal users in production: @@ -172,6 +172,8 @@ The toolbar shows on `localhost` by default and lets you toggle Boolean flags fo ``` +To override a flag from code, call `useClient().setFlagOverride(key, value)`. Pass `undefined` to remove the override. + ## Type safety Optionally declare your flags to get autocompletion for keys and type checks for defaults: @@ -187,11 +189,15 @@ declare module "@reflag/react-sdk" { } ``` -The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you. Declarations are checked at compile time only. +The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you with `--format react`. Declarations are checked at compile time only. ## Use an existing client -`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to ``; your application is then responsible for initializing and stopping it. `useOnEvent(type, handler)` subscribes to client events and unsubscribes when the component unmounts. +`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to ``; your application is then responsible for initializing and stopping it. + +## Events + +`useOnEvent(type, handler)` subscribes to [client events](../../../supported-languages/browser-sdk/README.md) and unsubscribes when the component unmounts. ## Configuration diff --git a/sdk/@reflag/vue-sdk/README.md b/sdk/@reflag/vue-sdk/README.md index 2055328..c32fb8a 100644 --- a/sdk/@reflag/vue-sdk/README.md +++ b/sdk/@reflag/vue-sdk/README.md @@ -48,8 +48,6 @@ import { ReflagProvider } from "@reflag/vue-sdk"; ``` -In Nuxt, wrap the provider in ``. - Then read a flag in any component: ```vue @@ -65,6 +63,8 @@ const track = useTrack(); ``` +In Nuxt, wrap the provider in ``. + ## Read flags `useFlag()` returns a ref that updates when the flag changes. Vue unwraps refs in templates; use `.value` in script. @@ -86,7 +86,7 @@ While flags are loading, if the flag doesn't exist, or if its value has a differ The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. -Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. +Each read records a check, which Reflag uses for launch monitoring. ## Loading states @@ -141,7 +141,7 @@ await setOptIn("huddles", { optedIn: false, scope: "company" }); Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent. Check `isLoading` before rendering an empty state. -## Toolbar +## Overrides and toolbar The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` prop to show it elsewhere, for example to internal users in production: @@ -176,7 +176,11 @@ The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declaration ## Use an existing client -`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to `ReflagClientProvider`; your application is then responsible for initializing and stopping it. `useOnEvent(type, handler)` subscribes to client events and unsubscribes when the component unmounts. +`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to `ReflagClientProvider`; your application is then responsible for initializing and stopping it. + +## Events + +`useOnEvent(type, handler)` subscribes to [client events](../../../supported-languages/browser-sdk/README.md) and unsubscribes when the component unmounts. ## Configuration diff --git a/sdk/documents/browser-sdk/FEEDBACK.md b/sdk/documents/browser-sdk/FEEDBACK.md index 000d8ae..87b8d06 100644 --- a/sdk/documents/browser-sdk/FEEDBACK.md +++ b/sdk/documents/browser-sdk/FEEDBACK.md @@ -284,7 +284,7 @@ See examples below. ![image](https://github.com/reflagcom/javascript/assets/331790/68805b38-e9f6-4de5-9f55-188216983e3c) -See [default English localization keys](https://github.com/reflagcom/javascript/tree/e7d2a4039d435f4f1c758b6e72d4ff5222bcc340/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) +See [default English localization keys](https://github.com/reflagcom/javascript/tree/d782fd0339de86a82a0b4293d18bf156fcdb63c4/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) for a reference of what translation keys can be supplied. ### Static language configuration @@ -398,7 +398,7 @@ For example, a dark mode theme might look like this: } ``` -Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/e7d2a4039d435f4f1c758b6e72d4ff5222bcc340/packages/browser-sdk/src/feedback/ui/index.css). +Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/d782fd0339de86a82a0b4293d18bf156fcdb63c4/packages/browser-sdk/src/feedback/ui/index.css). ## Using your own UI to collect feedback @@ -423,7 +423,7 @@ Reflag API. ### Manual feedback collection with custom UI Examples of a HTML-form that collects the relevant data can be found -in [feedback.html](https://github.com/reflagcom/javascript/tree/e7d2a4039d435f4f1c758b6e72d4ff5222bcc340/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/e7d2a4039d435f4f1c758b6e72d4ff5222bcc340/packages/browser-sdk/example/feedback/Feedback.jsx). +in [feedback.html](https://github.com/reflagcom/javascript/tree/d782fd0339de86a82a0b4293d18bf156fcdb63c4/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/d782fd0339de86a82a0b4293d18bf156fcdb63c4/packages/browser-sdk/example/feedback/Feedback.jsx). Once you have collected the feedback data, pass it along to `reflagClient.feedback()`: diff --git a/sdk/documents/react-sdk/README.md b/sdk/documents/react-sdk/README.md index 6d346aa..f3a1de7 100644 --- a/sdk/documents/react-sdk/README.md +++ b/sdk/documents/react-sdk/README.md @@ -75,7 +75,7 @@ While flags are loading, if the flag doesn't exist, or if its value has a differ The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. -Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. +Each read records a check, which Reflag uses for launch monitoring. ## Loading states and Suspense @@ -158,7 +158,7 @@ await setOptIn("huddles", { optedIn: false, scope: "company" }); Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent. Check `isLoading` before rendering an empty state. The provider's `suspense` prop, or `useOptInFlags({ suspense: true })`, makes this hook suspend instead. See [Beta feature opt-in](https://docs.reflag.com/guides/self-opt-in) for a complete example. -## Toolbar +## Overrides and toolbar The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` prop to show it elsewhere, for example to internal users in production: @@ -172,6 +172,8 @@ The toolbar shows on `localhost` by default and lets you toggle Boolean flags fo ``` +To override a flag from code, call `useClient().setFlagOverride(key, value)`. Pass `undefined` to remove the override. + ## Type safety Optionally declare your flags to get autocompletion for keys and type checks for defaults: @@ -187,11 +189,15 @@ declare module "@reflag/react-sdk" { } ``` -The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you. Declarations are checked at compile time only. +The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you with `--format react`. Declarations are checked at compile time only. ## Use an existing client -`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to ``; your application is then responsible for initializing and stopping it. `useOnEvent(type, handler)` subscribes to client events and unsubscribes when the component unmounts. +`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to ``; your application is then responsible for initializing and stopping it. + +## Events + +`useOnEvent(type, handler)` subscribes to [client events](../../../supported-languages/browser-sdk/README.md) and unsubscribes when the component unmounts. ## Configuration diff --git a/supported-languages/browser-sdk/README.md b/supported-languages/browser-sdk/README.md index 5c9a2b1..b7acf83 100644 --- a/supported-languages/browser-sdk/README.md +++ b/supported-languages/browser-sdk/README.md @@ -65,15 +65,20 @@ If the flag doesn't exist, or its value has a different type, you get `false`, o The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. -`getFlags()` returns all flag values as a record. Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. +`getFlags()` returns all flag values as a record. + +Each read records a check, which Reflag uses for launch monitoring. ## Track usage and feedback ```ts await reflag.track("Started huddle", { button: "cta" }); reflag.requestFeedback({ flagKey: "huddles", title: "How did it go?" }); +await reflag.feedback({ flagKey: "huddles", score: 5 }); ``` +`requestFeedback()` opens the feedback form. `feedback()` sends feedback you collected yourself. + Configure your flag's adoption rules to match the event names you send. See [FEEDBACK.md](feedback.md) to configure feedback prompts and the feedback UI. ## Update context @@ -109,7 +114,7 @@ await reflag.initialize(); Pass the whole object returned by `getFlagsForBootstrap()`, serialized with your framework's usual mechanism. Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. -Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, disable live updates. +Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, leave `enableLiveFlagUpdates` off (the default). ## Let users opt in to flags @@ -164,7 +169,9 @@ const reflag = new ReflagClient({ | `eventSourceFactory` | Custom EventSource implementation for runtimes without one | | `trackingQueue` | Event batching: `flushDelayMs` and `maxSize` | -Call `await reflag.stop()` to send buffered events and close the client. +## Shut down + +Call `await reflag.stop()` to send buffered events and close the client, for example when the user signs out. ## Content Security Policy (CSP) diff --git a/supported-languages/browser-sdk/feedback.md b/supported-languages/browser-sdk/feedback.md index 0ecb8e2..1481d96 100644 --- a/supported-languages/browser-sdk/feedback.md +++ b/supported-languages/browser-sdk/feedback.md @@ -284,7 +284,7 @@ See examples below. ![image](https://github.com/reflagcom/javascript/assets/331790/68805b38-e9f6-4de5-9f55-188216983e3c) -See [default English localization keys](https://github.com/reflagcom/javascript/tree/e7d2a4039d435f4f1c758b6e72d4ff5222bcc340/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) +See [default English localization keys](https://github.com/reflagcom/javascript/tree/d782fd0339de86a82a0b4293d18bf156fcdb63c4/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) for a reference of what translation keys can be supplied. ### Static language configuration @@ -398,7 +398,7 @@ For example, a dark mode theme might look like this: } ``` -Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/e7d2a4039d435f4f1c758b6e72d4ff5222bcc340/packages/browser-sdk/src/feedback/ui/index.css). +Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/d782fd0339de86a82a0b4293d18bf156fcdb63c4/packages/browser-sdk/src/feedback/ui/index.css). ## Using your own UI to collect feedback @@ -423,7 +423,7 @@ Reflag API. ### Manual feedback collection with custom UI Examples of a HTML-form that collects the relevant data can be found -in [feedback.html](https://github.com/reflagcom/javascript/tree/e7d2a4039d435f4f1c758b6e72d4ff5222bcc340/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/e7d2a4039d435f4f1c758b6e72d4ff5222bcc340/packages/browser-sdk/example/feedback/Feedback.jsx). +in [feedback.html](https://github.com/reflagcom/javascript/tree/d782fd0339de86a82a0b4293d18bf156fcdb63c4/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/d782fd0339de86a82a0b4293d18bf156fcdb63c4/packages/browser-sdk/example/feedback/Feedback.jsx). Once you have collected the feedback data, pass it along to `reflagClient.feedback()`: diff --git a/supported-languages/node-sdk/README.md b/supported-languages/node-sdk/README.md index f7747f5..756130f 100644 --- a/supported-languages/node-sdk/README.md +++ b/supported-languages/node-sdk/README.md @@ -74,7 +74,7 @@ The SDK checks only the top-level type of a value. If your application depends o `getFlags(context)` returns all flag values as a record; a value can be `undefined` if the flag is unavailable. -Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. +Each read records a check, which Reflag uses for launch monitoring. ## Bind a client to a request @@ -95,7 +95,7 @@ Binding also sends the user's and company's attributes to Reflag, so you can tar await bound.track("Document created", { attributes: { source: "editor" } }); ``` -Configure your flag's adoption rules to match the event names you send. Events are sent in batches. Call `await reflag.flush()` to send any queued events, for example before your process exits. +Configure your flag's adoption rules to match the event names you send. Events are sent in batches; see [Shutting down](#shutting-down) to send them before your process exits. ## Keep flags up to date @@ -168,7 +168,7 @@ declare module "@reflag/node-sdk" { } ``` -The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you. Declarations are checked at compile time only. +The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you with `--format node`. Declarations are checked at compile time only. ## Bootstrap the browser @@ -194,19 +194,50 @@ const values = await reflag.getFlagsRemote("user-1", "acme", { }); ``` -On the root client, the default comes second: `getFlagRemote(key, defaultValue, userId?, companyId?, context?)`. Pass `undefined` as the default for a Boolean read. +Unlike `getFlag()`, `getFlagRemote()` on the root client takes the default before the user and company IDs. To read a Boolean, pass `undefined` as the default. ## Edge runtimes -Use `EdgeClient` in edge runtimes such as Cloudflare Workers, with Node.js compatibility enabled. It refreshes flags as they're read. Call `ctx.waitUntil(client.flush())` before returning from a Worker so queued events are sent. +Use `EdgeClient` in edge runtimes such as Cloudflare Workers, with Node.js compatibility enabled. It refreshes flags as they're read, instead of in the background: + +```ts +import { EdgeClient } from "@reflag/node-sdk"; + +let reflag: EdgeClient | undefined; + +export default { + async fetch(request, env, ctx) { + reflag ??= new EdgeClient({ secretKey: env.REFLAG_SECRET_KEY }); + await reflag.initialize(); + const enabled = reflag.getFlag({ user: { id: "user-1" } }, "new-editor"); + ctx.waitUntil(reflag.flush()); + return new Response(enabled ? "New editor" : "Old editor"); + }, +}; +``` + +Call `ctx.waitUntil(reflag.flush())` before returning so queued events are sent. ## Configuration Options can be set in the constructor, through environment variables, or in `reflag.config.json`, in that order of precedence. -Environment variables include `REFLAG_SECRET_KEY`, `REFLAG_API_BASE_URL`, `REFLAG_LOG_LEVEL`, `REFLAG_OFFLINE`, `REFLAG_CONFIG_FILE`, and `REFLAG_FLAGS_ENABLED` / `REFLAG_FLAGS_DISABLED` to override Boolean flags. - -Constructor options include `logger`, `httpClient`, `flagsSyncMode`, `fetchTimeoutMs`, `flagsFetchRetries`, `flagsFallbackProvider`, `flagOverrides`, `enableTracking`, `offline` and `batchOptions` (`maxSize`, `intervalMs`, `flushOnExit`). +| Option | Environment variable | Description | +| ----------------------- | ----------------------------------------------- | -------------------------------------------------------------------- | +| `secretKey` | `REFLAG_SECRET_KEY` | Your environment's secret key | +| `apiBaseUrl` | `REFLAG_API_BASE_URL` | Override the API URL | +| `logLevel`, `logger` | `REFLAG_LOG_LEVEL` | Log level (default `INFO`) or a custom logger | +| `offline` | `REFLAG_OFFLINE` | Make no network requests, for example in tests | +| `configFile` | `REFLAG_CONFIG_FILE` | Path to a config file other than `reflag.config.json` | +| `flagOverrides` | `REFLAG_FLAGS_ENABLED`, `REFLAG_FLAGS_DISABLED` | Override flags; the variables take comma-separated Boolean flag keys | +| `flagsSyncMode` | | How flag definitions are kept up to date; default `push` | +| `flagsFallbackProvider` | | Where to save flag definitions for startup | +| `fetchTimeoutMs` | | Request timeout; default 10,000 ms | +| `flagsFetchRetries` | | Retries for fetching flag definitions; default 3 | +| `batchOptions` | | Event batching: `maxSize`, `intervalMs` and `flushOnExit` | +| `httpClient` | | Custom HTTP client | + +To stop sending checks and events for a context, include `enableTracking: false` in it. ## Shutting down diff --git a/supported-languages/react-sdk/README.md b/supported-languages/react-sdk/README.md index 37aacd5..7659ce5 100644 --- a/supported-languages/react-sdk/README.md +++ b/supported-languages/react-sdk/README.md @@ -75,7 +75,7 @@ While flags are loading, if the flag doesn't exist, or if its value has a differ The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. -Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. +Each read records a check, which Reflag uses for launch monitoring. ## Loading states and Suspense @@ -158,7 +158,7 @@ await setOptIn("huddles", { optedIn: false, scope: "company" }); Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent. Check `isLoading` before rendering an empty state. The provider's `suspense` prop, or `useOptInFlags({ suspense: true })`, makes this hook suspend instead. See [Beta feature opt-in](https://docs.reflag.com/guides/self-opt-in) for a complete example. -## Toolbar +## Overrides and toolbar The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` prop to show it elsewhere, for example to internal users in production: @@ -172,6 +172,8 @@ The toolbar shows on `localhost` by default and lets you toggle Boolean flags fo ``` +To override a flag from code, call `useClient().setFlagOverride(key, value)`. Pass `undefined` to remove the override. + ## Type safety Optionally declare your flags to get autocompletion for keys and type checks for defaults: @@ -187,11 +189,15 @@ declare module "@reflag/react-sdk" { } ``` -The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you. Declarations are checked at compile time only. +The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you with `--format react`. Declarations are checked at compile time only. ## Use an existing client -`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to ``; your application is then responsible for initializing and stopping it. `useOnEvent(type, handler)` subscribes to client events and unsubscribes when the component unmounts. +`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to ``; your application is then responsible for initializing and stopping it. + +## Events + +`useOnEvent(type, handler)` subscribes to [client events](../browser-sdk/README.md) and unsubscribes when the component unmounts. ## Configuration diff --git a/supported-languages/vue-sdk/README.md b/supported-languages/vue-sdk/README.md index 47abe03..7c6c0b0 100644 --- a/supported-languages/vue-sdk/README.md +++ b/supported-languages/vue-sdk/README.md @@ -48,8 +48,6 @@ import { ReflagProvider } from "@reflag/vue-sdk"; ``` -In Nuxt, wrap the provider in ``. - Then read a flag in any component: ```vue @@ -65,6 +63,8 @@ const track = useTrack(); ``` +In Nuxt, wrap the provider in ``. + ## Read flags `useFlag()` returns a ref that updates when the flag changes. Vue unwraps refs in templates; use `.value` in script. @@ -86,7 +86,7 @@ While flags are loading, if the flag doesn't exist, or if its value has a differ The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. -Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. +Each read records a check, which Reflag uses for launch monitoring. ## Loading states @@ -141,7 +141,7 @@ await setOptIn("huddles", { optedIn: false, scope: "company" }); Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent. Check `isLoading` before rendering an empty state. -## Toolbar +## Overrides and toolbar The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` prop to show it elsewhere, for example to internal users in production: @@ -176,7 +176,11 @@ The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declaration ## Use an existing client -`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to `ReflagClientProvider`; your application is then responsible for initializing and stopping it. `useOnEvent(type, handler)` subscribes to client events and unsubscribes when the component unmounts. +`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to `ReflagClientProvider`; your application is then responsible for initializing and stopping it. + +## Events + +`useOnEvent(type, handler)` subscribes to [client events](../browser-sdk/README.md) and unsubscribes when the component unmounts. ## Configuration From 688a485a962fce48acf3ac4e8e011e273dc151d4 Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:06:22 +0000 Subject: [PATCH 16/18] docs: lead remote config migration with agent guidance --- .github/scripts/sdk-docs.test.mjs | 5 ++++- product-handbook/multivariate-flags.md | 16 +++++++++------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/.github/scripts/sdk-docs.test.mjs b/.github/scripts/sdk-docs.test.mjs index 76820a3..2eb814e 100644 --- a/.github/scripts/sdk-docs.test.mjs +++ b/.github/scripts/sdk-docs.test.mjs @@ -90,7 +90,10 @@ test("handbook keeps Remote config as a short pointer to the full Multivariate f assert.match(multivariate, /^# Multivariate flags$/m); assert(multivariate.includes("export function AssistantSettings()")); assert(multivariate.includes("export function AssistantModel()")); - assert.match(multivariate, /^## Migrating from Remote config$/m); + assert.match( + multivariate, + /^## Migrating from Remote config$[\s\S]*^### Using an AI agent$[\s\S]*^### Manual migration\n\n1\./m, + ); assert(multivariate.includes("[Reflag MCP](../api/mcp.md)")); checkLinks(root, ["product-handbook/remote-config.md", "product-handbook/multivariate-flags.md"]); }); diff --git a/product-handbook/multivariate-flags.md b/product-handbook/multivariate-flags.md index a6b4fa2..bb288a6 100644 --- a/product-handbook/multivariate-flags.md +++ b/product-handbook/multivariate-flags.md @@ -99,13 +99,6 @@ If access and configuration are separate decisions, use a Boolean flag such as ` Legacy Remote config and Multivariate flags are separate features. Existing remote configs aren't converted automatically. -1. **Review the existing config.** Record its keys and JSON payloads, along with the assignments, rules, and default in each environment. Check whether your application reads `config.payload`, `config.key`, or both. -2. **Create a Multivariate flag with a new key**, such as `assistant-settings`. Keep the original Release flag and its access rules in place while you migrate. -3. **Copy the values your application uses.** If it reads `config.payload`, use that JSON as the variant value. If it reads `config.key`, use the old key as a string value. If it needs both, include both in an object and update your code to read that object. -4. **Recreate targeting in each environment.** Copy user/company assignments, rules, and the default. Preserve the original evaluation order when rules overlap. Unlike legacy Remote config, Multivariate variants and values are configured separately in each environment. -5. **Update and test your application.** [Upgrade to SDK v2](../supported-languages/migrating-from-v1.md) and read the new flag's value directly, rather than through `.config`. Keep any existing Boolean access checks. Compare the old and new results for representative users and companies in each environment. -6. **Retire the old config once clients no longer use it.** Leave it available for any clients still on SDK v1. Don't delete a Release flag that's still used for access checks. - ### Using an AI agent An agent connected to [Reflag MCP](../api/mcp.md) can read your existing Remote configs and help migrate them to Multivariate flags. @@ -113,3 +106,12 @@ An agent connected to [Reflag MCP](../api/mcp.md) can read your existing Remote Start by asking for a migration plan, rather than an immediate bulk migration: > Review this app's legacy Remote configs through Reflag MCP and plan a migration to Multivariate flags. Preserve values, defaults, and targeting in each environment, and keep existing Boolean access checks. Identify any clients still using SDK v1. Show the proposed flag keys and code changes. Ask for my approval before creating flags or changing configuration. Don't remove the old configs. + +### Manual migration + +1. **Review the existing config.** Record its keys and JSON payloads, along with the assignments, rules, and default in each environment. Check whether your application reads `config.payload`, `config.key`, or both. +2. **Create a Multivariate flag with a new key**, such as `assistant-settings`. Keep the original Release flag and its access rules in place while you migrate. +3. **Copy the values your application uses.** If it reads `config.payload`, use that JSON as the variant value. If it reads `config.key`, use the old key as a string value. If it needs both, include both in an object and update your code to read that object. +4. **Recreate targeting in each environment.** Copy user/company assignments, rules, and the default. Preserve the original evaluation order when rules overlap. Unlike legacy Remote config, Multivariate variants and values are configured separately in each environment. +5. **Update and test your application.** [Upgrade to SDK v2](../supported-languages/migrating-from-v1.md) and read the new flag's value directly, rather than through `.config`. Keep any existing Boolean access checks. Compare the old and new results for representative users and companies in each environment. +6. **Retire the old config once clients no longer use it.** Leave it available for any clients still on SDK v1. Don't delete a Release flag that's still used for access checks. From e52208b66f68166157089d283b4c2b642fc59e22 Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:18:46 +0000 Subject: [PATCH 17/18] docs: restore numbered get-started steps in SDK guides Co-Authored-By: Claude Opus 5.5 --- .generated/sdk-docs/browser-sdk/v2.json | 10 +++---- .generated/sdk-docs/node-sdk/v2.json | 6 ++-- .generated/sdk-docs/react-sdk/v2.json | 8 +++--- .generated/sdk-docs/vue-sdk/v2.json | 6 ++-- product-handbook/type-safety.md | 1 - sdk/@reflag/browser-sdk/README.md | 16 +++++++++-- sdk/@reflag/node-sdk/README.md | 25 ++++++++++++++--- sdk/@reflag/react-sdk/README.md | 21 ++++++++++++-- sdk/@reflag/vue-sdk/README.md | 31 ++++++++------------- sdk/documents/browser-sdk/FEEDBACK.md | 6 ++-- sdk/documents/react-sdk/README.md | 21 ++++++++++++-- supported-languages/browser-sdk/README.md | 16 +++++++++-- supported-languages/browser-sdk/feedback.md | 6 ++-- supported-languages/node-sdk/README.md | 25 ++++++++++++++--- supported-languages/react-sdk/README.md | 21 ++++++++++++-- supported-languages/vue-sdk/README.md | 31 ++++++++------------- 16 files changed, 165 insertions(+), 85 deletions(-) diff --git a/.generated/sdk-docs/browser-sdk/v2.json b/.generated/sdk-docs/browser-sdk/v2.json index 57c06a9..bd51971 100644 --- a/.generated/sdk-docs/browser-sdk/v2.json +++ b/.generated/sdk-docs/browser-sdk/v2.json @@ -1,14 +1,14 @@ { "sourceRepository": "https://github.com/reflagcom/javascript", - "sourceCommit": "d782fd0339de86a82a0b4293d18bf156fcdb63c4", + "sourceCommit": "ed0e7725719756855c20e939265713914e956b8b", "package": "@reflag/browser-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/browser-sdk/README.md": "a8f1a90ea81f31f6ddcf07e34c6af39f3addf8f3485535652e16bb90b7e3b2c0", - "sdk/@reflag/browser-sdk/README.md": "7f64f5357cae8be2328ed38599fb2210ebbd5e0e8210cfb8dc748ae9e3e664b4", + "supported-languages/browser-sdk/README.md": "74c3b73ac4a3cfbdef57a1eadff0da041b7f6d39db3697b480e6e8b69afae74b", + "sdk/@reflag/browser-sdk/README.md": "f29ed94303254887c39f995588e85481c851873f78ef6d62e8ce24ecd109f133", "supported-languages/browser-sdk/globals.md": "4a3be858a621eb3839408d759329a60ab2ea406d0e21174b44b0639c678a1ffc", "sdk/@reflag/browser-sdk/globals.md": "a60d58526686dcc14ea5cdcecfa1d17388aff78f198f97f41bd667d35c7c39aa", - "supported-languages/browser-sdk/feedback.md": "18902ebb57a7a278095a4b5662b2d023c3ef33092a0646017e39cf2620606794", - "sdk/documents/browser-sdk/FEEDBACK.md": "6c98fb8305be3328a7fd70a5bf18246d057ebadc4bfe7fbee0e9c70f56b8137f" + "supported-languages/browser-sdk/feedback.md": "2a2a3aa124d872970a7b2303b3318b21d675faf1c414525b2e62b31d3f2eb90d", + "sdk/documents/browser-sdk/FEEDBACK.md": "552bee6f6059a5c27a7be36a60e5fc071bd6e95af66bbd6ba45f98aaf29a8478" } } diff --git a/.generated/sdk-docs/node-sdk/v2.json b/.generated/sdk-docs/node-sdk/v2.json index a890bed..072bf64 100644 --- a/.generated/sdk-docs/node-sdk/v2.json +++ b/.generated/sdk-docs/node-sdk/v2.json @@ -1,11 +1,11 @@ { "sourceRepository": "https://github.com/reflagcom/javascript", - "sourceCommit": "c6d714437b00d1f3303eef3f7ccf86b880c409ff", + "sourceCommit": "81297fbca156feadd3e666188f5141f42e0488dd", "package": "@reflag/node-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/node-sdk/README.md": "067e67bf1455824933fbb6e406d3528097ca54e43b61447944847c4763dbbbd2", - "sdk/@reflag/node-sdk/README.md": "27a9916f23a1e3cba2640e489ad06a14184cc70257143e0c9187225cf12836f2", + "supported-languages/node-sdk/README.md": "e82d3aecfc0bb3ec11b48c7a16337fd1c585b57d37be35e3cbffe24c4dbd0136", + "sdk/@reflag/node-sdk/README.md": "ee5d3ffa7fb8e845737022fc35265c87fefc9c1d6085d87939d06395d086ff88", "supported-languages/node-sdk/globals.md": "e1fc21f052e69b74582782ac7133513b077f328294f674523f087e4846338815", "sdk/@reflag/node-sdk/globals.md": "3fc142c7e452af2515b11c7efafa34d81bfe887f29ad1e2d6c81d31fb6736cc3" } diff --git a/.generated/sdk-docs/react-sdk/v2.json b/.generated/sdk-docs/react-sdk/v2.json index 03bbb1d..03df1fa 100644 --- a/.generated/sdk-docs/react-sdk/v2.json +++ b/.generated/sdk-docs/react-sdk/v2.json @@ -1,12 +1,12 @@ { "sourceRepository": "https://github.com/reflagcom/javascript", - "sourceCommit": "d782fd0339de86a82a0b4293d18bf156fcdb63c4", + "sourceCommit": "ed0e7725719756855c20e939265713914e956b8b", "package": "@reflag/react-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/react-sdk/README.md": "d86f92dac992e767fe54bd6923246cb50e35c7152c5ee3cbe6be014715bb2c6b", - "sdk/@reflag/react-sdk/README.md": "f738b8bc35662c30fe645dc2fec3d8632a4f880c21f77bfc1d95aebc4030eb9f", - "sdk/documents/react-sdk/README.md": "f738b8bc35662c30fe645dc2fec3d8632a4f880c21f77bfc1d95aebc4030eb9f", + "supported-languages/react-sdk/README.md": "745947496f5c82508124461e0d0e9e29d3182cdfd7155f79a59fa9387e1b060e", + "sdk/@reflag/react-sdk/README.md": "ef70d89d71d5f52d0adea0163fda82658fc8ec5fb0096fcd2c8424e009307478", + "sdk/documents/react-sdk/README.md": "ef70d89d71d5f52d0adea0163fda82658fc8ec5fb0096fcd2c8424e009307478", "supported-languages/react-sdk/globals.md": "f414859dd7cc94089d06f27613e1c554e3e3d5f049a9a141c2590058af768b1a", "sdk/@reflag/react-sdk/globals.md": "4cf0d20cca9c19d3998d9c5d0f6670d17d6782c24ee0ccd25e1d34100f42fcc6" } diff --git a/.generated/sdk-docs/vue-sdk/v2.json b/.generated/sdk-docs/vue-sdk/v2.json index a714253..2f33800 100644 --- a/.generated/sdk-docs/vue-sdk/v2.json +++ b/.generated/sdk-docs/vue-sdk/v2.json @@ -1,11 +1,11 @@ { "sourceRepository": "https://github.com/reflagcom/javascript", - "sourceCommit": "d782fd0339de86a82a0b4293d18bf156fcdb63c4", + "sourceCommit": "ed0e7725719756855c20e939265713914e956b8b", "package": "@reflag/vue-sdk", "version": "2.0.0-next.0", "files": { - "supported-languages/vue-sdk/README.md": "cfc611d1d63d205c0daab869d466e14cd8fef77547305b1bb96fb827ed2b56f6", - "sdk/@reflag/vue-sdk/README.md": "fe9f5e9f331327075d6988d941da20b120279474e31df149b1d3467c400dab3c", + "supported-languages/vue-sdk/README.md": "b50eddc96c442532d6734450e068153da3778c47d98d028dcf1ff36f1e67c530", + "sdk/@reflag/vue-sdk/README.md": "8b256ff3e64959521508bc74a4b3d0d36873f65c797ee8bc00764875b819768f", "supported-languages/vue-sdk/globals.md": "968ec7df896ee2e78d1d23578acfadfc3378bd511b15c55eca79b6558588727f", "sdk/@reflag/vue-sdk/globals.md": "73ceaa29875b0d33a02dcfbf12cf1e50644b51d871cc496681bdbcbeee56ab2d" } diff --git a/product-handbook/type-safety.md b/product-handbook/type-safety.md index af165e2..bbfcf70 100644 --- a/product-handbook/type-safety.md +++ b/product-handbook/type-safety.md @@ -32,7 +32,6 @@ npx reflag flags types ```sh npx reflag flags types --format react --out gen/flags.d.ts npx reflag flags types --format node --out gen/flags.d.ts -npx reflag flags types --format vue --out gen/flags.d.ts ``` Make sure TypeScript includes the output file. diff --git a/sdk/@reflag/browser-sdk/README.md b/sdk/@reflag/browser-sdk/README.md index 925f4f4..bb7dbdd 100644 --- a/sdk/@reflag/browser-sdk/README.md +++ b/sdk/@reflag/browser-sdk/README.md @@ -21,13 +21,15 @@ This page covers SDK v2. ## Get started +### 1. Create a client + Install the SDK: ```sh npm install @reflag/browser-sdk ``` -Create a client with your **publishable** key and the signed-in user's context, then read a flag: +Create a client with your **publishable** key and the signed-in user's context: ```ts import { ReflagClient } from "@reflag/browser-sdk"; @@ -38,14 +40,22 @@ const reflag = new ReflagClient({ company: { id: "acme", plan: "enterprise" }, }); await reflag.initialize(); +``` + +Publishable keys are safe to ship to the browser. Keep secret keys on your server. + +### 2. Create a flag +Create a flag with the key `huddles` in the Reflag app. + +### 3. Read the flag + +```ts if (reflag.getFlag("huddles")) { await reflag.track("Started huddle"); } ``` -Publishable keys are safe to ship to the browser. Keep secret keys on your server. - ## Read flags Pass a flag key to check whether the flag is enabled: diff --git a/sdk/@reflag/node-sdk/README.md b/sdk/@reflag/node-sdk/README.md index 3bcdd1b..dd98fec 100644 --- a/sdk/@reflag/node-sdk/README.md +++ b/sdk/@reflag/node-sdk/README.md @@ -21,6 +21,8 @@ This page covers SDK v2. ## Get started +### 1. Create a client + Install the SDK: ```sh @@ -38,7 +40,22 @@ export const reflag = new ReflagClient({ await reflag.initialize(); ``` -Then read a flag for a user and company: +Keep the secret key on your server. + +### 2. Create a flag + +Install the Reflag CLI and create a flag: + +```sh +yarn add --dev @reflag/cli +npx reflag new +``` + +The first time you run it, it signs you in to Reflag, saves its settings in `reflag.config.json` and generates types for your flags in `gen/flags.d.ts`. Choose `node` when asked for the output format, and make sure your `tsconfig.json` includes the generated file. You can also create flags in the Reflag app. + +### 3. Read the flag + +Read a flag for a user and company: ```ts const context = { @@ -51,7 +68,7 @@ if (reflag.getFlag(context, "new-editor")) { } ``` -The SDK downloads your flag definitions and evaluates flags locally, so reads don't make network requests. Keep the secret key on your server. +The SDK downloads your flag definitions and evaluates flags locally, so reads don't make network requests. ## Read flags @@ -156,7 +173,7 @@ Overrides pushed with `pushFlagOverrides()` take precedence over base overrides ## Type safety -Optionally declare your flags to get autocompletion for keys, type checks for defaults and typed `getFlags()` results: +Declaring your flags gives you autocompletion for keys, type checks for defaults and typed `getFlags()` results. If you created a flag with `npx reflag new`, the declarations are already generated; run `npx reflag flags types` again when your flags change. A declaration looks like this: ```ts declare module "@reflag/node-sdk" { @@ -168,7 +185,7 @@ declare module "@reflag/node-sdk" { } ``` -The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you with `--format node`. Declarations are checked at compile time only. +Declarations are checked at compile time only. See the [Reflag CLI](https://docs.reflag.com/api/cli) for more options. ## Bootstrap the browser diff --git a/sdk/@reflag/react-sdk/README.md b/sdk/@reflag/react-sdk/README.md index f3a1de7..9678be2 100644 --- a/sdk/@reflag/react-sdk/README.md +++ b/sdk/@reflag/react-sdk/README.md @@ -21,6 +21,8 @@ This page covers SDK v2. ## Get started +### 1. Add the provider + Install the SDK: ```sh @@ -43,7 +45,20 @@ import { ReflagProvider } from "@reflag/react-sdk"; ; ``` -Then read a flag in any component: +### 2. Create a flag + +Install the Reflag CLI and create a flag: + +```sh +npm install --save-dev @reflag/cli +npx reflag new +``` + +The first time you run it, it signs you in to Reflag, saves its settings in `reflag.config.json` and generates types for your flags in `gen/flags.d.ts`. Choose `react` when asked for the output format, and make sure your `tsconfig.json` includes the generated file. You can also create flags in the Reflag app. + +### 3. Read the flag + +Use `useFlag()` in any component: ```tsx import { useFlag, useTrack } from "@reflag/react-sdk"; @@ -176,7 +191,7 @@ To override a flag from code, call `useClient().setFlagOverride(key, value)`. Pa ## Type safety -Optionally declare your flags to get autocompletion for keys and type checks for defaults: +Declaring your flags gives you autocompletion for keys and type checks for defaults. If you created a flag with `npx reflag new`, the declarations are already generated; run `npx reflag flags types` again when your flags change. A declaration looks like this: ```ts import "@reflag/react-sdk"; @@ -189,7 +204,7 @@ declare module "@reflag/react-sdk" { } ``` -The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you with `--format react`. Declarations are checked at compile time only. +Declarations are checked at compile time only. See the [Reflag CLI](https://docs.reflag.com/api/cli) for more options. ## Use an existing client diff --git a/sdk/@reflag/vue-sdk/README.md b/sdk/@reflag/vue-sdk/README.md index c32fb8a..bca1497 100644 --- a/sdk/@reflag/vue-sdk/README.md +++ b/sdk/@reflag/vue-sdk/README.md @@ -21,6 +21,8 @@ This page covers SDK v2. ## Get started +### 1. Add the provider + Install the SDK: ```sh @@ -48,7 +50,15 @@ import { ReflagProvider } from "@reflag/vue-sdk"; ``` -Then read a flag in any component: +In Nuxt, wrap the provider in ``. + +### 2. Create a flag + +Create a flag with the key `huddles` in the Reflag app. + +### 3. Read the flag + +Use `useFlag()` in any component: ```vue