diff --git a/.changeset/vue-integration.md b/.changeset/vue-integration.md
new file mode 100644
index 00000000..dcf32794
--- /dev/null
+++ b/.changeset/vue-integration.md
@@ -0,0 +1,5 @@
+---
+"@tryabby/vue": minor
+---
+
+Add `@tryabby/vue`, a Vue 3 / Nuxt integration with `useAbby`, `useFeatureFlag`, `useRemoteConfig` and an `AbbyPlugin`
diff --git a/apps/docs/pages/integrations/_meta.json b/apps/docs/pages/integrations/_meta.json
index 5cbf2999..8b9353d2 100644
--- a/apps/docs/pages/integrations/_meta.json
+++ b/apps/docs/pages/integrations/_meta.json
@@ -3,6 +3,7 @@
"react": "React",
"remix": "Remix",
"svelte": "Svelte",
+ "vue": "Vue / Nuxt",
"angular": "Angular",
"node": "Node",
"express": "Express",
diff --git a/apps/docs/pages/integrations/vue.mdx b/apps/docs/pages/integrations/vue.mdx
new file mode 100644
index 00000000..135b94a6
--- /dev/null
+++ b/apps/docs/pages/integrations/vue.mdx
@@ -0,0 +1,209 @@
+import { Tab, Tabs, Callout } from "nextra-theme-docs";
+
+# Vue
+
+Our Vue integration works with Vue 3.3 or later. It works with SPAs as well as server side rendered apps (e.g. Nuxt).
+
+## Installation
+
+To get started make sure to install the package using your favorite package manager.
+
+
+
+ ```bash
+ npm i @tryabby/vue
+ ```
+
+
+ ```bash
+ yarn add @tryabby/vue
+ ```
+
+
+ ```bash
+ pnpm i @tryabby/vue
+ ```
+
+
+
+### Create your config
+
+To use Abby you need to create your config first. You can do this by creating a file called `abby.config.ts` in your `root` folder.
+
+```ts
+// abby.config.ts
+import { defineConfig } from "@tryabby/vue";
+
+export default defineConfig({
+ projectId: "",
+ currentEnvironment: process.env.NODE_ENV,
+ environments: ["production", "development"],
+ tests: {
+ footer: { variants: ["dark", "orange", "green"] },
+ },
+ flags: ["darkMode", "newFeature"],
+ remoteConfig: {
+ customButtonText: "String",
+ },
+});
+```
+
+### Create your Instance
+
+`createAbby` returns a typed Vue plugin and typed composables.
+
+```ts
+// abby.ts
+import { createAbby } from "@tryabby/vue";
+import abbyConfig from "../abby.config";
+
+export const {
+ AbbyPlugin,
+ useAbby,
+ useFeatureFlag,
+ useRemoteConfig,
+ getInitialData,
+ withDevtools,
+} = createAbby(abbyConfig);
+```
+
+### Install the plugin
+
+```ts
+// main.ts
+import { createApp } from "vue";
+import App from "./App.vue";
+import { AbbyPlugin } from "./abby";
+
+createApp(App).use(AbbyPlugin).mount("#app");
+```
+
+## Usage
+
+All composables return refs (`ComputedRef`), so they update automatically once the project data is loaded or changes.
+
+### useAbby
+
+`useAbby` returns an object with the following values:
+
+- `variant` - A ref with the variant that is currently active
+- `onAct` - A function that you can call to trigger any kind of interaction with the tested component (will be used to track conversions)
+
+```vue
+
+
+
+
+
+```
+
+Optionally, you can pass a lookup object to automatically map the selected variant to a custom value.
+
+```ts
+const { variant, onAct } = useAbby("footer", {
+ dark: "bg-gray-900",
+ orange: "bg-orange-500",
+ green: "bg-green-500",
+});
+```
+
+
+ The variant is selected after the component is mounted (it's an empty string on the server), the same way the React integration avoids hydration mismatches.
+
+
+### useFeatureFlag
+
+`useFeatureFlag` returns a boolean ref that indicates if the flag is active or not.
+
+```vue
+
+
+
+
Here is the new feature
+
+```
+
+### useRemoteConfig
+
+`useRemoteConfig` returns a ref with the value of the given remote config variable.
+
+```vue
+
+
+
+
+
+```
+
+`useFeatureFlags` and `useRemoteConfigVariables` return all flags / remote config variables, and
+`getFeatureFlagValue`, `getRemoteConfig`, `getABTestValue`, `getVariants` and `getABResetFunction` can be used outside of components.
+
+## Nuxt
+
+Fetch the project data on the server with `getInitialData` and pass it to the plugin, so the page is rendered with the right flags and the client doesn't fetch the data again.
+
+```ts
+// plugins/abby.ts
+import { AbbyPlugin, getInitialData } from "~/abby";
+
+export default defineNuxtPlugin(async (nuxtApp) => {
+ const { data } = await useAsyncData("abby", () => getInitialData());
+ nuxtApp.vueApp.use(AbbyPlugin, { initialData: data.value ?? undefined });
+});
+```
+
+## Devtools
+
+Install the devtools package. `@tryabby/vue` does not install it:
+
+
+
+ ```bash
+ npm i @tryabby/devtools
+ ```
+
+
+ ```bash
+ yarn add @tryabby/devtools
+ ```
+
+
+ ```bash
+ pnpm i @tryabby/devtools
+ ```
+
+
+
+```vue
+
+
+
+
+
+```
diff --git a/packages/core/src/helpers.ts b/packages/core/src/helpers.ts
index c0b7f49a..28b14fca 100644
--- a/packages/core/src/helpers.ts
+++ b/packages/core/src/helpers.ts
@@ -6,7 +6,13 @@ export function parseCookies(cookieHeader: string) {
// biome-ignore lint/suspicious/noImplicitAnyLet:>
for (let m; (m = cookieRegexp.exec(cookieHeader)); ) {
const [, cookieName, cookieValue] = m;
- cookies[decodeURIComponent(cookieName)] = decodeURIComponent(cookieValue);
+ try {
+ cookies[decodeURIComponent(cookieName)] = decodeURIComponent(cookieValue);
+ } catch {
+ // Skip cookies that fail to decode (e.g. a value of "100%") so
+ // the remaining valid cookies can still be applied.
+ continue;
+ }
}
return cookies;
diff --git a/packages/core/tests/helpers.test.ts b/packages/core/tests/helpers.test.ts
new file mode 100644
index 00000000..b498ac7c
--- /dev/null
+++ b/packages/core/tests/helpers.test.ts
@@ -0,0 +1,15 @@
+import { parseCookies } from "../src/helpers";
+
+describe("parseCookies", () => {
+ it("skips cookies that fail to decode and keeps valid ones", () => {
+ const cookies = parseCookies("ok=hello; broken=100%; also=world");
+ expect(cookies.ok).toBe("hello");
+ expect(cookies.also).toBe("world");
+ expect(cookies.broken).toBeUndefined();
+ });
+
+ it("parses ordinary cookies", () => {
+ const cookies = parseCookies("foo=bar; baz=qux");
+ expect(cookies).toEqual({ foo: "bar", baz: "qux" });
+ });
+});
diff --git a/packages/vue/.gitignore b/packages/vue/.gitignore
new file mode 100644
index 00000000..53c37a16
--- /dev/null
+++ b/packages/vue/.gitignore
@@ -0,0 +1 @@
+dist
\ No newline at end of file
diff --git a/packages/vue/README.md b/packages/vue/README.md
new file mode 100644
index 00000000..5571a821
--- /dev/null
+++ b/packages/vue/README.md
@@ -0,0 +1,27 @@
+# @tryabby/vue
+
+Vue 3 (and Nuxt) integration for [Abby](https://www.tryabby.com): A/B tests, feature flags and remote config with full type inference.
+
+```ts
+import { createAbby } from "@tryabby/vue";
+
+export const { AbbyPlugin, useAbby, useFeatureFlag, useRemoteConfig } =
+ createAbby({
+ projectId: "",
+ currentEnvironment: "development",
+ environments: ["development", "production"],
+ tests: { footer: { variants: ["dark", "light"] } },
+ flags: ["newFeature"],
+ remoteConfig: { buttonText: "String" },
+ });
+
+// main.ts
+createApp(App).use(AbbyPlugin).mount("#app");
+
+// in a component
+const { variant, onAct } = useAbby("footer"); // ComputedRef<"dark" | "light">
+const newFeature = useFeatureFlag("newFeature"); // ComputedRef
+const buttonText = useRemoteConfig("buttonText"); // ComputedRef
+```
+
+See the [docs](https://docs.tryabby.com/integrations/vue) for SSR / Nuxt usage.
diff --git a/packages/vue/package.json b/packages/vue/package.json
new file mode 100644
index 00000000..4073419e
--- /dev/null
+++ b/packages/vue/package.json
@@ -0,0 +1,47 @@
+{
+ "name": "@tryabby/vue",
+ "version": "0.0.1",
+ "description": "Vue 3 integration for Abby (A/B tests, feature flags and remote config)",
+ "main": "dist/index.js",
+ "files": ["dist"],
+ "module": "dist/index.mjs",
+ "types": "dist/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.mjs",
+ "require": "./dist/index.js"
+ }
+ },
+ "scripts": {
+ "build": "tsup src/",
+ "dev": "pnpm run build --watch",
+ "test": "vitest",
+ "test:types": "tsc --noEmit"
+ },
+ "homepage": "https://docs.tryabby.com",
+ "keywords": ["abby", "vue", "nuxt", "ab-testing", "feature-flags"],
+ "author": "",
+ "license": "ISC",
+ "devDependencies": {
+ "@tryabby/devtools": "workspace:*",
+ "@types/js-cookie": "^3.0.3",
+ "@vue/test-utils": "^2.4.6",
+ "jsdom": "^20.0.3",
+ "msw": "^0.49.1",
+ "node-fetch": "^3.3.0",
+ "tsconfig": "workspace:*",
+ "tsup": "^6.5.0",
+ "typescript": "5.5.4",
+ "vite": "5.4.0",
+ "vitest": "2.0.5",
+ "vue": "^3.4.0"
+ },
+ "peerDependencies": {
+ "vue": "^3.3.0"
+ },
+ "dependencies": {
+ "@tryabby/core": "workspace:*",
+ "js-cookie": "^3.0.1"
+ }
+}
diff --git a/packages/vue/src/StorageService.ts b/packages/vue/src/StorageService.ts
new file mode 100644
index 00000000..5e9b785b
--- /dev/null
+++ b/packages/vue/src/StorageService.ts
@@ -0,0 +1,74 @@
+import {
+ type IStorageService,
+ type StorageServiceOptions,
+ getABStorageKey,
+ getFFStorageKey,
+ getRCStorageKey,
+} from "@tryabby/core";
+import Cookie from "js-cookie";
+
+const DEFAULT_COOKIE_AGE = 365;
+
+class ABStorageService implements IStorageService {
+ get(projectId: string, testName: string): string | null {
+ const retrievedValue = Cookie.get(getABStorageKey(projectId, testName));
+ if (!retrievedValue) return null;
+
+ return retrievedValue;
+ }
+
+ set(
+ projectId: string,
+ testName: string,
+ value: string,
+ options?: StorageServiceOptions
+ ): void {
+ Cookie.set(getABStorageKey(projectId, testName), value, {
+ expires: options?.expiresInDays ?? DEFAULT_COOKIE_AGE,
+ });
+ }
+
+ remove(projectId: string, testName: string): void {
+ Cookie.remove(getABStorageKey(projectId, testName));
+ }
+}
+
+class FFStorageService implements IStorageService {
+ get(projectId: string, flagName: string): string | null {
+ const retrievedValue = Cookie.get(getFFStorageKey(projectId, flagName));
+ if (!retrievedValue) return null;
+
+ return retrievedValue;
+ }
+
+ set(projectId: string, flagName: string, value: string): void {
+ Cookie.set(getFFStorageKey(projectId, flagName), value, {
+ expires: DEFAULT_COOKIE_AGE,
+ });
+ }
+
+ remove(projectId: string, flagName: string): void {
+ Cookie.remove(getFFStorageKey(projectId, flagName));
+ }
+}
+
+class RCStorageService implements IStorageService {
+ get(projectId: string, key: string): string | null {
+ const retrievedValue = Cookie.get(getRCStorageKey(projectId, key));
+ return retrievedValue ?? null;
+ }
+
+ set(projectId: string, key: string, value: string): void {
+ Cookie.set(getRCStorageKey(projectId, key), value, {
+ expires: DEFAULT_COOKIE_AGE,
+ });
+ }
+
+ remove(projectId: string, key: string): void {
+ Cookie.remove(getRCStorageKey(projectId, key));
+ }
+}
+
+export const TestStorageService = new ABStorageService();
+export const FlagStorageService = new FFStorageService();
+export const RemoteConfigStorageService = new RCStorageService();
diff --git a/packages/vue/src/createAbby.ts b/packages/vue/src/createAbby.ts
new file mode 100644
index 00000000..88320e37
--- /dev/null
+++ b/packages/vue/src/createAbby.ts
@@ -0,0 +1,571 @@
+import {
+ type ABConfig,
+ Abby,
+ type AbbyConfig,
+ type AbbyDataResponse,
+ AbbyEventType,
+ getDefaultRemoteConfigValue,
+ HttpService,
+ type RemoteConfigValueString,
+ type RemoteConfigValueStringToType,
+ type StorageServiceOptions,
+ type ValidatorType,
+} from "@tryabby/core";
+import type { Infer } from "@tryabby/core/validation";
+import type { AbbyDevtoolProps, DevtoolsFactory } from "@tryabby/devtools";
+import {
+ type App,
+ type Component,
+ type ComputedRef,
+ type InjectionKey,
+ type Plugin,
+ type ShallowRef,
+ computed,
+ defineComponent,
+ getCurrentInstance,
+ hasInjectionContext,
+ inject,
+ onBeforeUnmount,
+ onMounted,
+ shallowRef,
+ watch,
+} from "vue";
+import {
+ FlagStorageService,
+ RemoteConfigStorageService,
+ TestStorageService,
+} from "./StorageService";
+
+export type ABTestReturnValue = Lookup extends undefined
+ ? TestVariant
+ : TestVariant extends keyof Lookup
+ ? Lookup[TestVariant]
+ : never;
+
+export type AbbyPluginOptions = {
+ /**
+ * Project data that was already fetched (e.g. on the server with Nuxt).
+ * If it is passed, the plugin will not fetch the data again on the client.
+ */
+ initialData?: AbbyDataResponse | null;
+};
+
+export type withDevtoolsFunction = (
+ factory: DevtoolsFactory,
+ props: Omit & {
+ dangerouslyForceShow?: boolean;
+ }
+) => Component;
+
+type AsyncLocalStorageLike = {
+ getStore(): T | undefined;
+ enterWith(value: T): void;
+};
+
+function getAsyncLocalStorageConstructor():
+ | (new () => AsyncLocalStorageLike)
+ | undefined {
+ // Only available during SSR. Avoid a static `node:async_hooks` import so
+ // the browser bundle does not pull in a Node builtin.
+ if (typeof process === "undefined" || typeof window !== "undefined") {
+ return undefined;
+ }
+ try {
+ const proc = process as typeof process & {
+ getBuiltinModule?: (name: string) => {
+ AsyncLocalStorage: new () => AsyncLocalStorageLike;
+ };
+ };
+ return proc.getBuiltinModule?.("async_hooks")?.AsyncLocalStorage;
+ } catch {
+ return undefined;
+ }
+}
+
+export function createAbby<
+ const FlagName extends string,
+ const TestName extends string,
+ const Tests extends Record,
+ const RemoteConfig extends Record,
+ const RemoteConfigName extends Extract,
+ const User extends Record = Record<
+ string,
+ ValidatorType
+ >,
+>(
+ abbyConfig: AbbyConfig<
+ FlagName,
+ Tests,
+ string[],
+ RemoteConfigName,
+ RemoteConfig,
+ User
+ >
+) {
+ type AbbyInstance = Abby<
+ FlagName,
+ TestName,
+ Tests,
+ RemoteConfig,
+ RemoteConfigName,
+ string[],
+ User
+ >;
+
+ // we need to return the config as a const so that the types are narrowed
+ const config = abbyConfig;
+
+ const testStorage = {
+ get: (key: string) => {
+ if (typeof window === "undefined") return null;
+ return TestStorageService.get(abbyConfig.projectId, key);
+ },
+ set: (key: string, value: any, options?: StorageServiceOptions) => {
+ if (typeof window === "undefined" || config.cookies?.disableByDefault)
+ return;
+ TestStorageService.set(abbyConfig.projectId, key, value, options);
+ },
+ };
+
+ const flagStorage = {
+ get: (key: string) => {
+ if (typeof window === "undefined") return null;
+ return FlagStorageService.get(abbyConfig.projectId, key);
+ },
+ set: (key: string, value: any) => {
+ if (typeof window === "undefined") return;
+ FlagStorageService.set(abbyConfig.projectId, key, value);
+ },
+ };
+
+ const remoteConfigStorage = {
+ get: (key: string) => {
+ if (typeof window === "undefined") return null;
+ return RemoteConfigStorageService.get(abbyConfig.projectId, key);
+ },
+ set: (key: string, value: any) => {
+ if (typeof window === "undefined") return;
+ RemoteConfigStorageService.set(abbyConfig.projectId, key, value);
+ },
+ };
+
+ const createAbbyInstance = (): AbbyInstance =>
+ new Abby<
+ FlagName,
+ TestName,
+ Tests,
+ RemoteConfig,
+ RemoteConfigName,
+ string[],
+ User
+ >(abbyConfig, testStorage, flagStorage, remoteConfigStorage);
+
+ const sharedAbby = createAbbyInstance();
+
+ const AsyncLocalStorageCtor = getAsyncLocalStorageConstructor();
+ const requestAbby = AsyncLocalStorageCtor
+ ? new AsyncLocalStorageCtor()
+ : undefined;
+
+ const currentAbby = (): AbbyInstance =>
+ requestAbby?.getStore() ?? sharedAbby;
+
+ const getProjectDataRequestOptions = () => ({
+ projectId: config.projectId,
+ environment: config.currentEnvironment as string,
+ url: config.apiUrl,
+ fetch: config.fetch,
+ __experimentalCdnUrl: config.__experimentalCdnUrl
+ ? `${config.__experimentalCdnUrl}/${config.projectId}/${config.currentEnvironment}`
+ : undefined,
+ });
+
+ type AbbyProjectData = ReturnType;
+
+ const AbbyInjectionKey: InjectionKey> =
+ Symbol("abby");
+
+ const useAbbyData = (): ShallowRef => {
+ const data = hasInjectionContext() ? inject(AbbyInjectionKey, null) : null;
+
+ if (!data) {
+ throw new Error(
+ "useAbbyData must be used within an app that installed the Abby plugin. Call app.use(AbbyPlugin) to fix this error."
+ );
+ }
+
+ return data;
+ };
+
+ /**
+ * Vue plugin that makes the Abby data available to all composables.
+ *
+ * @example
+ * const app = createApp(App);
+ * app.use(AbbyPlugin); // or app.use(AbbyPlugin, { initialData })
+ */
+ const AbbyPlugin: Plugin<[AbbyPluginOptions?]> = {
+ install(app: App, options?: AbbyPluginOptions) {
+ const isServer = typeof window === "undefined";
+ // Each server request gets an isolated instance so overlapping
+ // installs cannot leak flags, tests, remote config, user
+ // properties, or listeners. The client keeps the shared instance.
+ const instance = isServer ? createAbbyInstance() : sharedAbby;
+ if (isServer) {
+ requestAbby?.enterWith(instance);
+ }
+
+ const data = shallowRef(
+ options?.initialData
+ ? instance.init(options.initialData)
+ : instance.getProjectData()
+ );
+
+ // subscribe to changes in the project data
+ const unsubscribe = instance.subscribe(() => {
+ data.value = instance.getProjectData();
+ });
+
+ // load the project data if it hasn't been passed in
+ if (!options?.initialData && typeof window !== "undefined") {
+ instance.loadProjectData().then((newData) => {
+ if (!newData) return;
+ // Read live state so later user-property updates and cookie
+ // overrides are not overwritten by the snapshot init built.
+ data.value = instance.getProjectData();
+ });
+ }
+
+ app.provide(AbbyInjectionKey, data);
+
+ const originalUnmount = app.unmount.bind(app);
+ app.unmount = () => {
+ unsubscribe();
+ originalUnmount();
+ };
+ },
+ };
+
+ const useAbby = <
+ K extends keyof Tests,
+ TestVariant extends Tests[K]["variants"][number],
+ LookupValue,
+ const Lookup extends
+ | Record
+ | undefined = undefined,
+ >(
+ name: K,
+ lookupObject?: Lookup
+ ): {
+ variant: ComputedRef<
+ Lookup extends undefined
+ ? ABTestReturnValue | ""
+ : ABTestReturnValue | undefined
+ >;
+ onAct: () => void;
+ } => {
+ const data = useAbbyData();
+
+ // always render an empty string before mount to avoid SSR hydration
+ // mismatches because the server doesn't know which variant to render
+ const selectedVariant = shallowRef("");
+
+ const readVariant = () =>
+ data.value.tests[name as unknown as TestName]?.selectedVariant;
+
+ const syncVariant = () => {
+ const newVariant =
+ readVariant() ??
+ currentAbby().getProjectData().tests[name as unknown as TestName]
+ ?.selectedVariant;
+ // should never be undefined after mount
+ if (newVariant !== undefined) {
+ selectedVariant.value = newVariant;
+ }
+ };
+
+ const sendPing = (variant: string) => {
+ if (!name || !variant) return;
+ HttpService.sendData({
+ url: config.apiUrl,
+ type: AbbyEventType.PING,
+ data: {
+ projectId: config.projectId,
+ selectedVariant: variant,
+ testName: name as string,
+ },
+ });
+ };
+
+ let hasMounted = false;
+
+ if (getCurrentInstance()) {
+ onMounted(() => {
+ const previous = selectedVariant.value;
+ syncVariant();
+ hasMounted = true;
+ // If the variant was already chosen before mount, the watcher
+ // will not fire, so ping it here. A change from "" is pinged by
+ // the watcher after this hook, once hasMounted is true.
+ if (selectedVariant.value && selectedVariant.value === previous) {
+ sendPing(selectedVariant.value);
+ }
+ });
+ } else {
+ syncVariant();
+ }
+
+ // listen to changes for the current variant
+ watch(readVariant, (newVariant) => {
+ if (newVariant !== undefined) {
+ selectedVariant.value = newVariant;
+ }
+ });
+
+ // send a ping whenever a variant is shown after mount
+ watch(selectedVariant, (variant, previous) => {
+ if (!hasMounted || !variant || variant === previous) return;
+ sendPing(variant);
+ });
+
+ /**
+ * This function can be called to indicate that something that
+ * uses the selected variant has been rendered.
+ * It will automatically send the selected variant to the server.
+ */
+ const onAct = () => {
+ if (!selectedVariant.value) return;
+
+ HttpService.sendData({
+ url: config.apiUrl,
+ type: AbbyEventType.ACT,
+ data: {
+ projectId: config.projectId,
+ selectedVariant: selectedVariant.value,
+ testName: name as string,
+ },
+ });
+ };
+
+ const variant = computed(() =>
+ lookupObject
+ ? lookupObject[selectedVariant.value as TestVariant]
+ : // Typescript fails here. If we cast selectedVariant to TestVariant
+ // it still assumes that it is a string. So we cast it to any instead
+ (selectedVariant.value as any)
+ ) as ComputedRef<
+ Lookup extends undefined
+ ? ABTestReturnValue | ""
+ : ABTestReturnValue | undefined
+ >;
+
+ return { variant, onAct };
+ };
+
+ const useFeatureFlag = (name: FlagName): ComputedRef => {
+ const data = useAbbyData();
+ return computed(() => {
+ // Stay reactive to the snapshot, then resolve through core so a
+ // missing flag uses the configured fallback and a fetched `false` is kept.
+ void data.value.flags[name];
+ return currentAbby().getFeatureFlag(name);
+ });
+ };
+
+ /**
+ * Returns an Array of all flags with their name and value
+ */
+ const useFeatureFlags = () => {
+ const data = useAbbyData();
+ return computed(() =>
+ (Object.keys(data.value.flags) as Array).map((flagName) => ({
+ name: flagName,
+ value: data.value.flags[flagName].value,
+ }))
+ );
+ };
+
+ const resolveRemoteConfig = <
+ T extends RemoteConfigName,
+ Config extends RemoteConfig[T],
+ >(
+ remoteConfigName: T,
+ snapshot: AbbyProjectData
+ ): RemoteConfigValueStringToType => {
+ const entry = snapshot.remoteConfig[remoteConfigName];
+ if (entry !== undefined) {
+ return entry.value as RemoteConfigValueStringToType;
+ }
+
+ const fallback =
+ config.settings?.remoteConfig?.fallbackValues?.[remoteConfigName];
+ if (fallback !== undefined) {
+ return fallback as RemoteConfigValueStringToType;
+ }
+
+ const configType = config.remoteConfig?.[remoteConfigName];
+ const defaultValue = configType
+ ? config.settings?.remoteConfig?.defaultValues?.[configType]
+ : undefined;
+ if (defaultValue != null) {
+ return defaultValue as RemoteConfigValueStringToType;
+ }
+
+ return getDefaultRemoteConfigValue(
+ configType ?? "String"
+ ) as RemoteConfigValueStringToType;
+ };
+
+ const useRemoteConfig = <
+ T extends RemoteConfigName,
+ Config extends RemoteConfig[T],
+ >(
+ remoteConfigName: T
+ ): ComputedRef> => {
+ const data = useAbbyData();
+ return computed(() => resolveRemoteConfig(remoteConfigName, data.value));
+ };
+
+ /**
+ * Returns an Array of all remote config variables with their name and value
+ */
+ const useRemoteConfigVariables = () => {
+ const data = useAbbyData();
+ return computed(
+ () =>
+ (Object.keys(data.value.remoteConfig) as Array).map(
+ (configName) => ({
+ name: configName,
+ value: data.value.remoteConfig[configName].value,
+ })
+ ) as Array<{
+ name: RemoteConfigName;
+ value: RemoteConfigValueStringToType;
+ }>
+ );
+ };
+
+ const getFeatureFlagValue = (name: FlagName) => {
+ return currentAbby().getFeatureFlag(name);
+ };
+
+ const getRemoteConfig = <
+ T extends RemoteConfigName,
+ Config extends RemoteConfig[T],
+ >(
+ remoteConfigName: T
+ ): RemoteConfigValueStringToType => {
+ return resolveRemoteConfig(
+ remoteConfigName,
+ currentAbby().getProjectData()
+ );
+ };
+
+ const getABTestValue = <
+ TestName extends keyof Tests,
+ TestVariant extends Tests[TestName]["variants"][number],
+ LookupValue,
+ const Lookup extends
+ | Record
+ | undefined = undefined,
+ >(
+ testName: TestName,
+ lookupObject?: Lookup
+ ): ABTestReturnValue => {
+ const variant = currentAbby().getTestVariant(testName);
+ // Typescript looses its typing here, so we cast as any in favor of having
+ // better type inference for the user
+ if (lookupObject === undefined) {
+ return variant as any;
+ }
+
+ return lookupObject[variant as TestVariant] as any;
+ };
+
+ /**
+ * Returns a renderless component that mounts the Abby devtools
+ * (only in development unless `dangerouslyForceShow` is set)
+ */
+ const withDevtools: withDevtoolsFunction = (factory, props) => {
+ return defineComponent({
+ name: "AbbyDevtools",
+ setup() {
+ let destroy: (() => void) | undefined;
+
+ onMounted(() => {
+ if (
+ !props?.dangerouslyForceShow &&
+ process.env.NODE_ENV !== "development"
+ ) {
+ return;
+ }
+ destroy = factory.create({ ...props, abby: currentAbby() });
+ });
+
+ onBeforeUnmount(() => {
+ destroy?.();
+ destroy = undefined;
+ });
+
+ return () => null;
+ },
+ });
+ };
+
+ /**
+ * Simple helper function create a function that resets an AB test
+ * @param name the name of the test
+ * @returns A function that can be called to reset the test
+ */
+ const getABResetFunction = (name: T) => {
+ return () => {
+ TestStorageService.remove(config.projectId, name as string);
+ };
+ };
+
+ /**
+ * Simple helper function to get a list of all variants for a given test
+ * @param name the name of the test
+ * @returns an array of all variants
+ */
+ const getVariants = (name: T) => {
+ return currentAbby().getVariants(name);
+ };
+
+ /**
+ * Fetches the project data from the Abby API. Use this on the server
+ * (e.g. in a Nuxt plugin) and pass the result to the plugin as `initialData`
+ * so the client doesn't need to fetch it again.
+ */
+ const getInitialData = () => {
+ return HttpService.getProjectData(getProjectDataRequestOptions());
+ };
+
+ const updateUserProperties = (
+ user: Partial<{
+ -readonly [K in keyof User]: Infer;
+ }>
+ ) => {
+ currentAbby().updateUserProperties(user);
+ };
+
+ return {
+ AbbyPlugin,
+ useAbby,
+ useFeatureFlag,
+ useFeatureFlags,
+ useRemoteConfig,
+ useRemoteConfigVariables,
+ getFeatureFlagValue,
+ getRemoteConfig,
+ getABTestValue,
+ getABResetFunction,
+ getVariants,
+ updateUserProperties,
+ getInitialData,
+ withDevtools,
+ get __abby__() {
+ return currentAbby();
+ },
+ };
+}
diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts
new file mode 100644
index 00000000..a62b597a
--- /dev/null
+++ b/packages/vue/src/index.ts
@@ -0,0 +1,7 @@
+export {
+ createAbby,
+ type ABTestReturnValue,
+ type AbbyPluginOptions,
+ type withDevtoolsFunction,
+} from "./createAbby";
+export { type ABConfig, type AbbyConfig, defineConfig } from "@tryabby/core";
diff --git a/packages/vue/tests/createAbby.test.ts b/packages/vue/tests/createAbby.test.ts
new file mode 100644
index 00000000..8261139c
--- /dev/null
+++ b/packages/vue/tests/createAbby.test.ts
@@ -0,0 +1,51 @@
+import { createAbby } from "../src";
+import { TestStorageService } from "../src/StorageService";
+import { withSetup } from "./utils";
+
+describe("createAbby helpers", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("getInitialData uses config.fetch and the CDN URL when configured", async () => {
+ const fetchImpl = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ tests: [], flags: [], remoteConfig: [] }),
+ });
+
+ const { getInitialData } = createAbby({
+ environments: ["production"],
+ currentEnvironment: "production",
+ projectId: "proj-1",
+ apiUrl: "https://api.example/",
+ fetch: fetchImpl,
+ __experimentalCdnUrl: "https://cdn.example",
+ });
+
+ await getInitialData();
+
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ expect(fetchImpl).toHaveBeenCalledWith(
+ "https://cdn.example/proj-1/production"
+ );
+ });
+
+ it("forwards expiresInDays, including an explicit zero, to TestStorageService", () => {
+ const getSpy = vi.spyOn(TestStorageService, "get").mockReturnValue(null);
+ const setSpy = vi.spyOn(TestStorageService, "set");
+ const { AbbyPlugin, useAbby } = createAbby({
+ environments: [""],
+ currentEnvironment: "",
+ projectId: "123",
+ tests: { test: { variants: ["A", "B"] } },
+ cookies: { expiresInDays: 0 },
+ });
+
+ withSetup(() => useAbby("test"), AbbyPlugin);
+
+ expect(getSpy).toHaveBeenCalled();
+ expect(setSpy).toHaveBeenCalled();
+ const last = setSpy.mock.calls.at(-1);
+ expect(last?.[3]).toEqual({ expiresInDays: 0 });
+ });
+});
diff --git a/packages/vue/tests/featureFlags.test.ts b/packages/vue/tests/featureFlags.test.ts
new file mode 100644
index 00000000..93d0c2f2
--- /dev/null
+++ b/packages/vue/tests/featureFlags.test.ts
@@ -0,0 +1,148 @@
+import { flushPromises } from "@vue/test-utils";
+import { createAbby } from "../src";
+import { withSetup } from "./utils";
+
+describe("useFeatureFlag", () => {
+ it("returns the default value before the data is loaded", () => {
+ const { AbbyPlugin, useFeatureFlag } = createAbby({
+ environments: [""],
+ currentEnvironment: "",
+ projectId: "123",
+ flags: ["flag1", "flag2"],
+ });
+
+ const { result } = withSetup(() => useFeatureFlag("flag1"), AbbyPlugin);
+ expect(result.value).toBe(false);
+ });
+
+ it("updates reactively once the project data was fetched", async () => {
+ const { AbbyPlugin, useFeatureFlag, useFeatureFlags } = createAbby({
+ environments: [""],
+ currentEnvironment: "",
+ projectId: "123",
+ flags: ["flag1", "flag2"],
+ });
+
+ const { result } = withSetup(
+ () => ({ flag1: useFeatureFlag("flag1"), all: useFeatureFlags() }),
+ AbbyPlugin
+ );
+
+ await vi.waitFor(() => expect(result.flag1.value).toBe(true));
+ expect(result.all.value).toEqual([
+ { name: "flag1", value: true },
+ { name: "flag2", value: false },
+ ]);
+ });
+
+ it("uses the initialData passed to the plugin without fetching", async () => {
+ const fetchSpy = vi.spyOn(global, "fetch");
+ const { AbbyPlugin, useFeatureFlag, getFeatureFlagValue } = createAbby({
+ environments: [""],
+ currentEnvironment: "",
+ projectId: "123",
+ flags: ["flag1", "flag2"],
+ });
+
+ const { result } = withSetup(() => useFeatureFlag("flag2"), AbbyPlugin, {
+ initialData: {
+ tests: [],
+ flags: [
+ { name: "flag1", value: false },
+ { name: "flag2", value: true },
+ ],
+ remoteConfig: [],
+ },
+ });
+
+ await flushPromises();
+ expect(result.value).toBe(true);
+ expect(getFeatureFlagValue("flag2")).toBe(true);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ fetchSpy.mockRestore();
+ });
+
+ it("reacts to local updates of a flag", async () => {
+ const { AbbyPlugin, useFeatureFlag, __abby__ } = createAbby({
+ environments: [""],
+ currentEnvironment: "",
+ projectId: "123",
+ flags: ["flag1"],
+ });
+
+ const { result } = withSetup(() => useFeatureFlag("flag1"), AbbyPlugin, {
+ initialData: {
+ tests: [],
+ flags: [{ name: "flag1", value: false }],
+ remoteConfig: [],
+ },
+ });
+ expect(result.value).toBe(false);
+
+ __abby__.updateFlag("flag1", true);
+ expect(result.value).toBe(true);
+ });
+
+ it("can be server-rendered with data from getInitialData()", async () => {
+ const { AbbyPlugin, useFeatureFlag, getInitialData } = createAbby({
+ environments: [""],
+ currentEnvironment: "",
+ projectId: "123",
+ flags: ["flag1", "flag2"],
+ });
+
+ const initialData = await getInitialData();
+ expect(initialData).not.toBeNull();
+
+ const { result } = withSetup(() => useFeatureFlag("flag1"), AbbyPlugin, {
+ initialData,
+ });
+ expect(result.value).toBe(true);
+ });
+});
+
+ it("uses the configured fallback when a flag is omitted from the snapshot", () => {
+ const { AbbyPlugin, useFeatureFlag } = createAbby({
+ environments: [""],
+ currentEnvironment: "",
+ projectId: "123",
+ flags: ["newFeature"],
+ settings: {
+ flags: {
+ fallbackValues: { newFeature: true },
+ },
+ },
+ });
+
+ const { result } = withSetup(() => useFeatureFlag("newFeature"), AbbyPlugin, {
+ initialData: {
+ tests: [],
+ flags: [],
+ remoteConfig: [],
+ },
+ });
+ expect(result.value).toBe(true);
+ });
+
+ it("keeps a fetched false rather than falling back", () => {
+ const { AbbyPlugin, useFeatureFlag } = createAbby({
+ environments: [""],
+ currentEnvironment: "",
+ projectId: "123",
+ flags: ["newFeature"],
+ settings: {
+ flags: {
+ fallbackValues: { newFeature: true },
+ },
+ },
+ });
+
+ const { result } = withSetup(() => useFeatureFlag("newFeature"), AbbyPlugin, {
+ initialData: {
+ tests: [],
+ flags: [{ name: "newFeature", value: false }],
+ remoteConfig: [],
+ },
+ });
+ expect(result.value).toBe(false);
+ });
diff --git a/packages/vue/tests/mocks/handlers.ts b/packages/vue/tests/mocks/handlers.ts
new file mode 100644
index 00000000..f2028cb7
--- /dev/null
+++ b/packages/vue/tests/mocks/handlers.ts
@@ -0,0 +1,42 @@
+import { ABBY_BASE_URL, type AbbyDataResponse } from "@tryabby/core";
+import { rest } from "msw";
+
+const returnData: AbbyDataResponse = {
+ tests: [
+ {
+ name: "test",
+ weights: [1, 1, 1, 1],
+ },
+ {
+ name: "test2",
+ weights: [1, 0],
+ },
+ ],
+ flags: [
+ {
+ name: "flag1",
+ value: true,
+ },
+ {
+ name: "flag2",
+ value: false,
+ },
+ ],
+ remoteConfig: [
+ {
+ name: "remoteConfig1",
+ value: "FooBar",
+ },
+ ],
+};
+export const handlers = [
+ rest.get(
+ `${ABBY_BASE_URL}api/dashboard/:projectId/data`,
+ (_req, res, ctx) => {
+ return res(ctx.json(returnData));
+ }
+ ),
+ rest.get(`${ABBY_BASE_URL}api/v2/data/:projectId`, (_req, res, ctx) => {
+ return res(ctx.json(returnData));
+ }),
+];
diff --git a/packages/vue/tests/mocks/server.ts b/packages/vue/tests/mocks/server.ts
new file mode 100644
index 00000000..9bb8a870
--- /dev/null
+++ b/packages/vue/tests/mocks/server.ts
@@ -0,0 +1,5 @@
+import { setupServer } from "msw/node";
+import { handlers } from "./handlers";
+
+// This configures a request mocking server with the given request handlers.
+export const server = setupServer(...handlers);
diff --git a/packages/vue/tests/remoteConfig.test.ts b/packages/vue/tests/remoteConfig.test.ts
new file mode 100644
index 00000000..eca67c1b
--- /dev/null
+++ b/packages/vue/tests/remoteConfig.test.ts
@@ -0,0 +1,99 @@
+import { createAbby } from "../src";
+import { withSetup } from "./utils";
+
+describe("useRemoteConfig", () => {
+ it("returns the default value before the data is loaded", () => {
+ const { AbbyPlugin, useRemoteConfig } = createAbby({
+ environments: [""],
+ currentEnvironment: "",
+ projectId: "123",
+ remoteConfig: { remoteConfig1: "String", count: "Number" },
+ });
+
+ const { result } = withSetup(
+ () => ({
+ str: useRemoteConfig("remoteConfig1"),
+ num: useRemoteConfig("count"),
+ }),
+ AbbyPlugin
+ );
+ expect(result.str.value).toBe("");
+ expect(result.num.value).toBe(0);
+ });
+
+ it("updates reactively once the project data was fetched", async () => {
+ const { AbbyPlugin, useRemoteConfig, useRemoteConfigVariables } =
+ createAbby({
+ environments: [""],
+ currentEnvironment: "",
+ projectId: "123",
+ remoteConfig: { remoteConfig1: "String" },
+ });
+
+ const { result } = withSetup(
+ () => ({
+ value: useRemoteConfig("remoteConfig1"),
+ all: useRemoteConfigVariables(),
+ }),
+ AbbyPlugin
+ );
+
+ await vi.waitFor(() => expect(result.value.value).toBe("FooBar"));
+ expect(result.all.value).toEqual([
+ { name: "remoteConfig1", value: "FooBar" },
+ ]);
+ });
+});
+
+ it("uses the configured fallback when a remote config is omitted", () => {
+ const { AbbyPlugin, useRemoteConfig } = createAbby({
+ environments: [""],
+ currentEnvironment: "",
+ projectId: "123",
+ remoteConfig: { buttonText: "String" },
+ settings: {
+ remoteConfig: {
+ fallbackValues: { buttonText: "Buy now" },
+ },
+ },
+ });
+
+ const { result } = withSetup(
+ () => useRemoteConfig("buttonText"),
+ AbbyPlugin,
+ {
+ initialData: {
+ tests: [],
+ flags: [],
+ remoteConfig: [],
+ },
+ }
+ );
+ expect(result.value).toBe("Buy now");
+ });
+
+ it("uses the type default when a remote config is omitted without a fallback", () => {
+ const { AbbyPlugin, useRemoteConfig } = createAbby({
+ environments: [""],
+ currentEnvironment: "",
+ projectId: "123",
+ remoteConfig: { buttonText: "String", count: "Number" },
+ });
+
+ const { result } = withSetup(
+ () => ({
+ str: useRemoteConfig("buttonText"),
+ num: useRemoteConfig("count"),
+ }),
+ AbbyPlugin,
+ {
+ initialData: {
+ tests: [],
+ flags: [],
+ remoteConfig: [],
+ },
+ }
+ );
+ expect(result.str.value).toBe("");
+ expect(result.num.value).toBe(0);
+ });
diff --git a/packages/vue/tests/setup.ts b/packages/vue/tests/setup.ts
new file mode 100644
index 00000000..5f0f9e44
--- /dev/null
+++ b/packages/vue/tests/setup.ts
@@ -0,0 +1,16 @@
+import fetch from "node-fetch";
+import { afterAll, afterEach, beforeAll } from "vitest";
+import { server } from "./mocks/server";
+
+/// @ts-ignore
+global.fetch = fetch;
+
+// Establish API mocking before all tests.
+beforeAll(() => server.listen());
+
+// Clean up after the tests are finished.
+afterAll(() => server.close());
+
+// Reset any request handlers that we may add during the tests,
+// so they don't affect other tests.
+afterEach(() => server.resetHandlers());
diff --git a/packages/vue/tests/ssr.test.ts b/packages/vue/tests/ssr.test.ts
new file mode 100644
index 00000000..6c81f078
--- /dev/null
+++ b/packages/vue/tests/ssr.test.ts
@@ -0,0 +1,89 @@
+// @vitest-environment node
+import { createSSRApp, defineComponent, h } from "vue";
+import { renderToString } from "vue/server-renderer";
+import { createAbby } from "../src";
+
+describe("server side rendering", () => {
+ it("renders flags and remote config from initialData and no variant", async () => {
+ const { AbbyPlugin, useAbby, useFeatureFlag, useRemoteConfig } = createAbby(
+ {
+ environments: [""],
+ currentEnvironment: "",
+ projectId: "123",
+ tests: { footer: { variants: ["dark", "light"] } },
+ flags: ["newFeature"],
+ remoteConfig: { buttonText: "String" },
+ }
+ );
+
+ const app = createSSRApp(
+ defineComponent({
+ setup() {
+ const { variant } = useAbby("footer");
+ const newFeature = useFeatureFlag("newFeature");
+ const buttonText = useRemoteConfig("buttonText");
+ return () =>
+ h("main", [
+ h("span", { id: "variant" }, variant.value),
+ newFeature.value ? h("p", "new feature") : null,
+ h("button", buttonText.value),
+ ]);
+ },
+ })
+ );
+ app.use(AbbyPlugin, {
+ initialData: {
+ tests: [{ name: "footer", weights: [1, 1] }],
+ flags: [{ name: "newFeature", value: true }],
+ remoteConfig: [{ name: "buttonText", value: "Buy now" }],
+ },
+ });
+
+ const html = await renderToString(app);
+ // the variant is only selected on the client to avoid hydration mismatches
+ expect(html).toContain('');
+ expect(html).toContain("