@anievo-id/rbac-evolution-vue 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AniEvo-ID
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,119 @@
1
- # Temporary Holding Version
1
+ # @anievo-id/rbac-evolution-vue
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Vue 3 bindings for [rbac-evolution](../core): a `v-can` / `v-role` directive, `<Can>` / `<HasRole>` components,
4
+ composables and template helpers — the Vue counterpart of spatie/laravel-permission's `@can` / `@role` Blade directives.
5
+
6
+ > **Security note:** everything in this package runs in the browser and only decides what the UI *shows*.
7
+ > A user can always edit client-side state. **Always enforce authorization on the server**
8
+ > (e.g. with [`@anievo-id/rbac-evolution-express`](../express)).
9
+
10
+ ```bash
11
+ npm i @anievo-id/rbac-evolution @anievo-id/rbac-evolution-vue
12
+ ```
13
+
14
+ ## Setup
15
+
16
+ Send the user's snapshot from the server (`await rbac.for(user).snapshot()` → `{ roles, permissions }`)
17
+ and install the plugin:
18
+
19
+ ```ts
20
+ import { createApp } from 'vue'
21
+ import { createRbacPlugin } from '@anievo-id/rbac-evolution-vue'
22
+
23
+ export const rbac = createRbacPlugin({
24
+ snapshot: await fetch('/api/me/permissions').then((r) => r.json()), // or null for guests
25
+ wildcard: true, // match `articles.*` like the server (must mirror `createRbac({ wildcard })`)
26
+ superAdminRoles: ['super-admin'], // these roles pass every permission check
27
+ })
28
+
29
+ createApp(App).use(rbac).mount('#app')
30
+
31
+ // after login / logout — everything re-renders:
32
+ rbac.setSnapshot(await fetch('/api/me/permissions').then((r) => r.json()))
33
+ rbac.setSnapshot(null)
34
+ ```
35
+
36
+ The object returned by `createRbacPlugin` is also the RBAC instance, so it can be used outside
37
+ components (router guards, Pinia stores): `rbac.can('edit articles')`.
38
+
39
+ Options: `snapshot`, `wildcard`, `superAdminRoles`, and `directives` / `components` / `globalProperties`
40
+ (all `true` by default) to opt out of global registration.
41
+
42
+ ## Directives
43
+
44
+ Elements are hidden with `display: none` (like `v-show`) and re-evaluated whenever the snapshot or the bound value changes.
45
+
46
+ ```vue
47
+ <button v-can="'edit articles'">Edit</button>
48
+ <button v-can="['edit articles', 'publish articles']">Edit & publish</button> <!-- all -->
49
+ <button v-can.all="['edit articles', 'publish articles']">Edit & publish</button>
50
+ <button v-can.any="['edit articles', 'delete articles']">Moderate</button>
51
+ <p v-can.not="'edit articles'">Read only</p>
52
+
53
+ <a v-role="'admin'">Admin</a>
54
+ <a v-role="'admin|editor'">Staff</a> <!-- any (spatie pipe syntax) -->
55
+ <a v-role="['admin', 'editor']">Staff</a> <!-- any -->
56
+ <a v-role.all="['writer', 'editor']">Both</a>
57
+ <a v-role.not="'banned'">Post a comment</a>
58
+ ```
59
+
60
+ Need the element gone from the DOM instead of hidden? Use `v-if="$can(...)"` or `<Can>`.
61
+
62
+ ## Components
63
+
64
+ ```vue
65
+ <Can permission="edit articles">
66
+ <EditButton />
67
+ <template #fallback>You can't edit this article.</template>
68
+ </Can>
69
+
70
+ <Can :any-of="['edit articles', 'delete articles']">...</Can>
71
+ <Can :all-of="['edit articles', 'publish articles']">...</Can>
72
+ <Can permission="edit articles" not>Read only</Can>
73
+
74
+ <HasRole role="admin">...</HasRole>
75
+ <HasRole role="admin|editor">...</HasRole>
76
+ <HasRole :all-of="['writer', 'editor']">...</HasRole>
77
+ ```
78
+
79
+ They are registered globally by the plugin; you can also import them: `import { Can, HasRole } from '@anievo-id/rbac-evolution-vue'`.
80
+
81
+ ## Composables
82
+
83
+ All return a `ComputedRef<boolean>` and accept a value, a ref or a getter.
84
+
85
+ ```ts
86
+ import { useCan, useCanAll, useCanAny, useHasRole, useHasAnyRole, useRbac } from '@anievo-id/rbac-evolution-vue'
87
+
88
+ const canEdit = useCan('edit articles')
89
+ const canModerate = useCanAny(['edit articles', 'delete articles'])
90
+ const canEditThis = useCan(() => `edit ${props.type}`)
91
+ const isStaff = useHasRole('admin|editor')
92
+
93
+ const rbac = useRbac() // the instance: rbac.can(), rbac.hasRole(), rbac.snapshot, rbac.setSnapshot()
94
+ ```
95
+
96
+ ## Template helpers
97
+
98
+ ```vue
99
+ <button v-if="$can('edit articles')">Edit</button>
100
+ <span v-if="$hasRole('admin')">Admin</span>
101
+ <!-- also: $cannot, $canAny, $canAll, $hasAnyRole, $hasAllRoles, $rbac -->
102
+ ```
103
+
104
+ They are typed through `ComponentCustomProperties` module augmentation — nothing to configure.
105
+
106
+ ## Semantics
107
+
108
+ | Check | Single | List | `'a\|b'` |
109
+ | --- | --- | --- | --- |
110
+ | `can` / `v-can` / `<Can permission>` | has it | **all** | literal name |
111
+ | `canAny` / `v-can.any` / `<Can any-of>` | has it | any | literal name |
112
+ | `hasRole` / `v-role` / `<HasRole role>` | has it | **any** | any |
113
+ | `hasAllRoles` / `v-role.all` / `<HasRole all-of>` | has it | all | all |
114
+
115
+ An empty list never passes.
116
+
117
+ ## License
118
+
119
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,241 @@
1
+ 'use strict';
2
+
3
+ var vue = require('vue');
4
+ var rbacEvolution = require('@anievo-id/rbac-evolution');
5
+
6
+ // src/components.ts
7
+ var RBAC_KEY = /* @__PURE__ */ Symbol("rbac-evolution");
8
+ var EMPTY = Object.freeze({ roles: [], permissions: [] });
9
+ function normalizeSnapshot(snapshot) {
10
+ if (!snapshot) return EMPTY;
11
+ return Object.freeze({
12
+ roles: snapshot.roles.map((r) => r.trim()),
13
+ permissions: snapshot.permissions.map((p) => p.trim())
14
+ });
15
+ }
16
+ var toList = (value) => (typeof value === "string" ? [value] : [...value]).map((v) => v.trim()).filter((v) => v !== "");
17
+ var toRoleList = (value) => toList(value).flatMap((v) => toList(v.split("|")));
18
+ function createRbacState(options = {}) {
19
+ const state = vue.shallowRef(normalizeSnapshot(options.snapshot));
20
+ const wildcard = options.wildcard ?? false;
21
+ const superAdminRoles = toList(options.superAdminRoles ?? []);
22
+ const matches = (granted, required) => {
23
+ if (!wildcard) return granted.includes(required);
24
+ return granted.some((pattern) => {
25
+ try {
26
+ return rbacEvolution.wildcardImplies(pattern, required);
27
+ } catch {
28
+ return false;
29
+ }
30
+ });
31
+ };
32
+ const isSuperAdmin = () => superAdminRoles.some((r) => state.value.roles.includes(r));
33
+ const canAny = (permissions) => {
34
+ const { permissions: granted } = state.value;
35
+ if (isSuperAdmin()) return toList(permissions).length > 0;
36
+ return toList(permissions).some((p) => matches(granted, p));
37
+ };
38
+ const canAll = (permissions) => {
39
+ const { permissions: granted } = state.value;
40
+ const wanted = toList(permissions);
41
+ if (wanted.length === 0) return false;
42
+ if (isSuperAdmin()) return true;
43
+ return wanted.every((p) => matches(granted, p));
44
+ };
45
+ const hasAnyRole = (roles) => {
46
+ const mine = state.value.roles;
47
+ return toRoleList(roles).some((r) => mine.includes(r));
48
+ };
49
+ const hasAllRoles = (roles) => {
50
+ const mine = state.value.roles;
51
+ const wanted = toRoleList(roles);
52
+ return wanted.length > 0 && wanted.every((r) => mine.includes(r));
53
+ };
54
+ return {
55
+ snapshot: vue.readonly(state),
56
+ setSnapshot(snapshot) {
57
+ state.value = normalizeSnapshot(snapshot);
58
+ },
59
+ can: canAll,
60
+ cannot: (permission) => !canAll(permission),
61
+ canAny,
62
+ canAll,
63
+ hasRole: hasAnyRole,
64
+ hasAnyRole,
65
+ hasAllRoles,
66
+ isSuperAdmin
67
+ };
68
+ }
69
+
70
+ // src/composables.ts
71
+ function useRbac() {
72
+ const rbac = vue.inject(RBAC_KEY, null);
73
+ if (!rbac) {
74
+ throw new Error("[rbac-evolution] No RBAC instance found. Did you call `app.use(createRbacPlugin(...))`?");
75
+ }
76
+ return rbac;
77
+ }
78
+ var check = (pick) => (names) => {
79
+ const rbac = useRbac();
80
+ const fn = pick(rbac);
81
+ return vue.computed(() => fn(vue.toValue(names)));
82
+ };
83
+ var useCan = check((rbac) => rbac.can);
84
+ var useCannot = check((rbac) => rbac.cannot);
85
+ var useCanAny = check((rbac) => rbac.canAny);
86
+ var useCanAll = check((rbac) => rbac.canAll);
87
+ var useHasRole = check((rbac) => rbac.hasRole);
88
+ var useHasAnyRole = check((rbac) => rbac.hasAnyRole);
89
+ var useHasAllRoles = check((rbac) => rbac.hasAllRoles);
90
+
91
+ // src/components.ts
92
+ var nameList = { type: [String, Array], default: void 0 };
93
+ var Can = vue.defineComponent({
94
+ name: "Can",
95
+ props: {
96
+ permission: nameList,
97
+ anyOf: nameList,
98
+ allOf: nameList,
99
+ not: { type: Boolean, default: false }
100
+ },
101
+ slots: Object,
102
+ setup(props, { slots }) {
103
+ const rbac = useRbac();
104
+ return () => {
105
+ let allowed = true;
106
+ let checked = false;
107
+ if (props.permission !== void 0) {
108
+ checked = true;
109
+ allowed &&= rbac.canAll(props.permission);
110
+ }
111
+ if (props.allOf !== void 0) {
112
+ checked = true;
113
+ allowed &&= rbac.canAll(props.allOf);
114
+ }
115
+ if (props.anyOf !== void 0) {
116
+ checked = true;
117
+ allowed &&= rbac.canAny(props.anyOf);
118
+ }
119
+ const pass = checked && allowed !== props.not;
120
+ return (pass ? slots.default?.() : slots.fallback?.()) ?? null;
121
+ };
122
+ }
123
+ });
124
+ var HasRole = vue.defineComponent({
125
+ name: "HasRole",
126
+ props: {
127
+ role: nameList,
128
+ anyOf: nameList,
129
+ allOf: nameList,
130
+ not: { type: Boolean, default: false }
131
+ },
132
+ slots: Object,
133
+ setup(props, { slots }) {
134
+ const rbac = useRbac();
135
+ return () => {
136
+ let allowed = true;
137
+ let checked = false;
138
+ if (props.role !== void 0) {
139
+ checked = true;
140
+ allowed &&= rbac.hasAnyRole(props.role);
141
+ }
142
+ if (props.anyOf !== void 0) {
143
+ checked = true;
144
+ allowed &&= rbac.hasAnyRole(props.anyOf);
145
+ }
146
+ if (props.allOf !== void 0) {
147
+ checked = true;
148
+ allowed &&= rbac.hasAllRoles(props.allOf);
149
+ }
150
+ const pass = checked && allowed !== props.not;
151
+ return (pass ? slots.default?.() : slots.fallback?.()) ?? null;
152
+ };
153
+ }
154
+ });
155
+ function createVisibilityDirective(rbac, check2) {
156
+ const states = /* @__PURE__ */ new WeakMap();
157
+ return {
158
+ beforeMount(el, binding) {
159
+ const current = vue.shallowRef(binding);
160
+ const display = el.style.display === "none" ? "" : el.style.display;
161
+ const stop = vue.watchEffect(
162
+ () => {
163
+ el.style.display = check2(rbac, current.value) ? display : "none";
164
+ },
165
+ { flush: "sync" }
166
+ );
167
+ states.set(el, { binding: current, display, stop });
168
+ },
169
+ updated(el, binding) {
170
+ const state = states.get(el);
171
+ if (state) state.binding.value = binding;
172
+ },
173
+ unmounted(el) {
174
+ states.get(el)?.stop();
175
+ states.delete(el);
176
+ },
177
+ getSSRProps(binding) {
178
+ return check2(rbac, binding) ? {} : { style: { display: "none" } };
179
+ }
180
+ };
181
+ }
182
+ function createCanDirective(rbac) {
183
+ return createVisibilityDirective(rbac, (r, { value, modifiers }) => {
184
+ const allowed = modifiers["any"] ? r.canAny(value) : r.canAll(value);
185
+ return modifiers["not"] ? !allowed : allowed;
186
+ });
187
+ }
188
+ function createRoleDirective(rbac) {
189
+ return createVisibilityDirective(rbac, (r, { value, modifiers }) => {
190
+ const allowed = modifiers["all"] ? r.hasAllRoles(value) : r.hasAnyRole(value);
191
+ return modifiers["not"] ? !allowed : allowed;
192
+ });
193
+ }
194
+
195
+ // src/plugin.ts
196
+ function createRbacPlugin(options = {}) {
197
+ const rbac = createRbacState(options);
198
+ return {
199
+ ...rbac,
200
+ install(app) {
201
+ app.provide(RBAC_KEY, rbac);
202
+ if (options.directives ?? true) {
203
+ app.directive("can", createCanDirective(rbac));
204
+ app.directive("role", createRoleDirective(rbac));
205
+ }
206
+ if (options.components ?? true) {
207
+ app.component("Can", Can);
208
+ app.component("HasRole", HasRole);
209
+ }
210
+ if (options.globalProperties ?? true) {
211
+ const props = app.config.globalProperties;
212
+ props.$rbac = rbac;
213
+ props.$can = rbac.can;
214
+ props.$cannot = rbac.cannot;
215
+ props.$canAny = rbac.canAny;
216
+ props.$canAll = rbac.canAll;
217
+ props.$hasRole = rbac.hasRole;
218
+ props.$hasAnyRole = rbac.hasAnyRole;
219
+ props.$hasAllRoles = rbac.hasAllRoles;
220
+ }
221
+ }
222
+ };
223
+ }
224
+
225
+ exports.Can = Can;
226
+ exports.HasRole = HasRole;
227
+ exports.RBAC_KEY = RBAC_KEY;
228
+ exports.createCanDirective = createCanDirective;
229
+ exports.createRbacPlugin = createRbacPlugin;
230
+ exports.createRbacState = createRbacState;
231
+ exports.createRoleDirective = createRoleDirective;
232
+ exports.useCan = useCan;
233
+ exports.useCanAll = useCanAll;
234
+ exports.useCanAny = useCanAny;
235
+ exports.useCannot = useCannot;
236
+ exports.useHasAllRoles = useHasAllRoles;
237
+ exports.useHasAnyRole = useHasAnyRole;
238
+ exports.useHasRole = useHasRole;
239
+ exports.useRbac = useRbac;
240
+ //# sourceMappingURL=index.cjs.map
241
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/state.ts","../src/composables.ts","../src/components.ts","../src/directives.ts","../src/plugin.ts"],"names":["shallowRef","wildcardImplies","readonly","inject","computed","toValue","defineComponent","check","watchEffect"],"mappings":";;;;;;AAyCO,IAAM,QAAA,0BAAyC,gBAAgB;AAEtE,IAAM,KAAA,GAAgC,MAAA,CAAO,MAAA,CAAO,EAAE,KAAA,EAAO,EAAC,EAAG,WAAA,EAAa,EAAC,EAAG,CAAA;AAElF,SAAS,kBAAkB,QAAA,EAAmE;AAC5F,EAAA,IAAI,CAAC,UAAU,OAAO,KAAA;AACtB,EAAA,OAAO,OAAO,MAAA,CAAO;AAAA,IACnB,KAAA,EAAO,SAAS,KAAA,CAAM,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,MAAM,CAAA;AAAA,IACzC,WAAA,EAAa,SAAS,WAAA,CAAY,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,MAAM;AAAA,GACtD,CAAA;AACH;AAEA,IAAM,MAAA,GAAS,CAAC,KAAA,KAAA,CACb,OAAO,KAAA,KAAU,WAAW,CAAC,KAAK,CAAA,GAAI,CAAC,GAAG,KAAK,GAAG,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,EAAM,EAAE,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,KAAM,EAAE,CAAA;AAGhG,IAAM,UAAA,GAAa,CAAC,KAAA,KAA8B,MAAA,CAAO,KAAK,CAAA,CAAE,OAAA,CAAQ,CAAC,CAAA,KAAM,MAAA,CAAO,CAAA,CAAE,KAAA,CAAM,GAAG,CAAC,CAAC,CAAA;AAG5F,SAAS,eAAA,CAAgB,OAAA,GAA4B,EAAC,EAAY;AACvE,EAAA,MAAM,KAAA,GAAQA,cAAA,CAAmC,iBAAA,CAAk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,KAAA,CAAM,cAAc,IAAA,CAAK,UAAA;AACzB,QAAA,KAAA,CAAM,eAAe,IAAA,CAAK,WAAA;AAAA,MAC5B;AAAA,IACF;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["import { wildcardImplies, type RbacSnapshot } from '@anievo-id/rbac-evolution'\nimport { type DeepReadonly, type InjectionKey, type Ref, readonly, shallowRef } from 'vue'\n\n/** A permission or role name, or a list of them. */\nexport type NameList = string | readonly string[]\n\nexport interface RbacStateOptions {\n /** Initial snapshot, usually `await rbac.for(user).snapshot()` sent by the server. `null` = guest. */\n snapshot?: RbacSnapshot | null\n /** Match permissions with wildcard semantics (`articles.*` covers `articles.edit`). Default: `false`. */\n wildcard?: boolean\n /** Roles that pass every permission check, like a `Gate::before` super-admin rule. Default: `[]`. */\n superAdminRoles?: readonly string[]\n}\n\n/**\n * Client-side, reactive view of the current user's roles & permissions.\n *\n * Every check reads reactive state, so calling it inside `computed`, a template\n * or a render function re-runs when {@link VueRbac.setSnapshot} is called.\n *\n * This is for UI only: the server must always enforce authorization.\n */\nexport interface VueRbac {\n /** Current snapshot (read-only, reactive). */\n readonly snapshot: Readonly<Ref<DeepReadonly<RbacSnapshot>>>\n /** Replaces the snapshot, e.g. after login (`snapshot`) or logout (`null`). */\n setSnapshot(snapshot: RbacSnapshot | null): void\n /** `true` if the user has the permission (or, for a list, ALL of them). */\n can(permission: NameList): boolean\n cannot(permission: NameList): boolean\n canAny(permissions: NameList): boolean\n canAll(permissions: NameList): boolean\n /** `true` if the user has the role, or ANY of the roles. Supports `'writer|editor'`. */\n hasRole(roles: NameList): boolean\n hasAnyRole(roles: NameList): boolean\n hasAllRoles(roles: NameList): boolean\n /** `true` if the user has one of the configured `superAdminRoles`. */\n isSuperAdmin(): boolean\n}\n\nexport const RBAC_KEY: InjectionKey<VueRbac> = Symbol('rbac-evolution')\n\nconst EMPTY: Readonly<RbacSnapshot> = Object.freeze({ roles: [], permissions: [] })\n\nfunction normalizeSnapshot(snapshot: RbacSnapshot | null | undefined): Readonly<RbacSnapshot> {\n if (!snapshot) return EMPTY\n return Object.freeze({\n roles: snapshot.roles.map((r) => r.trim()),\n permissions: snapshot.permissions.map((p) => p.trim()),\n })\n}\n\nconst toList = (value: NameList): string[] =>\n (typeof value === 'string' ? [value] : [...value]).map((v) => v.trim()).filter((v) => v !== '')\n\n/** Like {@link toList}, but also splits spatie-style pipes: `'writer|editor'`. */\nconst toRoleList = (value: NameList): string[] => toList(value).flatMap((v) => toList(v.split('|')))\n\n/** Creates the reactive RBAC state without installing it (used by `createRbacPlugin`). */\nexport function createRbacState(options: RbacStateOptions = {}): VueRbac {\n const state = shallowRef<Readonly<RbacSnapshot>>(normalizeSnapshot(options.snapshot))\n const wildcard = options.wildcard ?? false\n const superAdminRoles = toList(options.superAdminRoles ?? [])\n\n const matches = (granted: readonly string[], required: string): boolean => {\n if (!wildcard) return granted.includes(required)\n return granted.some((pattern) => {\n try {\n return wildcardImplies(pattern, required)\n } catch {\n return false\n }\n })\n }\n\n const isSuperAdmin = (): boolean => superAdminRoles.some((r) => state.value.roles.includes(r))\n\n const canAny = (permissions: NameList): boolean => {\n const { permissions: granted } = state.value\n if (isSuperAdmin()) return toList(permissions).length > 0\n return toList(permissions).some((p) => matches(granted, p))\n }\n\n const canAll = (permissions: NameList): boolean => {\n const { permissions: granted } = state.value\n const wanted = toList(permissions)\n if (wanted.length === 0) return false\n if (isSuperAdmin()) return true\n return wanted.every((p) => matches(granted, p))\n }\n\n const hasAnyRole = (roles: NameList): boolean => {\n const mine = state.value.roles\n return toRoleList(roles).some((r) => mine.includes(r))\n }\n\n const hasAllRoles = (roles: NameList): boolean => {\n const mine = state.value.roles\n const wanted = toRoleList(roles)\n return wanted.length > 0 && wanted.every((r) => mine.includes(r))\n }\n\n return {\n snapshot: readonly(state),\n setSnapshot(snapshot) {\n state.value = normalizeSnapshot(snapshot)\n },\n can: canAll,\n cannot: (permission) => !canAll(permission),\n canAny,\n canAll,\n hasRole: hasAnyRole,\n hasAnyRole,\n hasAllRoles,\n isSuperAdmin,\n }\n}\n","import { type ComputedRef, computed, inject, type MaybeRefOrGetter, toValue } from 'vue'\nimport { type NameList, RBAC_KEY, type VueRbac } from './state'\n\n/** Returns the RBAC instance installed with `app.use(createRbacPlugin(...))`. */\nexport function useRbac(): VueRbac {\n const rbac = inject(RBAC_KEY, null)\n if (!rbac) {\n throw new Error('[rbac-evolution] No RBAC instance found. Did you call `app.use(createRbacPlugin(...))`?')\n }\n return rbac\n}\n\nconst check =\n (pick: (rbac: VueRbac) => (names: NameList) => boolean) =>\n (names: MaybeRefOrGetter<NameList>): ComputedRef<boolean> => {\n const rbac = useRbac()\n const fn = pick(rbac)\n return computed(() => fn(toValue(names)))\n }\n\n/** Reactive permission check. A list means ALL of them. Accepts a ref or getter. */\nexport const useCan = check((rbac) => rbac.can)\nexport const useCannot = check((rbac) => rbac.cannot)\nexport const useCanAny = check((rbac) => rbac.canAny)\nexport const useCanAll = check((rbac) => rbac.canAll)\n/** Reactive role check. A list or `'a|b'` means ANY of them. */\nexport const useHasRole = check((rbac) => rbac.hasRole)\nexport const useHasAnyRole = check((rbac) => rbac.hasAnyRole)\nexport const useHasAllRoles = check((rbac) => rbac.hasAllRoles)\n","import { defineComponent, type PropType, type SlotsType, type VNode } from 'vue'\nimport { useRbac } from './composables'\nimport type { NameList } from './state'\n\ntype Slots = SlotsType<{ default?: () => VNode[]; fallback?: () => VNode[] }>\n\nconst nameList = { type: [String, Array] as PropType<NameList>, default: undefined }\n\n/**\n * Renders the default slot when the user has the permission(s), otherwise the `#fallback` slot.\n *\n * ```vue\n * <Can permission=\"edit articles\">...</Can>\n * <Can :any-of=\"['edit articles', 'delete articles']\">...<template #fallback>No access</template></Can>\n * <Can :all-of=\"['a', 'b']\">...</Can>\n * ```\n */\nexport const Can = defineComponent({\n name: 'Can',\n props: {\n permission: nameList,\n anyOf: nameList,\n allOf: nameList,\n not: { type: Boolean, default: false },\n },\n slots: Object as Slots,\n setup(props, { slots }) {\n const rbac = useRbac()\n return () => {\n let allowed = true\n let checked = false\n if (props.permission !== undefined) {\n checked = true\n allowed &&= rbac.canAll(props.permission)\n }\n if (props.allOf !== undefined) {\n checked = true\n allowed &&= rbac.canAll(props.allOf)\n }\n if (props.anyOf !== undefined) {\n checked = true\n allowed &&= rbac.canAny(props.anyOf)\n }\n const pass = checked && allowed !== props.not\n return (pass ? slots.default?.() : slots.fallback?.()) ?? null\n }\n },\n})\n\n/**\n * Renders the default slot when the user has the role(s), otherwise the `#fallback` slot.\n *\n * ```vue\n * <HasRole role=\"admin\">...</HasRole>\n * <HasRole role=\"writer|editor\">...</HasRole>\n * <HasRole :all-of=\"['writer', 'editor']\">...</HasRole>\n * ```\n */\nexport const HasRole = defineComponent({\n name: 'HasRole',\n props: {\n role: nameList,\n anyOf: nameList,\n allOf: nameList,\n not: { type: Boolean, default: false },\n },\n slots: Object as Slots,\n setup(props, { slots }) {\n const rbac = useRbac()\n return () => {\n let allowed = true\n let checked = false\n if (props.role !== undefined) {\n checked = true\n allowed &&= rbac.hasAnyRole(props.role)\n }\n if (props.anyOf !== undefined) {\n checked = true\n allowed &&= rbac.hasAnyRole(props.anyOf)\n }\n if (props.allOf !== undefined) {\n checked = true\n allowed &&= rbac.hasAllRoles(props.allOf)\n }\n const pass = checked && allowed !== props.not\n return (pass ? slots.default?.() : slots.fallback?.()) ?? null\n }\n },\n})\n","import { type Directive, type DirectiveBinding, type ShallowRef, shallowRef, watchEffect, type WatchStopHandle } from 'vue'\nimport type { NameList, VueRbac } from './state'\n\ntype Check = (rbac: VueRbac, binding: DirectiveBinding<NameList>) => boolean\n\ninterface ElementState {\n binding: ShallowRef<DirectiveBinding<NameList>>\n display: string\n stop: WatchStopHandle\n}\n\n/**\n * Builds a directive that hides its element (`display: none`, like `v-show`) when the check fails.\n * Each element gets its own effect, so it re-evaluates when the snapshot or the bound value changes.\n */\nfunction createVisibilityDirective(rbac: VueRbac, check: Check): Directive<HTMLElement, NameList> {\n const states = new WeakMap<HTMLElement, ElementState>()\n\n return {\n beforeMount(el, binding) {\n const current = shallowRef(binding)\n const display = el.style.display === 'none' ? '' : el.style.display\n const stop = watchEffect(\n () => {\n el.style.display = check(rbac, current.value) ? display : 'none'\n },\n { flush: 'sync' },\n )\n states.set(el, { binding: current, display, stop })\n },\n updated(el, binding) {\n const state = states.get(el)\n if (state) state.binding.value = binding\n },\n unmounted(el) {\n states.get(el)?.stop()\n states.delete(el)\n },\n getSSRProps(binding) {\n return check(rbac, binding) ? {} : { style: { display: 'none' } }\n },\n }\n}\n\n/**\n * `v-can=\"'edit articles'\"` — single permission.\n * `v-can=\"['a', 'b']\"` / `v-can.all=\"[...]\"` — all of them.\n * `v-can.any=\"[...]\"` — any of them.\n * `v-can.not=\"'x'\"` — shown only when the user does NOT have it.\n */\nexport function createCanDirective(rbac: VueRbac): Directive<HTMLElement, NameList> {\n return createVisibilityDirective(rbac, (r, { value, modifiers }) => {\n const allowed = modifiers['any'] ? r.canAny(value) : r.canAll(value)\n return modifiers['not'] ? !allowed : allowed\n })\n}\n\n/**\n * `v-role=\"'admin'\"`, `v-role=\"'writer|editor'\"`, `v-role=\"['a', 'b']\"` — any of the roles.\n * `v-role.all=\"[...]\"` — all of them. `v-role.not=\"'banned'\"` — negated.\n */\nexport function createRoleDirective(rbac: VueRbac): Directive<HTMLElement, NameList> {\n return createVisibilityDirective(rbac, (r, { value, modifiers }) => {\n const allowed = modifiers['all'] ? r.hasAllRoles(value) : r.hasAnyRole(value)\n return modifiers['not'] ? !allowed : allowed\n })\n}\n","import type { App, Plugin } from 'vue'\nimport { Can, HasRole } from './components'\nimport { createCanDirective, createRoleDirective } from './directives'\nimport { createRbacState, type NameList, RBAC_KEY, type RbacStateOptions, type VueRbac } from './state'\n\nexport interface RbacPluginOptions extends RbacStateOptions {\n /** Register `v-can` and `v-role` globally. Default: `true`. */\n directives?: boolean\n /** Register `<Can>` and `<HasRole>` globally. Default: `true`. */\n components?: boolean\n /** Add `$can`, `$canAny`, `$canAll`, `$hasRole`, `$hasAnyRole`, `$hasAllRoles`, `$rbac` to templates. Default: `true`. */\n globalProperties?: boolean\n}\n\nexport type RbacPlugin = VueRbac & Plugin\n\n/**\n * Creates the Vue plugin. The returned object is also the RBAC instance, so it can be used\n * outside components (router guards, stores):\n *\n * ```ts\n * export const rbac = createRbacPlugin({ snapshot: window.__RBAC__, wildcard: true })\n * app.use(rbac)\n * // later, after login:\n * rbac.setSnapshot(await api.get('/me/permissions'))\n * ```\n */\nexport function createRbacPlugin(options: RbacPluginOptions = {}): RbacPlugin {\n const rbac = createRbacState(options)\n\n return {\n ...rbac,\n install(app: App) {\n app.provide(RBAC_KEY, rbac)\n\n if (options.directives ?? true) {\n app.directive('can', createCanDirective(rbac))\n app.directive('role', createRoleDirective(rbac))\n }\n\n if (options.components ?? true) {\n app.component('Can', Can)\n app.component('HasRole', HasRole)\n }\n\n if (options.globalProperties ?? true) {\n const props = app.config.globalProperties\n props.$rbac = rbac\n props.$can = rbac.can\n props.$cannot = rbac.cannot\n props.$canAny = rbac.canAny\n props.$canAll = rbac.canAll\n props.$hasRole = rbac.hasRole\n props.$hasAnyRole = rbac.hasAnyRole\n props.$hasAllRoles = rbac.hasAllRoles\n }\n },\n }\n}\n\ndeclare module 'vue' {\n interface ComponentCustomProperties {\n $rbac: VueRbac\n $can: (permission: NameList) => boolean\n $cannot: (permission: NameList) => boolean\n $canAny: (permissions: NameList) => boolean\n $canAll: (permissions: NameList) => boolean\n $hasRole: (roles: NameList) => boolean\n $hasAnyRole: (roles: NameList) => boolean\n $hasAllRoles: (roles: NameList) => boolean\n }\n\n interface GlobalComponents {\n Can: typeof Can\n HasRole: typeof HasRole\n }\n\n interface GlobalDirectives {\n vCan: ReturnType<typeof createCanDirective>\n vRole: ReturnType<typeof createRoleDirective>\n }\n}\n"]}
@@ -0,0 +1,219 @@
1
+ import * as vue from 'vue';
2
+ import { Ref, DeepReadonly, InjectionKey, PropType, VNode, SlotsType, Directive, Plugin, MaybeRefOrGetter, ComputedRef } from 'vue';
3
+ import { RbacSnapshot } from '@anievo-id/rbac-evolution';
4
+ export { RbacSnapshot } from '@anievo-id/rbac-evolution';
5
+
6
+ /** A permission or role name, or a list of them. */
7
+ type NameList = string | readonly string[];
8
+ interface RbacStateOptions {
9
+ /** Initial snapshot, usually `await rbac.for(user).snapshot()` sent by the server. `null` = guest. */
10
+ snapshot?: RbacSnapshot | null;
11
+ /** Match permissions with wildcard semantics (`articles.*` covers `articles.edit`). Default: `false`. */
12
+ wildcard?: boolean;
13
+ /** Roles that pass every permission check, like a `Gate::before` super-admin rule. Default: `[]`. */
14
+ superAdminRoles?: readonly string[];
15
+ }
16
+ /**
17
+ * Client-side, reactive view of the current user's roles & permissions.
18
+ *
19
+ * Every check reads reactive state, so calling it inside `computed`, a template
20
+ * or a render function re-runs when {@link VueRbac.setSnapshot} is called.
21
+ *
22
+ * This is for UI only: the server must always enforce authorization.
23
+ */
24
+ interface VueRbac {
25
+ /** Current snapshot (read-only, reactive). */
26
+ readonly snapshot: Readonly<Ref<DeepReadonly<RbacSnapshot>>>;
27
+ /** Replaces the snapshot, e.g. after login (`snapshot`) or logout (`null`). */
28
+ setSnapshot(snapshot: RbacSnapshot | null): void;
29
+ /** `true` if the user has the permission (or, for a list, ALL of them). */
30
+ can(permission: NameList): boolean;
31
+ cannot(permission: NameList): boolean;
32
+ canAny(permissions: NameList): boolean;
33
+ canAll(permissions: NameList): boolean;
34
+ /** `true` if the user has the role, or ANY of the roles. Supports `'writer|editor'`. */
35
+ hasRole(roles: NameList): boolean;
36
+ hasAnyRole(roles: NameList): boolean;
37
+ hasAllRoles(roles: NameList): boolean;
38
+ /** `true` if the user has one of the configured `superAdminRoles`. */
39
+ isSuperAdmin(): boolean;
40
+ }
41
+ declare const RBAC_KEY: InjectionKey<VueRbac>;
42
+ /** Creates the reactive RBAC state without installing it (used by `createRbacPlugin`). */
43
+ declare function createRbacState(options?: RbacStateOptions): VueRbac;
44
+
45
+ type Slots = SlotsType<{
46
+ default?: () => VNode[];
47
+ fallback?: () => VNode[];
48
+ }>;
49
+ /**
50
+ * Renders the default slot when the user has the permission(s), otherwise the `#fallback` slot.
51
+ *
52
+ * ```vue
53
+ * <Can permission="edit articles">...</Can>
54
+ * <Can :any-of="['edit articles', 'delete articles']">...<template #fallback>No access</template></Can>
55
+ * <Can :all-of="['a', 'b']">...</Can>
56
+ * ```
57
+ */
58
+ declare const Can: vue.DefineComponent<vue.ExtractPropTypes<{
59
+ permission: {
60
+ type: PropType<NameList>;
61
+ default: undefined;
62
+ };
63
+ anyOf: {
64
+ type: PropType<NameList>;
65
+ default: undefined;
66
+ };
67
+ allOf: {
68
+ type: PropType<NameList>;
69
+ default: undefined;
70
+ };
71
+ not: {
72
+ type: BooleanConstructor;
73
+ default: boolean;
74
+ };
75
+ }>, () => VNode<vue.RendererNode, vue.RendererElement, {
76
+ [key: string]: any;
77
+ }>[] | null, {}, {}, {}, vue.ComponentOptionsMixin, vue.ComponentOptionsMixin, {}, string, vue.PublicProps, Readonly<vue.ExtractPropTypes<{
78
+ permission: {
79
+ type: PropType<NameList>;
80
+ default: undefined;
81
+ };
82
+ anyOf: {
83
+ type: PropType<NameList>;
84
+ default: undefined;
85
+ };
86
+ allOf: {
87
+ type: PropType<NameList>;
88
+ default: undefined;
89
+ };
90
+ not: {
91
+ type: BooleanConstructor;
92
+ default: boolean;
93
+ };
94
+ }>> & Readonly<{}>, {
95
+ permission: NameList;
96
+ anyOf: NameList;
97
+ allOf: NameList;
98
+ not: boolean;
99
+ }, Slots, {}, {}, string, vue.ComponentProvideOptions, true, {}, any>;
100
+ /**
101
+ * Renders the default slot when the user has the role(s), otherwise the `#fallback` slot.
102
+ *
103
+ * ```vue
104
+ * <HasRole role="admin">...</HasRole>
105
+ * <HasRole role="writer|editor">...</HasRole>
106
+ * <HasRole :all-of="['writer', 'editor']">...</HasRole>
107
+ * ```
108
+ */
109
+ declare const HasRole: vue.DefineComponent<vue.ExtractPropTypes<{
110
+ role: {
111
+ type: PropType<NameList>;
112
+ default: undefined;
113
+ };
114
+ anyOf: {
115
+ type: PropType<NameList>;
116
+ default: undefined;
117
+ };
118
+ allOf: {
119
+ type: PropType<NameList>;
120
+ default: undefined;
121
+ };
122
+ not: {
123
+ type: BooleanConstructor;
124
+ default: boolean;
125
+ };
126
+ }>, () => VNode<vue.RendererNode, vue.RendererElement, {
127
+ [key: string]: any;
128
+ }>[] | null, {}, {}, {}, vue.ComponentOptionsMixin, vue.ComponentOptionsMixin, {}, string, vue.PublicProps, Readonly<vue.ExtractPropTypes<{
129
+ role: {
130
+ type: PropType<NameList>;
131
+ default: undefined;
132
+ };
133
+ anyOf: {
134
+ type: PropType<NameList>;
135
+ default: undefined;
136
+ };
137
+ allOf: {
138
+ type: PropType<NameList>;
139
+ default: undefined;
140
+ };
141
+ not: {
142
+ type: BooleanConstructor;
143
+ default: boolean;
144
+ };
145
+ }>> & Readonly<{}>, {
146
+ anyOf: NameList;
147
+ allOf: NameList;
148
+ not: boolean;
149
+ role: NameList;
150
+ }, Slots, {}, {}, string, vue.ComponentProvideOptions, true, {}, any>;
151
+
152
+ /**
153
+ * `v-can="'edit articles'"` — single permission.
154
+ * `v-can="['a', 'b']"` / `v-can.all="[...]"` — all of them.
155
+ * `v-can.any="[...]"` — any of them.
156
+ * `v-can.not="'x'"` — shown only when the user does NOT have it.
157
+ */
158
+ declare function createCanDirective(rbac: VueRbac): Directive<HTMLElement, NameList>;
159
+ /**
160
+ * `v-role="'admin'"`, `v-role="'writer|editor'"`, `v-role="['a', 'b']"` — any of the roles.
161
+ * `v-role.all="[...]"` — all of them. `v-role.not="'banned'"` — negated.
162
+ */
163
+ declare function createRoleDirective(rbac: VueRbac): Directive<HTMLElement, NameList>;
164
+
165
+ interface RbacPluginOptions extends RbacStateOptions {
166
+ /** Register `v-can` and `v-role` globally. Default: `true`. */
167
+ directives?: boolean;
168
+ /** Register `<Can>` and `<HasRole>` globally. Default: `true`. */
169
+ components?: boolean;
170
+ /** Add `$can`, `$canAny`, `$canAll`, `$hasRole`, `$hasAnyRole`, `$hasAllRoles`, `$rbac` to templates. Default: `true`. */
171
+ globalProperties?: boolean;
172
+ }
173
+ type RbacPlugin = VueRbac & Plugin;
174
+ /**
175
+ * Creates the Vue plugin. The returned object is also the RBAC instance, so it can be used
176
+ * outside components (router guards, stores):
177
+ *
178
+ * ```ts
179
+ * export const rbac = createRbacPlugin({ snapshot: window.__RBAC__, wildcard: true })
180
+ * app.use(rbac)
181
+ * // later, after login:
182
+ * rbac.setSnapshot(await api.get('/me/permissions'))
183
+ * ```
184
+ */
185
+ declare function createRbacPlugin(options?: RbacPluginOptions): RbacPlugin;
186
+ declare module 'vue' {
187
+ interface ComponentCustomProperties {
188
+ $rbac: VueRbac;
189
+ $can: (permission: NameList) => boolean;
190
+ $cannot: (permission: NameList) => boolean;
191
+ $canAny: (permissions: NameList) => boolean;
192
+ $canAll: (permissions: NameList) => boolean;
193
+ $hasRole: (roles: NameList) => boolean;
194
+ $hasAnyRole: (roles: NameList) => boolean;
195
+ $hasAllRoles: (roles: NameList) => boolean;
196
+ }
197
+ interface GlobalComponents {
198
+ Can: typeof Can;
199
+ HasRole: typeof HasRole;
200
+ }
201
+ interface GlobalDirectives {
202
+ vCan: ReturnType<typeof createCanDirective>;
203
+ vRole: ReturnType<typeof createRoleDirective>;
204
+ }
205
+ }
206
+
207
+ /** Returns the RBAC instance installed with `app.use(createRbacPlugin(...))`. */
208
+ declare function useRbac(): VueRbac;
209
+ /** Reactive permission check. A list means ALL of them. Accepts a ref or getter. */
210
+ declare const useCan: (names: MaybeRefOrGetter<NameList>) => ComputedRef<boolean>;
211
+ declare const useCannot: (names: MaybeRefOrGetter<NameList>) => ComputedRef<boolean>;
212
+ declare const useCanAny: (names: MaybeRefOrGetter<NameList>) => ComputedRef<boolean>;
213
+ declare const useCanAll: (names: MaybeRefOrGetter<NameList>) => ComputedRef<boolean>;
214
+ /** Reactive role check. A list or `'a|b'` means ANY of them. */
215
+ declare const useHasRole: (names: MaybeRefOrGetter<NameList>) => ComputedRef<boolean>;
216
+ declare const useHasAnyRole: (names: MaybeRefOrGetter<NameList>) => ComputedRef<boolean>;
217
+ declare const useHasAllRoles: (names: MaybeRefOrGetter<NameList>) => ComputedRef<boolean>;
218
+
219
+ export { Can, HasRole, type NameList, RBAC_KEY, type RbacPlugin, type RbacPluginOptions, type RbacStateOptions, type VueRbac, createCanDirective, createRbacPlugin, createRbacState, createRoleDirective, useCan, useCanAll, useCanAny, useCannot, useHasAllRoles, useHasAnyRole, useHasRole, useRbac };
@@ -0,0 +1,219 @@
1
+ import * as vue from 'vue';
2
+ import { Ref, DeepReadonly, InjectionKey, PropType, VNode, SlotsType, Directive, Plugin, MaybeRefOrGetter, ComputedRef } from 'vue';
3
+ import { RbacSnapshot } from '@anievo-id/rbac-evolution';
4
+ export { RbacSnapshot } from '@anievo-id/rbac-evolution';
5
+
6
+ /** A permission or role name, or a list of them. */
7
+ type NameList = string | readonly string[];
8
+ interface RbacStateOptions {
9
+ /** Initial snapshot, usually `await rbac.for(user).snapshot()` sent by the server. `null` = guest. */
10
+ snapshot?: RbacSnapshot | null;
11
+ /** Match permissions with wildcard semantics (`articles.*` covers `articles.edit`). Default: `false`. */
12
+ wildcard?: boolean;
13
+ /** Roles that pass every permission check, like a `Gate::before` super-admin rule. Default: `[]`. */
14
+ superAdminRoles?: readonly string[];
15
+ }
16
+ /**
17
+ * Client-side, reactive view of the current user's roles & permissions.
18
+ *
19
+ * Every check reads reactive state, so calling it inside `computed`, a template
20
+ * or a render function re-runs when {@link VueRbac.setSnapshot} is called.
21
+ *
22
+ * This is for UI only: the server must always enforce authorization.
23
+ */
24
+ interface VueRbac {
25
+ /** Current snapshot (read-only, reactive). */
26
+ readonly snapshot: Readonly<Ref<DeepReadonly<RbacSnapshot>>>;
27
+ /** Replaces the snapshot, e.g. after login (`snapshot`) or logout (`null`). */
28
+ setSnapshot(snapshot: RbacSnapshot | null): void;
29
+ /** `true` if the user has the permission (or, for a list, ALL of them). */
30
+ can(permission: NameList): boolean;
31
+ cannot(permission: NameList): boolean;
32
+ canAny(permissions: NameList): boolean;
33
+ canAll(permissions: NameList): boolean;
34
+ /** `true` if the user has the role, or ANY of the roles. Supports `'writer|editor'`. */
35
+ hasRole(roles: NameList): boolean;
36
+ hasAnyRole(roles: NameList): boolean;
37
+ hasAllRoles(roles: NameList): boolean;
38
+ /** `true` if the user has one of the configured `superAdminRoles`. */
39
+ isSuperAdmin(): boolean;
40
+ }
41
+ declare const RBAC_KEY: InjectionKey<VueRbac>;
42
+ /** Creates the reactive RBAC state without installing it (used by `createRbacPlugin`). */
43
+ declare function createRbacState(options?: RbacStateOptions): VueRbac;
44
+
45
+ type Slots = SlotsType<{
46
+ default?: () => VNode[];
47
+ fallback?: () => VNode[];
48
+ }>;
49
+ /**
50
+ * Renders the default slot when the user has the permission(s), otherwise the `#fallback` slot.
51
+ *
52
+ * ```vue
53
+ * <Can permission="edit articles">...</Can>
54
+ * <Can :any-of="['edit articles', 'delete articles']">...<template #fallback>No access</template></Can>
55
+ * <Can :all-of="['a', 'b']">...</Can>
56
+ * ```
57
+ */
58
+ declare const Can: vue.DefineComponent<vue.ExtractPropTypes<{
59
+ permission: {
60
+ type: PropType<NameList>;
61
+ default: undefined;
62
+ };
63
+ anyOf: {
64
+ type: PropType<NameList>;
65
+ default: undefined;
66
+ };
67
+ allOf: {
68
+ type: PropType<NameList>;
69
+ default: undefined;
70
+ };
71
+ not: {
72
+ type: BooleanConstructor;
73
+ default: boolean;
74
+ };
75
+ }>, () => VNode<vue.RendererNode, vue.RendererElement, {
76
+ [key: string]: any;
77
+ }>[] | null, {}, {}, {}, vue.ComponentOptionsMixin, vue.ComponentOptionsMixin, {}, string, vue.PublicProps, Readonly<vue.ExtractPropTypes<{
78
+ permission: {
79
+ type: PropType<NameList>;
80
+ default: undefined;
81
+ };
82
+ anyOf: {
83
+ type: PropType<NameList>;
84
+ default: undefined;
85
+ };
86
+ allOf: {
87
+ type: PropType<NameList>;
88
+ default: undefined;
89
+ };
90
+ not: {
91
+ type: BooleanConstructor;
92
+ default: boolean;
93
+ };
94
+ }>> & Readonly<{}>, {
95
+ permission: NameList;
96
+ anyOf: NameList;
97
+ allOf: NameList;
98
+ not: boolean;
99
+ }, Slots, {}, {}, string, vue.ComponentProvideOptions, true, {}, any>;
100
+ /**
101
+ * Renders the default slot when the user has the role(s), otherwise the `#fallback` slot.
102
+ *
103
+ * ```vue
104
+ * <HasRole role="admin">...</HasRole>
105
+ * <HasRole role="writer|editor">...</HasRole>
106
+ * <HasRole :all-of="['writer', 'editor']">...</HasRole>
107
+ * ```
108
+ */
109
+ declare const HasRole: vue.DefineComponent<vue.ExtractPropTypes<{
110
+ role: {
111
+ type: PropType<NameList>;
112
+ default: undefined;
113
+ };
114
+ anyOf: {
115
+ type: PropType<NameList>;
116
+ default: undefined;
117
+ };
118
+ allOf: {
119
+ type: PropType<NameList>;
120
+ default: undefined;
121
+ };
122
+ not: {
123
+ type: BooleanConstructor;
124
+ default: boolean;
125
+ };
126
+ }>, () => VNode<vue.RendererNode, vue.RendererElement, {
127
+ [key: string]: any;
128
+ }>[] | null, {}, {}, {}, vue.ComponentOptionsMixin, vue.ComponentOptionsMixin, {}, string, vue.PublicProps, Readonly<vue.ExtractPropTypes<{
129
+ role: {
130
+ type: PropType<NameList>;
131
+ default: undefined;
132
+ };
133
+ anyOf: {
134
+ type: PropType<NameList>;
135
+ default: undefined;
136
+ };
137
+ allOf: {
138
+ type: PropType<NameList>;
139
+ default: undefined;
140
+ };
141
+ not: {
142
+ type: BooleanConstructor;
143
+ default: boolean;
144
+ };
145
+ }>> & Readonly<{}>, {
146
+ anyOf: NameList;
147
+ allOf: NameList;
148
+ not: boolean;
149
+ role: NameList;
150
+ }, Slots, {}, {}, string, vue.ComponentProvideOptions, true, {}, any>;
151
+
152
+ /**
153
+ * `v-can="'edit articles'"` — single permission.
154
+ * `v-can="['a', 'b']"` / `v-can.all="[...]"` — all of them.
155
+ * `v-can.any="[...]"` — any of them.
156
+ * `v-can.not="'x'"` — shown only when the user does NOT have it.
157
+ */
158
+ declare function createCanDirective(rbac: VueRbac): Directive<HTMLElement, NameList>;
159
+ /**
160
+ * `v-role="'admin'"`, `v-role="'writer|editor'"`, `v-role="['a', 'b']"` — any of the roles.
161
+ * `v-role.all="[...]"` — all of them. `v-role.not="'banned'"` — negated.
162
+ */
163
+ declare function createRoleDirective(rbac: VueRbac): Directive<HTMLElement, NameList>;
164
+
165
+ interface RbacPluginOptions extends RbacStateOptions {
166
+ /** Register `v-can` and `v-role` globally. Default: `true`. */
167
+ directives?: boolean;
168
+ /** Register `<Can>` and `<HasRole>` globally. Default: `true`. */
169
+ components?: boolean;
170
+ /** Add `$can`, `$canAny`, `$canAll`, `$hasRole`, `$hasAnyRole`, `$hasAllRoles`, `$rbac` to templates. Default: `true`. */
171
+ globalProperties?: boolean;
172
+ }
173
+ type RbacPlugin = VueRbac & Plugin;
174
+ /**
175
+ * Creates the Vue plugin. The returned object is also the RBAC instance, so it can be used
176
+ * outside components (router guards, stores):
177
+ *
178
+ * ```ts
179
+ * export const rbac = createRbacPlugin({ snapshot: window.__RBAC__, wildcard: true })
180
+ * app.use(rbac)
181
+ * // later, after login:
182
+ * rbac.setSnapshot(await api.get('/me/permissions'))
183
+ * ```
184
+ */
185
+ declare function createRbacPlugin(options?: RbacPluginOptions): RbacPlugin;
186
+ declare module 'vue' {
187
+ interface ComponentCustomProperties {
188
+ $rbac: VueRbac;
189
+ $can: (permission: NameList) => boolean;
190
+ $cannot: (permission: NameList) => boolean;
191
+ $canAny: (permissions: NameList) => boolean;
192
+ $canAll: (permissions: NameList) => boolean;
193
+ $hasRole: (roles: NameList) => boolean;
194
+ $hasAnyRole: (roles: NameList) => boolean;
195
+ $hasAllRoles: (roles: NameList) => boolean;
196
+ }
197
+ interface GlobalComponents {
198
+ Can: typeof Can;
199
+ HasRole: typeof HasRole;
200
+ }
201
+ interface GlobalDirectives {
202
+ vCan: ReturnType<typeof createCanDirective>;
203
+ vRole: ReturnType<typeof createRoleDirective>;
204
+ }
205
+ }
206
+
207
+ /** Returns the RBAC instance installed with `app.use(createRbacPlugin(...))`. */
208
+ declare function useRbac(): VueRbac;
209
+ /** Reactive permission check. A list means ALL of them. Accepts a ref or getter. */
210
+ declare const useCan: (names: MaybeRefOrGetter<NameList>) => ComputedRef<boolean>;
211
+ declare const useCannot: (names: MaybeRefOrGetter<NameList>) => ComputedRef<boolean>;
212
+ declare const useCanAny: (names: MaybeRefOrGetter<NameList>) => ComputedRef<boolean>;
213
+ declare const useCanAll: (names: MaybeRefOrGetter<NameList>) => ComputedRef<boolean>;
214
+ /** Reactive role check. A list or `'a|b'` means ANY of them. */
215
+ declare const useHasRole: (names: MaybeRefOrGetter<NameList>) => ComputedRef<boolean>;
216
+ declare const useHasAnyRole: (names: MaybeRefOrGetter<NameList>) => ComputedRef<boolean>;
217
+ declare const useHasAllRoles: (names: MaybeRefOrGetter<NameList>) => ComputedRef<boolean>;
218
+
219
+ export { Can, HasRole, type NameList, RBAC_KEY, type RbacPlugin, type RbacPluginOptions, type RbacStateOptions, type VueRbac, createCanDirective, createRbacPlugin, createRbacState, createRoleDirective, useCan, useCanAll, useCanAny, useCannot, useHasAllRoles, useHasAnyRole, useHasRole, useRbac };
package/dist/index.js ADDED
@@ -0,0 +1,225 @@
1
+ import { defineComponent, inject, shallowRef, readonly, computed, toValue, watchEffect } from 'vue';
2
+ import { wildcardImplies } from '@anievo-id/rbac-evolution';
3
+
4
+ // src/components.ts
5
+ var RBAC_KEY = /* @__PURE__ */ Symbol("rbac-evolution");
6
+ var EMPTY = Object.freeze({ roles: [], permissions: [] });
7
+ function normalizeSnapshot(snapshot) {
8
+ if (!snapshot) return EMPTY;
9
+ return Object.freeze({
10
+ roles: snapshot.roles.map((r) => r.trim()),
11
+ permissions: snapshot.permissions.map((p) => p.trim())
12
+ });
13
+ }
14
+ var toList = (value) => (typeof value === "string" ? [value] : [...value]).map((v) => v.trim()).filter((v) => v !== "");
15
+ var toRoleList = (value) => toList(value).flatMap((v) => toList(v.split("|")));
16
+ function createRbacState(options = {}) {
17
+ const state = shallowRef(normalizeSnapshot(options.snapshot));
18
+ const wildcard = options.wildcard ?? false;
19
+ const superAdminRoles = toList(options.superAdminRoles ?? []);
20
+ const matches = (granted, required) => {
21
+ if (!wildcard) return granted.includes(required);
22
+ return granted.some((pattern) => {
23
+ try {
24
+ return wildcardImplies(pattern, required);
25
+ } catch {
26
+ return false;
27
+ }
28
+ });
29
+ };
30
+ const isSuperAdmin = () => superAdminRoles.some((r) => state.value.roles.includes(r));
31
+ const canAny = (permissions) => {
32
+ const { permissions: granted } = state.value;
33
+ if (isSuperAdmin()) return toList(permissions).length > 0;
34
+ return toList(permissions).some((p) => matches(granted, p));
35
+ };
36
+ const canAll = (permissions) => {
37
+ const { permissions: granted } = state.value;
38
+ const wanted = toList(permissions);
39
+ if (wanted.length === 0) return false;
40
+ if (isSuperAdmin()) return true;
41
+ return wanted.every((p) => matches(granted, p));
42
+ };
43
+ const hasAnyRole = (roles) => {
44
+ const mine = state.value.roles;
45
+ return toRoleList(roles).some((r) => mine.includes(r));
46
+ };
47
+ const hasAllRoles = (roles) => {
48
+ const mine = state.value.roles;
49
+ const wanted = toRoleList(roles);
50
+ return wanted.length > 0 && wanted.every((r) => mine.includes(r));
51
+ };
52
+ return {
53
+ snapshot: readonly(state),
54
+ setSnapshot(snapshot) {
55
+ state.value = normalizeSnapshot(snapshot);
56
+ },
57
+ can: canAll,
58
+ cannot: (permission) => !canAll(permission),
59
+ canAny,
60
+ canAll,
61
+ hasRole: hasAnyRole,
62
+ hasAnyRole,
63
+ hasAllRoles,
64
+ isSuperAdmin
65
+ };
66
+ }
67
+
68
+ // src/composables.ts
69
+ function useRbac() {
70
+ const rbac = inject(RBAC_KEY, null);
71
+ if (!rbac) {
72
+ throw new Error("[rbac-evolution] No RBAC instance found. Did you call `app.use(createRbacPlugin(...))`?");
73
+ }
74
+ return rbac;
75
+ }
76
+ var check = (pick) => (names) => {
77
+ const rbac = useRbac();
78
+ const fn = pick(rbac);
79
+ return computed(() => fn(toValue(names)));
80
+ };
81
+ var useCan = check((rbac) => rbac.can);
82
+ var useCannot = check((rbac) => rbac.cannot);
83
+ var useCanAny = check((rbac) => rbac.canAny);
84
+ var useCanAll = check((rbac) => rbac.canAll);
85
+ var useHasRole = check((rbac) => rbac.hasRole);
86
+ var useHasAnyRole = check((rbac) => rbac.hasAnyRole);
87
+ var useHasAllRoles = check((rbac) => rbac.hasAllRoles);
88
+
89
+ // src/components.ts
90
+ var nameList = { type: [String, Array], default: void 0 };
91
+ var Can = defineComponent({
92
+ name: "Can",
93
+ props: {
94
+ permission: nameList,
95
+ anyOf: nameList,
96
+ allOf: nameList,
97
+ not: { type: Boolean, default: false }
98
+ },
99
+ slots: Object,
100
+ setup(props, { slots }) {
101
+ const rbac = useRbac();
102
+ return () => {
103
+ let allowed = true;
104
+ let checked = false;
105
+ if (props.permission !== void 0) {
106
+ checked = true;
107
+ allowed &&= rbac.canAll(props.permission);
108
+ }
109
+ if (props.allOf !== void 0) {
110
+ checked = true;
111
+ allowed &&= rbac.canAll(props.allOf);
112
+ }
113
+ if (props.anyOf !== void 0) {
114
+ checked = true;
115
+ allowed &&= rbac.canAny(props.anyOf);
116
+ }
117
+ const pass = checked && allowed !== props.not;
118
+ return (pass ? slots.default?.() : slots.fallback?.()) ?? null;
119
+ };
120
+ }
121
+ });
122
+ var HasRole = defineComponent({
123
+ name: "HasRole",
124
+ props: {
125
+ role: nameList,
126
+ anyOf: nameList,
127
+ allOf: nameList,
128
+ not: { type: Boolean, default: false }
129
+ },
130
+ slots: Object,
131
+ setup(props, { slots }) {
132
+ const rbac = useRbac();
133
+ return () => {
134
+ let allowed = true;
135
+ let checked = false;
136
+ if (props.role !== void 0) {
137
+ checked = true;
138
+ allowed &&= rbac.hasAnyRole(props.role);
139
+ }
140
+ if (props.anyOf !== void 0) {
141
+ checked = true;
142
+ allowed &&= rbac.hasAnyRole(props.anyOf);
143
+ }
144
+ if (props.allOf !== void 0) {
145
+ checked = true;
146
+ allowed &&= rbac.hasAllRoles(props.allOf);
147
+ }
148
+ const pass = checked && allowed !== props.not;
149
+ return (pass ? slots.default?.() : slots.fallback?.()) ?? null;
150
+ };
151
+ }
152
+ });
153
+ function createVisibilityDirective(rbac, check2) {
154
+ const states = /* @__PURE__ */ new WeakMap();
155
+ return {
156
+ beforeMount(el, binding) {
157
+ const current = shallowRef(binding);
158
+ const display = el.style.display === "none" ? "" : el.style.display;
159
+ const stop = watchEffect(
160
+ () => {
161
+ el.style.display = check2(rbac, current.value) ? display : "none";
162
+ },
163
+ { flush: "sync" }
164
+ );
165
+ states.set(el, { binding: current, display, stop });
166
+ },
167
+ updated(el, binding) {
168
+ const state = states.get(el);
169
+ if (state) state.binding.value = binding;
170
+ },
171
+ unmounted(el) {
172
+ states.get(el)?.stop();
173
+ states.delete(el);
174
+ },
175
+ getSSRProps(binding) {
176
+ return check2(rbac, binding) ? {} : { style: { display: "none" } };
177
+ }
178
+ };
179
+ }
180
+ function createCanDirective(rbac) {
181
+ return createVisibilityDirective(rbac, (r, { value, modifiers }) => {
182
+ const allowed = modifiers["any"] ? r.canAny(value) : r.canAll(value);
183
+ return modifiers["not"] ? !allowed : allowed;
184
+ });
185
+ }
186
+ function createRoleDirective(rbac) {
187
+ return createVisibilityDirective(rbac, (r, { value, modifiers }) => {
188
+ const allowed = modifiers["all"] ? r.hasAllRoles(value) : r.hasAnyRole(value);
189
+ return modifiers["not"] ? !allowed : allowed;
190
+ });
191
+ }
192
+
193
+ // src/plugin.ts
194
+ function createRbacPlugin(options = {}) {
195
+ const rbac = createRbacState(options);
196
+ return {
197
+ ...rbac,
198
+ install(app) {
199
+ app.provide(RBAC_KEY, rbac);
200
+ if (options.directives ?? true) {
201
+ app.directive("can", createCanDirective(rbac));
202
+ app.directive("role", createRoleDirective(rbac));
203
+ }
204
+ if (options.components ?? true) {
205
+ app.component("Can", Can);
206
+ app.component("HasRole", HasRole);
207
+ }
208
+ if (options.globalProperties ?? true) {
209
+ const props = app.config.globalProperties;
210
+ props.$rbac = rbac;
211
+ props.$can = rbac.can;
212
+ props.$cannot = rbac.cannot;
213
+ props.$canAny = rbac.canAny;
214
+ props.$canAll = rbac.canAll;
215
+ props.$hasRole = rbac.hasRole;
216
+ props.$hasAnyRole = rbac.hasAnyRole;
217
+ props.$hasAllRoles = rbac.hasAllRoles;
218
+ }
219
+ }
220
+ };
221
+ }
222
+
223
+ export { Can, HasRole, RBAC_KEY, createCanDirective, createRbacPlugin, createRbacState, createRoleDirective, useCan, useCanAll, useCanAny, useCannot, useHasAllRoles, useHasAnyRole, useHasRole, useRbac };
224
+ //# sourceMappingURL=index.js.map
225
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/state.ts","../src/composables.ts","../src/components.ts","../src/directives.ts","../src/plugin.ts"],"names":["check","shallowRef"],"mappings":";;;;AAyCO,IAAM,QAAA,0BAAyC,gBAAgB;AAEtE,IAAM,KAAA,GAAgC,MAAA,CAAO,MAAA,CAAO,EAAE,KAAA,EAAO,EAAC,EAAG,WAAA,EAAa,EAAC,EAAG,CAAA;AAElF,SAAS,kBAAkB,QAAA,EAAmE;AAC5F,EAAA,IAAI,CAAC,UAAU,OAAO,KAAA;AACtB,EAAA,OAAO,OAAO,MAAA,CAAO;AAAA,IACnB,KAAA,EAAO,SAAS,KAAA,CAAM,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,MAAM,CAAA;AAAA,IACzC,WAAA,EAAa,SAAS,WAAA,CAAY,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,MAAM;AAAA,GACtD,CAAA;AACH;AAEA,IAAM,MAAA,GAAS,CAAC,KAAA,KAAA,CACb,OAAO,KAAA,KAAU,WAAW,CAAC,KAAK,CAAA,GAAI,CAAC,GAAG,KAAK,GAAG,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,IA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AA,GAAQ,IAAI,MAAA,CAAO,gBAAA;AACzB,QAAA,KAAA,CAAM,KAAA,GAAQ,IAAA;AACd,QAAA,KAAA,CAAM,OAAO,IAAA,CAAK,GAAA;AAClB,QAAA,KAAA,CAAM,UAAU,IAAA,CAAK,MAAA;AACrB,QAAA,KAAA,CAAM,UAAU,IAAA,CAAK,MAAA;AACrB,QAAA,KAAA,CAAM,UAAU,IAAA,CAAK,MAAA;AACrB,QAAA,KAAA,CAAM,WAAW,IAAA,CAAK,OAAA;AACtB,QAAA,KAAA,CAAM,cAAc,IAAA,CAAK,UAAA;AACzB,QAAA,KAAA,CAAM,eAAe,IAAA,CAAK,WAAA;AAAA,MAC5B;AAAA,IACF;AAAA,GACF;AACF","file":"index.js","sourcesContent":["import { wildcardImplies, type RbacSnapshot } from '@anievo-id/rbac-evolution'\nimport { type DeepReadonly, type InjectionKey, type Ref, readonly, shallowRef } from 'vue'\n\n/** A permission or role name, or a list of them. */\nexport type NameList = string | readonly string[]\n\nexport interface RbacStateOptions {\n /** Initial snapshot, usually `await rbac.for(user).snapshot()` sent by the server. `null` = guest. */\n snapshot?: RbacSnapshot | null\n /** Match permissions with wildcard semantics (`articles.*` covers `articles.edit`). Default: `false`. */\n wildcard?: boolean\n /** Roles that pass every permission check, like a `Gate::before` super-admin rule. Default: `[]`. */\n superAdminRoles?: readonly string[]\n}\n\n/**\n * Client-side, reactive view of the current user's roles & permissions.\n *\n * Every check reads reactive state, so calling it inside `computed`, a template\n * or a render function re-runs when {@link VueRbac.setSnapshot} is called.\n *\n * This is for UI only: the server must always enforce authorization.\n */\nexport interface VueRbac {\n /** Current snapshot (read-only, reactive). */\n readonly snapshot: Readonly<Ref<DeepReadonly<RbacSnapshot>>>\n /** Replaces the snapshot, e.g. after login (`snapshot`) or logout (`null`). */\n setSnapshot(snapshot: RbacSnapshot | null): void\n /** `true` if the user has the permission (or, for a list, ALL of them). */\n can(permission: NameList): boolean\n cannot(permission: NameList): boolean\n canAny(permissions: NameList): boolean\n canAll(permissions: NameList): boolean\n /** `true` if the user has the role, or ANY of the roles. Supports `'writer|editor'`. */\n hasRole(roles: NameList): boolean\n hasAnyRole(roles: NameList): boolean\n hasAllRoles(roles: NameList): boolean\n /** `true` if the user has one of the configured `superAdminRoles`. */\n isSuperAdmin(): boolean\n}\n\nexport const RBAC_KEY: InjectionKey<VueRbac> = Symbol('rbac-evolution')\n\nconst EMPTY: Readonly<RbacSnapshot> = Object.freeze({ roles: [], permissions: [] })\n\nfunction normalizeSnapshot(snapshot: RbacSnapshot | null | undefined): Readonly<RbacSnapshot> {\n if (!snapshot) return EMPTY\n return Object.freeze({\n roles: snapshot.roles.map((r) => r.trim()),\n permissions: snapshot.permissions.map((p) => p.trim()),\n })\n}\n\nconst toList = (value: NameList): string[] =>\n (typeof value === 'string' ? [value] : [...value]).map((v) => v.trim()).filter((v) => v !== '')\n\n/** Like {@link toList}, but also splits spatie-style pipes: `'writer|editor'`. */\nconst toRoleList = (value: NameList): string[] => toList(value).flatMap((v) => toList(v.split('|')))\n\n/** Creates the reactive RBAC state without installing it (used by `createRbacPlugin`). */\nexport function createRbacState(options: RbacStateOptions = {}): VueRbac {\n const state = shallowRef<Readonly<RbacSnapshot>>(normalizeSnapshot(options.snapshot))\n const wildcard = options.wildcard ?? false\n const superAdminRoles = toList(options.superAdminRoles ?? [])\n\n const matches = (granted: readonly string[], required: string): boolean => {\n if (!wildcard) return granted.includes(required)\n return granted.some((pattern) => {\n try {\n return wildcardImplies(pattern, required)\n } catch {\n return false\n }\n })\n }\n\n const isSuperAdmin = (): boolean => superAdminRoles.some((r) => state.value.roles.includes(r))\n\n const canAny = (permissions: NameList): boolean => {\n const { permissions: granted } = state.value\n if (isSuperAdmin()) return toList(permissions).length > 0\n return toList(permissions).some((p) => matches(granted, p))\n }\n\n const canAll = (permissions: NameList): boolean => {\n const { permissions: granted } = state.value\n const wanted = toList(permissions)\n if (wanted.length === 0) return false\n if (isSuperAdmin()) return true\n return wanted.every((p) => matches(granted, p))\n }\n\n const hasAnyRole = (roles: NameList): boolean => {\n const mine = state.value.roles\n return toRoleList(roles).some((r) => mine.includes(r))\n }\n\n const hasAllRoles = (roles: NameList): boolean => {\n const mine = state.value.roles\n const wanted = toRoleList(roles)\n return wanted.length > 0 && wanted.every((r) => mine.includes(r))\n }\n\n return {\n snapshot: readonly(state),\n setSnapshot(snapshot) {\n state.value = normalizeSnapshot(snapshot)\n },\n can: canAll,\n cannot: (permission) => !canAll(permission),\n canAny,\n canAll,\n hasRole: hasAnyRole,\n hasAnyRole,\n hasAllRoles,\n isSuperAdmin,\n }\n}\n","import { type ComputedRef, computed, inject, type MaybeRefOrGetter, toValue } from 'vue'\nimport { type NameList, RBAC_KEY, type VueRbac } from './state'\n\n/** Returns the RBAC instance installed with `app.use(createRbacPlugin(...))`. */\nexport function useRbac(): VueRbac {\n const rbac = inject(RBAC_KEY, null)\n if (!rbac) {\n throw new Error('[rbac-evolution] No RBAC instance found. Did you call `app.use(createRbacPlugin(...))`?')\n }\n return rbac\n}\n\nconst check =\n (pick: (rbac: VueRbac) => (names: NameList) => boolean) =>\n (names: MaybeRefOrGetter<NameList>): ComputedRef<boolean> => {\n const rbac = useRbac()\n const fn = pick(rbac)\n return computed(() => fn(toValue(names)))\n }\n\n/** Reactive permission check. A list means ALL of them. Accepts a ref or getter. */\nexport const useCan = check((rbac) => rbac.can)\nexport const useCannot = check((rbac) => rbac.cannot)\nexport const useCanAny = check((rbac) => rbac.canAny)\nexport const useCanAll = check((rbac) => rbac.canAll)\n/** Reactive role check. A list or `'a|b'` means ANY of them. */\nexport const useHasRole = check((rbac) => rbac.hasRole)\nexport const useHasAnyRole = check((rbac) => rbac.hasAnyRole)\nexport const useHasAllRoles = check((rbac) => rbac.hasAllRoles)\n","import { defineComponent, type PropType, type SlotsType, type VNode } from 'vue'\nimport { useRbac } from './composables'\nimport type { NameList } from './state'\n\ntype Slots = SlotsType<{ default?: () => VNode[]; fallback?: () => VNode[] }>\n\nconst nameList = { type: [String, Array] as PropType<NameList>, default: undefined }\n\n/**\n * Renders the default slot when the user has the permission(s), otherwise the `#fallback` slot.\n *\n * ```vue\n * <Can permission=\"edit articles\">...</Can>\n * <Can :any-of=\"['edit articles', 'delete articles']\">...<template #fallback>No access</template></Can>\n * <Can :all-of=\"['a', 'b']\">...</Can>\n * ```\n */\nexport const Can = defineComponent({\n name: 'Can',\n props: {\n permission: nameList,\n anyOf: nameList,\n allOf: nameList,\n not: { type: Boolean, default: false },\n },\n slots: Object as Slots,\n setup(props, { slots }) {\n const rbac = useRbac()\n return () => {\n let allowed = true\n let checked = false\n if (props.permission !== undefined) {\n checked = true\n allowed &&= rbac.canAll(props.permission)\n }\n if (props.allOf !== undefined) {\n checked = true\n allowed &&= rbac.canAll(props.allOf)\n }\n if (props.anyOf !== undefined) {\n checked = true\n allowed &&= rbac.canAny(props.anyOf)\n }\n const pass = checked && allowed !== props.not\n return (pass ? slots.default?.() : slots.fallback?.()) ?? null\n }\n },\n})\n\n/**\n * Renders the default slot when the user has the role(s), otherwise the `#fallback` slot.\n *\n * ```vue\n * <HasRole role=\"admin\">...</HasRole>\n * <HasRole role=\"writer|editor\">...</HasRole>\n * <HasRole :all-of=\"['writer', 'editor']\">...</HasRole>\n * ```\n */\nexport const HasRole = defineComponent({\n name: 'HasRole',\n props: {\n role: nameList,\n anyOf: nameList,\n allOf: nameList,\n not: { type: Boolean, default: false },\n },\n slots: Object as Slots,\n setup(props, { slots }) {\n const rbac = useRbac()\n return () => {\n let allowed = true\n let checked = false\n if (props.role !== undefined) {\n checked = true\n allowed &&= rbac.hasAnyRole(props.role)\n }\n if (props.anyOf !== undefined) {\n checked = true\n allowed &&= rbac.hasAnyRole(props.anyOf)\n }\n if (props.allOf !== undefined) {\n checked = true\n allowed &&= rbac.hasAllRoles(props.allOf)\n }\n const pass = checked && allowed !== props.not\n return (pass ? slots.default?.() : slots.fallback?.()) ?? null\n }\n },\n})\n","import { type Directive, type DirectiveBinding, type ShallowRef, shallowRef, watchEffect, type WatchStopHandle } from 'vue'\nimport type { NameList, VueRbac } from './state'\n\ntype Check = (rbac: VueRbac, binding: DirectiveBinding<NameList>) => boolean\n\ninterface ElementState {\n binding: ShallowRef<DirectiveBinding<NameList>>\n display: string\n stop: WatchStopHandle\n}\n\n/**\n * Builds a directive that hides its element (`display: none`, like `v-show`) when the check fails.\n * Each element gets its own effect, so it re-evaluates when the snapshot or the bound value changes.\n */\nfunction createVisibilityDirective(rbac: VueRbac, check: Check): Directive<HTMLElement, NameList> {\n const states = new WeakMap<HTMLElement, ElementState>()\n\n return {\n beforeMount(el, binding) {\n const current = shallowRef(binding)\n const display = el.style.display === 'none' ? '' : el.style.display\n const stop = watchEffect(\n () => {\n el.style.display = check(rbac, current.value) ? display : 'none'\n },\n { flush: 'sync' },\n )\n states.set(el, { binding: current, display, stop })\n },\n updated(el, binding) {\n const state = states.get(el)\n if (state) state.binding.value = binding\n },\n unmounted(el) {\n states.get(el)?.stop()\n states.delete(el)\n },\n getSSRProps(binding) {\n return check(rbac, binding) ? {} : { style: { display: 'none' } }\n },\n }\n}\n\n/**\n * `v-can=\"'edit articles'\"` — single permission.\n * `v-can=\"['a', 'b']\"` / `v-can.all=\"[...]\"` — all of them.\n * `v-can.any=\"[...]\"` — any of them.\n * `v-can.not=\"'x'\"` — shown only when the user does NOT have it.\n */\nexport function createCanDirective(rbac: VueRbac): Directive<HTMLElement, NameList> {\n return createVisibilityDirective(rbac, (r, { value, modifiers }) => {\n const allowed = modifiers['any'] ? r.canAny(value) : r.canAll(value)\n return modifiers['not'] ? !allowed : allowed\n })\n}\n\n/**\n * `v-role=\"'admin'\"`, `v-role=\"'writer|editor'\"`, `v-role=\"['a', 'b']\"` — any of the roles.\n * `v-role.all=\"[...]\"` — all of them. `v-role.not=\"'banned'\"` — negated.\n */\nexport function createRoleDirective(rbac: VueRbac): Directive<HTMLElement, NameList> {\n return createVisibilityDirective(rbac, (r, { value, modifiers }) => {\n const allowed = modifiers['all'] ? r.hasAllRoles(value) : r.hasAnyRole(value)\n return modifiers['not'] ? !allowed : allowed\n })\n}\n","import type { App, Plugin } from 'vue'\nimport { Can, HasRole } from './components'\nimport { createCanDirective, createRoleDirective } from './directives'\nimport { createRbacState, type NameList, RBAC_KEY, type RbacStateOptions, type VueRbac } from './state'\n\nexport interface RbacPluginOptions extends RbacStateOptions {\n /** Register `v-can` and `v-role` globally. Default: `true`. */\n directives?: boolean\n /** Register `<Can>` and `<HasRole>` globally. Default: `true`. */\n components?: boolean\n /** Add `$can`, `$canAny`, `$canAll`, `$hasRole`, `$hasAnyRole`, `$hasAllRoles`, `$rbac` to templates. Default: `true`. */\n globalProperties?: boolean\n}\n\nexport type RbacPlugin = VueRbac & Plugin\n\n/**\n * Creates the Vue plugin. The returned object is also the RBAC instance, so it can be used\n * outside components (router guards, stores):\n *\n * ```ts\n * export const rbac = createRbacPlugin({ snapshot: window.__RBAC__, wildcard: true })\n * app.use(rbac)\n * // later, after login:\n * rbac.setSnapshot(await api.get('/me/permissions'))\n * ```\n */\nexport function createRbacPlugin(options: RbacPluginOptions = {}): RbacPlugin {\n const rbac = createRbacState(options)\n\n return {\n ...rbac,\n install(app: App) {\n app.provide(RBAC_KEY, rbac)\n\n if (options.directives ?? true) {\n app.directive('can', createCanDirective(rbac))\n app.directive('role', createRoleDirective(rbac))\n }\n\n if (options.components ?? true) {\n app.component('Can', Can)\n app.component('HasRole', HasRole)\n }\n\n if (options.globalProperties ?? true) {\n const props = app.config.globalProperties\n props.$rbac = rbac\n props.$can = rbac.can\n props.$cannot = rbac.cannot\n props.$canAny = rbac.canAny\n props.$canAll = rbac.canAll\n props.$hasRole = rbac.hasRole\n props.$hasAnyRole = rbac.hasAnyRole\n props.$hasAllRoles = rbac.hasAllRoles\n }\n },\n }\n}\n\ndeclare module 'vue' {\n interface ComponentCustomProperties {\n $rbac: VueRbac\n $can: (permission: NameList) => boolean\n $cannot: (permission: NameList) => boolean\n $canAny: (permissions: NameList) => boolean\n $canAll: (permissions: NameList) => boolean\n $hasRole: (roles: NameList) => boolean\n $hasAnyRole: (roles: NameList) => boolean\n $hasAllRoles: (roles: NameList) => boolean\n }\n\n interface GlobalComponents {\n Can: typeof Can\n HasRole: typeof HasRole\n }\n\n interface GlobalDirectives {\n vCan: ReturnType<typeof createCanDirective>\n vRole: ReturnType<typeof createRoleDirective>\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@anievo-id/rbac-evolution-vue",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Vue 3 bindings for rbac-evolution: v-can directive & composables.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/AniEvo-ID/rbac-evolution.git",
10
+ "directory": "packages/vue"
11
+ },
12
+ "keywords": [
13
+ "rbac",
14
+ "permissions",
15
+ "roles",
16
+ "authorization",
17
+ "vue",
18
+ "vue3",
19
+ "directive"
20
+ ],
21
+ "sideEffects": false,
22
+ "main": "./dist/index.cjs",
23
+ "module": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "import": {
28
+ "types": "./dist/index.d.ts",
29
+ "default": "./dist/index.js"
30
+ },
31
+ "require": {
32
+ "types": "./dist/index.d.cts",
33
+ "default": "./dist/index.cjs"
34
+ }
35
+ },
36
+ "./package.json": "./package.json"
37
+ },
38
+ "files": [
39
+ "dist"
40
+ ],
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "dependencies": {
45
+ "@anievo-id/rbac-evolution": "^0.1.0"
46
+ },
47
+ "peerDependencies": {
48
+ "vue": ">=3.3"
49
+ },
50
+ "devDependencies": {
51
+ "vue": "^3.5.0",
52
+ "@vue/test-utils": "^2.4.0",
53
+ "jsdom": "^25.0.0",
54
+ "tsup": "^8.3.0",
55
+ "typescript": "^5.7.0",
56
+ "vitest": "^2.1.0"
57
+ },
58
+ "scripts": {
59
+ "build": "tsup",
60
+ "dev": "tsup --watch",
61
+ "typecheck": "tsc --noEmit",
62
+ "test": "vitest run --passWithNoTests",
63
+ "clean": "rm -rf dist .turbo"
64
+ }
6
65
  }