@rebasepro/client-firebase 0.0.1-canary.000dc36

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.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +4 -0
  3. package/dist/components/FirebaseLoginView.d.ts +72 -0
  4. package/dist/components/RebaseFirebaseApp.d.ts +19 -0
  5. package/dist/components/RebaseFirebaseAppProps.d.ts +144 -0
  6. package/dist/components/index.d.ts +3 -0
  7. package/dist/components/social_icons.d.ts +6 -0
  8. package/dist/hooks/index.d.ts +8 -0
  9. package/dist/hooks/useAppCheck.d.ts +20 -0
  10. package/dist/hooks/useBuildUserManagement.d.ts +46 -0
  11. package/dist/hooks/useFirebaseAuthController.d.ts +15 -0
  12. package/dist/hooks/useFirebaseRealTimeDBDelegate.d.ts +5 -0
  13. package/dist/hooks/useFirebaseStorageSource.d.ts +14 -0
  14. package/dist/hooks/useFirestoreDriver.d.ts +56 -0
  15. package/dist/hooks/useInitialiseFirebase.d.ts +34 -0
  16. package/dist/hooks/useRecaptcha.d.ts +8 -0
  17. package/dist/index.d.ts +4 -0
  18. package/dist/index.es.js +3059 -0
  19. package/dist/index.es.js.map +1 -0
  20. package/dist/index.umd.js +3043 -0
  21. package/dist/index.umd.js.map +1 -0
  22. package/dist/social_icons.d.ts +6 -0
  23. package/dist/types/appcheck.d.ts +10 -0
  24. package/dist/types/auth.d.ts +41 -0
  25. package/dist/types/index.d.ts +3 -0
  26. package/dist/types/text_search.d.ts +39 -0
  27. package/dist/utils/algolia.d.ts +9 -0
  28. package/dist/utils/collections_firestore.d.ts +5 -0
  29. package/dist/utils/database.d.ts +2 -0
  30. package/dist/utils/index.d.ts +7 -0
  31. package/dist/utils/local_text_search_controller.d.ts +2 -0
  32. package/dist/utils/pinecone.d.ts +24 -0
  33. package/dist/utils/rebase_search_controller.d.ts +73 -0
  34. package/dist/utils/text_search_controller.d.ts +13 -0
  35. package/package.json +62 -0
  36. package/src/components/FirebaseLoginView.tsx +693 -0
  37. package/src/components/RebaseFirebaseApp.tsx +291 -0
  38. package/src/components/RebaseFirebaseAppProps.tsx +180 -0
  39. package/src/components/index.ts +3 -0
  40. package/src/components/social_icons.tsx +135 -0
  41. package/src/hooks/index.ts +8 -0
  42. package/src/hooks/useAppCheck.ts +101 -0
  43. package/src/hooks/useBuildUserManagement.tsx +374 -0
  44. package/src/hooks/useFirebaseAuthController.ts +334 -0
  45. package/src/hooks/useFirebaseRealTimeDBDelegate.ts +269 -0
  46. package/src/hooks/useFirebaseStorageSource.ts +207 -0
  47. package/src/hooks/useFirestoreDriver.ts +784 -0
  48. package/src/hooks/useInitialiseFirebase.ts +132 -0
  49. package/src/hooks/useRecaptcha.tsx +28 -0
  50. package/src/index.ts +4 -0
  51. package/src/social_icons.tsx +135 -0
  52. package/src/types/appcheck.ts +11 -0
  53. package/src/types/auth.tsx +74 -0
  54. package/src/types/index.ts +3 -0
  55. package/src/types/text_search.ts +42 -0
  56. package/src/utils/algolia.ts +27 -0
  57. package/src/utils/collections_firestore.ts +148 -0
  58. package/src/utils/database.ts +39 -0
  59. package/src/utils/index.ts +7 -0
  60. package/src/utils/local_text_search_controller.ts +143 -0
  61. package/src/utils/pinecone.ts +75 -0
  62. package/src/utils/rebase_search_controller.ts +357 -0
  63. package/src/utils/text_search_controller.ts +34 -0
@@ -0,0 +1,3059 @@
1
+ import React, { useState, useCallback, useRef, useEffect } from "react";
2
+ import { deepEqual } from "fast-equals";
3
+ import { getAuth, onAuthStateChanged, GoogleAuthProvider, signInWithPopup, signInWithEmailAndPassword, createUserWithEmailAndPassword, sendPasswordResetEmail, fetchSignInMethodsForEmail, signOut, signInAnonymously, signInWithPhoneNumber, OAuthProvider, FacebookAuthProvider, GithubAuthProvider, TwitterAuthProvider, RecaptchaVerifier, getMultiFactorResolver, PhoneMultiFactorGenerator, PhoneAuthProvider } from "@firebase/auth";
4
+ import { getStorage, ref, deleteObject, list, getDownloadURL, getMetadata, uploadBytesResumable } from "@firebase/storage";
5
+ import { getApps, deleteApp, initializeApp } from "@firebase/app";
6
+ import { getToken, initializeAppCheck } from "@firebase/app-check";
7
+ import { GeoPoint, EntityReference } from "@rebasepro/types";
8
+ import { getFirestore, query, collection, limit, getDocs, onSnapshot, deleteField, doc, GeoPoint as GeoPoint$1, Timestamp, vector, serverTimestamp, VectorValue, DocumentReference, where, orderBy, startAfter, getDoc, getCountFromServer, deleteDoc, setDoc } from "@firebase/firestore";
9
+ import { stripCollectionPath, COLLECTION_PATH_SEPARATOR, sortProperties, buildRebaseData } from "@rebasepro/common";
10
+ import Fuse from "fuse.js";
11
+ import { getFunctions, httpsCallable } from "@firebase/functions";
12
+ import { c } from "react-compiler-runtime";
13
+ import { getDatabase, query as query$1, ref as ref$1, orderByKey, startAt, limitToFirst, get, onValue, push, set, remove, orderByChild } from "@firebase/database";
14
+ import { removeUndefined } from "@rebasepro/utils";
15
+ import { jsx, Fragment, jsxs } from "react/jsx-runtime";
16
+ import { useModeController, ErrorView, useSnackbarController, RebaseLogo, useBrowserTitleAndIcon, useBuildModeController, useBuildAdminModeController, useBuildLocalConfigurationPersistence, useValidateAuthenticator, RebaseRoutes, Rebase, AdminModeControllerProvider, SnackbarProvider, ModeControllerProvider } from "@rebasepro/core";
17
+ import { useBuildCollectionRegistryController, useBuildUrlController, useBuildNavigationStateController, NavigationStateContext, UrlContext, CollectionRegistryContext, SideEntityProvider, RebaseRoute, Scaffold, AppBar, Drawer, SideDialogs } from "@rebasepro/admin";
18
+ import { iconSize, Button, cls, IconButton, Typography, TextField, CircularProgress, LoadingButton, CircularProgressCenter, CenteredView } from "@rebasepro/ui";
19
+ import { Navigate, Route, Outlet } from "react-router-dom";
20
+ import { MailIcon, PhoneIcon, UserIcon, ArrowLeftIcon } from "lucide-react";
21
+ const useFirebaseAuthController = ({
22
+ loading,
23
+ firebaseApp,
24
+ signInOptions,
25
+ onSignOut: onSignOutProp,
26
+ defineRolesFor
27
+ }) => {
28
+ const [loggedUser, setLoggedUser] = useState(void 0);
29
+ const [authError, setAuthError] = useState();
30
+ const [authProviderError, setAuthProviderError] = useState();
31
+ const [initialLoading, setInitialLoading] = useState(true);
32
+ const [authLoading, setAuthLoading] = useState(true);
33
+ const [loginSkipped, setLoginSkipped] = useState(false);
34
+ const [confirmationResult, setConfirmationResult] = useState();
35
+ const [userRoles, _setUserRoles] = useState();
36
+ const [extra, setExtra] = useState();
37
+ const setUserRoles = useCallback((roles) => {
38
+ const currentRoleIds = userRoles?.map((r) => r.id);
39
+ const newRoleIds = roles?.map((r_0) => r_0.id);
40
+ if (!deepEqual(currentRoleIds, newRoleIds)) {
41
+ _setUserRoles(roles);
42
+ }
43
+ }, [userRoles]);
44
+ const authRef = useRef(null);
45
+ const updateUser = useCallback(async (user, initialize) => {
46
+ if (loading) return;
47
+ if (defineRolesFor && user) {
48
+ setUserRoles(await defineRolesFor(user));
49
+ }
50
+ setLoggedUser(user);
51
+ setAuthLoading(false);
52
+ if (initialize) {
53
+ setInitialLoading(false);
54
+ }
55
+ }, [loading]);
56
+ const updateRoles = useCallback(async (user_0) => {
57
+ if (defineRolesFor && user_0) {
58
+ const userRoles_0 = await defineRolesFor(user_0);
59
+ if (!deepEqual(userRoles_0, userRoles_0)) {
60
+ setUserRoles(userRoles_0);
61
+ }
62
+ }
63
+ }, [defineRolesFor, userRoles]);
64
+ useEffect(() => {
65
+ if (updateRoles && loggedUser) {
66
+ updateRoles(loggedUser);
67
+ }
68
+ }, [updateRoles, loggedUser]);
69
+ useEffect(() => {
70
+ if (!firebaseApp) return;
71
+ try {
72
+ const auth = getAuth(firebaseApp);
73
+ authRef.current = auth;
74
+ setAuthError(void 0);
75
+ updateUser(auth.currentUser, false);
76
+ return onAuthStateChanged(auth, async (user_1) => {
77
+ console.debug("User state changed", user_1);
78
+ await updateUser(user_1, true);
79
+ }, (error) => setAuthProviderError(error));
80
+ } catch (e) {
81
+ setAuthError(e);
82
+ setInitialLoading(false);
83
+ return () => {
84
+ };
85
+ }
86
+ }, [firebaseApp, updateUser]);
87
+ useEffect(() => {
88
+ if (!loading && authRef.current) {
89
+ updateUser(authRef.current.currentUser, false);
90
+ }
91
+ }, [loading, updateUser]);
92
+ const getProviderOptions = useCallback((providerId) => {
93
+ return signInOptions?.find((option) => {
94
+ if (option === null) throw Error("useFirebaseAuthController");
95
+ if (typeof option === "object" && option.provider === providerId) return option;
96
+ return void 0;
97
+ });
98
+ }, []);
99
+ const googleLogin = useCallback(() => {
100
+ const provider = new GoogleAuthProvider();
101
+ const options = getProviderOptions("google.com");
102
+ if (options?.scopes) options.scopes.forEach((scope) => provider.addScope(scope));
103
+ if (options?.customParameters) {
104
+ provider.setCustomParameters(options.customParameters);
105
+ } else {
106
+ provider.setCustomParameters({
107
+ prompt: "select_account"
108
+ });
109
+ }
110
+ const auth_0 = authRef.current;
111
+ if (!auth_0) throw Error("No auth");
112
+ signInWithPopup(auth_0, provider).catch(setAuthProviderError);
113
+ }, [getProviderOptions]);
114
+ const getAuthToken = useCallback(async () => {
115
+ if (!loggedUser) throw Error("No client user is logged in");
116
+ if (!loggedUser.getIdToken) {
117
+ throw Error("No getIdToken method available");
118
+ }
119
+ return loggedUser.getIdToken?.();
120
+ }, [loggedUser]);
121
+ const emailPasswordLogin = useCallback((email, password) => {
122
+ const auth_1 = authRef.current;
123
+ if (!auth_1) throw Error("No auth");
124
+ setAuthLoading(true);
125
+ signInWithEmailAndPassword(auth_1, email, password).catch(setAuthProviderError).then(() => setAuthLoading(false));
126
+ }, []);
127
+ const createUserWithEmailAndPassword$1 = useCallback((email_0, password_0) => {
128
+ const auth_2 = authRef.current;
129
+ if (!auth_2) throw Error("No auth");
130
+ setAuthLoading(true);
131
+ createUserWithEmailAndPassword(auth_2, email_0, password_0).catch(setAuthProviderError).then(() => setAuthLoading(false));
132
+ }, []);
133
+ const sendPasswordResetEmail$1 = useCallback((email_1) => {
134
+ const auth_3 = authRef.current;
135
+ if (!auth_3) throw Error("No auth");
136
+ return sendPasswordResetEmail(auth_3, email_1);
137
+ }, []);
138
+ const fetchSignInMethodsForEmail$1 = useCallback((email_2) => {
139
+ const auth_4 = authRef.current;
140
+ if (!auth_4) throw Error("No auth");
141
+ setAuthLoading(true);
142
+ return fetchSignInMethodsForEmail(auth_4, email_2).then((res) => {
143
+ setAuthLoading(false);
144
+ return res;
145
+ });
146
+ }, []);
147
+ const onSignOut = useCallback(async () => {
148
+ const auth_5 = authRef.current;
149
+ if (!auth_5) throw Error("No auth");
150
+ await signOut(auth_5).then((_) => {
151
+ setLoggedUser(null);
152
+ setUserRoles(void 0);
153
+ setAuthProviderError(null);
154
+ onSignOutProp?.();
155
+ });
156
+ setLoginSkipped(false);
157
+ }, [onSignOutProp]);
158
+ const doOauthLogin = useCallback((auth_6, provider_0) => {
159
+ setAuthLoading(true);
160
+ signInWithPopup(auth_6, provider_0).catch(setAuthProviderError).then(() => setAuthLoading(false));
161
+ }, []);
162
+ const anonymousLogin = useCallback(() => {
163
+ const auth_7 = authRef.current;
164
+ if (!auth_7) throw Error("No auth");
165
+ setAuthLoading(true);
166
+ signInAnonymously(auth_7).catch(setAuthProviderError).then(() => setAuthLoading(false));
167
+ }, []);
168
+ const phoneLogin = useCallback((phone, applicationVerifier) => {
169
+ const auth_8 = authRef.current;
170
+ if (!auth_8) throw Error("No auth");
171
+ setAuthLoading(true);
172
+ return signInWithPhoneNumber(auth_8, phone, applicationVerifier).catch(setAuthProviderError).then((res_0) => {
173
+ setAuthLoading(false);
174
+ setConfirmationResult(res_0 ?? void 0);
175
+ });
176
+ }, []);
177
+ const appleLogin = useCallback(() => {
178
+ const provider_1 = new OAuthProvider("apple.com");
179
+ const options_0 = getProviderOptions("apple.com");
180
+ if (options_0?.scopes) options_0.scopes.forEach((scope_0) => provider_1.addScope(scope_0));
181
+ if (options_0?.customParameters) provider_1.setCustomParameters(options_0.customParameters);
182
+ const auth_9 = authRef.current;
183
+ if (!auth_9) throw Error("No auth");
184
+ doOauthLogin(auth_9, provider_1);
185
+ }, [doOauthLogin, getProviderOptions]);
186
+ const facebookLogin = useCallback(() => {
187
+ const provider_2 = new FacebookAuthProvider();
188
+ const options_1 = getProviderOptions("facebook.com");
189
+ if (options_1?.scopes) options_1.scopes.forEach((scope_1) => provider_2.addScope(scope_1));
190
+ if (options_1?.customParameters) provider_2.setCustomParameters(options_1.customParameters);
191
+ const auth_10 = authRef.current;
192
+ if (!auth_10) throw Error("No auth");
193
+ doOauthLogin(auth_10, provider_2);
194
+ }, [doOauthLogin, getProviderOptions]);
195
+ const githubLogin = useCallback(() => {
196
+ const provider_3 = new GithubAuthProvider();
197
+ const options_2 = getProviderOptions("github.com");
198
+ if (options_2?.scopes) options_2.scopes.forEach((scope_2) => provider_3.addScope(scope_2));
199
+ if (options_2?.customParameters) provider_3.setCustomParameters(options_2.customParameters);
200
+ const auth_11 = authRef.current;
201
+ if (!auth_11) throw Error("No auth");
202
+ doOauthLogin(auth_11, provider_3);
203
+ }, [doOauthLogin, getProviderOptions]);
204
+ const microsoftLogin = useCallback(() => {
205
+ const provider_4 = new OAuthProvider("microsoft.com");
206
+ const options_3 = getProviderOptions("microsoft.com");
207
+ if (options_3?.scopes) options_3.scopes.forEach((scope_3) => provider_4.addScope(scope_3));
208
+ if (options_3?.customParameters) provider_4.setCustomParameters(options_3.customParameters);
209
+ const auth_12 = authRef.current;
210
+ if (!auth_12) throw Error("No auth");
211
+ doOauthLogin(auth_12, provider_4);
212
+ }, [doOauthLogin, getProviderOptions]);
213
+ const twitterLogin = useCallback(() => {
214
+ const provider_5 = new TwitterAuthProvider();
215
+ const options_4 = getProviderOptions("twitter.com");
216
+ if (options_4?.customParameters) provider_5.setCustomParameters(options_4.customParameters);
217
+ const auth_13 = authRef.current;
218
+ if (!auth_13) throw Error("No auth");
219
+ doOauthLogin(auth_13, provider_5);
220
+ }, [doOauthLogin, getProviderOptions]);
221
+ const skipLogin = useCallback(() => {
222
+ setLoginSkipped(true);
223
+ setLoggedUser(null);
224
+ setUserRoles(void 0);
225
+ }, []);
226
+ const firebaseUserWrapper = loggedUser ? {
227
+ ...loggedUser,
228
+ roles: userRoles?.map((r_1) => r_1.id),
229
+ // User.roles is string[], keep Role[] internally only
230
+ firebaseUser: loggedUser
231
+ } : null;
232
+ return {
233
+ user: firebaseUserWrapper,
234
+ setUser: updateUser,
235
+ setUserRoles,
236
+ authProviderError,
237
+ authLoading,
238
+ initialLoading: loading || initialLoading,
239
+ signOut: onSignOut,
240
+ getAuthToken,
241
+ googleLogin,
242
+ skipLogin,
243
+ loginSkipped,
244
+ emailPasswordLogin,
245
+ createUserWithEmailAndPassword: createUserWithEmailAndPassword$1,
246
+ sendPasswordResetEmail: sendPasswordResetEmail$1,
247
+ fetchSignInMethodsForEmail: fetchSignInMethodsForEmail$1,
248
+ anonymousLogin,
249
+ phoneLogin,
250
+ appleLogin,
251
+ facebookLogin,
252
+ githubLogin,
253
+ microsoftLogin,
254
+ twitterLogin,
255
+ confirmationResult,
256
+ extra,
257
+ setExtra
258
+ };
259
+ };
260
+ function useFirebaseStorageSource({
261
+ firebaseApp,
262
+ bucketUrl
263
+ }) {
264
+ const projectId = firebaseApp?.options?.projectId;
265
+ const urlsCache = {};
266
+ return {
267
+ putObject({
268
+ file,
269
+ key,
270
+ metadata,
271
+ bucket
272
+ }) {
273
+ try {
274
+ if (!firebaseApp) throw Error("useFirebaseStorageSource Firebase not initialised");
275
+ const storageBucketUrl = bucket ?? bucketUrl;
276
+ const storage = getStorage(firebaseApp, storageBucketUrl);
277
+ if (!storage) throw Error("useFirebaseStorageSource Firebase not initialised");
278
+ const storageRef = ref(storage, key);
279
+ const uploadTask = uploadBytesResumable(storageRef, file, metadata);
280
+ return new Promise((resolve, reject) => {
281
+ let lastProgress = 0;
282
+ let timeoutId = null;
283
+ const clearTimeoutIfExists = () => {
284
+ if (timeoutId) {
285
+ clearTimeout(timeoutId);
286
+ timeoutId = null;
287
+ }
288
+ };
289
+ const setProgressTimeout = () => {
290
+ clearTimeoutIfExists();
291
+ timeoutId = setTimeout(() => {
292
+ uploadTask.cancel();
293
+ reject(new Error(`Upload failed - This is likely a CORS configuration issue. Make sure Firebase Storage is enabled in your project: https://console.firebase.google.com/u/0/project/${projectId}/storage. If it is, check Firebase Storage CORS settings.`));
294
+ }, 5e3);
295
+ };
296
+ setProgressTimeout();
297
+ uploadTask.on("state_changed", (snapshot) => {
298
+ const progress = snapshot.bytesTransferred / snapshot.totalBytes * 100;
299
+ if (progress > lastProgress) {
300
+ lastProgress = progress;
301
+ setProgressTimeout();
302
+ }
303
+ }, (error) => {
304
+ clearTimeoutIfExists();
305
+ console.error("Firebase Storage upload error:", error);
306
+ let errorMessage = "Unknown upload error";
307
+ if (error?.message) {
308
+ errorMessage = error.message;
309
+ } else if (typeof error === "string") {
310
+ errorMessage = error;
311
+ } else if (error?.code) {
312
+ errorMessage = error.code;
313
+ }
314
+ if (error?.code === "storage/unauthorized") {
315
+ reject(new Error("Unauthorized: Check Firebase Storage security rules"));
316
+ } else if (error?.code === "storage/canceled") {
317
+ reject(new Error("Upload canceled"));
318
+ } else if (error?.code === "storage/unknown" || !error?.code) {
319
+ reject(new Error("Upload failed - Check Firebase Storage CORS configuration or network connection"));
320
+ } else if (errorMessage.toLowerCase().includes("network")) {
321
+ reject(new Error("Network error: Check your internet connection"));
322
+ } else {
323
+ const newError = Object.assign(new Error(errorMessage), {
324
+ code: error?.code
325
+ });
326
+ reject(newError);
327
+ }
328
+ }, () => {
329
+ clearTimeoutIfExists();
330
+ const fullPath = uploadTask.snapshot.ref.fullPath;
331
+ const bucketName = uploadTask.snapshot.ref.bucket;
332
+ resolve({
333
+ key: fullPath,
334
+ bucket: bucketName,
335
+ storageUrl: `s3://${bucketName}/${fullPath}`
336
+ });
337
+ });
338
+ });
339
+ } catch (error) {
340
+ return Promise.reject(error);
341
+ }
342
+ },
343
+ async getObject(path, bucket) {
344
+ try {
345
+ if (!firebaseApp) throw Error("useFirebaseStorageSource Firebase not initialised");
346
+ const storageBucketUrl = bucket ?? bucketUrl;
347
+ const storage = getStorage(firebaseApp, storageBucketUrl);
348
+ if (!storage) throw Error("useFirebaseStorageSource Firebase not initialised");
349
+ const fileRef = ref(storage, path);
350
+ const url = await getDownloadURL(fileRef);
351
+ const response = await fetch(url);
352
+ const blob = await response.blob();
353
+ return new File([blob], path);
354
+ } catch (e) {
355
+ if (e?.code === "storage/object-not-found") return null;
356
+ throw e;
357
+ }
358
+ },
359
+ async getSignedUrl(storagePathOrUrl, bucket) {
360
+ if (!firebaseApp) throw Error("useFirebaseStorageSource Firebase not initialised");
361
+ let resolvedPathOrUrl = storagePathOrUrl;
362
+ let resolvedBucket = bucket;
363
+ const match = storagePathOrUrl.match(/^(s3|gs):\/\//);
364
+ if (match) {
365
+ const protocolLength = match[0].length;
366
+ const withoutProtocol = storagePathOrUrl.substring(protocolLength);
367
+ const firstSlash = withoutProtocol.indexOf("/");
368
+ if (firstSlash > 0) {
369
+ resolvedBucket = withoutProtocol.substring(0, firstSlash);
370
+ resolvedPathOrUrl = withoutProtocol.substring(firstSlash + 1);
371
+ }
372
+ }
373
+ const storageBucketUrl = resolvedBucket ?? bucketUrl;
374
+ const storage = getStorage(firebaseApp, storageBucketUrl);
375
+ if (!storage) throw Error("useFirebaseStorageSource Firebase not initialised");
376
+ if (urlsCache[storagePathOrUrl]) return urlsCache[storagePathOrUrl];
377
+ try {
378
+ const fileRef = ref(storage, resolvedPathOrUrl);
379
+ const [url, metadata] = await Promise.all([getDownloadURL(fileRef), getMetadata(fileRef)]);
380
+ const result = {
381
+ url,
382
+ metadata
383
+ };
384
+ urlsCache[storagePathOrUrl] = result;
385
+ return result;
386
+ } catch (e) {
387
+ if (e?.code === "storage/object-not-found") return {
388
+ url: null,
389
+ fileNotFound: true
390
+ };
391
+ throw e;
392
+ }
393
+ },
394
+ async listObjects(prefix, options) {
395
+ if (!firebaseApp) throw Error("useFirebaseStorageSource Firebase not initialised");
396
+ const storageBucketUrl = options?.bucket ?? bucketUrl;
397
+ const storage = getStorage(firebaseApp, storageBucketUrl);
398
+ if (!storage) throw Error("useFirebaseStorageSource Firebase not initialised");
399
+ const folderRef = ref(storage, prefix);
400
+ return await list(folderRef, {
401
+ maxResults: options?.maxResults,
402
+ pageToken: options?.pageToken
403
+ });
404
+ },
405
+ async deleteObject(path, bucket) {
406
+ if (!firebaseApp) throw Error("useFirebaseStorageSource Firebase not initialised");
407
+ const storageBucketUrl = bucket ?? bucketUrl;
408
+ const storage = getStorage(firebaseApp, storageBucketUrl);
409
+ if (!storage) throw Error("useFirebaseStorageSource Firebase not initialised");
410
+ const fileRef = ref(storage, path);
411
+ return deleteObject(fileRef);
412
+ }
413
+ };
414
+ }
415
+ const hostingError = "It seems like the provided Firebase config is not correct. If you \nare using the credentials provided automatically by Firebase \nHosting, make sure you link your Firebase app to Firebase Hosting. \n";
416
+ function useInitialiseFirebase({
417
+ firebaseConfig,
418
+ fromUrl,
419
+ onFirebaseInit,
420
+ name,
421
+ authDomain
422
+ }) {
423
+ const [firebaseApp, setFirebaseApp] = useState();
424
+ const [firebaseConfigLoading, setFirebaseConfigLoading] = useState(false);
425
+ const [configError, setConfigError] = useState();
426
+ const initFirebase = useCallback((config) => {
427
+ if (config.projectId === firebaseApp?.options.projectId) {
428
+ console.debug("Firebase app already initialised with the same project ID. This should happen only in development mode.");
429
+ setConfigError(void 0);
430
+ setFirebaseConfigLoading(false);
431
+ return;
432
+ }
433
+ try {
434
+ const targetName = name ?? "[DEFAULT]";
435
+ const currentApps = getApps();
436
+ const existingApp = currentApps.find((app) => app.name === targetName);
437
+ if (existingApp) {
438
+ deleteApp(existingApp);
439
+ }
440
+ const initialisedFirebaseApp = initializeApp(config, targetName);
441
+ setConfigError(void 0);
442
+ setFirebaseConfigLoading(false);
443
+ setFirebaseApp(initialisedFirebaseApp);
444
+ } catch (e) {
445
+ console.error("Error initialising Firebase", e);
446
+ setConfigError(hostingError + "\n" + (e.message ?? JSON.stringify(e)));
447
+ }
448
+ }, [name]);
449
+ useEffect(() => {
450
+ if (onFirebaseInit && firebaseConfig && firebaseApp) {
451
+ onFirebaseInit(firebaseConfig, firebaseApp);
452
+ }
453
+ }, [firebaseApp]);
454
+ useEffect(() => {
455
+ setFirebaseConfigLoading(true);
456
+ function fetchFromUrl(url) {
457
+ fetch(url).then(async (response) => {
458
+ console.debug("Firebase init response", response.status);
459
+ if (response && response.status < 300) {
460
+ const config_0 = await response.json();
461
+ if (authDomain) config_0.authDomain = authDomain;
462
+ initFirebase(config_0);
463
+ }
464
+ }).catch((e_0) => {
465
+ setFirebaseConfigLoading(false);
466
+ setConfigError("Could not load Firebase configuration from Firebase hosting. If the app is not deployed in Firebase hosting, you need to specify the configuration manually" + e_0.toString());
467
+ });
468
+ }
469
+ if (firebaseConfig) {
470
+ initFirebase(firebaseConfig);
471
+ } else {
472
+ if (fromUrl) {
473
+ fetchFromUrl(fromUrl);
474
+ } else if (process.env.NODE_ENV === "production") {
475
+ fetchFromUrl("/__/firebase/init.json");
476
+ } else {
477
+ setFirebaseConfigLoading(false);
478
+ setConfigError("You need to deploy the app to Firebase hosting or specify a Firebase configuration object");
479
+ }
480
+ }
481
+ }, []);
482
+ return {
483
+ firebaseApp,
484
+ firebaseConfigLoading,
485
+ configError
486
+ };
487
+ }
488
+ function useAppCheck({
489
+ firebaseApp,
490
+ options
491
+ }) {
492
+ if (options?.debugToken) {
493
+ Object.assign(window, {
494
+ FIREBASE_APPCHECK_DEBUG_TOKEN: options?.debugToken
495
+ });
496
+ }
497
+ const [appCheckLoading, setAppCheckLoading] = React.useState(false);
498
+ const [appCheckVerified, setAppCheckVerified] = React.useState(void 0);
499
+ const [error, setError] = React.useState();
500
+ const initialCheck = useRef(false);
501
+ const verifyToken = useCallback(async (appCheck) => {
502
+ console.debug("Verifying App Check token...", appCheck);
503
+ try {
504
+ const token = await getToken(appCheck, options?.forceRefresh);
505
+ console.debug("App Check token:", token);
506
+ if (!token) {
507
+ setError("App Check failed.");
508
+ setAppCheckVerified(false);
509
+ } else {
510
+ setAppCheckVerified(true);
511
+ console.debug("App Check success.");
512
+ }
513
+ } catch (e) {
514
+ console.error("App Check error:", e);
515
+ setError(e.message);
516
+ }
517
+ }, [options?.forceRefresh]);
518
+ useEffect(() => {
519
+ if (!options) return;
520
+ if (!firebaseApp) return;
521
+ if (appCheckVerified !== void 0) return;
522
+ if (initialCheck.current) return;
523
+ setAppCheckLoading(true);
524
+ const {
525
+ provider,
526
+ isTokenAutoRefreshEnabled
527
+ } = options;
528
+ removeCurrentAppCheckDiv();
529
+ const appCheck_0 = initializeAppCheck(firebaseApp, {
530
+ provider,
531
+ isTokenAutoRefreshEnabled
532
+ });
533
+ verifyToken(appCheck_0).then(() => {
534
+ setAppCheckLoading(false);
535
+ });
536
+ initialCheck.current = true;
537
+ }, [appCheckVerified, firebaseApp, options, verifyToken]);
538
+ return {
539
+ loading: appCheckLoading,
540
+ appCheckVerified,
541
+ error
542
+ };
543
+ }
544
+ function removeCurrentAppCheckDiv() {
545
+ const div = document.getElementById("fire_app_check_[DEFAULT]");
546
+ if (div) {
547
+ div.remove();
548
+ }
549
+ }
550
+ function buildCollectionId(idOrPath, parentCollectionSlugs, parentEntityIds) {
551
+ if (!parentCollectionSlugs) return stripCollectionPath(idOrPath);
552
+ return [...parentCollectionSlugs.map(stripCollectionPath), stripCollectionPath(idOrPath)].join(COLLECTION_PATH_SEPARATOR);
553
+ }
554
+ const docsToCollectionTree = (docs) => {
555
+ const collectionsMap = docs.map((doc2) => {
556
+ const id = doc2.id;
557
+ const collection2 = docToCollection(doc2);
558
+ return {
559
+ [id]: collection2
560
+ };
561
+ }).reduce((a, b) => ({
562
+ ...a,
563
+ ...b
564
+ }), {});
565
+ const orderedKeys = Object.keys(collectionsMap).sort((a, b) => b.split(COLLECTION_PATH_SEPARATOR).length - a.split(COLLECTION_PATH_SEPARATOR).length);
566
+ orderedKeys.forEach((id) => {
567
+ const collection2 = collectionsMap[id];
568
+ if (id.includes(COLLECTION_PATH_SEPARATOR)) {
569
+ const parentId = id.split(COLLECTION_PATH_SEPARATOR).slice(0, -1).join(COLLECTION_PATH_SEPARATOR);
570
+ const parentCollection = collectionsMap[parentId];
571
+ if (parentCollection) parentCollection.subcollections = () => [...parentCollection.subcollections?.() ?? [], collection2];
572
+ delete collectionsMap[id];
573
+ }
574
+ });
575
+ return Object.values(collectionsMap);
576
+ };
577
+ const docToCollection = (doc2) => {
578
+ const data = doc2.data();
579
+ if (!data) throw Error("Entity collection has not been persisted correctly");
580
+ const propertiesOrder = data.propertiesOrder;
581
+ const properties = data.properties ?? {};
582
+ const normalizedProperties = normalizePropertiesEnumValues(properties, true);
583
+ const sortedProperties = sortProperties(normalizedProperties, propertiesOrder);
584
+ return {
585
+ ...data,
586
+ properties: sortedProperties,
587
+ slug: data.id ?? data.alias ?? data.slug
588
+ };
589
+ };
590
+ function normalizeEnumValuesToArray(enumValues, sortObjectFormat = false) {
591
+ if (Array.isArray(enumValues)) {
592
+ return enumValues;
593
+ } else if (typeof enumValues === "object" && enumValues !== null) {
594
+ const entries = Object.entries(enumValues).map(([id, value]) => typeof value === "string" ? {
595
+ id,
596
+ label: value
597
+ } : {
598
+ ...value,
599
+ id
600
+ });
601
+ if (sortObjectFormat) {
602
+ entries.sort((a, b) => String(a.id).localeCompare(String(b.id)));
603
+ }
604
+ return entries;
605
+ }
606
+ return [];
607
+ }
608
+ function normalizePropertiesEnumValues(properties, sortObjectFormat = false) {
609
+ const result = {};
610
+ Object.entries(properties).forEach(([key, property]) => {
611
+ if (typeof property === "object" && property !== null) {
612
+ const normalizedProperty = {
613
+ ...property
614
+ };
615
+ if (normalizedProperty.enum) {
616
+ normalizedProperty.enum = normalizeEnumValuesToArray(normalizedProperty.enum, sortObjectFormat);
617
+ }
618
+ if (normalizedProperty.dataType === "array" && typeof normalizedProperty.of === "object" && normalizedProperty.of !== null) {
619
+ const ofProp = normalizedProperty.of;
620
+ if (ofProp.enum) {
621
+ normalizedProperty.of = {
622
+ ...ofProp,
623
+ enum: normalizeEnumValuesToArray(ofProp.enum, sortObjectFormat)
624
+ };
625
+ }
626
+ }
627
+ if (normalizedProperty.dataType === "map" && normalizedProperty.properties) {
628
+ normalizedProperty.properties = normalizePropertiesEnumValues(normalizedProperty.properties, sortObjectFormat);
629
+ }
630
+ result[key] = normalizedProperty;
631
+ } else {
632
+ result[key] = property;
633
+ }
634
+ });
635
+ return result;
636
+ }
637
+ async function getFirestoreDataInPath(firebaseApp, path, parentPaths, limit$1) {
638
+ const firestore = getFirestore(firebaseApp);
639
+ if (!parentPaths || parentPaths.length === 0) {
640
+ const q = query(collection(firestore, path), limit(limit$1));
641
+ return getDocs(q).then((querySnapshot) => {
642
+ return querySnapshot.docs.map((doc2) => doc2.data());
643
+ });
644
+ } else {
645
+ let currentDocs = void 0;
646
+ let index = 0;
647
+ const allPaths = parentPaths;
648
+ allPaths.push(path);
649
+ let parentPath = allPaths[0];
650
+ while (parentPath) {
651
+ if (currentDocs) {
652
+ currentDocs = (await Promise.all(currentDocs.map(async (doc2) => {
653
+ const q = query(collection(firestore, doc2.ref.path, parentPath), limit(5));
654
+ return (await getDocs(q)).docs;
655
+ }))).flat();
656
+ } else {
657
+ const q = query(collection(firestore, parentPath), limit(5));
658
+ currentDocs = (await getDocs(q)).docs;
659
+ }
660
+ index++;
661
+ parentPath = index < allPaths.length ? allPaths[index] : void 0;
662
+ }
663
+ return currentDocs ? currentDocs.map((doc2) => doc2.data()) : [];
664
+ }
665
+ }
666
+ function performAlgoliaTextSearch(client, indexName, query2) {
667
+ console.debug("Performing Algolia query", client, query2);
668
+ return client.searchSingleIndex({
669
+ indexName,
670
+ searchParams: {
671
+ query: query2
672
+ }
673
+ }).then(({
674
+ hits
675
+ }) => {
676
+ return hits.map((hit) => hit.objectID);
677
+ }).catch((err) => {
678
+ console.error(err);
679
+ return [];
680
+ });
681
+ }
682
+ const DEFAULT_SERVER = "https://api.rebase.pro";
683
+ async function performPineconeTextSearch({
684
+ host = DEFAULT_SERVER,
685
+ firebaseToken,
686
+ projectId,
687
+ collectionPath,
688
+ query: query2
689
+ }) {
690
+ console.debug("Performing Pinecone query", collectionPath, query2);
691
+ const response = await fetch((host ?? DEFAULT_SERVER) + `/projects/${projectId}/search/${collectionPath}`, {
692
+ // mode: "no-cors",
693
+ method: "POST",
694
+ headers: {
695
+ "Content-Type": "application/json",
696
+ Authorization: `Basic ${firebaseToken}`
697
+ // "x-de-version": version
698
+ },
699
+ body: JSON.stringify({
700
+ query: query2
701
+ })
702
+ });
703
+ const promise = await response.json();
704
+ return promise.data.ids;
705
+ }
706
+ function buildPineconeSearchController({
707
+ isPathSupported,
708
+ search
709
+ }) {
710
+ return (props) => {
711
+ const init = (props2) => {
712
+ return Promise.resolve(isPathSupported(props2.path));
713
+ };
714
+ return {
715
+ init,
716
+ search
717
+ };
718
+ };
719
+ }
720
+ function buildExternalSearchController({
721
+ isPathSupported,
722
+ search
723
+ }) {
724
+ return (props) => {
725
+ const init = (props2) => {
726
+ return Promise.resolve(isPathSupported(props2.path));
727
+ };
728
+ return {
729
+ init,
730
+ search
731
+ };
732
+ };
733
+ }
734
+ const MAX_SEARCH_RESULTS = 80;
735
+ const localSearchControllerBuilder = ({
736
+ firebaseApp
737
+ }) => {
738
+ let currentPath;
739
+ const indexes = {};
740
+ const listeners = {};
741
+ const destroyListener = (path) => {
742
+ if (listeners[path]) {
743
+ listeners[path]();
744
+ delete listeners[path];
745
+ delete indexes[path];
746
+ }
747
+ };
748
+ const init = ({
749
+ path,
750
+ collection: collectionProp,
751
+ databaseId
752
+ }) => {
753
+ if (currentPath && path !== currentPath) {
754
+ destroyListener(currentPath);
755
+ }
756
+ currentPath = path;
757
+ return new Promise(async (resolve, reject) => {
758
+ if (collectionProp) {
759
+ console.debug("Init local search controller", path);
760
+ const firestore = databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp);
761
+ const col = collection(firestore, path);
762
+ listeners[path] = onSnapshot(query(col), {
763
+ next: (snapshot) => {
764
+ if (snapshot.metadata.fromCache && snapshot.metadata.hasPendingWrites) {
765
+ return;
766
+ }
767
+ const docs = snapshot.docs.map((doc2) => ({
768
+ id: doc2.id,
769
+ ...doc2.data()
770
+ }));
771
+ indexes[path] = buildIndex(docs, collectionProp);
772
+ console.debug("Added docs to index", path, docs.length);
773
+ resolve(true);
774
+ },
775
+ error: (e) => {
776
+ console.error("Error initializing local search controller", path);
777
+ console.error(e);
778
+ reject(e);
779
+ }
780
+ });
781
+ }
782
+ });
783
+ };
784
+ const search = async ({
785
+ searchString,
786
+ path
787
+ }) => {
788
+ console.debug("Searching local index", path, searchString);
789
+ const index = indexes[path];
790
+ if (!index) {
791
+ throw new Error(`Index not found for path ${path}`);
792
+ }
793
+ let searchResult = index.search(searchString);
794
+ searchResult = searchResult.splice(0, MAX_SEARCH_RESULTS);
795
+ searchResult = searchResult.sort((a, b) => {
796
+ const aExactMatch = a.item.id === searchString;
797
+ const bExactMatch = b.item.id === searchString;
798
+ if (aExactMatch && !bExactMatch) {
799
+ return -1;
800
+ } else if (!aExactMatch && bExactMatch) {
801
+ return 1;
802
+ } else {
803
+ return (a.score ?? 0) - (b.score ?? 0);
804
+ }
805
+ });
806
+ return searchResult.map((e) => e.item.id);
807
+ };
808
+ return {
809
+ init,
810
+ search
811
+ };
812
+ };
813
+ function buildIndex(list2, collection2) {
814
+ const keys = ["id", ...Object.keys(collection2.properties)];
815
+ const fuseOptions = {
816
+ // isCaseSensitive: false,
817
+ // includeScore: false,
818
+ // shouldSort: true,
819
+ // includeMatches: false,
820
+ // findAllMatches: false,
821
+ // minMatchCharLength: 1,
822
+ // location: 0,
823
+ threshold: 0.6,
824
+ // distance: 100,
825
+ // useExtendedSearch: false,
826
+ // ignoreLocation: false,
827
+ // ignoreFieldNorm: false,
828
+ // fieldNormWeight: 1,
829
+ includeScore: true,
830
+ keys: [{
831
+ name: "title",
832
+ weight: 1
833
+ }, ...keys.map((key) => ({
834
+ name: key,
835
+ weight: 0.5
836
+ }))]
837
+ };
838
+ return new Fuse(list2, fuseOptions);
839
+ }
840
+ function buildRebaseSearchController(options) {
841
+ const region = options?.region || "us-central1";
842
+ const extensionInstanceId = options?.extensionInstanceId || "typesense-search";
843
+ let searchConfig = null;
844
+ let typesenseClient = null;
845
+ let initPromise = null;
846
+ return ({
847
+ firebaseApp
848
+ }) => {
849
+ const initializeClient = async () => {
850
+ if (typesenseClient) return;
851
+ if (options?.customConfig) {
852
+ searchConfig = {
853
+ host: options.customConfig.host,
854
+ port: options.customConfig.port || 443,
855
+ protocol: options.customConfig.protocol || "https",
856
+ apiKey: options.customConfig.apiKey,
857
+ path: options.customConfig.path,
858
+ collectionsToIndex: ["*"]
859
+ };
860
+ } else {
861
+ const functions = getFunctions(firebaseApp, region);
862
+ const getConfig = httpsCallable(functions, `ext-${extensionInstanceId}-getSearchConfig`);
863
+ try {
864
+ const result = await getConfig();
865
+ searchConfig = result.data;
866
+ if (options?.collections && options.collections.length > 0) {
867
+ searchConfig.collectionsToIndex = options.collections;
868
+ }
869
+ } catch (error) {
870
+ console.error("Failed to get search config from extension:", error);
871
+ throw new Error(`Failed to initialize Rebase Search. Make sure the rebase-search extension is installed and configured. Error: ${error.message || error}`);
872
+ }
873
+ }
874
+ if (!searchConfig) {
875
+ throw new Error("Search config not available");
876
+ }
877
+ const Typesense = (await import("typesense")).default;
878
+ typesenseClient = new Typesense.Client({
879
+ nodes: [{
880
+ host: searchConfig.host,
881
+ port: searchConfig.port,
882
+ protocol: searchConfig.protocol,
883
+ path: searchConfig.path || ""
884
+ }],
885
+ apiKey: searchConfig.apiKey,
886
+ connectionTimeoutSeconds: 5,
887
+ retryIntervalSeconds: 0.5,
888
+ numRetries: 2
889
+ });
890
+ };
891
+ const getTypesenseCollectionName = (path) => {
892
+ const pathParts = path.split("/");
893
+ const collectionNames = [];
894
+ for (let i = 0; i < pathParts.length; i += 2) {
895
+ if (pathParts[i]) {
896
+ collectionNames.push(pathParts[i]);
897
+ }
898
+ }
899
+ return collectionNames.join("_");
900
+ };
901
+ const getParentFilter = (path) => {
902
+ const pathParts = path.split("/");
903
+ if (pathParts.length <= 1) return null;
904
+ const filters = [];
905
+ for (let i = 0; i < pathParts.length - 1; i += 2) {
906
+ const collectionName = pathParts[i];
907
+ const docId = pathParts[i + 1];
908
+ if (collectionName && docId) {
909
+ filters.push(`_parent_${collectionName}_id:=${docId}`);
910
+ }
911
+ }
912
+ return filters.length > 0 ? filters.join(" && ") : null;
913
+ };
914
+ const init = async (props) => {
915
+ try {
916
+ if (!initPromise) {
917
+ initPromise = initializeClient();
918
+ }
919
+ await initPromise;
920
+ if (!searchConfig) return false;
921
+ const pathParts = props.path.split("/");
922
+ const collectionNames = [];
923
+ for (let i = 0; i < pathParts.length; i += 2) {
924
+ if (pathParts[i]) collectionNames.push(pathParts[i]);
925
+ }
926
+ const collectionPattern = collectionNames.join("/");
927
+ const rootCollection = collectionNames[0];
928
+ if (searchConfig.collectionsToIndex.includes("*")) {
929
+ return true;
930
+ }
931
+ return searchConfig.collectionsToIndex.includes(collectionPattern) || searchConfig.collectionsToIndex.includes(rootCollection);
932
+ } catch (error) {
933
+ console.error("Failed to initialize Rebase Search:", error);
934
+ return false;
935
+ }
936
+ };
937
+ const schemaCache = /* @__PURE__ */ new Map();
938
+ const getSearchableFieldsFromSchema = async (collectionName) => {
939
+ if (schemaCache.has(collectionName)) {
940
+ return schemaCache.get(collectionName);
941
+ }
942
+ try {
943
+ const collection2 = await typesenseClient.collections(collectionName).retrieve();
944
+ const stringFields = collection2.fields.filter((f) => {
945
+ const isStringType = f.type === "string" || f.type === "string[]" || f.type === "string*" || f.type === "auto";
946
+ const isNotInternal = !f.name.startsWith("_") && f.name !== ".*";
947
+ return isStringType && isNotInternal;
948
+ }).map((f) => f.name);
949
+ schemaCache.set(collectionName, stringFields);
950
+ return stringFields;
951
+ } catch (error) {
952
+ if (error.httpStatus === 404) {
953
+ throw new Error(`Collection "${collectionName}" not found in Typesense. Make sure the collection has been indexed. Try running the backfill function.`);
954
+ }
955
+ throw error;
956
+ }
957
+ };
958
+ const search = async (props) => {
959
+ if (!typesenseClient) {
960
+ if (!initPromise) {
961
+ initPromise = initializeClient();
962
+ }
963
+ await initPromise;
964
+ }
965
+ if (!typesenseClient) {
966
+ throw new Error("Typesense client not initialized. Check extension configuration.");
967
+ }
968
+ const collectionName = getTypesenseCollectionName(props.path);
969
+ const parentFilter = getParentFilter(props.path);
970
+ const searchableFields = await getSearchableFieldsFromSchema(collectionName);
971
+ if (searchableFields.length === 0) {
972
+ throw new Error(`No searchable string fields found in Typesense collection "${collectionName}". Make sure some documents have been indexed with string fields.`);
973
+ }
974
+ const queryBy = searchableFields.join(",");
975
+ try {
976
+ const searchParams = {
977
+ q: props.searchString,
978
+ query_by: queryBy,
979
+ per_page: 100,
980
+ prefix: true,
981
+ // Enable prefix matching
982
+ typo_tokens_threshold: 1
983
+ // Allow some typos
984
+ };
985
+ if (parentFilter) {
986
+ searchParams.filter_by = parentFilter;
987
+ }
988
+ const result = await typesenseClient.collections(collectionName).documents().search(searchParams);
989
+ const ids = result.hits?.map((hit) => hit.document.id) ?? [];
990
+ return ids;
991
+ } catch (error) {
992
+ const message = error.message || error.toString();
993
+ throw new Error(`Search failed: ${message}`);
994
+ }
995
+ };
996
+ return {
997
+ init,
998
+ search
999
+ };
1000
+ };
1001
+ }
1002
+ function useFirestoreDriver({
1003
+ firebaseApp,
1004
+ textSearchControllerBuilder,
1005
+ firestoreIndexesBuilder,
1006
+ localTextSearchEnabled
1007
+ }) {
1008
+ const searchControllerRef = useRef(void 0);
1009
+ useEffect(() => {
1010
+ if (!searchControllerRef.current && firebaseApp) {
1011
+ if ((textSearchControllerBuilder || localTextSearchEnabled) && !searchControllerRef.current) {
1012
+ searchControllerRef.current = buildTextSearchControllerWithLocalSearch({
1013
+ firebaseApp,
1014
+ textSearchControllerBuilder,
1015
+ localTextSearchEnabled: localTextSearchEnabled ?? false
1016
+ });
1017
+ }
1018
+ }
1019
+ }, [firebaseApp, localTextSearchEnabled, textSearchControllerBuilder]);
1020
+ const buildQuery = useCallback((path, filter, orderBy$1, order, startAfter$1, limit$1, databaseId) => {
1021
+ if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
1022
+ const firestore = databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp);
1023
+ const collectionReference = collection(firestore, path);
1024
+ const queryParams = [];
1025
+ if (filter) {
1026
+ Object.entries(filter).filter(([_, entry]) => !!entry).forEach(([key, filterParameter]) => {
1027
+ const [op, value] = filterParameter;
1028
+ queryParams.push(where(key, op, cmsToFirestoreModel(value, firestore)));
1029
+ });
1030
+ }
1031
+ if (orderBy$1 && order) {
1032
+ queryParams.push(orderBy(orderBy$1, order));
1033
+ }
1034
+ if (startAfter$1) {
1035
+ queryParams.push(startAfter(startAfter$1));
1036
+ }
1037
+ if (limit$1) {
1038
+ queryParams.push(limit(limit$1));
1039
+ }
1040
+ return query(collectionReference, ...queryParams);
1041
+ }, [firebaseApp]);
1042
+ const getAndBuildEntity = useCallback((path_0, entityId, databaseId_0) => {
1043
+ if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
1044
+ const firestore_0 = databaseId_0 ? getFirestore(firebaseApp, databaseId_0) : getFirestore(firebaseApp);
1045
+ return getDoc(doc(firestore_0, path_0, String(entityId))).then((docSnapshot) => {
1046
+ if (!docSnapshot.exists()) {
1047
+ return void 0;
1048
+ }
1049
+ return createEntityFromDocument(docSnapshot, databaseId_0);
1050
+ });
1051
+ }, [firebaseApp]);
1052
+ const listenEntity = useCallback(({
1053
+ path: path_1,
1054
+ entityId: entityId_0,
1055
+ collection: collection2,
1056
+ onUpdate,
1057
+ onError
1058
+ }) => {
1059
+ if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
1060
+ const databaseId_1 = collection2?.databaseId;
1061
+ const firestore_1 = databaseId_1 ? getFirestore(firebaseApp, databaseId_1) : getFirestore(firebaseApp);
1062
+ const resolvedPath = path_1;
1063
+ return onSnapshot(doc(firestore_1, resolvedPath, String(entityId_0)), {
1064
+ next: (docSnapshot_0) => {
1065
+ onUpdate(createEntityFromDocument(docSnapshot_0, databaseId_1));
1066
+ },
1067
+ error: onError
1068
+ });
1069
+ }, [firebaseApp]);
1070
+ const performTextSearch = useCallback(({
1071
+ path: path_2,
1072
+ databaseId: databaseId_2,
1073
+ searchString,
1074
+ onUpdate: onUpdate_0
1075
+ }) => {
1076
+ if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
1077
+ const textSearchController = searchControllerRef.current;
1078
+ if (!textSearchController) throw Error("Trying to make text search without specifying a FirestoreTextSearchController");
1079
+ let subscriptions = [];
1080
+ const auth = getAuth(firebaseApp);
1081
+ const currentUser = auth?.currentUser;
1082
+ const search = textSearchController.search({
1083
+ path: path_2,
1084
+ searchString,
1085
+ currentUser: currentUser ?? void 0,
1086
+ databaseId: databaseId_2
1087
+ });
1088
+ if (!search) {
1089
+ throw Error("The current path is not supported by the specified FirestoreTextSearchController");
1090
+ }
1091
+ search.then((ids) => {
1092
+ if (!ids || ids.length === 0) {
1093
+ subscriptions = [];
1094
+ onUpdate_0([]);
1095
+ }
1096
+ const entities = [];
1097
+ const addedEntitiesSet = /* @__PURE__ */ new Set();
1098
+ subscriptions = (ids ?? []).map((entityId_1) => {
1099
+ return listenEntity({
1100
+ path: path_2,
1101
+ entityId: entityId_1,
1102
+ onUpdate: (entity) => {
1103
+ if (entity?.values) {
1104
+ if (entity.id && !addedEntitiesSet.has(entity.id)) {
1105
+ addedEntitiesSet.add(entity.id);
1106
+ entities.push(entity);
1107
+ onUpdate_0(entities);
1108
+ }
1109
+ } else if (entity?.id) {
1110
+ addedEntitiesSet.delete(entity.id);
1111
+ onUpdate_0([...entities.filter((e) => e.id !== entityId_1)]);
1112
+ }
1113
+ }
1114
+ });
1115
+ });
1116
+ });
1117
+ return () => {
1118
+ subscriptions.forEach((p) => p());
1119
+ };
1120
+ }, [firebaseApp, listenEntity]);
1121
+ return {
1122
+ key: "firestore",
1123
+ currentTime,
1124
+ initialised: Boolean(firebaseApp),
1125
+ initTextSearch: useCallback(async (props) => {
1126
+ console.debug("Init text search controller", searchControllerRef.current, props.path);
1127
+ if (!searchControllerRef.current) {
1128
+ console.warn("You are trying to use text search, but have not provided a text search controller in `useFirestoreDriver`. You can also set the flag `localTextSearchEnabled` to use local search in `useFirestoreDriver`. Local text search can incur in performance issues and higher costs for large datasets.");
1129
+ return false;
1130
+ }
1131
+ try {
1132
+ return searchControllerRef.current.init(props);
1133
+ } catch (e_0) {
1134
+ console.error("Error initializing text search controller", e_0);
1135
+ return false;
1136
+ }
1137
+ }, []),
1138
+ /**
1139
+ * Fetch entities in a Firestore path
1140
+ * @param path
1141
+ * @param collection
1142
+ * @param filter
1143
+ * @param limit
1144
+ * @param startAfter
1145
+ * @param searchString
1146
+ * @param orderBy
1147
+ * @param order
1148
+ * @return Function to cancel subscription
1149
+ * @see useCollectionFetch if you need this functionality implemented as a hook
1150
+ * @group Firestore
1151
+ */
1152
+ fetchCollection: useCallback(async ({
1153
+ path: path_3,
1154
+ filter: filter_0,
1155
+ limit: limit_0,
1156
+ startAfter: startAfter_0,
1157
+ searchString: searchString_0,
1158
+ orderBy: orderBy_0,
1159
+ order: order_0,
1160
+ collection: collection_0
1161
+ }) => {
1162
+ const databaseId_3 = collection_0?.databaseId;
1163
+ const resolvedPath_0 = path_3;
1164
+ console.debug("Fetching collection", {
1165
+ path: path_3,
1166
+ limit: limit_0,
1167
+ filter: filter_0,
1168
+ startAfter: startAfter_0,
1169
+ orderBy: orderBy_0,
1170
+ order: order_0
1171
+ });
1172
+ const query2 = buildQuery(resolvedPath_0, filter_0, orderBy_0, order_0, startAfter_0, limit_0, databaseId_3);
1173
+ const snapshot = await getDocs(query2);
1174
+ return snapshot.docs.map((doc2) => createEntityFromDocument(doc2, databaseId_3));
1175
+ }, [buildQuery]),
1176
+ /**
1177
+ * Listen to a entities in a given path
1178
+ * @param path
1179
+ * @param collection
1180
+ * @param onError
1181
+ * @param filter
1182
+ * @param limit
1183
+ * @param startAfter
1184
+ * @param searchString
1185
+ * @param orderBy
1186
+ * @param order
1187
+ * @param onUpdate
1188
+ * @return Function to cancel subscription
1189
+ * @see useCollectionFetch if you need this functionality implemented as a hook
1190
+ * @group Firestore
1191
+ */
1192
+ listenCollection: useCallback(({
1193
+ path: path_4,
1194
+ filter: filter_1,
1195
+ limit: limit_1,
1196
+ startAfter: startAfter_1,
1197
+ searchString: searchString_1,
1198
+ orderBy: orderBy_1,
1199
+ order: order_1,
1200
+ onUpdate: onUpdate_1,
1201
+ onError: onError_0,
1202
+ collection: collection_1
1203
+ }) => {
1204
+ console.debug("Listening collection", {
1205
+ path: path_4,
1206
+ searchString: searchString_1,
1207
+ limit: limit_1,
1208
+ filter: filter_1,
1209
+ startAfter: startAfter_1,
1210
+ orderBy: orderBy_1,
1211
+ order: order_1,
1212
+ collection: collection_1
1213
+ });
1214
+ if (!firebaseApp) {
1215
+ throw Error("useFirestoreDriver Firebase not initialised");
1216
+ }
1217
+ const databaseId_4 = collection_1?.databaseId;
1218
+ if (searchString_1) {
1219
+ return performTextSearch({
1220
+ path: path_4,
1221
+ searchString: searchString_1,
1222
+ onUpdate: onUpdate_1,
1223
+ databaseId: databaseId_4
1224
+ });
1225
+ }
1226
+ const resolvedPath_1 = path_4;
1227
+ console.debug("Resolved path for listening", {
1228
+ path: path_4,
1229
+ resolvedPath: resolvedPath_1
1230
+ });
1231
+ const query_0 = buildQuery(resolvedPath_1, filter_1, orderBy_1, order_1, startAfter_1, limit_1, databaseId_4);
1232
+ return onSnapshot(query_0, {
1233
+ next: (snapshot_0) => {
1234
+ if (!searchString_1) onUpdate_1(snapshot_0.docs.map((doc_0) => createEntityFromDocument(doc_0, databaseId_4)));
1235
+ },
1236
+ error: onError_0
1237
+ });
1238
+ }, [buildQuery, firebaseApp, performTextSearch]),
1239
+ /**
1240
+ * Retrieve an entity given a path and a collection
1241
+ * @param path
1242
+ * @param entityId
1243
+ * @param collection
1244
+ * @group Firestore
1245
+ */
1246
+ fetchEntity: useCallback(({
1247
+ path: path_5,
1248
+ entityId: entityId_2,
1249
+ collection: collection_2
1250
+ }) => {
1251
+ const resolvedPath_2 = path_5;
1252
+ return getAndBuildEntity(resolvedPath_2, entityId_2, collection_2?.databaseId);
1253
+ }, [getAndBuildEntity]),
1254
+ /**
1255
+ *
1256
+ * @param path
1257
+ * @param entityId
1258
+ * @param collection
1259
+ * @param onUpdate
1260
+ * @param onError
1261
+ * @return Function to cancel subscription
1262
+ * @group Firestore
1263
+ */
1264
+ listenEntity,
1265
+ /**
1266
+ * Save entity to the specified path. Note that Firestore does not allow
1267
+ * undefined values.
1268
+ * @param path
1269
+ * @param entityId
1270
+ * @param values
1271
+ * @param schemaId
1272
+ * @param collection
1273
+ * @param status
1274
+ * @group Firestore
1275
+ */
1276
+ saveEntity: useCallback(({
1277
+ path: path_6,
1278
+ entityId: entityId_3,
1279
+ values: valuesProp,
1280
+ collection: collection_3,
1281
+ status
1282
+ }) => {
1283
+ if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
1284
+ console.debug("1", {
1285
+ path: path_6,
1286
+ entityId: entityId_3,
1287
+ values: valuesProp,
1288
+ collection: collection_3
1289
+ });
1290
+ const values = cmsToFirestoreModel(valuesProp, getFirestore(firebaseApp));
1291
+ console.debug("2", {
1292
+ path: path_6,
1293
+ entityId: entityId_3,
1294
+ values: valuesProp,
1295
+ collection: collection_3
1296
+ });
1297
+ const databaseId_5 = collection_3?.databaseId;
1298
+ const firestore_2 = databaseId_5 ? getFirestore(firebaseApp, databaseId_5) : getFirestore(firebaseApp);
1299
+ const collectionReference_0 = collection(firestore_2, path_6);
1300
+ console.debug("Saving entity", {
1301
+ path: path_6,
1302
+ entityId: entityId_3,
1303
+ values,
1304
+ databaseId: databaseId_5
1305
+ });
1306
+ let documentReference;
1307
+ if (entityId_3) {
1308
+ documentReference = doc(collectionReference_0, String(entityId_3));
1309
+ } else {
1310
+ documentReference = doc(collectionReference_0);
1311
+ }
1312
+ return setDoc(documentReference, values, {
1313
+ merge: true
1314
+ }).then(() => {
1315
+ return {
1316
+ id: documentReference.id,
1317
+ path: path_6,
1318
+ values: firestoreToCMSModel(values)
1319
+ };
1320
+ }).catch((error) => {
1321
+ console.error("Error saving entity", error);
1322
+ throw error;
1323
+ });
1324
+ }, [firebaseApp]),
1325
+ /**
1326
+ * Delete an entity
1327
+ * @param entity
1328
+ * @param collection
1329
+ * @group Firestore
1330
+ */
1331
+ deleteEntity: useCallback(({
1332
+ entity: entity_0
1333
+ }) => {
1334
+ if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
1335
+ const databaseId_6 = entity_0.databaseId;
1336
+ const firestore_3 = databaseId_6 ? getFirestore(firebaseApp, databaseId_6) : getFirestore(firebaseApp);
1337
+ return deleteDoc(doc(firestore_3, entity_0.path, String(entity_0.id)));
1338
+ }, [firebaseApp]),
1339
+ /**
1340
+ * Check if the given property is unique in the given collection
1341
+ * @param path Collection path
1342
+ * @param name of the property
1343
+ * @param value
1344
+ * @param property
1345
+ * @param entityId
1346
+ * @return `true` if there are no other fields besides the given entity
1347
+ * @group Firestore
1348
+ */
1349
+ checkUniqueField: useCallback(async (path_7, name, value_0, entityId_4, collection_4) => {
1350
+ if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
1351
+ const databaseId_7 = collection_4?.databaseId;
1352
+ const firestore_4 = databaseId_7 ? getFirestore(firebaseApp, databaseId_7) : getFirestore(firebaseApp);
1353
+ if (value_0 === void 0 || value_0 === null) {
1354
+ return Promise.resolve(true);
1355
+ }
1356
+ const q = query(collection(firestore_4, path_7), where(name, "==", cmsToFirestoreModel(value_0, firestore_4)));
1357
+ const snapshot_1 = await getDocs(q);
1358
+ return snapshot_1.docs.filter((doc_1) => doc_1.id !== entityId_4).length === 0;
1359
+ }, [firebaseApp]),
1360
+ countEntities: useCallback(async ({
1361
+ path: path_8,
1362
+ filter: filter_2,
1363
+ order: order_2,
1364
+ orderBy: orderBy_2,
1365
+ collection: collection_5
1366
+ }) => {
1367
+ if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
1368
+ const databaseId_8 = collection_5?.databaseId;
1369
+ const resolvedPath_4 = path_8;
1370
+ const query_1 = buildQuery(resolvedPath_4, filter_2, orderBy_2, order_2, void 0, void 0, databaseId_8);
1371
+ const snapshot_2 = await getCountFromServer(query_1);
1372
+ return snapshot_2.data().count;
1373
+ }, [firebaseApp]),
1374
+ isFilterCombinationValid: useCallback(({
1375
+ path: path_9,
1376
+ collection: collection_6,
1377
+ filterValues,
1378
+ sortBy
1379
+ }) => {
1380
+ if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
1381
+ if (firestoreIndexesBuilder === void 0) return true;
1382
+ const resolvedPath_5 = path_9;
1383
+ const indexes = firestoreIndexesBuilder?.({
1384
+ path: resolvedPath_5,
1385
+ collection: collection_6
1386
+ });
1387
+ const sortKey = sortBy ? sortBy[0] : void 0;
1388
+ const sortDirection = sortBy ? sortBy[1] : void 0;
1389
+ const values_0 = Object.values(filterValues);
1390
+ const filterKeys = Object.keys(filterValues);
1391
+ const filtersCount = filterKeys.length;
1392
+ if (!sortKey && values_0.every((v) => v[0] === "==")) {
1393
+ return true;
1394
+ }
1395
+ if (filtersCount === 1 && (!sortKey || sortKey === filterKeys[0])) {
1396
+ return true;
1397
+ }
1398
+ if (!indexes && filtersCount > 1) {
1399
+ return false;
1400
+ }
1401
+ return !!indexes && indexes.filter((compositeIndex) => !sortKey || sortKey in compositeIndex).find((compositeIndex_0) => Object.entries(filterValues).every(([key_0, value_1]) => compositeIndex_0[key_0] !== void 0 && (!sortDirection || compositeIndex_0[key_0] === sortDirection))) !== void 0;
1402
+ }, [firebaseApp])
1403
+ };
1404
+ }
1405
+ const createEntityFromDocument = (docSnap, databaseId) => {
1406
+ const values = firestoreToCMSModel(docSnap.data());
1407
+ const path = getCMSPathFromFirestorePath(docSnap.ref.path);
1408
+ return {
1409
+ id: docSnap.id,
1410
+ path,
1411
+ values,
1412
+ databaseId
1413
+ };
1414
+ };
1415
+ function firestoreToCMSModel(data) {
1416
+ if (data === null || data === void 0) return null;
1417
+ if (deleteField().isEqual(data)) {
1418
+ return void 0;
1419
+ }
1420
+ if (serverTimestamp().isEqual(data)) {
1421
+ return null;
1422
+ }
1423
+ if (data instanceof Timestamp || typeof data.toDate === "function" && data.toDate() instanceof Date) {
1424
+ return data.toDate();
1425
+ }
1426
+ if (data instanceof Date) {
1427
+ return data;
1428
+ }
1429
+ if (typeof data === "object" && "__type__" in data && data.__type__ === "__vector__") {
1430
+ return data;
1431
+ }
1432
+ if (data instanceof VectorValue || typeof data === "object" && data !== null && typeof data.toArray === "function" && data.constructor?.name === "VectorValue") {
1433
+ return {
1434
+ __type__: "__vector__",
1435
+ value: data.toArray()
1436
+ };
1437
+ }
1438
+ if (data instanceof GeoPoint$1) {
1439
+ return new GeoPoint(data.latitude, data.longitude);
1440
+ }
1441
+ if (data instanceof DocumentReference) {
1442
+ const databaseId = data?.firestore?._databaseId?.database;
1443
+ return new EntityReference({
1444
+ id: data.id,
1445
+ path: getCMSPathFromFirestorePath(data.path),
1446
+ databaseId
1447
+ });
1448
+ }
1449
+ if (Array.isArray(data)) {
1450
+ return data.map(firestoreToCMSModel).filter((v) => v !== void 0);
1451
+ }
1452
+ if (typeof data === "object") {
1453
+ const result = {};
1454
+ for (const key of Object.keys(data)) {
1455
+ const childValue = firestoreToCMSModel(data[key]);
1456
+ if (childValue !== void 0) result[key] = childValue;
1457
+ }
1458
+ return result;
1459
+ }
1460
+ return data;
1461
+ }
1462
+ function getCMSPathFromFirestorePath(fsPath) {
1463
+ let to = fsPath.lastIndexOf("/");
1464
+ to = to === -1 ? fsPath.length : to;
1465
+ return fsPath.substring(0, to);
1466
+ }
1467
+ function cmsToFirestoreModel(data, firestore, inArray = false) {
1468
+ if (data === void 0) {
1469
+ return deleteField();
1470
+ } else if (data === null) {
1471
+ return null;
1472
+ } else if (Array.isArray(data)) {
1473
+ return data.filter((v) => v !== void 0).map((v) => cmsToFirestoreModel(v, firestore, true));
1474
+ } else if (data.isEntityReference && data.isEntityReference()) {
1475
+ const targetFirestore = data.databaseId ? getFirestore(firestore.app, data.databaseId) : firestore;
1476
+ return doc(targetFirestore, data.path, data.id);
1477
+ } else if (data && typeof data === "object" && data.__type === "relation" && data.path && data.id) {
1478
+ return doc(firestore, data.path, String(data.id));
1479
+ } else if (data instanceof GeoPoint) {
1480
+ return new GeoPoint$1(data.latitude, data.longitude);
1481
+ } else if (data instanceof Date) {
1482
+ return Timestamp.fromDate(data);
1483
+ } else if (data && typeof data === "object" && "__type__" in data && data.__type__ === "__vector__") {
1484
+ return vector(data.value || []);
1485
+ } else if (data && typeof data === "object") {
1486
+ return Object.entries(data).map(([key, v]) => {
1487
+ const firestoreModel = cmsToFirestoreModel(v, firestore);
1488
+ if (firestoreModel !== void 0) return {
1489
+ [key]: firestoreModel
1490
+ };
1491
+ else return {};
1492
+ }).reduce((a, b) => ({
1493
+ ...a,
1494
+ ...b
1495
+ }), {});
1496
+ }
1497
+ return data;
1498
+ }
1499
+ function currentTime() {
1500
+ return serverTimestamp();
1501
+ }
1502
+ function buildTextSearchControllerWithLocalSearch({
1503
+ textSearchControllerBuilder,
1504
+ firebaseApp,
1505
+ localTextSearchEnabled
1506
+ }) {
1507
+ if (!textSearchControllerBuilder && localTextSearchEnabled) {
1508
+ console.debug("Using local search only");
1509
+ return localSearchControllerBuilder({
1510
+ firebaseApp
1511
+ });
1512
+ }
1513
+ if (!localTextSearchEnabled && textSearchControllerBuilder) {
1514
+ console.debug("Using external text search only");
1515
+ return textSearchControllerBuilder({
1516
+ firebaseApp
1517
+ });
1518
+ }
1519
+ if (!textSearchControllerBuilder && !localTextSearchEnabled) {
1520
+ return void 0;
1521
+ }
1522
+ const localSearchController = localSearchControllerBuilder({
1523
+ firebaseApp
1524
+ });
1525
+ const textSearchController = textSearchControllerBuilder({
1526
+ firebaseApp
1527
+ });
1528
+ return {
1529
+ init: async (props) => {
1530
+ const b = await textSearchController.init(props);
1531
+ if (b) {
1532
+ console.debug("External Text search controller supports path", props.path);
1533
+ return true;
1534
+ }
1535
+ if (localTextSearchEnabled) return localSearchController.init(props);
1536
+ return false;
1537
+ },
1538
+ search: async (props) => {
1539
+ const search = await textSearchController.search(props);
1540
+ return search ?? await localSearchController.search(props);
1541
+ }
1542
+ };
1543
+ }
1544
+ function useFirebaseRTDBDelegate(t0) {
1545
+ const $ = c(22);
1546
+ const {
1547
+ firebaseApp
1548
+ } = t0;
1549
+ let t1;
1550
+ if ($[0] !== firebaseApp) {
1551
+ t1 = async (t22) => {
1552
+ const {
1553
+ path,
1554
+ limit: limit2,
1555
+ startAfter: startAfter2
1556
+ } = t22;
1557
+ if (!firebaseApp) {
1558
+ throw new Error("Firebase app not provided");
1559
+ }
1560
+ const database = getDatabase(firebaseApp);
1561
+ let dbQuery = query$1(ref$1(database, path));
1562
+ if (startAfter2 !== void 0) {
1563
+ dbQuery = query$1(dbQuery, orderByKey(), startAt(String(startAfter2)));
1564
+ }
1565
+ if (limit2 !== void 0) {
1566
+ dbQuery = query$1(dbQuery, limitToFirst(limit2));
1567
+ }
1568
+ const snapshot = await get(dbQuery);
1569
+ if (snapshot.exists()) {
1570
+ return Object.entries(snapshot.val()).map((t32) => {
1571
+ const [id, values] = t32;
1572
+ return {
1573
+ id,
1574
+ path,
1575
+ values: delegateToCMSModel(values)
1576
+ };
1577
+ });
1578
+ }
1579
+ return [];
1580
+ };
1581
+ $[0] = firebaseApp;
1582
+ $[1] = t1;
1583
+ } else {
1584
+ t1 = $[1];
1585
+ }
1586
+ const fetchCollection = t1;
1587
+ let t2;
1588
+ if ($[2] !== firebaseApp) {
1589
+ t2 = (t32) => {
1590
+ const {
1591
+ path: path_0,
1592
+ onUpdate
1593
+ } = t32;
1594
+ if (!firebaseApp) {
1595
+ throw new Error("Firebase app not provided");
1596
+ }
1597
+ const database_0 = getDatabase(firebaseApp);
1598
+ const dbRef = ref$1(database_0, path_0);
1599
+ const unsubscribe = onValue(dbRef, (snapshot_0) => {
1600
+ if (snapshot_0.exists()) {
1601
+ const result = Object.entries(snapshot_0.val()).map((t42) => {
1602
+ const [id_0, values_0] = t42;
1603
+ return {
1604
+ id: id_0,
1605
+ path: path_0,
1606
+ values: delegateToCMSModel(values_0)
1607
+ };
1608
+ });
1609
+ onUpdate(result);
1610
+ } else {
1611
+ onUpdate([]);
1612
+ }
1613
+ });
1614
+ return () => unsubscribe();
1615
+ };
1616
+ $[2] = firebaseApp;
1617
+ $[3] = t2;
1618
+ } else {
1619
+ t2 = $[3];
1620
+ }
1621
+ const listenCollection = t2;
1622
+ let t3;
1623
+ if ($[4] !== firebaseApp) {
1624
+ t3 = async (t42) => {
1625
+ const {
1626
+ path: path_1,
1627
+ entityId
1628
+ } = t42;
1629
+ if (!firebaseApp) {
1630
+ throw new Error("Firebase app not provided");
1631
+ }
1632
+ const database_1 = getDatabase(firebaseApp);
1633
+ const snapshot_1 = await get(ref$1(database_1, `${path_1}/${entityId}`));
1634
+ if (snapshot_1.exists()) {
1635
+ return {
1636
+ id: entityId,
1637
+ path: path_1,
1638
+ values: delegateToCMSModel(snapshot_1.val())
1639
+ };
1640
+ }
1641
+ };
1642
+ $[4] = firebaseApp;
1643
+ $[5] = t3;
1644
+ } else {
1645
+ t3 = $[5];
1646
+ }
1647
+ const fetchEntity = t3;
1648
+ let t4;
1649
+ if ($[6] !== firebaseApp) {
1650
+ t4 = (t52) => {
1651
+ const {
1652
+ path: path_2,
1653
+ entityId: entityId_0,
1654
+ onUpdate: onUpdate_0,
1655
+ onError
1656
+ } = t52;
1657
+ if (!firebaseApp) {
1658
+ throw new Error("Firebase app not provided");
1659
+ }
1660
+ const database_2 = getDatabase(firebaseApp);
1661
+ const dbRef_0 = ref$1(database_2, `${path_2}/${entityId_0}`);
1662
+ const unsubscribe_0 = onValue(dbRef_0, (snapshot_2) => {
1663
+ if (snapshot_2.exists()) {
1664
+ onUpdate_0({
1665
+ id: entityId_0,
1666
+ path: path_2,
1667
+ values: delegateToCMSModel(snapshot_2.val())
1668
+ });
1669
+ } else {
1670
+ onError?.(new Error("Entity does not exist"));
1671
+ }
1672
+ });
1673
+ return () => unsubscribe_0();
1674
+ };
1675
+ $[6] = firebaseApp;
1676
+ $[7] = t4;
1677
+ } else {
1678
+ t4 = $[7];
1679
+ }
1680
+ const listenEntity = t4;
1681
+ let t5;
1682
+ if ($[8] !== firebaseApp) {
1683
+ t5 = async (t62) => {
1684
+ const {
1685
+ path: path_3,
1686
+ entityId: entityId_1,
1687
+ values: values_1
1688
+ } = t62;
1689
+ if (!firebaseApp) {
1690
+ throw new Error("Firebase app not provided");
1691
+ }
1692
+ const database_3 = getDatabase(firebaseApp);
1693
+ const finalId = entityId_1 ?? push(ref$1(database_3, path_3)).key;
1694
+ if (!finalId) {
1695
+ throw new Error("Could not generate a new id");
1696
+ }
1697
+ const transformedValues = cmsToRTDBModel(values_1, database_3);
1698
+ await set(ref$1(database_3, `${path_3}/${finalId}`), transformedValues);
1699
+ return {
1700
+ id: finalId,
1701
+ path: path_3,
1702
+ values: values_1
1703
+ };
1704
+ };
1705
+ $[8] = firebaseApp;
1706
+ $[9] = t5;
1707
+ } else {
1708
+ t5 = $[9];
1709
+ }
1710
+ const saveEntity = t5;
1711
+ let t6;
1712
+ if ($[10] !== firebaseApp) {
1713
+ t6 = async (t72) => {
1714
+ const {
1715
+ entity
1716
+ } = t72;
1717
+ if (!firebaseApp) {
1718
+ throw new Error("Firebase app not provided");
1719
+ }
1720
+ const database_4 = getDatabase(firebaseApp);
1721
+ await remove(ref$1(database_4, `${entity.path}/${entity.id}`));
1722
+ };
1723
+ $[10] = firebaseApp;
1724
+ $[11] = t6;
1725
+ } else {
1726
+ t6 = $[11];
1727
+ }
1728
+ const deleteEntity = t6;
1729
+ let t7;
1730
+ if ($[12] !== firebaseApp) {
1731
+ t7 = async (slug, name, value, entityId_2) => {
1732
+ if (!firebaseApp) {
1733
+ throw new Error("Firebase app not provided");
1734
+ }
1735
+ const database_5 = getDatabase(firebaseApp);
1736
+ const dbRef_1 = query$1(ref$1(database_5, slug), orderByChild(name), startAt(value), limitToFirst(1));
1737
+ const snapshot_3 = await get(dbRef_1);
1738
+ if (!snapshot_3.exists()) {
1739
+ return true;
1740
+ }
1741
+ const [key, entityValue] = Object.entries(snapshot_3.val())[0];
1742
+ if (entityValue && typeof entityValue === "object" && entityValue[name] === value && key === entityId_2) {
1743
+ return true;
1744
+ }
1745
+ return false;
1746
+ };
1747
+ $[12] = firebaseApp;
1748
+ $[13] = t7;
1749
+ } else {
1750
+ t7 = $[13];
1751
+ }
1752
+ const checkUniqueField = t7;
1753
+ const isFilterCombinationValid = _temp$2;
1754
+ let t8;
1755
+ if ($[14] !== checkUniqueField || $[15] !== deleteEntity || $[16] !== fetchCollection || $[17] !== fetchEntity || $[18] !== listenCollection || $[19] !== listenEntity || $[20] !== saveEntity) {
1756
+ t8 = {
1757
+ key: "firebase_rtdb",
1758
+ fetchCollection,
1759
+ listenCollection,
1760
+ fetchEntity,
1761
+ listenEntity,
1762
+ saveEntity,
1763
+ deleteEntity,
1764
+ checkUniqueField,
1765
+ isFilterCombinationValid,
1766
+ currentTime: _temp2$1
1767
+ };
1768
+ $[14] = checkUniqueField;
1769
+ $[15] = deleteEntity;
1770
+ $[16] = fetchCollection;
1771
+ $[17] = fetchEntity;
1772
+ $[18] = listenCollection;
1773
+ $[19] = listenEntity;
1774
+ $[20] = saveEntity;
1775
+ $[21] = t8;
1776
+ } else {
1777
+ t8 = $[21];
1778
+ }
1779
+ return t8;
1780
+ }
1781
+ function _temp2$1() {
1782
+ return /* @__PURE__ */ new Date();
1783
+ }
1784
+ function _temp$2(t0) {
1785
+ return false;
1786
+ }
1787
+ function delegateToCMSModel(data) {
1788
+ if (data === null || data === void 0) return null;
1789
+ if (Array.isArray(data)) {
1790
+ return data.map(delegateToCMSModel).filter((v) => v !== void 0);
1791
+ }
1792
+ if (typeof data === "object") {
1793
+ const result = {};
1794
+ for (const key of Object.keys(data)) {
1795
+ const childValue = delegateToCMSModel(data[key]);
1796
+ if (childValue !== void 0) result[key] = childValue;
1797
+ }
1798
+ return result;
1799
+ }
1800
+ return data;
1801
+ }
1802
+ function cmsToRTDBModel(data, database) {
1803
+ if (data === void 0) {
1804
+ return null;
1805
+ } else if (data === null) {
1806
+ return null;
1807
+ } else if (Array.isArray(data)) {
1808
+ return data.filter((v) => v !== void 0).map((v) => cmsToRTDBModel(v, database));
1809
+ } else if (data.isEntityReference && data.isEntityReference()) {
1810
+ return ref$1(database, `${data.slug}/${data.id}`);
1811
+ } else if (data instanceof Date) {
1812
+ return data.toISOString();
1813
+ } else if (data && typeof data === "object") {
1814
+ return Object.entries(data).map(([key, v]) => {
1815
+ const rtdbModel = cmsToRTDBModel(v, database);
1816
+ if (rtdbModel !== void 0) return {
1817
+ [key]: rtdbModel
1818
+ };
1819
+ else return {};
1820
+ }).reduce((a, b) => ({
1821
+ ...a,
1822
+ ...b
1823
+ }), {});
1824
+ }
1825
+ return data;
1826
+ }
1827
+ const RECAPTCHA_CONTAINER_ID = "recaptcha-container";
1828
+ function useRecaptcha() {
1829
+ const $ = c(1);
1830
+ let t0;
1831
+ if ($[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
1832
+ t0 = [];
1833
+ $[0] = t0;
1834
+ } else {
1835
+ t0 = $[0];
1836
+ }
1837
+ useEffect(_temp$1, t0);
1838
+ return null;
1839
+ }
1840
+ function _temp$1() {
1841
+ if (!window || window?.recaptchaVerifier) {
1842
+ return;
1843
+ }
1844
+ const auth = getAuth();
1845
+ window.recaptchaVerifier = new RecaptchaVerifier(auth, RECAPTCHA_CONTAINER_ID, {
1846
+ size: "invisible"
1847
+ });
1848
+ }
1849
+ function useBuildUserManagement({
1850
+ authController,
1851
+ dataSourceDelegate,
1852
+ roles: rolesProp,
1853
+ usersPath = "__FIRECMS/config/users",
1854
+ rolesPath = "__FIRECMS/config/roles",
1855
+ allowDefaultRolesCreation,
1856
+ includeCollectionConfigPermissions
1857
+ }) {
1858
+ if (!authController) {
1859
+ throw Error("useBuildUserManagement: You need to provide an authController since version 3.0.0-beta.11. Check https://firecms.co/docs/pro/migrating_from_v3_beta");
1860
+ }
1861
+ const rolesDefinedInCode = (rolesProp ?? [])?.length > 0;
1862
+ const [rolesLoading, setRolesLoading] = React.useState(!rolesDefinedInCode);
1863
+ const [usersLoading, setUsersLoading] = React.useState(true);
1864
+ const [roles, setRoles] = React.useState(rolesProp ?? []);
1865
+ const [usersWithRoleIds, setUsersWithRoleIds] = React.useState([]);
1866
+ const users = usersWithRoleIds.map((u) => ({
1867
+ ...u
1868
+ }));
1869
+ const [rolesError, setRolesError] = React.useState();
1870
+ const [usersError, setUsersError] = React.useState();
1871
+ const _usersLoading = usersLoading;
1872
+ const _rolesLoading = rolesLoading;
1873
+ const loading = _rolesLoading || _usersLoading;
1874
+ useEffect(() => {
1875
+ if (rolesDefinedInCode) return;
1876
+ if (!dataSourceDelegate || !rolesPath) return;
1877
+ if (dataSourceDelegate.initialised !== void 0 && !dataSourceDelegate.initialised) return;
1878
+ if (authController?.initialLoading) return;
1879
+ setRolesLoading(true);
1880
+ return dataSourceDelegate.listenCollection?.({
1881
+ path: rolesPath,
1882
+ onUpdate(entities) {
1883
+ setRolesError(void 0);
1884
+ console.debug("Updating roles", entities);
1885
+ try {
1886
+ const newRoles = entityToRoles(entities);
1887
+ if (!deepEqual(newRoles, roles)) {
1888
+ setRoles(newRoles);
1889
+ }
1890
+ } catch (e) {
1891
+ setRoles([]);
1892
+ console.error("Error loading roles", e);
1893
+ setRolesError(e);
1894
+ }
1895
+ setRolesLoading(false);
1896
+ },
1897
+ onError(e_0) {
1898
+ setRoles([]);
1899
+ console.error("Error loading roles", e_0);
1900
+ setRolesError(e_0);
1901
+ setRolesLoading(false);
1902
+ }
1903
+ });
1904
+ }, [rolesDefinedInCode, dataSourceDelegate?.initialised, authController?.initialLoading, authController?.user?.uid, rolesPath]);
1905
+ useEffect(() => {
1906
+ if (!dataSourceDelegate || !usersPath) return;
1907
+ if (dataSourceDelegate.initialised !== void 0 && !dataSourceDelegate.initialised) {
1908
+ return;
1909
+ }
1910
+ if (authController?.initialLoading) {
1911
+ return;
1912
+ }
1913
+ setUsersLoading(true);
1914
+ return dataSourceDelegate.listenCollection?.({
1915
+ path: usersPath,
1916
+ onUpdate(entities_0) {
1917
+ console.debug("Updating users", entities_0);
1918
+ setUsersError(void 0);
1919
+ try {
1920
+ const newUsers = entitiesToUsers(entities_0);
1921
+ setUsersWithRoleIds(newUsers);
1922
+ } catch (e_1) {
1923
+ setUsersWithRoleIds([]);
1924
+ console.error("Error loading users", e_1);
1925
+ setUsersError(e_1);
1926
+ }
1927
+ setUsersLoading(false);
1928
+ },
1929
+ onError(e_2) {
1930
+ console.error("Error loading users", e_2);
1931
+ setUsersWithRoleIds([]);
1932
+ setUsersError(e_2);
1933
+ setUsersLoading(false);
1934
+ }
1935
+ });
1936
+ }, [dataSourceDelegate?.initialised, authController?.initialLoading, authController?.user?.uid, usersPath]);
1937
+ const saveUser = useCallback(async (user) => {
1938
+ if (!dataSourceDelegate) throw Error("useBuildUserManagement Firebase not initialised");
1939
+ if (!usersPath) throw Error("useBuildUserManagement Firestore not initialised");
1940
+ console.debug("Persisting user", user);
1941
+ const roleIds = user.roles;
1942
+ const email = user.email?.toLowerCase().trim();
1943
+ if (!email) throw Error("Email is required");
1944
+ const userExists = users.find((u_0) => u_0.email?.toLowerCase() === email);
1945
+ const data = {
1946
+ ...user,
1947
+ roles: roleIds ?? []
1948
+ };
1949
+ if (!userExists) {
1950
+ data.created_on = /* @__PURE__ */ new Date();
1951
+ }
1952
+ if (userExists && userExists.uid !== user.uid) {
1953
+ const entity = {
1954
+ values: {},
1955
+ path: usersPath,
1956
+ id: userExists.uid
1957
+ };
1958
+ await dataSourceDelegate.deleteEntity({
1959
+ entity
1960
+ }).then(() => {
1961
+ console.debug("Deleted previous user", userExists);
1962
+ }).catch((e_3) => {
1963
+ console.error("Error deleting user", e_3);
1964
+ });
1965
+ }
1966
+ return dataSourceDelegate.saveEntity({
1967
+ status: "existing",
1968
+ path: usersPath,
1969
+ entityId: email,
1970
+ values: removeUndefined(data)
1971
+ }).then(() => user);
1972
+ }, [usersPath, dataSourceDelegate?.initialised]);
1973
+ const saveRole = useCallback((role) => {
1974
+ if (!dataSourceDelegate) throw Error("useBuildUserManagement Firebase not initialised");
1975
+ if (!rolesPath) throw Error("useBuildUserManagement Firestore not initialised");
1976
+ console.debug("Persisting role", role);
1977
+ const {
1978
+ id,
1979
+ ...roleData
1980
+ } = role;
1981
+ return dataSourceDelegate.saveEntity({
1982
+ status: "existing",
1983
+ path: rolesPath,
1984
+ entityId: id,
1985
+ values: removeUndefined(roleData)
1986
+ }).then(() => {
1987
+ return;
1988
+ });
1989
+ }, [rolesPath, dataSourceDelegate?.initialised]);
1990
+ const deleteUser = useCallback(async (user_0) => {
1991
+ if (!dataSourceDelegate) throw Error("useBuildUserManagement Firebase not initialised");
1992
+ if (!usersPath) throw Error("useBuildUserManagement Firestore not initialised");
1993
+ console.debug("Deleting", user_0);
1994
+ const {
1995
+ uid
1996
+ } = user_0;
1997
+ const entity_0 = {
1998
+ path: usersPath,
1999
+ id: uid,
2000
+ values: {}
2001
+ };
2002
+ await dataSourceDelegate.deleteEntity({
2003
+ entity: entity_0
2004
+ });
2005
+ }, [usersPath, dataSourceDelegate?.initialised]);
2006
+ const deleteRole = useCallback(async (role_0) => {
2007
+ if (!dataSourceDelegate) throw Error("useBuildUserManagement Firebase not initialised");
2008
+ if (!rolesPath) throw Error("useBuildUserManagement Firestore not initialised");
2009
+ console.debug("Deleting", role_0);
2010
+ const {
2011
+ id: id_0
2012
+ } = role_0;
2013
+ const entity_1 = {
2014
+ path: rolesPath,
2015
+ id: id_0,
2016
+ values: {}
2017
+ };
2018
+ await dataSourceDelegate.deleteEntity({
2019
+ entity: entity_1
2020
+ });
2021
+ }, [rolesPath, dataSourceDelegate?.initialised]);
2022
+ const defineRolesFor = useCallback((user_1) => {
2023
+ if (!usersWithRoleIds) throw Error("Users not loaded");
2024
+ const mgmtUser = usersWithRoleIds.find((u_1) => u_1.email?.toLowerCase() === user_1?.email?.toLowerCase());
2025
+ if (!mgmtUser || !mgmtUser.roles) return void 0;
2026
+ return roles.filter((r) => mgmtUser.roles.includes(r.id));
2027
+ }, [roles, usersWithRoleIds]);
2028
+ const authenticator = useCallback(({
2029
+ user: user_2
2030
+ }) => {
2031
+ if (loading) {
2032
+ return false;
2033
+ }
2034
+ if (user_2 === null) {
2035
+ console.warn("User is null, returning");
2036
+ return false;
2037
+ }
2038
+ if (users.length === 0) {
2039
+ console.warn("No users created yet");
2040
+ return true;
2041
+ }
2042
+ const mgmtUser_0 = users.find((u_2) => u_2.email?.toLowerCase() === user_2?.email?.toLowerCase());
2043
+ if (mgmtUser_0) {
2044
+ const needsUidUpdate = mgmtUser_0.uid !== user_2.uid;
2045
+ const needsPhotoUpdate = user_2.photoURL && mgmtUser_0.photoURL !== user_2.photoURL;
2046
+ if (needsUidUpdate || needsPhotoUpdate) {
2047
+ const updateReason = needsUidUpdate ? "uid" : "photoURL";
2048
+ console.debug(`User ${updateReason} has changed, updating user in user management system`);
2049
+ saveUser({
2050
+ ...mgmtUser_0,
2051
+ uid: user_2.uid,
2052
+ ...needsPhotoUpdate ? {
2053
+ photoURL: user_2.photoURL
2054
+ } : {}
2055
+ }).then(() => {
2056
+ console.debug("User updated in user management system", mgmtUser_0);
2057
+ }).catch((e_4) => {
2058
+ console.error("Error updating user in user management system", e_4);
2059
+ });
2060
+ }
2061
+ console.debug("User found in user management system", mgmtUser_0);
2062
+ return true;
2063
+ }
2064
+ throw Error("Could not find a user with the provided email in the user management system.");
2065
+ }, [loading, users]);
2066
+ const userRoles = authController.user ? defineRolesFor(authController.user) : void 0;
2067
+ const isAdmin = (userRoles ?? []).some((r_0) => r_0.id === "admin");
2068
+ const userRoleIds = userRoles?.map((r_1) => r_1.id);
2069
+ useEffect(() => {
2070
+ console.debug("Setting user roles", {
2071
+ userRoles,
2072
+ roles
2073
+ });
2074
+ authController.setUserRoles?.(userRoles ?? []);
2075
+ }, [userRoleIds]);
2076
+ const getUser = useCallback((uid_0) => {
2077
+ if (!users) return null;
2078
+ const user_3 = users.find((u_3) => u_3.uid === uid_0);
2079
+ return user_3 ?? null;
2080
+ }, [users]);
2081
+ return {
2082
+ loading,
2083
+ roles,
2084
+ users,
2085
+ saveUser,
2086
+ saveRole,
2087
+ rolesError,
2088
+ deleteUser,
2089
+ deleteRole,
2090
+ usersError,
2091
+ isAdmin,
2092
+ allowDefaultRolesCreation: allowDefaultRolesCreation === void 0 ? true : allowDefaultRolesCreation,
2093
+ includeCollectionConfigPermissions: Boolean(includeCollectionConfigPermissions),
2094
+ defineRolesFor,
2095
+ authenticator,
2096
+ ...authController,
2097
+ initialLoading: authController.initialLoading || loading,
2098
+ userRoles,
2099
+ getUser,
2100
+ user: authController.user ? {
2101
+ ...authController.user,
2102
+ roles: userRoles
2103
+ } : null
2104
+ };
2105
+ }
2106
+ const entitiesToUsers = (docs) => {
2107
+ return docs.map((doc2) => {
2108
+ const data = doc2.values;
2109
+ const newVar = {
2110
+ uid: doc2.id,
2111
+ ...data,
2112
+ created_on: data?.created_on,
2113
+ updated_on: data?.updated_on
2114
+ };
2115
+ return newVar;
2116
+ });
2117
+ };
2118
+ const entityToRoles = (entities) => {
2119
+ return entities.map((doc2) => ({
2120
+ id: doc2.id,
2121
+ ...doc2.values
2122
+ }));
2123
+ };
2124
+ const googleIcon = (mode) => /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsxs("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 64 64", width: 24, height: 24, children: [
2125
+ /* @__PURE__ */ jsxs("linearGradient", { id: "95yY7w43Oj6n2vH63j6HJb", x1: "29.401", x2: "29.401", y1: "4.064", y2: "106.734", gradientTransform: "matrix(1 0 0 -1 0 66)", gradientUnits: "userSpaceOnUse", children: [
2126
+ /* @__PURE__ */ jsx("stop", { offset: "0", stopColor: "#ff5840" }),
2127
+ /* @__PURE__ */ jsx("stop", { offset: ".007", stopColor: "#ff5840" }),
2128
+ /* @__PURE__ */ jsx("stop", { offset: ".989", stopColor: "#fa528c" }),
2129
+ /* @__PURE__ */ jsx("stop", { offset: "1", stopColor: "#fa528c" })
2130
+ ] }),
2131
+ /* @__PURE__ */ jsx("path", { fill: "url(#95yY7w43Oj6n2vH63j6HJb)", d: "M47.46,15.5l-1.37,1.48c-1.34,1.44-3.5,1.67-5.15,0.6c-2.71-1.75-6.43-3.13-11-2.37 c-4.94,0.83-9.17,3.85-11.64, 7.97l-8.03-6.08C14.99,9.82,23.2,5,32.5,5c5,0,9.94,1.56,14.27,4.46 C48.81,10.83,49.13,13.71,47.46,15.5z" }),
2132
+ /* @__PURE__ */ jsxs("linearGradient", { id: "95yY7w43Oj6n2vH63j6HJc", x1: "12.148", x2: "12.148", y1: ".872", y2: "47.812", gradientTransform: "matrix(1 0 0 -1 0 66)", gradientUnits: "userSpaceOnUse", children: [
2133
+ /* @__PURE__ */ jsx("stop", { offset: "0", stopColor: "#feaa53" }),
2134
+ /* @__PURE__ */ jsx("stop", { offset: ".612", stopColor: "#ffcd49" }),
2135
+ /* @__PURE__ */ jsx("stop", { offset: "1", stopColor: "#ffde44" })
2136
+ ] }),
2137
+ /* @__PURE__ */ jsx("path", { fill: "url(#95yY7w43Oj6n2vH63j6HJc)", d: "M16.01,30.91c-0.09,2.47,0.37,4.83,1.27,6.96l-8.21,6.05c-1.35-2.51-2.3-5.28-2.75-8.22 c-1.06-6.88,0.54-13.38, 3.95-18.6l8.03,6.08C16.93,25.47,16.1,28.11,16.01,30.91z" }),
2138
+ /* @__PURE__ */ jsxs("linearGradient", { id: "95yY7w43Oj6n2vH63j6HJd", x1: "29.76", x2: "29.76", y1: "32.149", y2: "-6.939", gradientTransform: "matrix(1 0 0 -1 0 66)", gradientUnits: "userSpaceOnUse", children: [
2139
+ /* @__PURE__ */ jsx("stop", { offset: "0", stopColor: "#42d778" }),
2140
+ /* @__PURE__ */ jsx("stop", { offset: ".428", stopColor: "#3dca76" }),
2141
+ /* @__PURE__ */ jsx("stop", { offset: "1", stopColor: "#34b171" })
2142
+ ] }),
2143
+ /* @__PURE__ */ jsx("path", { fill: "url(#95yY7w43Oj6n2vH63j6HJd)", d: "M50.45,51.28c-4.55,4.07-10.61,6.57-17.36,6.71C22.91,58.2,13.66,52.53,9.07,43.92l8.21-6.05 C19.78,43.81, 25.67,48,32.5,48c3.94,0,7.52-1.28,10.33-3.44L50.45,51.28z" }),
2144
+ /* @__PURE__ */ jsxs("linearGradient", { id: "95yY7w43Oj6n2vH63j6HJe", x1: "46", x2: "46", y1: "3.638", y2: "35.593", gradientTransform: "matrix(1 0 0 -1 0 66)", gradientUnits: "userSpaceOnUse", children: [
2145
+ /* @__PURE__ */ jsx("stop", { offset: "0", stopColor: "#155cde" }),
2146
+ /* @__PURE__ */ jsx("stop", { offset: ".278", stopColor: "#1f7fe5" }),
2147
+ /* @__PURE__ */ jsx("stop", { offset: ".569", stopColor: "#279ceb" }),
2148
+ /* @__PURE__ */ jsx("stop", { offset: ".82", stopColor: "#2cafef" }),
2149
+ /* @__PURE__ */ jsx("stop", { offset: "1", stopColor: "#2eb5f0" })
2150
+ ] }),
2151
+ /* @__PURE__ */ jsx("path", { fill: "url(#95yY7w43Oj6n2vH63j6HJe)", d: "M59,31.97c0.01,7.73-3.26,14.58-8.55,19.31l-7.62-6.72c2.1-1.61,3.77-3.71,4.84-6.15\n c0.29-0.66-0.2-1.41-0.92-1.41H37c-2.21,0-4-1.79-4-4v-2c0-2.21,1.79-4,4-4h17C56.75,27,59,29.22,59,31.97z" })
2152
+ ] }) });
2153
+ const appleIcon = (mode) => /* @__PURE__ */ jsx("svg", { width: 24, height: 24, viewBox: "0 0 56 56", style: {
2154
+ transform: "scale(2.8)"
2155
+ }, version: "1.1", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ jsx("g", { stroke: mode === "light" ? "#424245" : "white", strokeWidth: "0.5", fillRule: "evenodd", children: /* @__PURE__ */ jsx("path", { d: "M28.2226562,20.3846154 C29.0546875,20.3846154 30.0976562,19.8048315 30.71875,19.0317864 C31.28125,18.3312142 31.6914062,17.352829 31.6914062,16.3744437 C31.6914062,16.2415766 31.6796875,16.1087095 31.65625,16 C30.7304687,16.0362365 29.6171875,16.640178 28.9492187,17.4494596 C28.421875,18.06548 27.9414062,19.0317864 27.9414062,20.0222505 C27.9414062,20.1671964 27.9648438,20.3121424 27.9765625,20.3604577 C28.0351562,20.3725366 28.1289062,20.3846154 28.2226562,20.3846154 Z M25.2929688,35 C26.4296875,35 26.9335938,34.214876 28.3515625,34.214876 C29.7929688,34.214876 30.109375,34.9758423 31.375,34.9758423 C32.6171875,34.9758423 33.4492188,33.792117 34.234375,32.6325493 C35.1132812,31.3038779 35.4765625,29.9993643 35.5,29.9389701 C35.4179688,29.9148125 33.0390625,28.9122695 33.0390625,26.0979021 C33.0390625,23.6579784 34.9140625,22.5588048 35.0195312,22.474253 C33.7773438,20.6382708 31.890625,20.5899555 31.375,20.5899555 C29.9804688,20.5899555 28.84375,21.4596313 28.1289062,21.4596313 C27.3554688,21.4596313 26.3359375,20.6382708 25.1289062,20.6382708 C22.8320312,20.6382708 20.5,22.5950413 20.5,26.2911634 C20.5,28.5861411 21.3671875,31.013986 22.4335938,32.5842339 C23.3476562,33.9129053 24.1445312,35 25.2929688,35 Z", fill: mode === "light" ? "#424245" : "white", fillRule: "nonzero" }) }) });
2156
+ const githubIcon = (mode) => /* @__PURE__ */ jsx("svg", { fill: mode === "light" ? "#1c1e21" : "white", role: "img", viewBox: "0 0 24 24", width: 24, height: 24, xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ jsx("path", { d: "M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" }) });
2157
+ const facebookIcon = (mode) => /* @__PURE__ */ jsx("svg", { xmlns: "http://www.w3.org/2000/svg", width: 24, height: 24, viewBox: "0 0 90 90", children: /* @__PURE__ */ jsx("g", { children: /* @__PURE__ */ jsx("path", { d: "M90,15.001C90,7.119,82.884,0,75,0H15C7.116,0,0,7.119,0,15.001v59.998 C0,82.881,7.116,90,15.001,90H45V56H34V41h11v-5.844C45,25.077,52.568,16,61.875,16H74v15H61.875C60.548,31,59,32.611,59,35.024V41 h15v15H59v34h16c7.884,0,15-7.119,15-15.001V15.001z", fill: mode === "light" ? "#39569c" : "white" }) }) });
2158
+ const microsoftIcon = (mode) => /* @__PURE__ */ jsx("svg", { xmlns: "http://www.w3.org/2000/svg", width: 24, height: 24, viewBox: "0 0 480 480", children: /* @__PURE__ */ jsx("g", { children: /* @__PURE__ */ jsx("path", { d: "M0.176,224L0.001,67.963l192-26.072V224H0.176z M224.001,37.241L479.937,0v224H224.001V37.241z M479.999,256l-0.062,224 l-255.936-36.008V256H479.999z M192.001,439.918L0.157,413.621L0.147,256h191.854V439.918z", fill: mode === "light" ? "#00a2ed" : "white" }) }) });
2159
+ const twitterIcon = (mode) => /* @__PURE__ */ jsx("svg", { xmlns: "http://www.w3.org/2000/svg", width: 24, height: 24, viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { fill: mode === "light" ? "#00acee" : "white", d: "M24 4.557c-.883.392-1.832.656-2.828.775 1.017-.609 1.798-1.574 2.165-2.724-.951.564-2.005.974-3.127 1.195-.897-.957-2.178-1.555-3.594-1.555-3.179 0-5.515 2.966-4.797 6.045-4.091-.205-7.719-2.165-10.148-5.144-1.29 2.213-.669 5.108 1.523 6.574-.806-.026-1.566-.247-2.229-.616-.054 2.281 1.581 4.415 3.949 4.89-.693.188-1.452.232-2.224.084.626 1.956 2.444 3.379 4.6 3.419-2.07 1.623-4.678 2.348-7.29 2.04 2.179 1.397 4.768 2.212 7.548 2.212 9.142 0 14.307-7.721 13.995-14.646.962-.695 1.797-1.562 2.457-2.549z" }) });
2160
+ function FirebaseLoginView({
2161
+ children,
2162
+ allowSkipLogin,
2163
+ logo,
2164
+ signInOptions,
2165
+ firebaseApp,
2166
+ authController,
2167
+ noUserComponent,
2168
+ disableSignupScreen = false,
2169
+ disableResetPassword = false,
2170
+ disabled = false,
2171
+ additionalComponent,
2172
+ notAllowedError,
2173
+ className
2174
+ }) {
2175
+ const modeState = useModeController();
2176
+ const [passwordLoginSelected, setPasswordLoginSelected] = useState(false);
2177
+ const [phoneLoginSelected, setPhoneLoginSelected] = useState(false);
2178
+ const [fadeIn, setFadeIn] = useState(false);
2179
+ useEffect(() => {
2180
+ const timer = setTimeout(() => {
2181
+ setFadeIn(true);
2182
+ }, 50);
2183
+ return () => clearTimeout(timer);
2184
+ }, []);
2185
+ const resolvedSignInOptions = signInOptions.map((o) => {
2186
+ if (typeof o === "object") {
2187
+ return o.provider;
2188
+ } else return o;
2189
+ });
2190
+ const sendMFASms = useCallback(() => {
2191
+ const auth = getAuth(firebaseApp);
2192
+ const recaptchaVerifier = new RecaptchaVerifier(auth, "recaptcha", {
2193
+ size: "invisible"
2194
+ });
2195
+ const resolver = getMultiFactorResolver(auth, authController.authProviderError);
2196
+ if (resolver.hints[0].factorId === PhoneMultiFactorGenerator.FACTOR_ID) {
2197
+ const phoneInfoOptions = {
2198
+ multiFactorHint: resolver.hints[0],
2199
+ session: resolver.session
2200
+ };
2201
+ const phoneAuthProvider = new PhoneAuthProvider(auth);
2202
+ phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier).then(function(verificationId) {
2203
+ const verificationCode = String(window.prompt("Please enter the verification code that was sent to your mobile device."));
2204
+ const cred = PhoneAuthProvider.credential(verificationId, verificationCode);
2205
+ const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);
2206
+ return resolver.resolveSignIn(multiFactorAssertion);
2207
+ });
2208
+ } else {
2209
+ console.warn("Unsupported second factor.");
2210
+ }
2211
+ }, [authController.authProviderError]);
2212
+ function buildErrorView() {
2213
+ let errorView;
2214
+ if (authController.user != null) return errorView;
2215
+ const ignoredCodes = ["auth/popup-closed-by-user", "auth/cancelled-popup-request"];
2216
+ if (authController.authProviderError) {
2217
+ const authError = authController.authProviderError;
2218
+ if (authError.code === "auth/operation-not-allowed" || authError.code === "auth/configuration-not-found") {
2219
+ errorView = /* @__PURE__ */ jsxs(Fragment, { children: [
2220
+ /* @__PURE__ */ jsx("div", { className: "p-4", children: /* @__PURE__ */ jsx(ErrorView, { title: "Firebase Auth not enabled", error: "You need to enable Firebase Auth and the corresponding login provider in your Firebase project" }) }),
2221
+ firebaseApp && /* @__PURE__ */ jsx("div", { className: "p-4", children: /* @__PURE__ */ jsx("a", { href: `https://console.firebase.google.com/project/${firebaseApp.options.projectId}/authentication/providers`, rel: "noopener noreferrer", target: "_blank", children: /* @__PURE__ */ jsx(Button, { variant: "text", color: "error", children: "Open Firebase configuration" }) }) })
2222
+ ] });
2223
+ } else if (authError.code === "auth/invalid-api-key") {
2224
+ errorView = /* @__PURE__ */ jsx("div", { className: "p-4", children: /* @__PURE__ */ jsx(ErrorView, { title: "Invalid API key", error: "auth/invalid-api-key: Check that your Firebase config is set correctly in your `firebase_config.ts` file" }) });
2225
+ } else if (authError.code === "auth/email-already-in-use") {
2226
+ errorView = /* @__PURE__ */ jsx("div", { className: "p-4", children: /* @__PURE__ */ jsx(ErrorView, { title: "Email already in use", error: "The selected email is already in use by another account" }) });
2227
+ } else if (authError.code === "auth/invalid-credential") {
2228
+ errorView = /* @__PURE__ */ jsx("div", { className: "p-4", children: /* @__PURE__ */ jsx(ErrorView, { title: "Invalid credential", error: "The provided credential is not correct" }) });
2229
+ } else if (!ignoredCodes.includes(authError.code)) {
2230
+ if (authError.code === "auth/multi-factor-auth-required") {
2231
+ sendMFASms();
2232
+ }
2233
+ errorView = /* @__PURE__ */ jsx("div", { className: "p-4", children: /* @__PURE__ */ jsx(ErrorView, { error: authController.authProviderError }) });
2234
+ }
2235
+ }
2236
+ return errorView;
2237
+ }
2238
+ let logoComponent;
2239
+ if (logo) {
2240
+ logoComponent = /* @__PURE__ */ jsx("img", { src: logo, style: {
2241
+ height: "100%",
2242
+ width: "100%",
2243
+ objectFit: "contain"
2244
+ }, alt: "Logo" });
2245
+ } else {
2246
+ logoComponent = /* @__PURE__ */ jsx(RebaseLogo, {});
2247
+ }
2248
+ let notAllowedMessage;
2249
+ if (notAllowedError) {
2250
+ if (typeof notAllowedError === "string") {
2251
+ notAllowedMessage = notAllowedError;
2252
+ } else if (notAllowedError instanceof Error) {
2253
+ notAllowedMessage = notAllowedError.message;
2254
+ } else {
2255
+ notAllowedMessage = "It looks like you don't have access to the CMS, based on the specified Authenticator configuration";
2256
+ }
2257
+ }
2258
+ const fadeStyle = {
2259
+ opacity: fadeIn ? 1 : 0,
2260
+ transition: "opacity 0.6s ease-in-out"
2261
+ };
2262
+ return /* @__PURE__ */ jsxs("div", { className: cls("flex flex-col items-center justify-center min-w-full p-4", className), style: fadeStyle, children: [
2263
+ /* @__PURE__ */ jsx("div", { id: "recaptcha" }),
2264
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center w-full max-w-[500px]", children: [
2265
+ /* @__PURE__ */ jsx("div", { className: "p-1 w-64 h-64 m-4", children: logoComponent }),
2266
+ children,
2267
+ notAllowedMessage && /* @__PURE__ */ jsx("div", { className: "p-8", children: /* @__PURE__ */ jsx(ErrorView, { error: notAllowedMessage }) }),
2268
+ buildErrorView(),
2269
+ !passwordLoginSelected && !phoneLoginSelected && /* @__PURE__ */ jsxs("div", { className: "my-4 w-full", children: [
2270
+ buildOauthLoginButtons(authController, resolvedSignInOptions, modeState.mode, disabled),
2271
+ resolvedSignInOptions.includes("password") && /* @__PURE__ */ jsx(LoginButton, { disabled, text: "Email/password", icon: /* @__PURE__ */ jsx(MailIcon, { size: iconSize.medium }), onClick: () => setPasswordLoginSelected(true) }),
2272
+ resolvedSignInOptions.includes("phone") && /* @__PURE__ */ jsx(LoginButton, { disabled, text: "PhoneIcon number", icon: /* @__PURE__ */ jsx(PhoneIcon, { size: iconSize.medium }), onClick: () => setPhoneLoginSelected(true) }),
2273
+ resolvedSignInOptions.includes("anonymous") && /* @__PURE__ */ jsx(LoginButton, { disabled, text: "Log in anonymously", icon: /* @__PURE__ */ jsx(UserIcon, { size: "medium" }), onClick: authController.anonymousLogin }),
2274
+ allowSkipLogin && /* @__PURE__ */ jsx(Button, { className: "m-1 mb-4", variant: "text", disabled, onClick: authController.skipLogin, children: "Skip login" })
2275
+ ] }),
2276
+ passwordLoginSelected && /* @__PURE__ */ jsx(LoginForm, { authController, onClose: () => setPasswordLoginSelected(false), mode: modeState.mode, noUserComponent, disableSignupScreen, disableResetPassword }),
2277
+ phoneLoginSelected && /* @__PURE__ */ jsx(PhoneLoginForm, { authController, onClose: () => setPhoneLoginSelected(false) }),
2278
+ !passwordLoginSelected && !phoneLoginSelected && additionalComponent
2279
+ ] })
2280
+ ] });
2281
+ }
2282
+ function LoginButton(t0) {
2283
+ const $ = c(15);
2284
+ const {
2285
+ icon,
2286
+ onClick,
2287
+ text,
2288
+ disabled
2289
+ } = t0;
2290
+ const t1 = disabled ? "" : "hover:text-surface-950 hover:dark:text-white";
2291
+ let t2;
2292
+ if ($[0] !== t1) {
2293
+ t2 = cls("w-full bg-white dark:bg-surface-950 text-surface-900 dark:text-surface-100", t1);
2294
+ $[0] = t1;
2295
+ $[1] = t2;
2296
+ } else {
2297
+ t2 = $[1];
2298
+ }
2299
+ let t3;
2300
+ if ($[2] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
2301
+ t3 = {
2302
+ height: "40px",
2303
+ borderRadius: "4px",
2304
+ fontSize: "14px"
2305
+ };
2306
+ $[2] = t3;
2307
+ } else {
2308
+ t3 = $[2];
2309
+ }
2310
+ let t4;
2311
+ if ($[3] !== icon) {
2312
+ t4 = /* @__PURE__ */ jsx("div", { className: "flex flex-col w-8 items-center justify-items-center mr-4", children: icon });
2313
+ $[3] = icon;
2314
+ $[4] = t4;
2315
+ } else {
2316
+ t4 = $[4];
2317
+ }
2318
+ let t5;
2319
+ if ($[5] !== text) {
2320
+ t5 = /* @__PURE__ */ jsx("div", { className: "grow pl-2 text-center", children: text });
2321
+ $[5] = text;
2322
+ $[6] = t5;
2323
+ } else {
2324
+ t5 = $[6];
2325
+ }
2326
+ let t6;
2327
+ if ($[7] !== t4 || $[8] !== t5) {
2328
+ t6 = /* @__PURE__ */ jsxs("div", { className: "p-1 flex h-8 items-center justify-items-center", children: [
2329
+ t4,
2330
+ t5
2331
+ ] });
2332
+ $[7] = t4;
2333
+ $[8] = t5;
2334
+ $[9] = t6;
2335
+ } else {
2336
+ t6 = $[9];
2337
+ }
2338
+ let t7;
2339
+ if ($[10] !== disabled || $[11] !== onClick || $[12] !== t2 || $[13] !== t6) {
2340
+ t7 = /* @__PURE__ */ jsx("div", { className: "my-1 w-full", children: /* @__PURE__ */ jsx(Button, { className: t2, style: t3, disabled, onClick, children: t6 }) });
2341
+ $[10] = disabled;
2342
+ $[11] = onClick;
2343
+ $[12] = t2;
2344
+ $[13] = t6;
2345
+ $[14] = t7;
2346
+ } else {
2347
+ t7 = $[14];
2348
+ }
2349
+ return t7;
2350
+ }
2351
+ function PhoneLoginForm(t0) {
2352
+ const $ = c(33);
2353
+ const {
2354
+ onClose,
2355
+ authController
2356
+ } = t0;
2357
+ useRecaptcha();
2358
+ const [phone, setPhone] = useState();
2359
+ const [code, setCode] = useState();
2360
+ const [isInvalidCode, setIsInvalidCode] = useState(false);
2361
+ let t1;
2362
+ if ($[0] !== authController || $[1] !== code || $[2] !== phone) {
2363
+ t1 = async (event) => {
2364
+ event.preventDefault();
2365
+ if (code && authController.confirmationResult) {
2366
+ setIsInvalidCode(false);
2367
+ authController.confirmationResult.confirm(code).catch((e) => {
2368
+ if (e.code === "auth/invalid-verification-code") {
2369
+ setIsInvalidCode(true);
2370
+ }
2371
+ });
2372
+ } else {
2373
+ if (phone) {
2374
+ authController.phoneLogin(phone, window.recaptchaVerifier);
2375
+ }
2376
+ }
2377
+ };
2378
+ $[0] = authController;
2379
+ $[1] = code;
2380
+ $[2] = phone;
2381
+ $[3] = t1;
2382
+ } else {
2383
+ t1 = $[3];
2384
+ }
2385
+ const handleSubmit = t1;
2386
+ let t2;
2387
+ if ($[4] !== isInvalidCode) {
2388
+ t2 = isInvalidCode && /* @__PURE__ */ jsx("div", { className: "p-8", children: /* @__PURE__ */ jsx(ErrorView, { error: "Invalid confirmation code" }) });
2389
+ $[4] = isInvalidCode;
2390
+ $[5] = t2;
2391
+ } else {
2392
+ t2 = $[5];
2393
+ }
2394
+ let t3;
2395
+ if ($[6] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
2396
+ t3 = /* @__PURE__ */ jsx("div", { id: RECAPTCHA_CONTAINER_ID });
2397
+ $[6] = t3;
2398
+ } else {
2399
+ t3 = $[6];
2400
+ }
2401
+ let t4;
2402
+ if ($[7] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
2403
+ t4 = /* @__PURE__ */ jsx(ArrowLeftIcon, { className: "w-5 h-5" });
2404
+ $[7] = t4;
2405
+ } else {
2406
+ t4 = $[7];
2407
+ }
2408
+ let t5;
2409
+ if ($[8] !== onClose) {
2410
+ t5 = /* @__PURE__ */ jsx(IconButton, { onClick: onClose, children: t4 });
2411
+ $[8] = onClose;
2412
+ $[9] = t5;
2413
+ } else {
2414
+ t5 = $[9];
2415
+ }
2416
+ let t6;
2417
+ if ($[10] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
2418
+ t6 = /* @__PURE__ */ jsx("div", { className: "p-1 flex", children: /* @__PURE__ */ jsx(Typography, { align: "center", variant: "subtitle2", children: "Please enter your phone number" }) });
2419
+ $[10] = t6;
2420
+ } else {
2421
+ t6 = $[10];
2422
+ }
2423
+ const t7 = phone ?? "";
2424
+ const t8 = Boolean(phone && (authController.authLoading || authController.confirmationResult));
2425
+ let t9;
2426
+ if ($[11] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
2427
+ t9 = (event_0) => setPhone(event_0.target.value);
2428
+ $[11] = t9;
2429
+ } else {
2430
+ t9 = $[11];
2431
+ }
2432
+ let t10;
2433
+ if ($[12] !== t7 || $[13] !== t8) {
2434
+ t10 = /* @__PURE__ */ jsx(TextField, { placeholder: "", value: t7, disabled: t8, type: "phone", onChange: t9 });
2435
+ $[12] = t7;
2436
+ $[13] = t8;
2437
+ $[14] = t10;
2438
+ } else {
2439
+ t10 = $[14];
2440
+ }
2441
+ let t11;
2442
+ if ($[15] !== authController.confirmationResult || $[16] !== code || $[17] !== phone) {
2443
+ t11 = Boolean(phone && authController.confirmationResult) && /* @__PURE__ */ jsxs(Fragment, { children: [
2444
+ /* @__PURE__ */ jsx("div", { className: "mt-2 p-1 flex", children: /* @__PURE__ */ jsx(Typography, { align: "center", variant: "subtitle2", children: "Please enter the confirmation code" }) }),
2445
+ /* @__PURE__ */ jsx(TextField, { placeholder: "", value: code ?? "", type: "text", onChange: (event_1) => setCode(event_1.target.value) })
2446
+ ] });
2447
+ $[15] = authController.confirmationResult;
2448
+ $[16] = code;
2449
+ $[17] = phone;
2450
+ $[18] = t11;
2451
+ } else {
2452
+ t11 = $[18];
2453
+ }
2454
+ let t12;
2455
+ if ($[19] !== authController.authLoading) {
2456
+ t12 = authController.authLoading && /* @__PURE__ */ jsx(CircularProgress, { className: "p-1", size: "small" });
2457
+ $[19] = authController.authLoading;
2458
+ $[20] = t12;
2459
+ } else {
2460
+ t12 = $[20];
2461
+ }
2462
+ let t13;
2463
+ if ($[21] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
2464
+ t13 = /* @__PURE__ */ jsx(Button, { type: "submit", children: "Ok" });
2465
+ $[21] = t13;
2466
+ } else {
2467
+ t13 = $[21];
2468
+ }
2469
+ let t14;
2470
+ if ($[22] !== t12) {
2471
+ t14 = /* @__PURE__ */ jsxs("div", { className: "flex justify-end items-center w-full", children: [
2472
+ t12,
2473
+ t13
2474
+ ] });
2475
+ $[22] = t12;
2476
+ $[23] = t14;
2477
+ } else {
2478
+ t14 = $[23];
2479
+ }
2480
+ let t15;
2481
+ if ($[24] !== t10 || $[25] !== t11 || $[26] !== t14 || $[27] !== t5) {
2482
+ t15 = /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
2483
+ t5,
2484
+ t6,
2485
+ t10,
2486
+ t11,
2487
+ t14
2488
+ ] });
2489
+ $[24] = t10;
2490
+ $[25] = t11;
2491
+ $[26] = t14;
2492
+ $[27] = t5;
2493
+ $[28] = t15;
2494
+ } else {
2495
+ t15 = $[28];
2496
+ }
2497
+ let t16;
2498
+ if ($[29] !== handleSubmit || $[30] !== t15 || $[31] !== t2) {
2499
+ t16 = /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit, children: [
2500
+ t2,
2501
+ t3,
2502
+ t15
2503
+ ] });
2504
+ $[29] = handleSubmit;
2505
+ $[30] = t15;
2506
+ $[31] = t2;
2507
+ $[32] = t16;
2508
+ } else {
2509
+ t16 = $[32];
2510
+ }
2511
+ return t16;
2512
+ }
2513
+ function LoginForm({
2514
+ onClose,
2515
+ authController,
2516
+ mode,
2517
+ noUserComponent,
2518
+ disableSignupScreen,
2519
+ disableResetPassword
2520
+ }) {
2521
+ const passwordRef = useRef(null);
2522
+ const [loginState, setLoginState] = useState("email");
2523
+ const [email, setEmail] = useState();
2524
+ const [password, setPassword] = useState();
2525
+ const [previouslyUsedMethodsForUser, setPreviouslyUsedMethodsForUser] = useState();
2526
+ const [resettingPassword, setResettingPassword] = useState(false);
2527
+ const snackbarController = useSnackbarController();
2528
+ useEffect(() => {
2529
+ if ((loginState === "password" || loginState === "registration") && passwordRef.current) {
2530
+ passwordRef.current.focus();
2531
+ }
2532
+ }, [loginState]);
2533
+ useEffect(() => {
2534
+ if (!document) return;
2535
+ const escFunction = (event) => {
2536
+ if (event.keyCode === 27) {
2537
+ onClose();
2538
+ }
2539
+ };
2540
+ document.addEventListener("keydown", escFunction, false);
2541
+ return () => {
2542
+ document.removeEventListener("keydown", escFunction, false);
2543
+ };
2544
+ }, [onClose]);
2545
+ function handleEnterEmail() {
2546
+ if (email) {
2547
+ authController.fetchSignInMethodsForEmail(email).then((availableProviders) => {
2548
+ setPreviouslyUsedMethodsForUser(availableProviders.filter((p) => p !== "password"));
2549
+ });
2550
+ setLoginState("password");
2551
+ }
2552
+ }
2553
+ function handleEnterPassword() {
2554
+ if (email && password) {
2555
+ authController.emailPasswordLogin(email, password);
2556
+ }
2557
+ }
2558
+ function handleRegistration() {
2559
+ if (email && password) {
2560
+ authController.createUserWithEmailAndPassword(email, password);
2561
+ }
2562
+ }
2563
+ const onBackPressed = () => {
2564
+ if (loginState === "email") {
2565
+ onClose();
2566
+ } else if (loginState === "password" || loginState === "registration") {
2567
+ setLoginState("email");
2568
+ } else {
2569
+ setPreviouslyUsedMethodsForUser(void 0);
2570
+ }
2571
+ };
2572
+ const handleSubmit = (event_0) => {
2573
+ event_0.preventDefault();
2574
+ if (loginState === "email") {
2575
+ handleEnterEmail();
2576
+ } else if (loginState === "password") {
2577
+ handleEnterPassword();
2578
+ } else if (loginState === "registration") {
2579
+ handleRegistration();
2580
+ }
2581
+ };
2582
+ const label = loginState === "registration" ? "Please enter your email and password to create an account" : loginState === "password" ? "Please enter your password" : "Please enter your email";
2583
+ return /* @__PURE__ */ jsx("form", { className: "w-full", onSubmit: handleSubmit, children: /* @__PURE__ */ jsxs("div", { className: "max-w-[480px] w-full flex flex-col gap-4", children: [
2584
+ /* @__PURE__ */ jsx(IconButton, { onClick: onBackPressed, children: /* @__PURE__ */ jsx(ArrowLeftIcon, { className: "w-5 h-5" }) }),
2585
+ /* @__PURE__ */ jsx("div", { children: loginState === "registration" && noUserComponent }),
2586
+ /* @__PURE__ */ jsx(Typography, { className: `${loginState === "registration" && disableSignupScreen ? "hidden" : "flex"}`, variant: "subtitle2", children: label }),
2587
+ (loginState === "email" || loginState === "registration") && /* @__PURE__ */ jsx(TextField, { placeholder: "Email", autoFocus: true, value: email ?? "", disabled: authController.authLoading, type: "email", onChange: (event_1) => setEmail(event_1.target.value) }),
2588
+ /* @__PURE__ */ jsx("div", { className: `${loginState === "password" || loginState === "registration" && !disableSignupScreen ? "block" : "hidden"}`, children: /* @__PURE__ */ jsx(TextField, { placeholder: "Password", value: password ?? "", disabled: authController.authLoading, inputRef: passwordRef, type: "password", onChange: (event_2) => setPassword(event_2.target.value) }) }),
2589
+ /* @__PURE__ */ jsxs("div", { className: `${loginState === "registration" && disableSignupScreen ? "hidden" : "flex"} justify-end items-center w-full flex gap-2`, children: [
2590
+ authController.authLoading && /* @__PURE__ */ jsx(CircularProgress, { className: "p-1", size: "small" }),
2591
+ !disableResetPassword && /* @__PURE__ */ jsx(LoadingButton, { variant: "text", loading: resettingPassword, onClick: email ? async () => {
2592
+ setResettingPassword(true);
2593
+ try {
2594
+ try {
2595
+ await authController.sendPasswordResetEmail(email);
2596
+ snackbarController.open({
2597
+ message: "Password reset email sent",
2598
+ type: "success"
2599
+ });
2600
+ } catch (e) {
2601
+ snackbarController.open({
2602
+ message: e.message,
2603
+ type: "error"
2604
+ });
2605
+ }
2606
+ } finally {
2607
+ setResettingPassword(false);
2608
+ }
2609
+ } : void 0, children: "Reset password" }),
2610
+ !disableSignupScreen && loginState === "email" && /* @__PURE__ */ jsx(Button, { variant: "text", onClick: () => setLoginState("registration"), children: "New user" }),
2611
+ /* @__PURE__ */ jsx(Button, { type: "submit", children: loginState === "registration" ? "Create account" : loginState === "password" ? "Login" : "Login" })
2612
+ ] }),
2613
+ previouslyUsedMethodsForUser && previouslyUsedMethodsForUser.length > 0 && /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-4 p-4", children: [
2614
+ /* @__PURE__ */ jsxs("div", { children: [
2615
+ /* @__PURE__ */ jsx(Typography, { variant: "subtitle2", children: "You already have an account" }),
2616
+ /* @__PURE__ */ jsxs(Typography, { variant: "body2", children: [
2617
+ "You can use one of these methods to login with ",
2618
+ email
2619
+ ] })
2620
+ ] }),
2621
+ /* @__PURE__ */ jsx("div", { children: previouslyUsedMethodsForUser && buildOauthLoginButtons(authController, previouslyUsedMethodsForUser, mode, false) })
2622
+ ] })
2623
+ ] }) });
2624
+ }
2625
+ function buildOauthLoginButtons(authController, providers, mode, disabled) {
2626
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
2627
+ providers.includes("google.com") && /* @__PURE__ */ jsx(LoginButton, { disabled, text: "Sign in with Google", icon: googleIcon(), onClick: authController.googleLogin }),
2628
+ providers.includes("microsoft.com") && /* @__PURE__ */ jsx(LoginButton, { disabled, text: "Sign in with Microsoft", icon: microsoftIcon(mode), onClick: authController.microsoftLogin }),
2629
+ providers.includes("apple.com") && /* @__PURE__ */ jsx(LoginButton, { disabled, text: "Sign in with Apple", icon: appleIcon(mode), onClick: authController.appleLogin }),
2630
+ providers.includes("github.com") && /* @__PURE__ */ jsx(LoginButton, { disabled, text: "Sign in with Github", icon: githubIcon(mode), onClick: authController.githubLogin }),
2631
+ providers.includes("facebook.com") && /* @__PURE__ */ jsx(LoginButton, { disabled, text: "Sign in with Facebook", icon: facebookIcon(mode), onClick: authController.facebookLogin }),
2632
+ providers.includes("twitter.com") && /* @__PURE__ */ jsx(LoginButton, { disabled, text: "Sign in with Twitter", icon: twitterIcon(mode), onClick: authController.twitterLogin })
2633
+ ] });
2634
+ }
2635
+ const DEFAULT_SIGN_IN_OPTIONS = [GoogleAuthProvider.PROVIDER_ID];
2636
+ function RebaseFirebaseApp(t0) {
2637
+ const $ = c(98);
2638
+ const {
2639
+ name,
2640
+ logo,
2641
+ logoDark,
2642
+ authenticator,
2643
+ collections,
2644
+ views,
2645
+ adminViews,
2646
+ textSearchControllerBuilder,
2647
+ allowSkipLogin,
2648
+ signInOptions: t1,
2649
+ firebaseConfig,
2650
+ onFirebaseInit,
2651
+ appCheckOptions,
2652
+ dateTimeFormat,
2653
+ locale,
2654
+ basePath,
2655
+ baseCollectionPath,
2656
+ onAnalyticsEvent,
2657
+ propertyConfigs: propertyConfigsProp,
2658
+ plugins,
2659
+ autoOpenDrawer,
2660
+ firestoreIndexesBuilder,
2661
+ components,
2662
+ localTextSearchEnabled: t2,
2663
+ userManagement
2664
+ } = t0;
2665
+ const signInOptions = t1 === void 0 ? DEFAULT_SIGN_IN_OPTIONS : t1;
2666
+ const localTextSearchEnabled = t2 === void 0 ? false : t2;
2667
+ useBrowserTitleAndIcon(name, logo);
2668
+ let t3;
2669
+ if ($[0] !== propertyConfigsProp) {
2670
+ t3 = propertyConfigsProp ?? [];
2671
+ $[0] = propertyConfigsProp;
2672
+ $[1] = t3;
2673
+ } else {
2674
+ t3 = $[1];
2675
+ }
2676
+ let t4;
2677
+ if ($[2] !== t3) {
2678
+ t4 = t3.map(_temp).reduce(_temp2, {});
2679
+ $[2] = t3;
2680
+ $[3] = t4;
2681
+ } else {
2682
+ t4 = $[3];
2683
+ }
2684
+ const propertyConfigs = t4;
2685
+ let t5;
2686
+ if ($[4] !== firebaseConfig || $[5] !== onFirebaseInit) {
2687
+ t5 = {
2688
+ onFirebaseInit,
2689
+ firebaseConfig
2690
+ };
2691
+ $[4] = firebaseConfig;
2692
+ $[5] = onFirebaseInit;
2693
+ $[6] = t5;
2694
+ } else {
2695
+ t5 = $[6];
2696
+ }
2697
+ const {
2698
+ firebaseApp,
2699
+ firebaseConfigLoading,
2700
+ configError
2701
+ } = useInitialiseFirebase(t5);
2702
+ const modeController = useBuildModeController();
2703
+ const adminModeController = useBuildAdminModeController();
2704
+ let t6;
2705
+ if ($[7] !== appCheckOptions || $[8] !== firebaseApp) {
2706
+ t6 = {
2707
+ firebaseApp,
2708
+ options: appCheckOptions
2709
+ };
2710
+ $[7] = appCheckOptions;
2711
+ $[8] = firebaseApp;
2712
+ $[9] = t6;
2713
+ } else {
2714
+ t6 = $[9];
2715
+ }
2716
+ const {
2717
+ loading
2718
+ } = useAppCheck(t6);
2719
+ let t7;
2720
+ if ($[10] !== firebaseApp || $[11] !== signInOptions) {
2721
+ t7 = {
2722
+ firebaseApp,
2723
+ signInOptions
2724
+ };
2725
+ $[10] = firebaseApp;
2726
+ $[11] = signInOptions;
2727
+ $[12] = t7;
2728
+ } else {
2729
+ t7 = $[12];
2730
+ }
2731
+ const authController = useFirebaseAuthController(t7);
2732
+ const userConfigPersistence = useBuildLocalConfigurationPersistence();
2733
+ let t8;
2734
+ if ($[13] !== firebaseApp || $[14] !== firestoreIndexesBuilder || $[15] !== localTextSearchEnabled || $[16] !== textSearchControllerBuilder) {
2735
+ t8 = {
2736
+ firebaseApp,
2737
+ textSearchControllerBuilder,
2738
+ firestoreIndexesBuilder,
2739
+ localTextSearchEnabled
2740
+ };
2741
+ $[13] = firebaseApp;
2742
+ $[14] = firestoreIndexesBuilder;
2743
+ $[15] = localTextSearchEnabled;
2744
+ $[16] = textSearchControllerBuilder;
2745
+ $[17] = t8;
2746
+ } else {
2747
+ t8 = $[17];
2748
+ }
2749
+ const firestoreDelegate = useFirestoreDriver(t8);
2750
+ let t9;
2751
+ if ($[18] !== firebaseApp) {
2752
+ t9 = {
2753
+ firebaseApp
2754
+ };
2755
+ $[18] = firebaseApp;
2756
+ $[19] = t9;
2757
+ } else {
2758
+ t9 = $[19];
2759
+ }
2760
+ const storageSource = useFirebaseStorageSource(t9);
2761
+ let t10;
2762
+ if ($[20] !== firestoreDelegate) {
2763
+ t10 = buildRebaseData(firestoreDelegate);
2764
+ $[20] = firestoreDelegate;
2765
+ $[21] = t10;
2766
+ } else {
2767
+ t10 = $[21];
2768
+ }
2769
+ let t11;
2770
+ if ($[22] !== authController || $[23] !== authenticator || $[24] !== storageSource || $[25] !== t10) {
2771
+ t11 = {
2772
+ authController,
2773
+ authenticator,
2774
+ data: t10,
2775
+ storageSource
2776
+ };
2777
+ $[22] = authController;
2778
+ $[23] = authenticator;
2779
+ $[24] = storageSource;
2780
+ $[25] = t10;
2781
+ $[26] = t11;
2782
+ } else {
2783
+ t11 = $[26];
2784
+ }
2785
+ const {
2786
+ authLoading,
2787
+ canAccessMainView,
2788
+ notAllowedError
2789
+ } = useValidateAuthenticator(t11);
2790
+ let t12;
2791
+ if ($[27] !== userConfigPersistence) {
2792
+ t12 = {
2793
+ userConfigPersistence
2794
+ };
2795
+ $[27] = userConfigPersistence;
2796
+ $[28] = t12;
2797
+ } else {
2798
+ t12 = $[28];
2799
+ }
2800
+ const collectionRegistryController = useBuildCollectionRegistryController(t12);
2801
+ const t13 = basePath ?? "/";
2802
+ const t14 = baseCollectionPath ?? "/c";
2803
+ let t15;
2804
+ if ($[29] !== collectionRegistryController || $[30] !== t13 || $[31] !== t14) {
2805
+ t15 = {
2806
+ basePath: t13,
2807
+ baseCollectionPath: t14,
2808
+ collectionRegistryController
2809
+ };
2810
+ $[29] = collectionRegistryController;
2811
+ $[30] = t13;
2812
+ $[31] = t14;
2813
+ $[32] = t15;
2814
+ } else {
2815
+ t15 = $[32];
2816
+ }
2817
+ const urlController = useBuildUrlController(t15);
2818
+ let t16;
2819
+ if ($[33] !== authController || $[34] !== firestoreDelegate) {
2820
+ t16 = {
2821
+ authController,
2822
+ dataSourceDelegate: firestoreDelegate
2823
+ };
2824
+ $[33] = authController;
2825
+ $[34] = firestoreDelegate;
2826
+ $[35] = t16;
2827
+ } else {
2828
+ t16 = $[35];
2829
+ }
2830
+ const defaultUserManagement = useBuildUserManagement(t16);
2831
+ const activeUserManagement = userManagement ?? defaultUserManagement;
2832
+ let t17;
2833
+ if ($[36] !== firestoreDelegate) {
2834
+ t17 = buildRebaseData(firestoreDelegate);
2835
+ $[36] = firestoreDelegate;
2836
+ $[37] = t17;
2837
+ } else {
2838
+ t17 = $[37];
2839
+ }
2840
+ const t18 = activeUserManagement;
2841
+ let t19;
2842
+ if ($[38] !== adminModeController.mode || $[39] !== adminViews || $[40] !== authController || $[41] !== collectionRegistryController || $[42] !== collections || $[43] !== plugins || $[44] !== t17 || $[45] !== t18 || $[46] !== urlController || $[47] !== views) {
2843
+ t19 = {
2844
+ collections,
2845
+ views,
2846
+ adminViews,
2847
+ authController,
2848
+ data: t17,
2849
+ plugins,
2850
+ collectionRegistryController,
2851
+ urlController,
2852
+ adminMode: adminModeController.mode,
2853
+ userManagement: t18
2854
+ };
2855
+ $[38] = adminModeController.mode;
2856
+ $[39] = adminViews;
2857
+ $[40] = authController;
2858
+ $[41] = collectionRegistryController;
2859
+ $[42] = collections;
2860
+ $[43] = plugins;
2861
+ $[44] = t17;
2862
+ $[45] = t18;
2863
+ $[46] = urlController;
2864
+ $[47] = views;
2865
+ $[48] = t19;
2866
+ } else {
2867
+ t19 = $[48];
2868
+ }
2869
+ const navigationStateController = useBuildNavigationStateController(t19);
2870
+ if (firebaseConfigLoading || !firebaseApp || loading) {
2871
+ let t202;
2872
+ if ($[49] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
2873
+ t202 = /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsx(CircularProgressCenter, {}) });
2874
+ $[49] = t202;
2875
+ } else {
2876
+ t202 = $[49];
2877
+ }
2878
+ return t202;
2879
+ }
2880
+ if (configError) {
2881
+ let t202;
2882
+ if ($[50] !== configError) {
2883
+ t202 = /* @__PURE__ */ jsx(CenteredView, { children: configError });
2884
+ $[50] = configError;
2885
+ $[51] = t202;
2886
+ } else {
2887
+ t202 = $[51];
2888
+ }
2889
+ return t202;
2890
+ }
2891
+ let t20;
2892
+ if ($[52] !== firebaseApp.options.projectId) {
2893
+ t20 = (t212) => {
2894
+ const {
2895
+ entity
2896
+ } = t212;
2897
+ return `https://console.firebase.google.com/project/${firebaseApp.options.projectId}/firestore/data/${entity.path}/${entity.id}`;
2898
+ };
2899
+ $[52] = firebaseApp.options.projectId;
2900
+ $[53] = t20;
2901
+ } else {
2902
+ t20 = $[53];
2903
+ }
2904
+ let t21;
2905
+ if ($[54] !== allowSkipLogin || $[55] !== authController || $[56] !== authLoading || $[57] !== autoOpenDrawer || $[58] !== canAccessMainView || $[59] !== components || $[60] !== firebaseApp || $[61] !== logo || $[62] !== logoDark || $[63] !== modeController || $[64] !== name || $[65] !== navigationStateController || $[66] !== notAllowedError || $[67] !== signInOptions || $[68] !== urlController) {
2906
+ t21 = (t222) => {
2907
+ const {
2908
+ loading: loading_0
2909
+ } = t222;
2910
+ let component;
2911
+ if (loading_0 || authLoading) {
2912
+ component = /* @__PURE__ */ jsx(CircularProgressCenter, { size: "large" });
2913
+ } else {
2914
+ const usedLogo = modeController.mode === "dark" && logoDark ? logoDark : logo;
2915
+ if (!canAccessMainView) {
2916
+ const LoginViewUsed = components?.LoginView ?? FirebaseLoginView;
2917
+ component = /* @__PURE__ */ jsx(LoginViewUsed, { logo: usedLogo, allowSkipLogin, signInOptions: signInOptions ?? DEFAULT_SIGN_IN_OPTIONS, firebaseApp, authController, notAllowedError });
2918
+ } else {
2919
+ const firstCollectionEntry = navigationStateController.topLevelNavigation?.navigationEntries.find(_temp3);
2920
+ const fallbackRoute = firstCollectionEntry ? /* @__PURE__ */ jsx(Navigate, { to: urlController.buildUrlCollectionPath(firstCollectionEntry.id), replace: true }) : /* @__PURE__ */ jsx(CenteredView, { children: "No home page or collections provided." });
2921
+ component = /* @__PURE__ */ jsx(SideEntityProvider, { children: /* @__PURE__ */ jsx(RebaseRoutes, { children: /* @__PURE__ */ jsxs(Route, { element: /* @__PURE__ */ jsxs(Scaffold, { logo: usedLogo, autoOpenDrawer, children: [
2922
+ /* @__PURE__ */ jsx(AppBar, { title: name, logo: usedLogo }),
2923
+ /* @__PURE__ */ jsx(Drawer, {}),
2924
+ /* @__PURE__ */ jsx(Outlet, {}),
2925
+ /* @__PURE__ */ jsx(SideDialogs, {})
2926
+ ] }), children: [
2927
+ /* @__PURE__ */ jsx(Route, { path: "/", element: components?.HomePage ? /* @__PURE__ */ jsx(components.HomePage, {}) : fallbackRoute }),
2928
+ /* @__PURE__ */ jsx(Route, { path: "/c/*", element: /* @__PURE__ */ jsx(RebaseRoute, {}) })
2929
+ ] }) }) });
2930
+ }
2931
+ }
2932
+ return component;
2933
+ };
2934
+ $[54] = allowSkipLogin;
2935
+ $[55] = authController;
2936
+ $[56] = authLoading;
2937
+ $[57] = autoOpenDrawer;
2938
+ $[58] = canAccessMainView;
2939
+ $[59] = components;
2940
+ $[60] = firebaseApp;
2941
+ $[61] = logo;
2942
+ $[62] = logoDark;
2943
+ $[63] = modeController;
2944
+ $[64] = name;
2945
+ $[65] = navigationStateController;
2946
+ $[66] = notAllowedError;
2947
+ $[67] = signInOptions;
2948
+ $[68] = urlController;
2949
+ $[69] = t21;
2950
+ } else {
2951
+ t21 = $[69];
2952
+ }
2953
+ let t22;
2954
+ if ($[70] !== activeUserManagement || $[71] !== authController || $[72] !== dateTimeFormat || $[73] !== firestoreDelegate || $[74] !== locale || $[75] !== onAnalyticsEvent || $[76] !== plugins || $[77] !== propertyConfigs || $[78] !== storageSource || $[79] !== t20 || $[80] !== t21 || $[81] !== userConfigPersistence) {
2955
+ t22 = /* @__PURE__ */ jsx(Rebase, { authController, userConfigPersistence, dateTimeFormat, driver: firestoreDelegate, storageSource, userManagement: activeUserManagement, entityLinkBuilder: t20, locale, onAnalyticsEvent, plugins, propertyConfigs, children: t21 });
2956
+ $[70] = activeUserManagement;
2957
+ $[71] = authController;
2958
+ $[72] = dateTimeFormat;
2959
+ $[73] = firestoreDelegate;
2960
+ $[74] = locale;
2961
+ $[75] = onAnalyticsEvent;
2962
+ $[76] = plugins;
2963
+ $[77] = propertyConfigs;
2964
+ $[78] = storageSource;
2965
+ $[79] = t20;
2966
+ $[80] = t21;
2967
+ $[81] = userConfigPersistence;
2968
+ $[82] = t22;
2969
+ } else {
2970
+ t22 = $[82];
2971
+ }
2972
+ let t23;
2973
+ if ($[83] !== navigationStateController || $[84] !== t22) {
2974
+ t23 = /* @__PURE__ */ jsx(NavigationStateContext.Provider, { value: navigationStateController, children: t22 });
2975
+ $[83] = navigationStateController;
2976
+ $[84] = t22;
2977
+ $[85] = t23;
2978
+ } else {
2979
+ t23 = $[85];
2980
+ }
2981
+ let t24;
2982
+ if ($[86] !== t23 || $[87] !== urlController) {
2983
+ t24 = /* @__PURE__ */ jsx(UrlContext.Provider, { value: urlController, children: t23 });
2984
+ $[86] = t23;
2985
+ $[87] = urlController;
2986
+ $[88] = t24;
2987
+ } else {
2988
+ t24 = $[88];
2989
+ }
2990
+ let t25;
2991
+ if ($[89] !== collectionRegistryController || $[90] !== t24) {
2992
+ t25 = /* @__PURE__ */ jsx(CollectionRegistryContext.Provider, { value: collectionRegistryController, children: t24 });
2993
+ $[89] = collectionRegistryController;
2994
+ $[90] = t24;
2995
+ $[91] = t25;
2996
+ } else {
2997
+ t25 = $[91];
2998
+ }
2999
+ let t26;
3000
+ if ($[92] !== adminModeController || $[93] !== t25) {
3001
+ t26 = /* @__PURE__ */ jsx(AdminModeControllerProvider, { value: adminModeController, children: t25 });
3002
+ $[92] = adminModeController;
3003
+ $[93] = t25;
3004
+ $[94] = t26;
3005
+ } else {
3006
+ t26 = $[94];
3007
+ }
3008
+ let t27;
3009
+ if ($[95] !== modeController || $[96] !== t26) {
3010
+ t27 = /* @__PURE__ */ jsx(SnackbarProvider, { children: /* @__PURE__ */ jsx(ModeControllerProvider, { value: modeController, children: t26 }) });
3011
+ $[95] = modeController;
3012
+ $[96] = t26;
3013
+ $[97] = t27;
3014
+ } else {
3015
+ t27 = $[97];
3016
+ }
3017
+ return t27;
3018
+ }
3019
+ function _temp3(e) {
3020
+ return e.type === "collection";
3021
+ }
3022
+ function _temp2(a, b) {
3023
+ return {
3024
+ ...a,
3025
+ ...b
3026
+ };
3027
+ }
3028
+ function _temp(pc) {
3029
+ return {
3030
+ [pc.key]: pc
3031
+ };
3032
+ }
3033
+ export {
3034
+ FirebaseLoginView,
3035
+ LoginButton,
3036
+ RECAPTCHA_CONTAINER_ID,
3037
+ RebaseFirebaseApp,
3038
+ buildCollectionId,
3039
+ buildExternalSearchController,
3040
+ buildPineconeSearchController,
3041
+ buildRebaseSearchController,
3042
+ cmsToFirestoreModel,
3043
+ docToCollection,
3044
+ docsToCollectionTree,
3045
+ firestoreToCMSModel,
3046
+ getFirestoreDataInPath,
3047
+ localSearchControllerBuilder,
3048
+ performAlgoliaTextSearch,
3049
+ performPineconeTextSearch,
3050
+ useAppCheck,
3051
+ useBuildUserManagement,
3052
+ useFirebaseAuthController,
3053
+ useFirebaseRTDBDelegate,
3054
+ useFirebaseStorageSource,
3055
+ useFirestoreDriver,
3056
+ useInitialiseFirebase,
3057
+ useRecaptcha
3058
+ };
3059
+ //# sourceMappingURL=index.es.js.map