@korajs/auth 0.5.0 → 0.6.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/dist/chunk-7OXBRSJL.js +203 -0
- package/dist/chunk-7OXBRSJL.js.map +1 -0
- package/dist/{org-client-q2u55qod.d.cts → create-org-session-RsDj9cl4.d.cts} +58 -1
- package/dist/{org-client-q2u55qod.d.ts → create-org-session-RsDj9cl4.d.ts} +58 -1
- package/dist/index.cjs +168 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -19
- package/dist/index.d.ts +9 -19
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -1
- package/dist/react.cjs +293 -258
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +15 -215
- package/dist/react.d.ts +15 -215
- package/dist/react.js +134 -288
- package/dist/react.js.map +1 -1
- package/dist/svelte.cjs +512 -0
- package/dist/svelte.cjs.map +1 -0
- package/dist/svelte.d.cts +100 -0
- package/dist/svelte.d.ts +100 -0
- package/dist/svelte.js +278 -0
- package/dist/svelte.js.map +1 -0
- package/dist/vue.cjs +565 -0
- package/dist/vue.cjs.map +1 -0
- package/dist/vue.d.cts +136 -0
- package/dist/vue.d.ts +136 -0
- package/dist/vue.js +338 -0
- package/dist/vue.js.map +1 -0
- package/package.json +40 -6
- package/src/svelte/AuthProvider.svelte +37 -0
- package/src/svelte/OrgProvider.svelte +22 -0
package/dist/react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react/AuthProvider.tsx","../src/react/auth-context.ts","../src/react/hooks.ts","../src/react/org-hooks.ts"],"sourcesContent":["import { createElement, useEffect, useState } from 'react'\nimport type { ReactElement, ReactNode } from 'react'\nimport type { AuthClient, AuthState } from '../client/auth-client'\nimport { AuthContext } from './auth-context'\n\n/**\n * Props for the AuthProvider component.\n */\ninterface AuthProviderProps {\n\t/** The AuthClient instance to provide to child components */\n\tclient: AuthClient\n\n\t/** Child components that will have access to auth context */\n\tchildren: ReactNode\n\n\t/**\n\t * Optional fallback content to render while the auth client is initializing.\n\t * If not provided, children are rendered with `isLoading: true` in the context.\n\t */\n\tfallback?: ReactNode\n}\n\n/**\n * React context provider that wraps the AuthClient for use with auth hooks.\n *\n * Calls `client.initialize()` on mount to restore any existing session from\n * stored tokens. Subscribes to auth state changes and re-renders children\n * when the state transitions.\n *\n * Must be placed above any component that uses {@link useAuth},\n * {@link useCurrentUser}, or {@link useAuthStatus}.\n *\n * @param props - Provider props including the AuthClient instance and children\n * @returns A React element wrapping children in the AuthContext\n *\n * @example\n * ```typescript\n * import { AuthClient } from '@korajs/auth'\n * import { AuthProvider } from '@korajs/auth/react'\n *\n * const authClient = new AuthClient({ serverUrl: 'http://localhost:3001' })\n *\n * function App() {\n * return (\n * <AuthProvider client={authClient} fallback={<div>Loading...</div>}>\n * <MyApp />\n * </AuthProvider>\n * )\n * }\n * ```\n */\nfunction AuthProvider({ client, children, fallback }: AuthProviderProps): ReactElement {\n\tconst [state, setState] = useState<AuthState>(client.state)\n\tconst [isLoading, setIsLoading] = useState(true)\n\tconst [initError, setInitError] = useState<Error | null>(null)\n\n\t// Initialize the auth client on mount\n\tuseEffect(() => {\n\t\tlet cancelled = false\n\n\t\t// Subscribe to auth state changes\n\t\tconst unsubscribe = client.onAuthChange((newState) => {\n\t\t\tif (!cancelled) {\n\t\t\t\tsetState(newState)\n\t\t\t}\n\t\t})\n\n\t\tclient\n\t\t\t.initialize()\n\t\t\t.then(() => {\n\t\t\t\tif (!cancelled) {\n\t\t\t\t\tsetState(client.state)\n\t\t\t\t\tsetIsLoading(false)\n\t\t\t\t}\n\t\t\t})\n\t\t\t.catch((error: unknown) => {\n\t\t\t\tif (!cancelled) {\n\t\t\t\t\tconst err = error instanceof Error ? error : new Error(String(error))\n\t\t\t\t\tconsole.error('[Kora Auth] Initialization failed:', err)\n\t\t\t\t\tsetInitError(err)\n\t\t\t\t\tsetIsLoading(false)\n\t\t\t\t}\n\t\t\t})\n\n\t\treturn () => {\n\t\t\tcancelled = true\n\t\t\tunsubscribe()\n\t\t}\n\t}, [client])\n\n\t// Show error if initialization failed\n\tif (initError) {\n\t\treturn createElement(\n\t\t\t'div',\n\t\t\t{\n\t\t\t\tstyle: { color: 'red', padding: '1rem', fontFamily: 'monospace' },\n\t\t\t\trole: 'alert',\n\t\t\t},\n\t\t\tcreateElement('strong', null, 'Kora Auth initialization error: '),\n\t\t\tinitError.message,\n\t\t)\n\t}\n\n\t// Show fallback while loading\n\tif (isLoading && fallback !== undefined) {\n\t\treturn fallback as ReactElement\n\t}\n\n\tconst contextValue = {\n\t\tclient,\n\t\tstate,\n\t\tisLoading,\n\t}\n\n\treturn createElement(AuthContext.Provider, { value: contextValue }, children)\n}\n\nexport { AuthProvider }\nexport type { AuthProviderProps }\n","import { createContext } from 'react'\nimport type { AuthClient } from '../client/auth-client'\n\n/**\n * Possible authentication states for the client.\n * - 'loading': Initial state while restoring tokens from storage\n * - 'authenticated': User is signed in with a valid session\n * - 'unauthenticated': No valid session exists\n */\ntype AuthState = 'loading' | 'authenticated' | 'unauthenticated'\n\n/**\n * Shape of the value provided by the AuthContext.\n * Includes the AuthClient instance, reactive state, and a loading flag.\n */\ninterface AuthContextValue {\n\t/** The underlying AuthClient instance for direct access */\n\tclient: AuthClient\n\n\t/** Current authentication state */\n\tstate: AuthState\n\n\t/** Whether the client is still initializing (restoring session from storage) */\n\tisLoading: boolean\n}\n\n/**\n * React context for Kora authentication.\n *\n * Provides the AuthClient and reactive auth state to child components.\n * Must be provided by an AuthProvider higher in the component tree.\n * Defaults to null — hooks that consume this context throw if it is missing.\n */\nconst AuthContext = createContext<AuthContextValue | null>(null)\n\nexport { AuthContext }\nexport type { AuthContextValue, AuthState }\n","import { useCallback, useContext, useEffect, useRef, useState, useSyncExternalStore } from 'react'\nimport type {\n\tAuthState,\n\tAuthUser,\n\tLinkedOAuthAccount,\n\tOAuthAuthorizationOptions,\n\tOAuthAuthorizationResult,\n\tOAuthCallbackParams,\n} from '../client/auth-client'\nimport { AuthContext } from './auth-context'\n\n// ---------------------------------------------------------------------------\n// Internal context accessor\n// ---------------------------------------------------------------------------\n\n/**\n * Internal hook that reads and validates the AuthContext.\n * Throws a descriptive error if used outside an AuthProvider.\n */\nfunction useAuthContext(): {\n\tclient: import('../client/auth-client').AuthClient\n\tstate: AuthState\n\tisLoading: boolean\n} {\n\tconst ctx = useContext(AuthContext)\n\tif (ctx === null) {\n\t\tthrow new Error(\n\t\t\t'useAuth / useCurrentUser / useAuthStatus must be used within an <AuthProvider>. ' +\n\t\t\t\t'Wrap your component tree with <AuthProvider client={authClient}>.',\n\t\t)\n\t}\n\treturn ctx\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Return value of the {@link useAuth} hook.\n */\ninterface UseAuthResult {\n\t/** Current authenticated user, or null if not signed in */\n\tuser: AuthUser | null\n\n\t/** Whether the user is currently authenticated */\n\tisAuthenticated: boolean\n\n\t/** Whether the auth client is still initializing (restoring session) */\n\tisLoading: boolean\n\n\t/** Sign up a new user account */\n\tsignUp: (params: {\n\t\temail: string\n\t\tpassword: string\n\t\tname?: string\n\t\tdeviceId?: string\n\t\tdevicePublicKey?: string\n\t}) => Promise<void>\n\n\t/** Sign in with email and password */\n\tsignIn: (params: {\n\t\temail: string\n\t\tpassword: string\n\t\tdeviceId?: string\n\t\tdevicePublicKey?: string\n\t}) => Promise<void>\n\n\t/** Start OAuth sign-in. Web apps can redirect; desktop/mobile can open the returned URL. */\n\tsignInWithOAuth: (\n\t\tprovider: string,\n\t\toptions?: OAuthAuthorizationOptions,\n\t) => Promise<OAuthAuthorizationResult>\n\n\t/** Complete an OAuth sign-in callback with code and state. */\n\tcompleteOAuthSignIn: (provider: string, params: OAuthCallbackParams) => Promise<void>\n\n\t/** Create an OAuth authorization URL without redirecting. */\n\tgetOAuthAuthorizationUrl: (\n\t\tprovider: string,\n\t\toptions?: OAuthAuthorizationOptions,\n\t) => Promise<OAuthAuthorizationResult>\n\n\t/** Link an OAuth provider to the current user. */\n\tlinkOAuth: (provider: string, params: OAuthCallbackParams) => Promise<LinkedOAuthAccount | null>\n\n\t/** List OAuth accounts linked to the current user. */\n\tlistLinkedAccounts: () => Promise<LinkedOAuthAccount[]>\n\n\t/** Unlink an OAuth provider from the current user. */\n\tunlinkOAuth: (provider: string) => Promise<void>\n\n\t/** Sign out the current user */\n\tsignOut: () => Promise<void>\n\n\t/** Last error message from a sign-up, sign-in, or sign-out attempt, or null */\n\terror: string | null\n}\n\n/**\n * Auth status information returned by {@link useAuthStatus}.\n */\ninterface AuthStatus {\n\t/** Current authentication state */\n\tstate: AuthState\n\n\t/** Whether the user is currently authenticated */\n\tisAuthenticated: boolean\n\n\t/** Whether the auth client is still initializing */\n\tisLoading: boolean\n}\n\n// ---------------------------------------------------------------------------\n// useAuth\n// ---------------------------------------------------------------------------\n\n/**\n * React hook providing full authentication functionality.\n *\n * Returns the current user, loading state, error state, and methods for\n * sign-up, sign-in, and sign-out. Re-renders when auth state changes.\n *\n * Must be used within an {@link AuthProvider}.\n *\n * @returns An object with user info, auth methods, and status flags\n *\n * @example\n * ```typescript\n * function LoginPage() {\n * const { user, isAuthenticated, isLoading, signIn, error } = useAuth()\n *\n * if (isLoading) return <div>Loading...</div>\n * if (isAuthenticated) return <div>Welcome, {user?.name}</div>\n *\n * return (\n * <form onSubmit={async (e) => {\n * e.preventDefault()\n * await signIn({ email: 'user@example.com', password: 'secret' })\n * }}>\n * {error && <p>{error}</p>}\n * <button type=\"submit\">Sign In</button>\n * </form>\n * )\n * }\n * ```\n */\nfunction useAuth(): UseAuthResult {\n\tconst { client, state, isLoading } = useAuthContext()\n\tconst [error, setError] = useState<string | null>(null)\n\n\t// Use useSyncExternalStore to track the user reactively via auth state changes\n\tconst userSnapshotRef = useRef<AuthUser | null>(client.currentUser)\n\tconst stateSerializedRef = useRef<string>(JSON.stringify(client.currentUser))\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\treturn client.onAuthChange(() => {\n\t\t\t\tconst newUser = client.currentUser\n\t\t\t\tconst newSerialized = JSON.stringify(newUser)\n\t\t\t\tif (newSerialized !== stateSerializedRef.current) {\n\t\t\t\t\tuserSnapshotRef.current = newUser\n\t\t\t\t\tstateSerializedRef.current = newSerialized\n\t\t\t\t\tonStoreChange()\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\t[client],\n\t)\n\n\tconst getSnapshot = useCallback((): AuthUser | null => {\n\t\treturn userSnapshotRef.current\n\t}, [])\n\n\tconst user = useSyncExternalStore(subscribe, getSnapshot)\n\n\tconst signUp = useCallback(\n\t\tasync (params: {\n\t\t\temail: string\n\t\t\tpassword: string\n\t\t\tname?: string\n\t\t\tdeviceId?: string\n\t\t\tdevicePublicKey?: string\n\t\t}): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.signUp(params)\n\t\t\t} catch (err: unknown) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(message)\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst signIn = useCallback(\n\t\tasync (params: {\n\t\t\temail: string\n\t\t\tpassword: string\n\t\t\tdeviceId?: string\n\t\t\tdevicePublicKey?: string\n\t\t}): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.signIn(params)\n\t\t\t} catch (err: unknown) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(message)\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst signInWithOAuth = useCallback(\n\t\tasync (\n\t\t\tprovider: string,\n\t\t\toptions?: OAuthAuthorizationOptions,\n\t\t): Promise<OAuthAuthorizationResult> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\treturn await client.signInWithOAuth(provider, options)\n\t\t\t} catch (err: unknown) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(message)\n\t\t\t\tthrow err\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst completeOAuthSignIn = useCallback(\n\t\tasync (provider: string, params: OAuthCallbackParams): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.completeOAuthSignIn(provider, params)\n\t\t\t} catch (err: unknown) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(message)\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst getOAuthAuthorizationUrl = useCallback(\n\t\tasync (\n\t\t\tprovider: string,\n\t\t\toptions?: OAuthAuthorizationOptions,\n\t\t): Promise<OAuthAuthorizationResult> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\treturn await client.getOAuthAuthorizationUrl(provider, options)\n\t\t\t} catch (err: unknown) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(message)\n\t\t\t\tthrow err\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst linkOAuth = useCallback(\n\t\tasync (provider: string, params: OAuthCallbackParams): Promise<LinkedOAuthAccount | null> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\treturn await client.linkOAuth(provider, params)\n\t\t\t} catch (err: unknown) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(message)\n\t\t\t\treturn null\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst listLinkedAccounts = useCallback(async (): Promise<LinkedOAuthAccount[]> => {\n\t\tsetError(null)\n\t\ttry {\n\t\t\treturn await client.listLinkedAccounts()\n\t\t} catch (err: unknown) {\n\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\tsetError(message)\n\t\t\treturn []\n\t\t}\n\t}, [client])\n\n\tconst unlinkOAuth = useCallback(\n\t\tasync (provider: string): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.unlinkOAuth(provider)\n\t\t\t} catch (err: unknown) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(message)\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst signOut = useCallback(async (): Promise<void> => {\n\t\tsetError(null)\n\t\ttry {\n\t\t\tawait client.signOut()\n\t\t} catch (err: unknown) {\n\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\tsetError(message)\n\t\t}\n\t}, [client])\n\n\treturn {\n\t\tuser,\n\t\tisAuthenticated: state === 'authenticated',\n\t\tisLoading,\n\t\tsignUp,\n\t\tsignIn,\n\t\tsignInWithOAuth,\n\t\tcompleteOAuthSignIn,\n\t\tgetOAuthAuthorizationUrl,\n\t\tlinkOAuth,\n\t\tlistLinkedAccounts,\n\t\tunlinkOAuth,\n\t\tsignOut,\n\t\terror,\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// useCurrentUser\n// ---------------------------------------------------------------------------\n\n/**\n * React hook that returns the currently authenticated user, or null.\n *\n * A lightweight alternative to {@link useAuth} when you only need the user\n * object and do not need auth methods or error state.\n *\n * Must be used within an {@link AuthProvider}.\n *\n * @returns The current AuthUser or null if not authenticated\n *\n * @example\n * ```typescript\n * function UserAvatar() {\n * const user = useCurrentUser()\n * if (!user) return null\n * return <span>{user.name ?? user.email}</span>\n * }\n * ```\n */\nfunction useCurrentUser(): AuthUser | null {\n\tconst { client } = useAuthContext()\n\n\tconst userSnapshotRef = useRef<AuthUser | null>(client.currentUser)\n\tconst stateSerializedRef = useRef<string>(JSON.stringify(client.currentUser))\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\treturn client.onAuthChange(() => {\n\t\t\t\tconst newUser = client.currentUser\n\t\t\t\tconst newSerialized = JSON.stringify(newUser)\n\t\t\t\tif (newSerialized !== stateSerializedRef.current) {\n\t\t\t\t\tuserSnapshotRef.current = newUser\n\t\t\t\t\tstateSerializedRef.current = newSerialized\n\t\t\t\t\tonStoreChange()\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\t[client],\n\t)\n\n\tconst getSnapshot = useCallback((): AuthUser | null => {\n\t\treturn userSnapshotRef.current\n\t}, [])\n\n\treturn useSyncExternalStore(subscribe, getSnapshot)\n}\n\n// ---------------------------------------------------------------------------\n// useAuthStatus\n// ---------------------------------------------------------------------------\n\n/**\n * React hook that returns the current authentication status.\n *\n * Re-renders only when the auth state changes, not on every auth event.\n * Use this for status indicators, route guards, and conditional rendering.\n *\n * Must be used within an {@link AuthProvider}.\n *\n * @returns An AuthStatus object with state, isAuthenticated, and isLoading flags\n *\n * @example\n * ```typescript\n * function AuthGuard({ children }: { children: React.ReactNode }) {\n * const { isAuthenticated, isLoading } = useAuthStatus()\n * if (isLoading) return <Spinner />\n * if (!isAuthenticated) return <Navigate to=\"/login\" />\n * return <>{children}</>\n * }\n * ```\n */\nfunction useAuthStatus(): AuthStatus {\n\tconst { state, isLoading } = useAuthContext()\n\n\treturn {\n\t\tstate,\n\t\tisAuthenticated: state === 'authenticated',\n\t\tisLoading,\n\t}\n}\n\nexport { useAuth, useCurrentUser, useAuthStatus }\nexport type { UseAuthResult, AuthStatus }\n","import {\n\tcreateContext,\n\tuseCallback,\n\tuseContext,\n\tuseEffect,\n\tuseRef,\n\tuseState,\n\tuseSyncExternalStore,\n} from 'react'\nimport type {\n\tClientInvitation,\n\tClientMembership,\n\tClientOrganization,\n\tOrgClient,\n} from '../client/org-client'\n\n// ============================================================================\n// OrgContext\n// ============================================================================\n\n/**\n * Shape of the OrgContext value.\n */\nexport interface OrgContextValue {\n\t/** The OrgClient instance */\n\tclient: OrgClient\n}\n\n/**\n * React context for organization state.\n */\nexport const OrgContext = createContext<OrgContextValue | null>(null)\n\nfunction useOrgContext(): OrgContextValue {\n\tconst ctx = useContext(OrgContext)\n\tif (ctx === null) {\n\t\tthrow new Error(\n\t\t\t'useOrg / useOrgMembers / usePermission must be used within an <OrgProvider>. ' +\n\t\t\t\t'Wrap your component tree with <OrgProvider client={orgClient}>.',\n\t\t)\n\t}\n\treturn ctx\n}\n\n// ============================================================================\n// useOrg\n// ============================================================================\n\n/**\n * Return value of the {@link useOrg} hook.\n */\nexport interface UseOrgResult {\n\t/** Currently active organization, or null */\n\torg: ClientOrganization | null\n\t/** Current user's role in the active organization, or null */\n\trole: string | null\n\t/** Active organization ID, or null */\n\torgId: string | null\n\t/** Switch to a different organization */\n\tswitchOrg: (orgId: string) => Promise<void>\n\t/** Create a new organization */\n\tcreateOrg: (params: { name: string; slug?: string }) => Promise<ClientOrganization>\n\t/** Leave the active organization */\n\tleaveOrg: () => Promise<void>\n\t/** Clear the active organization */\n\tclearOrg: () => void\n\t/** List all organizations the user belongs to */\n\tlistOrgs: () => Promise<ClientOrganization[]>\n\t/** Last error, or null */\n\terror: string | null\n}\n\n/**\n * React hook for organization management and context switching.\n *\n * Re-renders when the active organization changes.\n *\n * @example\n * ```typescript\n * function OrgSwitcher() {\n * const { org, switchOrg, listOrgs, error } = useOrg()\n * const [orgs, setOrgs] = useState<ClientOrganization[]>([])\n *\n * useEffect(() => { listOrgs().then(setOrgs) }, [listOrgs])\n *\n * return (\n * <select value={org?.id ?? ''} onChange={(e) => switchOrg(e.target.value)}>\n * <option value=\"\">Select org...</option>\n * {orgs.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}\n * </select>\n * )\n * }\n * ```\n */\nexport function useOrg(): UseOrgResult {\n\tconst { client } = useOrgContext()\n\tconst [error, setError] = useState<string | null>(null)\n\n\t// Track active org reactively\n\tconst orgSnapshotRef = useRef({\n\t\torgId: client.activeOrgId,\n\t\torg: client.activeOrg,\n\t\trole: client.activeRole,\n\t})\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\treturn client.onOrgChange(() => {\n\t\t\t\torgSnapshotRef.current = {\n\t\t\t\t\torgId: client.activeOrgId,\n\t\t\t\t\torg: client.activeOrg,\n\t\t\t\t\trole: client.activeRole,\n\t\t\t\t}\n\t\t\t\tonStoreChange()\n\t\t\t})\n\t\t},\n\t\t[client],\n\t)\n\n\tconst getSnapshot = useCallback(() => orgSnapshotRef.current, [])\n\n\tconst { orgId, org, role } = useSyncExternalStore(subscribe, getSnapshot)\n\n\tconst switchOrg = useCallback(\n\t\tasync (newOrgId: string): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.switchOrg(newOrgId)\n\t\t\t} catch (err) {\n\t\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst createOrg = useCallback(\n\t\tasync (params: { name: string; slug?: string }): Promise<ClientOrganization> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\treturn await client.createOrg(params)\n\t\t\t} catch (err) {\n\t\t\t\tconst msg = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(msg)\n\t\t\t\tthrow err\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst leaveOrg = useCallback(async (): Promise<void> => {\n\t\tif (!orgId) return\n\t\tsetError(null)\n\t\ttry {\n\t\t\tawait client.leaveOrg(orgId)\n\t\t} catch (err) {\n\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t}\n\t}, [client, orgId])\n\n\tconst clearOrg = useCallback((): void => {\n\t\tclient.clearActiveOrg()\n\t}, [client])\n\n\tconst listOrgs = useCallback(async (): Promise<ClientOrganization[]> => {\n\t\ttry {\n\t\t\treturn await client.listOrgs()\n\t\t} catch (err) {\n\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t\treturn []\n\t\t}\n\t}, [client])\n\n\treturn { org, role, orgId, switchOrg, createOrg, leaveOrg, clearOrg, listOrgs, error }\n}\n\n// ============================================================================\n// useOrgMembers\n// ============================================================================\n\n/**\n * Return value of the {@link useOrgMembers} hook.\n */\nexport interface UseOrgMembersResult {\n\t/** Members of the organization (empty until loaded) */\n\tmembers: ClientMembership[]\n\t/** Whether members are being loaded */\n\tisLoading: boolean\n\t/** Reload the members list */\n\trefresh: () => Promise<void>\n\t/** Invite a user by email */\n\tinvite: (email: string, role: string) => Promise<ClientInvitation>\n\t/** Remove a member */\n\tremoveMember: (userId: string) => Promise<void>\n\t/** Update a member's role */\n\tupdateRole: (userId: string, role: string) => Promise<void>\n\t/** Last error, or null */\n\terror: string | null\n}\n\n/**\n * React hook for managing organization members.\n *\n * Automatically loads members when the orgId changes.\n *\n * @param orgId - Organization ID to manage members for\n */\nexport function useOrgMembers(orgId: string): UseOrgMembersResult {\n\tconst { client } = useOrgContext()\n\tconst [members, setMembers] = useState<ClientMembership[]>([])\n\tconst [isLoading, setIsLoading] = useState(true)\n\tconst [error, setError] = useState<string | null>(null)\n\n\tconst refresh = useCallback(async () => {\n\t\tsetIsLoading(true)\n\t\tsetError(null)\n\t\ttry {\n\t\t\tconst result = await client.listMembers(orgId)\n\t\t\tsetMembers(result)\n\t\t} catch (err) {\n\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t} finally {\n\t\t\tsetIsLoading(false)\n\t\t}\n\t}, [client, orgId])\n\n\tuseEffect(() => {\n\t\trefresh()\n\t}, [refresh])\n\n\tconst invite = useCallback(\n\t\tasync (email: string, role: string): Promise<ClientInvitation> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tconst result = await client.inviteMember(orgId, { email, role })\n\t\t\t\treturn result\n\t\t\t} catch (err) {\n\t\t\t\tconst msg = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(msg)\n\t\t\t\tthrow err\n\t\t\t}\n\t\t},\n\t\t[client, orgId],\n\t)\n\n\tconst removeMember = useCallback(\n\t\tasync (userId: string): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.removeMember(orgId, userId)\n\t\t\t\tawait refresh()\n\t\t\t} catch (err) {\n\t\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t\t}\n\t\t},\n\t\t[client, orgId, refresh],\n\t)\n\n\tconst updateRole = useCallback(\n\t\tasync (userId: string, role: string): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.updateMemberRole(orgId, userId, role)\n\t\t\t\tawait refresh()\n\t\t\t} catch (err) {\n\t\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t\t}\n\t\t},\n\t\t[client, orgId, refresh],\n\t)\n\n\treturn { members, isLoading, refresh, invite, removeMember, updateRole, error }\n}\n\n// ============================================================================\n// usePermission\n// ============================================================================\n\n/**\n * React hook that checks if the current user has a specific role level\n * in the active organization.\n *\n * @param requiredRole - Minimum role required (uses ROLE_HIERARCHY from org-types)\n * @returns true if the user's role is at least requiredRole\n *\n * @example\n * ```typescript\n * function AdminPanel() {\n * const canManage = usePermission('admin')\n * if (!canManage) return <p>Access denied</p>\n * return <AdminSettings />\n * }\n * ```\n */\nexport function usePermission(requiredRole: string): boolean {\n\tconst { client } = useOrgContext()\n\n\tconst snapshotRef = useRef(checkPermission(client.activeRole, requiredRole))\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\treturn client.onOrgChange(() => {\n\t\t\t\tconst newValue = checkPermission(client.activeRole, requiredRole)\n\t\t\t\tif (newValue !== snapshotRef.current) {\n\t\t\t\t\tsnapshotRef.current = newValue\n\t\t\t\t\tonStoreChange()\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\t[client, requiredRole],\n\t)\n\n\tconst getSnapshot = useCallback(() => snapshotRef.current, [])\n\n\treturn useSyncExternalStore(subscribe, getSnapshot)\n}\n\n// Simple role hierarchy check (mirrors ROLE_HIERARCHY from org-types)\nconst ROLE_LEVELS: Record<string, number> = {\n\tviewer: 10,\n\tbilling: 15,\n\tmember: 20,\n\tadmin: 30,\n\towner: 40,\n}\n\nfunction checkPermission(currentRole: string | null, requiredRole: string): boolean {\n\tif (!currentRole) return false\n\tconst currentLevel = ROLE_LEVELS[currentRole] ?? 0\n\tconst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AW,KAAK;AACjD,QAAM,gBAAgB,YAAY,YAAY,KAAK;AACnD,SAAO,gBAAgB;AACxB;","names":["useState","useState","createContext","useCallback","useContext","useEffect","useRef","useState","useSyncExternalStore"]}
|
|
1
|
+
{"version":3,"sources":["../src/react/AuthProvider.tsx","../src/react/auth-context.ts","../src/react/hooks.ts","../src/react/OrgProvider.tsx","../src/react/org-hooks.ts"],"sourcesContent":["import { createElement, useEffect, useMemo, useSyncExternalStore } from 'react'\nimport type { ReactElement, ReactNode } from 'react'\nimport type { AuthClient } from '../client/auth-client'\nimport { createAuthSession } from '../bindings/create-auth-session'\nimport { AuthContext } from './auth-context'\n\ninterface AuthProviderProps {\n\tclient: AuthClient\n\tchildren: ReactNode\n\tfallback?: ReactNode\n}\n\nfunction AuthProvider({ client, children, fallback }: AuthProviderProps): ReactElement {\n\tconst session = useMemo(() => createAuthSession(client), [client])\n\n\tuseEffect(() => () => session.destroy(), [session])\n\n\tconst snapshot = useSyncExternalStore(\n\t\t(onStoreChange) => session.subscribe(onStoreChange),\n\t\t() => session.getSnapshot(),\n\t\t() => session.getSnapshot(),\n\t)\n\n\tif (snapshot.initError) {\n\t\treturn createElement(\n\t\t\t'div',\n\t\t\t{\n\t\t\t\tstyle: { color: 'red', padding: '1rem', fontFamily: 'monospace' },\n\t\t\t\trole: 'alert',\n\t\t\t},\n\t\t\tcreateElement('strong', null, 'Kora Auth initialization error: '),\n\t\t\tsnapshot.initError.message,\n\t\t)\n\t}\n\n\tif (snapshot.isLoading && fallback !== undefined) {\n\t\treturn fallback as ReactElement\n\t}\n\n\tconst contextValue = {\n\t\tclient,\n\t\tsession,\n\t\tstate: snapshot.state,\n\t\tisLoading: snapshot.isLoading,\n\t}\n\n\treturn createElement(AuthContext.Provider, { value: contextValue }, children)\n}\n\nexport { AuthProvider }\nexport type { AuthProviderProps }\n","import { createContext } from 'react'\nimport type { AuthSession } from '../bindings/create-auth-session'\nimport type { AuthClient } from '../client/auth-client'\n\n/**\n * Possible authentication states for the client.\n */\ntype AuthState = 'loading' | 'authenticated' | 'unauthenticated'\n\n/**\n * Shape of the value provided by the AuthContext.\n */\ninterface AuthContextValue {\n\tclient: AuthClient\n\tsession: AuthSession\n\tstate: AuthState\n\tisLoading: boolean\n}\n\n/**\n * React context for Kora authentication.\n */\nconst AuthContext = createContext<AuthContextValue | null>(null)\n\nexport { AuthContext }\nexport type { AuthContextValue, AuthState }\n","import { useContext, useSyncExternalStore } from 'react'\nimport type {\n\tAuthState,\n\tAuthUser,\n\tLinkedOAuthAccount,\n\tOAuthAuthorizationOptions,\n\tOAuthAuthorizationResult,\n\tOAuthCallbackParams,\n} from '../client/auth-client'\nimport { AuthContext } from './auth-context'\n\nfunction useAuthContext() {\n\tconst ctx = useContext(AuthContext)\n\tif (ctx === null) {\n\t\tthrow new Error(\n\t\t\t'useAuth / useCurrentUser / useAuthStatus must be used within an <AuthProvider>. ' +\n\t\t\t\t'Wrap your component tree with <AuthProvider client={authClient}>.',\n\t\t)\n\t}\n\treturn ctx\n}\n\ninterface UseAuthResult {\n\tuser: AuthUser | null\n\tisAuthenticated: boolean\n\tisLoading: boolean\n\tsignUp: (params: {\n\t\temail: string\n\t\tpassword: string\n\t\tname?: string\n\t\tdeviceId?: string\n\t\tdevicePublicKey?: string\n\t}) => Promise<void>\n\tsignIn: (params: {\n\t\temail: string\n\t\tpassword: string\n\t\tdeviceId?: string\n\t\tdevicePublicKey?: string\n\t}) => Promise<void>\n\tsignInWithOAuth: (\n\t\tprovider: string,\n\t\toptions?: OAuthAuthorizationOptions,\n\t) => Promise<OAuthAuthorizationResult>\n\tcompleteOAuthSignIn: (provider: string, params: OAuthCallbackParams) => Promise<void>\n\tgetOAuthAuthorizationUrl: (\n\t\tprovider: string,\n\t\toptions?: OAuthAuthorizationOptions,\n\t) => Promise<OAuthAuthorizationResult>\n\tlinkOAuth: (provider: string, params: OAuthCallbackParams) => Promise<LinkedOAuthAccount | null>\n\tlistLinkedAccounts: () => Promise<LinkedOAuthAccount[]>\n\tunlinkOAuth: (provider: string) => Promise<void>\n\tsignOut: () => Promise<void>\n\terror: string | null\n\tinitError: Error | null\n}\n\ninterface AuthStatus {\n\tstate: AuthState\n\tisAuthenticated: boolean\n\tisLoading: boolean\n}\n\nfunction useAuthSessionSnapshot() {\n\tconst { session } = useAuthContext()\n\n\treturn useSyncExternalStore(\n\t\t(onStoreChange) => session.subscribe(onStoreChange),\n\t\t() => session.getSnapshot(),\n\t\t() => session.getSnapshot(),\n\t)\n}\n\nfunction useAuth(): UseAuthResult {\n\tconst { session } = useAuthContext()\n\tconst snapshot = useAuthSessionSnapshot()\n\n\treturn {\n\t\tuser: snapshot.user,\n\t\tisAuthenticated: snapshot.isAuthenticated,\n\t\tisLoading: snapshot.isLoading,\n\t\terror: snapshot.error,\n\t\tinitError: snapshot.initError,\n\t\tsignUp: (params) => session.signUp(params),\n\t\tsignIn: (params) => session.signIn(params),\n\t\tsignInWithOAuth: (provider, options) => session.signInWithOAuth(provider, options),\n\t\tcompleteOAuthSignIn: (provider, params) => session.completeOAuthSignIn(provider, params),\n\t\tgetOAuthAuthorizationUrl: (provider, options) =>\n\t\t\tsession.getOAuthAuthorizationUrl(provider, options),\n\t\tlinkOAuth: (provider, params) => session.linkOAuth(provider, params),\n\t\tlistLinkedAccounts: () => session.listLinkedAccounts(),\n\t\tunlinkOAuth: (provider) => session.unlinkOAuth(provider),\n\t\tsignOut: () => session.signOut(),\n\t}\n}\n\nfunction useCurrentUser(): AuthUser | null {\n\treturn useAuthSessionSnapshot().user\n}\n\nfunction useAuthStatus(): AuthStatus {\n\tconst snapshot = useAuthSessionSnapshot()\n\treturn {\n\t\tstate: snapshot.state,\n\t\tisAuthenticated: snapshot.isAuthenticated,\n\t\tisLoading: snapshot.isLoading,\n\t}\n}\n\nexport { useAuth, useCurrentUser, useAuthStatus }\nexport type { UseAuthResult, AuthStatus }\n","import { useEffect, useMemo, useRef, type ReactNode } from 'react'\nimport type { OrgClient } from '../client/org-client'\nimport { createOrgSession, type OrgSession } from '../bindings/create-org-session'\nimport { OrgContext, type OrgContextValue } from './org-hooks'\n\nexport interface OrgProviderProps {\n\tclient: OrgClient\n\tchildren?: ReactNode\n}\n\n/**\n * Provides organization context for {@link useOrg}, {@link useOrgMembers}, and {@link usePermission}.\n */\nexport function OrgProvider({ client, children }: OrgProviderProps) {\n\tconst sessionRef = useRef<OrgSession | null>(null)\n\n\tif (sessionRef.current === null || sessionRef.current.client !== client) {\n\t\tsessionRef.current?.destroy()\n\t\tsessionRef.current = createOrgSession(client)\n\t}\n\n\tuseEffect(() => {\n\t\treturn () => {\n\t\t\tsessionRef.current?.destroy()\n\t\t\tsessionRef.current = null\n\t\t}\n\t}, [])\n\n\tconst value = useMemo<OrgContextValue>(\n\t\t() => ({\n\t\t\tclient,\n\t\t\tsession: sessionRef.current!,\n\t\t}),\n\t\t[client],\n\t)\n\n\treturn <OrgContext.Provider value={value}>{children}</OrgContext.Provider>\n}\n\nexport type { OrgContextValue }\n","import {\n\tcreateContext,\n\tuseCallback,\n\tuseContext,\n\tuseEffect,\n\tuseRef,\n\tuseState,\n\tuseSyncExternalStore,\n} from 'react'\nimport type {\n\tClientInvitation,\n\tClientMembership,\n\tClientOrganization,\n\tOrgClient,\n} from '../client/org-client'\nimport {\n\tcheckOrgPermission,\n\tcreateOrgMembersActions,\n\tcreateOrgSession,\n\tloadOrgMembers,\n\ttype OrgSession,\n\ttype OrgSnapshot,\n} from '../bindings/create-org-session'\n\nexport interface OrgContextValue {\n\tclient: OrgClient\n\tsession: OrgSession\n}\n\nexport const OrgContext = createContext<OrgContextValue | null>(null)\n\nfunction useOrgContext(): OrgContextValue {\n\tconst ctx = useContext(OrgContext)\n\tif (ctx === null) {\n\t\tthrow new Error(\n\t\t\t'useOrg / useOrgMembers / usePermission must be used within an <OrgProvider>. ' +\n\t\t\t\t'Wrap your component tree with <OrgProvider client={orgClient}>.',\n\t\t)\n\t}\n\treturn ctx\n}\n\nfunction useOrgSnapshot(session: OrgSession): OrgSnapshot {\n\tconst snapshotRef = useRef(session.getSnapshot())\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\treturn session.subscribe(() => {\n\t\t\t\tsnapshotRef.current = session.getSnapshot()\n\t\t\t\tonStoreChange()\n\t\t\t})\n\t\t},\n\t\t[session],\n\t)\n\n\tconst getSnapshot = useCallback(() => snapshotRef.current, [])\n\n\treturn useSyncExternalStore(subscribe, getSnapshot)\n}\n\nexport interface UseOrgResult {\n\torg: ClientOrganization | null\n\trole: string | null\n\torgId: string | null\n\tswitchOrg: (orgId: string) => Promise<void>\n\tcreateOrg: (params: { name: string; slug?: string }) => Promise<ClientOrganization>\n\tleaveOrg: () => Promise<void>\n\tclearOrg: () => void\n\tlistOrgs: () => Promise<ClientOrganization[]>\n\terror: string | null\n}\n\nexport function useOrg(): UseOrgResult {\n\tconst { client, session } = useOrgContext()\n\tconst { orgId, org, role } = useOrgSnapshot(session)\n\tconst [error, setError] = useState<string | null>(null)\n\n\tconst switchOrg = useCallback(\n\t\tasync (newOrgId: string): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.switchOrg(newOrgId)\n\t\t\t} catch (err) {\n\t\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst createOrg = useCallback(\n\t\tasync (params: { name: string; slug?: string }): Promise<ClientOrganization> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\treturn await client.createOrg(params)\n\t\t\t} catch (err) {\n\t\t\t\tconst msg = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(msg)\n\t\t\t\tthrow err\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst leaveOrg = useCallback(async (): Promise<void> => {\n\t\tif (!orgId) return\n\t\tsetError(null)\n\t\ttry {\n\t\t\tawait client.leaveOrg(orgId)\n\t\t} catch (err) {\n\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t}\n\t}, [client, orgId])\n\n\tconst clearOrg = useCallback((): void => {\n\t\tclient.clearActiveOrg()\n\t}, [client])\n\n\tconst listOrgs = useCallback(async (): Promise<ClientOrganization[]> => {\n\t\ttry {\n\t\t\treturn await client.listOrgs()\n\t\t} catch (err) {\n\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t\treturn []\n\t\t}\n\t}, [client])\n\n\treturn { org, role, orgId, switchOrg, createOrg, leaveOrg, clearOrg, listOrgs, error }\n}\n\nexport interface UseOrgMembersResult {\n\tmembers: ClientMembership[]\n\tisLoading: boolean\n\trefresh: () => Promise<void>\n\tinvite: (email: string, role: string) => Promise<ClientInvitation>\n\tremoveMember: (userId: string) => Promise<void>\n\tupdateRole: (userId: string, role: string) => Promise<void>\n\terror: string | null\n}\n\nexport function useOrgMembers(orgId: string): UseOrgMembersResult {\n\tconst { client } = useOrgContext()\n\tconst [members, setMembers] = useState<ClientMembership[]>([])\n\tconst [isLoading, setIsLoading] = useState(true)\n\tconst [error, setError] = useState<string | null>(null)\n\n\tconst refresh = useCallback(async () => {\n\t\tsetIsLoading(true)\n\t\tsetError(null)\n\t\ttry {\n\t\t\tsetMembers(await loadOrgMembers(client, orgId))\n\t\t} catch (err) {\n\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t} finally {\n\t\t\tsetIsLoading(false)\n\t\t}\n\t}, [client, orgId])\n\n\tuseEffect(() => {\n\t\tvoid refresh()\n\t}, [refresh])\n\n\tconst actions = createOrgMembersActions(client, orgId, setError)\n\n\tconst invite = useCallback(\n\t\tasync (email: string, role: string): Promise<ClientInvitation> => {\n\t\t\tconst result = await actions.invite(email, role)\n\t\t\tawait refresh()\n\t\t\treturn result\n\t\t},\n\t\t[actions, refresh],\n\t)\n\n\tconst removeMember = useCallback(\n\t\tasync (userId: string): Promise<void> => {\n\t\t\tawait actions.removeMember(userId)\n\t\t\tawait refresh()\n\t\t},\n\t\t[actions, refresh],\n\t)\n\n\tconst updateRole = useCallback(\n\t\tasync (userId: string, role: string): Promise<void> => {\n\t\t\tawait actions.updateRole(userId, role)\n\t\t\tawait refresh()\n\t\t},\n\t\t[actions, refresh],\n\t)\n\n\treturn { members, isLoading, refresh, invite, removeMember, updateRole, error }\n}\n\nexport function usePermission(requiredRole: string): boolean {\n\tconst { session } = useOrgContext()\n\tconst snapshotRef = useRef(session.checkPermission(requiredRole))\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\treturn session.subscribe(() => {\n\t\t\t\tconst next = session.checkPermission(requiredRole)\n\t\t\t\tif (next !== snapshotRef.current) {\n\t\t\t\t\tsnapshotRef.current = next\n\t\t\t\t\tonStoreChange()\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\t[session, requiredRole],\n\t)\n\n\tconst getSnapshot = useCallback(() => snapshotRef.current, [])\n\n\treturn useSyncExternalStore(subscribe, getSnapshot)\n}\n\nexport { checkOrgPermission }\n"],"mappings":";;;;;;;;;AAAA,SAAS,eAAe,WAAW,SAAS,4BAA4B;;;ACAxE,SAAS,qBAAqB;AAsB9B,IAAM,cAAc,cAAuC,IAAI;;;ADV/D,SAAS,aAAa,EAAE,QAAQ,UAAU,SAAS,GAAoC;AACtF,QAAM,UAAU,QAAQ,MAAM,kBAAkB,MAAM,GAAG,CAAC,MAAM,CAAC;AAEjE,YAAU,MAAM,MAAM,QAAQ,QAAQ,GAAG,CAAC,OAAO,CAAC;AAElD,QAAM,WAAW;AAAA,IAChB,CAAC,kBAAkB,QAAQ,UAAU,aAAa;AAAA,IAClD,MAAM,QAAQ,YAAY;AAAA,IAC1B,MAAM,QAAQ,YAAY;AAAA,EAC3B;AAEA,MAAI,SAAS,WAAW;AACvB,WAAO;AAAA,MACN;AAAA,MACA;AAAA,QACC,OAAO,EAAE,OAAO,OAAO,SAAS,QAAQ,YAAY,YAAY;AAAA,QAChE,MAAM;AAAA,MACP;AAAA,MACA,cAAc,UAAU,MAAM,kCAAkC;AAAA,MAChE,SA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A,IACjB,CAAC,kBAA4C;AAC5C,aAAO,QAAQ,UAAU,MAAM;AAC9B,cAAM,OAAO,QAAQ,gBAAgB,YAAY;AACjD,YAAI,SAAS,YAAY,SAAS;AACjC,sBAAY,UAAU;AACtB,wBAAc;AAAA,QACf;AAAA,MACD,CAAC;AAAA,IACF;AAAA,IACA,CAAC,SAAS,YAAY;AAAA,EACvB;AAEA,QAAM,cAAc,YAAY,MAAM,YAAY,SAAS,CAAC,CAAC;AAE7D,SAAOD,sBAAqB,WAAW,WAAW;AACnD;;;AD/KQ;AAvBD,SAAS,YAAY,EAAE,QAAQ,SAAS,GAAqB;AACnE,QAAM,aAAaE,QAA0B,IAAI;AAEjD,MAAI,WAAW,YAAY,QAAQ,WAAW,QAAQ,WAAW,QAAQ;AACxE,eAAW,SAAS,QAAQ;AAC5B,eAAW,UAAU,iBAAiB,MAAM;AAAA,EAC7C;AAEA,EAAAC,WAAU,MAAM;AACf,WAAO,MAAM;AACZ,iBAAW,SAAS,QAAQ;AAC5B,iBAAW,UAAU;AAAA,IACtB;AAAA,EACD,GAAG,CAAC,CAAC;AAEL,QAAM,QAAQC;AAAA,IACb,OAAO;AAAA,MACN;AAAA,MACA,SAAS,WAAW;AAAA,IACrB;AAAA,IACA,CAAC,MAAM;AAAA,EACR;AAEA,SAAO,oBAAC,WAAW,UAAX,EAAoB,OAAe,UAAS;AACrD;","names":["useSyncExternalStore","useSyncExternalStore","useEffect","useMemo","useRef","createContext","useContext","useEffect","useSyncExternalStore","createContext","useContext","useSyncExternalStore","useEffect","useRef","useEffect","useMemo"]}
|
package/dist/svelte.cjs
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
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/svelte.ts
|
|
21
|
+
var svelte_exports = {};
|
|
22
|
+
__export(svelte_exports, {
|
|
23
|
+
checkOrgPermission: () => checkOrgPermission,
|
|
24
|
+
createAuthStatusStore: () => createAuthStatusStore,
|
|
25
|
+
createAuthStore: () => createAuthStore,
|
|
26
|
+
createCurrentUserStore: () => createCurrentUserStore,
|
|
27
|
+
createPermissionStore: () => createPermissionStore,
|
|
28
|
+
destroyAuthProvider: () => destroyAuthProvider,
|
|
29
|
+
destroyOrgProvider: () => destroyOrgProvider,
|
|
30
|
+
getAuthContext: () => getAuthContext,
|
|
31
|
+
getOrgContext: () => getOrgContext,
|
|
32
|
+
initAuthProvider: () => initAuthProvider,
|
|
33
|
+
initOrgProvider: () => initOrgProvider,
|
|
34
|
+
useAuth: () => useAuth,
|
|
35
|
+
useAuthStatus: () => useAuthStatus,
|
|
36
|
+
useCurrentUser: () => useCurrentUser,
|
|
37
|
+
useOrg: () => useOrg,
|
|
38
|
+
useOrgMembers: () => useOrgMembers,
|
|
39
|
+
usePermission: () => usePermission
|
|
40
|
+
});
|
|
41
|
+
module.exports = __toCommonJS(svelte_exports);
|
|
42
|
+
|
|
43
|
+
// src/svelte/auth-context.ts
|
|
44
|
+
var import_svelte = require("svelte");
|
|
45
|
+
|
|
46
|
+
// src/bindings/create-auth-session.ts
|
|
47
|
+
function createAuthSession(client) {
|
|
48
|
+
let state = client.state;
|
|
49
|
+
let isLoading = true;
|
|
50
|
+
let initError = null;
|
|
51
|
+
let lastError = null;
|
|
52
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
53
|
+
let snapshot = buildSnapshot2();
|
|
54
|
+
const refreshSnapshot = () => {
|
|
55
|
+
snapshot = buildSnapshot2();
|
|
56
|
+
};
|
|
57
|
+
const notify = () => {
|
|
58
|
+
refreshSnapshot();
|
|
59
|
+
for (const listener of listeners) {
|
|
60
|
+
listener();
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
function buildSnapshot2() {
|
|
64
|
+
return {
|
|
65
|
+
state,
|
|
66
|
+
user: client.currentUser,
|
|
67
|
+
isAuthenticated: state === "authenticated",
|
|
68
|
+
isLoading,
|
|
69
|
+
initError,
|
|
70
|
+
error: lastError
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
const captureError = (error) => {
|
|
74
|
+
lastError = error instanceof Error ? error.message : String(error);
|
|
75
|
+
notify();
|
|
76
|
+
};
|
|
77
|
+
const run = async (action) => {
|
|
78
|
+
lastError = null;
|
|
79
|
+
try {
|
|
80
|
+
await action();
|
|
81
|
+
} catch (error) {
|
|
82
|
+
captureError(error);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
const runWithResult = async (action) => {
|
|
86
|
+
lastError = null;
|
|
87
|
+
try {
|
|
88
|
+
return await action();
|
|
89
|
+
} catch (error) {
|
|
90
|
+
captureError(error);
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
const unsubscribeAuth = client.onAuthChange((nextState) => {
|
|
95
|
+
state = nextState;
|
|
96
|
+
notify();
|
|
97
|
+
});
|
|
98
|
+
void client.initialize().then(() => {
|
|
99
|
+
state = client.state;
|
|
100
|
+
isLoading = false;
|
|
101
|
+
notify();
|
|
102
|
+
}).catch((error) => {
|
|
103
|
+
initError = error instanceof Error ? error : new Error(String(error));
|
|
104
|
+
isLoading = false;
|
|
105
|
+
notify();
|
|
106
|
+
});
|
|
107
|
+
return {
|
|
108
|
+
client,
|
|
109
|
+
getSnapshot: () => snapshot,
|
|
110
|
+
subscribe(listener) {
|
|
111
|
+
listeners.add(listener);
|
|
112
|
+
return () => {
|
|
113
|
+
listeners.delete(listener);
|
|
114
|
+
};
|
|
115
|
+
},
|
|
116
|
+
signUp: (params) => run(async () => {
|
|
117
|
+
await client.signUp(params);
|
|
118
|
+
}),
|
|
119
|
+
signIn: (params) => run(async () => {
|
|
120
|
+
await client.signIn(params);
|
|
121
|
+
}),
|
|
122
|
+
signInWithOAuth: async (provider, options) => {
|
|
123
|
+
lastError = null;
|
|
124
|
+
try {
|
|
125
|
+
return await client.signInWithOAuth(provider, options);
|
|
126
|
+
} catch (error) {
|
|
127
|
+
captureError(error);
|
|
128
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
129
|
+
}
|
|
130
|
+
},
|
|
131
|
+
completeOAuthSignIn: (provider, params) => run(async () => {
|
|
132
|
+
await client.completeOAuthSignIn(provider, params);
|
|
133
|
+
}),
|
|
134
|
+
getOAuthAuthorizationUrl: async (provider, options) => {
|
|
135
|
+
lastError = null;
|
|
136
|
+
try {
|
|
137
|
+
return await client.getOAuthAuthorizationUrl(provider, options);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
captureError(error);
|
|
140
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
linkOAuth: (provider, params) => runWithResult(async () => client.linkOAuth(provider, params)),
|
|
144
|
+
listLinkedAccounts: () => runWithResult(async () => client.listLinkedAccounts()).then((value) => value ?? []),
|
|
145
|
+
unlinkOAuth: (provider) => run(async () => {
|
|
146
|
+
await client.unlinkOAuth(provider);
|
|
147
|
+
}),
|
|
148
|
+
signOut: () => run(async () => {
|
|
149
|
+
await client.signOut();
|
|
150
|
+
}),
|
|
151
|
+
destroy() {
|
|
152
|
+
unsubscribeAuth();
|
|
153
|
+
listeners.clear();
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// src/svelte/auth-context.ts
|
|
159
|
+
var authContextKey = /* @__PURE__ */ Symbol("korajs-auth-context");
|
|
160
|
+
function initAuthProvider(client) {
|
|
161
|
+
const session = createAuthSession(client);
|
|
162
|
+
const value = {
|
|
163
|
+
client,
|
|
164
|
+
session,
|
|
165
|
+
get state() {
|
|
166
|
+
return session.getSnapshot().state;
|
|
167
|
+
},
|
|
168
|
+
get isLoading() {
|
|
169
|
+
return session.getSnapshot().isLoading;
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
(0, import_svelte.setContext)(authContextKey, value);
|
|
173
|
+
return value;
|
|
174
|
+
}
|
|
175
|
+
function getAuthContext() {
|
|
176
|
+
const context = (0, import_svelte.getContext)(authContextKey);
|
|
177
|
+
if (!context) {
|
|
178
|
+
throw new Error(
|
|
179
|
+
"Auth context missing. Call initAuthProvider(client) in your root layout component."
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
return context;
|
|
183
|
+
}
|
|
184
|
+
function destroyAuthProvider(context) {
|
|
185
|
+
context.session.destroy();
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// src/svelte/use-auth.ts
|
|
189
|
+
var import_store = require("svelte/store");
|
|
190
|
+
function createAuthStore() {
|
|
191
|
+
const { session } = getAuthContext();
|
|
192
|
+
return (0, import_store.readable)(buildResult(session), (set) => {
|
|
193
|
+
const sync = () => {
|
|
194
|
+
set(buildResult(session));
|
|
195
|
+
};
|
|
196
|
+
sync();
|
|
197
|
+
return session.subscribe(sync);
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
var useAuth = createAuthStore;
|
|
201
|
+
function buildResult(session) {
|
|
202
|
+
const snapshot = session.getSnapshot();
|
|
203
|
+
return {
|
|
204
|
+
...snapshot,
|
|
205
|
+
signUp: (params) => session.signUp(params),
|
|
206
|
+
signIn: (params) => session.signIn(params),
|
|
207
|
+
signInWithOAuth: (provider, options) => session.signInWithOAuth(provider, options),
|
|
208
|
+
completeOAuthSignIn: (provider, params) => session.completeOAuthSignIn(provider, params),
|
|
209
|
+
getOAuthAuthorizationUrl: (provider, options) => session.getOAuthAuthorizationUrl(provider, options),
|
|
210
|
+
linkOAuth: (provider, params) => session.linkOAuth(provider, params),
|
|
211
|
+
listLinkedAccounts: () => session.listLinkedAccounts(),
|
|
212
|
+
unlinkOAuth: (provider) => session.unlinkOAuth(provider),
|
|
213
|
+
signOut: () => session.signOut()
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
function createCurrentUserStore() {
|
|
217
|
+
const { session } = getAuthContext();
|
|
218
|
+
return (0, import_store.readable)(session.getSnapshot().user, (set) => {
|
|
219
|
+
const sync = () => {
|
|
220
|
+
set(session.getSnapshot().user);
|
|
221
|
+
};
|
|
222
|
+
sync();
|
|
223
|
+
return session.subscribe(sync);
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
var useCurrentUser = createCurrentUserStore;
|
|
227
|
+
function createAuthStatusStore() {
|
|
228
|
+
const { session } = getAuthContext();
|
|
229
|
+
return (0, import_store.readable)(
|
|
230
|
+
{
|
|
231
|
+
state: session.getSnapshot().state,
|
|
232
|
+
isAuthenticated: session.getSnapshot().isAuthenticated,
|
|
233
|
+
isLoading: session.getSnapshot().isLoading
|
|
234
|
+
},
|
|
235
|
+
(set) => {
|
|
236
|
+
const sync = () => {
|
|
237
|
+
const snapshot = session.getSnapshot();
|
|
238
|
+
set({
|
|
239
|
+
state: snapshot.state,
|
|
240
|
+
isAuthenticated: snapshot.isAuthenticated,
|
|
241
|
+
isLoading: snapshot.isLoading
|
|
242
|
+
});
|
|
243
|
+
};
|
|
244
|
+
sync();
|
|
245
|
+
return session.subscribe(sync);
|
|
246
|
+
}
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
var useAuthStatus = createAuthStatusStore;
|
|
250
|
+
|
|
251
|
+
// src/svelte/org-context.ts
|
|
252
|
+
var import_svelte2 = require("svelte");
|
|
253
|
+
|
|
254
|
+
// src/bindings/create-org-session.ts
|
|
255
|
+
var ROLE_LEVELS = {
|
|
256
|
+
viewer: 10,
|
|
257
|
+
billing: 15,
|
|
258
|
+
member: 20,
|
|
259
|
+
admin: 30,
|
|
260
|
+
owner: 40
|
|
261
|
+
};
|
|
262
|
+
function checkOrgPermission(currentRole, requiredRole) {
|
|
263
|
+
if (!currentRole) return false;
|
|
264
|
+
const currentLevel = ROLE_LEVELS[currentRole] ?? 0;
|
|
265
|
+
const requiredLevel = ROLE_LEVELS[requiredRole] ?? 0;
|
|
266
|
+
return currentLevel >= requiredLevel;
|
|
267
|
+
}
|
|
268
|
+
function createOrgSession(client) {
|
|
269
|
+
let snapshot = buildSnapshot(client);
|
|
270
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
271
|
+
const notify = () => {
|
|
272
|
+
snapshot = buildSnapshot(client);
|
|
273
|
+
for (const listener of listeners) {
|
|
274
|
+
listener();
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
const unsubscribeOrgChange = client.onOrgChange(notify);
|
|
278
|
+
return {
|
|
279
|
+
client,
|
|
280
|
+
getSnapshot: () => snapshot,
|
|
281
|
+
subscribe(listener) {
|
|
282
|
+
listeners.add(listener);
|
|
283
|
+
return () => {
|
|
284
|
+
listeners.delete(listener);
|
|
285
|
+
};
|
|
286
|
+
},
|
|
287
|
+
checkPermission(requiredRole) {
|
|
288
|
+
return checkOrgPermission(snapshot.role, requiredRole);
|
|
289
|
+
},
|
|
290
|
+
destroy() {
|
|
291
|
+
unsubscribeOrgChange();
|
|
292
|
+
listeners.clear();
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
function buildSnapshot(client) {
|
|
297
|
+
return {
|
|
298
|
+
orgId: client.activeOrgId,
|
|
299
|
+
org: client.activeOrg,
|
|
300
|
+
role: client.activeRole
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
function createOrgMembersActions(client, orgId, onError) {
|
|
304
|
+
return {
|
|
305
|
+
async refresh() {
|
|
306
|
+
await client.listMembers(orgId);
|
|
307
|
+
},
|
|
308
|
+
async invite(email, role) {
|
|
309
|
+
try {
|
|
310
|
+
return await client.inviteMember(orgId, { email, role });
|
|
311
|
+
} catch (error) {
|
|
312
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
313
|
+
onError(message);
|
|
314
|
+
throw error;
|
|
315
|
+
}
|
|
316
|
+
},
|
|
317
|
+
async removeMember(userId) {
|
|
318
|
+
try {
|
|
319
|
+
await client.removeMember(orgId, userId);
|
|
320
|
+
} catch (error) {
|
|
321
|
+
onError(error instanceof Error ? error.message : String(error));
|
|
322
|
+
}
|
|
323
|
+
},
|
|
324
|
+
async updateRole(userId, role) {
|
|
325
|
+
try {
|
|
326
|
+
await client.updateMemberRole(orgId, userId, role);
|
|
327
|
+
} catch (error) {
|
|
328
|
+
onError(error instanceof Error ? error.message : String(error));
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
async function loadOrgMembers(client, orgId) {
|
|
334
|
+
return client.listMembers(orgId);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// src/svelte/org-context.ts
|
|
338
|
+
var orgContextKey = /* @__PURE__ */ Symbol("korajs-org-context");
|
|
339
|
+
function initOrgProvider(client) {
|
|
340
|
+
const session = createOrgSession(client);
|
|
341
|
+
const value = { client, session };
|
|
342
|
+
(0, import_svelte2.setContext)(orgContextKey, value);
|
|
343
|
+
return value;
|
|
344
|
+
}
|
|
345
|
+
function getOrgContext() {
|
|
346
|
+
const context = (0, import_svelte2.getContext)(orgContextKey);
|
|
347
|
+
if (!context) {
|
|
348
|
+
throw new Error(
|
|
349
|
+
"Org context missing. Wrap your app with <OrgProvider client={orgClient}> from @korajs/auth/svelte."
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
return context;
|
|
353
|
+
}
|
|
354
|
+
function destroyOrgProvider(context) {
|
|
355
|
+
context.session.destroy();
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// src/svelte/org-hooks.ts
|
|
359
|
+
var import_store2 = require("svelte/store");
|
|
360
|
+
function createOrgSnapshotStore() {
|
|
361
|
+
const { session } = getOrgContext();
|
|
362
|
+
return (0, import_store2.readable)(session.getSnapshot(), (set) => {
|
|
363
|
+
set(session.getSnapshot());
|
|
364
|
+
return session.subscribe(() => {
|
|
365
|
+
set(session.getSnapshot());
|
|
366
|
+
});
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
function useOrg() {
|
|
370
|
+
const { client, session } = getOrgContext();
|
|
371
|
+
const snapshotStore = createOrgSnapshotStore();
|
|
372
|
+
const error = (0, import_store2.writable)(null);
|
|
373
|
+
const store = (0, import_store2.derived)([snapshotStore, error], ([snapshot, errorValue]) => ({
|
|
374
|
+
...snapshot,
|
|
375
|
+
error: errorValue
|
|
376
|
+
}));
|
|
377
|
+
const switchOrg = async (orgId) => {
|
|
378
|
+
error.set(null);
|
|
379
|
+
try {
|
|
380
|
+
await client.switchOrg(orgId);
|
|
381
|
+
} catch (err) {
|
|
382
|
+
error.set(err instanceof Error ? err.message : String(err));
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
const createOrg = async (params) => {
|
|
386
|
+
error.set(null);
|
|
387
|
+
try {
|
|
388
|
+
return await client.createOrg(params);
|
|
389
|
+
} catch (err) {
|
|
390
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
391
|
+
error.set(message);
|
|
392
|
+
throw err;
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
const leaveOrg = async () => {
|
|
396
|
+
const orgId = (0, import_store2.get)(snapshotStore).orgId;
|
|
397
|
+
if (!orgId) return;
|
|
398
|
+
error.set(null);
|
|
399
|
+
try {
|
|
400
|
+
await client.leaveOrg(orgId);
|
|
401
|
+
} catch (err) {
|
|
402
|
+
error.set(err instanceof Error ? err.message : String(err));
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
const clearOrg = () => {
|
|
406
|
+
client.clearActiveOrg();
|
|
407
|
+
};
|
|
408
|
+
const listOrgs = async () => {
|
|
409
|
+
try {
|
|
410
|
+
return await client.listOrgs();
|
|
411
|
+
} catch (err) {
|
|
412
|
+
error.set(err instanceof Error ? err.message : String(err));
|
|
413
|
+
return [];
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
return {
|
|
417
|
+
subscribe: store.subscribe,
|
|
418
|
+
get org() {
|
|
419
|
+
return (0, import_store2.get)(snapshotStore).org;
|
|
420
|
+
},
|
|
421
|
+
get role() {
|
|
422
|
+
return (0, import_store2.get)(snapshotStore).role;
|
|
423
|
+
},
|
|
424
|
+
get orgId() {
|
|
425
|
+
return (0, import_store2.get)(snapshotStore).orgId;
|
|
426
|
+
},
|
|
427
|
+
switchOrg,
|
|
428
|
+
createOrg,
|
|
429
|
+
leaveOrg,
|
|
430
|
+
clearOrg,
|
|
431
|
+
listOrgs
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
function useOrgMembers(orgId) {
|
|
435
|
+
const { client } = getOrgContext();
|
|
436
|
+
const members = (0, import_store2.writable)([]);
|
|
437
|
+
const isLoading = (0, import_store2.writable)(true);
|
|
438
|
+
const error = (0, import_store2.writable)(null);
|
|
439
|
+
const refresh = async (targetOrgId) => {
|
|
440
|
+
isLoading.set(true);
|
|
441
|
+
error.set(null);
|
|
442
|
+
try {
|
|
443
|
+
members.set(await loadOrgMembers(client, targetOrgId));
|
|
444
|
+
} catch (err) {
|
|
445
|
+
error.set(err instanceof Error ? err.message : String(err));
|
|
446
|
+
} finally {
|
|
447
|
+
isLoading.set(false);
|
|
448
|
+
}
|
|
449
|
+
};
|
|
450
|
+
$effect(() => {
|
|
451
|
+
void refresh(orgId);
|
|
452
|
+
});
|
|
453
|
+
const actions = createOrgMembersActions(client, orgId, (message) => {
|
|
454
|
+
error.set(message);
|
|
455
|
+
});
|
|
456
|
+
const invite = async (email, role) => {
|
|
457
|
+
const result = await actions.invite(email, role);
|
|
458
|
+
await refresh(orgId);
|
|
459
|
+
return result;
|
|
460
|
+
};
|
|
461
|
+
const removeMember = async (userId) => {
|
|
462
|
+
await actions.removeMember(userId);
|
|
463
|
+
await refresh(orgId);
|
|
464
|
+
};
|
|
465
|
+
const updateRole = async (userId, role) => {
|
|
466
|
+
await actions.updateRole(userId, role);
|
|
467
|
+
await refresh(orgId);
|
|
468
|
+
};
|
|
469
|
+
const store = (0, import_store2.derived)([members, isLoading, error], ([memberList, loading, errorValue]) => ({
|
|
470
|
+
members: memberList,
|
|
471
|
+
isLoading: loading,
|
|
472
|
+
error: errorValue
|
|
473
|
+
}));
|
|
474
|
+
return {
|
|
475
|
+
subscribe: store.subscribe,
|
|
476
|
+
refresh: () => refresh(orgId),
|
|
477
|
+
invite,
|
|
478
|
+
removeMember,
|
|
479
|
+
updateRole
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
function createPermissionStore(requiredRole) {
|
|
483
|
+
const { session } = getOrgContext();
|
|
484
|
+
return (0, import_store2.readable)(session.checkPermission(requiredRole), (set) => {
|
|
485
|
+
set(session.checkPermission(requiredRole));
|
|
486
|
+
return session.subscribe(() => {
|
|
487
|
+
set(session.checkPermission(requiredRole));
|
|
488
|
+
});
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
var usePermission = createPermissionStore;
|
|
492
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
493
|
+
0 && (module.exports = {
|
|
494
|
+
checkOrgPermission,
|
|
495
|
+
createAuthStatusStore,
|
|
496
|
+
createAuthStore,
|
|
497
|
+
createCurrentUserStore,
|
|
498
|
+
createPermissionStore,
|
|
499
|
+
destroyAuthProvider,
|
|
500
|
+
destroyOrgProvider,
|
|
501
|
+
getAuthContext,
|
|
502
|
+
getOrgContext,
|
|
503
|
+
initAuthProvider,
|
|
504
|
+
initOrgProvider,
|
|
505
|
+
useAuth,
|
|
506
|
+
useAuthStatus,
|
|
507
|
+
useCurrentUser,
|
|
508
|
+
useOrg,
|
|
509
|
+
useOrgMembers,
|
|
510
|
+
usePermission
|
|
511
|
+
});
|
|
512
|
+
//# sourceMappingURL=svelte.cjs.map
|