@anievo-id/rbac-evolution-react 0.8.0 → 0.9.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/README.md CHANGED
@@ -1,149 +1,47 @@
1
1
  # @anievo-id/rbac-evolution-react
2
2
 
3
- 📖 **[Documentation](https://creation.anievo.id/rbac-evolution/frameworks/react)**
4
-
5
- React bindings for [rbac-evolution](https://github.com/AniEvo-ID/rbac-evolution): `<RbacProvider>`, `useCan()`, `<Can>`, `<HasRole>`, ... — the React
6
- counterpart of spatie/laravel-permission's Blade directives (`@can`, `@cannot`, `@role`, `@hasanyrole`, ...).
3
+ React bindings for [RBAC Evolution](https://github.com/AniEvo-ID/rbac-evolution): `<RbacProvider>`, `<Can>`,
4
+ `<HasRole>`, `useCan()` and friends, the counterpart of spatie's `@can` and `@role` Blade directives.
7
5
 
8
6
  > **UI only.** These helpers show and hide elements based on a snapshot sent to the browser. Anyone can edit
9
- > client-side state, so they are **not** a security boundary. Always enforce authorization on the server
10
- > (route handlers, server actions, API) — e.g. with `@anievo-id/rbac-evolution-next` or the core `rbac.for(user).can()`.
7
+ > client-side state, so they are not a security boundary. Always check permissions on the server too.
8
+
9
+ ## Install
11
10
 
12
11
  ```bash
13
- npm i @anievo-id/rbac-evolution @anievo-id/rbac-evolution-react
12
+ npm i @anievo-id/rbac-evolution @anievo-id/rbac-evolution-react react
14
13
  ```
15
14
 
16
15
  Works with React 18+ and the Next.js App Router (the bundle starts with `'use client'`).
17
16
 
18
- ## How it works
19
-
20
- 1. On the server, take a snapshot of the user's access: `await rbac.for(user).snapshot()` → `{ roles, permissions }`.
21
- 2. Pass it to `<RbacProvider snapshot={...}>`.
22
- 3. Check synchronously anywhere below it — no requests, no loading states.
23
-
24
- ## Next.js App Router
17
+ ## Usage
25
18
 
26
19
  ```tsx
27
- // app/layout.tsx — server component
28
- import { RbacProvider } from '@anievo-id/rbac-evolution-react'
29
- import { rbac } from '@/lib/rbac'
30
- import { auth } from '@/auth'
31
-
32
- export default async function RootLayout({ children }: { children: React.ReactNode }) {
33
- const session = await auth()
34
- const snapshot = session?.user
35
- ? await rbac.for({ type: 'user', id: session.user.id }).snapshot()
36
- : null // guest
37
-
38
- return (
39
- <html lang="en">
40
- <body>
41
- <RbacProvider snapshot={snapshot} wildcard={rbac.wildcard}>
42
- {children}
43
- </RbacProvider>
44
- </body>
45
- </html>
46
- )
47
- }
48
- ```
20
+ import { Can, HasRole, RbacProvider, useCan } from '@anievo-id/rbac-evolution-react'
49
21
 
50
- (With `@anievo-id/rbac-evolution-next` this is just `snapshot={await getSnapshot()}`.)
51
-
52
- ```tsx
53
- // app/articles/article-actions.tsx — client component
54
- 'use client'
55
-
56
- import { Can, Cannot, HasRole, useCan } from '@anievo-id/rbac-evolution-react'
22
+ // snapshot = await rbac.for(user).snapshot() on the server, or null for guests
23
+ <RbacProvider snapshot={snapshot} wildcard>
24
+ <Toolbar />
25
+ </RbacProvider>
57
26
 
58
- export function ArticleActions() {
27
+ function Toolbar() {
59
28
  const canPublish = useCan('articles.publish')
60
-
61
29
  return (
62
- <div>
63
- <Can permission="articles.edit">
64
- <button>Edit</button>
65
- </Can>
66
-
67
- <Can anyOf={['articles.delete', 'articles.archive']} fallback={<span>Read only</span>}>
68
- <button>Remove</button>
69
- </Can>
70
-
71
- <Cannot permission="articles.edit">
72
- <p>Ask an editor to make changes.</p>
73
- </Cannot>
74
-
75
- <HasRole role="admin">
76
- <a href="/admin">Admin panel</a>
77
- </HasRole>
78
-
30
+ <>
31
+ <Can permission="articles.edit" fallback={<span>Read only</span>}><button>Edit</button></Can>
32
+ <HasRole role="admin"><a href="/admin">Admin</a></HasRole>
79
33
  <button disabled={!canPublish}>Publish</button>
80
- </div>
34
+ </>
81
35
  )
82
36
  }
83
37
  ```
84
38
 
85
- ## Other React apps
86
-
87
- Fetch the snapshot from your API (e.g. `GET /api/me/permissions` returning `rbac.for(user).snapshot()`) and pass it in:
88
-
89
- ```tsx
90
- <RbacProvider snapshot={data ?? null}>
91
- <App />
92
- </RbacProvider>
93
- ```
94
-
95
- ## API
96
-
97
- ### `<RbacProvider>`
98
-
99
- | Prop | Type | Description |
100
- | ----------------- | ------------------------------ | ------------------------------------------------------------------------------ |
101
- | `snapshot` | `RbacSnapshot \| null` | `{ roles, permissions }` of the current user. `null`/`undefined` = guest. |
102
- | `wildcard` | `boolean` | Match `articles.*`-style permissions. Use the same value as `createRbac`. |
103
- | `superAdminRoles` | `string[]` | Users with one of these roles pass every `can` check (not role checks). |
104
-
105
- Providers can be nested; the nearest one wins.
106
-
107
- ### Hooks
108
-
109
- | Hook | Returns `true` when |
110
- | ------------------------------ | -------------------------------------------------------- |
111
- | `useCan(permission)` | the user has the permission |
112
- | `useCannot(permission)` | the user does not have the permission |
113
- | `useCanAny(...permissions)` | the user has ANY of them (arrays or varargs) |
114
- | `useCanAll(...permissions)` | the user has ALL of them |
115
- | `useHasRole(role \| roles[])` | the user has the role / ANY of the roles |
116
- | `useHasAnyRole(...roles)` | the user has ANY of the roles |
117
- | `useHasAllRoles(...roles)` | the user has ALL of the roles |
118
- | `useRbac()` | returns the checker (`can`, `canAny`, `hasRole`, `roles`, `permissions`, ...) |
119
-
120
- Hooks throw when used outside `<RbacProvider>`.
121
-
122
- ### Components
123
-
124
- ```tsx
125
- <Can permission="a">…</Can> // @can('a')
126
- <Can anyOf={['a', 'b']}>…</Can> // @canany(['a', 'b'])
127
- <Can allOf={['a', 'b']}>…</Can> // all of them
128
- <Cannot permission="a">…</Cannot> // @cannot('a')
129
- <HasRole role="admin">…</HasRole> // @role('admin')
130
- <HasRole anyOf={['a', 'b']}>…</HasRole> // @hasanyrole
131
- <HasRole allOf={['a', 'b']}>…</HasRole> // @hasallroles
132
- ```
133
-
134
- All accept `fallback` (rendered when the check fails). TypeScript enforces exactly one condition; at runtime a
135
- component with no condition renders the fallback (deny by default).
136
-
137
- ### `createRbacChecker(snapshot, { wildcard?, superAdminRoles? })`
138
-
139
- The pure checker behind the provider, usable outside React.
39
+ - Take the snapshot with the same guard and team you check on the server.
40
+ - A snapshot is a copy. After changing a user's roles, render with a fresh one (`router.refresh()` in Next.js).
140
41
 
141
- ## Notes
42
+ ## Documentation
142
43
 
143
- - Name matching is exact (after trimming), like the core. With `wildcard`, matching uses the core's `wildcardImplies`.
144
- - Snapshots are per guard/team: take the snapshot with the same `guard`/`team` you check on the server.
145
- - A snapshot is a point-in-time copy. After changing a user's roles, re-render with a fresh snapshot
146
- (e.g. `router.refresh()` in Next.js).
44
+ https://creation.anievo.id/rbac-evolution/frameworks/react
147
45
 
148
46
  ## License
149
47
 
package/dist/index.cjs CHANGED
@@ -25,6 +25,7 @@ __export(index_exports, {
25
25
  Cannot: () => Cannot,
26
26
  HasRole: () => HasRole,
27
27
  RbacProvider: () => RbacProvider,
28
+ UnlessRole: () => UnlessRole,
28
29
  createRbacChecker: () => createRbacChecker,
29
30
  useCan: () => useCan,
30
31
  useCanAll: () => useCanAll,
@@ -161,12 +162,20 @@ function HasRole(props) {
161
162
  if (rbac.loading) return null;
162
163
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_jsx_runtime2.Fragment, { children: checkRoles(rbac, props) ? props.children : props.fallback });
163
164
  }
165
+ function UnlessRole(props) {
166
+ const rbac = useRbac();
167
+ if (rbac.loading) return null;
168
+ const loose = props;
169
+ const hasCondition = loose.role !== void 0 || loose.anyOf !== void 0 || loose.allOf !== void 0;
170
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_jsx_runtime2.Fragment, { children: hasCondition && !checkRoles(rbac, props) ? props.children : props.fallback });
171
+ }
164
172
  // Annotate the CommonJS export names for ESM import in node:
165
173
  0 && (module.exports = {
166
174
  Can,
167
175
  Cannot,
168
176
  HasRole,
169
177
  RbacProvider,
178
+ UnlessRole,
170
179
  createRbacChecker,
171
180
  useCan,
172
181
  useCanAll,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/checker.ts","../src/context.tsx","../src/components.tsx"],"sourcesContent":["/**\n * @anievo-id/rbac-evolution-react\n *\n * Client-side UI helpers. They only show/hide UI — always enforce authorization on the server.\n */\n\nexport { createRbacChecker } from './checker'\nexport type { RbacChecker, RbacCheckerOptions } from './checker'\n\nexport {\n RbacProvider,\n useCan,\n useCanAll,\n useCanAny,\n useCannot,\n useHasAllRoles,\n useHasAnyRole,\n useHasRole,\n useRbac,\n} from './context'\nexport type { RbacProviderProps } from './context'\n\nexport { Can, Cannot, HasRole } from './components'\nexport type { CannotProps, CanProps, HasRoleProps, PermissionCondition, RoleCondition } from './components'\n","import { wildcardImplies } from '@anievo-id/rbac-evolution'\nimport type { Many, RbacSnapshot } from '@anievo-id/rbac-evolution'\n\nexport interface RbacCheckerOptions {\n /** Treat granted permissions as wildcard patterns (`articles.*`). Must match the server's `wildcard` setting. */\n wildcard?: boolean | undefined\n /** Roles that pass every permission check (like spatie's `Gate::before` super-admin pattern). */\n superAdminRoles?: readonly string[] | undefined\n /** The snapshot is still being fetched: `<Can>`, `<Cannot>` and `<HasRole>` render nothing. Default: `false`. */\n loading?: boolean | undefined\n}\n\n/** Synchronous checks against a {@link RbacSnapshot}. */\nexport interface RbacChecker {\n readonly roles: readonly string[]\n readonly permissions: readonly string[]\n /** `true` if the subject has one of the configured `superAdminRoles`. */\n readonly isSuperAdmin: boolean\n /** `true` while the snapshot is still being fetched (the `loading` option). Every check, `cannot` included, returns `false` meanwhile. */\n readonly loading: boolean\n can(permission: string): boolean\n cannot(permission: string): boolean\n /** `true` if ANY of the permissions is granted. `false` for an empty list. */\n canAny(...permissions: Many<string>[]): boolean\n /** `true` if ALL of the permissions are granted. `false` for an empty list (deny by default, like the Vue package). */\n canAll(...permissions: Many<string>[]): boolean\n /** `true` if the subject has the role — or ANY of the roles when given an array. */\n hasRole(roles: Many<string>): boolean\n hasAnyRole(...roles: Many<string>[]): boolean\n hasAllRoles(...roles: Many<string>[]): boolean\n}\n\nconst EMPTY: RbacSnapshot = { roles: [], permissions: [] }\n\nfunction flatten(items: readonly Many<string>[]): string[] {\n const out: string[] = []\n for (const item of items) {\n if (typeof item === 'string') out.push(item)\n else out.push(...item)\n }\n return out\n}\n\nfunction safeImplies(granted: string, required: string): boolean {\n try {\n return wildcardImplies(granted, required)\n } catch {\n return false\n }\n}\n\n/**\n * Builds a pure, synchronous checker for a snapshot (as returned by `rbac.for(user).snapshot()`).\n * Used by `RbacProvider`, but usable on its own too.\n */\nexport function createRbacChecker(\n snapshot: RbacSnapshot | null | undefined,\n options: RbacCheckerOptions = {},\n): RbacChecker {\n const { roles, permissions } = snapshot ?? EMPTY\n const roleSet = new Set(roles)\n const permissionSet = new Set(permissions)\n const wildcard = options.wildcard ?? false\n // While loading, every check (`cannot` too) is false: neither a stale grant nor \"no access\" UI shows.\n const loading = options.loading ?? false\n const isSuperAdmin = !loading && (options.superAdminRoles ?? []).some((r) => roleSet.has(r))\n\n const can = (permission: string): boolean => {\n if (loading) return false\n if (isSuperAdmin) return true\n const name = permission.trim()\n if (name === '') return false\n if (permissionSet.has(name)) return true\n return wildcard && permissions.some((granted) => safeImplies(granted, name))\n }\n const hasOne = (role: string): boolean => !loading && roleSet.has(role.trim())\n\n return {\n roles,\n permissions,\n isSuperAdmin,\n loading,\n can,\n cannot: (permission) => !loading && !can(permission),\n canAny: (...list) => flatten(list).some(can),\n canAll: (...list) => {\n const wanted = flatten(list)\n return wanted.length > 0 && wanted.every(can)\n },\n hasRole: (list) => flatten([list]).some(hasOne),\n hasAnyRole: (...list) => flatten(list).some(hasOne),\n hasAllRoles: (...list) => {\n const wanted = flatten(list)\n return wanted.length > 0 && wanted.every(hasOne)\n },\n }\n}\n","import { createContext, useContext, useMemo } from 'react'\nimport type { ReactNode } from 'react'\nimport type { Many, RbacSnapshot } from '@anievo-id/rbac-evolution'\nimport { createRbacChecker } from './checker'\nimport type { RbacChecker } from './checker'\n\nconst RbacContext = createContext<RbacChecker | null>(null)\nRbacContext.displayName = 'RbacContext'\n\nexport interface RbacProviderProps {\n /** Roles & permissions of the current user, e.g. from `rbac.for(user).snapshot()` on the server. `null` = guest. */\n snapshot: RbacSnapshot | null | undefined\n /** Enable wildcard matching (`articles.*`). Must match the server's `wildcard` setting. Default: `false`. */\n wildcard?: boolean | undefined\n /** Roles that pass every `can` check (super admin). */\n superAdminRoles?: readonly string[] | undefined\n /**\n * The snapshot is still being fetched. `<Can>`, `<Cannot>` and `<HasRole>` then render nothing\n * (not even `fallback`), so nothing flashes before the real permissions arrive. Default: `false`.\n */\n loading?: boolean | undefined\n children?: ReactNode | undefined\n}\n\n/**\n * Provides a user's roles & permissions to `useCan()`, `<Can>`, ...\n *\n * UI only: this hides and shows elements. Always enforce authorization on the server.\n */\nexport function RbacProvider({ snapshot, wildcard = false, superAdminRoles, loading = false, children }: RbacProviderProps) {\n const superKey = superAdminRoles?.join('\\u0000') ?? ''\n const checker = useMemo(\n () => createRbacChecker(snapshot, superAdminRoles ? { wildcard, superAdminRoles, loading } : { wildcard, loading }),\n // `superKey` keeps inline arrays (`superAdminRoles={['admin']}`) from recomputing every render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [snapshot, wildcard, superKey, loading],\n )\n return <RbacContext.Provider value={checker}>{children}</RbacContext.Provider>\n}\n\n/** Returns the checker of the nearest `RbacProvider`. Throws when there is none. */\nexport function useRbac(): RbacChecker {\n const checker = useContext(RbacContext)\n if (!checker) {\n throw new Error('useRbac() must be used inside <RbacProvider>.')\n }\n return checker\n}\n\nexport function useCan(permission: string): boolean {\n return useRbac().can(permission)\n}\n\nexport function useCannot(permission: string): boolean {\n return useRbac().cannot(permission)\n}\n\nexport function useCanAny(...permissions: Many<string>[]): boolean {\n return useRbac().canAny(...permissions)\n}\n\nexport function useCanAll(...permissions: Many<string>[]): boolean {\n return useRbac().canAll(...permissions)\n}\n\n/** `true` if the user has the role — or ANY of the roles when given an array. */\nexport function useHasRole(role: Many<string>): boolean {\n return useRbac().hasRole(role)\n}\n\nexport function useHasAnyRole(...roles: Many<string>[]): boolean {\n return useRbac().hasAnyRole(...roles)\n}\n\nexport function useHasAllRoles(...roles: Many<string>[]): boolean {\n return useRbac().hasAllRoles(...roles)\n}\n","import type { ReactNode } from 'react'\nimport type { RbacChecker } from './checker'\nimport { useRbac } from './context'\n\n/** Exactly one of `permission`, `anyOf` or `allOf`. */\nexport type PermissionCondition =\n | { permission: string; anyOf?: never; allOf?: never }\n | { permission?: never; anyOf: readonly string[]; allOf?: never }\n | { permission?: never; anyOf?: never; allOf: readonly string[] }\n\n/** Exactly one of `role`, `anyOf` or `allOf`. */\nexport type RoleCondition =\n | { role: string; anyOf?: never; allOf?: never }\n | { role?: never; anyOf: readonly string[]; allOf?: never }\n | { role?: never; anyOf?: never; allOf: readonly string[] }\n\ninterface GateProps {\n children?: ReactNode | undefined\n /** Rendered when the check fails. Default: nothing. */\n fallback?: ReactNode | undefined\n}\n\nexport type CanProps = PermissionCondition & GateProps\nexport type CannotProps = PermissionCondition & GateProps\nexport type HasRoleProps = RoleCondition & GateProps\n\ninterface LooseCondition {\n anyOf?: readonly string[] | undefined\n allOf?: readonly string[] | undefined\n}\n\n// Conditions are ANDed; no condition at all is denied (deny by default, also for untyped JS callers).\nfunction checkPermissions(rbac: RbacChecker, p: LooseCondition & { permission?: string | undefined }): boolean {\n if (p.permission === undefined && p.anyOf === undefined && p.allOf === undefined) return false\n return (\n (p.permission === undefined || rbac.can(p.permission)) &&\n (p.anyOf === undefined || rbac.canAny(p.anyOf)) &&\n (p.allOf === undefined || rbac.canAll(p.allOf))\n )\n}\n\nfunction checkRoles(rbac: RbacChecker, p: LooseCondition & { role?: string | undefined }): boolean {\n if (p.role === undefined && p.anyOf === undefined && p.allOf === undefined) return false\n return (\n (p.role === undefined || rbac.hasRole(p.role)) &&\n (p.anyOf === undefined || rbac.hasAnyRole(p.anyOf)) &&\n (p.allOf === undefined || rbac.hasAllRoles(p.allOf))\n )\n}\n\n/** Renders `children` if the user has the permission(s) — like spatie's `@can` / `@canany`. */\nexport function Can(props: CanProps) {\n const rbac = useRbac()\n if (rbac.loading) return null\n return <>{checkPermissions(rbac, props) ? props.children : props.fallback}</>\n}\n\n/** Renders `children` if the user does NOT have the permission(s) — like spatie's `@cannot`. */\nexport function Cannot(props: CannotProps) {\n const rbac = useRbac()\n if (rbac.loading) return null\n return <>{checkPermissions(rbac, props) ? props.fallback : props.children}</>\n}\n\n/** Renders `children` if the user has the role(s) — like spatie's `@role` / `@hasanyrole` / `@hasallroles`. */\nexport function HasRole(props: HasRoleProps) {\n const rbac = useRbac()\n if (rbac.loading) return null\n return <>{checkRoles(rbac, props) ? props.children : props.fallback}</>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,4BAAgC;AAgChC,IAAM,QAAsB,EAAE,OAAO,CAAC,GAAG,aAAa,CAAC,EAAE;AAEzD,SAAS,QAAQ,OAA0C;AACzD,QAAM,MAAgB,CAAC;AACvB,aAAW,QAAQ,OAAO;AACxB,QAAI,OAAO,SAAS,SAAU,KAAI,KAAK,IAAI;AAAA,QACtC,KAAI,KAAK,GAAG,IAAI;AAAA,EACvB;AACA,SAAO;AACT;AAEA,SAAS,YAAY,SAAiB,UAA2B;AAC/D,MAAI;AACF,eAAO,uCAAgB,SAAS,QAAQ;AAAA,EAC1C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,kBACd,UACA,UAA8B,CAAC,GAClB;AACb,QAAM,EAAE,OAAO,YAAY,IAAI,YAAY;AAC3C,QAAM,UAAU,IAAI,IAAI,KAAK;AAC7B,QAAM,gBAAgB,IAAI,IAAI,WAAW;AACzC,QAAM,WAAW,QAAQ,YAAY;AAErC,QAAM,UAAU,QAAQ,WAAW;AACnC,QAAM,eAAe,CAAC,YAAY,QAAQ,mBAAmB,CAAC,GAAG,KAAK,CAAC,MAAM,QAAQ,IAAI,CAAC,CAAC;A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AAE,IAAI,OAC3C,EAAE,UAAU,UAAa,KAAK,WAAW,EAAE,KAAK,OAChD,EAAE,UAAU,UAAa,KAAK,YAAY,EAAE,KAAK;AAEtD;AAGO,SAAS,IAAI,OAAiB;AACnC,QAAM,OAAO,QAAQ;AACrB,MAAI,KAAK,QAAS,QAAO;AACzB,SAAO,6EAAG,2BAAiB,MAAM,KAAK,IAAI,MAAM,WAAW,MAAM,UAAS;AAC5E;AAGO,SAAS,OAAO,OAAoB;AACzC,QAAM,OAAO,QAAQ;AACrB,MAAI,KAAK,QAAS,QAAO;AACzB,SAAO,6EAAG,2BAAiB,MAAM,KAAK,IAAI,MAAM,WAAW,MAAM,UAAS;AAC5E;AAGO,SAAS,QAAQ,OAAqB;AAC3C,QAAM,OAAO,QAAQ;AACrB,MAAI,KAAK,QAAS,QAAO;AACzB,SAAO,6EAAG,qBAAW,MAAM,KAAK,IAAI,MAAM,WAAW,MAAM,UAAS;AACtE;","names":["import_jsx_runtime"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/checker.ts","../src/context.tsx","../src/components.tsx"],"sourcesContent":["/**\n * @anievo-id/rbac-evolution-react\n *\n * Client-side UI helpers. They only show/hide UI — always enforce authorization on the server.\n */\n\nexport { createRbacChecker } from './checker'\nexport type { RbacChecker, RbacCheckerOptions } from './checker'\n\nexport {\n RbacProvider,\n useCan,\n useCanAll,\n useCanAny,\n useCannot,\n useHasAllRoles,\n useHasAnyRole,\n useHasRole,\n useRbac,\n} from './context'\nexport type { RbacProviderProps } from './context'\n\nexport { Can, Cannot, HasRole, UnlessRole } from './components'\nexport type { CannotProps, CanProps, HasRoleProps, PermissionCondition, RoleCondition, UnlessRoleProps } from './components'\n","import { wildcardImplies } from '@anievo-id/rbac-evolution'\nimport type { Many, RbacSnapshot } from '@anievo-id/rbac-evolution'\n\nexport interface RbacCheckerOptions {\n /** Treat granted permissions as wildcard patterns (`articles.*`). Must match the server's `wildcard` setting. */\n wildcard?: boolean | undefined\n /** Roles that pass every permission check (like spatie's `Gate::before` super-admin pattern). */\n superAdminRoles?: readonly string[] | undefined\n /** The snapshot is still being fetched: `<Can>`, `<Cannot>` and `<HasRole>` render nothing. Default: `false`. */\n loading?: boolean | undefined\n}\n\n/** Synchronous checks against a {@link RbacSnapshot}. */\nexport interface RbacChecker {\n readonly roles: readonly string[]\n readonly permissions: readonly string[]\n /** `true` if the subject has one of the configured `superAdminRoles`. */\n readonly isSuperAdmin: boolean\n /** `true` while the snapshot is still being fetched (the `loading` option). Every check, `cannot` included, returns `false` meanwhile. */\n readonly loading: boolean\n can(permission: string): boolean\n cannot(permission: string): boolean\n /** `true` if ANY of the permissions is granted. `false` for an empty list. */\n canAny(...permissions: Many<string>[]): boolean\n /** `true` if ALL of the permissions are granted. `false` for an empty list (deny by default, like the Vue package). */\n canAll(...permissions: Many<string>[]): boolean\n /** `true` if the subject has the role — or ANY of the roles when given an array. */\n hasRole(roles: Many<string>): boolean\n hasAnyRole(...roles: Many<string>[]): boolean\n hasAllRoles(...roles: Many<string>[]): boolean\n}\n\nconst EMPTY: RbacSnapshot = { roles: [], permissions: [] }\n\nfunction flatten(items: readonly Many<string>[]): string[] {\n const out: string[] = []\n for (const item of items) {\n if (typeof item === 'string') out.push(item)\n else out.push(...item)\n }\n return out\n}\n\nfunction safeImplies(granted: string, required: string): boolean {\n try {\n return wildcardImplies(granted, required)\n } catch {\n return false\n }\n}\n\n/**\n * Builds a pure, synchronous checker for a snapshot (as returned by `rbac.for(user).snapshot()`).\n * Used by `RbacProvider`, but usable on its own too.\n */\nexport function createRbacChecker(\n snapshot: RbacSnapshot | null | undefined,\n options: RbacCheckerOptions = {},\n): RbacChecker {\n const { roles, permissions } = snapshot ?? EMPTY\n const roleSet = new Set(roles)\n const permissionSet = new Set(permissions)\n const wildcard = options.wildcard ?? false\n // While loading, every check (`cannot` too) is false: neither a stale grant nor \"no access\" UI shows.\n const loading = options.loading ?? false\n const isSuperAdmin = !loading && (options.superAdminRoles ?? []).some((r) => roleSet.has(r))\n\n const can = (permission: string): boolean => {\n if (loading) return false\n if (isSuperAdmin) return true\n const name = permission.trim()\n if (name === '') return false\n if (permissionSet.has(name)) return true\n return wildcard && permissions.some((granted) => safeImplies(granted, name))\n }\n const hasOne = (role: string): boolean => !loading && roleSet.has(role.trim())\n\n return {\n roles,\n permissions,\n isSuperAdmin,\n loading,\n can,\n cannot: (permission) => !loading && !can(permission),\n canAny: (...list) => flatten(list).some(can),\n canAll: (...list) => {\n const wanted = flatten(list)\n return wanted.length > 0 && wanted.every(can)\n },\n hasRole: (list) => flatten([list]).some(hasOne),\n hasAnyRole: (...list) => flatten(list).some(hasOne),\n hasAllRoles: (...list) => {\n const wanted = flatten(list)\n return wanted.length > 0 && wanted.every(hasOne)\n },\n }\n}\n","import { createContext, useContext, useMemo } from 'react'\nimport type { ReactNode } from 'react'\nimport type { Many, RbacSnapshot } from '@anievo-id/rbac-evolution'\nimport { createRbacChecker } from './checker'\nimport type { RbacChecker } from './checker'\n\nconst RbacContext = createContext<RbacChecker | null>(null)\nRbacContext.displayName = 'RbacContext'\n\nexport interface RbacProviderProps {\n /** Roles & permissions of the current user, e.g. from `rbac.for(user).snapshot()` on the server. `null` = guest. */\n snapshot: RbacSnapshot | null | undefined\n /** Enable wildcard matching (`articles.*`). Must match the server's `wildcard` setting. Default: `false`. */\n wildcard?: boolean | undefined\n /** Roles that pass every `can` check (super admin). */\n superAdminRoles?: readonly string[] | undefined\n /**\n * The snapshot is still being fetched. `<Can>`, `<Cannot>` and `<HasRole>` then render nothing\n * (not even `fallback`), so nothing flashes before the real permissions arrive. Default: `false`.\n */\n loading?: boolean | undefined\n children?: ReactNode | undefined\n}\n\n/**\n * Provides a user's roles & permissions to `useCan()`, `<Can>`, ...\n *\n * UI only: this hides and shows elements. Always enforce authorization on the server.\n */\nexport function RbacProvider({ snapshot, wildcard = false, superAdminRoles, loading = false, children }: RbacProviderProps) {\n const superKey = superAdminRoles?.join('\\u0000') ?? ''\n const checker = useMemo(\n () => createRbacChecker(snapshot, superAdminRoles ? { wildcard, superAdminRoles, loading } : { wildcard, loading }),\n // `superKey` keeps inline arrays (`superAdminRoles={['admin']}`) from recomputing every render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [snapshot, wildcard, superKey, loading],\n )\n return <RbacContext.Provider value={checker}>{children}</RbacContext.Provider>\n}\n\n/** Returns the checker of the nearest `RbacProvider`. Throws when there is none. */\nexport function useRbac(): RbacChecker {\n const checker = useContext(RbacContext)\n if (!checker) {\n throw new Error('useRbac() must be used inside <RbacProvider>.')\n }\n return checker\n}\n\nexport function useCan(permission: string): boolean {\n return useRbac().can(permission)\n}\n\nexport function useCannot(permission: string): boolean {\n return useRbac().cannot(permission)\n}\n\nexport function useCanAny(...permissions: Many<string>[]): boolean {\n return useRbac().canAny(...permissions)\n}\n\nexport function useCanAll(...permissions: Many<string>[]): boolean {\n return useRbac().canAll(...permissions)\n}\n\n/** `true` if the user has the role — or ANY of the roles when given an array. */\nexport function useHasRole(role: Many<string>): boolean {\n return useRbac().hasRole(role)\n}\n\nexport function useHasAnyRole(...roles: Many<string>[]): boolean {\n return useRbac().hasAnyRole(...roles)\n}\n\nexport function useHasAllRoles(...roles: Many<string>[]): boolean {\n return useRbac().hasAllRoles(...roles)\n}\n","import type { ReactNode } from 'react'\nimport type { RbacChecker } from './checker'\nimport { useRbac } from './context'\n\n/** Exactly one of `permission`, `anyOf` or `allOf`. */\nexport type PermissionCondition =\n | { permission: string; anyOf?: never; allOf?: never }\n | { permission?: never; anyOf: readonly string[]; allOf?: never }\n | { permission?: never; anyOf?: never; allOf: readonly string[] }\n\n/** Exactly one of `role`, `anyOf` or `allOf`. */\nexport type RoleCondition =\n | { role: string; anyOf?: never; allOf?: never }\n | { role?: never; anyOf: readonly string[]; allOf?: never }\n | { role?: never; anyOf?: never; allOf: readonly string[] }\n\ninterface GateProps {\n children?: ReactNode | undefined\n /** Rendered when the check fails. Default: nothing. */\n fallback?: ReactNode | undefined\n}\n\nexport type CanProps = PermissionCondition & GateProps\nexport type CannotProps = PermissionCondition & GateProps\nexport type HasRoleProps = RoleCondition & GateProps\nexport type UnlessRoleProps = RoleCondition & GateProps\n\ninterface LooseCondition {\n anyOf?: readonly string[] | undefined\n allOf?: readonly string[] | undefined\n}\n\n// Conditions are ANDed; no condition at all is denied (deny by default, also for untyped JS callers).\nfunction checkPermissions(rbac: RbacChecker, p: LooseCondition & { permission?: string | undefined }): boolean {\n if (p.permission === undefined && p.anyOf === undefined && p.allOf === undefined) return false\n return (\n (p.permission === undefined || rbac.can(p.permission)) &&\n (p.anyOf === undefined || rbac.canAny(p.anyOf)) &&\n (p.allOf === undefined || rbac.canAll(p.allOf))\n )\n}\n\nfunction checkRoles(rbac: RbacChecker, p: LooseCondition & { role?: string | undefined }): boolean {\n if (p.role === undefined && p.anyOf === undefined && p.allOf === undefined) return false\n return (\n (p.role === undefined || rbac.hasRole(p.role)) &&\n (p.anyOf === undefined || rbac.hasAnyRole(p.anyOf)) &&\n (p.allOf === undefined || rbac.hasAllRoles(p.allOf))\n )\n}\n\n/** Renders `children` if the user has the permission(s) — like spatie's `@can` / `@canany`. */\nexport function Can(props: CanProps) {\n const rbac = useRbac()\n if (rbac.loading) return null\n return <>{checkPermissions(rbac, props) ? props.children : props.fallback}</>\n}\n\n/** Renders `children` if the user does NOT have the permission(s) — like spatie's `@cannot`. */\nexport function Cannot(props: CannotProps) {\n const rbac = useRbac()\n if (rbac.loading) return null\n return <>{checkPermissions(rbac, props) ? props.fallback : props.children}</>\n}\n\n/** Renders `children` if the user has the role(s) — like spatie's `@role` / `@hasanyrole` / `@hasallroles`. */\nexport function HasRole(props: HasRoleProps) {\n const rbac = useRbac()\n if (rbac.loading) return null\n return <>{checkRoles(rbac, props) ? props.children : props.fallback}</>\n}\n\n/**\n * Renders `children` if the user does NOT have the role(s) — like spatie's `@unlessrole`.\n * `anyOf`: none of them. `allOf`: not all of them. Without a condition it renders `fallback` (deny by default).\n */\nexport function UnlessRole(props: UnlessRoleProps) {\n const rbac = useRbac()\n if (rbac.loading) return null\n const loose = props as LooseCondition & { role?: string | undefined }\n const hasCondition = loose.role !== undefined || loose.anyOf !== undefined || loose.allOf !== undefined\n return <>{hasCondition && !checkRoles(rbac, props) ? props.children : props.fallback}</>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,4BAAgC;AAgChC,IAAM,QAAsB,EAAE,OAAO,CAAC,GAAG,aAAa,CAAC,EAAE;AAEzD,SAAS,QAAQ,OAA0C;AACzD,QAAM,MAAgB,CAAC;AACvB,aAAW,QAAQ,OAAO;AACxB,QAAI,OAAO,SAAS,SAAU,KAAI,KAAK,IAAI;AAAA,QACtC,KAAI,KAAK,GAAG,IAAI;AAAA,EACvB;AACA,SAAO;AACT;AAEA,SAAS,YAAY,SAAiB,UAA2B;AAC/D,MAAI;AACF,eAAO,uCAAgB,SAAS,QAAQ;AAAA,EAC1C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,kBACd,UACA,UAA8B,CAAC,GAClB;AACb,QAAM,EAAE,OAAO,YAAY,IAAI,YAAY;AAC3C,QAAM,UAAU,IAAI,IAAI,KAAK;AAC7B,QAAM,gBAAgB,IAAI,IAAI,WAAW;AACzC,QAAM,WAAW,QAAQ,YAAY;AAErC,QAAM,UAAU,QAAQ,WAAW;AACnC,QAAM,eAAe,CAAC,YAAY,QAAQ,mBAAmB,CAAC,GAAG,KAAK,CAAC,MAAM,QAAQ,IAAI,CAAC,CAAC;AAE3F,QAAM,MAAM,CAAC,eAAgC;AAC3C,QAAI,QAAS,QAAO;AACpB,QAAI,aAAc,QAAO;AACzB,UAAM,OAAO,WAAW,KAAK;AAC7B,QAAI,SAAS,GAAI,QAAO;AACxB,QAAI,cAAc,IAAI,IAAI,EAAG,QAAO;AACpC,WAAO,YAAY,YAA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O,6EAAG,2BAAiB,MAAM,KAAK,IAAI,MAAM,WAAW,MAAM,UAAS;AAC5E;AAGO,SAAS,OAAO,OAAoB;AACzC,QAAM,OAAO,QAAQ;AACrB,MAAI,KAAK,QAAS,QAAO;AACzB,SAAO,6EAAG,2BAAiB,MAAM,KAAK,IAAI,MAAM,WAAW,MAAM,UAAS;AAC5E;AAGO,SAAS,QAAQ,OAAqB;AAC3C,QAAM,OAAO,QAAQ;AACrB,MAAI,KAAK,QAAS,QAAO;AACzB,SAAO,6EAAG,qBAAW,MAAM,KAAK,IAAI,MAAM,WAAW,MAAM,UAAS;AACtE;AAMO,SAAS,WAAW,OAAwB;AACjD,QAAM,OAAO,QAAQ;AACrB,MAAI,KAAK,QAAS,QAAO;AACzB,QAAM,QAAQ;AACd,QAAM,eAAe,MAAM,SAAS,UAAa,MAAM,UAAU,UAAa,MAAM,UAAU;AAC9F,SAAO,6EAAG,0BAAgB,CAAC,WAAW,MAAM,KAAK,IAAI,MAAM,WAAW,MAAM,UAAS;AACvF;","names":["import_jsx_runtime"]}
package/dist/index.d.cts CHANGED
@@ -102,11 +102,17 @@ interface GateProps {
102
102
  type CanProps = PermissionCondition & GateProps;
103
103
  type CannotProps = PermissionCondition & GateProps;
104
104
  type HasRoleProps = RoleCondition & GateProps;
105
+ type UnlessRoleProps = RoleCondition & GateProps;
105
106
  /** Renders `children` if the user has the permission(s) — like spatie's `@can` / `@canany`. */
106
107
  declare function Can(props: CanProps): react.JSX.Element | null;
107
108
  /** Renders `children` if the user does NOT have the permission(s) — like spatie's `@cannot`. */
108
109
  declare function Cannot(props: CannotProps): react.JSX.Element | null;
109
110
  /** Renders `children` if the user has the role(s) — like spatie's `@role` / `@hasanyrole` / `@hasallroles`. */
110
111
  declare function HasRole(props: HasRoleProps): react.JSX.Element | null;
112
+ /**
113
+ * Renders `children` if the user does NOT have the role(s) — like spatie's `@unlessrole`.
114
+ * `anyOf`: none of them. `allOf`: not all of them. Without a condition it renders `fallback` (deny by default).
115
+ */
116
+ declare function UnlessRole(props: UnlessRoleProps): react.JSX.Element | null;
111
117
 
112
- export { Can, type CanProps, Cannot, type CannotProps, HasRole, type HasRoleProps, type PermissionCondition, type RbacChecker, type RbacCheckerOptions, RbacProvider, type RbacProviderProps, type RoleCondition, createRbacChecker, useCan, useCanAll, useCanAny, useCannot, useHasAllRoles, useHasAnyRole, useHasRole, useRbac };
118
+ export { Can, type CanProps, Cannot, type CannotProps, HasRole, type HasRoleProps, type PermissionCondition, type RbacChecker, type RbacCheckerOptions, RbacProvider, type RbacProviderProps, type RoleCondition, UnlessRole, type UnlessRoleProps, createRbacChecker, useCan, useCanAll, useCanAny, useCannot, useHasAllRoles, useHasAnyRole, useHasRole, useRbac };
package/dist/index.d.ts CHANGED
@@ -102,11 +102,17 @@ interface GateProps {
102
102
  type CanProps = PermissionCondition & GateProps;
103
103
  type CannotProps = PermissionCondition & GateProps;
104
104
  type HasRoleProps = RoleCondition & GateProps;
105
+ type UnlessRoleProps = RoleCondition & GateProps;
105
106
  /** Renders `children` if the user has the permission(s) — like spatie's `@can` / `@canany`. */
106
107
  declare function Can(props: CanProps): react.JSX.Element | null;
107
108
  /** Renders `children` if the user does NOT have the permission(s) — like spatie's `@cannot`. */
108
109
  declare function Cannot(props: CannotProps): react.JSX.Element | null;
109
110
  /** Renders `children` if the user has the role(s) — like spatie's `@role` / `@hasanyrole` / `@hasallroles`. */
110
111
  declare function HasRole(props: HasRoleProps): react.JSX.Element | null;
112
+ /**
113
+ * Renders `children` if the user does NOT have the role(s) — like spatie's `@unlessrole`.
114
+ * `anyOf`: none of them. `allOf`: not all of them. Without a condition it renders `fallback` (deny by default).
115
+ */
116
+ declare function UnlessRole(props: UnlessRoleProps): react.JSX.Element | null;
111
117
 
112
- export { Can, type CanProps, Cannot, type CannotProps, HasRole, type HasRoleProps, type PermissionCondition, type RbacChecker, type RbacCheckerOptions, RbacProvider, type RbacProviderProps, type RoleCondition, createRbacChecker, useCan, useCanAll, useCanAny, useCannot, useHasAllRoles, useHasAnyRole, useHasRole, useRbac };
118
+ export { Can, type CanProps, Cannot, type CannotProps, HasRole, type HasRoleProps, type PermissionCondition, type RbacChecker, type RbacCheckerOptions, RbacProvider, type RbacProviderProps, type RoleCondition, UnlessRole, type UnlessRoleProps, createRbacChecker, useCan, useCanAll, useCanAny, useCannot, useHasAllRoles, useHasAnyRole, useHasRole, useRbac };
package/dist/index.js CHANGED
@@ -124,11 +124,19 @@ function HasRole(props) {
124
124
  if (rbac.loading) return null;
125
125
  return /* @__PURE__ */ jsx2(Fragment, { children: checkRoles(rbac, props) ? props.children : props.fallback });
126
126
  }
127
+ function UnlessRole(props) {
128
+ const rbac = useRbac();
129
+ if (rbac.loading) return null;
130
+ const loose = props;
131
+ const hasCondition = loose.role !== void 0 || loose.anyOf !== void 0 || loose.allOf !== void 0;
132
+ return /* @__PURE__ */ jsx2(Fragment, { children: hasCondition && !checkRoles(rbac, props) ? props.children : props.fallback });
133
+ }
127
134
  export {
128
135
  Can,
129
136
  Cannot,
130
137
  HasRole,
131
138
  RbacProvider,
139
+ UnlessRole,
132
140
  createRbacChecker,
133
141
  useCan,
134
142
  useCanAll,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/checker.ts","../src/context.tsx","../src/components.tsx"],"sourcesContent":["import { wildcardImplies } from '@anievo-id/rbac-evolution'\nimport type { Many, RbacSnapshot } from '@anievo-id/rbac-evolution'\n\nexport interface RbacCheckerOptions {\n /** Treat granted permissions as wildcard patterns (`articles.*`). Must match the server's `wildcard` setting. */\n wildcard?: boolean | undefined\n /** Roles that pass every permission check (like spatie's `Gate::before` super-admin pattern). */\n superAdminRoles?: readonly string[] | undefined\n /** The snapshot is still being fetched: `<Can>`, `<Cannot>` and `<HasRole>` render nothing. Default: `false`. */\n loading?: boolean | undefined\n}\n\n/** Synchronous checks against a {@link RbacSnapshot}. */\nexport interface RbacChecker {\n readonly roles: readonly string[]\n readonly permissions: readonly string[]\n /** `true` if the subject has one of the configured `superAdminRoles`. */\n readonly isSuperAdmin: boolean\n /** `true` while the snapshot is still being fetched (the `loading` option). Every check, `cannot` included, returns `false` meanwhile. */\n readonly loading: boolean\n can(permission: string): boolean\n cannot(permission: string): boolean\n /** `true` if ANY of the permissions is granted. `false` for an empty list. */\n canAny(...permissions: Many<string>[]): boolean\n /** `true` if ALL of the permissions are granted. `false` for an empty list (deny by default, like the Vue package). */\n canAll(...permissions: Many<string>[]): boolean\n /** `true` if the subject has the role — or ANY of the roles when given an array. */\n hasRole(roles: Many<string>): boolean\n hasAnyRole(...roles: Many<string>[]): boolean\n hasAllRoles(...roles: Many<string>[]): boolean\n}\n\nconst EMPTY: RbacSnapshot = { roles: [], permissions: [] }\n\nfunction flatten(items: readonly Many<string>[]): string[] {\n const out: string[] = []\n for (const item of items) {\n if (typeof item === 'string') out.push(item)\n else out.push(...item)\n }\n return out\n}\n\nfunction safeImplies(granted: string, required: string): boolean {\n try {\n return wildcardImplies(granted, required)\n } catch {\n return false\n }\n}\n\n/**\n * Builds a pure, synchronous checker for a snapshot (as returned by `rbac.for(user).snapshot()`).\n * Used by `RbacProvider`, but usable on its own too.\n */\nexport function createRbacChecker(\n snapshot: RbacSnapshot | null | undefined,\n options: RbacCheckerOptions = {},\n): RbacChecker {\n const { roles, permissions } = snapshot ?? EMPTY\n const roleSet = new Set(roles)\n const permissionSet = new Set(permissions)\n const wildcard = options.wildcard ?? false\n // While loading, every check (`cannot` too) is false: neither a stale grant nor \"no access\" UI shows.\n const loading = options.loading ?? false\n const isSuperAdmin = !loading && (options.superAdminRoles ?? []).some((r) => roleSet.has(r))\n\n const can = (permission: string): boolean => {\n if (loading) return false\n if (isSuperAdmin) return true\n const name = permission.trim()\n if (name === '') return false\n if (permissionSet.has(name)) return true\n return wildcard && permissions.some((granted) => safeImplies(granted, name))\n }\n const hasOne = (role: string): boolean => !loading && roleSet.has(role.trim())\n\n return {\n roles,\n permissions,\n isSuperAdmin,\n loading,\n can,\n cannot: (permission) => !loading && !can(permission),\n canAny: (...list) => flatten(list).some(can),\n canAll: (...list) => {\n const wanted = flatten(list)\n return wanted.length > 0 && wanted.every(can)\n },\n hasRole: (list) => flatten([list]).some(hasOne),\n hasAnyRole: (...list) => flatten(list).some(hasOne),\n hasAllRoles: (...list) => {\n const wanted = flatten(list)\n return wanted.length > 0 && wanted.every(hasOne)\n },\n }\n}\n","import { createContext, useContext, useMemo } from 'react'\nimport type { ReactNode } from 'react'\nimport type { Many, RbacSnapshot } from '@anievo-id/rbac-evolution'\nimport { createRbacChecker } from './checker'\nimport type { RbacChecker } from './checker'\n\nconst RbacContext = createContext<RbacChecker | null>(null)\nRbacContext.displayName = 'RbacContext'\n\nexport interface RbacProviderProps {\n /** Roles & permissions of the current user, e.g. from `rbac.for(user).snapshot()` on the server. `null` = guest. */\n snapshot: RbacSnapshot | null | undefined\n /** Enable wildcard matching (`articles.*`). Must match the server's `wildcard` setting. Default: `false`. */\n wildcard?: boolean | undefined\n /** Roles that pass every `can` check (super admin). */\n superAdminRoles?: readonly string[] | undefined\n /**\n * The snapshot is still being fetched. `<Can>`, `<Cannot>` and `<HasRole>` then render nothing\n * (not even `fallback`), so nothing flashes before the real permissions arrive. Default: `false`.\n */\n loading?: boolean | undefined\n children?: ReactNode | undefined\n}\n\n/**\n * Provides a user's roles & permissions to `useCan()`, `<Can>`, ...\n *\n * UI only: this hides and shows elements. Always enforce authorization on the server.\n */\nexport function RbacProvider({ snapshot, wildcard = false, superAdminRoles, loading = false, children }: RbacProviderProps) {\n const superKey = superAdminRoles?.join('\\u0000') ?? ''\n const checker = useMemo(\n () => createRbacChecker(snapshot, superAdminRoles ? { wildcard, superAdminRoles, loading } : { wildcard, loading }),\n // `superKey` keeps inline arrays (`superAdminRoles={['admin']}`) from recomputing every render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [snapshot, wildcard, superKey, loading],\n )\n return <RbacContext.Provider value={checker}>{children}</RbacContext.Provider>\n}\n\n/** Returns the checker of the nearest `RbacProvider`. Throws when there is none. */\nexport function useRbac(): RbacChecker {\n const checker = useContext(RbacContext)\n if (!checker) {\n throw new Error('useRbac() must be used inside <RbacProvider>.')\n }\n return checker\n}\n\nexport function useCan(permission: string): boolean {\n return useRbac().can(permission)\n}\n\nexport function useCannot(permission: string): boolean {\n return useRbac().cannot(permission)\n}\n\nexport function useCanAny(...permissions: Many<string>[]): boolean {\n return useRbac().canAny(...permissions)\n}\n\nexport function useCanAll(...permissions: Many<string>[]): boolean {\n return useRbac().canAll(...permissions)\n}\n\n/** `true` if the user has the role — or ANY of the roles when given an array. */\nexport function useHasRole(role: Many<string>): boolean {\n return useRbac().hasRole(role)\n}\n\nexport function useHasAnyRole(...roles: Many<string>[]): boolean {\n return useRbac().hasAnyRole(...roles)\n}\n\nexport function useHasAllRoles(...roles: Many<string>[]): boolean {\n return useRbac().hasAllRoles(...roles)\n}\n","import type { ReactNode } from 'react'\nimport type { RbacChecker } from './checker'\nimport { useRbac } from './context'\n\n/** Exactly one of `permission`, `anyOf` or `allOf`. */\nexport type PermissionCondition =\n | { permission: string; anyOf?: never; allOf?: never }\n | { permission?: never; anyOf: readonly string[]; allOf?: never }\n | { permission?: never; anyOf?: never; allOf: readonly string[] }\n\n/** Exactly one of `role`, `anyOf` or `allOf`. */\nexport type RoleCondition =\n | { role: string; anyOf?: never; allOf?: never }\n | { role?: never; anyOf: readonly string[]; allOf?: never }\n | { role?: never; anyOf?: never; allOf: readonly string[] }\n\ninterface GateProps {\n children?: ReactNode | undefined\n /** Rendered when the check fails. Default: nothing. */\n fallback?: ReactNode | undefined\n}\n\nexport type CanProps = PermissionCondition & GateProps\nexport type CannotProps = PermissionCondition & GateProps\nexport type HasRoleProps = RoleCondition & GateProps\n\ninterface LooseCondition {\n anyOf?: readonly string[] | undefined\n allOf?: readonly string[] | undefined\n}\n\n// Conditions are ANDed; no condition at all is denied (deny by default, also for untyped JS callers).\nfunction checkPermissions(rbac: RbacChecker, p: LooseCondition & { permission?: string | undefined }): boolean {\n if (p.permission === undefined && p.anyOf === undefined && p.allOf === undefined) return false\n return (\n (p.permission === undefined || rbac.can(p.permission)) &&\n (p.anyOf === undefined || rbac.canAny(p.anyOf)) &&\n (p.allOf === undefined || rbac.canAll(p.allOf))\n )\n}\n\nfunction checkRoles(rbac: RbacChecker, p: LooseCondition & { role?: string | undefined }): boolean {\n if (p.role === undefined && p.anyOf === undefined && p.allOf === undefined) return false\n return (\n (p.role === undefined || rbac.hasRole(p.role)) &&\n (p.anyOf === undefined || rbac.hasAnyRole(p.anyOf)) &&\n (p.allOf === undefined || rbac.hasAllRoles(p.allOf))\n )\n}\n\n/** Renders `children` if the user has the permission(s) — like spatie's `@can` / `@canany`. */\nexport function Can(props: CanProps) {\n const rbac = useRbac()\n if (rbac.loading) return null\n return <>{checkPermissions(rbac, props) ? props.children : props.fallback}</>\n}\n\n/** Renders `children` if the user does NOT have the permission(s) — like spatie's `@cannot`. */\nexport function Cannot(props: CannotProps) {\n const rbac = useRbac()\n if (rbac.loading) return null\n return <>{checkPermissions(rbac, props) ? props.fallback : props.children}</>\n}\n\n/** Renders `children` if the user has the role(s) — like spatie's `@role` / `@hasanyrole` / `@hasallroles`. */\nexport function HasRole(props: HasRoleProps) {\n const rbac = useRbac()\n if (rbac.loading) return null\n return <>{checkRoles(rbac, props) ? props.children : props.fallback}</>\n}\n"],"mappings":";;;AAAA,SAAS,uBAAuB;AAgChC,IAAM,QAAsB,EAAE,OAAO,CAAC,GAAG,aAAa,CAAC,EAAE;AAEzD,SAAS,QAAQ,OAA0C;AACzD,QAAM,MAAgB,CAAC;AACvB,aAAW,QAAQ,OAAO;AACxB,QAAI,OAAO,SAAS,SAAU,KAAI,KAAK,IAAI;AAAA,QACtC,KAAI,KAAK,GAAG,IAAI;AAAA,EACvB;AACA,SAAO;AACT;AAEA,SAAS,YAAY,SAAiB,UAA2B;AAC/D,MAAI;AACF,WAAO,gBAAgB,SAAS,QAAQ;AAAA,EAC1C,QAAQ;AACN,WAAO;AAAA,E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AE,UAAU,UAAa,EAAE,UAAU,OAAW,QAAO;AACzF,UACG,EAAE,eAAe,UAAa,KAAK,IAAI,EAAE,UAAU,OACnD,EAAE,UAAU,UAAa,KAAK,OAAO,EAAE,KAAK,OAC5C,EAAE,UAAU,UAAa,KAAK,OAAO,EAAE,KAAK;AAEjD;AAEA,SAAS,WAAW,MAAmB,GAA4D;AACjG,MAAI,EAAE,SAAS,UAAa,EAAE,UAAU,UAAa,EAAE,UAAU,OAAW,QAAO;AACnF,UACG,EAAE,SAAS,UAAa,KAAK,QAAQ,EAAE,IAAI,OAC3C,EAAE,UAAU,UAAa,KAAK,WAAW,EAAE,KAAK,OAChD,EAAE,UAAU,UAAa,KAAK,YAAY,EAAE,KAAK;AAEtD;AAGO,SAAS,IAAI,OAAiB;AACnC,QAAM,OAAO,QAAQ;AACrB,MAAI,KAAK,QAAS,QAAO;AACzB,SAAO,gBAAAA,KAAA,YAAG,2BAAiB,MAAM,KAAK,IAAI,MAAM,WAAW,MAAM,UAAS;AAC5E;AAGO,SAAS,OAAO,OAAoB;AACzC,QAAM,OAAO,QAAQ;AACrB,MAAI,KAAK,QAAS,QAAO;AACzB,SAAO,gBAAAA,KAAA,YAAG,2BAAiB,MAAM,KAAK,IAAI,MAAM,WAAW,MAAM,UAAS;AAC5E;AAGO,SAAS,QAAQ,OAAqB;AAC3C,QAAM,OAAO,QAAQ;AACrB,MAAI,KAAK,QAAS,QAAO;AACzB,SAAO,gBAAAA,KAAA,YAAG,qBAAW,MAAM,KAAK,IAAI,MAAM,WAAW,MAAM,UAAS;AACtE;","names":["jsx"]}
1
+ {"version":3,"sources":["../src/checker.ts","../src/context.tsx","../src/components.tsx"],"sourcesContent":["import { wildcardImplies } from '@anievo-id/rbac-evolution'\nimport type { Many, RbacSnapshot } from '@anievo-id/rbac-evolution'\n\nexport interface RbacCheckerOptions {\n /** Treat granted permissions as wildcard patterns (`articles.*`). Must match the server's `wildcard` setting. */\n wildcard?: boolean | undefined\n /** Roles that pass every permission check (like spatie's `Gate::before` super-admin pattern). */\n superAdminRoles?: readonly string[] | undefined\n /** The snapshot is still being fetched: `<Can>`, `<Cannot>` and `<HasRole>` render nothing. Default: `false`. */\n loading?: boolean | undefined\n}\n\n/** Synchronous checks against a {@link RbacSnapshot}. */\nexport interface RbacChecker {\n readonly roles: readonly string[]\n readonly permissions: readonly string[]\n /** `true` if the subject has one of the configured `superAdminRoles`. */\n readonly isSuperAdmin: boolean\n /** `true` while the snapshot is still being fetched (the `loading` option). Every check, `cannot` included, returns `false` meanwhile. */\n readonly loading: boolean\n can(permission: string): boolean\n cannot(permission: string): boolean\n /** `true` if ANY of the permissions is granted. `false` for an empty list. */\n canAny(...permissions: Many<string>[]): boolean\n /** `true` if ALL of the permissions are granted. `false` for an empty list (deny by default, like the Vue package). */\n canAll(...permissions: Many<string>[]): boolean\n /** `true` if the subject has the role — or ANY of the roles when given an array. */\n hasRole(roles: Many<string>): boolean\n hasAnyRole(...roles: Many<string>[]): boolean\n hasAllRoles(...roles: Many<string>[]): boolean\n}\n\nconst EMPTY: RbacSnapshot = { roles: [], permissions: [] }\n\nfunction flatten(items: readonly Many<string>[]): string[] {\n const out: string[] = []\n for (const item of items) {\n if (typeof item === 'string') out.push(item)\n else out.push(...item)\n }\n return out\n}\n\nfunction safeImplies(granted: string, required: string): boolean {\n try {\n return wildcardImplies(granted, required)\n } catch {\n return false\n }\n}\n\n/**\n * Builds a pure, synchronous checker for a snapshot (as returned by `rbac.for(user).snapshot()`).\n * Used by `RbacProvider`, but usable on its own too.\n */\nexport function createRbacChecker(\n snapshot: RbacSnapshot | null | undefined,\n options: RbacCheckerOptions = {},\n): RbacChecker {\n const { roles, permissions } = snapshot ?? EMPTY\n const roleSet = new Set(roles)\n const permissionSet = new Set(permissions)\n const wildcard = options.wildcard ?? false\n // While loading, every check (`cannot` too) is false: neither a stale grant nor \"no access\" UI shows.\n const loading = options.loading ?? false\n const isSuperAdmin = !loading && (options.superAdminRoles ?? []).some((r) => roleSet.has(r))\n\n const can = (permission: string): boolean => {\n if (loading) return false\n if (isSuperAdmin) return true\n const name = permission.trim()\n if (name === '') return false\n if (permissionSet.has(name)) return true\n return wildcard && permissions.some((granted) => safeImplies(granted, name))\n }\n const hasOne = (role: string): boolean => !loading && roleSet.has(role.trim())\n\n return {\n roles,\n permissions,\n isSuperAdmin,\n loading,\n can,\n cannot: (permission) => !loading && !can(permission),\n canAny: (...list) => flatten(list).some(can),\n canAll: (...list) => {\n const wanted = flatten(list)\n return wanted.length > 0 && wanted.every(can)\n },\n hasRole: (list) => flatten([list]).some(hasOne),\n hasAnyRole: (...list) => flatten(list).some(hasOne),\n hasAllRoles: (...list) => {\n const wanted = flatten(list)\n return wanted.length > 0 && wanted.every(hasOne)\n },\n }\n}\n","import { createContext, useContext, useMemo } from 'react'\nimport type { ReactNode } from 'react'\nimport type { Many, RbacSnapshot } from '@anievo-id/rbac-evolution'\nimport { createRbacChecker } from './checker'\nimport type { RbacChecker } from './checker'\n\nconst RbacContext = createContext<RbacChecker | null>(null)\nRbacContext.displayName = 'RbacContext'\n\nexport interface RbacProviderProps {\n /** Roles & permissions of the current user, e.g. from `rbac.for(user).snapshot()` on the server. `null` = guest. */\n snapshot: RbacSnapshot | null | undefined\n /** Enable wildcard matching (`articles.*`). Must match the server's `wildcard` setting. Default: `false`. */\n wildcard?: boolean | undefined\n /** Roles that pass every `can` check (super admin). */\n superAdminRoles?: readonly string[] | undefined\n /**\n * The snapshot is still being fetched. `<Can>`, `<Cannot>` and `<HasRole>` then render nothing\n * (not even `fallback`), so nothing flashes before the real permissions arrive. Default: `false`.\n */\n loading?: boolean | undefined\n children?: ReactNode | undefined\n}\n\n/**\n * Provides a user's roles & permissions to `useCan()`, `<Can>`, ...\n *\n * UI only: this hides and shows elements. Always enforce authorization on the server.\n */\nexport function RbacProvider({ snapshot, wildcard = false, superAdminRoles, loading = false, children }: RbacProviderProps) {\n const superKey = superAdminRoles?.join('\\u0000') ?? ''\n const checker = useMemo(\n () => createRbacChecker(snapshot, superAdminRoles ? { wildcard, superAdminRoles, loading } : { wildcard, loading }),\n // `superKey` keeps inline arrays (`superAdminRoles={['admin']}`) from recomputing every render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [snapshot, wildcard, superKey, loading],\n )\n return <RbacContext.Provider value={checker}>{children}</RbacContext.Provider>\n}\n\n/** Returns the checker of the nearest `RbacProvider`. Throws when there is none. */\nexport function useRbac(): RbacChecker {\n const checker = useContext(RbacContext)\n if (!checker) {\n throw new Error('useRbac() must be used inside <RbacProvider>.')\n }\n return checker\n}\n\nexport function useCan(permission: string): boolean {\n return useRbac().can(permission)\n}\n\nexport function useCannot(permission: string): boolean {\n return useRbac().cannot(permission)\n}\n\nexport function useCanAny(...permissions: Many<string>[]): boolean {\n return useRbac().canAny(...permissions)\n}\n\nexport function useCanAll(...permissions: Many<string>[]): boolean {\n return useRbac().canAll(...permissions)\n}\n\n/** `true` if the user has the role — or ANY of the roles when given an array. */\nexport function useHasRole(role: Many<string>): boolean {\n return useRbac().hasRole(role)\n}\n\nexport function useHasAnyRole(...roles: Many<string>[]): boolean {\n return useRbac().hasAnyRole(...roles)\n}\n\nexport function useHasAllRoles(...roles: Many<string>[]): boolean {\n return useRbac().hasAllRoles(...roles)\n}\n","import type { ReactNode } from 'react'\nimport type { RbacChecker } from './checker'\nimport { useRbac } from './context'\n\n/** Exactly one of `permission`, `anyOf` or `allOf`. */\nexport type PermissionCondition =\n | { permission: string; anyOf?: never; allOf?: never }\n | { permission?: never; anyOf: readonly string[]; allOf?: never }\n | { permission?: never; anyOf?: never; allOf: readonly string[] }\n\n/** Exactly one of `role`, `anyOf` or `allOf`. */\nexport type RoleCondition =\n | { role: string; anyOf?: never; allOf?: never }\n | { role?: never; anyOf: readonly string[]; allOf?: never }\n | { role?: never; anyOf?: never; allOf: readonly string[] }\n\ninterface GateProps {\n children?: ReactNode | undefined\n /** Rendered when the check fails. Default: nothing. */\n fallback?: ReactNode | undefined\n}\n\nexport type CanProps = PermissionCondition & GateProps\nexport type CannotProps = PermissionCondition & GateProps\nexport type HasRoleProps = RoleCondition & GateProps\nexport type UnlessRoleProps = RoleCondition & GateProps\n\ninterface LooseCondition {\n anyOf?: readonly string[] | undefined\n allOf?: readonly string[] | undefined\n}\n\n// Conditions are ANDed; no condition at all is denied (deny by default, also for untyped JS callers).\nfunction checkPermissions(rbac: RbacChecker, p: LooseCondition & { permission?: string | undefined }): boolean {\n if (p.permission === undefined && p.anyOf === undefined && p.allOf === undefined) return false\n return (\n (p.permission === undefined || rbac.can(p.permission)) &&\n (p.anyOf === undefined || rbac.canAny(p.anyOf)) &&\n (p.allOf === undefined || rbac.canAll(p.allOf))\n )\n}\n\nfunction checkRoles(rbac: RbacChecker, p: LooseCondition & { role?: string | undefined }): boolean {\n if (p.role === undefined && p.anyOf === undefined && p.allOf === undefined) return false\n return (\n (p.role === undefined || rbac.hasRole(p.role)) &&\n (p.anyOf === undefined || rbac.hasAnyRole(p.anyOf)) &&\n (p.allOf === undefined || rbac.hasAllRoles(p.allOf))\n )\n}\n\n/** Renders `children` if the user has the permission(s) — like spatie's `@can` / `@canany`. */\nexport function Can(props: CanProps) {\n const rbac = useRbac()\n if (rbac.loading) return null\n return <>{checkPermissions(rbac, props) ? props.children : props.fallback}</>\n}\n\n/** Renders `children` if the user does NOT have the permission(s) — like spatie's `@cannot`. */\nexport function Cannot(props: CannotProps) {\n const rbac = useRbac()\n if (rbac.loading) return null\n return <>{checkPermissions(rbac, props) ? props.fallback : props.children}</>\n}\n\n/** Renders `children` if the user has the role(s) — like spatie's `@role` / `@hasanyrole` / `@hasallroles`. */\nexport function HasRole(props: HasRoleProps) {\n const rbac = useRbac()\n if (rbac.loading) return null\n return <>{checkRoles(rbac, props) ? props.children : props.fallback}</>\n}\n\n/**\n * Renders `children` if the user does NOT have the role(s) — like spatie's `@unlessrole`.\n * `anyOf`: none of them. `allOf`: not all of them. Without a condition it renders `fallback` (deny by default).\n */\nexport function UnlessRole(props: UnlessRoleProps) {\n const rbac = useRbac()\n if (rbac.loading) return null\n const loose = props as LooseCondition & { role?: string | undefined }\n const hasCondition = loose.role !== undefined || loose.anyOf !== undefined || loose.allOf !== undefined\n return <>{hasCondition && !checkRoles(rbac, props) ? props.children : props.fallback}</>\n}\n"],"mappings":";;;AAAA,SAAS,uBAAuB;AAgChC,IAAM,QAAsB,EAAE,OAAO,CAAC,GAAG,aAAa,CAAC,EAAE;AAEzD,SAAS,QAAQ,OAA0C;AACzD,QAAM,MAAgB,CAAC;AACvB,aAAW,QAAQ,OAAO;AACxB,QAAI,OAAO,SAAS,SAAU,KAAI,KAAK,IAAI;AAAA,QACtC,KAAI,KAAK,GAAG,IAAI;AAAA,EACvB;AACA,SAAO;AACT;AAEA,SAAS,YAAY,SAAiB,UAA2B;AAC/D,MAAI;AACF,WAAO,gBAAgB,SAAS,QAAQ;AAAA,EAC1C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,kBACd,UACA,UAA8B,CAAC,GAClB;AACb,QAAM,EAAE,OAAO,YAAY,IAAI,YAAY;AAC3C,QAAM,UAAU,IAAI,IAAI,KAAK;AAC7B,QAAM,gBAAgB,IAAI,IAAI,WAAW;AACzC,QAAM,WAAW,QAAQ,YAAY;AAErC,QAAM,UAAU,QAAQ,WAAW;AACnC,QAAM,eAAe,CAAC,YAAY,QAAQ,mBAAmB,CAAC,GAAG,KAAK,CAAC,MAAM,QAAQ,IAAI,CAAC,CAAC;AAE3F,QAAM,MAAM,CAAC,eAAgC;AAC3C,QAAI,QAAS,QAAO;AACpB,QAAI,aAAc,QAAO;AACzB,UAAM,OAAO,WAAW,KAAK;AAC7B,QAAI,SAAS,GAAI,QAAO;AACxB,QAAI,cAAc,IAAI,IAAI,EAAG,QAAO;AACpC,WAAO,YAAY,YAAY,KAAK,CAAC,YAAY,YAAY,SAAS,IAAI,CAAC;AAAA,EAC7E;AACA,QAAM,SAAS,CAAC,SAA0B,CAAC,WAAW,QAAQ,IAAI,KAAK,KAAK,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AAM,OAAO,QAAQ;AACrB,MAAI,KAAK,QAAS,QAAO;AACzB,SAAO,gBAAAA,KAAA,YAAG,2BAAiB,MAAM,KAAK,IAAI,MAAM,WAAW,MAAM,UAAS;AAC5E;AAGO,SAAS,QAAQ,OAAqB;AAC3C,QAAM,OAAO,QAAQ;AACrB,MAAI,KAAK,QAAS,QAAO;AACzB,SAAO,gBAAAA,KAAA,YAAG,qBAAW,MAAM,KAAK,IAAI,MAAM,WAAW,MAAM,UAAS;AACtE;AAMO,SAAS,WAAW,OAAwB;AACjD,QAAM,OAAO,QAAQ;AACrB,MAAI,KAAK,QAAS,QAAO;AACzB,QAAM,QAAQ;AACd,QAAM,eAAe,MAAM,SAAS,UAAa,MAAM,UAAU,UAAa,MAAM,UAAU;AAC9F,SAAO,gBAAAA,KAAA,YAAG,0BAAgB,CAAC,WAAW,MAAM,KAAK,IAAI,MAAM,WAAW,MAAM,UAAS;AACvF;","names":["jsx"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anievo-id/rbac-evolution-react",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "React bindings for rbac-evolution: <Can>, useCan(), useHasRole().",
5
5
  "license": "MIT",
6
6
  "author": "AniEvo-ID (https://github.com/AniEvo-ID)",
@@ -46,7 +46,7 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@anievo-id/rbac-evolution": "^0.8.0"
49
+ "@anievo-id/rbac-evolution": "^0.9.0"
50
50
  },
51
51
  "peerDependencies": {
52
52
  "react": ">=18"