permix
Version:
Permix is a lightweight, framework-agnostic, type-safe permissions management library for JavaScript applications on the client and server sides.
92 lines (85 loc) • 2.27 kB
JavaScript
import { ref, computed, inject } from 'vue';
import { v as validatePermix, g as getRules, b as checkWithRules } from '../shared/permix.Q-O041RP.mjs';
const PERMIX_CONTEXT_KEY = Symbol('vue-permix');
/**
* Vue plugin that provides the Permix context to your application.
*
* @link https://permix.letstri.dev/docs/integrations/vue
*/
const permixPlugin = (app, {
permix
}) => {
if (!permix) {
throw new Error('[Permix]: Looks like you forgot to provide the permix instance to the plugin');
}
validatePermix(permix);
const context = ref({
permix,
state: getRules(permix),
isReady: false
});
app.provide(PERMIX_CONTEXT_KEY, context);
permix.hook('setup', () => {
context.value.state = getRules(permix);
});
permix.hook('ready', () => {
context.value.isReady = permix.isReady();
});
};
function usePermixContext() {
const context = inject(PERMIX_CONTEXT_KEY);
if (!context) {
throw new Error('[Permix]: Looks like you forgot to install the plugin');
}
return context;
}
/**
* Composable that provides the Permix context to your Vue components.
*
* @link https://permix.letstri.dev/docs/integrations/vue
*/
function usePermix(permix) {
validatePermix(permix);
const context = usePermixContext();
const check = (...args) => {
validatePermix(context.value.permix);
return checkWithRules(context.value.state, ...args);
};
return {
check,
isReady: computed(() => context.value.isReady)
};
}
function createComponents(permix) {
function Check(props, context) {
const {
check
} = usePermix(permix);
const hasPermission = check(props.entity, props.action, props.data);
return props.reverse ? hasPermission ? context.slots.otherwise?.() : context.slots.default?.() : hasPermission ? context.slots.default?.() : context.slots.otherwise?.();
}
Check.inheritAttrs = false;
Check.props = {
entity: {
type: String,
required: true
},
action: {
type: [String, Array],
required: true
},
data: {
type: Object,
required: false
},
reverse: {
type: Boolean,
required: false,
default: false
}
};
return {
Check
};
}
export { createComponents, permixPlugin, usePermix };