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