UNPKG

flagmint-vuejs-feature-flags

Version:

A Vue.js SDK for managing feature flags in Flagmint applications, supporting both Vue 2 and Vue 3.

67 lines (62 loc) 2.17 kB
'use strict'; var vue = require('vue'); const FLAGMINT_INIT = Symbol.for('FLAGMINT_INIT'); const FLAGMINT_READY = Symbol.for('FLAGMINT_READY'); const FLAGMINT_CLIENT = Symbol.for('FLAGMINT_CLIENT'); const flags = vue.ref({}); let unsubscribe = null; let subscriberCount = 0; function useFlagmint() { // inject() called synchronously at top level — safe because provides // are registered before install() returns, before any component mounts const clientRef = vue.inject(FLAGMINT_CLIENT, vue.ref(null)); const isReady = vue.inject(FLAGMINT_READY, vue.ref(false)); const init = vue.inject(FLAGMINT_INIT, null); let stopWatch = null; const onReady = (ready) => { if (ready) { startSubscription(); stopWatch === null || stopWatch === void 0 ? void 0 : stopWatch(); } }; const startSubscription = () => { subscriberCount++; const client = clientRef.value; if (!client || unsubscribe) return; unsubscribe = client.subscribe((updatedFlags) => { flags.value = updatedFlags; }); }; // Watch isReady — handles both "already ready at mount" and "becomes ready later" stopWatch = vue.watch(() => isReady.value, onReady, { immediate: true }); vue.onUnmounted(() => { subscriberCount--; stopWatch === null || stopWatch === void 0 ? void 0 : stopWatch(); if (unsubscribe && subscriberCount === 0) { unsubscribe(); unsubscribe = null; } }); const getFlag = (key, fallback) => { var _a; return ((_a = flags.value[key]) !== null && _a !== void 0 ? _a : fallback); }; const updateFlagmintContext = async (context) => { const client = clientRef.value; if (!client) { console.warn('[Flagmint] updateFlagmintContext called before client was ready.'); return; } await client.updateContext(context); }; return { client: clientRef, isReady, init, flags, getFlag, updateFlagmintContext }; } exports.useFlagmint = useFlagmint;