Repository navigation
Add a typed Vue 3 integration for Abby #237
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| # Abby for Vue 3 | ||
|
|
||
| Install `@tryabby/vue` in a Vue 3.5 application. Create the plugin from your project configuration and install it before mounting the app. | ||
|
|
||
| ```ts | ||
| import { createApp } from "vue"; | ||
| import { createAbby } from "@tryabby/vue"; | ||
| import App from "./App.vue"; | ||
|
|
||
| export const abby = createAbby({ | ||
| projectId: "YOUR_PROJECT_ID", currentEnvironment: "production", | ||
| environments: ["production"], flags: ["newCheckout"], | ||
| remoteConfig: { checkoutLabel: "String" }, | ||
| tests: { checkout: { variants: ["control", "short"] } }, | ||
| }); | ||
| createApp(App).use(abby).mount("#app"); | ||
| ``` | ||
|
|
||
| Inside a component's setup, the three composables return computed values that update when the core loads project data. | ||
|
|
||
| ```vue | ||
| <script setup lang="ts"> | ||
| import { abby } from "./abby"; | ||
| const enabled = abby.useFeatureFlag("newCheckout"); | ||
| const label = abby.useRemoteConfig("checkoutLabel"); | ||
| const { variant, onAct } = abby.useAbby("checkout", { | ||
| control: "Checkout", short: "Pay", | ||
| }); | ||
| </script> | ||
| <template> | ||
| <button v-if="enabled" @click="onAct">{{ label || variant }}</button> | ||
| </template> | ||
| ``` | ||
|
|
||
| Each installation gets its own core instance. For SSR or a preloaded application, pass the same project response into `app.use(abby, initialData)` on the server and client. The A/B test renders its first configured variant for hydration, then selects the visitor's assigned variant on mount. Call `onAct()` on conversion to record the raw variant name even when the display value uses a lookup. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| { | ||
| "name": "@tryabby/vue", | ||
| "version": "0.1.0", | ||
| "description": "Typed Vue 3 composables for Abby", | ||
| "license": "ISC", | ||
| "main": "./dist/index.js", | ||
| "module": "./dist/index.mjs", | ||
| "types": "./dist/index.d.ts", | ||
| "exports": { | ||
| ".": { | ||
| "types": "./dist/index.d.ts", | ||
| "import": "./dist/index.mjs", | ||
| "require": "./dist/index.js" | ||
| } | ||
| }, | ||
| "files": ["dist"], | ||
| "scripts": { | ||
| "build": "tsup src/index.ts --format esm,cjs --dts --clean", | ||
| "test": "tsc --noEmit && vitest run" | ||
| }, | ||
| "dependencies": { "@tryabby/core": "workspace:*", "js-cookie": "^3.0.1" }, | ||
| "peerDependencies": { "vue": "^3.5.0" }, | ||
| "devDependencies": { | ||
| "@types/js-cookie": "^3.0.3", | ||
| "jsdom": "^20.0.3", | ||
| "tsup": "^6.5.0", | ||
| "typescript": "5.5.4", | ||
| "vitest": "2.0.5", | ||
| "vue": "^3.5.0" | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| import { | ||
| Abby, AbbyEventType, HttpService, getABStorageKey, getFFStorageKey, | ||
| getRCStorageKey, type ABConfig, type AbbyConfig, type AbbyDataResponse, | ||
| type RemoteConfigValueString, type StorageServiceOptions, | ||
| } from "@tryabby/core"; | ||
| import Cookies from "js-cookie"; | ||
| import { | ||
| computed, inject, onMounted, ref, shallowRef, watch, | ||
| type App, type InjectionKey, | ||
| } from "vue"; | ||
|
|
||
| export { defineConfig, type ABConfig, type AbbyConfig } from "@tryabby/core"; | ||
|
|
||
| export function createAbby< | ||
| const Flag extends string, | ||
| const Tests extends Record<string, ABConfig>, | ||
| const Remote extends Record<string, RemoteConfigValueString>, | ||
| >(config: AbbyConfig<Flag, Tests, string[], Extract<keyof Remote, string>, Remote>) { | ||
| type Test = Extract<keyof Tests, string>; | ||
| type RemoteKey = Extract<keyof Remote, string>; | ||
| type Variant<K extends Test> = Tests[K]["variants"][number]; | ||
|
|
||
| function storage(keyFor: (project: string, name: string) => string) { | ||
| return { | ||
| get: (name: string) => Cookies.get(keyFor(config.projectId, name)) ?? null, | ||
| set: (name: string, value: string, options?: StorageServiceOptions) => | ||
| Cookies.set(keyFor(config.projectId, name), value, { expires: options?.expiresInDays }), | ||
| }; | ||
| } | ||
|
|
||
| function state(initialData?: AbbyDataResponse) { | ||
| // Core updates the tests object as it selects variants. Give each app | ||
| // its own copy, including separate SSR requests that reuse this plugin. | ||
| const tests = Object.fromEntries(Object.entries(config.tests ?? {}).map( | ||
| ([name, test]) => [name, { ...test }], | ||
| )) as Tests; | ||
| const client = new Abby<Flag, Test, Tests, Remote, RemoteKey>( | ||
| { ...config, tests }, storage(getABStorageKey), storage(getFFStorageKey), storage(getRCStorageKey), | ||
| ); | ||
| if (initialData) client.init(initialData); | ||
| const revision = shallowRef(0); | ||
| const unsubscribe = client.subscribe(() => { revision.value++; }); | ||
| return { client, revision, unsubscribe }; | ||
| } | ||
|
|
||
| const key: InjectionKey<ReturnType<typeof state>> = Symbol("Abby"); | ||
| function useState() { | ||
| const current = inject(key); | ||
| if (!current) throw new Error("Install the Abby plugin with app.use(abby) before using its composables."); | ||
| return current; | ||
| } | ||
|
|
||
| function install(app: App, initialData?: AbbyDataResponse) { | ||
| const current = state(initialData); | ||
| app.provide(key, current); | ||
| app.onUnmount(current.unsubscribe); | ||
| if (!initialData && typeof window !== "undefined") void current.client.loadProjectData(); | ||
| } | ||
|
|
||
| function useFeatureFlag(name: Flag) { | ||
| const { client, revision } = useState(); | ||
| return computed(() => { void revision.value; return client.getFeatureFlag(name); }); | ||
| } | ||
|
|
||
| function useRemoteConfig<K extends RemoteKey>(name: K) { | ||
| const { client, revision } = useState(); | ||
| return computed(() => { void revision.value; return client.getRemoteConfig(name); }); | ||
| } | ||
|
|
||
| function useAbby<K extends Test, const Lookup extends Record<Variant<K>, unknown> | undefined = undefined>( | ||
| name: K, lookup?: Lookup, | ||
| ) { | ||
| const { client, revision } = useState(); | ||
| const mounted = ref(false); | ||
| const selected = computed<Variant<K>>(() => { | ||
| void revision.value; | ||
| // The initial render uses the same fallback on the server and client. | ||
| return mounted.value ? client.getTestVariant(name) : config.tests![name].variants[0]; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Wait for project data before assigning a variant. If the app mounts before Keep the hydration placeholder until initialization succeeds. Then enable assignment and tracking. Preserve immediate selection when
|
||
| }); | ||
| function track(type: AbbyEventType) { | ||
| if (mounted.value && selected.value) HttpService.sendData({ | ||
| url: config.apiUrl, type, | ||
| data: { projectId: config.projectId, testName: name, selectedVariant: selected.value }, | ||
| }); | ||
| } | ||
| onMounted(() => { | ||
| mounted.value = true; | ||
| watch(selected, () => track(AbbyEventType.PING), { immediate: true }); | ||
| }); | ||
| type Value = Lookup extends Record<Variant<K>, unknown> ? Lookup[Variant<K>] : Variant<K>; | ||
| const variant = computed(() => (lookup ? lookup[selected.value] : selected.value) as Value); | ||
| return { variant, onAct: () => track(AbbyEventType.ACT) }; | ||
| } | ||
|
|
||
| return { install, useAbby, useFeatureFlag, useRemoteConfig }; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| // @vitest-environment node | ||
| import { HttpService } from "@tryabby/core"; | ||
| import { createSSRApp, h } from "vue"; | ||
| import { renderToString } from "vue/server-renderer"; | ||
| import { expect, it, vi } from "vitest"; | ||
| import { createAbby } from "../src"; | ||
|
|
||
| it("renders preloaded flags independently across SSR requests without fetching or tracking", async () => { | ||
| const fetch = vi.spyOn(HttpService, "getProjectData"); | ||
| const track = vi.spyOn(HttpService, "sendData"); | ||
| try { | ||
| const abby = createAbby({ projectId: "ssr", environments: ["test"], currentEnvironment: "test", | ||
| flags: ["enabled"], tests: { layout: { variants: ["first", "second"] } } }); | ||
| function render(enabled: boolean) { | ||
| const app = createSSRApp({ setup() { | ||
| const flag = abby.useFeatureFlag("enabled"); | ||
| const { variant } = abby.useAbby("layout"); | ||
| return () => h("p", String(flag.value) + "/" + variant.value); | ||
| }}); | ||
| app.use(abby, { tests: [], flags: [{ name: "enabled", value: enabled }], remoteConfig: [] }); | ||
| return renderToString(app); | ||
| } | ||
| expect(await Promise.all([render(true), render(false)])).toEqual(["<p>true/first</p>", "<p>false/first</p>"]); | ||
| expect(fetch).not.toHaveBeenCalled(); | ||
| expect(track).not.toHaveBeenCalled(); | ||
| } finally { fetch.mockRestore(); track.mockRestore(); } | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| import { expectTypeOf } from "vitest"; | ||
| import type { ComputedRef } from "vue"; | ||
| import { createAbby } from "../src"; | ||
|
|
||
| // Compiled by tsc. Composables run inside component setup at runtime. | ||
| export function checkInference() { | ||
| const abby = createAbby({ | ||
| projectId: "types", environments: ["prod"], currentEnvironment: "prod", | ||
| flags: ["beta"], remoteConfig: { price: "Number", label: "String" }, | ||
| tests: { treatment: { variants: ["control", "test"] } }, | ||
| }); | ||
| expectTypeOf(abby.useAbby("treatment").variant).toEqualTypeOf<ComputedRef<"control" | "test">>(); | ||
| expectTypeOf(abby.useAbby("treatment", { control: 1, test: 2 }).variant).toEqualTypeOf<ComputedRef<1 | 2>>(); | ||
| expectTypeOf(abby.useFeatureFlag("beta")).toEqualTypeOf<ComputedRef<boolean>>(); | ||
| expectTypeOf(abby.useRemoteConfig("price")).toEqualTypeOf<ComputedRef<number>>(); | ||
| expectTypeOf(abby.useRemoteConfig("label")).toEqualTypeOf<ComputedRef<string>>(); | ||
| // @ts-expect-error Unknown flag. | ||
| abby.useFeatureFlag("other"); | ||
| // @ts-expect-error Missing a variant. | ||
| abby.useAbby("treatment", { control: 1 }); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| // @vitest-environment jsdom | ||
| import { AbbyEventType, HttpService, type AbbyDataResponse } from "@tryabby/core"; | ||
| import { createApp, defineComponent, h, nextTick } from "vue"; | ||
| import { afterEach, describe, expect, it, vi } from "vitest"; | ||
| import { createAbby } from "../src"; | ||
|
|
||
| const config = { | ||
| projectId: "vue-test", currentEnvironment: "test", environments: ["test"], | ||
| flags: ["showBanner"] as ("showBanner")[], | ||
| remoteConfig: { caption: "String" } as const, | ||
| tests: { color: { variants: ["blue", "green"] as const } }, | ||
| cookies: { disableByDefault: true }, | ||
| }; | ||
| const data = (caption: string, enabled: boolean): AbbyDataResponse => ({ | ||
| tests: [{ name: "color", weights: [0, 1] }], | ||
| flags: [{ name: "showBanner", value: enabled }], | ||
| remoteConfig: [{ name: "caption", value: caption }], | ||
| }); | ||
|
|
||
| afterEach(() => { vi.restoreAllMocks(); }); | ||
|
|
||
| describe("Vue plugin", () => { | ||
| it("isolates installations and tracks the chosen variant for an action", async () => { | ||
| const events = vi.spyOn(HttpService, "sendData").mockImplementation(() => undefined); | ||
| const abby = createAbby(config); | ||
| function mount(caption: string, flag: boolean) { | ||
| const host = document.createElement("div"); | ||
| const app = createApp(defineComponent({ setup() { | ||
| const { variant, onAct } = abby.useAbby("color", { blue: "B", green: "G" }); | ||
| const enabled = abby.useFeatureFlag("showBanner"); | ||
| const text = abby.useRemoteConfig("caption"); | ||
| return () => h("button", { onClick: onAct }, [text.value, String(enabled.value), variant.value].join("/")); | ||
| }})); | ||
| app.use(abby, data(caption, flag)); | ||
| app.mount(host); | ||
| return { host, app }; | ||
| } | ||
| const a = mount("First", true); | ||
| const b = mount("Second", false); | ||
| await nextTick(); | ||
| expect(a.host.textContent).toBe("First/true/G"); | ||
| expect(b.host.textContent).toBe("Second/false/G"); | ||
| a.host.querySelector("button")!.click(); | ||
| expect(events.mock.lastCall?.[0]).toMatchObject({ | ||
| type: AbbyEventType.ACT, data: { projectId: "vue-test", selectedVariant: "green", testName: "color" }, | ||
| }); | ||
| a.app.unmount(); | ||
| b.app.unmount(); | ||
| }); | ||
|
|
||
| it("updates a mounted component after the project data arrives", async () => { | ||
| let release!: (value: AbbyDataResponse) => void; | ||
| const response = new Promise<AbbyDataResponse>(resolve => { release = resolve; }); | ||
| vi.spyOn(HttpService, "getProjectData").mockReturnValue(response); | ||
| const abby = createAbby(config); | ||
| const app = createApp(defineComponent({ setup() { | ||
| const flag = abby.useFeatureFlag("showBanner"); | ||
| return () => h("p", String(flag.value)); | ||
| }})); | ||
| const host = document.createElement("div"); | ||
| app.use(abby); | ||
| app.mount(host); | ||
| expect(host.textContent).toBe("false"); | ||
| release(data("Ready", true)); | ||
| await vi.waitFor(() => expect(host.textContent).toBe("true")); | ||
| app.unmount(); | ||
| }); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| { | ||
| "compilerOptions": { | ||
| "strict": true, | ||
| "module": "ESNext", | ||
| "moduleResolution": "Bundler", | ||
| "target": "ES2022", | ||
| "skipLibCheck": true, | ||
| "allowSyntheticDefaultImports": true | ||
| }, | ||
| "include": ["src", "tests"] | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Preserve preloaded values until hydration completes.
With preloaded
enabled=falseand a browser override cookie containingtrue, this initialization produces different first renders. Core applies browser cookie overrides duringinit(), but the server has no browser cookie state.useFeatureFlag()therefore rendersfalseon the server andtrueduring client hydration. IdenticalinitialDatadoes not prevent this mismatch. (raw.githubusercontent.com)Defer browser overrides until mount, or accept matching request-scoped override state for both renders. Keep synchronous preloaded values when no override exists.