zitejs 0.9.73 → 0.9.75

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