flagmint-vuejs-feature-flags
Version:
A Vue.js SDK for managing feature flags in Flagmint applications, supporting both Vue 2 and Vue 3.
96 lines (91 loc) • 3.67 kB
JavaScript
;
var vueDemi = require('vue-demi');
var flagmintJsSdk = require('flagmint-js-sdk');
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');
// Reactive references
const flagClientRef = vue.ref(null);
const readyRef = vue.ref(false);
const createFeatureFlagPlugin = (options) => ({
install(appOrVue) {
// Provide early so inject() sees them before init
if (vueDemi.isVue3) {
appOrVue.provide(FLAGMINT_READY, vue.readonly(readyRef));
appOrVue.provide(FLAGMINT_CLIENT, flagClientRef);
}
// Init function
const init = async () => {
if (flagClientRef.value)
return flagClientRef.value; // Avoid re-init
const client = new flagmintJsSdk.FlagClient(options);
await client.ready();
flagClientRef.value = client;
readyRef.value = true;
if (vueDemi.isVue3) {
appOrVue.config.globalProperties.$flagmint = flagClientRef;
appOrVue.config.globalProperties.$flagmintReady = readyRef;
}
else if (vueDemi.isVue2) {
// Use Vue.observable to make the state reactive in Vue 2
const Vue = appOrVue.constructor;
if (Vue.observable && !Vue.prototype.$flagmintState) {
Vue.prototype.$flagmintState = Vue.observable({
flagClientRef,
readyRef,
});
}
if (!Object.getOwnPropertyDescriptor(Vue.prototype, "$flagmint")) {
Object.defineProperty(Vue.prototype, "$flagmint", {
configurable: true,
get() {
var _a;
return (_a = Vue.prototype.$flagmintState.flagClientRef.value) !== null && _a !== void 0 ? _a : null;
},
});
}
if (!Object.getOwnPropertyDescriptor(Vue.prototype, "$flagmintReady")) {
Object.defineProperty(Vue.prototype, "$flagmintReady", {
configurable: true,
get() {
var _a;
return (_a = Vue.prototype.$flagmintState.readyRef.value) !== null && _a !== void 0 ? _a : null;
},
});
}
if (!Object.getOwnPropertyDescriptor(Vue.prototype, "$flagmintInit")) {
Object.defineProperty(Vue.prototype, "$flagmintInit", {
configurable: true,
value: init,
});
}
}
return client;
};
// Provide init
if (vueDemi.isVue3) {
appOrVue.provide(FLAGMINT_INIT, init);
}
else if (vueDemi.isVue2) {
// Use Vue.prototype for Vue 2
appOrVue.prototype.$flagmintInit = init;
}
// Auto-init if not deferred
if (!options.deferInitialization) {
void init();
}
},
});
function useFlagClient() {
return flagClientRef;
}
function useFlagmintReady() {
return readyRef;
}
exports.FLAGMINT_CLIENT = FLAGMINT_CLIENT;
exports.FLAGMINT_INIT = FLAGMINT_INIT;
exports.FLAGMINT_READY = FLAGMINT_READY;
exports.createFeatureFlagPlugin = createFeatureFlagPlugin;
exports.useFlagClient = useFlagClient;
exports.useFlagmintReady = useFlagmintReady;