@rebasepro/firebase 0.30.1 → 0.31.0-canary.g59cd6fd

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -1,11 +1,12 @@
1
+ import { ALL_WHERE_FILTER_OPS, DEFAULT_DATA_SOURCE_KEY, registerDataSourceCapabilities, resolveResourceRefs, resourceKeyOf } from "@rebasepro/types";
1
2
  import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
3
  import { deepEqual } from "fast-equals";
3
4
  import { FacebookAuthProvider, GithubAuthProvider, GoogleAuthProvider, OAuthProvider, PhoneAuthProvider, PhoneMultiFactorGenerator, RecaptchaVerifier, TwitterAuthProvider, createUserWithEmailAndPassword, fetchSignInMethodsForEmail, getAuth, getMultiFactorResolver, onAuthStateChanged, sendPasswordResetEmail, signInAnonymously, signInWithEmailAndPassword, signInWithPhoneNumber, signInWithPopup, signOut } from "firebase/auth";
4
5
  import { deleteObject, getDownloadURL, getMetadata, getStorage, list, ref, uploadBytesResumable } from "firebase/storage";
5
6
  import { deleteApp, getApps, initializeApp } from "firebase/app";
6
7
  import { getToken, initializeAppCheck } from "firebase/app-check";
7
- import { DEFAULT_DATA_SOURCE_KEY, EntityReference, GeoPoint } from "@rebasepro/types";
8
- import { COLLECTION_PATH_SEPARATOR, buildRebaseData, buildSdkData, normalizeDriverOrderBy, sortProperties, stripCollectionPath, toFilterTuples } from "@rebasepro/common";
8
+ import { buildSdkData, normalizeDriverOrderBy, toFilterTuples } from "@rebasepro/common";
9
+ import { COLLECTION_PATH_SEPARATOR, EntityReference, GeoPoint, buildRebaseData, sortProperties, stripCollectionPath } from "@rebasepro/cms-types";
9
10
  import { DocumentReference, GeoPoint as GeoPoint$1, Timestamp, VectorValue, and, collection, deleteDoc, deleteField, doc, getCountFromServer, getDoc, getDocs, getFirestore, limit, onSnapshot, or, orderBy, query, serverTimestamp, setDoc, startAfter, vector, where } from "firebase/firestore";
10
11
  import Fuse from "fuse.js";
11
12
  import { getFunctions, httpsCallable } from "firebase/functions";
@@ -16,6 +17,171 @@ import { AppBar, CollectionRegistryContext, Drawer, NavigationStateContext, Reba
16
17
  import { ArrowLeftIcon, Button, CenteredView, CircularProgress, CircularProgressCenter, IconButton, LoadingButton, MailIcon, PhoneIcon, TextField, Typography, UserIcon, cls, iconSize } from "@rebasepro/ui";
17
18
  import { Navigate, Outlet, Route } from "react-router";
18
19
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
20
+ //#region src/capabilities.ts
21
+ /**
22
+ * What the Firestore engine can do, as the admin asks it: which editor tabs a
23
+ * collection gets (subcollections, never relations), which filter operators a
24
+ * column offers, whether a reference property exists.
25
+ *
26
+ * Firestore's own declaration, owned by the package that drives it. The admin
27
+ * reads capabilities through `getDataSourceCapabilities(engine)`, and this
28
+ * package registers this object under `firestore` before any of its
29
+ * collections can be rendered (see {@link registerFirestoreCapabilities}) — so
30
+ * the admin's answer for a Firestore collection never depends on a copy kept in
31
+ * `@rebasepro/types`.
32
+ *
33
+ * @group Firebase
34
+ */
35
+ var FIRESTORE_CAPABILITIES = {
36
+ key: "firestore",
37
+ label: "Firebase / Firestore",
38
+ supportsRelations: false,
39
+ supportsSubcollections: true,
40
+ supportsRLS: false,
41
+ supportsReferences: true,
42
+ supportsColumnTypes: false,
43
+ supportsRealtime: true,
44
+ supportsVectors: false,
45
+ filterOperators: ALL_WHERE_FILTER_OPS.filter((op) => op !== "like" && op !== "ilike" && op !== "not-like" && op !== "not-ilike" && op !== "array-contains-all" && op !== "array-contained-by"),
46
+ filterableRelationKinds: [],
47
+ supportsRelationFieldFilters: false,
48
+ relationAggregateSorts: false,
49
+ supportsSQLAdmin: false,
50
+ supportsSchemaAdmin: false
51
+ };
52
+ /**
53
+ * Register {@link FIRESTORE_CAPABILITIES} under the `firestore` engine.
54
+ *
55
+ * Runs when this module is evaluated — which importing `defineFirestoreCollection`
56
+ * or anything else from `@rebasepro/firebase` does — and again from
57
+ * `useFirestoreDataSource`, for a bundle that evaluated a second copy of the
58
+ * types package after this one. Without it, `getDataSourceCapabilities("firestore")`
59
+ * would answer with the permissive default: relation tabs, and "Contains"
60
+ * filters the driver refuses at query time.
61
+ *
62
+ * Idempotent: the registry is a map on a global symbol, keyed by engine.
63
+ *
64
+ * @group Firebase
65
+ */
66
+ function registerFirestoreCapabilities() {
67
+ registerDataSourceCapabilities(FIRESTORE_CAPABILITIES);
68
+ }
69
+ registerFirestoreCapabilities();
70
+ //#endregion
71
+ //#region src/collections/fields.ts
72
+ /**
73
+ * Turn a collection's fields into the property model the admin and the
74
+ * Firestore driver read: `required` becomes `validation.required`, a
75
+ * reference's `target` becomes its `path`, nested fields are normalised the
76
+ * same way. Every other key is kept as written.
77
+ *
78
+ * @param fields the fields, by key
79
+ * @param where who is asking, for the error messages — the collection's slug
80
+ * @group Firebase
81
+ */
82
+ function normalizeFirestoreFields(fields, where) {
83
+ const properties = {};
84
+ for (const [key, field] of Object.entries(fields)) properties[key] = normalizeFirestoreField(field, `${where}: field "${key}"`);
85
+ return properties;
86
+ }
87
+ function normalizeFirestoreField(field, where) {
88
+ if (typeof field !== "object" || field === null || typeof field.type !== "string") throw new Error(`${where} is not a field: write \`{ type: "string" }\` (or another field type) as its value.`);
89
+ const type = field.type;
90
+ switch (field.type) {
91
+ case "reference": {
92
+ if ("path" in field) throw new Error(`${where} sets \`path\`. A Firestore field names the collection it points at with \`target: "<collection slug>"\`, on any data source — write that instead.`);
93
+ const { required, target, ...property } = field;
94
+ return withRequired(target !== void 0 ? {
95
+ ...property,
96
+ path: target
97
+ } : property, required, where);
98
+ }
99
+ case "map": {
100
+ const { required, properties, ...property } = field;
101
+ return withRequired(properties !== void 0 ? {
102
+ ...property,
103
+ properties: normalizeFirestoreFields(properties, `${where}.properties`)
104
+ } : property, required, where);
105
+ }
106
+ case "array": {
107
+ const { required, of, oneOf, ...property } = field;
108
+ const normalizedOf = of === void 0 ? void 0 : isFieldList(of) ? of.map((item, index) => normalizeFirestoreField(item, `${where}.of[${index}]`)) : normalizeFirestoreField(of, `${where}.of`);
109
+ const normalizedOneOf = oneOf === void 0 ? void 0 : {
110
+ ...oneOf,
111
+ properties: normalizeFirestoreFields(oneOf.properties, `${where}.oneOf`)
112
+ };
113
+ return withRequired({
114
+ ...property,
115
+ ...normalizedOf !== void 0 ? { of: normalizedOf } : {},
116
+ ...normalizedOneOf !== void 0 ? { oneOf: normalizedOneOf } : {}
117
+ }, required, where);
118
+ }
119
+ case "string": {
120
+ const { required, ...property } = field;
121
+ return withRequired(property, required, where);
122
+ }
123
+ case "number": {
124
+ const { required, ...property } = field;
125
+ return withRequired(property, required, where);
126
+ }
127
+ case "boolean": {
128
+ const { required, ...property } = field;
129
+ return withRequired(property, required, where);
130
+ }
131
+ case "date": {
132
+ const { required, ...property } = field;
133
+ return withRequired(property, required, where);
134
+ }
135
+ case "geopoint": {
136
+ const { required, ...property } = field;
137
+ return withRequired(property, required, where);
138
+ }
139
+ case "binary": {
140
+ const { required, ...property } = field;
141
+ return withRequired(property, required, where);
142
+ }
143
+ default: throw new Error(`${where} has type "${type}", which Firestore does not store. Use one of string, number, boolean, date, geopoint, map, array, reference or binary — a relation or a vector belongs to a Postgres table.`);
144
+ }
145
+ }
146
+ function isFieldList(of) {
147
+ return Array.isArray(of);
148
+ }
149
+ /** `property` with `required` written into its `validation`; refused when the two disagree. */
150
+ function withRequired(property, required, where) {
151
+ if (required === void 0) return property;
152
+ const declared = property.validation?.required;
153
+ if (declared !== void 0 && declared !== required) throw new Error(`${where} says \`required: ${String(required)}\` and \`validation.required: ${String(declared)}\`. Write it once — \`required\` is short for \`validation.required\`.`);
154
+ return {
155
+ ...property,
156
+ validation: {
157
+ ...property.validation,
158
+ required
159
+ }
160
+ };
161
+ }
162
+ //#endregion
163
+ //#region src/collections/defineFirestoreCollection.ts
164
+ /**
165
+ * At runtime: the fields normalised into properties, `engine: "firestore"`
166
+ * stamped, and a resource handle written where a key belongs (`dataSource`,
167
+ * a field's `storage.storageSource`) replaced by its key.
168
+ * @group Firebase
169
+ */
170
+ function defineFirestoreCollection(collection) {
171
+ const where = `defineFirestoreCollection("${String(collection.slug)}")`;
172
+ if ("properties" in collection) throw new Error(`${where} has \`properties\`. A Firestore collection declares its fields under \`fields\`.`);
173
+ if ("engine" in collection) throw new Error(`${where} has \`engine\`. Leave it out: a collection defined here is always a Firestore one.`);
174
+ if (typeof collection.fields !== "object" || collection.fields === null) throw new Error(`${where} has no \`fields\`. Declare the collection's fields: \`fields: { name: { type: "string" } }\`.`);
175
+ const { fields, dataSource, subcollections, ...rest } = collection;
176
+ return resolveResourceRefs({
177
+ ...rest,
178
+ engine: "firestore",
179
+ properties: normalizeFirestoreFields(fields, where),
180
+ ...dataSource !== void 0 ? { dataSource: resourceKeyOf(dataSource) } : {},
181
+ ...subcollections !== void 0 ? { subcollections } : {}
182
+ });
183
+ }
184
+ //#endregion
19
185
  //#region src/hooks/useFirebaseAuthController.ts
20
186
  /**
21
187
  * Resolve `user`'s roles through `defineRolesFor` and report whether they
@@ -1039,12 +1205,12 @@ function listenToSearchResults({ ids, limit, offset, listenOne, onUpdate, onErro
1039
1205
  * Null-testing operators map to `==` / `!=` against null. Firestore has no
1040
1206
  * LIKE/ILIKE, so those fail loudly rather than return wrong results.
1041
1207
  */
1042
- function firestoreCondition(key, op, value, firestore) {
1208
+ function firestoreCondition(key, op, value, firestore, options) {
1043
1209
  if (op === "is-null") return where(key, "==", null);
1044
1210
  if (op === "is-not-null") return where(key, "!=", null);
1045
1211
  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.`);
1046
1212
  if (op === "array-contains-all" || op === "array-contained-by") throw new Error(`Firestore does not support the "${op}" operator: it matches one element of an array (array-contains) or any of a list (array-contains-any).`);
1047
- return where(key, op, rebaseToFirestoreModel(value, firestore));
1213
+ return where(key, op, rebaseToFirestoreModel(value, firestore, options));
1048
1214
  }
1049
1215
  /**
1050
1216
  * An `or(...)` / `and(...)` group as a Firestore composite filter, nesting
@@ -1055,18 +1221,18 @@ function firestoreCondition(key, op, value, firestore) {
1055
1221
  * one — Firestore has no negation of a conjunction, and `!=` on each leaf
1056
1222
  * matches a different set of documents.
1057
1223
  */
1058
- function firestoreLogicalCondition(logical, firestore) {
1224
+ function firestoreLogicalCondition(logical, firestore, options) {
1059
1225
  if (!logical || !Array.isArray(logical.conditions)) return void 0;
1060
1226
  if (logical.type === "not") throw new Error("Firestore does not support a not(...) filter group. Write the condition without the negation.");
1061
1227
  const parts = [];
1062
1228
  for (const entry of logical.conditions) {
1063
1229
  if (!entry) continue;
1064
1230
  if ("conditions" in entry) {
1065
- const nested = firestoreLogicalCondition(entry, firestore);
1231
+ const nested = firestoreLogicalCondition(entry, firestore, options);
1066
1232
  if (nested) parts.push(nested);
1067
1233
  continue;
1068
1234
  }
1069
- parts.push(firestoreCondition(entry.column, entry.operator, entry.value, firestore));
1235
+ parts.push(firestoreCondition(entry.column, entry.operator, entry.value, firestore, options));
1070
1236
  }
1071
1237
  if (parts.length === 0) return void 0;
1072
1238
  return logical.type === "or" ? or(...parts) : and(...parts);
@@ -1077,7 +1243,14 @@ function firestoreLogicalCondition(logical, firestore) {
1077
1243
  * @param textSearchControllerBuilder
1078
1244
  * @group Firebase
1079
1245
  */
1080
- function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestoreIndexesBuilder, localTextSearchEnabled }) {
1246
+ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestoreIndexesBuilder, localTextSearchEnabled, dataSourceKey, databaseId: defaultDatabaseId }) {
1247
+ /** The Firestore of `databaseId`, else of the driver's default database. */
1248
+ const firestoreOf = useCallback((app, databaseId) => {
1249
+ const resolved = databaseId ?? defaultDatabaseId;
1250
+ return resolved ? getFirestore(app, resolved) : getFirestore(app);
1251
+ }, [defaultDatabaseId]);
1252
+ /** How this driver converts values: see {@link FirestoreModelOptions}. */
1253
+ const modelOptions = useMemo(() => ({ dataSourceKey }), [dataSourceKey]);
1081
1254
  const searchControllerRef = useRef(void 0);
1082
1255
  useEffect(() => {
1083
1256
  if (!searchControllerRef.current && firebaseApp) {
@@ -1094,35 +1267,46 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1094
1267
  ]);
1095
1268
  const buildQuery = useCallback((path, filter, orderBy$1, order, startAfter$2, limit$1, databaseId, logical) => {
1096
1269
  if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
1097
- const firestore = databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp);
1270
+ const firestore = firestoreOf(firebaseApp, databaseId);
1098
1271
  const collectionReference = collection(firestore, path);
1099
1272
  const filters = [];
1100
- for (const [key, filterParameter] of Object.entries(filter ?? {})) for (const [op, value] of toFilterTuples(filterParameter)) filters.push(firestoreCondition(key, op, value, firestore));
1101
- const group = firestoreLogicalCondition(logical, firestore);
1273
+ for (const [key, filterParameter] of Object.entries(filter ?? {})) for (const [op, value] of toFilterTuples(filterParameter)) filters.push(firestoreCondition(key, op, value, firestore, modelOptions));
1274
+ const group = firestoreLogicalCondition(logical, firestore, modelOptions);
1102
1275
  const queryParams = [];
1103
1276
  for (const [field, direction] of normalizeDriverOrderBy(orderBy$1, order) ?? []) queryParams.push(orderBy(field, direction));
1104
1277
  if (startAfter$2) queryParams.push(startAfter(startAfter$2));
1105
1278
  if (limit$1) queryParams.push(limit(limit$1));
1106
1279
  if (group) return query(collectionReference, and(...filters, group), ...queryParams);
1107
1280
  return query(collectionReference, ...filters, ...queryParams);
1108
- }, [firebaseApp]);
1281
+ }, [
1282
+ firebaseApp,
1283
+ firestoreOf,
1284
+ modelOptions
1285
+ ]);
1109
1286
  const getAndBuildEntity = useCallback((path, id, databaseId) => {
1110
1287
  if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
1111
- return getDoc(doc(databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp), path, String(id))).then((docEntity) => {
1288
+ return getDoc(doc(firestoreOf(firebaseApp, databaseId), path, String(id))).then((docEntity) => {
1112
1289
  if (!docEntity.exists()) return;
1113
- return createRowFromDocument(docEntity);
1290
+ return createRowFromDocument(docEntity, modelOptions);
1114
1291
  });
1115
- }, [firebaseApp]);
1292
+ }, [
1293
+ firebaseApp,
1294
+ firestoreOf,
1295
+ modelOptions
1296
+ ]);
1116
1297
  const listenOne = useCallback(({ path, id, collection, onUpdate, onError }) => {
1117
1298
  if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
1118
- const databaseId = collection?.databaseId;
1119
- return onSnapshot(doc(databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp), path, String(id)), {
1299
+ return onSnapshot(doc(firestoreOf(firebaseApp, collection?.databaseId), path, String(id)), {
1120
1300
  next: (docEntity) => {
1121
- onUpdate(docEntity.exists() ? createRowFromDocument(docEntity) : null);
1301
+ onUpdate(docEntity.exists() ? createRowFromDocument(docEntity, modelOptions) : null);
1122
1302
  },
1123
1303
  error: onError
1124
1304
  });
1125
- }, [firebaseApp]);
1305
+ }, [
1306
+ firebaseApp,
1307
+ firestoreOf,
1308
+ modelOptions
1309
+ ]);
1126
1310
  /** The ids the text search controller finds for `searchString` under `path`. */
1127
1311
  const searchIds = useCallback((path, searchString, databaseId) => {
1128
1312
  if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
@@ -1201,11 +1385,12 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1201
1385
  readOne: (id) => getAndBuildEntity(resolvedPath, id, databaseId)
1202
1386
  });
1203
1387
  const { fetchLimit, skip } = resolveOffsetWindow(limit, offset);
1204
- return (await getDocs(buildQuery(resolvedPath, filter, orderBy, order, startAfter, fetchLimit, databaseId, logical))).docs.slice(skip).map((doc) => createRowFromDocument(doc));
1388
+ return (await getDocs(buildQuery(resolvedPath, filter, orderBy, order, startAfter, fetchLimit, databaseId, logical))).docs.slice(skip).map((doc) => createRowFromDocument(doc, modelOptions));
1205
1389
  }, [
1206
1390
  buildQuery,
1207
1391
  searchIds,
1208
- getAndBuildEntity
1392
+ getAndBuildEntity,
1393
+ modelOptions
1209
1394
  ]);
1210
1395
  /**
1211
1396
  * Listen to a entities in a given path
@@ -1253,14 +1438,15 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1253
1438
  const { fetchLimit, skip } = resolveOffsetWindow(limit, offset);
1254
1439
  return onSnapshot(buildQuery(resolvedPath, filter, orderBy, order, startAfter, fetchLimit, databaseId, logical), {
1255
1440
  next: (entity) => {
1256
- onUpdate(entity.docs.slice(skip).map((doc) => createRowFromDocument(doc)));
1441
+ onUpdate(entity.docs.slice(skip).map((doc) => createRowFromDocument(doc, modelOptions)));
1257
1442
  },
1258
1443
  error: onError
1259
1444
  });
1260
1445
  }, [
1261
1446
  buildQuery,
1262
1447
  firebaseApp,
1263
- performTextSearch
1448
+ performTextSearch,
1449
+ modelOptions
1264
1450
  ]);
1265
1451
  /**
1266
1452
  * Retrieve a entity given a path and a collection
@@ -1291,15 +1477,16 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1291
1477
  values: valuesProp,
1292
1478
  collection: collection$1
1293
1479
  });
1294
- const values = rebaseToFirestoreModel(valuesProp, getFirestore(firebaseApp));
1480
+ const databaseId = collection$1?.databaseId;
1481
+ const firestore = firestoreOf(firebaseApp, databaseId);
1482
+ const values = rebaseToFirestoreModel(valuesProp, firestore, modelOptions);
1295
1483
  console.debug("2", {
1296
1484
  path,
1297
1485
  id,
1298
1486
  values: valuesProp,
1299
1487
  collection: collection$1
1300
1488
  });
1301
- const databaseId = collection$1?.databaseId;
1302
- const collectionReference = collection(databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp), path);
1489
+ const collectionReference = collection(firestore, path);
1303
1490
  console.debug("Saving entity", {
1304
1491
  path,
1305
1492
  id,
@@ -1311,14 +1498,18 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1311
1498
  else documentReference = doc(collectionReference);
1312
1499
  return setDoc(documentReference, values, { merge: true }).then(() => {
1313
1500
  return {
1314
- ...firestoreToRebaseModel(values),
1501
+ ...firestoreToRebaseModel(values, modelOptions),
1315
1502
  id: documentReference.id
1316
1503
  };
1317
1504
  }).catch((error) => {
1318
1505
  console.error("Error saving entity", error);
1319
1506
  throw error;
1320
1507
  });
1321
- }, [firebaseApp]);
1508
+ }, [
1509
+ firebaseApp,
1510
+ firestoreOf,
1511
+ modelOptions
1512
+ ]);
1322
1513
  /**
1323
1514
  * Delete a entity
1324
1515
  * @param entity
@@ -1327,9 +1518,8 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1327
1518
  */
1328
1519
  const deleteOne = useCallback(({ row, collection }) => {
1329
1520
  if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
1330
- const databaseId = collection?.databaseId;
1331
- return deleteDoc(doc(databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp), row.path, String(row.id)));
1332
- }, [firebaseApp]);
1521
+ return deleteDoc(doc(firestoreOf(firebaseApp, collection?.databaseId), row.path, String(row.id)));
1522
+ }, [firebaseApp, firestoreOf]);
1333
1523
  /**
1334
1524
  * Check if the given property is unique in the given collection
1335
1525
  * @param path Collection path
@@ -1342,11 +1532,14 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1342
1532
  */
1343
1533
  const checkUniqueField = useCallback(async (path, name, value, id, collection$2) => {
1344
1534
  if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
1345
- const databaseId = collection$2?.databaseId;
1346
- const firestore = databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp);
1535
+ const firestore = firestoreOf(firebaseApp, collection$2?.databaseId);
1347
1536
  if (value === void 0 || value === null) return Promise.resolve(true);
1348
- return (await getDocs(query(collection(firestore, path), where(name, "==", rebaseToFirestoreModel(value, firestore))))).docs.filter((doc) => doc.id !== id).length === 0;
1349
- }, [firebaseApp]);
1537
+ return (await getDocs(query(collection(firestore, path), where(name, "==", rebaseToFirestoreModel(value, firestore, modelOptions))))).docs.filter((doc) => doc.id !== id).length === 0;
1538
+ }, [
1539
+ firebaseApp,
1540
+ firestoreOf,
1541
+ modelOptions
1542
+ ]);
1350
1543
  const count = useCallback(async ({ path, filter, logical, order, orderBy, searchString, collection }) => {
1351
1544
  if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
1352
1545
  const databaseId = collection?.databaseId;
@@ -1403,9 +1596,25 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1403
1596
  isFilterCombinationValid
1404
1597
  ]);
1405
1598
  }
1406
- var createRowFromDocument = (docSnap) => {
1599
+ /**
1600
+ * The engine name a reference's `driver` may carry instead of a data-source
1601
+ * key — `new EntityReference({ …, driver: "firestore" })` — and which always
1602
+ * means a Firestore document.
1603
+ */
1604
+ var FIRESTORE_ENGINE = "firestore";
1605
+ /**
1606
+ * Does `reference` point into another data source than the one `options`
1607
+ * describes? Only when both are known and differ: a reference that names no
1608
+ * `driver` is one of the driver's own documents, as it always was.
1609
+ */
1610
+ function isForeignReference(reference, options) {
1611
+ const own = options?.dataSourceKey;
1612
+ const target = reference.driver;
1613
+ return own !== void 0 && target !== void 0 && target !== own && target !== FIRESTORE_ENGINE;
1614
+ }
1615
+ var createRowFromDocument = (docSnap, options) => {
1407
1616
  return {
1408
- ...firestoreToRebaseModel(docSnap.data()),
1617
+ ...firestoreToRebaseModel(docSnap.data(), options),
1409
1618
  id: docSnap.id
1410
1619
  };
1411
1620
  };
@@ -1415,11 +1624,20 @@ var createRowFromDocument = (docSnap) => {
1415
1624
  * Rebase uses Javascript dates internally instead of Firestore timestamps.
1416
1625
  * This makes it easier to interact with the rest of the libraries and
1417
1626
  * bindings.
1418
- * Also, Firestore references are replaced with {@link EntityReference}
1627
+ *
1628
+ * Firestore references are replaced with {@link EntityReference}s carrying
1629
+ * the stored path, the Firestore database, and — when `options` names the
1630
+ * driver's data source — that key as their `driver`.
1631
+ *
1632
+ * A reference to a record of another data source is stored as the record's
1633
+ * id (see {@link rebaseToFirestoreModel}) and comes back as that id: the
1634
+ * document holds no more than that. The admin turns it back into a reference
1635
+ * from the field's `target`, which it knows and this function does not.
1419
1636
  * @param data
1637
+ * @param options
1420
1638
  * @group Firestore
1421
1639
  */
1422
- function firestoreToRebaseModel(data) {
1640
+ function firestoreToRebaseModel(data, options) {
1423
1641
  if (data === null || data === void 0) return null;
1424
1642
  if (typeof data === "object" && data !== null && "isEqual" in data && typeof data.isEqual === "function" && deleteField().isEqual(data)) return;
1425
1643
  if (typeof data === "object" && data !== null && "isEqual" in data && typeof data.isEqual === "function" && serverTimestamp().isEqual(data)) return null;
@@ -1437,14 +1655,16 @@ function firestoreToRebaseModel(data) {
1437
1655
  return new EntityReference({
1438
1656
  id: data.id,
1439
1657
  path: getCMSPathFromFirestorePath(data.path),
1440
- databaseId
1658
+ databaseId,
1659
+ ...options?.dataSourceKey !== void 0 ? { driver: options.dataSourceKey } : {}
1441
1660
  });
1442
1661
  }
1443
- if (Array.isArray(data)) return data.map(firestoreToRebaseModel).filter((v) => v !== void 0);
1662
+ if (data instanceof EntityReference) return data;
1663
+ if (Array.isArray(data)) return data.map((item) => firestoreToRebaseModel(item, options)).filter((v) => v !== void 0);
1444
1664
  if (typeof data === "object") {
1445
1665
  const result = {};
1446
1666
  for (const key of Object.keys(data)) {
1447
- const childValue = firestoreToRebaseModel(data[key]);
1667
+ const childValue = firestoreToRebaseModel(data[key], options);
1448
1668
  if (childValue !== void 0) result[key] = childValue;
1449
1669
  }
1450
1670
  return result;
@@ -1460,12 +1680,42 @@ function getCMSPathFromFirestorePath(fsPath) {
1460
1680
  to = to === -1 ? fsPath.length : to;
1461
1681
  return fsPath.substring(0, to);
1462
1682
  }
1463
- function rebaseToFirestoreModel(data, firestore, inArray = false) {
1683
+ /**
1684
+ * Convert values as the admin holds them into what Firestore stores: a
1685
+ * `Date` as a `Timestamp`, a `GeoPoint` as Firestore's, a vector as a
1686
+ * `VectorValue`, `undefined` as a field deletion.
1687
+ *
1688
+ * References are stored by where they point:
1689
+ *
1690
+ * - to a document of this Firestore — a reference with no `driver`, or one
1691
+ * naming this data source — as a `DocumentReference`, exactly as before;
1692
+ * - to a record of **another** data source (its `driver` names a different
1693
+ * key than `options.dataSourceKey`) as the record's id, a plain string. A
1694
+ * `DocumentReference` there would point at a document that does not exist,
1695
+ * and a query for the record would never match it.
1696
+ *
1697
+ * @param data the values
1698
+ * @param firestore the Firestore the references point into
1699
+ * @param options which data source the values belong to; `inArray` is
1700
+ * internal (an element of an array cannot hold a field deletion)
1701
+ * @group Firestore
1702
+ */
1703
+ function rebaseToFirestoreModel(data, firestore, options) {
1704
+ const inArray = options?.inArray ?? false;
1464
1705
  if (data === void 0) return inArray ? void 0 : deleteField();
1465
1706
  else if (data === null) return null;
1466
- else if (Array.isArray(data)) return data.filter((v) => v !== void 0).map((v) => rebaseToFirestoreModel(v, firestore, true));
1467
- else if (typeof data === "object" && data !== null && "isEntityReference" in data && typeof data.isEntityReference === "function" && data.isEntityReference()) {
1468
- const entityRef = data;
1707
+ else if (Array.isArray(data)) return data.filter((v) => v !== void 0).map((v) => rebaseToFirestoreModel(v, firestore, {
1708
+ ...options,
1709
+ inArray: true
1710
+ }));
1711
+ else if (data instanceof EntityReference || typeof data === "object" && "isEntityReference" in data && typeof data.isEntityReference === "function" && data.isEntityReference() === true && "path" in data && "id" in data) {
1712
+ const entityRef = data instanceof EntityReference ? data : new EntityReference({
1713
+ id: String(Reflect.get(data, "id")),
1714
+ path: String(Reflect.get(data, "path")),
1715
+ driver: stringOrUndefined(Reflect.get(data, "driver")),
1716
+ databaseId: stringOrUndefined(Reflect.get(data, "databaseId"))
1717
+ });
1718
+ if (isForeignReference(entityRef, options)) return entityRef.id;
1469
1719
  return doc(entityRef.databaseId ? getFirestore(firestore.app, entityRef.databaseId) : firestore, entityRef.path, entityRef.id);
1470
1720
  } else if (data && typeof data === "object" && "__type" in data && data.__type === "relation" && "path" in data && "id" in data) {
1471
1721
  const rel = data;
@@ -1474,7 +1724,7 @@ function rebaseToFirestoreModel(data, firestore, inArray = false) {
1474
1724
  else if (data instanceof Date) return Timestamp.fromDate(data);
1475
1725
  else if (data && typeof data === "object" && "__type__" in data && data.__type__ === "__vector__") return vector(data.value || []);
1476
1726
  else if (data && typeof data === "object") return Object.entries(data).map(([key, v]) => {
1477
- const firestoreModel = rebaseToFirestoreModel(v, firestore, inArray);
1727
+ const firestoreModel = rebaseToFirestoreModel(v, firestore, options);
1478
1728
  if (firestoreModel !== void 0) return { [key]: firestoreModel };
1479
1729
  else return {};
1480
1730
  }).reduce((a, b) => ({
@@ -1483,6 +1733,9 @@ function rebaseToFirestoreModel(data, firestore, inArray = false) {
1483
1733
  }), {});
1484
1734
  return data;
1485
1735
  }
1736
+ function stringOrUndefined(value) {
1737
+ return typeof value === "string" ? value : void 0;
1738
+ }
1486
1739
  function currentTime() {
1487
1740
  return serverTimestamp();
1488
1741
  }
@@ -1513,6 +1766,49 @@ function buildTextSearchControllerWithLocalSearch({ textSearchControllerBuilder,
1513
1766
  };
1514
1767
  }
1515
1768
  //#endregion
1769
+ //#region src/hooks/useFirestoreDataSource.ts
1770
+ /**
1771
+ * A Firestore data source for `<Rebase dataSources={[…]}>`: the browser reads
1772
+ * and writes the collections whose `dataSource` is `key` straight from
1773
+ * Firestore, beside the Postgres tables the Rebase client serves.
1774
+ *
1775
+ * The entry is the same object on every render while the options are, so it
1776
+ * can be written inline in `dataSources` without rebuilding the data layer.
1777
+ * It also registers Firestore's capabilities, so its collections never get
1778
+ * relation tabs or filters Firestore cannot run.
1779
+ *
1780
+ * @example
1781
+ * ```tsx
1782
+ * const firestoreSource = useFirestoreDataSource({ key: "firestore", firebaseApp });
1783
+ * return <Rebase client={rebaseClient} dataSources={[firestoreSource]}>…</Rebase>;
1784
+ * ```
1785
+ * @group Firebase
1786
+ */
1787
+ function useFirestoreDataSource({ key, firebaseApp, databaseId, label, textSearchControllerBuilder, localTextSearchEnabled, firestoreIndexesBuilder }) {
1788
+ registerFirestoreCapabilities();
1789
+ const driver = useFirestoreDriver({
1790
+ firebaseApp,
1791
+ textSearchControllerBuilder,
1792
+ localTextSearchEnabled,
1793
+ firestoreIndexesBuilder,
1794
+ dataSourceKey: key,
1795
+ databaseId
1796
+ });
1797
+ return useMemo(() => ({
1798
+ key,
1799
+ engine: "firestore",
1800
+ transport: "direct",
1801
+ driver,
1802
+ ...databaseId !== void 0 ? { databaseId } : {},
1803
+ ...label !== void 0 ? { label } : {}
1804
+ }), [
1805
+ key,
1806
+ driver,
1807
+ databaseId,
1808
+ label
1809
+ ]);
1810
+ }
1811
+ //#endregion
1516
1812
  //#region src/hooks/useFirebaseRealTimeDBDelegate.ts
1517
1813
  var RTDB = "useFirebaseRTDBDelegate";
1518
1814
  var isRTDBValue = (value) => value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
@@ -2787,12 +3083,14 @@ function RebaseFirebaseApp({ name, logo, logoDark, accessGate, collections, view
2787
3083
  * Controller for saving some user preferences locally.
2788
3084
  */
2789
3085
  const userConfigPersistence = useBuildLocalConfigurationPersistence();
2790
- const firestoreDelegate = useFirestoreDriver({
3086
+ const firestoreSource = useFirestoreDataSource({
3087
+ key: DEFAULT_DATA_SOURCE_KEY,
2791
3088
  firebaseApp,
2792
3089
  textSearchControllerBuilder,
2793
3090
  firestoreIndexesBuilder,
2794
3091
  localTextSearchEnabled
2795
3092
  });
3093
+ const firestoreDelegate = firestoreSource.driver;
2796
3094
  /**
2797
3095
  * Controller used for saving and fetching files in storage
2798
3096
  */
@@ -2844,12 +3142,7 @@ function RebaseFirebaseApp({ name, logo, logoDark, accessGate, collections, view
2844
3142
  modeController,
2845
3143
  userConfigPersistence,
2846
3144
  dateTimeFormat,
2847
- dataSources: [{
2848
- key: DEFAULT_DATA_SOURCE_KEY,
2849
- engine: "firestore",
2850
- transport: "direct",
2851
- driver: firestoreDelegate
2852
- }],
3145
+ dataSources: [firestoreSource],
2853
3146
  storageSource,
2854
3147
  entityLinkBuilder: ({ id, path }) => `https://console.firebase.google.com/project/${firebaseApp.options.projectId}/firestore/data/${path}/${id}`,
2855
3148
  locale,
@@ -2909,6 +3202,6 @@ function RebaseFirebaseApp({ name, logo, logoDark, accessGate, collections, view
2909
3202
  }) });
2910
3203
  }
2911
3204
  //#endregion
2912
- export { FirebaseLoginView, LoginButton, RECAPTCHA_CONTAINER_ID, RebaseFirebaseApp, buildCollectionId, buildExternalSearchController, buildPineconeSearchController, buildRebaseSearchController, docToCollection, docsToCollectionTree, firestoreLogicalCondition, firestoreToRebaseModel, getFirestoreDataInPath, listenToSearchResults, localSearchControllerBuilder, performAlgoliaTextSearch, performPineconeTextSearch, planRTDBQuery, readSearchResults, rebaseToFirestoreModel, resolveAccessDecision, resolveOffsetWindow, resolveRoleRefresh, useAppCheck, useBuildUserManagement, useFirebaseAccessGate, useFirebaseAuthController, useFirebaseRTDBDelegate, useFirebaseStorageSource, useFirestoreDriver, useInitialiseFirebase, useRecaptcha };
3205
+ export { FIRESTORE_CAPABILITIES, FirebaseLoginView, LoginButton, RECAPTCHA_CONTAINER_ID, RebaseFirebaseApp, buildCollectionId, buildExternalSearchController, buildPineconeSearchController, buildRebaseSearchController, defineFirestoreCollection, docToCollection, docsToCollectionTree, firestoreLogicalCondition, firestoreToRebaseModel, getFirestoreDataInPath, listenToSearchResults, localSearchControllerBuilder, normalizeFirestoreFields, performAlgoliaTextSearch, performPineconeTextSearch, planRTDBQuery, readSearchResults, rebaseToFirestoreModel, registerFirestoreCapabilities, resolveAccessDecision, resolveOffsetWindow, resolveRoleRefresh, useAppCheck, useBuildUserManagement, useFirebaseAccessGate, useFirebaseAuthController, useFirebaseRTDBDelegate, useFirebaseStorageSource, useFirestoreDataSource, useFirestoreDriver, useInitialiseFirebase, useRecaptcha };
2913
3206
 
2914
3207
  //# sourceMappingURL=index.es.js.map