@korajs/auth 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -30
- package/dist/chunk-FSU4SK32.js +786 -0
- package/dist/chunk-FSU4SK32.js.map +1 -0
- package/dist/chunk-HOZXDR6Y.js +52 -0
- package/dist/chunk-HOZXDR6Y.js.map +1 -0
- package/dist/index.cjs +1538 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +708 -5
- package/dist/index.d.ts +708 -5
- package/dist/index.js +926 -3
- package/dist/index.js.map +1 -1
- package/dist/{device-identity-DiwdLsUB.d.cts → operation-encryptor-DRmKNWpF.d.cts} +148 -2
- package/dist/{device-identity-DiwdLsUB.d.ts → operation-encryptor-DRmKNWpF.d.ts} +148 -2
- package/dist/{auth-client-CrDNuh10.d.cts → org-client-BVTLKcIk.d.cts} +177 -3
- package/dist/{auth-client-CrDNuh10.d.ts → org-client-BVTLKcIk.d.ts} +177 -3
- package/dist/password-hash-HDH6VQCQ.js +9 -0
- package/dist/password-hash-HDH6VQCQ.js.map +1 -0
- package/dist/react.cjs +183 -2
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +107 -2
- package/dist/react.d.ts +107 -2
- package/dist/react.js +186 -1
- package/dist/react.js.map +1 -1
- package/dist/server.cjs +4945 -224
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +3039 -29
- package/dist/server.d.ts +3039 -29
- package/dist/server.js +4272 -92
- package/dist/server.js.map +1 -1
- package/package.json +5 -5
- package/dist/chunk-L554ZDPY.js +0 -174
- package/dist/chunk-L554ZDPY.js.map +0 -1
package/dist/react.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react.ts","../src/react/AuthProvider.tsx","../src/react/auth-context.ts","../src/react/hooks.ts"],"sourcesContent":["// @korajs/auth/react — React-specific public API\n// Every export here is a public API commitment. Be explicit.\n\n// === Provider ===\nexport { AuthProvider } from './react/AuthProvider'\nexport type { AuthProviderProps } from './react/AuthProvider'\n\n// === Hooks ===\nexport { useAuth, useCurrentUser, useAuthStatus } from './react/hooks'\nexport type { UseAuthResult, AuthStatus } from './react/hooks'\n\n// === Context (for advanced use cases) ===\nexport { AuthContext } from './react/auth-context'\nexport type { AuthContextValue } from './react/auth-context'\n","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 { AuthUser, AuthState } 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(): { client: import('../client/auth-client').AuthClient; state: AuthState; isLoading: boolean } {\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: { email: string; password: string; name?: string }) => Promise<void>\n\n\t/** Sign in with email and password */\n\tsignIn: (params: { email: string; password: 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: { email: string; password: string; name?: string }): 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: { email: string; password: string }): 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 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\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAAmD;;;ACAnD,mBAA8B;AAiC9B,IAAM,kBAAc,4BAAuC,IAAI;;;ADkB/D,SAAS,aAAa,EAAE,QAAQ,UAAU,SAAS,GAAoC;AACtF,QAAM,CAAC,OAAO,QAAQ,QAAI,wBAAoB,OAAO,KAAK;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AACtD,aAAS,IAAI;AACb,QAAI;AACH,YAAM,OAAO,QAAQ;AAAA,IACtB,SAAS,KAAc;AACtB,YAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,eAAS,OAAO;AAAA,IACjB;AAAA,EACD,GAAG,CAAC,MAAM,CAAC;AAEX,SAAO;AAAA,IACN;AAAA,IACA,iBAAiB,UAAU;AAAA,IAC3B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AACD;AAyBA,SAAS,iBAAkC;AAC1C,QAAM,EAAE,OAAO,IAAI,eAAe;AAElC,QAAM,sBAAkB,sBAAwB,OAAO,WAAW;AAClE,QAAM,yBAAqB,sBAAe,KAAK,UAAU,OAAO,WAAW,CAAC;AAE5E,QAAM,gBAAY;AAAA,IACjB,CAAC,kBAA4C;AAC5C,aAAO,OAAO,aAAa,MAAM;AAChC,cAAM,UAAU,OAAO;AACvB,cAAM,gBAAgB,KAAK,UAAU,OAAO;AAC5C,YAAI,kBAAkB,mBAAmB,SAAS;AACjD,0BAAgB,UAAU;AAC1B,6BAAmB,UAAU;AAC7B,wBAAc;AAAA,QACf;AAAA,MACD,CAAC;AAAA,IACF;AAAA,IACA,CAAC,MAAM;AAAA,EACR;AAEA,QAAM,kBAAc,2BAAY,MAAuB;AACtD,WAAO,gBAAgB;AAAA,EACxB,GAAG,CAAC,CAAC;AAEL,aAAO,oCAAqB,WAAW,WAAW;AACnD;AA0BA,SAAS,gBAA4B;AACpC,QAAM,EAAE,OAAO,UAAU,IAAI,eAAe;AAE5C,SAAO;AAAA,IACN;AAAA,IACA,iBAAiB,UAAU;AAAA,IAC3B;AAAA,EACD;AACD;","names":["import_react","import_react"]}
|
|
1
|
+
{"version":3,"sources":["../src/react.ts","../src/react/AuthProvider.tsx","../src/react/auth-context.ts","../src/react/hooks.ts","../src/react/org-hooks.ts"],"sourcesContent":["// @korajs/auth/react — React-specific public API\n// Every export here is a public API commitment. Be explicit.\n\n// === Provider ===\nexport { AuthProvider } from './react/AuthProvider'\nexport type { AuthProviderProps } from './react/AuthProvider'\n\n// === Hooks ===\nexport { useAuth, useCurrentUser, useAuthStatus } from './react/hooks'\nexport type { UseAuthResult, AuthStatus } from './react/hooks'\n\n// === Context (for advanced use cases) ===\nexport { AuthContext } from './react/auth-context'\nexport type { AuthContextValue } from './react/auth-context'\n\n// === Organization Hooks ===\nexport { OrgContext, useOrg, useOrgMembers, usePermission } from './react/org-hooks'\nexport type { OrgContextValue, UseOrgResult, UseOrgMembersResult } from './react/org-hooks'\n","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 { AuthUser, AuthState } 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(): { client: import('../client/auth-client').AuthClient; state: AuthState; isLoading: boolean } {\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: { email: string; password: string; name?: string }) => Promise<void>\n\n\t/** Sign in with email and password */\n\tsignIn: (params: { email: string; password: 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: { email: string; password: string; name?: string }): 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: { email: string; password: string }): 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 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\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 { OrgClient, ClientOrganization, ClientMembership, ClientInvitation } 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 requiredLevel = ROLE_LEVELS[requiredRole] ?? 0\n\treturn currentLevel >= requiredLevel\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAAmD;;;ACAnD,mBAA8B;AAiC9B,IAAM,kBAAc,4BAAuC,IAAI;;;ADkB/D,SAAS,aAAa,EAAE,QAAQ,UAAU,SAAS,GAAoC;AACtF,QAAM,CAAC,OAAO,QAAQ,QAAI,wBAAoB,OAAO,KAAK;AAC1D,QAAM,CAAC,WAAW,YAAY,QAAI,wBAAS,IAAI;AAC/C,QAAM,CAAC,WAAW,YAAY,QAAI,wBAAuB,IAAI;AAG7D,+BAAU,MAAM;AACf,QAAI,YAAY;AAGhB,UAAM,cAAc,OAAO,aAAa,CAAC,aAAa;AACrD,UAAI,CAAC,WAAW;AACf,iBAAS,QAAQ;AAAA,MAClB;AAAA,IACD,CAAC;AAED,WACE,WAAW,EACX,KAAK,MAAM;AACX,UAAI,CAAC,WAAW;AACf,iBAAS,OAAO,KAAK;AACrB,qBAAa,KAAK;AAAA,MACnB;AAAA,IACD,CAAC,EACA,MAAM,CAAC,UAAmB;AAC1B,UAAI,CAAC,WAAW;AACf,cAAM,MAAM,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AACpE,gBAAQ,MAAM,sCAAsC,GAAG;AACvD,qBAAa,GAAG;AAChB,qB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AAS,IAAI;AACb,UAAI;AACH,cAAM,OAAO,iBAAiB,OAAO,QAAQ,IAAI;AACjD,cAAM,QAAQ;AAAA,MACf,SAAS,KAAK;AACb,iBAAS,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,MAC1D;AAAA,IACD;AAAA,IACA,CAAC,QAAQ,OAAO,OAAO;AAAA,EACxB;AAEA,SAAO,EAAE,SAAS,WAAW,SAAS,QAAQ,cAAc,YAAY,MAAM;AAC/E;AAsBO,SAAS,cAAc,cAA+B;AAC5D,QAAM,EAAE,OAAO,IAAI,cAAc;AAEjC,QAAM,kBAAc,sBAAO,gBAAgB,OAAO,YAAY,YAAY,CAAC;AAE3E,QAAM,gBAAY;AAAA,IACjB,CAAC,kBAA4C;AAC5C,aAAO,OAAO,YAAY,MAAM;AAC/B,cAAM,WAAW,gBAAgB,OAAO,YAAY,YAAY;AAChE,YAAI,aAAa,YAAY,SAAS;AACrC,sBAAY,UAAU;AACtB,wBAAc;AAAA,QACf;AAAA,MACD,CAAC;AAAA,IACF;AAAA,IACA,CAAC,QAAQ,YAAY;AAAA,EACtB;AAEA,QAAM,kBAAc,2BAAY,MAAM,YAAY,SAAS,CAAC,CAAC;AAE7D,aAAO,oCAAqB,WAAW,WAAW;AACnD;AAGA,IAAM,cAAsC;AAAA,EAC3C,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,OAAO;AACR;AAEA,SAAS,gBAAgB,aAA4B,cAA+B;AACnF,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,eAAe,YAAY,WAAW,KAAK;AACjD,QAAM,gBAAgB,YAAY,YAAY,KAAK;AACnD,SAAO,gBAAgB;AACxB;","names":["import_react","import_react","import_react"]}
|
package/dist/react.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
2
|
import { ReactNode, ReactElement } from 'react';
|
|
3
|
-
import { A as AuthClient, c as AuthState$1, d as AuthUser } from './
|
|
3
|
+
import { A as AuthClient, c as AuthState$1, d as AuthUser, O as OrgClient, e as ClientMembership, C as ClientInvitation, f as ClientOrganization } from './org-client-BVTLKcIk.cjs';
|
|
4
4
|
import '@korajs/core';
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -186,4 +186,109 @@ interface AuthContextValue {
|
|
|
186
186
|
*/
|
|
187
187
|
declare const AuthContext: react.Context<AuthContextValue | null>;
|
|
188
188
|
|
|
189
|
-
|
|
189
|
+
/**
|
|
190
|
+
* Shape of the OrgContext value.
|
|
191
|
+
*/
|
|
192
|
+
interface OrgContextValue {
|
|
193
|
+
/** The OrgClient instance */
|
|
194
|
+
client: OrgClient;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* React context for organization state.
|
|
198
|
+
*/
|
|
199
|
+
declare const OrgContext: react.Context<OrgContextValue | null>;
|
|
200
|
+
/**
|
|
201
|
+
* Return value of the {@link useOrg} hook.
|
|
202
|
+
*/
|
|
203
|
+
interface UseOrgResult {
|
|
204
|
+
/** Currently active organization, or null */
|
|
205
|
+
org: ClientOrganization | null;
|
|
206
|
+
/** Current user's role in the active organization, or null */
|
|
207
|
+
role: string | null;
|
|
208
|
+
/** Active organization ID, or null */
|
|
209
|
+
orgId: string | null;
|
|
210
|
+
/** Switch to a different organization */
|
|
211
|
+
switchOrg: (orgId: string) => Promise<void>;
|
|
212
|
+
/** Create a new organization */
|
|
213
|
+
createOrg: (params: {
|
|
214
|
+
name: string;
|
|
215
|
+
slug?: string;
|
|
216
|
+
}) => Promise<ClientOrganization>;
|
|
217
|
+
/** Leave the active organization */
|
|
218
|
+
leaveOrg: () => Promise<void>;
|
|
219
|
+
/** Clear the active organization */
|
|
220
|
+
clearOrg: () => void;
|
|
221
|
+
/** List all organizations the user belongs to */
|
|
222
|
+
listOrgs: () => Promise<ClientOrganization[]>;
|
|
223
|
+
/** Last error, or null */
|
|
224
|
+
error: string | null;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* React hook for organization management and context switching.
|
|
228
|
+
*
|
|
229
|
+
* Re-renders when the active organization changes.
|
|
230
|
+
*
|
|
231
|
+
* @example
|
|
232
|
+
* ```typescript
|
|
233
|
+
* function OrgSwitcher() {
|
|
234
|
+
* const { org, switchOrg, listOrgs, error } = useOrg()
|
|
235
|
+
* const [orgs, setOrgs] = useState<ClientOrganization[]>([])
|
|
236
|
+
*
|
|
237
|
+
* useEffect(() => { listOrgs().then(setOrgs) }, [listOrgs])
|
|
238
|
+
*
|
|
239
|
+
* return (
|
|
240
|
+
* <select value={org?.id ?? ''} onChange={(e) => switchOrg(e.target.value)}>
|
|
241
|
+
* <option value="">Select org...</option>
|
|
242
|
+
* {orgs.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}
|
|
243
|
+
* </select>
|
|
244
|
+
* )
|
|
245
|
+
* }
|
|
246
|
+
* ```
|
|
247
|
+
*/
|
|
248
|
+
declare function useOrg(): UseOrgResult;
|
|
249
|
+
/**
|
|
250
|
+
* Return value of the {@link useOrgMembers} hook.
|
|
251
|
+
*/
|
|
252
|
+
interface UseOrgMembersResult {
|
|
253
|
+
/** Members of the organization (empty until loaded) */
|
|
254
|
+
members: ClientMembership[];
|
|
255
|
+
/** Whether members are being loaded */
|
|
256
|
+
isLoading: boolean;
|
|
257
|
+
/** Reload the members list */
|
|
258
|
+
refresh: () => Promise<void>;
|
|
259
|
+
/** Invite a user by email */
|
|
260
|
+
invite: (email: string, role: string) => Promise<ClientInvitation>;
|
|
261
|
+
/** Remove a member */
|
|
262
|
+
removeMember: (userId: string) => Promise<void>;
|
|
263
|
+
/** Update a member's role */
|
|
264
|
+
updateRole: (userId: string, role: string) => Promise<void>;
|
|
265
|
+
/** Last error, or null */
|
|
266
|
+
error: string | null;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* React hook for managing organization members.
|
|
270
|
+
*
|
|
271
|
+
* Automatically loads members when the orgId changes.
|
|
272
|
+
*
|
|
273
|
+
* @param orgId - Organization ID to manage members for
|
|
274
|
+
*/
|
|
275
|
+
declare function useOrgMembers(orgId: string): UseOrgMembersResult;
|
|
276
|
+
/**
|
|
277
|
+
* React hook that checks if the current user has a specific role level
|
|
278
|
+
* in the active organization.
|
|
279
|
+
*
|
|
280
|
+
* @param requiredRole - Minimum role required (uses ROLE_HIERARCHY from org-types)
|
|
281
|
+
* @returns true if the user's role is at least requiredRole
|
|
282
|
+
*
|
|
283
|
+
* @example
|
|
284
|
+
* ```typescript
|
|
285
|
+
* function AdminPanel() {
|
|
286
|
+
* const canManage = usePermission('admin')
|
|
287
|
+
* if (!canManage) return <p>Access denied</p>
|
|
288
|
+
* return <AdminSettings />
|
|
289
|
+
* }
|
|
290
|
+
* ```
|
|
291
|
+
*/
|
|
292
|
+
declare function usePermission(requiredRole: string): boolean;
|
|
293
|
+
|
|
294
|
+
export { AuthContext, type AuthContextValue, AuthProvider, type AuthProviderProps, type AuthStatus, OrgContext, type OrgContextValue, type UseAuthResult, type UseOrgMembersResult, type UseOrgResult, useAuth, useAuthStatus, useCurrentUser, useOrg, useOrgMembers, usePermission };
|
package/dist/react.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
2
|
import { ReactNode, ReactElement } from 'react';
|
|
3
|
-
import { A as AuthClient, c as AuthState$1, d as AuthUser } from './
|
|
3
|
+
import { A as AuthClient, c as AuthState$1, d as AuthUser, O as OrgClient, e as ClientMembership, C as ClientInvitation, f as ClientOrganization } from './org-client-BVTLKcIk.js';
|
|
4
4
|
import '@korajs/core';
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -186,4 +186,109 @@ interface AuthContextValue {
|
|
|
186
186
|
*/
|
|
187
187
|
declare const AuthContext: react.Context<AuthContextValue | null>;
|
|
188
188
|
|
|
189
|
-
|
|
189
|
+
/**
|
|
190
|
+
* Shape of the OrgContext value.
|
|
191
|
+
*/
|
|
192
|
+
interface OrgContextValue {
|
|
193
|
+
/** The OrgClient instance */
|
|
194
|
+
client: OrgClient;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* React context for organization state.
|
|
198
|
+
*/
|
|
199
|
+
declare const OrgContext: react.Context<OrgContextValue | null>;
|
|
200
|
+
/**
|
|
201
|
+
* Return value of the {@link useOrg} hook.
|
|
202
|
+
*/
|
|
203
|
+
interface UseOrgResult {
|
|
204
|
+
/** Currently active organization, or null */
|
|
205
|
+
org: ClientOrganization | null;
|
|
206
|
+
/** Current user's role in the active organization, or null */
|
|
207
|
+
role: string | null;
|
|
208
|
+
/** Active organization ID, or null */
|
|
209
|
+
orgId: string | null;
|
|
210
|
+
/** Switch to a different organization */
|
|
211
|
+
switchOrg: (orgId: string) => Promise<void>;
|
|
212
|
+
/** Create a new organization */
|
|
213
|
+
createOrg: (params: {
|
|
214
|
+
name: string;
|
|
215
|
+
slug?: string;
|
|
216
|
+
}) => Promise<ClientOrganization>;
|
|
217
|
+
/** Leave the active organization */
|
|
218
|
+
leaveOrg: () => Promise<void>;
|
|
219
|
+
/** Clear the active organization */
|
|
220
|
+
clearOrg: () => void;
|
|
221
|
+
/** List all organizations the user belongs to */
|
|
222
|
+
listOrgs: () => Promise<ClientOrganization[]>;
|
|
223
|
+
/** Last error, or null */
|
|
224
|
+
error: string | null;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* React hook for organization management and context switching.
|
|
228
|
+
*
|
|
229
|
+
* Re-renders when the active organization changes.
|
|
230
|
+
*
|
|
231
|
+
* @example
|
|
232
|
+
* ```typescript
|
|
233
|
+
* function OrgSwitcher() {
|
|
234
|
+
* const { org, switchOrg, listOrgs, error } = useOrg()
|
|
235
|
+
* const [orgs, setOrgs] = useState<ClientOrganization[]>([])
|
|
236
|
+
*
|
|
237
|
+
* useEffect(() => { listOrgs().then(setOrgs) }, [listOrgs])
|
|
238
|
+
*
|
|
239
|
+
* return (
|
|
240
|
+
* <select value={org?.id ?? ''} onChange={(e) => switchOrg(e.target.value)}>
|
|
241
|
+
* <option value="">Select org...</option>
|
|
242
|
+
* {orgs.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}
|
|
243
|
+
* </select>
|
|
244
|
+
* )
|
|
245
|
+
* }
|
|
246
|
+
* ```
|
|
247
|
+
*/
|
|
248
|
+
declare function useOrg(): UseOrgResult;
|
|
249
|
+
/**
|
|
250
|
+
* Return value of the {@link useOrgMembers} hook.
|
|
251
|
+
*/
|
|
252
|
+
interface UseOrgMembersResult {
|
|
253
|
+
/** Members of the organization (empty until loaded) */
|
|
254
|
+
members: ClientMembership[];
|
|
255
|
+
/** Whether members are being loaded */
|
|
256
|
+
isLoading: boolean;
|
|
257
|
+
/** Reload the members list */
|
|
258
|
+
refresh: () => Promise<void>;
|
|
259
|
+
/** Invite a user by email */
|
|
260
|
+
invite: (email: string, role: string) => Promise<ClientInvitation>;
|
|
261
|
+
/** Remove a member */
|
|
262
|
+
removeMember: (userId: string) => Promise<void>;
|
|
263
|
+
/** Update a member's role */
|
|
264
|
+
updateRole: (userId: string, role: string) => Promise<void>;
|
|
265
|
+
/** Last error, or null */
|
|
266
|
+
error: string | null;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* React hook for managing organization members.
|
|
270
|
+
*
|
|
271
|
+
* Automatically loads members when the orgId changes.
|
|
272
|
+
*
|
|
273
|
+
* @param orgId - Organization ID to manage members for
|
|
274
|
+
*/
|
|
275
|
+
declare function useOrgMembers(orgId: string): UseOrgMembersResult;
|
|
276
|
+
/**
|
|
277
|
+
* React hook that checks if the current user has a specific role level
|
|
278
|
+
* in the active organization.
|
|
279
|
+
*
|
|
280
|
+
* @param requiredRole - Minimum role required (uses ROLE_HIERARCHY from org-types)
|
|
281
|
+
* @returns true if the user's role is at least requiredRole
|
|
282
|
+
*
|
|
283
|
+
* @example
|
|
284
|
+
* ```typescript
|
|
285
|
+
* function AdminPanel() {
|
|
286
|
+
* const canManage = usePermission('admin')
|
|
287
|
+
* if (!canManage) return <p>Access denied</p>
|
|
288
|
+
* return <AdminSettings />
|
|
289
|
+
* }
|
|
290
|
+
* ```
|
|
291
|
+
*/
|
|
292
|
+
declare function usePermission(requiredRole: string): boolean;
|
|
293
|
+
|
|
294
|
+
export { AuthContext, type AuthContextValue, AuthProvider, type AuthProviderProps, type AuthStatus, OrgContext, type OrgContextValue, type UseAuthResult, type UseOrgMembersResult, type UseOrgResult, useAuth, useAuthStatus, useCurrentUser, useOrg, useOrgMembers, usePermission };
|
package/dist/react.js
CHANGED
|
@@ -165,11 +165,196 @@ function useAuthStatus() {
|
|
|
165
165
|
isLoading
|
|
166
166
|
};
|
|
167
167
|
}
|
|
168
|
+
|
|
169
|
+
// src/react/org-hooks.ts
|
|
170
|
+
import {
|
|
171
|
+
createContext as createContext2,
|
|
172
|
+
useCallback as useCallback2,
|
|
173
|
+
useContext as useContext2,
|
|
174
|
+
useEffect as useEffect3,
|
|
175
|
+
useRef as useRef2,
|
|
176
|
+
useState as useState3,
|
|
177
|
+
useSyncExternalStore as useSyncExternalStore2
|
|
178
|
+
} from "react";
|
|
179
|
+
var OrgContext = createContext2(null);
|
|
180
|
+
function useOrgContext() {
|
|
181
|
+
const ctx = useContext2(OrgContext);
|
|
182
|
+
if (ctx === null) {
|
|
183
|
+
throw new Error(
|
|
184
|
+
"useOrg / useOrgMembers / usePermission must be used within an <OrgProvider>. Wrap your component tree with <OrgProvider client={orgClient}>."
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
return ctx;
|
|
188
|
+
}
|
|
189
|
+
function useOrg() {
|
|
190
|
+
const { client } = useOrgContext();
|
|
191
|
+
const [error, setError] = useState3(null);
|
|
192
|
+
const orgSnapshotRef = useRef2({
|
|
193
|
+
orgId: client.activeOrgId,
|
|
194
|
+
org: client.activeOrg,
|
|
195
|
+
role: client.activeRole
|
|
196
|
+
});
|
|
197
|
+
const subscribe = useCallback2(
|
|
198
|
+
(onStoreChange) => {
|
|
199
|
+
return client.onOrgChange(() => {
|
|
200
|
+
orgSnapshotRef.current = {
|
|
201
|
+
orgId: client.activeOrgId,
|
|
202
|
+
org: client.activeOrg,
|
|
203
|
+
role: client.activeRole
|
|
204
|
+
};
|
|
205
|
+
onStoreChange();
|
|
206
|
+
});
|
|
207
|
+
},
|
|
208
|
+
[client]
|
|
209
|
+
);
|
|
210
|
+
const getSnapshot = useCallback2(() => orgSnapshotRef.current, []);
|
|
211
|
+
const { orgId, org, role } = useSyncExternalStore2(subscribe, getSnapshot);
|
|
212
|
+
const switchOrg = useCallback2(
|
|
213
|
+
async (newOrgId) => {
|
|
214
|
+
setError(null);
|
|
215
|
+
try {
|
|
216
|
+
await client.switchOrg(newOrgId);
|
|
217
|
+
} catch (err) {
|
|
218
|
+
setError(err instanceof Error ? err.message : String(err));
|
|
219
|
+
}
|
|
220
|
+
},
|
|
221
|
+
[client]
|
|
222
|
+
);
|
|
223
|
+
const createOrg = useCallback2(
|
|
224
|
+
async (params) => {
|
|
225
|
+
setError(null);
|
|
226
|
+
try {
|
|
227
|
+
return await client.createOrg(params);
|
|
228
|
+
} catch (err) {
|
|
229
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
230
|
+
setError(msg);
|
|
231
|
+
throw err;
|
|
232
|
+
}
|
|
233
|
+
},
|
|
234
|
+
[client]
|
|
235
|
+
);
|
|
236
|
+
const leaveOrg = useCallback2(async () => {
|
|
237
|
+
if (!orgId) return;
|
|
238
|
+
setError(null);
|
|
239
|
+
try {
|
|
240
|
+
await client.leaveOrg(orgId);
|
|
241
|
+
} catch (err) {
|
|
242
|
+
setError(err instanceof Error ? err.message : String(err));
|
|
243
|
+
}
|
|
244
|
+
}, [client, orgId]);
|
|
245
|
+
const clearOrg = useCallback2(() => {
|
|
246
|
+
client.clearActiveOrg();
|
|
247
|
+
}, [client]);
|
|
248
|
+
const listOrgs = useCallback2(async () => {
|
|
249
|
+
try {
|
|
250
|
+
return await client.listOrgs();
|
|
251
|
+
} catch (err) {
|
|
252
|
+
setError(err instanceof Error ? err.message : String(err));
|
|
253
|
+
return [];
|
|
254
|
+
}
|
|
255
|
+
}, [client]);
|
|
256
|
+
return { org, role, orgId, switchOrg, createOrg, leaveOrg, clearOrg, listOrgs, error };
|
|
257
|
+
}
|
|
258
|
+
function useOrgMembers(orgId) {
|
|
259
|
+
const { client } = useOrgContext();
|
|
260
|
+
const [members, setMembers] = useState3([]);
|
|
261
|
+
const [isLoading, setIsLoading] = useState3(true);
|
|
262
|
+
const [error, setError] = useState3(null);
|
|
263
|
+
const refresh = useCallback2(async () => {
|
|
264
|
+
setIsLoading(true);
|
|
265
|
+
setError(null);
|
|
266
|
+
try {
|
|
267
|
+
const result = await client.listMembers(orgId);
|
|
268
|
+
setMembers(result);
|
|
269
|
+
} catch (err) {
|
|
270
|
+
setError(err instanceof Error ? err.message : String(err));
|
|
271
|
+
} finally {
|
|
272
|
+
setIsLoading(false);
|
|
273
|
+
}
|
|
274
|
+
}, [client, orgId]);
|
|
275
|
+
useEffect3(() => {
|
|
276
|
+
refresh();
|
|
277
|
+
}, [refresh]);
|
|
278
|
+
const invite = useCallback2(
|
|
279
|
+
async (email, role) => {
|
|
280
|
+
setError(null);
|
|
281
|
+
try {
|
|
282
|
+
const result = await client.inviteMember(orgId, { email, role });
|
|
283
|
+
return result;
|
|
284
|
+
} catch (err) {
|
|
285
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
286
|
+
setError(msg);
|
|
287
|
+
throw err;
|
|
288
|
+
}
|
|
289
|
+
},
|
|
290
|
+
[client, orgId]
|
|
291
|
+
);
|
|
292
|
+
const removeMember = useCallback2(
|
|
293
|
+
async (userId) => {
|
|
294
|
+
setError(null);
|
|
295
|
+
try {
|
|
296
|
+
await client.removeMember(orgId, userId);
|
|
297
|
+
await refresh();
|
|
298
|
+
} catch (err) {
|
|
299
|
+
setError(err instanceof Error ? err.message : String(err));
|
|
300
|
+
}
|
|
301
|
+
},
|
|
302
|
+
[client, orgId, refresh]
|
|
303
|
+
);
|
|
304
|
+
const updateRole = useCallback2(
|
|
305
|
+
async (userId, role) => {
|
|
306
|
+
setError(null);
|
|
307
|
+
try {
|
|
308
|
+
await client.updateMemberRole(orgId, userId, role);
|
|
309
|
+
await refresh();
|
|
310
|
+
} catch (err) {
|
|
311
|
+
setError(err instanceof Error ? err.message : String(err));
|
|
312
|
+
}
|
|
313
|
+
},
|
|
314
|
+
[client, orgId, refresh]
|
|
315
|
+
);
|
|
316
|
+
return { members, isLoading, refresh, invite, removeMember, updateRole, error };
|
|
317
|
+
}
|
|
318
|
+
function usePermission(requiredRole) {
|
|
319
|
+
const { client } = useOrgContext();
|
|
320
|
+
const snapshotRef = useRef2(checkPermission(client.activeRole, requiredRole));
|
|
321
|
+
const subscribe = useCallback2(
|
|
322
|
+
(onStoreChange) => {
|
|
323
|
+
return client.onOrgChange(() => {
|
|
324
|
+
const newValue = checkPermission(client.activeRole, requiredRole);
|
|
325
|
+
if (newValue !== snapshotRef.current) {
|
|
326
|
+
snapshotRef.current = newValue;
|
|
327
|
+
onStoreChange();
|
|
328
|
+
}
|
|
329
|
+
});
|
|
330
|
+
},
|
|
331
|
+
[client, requiredRole]
|
|
332
|
+
);
|
|
333
|
+
const getSnapshot = useCallback2(() => snapshotRef.current, []);
|
|
334
|
+
return useSyncExternalStore2(subscribe, getSnapshot);
|
|
335
|
+
}
|
|
336
|
+
var ROLE_LEVELS = {
|
|
337
|
+
viewer: 10,
|
|
338
|
+
billing: 15,
|
|
339
|
+
member: 20,
|
|
340
|
+
admin: 30,
|
|
341
|
+
owner: 40
|
|
342
|
+
};
|
|
343
|
+
function checkPermission(currentRole, requiredRole) {
|
|
344
|
+
if (!currentRole) return false;
|
|
345
|
+
const currentLevel = ROLE_LEVELS[currentRole] ?? 0;
|
|
346
|
+
const requiredLevel = ROLE_LEVELS[requiredRole] ?? 0;
|
|
347
|
+
return currentLevel >= requiredLevel;
|
|
348
|
+
}
|
|
168
349
|
export {
|
|
169
350
|
AuthContext,
|
|
170
351
|
AuthProvider,
|
|
352
|
+
OrgContext,
|
|
171
353
|
useAuth,
|
|
172
354
|
useAuthStatus,
|
|
173
|
-
useCurrentUser
|
|
355
|
+
useCurrentUser,
|
|
356
|
+
useOrg,
|
|
357
|
+
useOrgMembers,
|
|
358
|
+
usePermission
|
|
174
359
|
};
|
|
175
360
|
//# sourceMappingURL=react.js.map
|