├── tsup.dev.config.ts ├── examples └── vite │ ├── tsconfig.node.json │ ├── src │ ├── lib │ │ ├── utils.ts │ │ ├── api.ts │ │ └── auth.ts │ ├── components │ │ ├── user-info.tsx │ │ ├── ui.tsx │ │ └── auth-screen.tsx │ ├── mocks │ │ ├── db.ts │ │ └── api-server.ts │ └── App.tsx │ ├── vite.config.js │ ├── index.html │ ├── index.tsx │ ├── tsconfig.json │ ├── package.json │ └── public │ └── mockServiceWorker.js ├── tsup.config.ts ├── lefthook.yml ├── vitest.config.ts ├── .github └── workflows │ ├── publish.yaml │ └── pull-request.yaml ├── tsconfig.json ├── LICENSE ├── .vscode └── settings.json ├── biome.json ├── package.json ├── .gitignore ├── src ├── index.tsx └── index.test.tsx └── README.md /tsup.dev.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'tsup' 2 | 3 | export default defineConfig({ 4 | entry: ['src/index.tsx'], 5 | sourcemap: true, 6 | dts: true, 7 | minify: false, 8 | format: ['esm', 'cjs'], 9 | outDir: 'dist', 10 | }) 11 | -------------------------------------------------------------------------------- /examples/vite/tsconfig.node.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "composite": true, 4 | "module": "ESNext", 5 | "moduleResolution": "Node", 6 | "allowSyntheticDefaultImports": true 7 | }, 8 | "include": ["vite.config.ts"] 9 | } 10 | -------------------------------------------------------------------------------- /tsup.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'tsup' 2 | 3 | export default defineConfig({ 4 | entry: ['src/index.tsx'], 5 | sourcemap: true, 6 | clean: true, 7 | dts: true, 8 | minify: false, 9 | format: ['esm', 'cjs'], 10 | outDir: 'dist', 11 | }) 12 | -------------------------------------------------------------------------------- /lefthook.yml: -------------------------------------------------------------------------------- 1 | pre-commit: 2 | parallel: true 3 | commands: 4 | check: 5 | run: npm run check -- --staged --fix --no-errors-on-unmatched 6 | stage_fixed: true 7 | typecheck: 8 | run: npm run typecheck 9 | test: 10 | run: npm run test 11 | -------------------------------------------------------------------------------- /examples/vite/src/lib/utils.ts: -------------------------------------------------------------------------------- 1 | export const storage = { 2 | getToken: () => JSON.parse(window.localStorage.getItem('token') || 'null'), 3 | setToken: (token: string) => 4 | window.localStorage.setItem('token', JSON.stringify(token)), 5 | clearToken: () => window.localStorage.removeItem('token'), 6 | }; 7 | -------------------------------------------------------------------------------- /examples/vite/vite.config.js: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vite'; 2 | import ReactPlugin from 'vite-preset-react'; 3 | import path from 'path'; 4 | 5 | // https://vitejs.dev/config/ 6 | export default defineConfig({ 7 | plugins: [ 8 | ReactPlugin({ 9 | injectReact: false, 10 | }), 11 | ], 12 | resolve: { 13 | alias: { 14 | '@': path.resolve(__dirname, 'src'), 15 | }, 16 | }, 17 | }); 18 | -------------------------------------------------------------------------------- /examples/vite/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Playground 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import { defineConfig } from 'vitest/config' 3 | 4 | export default defineConfig({ 5 | test: { 6 | environment: 'jsdom', 7 | globals: true, 8 | 9 | coverage: { 10 | all: false, 11 | provider: 'v8', 12 | reporter: ['json-summary', 'html'], 13 | thresholds: { 14 | statements: 80, 15 | branches: 80, 16 | functions: 80, 17 | lines: 80, 18 | }, 19 | }, 20 | }, 21 | }) 22 | -------------------------------------------------------------------------------- /examples/vite/src/components/user-info.tsx: -------------------------------------------------------------------------------- 1 | 2 | 3 | import { useLogout, useUser } from '@/lib/auth'; 4 | 5 | import { Button } from './ui'; 6 | 7 | export const UserInfo = () => { 8 | const user = useUser({}); 9 | const logout = useLogout({}); 10 | 11 | return ( 12 | <> 13 |

Welcome {user.data?.name}

14 | 17 | 18 | ); 19 | }; 20 | -------------------------------------------------------------------------------- /examples/vite/index.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { createRoot } from 'react-dom/client'; 3 | 4 | import App from './src/App'; 5 | import { worker } from './src/mocks/api-server'; 6 | 7 | 8 | const root = document.getElementById('root'); 9 | 10 | if (!root) { 11 | throw new Error('Root element not found'); 12 | } 13 | 14 | worker.start().then(() => { 15 | createRoot(root).render( 16 | 17 | 18 | , 19 | ); 20 | }); -------------------------------------------------------------------------------- /.github/workflows/publish.yaml: -------------------------------------------------------------------------------- 1 | name: Publish Package to npmjs 2 | on: 3 | release: 4 | types: [published] 5 | jobs: 6 | npm-publish: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v4 10 | # Setup .npmrc file to publish to npm 11 | - uses: actions/setup-node@v4 12 | with: 13 | node-version: "20.x" 14 | registry-url: "https://registry.npmjs.org" 15 | - run: npm ci 16 | - run: npm publish 17 | env: 18 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 19 | -------------------------------------------------------------------------------- /examples/vite/src/mocks/db.ts: -------------------------------------------------------------------------------- 1 | export type DBUser = { 2 | email: string; 3 | name: string; 4 | password: string; 5 | }; 6 | 7 | const users: Record = JSON.parse( 8 | window.localStorage.getItem('db_users') || '{}' 9 | ); 10 | 11 | export function setUser(data: DBUser) { 12 | if (data?.email) { 13 | users[data.email] = data; 14 | window.localStorage.setItem('db_users', JSON.stringify(users)); 15 | return data; 16 | } else { 17 | return null; 18 | } 19 | } 20 | 21 | export function getUser(email: string | null) { 22 | if (email) { 23 | return users[email]; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /examples/vite/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": ["dom", "dom.iterable", "esnext"], 5 | "allowJs": true, 6 | "skipLibCheck": true, 7 | "strict": true, 8 | "forceConsistentCasingInFileNames": true, 9 | "noEmit": true, 10 | "esModuleInterop": true, 11 | "module": "esnext", 12 | "moduleResolution": "bundler", 13 | "resolveJsonModule": true, 14 | "isolatedModules": true, 15 | "jsx": "react-jsx", 16 | "incremental": true, 17 | "types": ["node", "vite/client"], 18 | "baseUrl": ".", 19 | "paths": { 20 | "@/*": ["./src/*"] 21 | } 22 | }, 23 | "include": ["src"], 24 | "exclude": ["node_modules"], 25 | "references": [{ "path": "./tsconfig.node.json" }] 26 | } 27 | -------------------------------------------------------------------------------- /examples/vite/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "@tanstack/react-query": "^5.62.3", 4 | "@tanstack/react-query-devtools": "^5.62.3", 5 | "cross-env": "^7.0.3", 6 | "msw": "^2.6.8", 7 | "react-app-polyfill": "^3.0.0", 8 | "react-query-auth": "*" 9 | }, 10 | "devDependencies": { 11 | "@types/node": "^22.10.1", 12 | "@types/react": "^19.0.1", 13 | "@types/react-dom": "^19.0.1", 14 | "react": "^19.0.0", 15 | "react-dom": "^19.0.0", 16 | "typescript": "^5", 17 | "vite": "latest", 18 | "vite-preset-react": "latest" 19 | }, 20 | "license": "MIT", 21 | "msw": { 22 | "workerDirectory": "public" 23 | }, 24 | "name": "example", 25 | "private": true, 26 | "scripts": { 27 | "build": "vite build", 28 | "dev": "vite", 29 | "start": "cross-env NODE_ENV=production vite --port=3000" 30 | }, 31 | "version": "1.0.0" 32 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ESNext" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, 4 | "moduleResolution": "Bundler", 5 | "module": "ESNext" /* Specify what module code is generated. */, 6 | "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, 7 | "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, 8 | "strict": true /* Enable all strict type-checking options. */, 9 | "skipLibCheck": true /* Skip type checking all .d.ts files. */, 10 | "types": ["vitest/globals"], 11 | "rootDir": ".", 12 | "outDir": "./dist", 13 | "noEmit": true, 14 | "jsx": "react-jsx" 15 | }, 16 | "include": ["src/**/*", "tests/**/*"], 17 | "exclude": ["node_modules", "dist"] 18 | } 19 | -------------------------------------------------------------------------------- /examples/vite/src/App.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; 3 | import { ReactQueryDevtools } from '@tanstack/react-query-devtools'; 4 | import { AuthScreen } from '@/components/auth-screen'; 5 | import { UserInfo } from '@/components/user-info'; 6 | import { AuthLoader } from '@/lib/auth'; 7 | import { Container } from '@/components/ui'; 8 | 9 | const SampleApp = () => { 10 | const [queryClient] = React.useState(() => new QueryClient()); 11 | 12 | return ( 13 | 14 | 15 | 16 |
Loading ...
} 18 | renderUnauthenticated={() => } 19 | > 20 | 21 |
22 |
23 |
24 | ); 25 | }; 26 | 27 | export default SampleApp; 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Alan Alickovic 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "biome.enabled": true, 3 | "editor.defaultFormatter": "biomejs.biome", 4 | "editor.formatOnSave": true, 5 | "javascript.format.enable": false, 6 | "javascript.suggest.autoImports": true, 7 | "javascript.suggest.paths": true, 8 | "typescript.format.enable": false, 9 | "typescript.suggest.paths": true, 10 | "typescript.suggest.autoImports": true, 11 | "editor.renderWhitespace": "all", 12 | "editor.rulers": [120, 160], 13 | "editor.codeActionsOnSave": { 14 | "source.fixAll": "always", 15 | "source.organizeImports": "never", 16 | "source.organizeImports.biome": "always", 17 | "quickfix.biome": "always" 18 | }, 19 | "editor.insertSpaces": false, 20 | "editor.detectIndentation": true, 21 | "editor.trimAutoWhitespace": true, 22 | "files.trimTrailingWhitespace": true, 23 | "files.trimTrailingWhitespaceInRegexAndStrings": true, 24 | "files.trimFinalNewlines": true, 25 | "explorer.fileNesting.patterns": { 26 | "*.ts": "${basename}.*.${extname}", 27 | ".env": ".env.*", 28 | "*.tsx": "${basename}.*.${extname},${basename}.*.ts", 29 | "package.json": "*.json, *.yml, *.config.js, *.config.ts, *.yaml" 30 | }, 31 | "eslint.enable": false, 32 | "eslint.format.enable": false, 33 | "prettier.enable": false 34 | } 35 | -------------------------------------------------------------------------------- /examples/vite/src/lib/api.ts: -------------------------------------------------------------------------------- 1 | import { storage } from "./utils" 2 | 3 | export interface AuthResponse { 4 | user: User 5 | jwt: string 6 | } 7 | 8 | export interface User { 9 | id: string 10 | email: string 11 | name?: string 12 | } 13 | 14 | export async function handleApiResponse(response: Response) { 15 | const data = await response.json() 16 | 17 | if (response.ok) { 18 | return data 19 | } 20 | 21 | return Promise.reject(data) 22 | } 23 | 24 | export function getUserProfile(): Promise<{ user: User | undefined }> { 25 | return fetch("/auth/me", { 26 | headers: { 27 | Authorization: storage.getToken(), 28 | }, 29 | }).then(handleApiResponse) 30 | } 31 | 32 | export function loginWithEmailAndPassword(data: unknown): Promise { 33 | return fetch("/auth/login", { 34 | method: "POST", 35 | body: JSON.stringify(data), 36 | }).then(handleApiResponse) 37 | } 38 | 39 | export function registerWithEmailAndPassword(data: unknown): Promise { 40 | return fetch("/auth/register", { 41 | method: "POST", 42 | body: JSON.stringify(data), 43 | }).then(handleApiResponse) 44 | } 45 | 46 | export function logout(): Promise<{ message: string }> { 47 | return fetch("/auth/logout", { method: "POST" }).then(handleApiResponse) 48 | } 49 | -------------------------------------------------------------------------------- /examples/vite/src/lib/auth.ts: -------------------------------------------------------------------------------- 1 | import { configureAuth } from "react-query-auth" 2 | import { 3 | type AuthResponse, 4 | getUserProfile, 5 | loginWithEmailAndPassword, 6 | logout, 7 | registerWithEmailAndPassword, 8 | } from "./api" 9 | import { storage } from "./utils" 10 | 11 | export type LoginCredentials = { 12 | email: string 13 | password: string 14 | } 15 | 16 | export type RegisterCredentials = { 17 | email: string 18 | name: string 19 | password: string 20 | } 21 | 22 | async function handleUserResponse(data: AuthResponse) { 23 | const { jwt, user } = data 24 | storage.setToken(jwt) 25 | return user 26 | } 27 | 28 | async function userFn() { 29 | const { user } = await getUserProfile() 30 | return user ?? null 31 | } 32 | 33 | async function loginFn(data: LoginCredentials) { 34 | const response = await loginWithEmailAndPassword(data) 35 | const user = await handleUserResponse(response) 36 | return user 37 | } 38 | 39 | async function registerFn(data: RegisterCredentials) { 40 | const response = await registerWithEmailAndPassword(data) 41 | const user = await handleUserResponse(response) 42 | return user 43 | } 44 | 45 | async function logoutFn() { 46 | await logout() 47 | } 48 | 49 | export const { useUser, useLogin, useRegister, useLogout, AuthLoader } = configureAuth({ 50 | userFn, 51 | loginFn, 52 | registerFn, 53 | logoutFn, 54 | }) 55 | -------------------------------------------------------------------------------- /biome.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@biomejs/biome/configuration_schema.json", 3 | "formatter": { 4 | "enabled": true, 5 | "formatWithErrors": false, 6 | "ignore": ["examples"], 7 | "indentStyle": "tab", 8 | "lineEnding": "lf", 9 | "lineWidth": 120 10 | }, 11 | "javascript": { 12 | "formatter": { 13 | "indentStyle": "tab", 14 | "quoteStyle": "single", 15 | "semicolons": "asNeeded", 16 | "trailingCommas": "es5" 17 | } 18 | }, 19 | "linter": { 20 | "enabled": true, 21 | "ignore": ["examples", "package.json"], 22 | "rules": { 23 | "a11y": { 24 | "recommended": true 25 | }, 26 | "complexity": { 27 | "recommended": true 28 | }, 29 | "correctness": { 30 | "noUnusedFunctionParameters": "error", 31 | "noUnusedImports": "error", 32 | "noUnusedLabels": "error", 33 | "noUnusedVariables": "error", 34 | "recommended": true 35 | }, 36 | "nursery": { 37 | "recommended": true 38 | }, 39 | "performance": { 40 | "recommended": true 41 | }, 42 | "recommended": true, 43 | "security": { 44 | "recommended": true 45 | }, 46 | "style": { 47 | "recommended": true 48 | }, 49 | "suspicious": { 50 | "noConsole": "error", 51 | "recommended": true 52 | } 53 | } 54 | }, 55 | "organizeImports": { 56 | "enabled": true, 57 | "ignore": ["examples", "package.json"] 58 | }, 59 | "vcs": { 60 | "clientKind": "git", 61 | "defaultBranch": "main", 62 | "enabled": true, 63 | "useIgnoreFile": true 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /examples/vite/src/mocks/api-server.ts: -------------------------------------------------------------------------------- 1 | import { http, HttpResponse, delay } from 'msw' 2 | import { setupWorker } from 'msw/browser' 3 | import { storage } from '@/lib/utils' 4 | import { DBUser, getUser, setUser } from './db' 5 | 6 | const handlers = [ 7 | http.get('/auth/me', async ({ request }) => { 8 | const user = getUser(request.headers.get('Authorization')) 9 | 10 | await delay(1000); 11 | 12 | return HttpResponse.json({ user }) 13 | }), 14 | 15 | http.post('/auth/login', async ({ request }) => { 16 | const parsedBody = (await request.json()) as DBUser 17 | const user = getUser(parsedBody.email) 18 | 19 | await delay(1000); 20 | 21 | if (user && user.password === parsedBody.password) { 22 | return HttpResponse.json({ 23 | jwt: user.email, 24 | user, 25 | }) 26 | } 27 | 28 | return HttpResponse.json( 29 | { message: 'Unauthorized' }, 30 | { status: 401 } 31 | ) 32 | }), 33 | 34 | http.post('/auth/register', async ({ request }) => { 35 | const parsedBody = (await request.json()) as DBUser 36 | const user = getUser(parsedBody?.email) 37 | 38 | await delay(1000); 39 | 40 | if (!user && parsedBody) { 41 | const newUser = setUser(parsedBody) 42 | if (newUser) { 43 | return HttpResponse.json({ 44 | jwt: newUser.email, 45 | user: getUser(newUser.email), 46 | }) 47 | } 48 | 49 | return HttpResponse.json( 50 | { message: 'Registration failed!' }, 51 | { status: 403 } 52 | ) 53 | } 54 | 55 | return HttpResponse.json( 56 | { message: 'The user already exists!' }, 57 | { status: 400 } 58 | ) 59 | }), 60 | 61 | http.post('/auth/logout', async () => { 62 | storage.clearToken() 63 | 64 | await delay(1000); 65 | 66 | return HttpResponse.json({ message: 'Logged out' }) 67 | }), 68 | ] 69 | 70 | export const worker = setupWorker(...handlers) 71 | -------------------------------------------------------------------------------- /examples/vite/src/components/ui.tsx: -------------------------------------------------------------------------------- 1 | import type * as React from "react" 2 | 3 | export const Button = (props: React.ButtonHTMLAttributes) => { 4 | return ( 5 | 16 | 17 | )} 18 | {mode === "register" && ( 19 | <> 20 | 21 | 22 | 23 | )} 24 | 25 | ) 26 | } 27 | 28 | const useForm = >(initialValues?: V) => { 29 | const [values, setValues] = React.useState(initialValues || {}) 30 | 31 | const onChange = (e: React.ChangeEvent) => { 32 | setValues((v) => ({ ...v, [e.target.name]: e.target.value })) 33 | } 34 | 35 | return { 36 | values: values as V, 37 | onChange, 38 | } 39 | } 40 | 41 | const RegisterForm = () => { 42 | const register = useRegister() 43 | const { values, onChange } = useForm() 44 | 45 | return ( 46 |
{ 49 | e.preventDefault() 50 | register.mutate(values, { 51 | onSuccess: () => console.log("registered"), 52 | }) 53 | }} 54 | error={register.error} 55 | > 56 | 57 | 58 | 59 | 62 |
63 | ) 64 | } 65 | 66 | const LoginForm = () => { 67 | const login = useLogin() 68 | const { values, onChange } = useForm() 69 | 70 | return ( 71 |
{ 74 | e.preventDefault() 75 | login.mutate(values) 76 | }} 77 | error={login.error} 78 | > 79 | 80 | 81 | 84 |
85 | ) 86 | } 87 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | .pnpm-debug.log* 9 | 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | *.lcov 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # Snowpack dependency directory (https://snowpack.dev/) 46 | web_modules/ 47 | 48 | # TypeScript cache 49 | *.tsbuildinfo 50 | 51 | # Optional npm cache directory 52 | .npm 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Optional stylelint cache 58 | .stylelintcache 59 | 60 | # Microbundle cache 61 | .rpt2_cache/ 62 | .rts2_cache_cjs/ 63 | .rts2_cache_es/ 64 | .rts2_cache_umd/ 65 | 66 | # Optional REPL history 67 | .node_repl_history 68 | 69 | # Output of 'npm pack' 70 | *.tgz 71 | 72 | # Yarn Integrity file 73 | .yarn-integrity 74 | 75 | # dotenv environment variable files 76 | .env 77 | .env.development.local 78 | .env.test.local 79 | .env.production.local 80 | .env.local 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | .parcel-cache 85 | 86 | # Next.js build output 87 | .next 88 | out 89 | 90 | # Nuxt.js build / generate output 91 | .nuxt 92 | dist 93 | 94 | # Gatsby files 95 | .cache/ 96 | # Comment in the public line in if your project uses Gatsby and not Next.js 97 | # https://nextjs.org/blog/next-9-1#public-directory-support 98 | # public 99 | 100 | # vuepress build output 101 | .vuepress/dist 102 | 103 | # vuepress v2.x temp and cache directory 104 | .temp 105 | .cache 106 | 107 | # Docusaurus cache and generated files 108 | .docusaurus 109 | 110 | # Serverless directories 111 | .serverless/ 112 | 113 | # FuseBox cache 114 | .fusebox/ 115 | 116 | # DynamoDB Local files 117 | .dynamodb/ 118 | 119 | # TernJS port file 120 | .tern-port 121 | 122 | # Stores VSCode versions used for testing VSCode extensions 123 | .vscode-test 124 | 125 | # yarn v2 126 | .yarn/cache 127 | .yarn/unplugged 128 | .yarn/build-state.yml 129 | .yarn/install-state.gz 130 | .pnp.* 131 | /dist 132 | .history -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import { 2 | type MutationFunction, 3 | type QueryFunction, 4 | type QueryKey, 5 | type UseMutationOptions, 6 | type UseQueryOptions, 7 | useMutation, 8 | useQuery, 9 | useQueryClient, 10 | } from '@tanstack/react-query' 11 | import React from 'react' 12 | 13 | export interface ReactQueryAuthConfig { 14 | userFn: QueryFunction 15 | loginFn: MutationFunction 16 | registerFn: MutationFunction 17 | logoutFn: MutationFunction 18 | userKey?: QueryKey 19 | } 20 | 21 | export interface AuthProviderProps { 22 | children: React.ReactNode 23 | } 24 | 25 | export function configureAuth( 26 | config: ReactQueryAuthConfig 27 | ) { 28 | const { userFn, userKey = ['authenticated-user'], loginFn, registerFn, logoutFn } = config 29 | 30 | const useUser = (options?: Omit, 'queryKey' | 'queryFn'>) => 31 | useQuery({ 32 | queryKey: userKey, 33 | queryFn: userFn, 34 | ...options, 35 | }) 36 | 37 | const useLogin = (options?: Omit, 'mutationFn'>) => { 38 | const queryClient = useQueryClient() 39 | 40 | const setUser = React.useCallback((data: User) => queryClient.setQueryData(userKey, data), [queryClient]) 41 | 42 | return useMutation({ 43 | mutationFn: loginFn, 44 | ...options, 45 | onSuccess: (user, ...rest) => { 46 | setUser(user) 47 | options?.onSuccess?.(user, ...rest) 48 | }, 49 | }) 50 | } 51 | 52 | const useRegister = (options?: Omit, 'mutationFn'>) => { 53 | const queryClient = useQueryClient() 54 | 55 | const setUser = React.useCallback((data: User) => queryClient.setQueryData(userKey, data), [queryClient]) 56 | 57 | return useMutation({ 58 | mutationFn: registerFn, 59 | ...options, 60 | onSuccess: (user, ...rest) => { 61 | setUser(user) 62 | options?.onSuccess?.(user, ...rest) 63 | }, 64 | }) 65 | } 66 | 67 | const useLogout = (options?: UseMutationOptions) => { 68 | const queryClient = useQueryClient() 69 | 70 | const setUser = React.useCallback((data: User | null) => queryClient.setQueryData(userKey, data), [queryClient]) 71 | 72 | return useMutation({ 73 | mutationFn: logoutFn, 74 | ...options, 75 | onSuccess: (...args) => { 76 | setUser(null) 77 | options?.onSuccess?.(...args) 78 | }, 79 | }) 80 | } 81 | 82 | function AuthLoader({ 83 | children, 84 | renderLoading, 85 | renderUnauthenticated, 86 | renderError = (error: Error) => <>{JSON.stringify(error)}, 87 | }: { 88 | children: React.ReactNode 89 | renderLoading: () => JSX.Element 90 | renderUnauthenticated?: () => JSX.Element 91 | renderError?: (error: Error) => JSX.Element 92 | }) { 93 | const { isSuccess, isFetched, status, data, error } = useUser() 94 | 95 | if (isSuccess) { 96 | if (renderUnauthenticated && !data) { 97 | return renderUnauthenticated() 98 | } 99 | return <>{children} 100 | } 101 | 102 | if (!isFetched) { 103 | return renderLoading() 104 | } 105 | 106 | if (status === 'error') { 107 | return renderError(error) 108 | } 109 | 110 | return null 111 | } 112 | 113 | return { 114 | useUser, 115 | useLogin, 116 | useRegister, 117 | useLogout, 118 | AuthLoader, 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/index.test.tsx: -------------------------------------------------------------------------------- 1 | import { act, render, renderHook, screen, waitFor } from '@testing-library/react' 2 | import type { ReactNode } from 'react' 3 | import { configureAuth } from './index' 4 | 5 | import '@testing-library/jest-dom' 6 | import { QueryClient, QueryClientProvider } from '@tanstack/react-query' 7 | import { beforeEach, describe, expect, it, vi } from 'vitest' 8 | 9 | const renderApp = (children: ReactNode) => { 10 | const client = new QueryClient() 11 | return render({children}) 12 | } 13 | 14 | const renderAppHook = (hook: () => Result) => { 15 | const client = new QueryClient() 16 | return renderHook(hook, { 17 | wrapper: ({ children }) => {children}, 18 | }) 19 | } 20 | 21 | beforeEach(() => { 22 | vi.resetAllMocks() 23 | }) 24 | 25 | const user = { 26 | id: '1', 27 | name: 'Test User', 28 | email: 'user@mail.com', 29 | } 30 | 31 | const config = { 32 | userFn: vi.fn(), 33 | loginFn: vi.fn(), 34 | logoutFn: vi.fn(), 35 | registerFn: vi.fn(), 36 | } 37 | 38 | const { AuthLoader, useUser, useLogin, useRegister, useLogout } = configureAuth(config) 39 | 40 | describe('useUser', () => { 41 | it('returns the authenticated user', async () => { 42 | config.userFn.mockResolvedValue(user) 43 | 44 | const { result } = renderAppHook(() => useUser()) 45 | 46 | await waitFor(() => expect(result.current.data).toEqual(user)) 47 | 48 | expect(config.userFn).toHaveBeenCalled() 49 | }) 50 | }) 51 | 52 | describe('useRegister', () => { 53 | it('calls the register function and sets the authenticated user on success', async () => { 54 | config.registerFn.mockResolvedValue(user) 55 | 56 | const registerCredentials = { 57 | name: 'Test User 2', 58 | email: 'user2@mail.com', 59 | password: 'password', 60 | } 61 | 62 | const { result } = renderAppHook(() => useRegister()) 63 | 64 | act(() => { 65 | result.current.mutate(registerCredentials) 66 | }) 67 | 68 | await waitFor(() => expect(config.registerFn).toHaveBeenCalledWith(registerCredentials)) 69 | expect(result.current.data).toEqual(user) 70 | }) 71 | }) 72 | 73 | describe('useLogin', () => { 74 | it('calls the login function and sets the authenticated user on success', async () => { 75 | config.loginFn.mockResolvedValue(user) 76 | 77 | const loginCredentials = { 78 | email: 'user@mail.com', 79 | password: 'password', 80 | } 81 | 82 | const { result } = renderAppHook(() => useLogin()) 83 | 84 | act(() => { 85 | result.current.mutate(loginCredentials) 86 | }) 87 | 88 | await waitFor(() => expect(config.loginFn).toHaveBeenCalledWith(loginCredentials)) 89 | expect(result.current.data).toEqual(user) 90 | }) 91 | }) 92 | 93 | describe('useLogout', () => { 94 | it('calls the logout function and removes the authenticated user on success', async () => { 95 | config.logoutFn.mockResolvedValue(true) 96 | 97 | const { result } = renderAppHook(() => useLogout()) 98 | 99 | act(() => { 100 | result.current.mutate({}) 101 | }) 102 | 103 | await waitFor(() => expect(config.logoutFn).toHaveBeenCalled()) 104 | expect(result.current.data).toEqual(true) 105 | }) 106 | }) 107 | 108 | describe('AuthLoader', () => { 109 | it('renders loading component when not yet fetched', () => { 110 | config.userFn.mockResolvedValue(null) 111 | renderApp( 112 |
Loading...
} renderUnauthenticated={() =>
Unauthenticated
}> 113 | Hello {user.name}! 114 |
115 | ) 116 | 117 | expect(screen.getByText('Loading...')).toBeInTheDocument() 118 | }) 119 | 120 | it('renders unauthenticated component when authenticated user is null', async () => { 121 | config.userFn.mockResolvedValue(null) 122 | renderApp( 123 |
Loading...
} renderUnauthenticated={() =>
Unauthenticated
}> 124 | Hello {user.name}! 125 |
126 | ) 127 | 128 | await waitFor(() => expect(screen.getByText('Unauthenticated')).toBeInTheDocument()) 129 | }) 130 | 131 | it('renders children when authenticated user is not null', async () => { 132 | const content = `Hello ${user.name}!` 133 | 134 | config.userFn.mockResolvedValue(user) 135 | 136 | renderApp(
Loading...
}>{content}
) 137 | 138 | await waitFor(() => expect(screen.getByText(content)).toBeInTheDocument()) 139 | }) 140 | }) 141 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # react-query-auth 2 | 3 | [![NPM](https://img.shields.io/npm/v/react-query-auth.svg)](https://www.npmjs.com/package/react-query-auth) 4 | 5 | Authenticate your react applications easily with [React Query](https://tanstack.com/query/v4/docs/react). 6 | 7 | ## Introduction 8 | 9 | Using React Query has allowed us to significantly reduce the size of our codebase by caching server state. However, we still need to consider where to store user data, which is a type of global application state that we need to access from many parts of the app, but is also a server state since it is obtained from a server. This library makes it easy to manage user authentication, and can be adapted to work with any API or authentication method. 10 | 11 | ## Installation 12 | 13 | ``` 14 | $ npm install @tanstack/react-query react-query-auth 15 | ``` 16 | 17 | Or if you use Yarn: 18 | 19 | ``` 20 | $ yarn add @tanstack/react-query react-query-auth 21 | ``` 22 | 23 | ## Usage 24 | 25 | To use this library, you will need to provide it with functions for fetching the current user, logging in, registering, and logging out. You can do this using the `configureAuth` function: 26 | 27 | ```ts 28 | import { configureAuth } from 'react-query-auth'; 29 | 30 | const { useUser, useLogin, useRegister, useLogout } = configureAuth({ 31 | userFn: () => api.get('/me'), 32 | loginFn: (credentials) => api.post('/login', credentials), 33 | registerFn: (credentials) => api.post('/register', credentials), 34 | logoutFn: () => api.post('/logout'), 35 | }); 36 | ``` 37 | 38 | With these hooks, you can then add authentication functionality to your app. For example, you could use the `useUser` hook to access the authenticated user in a component. 39 | 40 | You can also use the `useLogin`, `useRegister`, and `useLogout` hooks to allow users to authenticate and log out. 41 | 42 | ```tsx 43 | function UserInfo() { 44 | const user = useUser(); 45 | const logout = useLogout(); 46 | 47 | if (user.isLoading) { 48 | return
Loading ...
; 49 | } 50 | 51 | if (user.error) { 52 | return
{JSON.stringify(user.error, null, 2)}
; 53 | } 54 | 55 | if (!user.data) { 56 | return
Not logged in
; 57 | } 58 | 59 | return ( 60 |
61 |
Logged in as {user.data.email}
62 | 65 |
66 | ); 67 | } 68 | ``` 69 | 70 | The library also provides the `AuthLoader` component that can be used to handle loading states when fetching the authenticated user. You can use it like this: 71 | 72 | ```tsx 73 | function MyApp() { 74 | return ( 75 |
Loading ...
} 77 | renderUnauthenticated={() => } 78 | > 79 | 80 |
81 | ); 82 | } 83 | ``` 84 | 85 | **NOTE: All hooks and components must be used within `QueryClientProvider`.** 86 | 87 | ## API Reference: 88 | 89 | ### `configureAuth`: 90 | 91 | The `configureAuth` function takes in a configuration object and returns a set of custom hooks for handling authentication. 92 | 93 | #### The `configureAuth` configuration object: 94 | 95 | A configuration object that specifies the functions and keys to be used for various authentication actions. It accepts the following properties: 96 | 97 | - **`userFn`:** 98 | A function that is used to retrieve the authenticated user. It should return a Promise that resolves to the user object, or null if the user is not authenticated. 99 | 100 | - **`loginFn`:** 101 | A function that is used to log the user in. It should accept login credentials as its argument and return a Promise that resolves to the user object. 102 | 103 | - **`registerFn`:** 104 | A function that is used to register a new user. It should accept registration credentials as its argument and return a Promise that resolves to the new user object. 105 | 106 | - **`logoutFn`:** 107 | A function that is used to log the user out. It should return a Promise that resolves when the logout action is complete. 108 | 109 | - **`userKey`:** 110 | An optional key that is used to store the authenticated user in the react-query cache. The default value is `['authenticated-user']`. 111 | 112 | #### The `configureAuth` returned object: 113 | 114 | `configureAuth` returns an object with the following properties: 115 | 116 | - **`useUser`:** 117 | A custom hook that retrieves the authenticated user. It is a wrapper around [useQuery](https://tanstack.com/query/v4/docs/react/reference/useQuery) that uses the `userFn` and `userKey` specified in the `configAuth` configuration. The hook accepts the same options as [useQuery](https://tanstack.com/query/v4/docs/react/reference/useQuery), except for `queryKey` and `queryFn`, which are predefined by the configuration. 118 | 119 | - **`useLogin`:** 120 | A custom hook that logs the user in. It is a wrapper around [useMutation](https://tanstack.com/query/v4/docs/react/reference/useMutation) that uses the `loginFn` specified in the configuration. The hook accepts the same options as [useMutation](https://tanstack.com/query/v4/docs/react/reference/useMutation), except for `mutationFn`, which is set by the configuration. On success, the hook updates the authenticated user in the React Query cache using the `userKey` specified in the configuration. 121 | 122 | - **`useRegister`:** 123 | A custom hook that registers a new user. It is a wrapper around [useMutation](https://tanstack.com/query/v4/docs/react/reference/useMutation) that uses the `registerFn` specified in the configuration. The hook accepts the same options as [useMutation](https://tanstack.com/query/v4/docs/react/reference/useMutation), except for `mutationFn`, which is set by the configuration. On success, the hook updates the authenticated user in the React Query cache using the `userKey` specified in the configuration. 124 | 125 | - **`useLogout`:** 126 | A custom hook that logs the user out. It is a wrapper around [useMutation](https://tanstack.com/query/v4/docs/react/reference/useMutation) that uses the `logoutFn` specified in the configuration. The hook accepts the same options as [useMutation](https://tanstack.com/query/v4/docs/react/reference/useMutation), except for `mutationFn`, which is set by the configuration. On success, the hook removes the authenticated user from the React Query cache using the `userKey` specified in the configuration. 127 | 128 | - **`AuthLoader`:** 129 | 130 | A component that can be used to handle loading states when fetching the authenticated user. It accepts the following props: 131 | 132 | - **`renderLoading`**: 133 | A function that is called when the authenticated user is being fetched. It should return a React node that is rendered while the user is being fetched. 134 | 135 | - **`renderUnauthenticated`**: 136 | A function that is called when the authenticated user is not authenticated. It should return a React node that is rendered when the user is not authenticated. 137 | 138 | - **`renderError`**: 139 | A function that is called when an error is thrown during the authentication request. It should return a React node that is rendered when the error occurs. It receives the `Error` object which can be used during rendering. Defaults to `(error: Error) => <>{JSON.stringify(error)}`. 140 | 141 | - **`children`**: 142 | A React node that is rendered when the authenticated user is successfully fetched. 143 | 144 | If you need a more custom loading implementation, you can create your own `AuthLoader` component and use the `useUser` hook to fetch the authenticated user and handle the loading and error states yourself. 145 | 146 | 147 | If none of the provided hooks or components meet your needs, feel free to copy the source code into your project and modify it to your liking. 148 | 149 | ## Examples: 150 | 151 | To try out the library, check out the `examples` folder. 152 | 153 | ## Contributing 154 | 155 | 1. Clone this repo 156 | 2. Create a branch: `git checkout -b your-feature` 157 | 3. Make some changes 158 | 4. Test your changes 159 | 5. Push your branch and open a Pull Request 160 | 161 | ## LICENSE 162 | 163 | [MIT](/LICENSE) 164 | -------------------------------------------------------------------------------- /examples/vite/public/mockServiceWorker.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | /* tslint:disable */ 3 | 4 | /** 5 | * Mock Service Worker. 6 | * @see https://github.com/mswjs/msw 7 | * - Please do NOT modify this file. 8 | * - Please do NOT serve this file on production. 9 | */ 10 | 11 | const PACKAGE_VERSION = '2.6.8' 12 | const INTEGRITY_CHECKSUM = '00729d72e3b82faf54ca8b9621dbb96f' 13 | const IS_MOCKED_RESPONSE = Symbol('isMockedResponse') 14 | const activeClientIds = new Set() 15 | 16 | self.addEventListener('install', function () { 17 | self.skipWaiting() 18 | }) 19 | 20 | self.addEventListener('activate', function (event) { 21 | event.waitUntil(self.clients.claim()) 22 | }) 23 | 24 | self.addEventListener('message', async function (event) { 25 | const clientId = event.source.id 26 | 27 | if (!clientId || !self.clients) { 28 | return 29 | } 30 | 31 | const client = await self.clients.get(clientId) 32 | 33 | if (!client) { 34 | return 35 | } 36 | 37 | const allClients = await self.clients.matchAll({ 38 | type: 'window', 39 | }) 40 | 41 | switch (event.data) { 42 | case 'KEEPALIVE_REQUEST': { 43 | sendToClient(client, { 44 | type: 'KEEPALIVE_RESPONSE', 45 | }) 46 | break 47 | } 48 | 49 | case 'INTEGRITY_CHECK_REQUEST': { 50 | sendToClient(client, { 51 | type: 'INTEGRITY_CHECK_RESPONSE', 52 | payload: { 53 | packageVersion: PACKAGE_VERSION, 54 | checksum: INTEGRITY_CHECKSUM, 55 | }, 56 | }) 57 | break 58 | } 59 | 60 | case 'MOCK_ACTIVATE': { 61 | activeClientIds.add(clientId) 62 | 63 | sendToClient(client, { 64 | type: 'MOCKING_ENABLED', 65 | payload: { 66 | client: { 67 | id: client.id, 68 | frameType: client.frameType, 69 | }, 70 | }, 71 | }) 72 | break 73 | } 74 | 75 | case 'MOCK_DEACTIVATE': { 76 | activeClientIds.delete(clientId) 77 | break 78 | } 79 | 80 | case 'CLIENT_CLOSED': { 81 | activeClientIds.delete(clientId) 82 | 83 | const remainingClients = allClients.filter((client) => { 84 | return client.id !== clientId 85 | }) 86 | 87 | // Unregister itself when there are no more clients 88 | if (remainingClients.length === 0) { 89 | self.registration.unregister() 90 | } 91 | 92 | break 93 | } 94 | } 95 | }) 96 | 97 | self.addEventListener('fetch', function (event) { 98 | const { request } = event 99 | 100 | // Bypass navigation requests. 101 | if (request.mode === 'navigate') { 102 | return 103 | } 104 | 105 | // Opening the DevTools triggers the "only-if-cached" request 106 | // that cannot be handled by the worker. Bypass such requests. 107 | if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { 108 | return 109 | } 110 | 111 | // Bypass all requests when there are no active clients. 112 | // Prevents the self-unregistered worked from handling requests 113 | // after it's been deleted (still remains active until the next reload). 114 | if (activeClientIds.size === 0) { 115 | return 116 | } 117 | 118 | // Generate unique request ID. 119 | const requestId = crypto.randomUUID() 120 | event.respondWith(handleRequest(event, requestId)) 121 | }) 122 | 123 | async function handleRequest(event, requestId) { 124 | const client = await resolveMainClient(event) 125 | const response = await getResponse(event, client, requestId) 126 | 127 | // Send back the response clone for the "response:*" life-cycle events. 128 | // Ensure MSW is active and ready to handle the message, otherwise 129 | // this message will pend indefinitely. 130 | if (client && activeClientIds.has(client.id)) { 131 | ;(async function () { 132 | const responseClone = response.clone() 133 | 134 | sendToClient( 135 | client, 136 | { 137 | type: 'RESPONSE', 138 | payload: { 139 | requestId, 140 | isMockedResponse: IS_MOCKED_RESPONSE in response, 141 | type: responseClone.type, 142 | status: responseClone.status, 143 | statusText: responseClone.statusText, 144 | body: responseClone.body, 145 | headers: Object.fromEntries(responseClone.headers.entries()), 146 | }, 147 | }, 148 | [responseClone.body], 149 | ) 150 | })() 151 | } 152 | 153 | return response 154 | } 155 | 156 | // Resolve the main client for the given event. 157 | // Client that issues a request doesn't necessarily equal the client 158 | // that registered the worker. It's with the latter the worker should 159 | // communicate with during the response resolving phase. 160 | async function resolveMainClient(event) { 161 | const client = await self.clients.get(event.clientId) 162 | 163 | if (activeClientIds.has(event.clientId)) { 164 | return client 165 | } 166 | 167 | if (client?.frameType === 'top-level') { 168 | return client 169 | } 170 | 171 | const allClients = await self.clients.matchAll({ 172 | type: 'window', 173 | }) 174 | 175 | return allClients 176 | .filter((client) => { 177 | // Get only those clients that are currently visible. 178 | return client.visibilityState === 'visible' 179 | }) 180 | .find((client) => { 181 | // Find the client ID that's recorded in the 182 | // set of clients that have registered the worker. 183 | return activeClientIds.has(client.id) 184 | }) 185 | } 186 | 187 | async function getResponse(event, client, requestId) { 188 | const { request } = event 189 | 190 | // Clone the request because it might've been already used 191 | // (i.e. its body has been read and sent to the client). 192 | const requestClone = request.clone() 193 | 194 | function passthrough() { 195 | // Cast the request headers to a new Headers instance 196 | // so the headers can be manipulated with. 197 | const headers = new Headers(requestClone.headers) 198 | 199 | // Remove the "accept" header value that marked this request as passthrough. 200 | // This prevents request alteration and also keeps it compliant with the 201 | // user-defined CORS policies. 202 | const acceptHeader = headers.get('accept') 203 | if (acceptHeader) { 204 | const values = acceptHeader.split(',').map((value) => value.trim()) 205 | const filteredValues = values.filter( 206 | (value) => value !== 'msw/passthrough', 207 | ) 208 | 209 | if (filteredValues.length > 0) { 210 | headers.set('accept', filteredValues.join(', ')) 211 | } else { 212 | headers.delete('accept') 213 | } 214 | } 215 | 216 | return fetch(requestClone, { headers }) 217 | } 218 | 219 | // Bypass mocking when the client is not active. 220 | if (!client) { 221 | return passthrough() 222 | } 223 | 224 | // Bypass initial page load requests (i.e. static assets). 225 | // The absence of the immediate/parent client in the map of the active clients 226 | // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet 227 | // and is not ready to handle requests. 228 | if (!activeClientIds.has(client.id)) { 229 | return passthrough() 230 | } 231 | 232 | // Notify the client that a request has been intercepted. 233 | const requestBuffer = await request.arrayBuffer() 234 | const clientMessage = await sendToClient( 235 | client, 236 | { 237 | type: 'REQUEST', 238 | payload: { 239 | id: requestId, 240 | url: request.url, 241 | mode: request.mode, 242 | method: request.method, 243 | headers: Object.fromEntries(request.headers.entries()), 244 | cache: request.cache, 245 | credentials: request.credentials, 246 | destination: request.destination, 247 | integrity: request.integrity, 248 | redirect: request.redirect, 249 | referrer: request.referrer, 250 | referrerPolicy: request.referrerPolicy, 251 | body: requestBuffer, 252 | keepalive: request.keepalive, 253 | }, 254 | }, 255 | [requestBuffer], 256 | ) 257 | 258 | switch (clientMessage.type) { 259 | case 'MOCK_RESPONSE': { 260 | return respondWithMock(clientMessage.data) 261 | } 262 | 263 | case 'PASSTHROUGH': { 264 | return passthrough() 265 | } 266 | } 267 | 268 | return passthrough() 269 | } 270 | 271 | function sendToClient(client, message, transferrables = []) { 272 | return new Promise((resolve, reject) => { 273 | const channel = new MessageChannel() 274 | 275 | channel.port1.onmessage = (event) => { 276 | if (event.data && event.data.error) { 277 | return reject(event.data.error) 278 | } 279 | 280 | resolve(event.data) 281 | } 282 | 283 | client.postMessage( 284 | message, 285 | [channel.port2].concat(transferrables.filter(Boolean)), 286 | ) 287 | }) 288 | } 289 | 290 | async function respondWithMock(response) { 291 | // Setting response status code to 0 is a no-op. 292 | // However, when responding with a "Response.error()", the produced Response 293 | // instance will have status code set to 0. Since it's not possible to create 294 | // a Response instance with status code 0, handle that use-case separately. 295 | if (response.status === 0) { 296 | return Response.error() 297 | } 298 | 299 | const mockedResponse = new Response(response.body, response) 300 | 301 | Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, { 302 | value: true, 303 | enumerable: true, 304 | }) 305 | 306 | return mockedResponse 307 | } 308 | --------------------------------------------------------------------------------