@hono/auth-js 1.0.17 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.js CHANGED
@@ -1,409 +1,376 @@
1
- // src/react.tsx
2
1
  import * as React from "react";
3
- import { useCallback, useContext, useEffect as useEffect2, useMemo, useState as useState3 } from "react";
4
-
5
- // src/client.ts
2
+ import { useCallback, useContext, useEffect, useMemo, useState } from "react";
6
3
  import { AuthError } from "@auth/core/errors";
7
- import { useEffect, useState } from "react";
8
- var ClientFetchError = class extends AuthError {
9
- };
10
- var ClientSessionError = class extends AuthError {
11
- };
12
- async function fetchData(path, config, logger2, req = {}) {
13
- const url = `${config.baseUrl}${config.basePath}/${path}`;
14
- try {
15
- const options = {
16
- headers: {
17
- "Content-Type": "application/json",
18
- ...req?.headers?.cookie ? { cookie: req.headers.cookie } : {}
19
- },
20
- credentials: config.credentials
21
- };
22
- if (req?.body) {
23
- options.body = JSON.stringify(req.body);
24
- options.method = "POST";
25
- }
26
- const res = await fetch(url, options);
27
- const data = await res.json();
28
- if (!res.ok) {
29
- throw data;
30
- }
31
- return data;
32
- } catch (error) {
33
- logger2.error(new ClientFetchError(error.message, error));
34
- return null;
35
- }
4
+
5
+ //#region src/client.ts
6
+ var ClientFetchError = class extends AuthError {};
7
+ var ClientSessionError = class extends AuthError {};
8
+ async function fetchData(path, config, logger$1, req = {}) {
9
+ const url = `${config.baseUrl}${config.basePath}/${path}`;
10
+ try {
11
+ const options = {
12
+ headers: {
13
+ "Content-Type": "application/json",
14
+ ...req?.headers?.cookie ? { cookie: req.headers.cookie } : {}
15
+ },
16
+ credentials: config.credentials
17
+ };
18
+ if (req?.body) {
19
+ options.body = JSON.stringify(req.body);
20
+ options.method = "POST";
21
+ }
22
+ const res = await fetch(url, options);
23
+ const data = await res.json();
24
+ if (!res.ok) throw data;
25
+ return data;
26
+ } catch (error) {
27
+ logger$1.error(new ClientFetchError(error.message, error));
28
+ return null;
29
+ }
36
30
  }
37
31
  function useOnline() {
38
- const [isOnline, setIsOnline] = useState(
39
- typeof navigator !== "undefined" ? navigator.onLine : false
40
- );
41
- useEffect(() => {
42
- const abortController = new AbortController();
43
- const { signal } = abortController;
44
- const setOnline = () => setIsOnline(true);
45
- const setOffline = () => setIsOnline(false);
46
- window.addEventListener("online", setOnline, { signal });
47
- window.addEventListener("offline", setOffline, { signal });
48
- return () => {
49
- abortController.abort();
50
- };
51
- }, []);
52
- return isOnline;
32
+ const [isOnline, setIsOnline] = useState(typeof navigator !== "undefined" ? navigator.onLine : false);
33
+ useEffect(() => {
34
+ const abortController = new AbortController();
35
+ const { signal } = abortController;
36
+ const setOnline = () => {
37
+ setIsOnline(true);
38
+ };
39
+ const setOffline = () => {
40
+ setIsOnline(false);
41
+ };
42
+ window.addEventListener("online", setOnline, { signal });
43
+ window.addEventListener("offline", setOffline, { signal });
44
+ return () => {
45
+ abortController.abort();
46
+ };
47
+ }, []);
48
+ return isOnline;
53
49
  }
54
50
  function now() {
55
- return Math.floor(Date.now() / 1e3);
51
+ return Math.floor(Date.now() / 1e3);
52
+ }
53
+ function normalizeBasePath(config) {
54
+ if (config.basePath && /^https?:\/\//.test(config.basePath)) {
55
+ const url = new URL(config.basePath);
56
+ return {
57
+ ...config,
58
+ baseUrl: url.origin,
59
+ basePath: url.pathname.replace(/\/$/, "")
60
+ };
61
+ }
62
+ return config;
56
63
  }
57
64
  function parseUrl(url) {
58
- const defaultUrl = "http://localhost:3000/api/auth";
59
- const parsedUrl = new URL(url ? url.startsWith("http") ? url : `https://${url}` : defaultUrl);
60
- const path = parsedUrl.pathname === "/" ? "/api/auth" : parsedUrl.pathname.replace(/\/$/, "");
61
- const base = `${parsedUrl.origin}${path}`;
62
- return {
63
- origin: parsedUrl.origin,
64
- host: parsedUrl.host,
65
- path,
66
- base,
67
- toString: () => base
68
- };
65
+ const parsedUrl = new URL(url ? url.startsWith("http") ? url : `https://${url}` : "http://localhost:3000/api/auth");
66
+ const path = parsedUrl.pathname === "/" ? "/api/auth" : parsedUrl.pathname.replace(/\/$/, "");
67
+ const base = `${parsedUrl.origin}${path}`;
68
+ return {
69
+ origin: parsedUrl.origin,
70
+ host: parsedUrl.host,
71
+ path,
72
+ base,
73
+ toString: () => base
74
+ };
69
75
  }
70
76
 
71
- // src/react.tsx
72
- var logger = {
73
- debug: console.debug,
74
- error: console.error,
75
- warn: console.warn
77
+ //#endregion
78
+ //#region src/react.tsx
79
+ const logger = {
80
+ debug: console.debug,
81
+ error: console.error,
82
+ warn: console.warn
76
83
  };
77
- var AuthConfigManager = class _AuthConfigManager {
78
- static instance = null;
79
- config;
80
- constructor() {
81
- this.config = this.createDefaultConfig();
82
- }
83
- createDefaultConfig() {
84
- return {
85
- baseUrl: typeof window !== "undefined" ? parseUrl(window.location.origin).origin : "",
86
- basePath: typeof window !== "undefined" ? parseUrl(window.location.origin).path : "/api/auth",
87
- credentials: "same-origin",
88
- lastSync: 0,
89
- session: null,
90
- fetchSession: async () => void 0
91
- };
92
- }
93
- static getInstance() {
94
- if (!_AuthConfigManager.instance) {
95
- _AuthConfigManager.instance = new _AuthConfigManager();
96
- }
97
- return _AuthConfigManager.instance;
98
- }
99
- setConfig(userConfig) {
100
- this.config = { ...this.config, ...userConfig };
101
- }
102
- getConfig() {
103
- return this.config;
104
- }
105
- initializeConfig(hasInitialSession) {
106
- this.config.lastSync = hasInitialSession ? now() : 0;
107
- }
84
+ var AuthConfigManager = class AuthConfigManager {
85
+ static instance = null;
86
+ config;
87
+ constructor() {
88
+ this.config = this.createDefaultConfig();
89
+ }
90
+ createDefaultConfig() {
91
+ return {
92
+ baseUrl: typeof window !== "undefined" ? parseUrl(window.location.origin).origin : "",
93
+ basePath: typeof window !== "undefined" ? parseUrl(window.location.origin).path : "/api/auth",
94
+ credentials: "same-origin",
95
+ lastSync: 0,
96
+ session: null,
97
+ fetchSession: async () => void 0
98
+ };
99
+ }
100
+ static getInstance() {
101
+ if (!AuthConfigManager.instance) AuthConfigManager.instance = new AuthConfigManager();
102
+ return AuthConfigManager.instance;
103
+ }
104
+ setConfig(userConfig) {
105
+ const normalized = normalizeBasePath(userConfig);
106
+ this.config = {
107
+ ...this.config,
108
+ ...normalized
109
+ };
110
+ }
111
+ getConfig() {
112
+ return this.config;
113
+ }
114
+ initializeConfig(hasInitialSession) {
115
+ this.config.lastSync = hasInitialSession ? now() : 0;
116
+ }
108
117
  };
109
- var authConfigManager = AuthConfigManager.getInstance();
110
- var SessionContext = React.createContext(void 0);
118
+ const authConfigManager = AuthConfigManager.getInstance();
119
+ const SessionContext = React.createContext(void 0);
111
120
  function useInitializeSession(hasInitialSession, initialSession) {
112
- const authConfig = authConfigManager.getConfig();
113
- const [session, setSession] = React.useState(initialSession);
114
- const [loading, setLoading] = React.useState(!hasInitialSession);
115
- useEffect2(() => {
116
- authConfig.fetchSession = async ({ event } = {}) => {
117
- try {
118
- const isStorageEvent = event === "storage";
119
- if (isStorageEvent || !authConfig.session) {
120
- authConfig.lastSync = now();
121
- authConfig.session = await getSession();
122
- setSession(authConfig.session);
123
- return;
124
- }
125
- if (!event || !authConfig.session || now() < authConfig.lastSync) {
126
- return;
127
- }
128
- authConfig.lastSync = now();
129
- authConfig.session = await getSession();
130
- setSession(authConfig.session);
131
- } catch (error) {
132
- logger.error(new ClientSessionError(error.message, error));
133
- } finally {
134
- setLoading(false);
135
- }
136
- };
137
- authConfig.fetchSession();
138
- return () => {
139
- authConfig.lastSync = 0;
140
- authConfig.session = null;
141
- authConfig.fetchSession = async () => void 0;
142
- };
143
- }, []);
144
- return { session, setSession, loading, setLoading };
121
+ const authConfig = authConfigManager.getConfig();
122
+ const [session, setSession] = React.useState(initialSession);
123
+ const [loading, setLoading] = React.useState(!hasInitialSession);
124
+ useEffect(() => {
125
+ authConfig.fetchSession = async ({ event } = {}) => {
126
+ try {
127
+ if (event === "storage" || !authConfig.session) {
128
+ authConfig.lastSync = now();
129
+ authConfig.session = await getSession();
130
+ setSession(authConfig.session);
131
+ return;
132
+ }
133
+ if (!event || !authConfig.session || now() < authConfig.lastSync) return;
134
+ authConfig.lastSync = now();
135
+ authConfig.session = await getSession();
136
+ setSession(authConfig.session);
137
+ } catch (error) {
138
+ logger.error(new ClientSessionError(error.message, error));
139
+ } finally {
140
+ setLoading(false);
141
+ }
142
+ };
143
+ authConfig.fetchSession();
144
+ return () => {
145
+ authConfig.lastSync = 0;
146
+ authConfig.session = null;
147
+ authConfig.fetchSession = async () => void 0;
148
+ };
149
+ }, []);
150
+ return {
151
+ session,
152
+ setSession,
153
+ loading,
154
+ setLoading
155
+ };
145
156
  }
146
157
  function useVisibilityChangeEventListener(authConfig, refetchOnWindowFocus) {
147
- useEffect2(() => {
148
- const abortController = new AbortController();
149
- const handleVisibilityChange = () => {
150
- if (refetchOnWindowFocus && document.visibilityState === "visible") {
151
- authConfig.fetchSession({ event: "visibilitychange" });
152
- }
153
- };
154
- document.addEventListener("visibilitychange", handleVisibilityChange, {
155
- signal: abortController.signal
156
- });
157
- return () => abortController.abort();
158
- }, [refetchOnWindowFocus]);
158
+ useEffect(() => {
159
+ const abortController = new AbortController();
160
+ const handleVisibilityChange = () => {
161
+ if (refetchOnWindowFocus && document.visibilityState === "visible") authConfig.fetchSession({ event: "visibilitychange" });
162
+ };
163
+ document.addEventListener("visibilitychange", handleVisibilityChange, { signal: abortController.signal });
164
+ return () => {
165
+ abortController.abort();
166
+ };
167
+ }, [refetchOnWindowFocus]);
159
168
  }
160
169
  function useRefetchInterval(authConfig, refetchInterval, shouldRefetch) {
161
- useEffect2(() => {
162
- if (refetchInterval && shouldRefetch) {
163
- const intervalId = setInterval(() => {
164
- if (authConfig.session) {
165
- authConfig.fetchSession({ event: "poll" });
166
- }
167
- }, refetchInterval * 1e3);
168
- return () => clearInterval(intervalId);
169
- }
170
- }, [refetchInterval, shouldRefetch]);
170
+ useEffect(() => {
171
+ if (refetchInterval && shouldRefetch) {
172
+ const intervalId = setInterval(() => {
173
+ if (authConfig.session) authConfig.fetchSession({ event: "poll" });
174
+ }, refetchInterval * 1e3);
175
+ return () => {
176
+ clearInterval(intervalId);
177
+ };
178
+ }
179
+ }, [refetchInterval, shouldRefetch]);
171
180
  }
172
181
  async function getSession(params) {
173
- const { baseUrl, basePath, credentials } = authConfigManager.getConfig();
174
- const session = await fetchData(
175
- "session",
176
- {
177
- baseUrl,
178
- basePath,
179
- credentials
180
- },
181
- logger,
182
- params
183
- );
184
- return session;
182
+ const { baseUrl, basePath, credentials } = authConfigManager.getConfig();
183
+ return await fetchData("session", {
184
+ baseUrl,
185
+ basePath,
186
+ credentials
187
+ }, logger, params);
185
188
  }
186
189
  async function getCsrfToken() {
187
- const { baseUrl, basePath, credentials } = authConfigManager.getConfig();
188
- const response = await fetchData(
189
- "csrf",
190
- {
191
- baseUrl,
192
- basePath,
193
- credentials
194
- },
195
- logger
196
- );
197
- return response?.csrfToken ?? "";
190
+ const { baseUrl, basePath, credentials } = authConfigManager.getConfig();
191
+ return (await fetchData("csrf", {
192
+ baseUrl,
193
+ basePath,
194
+ credentials
195
+ }, logger))?.csrfToken ?? "";
198
196
  }
199
197
  function SessionProvider(props) {
200
- if (!SessionContext) {
201
- throw new Error("React Context is unavailable in Server Components");
202
- }
203
- const { children, refetchInterval, refetchWhenOffline = true } = props;
204
- const authConfig = authConfigManager.getConfig();
205
- const hasInitialSession = !!props.session;
206
- authConfigManager.initializeConfig(hasInitialSession);
207
- const { session, setSession, loading, setLoading } = useInitializeSession(
208
- hasInitialSession,
209
- props.session ?? null
210
- );
211
- useVisibilityChangeEventListener(authConfig, props.refetchOnWindowFocus ?? true);
212
- const isOnline = useOnline();
213
- const shouldRefetch = refetchWhenOffline || isOnline;
214
- useRefetchInterval(authConfig, refetchInterval, shouldRefetch);
215
- const contextValue = useMemo(
216
- () => ({
217
- data: session,
218
- status: loading ? "loading" : session ? "authenticated" : "unauthenticated",
219
- update: async (data) => {
220
- if (loading || !session) {
221
- return;
222
- }
223
- setLoading(true);
224
- const updatedSession = await fetchData(
225
- "session",
226
- authConfig,
227
- logger,
228
- data ? { body: { csrfToken: await getCsrfToken(), data } } : void 0
229
- );
230
- setLoading(false);
231
- if (updatedSession) {
232
- setSession(updatedSession);
233
- }
234
- return updatedSession;
235
- }
236
- }),
237
- [session, loading, setSession]
238
- );
239
- return /* @__PURE__ */ React.createElement(SessionContext.Provider, { value: contextValue }, children);
198
+ if (!SessionContext) throw new Error("React Context is unavailable in Server Components");
199
+ const { children, refetchInterval, refetchWhenOffline = true } = props;
200
+ const authConfig = authConfigManager.getConfig();
201
+ const hasInitialSession = !!props.session;
202
+ authConfigManager.initializeConfig(hasInitialSession);
203
+ const { session, setSession, loading, setLoading } = useInitializeSession(hasInitialSession, props.session ?? null);
204
+ useVisibilityChangeEventListener(authConfig, props.refetchOnWindowFocus ?? true);
205
+ const isOnline = useOnline();
206
+ useRefetchInterval(authConfig, refetchInterval, refetchWhenOffline || isOnline);
207
+ const contextValue = useMemo(() => ({
208
+ data: session,
209
+ status: loading ? "loading" : session ? "authenticated" : "unauthenticated",
210
+ update: async (data) => {
211
+ if (loading || !session) return;
212
+ setLoading(true);
213
+ const updatedSession = await fetchData("session", authConfig, logger, data ? { body: {
214
+ csrfToken: await getCsrfToken(),
215
+ data
216
+ } } : void 0);
217
+ setLoading(false);
218
+ if (updatedSession) setSession(updatedSession);
219
+ return updatedSession;
220
+ }
221
+ }), [
222
+ session,
223
+ loading,
224
+ setSession
225
+ ]);
226
+ return /* @__PURE__ */ React.createElement(SessionContext.Provider, { value: contextValue }, children);
240
227
  }
241
228
  function useSession(options) {
242
- if (!SessionContext) {
243
- throw new Error("React Context is unavailable in Server Components");
244
- }
245
- const config = authConfigManager.getConfig();
246
- const session = useContext(SessionContext);
247
- const { required, onUnauthenticated } = options ?? {};
248
- const requiredAndNotLoading = required && session?.status === "unauthenticated";
249
- useEffect2(() => {
250
- if (requiredAndNotLoading) {
251
- const url = `${config.baseUrl}${config.basePath}/signin?${new URLSearchParams({
252
- error: "SessionRequired",
253
- callbackUrl: window.location.href
254
- })}`;
255
- if (onUnauthenticated) {
256
- onUnauthenticated();
257
- } else {
258
- window.location.href = url;
259
- }
260
- }
261
- }, [requiredAndNotLoading, onUnauthenticated]);
262
- if (requiredAndNotLoading) {
263
- return {
264
- data: session?.data,
265
- update: session?.update,
266
- status: "loading"
267
- };
268
- }
269
- return session;
229
+ if (!SessionContext) throw new Error("React Context is unavailable in Server Components");
230
+ const config = authConfigManager.getConfig();
231
+ const session = useContext(SessionContext);
232
+ const { required, onUnauthenticated } = options ?? {};
233
+ const requiredAndNotLoading = required && session?.status === "unauthenticated";
234
+ useEffect(() => {
235
+ if (requiredAndNotLoading) {
236
+ const url = `${config.baseUrl}${config.basePath}/signin?${new URLSearchParams({
237
+ error: "SessionRequired",
238
+ callbackUrl: window.location.href
239
+ })}`;
240
+ if (onUnauthenticated) onUnauthenticated();
241
+ else window.location.href = url;
242
+ }
243
+ }, [requiredAndNotLoading, onUnauthenticated]);
244
+ if (requiredAndNotLoading) return {
245
+ data: session?.data,
246
+ update: session?.update,
247
+ status: "loading"
248
+ };
249
+ return session;
270
250
  }
271
251
  async function getProviders() {
272
- return fetchData("providers", authConfigManager.getConfig(), logger);
252
+ return fetchData("providers", authConfigManager.getConfig(), logger);
273
253
  }
274
254
  async function signIn(provider, options = {}, authorizationParams = {}) {
275
- const { callbackUrl = window.location.href, redirect = true, ...opts } = options;
276
- const config = authConfigManager.getConfig();
277
- const href = `${config.baseUrl}${config.basePath}`;
278
- const providers = await getProviders();
279
- if (!providers) {
280
- window.location.href = `${href}/error`;
281
- return;
282
- }
283
- if (!provider || !(provider in providers)) {
284
- window.location.href = `${href}/signin?${new URLSearchParams({ callbackUrl })}`;
285
- return;
286
- }
287
- const isCredentials = providers[provider].type === "credentials";
288
- const isEmail = providers[provider].type === "email";
289
- const signInUrl = `${href}/${isCredentials ? "callback" : "signin"}/${provider}`;
290
- const csrfToken = await getCsrfToken();
291
- const res = await fetch(`${signInUrl}?${new URLSearchParams(authorizationParams)}`, {
292
- method: "POST",
293
- headers: {
294
- "Content-Type": "application/x-www-form-urlencoded",
295
- "X-Auth-Return-Redirect": "1"
296
- },
297
- body: new URLSearchParams({ ...opts, csrfToken, callbackUrl }),
298
- credentials: config.credentials
299
- });
300
- const data = await res.json();
301
- if (redirect) {
302
- const url = data.url ?? callbackUrl;
303
- window.location.href = url;
304
- if (url.includes("#")) {
305
- window.location.reload();
306
- }
307
- return;
308
- }
309
- const error = new URL(data.url).searchParams.get("error");
310
- if (res.ok) {
311
- await config.fetchSession?.({ event: "storage" });
312
- }
313
- return {
314
- error,
315
- status: res.status,
316
- ok: res.ok,
317
- url: error ? null : data.url
318
- };
255
+ const { callbackUrl = window.location.href, redirect = true,...opts } = options;
256
+ const config = authConfigManager.getConfig();
257
+ const href = `${config.baseUrl}${config.basePath}`;
258
+ const providers = await getProviders();
259
+ if (!providers) {
260
+ window.location.href = `${href}/error`;
261
+ return;
262
+ }
263
+ if (!provider || !(provider in providers)) {
264
+ window.location.href = `${href}/signin?${new URLSearchParams({ callbackUrl })}`;
265
+ return;
266
+ }
267
+ const isCredentials = providers[provider].type === "credentials";
268
+ providers[provider].type;
269
+ const signInUrl = `${href}/${isCredentials ? "callback" : "signin"}/${provider}`;
270
+ const csrfToken = await getCsrfToken();
271
+ const res = await fetch(`${signInUrl}?${new URLSearchParams(authorizationParams)}`, {
272
+ method: "POST",
273
+ headers: {
274
+ "Content-Type": "application/x-www-form-urlencoded",
275
+ "X-Auth-Return-Redirect": "1"
276
+ },
277
+ body: new URLSearchParams({
278
+ ...opts,
279
+ csrfToken,
280
+ callbackUrl
281
+ }),
282
+ credentials: config.credentials
283
+ });
284
+ const data = await res.json();
285
+ if (redirect) {
286
+ const url = data.url ?? callbackUrl;
287
+ window.location.href = url;
288
+ if (url.includes("#")) window.location.reload();
289
+ return;
290
+ }
291
+ const error = new URL(data.url).searchParams.get("error");
292
+ if (res.ok) await config.fetchSession?.({ event: "storage" });
293
+ return {
294
+ error,
295
+ status: res.status,
296
+ ok: res.ok,
297
+ url: error ? null : data.url
298
+ };
319
299
  }
320
300
  async function signOut(options) {
321
- const { callbackUrl = window.location.href, redirect = true } = options ?? {};
322
- const config = authConfigManager.getConfig();
323
- const csrfToken = await getCsrfToken();
324
- const res = await fetch(`${config.baseUrl}${config.basePath}/signout`, {
325
- method: "POST",
326
- headers: {
327
- "Content-Type": "application/x-www-form-urlencoded",
328
- "X-Auth-Return-Redirect": "1"
329
- },
330
- body: new URLSearchParams({ csrfToken, callbackUrl }),
331
- credentials: config.credentials
332
- });
333
- const data = await res.json();
334
- if (redirect) {
335
- const url = data.url ?? callbackUrl;
336
- window.location.href = url;
337
- if (url.includes("#")) {
338
- window.location.reload();
339
- }
340
- return void 0;
341
- }
342
- await config.fetchSession?.({ event: "storage" });
343
- return data;
301
+ const { callbackUrl = window.location.href, redirect = true } = options ?? {};
302
+ const config = authConfigManager.getConfig();
303
+ const csrfToken = await getCsrfToken();
304
+ const data = await (await fetch(`${config.baseUrl}${config.basePath}/signout`, {
305
+ method: "POST",
306
+ headers: {
307
+ "Content-Type": "application/x-www-form-urlencoded",
308
+ "X-Auth-Return-Redirect": "1"
309
+ },
310
+ body: new URLSearchParams({
311
+ csrfToken,
312
+ callbackUrl
313
+ }),
314
+ credentials: config.credentials
315
+ })).json();
316
+ if (redirect) {
317
+ const url = data.url ?? callbackUrl;
318
+ window.location.href = url;
319
+ if (url.includes("#")) window.location.reload();
320
+ return;
321
+ }
322
+ await config.fetchSession?.({ event: "storage" });
323
+ return data;
344
324
  }
345
- var createPopup = ({ url, title, height, width }) => {
346
- const left = window.screenX + (window.outerWidth - width) / 2;
347
- const top = window.screenY + (window.outerHeight - height) / 2.5;
348
- const externalPopup = window.open(
349
- url,
350
- title,
351
- `width=${width},height=${height},left=${left},top=${top}`
352
- );
353
- return externalPopup;
354
- };
355
- var useOauthPopupLogin = (provider, options = {}) => {
356
- const { width = 500, height = 500, title = "Signin", onSuccess, callbackUrl = "/" } = options;
357
- const [externalWindow, setExternalWindow] = useState3();
358
- const [state, setState] = useState3({ status: "loading" });
359
- const popUpSignin = useCallback(async () => {
360
- const res = await signIn(provider, {
361
- redirect: false,
362
- callbackUrl
363
- });
364
- if (res?.error) {
365
- setState({ status: "errored", error: res.error });
366
- return;
367
- }
368
- setExternalWindow(
369
- createPopup({
370
- url: res?.url,
371
- title,
372
- width,
373
- height
374
- })
375
- );
376
- }, []);
377
- useEffect2(() => {
378
- const handleMessage = (event) => {
379
- if (event.origin !== window.location.origin) {
380
- return;
381
- }
382
- if (event.data.status) {
383
- setState(event.data);
384
- if (event.data.status === "success") {
385
- onSuccess?.();
386
- }
387
- externalWindow?.close();
388
- }
389
- };
390
- window.addEventListener("message", handleMessage);
391
- return () => {
392
- window.removeEventListener("message", handleMessage);
393
- externalWindow?.close();
394
- };
395
- }, [externalWindow]);
396
- return { popUpSignin, ...state };
325
+ const createPopup = ({ url, title, height, width }) => {
326
+ const left = window.screenX + (window.outerWidth - width) / 2;
327
+ const top = window.screenY + (window.outerHeight - height) / 2.5;
328
+ return window.open(url, title, `width=${width},height=${height},left=${left},top=${top}`);
397
329
  };
398
- export {
399
- SessionContext,
400
- SessionProvider,
401
- authConfigManager,
402
- getCsrfToken,
403
- getProviders,
404
- getSession,
405
- signIn,
406
- signOut,
407
- useOauthPopupLogin,
408
- useSession
330
+ const useOauthPopupLogin = (provider, options = {}) => {
331
+ const { width = 500, height = 500, title = "Signin", onSuccess, callbackUrl = "/" } = options;
332
+ const [externalWindow, setExternalWindow] = useState();
333
+ const [state, setState] = useState({ status: "loading" });
334
+ const popUpSignin = useCallback(async () => {
335
+ const res = await signIn(provider, {
336
+ redirect: false,
337
+ callbackUrl
338
+ });
339
+ if (res?.error) {
340
+ setState({
341
+ status: "errored",
342
+ error: res.error
343
+ });
344
+ return;
345
+ }
346
+ setExternalWindow(createPopup({
347
+ url: res?.url,
348
+ title,
349
+ width,
350
+ height
351
+ }));
352
+ }, []);
353
+ useEffect(() => {
354
+ const handleMessage = (event) => {
355
+ if (event.origin !== window.location.origin) return;
356
+ if (event.data.status) {
357
+ setState(event.data);
358
+ if (event.data.status === "success") onSuccess?.();
359
+ externalWindow?.close();
360
+ }
361
+ };
362
+ window.addEventListener("message", handleMessage);
363
+ return () => {
364
+ window.removeEventListener("message", handleMessage);
365
+ externalWindow?.close();
366
+ };
367
+ }, [externalWindow]);
368
+ return {
369
+ popUpSignin,
370
+ ...state
371
+ };
409
372
  };
373
+
374
+ //#endregion
375
+ export { SessionContext, SessionProvider, authConfigManager, getCsrfToken, getProviders, getSession, signIn, signOut, useOauthPopupLogin, useSession };
376
+ //# sourceMappingURL=react.js.map