react-permission-gate 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
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 ADDED
@@ -0,0 +1,203 @@
1
+ # react-permission-gate
2
+
3
+ Flexible, type-safe permission management for React and React Router applications.
4
+
5
+ ## Features
6
+
7
+ - **Pure TypeScript core** — use `PermissionChecker` anywhere, no React needed
8
+ - **React integration** — `PermissionProvider`, `usePermissions` hook, `PermissionGate` component
9
+ - **React Router integration** — `ProtectedRoute` with redirect support
10
+ - **Admin bypass** — configurable admin role types that skip all checks
11
+ - **Type-safe permission constants** — `createPermissions()` with literal types
12
+ - **Tree-shakeable** — separate entry points, import only what you need
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install react-permission-gate
18
+ ```
19
+
20
+ ## Quick Start
21
+
22
+ ### 1. Define your permissions (optional but recommended)
23
+
24
+ ```ts
25
+ import { createPermissions } from "react-permission-gate";
26
+
27
+ export const PERMISSIONS = createPermissions({
28
+ USERS: {
29
+ READ: "system.users.read",
30
+ CREATE: "system.users.create",
31
+ DELETE: "system.users.delete",
32
+ },
33
+ GROUPS: {
34
+ READ: "system.groups.read",
35
+ },
36
+ });
37
+ ```
38
+
39
+ ### 2. Wrap your app with PermissionProvider
40
+
41
+ ```tsx
42
+ import { PermissionProvider } from "react-permission-gate/react";
43
+
44
+ function App() {
45
+ const { user, isLoading } = useAuth(); // your auth hook
46
+
47
+ return (
48
+ <PermissionProvider
49
+ permissions={user?.permissions ?? []}
50
+ userType={user?.role}
51
+ loading={isLoading}
52
+ >
53
+ <Router />
54
+ </PermissionProvider>
55
+ );
56
+ }
57
+ ```
58
+
59
+ ### 3. Use PermissionGate in components
60
+
61
+ ```tsx
62
+ import { PermissionGate } from "react-permission-gate/react";
63
+
64
+ function UsersPage() {
65
+ return (
66
+ <div>
67
+ <h1>Users</h1>
68
+
69
+ <PermissionGate permission={PERMISSIONS.USERS.CREATE}>
70
+ <button>Create User</button>
71
+ </PermissionGate>
72
+
73
+ <PermissionGate
74
+ anyOf={[PERMISSIONS.USERS.CREATE, PERMISSIONS.USERS.DELETE]}
75
+ fallback={<span>No access</span>}
76
+ >
77
+ <AdminPanel />
78
+ </PermissionGate>
79
+ </div>
80
+ );
81
+ }
82
+ ```
83
+
84
+ ### 4. Use usePermissions hook
85
+
86
+ ```tsx
87
+ import { usePermissions } from "react-permission-gate/react";
88
+
89
+ function UserActions() {
90
+ const { hasPermission, isAdmin } = usePermissions();
91
+
92
+ if (!hasPermission(PERMISSIONS.USERS.DELETE)) return null;
93
+
94
+ return <button>Delete User</button>;
95
+ }
96
+ ```
97
+
98
+ ### 5. Protect routes
99
+
100
+ ```tsx
101
+ import { ProtectedRoute } from "react-permission-gate/react-router";
102
+
103
+ <Route
104
+ path="/users"
105
+ element={
106
+ <ProtectedRoute
107
+ permission={PERMISSIONS.USERS.READ}
108
+ redirectTo="/unauthorized"
109
+ loadingComponent={<Spinner />}
110
+ >
111
+ <UsersPage />
112
+ </ProtectedRoute>
113
+ }
114
+ />
115
+ ```
116
+
117
+ ## API Reference
118
+
119
+ ### Core (`react-permission-gate`)
120
+
121
+ #### `PermissionChecker`
122
+
123
+ Pure TypeScript permission checker class.
124
+
125
+ ```ts
126
+ const checker = new PermissionChecker({
127
+ permissions: ["users.read", "users.create"],
128
+ userType: "USER",
129
+ adminTypes: ["ADMIN"], // default: ["ADMIN"]
130
+ adminBypass: true, // default: true
131
+ });
132
+
133
+ checker.hasPermission("users.read"); // true
134
+ checker.hasAnyPermission(["a", "b"]); // boolean
135
+ checker.hasAllPermissions(["a", "b"]); // boolean
136
+ checker.check("users.read"); // { granted: true, reason: "permission_found" }
137
+ checker.admin; // boolean
138
+ ```
139
+
140
+ #### `createPermissions(definition)`
141
+
142
+ Creates a deeply frozen, type-safe permission constants object.
143
+
144
+ ```ts
145
+ const PERMS = createPermissions({
146
+ USERS: { READ: "users.read" },
147
+ });
148
+ // typeof PERMS.USERS.READ → "users.read" (literal type)
149
+ ```
150
+
151
+ ### React (`react-permission-gate/react`)
152
+
153
+ #### `<PermissionProvider>`
154
+
155
+ | Prop | Type | Default | Description |
156
+ |---|---|---|---|
157
+ | `permissions` | `string[]` | required | User's permission strings |
158
+ | `userType` | `string` | `""` | User's type/role |
159
+ | `adminTypes` | `string[]` | `["ADMIN"]` | Types that bypass all checks |
160
+ | `adminBypass` | `boolean` | `true` | Whether admin bypass is enabled |
161
+ | `loading` | `boolean` | `false` | External loading state |
162
+
163
+ #### `usePermissions()`
164
+
165
+ Returns: `{ permissions, userType, isAdmin, isLoading, hasPermission, hasAnyPermission, hasAllPermissions, check }`
166
+
167
+ #### `<PermissionGate>`
168
+
169
+ | Prop | Type | Default | Description |
170
+ |---|---|---|---|
171
+ | `permission` | `string` | - | Single required permission |
172
+ | `anyOf` | `string[]` | - | Show if user has any |
173
+ | `allOf` | `string[]` | - | Show if user has all |
174
+ | `fallback` | `ReactNode` | `null` | Shown when denied |
175
+
176
+ ### React Router (`react-permission-gate/react-router`)
177
+
178
+ #### `<ProtectedRoute>`
179
+
180
+ | Prop | Type | Default | Description |
181
+ |---|---|---|---|
182
+ | `permission` | `string` | - | Single required permission |
183
+ | `anyOf` | `string[]` | - | Access if user has any |
184
+ | `allOf` | `string[]` | - | Access if user has all |
185
+ | `redirectTo` | `string` | `"/"` | Redirect on denied |
186
+ | `loadingComponent` | `ReactNode` | `null` | Shown while loading |
187
+
188
+ ## Admin Bypass
189
+
190
+ By default, users with `userType: "ADMIN"` bypass all permission checks. Configure via:
191
+
192
+ ```tsx
193
+ <PermissionProvider
194
+ permissions={user.permissions}
195
+ userType={user.role}
196
+ adminTypes={["ADMIN", "SUPER_ADMIN"]} // custom admin types
197
+ adminBypass={false} // disable bypass entirely
198
+ >
199
+ ```
200
+
201
+ ## License
202
+
203
+ MIT
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/core/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ PermissionChecker: () => PermissionChecker,
24
+ createPermissions: () => createPermissions
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+
28
+ // src/core/permission-checker.ts
29
+ var PermissionChecker = class {
30
+ constructor(config) {
31
+ this.permissions = new Set(config.permissions);
32
+ const adminTypes = config.adminTypes ?? ["ADMIN"];
33
+ const bypass = config.adminBypass ?? true;
34
+ this.isAdmin = bypass && adminTypes.includes(config.userType ?? "");
35
+ }
36
+ /** Whether this checker was created with an admin-type user */
37
+ get admin() {
38
+ return this.isAdmin;
39
+ }
40
+ /** Check if user has a specific permission. Admins always return true. */
41
+ hasPermission(permission) {
42
+ if (this.isAdmin) return true;
43
+ return this.permissions.has(permission);
44
+ }
45
+ /** Check if user has ANY of the given permissions. Admins always return true. */
46
+ hasAnyPermission(permissionList) {
47
+ if (this.isAdmin) return true;
48
+ return permissionList.some((p) => this.permissions.has(p));
49
+ }
50
+ /** Check if user has ALL of the given permissions. Admins always return true. */
51
+ hasAllPermissions(permissionList) {
52
+ if (this.isAdmin) return true;
53
+ return permissionList.every((p) => this.permissions.has(p));
54
+ }
55
+ /** Detailed permission check with reason for the result */
56
+ check(permission) {
57
+ if (this.isAdmin) {
58
+ return { granted: true, reason: "admin_bypass" };
59
+ }
60
+ if (this.permissions.has(permission)) {
61
+ return { granted: true, reason: "permission_found" };
62
+ }
63
+ return { granted: false, reason: "permission_missing" };
64
+ }
65
+ };
66
+
67
+ // src/core/create-permissions.ts
68
+ function createPermissions(definition) {
69
+ const frozen = { ...definition };
70
+ for (const key of Object.keys(frozen)) {
71
+ frozen[key] = Object.freeze(
72
+ frozen[key]
73
+ );
74
+ }
75
+ return Object.freeze(frozen);
76
+ }
77
+ // Annotate the CommonJS export names for ESM import in node:
78
+ 0 && (module.exports = {
79
+ PermissionChecker,
80
+ createPermissions
81
+ });
82
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/index.ts","../../src/core/permission-checker.ts","../../src/core/create-permissions.ts"],"sourcesContent":["export { PermissionChecker } from \"./permission-checker\";\nexport { createPermissions } from \"./create-permissions\";\nexport type { ExtractPermissions } from \"./create-permissions\";\nexport type {\n PermissionConfig,\n PermissionCheckResult,\n PermissionCheckReason,\n DeepReadonly,\n} from \"./types\";\n","import type { PermissionCheckResult, PermissionConfig } from \"./types\";\n\n/**\n * Pure TypeScript permission checker — no React dependency.\n *\n * @example\n * const checker = new PermissionChecker({\n * permissions: [\"users.read\", \"users.create\"],\n * userType: \"USER\",\n * });\n *\n * checker.hasPermission(\"users.read\"); // true\n * checker.hasPermission(\"users.delete\"); // false\n */\nexport class PermissionChecker {\n private readonly permissions: Set<string>;\n private readonly isAdmin: boolean;\n\n constructor(config: PermissionConfig) {\n this.permissions = new Set(config.permissions);\n const adminTypes = config.adminTypes ?? [\"ADMIN\"];\n const bypass = config.adminBypass ?? true;\n this.isAdmin = bypass && adminTypes.includes(config.userType ?? \"\");\n }\n\n /** Whether this checker was created with an admin-type user */\n get admin(): boolean {\n return this.isAdmin;\n }\n\n /** Check if user has a specific permission. Admins always return true. */\n hasPermission(permission: string): boolean {\n if (this.isAdmin) return true;\n return this.permissions.has(permission);\n }\n\n /** Check if user has ANY of the given permissions. Admins always return true. */\n hasAnyPermission(permissionList: string[]): boolean {\n if (this.isAdmin) return true;\n return permissionList.some((p) => this.permissions.has(p));\n }\n\n /** Check if user has ALL of the given permissions. Admins always return true. */\n hasAllPermissions(permissionList: string[]): boolean {\n if (this.isAdmin) return true;\n return permissionList.every((p) => this.permissions.has(p));\n }\n\n /** Detailed permission check with reason for the result */\n check(permission: string): PermissionCheckResult {\n if (this.isAdmin) {\n return { granted: true, reason: \"admin_bypass\" };\n }\n\n if (this.permissions.has(permission)) {\n return { granted: true, reason: \"permission_found\" };\n }\n\n return { granted: false, reason: \"permission_missing\" };\n }\n}\n","import type { DeepReadonly } from \"./types\";\n\n/**\n * Type-safe helper to define permission constants with literal types.\n * Returns a deeply frozen, readonly object.\n *\n * @example\n * const PERMISSIONS = createPermissions({\n * USERS: {\n * READ: \"system.users.read\",\n * CREATE: \"system.users.create\",\n * },\n * GROUPS: {\n * READ: \"system.groups.read\",\n * },\n * });\n *\n * // typeof PERMISSIONS.USERS.READ → \"system.users.read\" (literal type)\n */\nexport function createPermissions<\n T extends Record<string, Record<string, string>>,\n>(definition: T): DeepReadonly<T> {\n const frozen = { ...definition };\n\n for (const key of Object.keys(frozen)) {\n (frozen as Record<string, unknown>)[key] = Object.freeze(\n (frozen as Record<string, Record<string, string>>)[key],\n );\n }\n\n return Object.freeze(frozen) as DeepReadonly<T>;\n}\n\n/** Extracts all permission string values from a createPermissions() result */\nexport type ExtractPermissions<T> =\n T extends Record<string, Record<string, infer V>> ? V : never;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACcO,IAAM,oBAAN,MAAwB;AAAA,EAI7B,YAAY,QAA0B;AACpC,SAAK,cAAc,IAAI,IAAI,OAAO,WAAW;AAC7C,UAAM,aAAa,OAAO,cAAc,CAAC,OAAO;AAChD,UAAM,SAAS,OAAO,eAAe;AACrC,SAAK,UAAU,UAAU,WAAW,SAAS,OAAO,YAAY,EAAE;AAAA,EACpE;AAAA;AAAA,EAGA,IAAI,QAAiB;AACnB,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,cAAc,YAA6B;AACzC,QAAI,KAAK,QAAS,QAAO;AACzB,WAAO,KAAK,YAAY,IAAI,UAAU;AAAA,EACxC;AAAA;AAAA,EAGA,iBAAiB,gBAAmC;AAClD,QAAI,KAAK,QAAS,QAAO;AACzB,WAAO,eAAe,KAAK,CAAC,MAAM,KAAK,YAAY,IAAI,CAAC,CAAC;AAAA,EAC3D;AAAA;AAAA,EAGA,kBAAkB,gBAAmC;AACnD,QAAI,KAAK,QAAS,QAAO;AACzB,WAAO,eAAe,MAAM,CAAC,MAAM,KAAK,YAAY,IAAI,CAAC,CAAC;AAAA,EAC5D;AAAA;AAAA,EAGA,MAAM,YAA2C;AAC/C,QAAI,KAAK,SAAS;AAChB,aAAO,EAAE,SAAS,MAAM,QAAQ,eAAe;AAAA,IACjD;AAEA,QAAI,KAAK,YAAY,IAAI,UAAU,GAAG;AACpC,aAAO,EAAE,SAAS,MAAM,QAAQ,mBAAmB;AAAA,IACrD;AAEA,WAAO,EAAE,SAAS,OAAO,QAAQ,qBAAqB;AAAA,EACxD;AACF;;;ACzCO,SAAS,kBAEd,YAAgC;AAChC,QAAM,SAAS,EAAE,GAAG,WAAW;AAE/B,aAAW,OAAO,OAAO,KAAK,MAAM,GAAG;AACrC,IAAC,OAAmC,GAAG,IAAI,OAAO;AAAA,MAC/C,OAAkD,GAAG;AAAA,IACxD;AAAA,EACF;AAEA,SAAO,OAAO,OAAO,MAAM;AAC7B;","names":[]}
@@ -0,0 +1,73 @@
1
+ /** Configuration for the permission checker */
2
+ interface PermissionConfig {
3
+ /** List of permission strings the user has */
4
+ permissions: string[];
5
+ /** User's type/role identifier (e.g., "ADMIN", "USER") */
6
+ userType?: string;
7
+ /** User types that bypass all permission checks (default: ["ADMIN"]) */
8
+ adminTypes?: string[];
9
+ /** Whether admin types bypass checks (default: true) */
10
+ adminBypass?: boolean;
11
+ }
12
+ /** Reason for a permission check result */
13
+ type PermissionCheckReason = "admin_bypass" | "permission_found" | "permission_missing" | "no_check";
14
+ /** Result of a permission check with detailed reason */
15
+ interface PermissionCheckResult {
16
+ granted: boolean;
17
+ reason: PermissionCheckReason;
18
+ }
19
+ /** Deep readonly utility type */
20
+ type DeepReadonly<T> = {
21
+ readonly [K in keyof T]: T[K] extends Record<string, unknown> ? DeepReadonly<T[K]> : T[K];
22
+ };
23
+
24
+ /**
25
+ * Pure TypeScript permission checker — no React dependency.
26
+ *
27
+ * @example
28
+ * const checker = new PermissionChecker({
29
+ * permissions: ["users.read", "users.create"],
30
+ * userType: "USER",
31
+ * });
32
+ *
33
+ * checker.hasPermission("users.read"); // true
34
+ * checker.hasPermission("users.delete"); // false
35
+ */
36
+ declare class PermissionChecker {
37
+ private readonly permissions;
38
+ private readonly isAdmin;
39
+ constructor(config: PermissionConfig);
40
+ /** Whether this checker was created with an admin-type user */
41
+ get admin(): boolean;
42
+ /** Check if user has a specific permission. Admins always return true. */
43
+ hasPermission(permission: string): boolean;
44
+ /** Check if user has ANY of the given permissions. Admins always return true. */
45
+ hasAnyPermission(permissionList: string[]): boolean;
46
+ /** Check if user has ALL of the given permissions. Admins always return true. */
47
+ hasAllPermissions(permissionList: string[]): boolean;
48
+ /** Detailed permission check with reason for the result */
49
+ check(permission: string): PermissionCheckResult;
50
+ }
51
+
52
+ /**
53
+ * Type-safe helper to define permission constants with literal types.
54
+ * Returns a deeply frozen, readonly object.
55
+ *
56
+ * @example
57
+ * const PERMISSIONS = createPermissions({
58
+ * USERS: {
59
+ * READ: "system.users.read",
60
+ * CREATE: "system.users.create",
61
+ * },
62
+ * GROUPS: {
63
+ * READ: "system.groups.read",
64
+ * },
65
+ * });
66
+ *
67
+ * // typeof PERMISSIONS.USERS.READ → "system.users.read" (literal type)
68
+ */
69
+ declare function createPermissions<T extends Record<string, Record<string, string>>>(definition: T): DeepReadonly<T>;
70
+ /** Extracts all permission string values from a createPermissions() result */
71
+ type ExtractPermissions<T> = T extends Record<string, Record<string, infer V>> ? V : never;
72
+
73
+ export { type DeepReadonly, type ExtractPermissions, type PermissionCheckReason, type PermissionCheckResult, PermissionChecker, type PermissionConfig, createPermissions };
@@ -0,0 +1,73 @@
1
+ /** Configuration for the permission checker */
2
+ interface PermissionConfig {
3
+ /** List of permission strings the user has */
4
+ permissions: string[];
5
+ /** User's type/role identifier (e.g., "ADMIN", "USER") */
6
+ userType?: string;
7
+ /** User types that bypass all permission checks (default: ["ADMIN"]) */
8
+ adminTypes?: string[];
9
+ /** Whether admin types bypass checks (default: true) */
10
+ adminBypass?: boolean;
11
+ }
12
+ /** Reason for a permission check result */
13
+ type PermissionCheckReason = "admin_bypass" | "permission_found" | "permission_missing" | "no_check";
14
+ /** Result of a permission check with detailed reason */
15
+ interface PermissionCheckResult {
16
+ granted: boolean;
17
+ reason: PermissionCheckReason;
18
+ }
19
+ /** Deep readonly utility type */
20
+ type DeepReadonly<T> = {
21
+ readonly [K in keyof T]: T[K] extends Record<string, unknown> ? DeepReadonly<T[K]> : T[K];
22
+ };
23
+
24
+ /**
25
+ * Pure TypeScript permission checker — no React dependency.
26
+ *
27
+ * @example
28
+ * const checker = new PermissionChecker({
29
+ * permissions: ["users.read", "users.create"],
30
+ * userType: "USER",
31
+ * });
32
+ *
33
+ * checker.hasPermission("users.read"); // true
34
+ * checker.hasPermission("users.delete"); // false
35
+ */
36
+ declare class PermissionChecker {
37
+ private readonly permissions;
38
+ private readonly isAdmin;
39
+ constructor(config: PermissionConfig);
40
+ /** Whether this checker was created with an admin-type user */
41
+ get admin(): boolean;
42
+ /** Check if user has a specific permission. Admins always return true. */
43
+ hasPermission(permission: string): boolean;
44
+ /** Check if user has ANY of the given permissions. Admins always return true. */
45
+ hasAnyPermission(permissionList: string[]): boolean;
46
+ /** Check if user has ALL of the given permissions. Admins always return true. */
47
+ hasAllPermissions(permissionList: string[]): boolean;
48
+ /** Detailed permission check with reason for the result */
49
+ check(permission: string): PermissionCheckResult;
50
+ }
51
+
52
+ /**
53
+ * Type-safe helper to define permission constants with literal types.
54
+ * Returns a deeply frozen, readonly object.
55
+ *
56
+ * @example
57
+ * const PERMISSIONS = createPermissions({
58
+ * USERS: {
59
+ * READ: "system.users.read",
60
+ * CREATE: "system.users.create",
61
+ * },
62
+ * GROUPS: {
63
+ * READ: "system.groups.read",
64
+ * },
65
+ * });
66
+ *
67
+ * // typeof PERMISSIONS.USERS.READ → "system.users.read" (literal type)
68
+ */
69
+ declare function createPermissions<T extends Record<string, Record<string, string>>>(definition: T): DeepReadonly<T>;
70
+ /** Extracts all permission string values from a createPermissions() result */
71
+ type ExtractPermissions<T> = T extends Record<string, Record<string, infer V>> ? V : never;
72
+
73
+ export { type DeepReadonly, type ExtractPermissions, type PermissionCheckReason, type PermissionCheckResult, PermissionChecker, type PermissionConfig, createPermissions };
@@ -0,0 +1,54 @@
1
+ // src/core/permission-checker.ts
2
+ var PermissionChecker = class {
3
+ constructor(config) {
4
+ this.permissions = new Set(config.permissions);
5
+ const adminTypes = config.adminTypes ?? ["ADMIN"];
6
+ const bypass = config.adminBypass ?? true;
7
+ this.isAdmin = bypass && adminTypes.includes(config.userType ?? "");
8
+ }
9
+ /** Whether this checker was created with an admin-type user */
10
+ get admin() {
11
+ return this.isAdmin;
12
+ }
13
+ /** Check if user has a specific permission. Admins always return true. */
14
+ hasPermission(permission) {
15
+ if (this.isAdmin) return true;
16
+ return this.permissions.has(permission);
17
+ }
18
+ /** Check if user has ANY of the given permissions. Admins always return true. */
19
+ hasAnyPermission(permissionList) {
20
+ if (this.isAdmin) return true;
21
+ return permissionList.some((p) => this.permissions.has(p));
22
+ }
23
+ /** Check if user has ALL of the given permissions. Admins always return true. */
24
+ hasAllPermissions(permissionList) {
25
+ if (this.isAdmin) return true;
26
+ return permissionList.every((p) => this.permissions.has(p));
27
+ }
28
+ /** Detailed permission check with reason for the result */
29
+ check(permission) {
30
+ if (this.isAdmin) {
31
+ return { granted: true, reason: "admin_bypass" };
32
+ }
33
+ if (this.permissions.has(permission)) {
34
+ return { granted: true, reason: "permission_found" };
35
+ }
36
+ return { granted: false, reason: "permission_missing" };
37
+ }
38
+ };
39
+
40
+ // src/core/create-permissions.ts
41
+ function createPermissions(definition) {
42
+ const frozen = { ...definition };
43
+ for (const key of Object.keys(frozen)) {
44
+ frozen[key] = Object.freeze(
45
+ frozen[key]
46
+ );
47
+ }
48
+ return Object.freeze(frozen);
49
+ }
50
+ export {
51
+ PermissionChecker,
52
+ createPermissions
53
+ };
54
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/permission-checker.ts","../../src/core/create-permissions.ts"],"sourcesContent":["import type { PermissionCheckResult, PermissionConfig } from \"./types\";\n\n/**\n * Pure TypeScript permission checker — no React dependency.\n *\n * @example\n * const checker = new PermissionChecker({\n * permissions: [\"users.read\", \"users.create\"],\n * userType: \"USER\",\n * });\n *\n * checker.hasPermission(\"users.read\"); // true\n * checker.hasPermission(\"users.delete\"); // false\n */\nexport class PermissionChecker {\n private readonly permissions: Set<string>;\n private readonly isAdmin: boolean;\n\n constructor(config: PermissionConfig) {\n this.permissions = new Set(config.permissions);\n const adminTypes = config.adminTypes ?? [\"ADMIN\"];\n const bypass = config.adminBypass ?? true;\n this.isAdmin = bypass && adminTypes.includes(config.userType ?? \"\");\n }\n\n /** Whether this checker was created with an admin-type user */\n get admin(): boolean {\n return this.isAdmin;\n }\n\n /** Check if user has a specific permission. Admins always return true. */\n hasPermission(permission: string): boolean {\n if (this.isAdmin) return true;\n return this.permissions.has(permission);\n }\n\n /** Check if user has ANY of the given permissions. Admins always return true. */\n hasAnyPermission(permissionList: string[]): boolean {\n if (this.isAdmin) return true;\n return permissionList.some((p) => this.permissions.has(p));\n }\n\n /** Check if user has ALL of the given permissions. Admins always return true. */\n hasAllPermissions(permissionList: string[]): boolean {\n if (this.isAdmin) return true;\n return permissionList.every((p) => this.permissions.has(p));\n }\n\n /** Detailed permission check with reason for the result */\n check(permission: string): PermissionCheckResult {\n if (this.isAdmin) {\n return { granted: true, reason: \"admin_bypass\" };\n }\n\n if (this.permissions.has(permission)) {\n return { granted: true, reason: \"permission_found\" };\n }\n\n return { granted: false, reason: \"permission_missing\" };\n }\n}\n","import type { DeepReadonly } from \"./types\";\n\n/**\n * Type-safe helper to define permission constants with literal types.\n * Returns a deeply frozen, readonly object.\n *\n * @example\n * const PERMISSIONS = createPermissions({\n * USERS: {\n * READ: \"system.users.read\",\n * CREATE: \"system.users.create\",\n * },\n * GROUPS: {\n * READ: \"system.groups.read\",\n * },\n * });\n *\n * // typeof PERMISSIONS.USERS.READ → \"system.users.read\" (literal type)\n */\nexport function createPermissions<\n T extends Record<string, Record<string, string>>,\n>(definition: T): DeepReadonly<T> {\n const frozen = { ...definition };\n\n for (const key of Object.keys(frozen)) {\n (frozen as Record<string, unknown>)[key] = Object.freeze(\n (frozen as Record<string, Record<string, string>>)[key],\n );\n }\n\n return Object.freeze(frozen) as DeepReadonly<T>;\n}\n\n/** Extracts all permission string values from a createPermissions() result */\nexport type ExtractPermissions<T> =\n T extends Record<string, Record<string, infer V>> ? V : never;\n"],"mappings":";AAcO,IAAM,oBAAN,MAAwB;AAAA,EAI7B,YAAY,QAA0B;AACpC,SAAK,cAAc,IAAI,IAAI,OAAO,WAAW;AAC7C,UAAM,aAAa,OAAO,cAAc,CAAC,OAAO;AAChD,UAAM,SAAS,OAAO,eAAe;AACrC,SAAK,UAAU,UAAU,WAAW,SAAS,OAAO,YAAY,EAAE;AAAA,EACpE;AAAA;AAAA,EAGA,IAAI,QAAiB;AACnB,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,cAAc,YAA6B;AACzC,QAAI,KAAK,QAAS,QAAO;AACzB,WAAO,KAAK,YAAY,IAAI,UAAU;AAAA,EACxC;AAAA;AAAA,EAGA,iBAAiB,gBAAmC;AAClD,QAAI,KAAK,QAAS,QAAO;AACzB,WAAO,eAAe,KAAK,CAAC,MAAM,KAAK,YAAY,IAAI,CAAC,CAAC;AAAA,EAC3D;AAAA;AAAA,EAGA,kBAAkB,gBAAmC;AACnD,QAAI,KAAK,QAAS,QAAO;AACzB,WAAO,eAAe,MAAM,CAAC,MAAM,KAAK,YAAY,IAAI,CAAC,CAAC;AAAA,EAC5D;AAAA;AAAA,EAGA,MAAM,YAA2C;AAC/C,QAAI,KAAK,SAAS;AAChB,aAAO,EAAE,SAAS,MAAM,QAAQ,eAAe;AAAA,IACjD;AAEA,QAAI,KAAK,YAAY,IAAI,UAAU,GAAG;AACpC,aAAO,EAAE,SAAS,MAAM,QAAQ,mBAAmB;AAAA,IACrD;AAEA,WAAO,EAAE,SAAS,OAAO,QAAQ,qBAAqB;AAAA,EACxD;AACF;;;ACzCO,SAAS,kBAEd,YAAgC;AAChC,QAAM,SAAS,EAAE,GAAG,WAAW;AAE/B,aAAW,OAAO,OAAO,KAAK,MAAM,GAAG;AACrC,IAAC,OAAmC,GAAG,IAAI,OAAO;AAAA,MAC/C,OAAkD,GAAG;AAAA,IACxD;AAAA,EACF;AAEA,SAAO,OAAO,OAAO,MAAM;AAC7B;","names":[]}