@ponceca/firestore-sdk 0.1.0

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 (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +692 -0
  3. package/dist/app.d.mts +51 -0
  4. package/dist/app.d.ts +51 -0
  5. package/dist/app.js +16 -0
  6. package/dist/app.js.map +1 -0
  7. package/dist/app.mjs +16 -0
  8. package/dist/app.mjs.map +1 -0
  9. package/dist/auth/index.d.mts +43 -0
  10. package/dist/auth/index.d.ts +43 -0
  11. package/dist/auth/index.js +18 -0
  12. package/dist/auth/index.js.map +1 -0
  13. package/dist/auth/index.mjs +18 -0
  14. package/dist/auth/index.mjs.map +1 -0
  15. package/dist/chunk-2RQUHE2K.js +719 -0
  16. package/dist/chunk-2RQUHE2K.js.map +1 -0
  17. package/dist/chunk-4CV4JOE5.js +27 -0
  18. package/dist/chunk-4CV4JOE5.js.map +1 -0
  19. package/dist/chunk-57XXMSJA.js +65 -0
  20. package/dist/chunk-57XXMSJA.js.map +1 -0
  21. package/dist/chunk-6J3LNKUQ.js +213 -0
  22. package/dist/chunk-6J3LNKUQ.js.map +1 -0
  23. package/dist/chunk-BXV7KTHB.js +645 -0
  24. package/dist/chunk-BXV7KTHB.js.map +1 -0
  25. package/dist/chunk-C3PCJJX4.mjs +645 -0
  26. package/dist/chunk-C3PCJJX4.mjs.map +1 -0
  27. package/dist/chunk-C6SKWUQV.mjs +213 -0
  28. package/dist/chunk-C6SKWUQV.mjs.map +1 -0
  29. package/dist/chunk-DXPQJR5D.mjs +2469 -0
  30. package/dist/chunk-DXPQJR5D.mjs.map +1 -0
  31. package/dist/chunk-MRVKMKSO.mjs +65 -0
  32. package/dist/chunk-MRVKMKSO.mjs.map +1 -0
  33. package/dist/chunk-NFEGQTCC.mjs +27 -0
  34. package/dist/chunk-NFEGQTCC.mjs.map +1 -0
  35. package/dist/chunk-RSBBZLDE.js +128 -0
  36. package/dist/chunk-RSBBZLDE.js.map +1 -0
  37. package/dist/chunk-RZWTSZSJ.js +2469 -0
  38. package/dist/chunk-RZWTSZSJ.js.map +1 -0
  39. package/dist/chunk-SZKHE2TQ.mjs +719 -0
  40. package/dist/chunk-SZKHE2TQ.mjs.map +1 -0
  41. package/dist/chunk-ZJ4A4Y2T.mjs +128 -0
  42. package/dist/chunk-ZJ4A4Y2T.mjs.map +1 -0
  43. package/dist/firestore/index.d.mts +1476 -0
  44. package/dist/firestore/index.d.ts +1476 -0
  45. package/dist/firestore/index.js +156 -0
  46. package/dist/firestore/index.js.map +1 -0
  47. package/dist/firestore/index.mjs +156 -0
  48. package/dist/firestore/index.mjs.map +1 -0
  49. package/dist/http-A2S5CWEV.js +10 -0
  50. package/dist/http-A2S5CWEV.js.map +1 -0
  51. package/dist/http-SZFONH6Z.mjs +10 -0
  52. package/dist/http-SZFONH6Z.mjs.map +1 -0
  53. package/dist/index.d.mts +4 -0
  54. package/dist/index.d.ts +4 -0
  55. package/dist/index.js +171 -0
  56. package/dist/index.js.map +1 -0
  57. package/dist/index.mjs +171 -0
  58. package/dist/index.mjs.map +1 -0
  59. package/dist/indexeddb-mutation-queue-5EB7C2D5.js +192 -0
  60. package/dist/indexeddb-mutation-queue-5EB7C2D5.js.map +1 -0
  61. package/dist/indexeddb-mutation-queue-M2MAH4E4.mjs +192 -0
  62. package/dist/indexeddb-mutation-queue-M2MAH4E4.mjs.map +1 -0
  63. package/dist/indexeddb-store-D23ZY3PR.mjs +162 -0
  64. package/dist/indexeddb-store-D23ZY3PR.mjs.map +1 -0
  65. package/dist/indexeddb-store-DNWBZUQE.js +162 -0
  66. package/dist/indexeddb-store-DNWBZUQE.js.map +1 -0
  67. package/dist/snapshot-MCQVLVHL.js +22 -0
  68. package/dist/snapshot-MCQVLVHL.js.map +1 -0
  69. package/dist/snapshot-ZWZFIFZD.mjs +22 -0
  70. package/dist/snapshot-ZWZFIFZD.mjs.map +1 -0
  71. package/dist/types-meoR-Ecp.d.mts +269 -0
  72. package/dist/types-meoR-Ecp.d.ts +269 -0
  73. package/package.json +78 -0
@@ -0,0 +1,1476 @@
1
+ import { g as Firestore, e as FirebaseApp, j as FirestoreSettings, a as DocumentData, l as FirestoreInstance, C as CollectionReference, b as DocumentReference, c as DocumentSnapshot, S as SetOptions, E as EndAtConstraint, Q as Query, k as QuerySnapshot, m as LimitConstraint, O as OrderByDirection, n as OrderByConstraint, o as QueryConstraint, p as StartAtConstraint, W as WhereFilterOp, q as WhereConstraint, r as SnapshotListenOptions, U as Unsubscribe, d as FieldValue } from '../types-meoR-Ecp.js';
2
+ export { A as AuthTokenProvider, D as DocumentChange, s as DocumentChangeType, F as FieldPath, h as FirestoreError, i as FirestoreErrorCode, L as ListenSource } from '../types-meoR-Ecp.js';
3
+
4
+ /**
5
+ * Firestore SDK - Firestore Instance
6
+ * getFirestore, initializeFirestore, connectFirestoreEmulator
7
+ * API 100% compatible con Firebase v9+
8
+ */
9
+
10
+ /**
11
+ * Obtiene la instancia de Firestore para una app
12
+ *
13
+ * @param app Aplicación Firebase (opcional, usa la app por defecto)
14
+ * @returns Instancia de Firestore
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import { initializeApp } from '@ponceca/firestore-sdk';
19
+ * import { getFirestore } from '@ponceca/firestore-sdk/firestore';
20
+ *
21
+ * const app = initializeApp({
22
+ * projectId: 'my-project'
23
+ * });
24
+ *
25
+ * const db = getFirestore(app);
26
+ * ```
27
+ */
28
+ declare function getFirestore(app?: FirebaseApp): Firestore;
29
+ /**
30
+ * Inicializa Firestore con configuración personalizada
31
+ *
32
+ * @param app Aplicación Firebase
33
+ * @param settings Configuración de Firestore
34
+ * @returns Instancia de Firestore configurada
35
+ *
36
+ * @example
37
+ * ```typescript
38
+ * const db = initializeFirestore(app, {
39
+ * host: 'firestore.example.com',
40
+ * ssl: true
41
+ * });
42
+ * ```
43
+ */
44
+ declare function initializeFirestore(app: FirebaseApp, settings: FirestoreSettings): Firestore;
45
+ /**
46
+ * Termina la instancia de Firestore
47
+ *
48
+ * @param firestore Instancia de Firestore
49
+ */
50
+ declare function terminate(firestore: Firestore): Promise<void>;
51
+ /**
52
+ * Limpia la persistencia local.
53
+ * Borra todo el cache de documentos y la cola de mutaciones pendientes.
54
+ * Debe llamarse cuando Firestore NO está en uso (antes de inicializar o después de terminar).
55
+ *
56
+ * @param firestore Instancia de Firestore
57
+ */
58
+ declare function clearIndexedDbPersistence(firestore: Firestore): Promise<void>;
59
+ /**
60
+ * Habilita la persistencia offline para Firestore.
61
+ * Activa el cache local de documentos y la cola de mutaciones para operaciones offline.
62
+ * Debe llamarse antes de cualquier otra operación con Firestore.
63
+ *
64
+ * @param firestore Instancia de Firestore
65
+ *
66
+ * @example
67
+ * ```typescript
68
+ * const db = getFirestore(app);
69
+ * await enableIndexedDbPersistence(db);
70
+ * // Ahora las lecturas/escrituras funcionan offline
71
+ * ```
72
+ */
73
+ declare function enableIndexedDbPersistence(firestore: Firestore): Promise<void>;
74
+ /**
75
+ * Habilita la persistencia offline multi-tab.
76
+ * Activa la misma persistencia que enableIndexedDbPersistence.
77
+ * En esta implementación, multi-tab opera igual que single-tab.
78
+ *
79
+ * @param firestore Instancia de Firestore
80
+ */
81
+ declare function enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise<void>;
82
+ /**
83
+ * Habilita la red — reanuda la comunicación con el servidor.
84
+ * Sincroniza las mutaciones pendientes en la cola.
85
+ * Si no hay persistencia habilitada, es un no-op.
86
+ *
87
+ * @param firestore Instancia de Firestore
88
+ */
89
+ declare function enableNetwork(firestore: Firestore): Promise<void>;
90
+ /**
91
+ * Deshabilita la red — todas las operaciones serán locales.
92
+ * Las escrituras se acumulan en la cola de mutaciones hasta que se re-habilite.
93
+ * Las lecturas se servirán desde el cache local.
94
+ * Si no hay persistencia habilitada, es un no-op.
95
+ *
96
+ * @param firestore Instancia de Firestore
97
+ */
98
+ declare function disableNetwork(firestore: Firestore): Promise<void>;
99
+ /**
100
+ * Espera a que todas las operaciones pendientes se sincronicen con el servidor.
101
+ * Resuelve inmediatamente si no hay escrituras pendientes o si la persistencia no está habilitada.
102
+ *
103
+ * @param firestore Instancia de Firestore
104
+ */
105
+ declare function waitForPendingWrites(firestore: Firestore): Promise<void>;
106
+ /**
107
+ * Conecta Firestore al emulador local
108
+ * Compatible con Firebase: connectFirestoreEmulator(db, 'localhost', 8080)
109
+ *
110
+ * @param firestore Instancia de Firestore
111
+ * @param host Host del emulador (ej: 'localhost')
112
+ * @param port Puerto del emulador (ej: 3000)
113
+ * @param options Opciones adicionales (mockUserToken para auth)
114
+ *
115
+ * @example
116
+ * ```typescript
117
+ * import { getFirestore, connectFirestoreEmulator } from '@ponceca/firestore-sdk/firestore';
118
+ *
119
+ * const db = getFirestore(app);
120
+ *
121
+ * // Conectar al emulador local
122
+ * connectFirestoreEmulator(db, 'localhost', 3000);
123
+ * ```
124
+ */
125
+ declare function connectFirestoreEmulator(firestore: Firestore, host: string, port: number, options?: {
126
+ mockUserToken?: string | object;
127
+ }): void;
128
+ /**
129
+ * Establece el token de autenticación para Firestore
130
+ * Útil para integrar con sistemas de auth externos o JWT personalizados
131
+ *
132
+ * @param firestore Instancia de Firestore
133
+ * @param token Token de autenticación (JWT, API Key, etc.) o null para eliminar
134
+ *
135
+ * @example
136
+ * ```typescript
137
+ * import { getFirestore, setAuthToken } from '@ponceca/firestore-sdk/firestore';
138
+ *
139
+ * const db = getFirestore(app);
140
+ *
141
+ * // Establecer token JWT
142
+ * setAuthToken(db, 'eyJhbGciOiJIUzI1NiIs...');
143
+ *
144
+ * // O con un token de tu sistema de auth
145
+ * const userToken = await myAuthSystem.getToken();
146
+ * setAuthToken(db, userToken);
147
+ *
148
+ * // Eliminar token (logout)
149
+ * setAuthToken(db, null);
150
+ * ```
151
+ */
152
+ declare function setAuthToken(firestore: Firestore, token: string | null): void;
153
+ /**
154
+ * Obtiene el token de autenticación actual
155
+ *
156
+ * @param firestore Instancia de Firestore
157
+ * @returns Token actual o undefined si no hay
158
+ */
159
+ declare function getAuthToken(firestore: Firestore): string | undefined;
160
+
161
+ /**
162
+ * Firestore SDK - Referencias
163
+ * doc(), collection(), DocumentReference, CollectionReference
164
+ */
165
+
166
+ /**
167
+ * Crea una referencia a un documento
168
+ *
169
+ * @param firestore Instancia de Firestore
170
+ * @param pathSegments Segmentos del path
171
+ * @returns DocumentReference
172
+ *
173
+ * @example
174
+ * ```typescript
175
+ * // Path directo
176
+ * const ref = doc(db, 'users', 'user123');
177
+ *
178
+ * // Desde colección
179
+ * const ref = doc(collection(db, 'users'), 'user123');
180
+ *
181
+ * // Subcolección
182
+ * const ref = doc(db, 'users', 'user123', 'posts', 'post456');
183
+ * ```
184
+ */
185
+ declare function doc<T = DocumentData>(firestore: FirestoreInstance, ...pathSegments: string[]): DocumentReference<T>;
186
+ declare function doc<T = DocumentData>(reference: CollectionReference<T>, ...pathSegments: string[]): DocumentReference<T>;
187
+ /**
188
+ * Crea una referencia a una colección
189
+ *
190
+ * @param firestore Instancia de Firestore
191
+ * @param pathSegments Segmentos del path
192
+ * @returns CollectionReference
193
+ *
194
+ * @example
195
+ * ```typescript
196
+ * // Colección de primer nivel
197
+ * const ref = collection(db, 'users');
198
+ *
199
+ * // Subcolección
200
+ * const ref = collection(db, 'users', 'user123', 'posts');
201
+ *
202
+ * // Desde documento
203
+ * const ref = collection(doc(db, 'users', 'user123'), 'posts');
204
+ * ```
205
+ */
206
+ declare function collection<T = DocumentData>(firestore: FirestoreInstance, ...pathSegments: string[]): CollectionReference<T>;
207
+ declare function collection<T = DocumentData>(reference: DocumentReference, ...pathSegments: string[]): CollectionReference<T>;
208
+
209
+ /**
210
+ * Firestore SDK - CRUD Operations
211
+ * getDoc, setDoc, updateDoc, deleteDoc, addDoc
212
+ */
213
+
214
+ /**
215
+ * Obtiene un documento de Firestore
216
+ *
217
+ * @param reference Referencia al documento
218
+ * @returns Promise con DocumentSnapshot
219
+ *
220
+ * @example
221
+ * ```typescript
222
+ * const docRef = doc(db, 'users', 'user123');
223
+ * const snapshot = await getDoc(docRef);
224
+ *
225
+ * if (snapshot.exists()) {
226
+ * console.log('Data:', snapshot.data());
227
+ * } else {
228
+ * console.log('No existe');
229
+ * }
230
+ * ```
231
+ */
232
+ declare function getDoc<T = DocumentData>(reference: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
233
+ /**
234
+ * Obtiene un documento exclusivamente del cache local.
235
+ * Compatible con Firestore Web SDK: getDocFromCache(ref)
236
+ */
237
+ declare function getDocFromCache<T = DocumentData>(reference: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
238
+ /**
239
+ * Escribe un documento en Firestore
240
+ * Sobrescribe el documento si existe, lo crea si no existe
241
+ *
242
+ * @param reference Referencia al documento
243
+ * @param data Datos a escribir
244
+ * @param options Opciones de escritura
245
+ *
246
+ * @example
247
+ * ```typescript
248
+ * // Sobrescribir completamente
249
+ * await setDoc(doc(db, 'users', 'user123'), {
250
+ * name: 'Juan',
251
+ * age: 25
252
+ * });
253
+ *
254
+ * // Merge con datos existentes
255
+ * await setDoc(doc(db, 'users', 'user123'), {
256
+ * age: 26
257
+ * }, { merge: true });
258
+ * ```
259
+ */
260
+ declare function setDoc<T = DocumentData>(reference: DocumentReference<T>, data: T, options?: SetOptions): Promise<void>;
261
+ /**
262
+ * Obtiene un documento forzando lectura desde el servidor
263
+ * Siempre hace la petición al servidor, ignorando el cache local.
264
+ * Actualiza el cache si la persistencia está habilitada.
265
+ *
266
+ * @param reference Referencia al documento
267
+ * @returns Promise con DocumentSnapshot
268
+ */
269
+ declare function getDocFromServer<T = DocumentData>(reference: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
270
+ /**
271
+ * Actualiza campos específicos de un documento
272
+ * El documento debe existir
273
+ *
274
+ * Soporta dos formas de invocación:
275
+ * 1. updateDoc(ref, { field: value, ... })
276
+ * 2. updateDoc(ref, field, value, ...moreFieldsAndValues)
277
+ *
278
+ * @param reference Referencia al documento
279
+ * @param dataOrField Objeto con campos o nombre del primer campo
280
+ * @param moreFieldsAndValues Valores alternados field, value, field, value...
281
+ *
282
+ * @example
283
+ * ```typescript
284
+ * // Forma objeto
285
+ * await updateDoc(doc(db, 'users', 'user123'), {
286
+ * age: 26,
287
+ * 'address.city': 'Madrid'
288
+ * });
289
+ *
290
+ * // Forma alternada campo/valor
291
+ * await updateDoc(doc(db, 'users', 'user123'), 'age', 26, 'name', 'Ana');
292
+ * ```
293
+ */
294
+ declare function updateDoc<T = DocumentData>(reference: DocumentReference<T>, dataOrField: Partial<T> | string, ...moreFieldsAndValues: unknown[]): Promise<void>;
295
+ /**
296
+ * Elimina un documento de Firestore
297
+ *
298
+ * @param reference Referencia al documento
299
+ *
300
+ * @example
301
+ * ```typescript
302
+ * await deleteDoc(doc(db, 'users', 'user123'));
303
+ * ```
304
+ */
305
+ declare function deleteDoc(reference: DocumentReference): Promise<void>;
306
+ /**
307
+ * Añade un nuevo documento a una colección con ID auto-generado
308
+ *
309
+ * @param reference Referencia a la colección
310
+ * @param data Datos del documento
311
+ * @returns Referencia al nuevo documento
312
+ *
313
+ * @example
314
+ * ```typescript
315
+ * const newDocRef = await addDoc(collection(db, 'users'), {
316
+ * name: 'Juan',
317
+ * age: 25
318
+ * });
319
+ * console.log('Nuevo ID:', newDocRef.id);
320
+ * ```
321
+ */
322
+ declare function addDoc<T = DocumentData>(reference: CollectionReference<T>, data: T): Promise<DocumentReference<T>>;
323
+
324
+ /**
325
+ * Firestore SDK - Query Builder
326
+ * query, where, orderBy, limit, limitToLast, startAt, startAfter, endAt, endBefore, getDocs
327
+ */
328
+
329
+ /**
330
+ * Crea una nueva query con las restricciones especificadas
331
+ *
332
+ * @param reference Referencia a la colección
333
+ * @param constraints Restricciones de query
334
+ * @returns Nueva Query
335
+ *
336
+ * @example
337
+ * ```typescript
338
+ * const q = query(
339
+ * collection(db, 'users'),
340
+ * where('age', '>=', 18),
341
+ * orderBy('age', 'desc'),
342
+ * limit(10)
343
+ * );
344
+ * ```
345
+ */
346
+ declare function query<T = DocumentData>(reference: CollectionReference<T> | Query<T>, ...constraints: QueryConstraint[]): Query<T>;
347
+ declare function where(field: string, op: WhereFilterOp, value: unknown): WhereConstraint;
348
+ /**
349
+ * Crea una restricción ORDER BY
350
+ *
351
+ * @param field Campo por el cual ordenar
352
+ * @param direction Dirección del orden ('asc' | 'desc')
353
+ *
354
+ * @example
355
+ * ```typescript
356
+ * orderBy('createdAt', 'desc')
357
+ * orderBy('name') // 'asc' por defecto
358
+ * ```
359
+ */
360
+ declare function orderBy(field: string, direction?: OrderByDirection): OrderByConstraint;
361
+ /**
362
+ * Limita el número de resultados
363
+ *
364
+ * @param n Número máximo de documentos
365
+ *
366
+ * @example
367
+ * ```typescript
368
+ * limit(10)
369
+ * ```
370
+ */
371
+ declare function limit(n: number): LimitConstraint;
372
+ /**
373
+ * Limita el número de resultados desde el final
374
+ *
375
+ * @param n Número máximo de documentos
376
+ *
377
+ * @example
378
+ * ```typescript
379
+ * limitToLast(5)
380
+ * ```
381
+ */
382
+ declare function limitToLast(n: number): LimitConstraint;
383
+ /**
384
+ * Inicia la query desde un punto específico (inclusivo)
385
+ *
386
+ * @param values Valores de cursor
387
+ *
388
+ * @example
389
+ * ```typescript
390
+ * query(ref, orderBy('age'), startAt(18))
391
+ * ```
392
+ */
393
+ declare function startAt(...values: unknown[]): StartAtConstraint;
394
+ /**
395
+ * Inicia la query después de un punto específico (exclusivo)
396
+ *
397
+ * @param values Valores de cursor
398
+ *
399
+ * @example
400
+ * ```typescript
401
+ * query(ref, orderBy('age'), startAfter(18))
402
+ * ```
403
+ */
404
+ declare function startAfter(...values: unknown[]): StartAtConstraint;
405
+ /**
406
+ * Termina la query en un punto específico (inclusivo)
407
+ *
408
+ * @param values Valores de cursor
409
+ *
410
+ * @example
411
+ * ```typescript
412
+ * query(ref, orderBy('age'), endAt(65))
413
+ * ```
414
+ */
415
+ declare function endAt(...values: unknown[]): EndAtConstraint;
416
+ /**
417
+ * Termina la query antes de un punto específico (exclusivo)
418
+ *
419
+ * @param values Valores de cursor
420
+ *
421
+ * @example
422
+ * ```typescript
423
+ * query(ref, orderBy('age'), endBefore(65))
424
+ * ```
425
+ */
426
+ declare function endBefore(...values: unknown[]): EndAtConstraint;
427
+ /**
428
+ * Ejecuta una query y obtiene los documentos
429
+ *
430
+ * @param queryRef Query a ejecutar
431
+ * @returns Promise con QuerySnapshot
432
+ *
433
+ * @example
434
+ * ```typescript
435
+ * const q = query(collection(db, 'users'), where('age', '>=', 18));
436
+ * const snapshot = await getDocs(q);
437
+ *
438
+ * snapshot.forEach(doc => {
439
+ * console.log(doc.id, '=>', doc.data());
440
+ * });
441
+ * ```
442
+ */
443
+ declare function getDocs<T = DocumentData>(queryRef: Query<T> | CollectionReference<T>): Promise<QuerySnapshot<T>>;
444
+ /**
445
+ * Obtiene documentos exclusivamente del cache local.
446
+ * Compatible con Firestore Web SDK: getDocsFromCache(query)
447
+ */
448
+ declare function getDocsFromCache<T = DocumentData>(queryRef: Query<T> | CollectionReference<T>): Promise<QuerySnapshot<T>>;
449
+ /**
450
+ * Obtiene documentos forzando lectura desde el servidor
451
+ * Siempre toca el servidor, ignorando el cache local.
452
+ * Actualiza el cache si la persistencia está habilitada.
453
+ *
454
+ * @param queryRef Query o referencia a colección
455
+ * @returns Promise con QuerySnapshot
456
+ */
457
+ declare function getDocsFromServer<T = DocumentData>(queryRef: Query<T> | CollectionReference<T>): Promise<QuerySnapshot<T>>;
458
+
459
+ /**
460
+ * Firestore SDK - Real-time Listeners
461
+ * onSnapshot para documentos y queries
462
+ */
463
+
464
+ /**
465
+ * Callback para cambios en documentos
466
+ */
467
+ type DocumentSnapshotCallback<T = DocumentData> = (snapshot: DocumentSnapshot<T>) => void;
468
+ /**
469
+ * Callback para cambios en queries
470
+ */
471
+ type QuerySnapshotCallback<T = DocumentData> = (snapshot: QuerySnapshot<T>) => void;
472
+ /**
473
+ * Callback para errores
474
+ */
475
+ type ErrorCallback = (error: Error) => void;
476
+ /**
477
+ * Observer para snapshots
478
+ */
479
+ interface SnapshotObserver<T> {
480
+ next?: (snapshot: T) => void;
481
+ error?: (error: Error) => void;
482
+ complete?: () => void;
483
+ }
484
+ /**
485
+ * Escucha cambios en un documento en tiempo real
486
+ *
487
+ * @param reference Referencia al documento
488
+ * @param onNext Callback llamado cuando hay cambios
489
+ * @param onError Callback para errores (opcional)
490
+ * @returns Función para cancelar la suscripción
491
+ *
492
+ * @example
493
+ * ```typescript
494
+ * const unsubscribe = onSnapshot(
495
+ * doc(db, 'users', 'user123'),
496
+ * (snapshot) => {
497
+ * if (snapshot.exists()) {
498
+ * console.log('Data:', snapshot.data());
499
+ * }
500
+ * },
501
+ * (error) => {
502
+ * console.error('Error:', error);
503
+ * }
504
+ * );
505
+ *
506
+ * // Cancelar suscripción
507
+ * unsubscribe();
508
+ * ```
509
+ */
510
+ declare function onSnapshot<T = DocumentData>(reference: DocumentReference<T>, options: SnapshotListenOptions, onNext: DocumentSnapshotCallback<T>, onError?: ErrorCallback): Unsubscribe;
511
+ /**
512
+ * Escucha cambios en un documento con opciones y observer
513
+ */
514
+ declare function onSnapshot<T = DocumentData>(reference: DocumentReference<T>, options: SnapshotListenOptions, observer: SnapshotObserver<DocumentSnapshot<T>>): Unsubscribe;
515
+ /**
516
+ * Escucha cambios en un documento en tiempo real
517
+ */
518
+ declare function onSnapshot<T = DocumentData>(reference: DocumentReference<T>, onNext: DocumentSnapshotCallback<T>, onError?: ErrorCallback): Unsubscribe;
519
+ /**
520
+ * Escucha cambios en un documento con observer
521
+ */
522
+ declare function onSnapshot<T = DocumentData>(reference: DocumentReference<T>, observer: SnapshotObserver<DocumentSnapshot<T>>): Unsubscribe;
523
+ /**
524
+ * Escucha cambios en una query en tiempo real
525
+ *
526
+ * @param query Query a escuchar
527
+ * @param onNext Callback llamado cuando hay cambios
528
+ * @param onError Callback para errores (opcional)
529
+ * @returns Función para cancelar la suscripción
530
+ *
531
+ * @example
532
+ * ```typescript
533
+ * const q = query(collection(db, 'messages'), orderBy('timestamp', 'desc'), limit(50));
534
+ *
535
+ * const unsubscribe = onSnapshot(q, (snapshot) => {
536
+ * snapshot.docChanges().forEach(change => {
537
+ * if (change.type === 'added') {
538
+ * console.log('Nuevo mensaje:', change.doc.data());
539
+ * }
540
+ * });
541
+ * });
542
+ * ```
543
+ */
544
+ declare function onSnapshot<T = DocumentData>(query: Query<T> | CollectionReference<T>, options: SnapshotListenOptions, onNext: QuerySnapshotCallback<T>, onError?: ErrorCallback): Unsubscribe;
545
+ /**
546
+ * Escucha cambios en una query con opciones y observer
547
+ */
548
+ declare function onSnapshot<T = DocumentData>(query: Query<T> | CollectionReference<T>, options: SnapshotListenOptions, observer: SnapshotObserver<QuerySnapshot<T>>): Unsubscribe;
549
+ /**
550
+ * Escucha cambios en una query en tiempo real
551
+ */
552
+ declare function onSnapshot<T = DocumentData>(query: Query<T> | CollectionReference<T>, onNext: QuerySnapshotCallback<T>, onError?: ErrorCallback): Unsubscribe;
553
+ /**
554
+ * Escucha cambios en una query con observer
555
+ */
556
+ declare function onSnapshot<T = DocumentData>(query: Query<T> | CollectionReference<T>, observer: SnapshotObserver<QuerySnapshot<T>>): Unsubscribe;
557
+
558
+ /**
559
+ * Firestore SDK - Field Values
560
+ * serverTimestamp, increment, arrayUnion, arrayRemove, deleteField
561
+ */
562
+
563
+ /**
564
+ * Crea un valor que será reemplazado por el timestamp del servidor
565
+ *
566
+ * @returns FieldValue representando el timestamp del servidor
567
+ *
568
+ * @example
569
+ * ```typescript
570
+ * await setDoc(doc(db, 'posts', 'post1'), {
571
+ * title: 'Mi post',
572
+ * createdAt: serverTimestamp()
573
+ * });
574
+ * ```
575
+ */
576
+ declare function serverTimestamp(): FieldValue;
577
+ /**
578
+ * Crea un valor que incrementa el campo numérico existente
579
+ * Soporta números y strings numéricos (para alta precisión).
580
+ *
581
+ * @param n Cantidad a incrementar (puede ser negativo)
582
+ * @returns FieldValue representando el incremento
583
+ *
584
+ * @example
585
+ * ```typescript
586
+ * await updateDoc(doc(db, 'counters', 'pageViews'), {
587
+ * count: increment(1)
588
+ * });
589
+ * // Precisión decimal
590
+ * await updateDoc(doc(db, 'accounts', 'wallet'), {
591
+ * balance: increment("100.50")
592
+ * });
593
+ * ```
594
+ */
595
+ declare function increment(n: number | string): FieldValue;
596
+ /**
597
+ * Crea un valor que añade elementos a un array existente
598
+ * Solo añade elementos que no existen ya
599
+ *
600
+ * @param elements Elementos a añadir
601
+ * @returns FieldValue representando la unión de arrays
602
+ *
603
+ * @example
604
+ * ```typescript
605
+ * await updateDoc(doc(db, 'users', 'user1'), {
606
+ * tags: arrayUnion('developer', 'javascript')
607
+ * });
608
+ * ```
609
+ */
610
+ declare function arrayUnion(...elements: unknown[]): FieldValue;
611
+ /**
612
+ * Crea un valor que elimina elementos de un array existente
613
+ *
614
+ * @param elements Elementos a eliminar
615
+ * @returns FieldValue representando la eliminación de elementos
616
+ *
617
+ * @example
618
+ * ```typescript
619
+ * await updateDoc(doc(db, 'users', 'user1'), {
620
+ * tags: arrayRemove('oldTag')
621
+ * });
622
+ * ```
623
+ */
624
+ declare function arrayRemove(...elements: unknown[]): FieldValue;
625
+ /**
626
+ * Crea un valor que elimina el campo del documento
627
+ *
628
+ * @returns FieldValue representando la eliminación del campo
629
+ *
630
+ * @example
631
+ * ```typescript
632
+ * await updateDoc(doc(db, 'users', 'user1'), {
633
+ * tempField: deleteField()
634
+ * });
635
+ * ```
636
+ */
637
+ declare function deleteField(): FieldValue;
638
+
639
+ /**
640
+ * Firestore SDK - WriteBatch & Transaction
641
+ * Operaciones atómicas en batch y transacciones
642
+ */
643
+
644
+ /**
645
+ * Batch de escrituras atómicas
646
+ */
647
+ interface WriteBatch {
648
+ /**
649
+ * Establece un documento
650
+ */
651
+ set<T = DocumentData>(reference: DocumentReference<T>, data: T, options?: SetOptions): WriteBatch;
652
+ /**
653
+ * Actualiza un documento
654
+ */
655
+ update<T = DocumentData>(reference: DocumentReference<T>, data: Partial<T>): WriteBatch;
656
+ /**
657
+ * Elimina un documento
658
+ */
659
+ delete(reference: DocumentReference): WriteBatch;
660
+ /**
661
+ * Ejecuta el batch
662
+ */
663
+ commit(): Promise<void>;
664
+ }
665
+ /**
666
+ * Crea un nuevo WriteBatch
667
+ *
668
+ * @param firestore Instancia de Firestore
669
+ * @returns WriteBatch
670
+ *
671
+ * @example
672
+ * ```typescript
673
+ * const batch = writeBatch(db);
674
+ *
675
+ * batch.set(doc(db, 'cities', 'NYC'), { name: 'New York' });
676
+ * batch.update(doc(db, 'cities', 'LA'), { population: 4000000 });
677
+ * batch.delete(doc(db, 'cities', 'OLD'));
678
+ *
679
+ * await batch.commit();
680
+ * ```
681
+ */
682
+ declare function writeBatch(firestore: FirestoreInstance): WriteBatch;
683
+ /**
684
+ * Transacción de Firestore
685
+ */
686
+ interface Transaction {
687
+ /**
688
+ * Lee un documento dentro de la transacción
689
+ */
690
+ get<T = DocumentData>(reference: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
691
+ /**
692
+ * Establece un documento
693
+ */
694
+ set<T = DocumentData>(reference: DocumentReference<T>, data: T, options?: SetOptions): Transaction;
695
+ /**
696
+ * Actualiza un documento
697
+ */
698
+ update<T = DocumentData>(reference: DocumentReference<T>, data: Partial<T>): Transaction;
699
+ /**
700
+ * Elimina un documento
701
+ */
702
+ delete(reference: DocumentReference): Transaction;
703
+ }
704
+ /**
705
+ * Opciones para runTransaction
706
+ */
707
+ interface TransactionOptions {
708
+ /** Número máximo de reintentos */
709
+ maxAttempts?: number;
710
+ }
711
+ /**
712
+ * Ejecuta una función dentro de una transacción
713
+ *
714
+ * @param firestore Instancia de Firestore
715
+ * @param updateFunction Función a ejecutar
716
+ * @param options Opciones de transacción
717
+ * @returns Resultado de la función
718
+ *
719
+ * @example
720
+ * ```typescript
721
+ * const newBalance = await runTransaction(db, async (transaction) => {
722
+ * const accountRef = doc(db, 'accounts', 'account1');
723
+ * const accountDoc = await transaction.get(accountRef);
724
+ *
725
+ * if (!accountDoc.exists()) {
726
+ * throw new Error('Account does not exist');
727
+ * }
728
+ *
729
+ * const currentBalance = accountDoc.data()!.balance;
730
+ * const newBalance = currentBalance - 100;
731
+ *
732
+ * if (newBalance < 0) {
733
+ * throw new Error('Insufficient funds');
734
+ * }
735
+ *
736
+ * transaction.update(accountRef, { balance: newBalance });
737
+ * return newBalance;
738
+ * });
739
+ * ```
740
+ */
741
+ declare function runTransaction<T>(firestore: FirestoreInstance, updateFunction: (transaction: Transaction) => Promise<T>, options?: TransactionOptions): Promise<T>;
742
+
743
+ /**
744
+ * Firestore SDK - Tipos Especiales
745
+ * Timestamp, GeoPoint, Bytes, FieldPath, VectorValue
746
+ * Compatible con Firebase Firestore v9
747
+ */
748
+ /**
749
+ * Representa un punto en el tiempo con precisión de nanosegundos.
750
+ * Compatible con Firestore Timestamp.
751
+ */
752
+ declare class Timestamp {
753
+ readonly seconds: number;
754
+ readonly nanoseconds: number;
755
+ /**
756
+ * Crea un nuevo Timestamp.
757
+ *
758
+ * @param seconds Segundos desde la época Unix (1 enero 1970 UTC)
759
+ * @param nanoseconds Nanosegundos adicionales (0-999999999)
760
+ */
761
+ constructor(seconds: number, nanoseconds: number);
762
+ /**
763
+ * Crea un Timestamp para el momento actual.
764
+ */
765
+ static now(): Timestamp;
766
+ /**
767
+ * Crea un Timestamp desde un objeto Date.
768
+ */
769
+ static fromDate(date: Date): Timestamp;
770
+ /**
771
+ * Crea un Timestamp desde milisegundos.
772
+ */
773
+ static fromMillis(milliseconds: number): Timestamp;
774
+ /**
775
+ * Convierte el Timestamp a un objeto Date.
776
+ */
777
+ toDate(): Date;
778
+ /**
779
+ * Convierte el Timestamp a milisegundos.
780
+ */
781
+ toMillis(): number;
782
+ /**
783
+ * Convierte a formato ISO 8601 para serialización.
784
+ */
785
+ toJSON(): string;
786
+ /**
787
+ * Compara con otro Timestamp.
788
+ */
789
+ isEqual(other: Timestamp): boolean;
790
+ /**
791
+ * Representación en string.
792
+ */
793
+ toString(): string;
794
+ /**
795
+ * Compara dos Timestamps.
796
+ * @returns negativo si this < other, positivo si this > other, 0 si iguales
797
+ */
798
+ compareTo(other: Timestamp): number;
799
+ /**
800
+ * Obtiene el valor primitivo para comparaciones.
801
+ */
802
+ valueOf(): number;
803
+ }
804
+ /**
805
+ * Representa un punto geográfico con latitud y longitud.
806
+ * Compatible con Firestore GeoPoint.
807
+ */
808
+ declare class GeoPoint {
809
+ readonly latitude: number;
810
+ readonly longitude: number;
811
+ /**
812
+ * Crea un nuevo GeoPoint.
813
+ *
814
+ * @param latitude Latitud en grados (-90 a 90)
815
+ * @param longitude Longitud en grados (-180 a 180)
816
+ */
817
+ constructor(latitude: number, longitude: number);
818
+ /**
819
+ * Compara con otro GeoPoint.
820
+ */
821
+ isEqual(other: GeoPoint): boolean;
822
+ /**
823
+ * Convierte a objeto plano para serialización.
824
+ */
825
+ toJSON(): {
826
+ latitude: number;
827
+ longitude: number;
828
+ };
829
+ /**
830
+ * Representación en string.
831
+ */
832
+ toString(): string;
833
+ }
834
+ /**
835
+ * Representa datos binarios inmutables.
836
+ * Compatible con Firestore Bytes.
837
+ */
838
+ declare class Bytes {
839
+ private readonly _bytes;
840
+ private constructor();
841
+ /**
842
+ * Crea Bytes desde una cadena Base64.
843
+ */
844
+ static fromBase64String(base64: string): Bytes;
845
+ /**
846
+ * Crea Bytes desde un Uint8Array.
847
+ */
848
+ static fromUint8Array(array: Uint8Array): Bytes;
849
+ /**
850
+ * Convierte a cadena Base64.
851
+ */
852
+ toBase64(): string;
853
+ /**
854
+ * Convierte a Uint8Array.
855
+ */
856
+ toUint8Array(): Uint8Array;
857
+ /**
858
+ * Compara con otro Bytes.
859
+ */
860
+ isEqual(other: Bytes): boolean;
861
+ /**
862
+ * Representación en string.
863
+ */
864
+ toString(): string;
865
+ }
866
+ /**
867
+ * Representa una ruta de campo en un documento.
868
+ * Permite acceder a campos anidados de forma segura.
869
+ */
870
+ declare class FieldPath {
871
+ private readonly _fields;
872
+ /**
873
+ * Crea un FieldPath desde segmentos de campo.
874
+ *
875
+ * @param fieldNames Nombres de campos anidados
876
+ *
877
+ * @example
878
+ * ```typescript
879
+ * new FieldPath('user', 'address', 'city')
880
+ * // Equivale a 'user.address.city'
881
+ * ```
882
+ */
883
+ constructor(...fieldNames: string[]);
884
+ /**
885
+ * Compara con otro FieldPath.
886
+ */
887
+ isEqual(other: FieldPath): boolean;
888
+ /**
889
+ * Convierte a string con notación de puntos.
890
+ */
891
+ toString(): string;
892
+ /**
893
+ * Obtiene los segmentos del path.
894
+ */
895
+ get segments(): string[];
896
+ }
897
+ /**
898
+ * Crea un FieldPath que apunta al ID del documento.
899
+ * Útil para queries que filtran por document ID.
900
+ *
901
+ * @example
902
+ * ```typescript
903
+ * query(collection(db, 'users'), where(documentId(), '==', 'user123'))
904
+ * ```
905
+ */
906
+ declare function documentId(): FieldPath;
907
+ /**
908
+ * Representa un vector de números para embeddings/ML.
909
+ * Compatible con Firestore VectorValue.
910
+ */
911
+ declare class VectorValue {
912
+ private readonly _values;
913
+ private constructor();
914
+ /**
915
+ * Convierte a array de números.
916
+ */
917
+ toArray(): number[];
918
+ /**
919
+ * Compara con otro VectorValue.
920
+ */
921
+ isEqual(other: VectorValue): boolean;
922
+ /**
923
+ * Representación en string.
924
+ */
925
+ toString(): string;
926
+ /**
927
+ * Obtiene la dimensión del vector.
928
+ */
929
+ get length(): number;
930
+ }
931
+ /**
932
+ * Crea un VectorValue desde un array de números.
933
+ *
934
+ * @param values Array de números
935
+ *
936
+ * @example
937
+ * ```typescript
938
+ * const embedding = vector([0.1, 0.2, 0.3, 0.4]);
939
+ * await setDoc(docRef, { embedding });
940
+ * ```
941
+ */
942
+ declare function vector(values: number[]): VectorValue;
943
+
944
+ /**
945
+ * Firestore SDK - Queries Avanzadas
946
+ * and(), or(), collectionGroup()
947
+ * Compatible con Firebase Firestore v9
948
+ */
949
+
950
+ /**
951
+ * Filtro compuesto AND
952
+ */
953
+ interface AndConstraint {
954
+ readonly type: 'and';
955
+ readonly constraints: QueryConstraint[];
956
+ }
957
+ /**
958
+ * Filtro compuesto OR
959
+ */
960
+ interface OrConstraint {
961
+ readonly type: 'or';
962
+ readonly constraints: QueryConstraint[];
963
+ }
964
+ /**
965
+ * Tipo unión para filtros compuestos
966
+ */
967
+ type CompositeFilterConstraint = AndConstraint | OrConstraint;
968
+ /**
969
+ * Combina múltiples constraints con lógica AND.
970
+ *
971
+ * @param constraints Restricciones a combinar
972
+ * @returns Constraint compuesto AND
973
+ *
974
+ * @example
975
+ * ```typescript
976
+ * const q = query(
977
+ * collection(db, 'products'),
978
+ * and(
979
+ * where('category', '==', 'electronics'),
980
+ * where('price', '<=', 1000),
981
+ * where('inStock', '==', true)
982
+ * )
983
+ * );
984
+ * ```
985
+ */
986
+ declare function and(...constraints: QueryConstraint[]): AndConstraint;
987
+ /**
988
+ * Combina múltiples constraints con lógica OR.
989
+ *
990
+ * @param constraints Restricciones a combinar
991
+ * @returns Constraint compuesto OR
992
+ *
993
+ * @example
994
+ * ```typescript
995
+ * const q = query(
996
+ * collection(db, 'products'),
997
+ * or(
998
+ * where('category', '==', 'electronics'),
999
+ * where('category', '==', 'computers')
1000
+ * )
1001
+ * );
1002
+ * ```
1003
+ */
1004
+ declare function or(...constraints: QueryConstraint[]): OrConstraint;
1005
+ /**
1006
+ * Referencia a un grupo de colecciones para queries.
1007
+ */
1008
+ interface CollectionGroupReference<T = DocumentData> extends Query<T> {
1009
+ readonly type: 'collectionGroup';
1010
+ readonly collectionId: string;
1011
+ }
1012
+ /**
1013
+ * Crea una query que abarca todas las colecciones con el mismo ID.
1014
+ * Útil para buscar en subcolecciones anidadas en cualquier parte.
1015
+ *
1016
+ * @param firestore Instancia de Firestore
1017
+ * @param collectionId ID de la colección a buscar
1018
+ * @returns Query sobre el grupo de colecciones
1019
+ *
1020
+ * @example
1021
+ * ```typescript
1022
+ * // Buscar todos los comentarios en cualquier post
1023
+ * const allComments = query(
1024
+ * collectionGroup(db, 'comments'),
1025
+ * where('author', '==', 'john'),
1026
+ * orderBy('createdAt', 'desc'),
1027
+ * limit(10)
1028
+ * );
1029
+ *
1030
+ * const snapshot = await getDocs(allComments);
1031
+ * ```
1032
+ */
1033
+ declare function collectionGroup<T = DocumentData>(firestore: FirestoreInstance, collectionId: string): CollectionGroupReference<T>;
1034
+ /**
1035
+ * Verifica si un constraint es un filtro compuesto AND
1036
+ */
1037
+ declare function isAndConstraint(constraint: QueryConstraint): constraint is AndConstraint;
1038
+ /**
1039
+ * Verifica si un constraint es un filtro compuesto OR
1040
+ */
1041
+ declare function isOrConstraint(constraint: QueryConstraint): constraint is OrConstraint;
1042
+ /**
1043
+ * Verifica si un constraint es un filtro compuesto
1044
+ */
1045
+ declare function isCompositeFilter(constraint: QueryConstraint): constraint is CompositeFilterConstraint;
1046
+ /**
1047
+ * Verifica si una query es un collection group
1048
+ */
1049
+ declare function isCollectionGroup<T>(ref: Query<T> | CollectionReference<T>): boolean;
1050
+
1051
+ /**
1052
+ * Firestore SDK - Agregaciones
1053
+ * getCountFromServer, getAggregateFromServer, count, sum, average
1054
+ * Compatible con Firebase Firestore v9
1055
+ */
1056
+
1057
+ /**
1058
+ * Especificación de campo de agregación
1059
+ */
1060
+ interface AggregateField<T> {
1061
+ readonly _aggregateType: 'count' | 'sum' | 'average';
1062
+ readonly _field?: string;
1063
+ /** Tipo interno para TypeScript */
1064
+ readonly _valueType?: T;
1065
+ }
1066
+ /**
1067
+ * Especificación de agregación (objeto con campos)
1068
+ */
1069
+ type AggregateSpec = {
1070
+ [key: string]: AggregateField<unknown>;
1071
+ };
1072
+ /**
1073
+ * Resultado de agregación basado en el spec
1074
+ */
1075
+ type AggregateSpecData<T extends AggregateSpec> = {
1076
+ [K in keyof T]: T[K] extends AggregateField<infer U> ? U : never;
1077
+ };
1078
+ /**
1079
+ * Snapshot de resultado de agregación
1080
+ */
1081
+ interface AggregateQuerySnapshot<T extends AggregateSpec> {
1082
+ /** Obtiene los datos de agregación */
1083
+ data(): AggregateSpecData<T>;
1084
+ }
1085
+ /**
1086
+ * Crea un campo de agregación para contar documentos.
1087
+ *
1088
+ * @example
1089
+ * ```typescript
1090
+ * const snapshot = await getAggregateFromServer(
1091
+ * query(collection(db, 'users')),
1092
+ * { userCount: count() }
1093
+ * );
1094
+ * console.log(snapshot.data().userCount);
1095
+ * ```
1096
+ */
1097
+ declare function count(): AggregateField<number>;
1098
+ /**
1099
+ * Crea un campo de agregación para sumar valores de un campo.
1100
+ *
1101
+ * @param field Nombre del campo a sumar
1102
+ *
1103
+ * @example
1104
+ * ```typescript
1105
+ * const snapshot = await getAggregateFromServer(
1106
+ * query(collection(db, 'orders')),
1107
+ * { totalAmount: sum('amount') }
1108
+ * );
1109
+ * console.log(snapshot.data().totalAmount);
1110
+ * ```
1111
+ */
1112
+ declare function sum(field: string): AggregateField<number>;
1113
+ /**
1114
+ * Crea un campo de agregación para calcular el promedio de un campo.
1115
+ *
1116
+ * @param field Nombre del campo a promediar
1117
+ *
1118
+ * @example
1119
+ * ```typescript
1120
+ * const snapshot = await getAggregateFromServer(
1121
+ * query(collection(db, 'products')),
1122
+ * { avgPrice: average('price') }
1123
+ * );
1124
+ * console.log(snapshot.data().avgPrice);
1125
+ * ```
1126
+ */
1127
+ declare function average(field: string): AggregateField<number | null>;
1128
+ /**
1129
+ * Obtiene el conteo de documentos de una query desde el servidor.
1130
+ *
1131
+ * @param query Query a contar
1132
+ * @returns Promise con snapshot conteniendo el conteo
1133
+ *
1134
+ * @example
1135
+ * ```typescript
1136
+ * const q = query(collection(db, 'users'), where('active', '==', true));
1137
+ * const snapshot = await getCountFromServer(q);
1138
+ * console.log('Active users:', snapshot.data().count);
1139
+ * ```
1140
+ */
1141
+ declare function getCountFromServer<T = DocumentData>(query: Query<T> | CollectionReference<T>): Promise<AggregateQuerySnapshot<{
1142
+ count: AggregateField<number>;
1143
+ }>>;
1144
+ /**
1145
+ * Ejecuta múltiples agregaciones en una query desde el servidor.
1146
+ *
1147
+ * @param query Query base para la agregación
1148
+ * @param aggregateSpec Especificación de campos a agregar
1149
+ * @returns Promise con snapshot conteniendo los resultados
1150
+ *
1151
+ * @example
1152
+ * ```typescript
1153
+ * const q = query(collection(db, 'orders'), where('status', '==', 'completed'));
1154
+ * const snapshot = await getAggregateFromServer(q, {
1155
+ * totalOrders: count(),
1156
+ * totalRevenue: sum('amount'),
1157
+ * avgOrderValue: average('amount')
1158
+ * });
1159
+ *
1160
+ * const data = snapshot.data();
1161
+ * console.log('Total orders:', data.totalOrders);
1162
+ * console.log('Total revenue:', data.totalRevenue);
1163
+ * console.log('Average order:', data.avgOrderValue);
1164
+ * ```
1165
+ */
1166
+ declare function getAggregateFromServer<T = DocumentData, S extends AggregateSpec = AggregateSpec>(query: Query<T> | CollectionReference<T>, aggregateSpec: S): Promise<AggregateQuerySnapshot<S>>;
1167
+
1168
+ /**
1169
+ * Firestore SDK - Utilidades
1170
+ * withConverter, refEqual, queryEqual, snapshotEqual, onSnapshotsInSync
1171
+ * Compatible con Firebase Firestore v9
1172
+ */
1173
+
1174
+ /**
1175
+ * Convertidor de datos para tipado fuerte.
1176
+ * Transforma datos entre el formato de la aplicación y Firestore.
1177
+ */
1178
+ interface FirestoreDataConverter<T> {
1179
+ /**
1180
+ * Convierte un objeto de la aplicación a datos de Firestore.
1181
+ */
1182
+ toFirestore(modelObject: T): DocumentData;
1183
+ /**
1184
+ * Convierte un snapshot de Firestore a un objeto de la aplicación.
1185
+ */
1186
+ fromFirestore(snapshot: QueryDocumentSnapshot<DocumentData>): T;
1187
+ }
1188
+ /**
1189
+ * QueryDocumentSnapshot garantiza que el documento existe.
1190
+ */
1191
+ interface QueryDocumentSnapshot<T = DocumentData> extends DocumentSnapshot<T> {
1192
+ exists(): true;
1193
+ data(): T;
1194
+ }
1195
+ /**
1196
+ * Referencia a documento con converter.
1197
+ */
1198
+ interface DocumentReferenceWithConverter<T> extends DocumentReference<T> {
1199
+ /** Converter asociado */
1200
+ readonly converter: FirestoreDataConverter<T> | null;
1201
+ }
1202
+ /**
1203
+ * Referencia a colección con converter.
1204
+ */
1205
+ interface CollectionReferenceWithConverter<T> extends CollectionReference<T> {
1206
+ /** Converter asociado */
1207
+ readonly converter: FirestoreDataConverter<T> | null;
1208
+ }
1209
+ /**
1210
+ * Query con converter.
1211
+ */
1212
+ interface QueryWithConverter<T> extends Query<T> {
1213
+ /** Converter asociado */
1214
+ readonly converter: FirestoreDataConverter<T> | null;
1215
+ }
1216
+ /**
1217
+ * Aplica un converter a una referencia de documento.
1218
+ *
1219
+ * @param reference Referencia de documento
1220
+ * @param converter Convertidor de datos
1221
+ * @returns Referencia con converter aplicado
1222
+ *
1223
+ * @example
1224
+ * ```typescript
1225
+ * interface User {
1226
+ * name: string;
1227
+ * age: number;
1228
+ * }
1229
+ *
1230
+ * const userConverter: FirestoreDataConverter<User> = {
1231
+ * toFirestore: (user) => ({ name: user.name, age: user.age }),
1232
+ * fromFirestore: (snap) => {
1233
+ * const data = snap.data();
1234
+ * return { name: data.name, age: data.age };
1235
+ * }
1236
+ * };
1237
+ *
1238
+ * const userRef = doc(db, 'users', '123').withConverter(userConverter);
1239
+ * const userSnap = await getDoc(userRef);
1240
+ * const user = userSnap.data(); // Tipo: User | undefined
1241
+ * ```
1242
+ */
1243
+ declare function withConverter<T>(reference: DocumentReference<DocumentData>, converter: FirestoreDataConverter<T> | null): DocumentReference<T>;
1244
+ declare function withConverter<T>(reference: CollectionReference<DocumentData>, converter: FirestoreDataConverter<T> | null): CollectionReference<T>;
1245
+ declare function withConverter<T>(reference: Query<DocumentData>, converter: FirestoreDataConverter<T> | null): Query<T>;
1246
+ /**
1247
+ * Compara dos referencias de documento.
1248
+ *
1249
+ * @param left Primera referencia
1250
+ * @param right Segunda referencia
1251
+ * @returns true si apuntan al mismo documento
1252
+ *
1253
+ * @example
1254
+ * ```typescript
1255
+ * const ref1 = doc(db, 'users', '123');
1256
+ * const ref2 = doc(db, 'users', '123');
1257
+ * console.log(refEqual(ref1, ref2)); // true
1258
+ * ```
1259
+ */
1260
+ declare function refEqual<T>(left: DocumentReference<T> | CollectionReference<T>, right: DocumentReference<T> | CollectionReference<T>): boolean;
1261
+ /**
1262
+ * Compara dos queries.
1263
+ *
1264
+ * @param left Primera query
1265
+ * @param right Segunda query
1266
+ * @returns true si son equivalentes
1267
+ *
1268
+ * @example
1269
+ * ```typescript
1270
+ * const q1 = query(collection(db, 'users'), where('age', '>', 18));
1271
+ * const q2 = query(collection(db, 'users'), where('age', '>', 18));
1272
+ * console.log(queryEqual(q1, q2)); // true
1273
+ * ```
1274
+ */
1275
+ declare function queryEqual<T>(left: Query<T>, right: Query<T>): boolean;
1276
+ /**
1277
+ * Compara dos snapshots de documento.
1278
+ *
1279
+ * @param left Primer snapshot
1280
+ * @param right Segundo snapshot
1281
+ * @returns true si representan el mismo estado
1282
+ *
1283
+ * @example
1284
+ * ```typescript
1285
+ * const snap1 = await getDoc(docRef);
1286
+ * const snap2 = await getDoc(docRef);
1287
+ * console.log(snapshotEqual(snap1, snap2)); // true si no hubo cambios
1288
+ * ```
1289
+ */
1290
+ declare function snapshotEqual<T>(left: DocumentSnapshot<T> | QuerySnapshot<T>, right: DocumentSnapshot<T> | QuerySnapshot<T>): boolean;
1291
+ /**
1292
+ * Escucha cuando todos los snapshots están sincronizados.
1293
+ * Se llama cuando todos los listeners activos han recibido una actualización.
1294
+ *
1295
+ * @param firestore Instancia de Firestore
1296
+ * @param onSync Callback a ejecutar cuando todos estén sincronizados
1297
+ * @returns Función para cancelar la suscripción
1298
+ *
1299
+ * @example
1300
+ * ```typescript
1301
+ * const unsubscribe = onSnapshotsInSync(db, () => {
1302
+ * console.log('All snapshots are in sync');
1303
+ * });
1304
+ *
1305
+ * // Más tarde...
1306
+ * unsubscribe();
1307
+ * ```
1308
+ */
1309
+ declare function onSnapshotsInSync(firestore: FirestoreInstance, onSync: () => void): Unsubscribe;
1310
+
1311
+ /**
1312
+ * Firestore SDK - Búsqueda Avanzada
1313
+ * Extensiones de búsqueda que superan las capacidades de Firestore original
1314
+ *
1315
+ * Operadores disponibles:
1316
+ * - _search: Full-text search con normalización de acentos
1317
+ * - _contains: Búsqueda in-string (busca "tel" en "Hotel")
1318
+ * - _fuzzy: Fuzzy matching con tolerancia a errores de tipeo
1319
+ * - _similar: Similitud de trigramas (coincidencia parcial)
1320
+ *
1321
+ * @example
1322
+ * ```typescript
1323
+ * import { whereContains, whereFuzzy, orderByRelevance } from '@ponceca/firestore-sdk';
1324
+ *
1325
+ * // Buscar "tel" dentro de cualquier parte del campo (encuentra "Hotel")
1326
+ * const q1 = query(collection(db, 'places'), whereContains('name', 'tel'));
1327
+ *
1328
+ * // Buscar con tolerancia a errores de tipeo ("algodoon" → "algodón")
1329
+ * const q2 = query(collection(db, 'products'), whereFuzzy('description', 'algodoon'));
1330
+ *
1331
+ * // Ordenar por relevancia
1332
+ * const q3 = query(
1333
+ * collection(db, 'articles'),
1334
+ * whereSearch('title', 'javascript'),
1335
+ * orderByRelevance()
1336
+ * );
1337
+ * ```
1338
+ */
1339
+
1340
+ /**
1341
+ * Busca texto usando full-text search con normalización de acentos.
1342
+ * Insensible a mayúsculas/minúsculas y acentos.
1343
+ *
1344
+ * @param field Campo a buscar
1345
+ * @param value Texto a buscar
1346
+ * @returns Constraint de búsqueda
1347
+ *
1348
+ * @example
1349
+ * ```typescript
1350
+ * // Busca "camion" y encuentra "Camión", "CAMIÓN", "camion"
1351
+ * const q = query(collection(db, 'vehicles'), whereSearch('name', 'camion'));
1352
+ * ```
1353
+ */
1354
+ declare function whereSearch(field: string, value: string): WhereConstraint;
1355
+ /**
1356
+ * Busca texto en cualquier posición del campo (in-string search).
1357
+ * Busca "tel" y encuentra "Hotel", "telefono", "cartel".
1358
+ *
1359
+ * @param field Campo a buscar
1360
+ * @param value Texto a buscar
1361
+ * @returns Constraint de búsqueda
1362
+ *
1363
+ * @example
1364
+ * ```typescript
1365
+ * // Busca "tel" dentro de cualquier parte (encuentra "Hotel", "telefono")
1366
+ * const q = query(collection(db, 'places'), whereContains('name', 'tel'));
1367
+ * ```
1368
+ */
1369
+ declare function whereContains(field: string, value: string): WhereConstraint;
1370
+ /**
1371
+ * Busca texto con tolerancia a errores de tipeo (fuzzy matching).
1372
+ * Usa distancia de Levenshtein para encontrar coincidencias aproximadas.
1373
+ *
1374
+ * @param field Campo a buscar
1375
+ * @param value Texto a buscar
1376
+ * @returns Constraint de búsqueda
1377
+ *
1378
+ * @example
1379
+ * ```typescript
1380
+ * // Busca "algodoon" y encuentra "algodón"
1381
+ * const q = query(collection(db, 'products'), whereFuzzy('material', 'algodoon'));
1382
+ * ```
1383
+ */
1384
+ declare function whereFuzzy(field: string, value: string): WhereConstraint;
1385
+ /**
1386
+ * Busca texto por similitud de trigramas.
1387
+ * Encuentra coincidencias parciales basadas en secuencias de 3 caracteres.
1388
+ *
1389
+ * @param field Campo a buscar
1390
+ * @param value Texto a buscar
1391
+ * @returns Constraint de búsqueda
1392
+ *
1393
+ * @example
1394
+ * ```typescript
1395
+ * // Encuentra palabras similares a "javascript"
1396
+ * const q = query(collection(db, 'articles'), whereSimilar('title', 'javascript'));
1397
+ * ```
1398
+ */
1399
+ declare function whereSimilar(field: string, value: string): WhereConstraint;
1400
+ /**
1401
+ * Ordena los resultados por relevancia (score de búsqueda).
1402
+ * Debe usarse junto con operadores de búsqueda (_search, _contains, _fuzzy, _similar).
1403
+ * Los documentos más relevantes aparecen primero.
1404
+ *
1405
+ * @param direction Dirección del ordenamiento ('desc' = más relevantes primero)
1406
+ * @returns Constraint de ordenamiento
1407
+ *
1408
+ * @example
1409
+ * ```typescript
1410
+ * const q = query(
1411
+ * collection(db, 'products'),
1412
+ * whereSearch('description', 'laptop gaming'),
1413
+ * orderByRelevance('desc')
1414
+ * );
1415
+ * ```
1416
+ */
1417
+ declare function orderByRelevance(direction?: 'asc' | 'desc'): OrderByConstraint;
1418
+ /**
1419
+ * Paginación por offset directo.
1420
+ * Permite saltar a cualquier página sin leer documentos anteriores.
1421
+ *
1422
+ * @param count Número de documentos a saltar
1423
+ * @returns Constraint de offset
1424
+ *
1425
+ * @example
1426
+ * ```typescript
1427
+ * // Ir directamente a la página 5 (saltando 40 documentos)
1428
+ * const q = query(
1429
+ * collection(db, 'products'),
1430
+ * limit(10),
1431
+ * offset(40)
1432
+ * );
1433
+ * ```
1434
+ */
1435
+ declare function offset(count: number): {
1436
+ type: 'offset';
1437
+ count: number;
1438
+ };
1439
+ interface FastSearchOptions {
1440
+ /** Campo específico donde buscar. Si está vacío, busca en todos los campos (global). */
1441
+ field?: string;
1442
+ /** Máximo de resultados a retornar. Default: 50 */
1443
+ limit?: number;
1444
+ /** Usar búsqueda fuzzy (tolerante a errores de tipeo). Default: false */
1445
+ fuzzy?: boolean;
1446
+ }
1447
+ interface FastSearchResult<T = DocumentData> {
1448
+ id: string;
1449
+ data: T;
1450
+ }
1451
+ interface FastSearchResponse<T = DocumentData> {
1452
+ count: number;
1453
+ documents: FastSearchResult<T>[];
1454
+ /** Indica si fue búsqueda global o por campo específico */
1455
+ searchMode?: string;
1456
+ }
1457
+ /**
1458
+ * Búsqueda ultra rápida vía endpoint dedicado.
1459
+ * Ideal para autocomplete y prefijos con latencia mínima.
1460
+ * Usa fetch directo para minimizar overhead.
1461
+ *
1462
+ * @param firestore Instancia de Firestore
1463
+ * @param collectionPath Ruta de colección
1464
+ * @param term Término de búsqueda
1465
+ * @param options Opciones de búsqueda (incluye field para búsqueda específica)
1466
+ *
1467
+ * @example
1468
+ * // Búsqueda en campo específico (recomendado)
1469
+ * const results = await fastSearch(db, 'articles', 'javascript', { field: 'title' });
1470
+ *
1471
+ * // Búsqueda global (todos los campos)
1472
+ * const results = await fastSearch(db, 'articles', 'javascript');
1473
+ */
1474
+ declare function fastSearch<T = DocumentData>(firestore: FirestoreInstance, collectionPath: string, term: string, options?: FastSearchOptions): Promise<FastSearchResponse<T>>;
1475
+
1476
+ export { type AggregateField, type AggregateQuerySnapshot, type AggregateSpec, type AggregateSpecData, type AndConstraint, Bytes, type CollectionGroupReference, CollectionReference, type CollectionReferenceWithConverter, type CompositeFilterConstraint, DocumentData, DocumentReference, type DocumentReferenceWithConverter, DocumentSnapshot, type DocumentSnapshotCallback, EndAtConstraint, type ErrorCallback, type FastSearchOptions, type FastSearchResponse, type FastSearchResult, FieldPath as FieldPathClass, FieldValue, Firestore, type FirestoreDataConverter, FirestoreInstance, FirestoreSettings, GeoPoint, LimitConstraint, type OrConstraint, OrderByConstraint, OrderByDirection, Query, QueryConstraint, type QueryDocumentSnapshot, QuerySnapshot, type QuerySnapshotCallback, type QueryWithConverter, SetOptions, SnapshotListenOptions, type SnapshotObserver, StartAtConstraint, Timestamp, type Transaction, type TransactionOptions, Unsubscribe, VectorValue, WhereConstraint, WhereFilterOp, type WriteBatch, addDoc, and, arrayRemove, arrayUnion, average, clearIndexedDbPersistence, collection, collectionGroup, connectFirestoreEmulator, count, deleteDoc, deleteField, disableNetwork, doc, documentId, enableIndexedDbPersistence, enableMultiTabIndexedDbPersistence, enableNetwork, endAt, endBefore, fastSearch, getAggregateFromServer, getAuthToken, getCountFromServer, getDoc, getDocFromCache, getDocFromServer, getDocs, getDocsFromCache, getDocsFromServer, getFirestore, increment, initializeFirestore, isAndConstraint, isCollectionGroup, isCompositeFilter, isOrConstraint, limit, limitToLast, offset, onSnapshot, onSnapshotsInSync, or, orderBy, orderByRelevance, query, queryEqual, refEqual, runTransaction, serverTimestamp, setAuthToken, setDoc, snapshotEqual, startAfter, startAt, sum, terminate, updateDoc, vector, waitForPendingWrites, where, whereContains, whereFuzzy, whereSearch, whereSimilar, withConverter, writeBatch };