@pol-studios/db 1.0.33 → 1.0.34
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/dist/UserMetadataContext-QLIv-mfF.d.ts +171 -0
- package/dist/auth/context.d.ts +52 -4
- package/dist/auth/context.js +26 -1
- package/dist/auth/hooks.d.ts +107 -3
- package/dist/auth/hooks.js +9 -2
- package/dist/auth/index.d.ts +5 -5
- package/dist/auth/index.js +40 -9
- package/dist/chunk-5HJLTYRA.js +355 -0
- package/dist/chunk-5HJLTYRA.js.map +1 -0
- package/dist/{chunk-E6JL3RUF.js → chunk-67HMVGV7.js} +144 -69
- package/dist/chunk-67HMVGV7.js.map +1 -0
- package/dist/chunk-6KN7KLEG.js +1 -0
- package/dist/{chunk-4EJ6LUH7.js → chunk-AML2TLXJ.js} +6 -4
- package/dist/{chunk-4EJ6LUH7.js.map → chunk-AML2TLXJ.js.map} +1 -1
- package/dist/{chunk-OUCPYEKC.js → chunk-FESQS4S5.js} +4 -4
- package/dist/{chunk-PNC6CG5U.js → chunk-MREERKQU.js} +42 -9
- package/dist/chunk-MREERKQU.js.map +1 -0
- package/dist/{chunk-3XCW225W.js → chunk-NP34C3O3.js} +53 -256
- package/dist/chunk-NP34C3O3.js.map +1 -0
- package/dist/{chunk-E64B4PJZ.js → chunk-TN7QINPK.js} +3 -3
- package/dist/chunk-UBHORKBS.js +215 -0
- package/dist/chunk-UBHORKBS.js.map +1 -0
- package/dist/hooks/index.js +9 -7
- package/dist/index.js +18 -15
- package/dist/index.native.js +18 -15
- package/dist/index.web.js +13 -10
- package/dist/index.web.js.map +1 -1
- package/dist/with-auth/index.js +7 -5
- package/dist/with-auth/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/UserMetadataContext-yLZQu24J.d.ts +0 -33
- package/dist/chunk-3XCW225W.js.map +0 -1
- package/dist/chunk-E6JL3RUF.js.map +0 -1
- package/dist/chunk-NSIAAYW3.js +0 -1
- package/dist/chunk-PNC6CG5U.js.map +0 -1
- /package/dist/{chunk-NSIAAYW3.js.map → chunk-6KN7KLEG.js.map} +0 -0
- /package/dist/{chunk-OUCPYEKC.js.map → chunk-FESQS4S5.js.map} +0 -0
- /package/dist/{chunk-E64B4PJZ.js.map → chunk-TN7QINPK.js.map} +0 -0
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useDbUpsert
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-NP34C3O3.js";
|
|
4
4
|
import {
|
|
5
5
|
UserMetadata
|
|
6
6
|
} from "./chunk-SM73S2DY.js";
|
|
7
7
|
import {
|
|
8
8
|
useSetupAuth
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-MREERKQU.js";
|
|
10
10
|
import {
|
|
11
11
|
useDbQuery
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-67HMVGV7.js";
|
|
13
13
|
import {
|
|
14
14
|
useSupabase
|
|
15
15
|
} from "./chunk-DMVUEJG2.js";
|
|
@@ -467,4 +467,4 @@ export {
|
|
|
467
467
|
useSetUserMetadata,
|
|
468
468
|
useUserMetadataState
|
|
469
469
|
};
|
|
470
|
-
//# sourceMappingURL=chunk-
|
|
470
|
+
//# sourceMappingURL=chunk-FESQS4S5.js.map
|
|
@@ -1,11 +1,41 @@
|
|
|
1
1
|
import {
|
|
2
2
|
permissionContext,
|
|
3
3
|
setupAuthContext
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-67HMVGV7.js";
|
|
5
|
+
|
|
6
|
+
// src/auth/hooks/useOfflineAuth.ts
|
|
7
|
+
import { useMemo } from "react";
|
|
8
|
+
var PROFILE_QUERY = `
|
|
9
|
+
SELECT id, email, firstName, lastName, fullName, status, profilePath
|
|
10
|
+
FROM Profile
|
|
11
|
+
WHERE id = ?
|
|
12
|
+
LIMIT 1
|
|
13
|
+
`;
|
|
14
|
+
var USER_ACCESS_QUERY = `
|
|
15
|
+
SELECT id, userId, accessKey
|
|
16
|
+
FROM UserAccess
|
|
17
|
+
WHERE userId = ?
|
|
18
|
+
`;
|
|
19
|
+
var offlineAuthQueryKeys = {
|
|
20
|
+
profile: (userId) => ["profile", userId],
|
|
21
|
+
userAccess: (userId) => ["userAccess", userId]
|
|
22
|
+
};
|
|
23
|
+
var offlineAuthQueries = {
|
|
24
|
+
async fetchProfile(db, userId) {
|
|
25
|
+
return db.getOptional(PROFILE_QUERY, [userId]);
|
|
26
|
+
},
|
|
27
|
+
async fetchUserAccess(db, userId) {
|
|
28
|
+
return db.getAll(USER_ACCESS_QUERY, [userId]);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
function extractAccessKeys(userAccess) {
|
|
32
|
+
if (!userAccess) return [];
|
|
33
|
+
return userAccess.map((ua) => ua.accessKey).filter(Boolean);
|
|
34
|
+
}
|
|
5
35
|
|
|
6
36
|
// src/auth/hooks/useAuth.ts
|
|
7
37
|
import { isUsable } from "@pol-studios/utils";
|
|
8
|
-
import { useCallback, useContext, useMemo } from "react";
|
|
38
|
+
import { useCallback as useCallback2, useContext, useMemo as useMemo2 } from "react";
|
|
9
39
|
function useAuth() {
|
|
10
40
|
const auth = useContext(setupAuthContext);
|
|
11
41
|
if (isUsable(auth.user) === false) {
|
|
@@ -20,7 +50,7 @@ function useAuth() {
|
|
|
20
50
|
function useSetupAuth() {
|
|
21
51
|
const auth = useContext(setupAuthContext);
|
|
22
52
|
const entityPermissions = useContext(permissionContext);
|
|
23
|
-
const hasAccess =
|
|
53
|
+
const hasAccess = useCallback2((key) => {
|
|
24
54
|
if (auth.hasAccess) {
|
|
25
55
|
return auth.hasAccess(key);
|
|
26
56
|
}
|
|
@@ -34,7 +64,7 @@ function useSetupAuth() {
|
|
|
34
64
|
if (isUsable(key) === false) return true;
|
|
35
65
|
return false;
|
|
36
66
|
}, [auth.hasAccess, auth.access, auth.isArchived, auth.isSuspended]);
|
|
37
|
-
const hasEntityAccess =
|
|
67
|
+
const hasEntityAccess = useCallback2((entityType, entityId, action) => {
|
|
38
68
|
if (auth.isArchived || auth.isSuspended) {
|
|
39
69
|
return false;
|
|
40
70
|
}
|
|
@@ -50,7 +80,7 @@ function useSetupAuth() {
|
|
|
50
80
|
}
|
|
51
81
|
return entityPermissions.checkPermission(entityType, entityId, action);
|
|
52
82
|
}, [auth.access, auth.isArchived, auth.isSuspended, entityPermissions]);
|
|
53
|
-
return
|
|
83
|
+
return useMemo2(() => ({
|
|
54
84
|
hasAccess,
|
|
55
85
|
hasEntityAccess,
|
|
56
86
|
...auth,
|
|
@@ -61,7 +91,7 @@ function useSetupAuth() {
|
|
|
61
91
|
|
|
62
92
|
// src/auth/hooks/usePermission.ts
|
|
63
93
|
import { c as _c } from "react/compiler-runtime";
|
|
64
|
-
import { useContext as useContext2, useEffect, useMemo as
|
|
94
|
+
import { useContext as useContext2, useEffect, useMemo as useMemo3 } from "react";
|
|
65
95
|
function usePermissionContext() {
|
|
66
96
|
const context = useContext2(permissionContext);
|
|
67
97
|
if (!context || Object.keys(context).length === 0) {
|
|
@@ -141,7 +171,7 @@ function usePermissionsBatch(entities) {
|
|
|
141
171
|
getPermission,
|
|
142
172
|
prefetchPermissions
|
|
143
173
|
} = usePermissionContext();
|
|
144
|
-
const entitiesKey =
|
|
174
|
+
const entitiesKey = useMemo3(() => entities.map((e) => `${e.type}:${e.id}`).sort().join(","), [entities]);
|
|
145
175
|
useEffect(() => {
|
|
146
176
|
if (entities.length === 0) {
|
|
147
177
|
return;
|
|
@@ -152,7 +182,7 @@ function usePermissionsBatch(entities) {
|
|
|
152
182
|
}));
|
|
153
183
|
prefetchPermissions(entitiesToPrefetch);
|
|
154
184
|
}, [entities, entitiesKey, prefetchPermissions]);
|
|
155
|
-
return
|
|
185
|
+
return useMemo3(() => {
|
|
156
186
|
if (entities.length === 0) {
|
|
157
187
|
return [];
|
|
158
188
|
}
|
|
@@ -192,6 +222,9 @@ function usePermissionLoading() {
|
|
|
192
222
|
}
|
|
193
223
|
|
|
194
224
|
export {
|
|
225
|
+
offlineAuthQueryKeys,
|
|
226
|
+
offlineAuthQueries,
|
|
227
|
+
extractAccessKeys,
|
|
195
228
|
useAuth,
|
|
196
229
|
useSetupAuth,
|
|
197
230
|
usePermission,
|
|
@@ -205,4 +238,4 @@ export {
|
|
|
205
238
|
useInvalidatePermission,
|
|
206
239
|
usePermissionLoading
|
|
207
240
|
};
|
|
208
|
-
//# sourceMappingURL=chunk-
|
|
241
|
+
//# sourceMappingURL=chunk-MREERKQU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/auth/hooks/useOfflineAuth.ts","../src/auth/hooks/useAuth.ts","../src/auth/hooks/usePermission.ts"],"sourcesContent":["/**\n * useOfflineAuth - Hook for offline-first authentication\n *\n * Reads Profile and UserAccess from PowerSync (local SQLite).\n * Works 100% offline once data is synced.\n *\n * Usage:\n * ```tsx\n * import { SimpleAuthProvider } from \"@pol-studios/db\";\n * import { useOfflineAuth } from \"@pol-studios/db\";\n *\n * function AuthWrapper({ children }) {\n * const authData = useOfflineAuth();\n *\n * return (\n * <SimpleAuthProvider {...authData}>\n * {children}\n * </SimpleAuthProvider>\n * );\n * }\n * ```\n */\n\nimport { useCallback, useMemo } from \"react\";\nimport { User } from \"@supabase/supabase-js\";\nimport type { SimpleProfile, SimpleUserAccess } from \"../context/SimpleAuthProvider\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface OfflineAuthData {\n /** Supabase user from auth session */\n user: User | null;\n /** Profile from PowerSync */\n profile: SimpleProfile | null;\n /** User access records from PowerSync */\n userAccess: SimpleUserAccess[] | null;\n /** Whether auth data is loading */\n isLoading: boolean;\n /** Sign out function */\n onSignOut: () => Promise<void>;\n}\nexport interface UseOfflineAuthOptions {\n /** Supabase client for auth operations */\n supabase: {\n auth: {\n getUser: () => Promise<{\n data: {\n user: User | null;\n };\n error: any;\n }>;\n signOut: () => Promise<{\n error: any;\n }>;\n onAuthStateChange: (callback: (event: string, session: any) => void) => {\n data: {\n subscription: {\n unsubscribe: () => void;\n };\n };\n };\n };\n };\n /** PowerSync database for local queries */\n db: {\n getAll: <T>(sql: string, params?: any[]) => Promise<T[]>;\n getOptional: <T>(sql: string, params?: any[]) => Promise<T | null>;\n } | null;\n /** Whether PowerSync is ready */\n isDbReady?: boolean;\n}\n\n// ─── SQL Queries ─────────────────────────────────────────────────────────────\n\nconst PROFILE_QUERY = `\n SELECT id, email, firstName, lastName, fullName, status, profilePath\n FROM Profile\n WHERE id = ?\n LIMIT 1\n`;\nconst USER_ACCESS_QUERY = `\n SELECT id, userId, accessKey\n FROM UserAccess\n WHERE userId = ?\n`;\n\n// ─── Hook Implementation ─────────────────────────────────────────────────────\n\n/**\n * Creates offline auth data by reading from PowerSync.\n *\n * This is a low-level hook. For most use cases, use the pre-built\n * `OfflineAuthProvider` component instead.\n */\nexport function createOfflineAuthHook(options: UseOfflineAuthOptions) {\n const {\n supabase,\n db,\n isDbReady = true\n } = options;\n return function useOfflineAuthInternal(user: User | null): {\n profile: SimpleProfile | null;\n userAccess: SimpleUserAccess[] | null;\n isLoading: boolean;\n } {\n // This is a synchronous hook that expects data to be pre-loaded\n // In practice, you'd use React Query or similar for async loading\n // Here we return loading state if DB isn't ready\n return useMemo(() => ({\n profile: null,\n userAccess: null,\n isLoading: !isDbReady || !user\n }), [user, isDbReady]);\n };\n}\n\n// ─── React Query Integration ─────────────────────────────────────────────────\n\n/**\n * Query keys for React Query integration\n */\nexport const offlineAuthQueryKeys = {\n profile: (userId: string | undefined) => [\"profile\", userId] as const,\n userAccess: (userId: string | undefined) => [\"userAccess\", userId] as const\n};\n\n/**\n * Query functions for React Query integration.\n * Use these with useQuery from @tanstack/react-query.\n *\n * @example\n * ```tsx\n * import { useQuery } from \"@tanstack/react-query\";\n * import { offlineAuthQueries, offlineAuthQueryKeys } from \"@pol-studios/db\";\n *\n * function useProfile(db, userId) {\n * return useQuery({\n * queryKey: offlineAuthQueryKeys.profile(userId),\n * queryFn: () => offlineAuthQueries.fetchProfile(db, userId),\n * enabled: !!userId && !!db,\n * });\n * }\n * ```\n */\nexport const offlineAuthQueries = {\n async fetchProfile(db: {\n getOptional: <T>(sql: string, params?: any[]) => Promise<T | null>;\n }, userId: string): Promise<SimpleProfile | null> {\n return db.getOptional<SimpleProfile>(PROFILE_QUERY, [userId]);\n },\n async fetchUserAccess(db: {\n getAll: <T>(sql: string, params?: any[]) => Promise<T[]>;\n }, userId: string): Promise<SimpleUserAccess[]> {\n return db.getAll<SimpleUserAccess>(USER_ACCESS_QUERY, [userId]);\n }\n};\n\n// ─── Utility Functions ───────────────────────────────────────────────────────\n\n/**\n * Extract access keys from UserAccess records.\n */\nexport function extractAccessKeys(userAccess: SimpleUserAccess[] | null): string[] {\n if (!userAccess) return [];\n return userAccess.map(ua => ua.accessKey).filter(Boolean);\n}","import { isUsable } from \"@pol-studios/utils\";\nimport { useCallback, useContext, useMemo } from \"react\";\nimport { User } from \"@supabase/supabase-js\";\nimport { SetupAuthContext, setupAuthContext, type EffectivePermission } from \"../context/AuthProvider\";\nimport { permissionContext } from \"../context/PermissionContext\";\nimport { EntityAction, EntityType } from \"../types/EntityPermissions\";\n\n// Re-export EffectivePermission type for consumers\nexport type { EffectivePermission };\n\n/**\n * Hook for authenticated users only.\n * Throws an error if the user is not authenticated.\n * Use useSetupAuth() if you need to handle unauthenticated users.\n *\n * @returns Auth context with guaranteed non-null user and hasAccess helper\n * @throws Error if user is not authenticated\n *\n * @example\n * ```tsx\n * function AuthenticatedComponent() {\n * const { user, hasAccess, profile } = useAuth();\n *\n * // user is guaranteed to be non-null\n * console.log(user.id);\n *\n * if (hasAccess('admin')) {\n * return <AdminDashboard />;\n * }\n *\n * return <UserDashboard />;\n * }\n * ```\n */\nexport function useAuth() {\n const auth = useContext(setupAuthContext);\n if (isUsable(auth.user) === false) {\n console.log({\n auth\n });\n throw new Error(\"User must not be null, use useSetupAuth() to use a nullable user.\");\n } else {\n return auth as any;\n }\n}\n\n/**\n * Hook for handling both authenticated and unauthenticated states.\n * Does not throw if user is not authenticated.\n *\n * @returns Auth context with possibly null user, hasAccess, and hasEntityAccess helpers\n *\n * @example\n * ```tsx\n * function FlexibleComponent() {\n * const { user, hasAccess, hasEntityAccess, isLoading } = useSetupAuth();\n *\n * if (isLoading) {\n * return <Spinner />;\n * }\n *\n * if (!user) {\n * return <LoginPrompt />;\n * }\n *\n * // Check global access\n * const isAdmin = hasAccess('admin');\n *\n * // Check entity-level access\n * const canEditProject = hasEntityAccess('Project', 123, 'edit');\n *\n * return <Dashboard />;\n * }\n * ```\n */\nexport function useSetupAuth(): SetupAuthContext & {\n hasAccess: (access: string) => boolean;\n hasEntityAccess: (entityType: EntityType, entityId: number, action: EntityAction) => boolean;\n effectivePermissions: EffectivePermission[];\n} {\n const auth = useContext(setupAuthContext);\n const entityPermissions = useContext(permissionContext);\n\n // Use the context's hasAccess which now includes effective permissions checking\n const hasAccess = useCallback((key: string) => {\n // Delegate to context hasAccess if available (includes effective permissions)\n if (auth.hasAccess) {\n return auth.hasAccess(key);\n }\n\n // Fallback for backward compatibility\n // Archived/suspended users have no access\n if (auth.isArchived || auth.isSuspended) {\n return false;\n }\n const accessGiven = auth.access;\n if (isUsable(accessGiven) === false) return false;\n // Super-admin key bypasses all permission checks\n if (accessGiven.includes(\"*:*:*\")) return true;\n if (accessGiven.includes(key)) return true;\n if (isUsable(key) === false) return true;\n return false;\n }, [auth.hasAccess, auth.access, auth.isArchived, auth.isSuspended]);\n\n /**\n * Check if the current user has access to a specific entity.\n * Super-admin key (*:*:*) bypasses entity permissions entirely.\n * Otherwise, delegates to the PermissionContext for granular permission checks.\n *\n * @param entityType - 'Project' | 'Client' | 'ProjectDatabase'\n * @param entityId - The ID of the entity to check\n * @param action - 'view' | 'adminView' | 'edit' | 'create' | 'delete' | 'share'\n * @returns boolean - true if user has permission for the action on the entity\n */\n const hasEntityAccess = useCallback((entityType: EntityType, entityId: number, action: EntityAction): boolean => {\n // Archived/suspended users have no entity access\n if (auth.isArchived || auth.isSuspended) {\n return false;\n }\n\n // Validate entityId is a valid positive integer\n if (!entityId || entityId <= 0 || !Number.isInteger(entityId)) {\n return false;\n }\n\n // Super-admin key bypasses all entity permission checks\n const accessGiven_0 = auth.access;\n if (isUsable(accessGiven_0) && accessGiven_0.includes(\"*:*:*\")) {\n return true;\n }\n\n // If PermissionContext is not available, deny access\n if (!entityPermissions || typeof entityPermissions.checkPermission !== \"function\") {\n return false;\n }\n\n // Delegate to PermissionContext\n return entityPermissions.checkPermission(entityType, entityId, action);\n }, [auth.access, auth.isArchived, auth.isSuspended, entityPermissions]);\n return useMemo(() => ({\n hasAccess,\n hasEntityAccess,\n ...auth,\n user: auth.user,\n effectivePermissions: auth.effectivePermissions || []\n }), [hasAccess, hasEntityAccess, auth]);\n}","import { c as _c } from \"react/compiler-runtime\";\nimport { useContext, useEffect, useMemo } from \"react\";\nimport { permissionContext } from \"../context/PermissionContext\";\nimport { EntityType, EntityAction, EntityPermissionCheck } from \"../types/EntityPermissions\";\n\n// Re-export types for convenience\nexport type { EntityType, EntityAction, EntityPermissionCheck };\n\n/**\n * Hook to get the full PermissionContext\n * @throws Error if used outside of PermissionProvider\n */\nfunction usePermissionContext() {\n const context = useContext(permissionContext);\n if (!context || Object.keys(context).length === 0) {\n throw new Error(\"usePermission hooks must be used within a PermissionProvider\");\n }\n return context;\n}\n\n/**\n * Hook to get full permission info for a single entity\n * @param entityType - 'Project' | 'Client' | 'ProjectDatabase'\n * @param entityId - The ID of the entity (can be undefined for loading states)\n * @returns EntityPermissionCheck with canView, canEdit, etc. and isLoading\n *\n * @example\n * ```tsx\n * function ProjectHeader({ projectId }: { projectId: number }) {\n * const permission = usePermission('Project', projectId);\n *\n * if (permission.isLoading) {\n * return <Spinner />;\n * }\n *\n * return (\n * <div>\n * {permission.canEdit && <EditButton />}\n * {permission.canDelete && <DeleteButton />}\n * </div>\n * );\n * }\n * ```\n */\nexport function usePermission(entityType, entityId) {\n const $ = _c(5);\n const {\n getPermission\n } = usePermissionContext();\n let t0;\n bb0: {\n if (entityId === undefined) {\n let t1;\n if ($[0] === Symbol.for(\"react.memo_cache_sentinel\")) {\n t1 = {\n canView: false,\n canAdminView: false,\n canEdit: false,\n canCreate: false,\n canDelete: false,\n canShare: false,\n permissionLevel: null,\n isLoading: true\n };\n $[0] = t1;\n } else {\n t1 = $[0];\n }\n t0 = t1;\n break bb0;\n }\n let t1;\n if ($[1] !== entityId || $[2] !== entityType || $[3] !== getPermission) {\n t1 = getPermission(entityType, entityId);\n $[1] = entityId;\n $[2] = entityType;\n $[3] = getPermission;\n $[4] = t1;\n } else {\n t1 = $[4];\n }\n t0 = t1;\n }\n return t0;\n}\n\n/**\n * Hook to check a single action permission\n * @param entityType - Entity type\n * @param entityId - Entity ID\n * @param action - 'view' | 'adminView' | 'edit' | 'create' | 'delete' | 'share'\n * @returns boolean - true if user has permission for action\n *\n * @example\n * ```tsx\n * function ProjectActions({ projectId }: { projectId: number }) {\n * const canEdit = usePermissionCheck('Project', projectId, 'edit');\n * const canDelete = usePermissionCheck('Project', projectId, 'delete');\n *\n * return (\n * <div>\n * <Button disabled={!canEdit}>Edit</Button>\n * <Button disabled={!canDelete}>Delete</Button>\n * </div>\n * );\n * }\n * ```\n */\nexport function usePermissionCheck(entityType, entityId, action) {\n const $ = _c(5);\n const {\n checkPermission\n } = usePermissionContext();\n let t0;\n bb0: {\n if (entityId === undefined) {\n t0 = false;\n break bb0;\n }\n let t1;\n if ($[0] !== action || $[1] !== checkPermission || $[2] !== entityId || $[3] !== entityType) {\n t1 = checkPermission(entityType, entityId, action);\n $[0] = action;\n $[1] = checkPermission;\n $[2] = entityId;\n $[3] = entityType;\n $[4] = t1;\n } else {\n t1 = $[4];\n }\n t0 = t1;\n }\n return t0;\n}\n\n/**\n * Result type for usePermissions batch hook\n */\nexport interface EntityWithPermission {\n type: EntityType;\n id: number;\n permission: EntityPermissionCheck;\n}\n\n/**\n * Hook for batch permission lookup - useful for lists\n * @param entities - Array of { type, id } objects\n * @returns Array of entities with their permissions attached\n *\n * This hook:\n * - Calls prefetchPermissions on mount and when entities change\n * - Returns memoized results\n * - Handles empty arrays gracefully\n *\n * @example\n * ```tsx\n * function ProjectList({ projects }: { projects: Array<{ id: number; name: string }> }) {\n * const entities = projects.map(p => ({ type: 'Project' as const, id: p.id }));\n * const entitiesWithPermissions = usePermissionsBatch(entities);\n *\n * return (\n * <ul>\n * {entitiesWithPermissions.map(({ id, permission }) => {\n * const project = projects.find(p => p.id === id);\n * return (\n * <li key={id}>\n * {project?.name}\n * {permission.canEdit && <EditIcon />}\n * </li>\n * );\n * })}\n * </ul>\n * );\n * }\n * ```\n */\nexport function usePermissionsBatch(entities: Array<{\n type: EntityType;\n id: number;\n}>): EntityWithPermission[] {\n const {\n getPermission,\n prefetchPermissions\n } = usePermissionContext();\n\n // Memoize the entities array to prevent unnecessary re-renders\n const entitiesKey = useMemo(() => entities.map(e => `${e.type}:${e.id}`).sort().join(\",\"), [entities]);\n\n // Prefetch permissions when entities change\n useEffect(() => {\n if (entities.length === 0) {\n return;\n }\n\n // Convert to the format expected by prefetchPermissions\n const entitiesToPrefetch = entities.map(e_0 => ({\n entityType: e_0.type,\n entityId: e_0.id\n }));\n prefetchPermissions(entitiesToPrefetch);\n }, [entities, entitiesKey, prefetchPermissions]);\n\n // Return memoized results\n return useMemo(() => {\n if (entities.length === 0) {\n return [];\n }\n return entities.map(entity => ({\n type: entity.type,\n id: entity.id,\n permission: getPermission(entity.type, entity.id)\n }));\n }, [getPermission, entitiesKey]);\n}\n\n/**\n * Simple boolean hook to check if user can view an entity\n * @param entityType - Entity type\n * @param entityId - Entity ID (can be undefined for loading states)\n * @returns boolean - true if user can view the entity\n *\n * @example\n * ```tsx\n * function ProjectPage({ projectId }: { projectId: number }) {\n * const canView = useCanView('Project', projectId);\n *\n * if (!canView) {\n * return <AccessDenied />;\n * }\n *\n * return <ProjectContent projectId={projectId} />;\n * }\n * ```\n */\nexport function useCanView(entityType, entityId) {\n return usePermissionCheck(entityType, entityId, \"view\");\n}\n\n/**\n * Simple boolean hook to check if user can edit an entity\n * @param entityType - Entity type\n * @param entityId - Entity ID (can be undefined for loading states)\n * @returns boolean - true if user can edit the entity\n *\n * @example\n * ```tsx\n * function ProjectEditor({ projectId }: { projectId: number }) {\n * const canEdit = useCanEdit('Project', projectId);\n *\n * return (\n * <form>\n * <input disabled={!canEdit} />\n * <button disabled={!canEdit}>Save</button>\n * </form>\n * );\n * }\n * ```\n */\nexport function useCanEdit(entityType, entityId) {\n return usePermissionCheck(entityType, entityId, \"edit\");\n}\n\n/**\n * Simple boolean hook to check if user can delete an entity\n * @param entityType - Entity type\n * @param entityId - Entity ID (can be undefined for loading states)\n * @returns boolean - true if user can delete the entity\n *\n * @example\n * ```tsx\n * function ProjectActions({ projectId }: { projectId: number }) {\n * const canDelete = useCanDelete('Project', projectId);\n *\n * return (\n * <Button\n * variant=\"destructive\"\n * disabled={!canDelete}\n * onClick={handleDelete}\n * >\n * Delete Project\n * </Button>\n * );\n * }\n * ```\n */\nexport function useCanDelete(entityType, entityId) {\n return usePermissionCheck(entityType, entityId, \"delete\");\n}\n\n/**\n * Simple boolean hook to check if user can share an entity\n * @param entityType - Entity type\n * @param entityId - Entity ID (can be undefined for loading states)\n * @returns boolean - true if user can share the entity\n *\n * @example\n * ```tsx\n * function ShareButton({ projectId }: { projectId: number }) {\n * const canShare = useCanShare('Project', projectId);\n *\n * if (!canShare) {\n * return null;\n * }\n *\n * return <Button onClick={openShareModal}>Share</Button>;\n * }\n * ```\n */\nexport function useCanShare(entityType, entityId) {\n return usePermissionCheck(entityType, entityId, \"share\");\n}\n\n/**\n * Simple boolean hook to check if user can create entities of a type\n * Note: For create permission, the entityId should be the parent entity ID\n * (e.g., for creating a ProjectDatabase, pass the Project ID)\n *\n * @param entityType - Entity type\n * @param entityId - Parent entity ID (can be undefined for loading states)\n * @returns boolean - true if user can create entities\n *\n * @example\n * ```tsx\n * function AddDatabaseButton({ projectId }: { projectId: number }) {\n * const canCreate = useCanCreate('ProjectDatabase', projectId);\n *\n * return (\n * <Button disabled={!canCreate} onClick={handleCreate}>\n * Add Database\n * </Button>\n * );\n * }\n * ```\n */\nexport function useCanCreate(entityType, entityId) {\n return usePermissionCheck(entityType, entityId, \"create\");\n}\n\n/**\n * Hook to invalidate permission cache for a specific entity\n * Useful after permission changes (e.g., after sharing an entity)\n *\n * @returns Function to invalidate permission for an entity\n *\n * @example\n * ```tsx\n * function ShareModal({ projectId }: { projectId: number }) {\n * const invalidatePermission = useInvalidatePermission();\n *\n * const handleShare = async (userId: string) => {\n * await shareProject(projectId, userId);\n * invalidatePermission('Project', projectId);\n * };\n *\n * return <ShareForm onShare={handleShare} />;\n * }\n * ```\n */\nexport function useInvalidatePermission() {\n const {\n invalidatePermission\n } = usePermissionContext();\n return invalidatePermission;\n}\n\n/**\n * Hook to get the loading state of the permission context\n * @returns boolean - true if permissions are being fetched\n *\n * @example\n * ```tsx\n * function PermissionAwareComponent() {\n * const isLoadingPermissions = usePermissionLoading();\n *\n * if (isLoadingPermissions) {\n * return <LoadingSpinner />;\n * }\n *\n * return <Content />;\n * }\n * ```\n */\nexport function usePermissionLoading() {\n const {\n isLoading\n } = usePermissionContext();\n return isLoading;\n}"],"mappings":";;;;;;AAuBA,SAAsB,eAAe;AAmDrC,IAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAMtB,IAAM,oBAAoB;AAAA;AAAA;AAAA;AAAA;AAyCnB,IAAM,uBAAuB;AAAA,EAClC,SAAS,CAAC,WAA+B,CAAC,WAAW,MAAM;AAAA,EAC3D,YAAY,CAAC,WAA+B,CAAC,cAAc,MAAM;AACnE;AAoBO,IAAM,qBAAqB;AAAA,EAChC,MAAM,aAAa,IAEhB,QAA+C;AAChD,WAAO,GAAG,YAA2B,eAAe,CAAC,MAAM,CAAC;AAAA,EAC9D;AAAA,EACA,MAAM,gBAAgB,IAEnB,QAA6C;AAC9C,WAAO,GAAG,OAAyB,mBA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