@rebasepro/firebase 0.12.1-canary.gf5f1d39 → 0.13.1-canary.g06dbe5b

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.
@@ -117,7 +117,7 @@ export type RebaseFirebaseAppProps = {
117
117
  */
118
118
  plugins?: RebasePlugin[];
119
119
  /**
120
- * Open the drawer on hover. Defaults to `false`
120
+ * Open the drawer on hover. Defaults to `true`
121
121
  */
122
122
  autoOpenDrawer?: boolean;
123
123
  /**
@@ -35,6 +35,35 @@ export interface UserManagementDelegateParams<CONTROLLER extends AuthController<
35
35
  */
36
36
  allowDefaultRolesCreation?: boolean;
37
37
  }
38
+ /**
39
+ * Why the access gate answered the way it did.
40
+ *
41
+ * `users-unreadable` is a state of its own because it used to be
42
+ * indistinguishable from `bootstrap`: the users listener's `onError` empties
43
+ * the user list, so a `permission-denied` on the users path — a rules
44
+ * misconfiguration, a rules deploy that has not landed, a renamed path —
45
+ * reached the gate as "no users created yet" and every authenticated user was
46
+ * let in. An unreadable list is not an empty one, and only one of the two may
47
+ * open the door.
48
+ */
49
+ export type AccessDecision = "loading" | "no-user" | "users-unreadable" | "bootstrap" | "known-user" | "unknown-user";
50
+ /**
51
+ * Decide whether a user may access the CMS, given the state of the user
52
+ * management collection.
53
+ *
54
+ * A plain function rather than logic inside the gate callback so the states
55
+ * that must stay distinct can be asserted without a React render.
56
+ */
57
+ export declare function resolveAccessDecision({ loading, usersError, users, user }: {
58
+ loading: boolean;
59
+ usersError?: Error;
60
+ users: {
61
+ email?: string | null;
62
+ }[];
63
+ user: {
64
+ email?: string | null;
65
+ } | null;
66
+ }): AccessDecision;
38
67
  /**
39
68
  * This hook is used to build a user management object that can be used to
40
69
  * manage users and roles in a Firestore backend.
@@ -1,6 +1,20 @@
1
1
  import { FirebaseApp } from "firebase/app";
2
2
  import { FirebaseAuthController, FirebaseSignInOption, FirebaseSignInProvider, FirebaseUserWrapper } from "../types";
3
3
  import type { User } from "@rebasepro/types";
4
+ /**
5
+ * Resolve `user`'s roles through `defineRolesFor` and report whether they
6
+ * differ from the ones already applied.
7
+ *
8
+ * A plain function rather than a check inside the hook because the check that
9
+ * used to live there read `!equal(userRoles, userRoles)` — the local shadowed
10
+ * the state of the same name, so the fresh roles were compared to themselves,
11
+ * the guard was never true, and a `defineRolesFor` result arriving after the
12
+ * auth-state change never reached the controller.
13
+ */
14
+ export declare function resolveRoleRefresh(defineRolesFor: (user: User) => Promise<string[] | undefined> | string[] | undefined, user: User, currentRoles: string[] | undefined): Promise<{
15
+ changed: boolean;
16
+ roles: string[] | undefined;
17
+ }>;
4
18
  export interface FirebaseAuthControllerProps {
5
19
  loading?: boolean;
6
20
  firebaseApp?: FirebaseApp;
@@ -1,5 +1,43 @@
1
1
  import { FirebaseApp } from "firebase/app";
2
- import { DataDriver } from "@rebasepro/types";
2
+ import { DataDriver, FetchCollectionProps } from "@rebasepro/types";
3
+ /** The values the Realtime Database can order or bound a query by. */
4
+ type RTDBFilterValue = string | number | boolean | null;
5
+ /**
6
+ * A read expressed in the Realtime Database's own query model.
7
+ *
8
+ * @see planRTDBQuery
9
+ */
10
+ export type RTDBQueryPlan = {
11
+ /** Child key to order — and therefore to bound — by. Absent means order by key. */
12
+ orderByChild?: string;
13
+ equalTo?: RTDBFilterValue;
14
+ startAt?: RTDBFilterValue;
15
+ /** Key the window starts after, exclusive. Only valid in key order. */
16
+ startAfter?: RTDBFilterValue;
17
+ endAt?: RTDBFilterValue;
18
+ limitToFirst?: number;
19
+ /**
20
+ * Rows to drop from the front of the result — the caller's `offset`, which
21
+ * the database has no constraint for. Applied by the caller, not by
22
+ * {@link rtdbConstraints}.
23
+ */
24
+ skip?: number;
25
+ };
26
+ /**
27
+ * Translate a driver read into the Realtime Database's query model, or refuse it.
28
+ *
29
+ * The Realtime Database orders by a single child key per query and bounds that
30
+ * one key with `equalTo`/`startAt`/`endAt`. Nothing else is expressible: no
31
+ * second field, no descending order, no text search, no `or(...)` group.
32
+ *
33
+ * Everything beyond `limit` and `startAfter` used to be destructured out of the
34
+ * read and then never referenced, so a caller asking for `status == "draft"`
35
+ * was handed the entire collection, presented as the answer. A query this
36
+ * database cannot express is refused here instead — a caller that sees an error
37
+ * can fall back, a caller that sees the wrong rows cannot.
38
+ */
39
+ export declare function planRTDBQuery<M extends Record<string, any>>({ filter, orderBy, order, searchString, logical, limit, offset, startAfter: startAfterKey }: Pick<FetchCollectionProps<M>, "filter" | "orderBy" | "order" | "searchString" | "logical" | "limit" | "offset" | "startAfter">): RTDBQueryPlan;
3
40
  export declare function useFirebaseRTDBDelegate({ firebaseApp }: {
4
41
  firebaseApp?: FirebaseApp;
5
42
  }): DataDriver;
43
+ export {};
@@ -36,6 +36,26 @@ export type FirestoreDataDriver = DataDriver & {
36
36
  collection?: CollectionConfig;
37
37
  }) => Promise<boolean>;
38
38
  };
39
+ /**
40
+ * The window a read has to ask Firestore for in order to honour `offset`.
41
+ *
42
+ * Firestore's web SDK has no `offset()` — it pages by cursor (`startAfter`)
43
+ * only. Callers that page by offset (`buildRebaseData`, and through it every
44
+ * `findAll()` and `iterate()`) were therefore served page one every time:
45
+ * `count` is a real server count, so `hasMore` never went false, the walk
46
+ * accumulated the same rows over and over, and it ended by tripping its row
47
+ * cap and reporting "matched more than N rows" — a condition that had not
48
+ * occurred.
49
+ *
50
+ * So the read asks for `offset + limit` documents and drops the first
51
+ * `offset`. Those documents are billed either way: Firestore charges for every
52
+ * document a cursor walks past, which is why `startAfter` is the cheap way to
53
+ * page and offset paging over a large collection is not.
54
+ */
55
+ export declare function resolveOffsetWindow(limit: number | undefined, offset: number | undefined): {
56
+ fetchLimit: number | undefined;
57
+ skip: number;
58
+ };
39
59
  /**
40
60
  * Use this hook to build a {@link DataDriver} based on Firestore
41
61
  * @param firebaseApp
@@ -53,5 +73,5 @@ export declare function useFirestoreDriver({ firebaseApp, textSearchControllerBu
53
73
  * @param data
54
74
  * @group Firestore
55
75
  */
56
- export declare function firestoreToCMSModel(data: unknown): unknown;
57
- export declare function cmsToFirestoreModel(data: unknown, firestore: Firestore, inArray?: boolean): unknown;
76
+ export declare function firestoreToRebaseModel(data: unknown): unknown;
77
+ export declare function rebaseToFirestoreModel(data: unknown, firestore: Firestore, inArray?: boolean): unknown;
package/dist/index.es.js CHANGED
@@ -9,15 +9,32 @@ import { DocumentReference, GeoPoint as GeoPoint$1, Timestamp, VectorValue, coll
9
9
  import { COLLECTION_PATH_SEPARATOR, buildRebaseData, sortProperties, stripCollectionPath } from "@rebasepro/common";
10
10
  import Fuse from "fuse.js";
11
11
  import { getFunctions, httpsCallable } from "firebase/functions";
12
- import { get, getDatabase, limitToFirst, onValue, orderByChild, orderByKey, push, query as query$1, ref as ref$1, remove, set, startAt } from "firebase/database";
12
+ import { endAt, equalTo, get, getDatabase, limitToFirst, onValue, orderByChild, orderByKey, push, query as query$1, ref as ref$1, remove, set, startAfter as startAfter$1, startAt } from "firebase/database";
13
13
  import { removeUndefined } from "@rebasepro/utils";
14
14
  import { AdminModeControllerProvider, ErrorView, ModeControllerProvider, Rebase, RebaseLogo, RebaseRoutes, SnackbarProvider, useBrowserTitleAndIcon, useBuildAdminModeController, useBuildLocalConfigurationPersistence, useBuildModeController, useModeController, useSnackbarController } from "@rebasepro/app";
15
15
  import { AppBar, CollectionRegistryContext, Drawer, NavigationStateContext, RebaseRoute, Scaffold, SideDialogs, SidePanelProvider, UrlContext, useBuildCollectionRegistryController, useBuildNavigationStateController, useBuildUrlController } from "@rebasepro/admin";
16
16
  import { ArrowLeftIcon, Button, CenteredView, CircularProgress, CircularProgressCenter, IconButton, LoadingButton, MailIcon, PhoneIcon, TextField, Typography, UserIcon, cls, iconSize } from "@rebasepro/ui";
17
- import { Navigate, Outlet, Route } from "react-router-dom";
17
+ import { Navigate, Outlet, Route } from "react-router";
18
18
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
19
19
  //#region src/hooks/useFirebaseAuthController.ts
20
20
  /**
21
+ * Resolve `user`'s roles through `defineRolesFor` and report whether they
22
+ * differ from the ones already applied.
23
+ *
24
+ * A plain function rather than a check inside the hook because the check that
25
+ * used to live there read `!equal(userRoles, userRoles)` — the local shadowed
26
+ * the state of the same name, so the fresh roles were compared to themselves,
27
+ * the guard was never true, and a `defineRolesFor` result arriving after the
28
+ * auth-state change never reached the controller.
29
+ */
30
+ async function resolveRoleRefresh(defineRolesFor, user, currentRoles) {
31
+ const roles = await defineRolesFor(user);
32
+ return {
33
+ changed: !deepEqual(currentRoles, roles),
34
+ roles
35
+ };
36
+ }
37
+ /**
21
38
  * Use this hook to build an {@link AuthController} based on Firebase Auth
22
39
  * @group Firebase
23
40
  */
@@ -44,8 +61,8 @@ var useFirebaseAuthController = ({ loading, firebaseApp, signInOptions, onSignOu
44
61
  }, [loading]);
45
62
  const updateRoles = useCallback(async (user) => {
46
63
  if (defineRolesFor && user) {
47
- const userRoles = await defineRolesFor(user);
48
- if (!deepEqual(userRoles, userRoles)) setUserRoles(userRoles);
64
+ const { changed, roles } = await resolveRoleRefresh(defineRolesFor, user, userRoles);
65
+ if (changed) setUserRoles(roles);
49
66
  }
50
67
  }, [defineRolesFor, userRoles]);
51
68
  useEffect(() => {
@@ -472,10 +489,11 @@ function useAppCheck({ firebaseApp, options }) {
472
489
  setAppCheckLoading(true);
473
490
  const { provider, isTokenAutoRefreshEnabled } = options;
474
491
  removeCurrentAppCheckDiv();
475
- verifyToken(initializeAppCheck(firebaseApp, {
492
+ const appCheck = initializeAppCheck(firebaseApp, {
476
493
  provider,
477
494
  isTokenAutoRefreshEnabled
478
- })).then(() => {
495
+ });
496
+ verifyToken(appCheck).then(() => {
479
497
  setAppCheckLoading(false);
480
498
  });
481
499
  initialCheck.current = true;
@@ -513,7 +531,8 @@ var docsToCollectionTree = (docs) => {
513
531
  Object.keys(collectionsMap).sort((a, b) => b.split(COLLECTION_PATH_SEPARATOR).length - a.split(COLLECTION_PATH_SEPARATOR).length).forEach((id) => {
514
532
  const collection = collectionsMap[id];
515
533
  if (id.includes(COLLECTION_PATH_SEPARATOR)) {
516
- const parentCollection = collectionsMap[id.split(COLLECTION_PATH_SEPARATOR).slice(0, -1).join(COLLECTION_PATH_SEPARATOR)];
534
+ const parentId = id.split(COLLECTION_PATH_SEPARATOR).slice(0, -1).join(COLLECTION_PATH_SEPARATOR);
535
+ const parentCollection = collectionsMap[parentId];
517
536
  if (parentCollection) parentCollection.subcollections = () => [...parentCollection.subcollections?.() ?? [], collection];
518
537
  delete collectionsMap[id];
519
538
  }
@@ -698,7 +717,8 @@ var localSearchControllerBuilder = ({ firebaseApp }) => {
698
717
  return new Promise((resolve, reject) => {
699
718
  if (collectionProp) {
700
719
  console.debug("Init local search controller", path);
701
- listeners[path] = onSnapshot(query(collection(databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp), path)), {
720
+ const col = collection(databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp), path);
721
+ listeners[path] = onSnapshot(query(col), {
702
722
  next: (entity) => {
703
723
  if (entity.metadata.fromCache && entity.metadata.hasPendingWrites) return;
704
724
  const docs = entity.docs.map((doc) => ({
@@ -941,6 +961,29 @@ function buildRebaseSearchController(options) {
941
961
  //#endregion
942
962
  //#region src/hooks/useFirestoreDriver.ts
943
963
  /**
964
+ * The window a read has to ask Firestore for in order to honour `offset`.
965
+ *
966
+ * Firestore's web SDK has no `offset()` — it pages by cursor (`startAfter`)
967
+ * only. Callers that page by offset (`buildRebaseData`, and through it every
968
+ * `findAll()` and `iterate()`) were therefore served page one every time:
969
+ * `count` is a real server count, so `hasMore` never went false, the walk
970
+ * accumulated the same rows over and over, and it ended by tripping its row
971
+ * cap and reporting "matched more than N rows" — a condition that had not
972
+ * occurred.
973
+ *
974
+ * So the read asks for `offset + limit` documents and drops the first
975
+ * `offset`. Those documents are billed either way: Firestore charges for every
976
+ * document a cursor walks past, which is why `startAfter` is the cheap way to
977
+ * page and offset paging over a large collection is not.
978
+ */
979
+ function resolveOffsetWindow(limit, offset) {
980
+ const skip = offset !== void 0 && Number.isFinite(offset) && offset > 0 ? Math.floor(offset) : 0;
981
+ return {
982
+ fetchLimit: limit === void 0 ? void 0 : limit + skip,
983
+ skip
984
+ };
985
+ }
986
+ /**
944
987
  * Use this hook to build a {@link DataDriver} based on Firestore
945
988
  * @param firebaseApp
946
989
  * @param textSearchControllerBuilder
@@ -961,7 +1004,7 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
961
1004
  localTextSearchEnabled,
962
1005
  textSearchControllerBuilder
963
1006
  ]);
964
- const buildQuery = useCallback((path, filter, orderBy$1, order, startAfter$1, limit$1, databaseId) => {
1007
+ const buildQuery = useCallback((path, filter, orderBy$1, order, startAfter$2, limit$1, databaseId) => {
965
1008
  if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
966
1009
  const firestore = databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp);
967
1010
  const collectionReference = collection(firestore, path);
@@ -977,10 +1020,10 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
977
1020
  return;
978
1021
  }
979
1022
  if (op === "like" || op === "ilike" || op === "not-like" || op === "not-ilike") throw new Error(`Firestore does not support the "${op}" operator (SQL pattern matching). Use a full-text search index or the collection's searchString instead.`);
980
- queryParams.push(where(key, op, cmsToFirestoreModel(value, firestore)));
1023
+ queryParams.push(where(key, op, rebaseToFirestoreModel(value, firestore)));
981
1024
  });
982
1025
  if (orderBy$1 && order) queryParams.push(orderBy(orderBy$1, order));
983
- if (startAfter$1) queryParams.push(startAfter(startAfter$1));
1026
+ if (startAfter$2) queryParams.push(startAfter(startAfter$2));
984
1027
  if (limit$1) queryParams.push(limit(limit$1));
985
1028
  return query(collectionReference, ...queryParams);
986
1029
  }, [firebaseApp]);
@@ -1064,26 +1107,29 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1064
1107
  * @param collection
1065
1108
  * @param filter
1066
1109
  * @param limit
1110
+ * @param offset
1067
1111
  * @param startAfter
1068
1112
  * @param searchString
1069
1113
  * @param orderBy
1070
1114
  * @param order
1071
- * @return Function to cancel subscription
1115
+ * @return The rows in the requested window
1072
1116
  * @see useCollection if you need this functionality implemented as a hook
1073
1117
  * @group Firestore
1074
1118
  */
1075
- const fetchCollection = useCallback(async ({ path, filter, limit, startAfter, searchString, orderBy, order, collection }) => {
1119
+ const fetchCollection = useCallback(async ({ path, filter, limit, offset, startAfter, searchString, orderBy, order, collection }) => {
1076
1120
  const databaseId = collection?.databaseId;
1077
1121
  const resolvedPath = path;
1078
1122
  console.debug("Fetching collection", {
1079
1123
  path,
1080
1124
  limit,
1125
+ offset,
1081
1126
  filter,
1082
1127
  startAfter,
1083
1128
  orderBy,
1084
1129
  order
1085
1130
  });
1086
- return (await getDocs(buildQuery(resolvedPath, filter, orderBy, order, startAfter, limit, databaseId))).docs.map((doc) => createRowFromDocument(doc));
1131
+ const { fetchLimit, skip } = resolveOffsetWindow(limit, offset);
1132
+ return (await getDocs(buildQuery(resolvedPath, filter, orderBy, order, startAfter, fetchLimit, databaseId))).docs.slice(skip).map((doc) => createRowFromDocument(doc));
1087
1133
  }, [buildQuery]);
1088
1134
  /**
1089
1135
  * Listen to a entities in a given path
@@ -1165,7 +1211,7 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1165
1211
  values: valuesProp,
1166
1212
  collection: collection$1
1167
1213
  });
1168
- const values = cmsToFirestoreModel(valuesProp, getFirestore(firebaseApp));
1214
+ const values = rebaseToFirestoreModel(valuesProp, getFirestore(firebaseApp));
1169
1215
  console.debug("2", {
1170
1216
  path,
1171
1217
  id,
@@ -1185,7 +1231,7 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1185
1231
  else documentReference = doc(collectionReference);
1186
1232
  return setDoc(documentReference, values, { merge: true }).then(() => {
1187
1233
  return {
1188
- ...firestoreToCMSModel(values),
1234
+ ...firestoreToRebaseModel(values),
1189
1235
  id: documentReference.id
1190
1236
  };
1191
1237
  }).catch((error) => {
@@ -1219,7 +1265,7 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1219
1265
  const databaseId = collection$2?.databaseId;
1220
1266
  const firestore = databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp);
1221
1267
  if (value === void 0 || value === null) return Promise.resolve(true);
1222
- return (await getDocs(query(collection(firestore, path), where(name, "==", cmsToFirestoreModel(value, firestore))))).docs.filter((doc) => doc.id !== id).length === 0;
1268
+ return (await getDocs(query(collection(firestore, path), where(name, "==", rebaseToFirestoreModel(value, firestore))))).docs.filter((doc) => doc.id !== id).length === 0;
1223
1269
  }, [firebaseApp]);
1224
1270
  const count = useCallback(async ({ path, filter, order, orderBy, collection }) => {
1225
1271
  if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
@@ -1273,7 +1319,7 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1273
1319
  }
1274
1320
  var createRowFromDocument = (docSnap) => {
1275
1321
  return {
1276
- ...firestoreToCMSModel(docSnap.data()),
1322
+ ...firestoreToRebaseModel(docSnap.data()),
1277
1323
  id: docSnap.id
1278
1324
  };
1279
1325
  };
@@ -1287,7 +1333,7 @@ var createRowFromDocument = (docSnap) => {
1287
1333
  * @param data
1288
1334
  * @group Firestore
1289
1335
  */
1290
- function firestoreToCMSModel(data) {
1336
+ function firestoreToRebaseModel(data) {
1291
1337
  if (data === null || data === void 0) return null;
1292
1338
  if (typeof data === "object" && data !== null && "isEqual" in data && typeof data.isEqual === "function" && deleteField().isEqual(data)) return;
1293
1339
  if (typeof data === "object" && data !== null && "isEqual" in data && typeof data.isEqual === "function" && serverTimestamp().isEqual(data)) return null;
@@ -1307,11 +1353,11 @@ function firestoreToCMSModel(data) {
1307
1353
  databaseId
1308
1354
  });
1309
1355
  }
1310
- if (Array.isArray(data)) return data.map(firestoreToCMSModel).filter((v) => v !== void 0);
1356
+ if (Array.isArray(data)) return data.map(firestoreToRebaseModel).filter((v) => v !== void 0);
1311
1357
  if (typeof data === "object") {
1312
1358
  const result = {};
1313
1359
  for (const key of Object.keys(data)) {
1314
- const childValue = firestoreToCMSModel(data[key]);
1360
+ const childValue = firestoreToRebaseModel(data[key]);
1315
1361
  if (childValue !== void 0) result[key] = childValue;
1316
1362
  }
1317
1363
  return result;
@@ -1327,10 +1373,10 @@ function getCMSPathFromFirestorePath(fsPath) {
1327
1373
  to = to === -1 ? fsPath.length : to;
1328
1374
  return fsPath.substring(0, to);
1329
1375
  }
1330
- function cmsToFirestoreModel(data, firestore, inArray = false) {
1376
+ function rebaseToFirestoreModel(data, firestore, inArray = false) {
1331
1377
  if (data === void 0) return deleteField();
1332
1378
  else if (data === null) return null;
1333
- else if (Array.isArray(data)) return data.filter((v) => v !== void 0).map((v) => cmsToFirestoreModel(v, firestore, true));
1379
+ else if (Array.isArray(data)) return data.filter((v) => v !== void 0).map((v) => rebaseToFirestoreModel(v, firestore, true));
1334
1380
  else if (typeof data === "object" && data !== null && "isEntityReference" in data && typeof data.isEntityReference === "function" && data.isEntityReference()) {
1335
1381
  const entityRef = data;
1336
1382
  return doc(entityRef.databaseId ? getFirestore(firestore.app, entityRef.databaseId) : firestore, entityRef.path, entityRef.id);
@@ -1341,7 +1387,7 @@ function cmsToFirestoreModel(data, firestore, inArray = false) {
1341
1387
  else if (data instanceof Date) return Timestamp.fromDate(data);
1342
1388
  else if (data && typeof data === "object" && "__type__" in data && data.__type__ === "__vector__") return vector(data.value || []);
1343
1389
  else if (data && typeof data === "object") return Object.entries(data).map(([key, v]) => {
1344
- const firestoreModel = cmsToFirestoreModel(v, firestore);
1390
+ const firestoreModel = rebaseToFirestoreModel(v, firestore);
1345
1391
  if (firestoreModel !== void 0) return { [key]: firestoreModel };
1346
1392
  else return {};
1347
1393
  }).reduce((a, b) => ({
@@ -1381,30 +1427,99 @@ function buildTextSearchControllerWithLocalSearch({ textSearchControllerBuilder,
1381
1427
  }
1382
1428
  //#endregion
1383
1429
  //#region src/hooks/useFirebaseRealTimeDBDelegate.ts
1430
+ var RTDB = "useFirebaseRTDBDelegate";
1431
+ var isRTDBValue = (value) => value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
1432
+ /**
1433
+ * Translate a driver read into the Realtime Database's query model, or refuse it.
1434
+ *
1435
+ * The Realtime Database orders by a single child key per query and bounds that
1436
+ * one key with `equalTo`/`startAt`/`endAt`. Nothing else is expressible: no
1437
+ * second field, no descending order, no text search, no `or(...)` group.
1438
+ *
1439
+ * Everything beyond `limit` and `startAfter` used to be destructured out of the
1440
+ * read and then never referenced, so a caller asking for `status == "draft"`
1441
+ * was handed the entire collection, presented as the answer. A query this
1442
+ * database cannot express is refused here instead — a caller that sees an error
1443
+ * can fall back, a caller that sees the wrong rows cannot.
1444
+ */
1445
+ function planRTDBQuery({ filter, orderBy, order, searchString, logical, limit, offset, startAfter: startAfterKey }) {
1446
+ if (searchString) throw new Error(`${RTDB}: the Realtime Database has no text search, so \`searchString\` cannot be applied. Index the data in a search service instead.`);
1447
+ if (logical) throw new Error(`${RTDB}: the Realtime Database cannot evaluate \`or(...)\`/\`and(...)\` groups.`);
1448
+ if (order === "desc") throw new Error(`${RTDB}: the Realtime Database only orders ascending, so \`order: "desc"\` cannot be applied.`);
1449
+ const conditions = [];
1450
+ Object.entries(filter ?? {}).forEach(([key, entry]) => {
1451
+ if (!entry) return;
1452
+ (Array.isArray(entry[0]) ? entry : [entry]).forEach(([op, value]) => conditions.push([
1453
+ key,
1454
+ op,
1455
+ value
1456
+ ]));
1457
+ });
1458
+ const fields = Array.from(new Set(conditions.map(([key]) => key)));
1459
+ if (fields.length > 1) throw new Error(`${RTDB}: the Realtime Database filters on one child key per query; this read asked for ${fields.join(", ")}.`);
1460
+ const [field] = fields;
1461
+ if (field && orderBy && orderBy !== field) throw new Error(`${RTDB}: a query is ordered by the key it filters on; cannot filter \`${field}\` while ordering by \`${orderBy}\`.`);
1462
+ const orderChild = field ?? orderBy;
1463
+ const plan = orderChild ? { orderByChild: orderChild } : {};
1464
+ for (const [key, op, value] of conditions) {
1465
+ if (!isRTDBValue(value)) throw new Error(`${RTDB}: cannot bound \`${key}\` by a ${Array.isArray(value) ? "array" : typeof value} value; the Realtime Database compares strings, numbers, booleans and null.`);
1466
+ if (op === "==") {
1467
+ if (conditions.length > 1) throw new Error(`${RTDB}: \`==\` bounds a query on its own; it cannot be combined with another condition on \`${key}\`.`);
1468
+ plan.equalTo = value;
1469
+ } else if (op === ">=") plan.startAt = value;
1470
+ else if (op === "<=") plan.endAt = value;
1471
+ else throw new Error(`${RTDB}: the Realtime Database does not support the "${op}" operator (on \`${key}\`). It bounds a single child key with ==, >= and <=.`);
1472
+ }
1473
+ if (startAfterKey !== void 0) {
1474
+ if (orderChild) throw new Error(`${RTDB}: \`startAfter\` pages in key order and cannot be combined with a filter or \`orderBy\`.`);
1475
+ plan.startAfter = String(startAfterKey);
1476
+ }
1477
+ const skip = offset !== void 0 && Number.isFinite(offset) && offset > 0 ? Math.floor(offset) : 0;
1478
+ if (skip > 0) plan.skip = skip;
1479
+ if (limit !== void 0) plan.limitToFirst = limit + skip;
1480
+ return plan;
1481
+ }
1482
+ /** The plan as Realtime Database query constraints. */
1483
+ function rtdbConstraints(plan) {
1484
+ const constraints = [];
1485
+ const bounded = plan.equalTo !== void 0 || plan.startAt !== void 0 || plan.startAfter !== void 0 || plan.endAt !== void 0;
1486
+ if (plan.orderByChild !== void 0) constraints.push(orderByChild(plan.orderByChild));
1487
+ else if (bounded) constraints.push(orderByKey());
1488
+ if (plan.equalTo !== void 0) constraints.push(equalTo(plan.equalTo));
1489
+ if (plan.startAt !== void 0) constraints.push(startAt(plan.startAt));
1490
+ if (plan.startAfter !== void 0) constraints.push(startAfter$1(plan.startAfter));
1491
+ if (plan.endAt !== void 0) constraints.push(endAt(plan.endAt));
1492
+ if (plan.limitToFirst !== void 0) constraints.push(limitToFirst(plan.limitToFirst));
1493
+ return constraints;
1494
+ }
1384
1495
  function useFirebaseRTDBDelegate({ firebaseApp }) {
1385
1496
  return {
1386
1497
  key: "firebase_rtdb",
1387
- fetchCollection: useCallback(async ({ path, filter, limit, startAfter, orderBy, order, searchString }) => {
1498
+ fetchCollection: useCallback(async (props) => {
1388
1499
  if (!firebaseApp) throw new Error("Firebase app not provided");
1389
- let dbQuery = query$1(ref$1(getDatabase(firebaseApp), path));
1390
- if (startAfter !== void 0) dbQuery = query$1(dbQuery, orderByKey(), startAt(String(startAfter)));
1391
- if (limit !== void 0) dbQuery = query$1(dbQuery, limitToFirst(limit));
1392
- const entity = await get(dbQuery);
1393
- if (entity.exists()) return Object.entries(entity.val()).map(([id, values]) => ({
1500
+ const database = getDatabase(firebaseApp);
1501
+ const plan = planRTDBQuery(props);
1502
+ const entity = await get(query$1(ref$1(database, props.path), ...rtdbConstraints(plan)));
1503
+ if (entity.exists()) return Object.entries(entity.val()).slice(plan.skip ?? 0).map(([id, values]) => ({
1394
1504
  ...delegateToCMSModel(values),
1395
1505
  id
1396
1506
  }));
1397
1507
  return [];
1398
1508
  }, [firebaseApp]),
1399
- listenCollection: useCallback(({ path, onUpdate }) => {
1509
+ listenCollection: useCallback((props) => {
1400
1510
  if (!firebaseApp) throw new Error("Firebase app not provided");
1401
- const unsubscribe = onValue(ref$1(getDatabase(firebaseApp), path), (entity) => {
1402
- if (entity.exists()) onUpdate(Object.entries(entity.val()).map(([id, values]) => ({
1403
- ...delegateToCMSModel(values),
1404
- id
1405
- })));
1406
- else onUpdate([]);
1407
- });
1511
+ const database = getDatabase(firebaseApp);
1512
+ const { onUpdate, onError } = props;
1513
+ const plan = planRTDBQuery(props);
1514
+ const unsubscribe = onValue(query$1(ref$1(database, props.path), ...rtdbConstraints(plan)), (entity) => {
1515
+ if (entity.exists()) {
1516
+ const result = Object.entries(entity.val()).slice(plan.skip ?? 0).map(([id, values]) => ({
1517
+ ...delegateToCMSModel(values),
1518
+ id
1519
+ }));
1520
+ onUpdate(result);
1521
+ } else onUpdate([]);
1522
+ }, (error) => onError?.(error));
1408
1523
  return () => unsubscribe();
1409
1524
  }, [firebaseApp]),
1410
1525
  fetchOne: useCallback(async ({ path, id }) => {
@@ -1509,6 +1624,20 @@ function useRecaptcha() {
1509
1624
  //#endregion
1510
1625
  //#region src/hooks/useBuildUserManagement.tsx
1511
1626
  /**
1627
+ * Decide whether a user may access the CMS, given the state of the user
1628
+ * management collection.
1629
+ *
1630
+ * A plain function rather than logic inside the gate callback so the states
1631
+ * that must stay distinct can be asserted without a React render.
1632
+ */
1633
+ function resolveAccessDecision({ loading, usersError, users, user }) {
1634
+ if (loading) return "loading";
1635
+ if (!user) return "no-user";
1636
+ if (usersError) return "users-unreadable";
1637
+ if (users.length === 0) return "bootstrap";
1638
+ return users.some((u) => u.email?.toLowerCase() === user.email?.toLowerCase()) ? "known-user" : "unknown-user";
1639
+ }
1640
+ /**
1512
1641
  * This hook is used to build a user management object that can be used to
1513
1642
  * manage users and roles in a Firestore backend.
1514
1643
  * @param authController
@@ -1575,7 +1704,8 @@ function useBuildUserManagement({ authController, dataSourceDelegate, roles: rol
1575
1704
  console.debug("Updating users", rows);
1576
1705
  setUsersError(void 0);
1577
1706
  try {
1578
- setUsersWithRoleIds(rowsToUsers(rows));
1707
+ const newUsers = rowsToUsers(rows);
1708
+ setUsersWithRoleIds(newUsers);
1579
1709
  } catch (e) {
1580
1710
  setUsersWithRoleIds([]);
1581
1711
  console.error("Error loading users", e);
@@ -1671,17 +1801,27 @@ function useBuildUserManagement({ authController, dataSourceDelegate, roles: rol
1671
1801
  return mgmtUser.roles;
1672
1802
  }, [usersWithRoleIds]);
1673
1803
  const accessGate = useCallback(({ user }) => {
1674
- if (loading) return false;
1675
- if (user === null) {
1804
+ const decision = resolveAccessDecision({
1805
+ loading,
1806
+ usersError,
1807
+ users,
1808
+ user
1809
+ });
1810
+ if (decision === "loading") return false;
1811
+ if (decision === "no-user") {
1676
1812
  console.warn("User is null, returning");
1677
1813
  return false;
1678
1814
  }
1679
- if (users.length === 0) {
1815
+ if (decision === "users-unreadable") {
1816
+ console.error("Denying access: the user management collection could not be read", usersError);
1817
+ return false;
1818
+ }
1819
+ if (decision === "bootstrap") {
1680
1820
  console.warn("No users created yet");
1681
1821
  return true;
1682
1822
  }
1683
1823
  const mgmtUser = users.find((u) => u.email?.toLowerCase() === user?.email?.toLowerCase());
1684
- if (mgmtUser) {
1824
+ if (decision === "known-user" && mgmtUser && user) {
1685
1825
  const needsUidUpdate = mgmtUser.uid !== user.uid;
1686
1826
  const needsPhotoUpdate = user.photoURL && mgmtUser.photoURL !== user.photoURL;
1687
1827
  if (needsUidUpdate || needsPhotoUpdate) {
@@ -1700,7 +1840,11 @@ function useBuildUserManagement({ authController, dataSourceDelegate, roles: rol
1700
1840
  return true;
1701
1841
  }
1702
1842
  throw Error("Could not find a user with the provided email in the user management system.");
1703
- }, [loading, users]);
1843
+ }, [
1844
+ loading,
1845
+ users,
1846
+ usersError
1847
+ ]);
1704
1848
  const userRoles = authController.user ? defineRolesFor(authController.user) : void 0;
1705
1849
  const isAdmin = (userRoles ?? []).some((r) => r === "admin");
1706
1850
  useEffect(() => {
@@ -2645,6 +2789,6 @@ function RebaseFirebaseApp({ name, logo, logoDark, accessGate, collections, view
2645
2789
  }) });
2646
2790
  }
2647
2791
  //#endregion
2648
- export { FirebaseLoginView, LoginButton, RECAPTCHA_CONTAINER_ID, RebaseFirebaseApp, buildCollectionId, buildExternalSearchController, buildPineconeSearchController, buildRebaseSearchController, cmsToFirestoreModel, docToCollection, docsToCollectionTree, firestoreToCMSModel, getFirestoreDataInPath, localSearchControllerBuilder, performAlgoliaTextSearch, performPineconeTextSearch, useAppCheck, useBuildUserManagement, useFirebaseAccessGate, useFirebaseAuthController, useFirebaseRTDBDelegate, useFirebaseStorageSource, useFirestoreDriver, useInitialiseFirebase, useRecaptcha };
2792
+ export { FirebaseLoginView, LoginButton, RECAPTCHA_CONTAINER_ID, RebaseFirebaseApp, buildCollectionId, buildExternalSearchController, buildPineconeSearchController, buildRebaseSearchController, docToCollection, docsToCollectionTree, firestoreToRebaseModel, getFirestoreDataInPath, localSearchControllerBuilder, performAlgoliaTextSearch, performPineconeTextSearch, planRTDBQuery, rebaseToFirestoreModel, resolveAccessDecision, resolveOffsetWindow, resolveRoleRefresh, useAppCheck, useBuildUserManagement, useFirebaseAccessGate, useFirebaseAuthController, useFirebaseRTDBDelegate, useFirebaseStorageSource, useFirestoreDriver, useInitialiseFirebase, useRecaptcha };
2649
2793
 
2650
2794
  //# sourceMappingURL=index.es.js.map