zitejs 0.9.74 → 0.9.76

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.
@@ -1,18 +1,237 @@
1
+ export declare const useSession: () => {
2
+ data: {
3
+ user: import("better-auth/react").StripEmptyObjects<{
4
+ id: string;
5
+ createdAt: Date;
6
+ updatedAt: Date;
7
+ email: string;
8
+ emailVerified: boolean;
9
+ name: string;
10
+ image?: string | null | undefined;
11
+ }>;
12
+ session: import("better-auth/react").StripEmptyObjects<{
13
+ id: string;
14
+ createdAt: Date;
15
+ updatedAt: Date;
16
+ userId: string;
17
+ expiresAt: Date;
18
+ token: string;
19
+ ipAddress?: string | null | undefined;
20
+ userAgent?: string | null | undefined;
21
+ }>;
22
+ } | null;
23
+ isPending: boolean;
24
+ isRefetching: boolean;
25
+ error: import("@better-fetch/fetch").BetterFetchError | null;
26
+ refetch: (queryParams?: {
27
+ query?: import("better-auth").SessionQueryParams;
28
+ } | undefined) => Promise<void>;
29
+ }, signIn: {
30
+ social: <FetchOptions extends import("better-auth").ClientFetchOption<Partial<{
31
+ provider: (string & {}) | "linear" | "huggingface" | "github" | "apple" | "atlassian" | "cognito" | "discord" | "facebook" | "figma" | "microsoft" | "google" | "slack" | "spotify" | "twitch" | "twitter" | "dropbox" | "kick" | "linkedin" | "gitlab" | "tiktok" | "reddit" | "roblox" | "salesforce" | "vk" | "zoom" | "notion" | "kakao" | "naver" | "line" | "paybin" | "paypal" | "polar" | "railway" | "vercel" | "wechat";
32
+ callbackURL?: string | undefined;
33
+ newUserCallbackURL?: string | undefined;
34
+ errorCallbackURL?: string | undefined;
35
+ disableRedirect?: boolean | undefined;
36
+ idToken?: {
37
+ token: string;
38
+ nonce?: string | undefined;
39
+ accessToken?: string | undefined;
40
+ refreshToken?: string | undefined;
41
+ expiresAt?: number | undefined;
42
+ user?: {
43
+ name?: {
44
+ firstName?: string | undefined;
45
+ lastName?: string | undefined;
46
+ } | undefined;
47
+ email?: string | undefined;
48
+ } | undefined;
49
+ } | undefined;
50
+ scopes?: string[] | undefined;
51
+ requestSignUp?: boolean | undefined;
52
+ loginHint?: string | undefined;
53
+ additionalData?: Record<string, any> | undefined;
54
+ }> & Record<string, any>, Partial<Record<string, any>> & Record<string, any>, Record<string, any> | undefined>>(data_0: import("better-auth/react").Prettify<{
55
+ provider: (string & {}) | "linear" | "huggingface" | "github" | "apple" | "atlassian" | "cognito" | "discord" | "facebook" | "figma" | "microsoft" | "google" | "slack" | "spotify" | "twitch" | "twitter" | "dropbox" | "kick" | "linkedin" | "gitlab" | "tiktok" | "reddit" | "roblox" | "salesforce" | "vk" | "zoom" | "notion" | "kakao" | "naver" | "line" | "paybin" | "paypal" | "polar" | "railway" | "vercel" | "wechat";
56
+ callbackURL?: string | undefined;
57
+ newUserCallbackURL?: string | undefined;
58
+ errorCallbackURL?: string | undefined;
59
+ disableRedirect?: boolean | undefined;
60
+ idToken?: {
61
+ token: string;
62
+ nonce?: string | undefined;
63
+ accessToken?: string | undefined;
64
+ refreshToken?: string | undefined;
65
+ expiresAt?: number | undefined;
66
+ user?: {
67
+ name?: {
68
+ firstName?: string | undefined;
69
+ lastName?: string | undefined;
70
+ } | undefined;
71
+ email?: string | undefined;
72
+ } | undefined;
73
+ } | undefined;
74
+ scopes?: string[] | undefined;
75
+ requestSignUp?: boolean | undefined;
76
+ loginHint?: string | undefined;
77
+ additionalData?: Record<string, any> | undefined;
78
+ } & {
79
+ fetchOptions?: FetchOptions | undefined;
80
+ }>, data_1?: FetchOptions | undefined) => Promise<import("@better-fetch/fetch").BetterFetchResponse<{
81
+ redirect: boolean;
82
+ url: string;
83
+ } | (Omit<{
84
+ redirect: boolean;
85
+ token: string;
86
+ url: undefined;
87
+ user: {
88
+ id: string;
89
+ createdAt: Date;
90
+ updatedAt: Date;
91
+ email: string;
92
+ emailVerified: boolean;
93
+ name: string;
94
+ image?: string | null | undefined | undefined;
95
+ };
96
+ }, "user"> & {
97
+ user: import("better-auth/react").StripEmptyObjects<{
98
+ id: string;
99
+ createdAt: Date;
100
+ updatedAt: Date;
101
+ email: string;
102
+ emailVerified: boolean;
103
+ name: string;
104
+ image?: string | null | undefined;
105
+ }>;
106
+ }), {
107
+ code?: string | undefined;
108
+ message?: string | undefined;
109
+ }, FetchOptions["throw"] extends true ? true : false>>;
110
+ } & {
111
+ email: <FetchOptions extends import("better-auth").ClientFetchOption<Partial<{
112
+ email: string;
113
+ password: string;
114
+ callbackURL?: string | undefined;
115
+ rememberMe?: boolean | undefined;
116
+ }> & Record<string, any>, Partial<Record<string, any>> & Record<string, any>, Record<string, any> | undefined>>(data_0: import("better-auth/react").Prettify<{
117
+ email: string;
118
+ password: string;
119
+ callbackURL?: string | undefined;
120
+ rememberMe?: boolean | undefined;
121
+ } & {
122
+ fetchOptions?: FetchOptions | undefined;
123
+ }>, data_1?: FetchOptions | undefined) => Promise<import("@better-fetch/fetch").BetterFetchResponse<Omit<{
124
+ redirect: boolean;
125
+ token: string;
126
+ url?: string | undefined;
127
+ user: {
128
+ id: string;
129
+ createdAt: Date;
130
+ updatedAt: Date;
131
+ email: string;
132
+ emailVerified: boolean;
133
+ name: string;
134
+ image?: string | null | undefined | undefined;
135
+ };
136
+ }, "user"> & {
137
+ user: import("better-auth/react").StripEmptyObjects<{
138
+ id: string;
139
+ createdAt: Date;
140
+ updatedAt: Date;
141
+ email: string;
142
+ emailVerified: boolean;
143
+ name: string;
144
+ image?: string | null | undefined;
145
+ }>;
146
+ }, {
147
+ code?: string | undefined;
148
+ message?: string | undefined;
149
+ }, FetchOptions["throw"] extends true ? true : false>>;
150
+ }, signOut: <FetchOptions extends import("better-auth").ClientFetchOption<never, Partial<Record<string, any>> & Record<string, any>, Record<string, any> | undefined>>(data_0?: import("better-auth/react").Prettify<{
151
+ query?: Record<string, any> | undefined;
152
+ fetchOptions?: FetchOptions | undefined;
153
+ }> | undefined, data_1?: FetchOptions | undefined) => Promise<import("@better-fetch/fetch").BetterFetchResponse<{
154
+ success: boolean;
155
+ }, {
156
+ code?: string | undefined;
157
+ message?: string | undefined;
158
+ }, FetchOptions["throw"] extends true ? true : false>>, signUp: {
159
+ email: <FetchOptions extends import("better-auth").ClientFetchOption<Partial<{
160
+ name: string;
161
+ email: string;
162
+ password: string;
163
+ image?: string | undefined;
164
+ callbackURL?: string | undefined;
165
+ rememberMe?: boolean | undefined;
166
+ }> & Record<string, any>, Partial<Record<string, any>> & Record<string, any>, Record<string, any> | undefined>>(data_0: import("better-auth/react").Prettify<{
167
+ email: string;
168
+ name: string;
169
+ password: string;
170
+ image?: string | undefined;
171
+ callbackURL?: string | undefined;
172
+ fetchOptions?: FetchOptions | undefined;
173
+ }>, data_1?: FetchOptions | undefined) => Promise<import("@better-fetch/fetch").BetterFetchResponse<(Omit<{
174
+ token: null;
175
+ user: {
176
+ id: string;
177
+ createdAt: Date;
178
+ updatedAt: Date;
179
+ email: string;
180
+ emailVerified: boolean;
181
+ name: string;
182
+ image?: string | null | undefined | undefined;
183
+ };
184
+ }, "user"> & {
185
+ user: import("better-auth/react").StripEmptyObjects<{
186
+ id: string;
187
+ createdAt: Date;
188
+ updatedAt: Date;
189
+ email: string;
190
+ emailVerified: boolean;
191
+ name: string;
192
+ image?: string | null | undefined;
193
+ }>;
194
+ }) | (Omit<{
195
+ token: string;
196
+ user: {
197
+ id: string;
198
+ createdAt: Date;
199
+ updatedAt: Date;
200
+ email: string;
201
+ emailVerified: boolean;
202
+ name: string;
203
+ image?: string | null | undefined | undefined;
204
+ };
205
+ }, "user"> & {
206
+ user: import("better-auth/react").StripEmptyObjects<{
207
+ id: string;
208
+ createdAt: Date;
209
+ updatedAt: Date;
210
+ email: string;
211
+ emailVerified: boolean;
212
+ name: string;
213
+ image?: string | null | undefined;
214
+ }>;
215
+ }), {
216
+ code?: string | undefined;
217
+ message?: string | undefined;
218
+ }, FetchOptions["throw"] extends true ? true : false>>;
219
+ };
220
+ export declare function loginWithRedirect(opts?: {
221
+ redirectUrl?: string;
222
+ initialView?: 'login' | 'signup';
223
+ }): void;
224
+ export declare function logout(opts?: {
225
+ returnTo?: string;
226
+ }): void;
1
227
  export type User = {
2
228
  id: string;
229
+ name: string;
3
230
  email: string;
231
+ emailVerified: boolean;
232
+ image?: string | null;
4
233
  firstName?: string;
5
234
  lastName?: string;
6
- [key: string]: unknown;
7
- };
8
- export declare function useAuth(): {
9
- user: User | undefined;
10
- isLoading: boolean;
11
- loginWithRedirect: (opts?: {
12
- redirectUrl?: string;
13
- initialView?: 'login' | 'signup';
14
- }) => void;
15
- logout: (options?: {
16
- returnTo?: string;
17
- }) => void;
235
+ createdAt: Date;
236
+ updatedAt: Date;
18
237
  };
@@ -1,280 +1,19 @@
1
- import { useCallback, useEffect, useRef } from 'react';
2
- import { useQuery, useQueryClient } from '@tanstack/react-query';
3
- import { getFlowId, getApiUrl, getAuthPageUrl, getDbToken } from './config.js';
4
- import { ZITE_APP_EDITOR_HOSTNAME_PREFIX, ZITE_APP_ACTION_HOSTNAME_PREFIX, ZITE_APP_SNAPSHOT_HOSTNAME_PREFIX, ZITE_SANDBOX_DOMAINS, USAGE_TOKEN_QUERY_PARAM, AUTH_SDK_VERSION, } from './constants.js';
5
- const _isLocalEnv = typeof window !== 'undefined' &&
6
- (window.location.hostname === 'localhost' ||
7
- window.location.hostname === '127.0.0.1' ||
8
- window.location.hostname.endsWith('.localhost') ||
9
- localStorage.getItem('zite.debug.log') === 'true');
10
- const debugLog = (...args) => {
11
- if (_isLocalEnv)
12
- console.log(...args);
13
- };
14
- const debugWarn = (...args) => {
15
- if (_isLocalEnv)
16
- console.warn(...args);
17
- };
18
- debugLog('[zite/auth-sdk] v' + AUTH_SDK_VERSION + ' initialized', {
19
- appPublicIdentifier: getFlowId(),
1
+ import { createAuthClient } from 'better-auth/react';
2
+ const authClient = createAuthClient({
3
+ baseURL: '',
20
4
  });
21
- const isInternalMode = () => {
22
- const win = window;
23
- if (win._ziteIsInternalMode === undefined) {
24
- const search = new URLSearchParams(window.location.search);
25
- const isInternalModeParam = search.get('isInternalMode');
26
- if (isInternalModeParam !== null) {
27
- win._ziteIsInternalMode = isInternalModeParam === 'true';
28
- }
29
- }
30
- const result = !!win._ziteIsInternalMode;
31
- debugLog('[zite/auth-sdk] isInternalMode:', result);
32
- return result;
33
- };
34
- const getZiteAppMode = (hostname) => {
35
- const hostnameParts = hostname.split('.');
36
- const maybeId = hostnameParts.length > 0 ? hostnameParts[0] : undefined;
37
- if (maybeId?.startsWith(ZITE_APP_EDITOR_HOSTNAME_PREFIX))
38
- return 'preview';
39
- if (maybeId?.startsWith(ZITE_APP_ACTION_HOSTNAME_PREFIX))
40
- return 'preview';
41
- if (maybeId?.startsWith(ZITE_APP_SNAPSHOT_HOSTNAME_PREFIX))
42
- return 'preview';
43
- if (ZITE_SANDBOX_DOMAINS.some(d => hostname === d || hostname.endsWith('.' + d))) {
44
- return 'preview';
45
- }
46
- return 'live';
47
- };
48
- async function getToken(code) {
49
- const mode = getZiteAppMode(window.location.hostname);
50
- const flowId = getFlowId();
51
- const res = await fetch(getApiUrl() +
52
- '/v1/zite/public/auth/' +
53
- flowId +
54
- '/token?mode=' +
55
- mode, {
56
- method: 'POST',
57
- headers: { 'Content-Type': 'application/json' },
58
- body: JSON.stringify({ code }),
59
- });
60
- if (!res.ok) {
61
- throw new Error('Failed to get token');
62
- }
63
- const { token } = await res.json();
64
- return token;
65
- }
66
- class ZiteAuthenticationError extends Error {
67
- status;
68
- constructor(message, status) {
69
- super(message);
70
- this.name = 'ZiteAuthenticationError';
71
- this.status = status;
72
- Object.setPrototypeOf(this, ZiteAuthenticationError.prototype);
73
- }
74
- }
75
- async function getCurrentUser() {
76
- const token = localStorage.getItem('zite.auth.token');
77
- if (!token)
78
- return null;
79
- const mode = getZiteAppMode(window.location.hostname);
80
- const flowId = getFlowId();
81
- const res = await fetch(getApiUrl() +
82
- '/v1/zite/public/auth/' +
83
- flowId +
84
- '/me?mode=' +
85
- mode, {
86
- method: 'GET',
87
- headers: { Authorization: 'Bearer ' + token },
88
- });
89
- if (res.status === 401) {
90
- throw new ZiteAuthenticationError('Unauthorized', res.status);
91
- }
92
- if (!res.ok)
93
- return null;
94
- const { user } = await res.json();
95
- return user;
96
- }
97
- async function getUser() {
98
- const win = window;
99
- debugLog('[zite/auth-sdk] getUser called', {
100
- hasExistingToken: !!localStorage.getItem('zite.auth.token'),
101
- hasUsageToken: !!win._ziteUsageToken,
102
- windowIsInternalMode: !!win._ziteIsInternalMode,
103
- hostname: window.location.hostname,
104
- });
105
- const isLocalDev = (window.location.hostname === 'localhost' ||
106
- window.location.hostname === '127.0.0.1') &&
107
- !win._ziteIsInternalMode &&
108
- !win._ziteUsageToken &&
109
- !localStorage.getItem('zite.auth.token');
110
- if (isLocalDev) {
111
- try {
112
- const rawToken = getDbToken();
113
- const jwt = rawToken?.startsWith('zitejwt_')
114
- ? rawToken.slice(8)
115
- : rawToken;
116
- if (jwt) {
117
- const payload = JSON.parse(atob(jwt.split('.')[1]));
118
- if (payload.devUser) {
119
- debugLog('[zite/auth-sdk] local dev mode — user from dev JWT:', payload.devUser.email);
120
- return payload.devUser;
121
- }
122
- }
123
- }
124
- catch { }
125
- debugLog('[zite/auth-sdk] local dev mode — returning fallback mock user');
126
- return {
127
- id: 'local-dev',
128
- email: 'dev@localhost',
129
- firstName: 'Local',
130
- lastName: 'Developer',
131
- };
132
- }
133
- const code = new URL(window.location.href).searchParams.get('code');
134
- if (code) {
135
- debugLog('[zite/auth-sdk] exchanging code from URL params for token');
136
- const token = await getToken(code);
137
- localStorage.setItem('zite.auth.token', token);
138
- window.history.replaceState({}, '', window.location.pathname);
139
- }
140
- if (isInternalMode() && !localStorage.getItem('zite.auth.token')) {
141
- const usageToken = win._ziteUsageToken;
142
- debugLog('[zite/auth-sdk] internal mode, no token yet. usageToken present:', !!usageToken);
143
- if (usageToken) {
144
- try {
145
- const mode = getZiteAppMode(window.location.hostname);
146
- const flowId = getFlowId();
147
- debugLog('[zite/auth-sdk] calling /usage-token endpoint', { mode });
148
- const res = await fetch(getApiUrl() +
149
- '/v1/zite/public/auth/' +
150
- flowId +
151
- '/usage-token?mode=' +
152
- mode, {
153
- method: 'POST',
154
- headers: { 'Content-Type': 'application/json' },
155
- body: JSON.stringify({
156
- usageToken,
157
- redirectUrl: window.location.href,
158
- }),
159
- });
160
- debugLog('[zite/auth-sdk] /usage-token response status:', res.status);
161
- if (res.ok) {
162
- const data = await res.json();
163
- if (data.token) {
164
- localStorage.setItem('zite.auth.token', data.token);
165
- debugLog('[zite/auth-sdk] token stored from usage-token response');
166
- }
167
- else if (data.redirectUrl) {
168
- const inlineCode = new URL(data.redirectUrl).searchParams.get('code');
169
- if (inlineCode) {
170
- const token = await getToken(inlineCode);
171
- localStorage.setItem('zite.auth.token', token);
172
- debugLog('[zite/auth-sdk] token stored from usage-token redirect fallback');
173
- }
174
- }
175
- }
176
- else {
177
- debugWarn('[zite/auth-sdk] /usage-token call failed with status:', res.status);
178
- }
179
- }
180
- catch (err) {
181
- debugWarn('[zite/auth-sdk] /usage-token exchange error:', err);
182
- }
183
- }
184
- }
185
- else if (isInternalMode()) {
186
- debugLog('[zite/auth-sdk] internal mode, existing token found — skipping usage-token exchange');
187
- }
188
- try {
189
- debugLog('[zite/auth-sdk] calling getCurrentUser');
190
- const user = await getCurrentUser();
191
- if (!user) {
192
- debugLog('[zite/auth-sdk] getCurrentUser returned null, clearing token');
193
- localStorage.removeItem('zite.auth.token');
194
- return null;
195
- }
196
- debugLog('[zite/auth-sdk] getUser resolved with user:', user.id);
197
- return user;
198
- }
199
- catch (err) {
200
- debugWarn('[zite/auth-sdk] getCurrentUser error:', err);
201
- if (err instanceof ZiteAuthenticationError) {
202
- localStorage.removeItem('zite.auth.token');
203
- debugLog('[zite/auth-sdk] cleared token due to auth error (status:', err.status, ')');
204
- }
205
- return null;
206
- }
5
+ export const { useSession, signIn, signOut, signUp } = authClient;
6
+ export function loginWithRedirect(opts) {
7
+ const params = new URLSearchParams();
8
+ if (opts?.redirectUrl)
9
+ params.set('redirectUrl', opts.redirectUrl);
10
+ if (opts?.initialView)
11
+ params.set('view', opts.initialView);
12
+ const query = params.toString();
13
+ window.location.href = '/auth/login' + (query ? '?' + query : '');
207
14
  }
208
- export function useAuth() {
209
- const queryClient = useQueryClient();
210
- const userQuery = useQuery({
211
- queryKey: ['zite.auth.user'],
212
- queryFn: getUser,
213
- retry: 3,
214
- staleTime: Infinity,
215
- refetchOnWindowFocus: false,
216
- refetchOnReconnect: false,
217
- refetchOnMount: false,
15
+ export function logout(opts) {
16
+ signOut().then(() => {
17
+ window.location.href = opts?.returnTo || '/';
218
18
  });
219
- const authErrorThrown = useRef(false);
220
- useEffect(() => {
221
- if (!userQuery.isPending &&
222
- !userQuery.data &&
223
- isInternalMode() &&
224
- !authErrorThrown.current) {
225
- authErrorThrown.current = true;
226
- setTimeout(() => {
227
- throw new ZiteAuthenticationError('Authentication failed in internal mode. The user could not be resolved after loading completed.', 401);
228
- }, 0);
229
- }
230
- }, [userQuery.isPending, userQuery.data]);
231
- useEffect(() => {
232
- const handler = () => {
233
- debugLog('[zite/auth-sdk] received zite:auth-sync event, invalidating user query');
234
- queryClient.invalidateQueries({ queryKey: ['zite.auth.user'] });
235
- };
236
- window.addEventListener('zite:auth-sync', handler);
237
- return () => window.removeEventListener('zite:auth-sync', handler);
238
- }, [queryClient]);
239
- const loginWithRedirect = useCallback((opts) => {
240
- if (isInternalMode()) {
241
- throw new Error('loginWithRedirect is not available in internal mode.');
242
- }
243
- const authUrl = getAuthPageUrl();
244
- if (!authUrl) {
245
- throw new Error('loginWithRedirect: AUTH_URL could not be resolved.');
246
- }
247
- const url = new URL(authUrl);
248
- url.searchParams.set('flowPublicIdentifier', getFlowId());
249
- if (opts?.redirectUrl)
250
- url.searchParams.set('redirectUrl', opts.redirectUrl);
251
- if (opts?.initialView === 'signup')
252
- url.searchParams.set('mode', 'signup');
253
- const win = window;
254
- if (win._ziteUsageToken) {
255
- url.searchParams.set(USAGE_TOKEN_QUERY_PARAM, win._ziteUsageToken);
256
- }
257
- window.location.href = url.toString();
258
- }, []);
259
- const logout = useCallback((options) => {
260
- if (isInternalMode()) {
261
- throw new Error('logout is not available in internal mode.');
262
- }
263
- localStorage.removeItem('zite.auth.token');
264
- queryClient.setQueryData(['zite.auth.user'], null);
265
- queryClient.removeQueries({ queryKey: ['zite.auth.user'] });
266
- if (window.top !== window.self) {
267
- debugLog('[zite/auth-sdk] sending auth.logout to parent');
268
- window.parent.postMessage({ type: 'auth.logout', data: {} }, '*');
269
- }
270
- if (options?.returnTo) {
271
- window.location.href = options.returnTo;
272
- }
273
- }, [queryClient]);
274
- return {
275
- user: userQuery.data ?? undefined,
276
- isLoading: userQuery.isPending,
277
- loginWithRedirect,
278
- logout,
279
- };
280
19
  }